From cc53e5258d2282fad61266a3ed229a25e8bde08c Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 23 Aug 2026 16:40:16 +0000 Subject: [PATCH] fix(telegram): compact tool output and drop turn caps Render completed ToolCallEvents as Telegram-safe streaming blocks with compact name/status and a short cleaned preview. Summarize file contents and listings instead of dumping source or quoted JSON. Collapse repeated legacy turn-budget failures. Remove max_tokens turn gating and the 200000 turn_budget_chars default so absent or commented config cannot restore an aggregate cap. Keep per-result max_result_chars and spill. Confine find/grep discovery to the active workspace/worktree. Refs #604 --- cmd/archied/chat_turn_model.go | 4 +- cmd/archied/config_update_test.go | 4 - cmd/archied/main.go | 5 +- config.example.toml | 2 - deployments/docker-nats-stack.toml | 1 - deployments/single-forge-github.toml | 1 - docs/architecture/configuration.md | 4 +- docs/archive/decisions.md | 27 + docs/data/generated/contracts.json | 3 - docs/prds/adversarial-self-review.md | 2 +- internal/agentexec/inprocess.go | 29 +- internal/agentexec/inprocess_test.go | 5 + internal/agentexec/nats_test.go | 12 +- internal/agentexec/protocol.go | 1 - internal/agentexec/protocol_test.go | 2 +- internal/agentexec/skill_test.go | 2 +- internal/agentexec/toolset.go | 43 +- internal/agentexec/toolset_test.go | 72 +-- internal/channels/telegram/live.go | 28 +- internal/channels/telegram/live_test.go | 72 ++- internal/config/config.go | 5 +- internal/config/config_test.go | 6 +- internal/domain/workflow/agent.go | 1 - internal/domain/workflow/agent_test.go | 2 +- internal/domain/workflow/implement.go | 1 - internal/gateway/stream.go | 130 ++++- internal/gateway/tool_render_test.go | 19 +- internal/gateway/turn.go | 8 +- .../configuration/apply_test.go | 4 - .../infrastructure/configuration/defaults.go | 5 +- .../infrastructure/configuration/dir_test.go | 2 +- .../configuration/loader_test.go | 66 ++- .../configuration/tomlwrite/tomlwrite_test.go | 6 +- internal/tools/budget.go | 216 +------- internal/tools/budget_test.go | 516 ++---------------- internal/tools/builtin/find.go | 8 +- internal/tools/builtin/grep.go | 4 +- internal/tools/builtin/pathutil.go | 11 +- internal/tools/builtin/pathutil_test.go | 44 +- internal/tools/classification.go | 4 +- internal/tools/dispatch.go | 87 +-- internal/tools/dispatch_test.go | 125 ++--- internal/tools/provider/builtin/provider.go | 2 +- internal/webui/api_config.go | 2 - ui/dist/assets/index.js | 2 +- ui/src/settings/settings.js | 1 - 46 files changed, 543 insertions(+), 1053 deletions(-) diff --git a/cmd/archied/chat_turn_model.go b/cmd/archied/chat_turn_model.go index d22f54012..839b4b65b 100644 --- a/cmd/archied/chat_turn_model.go +++ b/cmd/archied/chat_turn_model.go @@ -92,6 +92,8 @@ func (m *preparedChatTurnModel) Generate( } options.Messages[i] = chat.Message{Role: role, Content: message.Content} } - options.MaxTokens = request.MaxTokens + // This is one provider response's output allowance, not a turn- + // continuation budget. Tool loops remain free to continue. + options.MaxTokens = request.MaxOutputTokens return sendChatTurn(ctx, m.llm, m.model, options, stream) } diff --git a/cmd/archied/config_update_test.go b/cmd/archied/config_update_test.go index 3faf58c69..addf714eb 100644 --- a/cmd/archied/config_update_test.go +++ b/cmd/archied/config_update_test.go @@ -18,10 +18,6 @@ func TestApplyDottedOverlayNestsBeforeDecode(t *testing.T) { if cfg.Budgets.MaxSteps != 20 { t.Fatalf("MaxSteps = %d, want 20 (dotted key must be nested before decode)", cfg.Budgets.MaxSteps) } - // A field the update does not name keeps its value. - if cfg.Budgets.MaxTokens != 0 { - t.Errorf("MaxTokens = %d, want 0 (untouched)", cfg.Budgets.MaxTokens) - } } // TestApplyDottedOverlayRejectsEmptyKey pins that a malformed dotted key diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 40abd1cdf..d775d44c1 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -130,9 +130,8 @@ func isWithin(base, target string) bool { // toolLimits reads the configured per-turn result limits. func toolLimits(cfg config.Config) agentexec.ToolLimits { return agentexec.ToolLimits{ - MaxResultChars: cfg.Tools.Policy.MaxResultChars, - TurnBudgetChars: cfg.Tools.Policy.TurnBudgetChars, - SpillDir: cfg.Tools.Policy.SpillDir, + MaxResultChars: cfg.Tools.Policy.MaxResultChars, + SpillDir: cfg.Tools.Policy.SpillDir, } } diff --git a/config.example.toml b/config.example.toml index 98c366620..8fd6f02d8 100644 --- a/config.example.toml +++ b/config.example.toml @@ -225,7 +225,6 @@ listen = "127.0.0.1:8484" [budgets] max_steps = 60 -max_tokens = 400000 wall_clock = "30m" gate_max_failures = 5 @@ -305,7 +304,6 @@ gate_max_failures = 5 # zero cannot mean "off" because it is indistinguishable from an unset key. # [tools.tool_policy] # max_result_chars = 50000 # cap on one tool result; -1 for no cap -# turn_budget_chars = 200000 # cap on all tool results in one chat turn; -1 for no cap # spill_dir = "" # unset by default, which truncates oversized results # # inline. When set, a result over the cap is written # # here in full and the model is handed the path. diff --git a/deployments/docker-nats-stack.toml b/deployments/docker-nats-stack.toml index 88b4980ef..dc7cc9709 100644 --- a/deployments/docker-nats-stack.toml +++ b/deployments/docker-nats-stack.toml @@ -82,7 +82,6 @@ api_key_env = "DEEPSEEK_API_KEY" [budgets] max_steps = 90 -max_tokens = 100000000 wall_clock = "60m" gate_max_failures = 5 diff --git a/deployments/single-forge-github.toml b/deployments/single-forge-github.toml index a3daed038..533a8be97 100644 --- a/deployments/single-forge-github.toml +++ b/deployments/single-forge-github.toml @@ -44,7 +44,6 @@ command = "archie-agent" [budgets] max_steps = 60 -max_tokens = 400000 wall_clock = "30m" # List of repositories managed by this single GitHub forge configuration: diff --git a/docs/architecture/configuration.md b/docs/architecture/configuration.md index cd34e43cc..a85f9237f 100644 --- a/docs/architecture/configuration.md +++ b/docs/architecture/configuration.md @@ -147,7 +147,7 @@ existing structure combines different owners. | `Label`, `BotUser`, `BotEmail` | root `Config` | Identity and dispatch associations. `BotEmail` may be derived from the selected forge account but remains overrideable. | | `MaxRetries` | root `Config`, `Repo` | Retry policy owned by the operation being retried. The duplicate global/repository representation must disappear. | | `DiffCapLines` | root `Config` | Agent-change policy value. | -| `MaxSteps`, `MaxTokens`, `WallClock`, `GateMaxFailures` | `Budgets` | Workflow-execution policy, with units and zero/unlimited semantics made explicit. | +| `MaxSteps`, `WallClock`, `GateMaxFailures` | `Budgets` | Workflow-execution policy, with units and zero/unlimited semantics made explicit. | | `Class`, `APIKeyEnv`, `BaseURL` | `Provider` | Provider instance settings. Secret lookup becomes a `SecretRef`, not an environment variable name leaking into the provider domain. | | `Mode`, `Command`, `Env` | `Agent` | Agent-execution infrastructure settings. Arbitrary environment injection is explicitly trust-sensitive. | | `Type`, `Host`, `Token` / `TokenEnv` (older form) | `Forge` | Forge adapter settings. The older `TokenEnv` input is accepted only at the loader boundary. | @@ -180,7 +180,7 @@ decision; exact setting names are implementation details. | Chat agent | maximum steps `8` in `cmd/archied` | Workflow/chat execution policy. | | Context compression | enabled, threshold `0.5`, context size `128000`, protect first `3` and last `20`, compression marker, token estimate of four characters per token | Model/context runtime settings. The marker is presentation; the estimate is provider/model strategy, not a universal truth. | | Tool guardrails | escalation thresholds `3`, `5`, `10`, `2` | Tool-use policy with named meanings and bounded defaults. | -| Tool output | turn budget `200000` characters and preview `500` characters | Tool-execution resource and presentation settings. | +| Tool output | per-result cap `50000` characters, no aggregate turn cap, preview `500` characters | Tool-execution resource and presentation settings. Per-result spill/truncation remains; turn continuation is not character- or token-gated. | | Pairing/access | code TTL `1h`, maximum pending `3`, rate window `10m`, failures `5`, lockout `1h`, maximum lockout `24h` | Access policy. Code length/alphabet and salt length require an explicit security-constraint decision; they are not automatically valid constants. | | NATS daemon consumer | stream `ARCHIE_TASKS`, consumer `archie-daemon`, deduplication `2m`, poll `2s`, deliveries `3`, acknowledgement wait `5m`, inactive threshold `24h`, subjects | NATS topology settings plus delivery policy. Subject grammar or protocol headers may be invariants only if declared as versioned wire contracts. | | NATS worker consumer | stream `ARCHIE_TASKS`, consumer `archie-agent`, deduplication `2m`, poll `5s`, acknowledgement wait `30m`, deliveries `3`, inactive threshold `24h`, queue group and retry delay `1s` | Worker transport settings and delivery/retry policy. Shared stream defaults must have one owner rather than two copies. | diff --git a/docs/archive/decisions.md b/docs/archive/decisions.md index 0726b7a98..cc0805ff4 100644 --- a/docs/archive/decisions.md +++ b/docs/archive/decisions.md @@ -7,6 +7,30 @@ changing anything that contradicts a prior decision. --- +## 2026-08-24 -- Turn continuation is never output-volume or token gated + +**Decision**: A turn is never stopped because an aggregate token count or +aggregate tool-result character count was reached. `max_tokens` and +`turn_budget_chars` are not runtime continuation controls. Tool output is +bounded only per invocation with `max_result_chars`; oversized individual +results are spilled when a workspace-readable spill directory is configured, +or explicitly truncated otherwise. + +**Reasoning**: Aggregate caps discard useful work and caused the model to emit +repeated `turn budget exceeded (200000 chars)` tool failures instead of +finishing. Model context/output accounting and tool-result volume are distinct: +provider output limits may describe one model response, but they must never be +used to terminate the multi-step turn. + +**Context**: GitHub #604 showed full file and module listings followed by four +identical read failures and a shell failure at the old 200,000-character cap. +The renderer now summarizes those legacy events for replay, while current +dispatch never creates them. Find and grep are confined to the active +workspace/worktree; the Go module cache remains readable only by explicit +path, not by discovery. + +--- + ## 2026-07-23 -- Forge-agnostic issue creation via CreateIssue **Decision**: Add `CreateIssue(ctx, owner, repo, title, body, labels) @@ -49,6 +73,9 @@ in archie-core (`.beads/`). Six issues seeded for the scaling roadmap. ## 2026-07-23 -- Token budgets must be generous, not predictive +> **Superseded by the 2026-08-24 decision above.** There is no configured +> aggregate token cap; model token usage remains accounting only. + **Decision**: Set `max_tokens` to 100,000,000 (100M). Do not attempt to predict what a task needs without data. Lower limits later based on actual per-workflow/per-repo metrics. diff --git a/docs/data/generated/contracts.json b/docs/data/generated/contracts.json index f8c38211d..d672cffe2 100644 --- a/docs/data/generated/contracts.json +++ b/docs/data/generated/contracts.json @@ -147,9 +147,6 @@ "max_steps": { "type": "integer" }, - "max_tokens": { - "type": "integer" - }, "wall_clock": { "type": "integer" } diff --git a/docs/prds/adversarial-self-review.md b/docs/prds/adversarial-self-review.md index 6fe50c9f7..1fa09fa72 100644 --- a/docs/prds/adversarial-self-review.md +++ b/docs/prds/adversarial-self-review.md @@ -125,7 +125,7 @@ that works," not a mandated model-diversity policy. **Effort/budget:** reuse the per-stage budget override `AgentStage` already supports (`agent.go:35`), not a new config surface -- a repo wanting a -cheaper or more thorough reviewer sets `MaxSteps`/`MaxTokens` the same way +cheaper or more thorough reviewer sets `MaxSteps` the same way the plan stage already can. **Opt-in, not automatic:** `h019.5` (calibration -- confirm findings diff --git a/internal/agentexec/inprocess.go b/internal/agentexec/inprocess.go index 1df139b80..b768e60a9 100644 --- a/internal/agentexec/inprocess.go +++ b/internal/agentexec/inprocess.go @@ -93,15 +93,18 @@ func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request return Result{}, err } res, err := r.run(ctx, agentloop.Config{ - Runtime: r.runtime, - ModelRef: req.Model, - WorkDir: workspace, - Mission: req.Mission, - ExtraRules: req.ExtraRules, - Notes: notes, - Gate: toAgentGate(req.Gate), - Preflight: toAgentCommands(req.Preflight), - Budget: agentloop.Budget(req.Budget), + Runtime: r.runtime, + ModelRef: req.Model, + WorkDir: workspace, + Mission: req.Mission, + ExtraRules: projectScopedRules(workspace, req.ExtraRules), + Notes: notes, + Gate: toAgentGate(req.Gate), + Preflight: toAgentCommands(req.Preflight), + Budget: agentloop.Budget{ + MaxSteps: req.Budget.MaxSteps, + WallClock: req.Budget.WallClock, + }, ReadOnly: req.ReadOnly, ProtectPaths: protectionMatcher(req.Protection, req.ReadOnly), Extra: mergeToolSets( @@ -140,6 +143,14 @@ func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request return result, err } +func projectScopedRules(workspace, extra string) string { + rule := "Confine discovery to " + workspace + ". Do not inspect home directories, dependency/module caches, or unrelated projects unless the mission explicitly requests that external path." + if strings.TrimSpace(extra) == "" { + return rule + } + return rule + "\n" + extra +} + func pluginToolSet(req Request, workspace string, occupied ...core.ToolSet) (core.ToolSet, error) { if req.ReadOnly || len(req.Protection.Suffixes)+len(req.Protection.Globs) > 0 || len(req.Gate.Commands) > 0 { return nil, nil diff --git a/internal/agentexec/inprocess_test.go b/internal/agentexec/inprocess_test.go index a9171b5d4..211818231 100644 --- a/internal/agentexec/inprocess_test.go +++ b/internal/agentexec/inprocess_test.go @@ -6,6 +6,7 @@ import ( "errors" "os" "path/filepath" + "strings" "testing" "time" @@ -66,6 +67,10 @@ func TestInProcessRunnerMapsRequestAndCapturesOutput(t *testing.T) { if cfg.ProtectPaths == nil || !cfg.ProtectPaths("nested/file_test.go") || !cfg.ProtectPaths("view_templ.go") { t.Fatal("declarative path protection was not applied") } + if !strings.Contains(cfg.ExtraRules, "Confine discovery to /workspace") || + !strings.Contains(cfg.ExtraRules, "unless the mission explicitly requests") { + t.Fatalf("project discovery rule missing from ExtraRules: %q", cfg.ExtraRules) + } if err := cfg.Notes.Append(ctx, "verified note"); err != nil { t.Fatal(err) } diff --git a/internal/agentexec/nats_test.go b/internal/agentexec/nats_test.go index a886e0a7f..92407e344 100644 --- a/internal/agentexec/nats_test.go +++ b/internal/agentexec/nats_test.go @@ -56,7 +56,7 @@ func TestHandleMessageReadsWorkflowField(t *testing.T) { Request: Request{ Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "plan", Model: "test/model", Mission: "single", - Budget: Budget{MaxSteps: 1, MaxTokens: 10}, + Budget: Budget{MaxSteps: 1}, }, Providers: providers, } @@ -81,18 +81,18 @@ func TestHandleMessageReadsWorkflowField(t *testing.T) { Request: Request{ Version: ProtocolVersion, TaskID: 2, Attempt: 1, Stage: "plan", Model: "test/model", Mission: "multi-1", - Budget: Budget{MaxSteps: 1, MaxTokens: 10}, + Budget: Budget{MaxSteps: 1}, }, Stages: []Request{ { Version: ProtocolVersion, TaskID: 2, Attempt: 1, Stage: "plan", Model: "test/model", Mission: "multi-plan", - Budget: Budget{MaxSteps: 1, MaxTokens: 10}, + Budget: Budget{MaxSteps: 1}, }, { Version: ProtocolVersion, TaskID: 2, Attempt: 1, Stage: "build", Model: "test/model", Mission: "multi-build", - Budget: Budget{MaxSteps: 1, MaxTokens: 10}, + Budget: Budget{MaxSteps: 1}, }, }, Providers: providers, @@ -137,7 +137,7 @@ func TestHandleMessageRoutesSystemMessagesSeparately(t *testing.T) { Stage: "plan", Model: "test/model", Mission: "test", - Budget: Budget{MaxSteps: 1, MaxTokens: 10}, + Budget: Budget{MaxSteps: 1}, }, Providers: map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}}, } @@ -266,7 +266,7 @@ func TestNATSRunnerRoundTrip(t *testing.T) { Stage: "test", Model: "openai/gpt", Mission: "test mission", - Budget: Budget{MaxSteps: 5, MaxTokens: 100}, + Budget: Budget{MaxSteps: 5}, } result, err := runner.Run(ctx, "/tmp/test-workspace", req, nil) diff --git a/internal/agentexec/protocol.go b/internal/agentexec/protocol.go index ea4b269bd..eb332b9c1 100644 --- a/internal/agentexec/protocol.go +++ b/internal/agentexec/protocol.go @@ -35,7 +35,6 @@ type Gate struct { // Budget bounds one autonomous execution. type Budget struct { MaxSteps int `json:"max_steps,omitempty"` - MaxTokens int `json:"max_tokens,omitempty"` WallClock time.Duration `json:"wall_clock,omitempty"` } diff --git a/internal/agentexec/protocol_test.go b/internal/agentexec/protocol_test.go index 6ea347e2b..07337bfaf 100644 --- a/internal/agentexec/protocol_test.go +++ b/internal/agentexec/protocol_test.go @@ -10,7 +10,7 @@ import ( func TestProtocolRoundTrip(t *testing.T) { want := Request{ Version: ProtocolVersion, TaskID: 42, Attempt: 3, Stage: "fix", Model: "openai/gpt-5", - Mission: "fix it", Budget: Budget{MaxSteps: 12, MaxTokens: 4000, WallClock: 2 * time.Minute}, + Mission: "fix it", Budget: Budget{MaxSteps: 12, WallClock: 2 * time.Minute}, Gate: Gate{Commands: []Command{{Name: "go", Argv: []string{"go", "test", "./..."}}}, MaxConsecutiveFailures: 2}, Protection: Protection{Suffixes: []string{"_templ.go"}, Globs: []string{"*_test.go"}}, CaptureTools: []CaptureTool{{Name: "decide", Parameters: json.RawMessage(`{"type":"object"}`), MaxCalls: 1}}, diff --git a/internal/agentexec/skill_test.go b/internal/agentexec/skill_test.go index dd958551d..517cbcc69 100644 --- a/internal/agentexec/skill_test.go +++ b/internal/agentexec/skill_test.go @@ -76,7 +76,7 @@ Analyse the bug. Write repro tests. Fix. Version: ProtocolVersion, TaskID: 1, Attempt: 1, Stage: "analyse", Model: "test/model", Mission: alreadyPrepended, - Budget: Budget{MaxSteps: 1, MaxTokens: 10}, + Budget: Budget{MaxSteps: 1}, }, Providers: map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}}, } diff --git a/internal/agentexec/toolset.go b/internal/agentexec/toolset.go index 472687e94..8715c69f7 100644 --- a/internal/agentexec/toolset.go +++ b/internal/agentexec/toolset.go @@ -20,17 +20,16 @@ import ( // A negative limit means no limit; see config.ToolPolicy for why zero cannot // carry that meaning. type ToolLimits struct { - MaxResultChars int - TurnBudgetChars int - SpillDir string + MaxResultChars int + SpillDir string } // EnsureSpillDir creates the spill directory if one is configured. // -// Call it once at startup. Without it the directory never exists, and because -// TurnBudget's write failure is silent every oversized result falls back to -// inline truncation -- spilling looks configured and does nothing. An empty -// SpillDir is not an error: it selects inline truncation deliberately. +// Call it once at startup. Without it the directory never exists, and a +// failed spill write falls back to inline truncation -- spilling looks +// configured and does nothing. An empty SpillDir is not an error: it +// selects inline truncation deliberately. func (l ToolLimits) EnsureSpillDir() error { if l.SpillDir == "" { return nil @@ -43,18 +42,13 @@ func (l ToolLimits) EnsureSpillDir() error { return nil } -// Options builds the tool-set options for a single turn or stage, minting a -// fresh TurnBudget each time. -// -// The budget must never outlive one turn: a shared counter would let one -// task's tool output exhaust another's allowance, and nothing would reset it. +// Options builds the tool-set options for a single turn or stage. +// There is no aggregate turn output budget; only per-result caps apply. func (l ToolLimits) Options(excludeToolsets ...string) ToolSetOptions { opts := ToolSetOptions{ MaxResultChars: l.MaxResultChars, ExcludeToolsets: excludeToolsets, - } - if l.TurnBudgetChars > 0 { - opts.Budget = tools.NewTurnBudget(l.TurnBudgetChars, l.SpillDir) + SpillDir: l.SpillDir, } return opts } @@ -64,10 +58,9 @@ func (l ToolLimits) Options(excludeToolsets ...string) ToolSetOptions { // The zero value builds every available tool with no result limits, which is // the behaviour this package had before the options existed. type ToolSetOptions struct { - // Budget accounts for the aggregate size of tool results across one chat - // turn or agent stage, and supplies the spill directory oversized results - // are displaced to. Nil disables budget accounting entirely. - Budget *tools.TurnBudget + // SpillDir receives complete results displaced by the per-tool cap. Empty + // selects inline truncation. There is deliberately no aggregate turn cap. + SpillDir string // MaxResultChars caps a single tool result. Entries setting // ToolEntry.MaxResultSizeChars override it. Zero or negative means no cap. @@ -247,13 +240,6 @@ func toolExecute(entry tools.ToolEntry, opts ToolSetOptions) func(context.Contex return func(ctx context.Context, input string) (result string, err error) { defer func() { reportToolCallCompletion(opts, entry, result, err) }() - // A turn that has spent its budget must say so. Returning an error - // tells the model it has run out; returning an empty result would - // read as "the tool found nothing" and invite it to try again. - if opts.Budget != nil && opts.Budget.Exceeded() { - return "", fmt.Errorf("tool %s: turn budget exceeded (%d chars)", entry.Name, opts.Budget.MaxChars) - } - var args map[string]any if input != "" { if err := json.Unmarshal([]byte(input), &args); err != nil { @@ -307,10 +293,7 @@ func toolExecute(entry tools.ToolEntry, opts ToolSetOptions) func(context.Contex return "", fmt.Errorf("tool %s: encode output: %w", entry.Name, err) } - payload := tools.CapPayload(entry.Name, string(data), limit, opts.Budget) - if opts.Budget != nil { - opts.Budget.Consume(len(payload)) - } + payload := tools.CapPayload(entry.Name, string(data), limit, opts.SpillDir) return payload, nil } } diff --git a/internal/agentexec/toolset_test.go b/internal/agentexec/toolset_test.go index aca243a25..2a0c032b5 100644 --- a/internal/agentexec/toolset_test.go +++ b/internal/agentexec/toolset_test.go @@ -360,11 +360,10 @@ func TestToolSetCapsResults(t *testing.T) { // tool, which is the whole point of spilling instead of truncating. func TestToolSetSpillsOversizeResults(t *testing.T) { dir := t.TempDir() - budget := tools.NewTurnBudget(1_000_000, dir) payload := strings.Repeat("q", 4000) reg := registryReturning(t, tools.ToolEntry{Name: "big"}, payload) - set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, Budget: budget}) + set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, SpillDir: dir}) out, err := set["big"].Execute(context.Background(), "{}") if err != nil { @@ -374,14 +373,15 @@ func TestToolSetSpillsOversizeResults(t *testing.T) { t.Fatalf("result = %q, want a spill reference", out) } - spilled := budget.Spilled() - if len(spilled) != 1 || spilled[0].Path == "" { - t.Fatalf("Spilled() = %+v, want one spill with a path", spilled) + entries, err := os.ReadDir(dir) + if err != nil || len(entries) != 1 { + t.Fatalf("spill directory entries = %v, err = %v; want one spill", entries, err) } - if !strings.Contains(out, spilled[0].Path) { - t.Errorf("result %q does not name the spill path %q", out, spilled[0].Path) + spillPath := filepath.Join(dir, entries[0].Name()) + if !strings.Contains(out, spillPath) { + t.Errorf("result %q does not name the spill path %q", out, spillPath) } - body, err := os.ReadFile(spilled[0].Path) + body, err := os.ReadFile(spillPath) if err != nil { t.Fatal(err) } @@ -391,14 +391,12 @@ func TestToolSetSpillsOversizeResults(t *testing.T) { } // TestToolLimitsCreatesSpillDir covers the gap that made spilling dead code in -// production: the configured directory defaults to /tool-spill and -// nothing ever created it, while TurnBudget.Spill swallows the write error. So -// every oversized result silently fell back to inline truncation and the spill -// path was never exercised outside tests that made their own directory. +// production: the configured directory was never created, so every oversized +// result silently fell back to inline truncation. func TestToolLimitsCreatesSpillDir(t *testing.T) { // A nested path proves the whole tree is created, not just a leaf. dir := filepath.Join(t.TempDir(), "work", "tool-spill") - limits := ToolLimits{MaxResultChars: 100, TurnBudgetChars: 1_000_000, SpillDir: dir} + limits := ToolLimits{MaxResultChars: 100, SpillDir: dir} if err := limits.EnsureSpillDir(); err != nil { t.Fatal(err) @@ -434,13 +432,9 @@ func TestToolLimitsEnsureSpillDirNoop(t *testing.T) { } } -// TestToolSetChargesBudgetOnce pins the invariant that makes the turn budget -// mean anything: a turn is charged exactly the bytes it was shown. -// -// Displacing an oversized result to disk used to charge the full displaced -// size AND the short reference handed back, so two 60 KB results burned more -// than the 200 K default budget while the model saw about 200 characters. -func TestToolSetChargesBudgetOnce(t *testing.T) { +// Tool result volume is bounded per invocation only. Repeated large results +// may each be spilled or truncated, but accumulation never stops the turn. +func TestToolSetPerResultLimitNeverStopsFurtherCalls(t *testing.T) { tests := []struct { name string spillDir bool @@ -455,49 +449,19 @@ func TestToolSetChargesBudgetOnce(t *testing.T) { if tc.spillDir { dir = t.TempDir() } - budget := tools.NewTurnBudget(1_000_000, dir) reg := registryReturning(t, tools.ToolEntry{Name: "big"}, strings.Repeat("q", 60_000)) - set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, Budget: budget}) + set := mustBuildToolSetWith(t, reg, ToolSetOptions{MaxResultChars: 100, SpillDir: dir}) - delivered := 0 - for range 2 { - out, err := set["big"].Execute(context.Background(), "{}") + for range 5 { + _, err := set["big"].Execute(context.Background(), "{}") if err != nil { - t.Fatal(err) + t.Fatalf("later tool call was stopped by accumulated output: %v", err) } - delivered += len(out) - } - - if used := budget.Used(); used != delivered { - t.Errorf("budget charged %d for %d delivered characters", used, delivered) } }) } } -// TestToolSetBudgetStopsFurtherCalls checks the aggregate cap: once a turn has -// spent its budget the next tool call must fail loudly, so the model is told it -// has run out rather than silently receiving nothing. -func TestToolSetBudgetStopsFurtherCalls(t *testing.T) { - budget := tools.NewTurnBudget(50, "") - reg := registryReturning(t, tools.ToolEntry{Name: "chatty"}, strings.Repeat("w", 200)) - set := mustBuildToolSetWith(t, reg, ToolSetOptions{Budget: budget}) - - if _, err := set["chatty"].Execute(context.Background(), "{}"); err != nil { - t.Fatalf("first call: %v", err) - } - if !budget.Exceeded() { - t.Fatal("budget should be exceeded after a 200-byte result against a 50-byte cap") - } - _, err := set["chatty"].Execute(context.Background(), "{}") - if err == nil { - t.Fatal("second call succeeded, want a budget-exceeded error") - } - if !strings.Contains(err.Error(), "budget") { - t.Errorf("error = %v, want it to name the budget", err) - } -} - // TestToolSetExcludesToolsets covers the task-agent case: a task runs in its // own worktree, so the chat workspace's file and shell tools must not follow it // in and bypass the agent loop's read-only and protected-path enforcement. diff --git a/internal/channels/telegram/live.go b/internal/channels/telegram/live.go index e65929eb7..5f6c33cfb 100644 --- a/internal/channels/telegram/live.go +++ b/internal/channels/telegram/live.go @@ -107,6 +107,10 @@ type liveReply struct { // every rendering stage can lead with it rather than have it buried // mid-answer or clamped away. toolLines []string + // failureLines and failureCounts let ToolCall replace a repeated failure + // in place with one counted entry instead of appending noisy retries. + failureLines map[string]int + failureCounts map[string]int // rendered is the last body actually sent. Telegram rejects an edit // that changes nothing, so an unchanged body is not sent at all. rendered string @@ -142,6 +146,8 @@ func (g *Gateway) newLiveReply(ctx context.Context, b *bot.Bot, chatID int64, me cancelRender: cancelRender, renderRequests: make(chan chan struct{}, 1), renderDone: make(chan struct{}), + failureLines: make(map[string]int), + failureCounts: make(map[string]int), } go live.runRenderer(renderCtx) g.registerLive(ctx, live) @@ -321,9 +327,19 @@ func (l *liveReply) ToolCall(event gateway.ToolCallEvent) { // raw/JSON-shaped parameters: they are noisy, can expose secrets, and were // the source of unreadable schema placeholders in Telegram. line := event.RenderToolCall() + key := event.FailureKey() l.mu.Lock() - l.toolLines = append(l.toolLines, line) + if index, ok := l.failureLines[key]; key != "" && ok { + l.failureCounts[key]++ + l.toolLines[index] = countedToolLine(line, l.failureCounts[key]) + } else { + l.toolLines = append(l.toolLines, line) + if key != "" { + l.failureLines[key] = len(l.toolLines) - 1 + l.failureCounts[key] = 1 + } + } l.mu.Unlock() // A tool call is a discrete event rather than a token, and there are @@ -332,6 +348,16 @@ func (l *liveReply) ToolCall(event gateway.ToolCallEvent) { l.requestRender() } +func countedToolLine(line string, count int) string { + if count <= 1 { + return line + } + if newline := strings.IndexByte(line, '\n'); newline >= 0 { + return line[:newline] + fmt.Sprintf(" Γ—%d", count) + line[newline:] + } + return line + fmt.Sprintf(" Γ—%d", count) +} + // mediaSendTimeout bounds one Media delivery. It is independent of the // render loop's own lifecycle (unlike answerBuf/toolLines, which a // /restart abandons via abandonAllLive): an upload in flight when the live diff --git a/internal/channels/telegram/live_test.go b/internal/channels/telegram/live_test.go index 2803317c2..70ee2e38d 100644 --- a/internal/channels/telegram/live_test.go +++ b/internal/channels/telegram/live_test.go @@ -6,6 +6,7 @@ import ( "log/slog" "net/http" "net/http/httptest" + "strconv" "strings" "sync" "testing" @@ -195,7 +196,7 @@ func TestLiveReplySnapshotsToolCallVisibility(t *testing.T) { live.finalize(context.Background(), "done") last := (*calls)[len(*calls)-1] - if !strings.Contains(last.markdown, "πŸ”§ shell\n```text\nexit 0\n```") { + if !strings.Contains(last.markdown, "πŸ”§ shell β€” done\n```text\nexit 0\n```") { t.Fatalf("final reply = %q, want the visibility captured when the reply started", last.markdown) } } @@ -215,8 +216,8 @@ func TestLiveReplyToolCallEscapesMarkdownMetacharacters(t *testing.T) { live.finalize(context.Background(), "**the answer**") last := (*calls)[len(*calls)-1] - if !strings.Contains(last.markdown, "```text\nfound `*bold*` and _italic_ markers\n```") { - t.Fatalf("tool output was not rendered in a fenced block: %q", last.markdown) + if !strings.Contains(last.markdown, "```text\n1 matches found; excerpts hidden\n```") { + t.Fatalf("tool output was not summarized in a fenced block: %q", last.markdown) } if !strings.Contains(last.markdown, "**the answer**") { t.Fatalf("model reply's own markdown was altered: %q", last.markdown) @@ -226,6 +227,57 @@ func TestLiveReplyToolCallEscapesMarkdownMetacharacters(t *testing.T) { } } +// This is the regression seam for #604: realistic completed ToolCallEvents are +// fed through the live Telegram renderer and asserted at the Bot API boundary. +// It deliberately includes the production failure shapes Sam observed: a +// JSON-quoted source file, a module-cache listing, a failed shell probe, and +// repeated aggregate tool-output character-limit errors. +func TestLiveReplyRendersNoisyToolTurnAsCompactTelegramText(t *testing.T) { + live, calls := newTestLiveReply(t, true) + + source := "package gateway\n\nimport (\n \"context\"\n \"fmt\"\n)\n\nfunc run() {}\n" + live.ToolCall(gateway.ToolCallEvent{ + Name: "read", + Parameters: `{"path":"[string]","offset":1,"limit":2000}`, + Output: `{"content":` + strconv.Quote(source) + `,"is_error":false}`, + }) + live.flushRendering() + live.ToolCall(gateway.ToolCallEvent{ + Name: "find", + Output: `{"content":"/home/sam/go/pkg/mod/example.org/a@v1.0.0/go.mod\n/home/sam/go/pkg/mod/example.org/b@v2.0.0/file.go\n/home/sam/projects/unrelated/main.go\n"}`, + }) + live.flushRendering() + live.ToolCall(gateway.ToolCallEvent{ + Name: "shell", + Err: "tool shell: command_exit: exit status 2\n[stderr]\ngrep: unmatched [", + }) + live.flushRendering() + for _, name := range []string{"read", "read", "read", "read", "shell"} { + live.ToolCall(gateway.ToolCallEvent{Name: name, Err: "tool " + name + ": turn budget exceeded (200000 chars)"}) + } + live.flushRendering() + live.finalize(context.Background(), "I found the relevant renderer and stopped after the output-volume cap.") + + got := (*calls)[len(*calls)-1].markdown + want := "πŸ”§ read β€” done\n```text\n8 lines read; content hidden\n```\n" + + "πŸ”§ find β€” done\n```text\n3 paths found; listing hidden\n```\n" + + "πŸ”§ shell β€” failed\n```text\ncommand_exit: exit status 2\n```\n" + + "πŸ”§ tools β€” stopped Γ—5\n```text\ntool-output limit reached (200000 chars); further results suppressed\n```\n\n" + + "I found the relevant renderer and stopped after the output-volume cap." + if got != want { + t.Fatalf("Telegram-visible text:\n%s\n\nwant:\n%s", got, want) + } + for i, call := range *calls { + for _, forbidden := range []string{ + "package gateway", `\\n`, `\\\"`, "pkg/mod", "projects/unrelated", "[string]", "turn budget exceeded", + } { + if strings.Contains(call.markdown, forbidden) { + t.Fatalf("Telegram frame %d leaked %q:\n%s", i, forbidden, call.markdown) + } + } + } +} + func TestLiveReplyToolCallSnapshotIsRaceFreeDuringReload(t *testing.T) { live, _ := newTestLiveReply(t, true) var wg sync.WaitGroup @@ -251,8 +303,8 @@ func TestLiveReplyToolCalls(t *testing.T) { { name: "shown", showToolCalls: true, - wantLive: "πŸ”§ shell\n```text\nexit 0\n```\n\nchecking β–Œ", - wantFinal: "πŸ”§ shell\n```text\nexit 0\n```\n\nchecking", + wantLive: "πŸ”§ shell β€” done\n```text\nexit 0\n```\n\nchecking β–Œ", + wantFinal: "πŸ”§ shell β€” done\n```text\nexit 0\n```\n\nchecking", }, { name: "hidden", @@ -660,7 +712,7 @@ func TestLiveReplyToolLinesSurviveTheLiveClamp(t *testing.T) { live.flushRendering() last := (*calls)[len(*calls)-1] - if !strings.HasPrefix(last.markdown, "πŸ”§ shell\n```text\nexit 0\n```\n\n") { + if !strings.HasPrefix(last.markdown, "πŸ”§ shell β€” done\n```text\nexit 0\n```\n\n") { t.Fatalf("live frame lost the tool line once the answer grew past the clamp: %.60q…", last.markdown) } if n := len([]rune(last.markdown)); n > 4096 { @@ -678,10 +730,10 @@ func TestLiveReplyFinalizeWithToolsAndNoReplyMarksTheAbsence(t *testing.T) { live.finalize(context.Background(), "") last := (*calls)[len(*calls)-1] - if last.markdown == "πŸ”§ shell\n```text\nexit 0\n```" { + if last.markdown == "πŸ”§ shell β€” done\n```text\nexit 0\n```" { t.Fatalf("finalize sent the bare tool line as the finished answer: %q", last.markdown) } - if !strings.Contains(last.markdown, "πŸ”§ shell\n```text\nexit 0\n```") { + if !strings.Contains(last.markdown, "πŸ”§ shell β€” done\n```text\nexit 0\n```") { t.Fatalf("finalize dropped the tool activity: %q", last.markdown) } if !strings.Contains(last.markdown, "no response") { @@ -712,8 +764,8 @@ func TestLiveReplyFramedTextClampsAnOversizedToolBlock(t *testing.T) { if !strings.Contains(last.markdown, "the answer") { t.Fatalf("answer was lost after bounding oversized tool output: %.80q…", last.markdown) } - if !strings.Contains(last.markdown, "…") { - t.Fatalf("oversized tool output was not marked as bounded: %.80q…", last.markdown) + if strings.Count(last.markdown, "ok") > 0 || !strings.Contains(last.markdown, "output lines hidden") { + t.Fatalf("oversized tool output was not summarized: %.80q…", last.markdown) } } diff --git a/internal/config/config.go b/internal/config/config.go index 3c880cf54..1d9de6d00 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -164,7 +164,6 @@ func (r Repo) EffectiveMaxRetries(global int) int { // Budgets bound every agent stage. Zero disables a limit. type Budgets struct { MaxSteps int `toml:"max_steps" json:"max_steps" yaml:"max_steps"` - MaxTokens int `toml:"max_tokens" json:"max_tokens" yaml:"max_tokens"` WallClock Duration `toml:"wall_clock" json:"wall_clock" yaml:"wall_clock"` GateMaxFailures int `toml:"gate_max_failures" json:"gate_max_failures" yaml:"gate_max_failures"` } @@ -312,9 +311,7 @@ type ToolPolicy struct { // MaxResultChars caps a single tool result before it reaches the model. // Tools that set ToolEntry.MaxResultSizeChars override it. MaxResultChars int `toml:"max_result_chars" yaml:"max_result_chars" json:"max_result_chars"` - // TurnBudgetChars caps the aggregate size of all tool results in one - // chat turn or agent stage. - TurnBudgetChars int `toml:"turn_budget_chars" yaml:"turn_budget_chars" json:"turn_budget_chars"` + // SpillDir is where results too large to inline are written so the model // can be handed a path instead of losing the content. Empty disables // spilling, leaving inline truncation as the only option. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 142ceff3a..4e682cf60 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -16,7 +16,7 @@ func TestTaskConfigToConfigRoundTrip(t *testing.T) { cfg := Config{ DiffCapLines: 321, Models: map[string]string{"builder": "anthropic/claude"}, - Budgets: Budgets{MaxSteps: 12, MaxTokens: 34_000, WallClock: Duration(45 * time.Minute), GateMaxFailures: 3}, + Budgets: Budgets{MaxSteps: 12, WallClock: Duration(45 * time.Minute), GateMaxFailures: 3}, Dispatch: Dispatch{Trigger: "label", AckReaction: "eyes", Labels: map[string]string{"working": "bot:working"}}, Notify: Notify{Webhook: "https://notify.example.test/hook"}, Forge: Forge{Type: "github", Host: "https://forge.example.test", Token: secret.SecretRef{Engine: "env", Key: "TOP_SECRET"}}, @@ -91,8 +91,8 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) { "planner": "openai/gpt", }, Budgets: Budgets{ - MaxSteps: 12, - MaxTokens: 34_000, + MaxSteps: 12, + WallClock: Duration(45 * time.Minute), GateMaxFailures: 3, }, diff --git a/internal/domain/workflow/agent.go b/internal/domain/workflow/agent.go index ce392a7ad..7a4b0652b 100644 --- a/internal/domain/workflow/agent.go +++ b/internal/domain/workflow/agent.go @@ -75,7 +75,6 @@ func (a AgentStage) Stage() Stage { budget := agentexec.Budget{ MaxSteps: tc.Cfg.Budgets.MaxSteps, - MaxTokens: tc.Cfg.Budgets.MaxTokens, WallClock: tc.Cfg.Budgets.WallClock.Std(), } if a.MaxSteps > 0 { diff --git a/internal/domain/workflow/agent_test.go b/internal/domain/workflow/agent_test.go index bc284d3ed..d3b966bb2 100644 --- a/internal/domain/workflow/agent_test.go +++ b/internal/domain/workflow/agent_test.go @@ -69,7 +69,7 @@ func TestAgentStageBuildsExecutionRequestAndAppliesResult(t *testing.T) { Task: task, Agent: runner, Dir: "/tmp/workspace", Log: slog.New(slog.DiscardHandler), Cfg: config.Config{ Models: map[string]string{"builder": "provider/fallback"}, - Budgets: config.Budgets{MaxSteps: 50, MaxTokens: 5000}, + Budgets: config.Budgets{MaxSteps: 50}, }, Repo: config.Repo{Protect: []string{"_templ.go"}, Preflight: [][]string{{"go", "version"}}}, } diff --git a/internal/domain/workflow/implement.go b/internal/domain/workflow/implement.go index 85997f8ce..ee3db088e 100644 --- a/internal/domain/workflow/implement.go +++ b/internal/domain/workflow/implement.go @@ -74,7 +74,6 @@ func StageBaselineGate() Stage { Mission: mission, Budget: agentexec.Budget{ MaxSteps: tc.Cfg.Budgets.MaxSteps, - MaxTokens: tc.Cfg.Budgets.MaxTokens, WallClock: tc.Cfg.Budgets.WallClock.Std(), }, Gate: GateFromRepo(tc.Repo, tc.Cfg.Budgets), diff --git a/internal/gateway/stream.go b/internal/gateway/stream.go index 21ea53a17..1cafcd1e7 100644 --- a/internal/gateway/stream.go +++ b/internal/gateway/stream.go @@ -2,6 +2,7 @@ package gateway import ( "encoding/json" + "fmt" "strings" ) @@ -49,22 +50,125 @@ func (e ToolCallEvent) Summary() string { // RenderToolCall returns the channel-neutral compact representation used by // chat surfaces. Parameters are intentionally omitted: JSON/schema-shaped // inputs are noisy, often contain secrets, and are not useful progress text. -// The bounded fenced block keeps multiline command output readable without -// allowing one result to bury the answer or exceed Telegram's message limit. +// Results are reduced semantically instead of clipped blindly: file contents, +// listings and structured envelopes are described, never echoed. func (e ToolCallEvent) RenderToolCall() string { - header := "πŸ”§ " + strings.TrimSpace(e.Name) - if line := firstNonEmptyLine(e.Err); line != "" { - return header + " β€” ❌ " + truncateRunes(line, toolSummaryMaxRunes) + if limit, ok := legacyTurnBudgetLimit(e.Err); ok { + return toolProgressBlock("tools", "stopped", fmt.Sprintf("tool-output limit reached (%s chars); further results suppressed", limit)) } - if strings.TrimSpace(e.Output) == "" { - return header + " β€” done" + if line := cleanToolError(e.Name, e.Err); line != "" { + return toolProgressBlock(e.Name, "failed", line) } - const maxOutputRunes = 480 - output := strings.TrimSpace(e.Output) - output = truncateRunes(output, maxOutputRunes) - // A nested fence would terminate the block early in Markdown renderers. - output = strings.ReplaceAll(output, "```", "''' ") - return header + "\n```text\n" + output + "\n```" + return toolProgressBlock(e.Name, "done", toolPreview(e.Name, e.Output)) +} + +// FailureKey identifies equivalent failures for channel adapters that collapse +// retries. Legacy aggregate-output-limit errors deliberately share one key +// across tool names: they are one obsolete turn-level condition, not five +// independently useful failures. +func (e ToolCallEvent) FailureKey() string { + if _, ok := legacyTurnBudgetLimit(e.Err); ok { + return "legacy-turn-output-limit" + } + if line := cleanToolError(e.Name, e.Err); line != "" { + return strings.TrimSpace(e.Name) + "\x00" + line + } + return "" +} + +func toolProgressBlock(name, status, preview string) string { + name = strings.TrimSpace(name) + if name == "" { + name = "tool" + } + preview = strings.ReplaceAll(strings.TrimSpace(preview), "```", "''' ") + if preview == "" { + preview = "completed" + } + return "πŸ”§ " + name + " β€” " + status + "\n```text\n" + truncateRunes(preview, 180) + "\n```" +} + +func toolPreview(name, output string) string { + content, structured := unwrapToolContent(output) + trimmed := strings.TrimSpace(content) + lowerName := strings.ToLower(strings.TrimSpace(name)) + lines := countNonEmptyOrContentLines(content) + + switch { + case strings.Contains(lowerName, "read"): + if lines == 0 { + return "file read completed" + } + return fmt.Sprintf("%d lines read; content hidden", lines) + case strings.Contains(lowerName, "find") || strings.Contains(lowerName, "list"): + return fmt.Sprintf("%d paths found; listing hidden", lines) + case strings.Contains(lowerName, "grep") || strings.Contains(lowerName, "search"): + return fmt.Sprintf("%d matches found; excerpts hidden", lines) + case strings.Contains(lowerName, "shell") || strings.Contains(lowerName, "terminal"): + if lines > 1 || looksLikeSourceOrListing(trimmed) || structured { + return fmt.Sprintf("command completed; %d output lines hidden", lines) + } + } + if structured { + return "structured result received; details hidden" + } + if looksLikeSourceOrListing(trimmed) { + return fmt.Sprintf("%d output lines hidden", lines) + } + return firstNonEmptyLine(trimmed) +} + +func unwrapToolContent(output string) (string, bool) { + trimmed := strings.TrimSpace(output) + if trimmed == "" { + return "", false + } + var envelope struct { + Content string `json:"content"` + } + if json.Unmarshal([]byte(trimmed), &envelope) == nil && envelope.Content != "" { + return envelope.Content, true + } + var quoted string + if json.Unmarshal([]byte(trimmed), "ed) == nil { + return quoted, true + } + return output, false +} + +func countNonEmptyOrContentLines(s string) int { + if strings.TrimSpace(s) == "" { + return 0 + } + trimmed := strings.TrimRight(s, "\r\n") + return strings.Count(trimmed, "\n") + 1 +} + +func looksLikeSourceOrListing(s string) bool { + return strings.Contains(s, "\n") && (strings.Contains(s, "package ") || + strings.Contains(s, "module ") || strings.Contains(s, "/pkg/mod/") || + strings.Contains(s, "/home/") || strings.Contains(s, "func ")) +} + +func cleanToolError(name, raw string) string { + line := firstNonEmptyLine(raw) + prefix := "tool " + strings.TrimSpace(name) + ": " + line = strings.TrimPrefix(line, prefix) + return truncateRunes(strings.TrimSpace(line), toolSummaryMaxRunes) +} + +func legacyTurnBudgetLimit(raw string) (string, bool) { + const marker = "turn budget exceeded (" + _, after, ok := strings.Cut(raw, marker) + if !ok { + return "", false + } + rest := after + end := strings.Index(rest, " chars)") + if end < 1 { + return "", false + } + return rest[:end], true } // SummarizeToolParameters returns a bounded JSON shape of tool input. Every diff --git a/internal/gateway/tool_render_test.go b/internal/gateway/tool_render_test.go index 38f256c4a..55d3b71b1 100644 --- a/internal/gateway/tool_render_test.go +++ b/internal/gateway/tool_render_test.go @@ -10,7 +10,7 @@ func TestToolCallEventRenderToolCallUsesCompactSafeOutput(t *testing.T) { if strings.Contains(got, "schema placeholder") || strings.Contains(got, "Parameters") { t.Fatalf("render leaked input/schema noise: %q", got) } - want := "πŸ”§ shell\n```text\nline one\nline two\n```" + want := "πŸ”§ shell β€” done\n```text\ncommand completed; 2 output lines hidden\n```" if got != want { t.Fatalf("render = %q, want %q", got, want) } @@ -21,11 +21,22 @@ func TestToolCallEventRenderToolCallBoundsOutputAndPreservesFailure(t *testing.T if len([]rune(got)) > 520 { t.Fatalf("render has %d runes, want bounded output", len([]rune(got))) } - if !strings.Contains(got, "…") { - t.Fatal("bounded output lacks truncation marker") + if strings.Contains(got, strings.Repeat("x", 20)) || !strings.Contains(got, "content hidden") { + t.Fatalf("file contents were not summarized: %q", got) } failed := (ToolCallEvent{Name: "shell", Output: "ignored", Err: "command_exit: exit status 2"}).RenderToolCall() - if failed != "πŸ”§ shell β€” ❌ command_exit: exit status 2" { + if failed != "πŸ”§ shell β€” failed\n```text\ncommand_exit: exit status 2\n```" { t.Fatalf("failure render = %q", failed) } } + +func TestToolCallEventFailureKeyCollapsesLegacyTurnBudget(t *testing.T) { + first := ToolCallEvent{Name: "read", Err: "tool read: turn budget exceeded (200000 chars)"} + second := ToolCallEvent{Name: "shell", Err: "tool shell: turn budget exceeded (200000 chars)"} + if first.FailureKey() == "" || first.FailureKey() != second.FailureKey() { + t.Fatalf("legacy output-limit failures should share one key: %q vs %q", first.FailureKey(), second.FailureKey()) + } + if first.RenderToolCall() != "πŸ”§ tools β€” stopped\n```text\ntool-output limit reached (200000 chars); further results suppressed\n```" { + t.Fatalf("legacy output-limit render = %q", first.RenderToolCall()) + } +} diff --git a/internal/gateway/turn.go b/internal/gateway/turn.go index 6fb14c33a..52c8593c4 100644 --- a/internal/gateway/turn.go +++ b/internal/gateway/turn.go @@ -34,8 +34,8 @@ type PreparedTurnModel interface { // TurnModelRequest is the provider-neutral request assembled by the gateway. // Messages include the system prompt as their first entry. type TurnModelRequest struct { - Messages []CompressedMessage - MaxTokens int + Messages []CompressedMessage + MaxOutputTokens int } // PersonaPromptSource supplies the active persona prompt for a session. @@ -303,8 +303,8 @@ func (r *TurnRunner) Run(ctx context.Context, msg Message, stream TurnStream) (s ) recorder := &toolCallRecorder{next: stream} text, err := prepared.Generate(ctx, TurnModelRequest{ - Messages: view.Messages, - MaxTokens: modelDetails.MaxOutputTokens, + Messages: view.Messages, + MaxOutputTokens: modelDetails.MaxOutputTokens, }, recorder) if err != nil { return "", r.failTurn(ctx, turn, err) diff --git a/internal/infrastructure/configuration/apply_test.go b/internal/infrastructure/configuration/apply_test.go index dd5aa0e4f..ca15cbd20 100644 --- a/internal/infrastructure/configuration/apply_test.go +++ b/internal/infrastructure/configuration/apply_test.go @@ -28,10 +28,6 @@ func TestApplyOverlayValuesFieldLevelMerge(t *testing.T) { if cfg.BotUser != "a" { t.Errorf("BotUser = %q, want a (unchanged)", cfg.BotUser) } - // Unrelated nested fields keep their value too. - if cfg.Budgets.MaxTokens != 0 { - t.Errorf("MaxTokens = %d, want 0 (untouched)", cfg.Budgets.MaxTokens) - } } func TestLoaderApplyOverlayLayersDefaultsValidatesAndRecordsProvenance(t *testing.T) { diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index 61b131a7e..53a06835e 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -8,7 +8,6 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/secret" - "github.com/samcharles93/archie-core/internal/tools" ) // Defaults applied to absent input. Named so a reader can find the value @@ -99,9 +98,7 @@ func applyToolPolicyDefaults(cfg *config.Config) { if cfg.Tools.Policy.MaxResultChars == 0 { cfg.Tools.Policy.MaxResultChars = defaultMaxResultChars } - if cfg.Tools.Policy.TurnBudgetChars == 0 { - cfg.Tools.Policy.TurnBudgetChars = tools.DefaultTurnBudgetChars - } + // SpillDir is deliberately NOT defaulted. // // Spilling hands the model a file path to read back, and the read tool is diff --git a/internal/infrastructure/configuration/dir_test.go b/internal/infrastructure/configuration/dir_test.go index a39f1b02d..7e3aab9f4 100644 --- a/internal/infrastructure/configuration/dir_test.go +++ b/internal/infrastructure/configuration/dir_test.go @@ -517,7 +517,7 @@ func tmpConfigDir(t *testing.T) string { // - NO_COLOR // budgets: // max_steps: 60 -// max_tokens: 500000 + // wall_clock: 30m // `) diff --git a/internal/infrastructure/configuration/loader_test.go b/internal/infrastructure/configuration/loader_test.go index a6e9406d8..56786354c 100644 --- a/internal/infrastructure/configuration/loader_test.go +++ b/internal/infrastructure/configuration/loader_test.go @@ -1,6 +1,7 @@ package configuration import ( + "encoding/json" "os" "path/filepath" "strings" @@ -262,35 +263,32 @@ func TestLoadAgentDefaultsAndOverrides(t *testing.T) { // explicit 0 from an absent key, so zero has to stay available as "unset". func TestLoadToolPolicyDefaultsAndOverrides(t *testing.T) { tests := []struct { - name string - policy string - wantMaxResult int - wantTurnBudget int - wantSpillDir string + name string + policy string + wantMaxResult int + wantSpillDir string }{ { // SpillDir has no default on purpose: a path outside // chat.workspace is one the read tool refuses, so the model would // be handed a reference it cannot open. Absent means truncate // inline. - name: "defaults", - wantMaxResult: 50_000, - wantTurnBudget: 200_000, - wantSpillDir: "", + name: "defaults", + wantMaxResult: 50_000, + + wantSpillDir: "", }, { - name: "explicit values", - policy: "[tools.tool_policy]\nmax_result_chars = 1234\nturn_budget_chars = 5678\nspill_dir = \"/var/spool/archie\"\n", - wantMaxResult: 1234, - wantTurnBudget: 5678, - wantSpillDir: "/var/spool/archie", + name: "explicit values", + policy: "[tools.tool_policy]\nmax_result_chars = 1234\nspill_dir = \"/var/spool/archie\"\n", + wantMaxResult: 1234, + wantSpillDir: "/var/spool/archie", }, { - name: "negative disables both caps", - policy: "[tools.tool_policy]\nmax_result_chars = -1\nturn_budget_chars = -1\n", - wantMaxResult: -1, - wantTurnBudget: -1, - wantSpillDir: "", + name: "negative disables the per-result cap", + policy: "[tools.tool_policy]\nmax_result_chars = -1\n", + wantMaxResult: -1, + wantSpillDir: "", }, } @@ -312,9 +310,7 @@ func TestLoadToolPolicyDefaultsAndOverrides(t *testing.T) { if policy.MaxResultChars != tt.wantMaxResult { t.Errorf("MaxResultChars = %d, want %d", policy.MaxResultChars, tt.wantMaxResult) } - if policy.TurnBudgetChars != tt.wantTurnBudget { - t.Errorf("TurnBudgetChars = %d, want %d", policy.TurnBudgetChars, tt.wantTurnBudget) - } + if policy.SpillDir != tt.wantSpillDir { t.Errorf("SpillDir = %q, want %q", policy.SpillDir, tt.wantSpillDir) } @@ -322,6 +318,32 @@ func TestLoadToolPolicyDefaultsAndOverrides(t *testing.T) { } } +func TestRemovedTurnCapsAreIgnoredByLegacyConfig(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + contents := "bot_user = \"widget\"\n[budgets]\nmax_tokens = 1\n" + + "[tools.tool_policy]\nmax_result_chars = 1234\nturn_budget_chars = 1\n" + + "[[repos]]\nowner = \"acme\"\nname = \"app\"\n" + if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := loadFile(path) + if err != nil { + t.Fatal(err) + } + encoded, err := json.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + for _, removed := range []string{"max_tokens", "turn_budget_chars"} { + if strings.Contains(string(encoded), removed) { + t.Fatalf("removed turn cap %q survived config decode: %s", removed, encoded) + } + } + if cfg.Tools.Policy.MaxResultChars != 1234 { + t.Fatalf("per-tool result cap = %d, want 1234", cfg.Tools.Policy.MaxResultChars) + } +} + // TestLoadWebFetchDefaultsAndOverrides covers the fetch tool's settings. // // The enabled case matters most: it is a pointer precisely so an operator can diff --git a/internal/infrastructure/configuration/tomlwrite/tomlwrite_test.go b/internal/infrastructure/configuration/tomlwrite/tomlwrite_test.go index b95fe3829..98d55823d 100644 --- a/internal/infrastructure/configuration/tomlwrite/tomlwrite_test.go +++ b/internal/infrastructure/configuration/tomlwrite/tomlwrite_test.go @@ -71,14 +71,14 @@ func TestApply_CommentedTable_UncommentsOnlyRequestedKey(t *testing.T) { func TestApply_MissingKeyInExistingActiveTable_Appends(t *testing.T) { out, err := tomlwrite.Apply([]byte(sample), []tomlwrite.Edit{ - {Table: "budgets", Key: "max_tokens", Value: "400000"}, + {Table: "budgets", Key: "wall_clock", Value: "\"45m\""}, }) if err != nil { t.Fatal(err) } got := string(out) - if !strings.Contains(got, "[budgets]\nmax_steps = 60\nmax_tokens = 400000\n") { - t.Fatalf("expected max_tokens appended after max_steps, got:\n%s", got) + if !strings.Contains(got, "[budgets]\nmax_steps = 60\nwall_clock = \"45m\"\n") { + t.Fatalf("expected wall_clock appended after max_steps, got:\n%s", got) } } diff --git a/internal/tools/budget.go b/internal/tools/budget.go index 590a3dd2e..669c3c0ee 100644 --- a/internal/tools/budget.go +++ b/internal/tools/budget.go @@ -4,142 +4,17 @@ import ( "fmt" "os" "strings" - "sync" "unicode/utf8" ) -// DefaultTurnBudgetChars is the default per-turn aggregate output budget -// in characters (200,000 chars β‰ˆ 50K tokens at ~4 chars/token). -const DefaultTurnBudgetChars = 200_000 - -// SpillRef is a reference to a tool result that was spilled to disk because -// it exceeded the turn budget. -type SpillRef struct { - // Path is the absolute path to the spill file on disk. - Path string - - // SizeChars is the size of the spilled result in characters. - SizeChars int -} - -// TurnBudget tracks cumulative tool result sizes within a single turn. -// When the budget is exceeded the largest results are spilled to disk -// and replaced with spill references. A hard stop prevents further -// tool calls once the budget is exhausted. -// -// All methods are safe for concurrent use. -type TurnBudget struct { - MaxChars int - - mu sync.Mutex - used int - - // spillDir is where oversized results are written. Empty means - // spill-to-disk is disabled (results are truncated instead). - spillDir string - - // spilled tracks all results that have been spilled to disk. - spilled []SpillRef - - // exceeded is set to true when used >= MaxChars. - exceeded bool -} - -// NewTurnBudget creates a [TurnBudget] with the given character limit. -// If spillDir is non-empty, oversized results are written to that -// directory instead of being truncated inline. -func NewTurnBudget(maxChars int, spillDir string) *TurnBudget { - return &TurnBudget{ - MaxChars: maxChars, - spillDir: spillDir, - } -} - -// Consume attempts to allocate n characters against the budget. -// It returns true if the allocation succeeded (budget not yet exceeded). -// When the budget is exceeded on this call, exceeded is set and -// subsequent calls always return false. -func (b *TurnBudget) Consume(n int) bool { - b.mu.Lock() - defer b.mu.Unlock() - - if b.exceeded { - return false - } - - b.used += n - if b.used > b.MaxChars { - b.exceeded = true - return false - } - return true -} - -// Spill writes the given result content to disk and returns a [SpillRef]. -// When spillDir is empty, the content is discarded and a SpillRef with an -// empty Path is returned (callers should treat this as "result truncated"). -// -// The spill consumes len(content) characters from the budget regardless -// of whether a file was actually written. -func (b *TurnBudget) Spill(toolName string, content []byte) SpillRef { - b.mu.Lock() - defer b.mu.Unlock() - - ref := b.writeSpillLocked(toolName, content) - b.used += ref.SizeChars - if b.used > b.MaxChars { - b.exceeded = true - } - return ref -} - -// WriteSpill writes content to the spill directory and records the reference -// without charging the budget. -// -// It exists so that displacing a result to disk and billing for it are separate -// decisions. A caller that hands the model a short spill reference has shown it -// only those few characters and should be charged for those; charging the full -// displaced size as well bills a turn twice for one result and exhausts it -// early. [CapPayload] uses this; the batch-dispatch path uses [TurnBudget.Spill], -// which still charges, because it accounts for the result separately. -func (b *TurnBudget) WriteSpill(toolName string, content []byte) SpillRef { - b.mu.Lock() - defer b.mu.Unlock() - return b.writeSpillLocked(toolName, content) -} - -// writeSpillLocked performs the write. Must be called with b.mu held. -func (b *TurnBudget) writeSpillLocked(toolName string, content []byte) SpillRef { - ref := SpillRef{SizeChars: len(content)} - - if b.spillDir != "" { - ref.Path = writeSpillFile(b.spillDir, toolName, content) - } - - b.spilled = append(b.spilled, ref) - return ref -} - -// writeSpillFile writes content to a fresh file in dir, returning its path or -// "" when the write fails. A failure is not an error here: the caller falls -// back to inline truncation, which is degraded but correct. -// -// The name comes from CreateTemp rather than from budget state. A budget is -// minted per turn and every turn shares one directory, so any within-budget -// counter restarts at zero each turn and the second turn would overwrite the -// first turn's file, handing one session a reference that resolves to another -// session's output. -// -// 0600 because this is verbatim tool output -- shell stdout, file contents, MCP -// responses. It is the first place archie persists that material and it can -// hold anything the tools could read. +// writeSpillFile writes content to a fresh private file in dir, returning an +// empty path when writing fails so callers can fall back to inline truncation. func writeSpillFile(dir, toolName string, content []byte) string { f, err := os.CreateTemp(dir, "spill-"+sanitiseToolName(toolName)+"-*") if err != nil { return "" } defer f.Close() - if err := f.Chmod(0o600); err != nil { return "" } @@ -149,9 +24,6 @@ func writeSpillFile(dir, toolName string, content []byte) string { return f.Name() } -// sanitiseToolName strips path separators and other characters that must not -// reach a filename. MCP tool names are supplied by a third-party server, so a -// name like "../../etc/passwd" is reachable input rather than a hypothetical. func sanitiseToolName(name string) string { var b strings.Builder b.Grow(len(name)) @@ -169,49 +41,28 @@ func sanitiseToolName(name string) string { return b.String() } -// CapPayload bounds one tool result to max bytes before it reaches the model. -// It is the single definition of that rule: [enforcePerToolLimit] applies it on -// the batch-dispatch path, and the agent tool set applies it to the marshalled -// payload it hands back to the model. -// -// When budget has a spill directory the whole result is written there and the -// model is given the path, so an oversized result is displaced rather than -// lost. Without one -- or when the write fails -- the result is truncated -// inline on a rune boundary. -// -// Either way the return value carries a notice naming the tool and the full -// size. Shortening a result silently is how a model concludes a file is empty -// or a search found nothing, so the fact of truncation is never implicit. -// -// max <= 0 disables capping. -func CapPayload(toolName, payload string, limit int, budget *TurnBudget) string { +// CapPayload bounds one tool result before it reaches the model. Oversized +// results are spilled when spillDir is configured and writable; otherwise they +// are explicitly truncated on a rune boundary. There is deliberately no +// aggregate per-turn accounting or stopping condition. +func CapPayload(toolName, payload string, limit int, spillDir string) string { if limit <= 0 || len(payload) <= limit { return payload } - - if budget != nil { - // WriteSpill, not Spill: the caller charges for what it actually - // hands the model, which is the short reference below, not the - // displaced payload. - if ref := budget.WriteSpill(toolName, []byte(payload)); ref.Path != "" { + if spillDir != "" { + if path := writeSpillFile(spillDir, toolName, []byte(payload)); path != "" { return fmt.Sprintf( "[%s: result spilled to %s (%d characters); too large to inline]", - toolName, ref.Path, ref.SizeChars, + toolName, path, len(payload), ) } - // Spill was disabled or failed -- fall through to inline truncation. } - return truncateAtRuneBoundary(payload, limit) + fmt.Sprintf( "\n\n[%s: result truncated, showing the first %d of %d characters]", toolName, limit, len(payload), ) } -// truncateAtRuneBoundary cuts s to at most max bytes without splitting a -// multi-byte rune. A half rune is invalid UTF-8: some providers reject the -// request outright and others render a replacement character mid-word, so the -// cut always retreats to a boundary even when that costs a few bytes. func truncateAtRuneBoundary(s string, limit int) string { if limit >= len(s) { return s @@ -221,50 +72,3 @@ func truncateAtRuneBoundary(s string, limit int) string { } return s[:limit] } - -// Used reports the total characters consumed so far. -func (b *TurnBudget) Used() int { - b.mu.Lock() - defer b.mu.Unlock() - return b.used -} - -// Remaining reports how many characters are left in the budget. -// Returns 0 when the budget is exceeded. -func (b *TurnBudget) Remaining() int { - b.mu.Lock() - defer b.mu.Unlock() - if b.exceeded { - return 0 - } - remaining := b.MaxChars - b.used - if remaining < 0 { - return 0 - } - return remaining -} - -// Exceeded reports whether the budget has been exceeded. -func (b *TurnBudget) Exceeded() bool { - b.mu.Lock() - defer b.mu.Unlock() - return b.exceeded -} - -// Spilled returns a snapshot of all spill references. -func (b *TurnBudget) Spilled() []SpillRef { - b.mu.Lock() - defer b.mu.Unlock() - out := make([]SpillRef, len(b.spilled)) - copy(out, b.spilled) - return out -} - -// Reset clears all counters and spill tracking for the next turn. -func (b *TurnBudget) Reset() { - b.mu.Lock() - defer b.mu.Unlock() - b.used = 0 - b.spilled = nil - b.exceeded = false -} diff --git a/internal/tools/budget_test.go b/internal/tools/budget_test.go index 09846b0fe..7752f9459 100644 --- a/internal/tools/budget_test.go +++ b/internal/tools/budget_test.go @@ -8,498 +8,76 @@ import ( "unicode/utf8" ) -func TestDefaultTurnBudgetChars(t *testing.T) { - if DefaultTurnBudgetChars != 200_000 { - t.Errorf("DefaultTurnBudgetChars = %d, want 200000", DefaultTurnBudgetChars) - } -} - -func TestTurnBudgetConsume(t *testing.T) { - b := NewTurnBudget(1000, "") - - // Consume within budget. - if !b.Consume(500) { - t.Error("expected consume to succeed") - } - if b.Used() != 500 { - t.Errorf("Used = %d, want 500", b.Used()) - } - if b.Remaining() != 500 { - t.Errorf("Remaining = %d, want 500", b.Remaining()) - } - if b.Exceeded() { - t.Error("should not be exceeded") - } - - // Consume more within budget. - if !b.Consume(400) { - t.Error("expected consume to succeed") - } - - // This exceeds the budget. - if b.Consume(200) { - t.Error("expected consume to fail") - } - if !b.Exceeded() { - t.Error("should be exceeded") - } - if b.Remaining() != 0 { - t.Errorf("Remaining = %d, want 0", b.Remaining()) - } - - // Subsequent consumes always fail. - if b.Consume(1) { - t.Error("consume should fail after exceeded") - } -} - -func TestTurnBudgetExactBoundary(t *testing.T) { - // At exactly MaxChars, should succeed. Exceeded only above MaxChars. - b := NewTurnBudget(100, "") - if !b.Consume(99) { - t.Error("99/100 should succeed") - } - if !b.Consume(1) { - t.Error("100/100 should succeed (exactly at limit)") - } - if b.Exceeded() { - t.Error("should not be exceeded at exactly the limit") - } - // One more char triggers exceeded. - if b.Consume(1) { - t.Error("101/100 should be exceeded") - } - if !b.Exceeded() { - t.Error("should be exceeded above the limit") - } -} - -func TestTurnBudgetSpillToDisk(t *testing.T) { - dir := t.TempDir() - b := NewTurnBudget(100, dir) - - // Spill some content. - content := []byte(strings.Repeat("x", 200)) - ref := b.Spill("my-tool", content) - - if ref.SizeChars != 200 { - t.Errorf("SizeChars = %d, want 200", ref.SizeChars) - } - if ref.Path == "" { - t.Error("spill path should not be empty") - } - if !strings.HasPrefix(ref.Path, dir) { - t.Errorf("spill path %q should be under %q", ref.Path, dir) - } - - // Verify file exists and has correct content. - got, err := os.ReadFile(ref.Path) - if err != nil { - t.Fatalf("read spill file: %v", err) - } - if string(got) != string(content) { - t.Errorf("spill content mismatch: got %q, want %q", string(got), string(content)) - } - - // Budget should be exceeded after spill. - if !b.Exceeded() { - t.Error("budget should be exceeded after spilling 200 chars into 100 budget") - } -} - -func TestTurnBudgetSpillNoDir(t *testing.T) { - b := NewTurnBudget(100, "") - - ref := b.Spill("tool", []byte("hello")) - if ref.Path != "" { - t.Error("spill path should be empty when spillDir is empty") - } - if ref.SizeChars != 5 { - t.Errorf("SizeChars = %d, want 5", ref.SizeChars) - } -} - -func TestTurnBudgetSpilled(t *testing.T) { - b := NewTurnBudget(1000, "") - - b.Spill("a", []byte("aa")) - b.Spill("b", []byte("bb")) - - spilled := b.Spilled() - if len(spilled) != 2 { - t.Errorf("expected 2 spills, got %d", len(spilled)) - } - if spilled[0].SizeChars != 2 { - t.Errorf("first spill size = %d, want 2", spilled[0].SizeChars) - } - if spilled[1].SizeChars != 2 { - t.Errorf("second spill size = %d, want 2", spilled[1].SizeChars) - } -} - -func TestTurnBudgetReset(t *testing.T) { - b := NewTurnBudget(100, "") - b.Consume(99) - b.Spill("tool", []byte("overflow")) - - if !b.Exceeded() { - t.Fatal("expected exceeded") - } - - b.Reset() - - if b.Exceeded() { - t.Error("after reset, should not be exceeded") - } - if b.Used() != 0 { - t.Errorf("Used = %d, want 0", b.Used()) - } - if b.Remaining() != 100 { - t.Errorf("Remaining = %d, want 100", b.Remaining()) - } - if len(b.Spilled()) != 0 { - t.Errorf("Spilled = %d, want 0", len(b.Spilled())) - } -} - -func TestTurnBudgetConcurrent(t *testing.T) { - b := NewTurnBudget(100_000, "") - - done := make(chan struct{}) - for range 10 { - go func() { - for range 100 { - b.Consume(10) - b.Used() - b.Remaining() - b.Exceeded() - } - done <- struct{}{} - }() - } - - for range 10 { - <-done - } - - // No panic and budget was consumed. - if b.Used() < 1000 { - t.Errorf("Used = %d, expected at least 1000", b.Used()) - } -} - -func TestTurnBudgetSpillFileNaming(t *testing.T) { - dir := t.TempDir() - b := NewTurnBudget(100_000, dir) - - b.Spill("my-awesome-tool", []byte("data")) - - spilled := b.Spilled() - if len(spilled) != 1 { - t.Fatalf("expected 1 spill, got %d", len(spilled)) - } - - // File name should contain the tool name. - base := filepath.Base(spilled[0].Path) - if !strings.Contains(base, "my-awesome-tool") { - t.Errorf("spill file name %q should contain tool name", base) - } -} - -func TestCapPayload(t *testing.T) { - const ( - toolName = "skill_activate" - short = "abcdefghij" // 10 bytes - ) - long := strings.Repeat("x", 500) - // oversize begins with short, so a truncation at len(short) is - // recognisable in the result rather than being an opaque prefix. - oversize := short + long - - tests := []struct { - name string - // budget selects how the TurnBudget is built: "none" passes nil, - // "spill" gives it a usable directory, "nospill" gives it none, - // "badspill" gives it a directory that cannot be written. - budget string - payload string - max int - wantPayload string // exact result, when the payload passes through - wantContain []string // substrings the capped result must carry - }{ - { - name: "no cap when max is zero", - budget: "none", - payload: long, - max: 0, - wantPayload: long, - }, - { - name: "no cap when max is negative", - budget: "none", - payload: long, - max: -1, - wantPayload: long, - }, - { - name: "under the cap passes through", - budget: "none", - payload: short, - max: len(short) + 1, - wantPayload: short, - }, - { - name: "exactly at the cap passes through", - budget: "none", - payload: short, - max: len(short), - wantPayload: short, - }, - { - name: "over the cap without a budget truncates and names the tool", - budget: "none", - payload: oversize, - max: len(short), - wantContain: []string{short, toolName, "510"}, - }, - { - name: "over the cap with no spill directory truncates", - budget: "nospill", - payload: oversize, - max: len(short), - wantContain: []string{short, toolName, "510"}, - }, - { - name: "over the cap with a spill directory reports the path", - budget: "spill", - payload: oversize, - max: len(short), - wantContain: []string{toolName, "spill-"}, - }, - { - name: "spill write failure falls back to truncation", - budget: "badspill", - payload: oversize, - max: len(short), - wantContain: []string{short, toolName, "510"}, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - var budget *TurnBudget - switch tc.budget { - case "spill": - budget = NewTurnBudget(1_000_000, t.TempDir()) - case "nospill": - budget = NewTurnBudget(1_000_000, "") - case "badspill": - f, err := os.CreateTemp(t.TempDir(), "spill-blocker") - if err != nil { - t.Fatal(err) - } - f.Close() - budget = NewTurnBudget(1_000_000, filepath.Join(f.Name(), "sub")) - } - - got := CapPayload(toolName, tc.payload, tc.max, budget) - - if tc.wantPayload != "" { - if got != tc.wantPayload { - t.Errorf("CapPayload() = %q, want it returned unchanged", got) - } - return - } - for _, want := range tc.wantContain { - if !strings.Contains(got, want) { - t.Errorf("CapPayload() = %q, want it to contain %q", got, want) - } - } - if len(got) >= len(tc.payload) { - t.Errorf("CapPayload() returned %d bytes, want fewer than the %d-byte payload", len(got), len(tc.payload)) - } - }) - } -} - -// TestCapPayloadDoesNotChargeBudget pins the accounting boundary. -// -// CapPayload displaces an oversized result to disk; it must not also bill for -// it. Spill used to charge the FULL uncapped length while the caller charged -// the capped length on top, so a turn was billed for far more than it was ever -// shown and ran out of budget early. -func TestCapPayloadDoesNotChargeBudget(t *testing.T) { +func TestCapPayloadPerResultOnly(t *testing.T) { + payload := strings.Repeat("x", 500) tests := []struct { name string - spillDir bool + limit int + spillDir func(*testing.T) string + want string }{ - {name: "spilled to disk", spillDir: true}, - {name: "truncated inline", spillDir: false}, + {name: "disabled", limit: 0, want: payload}, + {name: "inline truncation", limit: 20, want: "result truncated"}, + {name: "spill", limit: 20, spillDir: func(t *testing.T) string { return t.TempDir() }, want: "result spilled"}, + {name: "failed spill falls back", limit: 20, spillDir: func(t *testing.T) string { + f, err := os.CreateTemp(t.TempDir(), "blocker") + if err != nil { + t.Fatal(err) + } + _ = f.Close() + return filepath.Join(f.Name(), "child") + }, want: "result truncated"}, } - for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { dir := "" - if tc.spillDir { - dir = t.TempDir() + if tc.spillDir != nil { + dir = tc.spillDir(t) } - budget := NewTurnBudget(1_000_000, dir) - - CapPayload("big", strings.Repeat("x", 5000), 100, budget) - - if used := budget.Used(); used != 0 { - t.Errorf("Used() = %d after CapPayload, want 0: accounting belongs to the caller", used) + got := CapPayload("read", payload, tc.limit, dir) + if tc.want == payload { + if got != payload { + t.Fatalf("got capped payload with disabled limit: %q", got) + } + return } - if budget.Exceeded() { - t.Error("budget reports exceeded after a single capped result") + if !strings.Contains(got, tc.want) || strings.Contains(got, strings.Repeat("x", 100)) { + t.Fatalf("CapPayload() = %q, want compact %q notice", got, tc.want) } }) } } -// TestSpillChargesBudget is the other half: the batch-dispatch path calls Spill -// directly and relies on it charging, so that behaviour must not drift. -func TestSpillChargesBudget(t *testing.T) { - budget := NewTurnBudget(1_000_000, t.TempDir()) - content := []byte(strings.Repeat("y", 300)) - - budget.Spill("tool", content) - - if used := budget.Used(); used != len(content) { - t.Errorf("Used() = %d, want %d", used, len(content)) +func TestCapPayloadNeverSplitsUTF8(t *testing.T) { + payload := strings.Repeat("Γ©", 100) + for limit := 1; limit <= 20; limit++ { + if got := CapPayload("read", payload, limit, ""); !utf8.ValidString(got) { + t.Errorf("limit=%d returned invalid UTF-8: %q", limit, got) + } } } -// TestWriteSpillUniquePaths guards a collision the previous naming scheme hid: -// the file name was derived from the budget's consumed count, so two spills -// that did not change it would overwrite each other. -func TestWriteSpillUniquePaths(t *testing.T) { - budget := NewTurnBudget(1_000_000, t.TempDir()) - - first := budget.WriteSpill("tool", []byte("first")) - second := budget.WriteSpill("tool", []byte("second")) - - if first.Path == "" || second.Path == "" { - t.Fatalf("spill paths empty: %q %q", first.Path, second.Path) +func TestCapPayloadSpillIsPrivateAndUnique(t *testing.T) { + dir := t.TempDir() + first := CapPayload("../../read", strings.Repeat("a", 100), 10, dir) + second := CapPayload("../../read", strings.Repeat("b", 100), 10, dir) + entries, err := os.ReadDir(dir) + if err != nil || len(entries) != 2 { + t.Fatalf("spill entries = %v, err = %v", entries, err) } - if first.Path == second.Path { - t.Fatalf("both spills wrote to %q; the second overwrote the first", first.Path) + if entries[0].Name() == entries[1].Name() { + t.Fatal("spill paths collided") } - for _, want := range []struct { - ref SpillRef - body string - }{{first, "first"}, {second, "second"}} { - got, err := os.ReadFile(want.ref.Path) + for _, entry := range entries { + info, err := entry.Info() if err != nil { t.Fatal(err) } - if string(got) != want.body { - t.Errorf("%s holds %q, want %q", want.ref.Path, got, want.body) + if info.Mode().Perm() != 0o600 || strings.Contains(entry.Name(), "..") { + t.Fatalf("unsafe spill entry %q mode %o", entry.Name(), info.Mode().Perm()) } } -} - -// TestWriteSpillUniqueAcrossBudgets is the collision that matters in practice. -// A TurnBudget is minted per chat turn and per agent stage while every one of -// them shares a single spill directory, so a name derived from within-budget -// state restarts each turn and the second turn silently overwrites the first -- -// leaving one session holding a reference to another session's output. -func TestWriteSpillUniqueAcrossBudgets(t *testing.T) { - dir := t.TempDir() - - firstTurn := NewTurnBudget(1_000_000, dir) - secondTurn := NewTurnBudget(1_000_000, dir) - - a := firstTurn.WriteSpill("read", []byte("first turn output")) - b := secondTurn.WriteSpill("read", []byte("second turn output")) - - if a.Path == "" || b.Path == "" { - t.Fatalf("spill paths empty: %q %q", a.Path, b.Path) - } - if a.Path == b.Path { - t.Fatalf("both turns wrote to %q", a.Path) - } - got, err := os.ReadFile(a.Path) - if err != nil { - t.Fatal(err) - } - if string(got) != "first turn output" { - t.Errorf("first turn's spill holds %q; a later turn overwrote it", got) - } -} - -// TestWriteSpillFilePermissions checks the mode on the first place archie -// persists verbatim tool output. It can hold anything the tools could read -- -// file contents, shell stdout, MCP responses -- so it must not be world- or -// group-readable. -func TestWriteSpillFilePermissions(t *testing.T) { - budget := NewTurnBudget(1_000_000, t.TempDir()) - - ref := budget.WriteSpill("shell", []byte("secret output")) - if ref.Path == "" { - t.Fatal("spill was not written") - } - info, err := os.Stat(ref.Path) - if err != nil { - t.Fatal(err) - } - if perm := info.Mode().Perm(); perm != 0o600 { - t.Errorf("spill file mode = %04o, want 0600", perm) - } -} - -// TestWriteSpillSanitisesToolName covers a name reaching the filesystem. MCP -// tool names come from a third-party server, so a name carrying path -// separators is reachable input rather than a hypothetical. -func TestWriteSpillSanitisesToolName(t *testing.T) { - dir := t.TempDir() - budget := NewTurnBudget(1_000_000, dir) - - ref := budget.WriteSpill("../../etc/passwd", []byte("payload")) - if ref.Path == "" { - t.Fatal("spill was not written") - } - if filepath.Dir(ref.Path) != dir { - t.Errorf("spill escaped to %q, want it inside %q", ref.Path, dir) - } -} - -// TestCapPayloadKeepsRunesIntact guards the truncation boundary: cutting a -// multi-byte rune in half hands the model invalid UTF-8, which some providers -// reject outright and others render as a replacement character mid-word. -func TestCapPayloadKeepsRunesIntact(t *testing.T) { - payload := strings.Repeat("Γ©", 100) // 2 bytes per rune - - for limit := 1; limit <= 20; limit++ { - got := CapPayload("read", payload, limit, nil) - if !utf8.ValidString(got) { - t.Errorf("limit=%d: CapPayload() returned invalid UTF-8: %q", limit, got) - } - } -} - -func TestTurnBudgetSpillDirPermissions(t *testing.T) { - // Create a regular file and use a sub-path as the spill directory. - // Even root cannot write a file when a path component is a regular - // file, making this test reliable regardless of privileges. - f, err := os.CreateTemp(t.TempDir(), "archie-test-spill-blocker") - if err != nil { - t.Fatal(err) - } - f.Close() - defer os.Remove(f.Name()) - - // spillDir is a sub-path of the regular file β€” WriteFile must fail. - spillDir := filepath.Join(f.Name(), "sub") - - b := NewTurnBudget(100_000, spillDir) - ref := b.Spill("tool", []byte("data")) - - // Spill should handle write failure gracefully. - if ref.Path != "" { - t.Errorf("spill path should be empty on write failure, got %q", ref.Path) - } - if ref.SizeChars != 4 { - t.Errorf("SizeChars should still be recorded: got %d", ref.SizeChars) + if !strings.Contains(first, dir) || !strings.Contains(second, dir) { + t.Fatalf("spill references do not name their paths: %q / %q", first, second) } } diff --git a/internal/tools/builtin/find.go b/internal/tools/builtin/find.go index 0850d8c37..d6a56d978 100644 --- a/internal/tools/builtin/find.go +++ b/internal/tools/builtin/find.go @@ -4,6 +4,8 @@ // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an // internal/tools package holding the registry these are registered into). +// - discovery is confined to the active workspace. Module-cache and other +// absolute paths are rejected so find cannot list home or pkg/mod trees. // // Refresh by diffing against that path at a newer tau commit. Do not // edit without recording the change above. @@ -40,7 +42,7 @@ var findSchema = Schema{ "properties": { "path": { "type": "string", - "description": "Directory to search in. Defaults to current directory." + "description": "Directory to search in. Defaults to the active workspace. Paths outside that workspace are rejected." }, "pattern": { "type": "string", @@ -87,8 +89,8 @@ func makeFindExecutor(cwd string) Executor { searchPath = resolvePath(cwd, p.Path) } - if !isReadConfined(cwd, searchPath) { - return Result{Content: "error: path escapes working directory", IsError: true}, nil + if !isConfined(cwd, searchPath) { + return Result{Content: "error: path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil } info, err := os.Stat(searchPath) diff --git a/internal/tools/builtin/grep.go b/internal/tools/builtin/grep.go index 1624b92c5..63e6033cb 100644 --- a/internal/tools/builtin/grep.go +++ b/internal/tools/builtin/grep.go @@ -8,6 +8,8 @@ // removed. They were 14MB of tracked binaries that were re-extracted to a // temporary directory on every run. grepBinary now resolves rg from PATH // and the existing pure-Go grepFallback covers its absence. +// - discovery is confined to the active workspace. Module-cache and other +// absolute paths are rejected so grep cannot search home or pkg/mod trees. // // Refresh by diffing against that path at a newer tau commit. Do not // edit without recording the change above. @@ -144,7 +146,7 @@ func makeGrepExecutor(cwd string, workspaceIndex GrepIndex) Executor { searchPath = resolvePath(cwd, p.Path) } - if !isReadConfined(cwd, searchPath) { + if !isConfined(cwd, searchPath) { return Result{Content: "error: path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil } diff --git a/internal/tools/builtin/pathutil.go b/internal/tools/builtin/pathutil.go index 3f9a3f832..2e7560ee5 100644 --- a/internal/tools/builtin/pathutil.go +++ b/internal/tools/builtin/pathutil.go @@ -64,12 +64,11 @@ var goModCacheDir = sync.OnceValue(func() string { return filepath.Join(home, "go", "pkg", "mod") }) -// isReadConfined reports whether a read-only tool may touch target. It permits -// the workspace plus the Go module cache: sandbox_escape on module-cache paths -// was the largest avoidable error class across analysed sessions, and every -// occurrence was a legitimate attempt to read dependency source. The cache is -// deliberately NOT extended to the mutating tools (edit, write), which stay -// confined to the workspace so the agent cannot corrupt shared dependencies. +// isReadConfined reports whether an explicit read may touch target. It permits +// the workspace plus the Go module cache so a known dependency file can be +// opened by path. Discovery tools (find, grep) use isConfined instead and stay +// inside the active project/worktree. The cache is deliberately NOT extended +// to the mutating tools (edit, write). func isReadConfined(base, target string) bool { if isConfined(base, target) { return true diff --git a/internal/tools/builtin/pathutil_test.go b/internal/tools/builtin/pathutil_test.go index a15f7b272..c0c22f0c0 100644 --- a/internal/tools/builtin/pathutil_test.go +++ b/internal/tools/builtin/pathutil_test.go @@ -99,7 +99,7 @@ func TestReadAllowsGoModCache(t *testing.T) { } } -func TestGrepAllowsGoModCache(t *testing.T) { +func TestGrepRejectsGoModCache(t *testing.T) { cwd := t.TempDir() cache := t.TempDir() withGoModCache(t, cache) @@ -115,11 +115,45 @@ func TestGrepAllowsGoModCache(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - if res.IsError { - t.Fatalf("expected grep of the module cache to succeed, got: %s", res.Content) + if !res.IsError || !strings.Contains(res.Content, "escapes working directory") { + t.Fatalf("expected grep of the module cache to be rejected, got: %#v", res) } - if !strings.Contains(res.Content, "Needle") { - t.Fatalf("unexpected content: %s", res.Content) +} + +func TestFindRejectsOutsideWorkspace(t *testing.T) { + cwd := t.TempDir() + cache := t.TempDir() + other := t.TempDir() + withGoModCache(t, cache) + + if err := os.MkdirAll(filepath.Join(cache, "example.com", "dep@v1.0.0"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(other, "main.go"), []byte("package main\n"), 0o644); err != nil { + t.Fatal(err) + } + + tool := NewFindTool(cwd) + for _, path := range []string{cache, other, "/home/sam"} { + res, err := tool.Execute(context.Background(), json.RawMessage(`{"path":`+quote(path)+`}`), nil) + if err != nil { + t.Fatalf("path %s: unexpected error: %v", path, err) + } + if !res.IsError || !strings.Contains(res.Content, "escapes working directory") { + t.Fatalf("path %s: expected workspace-confined find, got: %#v", path, res) + } + } + + inside := filepath.Join(cwd, "keep.go") + if err := os.WriteFile(inside, []byte("package keep\n"), 0o644); err != nil { + t.Fatal(err) + } + res, err := tool.Execute(context.Background(), json.RawMessage(`{"pattern":"keep.go"}`), nil) + if err != nil { + t.Fatal(err) + } + if res.IsError || !strings.Contains(res.Content, "keep.go") { + t.Fatalf("expected workspace find to succeed, got: %#v", res) } } diff --git a/internal/tools/classification.go b/internal/tools/classification.go index cf9d0098e..31d25a75d 100644 --- a/internal/tools/classification.go +++ b/internal/tools/classification.go @@ -3,8 +3,8 @@ package tools import "strings" // ToolClassification is a bitmask that describes a tool's behavioral -// characteristics for dispatch gating, guardrail decisions, and budget -// enforcement. +// characteristics for dispatch gating, guardrail decisions, and per-result +// limit enforcement. type ToolClassification int const ( diff --git a/internal/tools/dispatch.go b/internal/tools/dispatch.go index 0d7844e06..8f434195d 100644 --- a/internal/tools/dispatch.go +++ b/internal/tools/dispatch.go @@ -72,8 +72,7 @@ type DispatchResult struct { // inclusion in the conversation context. It is at most 500 chars. Preview string - // Error is the error returned by the handler, or a dispatch-level - // error (e.g. tool not found, budget exceeded). + // Error is the error returned by the handler or dispatch layer. Error error // Duration is the wall-clock time spent executing the tool @@ -153,16 +152,15 @@ func invokeTool(ctx context.Context, call ToolCall) DispatchResult { // previews and classifying errors. Each result includes a truncated // preview for inclusion in the conversation context. // -// If budget is non-nil, each result's output size is consumed from the -// budget. When the budget is exceeded, remaining calls are skipped with -// a budget-exceeded error. +// spillDir controls displacement of individual oversized results. Aggregate +// output volume never stops dispatch. // // If guardrail is non-nil, failures are recorded and the dispatch may // abort early on a hard-stop decision. func DispatchSequential( ctx context.Context, calls []ToolCall, - budget *TurnBudget, + spillDir string, guardrail *GuardrailEngine, ) []DispatchResult { results := make([]DispatchResult, 0, len(calls)) @@ -177,18 +175,7 @@ func DispatchSequential( break } - // Check budget before dispatching. Once exceeded, skip all - // remaining calls (break, not continue -- no point appending - // redundant budget-exceeded errors for every remaining call). - if budget != nil && budget.Exceeded() { - results = append(results, DispatchResult{ - ToolName: call.Entry.Name, - Error: fmt.Errorf("turn budget exceeded (%d chars)", budget.MaxChars), - }) - break - } - - result := dispatchOne(ctx, call, budget, guardrail) + result := dispatchOne(ctx, call, spillDir, guardrail) results = append(results, result) // Abort on hard-stop. @@ -224,7 +211,7 @@ type gatedGroup struct { func DispatchConcurrent( ctx context.Context, calls []ToolCall, - budget *TurnBudget, + spillDir string, guardrail *GuardrailEngine, ) []DispatchResult { if len(calls) == 0 { @@ -243,12 +230,12 @@ func DispatchConcurrent( if group.class == ExecNeverParallel || len(group.calls) == 1 { // Run sequentially. for _, call := range group.calls { - results[resultIdx] = dispatchOne(ctx, call, budget, guardrail) + results[resultIdx] = dispatchOne(ctx, call, spillDir, guardrail) resultIdx++ } } else { // Run in parallel within group. - res := dispatchParallel(ctx, group.calls, budget, guardrail) + res := dispatchParallel(ctx, group.calls, spillDir, guardrail) for _, r := range res { results[resultIdx] = r resultIdx++ @@ -337,8 +324,7 @@ func firstParallelSafeIdx(groups []gatedGroup) (int, bool) { return 0, false } -// dispatchOne runs a single call with budget, guardrail, and per-tool -// limit checks. +// dispatchOne runs a single call with guardrail and per-tool limit checks. // // Callers that do not own the batch cannot use this: it caps // DispatchResult.Preview, whereas a caller handing the result straight to a @@ -347,17 +333,9 @@ func firstParallelSafeIdx(groups []gatedGroup) (int, bool) { func dispatchOne( ctx context.Context, call ToolCall, - budget *TurnBudget, + spillDir string, guardrail *GuardrailEngine, ) DispatchResult { - // Check budget. - if budget != nil && budget.Exceeded() { - return DispatchResult{ - ToolName: call.Entry.Name, - Error: fmt.Errorf("turn budget exceeded (%d chars)", budget.MaxChars), - } - } - if guardrail != nil && guardrail.HardStopped() { return DispatchResult{ ToolName: call.Entry.Name, @@ -368,7 +346,7 @@ func dispatchOne( result := invokeTool(ctx, call) // Enforce per-tool result size limit (17.4). - capped := enforcePerToolLimit(&result, call.Entry, budget) + enforcePerToolLimit(&result, call.Entry, spillDir) // Track guardrail. if guardrail != nil { @@ -379,28 +357,22 @@ func dispatchOne( } } - // Consume budget. - if budget != nil && !result.IsError() { - consumeBudgetForResult(&result, call.Entry, budget, capped) - } - return result } // enforcePerToolLimit replaces the preview when the result exceeds the tool's -// MaxResultSizeChars, spilling to disk when the budget offers a directory and +// MaxResultSizeChars, spilling to disk when a directory is configured and // truncating inline otherwise. [CapPayload] owns that rule; this only decides // whether it applies. // -// Returns whether the result was capped, so the budget accounting below does -// not spill the same output a second time. -func enforcePerToolLimit(result *DispatchResult, entry ToolEntry, budget *TurnBudget) bool { +// Returns whether the result was capped. +func enforcePerToolLimit(result *DispatchResult, entry ToolEntry, spillDir string) bool { if result.IsError() || entry.MaxResultSizeChars <= 0 || result.Output == nil { return false } fullOutput := fmt.Sprint(result.Output) - capped := CapPayload(entry.Name, fullOutput, entry.MaxResultSizeChars, budget) + capped := CapPayload(entry.Name, fullOutput, entry.MaxResultSizeChars, spillDir) if capped == fullOutput { return false } @@ -408,37 +380,12 @@ func enforcePerToolLimit(result *DispatchResult, entry ToolEntry, budget *TurnBu return true } -// consumeBudgetForResult accounts for the result against the turn budget. -// When the budget is exceeded during consumption, the full output is -// spilled to disk and the preview is replaced with a spill reference. -func consumeBudgetForResult(result *DispatchResult, entry ToolEntry, budget *TurnBudget, alreadyCapped bool) { - if budget == nil || result.IsError() { - return - } - - if budget.Consume(len(result.Preview)) { - return - } - - // Budget exhausted on this result. Spill the full output so it is - // displaced rather than lost -- unless the per-tool limit already did, - // in which case repeating it would write a second identical file and - // orphan the first, whose path the preview already names. - if alreadyCapped || result.Output == nil { - return - } - fullOutput := fmt.Sprint(result.Output) - if ref := budget.WriteSpill(entry.Name, []byte(fullOutput)); ref.Path != "" { - result.Preview = fmt.Sprintf("[spilled to %s, %d chars]", ref.Path, ref.SizeChars) - } -} - // dispatchParallel runs multiple calls concurrently and returns results // in the same order. func dispatchParallel( ctx context.Context, calls []ToolCall, - budget *TurnBudget, + spillDir string, guardrail *GuardrailEngine, ) []DispatchResult { results := make([]DispatchResult, len(calls)) @@ -448,7 +395,7 @@ func dispatchParallel( for i, call := range calls { go func(idx int, c ToolCall) { defer wg.Done() - results[idx] = dispatchOne(ctx, c, budget, guardrail) + results[idx] = dispatchOne(ctx, c, spillDir, guardrail) }(i, call) } diff --git a/internal/tools/dispatch_test.go b/internal/tools/dispatch_test.go index 04fcbac1a..598668655 100644 --- a/internal/tools/dispatch_test.go +++ b/internal/tools/dispatch_test.go @@ -117,7 +117,7 @@ func TestInvokeToolError(t *testing.T) { // --- Sequential dispatch --- func TestDispatchSequentialEmpty(t *testing.T) { - results := DispatchSequential(context.Background(), nil, nil, nil) + results := DispatchSequential(context.Background(), nil, "", nil) if len(results) != 0 { t.Errorf("expected 0 results, got %d", len(results)) } @@ -134,7 +134,7 @@ func TestDispatchSequentialBasic(t *testing.T) { {Entry: e, Input: map[string]any{"msg": "second"}}, } - results := DispatchSequential(context.Background(), calls, nil, nil) + results := DispatchSequential(context.Background(), calls, "", nil) if len(results) != 2 { t.Fatalf("expected 2 results, got %d", len(results)) @@ -149,7 +149,7 @@ func TestDispatchSequentialBasic(t *testing.T) { } } -func TestDispatchSequentialBudgetLimit(t *testing.T) { +func TestDispatchSequentialOutputVolumeDoesNotStop(t *testing.T) { e := ToolEntry{ Name: "big-echo", Handler: echoHandler, @@ -160,19 +160,16 @@ func TestDispatchSequentialBudgetLimit(t *testing.T) { {Entry: e, Input: map[string]any{"msg": strings.Repeat("y", 100)}}, } - budget := NewTurnBudget(50, "") // Very small budget. + spillDir := "" // Aggregate output volume never stops dispatch. - results := DispatchSequential(context.Background(), calls, budget, nil) + results := DispatchSequential(context.Background(), calls, spillDir, nil) - // First call should consume budget (preview > 50 chars). - // Second should be skipped. if len(results) != 2 { t.Fatalf("expected 2 results, got %d", len(results)) } - if budget.Exceeded() { - // Budget was exceeded -- second result should have an error. - if !results[1].IsError() { - t.Error("second result should be an error after budget exceeded") + for i, result := range results { + if result.IsError() { + t.Errorf("result %d failed after accumulated output: %v", i, result.Error) } } } @@ -196,7 +193,7 @@ func TestDispatchSequentialGuardrailHardStop(t *testing.T) { {Entry: e}, {Entry: e}, {Entry: e}, } - results := DispatchSequential(context.Background(), calls, nil, g) + results := DispatchSequential(context.Background(), calls, "", g) // First call: warn, second call: hard-stop β†’ abort. // Should stop before completing all 3. @@ -205,32 +202,10 @@ func TestDispatchSequentialGuardrailHardStop(t *testing.T) { } } -func TestDispatchSequentialSpillOnBudgetExceeded(t *testing.T) { - dir := t.TempDir() - budget := NewTurnBudget(10, dir) // Very small, with spill dir. - - e := ToolEntry{ - Name: "verbose", - Handler: echoHandler, - } - - calls := []ToolCall{ - {Entry: e, Input: map[string]any{"msg": strings.Repeat("a", 100)}}, - } - - results := DispatchSequential(context.Background(), calls, budget, nil) - - if len(results) != 1 { - t.Fatalf("expected 1 result, got %d", len(results)) - } - // Budget should be exceeded when preview is large enough. - _ = results -} - // --- Concurrent dispatch --- func TestDispatchConcurrentEmpty(t *testing.T) { - results := DispatchConcurrent(context.Background(), nil, nil, nil) + results := DispatchConcurrent(context.Background(), nil, "", nil) if len(results) != 0 { t.Errorf("expected 0 results, got %d", len(results)) } @@ -255,7 +230,7 @@ func TestDispatchConcurrentParallel(t *testing.T) { {Entry: makeTool("d")}, } - results := DispatchConcurrent(context.Background(), calls, nil, nil) + results := DispatchConcurrent(context.Background(), calls, "", nil) if len(results) != 4 { t.Fatalf("expected 4 results, got %d", len(results)) @@ -299,7 +274,7 @@ func TestDispatchConcurrentNeverParallelIsolated(t *testing.T) { {Entry: makeMutating("m2")}, } - results := DispatchConcurrent(context.Background(), calls, nil, nil) + results := DispatchConcurrent(context.Background(), calls, "", nil) if len(results) != 2 { t.Fatalf("expected 2 results, got %d", len(results)) @@ -338,7 +313,7 @@ func TestDispatchConcurrentPathScoped(t *testing.T) { {Entry: makePathScoped("b", "path-2")}, // Different path β†’ can run concurrently with "a". } - results := DispatchConcurrent(context.Background(), calls, nil, nil) + results := DispatchConcurrent(context.Background(), calls, "", nil) if len(results) != 2 { t.Fatalf("expected 2 results, got %d", len(results)) } @@ -423,7 +398,7 @@ func TestDispatchSequentialErrorCapture(t *testing.T) { }, } - results := DispatchSequential(context.Background(), []ToolCall{{Entry: e}}, nil, nil) + results := DispatchSequential(context.Background(), []ToolCall{{Entry: e}}, "", nil) if len(results) != 1 { t.Fatalf("expected 1 result, got %d", len(results)) } @@ -435,34 +410,10 @@ func TestDispatchSequentialErrorCapture(t *testing.T) { } } -func TestDispatchBudgetSpillFilePath(t *testing.T) { - dir := t.TempDir() - budget := NewTurnBudget(5, dir) - - e := ToolEntry{ - Name: "verbose", - Handler: echoHandler, - } - - results := DispatchSequential(context.Background(), []ToolCall{ - {Entry: e, Input: map[string]any{"msg": strings.Repeat("x", 200)}}, - }, budget, nil) - - if results[0].Preview != "" && strings.Contains(results[0].Preview, "[spilled") { - // Verify the spill file exists. - spilled := budget.Spilled() - if len(spilled) > 0 && spilled[0].Path != "" { - if _, err := os.Stat(spilled[0].Path); err != nil { - t.Errorf("spill file not found: %v", err) - } - } - } -} - func TestDispatchPerToolResultSizeLimit(t *testing.T) { // 17.4 -- Per-tool max_result_size_chars enforcement. dir := t.TempDir() - budget := NewTurnBudget(100_000, dir) + spillDir := dir e := ToolEntry{ Name: "big-output", @@ -472,7 +423,7 @@ func TestDispatchPerToolResultSizeLimit(t *testing.T) { results := DispatchSequential(context.Background(), []ToolCall{ {Entry: e, Input: map[string]any{"msg": strings.Repeat("x", 200)}}, - }, budget, nil) + }, spillDir, nil) if len(results) != 1 { t.Fatalf("expected 1 result, got %d", len(results)) @@ -492,7 +443,7 @@ func TestDispatchPerToolLimitNoSpillDir(t *testing.T) { results := DispatchSequential(context.Background(), []ToolCall{ {Entry: e, Input: map[string]any{"msg": strings.Repeat("x", 200)}}, - }, nil, nil) + }, "", nil) if len(results) != 1 { t.Fatalf("expected 1 result, got %d", len(results)) @@ -582,8 +533,8 @@ func TestBuildGatingGroupsIndexTracking(t *testing.T) { } func TestDispatchPerToolLimitSpillFailureFallback(t *testing.T) { - // Regression: when per-tool MaxResultSizeChars is set, budget is - // non-nil but the spill directory is unwritable, inline truncation + // Regression: when per-tool MaxResultSizeChars is set but the configured + // spill directory is unwritable, inline truncation // must still be applied. // // Before fix: the "spill failed" path had no fallback; the per-tool @@ -601,7 +552,6 @@ func TestDispatchPerToolLimitSpillFailureFallback(t *testing.T) { spillDir := filepath.Join(f.Name(), "sub") - budget := NewTurnBudget(100_000, spillDir) e := ToolEntry{ Name: "big-output", Handler: echoHandler, @@ -610,7 +560,7 @@ func TestDispatchPerToolLimitSpillFailureFallback(t *testing.T) { results := DispatchSequential(context.Background(), []ToolCall{ {Entry: e, Input: map[string]any{"msg": strings.Repeat("x", 500)}}, - }, budget, nil) + }, spillDir, nil) if len(results) != 1 { t.Fatalf("expected 1 result, got %d", len(results)) @@ -628,38 +578,33 @@ func TestDispatchPerToolLimitSpillFailureFallback(t *testing.T) { } } -func TestDispatchSequentialBudgetExceededBreaks(t *testing.T) { - // Regression: DispatchSequential used 'continue' when budget exceeded, - // appending redundant errors for every remaining call. After fix it - // uses 'break' β€” only one budget-exceeded error. - +func TestDispatchSequentialOutputVolumeNeverStopsCalls(t *testing.T) { e := ToolEntry{ Name: "echo", Handler: echoHandler, } - budget := NewTurnBudget(5, "") + spillDir := "" calls := []ToolCall{ {Entry: e, Input: map[string]any{"msg": "short"}}, {Entry: e, Input: map[string]any{"msg": "also-short"}}, {Entry: e, Input: map[string]any{"msg": "never-runs"}}, } - results := DispatchSequential(context.Background(), calls, budget, nil) + results := DispatchSequential(context.Background(), calls, spillDir, nil) - // Budget exceeded after first call (preview of "short" > 5 chars). - // Only 2 results: first call result + one budget-exceeded error. - // The third call must not produce a redundant error. - if len(results) > 2 { - t.Errorf("expected at most 2 results (first call + one budget-exceeded), got %d", len(results)) + if len(results) != len(calls) { + t.Errorf("output accumulation stopped dispatch: got %d results, want %d", len(results), len(calls)) + } + for i, result := range results { + if result.Error != nil { + t.Errorf("result %d failed after accumulated output: %v", i, result.Error) + } } } -func TestDispatchPerToolLimitNoBudgetTruncates(t *testing.T) { - // Regression: when budget is nil, per-tool limit must still - // enforce inline truncation. Before fix: the inline truncation - // was inside an 'else' branch and unreachable when budget != nil. - // Verify it works when budget IS nil. +func TestDispatchPerToolLimitWithoutSpillTruncates(t *testing.T) { + // A per-tool limit without a spill directory must truncate explicitly. e := ToolEntry{ Name: "verbose", @@ -669,13 +614,13 @@ func TestDispatchPerToolLimitNoBudgetTruncates(t *testing.T) { results := DispatchSequential(context.Background(), []ToolCall{ {Entry: e, Input: map[string]any{"msg": strings.Repeat("y", 300)}}, - }, nil, nil) + }, "", nil) if len(results) != 1 { t.Fatalf("expected 1 result, got %d", len(results)) } if !strings.Contains(results[0].Preview, "truncated") { - t.Errorf("expected truncation with nil budget, got: %s", results[0].Preview) + t.Errorf("expected truncation without spill directory, got: %s", results[0].Preview) } } @@ -689,7 +634,7 @@ func TestDispatchPerToolLimitWithinLimit(t *testing.T) { results := DispatchSequential(context.Background(), []ToolCall{ {Entry: e, Input: map[string]any{"msg": "short"}}, - }, nil, nil) + }, "", nil) if len(results) != 1 { t.Fatalf("expected 1 result, got %d", len(results)) diff --git a/internal/tools/provider/builtin/provider.go b/internal/tools/provider/builtin/provider.go index 66789d279..f80e2f4bb 100644 --- a/internal/tools/provider/builtin/provider.go +++ b/internal/tools/provider/builtin/provider.go @@ -198,7 +198,7 @@ func screen(name string, input map[string]any) error { return nil } -// classify tags each tool so the guardrail engine and budget enforcement +// classify tags each tool so the guardrail engine and result-limit enforcement // can reason about it. This is categorisation, not a jail: it describes // what a tool does and does not gate whether it may run. // diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 5b7f1107e..673811b00 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -267,7 +267,6 @@ type ProviderView struct { // BudgetsView mirrors config.Budgets, none of which is secret. type BudgetsView struct { MaxSteps int `json:"max_steps"` - MaxTokens int `json:"max_tokens"` WallClock string `json:"wall_clock"` GateMaxFailures int `json:"gate_max_failures"` } @@ -347,7 +346,6 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { Providers: providersView(cfg.Providers), Budgets: BudgetsView{ MaxSteps: cfg.Budgets.MaxSteps, - MaxTokens: cfg.Budgets.MaxTokens, WallClock: cfg.Budgets.WallClock.Std().String(), GateMaxFailures: cfg.Budgets.GateMaxFailures, }, diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index edbf5ef34..5693b5f98 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -7,7 +7,7 @@ stroke-dasharray="${c}" stroke-dashoffset="${c*(1-i/100)}" class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room β€” what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`Γ—`)))))}function I(e,t){A(u,e,t)}function L(e){j(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function D(t,n){let r=O(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`β€”`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function O(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function k(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function A(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),y({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function j(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),b([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function M(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function N(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var P=new Set([`waiting_human`,`parked`]),F=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function I(e){let t=e?.get?.(`status`)||``;return F.has(t)?t:``}function L(e,t){return t?t===`needs_you`?P.has(e.status):e.status===t:!0}var R={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function z(e){return R[e]||e||`Unknown`}function B(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=I(t),f=``,p=Number(t.get(`task`)),h=Number.isFinite(p)&&p>0?p:null,g=h!==null,v=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(R).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,v]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),h&&u.some(e=>String(e.id)===String(h))&&W(h),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,_({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),_({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>L(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),h===e.id&&l.append(H(e));k()}function k(){!g||!h||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${h}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=h===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),h=h===t.id?null:t.id,O(),h===t.id&&W(t.id)};return e(`tr.task-row`,{...N(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`βˆ’`:`+`),B(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(z(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`β€”`),e(`td`,{"data-label":`Stage`},t.stage||`β€”`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`β€”`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await m.taskAction(e,t),x.delete(e),t===`archive`&&(h=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function P(e){return!v||!e.owner||!e.repo?null:`${v.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=P(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function B(t){let n=P(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=P(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting β€” retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await m.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function V(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var H={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function U(e){return H[e]?H[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function W(e,t){return t?Math.round(e/t*100):0}function G(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`β€”`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await m.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},U(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.wf-form`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await m.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=W(t.merged,t.runs);return e(`tr`,e(`td.strong`,U(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),G(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`β€”`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`β€”`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),G(W(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),G(W(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await m.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(e){return e==null||e===``?`β€”`:String(e)}function K(t,n,r){let i=ie(n),a=e(`span.kv-label`,t),o=e(`span.kv-value.mono${i===`β€”`?`.is-empty`:``}`,{title:i},i);if(!r?.key)return e(`div.kv`,a,o);let s=r.locked?.[r.key];if(s)return e(`div.kv.is-locked`,a,o,e(`span.kv-note`,s));let c=r.overridden?.includes(r.key),l=e(`button.kv-btn`,{type:`button`,title:`Edit ${t}`},`Edit`),u=c?e(`button.kv-btn`,{type:`button`,title:`Discard the dashboard value and fall back to the config file`},`Reset`):null,d=e(`div.kv-actions`,c&&e(`span.kv-flag`,{title:`Set from the dashboard; this shadows the value in the config file`},`overridden`),l,u),f=e(`div.kv`,a,o,d);return l.addEventListener(`click`,()=>se(f,t,r,[a,o,d])),u?.addEventListener(`click`,()=>ae(f,u,r)),f}function ae(e,t,n){let{key:r,onSaved:i}=n;t.disabled=!0,m.configReset(r).then(()=>i?.()).catch(n=>{t.disabled=!1,oe(e,String(n.message||n))})}function oe(t,n){let r=t.querySelector?.(`.kv-note`);r||(r=e(`span.kv-note.is-error`),t.appendChild(r)),r.classList.add(`is-error`),r.textContent=n}function se(t,r,i,a){let{key:o,type:s,raw:c,onSaved:l}=i,u=s===`bool`?e(`select.kv-input`,e(`option`,{value:`true`,selected:c===!0},`true`),e(`option`,{value:`false`,selected:c===!1},`false`)):e(`input.kv-input`,{type:`text`,value:String(c??``)}),d=e(`button.kv-save`,{type:`button`},`Save`),f=e(`button.kv-cancel`,{type:`button`},`Cancel`),p=e(`span.kv-note.is-error`);n(t,e(`span.kv-label`,r),u,e(`div.kv-actions`,d,f),p),u.focus?.(),u.select?.();let h=()=>n(t,...a);f.addEventListener(`click`,h),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault?.(),d.click()),e.key===`Escape`&&h()}),d.addEventListener(`click`,async()=>{let e=ce(s,u.value);if(e.error){p.textContent=e.error;return}d.disabled=!0;try{await m.configUpdate({[o]:e.value}),l?.()}catch(e){p.textContent=String(e.message||e),d.disabled=!1}})}function ce(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}var le={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},ue={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function de(t){return t.length?fe(`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Component`,`Install type`,`Running`,`Latest available`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,{title:[`Installed claim: ${t.installed_claim||`unknown`}`,`Running: ${t.running_version||`not observed`}`,t.reference?`Reference: ${t.reference}`:null].filter(Boolean).join(` -`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`β€”`),e(`td.mono`,t.running_version||`β€”`),e(`td.mono`,t.latest_available||`β€”`),e(`td`,r(le[t.status]||t.status,ue[t.status]||`idle`)))))))):fe(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function fe(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function pe(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await m.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await m.version();n(i,de(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,he(t.identity,a),ge(t.repositories),ve(t.models,t.providers),be(t.budgets,a),xe(t.agent,a),Ce(t.storage,t.containers,a),Te(t.web,a),me(t.provenance))}return t}function me(t){return t?.length?q(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>K(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):q(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function q(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function he(t,n){return t?q(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,K(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),K(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),K(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),K(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),K(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),K(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):q(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ge(t){return t?.length?q(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,_e(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`β€”`))))))):q(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function _e(e){return e?.length?e.map(e=>e.join(` `)).join(` β†’ `):`β€”`}function ve(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>K(ye(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`β€”`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return q(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ye(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function be(t,n){return t?q(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,K(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),K(`Max tokens`,t.max_tokens||`Unlimited`,{key:`budgets.max_tokens`,type:`int`,raw:t.max_tokens,...n}),K(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),K(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):q(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function xe(t,n){return t?q(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.kv-list`,K(`Execution mode`,Se(t.mode),{key:`agent.mode`,type:`string`,raw:t.mode,...n}),K(`Worker command`,t.command,{key:`agent.command`,type:`string`,raw:t.command,...n}),K(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):q(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function Se(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function Ce(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,K(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),K(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),K(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),K(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),K(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,K(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),K(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),K(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),K(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),K(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),K(`How images are refreshed`,we(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),K(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),q(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function we(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function Te(t,n){return t?q(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,K(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):q(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var Ee=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function De(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Oe(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...Ee.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Pe(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(Ne(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(ke(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(ke(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Ae)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function ke(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Ae(t){let n=t.fields||{};return e(`div.log-row.log-${De(t.level)}`,e(`span.log-time.mono`,Me(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(je(n))))))}function je(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Me(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function Ne(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Pe(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Fe(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`β€”`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Ie(t)]:[o]}function Ie(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),Le(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),Le(t.headers)))))}function Le(t){return t?e(`pre.capture-payload`,Re(t)):e(`div.capture-empty`,`(empty)`)}function Re(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function ze(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=h(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await m.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}g()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),g()}function g(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>Fe(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,g()}}))))))}return t}var Be=[`string`,`number`,`bool`,`object`,`array`,`any`];function Ve(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function He(e,t){return e?`${e}.${t}`:t}function Ue(e,t){return`${e}[${t}]`}function We(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,Ue(n,t)]):Object.entries(t).map(([e,t])=>[e,t,He(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:Ve(n),name:t})}},t),We(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:Ve(t),name:r})}},JSON.stringify(t))}function Ge(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...Be.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,Ke(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function Ke(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function qe(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`β€”`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function Je(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([m.mappings(),m.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await m.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function h(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await m.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await m.mappingUpdate(o.id,e):await m.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>qe(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`β€” pick a captured event β€”`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} β€” ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),Ge(o.fields,{preview:o.preview,onRemove:h,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload β€” click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):We(o.payload,{onPick:p})))}return t}function Ye(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Xe)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Xe(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ze(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now β€” a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ze(e){return e===`external`?`Added by you β€” an external store Archie was given`:`Built in β€” always available to Archie`}var Qe=`
+`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`β€”`),e(`td.mono`,t.running_version||`β€”`),e(`td.mono`,t.latest_available||`β€”`),e(`td`,r(le[t.status]||t.status,ue[t.status]||`idle`)))))))):fe(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function fe(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function pe(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await m.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await m.version();n(i,de(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,he(t.identity,a),ge(t.repositories),ve(t.models,t.providers),be(t.budgets,a),xe(t.agent,a),Ce(t.storage,t.containers,a),Te(t.web,a),me(t.provenance))}return t}function me(t){return t?.length?q(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>K(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):q(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function q(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function he(t,n){return t?q(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,K(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),K(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),K(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),K(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),K(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),K(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):q(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ge(t){return t?.length?q(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,_e(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`β€”`))))))):q(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function _e(e){return e?.length?e.map(e=>e.join(` `)).join(` β†’ `):`β€”`}function ve(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>K(ye(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`β€”`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return q(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ye(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function be(t,n){return t?q(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,K(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),K(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),K(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):q(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function xe(t,n){return t?q(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.kv-list`,K(`Execution mode`,Se(t.mode),{key:`agent.mode`,type:`string`,raw:t.mode,...n}),K(`Worker command`,t.command,{key:`agent.command`,type:`string`,raw:t.command,...n}),K(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):q(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function Se(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function Ce(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,K(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),K(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),K(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),K(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),K(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,K(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),K(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),K(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),K(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),K(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),K(`How images are refreshed`,we(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),K(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),q(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function we(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function Te(t,n){return t?q(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,K(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):q(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var Ee=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function De(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Oe(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...Ee.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Pe(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(Ne(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(ke(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(ke(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Ae)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function ke(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Ae(t){let n=t.fields||{};return e(`div.log-row.log-${De(t.level)}`,e(`span.log-time.mono`,Me(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(je(n))))))}function je(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Me(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function Ne(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Pe(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Fe(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`β€”`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Ie(t)]:[o]}function Ie(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),Le(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),Le(t.headers)))))}function Le(t){return t?e(`pre.capture-payload`,Re(t)):e(`div.capture-empty`,`(empty)`)}function Re(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function ze(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=h(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await m.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}g()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),g()}function g(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>Fe(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,g()}}))))))}return t}var Be=[`string`,`number`,`bool`,`object`,`array`,`any`];function Ve(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function He(e,t){return e?`${e}.${t}`:t}function Ue(e,t){return`${e}[${t}]`}function We(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,Ue(n,t)]):Object.entries(t).map(([e,t])=>[e,t,He(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:Ve(n),name:t})}},t),We(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:Ve(t),name:r})}},JSON.stringify(t))}function Ge(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...Be.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,Ke(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function Ke(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function qe(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`β€”`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function Je(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([m.mappings(),m.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await m.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function h(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await m.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await m.mappingUpdate(o.id,e):await m.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>qe(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`β€” pick a captured event β€”`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} β€” ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),Ge(o.fields,{preview:o.preview,onRemove:h,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload β€” click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):We(o.payload,{onPick:p})))}return t}function Ye(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Xe)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Xe(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ze(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now β€” a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ze(e){return e===`external`?`Added by you β€” an external store Archie was given`:`Built in β€” always available to Archie`}var Qe=`
ARCHIE WORKSPACE

Chat

diff --git a/ui/src/settings/settings.js b/ui/src/settings/settings.js index 895de73b2..7c66d1f32 100644 --- a/ui/src/settings/settings.js +++ b/ui/src/settings/settings.js @@ -241,7 +241,6 @@ function budgetsCard(budgets, ctx) { el( "div.kv-list", row("Max steps", budgets.max_steps || "Unlimited", { key: "budgets.max_steps", type: "int", raw: budgets.max_steps, ...ctx }), - row("Max tokens", budgets.max_tokens || "Unlimited", { key: "budgets.max_tokens", type: "int", raw: budgets.max_tokens, ...ctx }), row("Wall clock", budgets.wall_clock, { key: "budgets.wall_clock", type: "string", raw: budgets.wall_clock, ...ctx }), row("Max gate failures before parking", budgets.gate_max_failures || "Unlimited", { key: "budgets.gate_max_failures", type: "int", raw: budgets.gate_max_failures, ...ctx }), ),