Files
kandev/apps/backend/internal/agent/hostutility/public.go
T
João Salavisa 7e0b46c227 feat(slack): cookie-mode integration that triages threads via a utility agent (#775)
* feat(slack): add cookie-mode integration that triages messages via utility agent

Adds an install-wide Slack integration that polls the connected user's
own messages for `!kandev <instruction>`, hands the thread context to a
configured utility agent with the Kandev MCP server attached, and
creates the resulting task. Auth uses the user's xoxc- token + d cookie
so it works on locked-down Enterprise Slack tenants where bot installs
aren't possible.

Shared infra:
- ACP host-utility executor accepts McpServers on session/new
- New MCP tool list_repositories_kandev so the triage agent can pick the
  right repo
- Template engine exposes Slack-specific variables for prompt injection
- secretadapter + healthpoll reused from jira/linear

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(slack): address PR review feedback round 9

- Drop dead `var _ = time.Second` no-op and its misleading comment in
  trigger_test.go.
- `RecordAuthHealth` now invalidates the cached client when the probe
  fails, so the poller self-recovers from credential rotation without
  requiring a re-save.
- Stable secondary sort key (`workspace_id DESC`) on the legacy →
  singleton migration so promoted-row selection is deterministic on
  `updated_at` ties.
- Extract `categorySlack` constant in `engine.go` and update the
  `VariableInfo.Category` doc-comment to list the full set of values.
- Realign `slack-integration/spec.md` with what shipped: cookie-mode +
  `!kandev` triage as v1, with bot install / User OAuth / reaction &
  slash & shortcut triggers moved under Future scope.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-05 09:03:42 +01:00

129 lines
3.8 KiB
Go

package hostutility
import (
"context"
"errors"
"fmt"
"time"
"github.com/kandev/kandev/internal/agent/agents"
agentctlutil "github.com/kandev/kandev/internal/agentctl/server/utility"
)
// GetAll returns a snapshot of every probed agent type's capabilities.
func (m *Manager) GetAll() []AgentCapabilities {
if m == nil || m.cache == nil {
return nil
}
return m.cache.all()
}
// Get returns the cached capabilities for a single agent type.
func (m *Manager) Get(agentType string) (AgentCapabilities, bool) {
if m == nil || m.cache == nil {
return AgentCapabilities{}, false
}
return m.cache.get(agentType)
}
// Refresh re-probes the given agent type, refreshes the cache, and returns the
// new capabilities. If the warm instance is missing (never bootstrapped or
// crashed), it is lazily recreated.
func (m *Manager) Refresh(ctx context.Context, agentType string) (AgentCapabilities, error) {
// Publish "probing" so callers polling the cache see in-flight state.
m.cache.set(AgentCapabilities{
AgentType: agentType,
Status: StatusProbing,
LastCheckedAt: time.Now(),
})
inst, ia, err := m.getInstance(ctx, agentType)
if err != nil {
status := StatusFailed
if errors.Is(err, errAgentNotInstalled) {
status = StatusNotInstalled
}
m.cache.set(AgentCapabilities{
AgentType: agentType,
Status: status,
Error: err.Error(),
LastCheckedAt: time.Now(),
})
return AgentCapabilities{}, err
}
caps := m.probe(ctx, inst, ia)
m.cache.set(caps)
return caps, nil
}
// ExecutePrompt runs a sessionless utility prompt against the warm instance
// for the given agent type. Convenience wrapper over ExecutePromptWithMCP
// that opts the call out of MCP tool access — most callers (PR title, commit
// message, etc.) want pure text-in/text-out.
func (m *Manager) ExecutePrompt(
ctx context.Context,
agentType, model, mode, prompt string,
) (*PromptResult, error) {
return m.ExecutePromptWithMCP(ctx, agentType, model, mode, prompt, nil)
}
// ExecutePromptWithMCP runs a sessionless utility prompt with the given MCP
// servers wired into the agent's session. The agent (Claude Code, codex,
// etc.) can call MCP tools mid-prompt and incorporate the results into its
// final reply. Pass nil for mcpServers to disable MCP for this call.
func (m *Manager) ExecutePromptWithMCP(
ctx context.Context,
agentType, model, mode, prompt string,
mcpServers []agentctlutil.MCPServerDTO,
) (*PromptResult, error) {
if prompt == "" {
return nil, fmt.Errorf("prompt is required")
}
inst, ia, err := m.getInstance(ctx, agentType)
if err != nil {
return nil, err
}
cfg := ia.InferenceConfig()
resolved := m.resolveModel(agentType, model, ia)
req := &agentctlutil.PromptRequest{
Prompt: prompt,
AgentID: agentType,
Model: resolved,
Mode: mode,
InferenceConfig: &agentctlutil.InferenceConfigDTO{
Command: cfg.Command.Args(),
ModelFlag: cfg.ModelFlag.Args(),
WorkDir: inst.workDir,
},
MCPServers: mcpServers,
}
resp, err := inst.client.InferencePrompt(ctx, req)
if err != nil {
return nil, err
}
if !resp.Success {
return nil, fmt.Errorf("%s", resp.Error)
}
return &PromptResult{
Response: resp.Response,
Model: resp.Model,
PromptTokens: resp.PromptTokens,
ResponseTokens: resp.ResponseTokens,
DurationMs: resp.DurationMs,
}, nil
}
// resolveModel picks the model to use for an ExecutePrompt call.
// Precedence: explicit argument > cached probe currentModelID.
// Static per-agent default models no longer exist; probes are the source of truth.
func (m *Manager) resolveModel(agentType, explicit string, _ agents.InferenceAgent) string {
if explicit != "" {
return explicit
}
if caps, ok := m.cache.get(agentType); ok && caps.CurrentModelID != "" {
return caps.CurrentModelID
}
return ""
}