diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 1d42d991d..0ab3b26b7 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -93,6 +93,7 @@ var ( // chatGenerateOptions builds one chat turn's request. func chatGenerateOptions( + ctx context.Context, messages []chat.Message, registry *tools.Registry, maxSteps int, @@ -100,6 +101,9 @@ func chatGenerateOptions( extra []tools.ToolEntry, ) (core.GenerateOptions, error) { toolOpts := limits.Options() + if approval := gateway.ApprovalFromContext(ctx); approval != nil { + toolOpts.Approval = approval + } toolSet, err := agentexec.BuildToolSet(registry, toolOpts) if err != nil { return core.GenerateOptions{}, err diff --git a/cmd/archied/main_test.go b/cmd/archied/main_test.go index 91bdb41d4..86d5dbab2 100644 --- a/cmd/archied/main_test.go +++ b/cmd/archied/main_test.go @@ -201,7 +201,7 @@ func TestChatGenerateOptionsIncludesToolsAndMultipleSteps(t *testing.T) { } messages := []chat.Message{{Role: chat.RoleUser, Content: "remember this"}} - options, err := chatGenerateOptions(messages, registry, 0, agentexec.ToolLimits{}, nil) + options, err := chatGenerateOptions(context.Background(), messages, registry, 0, agentexec.ToolLimits{}, nil) if err != nil { t.Fatal(err) } @@ -227,8 +227,8 @@ func TestChatGenerateOptionsReportsInvalidToolSchemas(t *testing.T) { }); err != nil { t.Fatal(err) } - if _, err := chatGenerateOptions(nil, registry, 0, agentexec.ToolLimits{}, nil); err == nil { - t.Fatal("chatGenerateOptions() error = nil, want invalid tool schema error") + if _, err := chatGenerateOptions(context.Background(), nil, registry, 0, agentexec.ToolLimits{}, nil); err == nil { + t.Fatal("chatGenerateOptions(context.Background(),) error = nil, want invalid tool schema error") } } @@ -236,7 +236,7 @@ func TestChatGenerateOptionsReportsInvalidToolSchemas(t *testing.T) { // deployment-controlled. A cap that cannot be raised without a rebuild is // the situation this replaced. func TestChatGenerateOptionsHonoursConfiguredMaxSteps(t *testing.T) { - options, err := chatGenerateOptions(nil, tools.NewRegistry(), 250, agentexec.ToolLimits{}, nil) + options, err := chatGenerateOptions(context.Background(), nil, tools.NewRegistry(), 250, agentexec.ToolLimits{}, nil) if err != nil { t.Fatal(err) } diff --git a/cmd/archied/telegram_setup.go b/cmd/archied/telegram_setup.go index d4d911cc6..ba3ae239a 100644 --- a/cmd/archied/telegram_setup.go +++ b/cmd/archied/telegram_setup.go @@ -227,7 +227,11 @@ func makeChatLLMResponder( compressed = append(compressed, gateway.CompressedMessage{Role: role, Content: h.Text}) } view := gateway.CompressHistory(compressed, gateway.DefaultCompressionConfig()) - options, err := chatGenerateOptions(nil, s.ToolReg, s.Cfg.Chat.MaxSteps, toolLimits(s.Cfg), taskTools) + sessionTools := gateway.SessionTools(sessionStore, router.SessionTracker(), channel, msg) + allTools := make([]tools.ToolEntry, 0, len(taskTools)+len(sessionTools)) + allTools = append(allTools, taskTools...) + allTools = append(allTools, sessionTools...) + options, err := chatGenerateOptions(ctx, nil, s.ToolReg, s.Cfg.Chat.MaxSteps, toolLimits(s.Cfg), allTools) if err != nil { return "", fmt.Errorf("build chat tools: %w", err) } diff --git a/internal/agentexec/toolset.go b/internal/agentexec/toolset.go index a1a18338d..bce630c93 100644 --- a/internal/agentexec/toolset.go +++ b/internal/agentexec/toolset.go @@ -3,6 +3,7 @@ package agentexec import ( "context" "encoding/json" + "errors" "fmt" "os" "slices" @@ -77,6 +78,11 @@ type ToolSetOptions struct { // are rooted at a directory that is not the task's worktree and which // bypass the agent loop's read-only and protected-path enforcement. ExcludeToolsets []string + + // Approval is the human-consent gate for tools marked RequiresApproval. + // Nil means no approver is configured — such tools are omitted from the + // built set rather than failing at call time. + Approval tools.ApprovalRequester } // resultLimit returns the cap that applies to one entry. @@ -127,6 +133,13 @@ func BuildToolSetFrom(entries []tools.ToolEntry, opts ToolSetOptions) (aicore.To if opts.excludes(entry) { continue } + // A tool that requires approval must not appear in a set built without + // an approver: the model would see a tool it can never invoke. With an + // approver present the tool is built and the execute closure gates each + // call on the human's decision. + if entry.Classification.IsApprovalRequired() && opts.Approval == nil { + continue + } available, err := safeToolAvailable(entry) if err != nil { return nil, fmt.Errorf("tool %s availability: %w", entry.Name, err) @@ -195,6 +208,44 @@ func toolExecute(entry tools.ToolEntry, opts ToolSetOptions) func(context.Contex return "", fmt.Errorf("tool %s: decode input: %w", entry.Name, err) } } + if entry.Classification.IsApprovalRequired() { + if opts.Approval == nil { + return "", fmt.Errorf("tool %s requires approval but no approver is configured", entry.Name) + } + approveCtx, cancel := context.WithTimeout(ctx, tools.ToolApprovalTimeout) + defer cancel() + desc := entry.Description + if entry.BuildApprovalDescription != nil { + desc = entry.BuildApprovalDescription(args) + } + decision, err := opts.Approval.RequestApproval(approveCtx, entry.Name, desc) + if err != nil { + // Distinguish a tool-level timeout (our own deadline) + // from a turn-level cancellation (/stop). A turn + // cancellation must propagate as a context error; a + // tool timeout must surface as a plain error so the + // model can report it instead of the turn aborting. + if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && ctx.Err() == nil { + return "", fmt.Errorf("tool %s: approval timed out after %v", entry.Name, tools.ToolApprovalTimeout) + } + return "", fmt.Errorf("tool %s: approval: %w", entry.Name, err) + } + switch decision { + case tools.ApprovalApproved, tools.ApprovalPermanentlyApproved: + // Fall through to execution. PermanentlyApproved is + // handled by the adapter caching the decision; the + // dispatch layer treats both the same. + case tools.ApprovalDenied: + return "", fmt.Errorf("tool %s: %w", entry.Name, tools.ErrApprovalDenied) + default: + // Fail closed: an unrecognised decision value from + // a faulty or future Approver must not execute the + // tool. ApprovalDecision is an exported int type, + // so a value returned with nil error is a defect + // in the approver, not a grant. + return "", fmt.Errorf("tool %s: approval returned unexpected decision %v", entry.Name, decision) + } + } out, err := entry.Handler(ctx, args) if err != nil { return "", err diff --git a/internal/agentexec/toolset_test.go b/internal/agentexec/toolset_test.go index 936390d0d..e65519425 100644 --- a/internal/agentexec/toolset_test.go +++ b/internal/agentexec/toolset_test.go @@ -471,3 +471,203 @@ func TestToolSetExcludesToolsets(t *testing.T) { t.Error("memory tool was dropped, want only the workspace toolset excluded") } } + +// testApprover is a scripted ApprovalRequester for the tool-approval gate +// tests. It returns whatever decision and error the test wired up, so each +// test exercises one branch of the gate. +type testApprover struct { + decision tools.ApprovalDecision + err error +} + +func (a *testApprover) RequestApproval(context.Context, string, string) (tools.ApprovalDecision, error) { + return a.decision, a.err +} + +// approvalEntry returns a single-entry registry whose tool is marked +// RequiresApproval and records whether its handler ran. +func approvalEntry(t *testing.T, reg *tools.Registry, ran *bool) { + t.Helper() + if err := reg.Register(tools.ToolEntry{ + Name: "gated", + Description: "requires human consent", + Classification: tools.RequiresApproval, + Handler: func(context.Context, map[string]any) (any, error) { + *ran = true + return "ran", nil + }, + }); err != nil { + t.Fatal(err) + } +} + +func TestToolSetApprovalApprovedExecutes(t *testing.T) { + reg := tools.NewRegistry() + ran := false + approvalEntry(t, reg, &ran) + + set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: tools.ApprovalApproved}}) + out, err := set["gated"].Execute(context.Background(), `{}`) + if err != nil { + t.Fatal(err) + } + if !ran { + t.Error("handler did not run after approval was granted") + } + if out != `"ran"` { + t.Errorf("output = %q, want \"ran\"", out) + } +} + +func TestToolSetApprovalDeniedReturnsError(t *testing.T) { + reg := tools.NewRegistry() + ran := false + approvalEntry(t, reg, &ran) + + set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: tools.ApprovalDenied}}) + _, err := set["gated"].Execute(context.Background(), `{}`) + if err == nil { + t.Fatal("expected an error when approval is denied") + } + if !errors.Is(err, tools.ErrApprovalDenied) { + t.Errorf("error = %v, want it to wrap ErrApprovalDenied", err) + } + if ran { + t.Error("handler ran despite the denial") + } +} + +func TestToolSetApprovalPropagatesApproverError(t *testing.T) { + reg := tools.NewRegistry() + ran := false + approvalEntry(t, reg, &ran) + + wantErr := errors.New("approver exploded") + set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{err: wantErr}}) + _, err := set["gated"].Execute(context.Background(), `{}`) + if err == nil { + t.Fatal("expected an error from the approver") + } + if !errors.Is(err, wantErr) { + t.Errorf("error = %v, want it to wrap the approver error", err) + } + if ran { + t.Error("handler ran despite the approver error") + } +} + +func TestToolSetApprovalMissingApproverReturnsError(t *testing.T) { + ran := false + entry := tools.ToolEntry{ + Name: "gated", + Description: "requires human consent", + Classification: tools.RequiresApproval, + Handler: func(context.Context, map[string]any) (any, error) { + ran = true + return "should not run", nil + }, + } + // The build-time gate omits approval-requiring tools from a set built + // without an approver, so exercise the runtime gate directly: the execute + // closure must still refuse to run the tool. + tool := aicore.NewTool(entry.Name, entry.Description, json.RawMessage(`{"type":"object","properties":{}}`), toolExecute(entry, ToolSetOptions{})) + _, err := tool.Execute(context.Background(), `{}`) + if err == nil { + t.Fatal("expected an error when no approver is configured") + } + if !strings.Contains(err.Error(), "no approver") { + t.Errorf("error = %v, want it to name the missing approver", err) + } + if ran { + t.Error("handler ran despite there being no approver") + } +} + +func TestToolSetWithoutApprovalFlagExecutesNormally(t *testing.T) { + reg := tools.NewRegistry() + if err := reg.Register(tools.ToolEntry{ + Name: "plain", + Handler: func(context.Context, map[string]any) (any, error) { return "ok", nil }, + }); err != nil { + t.Fatal(err) + } + + // Even with an approver that would deny, a non-gated tool must run. + set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: tools.ApprovalDenied}}) + out, err := set["plain"].Execute(context.Background(), `{}`) + if err != nil { + t.Fatal(err) + } + if out != `"ok"` { + t.Errorf("output = %q, want \"ok\"", out) + } +} + +func TestBuildToolSetOmitsApprovalToolsWithoutApprover(t *testing.T) { + reg := tools.NewRegistry() + if err := reg.Register(tools.ToolEntry{ + Name: "gated", + Description: "requires human consent", + Classification: tools.RequiresApproval, + Handler: func(context.Context, map[string]any) (any, error) { return nil, nil }, + }); err != nil { + t.Fatal(err) + } + if err := reg.Register(tools.ToolEntry{ + Name: "plain", + Handler: func(context.Context, map[string]any) (any, error) { return nil, nil }, + }); err != nil { + t.Fatal(err) + } + + set := mustBuildToolSetWith(t, reg, ToolSetOptions{}) + if _, ok := set["gated"]; ok { + t.Error("ToolSet included an approval-requiring tool with no approver") + } + if _, ok := set["plain"]; !ok { + t.Error("ToolSet dropped a non-approval tool") + } +} + +func TestBuildToolSetIncludesApprovalToolsWithApprover(t *testing.T) { + reg := tools.NewRegistry() + if err := reg.Register(tools.ToolEntry{ + Name: "gated", + Description: "requires human consent", + Classification: tools.RequiresApproval, + Handler: func(context.Context, map[string]any) (any, error) { return nil, nil }, + }); err != nil { + t.Fatal(err) + } + + set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: tools.ApprovalApproved}}) + if _, ok := set["gated"]; !ok { + t.Error("ToolSet omitted an approval-requiring tool with an approver configured") + } +} + +func TestToolSetApprovalFailsClosedOnUnknownDecision(t *testing.T) { + reg := tools.NewRegistry() + ran := false + approvalEntry(t, reg, &ran) + + // ApprovalDecision 999 is not a recognised constant. The gate must + // fail closed: an unknown value from a faulty approver must not + // execute the tool. + unknownDecision := tools.ApprovalDecision(999) + set := mustBuildToolSetWith(t, reg, ToolSetOptions{Approval: &testApprover{decision: unknownDecision}}) + tool, ok := set["gated"] + if !ok { + t.Fatal("tool not in set") + } + _, err := tool.Execute(context.Background(), `{}`) + if err == nil { + t.Fatal("expected error for unknown decision, got nil") + } + if !strings.Contains(err.Error(), "unexpected decision") { + t.Errorf("error = %v, want 'unexpected decision'", err) + } + if ran { + t.Error("tool executed despite unknown approval decision") + } +} diff --git a/internal/channels/telegram/approval.go b/internal/channels/telegram/approval.go new file mode 100644 index 000000000..ab3c73472 --- /dev/null +++ b/internal/channels/telegram/approval.go @@ -0,0 +1,294 @@ +package telegram + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + + "github.com/samcharles93/archie-core/internal/gateway" +) + +// approvalCallbackPrefix separates tool-approval callbacks from other +// callback types handled in defaultHandler. It is deliberately distinct +// from dangerousCmdPrefix so the two approval systems never collide. +const approvalCallbackPrefix = "approval:" + +// telegramApprover implements gateway.ApprovalRequester by rendering an +// inline-button prompt in the chat it was built for and blocking until the +// human decides, the context is cancelled, or the approval window elapses. +// +// It generalises the dangerous-command approval machinery: instead of +// carrying an onApprove callback that executes a fixed command, a tool +// approval carries a result channel that the callback handler signals, and +// the blocked RequestApproval caller observes the decision. +type telegramApprover struct { + gw *Gateway + bot *bot.Bot + chatID int64 + threadID int + recipient int64 +} + +// pendingApproval records a tool-approval request waiting on a human +// decision. It is the tool-approval analogue of dangerousAction, kept +// separate so the dangerous-command model (onApprove callbacks) and the +// tool-approval model (result channels) cannot entangle. +type pendingApproval struct { + token string + action string + description string + recipient int64 + expiresAt time.Time + resultCh chan approvalResult +} + +// approvalResult carries the human's decision back to the blocked +// RequestApproval call. +type approvalResult struct { + decision gateway.ApprovalDecision + err error +} + +// Compile-time guard. +var _ gateway.ApprovalRequester = (*telegramApprover)(nil) + +// NewApprover returns an ApprovalRequester that renders prompts in the +// given chat. recipient is the Telegram user who may approve; in a private +// DM this is the same as chatID, in a group it is the sender of the turn +// that triggered the gated tool call. +func (g *Gateway) NewApprover(b *bot.Bot, chatID int64, threadID int, recipient int64) gateway.ApprovalRequester { + return &telegramApprover{ + gw: g, + bot: b, + chatID: chatID, + threadID: threadID, + recipient: recipient, + } +} + +// RequestApproval asks the recipient to approve or deny action. +// +// A current permanent approval for the action short-circuits the prompt and +// returns ApprovalPermanentlyApproved. Otherwise the recipient is shown the +// three-button inline keyboard and the call blocks until the human decides, +// the context is cancelled, or the 2-minute approval window +// (gateway.ToolApprovalTimeout) elapses. +func (a *telegramApprover) RequestApproval(ctx context.Context, action, description string) (gateway.ApprovalDecision, error) { + // Compose the lookup key so a permanent approval is scoped to + // the specific resource: "Approve Permanently" on "delete session + // abc123" only permanently approves that one session, not every + // session_delete forever. + permKey := action + "\x00" + description + if a.gw.hasPermanentApprovalExact(a.recipient, permKey) { + return gateway.ApprovalPermanentlyApproved, nil + } + + token := makeDangerousToken() + resultCh := make(chan approvalResult, 1) + a.gw.registerPendingApproval(pendingApproval{ + token: token, + action: action, + description: description, + recipient: a.recipient, + expiresAt: time.Now().Add(gateway.ToolApprovalTimeout), + resultCh: resultCh, + }) + + params := &bot.SendMessageParams{ + ChatID: a.chatID, + Text: approvalPromptText(action, description), + ReplyMarkup: a.gw.approvalKeyboard(token), + } + if a.threadID != 0 { + params.MessageThreadID = a.threadID + } + + approvalCtx, cancel := context.WithTimeout(ctx, gateway.ToolApprovalTimeout) + defer cancel() + + if _, err := a.bot.SendMessage(approvalCtx, params); err != nil { + a.gw.removePendingApproval(token) + if approvalCtx.Err() != nil { + return gateway.ApprovalDenied, approvalCtx.Err() + } + a.gw.log.Error("send approval prompt failed", "error", err) + return gateway.ApprovalDenied, fmt.Errorf("send approval prompt: %w", err) + } + + select { + case result := <-resultCh: + return a.applyApprovalDecision(action, description, result) + case <-approvalCtx.Done(): + // A decision may have raced the timeout: drain it rather than + // discarding a valid approval. + select { + case result := <-resultCh: + return a.applyApprovalDecision(action, description, result) + default: + a.gw.removePendingApproval(token) + return gateway.ApprovalDenied, approvalCtx.Err() + } + } +} + +// applyApprovalDecision maps a human decision to the gateway contract, +// recording a permanent approval when the human asked for one. +func (a *telegramApprover) applyApprovalDecision(action, description string, result approvalResult) (gateway.ApprovalDecision, error) { + switch result.decision { + case gateway.ApprovalApproved: + return gateway.ApprovalApproved, nil + case gateway.ApprovalPermanentlyApproved: + // Scoped: permanently approving "delete session abc123" only + // silences the prompt for that one resource, not every call to + // the same tool. + a.gw.recordPermanentApproval(a.recipient, action+"\x00"+description) + return gateway.ApprovalPermanentlyApproved, nil + case gateway.ApprovalDenied: + if result.err != nil { + return gateway.ApprovalDenied, result.err + } + return gateway.ApprovalDenied, gateway.ErrApprovalDenied + default: + return gateway.ApprovalDenied, fmt.Errorf("unexpected approval decision %v", result.decision) + } +} + +// approvalKeyboard builds the three-button inline keyboard for a tool +// approval: "Approve this time", "Approve Permanently", "Deny". It mirrors +// dangerousKeyboard but carries the approval: callback prefix. +func (g *Gateway) approvalKeyboard(token string) *models.InlineKeyboardMarkup { + return &models.InlineKeyboardMarkup{ + InlineKeyboard: [][]models.InlineKeyboardButton{ + { + { + Text: "Approve this time", + CallbackData: approvalCallbackPrefix + "approve:" + token, + }, + }, + { + { + Text: "Approve Permanently", + CallbackData: approvalCallbackPrefix + "permanent:" + token, + }, + }, + { + { + Text: "Deny", + CallbackData: approvalCallbackPrefix + "deny:" + token, + }, + }, + }, + } +} + +// registerPendingApproval stores a pending tool approval, pruning any that +// have already expired. +func (g *Gateway) registerPendingApproval(pa pendingApproval) { + g.approvalMu.Lock() + defer g.approvalMu.Unlock() + + now := time.Now() + for key, existing := range g.pendingApprovals { + if !existing.expiresAt.After(now) { + delete(g.pendingApprovals, key) + } + } + g.pendingApprovals[pa.token] = &pa +} + +// removePendingApproval drops a pending tool approval, if present. +func (g *Gateway) removePendingApproval(token string) { + g.approvalMu.Lock() + defer g.approvalMu.Unlock() + delete(g.pendingApprovals, token) +} + +// consumePendingApproval validates and atomically consumes the pending +// approval for the callback. It rejects expired tokens and callbacks from +// anyone other than the intended recipient, and enforces single use. +func (g *Gateway) consumePendingApproval(token string, recipient int64) (*pendingApproval, bool) { + g.approvalMu.Lock() + defer g.approvalMu.Unlock() + + pa, found := g.pendingApprovals[token] + if found && pa.recipient == recipient && pa.expiresAt.After(time.Now()) { + delete(g.pendingApprovals, token) + } + return pa, found && pa.recipient == recipient && pa.expiresAt.After(time.Now()) +} + +// handleApprovalCallback is the entrypoint for tool-approval inline-button +// taps. It validates the token (recipient, expiry, single use) and delivers +// the decision to the blocked RequestApproval call. +func (g *Gateway) handleApprovalCallback(ctx context.Context, b *bot.Bot, update *models.Update) { + query := update.CallbackQuery + if query == nil { + return + } + if !g.isSenderAllowed(query.From.ID) { + g.log.Warn("approval callback from unauthorized sender", "user_id", query.From.ID) + g.answerDangerousCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) + return + } + + decision, token := parseApprovalCallback(query.Data) + if decision == "" { + g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true) + return + } + + pa, ok := g.consumePendingApproval(token, query.From.ID) + if !ok { + g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true) + return + } + + g.log.Info("tool approval decision", + "action", pa.action, "decision", decision, + "recipient", query.From.ID, "username", query.From.Username, + ) + + switch decision { + case "approve": + pa.resultCh <- approvalResult{decision: gateway.ApprovalApproved} + g.answerDangerousCallback(ctx, b, query.ID, "Approved and executed.", false) + g.editDangerousMessage(ctx, b, query, "✅ Approved: "+pa.description) + case "permanent": + pa.resultCh <- approvalResult{decision: gateway.ApprovalPermanentlyApproved} + g.answerDangerousCallback(ctx, b, query.ID, "Permanently approved (valid 24h).", false) + g.editDangerousMessage(ctx, b, query, "✅ Approved (permanent, 24h): "+pa.description) + case "deny": + pa.resultCh <- approvalResult{decision: gateway.ApprovalDenied, err: gateway.ErrApprovalDenied} + g.answerDangerousCallback(ctx, b, query.ID, "Action denied.", false) + g.editDangerousMessage(ctx, b, query, "❌ Denied: "+pa.description) + } +} + +// parseApprovalCallback splits an approval callback into decision +// ("approve", "permanent", "deny") and token. +func parseApprovalCallback(data string) (decision, token string) { + data = strings.TrimPrefix(data, approvalCallbackPrefix) + decision, token, _ = strings.Cut(data, ":") + if decision != "approve" && decision != "permanent" && decision != "deny" { + return "", "" + } + return decision, token +} + +// approvalPromptText renders the message shown above the approval keyboard. +// The expiry figure is derived from the shared constant so a change to the +// approval window cannot leave the prompt out of date. +func approvalPromptText(action, description string) string { + minutes := int(gateway.ToolApprovalTimeout.Minutes()) + return fmt.Sprintf( + "⚠️ Approval required\n\n"+ + "Action: %s\n"+ + "%s\n\n"+ + "This request expires in %d minutes.", + action, description, minutes, + ) +} diff --git a/internal/channels/telegram/approval_test.go b/internal/channels/telegram/approval_test.go new file mode 100644 index 000000000..8a5b2ae2f --- /dev/null +++ b/internal/channels/telegram/approval_test.go @@ -0,0 +1,415 @@ +package telegram + +import ( + "context" + "errors" + "log/slog" + "strings" + "testing" + "time" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + + "github.com/samcharles93/archie-core/internal/gateway" +) + +const ( + approvalTestChatID = int64(7) + approvalTestRecipient = int64(42) +) + +func newApprovalTestGateway(t *testing.T) (*Gateway, *bot.Bot, *[]telegramRequest) { + t.Helper() + g := New("1:test", "", "", []int64{approvalTestRecipient}, slog.Default()) + b, requests := newTelegramTestBot(t) + return g, b, requests +} + +func newTestApprover(g *Gateway, b *bot.Bot) gateway.ApprovalRequester { + return g.NewApprover(b, approvalTestChatID, 0, approvalTestRecipient) +} + +// waitForPendingApproval polls the mutex-protected pending-approval map for +// the token RequestApproval registered. Polling the map (not the request +// recorder) is race-free: registerPendingApproval happens-before the goroutine +// blocks, and the map is guarded by approvalMu. +func waitForPendingApproval(t *testing.T, g *Gateway) string { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + g.approvalMu.Lock() + var token string + for tk := range g.pendingApprovals { + token = tk + break + } + g.approvalMu.Unlock() + if token != "" { + return token + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("no pending approval was registered") + return "" +} + +// ── Permanent approval short-circuit ───────────────────────────── + +func TestApprovalRequestPermanentShortCircuits(t *testing.T) { + g, b, requests := newApprovalTestGateway(t) + + g.dangerousMu.Lock() + g.permanentApprovals = append(g.permanentApprovals, permanentApproval{ + CommandPattern: "session_delete\x00Permanently delete session", + Recipient: approvalTestRecipient, + GrantedAt: time.Now(), + ExpiresAt: time.Now().Add(24 * time.Hour), + Scope: "test permanent approval", + }) + g.dangerousMu.Unlock() + + approver := newTestApprover(g, b) + decision, err := approver.RequestApproval(context.Background(), "session_delete", "Permanently delete session") + if err != nil { + t.Fatalf("RequestApproval error = %v", err) + } + if decision != gateway.ApprovalPermanentlyApproved { + t.Errorf("decision = %v, want ApprovalPermanentlyApproved", decision) + } + if len(*requests) != 0 { + t.Errorf("permanent approval rendered a prompt: %#v", *requests) + } + if len(g.pendingApprovals) != 0 { + t.Errorf("permanent approval registered a pending request: %#v", g.pendingApprovals) + } +} + +func TestApprovalRequestPermanentViaButton(t *testing.T) { + g, b, _ := newApprovalTestGateway(t) + approver := newTestApprover(g, b) + + done := make(chan struct{}) + var decision gateway.ApprovalDecision + var err error + go func() { + decision, err = approver.RequestApproval(context.Background(), "session_delete", "Delete session") + close(done) + }() + + token := waitForPendingApproval(t, g) + + g.handleApprovalCallback(context.Background(), b, &models.Update{ + CallbackQuery: &models.CallbackQuery{ + ID: "callback-id", + From: models.User{ID: approvalTestRecipient}, + Data: approvalCallbackPrefix + "permanent:" + token, + }, + }) + + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("RequestApproval did not return after permanent button") + } + if decision != gateway.ApprovalPermanentlyApproved { + t.Errorf("decision = %v, want ApprovalPermanentlyApproved", decision) + } + if err != nil { + t.Errorf("err = %v, want nil", err) + } + + g.dangerousMu.Lock() + var found bool + for _, pa := range g.permanentApprovals { + if pa.CommandPattern == "session_delete\x00Delete session" && pa.Recipient == approvalTestRecipient { + found = true + } + } + g.dangerousMu.Unlock() + if !found { + t.Error("permanent approval was not recorded") + } +} + +// ── Approve / deny through the callback handler ─────────────────── + +func TestApprovalRequestApprove(t *testing.T) { + g, b, _ := newApprovalTestGateway(t) + approver := newTestApprover(g, b) + + done := make(chan struct{}) + var decision gateway.ApprovalDecision + var err error + go func() { + decision, err = approver.RequestApproval(context.Background(), "session_delete", "Delete session") + close(done) + }() + + token := waitForPendingApproval(t, g) + + g.handleApprovalCallback(context.Background(), b, &models.Update{ + CallbackQuery: &models.CallbackQuery{ + ID: "callback-id", + From: models.User{ID: approvalTestRecipient}, + Data: approvalCallbackPrefix + "approve:" + token, + }, + }) + + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("RequestApproval did not return after approve") + } + if decision != gateway.ApprovalApproved { + t.Errorf("decision = %v, want ApprovalApproved", decision) + } + if err != nil { + t.Errorf("err = %v, want nil", err) + } +} + +func TestApprovalRequestDenied(t *testing.T) { + g, b, _ := newApprovalTestGateway(t) + approver := newTestApprover(g, b) + + done := make(chan struct{}) + var decision gateway.ApprovalDecision + var err error + go func() { + decision, err = approver.RequestApproval(context.Background(), "session_delete", "Delete session") + close(done) + }() + + token := waitForPendingApproval(t, g) + + g.handleApprovalCallback(context.Background(), b, &models.Update{ + CallbackQuery: &models.CallbackQuery{ + ID: "callback-id", + From: models.User{ID: approvalTestRecipient}, + Data: approvalCallbackPrefix + "deny:" + token, + }, + }) + + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("RequestApproval did not return after deny") + } + if decision != gateway.ApprovalDenied { + t.Errorf("decision = %v, want ApprovalDenied", decision) + } + if !errors.Is(err, gateway.ErrApprovalDenied) { + t.Errorf("err = %v, want ErrApprovalDenied", err) + } +} + +// ── Timeout / ctx cancellation ─────────────────────────────────── + +func TestApprovalRequestTimeoutReturnsContextError(t *testing.T) { + g, b, _ := newApprovalTestGateway(t) + approver := newTestApprover(g, b) + + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + + decision, err := approver.RequestApproval(ctx, "session_delete", "Delete session") + if decision != gateway.ApprovalDenied { + t.Errorf("decision = %v, want ApprovalDenied on timeout", decision) + } + if err == nil { + t.Fatal("expected a context error on timeout") + } + if errors.Is(err, gateway.ErrApprovalDenied) { + t.Errorf("timeout must not be ErrApprovalDenied, got %v", err) + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("err = %v, want context.DeadlineExceeded", err) + } + g.approvalMu.Lock() + defer g.approvalMu.Unlock() + if len(g.pendingApprovals) != 0 { + t.Errorf("timed-out approval was not cleaned up: %#v", g.pendingApprovals) + } +} + +// ── Callback validation ────────────────────────────────────────── + +func TestApprovalCallbackExpiredTokenRejected(t *testing.T) { + g, b, requests := newApprovalTestGateway(t) + + token := makeDangerousToken() + g.registerPendingApproval(pendingApproval{ + token: token, + action: "session_delete", + description: "Delete session", + recipient: approvalTestRecipient, + expiresAt: time.Now().Add(-1 * time.Minute), + resultCh: make(chan approvalResult, 1), + }) + + g.handleApprovalCallback(context.Background(), b, &models.Update{ + CallbackQuery: &models.CallbackQuery{ + ID: "callback-id", + From: models.User{ID: approvalTestRecipient}, + Data: approvalCallbackPrefix + "approve:" + token, + }, + }) + + for _, req := range *requests { + if req.method == "answerCallbackQuery" && req.form["text"] == "That action is no longer valid." { + return + } + } + t.Errorf("expired token was not rejected; requests: %#v", *requests) +} + +func TestApprovalCallbackWrongRecipientRejected(t *testing.T) { + const otherUserID = int64(43) + g := New("1:test", "", "", []int64{approvalTestRecipient, otherUserID}, slog.Default()) + b, requests := newTelegramTestBot(t) + + token := makeDangerousToken() + g.registerPendingApproval(pendingApproval{ + token: token, + action: "session_delete", + description: "Delete session", + recipient: approvalTestRecipient, + expiresAt: time.Now().Add(10 * time.Minute), + resultCh: make(chan approvalResult, 1), + }) + + g.handleApprovalCallback(context.Background(), b, &models.Update{ + CallbackQuery: &models.CallbackQuery{ + ID: "callback-id", + From: models.User{ID: otherUserID}, + Data: approvalCallbackPrefix + "approve:" + token, + }, + }) + + // The intended recipient's pending approval must survive. + g.approvalMu.Lock() + _, found := g.pendingApprovals[token] + g.approvalMu.Unlock() + if !found { + t.Error("wrong recipient's callback consumed the approval") + } + + var rejected bool + for _, req := range *requests { + if req.method == "answerCallbackQuery" && req.form["text"] == "That action is no longer valid." { + rejected = true + } + } + if !rejected { + t.Errorf("wrong recipient was not rejected; requests: %#v", *requests) + } +} + +// ── Prefix discipline and dispatch ─────────────────────────────── + +func TestApprovalCallbackPrefixDistinctFromDangerous(t *testing.T) { + if approvalCallbackPrefix == dangerousCmdPrefix { + t.Fatalf("approvalCallbackPrefix %q must differ from dangerousCmdPrefix %q", approvalCallbackPrefix, dangerousCmdPrefix) + } + if approvalCallbackPrefix != "approval:" { + t.Errorf("approvalCallbackPrefix = %q, want %q", approvalCallbackPrefix, "approval:") + } +} + +func TestDefaultHandlerDispatchesApprovalCallback(t *testing.T) { + g, b, requests := newApprovalTestGateway(t) + router := gateway.NewRouter(nil, nil, "telegram") + + token := makeDangerousToken() + g.registerPendingApproval(pendingApproval{ + token: token, + action: "session_delete", + description: "Delete session", + recipient: approvalTestRecipient, + expiresAt: time.Now().Add(10 * time.Minute), + resultCh: make(chan approvalResult, 1), + }) + + g.defaultHandler(router)(context.Background(), b, &models.Update{ + CallbackQuery: &models.CallbackQuery{ + ID: "callback-id", + From: models.User{ID: approvalTestRecipient}, + Data: approvalCallbackPrefix + "approve:" + token, + }, + }) + + var answered bool + for _, req := range *requests { + if req.method == "answerCallbackQuery" { + answered = true + } + } + if !answered { + t.Errorf("defaultHandler did not route approval callback; requests: %#v", *requests) + } + + g.approvalMu.Lock() + _, found := g.pendingApprovals[token] + g.approvalMu.Unlock() + if found { + t.Error("approval callback was not consumed by defaultHandler") + } +} + +// ── Prompt and keyboard rendering ──────────────────────────────── + +func TestApprovalPromptText(t *testing.T) { + text := approvalPromptText("session_delete", "Permanently delete session 'Refactor'") + for _, want := range []string{"Approval required", "session_delete", "Permanently delete session 'Refactor'"} { + if !strings.Contains(text, want) { + t.Errorf("prompt missing %q: %s", want, text) + } + } +} + +func TestApprovalKeyboardUsesApprovalPrefix(t *testing.T) { + g := New("1:test", "", "", []int64{approvalTestRecipient}, slog.Default()) + markup := g.approvalKeyboard("token123") + + if len(markup.InlineKeyboard) != 3 { + t.Fatalf("keyboard rows = %d, want 3", len(markup.InlineKeyboard)) + } + wantButtons := []string{"Approve this time", "Approve Permanently", "Deny"} + for i, want := range wantButtons { + if markup.InlineKeyboard[i][0].Text != want { + t.Errorf("button %d text = %q, want %q", i, markup.InlineKeyboard[i][0].Text, want) + } + if !strings.HasPrefix(markup.InlineKeyboard[i][0].CallbackData, approvalCallbackPrefix) { + t.Errorf("button %d callback = %q, want %q prefix", i, markup.InlineKeyboard[i][0].CallbackData, approvalCallbackPrefix) + } + } + if !strings.Contains(markup.InlineKeyboard[0][0].CallbackData, "token123") { + t.Errorf("approve callback = %q, want token embedded", markup.InlineKeyboard[0][0].CallbackData) + } +} + +func TestParseApprovalCallback(t *testing.T) { + tests := []struct { + name string + data string + decision string + token string + }{ + {name: "approve", data: approvalCallbackPrefix + "approve:abc", decision: "approve", token: "abc"}, + {name: "permanent", data: approvalCallbackPrefix + "permanent:def", decision: "permanent", token: "def"}, + {name: "deny", data: approvalCallbackPrefix + "deny:ghi", decision: "deny", token: "ghi"}, + {name: "dangerous prefix is not approval", data: dangerousCmdPrefix + "approve:abc", decision: "", token: ""}, + {name: "unknown decision", data: approvalCallbackPrefix + "unknown:abc", decision: "", token: ""}, + {name: "empty", data: "", decision: "", token: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + decision, token := parseApprovalCallback(tt.data) + if decision != tt.decision || token != tt.token { + t.Errorf("parseApprovalCallback(%q) = (%q, %q), want (%q, %q)", + tt.data, decision, token, tt.decision, tt.token) + } + }) + } +} diff --git a/internal/channels/telegram/dangerous.go b/internal/channels/telegram/dangerous.go index 8d9643901..db3c5eb60 100644 --- a/internal/channels/telegram/dangerous.go +++ b/internal/channels/telegram/dangerous.go @@ -273,6 +273,31 @@ func (g *Gateway) hasPermanentApproval(recipient int64, command string) bool { return found } +// hasPermanentApprovalExact is the exact-match variant used by the tool +// approval path. Prefix matching is appropriate for slash commands +// (/rollback covers /rollback 3); it is not for tool-approval keys +// composed of action + resource, where "delete session abc" must not +// grant on "delete session abc2". +func (g *Gateway) hasPermanentApprovalExact(recipient int64, pattern string) bool { + g.dangerousMu.Lock() + defer g.dangerousMu.Unlock() + + now := time.Now() + kept := g.permanentApprovals[:0] + found := false + for _, pa := range g.permanentApprovals { + if !pa.ExpiresAt.After(now) { + continue + } + kept = append(kept, pa) + if pa.Recipient == recipient && pa.CommandPattern == pattern { + found = true + } + } + g.permanentApprovals = kept + return found +} + func (g *Gateway) editDangerousMessage(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, text string) { if query.Message.Message == nil { return diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index c521a023f..cf500c871 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -73,6 +73,13 @@ type Gateway struct { dangerousActions map[string]dangerousAction permanentApprovals []permanentApproval + // tool approval state (gateway.ApprovalRequester). Kept separate from + // the dangerous-command state above: tool approvals deliver the human's + // decision on a channel to the blocked RequestApproval call rather than + // executing through an onApprove callback. + approvalMu sync.Mutex + pendingApprovals map[string]*pendingApproval + // turns serialises chat turns per session off the update worker and // makes the running one cancellable by /stop. Rebuilt on every launch // so a restart abandons in-flight turns with the old bot instance. @@ -119,6 +126,7 @@ func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *s updateActions: make(map[string]updateAction), dangerousActions: make(map[string]dangerousAction), permanentApprovals: nil, + pendingApprovals: make(map[string]*pendingApproval), log: log.With("component", "gateway-telegram"), } } @@ -433,26 +441,7 @@ func (g *Gateway) startHandler() bot.HandlerFunc { func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { return func(ctx context.Context, b *bot.Bot, update *models.Update) { if update.CallbackQuery != nil { - switch { - case strings.HasPrefix(update.CallbackQuery.Data, dangerousCmdPrefix): - g.handleDangerousCallback(ctx, b, update) - case strings.HasPrefix(update.CallbackQuery.Data, providerCallbackPrefix): - g.handleProviderCallback(ctx, b, update, router) - case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix): - g.handleModelCallback(ctx, b, update, router) - case strings.HasPrefix(update.CallbackQuery.Data, modelPageCallbackPrefix): - g.handleModelPageCallback(ctx, b, update, router) - case update.CallbackQuery.Data == modelBackCallback: - g.handleModelBackCallback(ctx, b, update, router) - case update.CallbackQuery.Data == modelCancelCallback: - g.handleModelCancelCallback(ctx, b, update) - case update.CallbackQuery.Data == modelNoopCallback: - g.handleModelNoopCallback(ctx, b, update) - case strings.HasPrefix(update.CallbackQuery.Data, personalityCallbackPrefix): - g.handlePersonalityCallback(ctx, b, update, router) - case strings.HasPrefix(update.CallbackQuery.Data, updateCallbackPrefix): - g.handleUpdateCallback(ctx, b, update) - } + g.handleCallback(ctx, b, update, router) return } @@ -476,6 +465,34 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { } } +// handleCallback dispatches an inline-button callback query to the handler +// for its prefix. Callback prefixes are mutually exclusive; an unknown +// callback is ignored. +func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models.Update, router *gateway.Router) { + switch { + case strings.HasPrefix(update.CallbackQuery.Data, approvalCallbackPrefix): + g.handleApprovalCallback(ctx, b, update) + case strings.HasPrefix(update.CallbackQuery.Data, dangerousCmdPrefix): + g.handleDangerousCallback(ctx, b, update) + case strings.HasPrefix(update.CallbackQuery.Data, providerCallbackPrefix): + g.handleProviderCallback(ctx, b, update, router) + case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix): + g.handleModelCallback(ctx, b, update, router) + case strings.HasPrefix(update.CallbackQuery.Data, modelPageCallbackPrefix): + g.handleModelPageCallback(ctx, b, update, router) + case update.CallbackQuery.Data == modelBackCallback: + g.handleModelBackCallback(ctx, b, update, router) + case update.CallbackQuery.Data == modelCancelCallback: + g.handleModelCancelCallback(ctx, b, update) + case update.CallbackQuery.Data == modelNoopCallback: + g.handleModelNoopCallback(ctx, b, update) + case strings.HasPrefix(update.CallbackQuery.Data, personalityCallbackPrefix): + g.handlePersonalityCallback(ctx, b, update, router) + case strings.HasPrefix(update.CallbackQuery.Data, updateCallbackPrefix): + g.handleUpdateCallback(ctx, b, update) + } +} + // submitTurn hands the message to its session's turn lane and returns at // once, leaving the bot's single update worker free. // @@ -510,6 +527,12 @@ func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Messag chatID, threadID := msg.Chat.ID, msg.MessageThreadID g.turns.Submit(ctx, session, func(turnCtx context.Context) { + // If the turn invokes a tool that requires human approval, + // the dispatch layer blocks on this approver. Nil is fine + // — most turns need no gating. + approver := g.NewApprover(b, chatID, threadID, msg.From.ID) + turnCtx = gateway.WithApprovalRequester(turnCtx, approver) + // reply appears as it is written; the typing indicator covers the // gap before the first token and any non-streaming path. stopTyping := g.startTyping(turnCtx, b, chatID, threadID) diff --git a/internal/gateway/approval.go b/internal/gateway/approval.go new file mode 100644 index 000000000..9c7fa9c6d --- /dev/null +++ b/internal/gateway/approval.go @@ -0,0 +1,38 @@ +// Package gateway: approval.go — re-exports the tool-approval contract +// from internal/tools so existing gateway-internal and adapter code +// continues to compile against the names it already uses. +// +// The canonical definitions live in internal/tools/approval.go so that +// internal/agentexec (also used by the archie-agent sandbox binary) can +// import them without pulling in the chat-gateway domain stack. + +package gateway + +import "github.com/samcharles93/archie-core/internal/tools" + +// Re-exported types so gateway-internal code uses the same concrete types +// as the dispatch layer without qualification churn. +type ( + ApprovalRequester = tools.ApprovalRequester + ApprovalDecision = tools.ApprovalDecision +) + +// Re-exported constants. +const ( + ApprovalApproved = tools.ApprovalApproved + ApprovalPermanentlyApproved = tools.ApprovalPermanentlyApproved + ApprovalDenied = tools.ApprovalDenied + ToolApprovalTimeout = tools.ToolApprovalTimeout +) + +// Re-exported sentinel errors. +var ( + ErrApprovalDenied = tools.ErrApprovalDenied + ErrApprovalNotConfigured = tools.ErrApprovalNotConfigured +) + +// Re-exported context plumbing. +var ( + WithApprovalRequester = tools.WithApprovalRequester + ApprovalFromContext = tools.ApprovalFromContext +) diff --git a/internal/gateway/approval_test.go b/internal/gateway/approval_test.go new file mode 100644 index 000000000..144152eaa --- /dev/null +++ b/internal/gateway/approval_test.go @@ -0,0 +1,77 @@ +package gateway + +import ( + "context" + "errors" + "testing" + "time" +) + +// approvalStub is a test double that returns a fixed decision or error. +type approvalStub struct { + decision ApprovalDecision + err error +} + +func (s *approvalStub) RequestApproval(_ context.Context, _, _ string) (ApprovalDecision, error) { + return s.decision, s.err +} + +func TestApprovalDecisionConstantsAreDistinct(t *testing.T) { + seen := make(map[ApprovalDecision]bool) + for _, d := range []ApprovalDecision{ + ApprovalApproved, + ApprovalPermanentlyApproved, + ApprovalDenied, + } { + if seen[d] { + t.Errorf("duplicate decision value %d", d) + } + seen[d] = true + } +} + +func TestApprovalStubRecordsRequests(t *testing.T) { + s := &approvalStub{decision: ApprovalApproved} + d, err := s.RequestApproval(context.Background(), "test_tool", "does something") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if d != ApprovalApproved { + t.Errorf("decision = %v, want Approved", d) + } +} + +func TestApprovalStubReturnsDenial(t *testing.T) { + s := &approvalStub{decision: ApprovalDenied} + d, err := s.RequestApproval(context.Background(), "x", "") + if err != nil || d != ApprovalDenied { + t.Errorf("(decision=%v, err=%v), want (Denied, nil)", d, err) + } +} + +func TestApprovalStubReturnsError(t *testing.T) { + s := &approvalStub{err: errors.New("timeout")} + _, err := s.RequestApproval(context.Background(), "x", "") + if err == nil { + t.Error("expected error from stub") + } +} + +func TestErrApprovalDeniedIsDistinguishable(t *testing.T) { + if !errors.Is(ErrApprovalDenied, ErrApprovalDenied) { + t.Error("ErrApprovalDenied does not match itself") + } + if errors.Is(ErrApprovalDenied, ErrApprovalNotConfigured) { + t.Error("ErrApprovalDenied should not match ErrApprovalNotConfigured") + } +} + +func TestToolApprovalTimeoutIsReasonable(t *testing.T) { + if ToolApprovalTimeout < time.Minute { + t.Errorf("timeout %v is too short for a human to decide", ToolApprovalTimeout) + } + if ToolApprovalTimeout > 5*time.Minute { + t.Errorf("timeout %v is too long for an LLM connection to hold", ToolApprovalTimeout) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d7a6298d1..e53387036 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -286,6 +286,13 @@ func (r *Router) InitSessions(sessions SessionStore) { r.sessionTracker = newSessionTracker(sessions) } +// SessionTracker exposes the session tracker so that tool constructors +// (SessionTools) can bind session_resume to the active session without +// reaching into the Router's unexported fields. +func (r *Router) SessionTracker() *sessionTracker { + return r.sessionTracker +} + // Route dispatches msg and returns the reply. Gateway-local commands // are handled directly; everything else goes to the LLM responder. func (r *Router) Route(ctx context.Context, msg Message) (string, error) { diff --git a/internal/gateway/session_tools.go b/internal/gateway/session_tools.go new file mode 100644 index 000000000..f4664dd9c --- /dev/null +++ b/internal/gateway/session_tools.go @@ -0,0 +1,321 @@ +package gateway + +import ( + "context" + "fmt" + "slices" + "strings" + "time" + + "github.com/samcharles93/archie-core/internal/tools" +) + +const ( + // defaultSessionListLimit is how many sessions a bare session_list returns. + defaultSessionListLimit = 20 + + // maxSessionListLimit bounds what the model can ask for. A chat that has + // churned for months could otherwise land its whole session catalog in the + // context window whole. + maxSessionListLimit = 100 + + // maxSessionTitleLen bounds the title session_title will accept. Titles are + // rendered in command replies and the dashboard; an unbounded one would let + // a model bloat every surface that shows it. + maxSessionTitleLen = 80 +) + +// ChatSessionSummary is the per-session view the session tools return. It is +// deliberately narrower than a store session: the source tuple (platform, bot, +// channel, thread) is addressing metadata, not something that helps the model +// pick which conversation to resume. +type ChatSessionSummary struct { + ID string `json:"id"` + Title string `json:"title"` + BranchName string `json:"branch_name,omitempty"` + CreatedAt time.Time `json:"created_at"` + LastActiveAt time.Time `json:"last_active_at"` +} + +// SessionListResult is what session_list returns. +type SessionListResult struct { + Sessions []ChatSessionSummary `json:"sessions"` +} + +// SessionResumeResult is what session_resume returns. +type SessionResumeResult struct { + SessionID string `json:"session_id"` + Title string `json:"title"` + Message string `json:"message"` +} + +// SessionTitleResult is what session_title returns. +type SessionTitleResult struct { + SessionID string `json:"session_id"` + Title string `json:"title"` + PreviousTitle string `json:"previous_title"` +} + +// SessionDeleteResult is what session_delete returns. +type SessionDeleteResult struct { + SessionID string `json:"session_id"` + Title string `json:"title"` + Message string `json:"message"` +} + +// SessionTools builds the chat tools that let Archie manage its own sessions. +// Until these existed, /resume, /title and /delete were slash commands only a +// human could type, so "switch back to that conversation" had no tool path at +// all. +// +// The tools are scoped to the current platform + channel: session_list returns +// only this channel's sessions (not every session the daemon knows), and +// session_resume/session_delete resolve references against that same scoped +// list. A model in chat A cannot list or manipulate chat B's history. +// +// msg is captured so the handlers act on the chat they were built for; the +// model never supplies a channel or thread. +// +// A nil store omits every tool rather than registering ones that always fail, +// so a daemon without session support advertises nothing. A nil tracker omits +// the two tools that need it (session_resume and session_delete). +func SessionTools(store SessionStore, tracker *sessionTracker, platform string, msg Message) []tools.ToolEntry { + if store == nil { + return nil + } + channelID := msg.ChannelID + var entries []tools.ToolEntry + entries = append(entries, sessionListTool(store, platform, channelID)) + if tracker != nil { + entries = append(entries, sessionResumeTool(store, tracker, platform, channelID, msg)) + entries = append(entries, sessionDeleteTool(store, tracker, platform, channelID)) + } + entries = append(entries, sessionTitleTool(store, platform, channelID)) + return entries +} + +func sessionListTool(store SessionStore, platform, channelID string) tools.ToolEntry { + return tools.ToolEntry{ + Name: "session_list", + Toolset: "session", + Description: "List this chat's sessions, most recent first. " + + "Use it to answer questions about past conversations and to find the " + + "session_id for session_resume, session_title or session_delete.", + Classification: tools.ClassIdempotent, + Schema: tools.JSONSchema{ + "type": "object", + "properties": map[string]any{ + "limit": map[string]any{ + "type": "integer", + "description": fmt.Sprintf("Maximum sessions to return. Defaults to %d, capped at %d.", defaultSessionListLimit, maxSessionListLimit), + }, + }, + }, + Handler: func(ctx context.Context, input map[string]any) (any, error) { + limit := sessionListLimit(input) + + all, err := store.GetByChannel(ctx, platform, channelID) + if err != nil { + return nil, fmt.Errorf("session_list: %w", err) + } + // GetByChannel returns newest first by contract, but sort anyway + // so the tool never depends on a backend honouring ordering. + slices.SortStableFunc(all, func(a, b SessionContext) int { + return sessionRecency(b).Compare(sessionRecency(a)) + }) + if len(all) > limit { + all = all[:limit] + } + // Non-nil even when empty: an empty catalog is an answer, and a + // null would read to the model as a failed call worth retrying. + sessions := make([]ChatSessionSummary, 0, len(all)) + for _, s := range all { + sessions = append(sessions, ChatSessionSummary{ + ID: s.SessionID, + Title: sessionDisplayTitle(s), + BranchName: s.BranchName, + CreatedAt: s.CreatedAt, + LastActiveAt: s.LastActiveAt, + }) + } + return SessionListResult{Sessions: sessions}, nil + }, + } +} + +func sessionResumeTool(store SessionStore, tracker *sessionTracker, platform, channelID string, msg Message) tools.ToolEntry { + return tools.ToolEntry{ + Name: "session_resume", + Toolset: "session", + Description: "Make the named session the active one for this chat, so subsequent messages " + + "continue that conversation. Use it when the user asks to resume or switch to a " + + "conversation listed by session_list.", + Classification: tools.ClassMutating, + Schema: tools.JSONSchema{ + "type": "object", + "properties": map[string]any{ + "session_id": map[string]any{ + "type": "string", + "description": "The session ID or a unique prefix, same as /resume.", + }, + }, + "required": []any{"session_id"}, + }, + Handler: func(ctx context.Context, input map[string]any) (any, error) { + ref := strings.TrimSpace(asString(input["session_id"])) + if ref == "" { + return nil, fmt.Errorf("session_resume: session_id is required") + } + + sessions, err := store.GetByChannel(ctx, platform, channelID) + if err != nil { + return nil, fmt.Errorf("session_resume: %w", err) + } + match, ambiguous := resolveSessionRef(sessions, ref) + switch { + case ambiguous: + return nil, fmt.Errorf("session_resume: multiple sessions match %q; be more specific", ref) + case match == nil: + return nil, fmt.Errorf("session_resume: no session matching %q", ref) + } + + // The channel+thread are the ones this tool was built for, never + // input. Tracker presence is guaranteed: SessionTools omits the + // tool when no tracker is wired. + tracker.setActive(msg.ChannelID, msg.ThreadID, match.SessionID) + return SessionResumeResult{ + SessionID: match.SessionID, + Title: sessionDisplayTitle(*match), + Message: fmt.Sprintf("Resumed session %s (%s).", + shortSessionID(match.SessionID), sessionDisplayTitle(*match)), + }, nil + }, + } +} + +func sessionTitleTool(store SessionStore, platform, channelID string) tools.ToolEntry { + return tools.ToolEntry{ + Name: "session_title", + Toolset: "session", + Description: "Set a display title on a session. Use it when the user asks to name or " + + "rename a conversation.", + Classification: tools.ClassMutating, + Schema: tools.JSONSchema{ + "type": "object", + "properties": map[string]any{ + "session_id": map[string]any{ + "type": "string", + "description": "The session ID, as returned by session_list.", + }, + "title": map[string]any{ + "type": "string", + "description": fmt.Sprintf("New title, at most %d characters.", maxSessionTitleLen), + }, + }, + "required": []any{"session_id", "title"}, + }, + Handler: func(ctx context.Context, input map[string]any) (any, error) { + sessionID := strings.TrimSpace(asString(input["session_id"])) + if sessionID == "" { + return nil, fmt.Errorf("session_title: session_id is required") + } + title := strings.TrimSpace(asString(input["title"])) + if title == "" { + return nil, fmt.Errorf("session_title: title is required") + } + if len([]rune(title)) > maxSessionTitleLen { + return nil, fmt.Errorf("session_title: title must be at most %d characters", maxSessionTitleLen) + } + + sc, err := store.Get(ctx, sessionID) + if err != nil { + return nil, fmt.Errorf("session_title: %w", err) + } + if sc == nil { + return nil, fmt.Errorf("session_title: session %q not found", sessionID) + } + // Guard against cross-channel writes: the session the model named + // must belong to the channel this turn is running in. + if sc.Source.Platform != platform || sc.Source.ChannelID != channelID { + return nil, fmt.Errorf("session_title: session %q does not belong to this channel", sessionID) + } + previous := sc.Title + sc.Title = title + if err := store.Save(ctx, *sc); err != nil { + return nil, fmt.Errorf("session_title: %w", err) + } + return SessionTitleResult{ + SessionID: sc.SessionID, + Title: title, + PreviousTitle: previous, + }, nil + }, + } +} + +func sessionDeleteTool(store SessionStore, tracker *sessionTracker, platform, channelID string) tools.ToolEntry { + return tools.ToolEntry{ + Name: "session_delete", + Toolset: "session", + Description: "Permanently delete a session and its message history. " + + "The dispatch layer asks a human to approve this before it runs.", + Classification: tools.ClassMutating | tools.RequiresApproval, + BuildApprovalDescription: func(input map[string]any) string { + id := strings.TrimSpace(asString(input["session_id"])) + return fmt.Sprintf("Permanently delete session %q and its message history. This cannot be undone.", id) + }, + Schema: tools.JSONSchema{ + "type": "object", + "properties": map[string]any{ + "session_id": map[string]any{ + "type": "string", + "description": "The session ID or a unique prefix, same as /delete.", + }, + }, + "required": []any{"session_id"}, + }, + Handler: func(ctx context.Context, input map[string]any) (any, error) { + ref := strings.TrimSpace(asString(input["session_id"])) + if ref == "" { + return nil, fmt.Errorf("session_delete: session_id is required") + } + + sessions, err := store.GetByChannel(ctx, platform, channelID) + if err != nil { + return nil, fmt.Errorf("session_delete: %w", err) + } + target, ambiguous := resolveSessionRef(sessions, ref) + switch { + case ambiguous: + return nil, fmt.Errorf("session_delete: multiple sessions match %q; be more specific", ref) + case target == nil: + return nil, fmt.Errorf("session_delete: no session matching %q", ref) + } + + if err := store.Delete(ctx, target.SessionID); err != nil { + return nil, fmt.Errorf("session_delete: %w", err) + } + // Only after the store has let go of it, mirroring /delete: a + // failed delete leaves the session live, and dropping the tracker + // entry then would strand the operator's conversation for no + // reason. + tracker.forget(target.SessionID) + return SessionDeleteResult{ + SessionID: target.SessionID, + Title: sessionDisplayTitle(*target), + Message: fmt.Sprintf("Deleted session %s (%s) and its history.", + shortSessionID(target.SessionID), sessionDisplayTitle(*target)), + }, nil + }, + } +} + +// sessionListLimit resolves the requested limit, falling back to the default +// for anything absent or non-positive and clamping the rest, exactly like the +// task list limit. +// +// JSON numbers decode as float64, but a model that emits an integer through a +// different provider path can arrive as int, so both are accepted. +func sessionListLimit(input map[string]any) int { + return tools.ListLimit(input, defaultSessionListLimit, maxSessionListLimit) +} diff --git a/internal/gateway/session_tools_test.go b/internal/gateway/session_tools_test.go new file mode 100644 index 000000000..fbd9f32de --- /dev/null +++ b/internal/gateway/session_tools_test.go @@ -0,0 +1,321 @@ +package gateway + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/tools" +) + +// seedSessionAt persists one session directly, bypassing the tracker, with an +// explicit recency time so ordering tests are deterministic. Source fields are +// fixed so GetByChannel and List behave deterministically. +func seedSessionAt(store SessionStore, id, title string, at time.Time) SessionContext { + sc := SessionContext{ + SessionID: id, + Source: SessionSource{ + Platform: "test-gw", + BotUser: "archie", + ChannelID: "chat-1", + }, + Title: title, + CreatedAt: at, + LastActiveAt: at, + } + _ = store.Save(context.Background(), sc) + return sc +} + +// sessionTool pulls one entry out of the session tool set. +func sessionTool(t *testing.T, entries []tools.ToolEntry, name string) tools.ToolEntry { + t.Helper() + for _, e := range entries { + if e.Name == name { + return e + } + } + t.Fatalf("SessionTools() has no %q entry", name) + return tools.ToolEntry{} +} + +func TestSessionToolListReturnsSessions(t *testing.T) { + store := newFakeSessionStore() + tr := newSessionTracker(store) + entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_list") + + now := time.Now() + seedSessionAt(store, "sess-1", "one", now.Add(-3*time.Hour)) + seedSessionAt(store, "sess-2", "two", now.Add(-2*time.Hour)) + seedSessionAt(store, "sess-3", "", now.Add(-time.Hour)) + + out, err := entry.Handler(context.Background(), map[string]any{}) + if err != nil { + t.Fatalf("handler: %v", err) + } + result, ok := out.(SessionListResult) + if !ok { + t.Fatalf("handler returned %T, want SessionListResult", out) + } + if len(result.Sessions) != 3 { + t.Fatalf("got %d sessions, want 3", len(result.Sessions)) + } + // Newest first, per the tool contract. + if got := result.Sessions[0].ID; got != "sess-3" { + t.Errorf("first session = %q, want the newest (sess-3)", got) + } + seen := make(map[string]bool, len(result.Sessions)) + for _, s := range result.Sessions { + seen[s.ID] = true + } + for _, id := range []string{"sess-1", "sess-2", "sess-3"} { + if !seen[id] { + t.Errorf("session %q missing from list", id) + } + } +} + +func TestSessionToolListRespectsLimit(t *testing.T) { + store := newFakeSessionStore() + tr := newSessionTracker(store) + entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_list") + + now := time.Now() + for i := range 5 { + seedSessionAt(store, fmt.Sprintf("sess-%d", i), "", now.Add(time.Duration(i)*time.Hour)) + } + + out, err := entry.Handler(context.Background(), map[string]any{"limit": float64(2)}) + if err != nil { + t.Fatalf("handler: %v", err) + } + result, ok := out.(SessionListResult) + if !ok { + t.Fatalf("handler returned %T, want SessionListResult", out) + } + if len(result.Sessions) != 2 { + t.Fatalf("got %d sessions, want 2", len(result.Sessions)) + } + // The two newest are kept, in order. + if got := result.Sessions[0].ID; got != "sess-4" { + t.Errorf("first = %q, want the newest sess-4", got) + } + if got := result.Sessions[1].ID; got != "sess-3" { + t.Errorf("second = %q, want sess-3", got) + } +} + +func TestSessionToolResumeSwitchesActive(t *testing.T) { + store := newFakeSessionStore() + tr := newSessionTracker(store) + msg := Message{ChannelID: "chat-1", ThreadID: "thread-9"} + entry := sessionTool(t, SessionTools(store, tr, "test-gw", msg), "session_resume") + + target := "resume-target" + seedSessionAt(store, target, "target session", time.Now()) + // Start somewhere else so the switch is observable. + tr.setActive("chat-1", "thread-9", "other-session") + + out, err := entry.Handler(context.Background(), map[string]any{"session_id": target}) + if err != nil { + t.Fatalf("handler: %v", err) + } + result, ok := out.(SessionResumeResult) + if !ok { + t.Fatalf("handler returned %T, want SessionResumeResult", out) + } + if result.SessionID != target { + t.Errorf("session_id = %q, want %q", result.SessionID, target) + } + // The channel+thread come from the message captured at construction. + if got := tr.getActive("chat-1", "thread-9"); got != target { + t.Errorf("active = %q, want %q", got, target) + } +} + +func TestSessionToolResumeRejectsUnknown(t *testing.T) { + store := newFakeSessionStore() + tr := newSessionTracker(store) + entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_resume") + + _, err := entry.Handler(context.Background(), map[string]any{"session_id": "does-not-exist"}) + if err == nil { + t.Fatal("handler error = nil, want a refusal") + } + if !strings.Contains(err.Error(), "no session matching") { + t.Errorf("error = %q, want a 'no session matching' refusal", err) + } +} + +func TestSessionToolTitleSetsTitle(t *testing.T) { + store := newFakeSessionStore() + tr := newSessionTracker(store) + entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_title") + + target := "title-target" + seedSessionAt(store, target, "old title", time.Now()) + + if _, err := entry.Handler(context.Background(), map[string]any{ + "session_id": target, + "title": "new title", + }); err != nil { + t.Fatalf("handler: %v", err) + } + + sc, err := store.Get(context.Background(), target) + if err != nil { + t.Fatalf("Get: %v", err) + } + if sc == nil { + t.Fatal("session not found") + } + if sc.Title != "new title" { + t.Errorf("stored title = %q, want %q", sc.Title, "new title") + } +} + +func TestSessionToolTitleReportsPrevious(t *testing.T) { + store := newFakeSessionStore() + tr := newSessionTracker(store) + entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_title") + + target := "title-prev" + seedSessionAt(store, target, "before", time.Now()) + + out, err := entry.Handler(context.Background(), map[string]any{ + "session_id": target, + "title": "after", + }) + if err != nil { + t.Fatalf("handler: %v", err) + } + result, ok := out.(SessionTitleResult) + if !ok { + t.Fatalf("handler returned %T, want SessionTitleResult", out) + } + if result.PreviousTitle != "before" { + t.Errorf("previous_title = %q, want %q", result.PreviousTitle, "before") + } + if result.Title != "after" { + t.Errorf("title = %q, want %q", result.Title, "after") + } +} + +func TestSessionToolDeleteRemovesSession(t *testing.T) { + store := newFakeSessionStore() + tr := newSessionTracker(store) + entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_delete") + + target := "delete-target" + seedSessionAt(store, target, "doomed", time.Now()) + + out, err := entry.Handler(context.Background(), map[string]any{"session_id": target}) + if err != nil { + t.Fatalf("handler: %v", err) + } + result, ok := out.(SessionDeleteResult) + if !ok { + t.Fatalf("handler returned %T, want SessionDeleteResult", out) + } + if result.SessionID != target { + t.Errorf("session_id = %q, want %q", result.SessionID, target) + } + + sc, err := store.Get(context.Background(), target) + if err != nil { + t.Fatalf("Get: %v", err) + } + if sc != nil { + t.Error("session still present after delete") + } +} + +func TestSessionToolDeleteClearsTracker(t *testing.T) { + store := newFakeSessionStore() + tr := newSessionTracker(store) + entry := sessionTool(t, SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}), "session_delete") + + target := "delete-active" + seedSessionAt(store, target, "active", time.Now()) + // Active under a flat key and a thread key; forget must sweep both. + tr.setActive("chat-1", "", target) + tr.setActive("chat-1", "thread-2", target) + + if _, err := entry.Handler(context.Background(), map[string]any{"session_id": target}); err != nil { + t.Fatalf("handler: %v", err) + } + if got := tr.getActive("chat-1", ""); got != "" { + t.Errorf("flat active = %q, want empty", got) + } + if got := tr.getActive("chat-1", "thread-2"); got != "" { + t.Errorf("thread active = %q, want empty", got) + } +} + +func TestSessionToolClassifications(t *testing.T) { + store := newFakeSessionStore() + tr := newSessionTracker(store) + entries := SessionTools(store, tr, "test-gw", Message{ChannelID: "chat-1"}) + if len(entries) != 4 { + t.Fatalf("got %d tools, want 4", len(entries)) + } + + tests := []struct { + name string + idempotent bool + mutating bool + approval bool + }{ + {name: "session_list", idempotent: true}, + {name: "session_resume", mutating: true}, + {name: "session_title", mutating: true}, + {name: "session_delete", mutating: true, approval: true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + e := sessionTool(t, entries, tc.name) + if e.Toolset != "session" { + t.Errorf("toolset = %q, want %q", e.Toolset, "session") + } + if got := e.Classification.IsIdempotent(); got != tc.idempotent { + t.Errorf("idempotent = %v, want %v", got, tc.idempotent) + } + if got := e.Classification.IsMutating(); got != tc.mutating { + t.Errorf("mutating = %v, want %v", got, tc.mutating) + } + if got := e.Classification.IsApprovalRequired(); got != tc.approval { + t.Errorf("requires_approval = %v, want %v", got, tc.approval) + } + }) + } +} + +func TestSessionToolNilStoreOmitsTools(t *testing.T) { + if entries := SessionTools(nil, nil, "test-gw", Message{ChannelID: "chat-1"}); len(entries) != 0 { + t.Errorf("SessionTools(nil, ...) = %d entries, want 0", len(entries)) + } +} + +// TestSessionToolNilTrackerOmitsTrackerTools checks that a tracker-dependent +// tool is not advertised when no tracker is wired, matching the TaskTools rule +// that a nil backend omits its tool rather than registering one that always +// fails. +func TestSessionToolNilTrackerOmitsTrackerTools(t *testing.T) { + store := newFakeSessionStore() + entries := SessionTools(store, nil, "test-gw", Message{ChannelID: "chat-1"}) + var names []string + for _, e := range entries { + names = append(names, e.Name) + } + if len(entries) != 2 { + t.Fatalf("got %d tools (%v), want the 2 store-only tools", len(entries), names) + } + for _, name := range names { + switch name { + case "session_resume", "session_delete": + t.Errorf("%q needs the tracker and must not be advertised without one", name) + } + } +} diff --git a/internal/gateway/task_tools.go b/internal/gateway/task_tools.go index abea8abfc..770e0caf6 100644 --- a/internal/gateway/task_tools.go +++ b/internal/gateway/task_tools.go @@ -180,17 +180,7 @@ func taskSpawnTool(creator TaskCreator, identity string) tools.ToolEntry { // JSON numbers decode as float64, but a model that emits an integer through a // different provider path can arrive as int, so both are accepted. func taskListLimit(input map[string]any) int { - var limit int - switch v := input["limit"].(type) { - case float64: - limit = int(v) - case int: - limit = v - } - if limit <= 0 { - return defaultTaskListLimit - } - return min(limit, maxTaskListLimit) + return tools.ListLimit(input, defaultTaskListLimit, maxTaskListLimit) } // asString reads a string field, tolerating an absent or wrongly-typed value diff --git a/internal/tools/approval.go b/internal/tools/approval.go new file mode 100644 index 000000000..c6965556b --- /dev/null +++ b/internal/tools/approval.go @@ -0,0 +1,90 @@ +// Package tools: approval.go — tool-approval contract. +// +// Some tools are irreversible on a path the model controls (deleting a +// session, cancelling a task, sending email). The dispatch layer blocks +// those calls until a human consents, through an ApprovalRequester the +// adapter supplies. One adapter renders inline buttons in Telegram; the +// web UI could render a modal. Neither the tool nor the dispatch layer +// knows which adapter is asking — they only see the decision. +// +// This contract lives in internal/tools rather than internal/gateway so +// that internal/agentexec (the tool-dispatch layer, also used by the +// archie-agent sandbox binary) can import it without pulling in the +// chat-gateway domain stack. + +package tools + +import ( + "context" + "errors" + "time" +) + +// ApprovalRequester asks a human to approve or deny a named action. +// +// The call blocks until the human decides or the context is cancelled. An +// adapter supplies the implementation — Telegram sends an inline keyboard, +// the web UI shows a modal, a headless test injects a decision directly. +// +// Implementations must honour ctx cancellation promptly (the turn lane holds +// the LLM connection open) and return [ErrApprovalDenied] or a context error, +// never nil, when approval was not granted. +type ApprovalRequester interface { + RequestApproval(ctx context.Context, action, description string) (ApprovalDecision, error) +} + +// ApprovalDecision is the outcome of a human consent request. +type ApprovalDecision int + +const ( + // ApprovalApproved means the human approved this one execution. + // The same tool invoked again will ask again. + ApprovalApproved ApprovalDecision = iota + + // ApprovalPermanentlyApproved means the human approved this action + // for the lifetime of the session. The adapter may cache this; the + // dispatch layer checks it on every call. + ApprovalPermanentlyApproved + + // ApprovalDenied means the human explicitly refused. The call must + // not retry: the model should report the refusal to the user. + ApprovalDenied +) + +// ErrApprovalDenied is returned when the human refuses the action. Callers +// should distinguish this from a timeout or transport error so the model +// can report the refusal accurately. +var ErrApprovalDenied = errors.New("approval denied") + +// ErrApprovalNotConfigured is returned when a tool requires approval but no +// ApprovalRequester is wired. It is an adapter problem, not a user decision +// — the model should report that the action cannot be performed, not that +// it was refused. +var ErrApprovalNotConfigured = errors.New("approval is not configured") + +// ToolApprovalTimeout bounds how long dispatch waits for a human to act. +// +// Longer than this and the LLM connection may time out or the user may have +// walked away; shorter and the human may not have time to read and decide. +// It is the dispatch layer's deadline, not the adapter's, and adapters +// should apply their own shorter timeout to the pending token. +const ToolApprovalTimeout = 2 * time.Minute + +// ── context plumbing ───────────────────────────────────────────────── + +type approvalCtxKey struct{} + +// WithApprovalRequester stores an ApprovalRequester on ctx so the tool +// dispatch layer can extract it without importing any adapter package. +// Callers that don't have an approver simply don't call this, and the +// dispatch layer treats a missing value as "not configured". +func WithApprovalRequester(ctx context.Context, a ApprovalRequester) context.Context { + return context.WithValue(ctx, approvalCtxKey{}, a) +} + +// ApprovalFromContext returns the ApprovalRequester stored by +// WithApprovalRequester, or nil when none was stored. +func ApprovalFromContext(ctx context.Context) ApprovalRequester { + a, _ := ctx.Value(approvalCtxKey{}).(ApprovalRequester) + return a +} diff --git a/internal/tools/approval_test.go b/internal/tools/approval_test.go new file mode 100644 index 000000000..95515b28a --- /dev/null +++ b/internal/tools/approval_test.go @@ -0,0 +1,94 @@ +package tools + +import ( + "context" + "errors" + "testing" + "time" +) + +// testApprover is a stub ApprovalRequester for tests. +type testApprover struct { + decision ApprovalDecision + err error +} + +func (a *testApprover) RequestApproval(context.Context, string, string) (ApprovalDecision, error) { + return a.decision, a.err +} + +func TestApprovalDecisionConstantsAreDistinct(t *testing.T) { + seen := make(map[ApprovalDecision]bool) + for _, d := range []ApprovalDecision{ + ApprovalApproved, + ApprovalPermanentlyApproved, + ApprovalDenied, + } { + if seen[d] { + t.Errorf("duplicate decision value %d", d) + } + seen[d] = true + } +} + +func TestApproverStubReturnsDecision(t *testing.T) { + s := &testApprover{decision: ApprovalApproved} + d, err := s.RequestApproval(context.Background(), "tool", "desc") + if err != nil || d != ApprovalApproved { + t.Errorf("(decision=%v, err=%v)", d, err) + } +} + +func TestApproverStubReturnsDenial(t *testing.T) { + s := &testApprover{decision: ApprovalDenied} + d, err := s.RequestApproval(context.Background(), "x", "") + if err != nil || d != ApprovalDenied { + t.Errorf("(decision=%v, err=%v)", d, err) + } +} + +func TestApproverStubReturnsError(t *testing.T) { + s := &testApprover{err: errors.New("timeout")} + _, err := s.RequestApproval(context.Background(), "x", "") + if err == nil { + t.Error("expected error from stub") + } +} + +func TestErrApprovalDeniedIsDistinguishable(t *testing.T) { + if !errors.Is(ErrApprovalDenied, ErrApprovalDenied) { + t.Error("ErrApprovalDenied does not match itself") + } + if errors.Is(ErrApprovalDenied, ErrApprovalNotConfigured) { + t.Error("ErrApprovalDenied should not match ErrApprovalNotConfigured") + } +} + +func TestToolApprovalTimeoutIsReasonable(t *testing.T) { + if ToolApprovalTimeout < time.Minute { + t.Errorf("timeout %v is too short for a human to decide", ToolApprovalTimeout) + } + if ToolApprovalTimeout > 5*time.Minute { + t.Errorf("timeout %v is too long for an LLM connection to hold", ToolApprovalTimeout) + } +} + +func TestApprovalContextRoundTrip(t *testing.T) { + a := &testApprover{decision: ApprovalApproved} + ctx := WithApprovalRequester(context.Background(), a) + + got := ApprovalFromContext(ctx) + if got == nil { + t.Fatal("ApprovalFromContext returned nil") + } + d, err := got.RequestApproval(context.Background(), "x", "") + if err != nil || d != ApprovalApproved { + t.Errorf("round-tripped approver: (decision=%v, err=%v)", d, err) + } +} + +func TestApprovalFromContextReturnsNilWhenNotStored(t *testing.T) { + if got := ApprovalFromContext(context.Background()); got != nil { + t.Error("ApprovalFromContext should return nil when nothing was stored") + } +} diff --git a/internal/tools/classification.go b/internal/tools/classification.go index c49dc8c5d..cf9d0098e 100644 --- a/internal/tools/classification.go +++ b/internal/tools/classification.go @@ -1,5 +1,7 @@ package tools +import "strings" + // ToolClassification is a bitmask that describes a tool's behavioral // characteristics for dispatch gating, guardrail decisions, and budget // enforcement. @@ -14,6 +16,16 @@ const ( // creates resources, sends messages, etc.). Mutating tools require // serialization, checkpointing, and stricter guardrail monitoring. ClassMutating + + // RequiresApproval marks a tool that must not execute without a human + // consent decision. The dispatch layer blocks the call until an + // ApprovalRequester resolves it (approve, permanently approve, or deny). + // + // It is independent of ClassMutating: writing a file is mutating but + // not necessarily gated (the agent loop's own path enforcement handles + // that), while deleting a session is gated because it is irreversible + // on a path the model controls. + RequiresApproval ) // IsIdempotent reports whether the classification includes the idempotent @@ -28,18 +40,29 @@ func (c ToolClassification) IsMutating() bool { return c&ClassMutating != 0 } +// IsApprovalRequired reports whether the classification includes the +// RequiresApproval flag. A zero-value classification reports false. +func (c ToolClassification) IsApprovalRequired() bool { + return c&RequiresApproval != 0 +} + // String returns a human-readable representation of the classification. func (c ToolClassification) String() string { - switch { - case c == 0: + if c == 0 { return "default" - case c.IsIdempotent() && c.IsMutating(): - return "idempotent|mutating" - case c.IsIdempotent(): - return "idempotent" - case c.IsMutating(): - return "mutating" - default: + } + var parts []string + if c.IsIdempotent() { + parts = append(parts, "idempotent") + } + if c.IsMutating() { + parts = append(parts, "mutating") + } + if c.IsApprovalRequired() { + parts = append(parts, "requires_approval") + } + if len(parts) == 0 { return "unknown" } + return strings.Join(parts, "|") } diff --git a/internal/tools/classification_test.go b/internal/tools/classification_test.go index bc3cbfe0a..2c267288d 100644 --- a/internal/tools/classification_test.go +++ b/internal/tools/classification_test.go @@ -57,6 +57,41 @@ func TestToolClassificationCombined(t *testing.T) { } } +func TestToolClassificationIsApprovalRequired(t *testing.T) { + t.Run("zero value does not require approval", func(t *testing.T) { + var c ToolClassification + if c.IsApprovalRequired() { + t.Error("zero classification should not require approval") + } + }) + + t.Run("explicit approval flag", func(t *testing.T) { + if !RequiresApproval.IsApprovalRequired() { + t.Error("RequiresApproval should require approval") + } + }) + + t.Run("approval is independent of idempotent", func(t *testing.T) { + c := ClassIdempotent | RequiresApproval + if !c.IsApprovalRequired() { + t.Error("idempotent + approval should require approval") + } + if !c.IsIdempotent() { + t.Error("idempotent + approval should still be idempotent") + } + }) + + t.Run("approval is independent of mutating", func(t *testing.T) { + c := ClassMutating | RequiresApproval + if !c.IsApprovalRequired() { + t.Error("mutating + approval should require approval") + } + if !c.IsMutating() { + t.Error("mutating + approval should still be mutating") + } + }) +} + func TestToolClassificationString(t *testing.T) { tests := []struct { c ToolClassification @@ -66,7 +101,9 @@ func TestToolClassificationString(t *testing.T) { {ClassIdempotent, "idempotent"}, {ClassMutating, "mutating"}, {ClassIdempotent | ClassMutating, "idempotent|mutating"}, - {ToolClassification(4), "unknown"}, + {RequiresApproval, "requires_approval"}, + {ClassMutating | RequiresApproval, "mutating|requires_approval"}, + {ToolClassification(8), "unknown"}, } for _, tt := range tests { diff --git a/internal/tools/disclosure.go b/internal/tools/disclosure.go index 2443b4f8c..8ce50d6fe 100644 --- a/internal/tools/disclosure.go +++ b/internal/tools/disclosure.go @@ -150,6 +150,9 @@ func bridgeCallHandler(reg *Registry) Handler { if e.Handler == nil { return nil, fmt.Errorf("tool_call: tool %q has no handler", name) } + if e.Classification.IsApprovalRequired() { + return nil, fmt.Errorf("tool_call: tool %q requires human approval and cannot be invoked through the bridge", name) + } return e.Handler(ctx, callInput) } } diff --git a/internal/tools/dispatch.go b/internal/tools/dispatch.go index 19d1e3187..0d7844e06 100644 --- a/internal/tools/dispatch.go +++ b/internal/tools/dispatch.go @@ -118,10 +118,20 @@ type ToolCall struct { } // invokeTool executes a single tool and returns a [DispatchResult]. +// +// Tools that require human approval are refused. The dispatch path has no +// ApprovalRequester — it is used by the agent execution loop, which runs +// without a human in the loop. The chat path gates approval through +// BuildToolSetFrom → toolExecute, which has the approver wired. func invokeTool(ctx context.Context, call ToolCall) DispatchResult { start := time.Now() result := DispatchResult{ToolName: call.Entry.Name} + if call.Entry.Classification.IsApprovalRequired() { + result.Error = fmt.Errorf("tool %s: requires human approval and cannot be invoked through the agent dispatch path", call.Entry.Name) + return result + } + output, err := call.Entry.Handler(ctx, call.Input) result.Duration = time.Since(start) diff --git a/internal/tools/limit.go b/internal/tools/limit.go new file mode 100644 index 000000000..13cbf89c9 --- /dev/null +++ b/internal/tools/limit.go @@ -0,0 +1,23 @@ +package tools + +// ListLimit resolves a limit value from a tool input map, falling back to +// def for anything absent or non-positive and clamping to at most max. +// +// JSON numbers decode as float64, but a model that emits an integer through +// a different provider path can arrive as int, so both are accepted. +func ListLimit(input map[string]any, def, max int) int { + var limit int + switch v := input["limit"].(type) { + case float64: + limit = int(v) + case int: + limit = v + } + if limit <= 0 { + return def + } + if limit > max { + return max + } + return limit +} diff --git a/internal/tools/limit_test.go b/internal/tools/limit_test.go new file mode 100644 index 000000000..8b5ec7210 --- /dev/null +++ b/internal/tools/limit_test.go @@ -0,0 +1,30 @@ +package tools + +import "testing" + +func TestListLimit(t *testing.T) { + tests := []struct { + name string + input map[string]any + def int + max int + want int + }{ + {name: "absent", input: map[string]any{}, def: 20, max: 100, want: 20}, + {name: "zero", input: map[string]any{"limit": float64(0)}, def: 20, max: 100, want: 20}, + {name: "negative", input: map[string]any{"limit": float64(-5)}, def: 20, max: 100, want: 20}, + {name: "float64 within range", input: map[string]any{"limit": float64(42)}, def: 20, max: 100, want: 42}, + {name: "int within range", input: map[string]any{"limit": 7}, def: 20, max: 100, want: 7}, + {name: "clamped to max", input: map[string]any{"limit": float64(200)}, def: 20, max: 100, want: 100}, + {name: "exactly max", input: map[string]any{"limit": float64(100)}, def: 20, max: 100, want: 100}, + {name: "exactly def", input: map[string]any{"limit": float64(20)}, def: 20, max: 100, want: 20}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ListLimit(tt.input, tt.def, tt.max); got != tt.want { + t.Errorf("ListLimit() = %d, want %d", got, tt.want) + } + }) + } +} diff --git a/internal/tools/provider/contract_test.go b/internal/tools/provider/contract_test.go index 23e029960..29f85b733 100644 --- a/internal/tools/provider/contract_test.go +++ b/internal/tools/provider/contract_test.go @@ -56,7 +56,7 @@ func TestArchiedWiresTypedProvidersAndExecutableConsumers(t *testing.T) { // system prompt is rendered, so the prompt can advertise exactly // the tools the model is handed. After the Phase 4 structural // refactor these calls live in telegram_setup.go. - "chatGenerateOptions(nil,", + "chatGenerateOptions(ctx,", "toolSummaries(options.Tools)", "agentexec.NewInProcessRunner(llm, log, toolReg)", } { diff --git a/internal/tools/toolentry.go b/internal/tools/toolentry.go index f2df1a43d..83e752fd7 100644 --- a/internal/tools/toolentry.go +++ b/internal/tools/toolentry.go @@ -85,6 +85,17 @@ type ToolEntry struct { // "🌐"). Single character or short sequence. May be empty. Emoji string `json:"emoji,omitempty"` + // BuildApprovalDescription is called with the decoded tool inputs to + // build the human-facing prompt shown when approval is required. When + // nil (the default), the tool's Description is used verbatim. + // + // The returned string should identify the specific resource being acted + // on so the human knows what they are consenting to. A prompt that says + // only "Delete a session" is not adequate; "Delete session 'Refactor + // auth' (abc12345)" is. This runs before the handler, so only the raw + // input is available — it cannot resolve references or look up titles. + BuildApprovalDescription func(input map[string]any) string `json:"-"` + // MaxResultSizeChars caps this tool's result size in characters. // Zero means use the global default from [ToolPolicy.MaxResultChars]. MaxResultSizeChars int `json:"max_result_size_chars,omitempty"`