From a502c394673bda1c67b980a52baa5ed439b5a077 Mon Sep 17 00:00:00 2001 From: Denys Vasyliev Date: Mon, 30 Nov 2026 20:34:18 +0000 Subject: [PATCH] fix(agent): a turn past its cap still sends the answer to an open request --- docs/spec.md | 4 +-- internal/agent/agent.go | 51 ++++++++++++++++----------- internal/agent/agent_test.go | 67 ++++++++++++++++++++++++++++++++++++ internal/agent/loop.go | 40 +++++++++++++++++---- internal/tools/tools.go | 32 +++++++++++++++-- internal/tools/tools_test.go | 54 +++++++++++++++++++++++++++++ 6 files changed, 216 insertions(+), 32 deletions(-) diff --git a/docs/spec.md b/docs/spec.md index 84b6b11..9d54cd3 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -46,8 +46,8 @@ A **wake** is why the supervisor starts a **turn**. Every wake is an empty conve | Limit or failure | Rule | |---|---| | 40 requests | `--max-steps`. Not a failure: `stepsExhausted`. | -| 150k tokens | `--max-turn-tokens`. The billable tokens of a wake (input without cache reads, output, cache writes). Checked after each step; past it a tool call is answered with an error and not run and the model is told to wrap up, as at the tool-call cap. `0` turns it off. Not a failure. | -| 20 tool calls | `--max-tool-calls`. Past it a call is answered with an error and not run, and the model is told to answer from what it has, call `schedule_next` and `finish`, which are never refused. A model that goes on calling tools ends the turn. Not a failure. | +| 150k tokens | `--max-turn-tokens`. The billable tokens of a wake (input without cache reads, output, cache writes). Checked after each step; past it a tool call is answered with an error and not run and the model is told to wrap up, as at the tool-call cap. `0` turns it off. One call still goes past either cap: an answer to a request, `say_in_workspace` with `reply_to`, once, and once more when it did not go; the post gate and the recall gate let that answer through, since the calls that open them are refused. Not a failure. | +| 20 tool calls | `--max-tool-calls`. Past it a call is answered with an error and not run, and the model is told to answer from what it has, call `schedule_next` and `finish`, which are never refused. A model that goes on calling tools ends the turn. One call still goes past either cap: an answer to a request, `say_in_workspace` with `reply_to`, once, and once more when it did not go; the post gate and the recall gate let that answer through, since the calls that open them are refused. Not a failure. | | 20m | `--turn-timeout`. Failed; reported as cut off on the next wake. | | SIGTERM | Cancels the turn, counts the tokens seen, marks it cut off, flushes the spans, writes `status.json`, exits. | | failure | An API error after the SDK’s two retries, a refusal, an answer cut at the output cap twice, a timeout, no core tools. The next wake backs off from `--min-wake`, doubling to `--max-wake`; edges wait too. A 401 or 403 sets `authFailed`. A failing tool is not a failed turn. | diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 7802231..50c7cb3 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -61,6 +61,10 @@ type Turn struct { // Result is what a turn did. type Result struct { + // answerTries and answered track the answer sent past a cap (mayAnswer). + answerTries int + answered bool + // Text is the final assistant text, for logs; nobody reads it. Text string // Summary is what the model passed to finish. @@ -200,12 +204,15 @@ func FirstMessage(prompt string, down []string, c Caps) string { } // toolLimitText is the result of a tool call refused at the cap. -const toolLimitText = "not run: this turn has used its %d tool calls. Do not call more tools. " + - "Answer from what you have, say what is still open, then call schedule_next and finish." +const toolLimitText = "not run: this turn has used its %d tool calls. " + wrapUpText // tokenLimitText is the result of a tool call refused at the token cap. -const tokenLimitText = "not run: this turn has used its token budget (%d tokens, every step sends the whole conversation again). " + - "Do not call more tools. Answer from what you have, say what is still open, then call schedule_next and finish." +const tokenLimitText = "not run: this turn has used its token budget (%d tokens, every step sends the whole conversation again). " + wrapUpText + +// wrapUpText says what a turn past a cap can still do (mayAnswer). +const wrapUpText = "Do not call more tools, with one exception: your answer to an open request still goes, " + + "with say_in_workspace, room \"bus\" and reply_to the request id. Send it now from what you have, " + + "say what is still open, then call schedule_next and finish." // Agent runs turns, one at a time. type Agent struct { @@ -356,6 +363,19 @@ func (a *Agent) Run(ctx context.Context, t Turn) (res Result) { } first := FirstMessage(t.Prompt, a.o.Tools.Down(), Caps{MaxSteps: a.o.MaxSteps, MaxToolCalls: a.o.MaxToolCalls, MaxTurnTokens: a.o.MaxTurnTokens}) + call := func(callCtx context.Context, c llm.Block) (string, bool) { + span := root.Tool(c.Name, c.ID, c.Input) + began := time.Now() + content, isErr := a.o.Tools.Call(callCtx, c.Name, c.Input) + span.End(content, isErr) + tr.add("tool", c.Name, began, 0) + attrs := []any{"tool", c.Name, "ms", time.Since(began).Milliseconds(), "error", isErr} + if a.o.LogContent { + attrs = append(attrs, "input", clip(string(c.Input), 600)) + } + log.Debug("tool call", attrs...) + return content, isErr + } steps := Steps{ Complete: func(req llm.Request) (llm.Response, error) { chat := root.Chat(a.o.Model, req) @@ -369,23 +389,12 @@ func (a *Agent) Run(ctx context.Context, t Turn) (res Result) { tr.add("model", name, began, resp.Usage.Billable()) return resp, err }, - Call: func(c llm.Block) (string, bool) { - span := root.Tool(c.Name, c.ID, c.Input) - began := time.Now() - content, isErr := a.o.Tools.Call(ctx, c.Name, c.Input) - span.End(content, isErr) - tr.add("tool", c.Name, began, 0) - attrs := []any{"tool", c.Name, "ms", time.Since(began).Milliseconds(), "error", isErr} - if a.o.LogContent { - attrs = append(attrs, "input", clip(string(c.Input), 600)) - } - log.Debug("tool call", attrs...) - return content, isErr - }, - Finished: func() bool { _, done := a.o.Tools.Finished(); return done }, - Stopped: ctx.Err, - IsStop: func(err error) bool { return isCtxErr(ctx, err) }, - Take: a.take, FinishOrTake: a.finishOrTake, + Call: func(c llm.Block) (string, bool) { return call(ctx, c) }, + CallPastCap: func(c llm.Block) (string, bool) { return call(tools.PastCap(ctx), c) }, + Finished: func() bool { _, done := a.o.Tools.Finished(); return done }, + Stopped: ctx.Err, + IsStop: func(err error) bool { return isCtxErr(ctx, err) }, + Take: a.take, FinishOrTake: a.finishOrTake, } if a.o.LogContent { steps.Text = func(step int, text string) { log.Debug("model text", "step", step, "text", clip(text, 600)) } diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index da91a17..92ac61f 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "slices" "strings" "sync" "testing" @@ -434,6 +435,72 @@ func TestAModelThatKeepsCallingToolsAfterTheTokenCapEndsTheTurn(t *testing.T) { } } +// A turn past its token cap still sends the answer to an open request: the +// work is done, and without this nobody is told until another turn. +func TestPastTheTokenCapTheAnswerToARequestStillGoes(t *testing.T) { + ft := newFakeTools() + ft.results["core__say_in_workspace"] = "posted" + read := llm.Call{Name: "core__list_open_issues"} + answer := llm.Call{Name: "core__say_in_workspace", Input: `{"room":"bus","reply_to":"$ask","body":"found"}`} + f := llm.NewFake( + llm.ToolUse(u, read), // 160 billed: under the cap of 100 only before this step + llm.ToolUse(u, answer, llm.Call{Name: "finish", Input: `{"summary":"answered"}`}), + llm.EndTurn("never", u)) + res := newAgent(f, ft, func(o *Options) { o.MaxTurnTokens = 100 }).Run(context.Background(), Turn{Prompt: "p"}) + if res.Failed || res.TokenLimit || res.Summary != "answered" { + t.Fatalf("result %+v", res) + } + if !slices.Equal(ft.calls, []string{"core__say_in_workspace", "finish"}) { + t.Fatalf("the read is refused and the answer goes: %v", ft.calls) + } + if rs := f.Requests()[1].Messages[2].Content; !strings.Contains(rs[0].Content, "reply_to") { + t.Errorf("the model is not told its answer still goes: %q", rs[0].Content) + } +} + +func TestPastTheCapOneAnswerGoesAndNothingElse(t *testing.T) { + ft := newFakeTools() + ft.results["core__say_in_workspace"] = "posted" + read := llm.Call{Name: "core__list_open_issues"} + answer := llm.Call{Name: "core__say_in_workspace", Input: `{"reply_to":"$ask"}`} + other := llm.Call{Name: "core__say_in_workspace", Input: `{"body":"more news"}`} + f := llm.NewFake(llm.ToolUse(u, read), llm.ToolUse(u, other), llm.ToolUse(u, other), llm.EndTurn("never", u)) + res := newAgent(f, ft, func(o *Options) { o.MaxToolCalls = 1 }).Run(context.Background(), Turn{Prompt: "p"}) + // The post that answers nothing is refused and, asked for after the model + // was told, ends the turn. + if !res.ToolLimit || !slices.Equal(ft.calls, []string{"core__list_open_issues"}) { + t.Fatalf("calls %v result %+v", ft.calls, res) + } + + ft = newFakeTools() + ft.results["core__say_in_workspace"] = "posted" + f = llm.NewFake(llm.ToolUse(u, read), llm.ToolUse(u, answer), llm.ToolUse(u, answer), llm.EndTurn("never", u)) + res = newAgent(f, ft, func(o *Options) { o.MaxToolCalls = 1 }).Run(context.Background(), Turn{Prompt: "p"}) + if res.Failed || !slices.Equal(ft.calls, []string{"core__list_open_issues", "core__say_in_workspace"}) { + t.Fatalf("a second answer ran: calls %v result %+v", ft.calls, res) + } + if rs := f.Requests()[3].Messages[6].Content; !rs[0].IsError || !strings.Contains(rs[0].Content, "not run") { + t.Errorf("a second answer is refused: %+v", rs) + } +} + +func TestPastTheCapAnAnswerThatDidNotGoIsTriedOnceMore(t *testing.T) { + ft := newFakeTools() + ft.results["core__say_in_workspace"] = "!not sent: reply_to must be the id of the request" + read := llm.Call{Name: "core__list_open_issues"} + answer := llm.Call{Name: "core__say_in_workspace", Input: `{"reply_to":"$wrong"}`} + finish := llm.Call{Name: "finish", Input: `{"summary":"done"}`} + f := llm.NewFake(llm.ToolUse(u, read), llm.ToolUse(u, answer, finish), llm.ToolUse(u, answer, finish), llm.EndTurn("never", u)) + res := newAgent(f, ft, func(o *Options) { o.MaxToolCalls = 1 }).Run(context.Background(), Turn{Prompt: "p"}) + if res.Summary != "done" || res.Steps != 3 { + t.Fatalf("the turn must not end on the first answer that did not go: %+v", res) + } + want := []string{"core__list_open_issues", "core__say_in_workspace", "core__say_in_workspace", "finish"} + if !slices.Equal(ft.calls, want) { + t.Fatalf("calls %v", ft.calls) + } +} + func TestFinishAndScheduleAreNeverRefusedAtTheCap(t *testing.T) { ft := newFakeTools() call := llm.Call{Name: "core__list_open_issues"} diff --git a/internal/agent/loop.go b/internal/agent/loop.go index 1febaf9..b43a8ae 100644 --- a/internal/agent/loop.go +++ b/internal/agent/loop.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log/slog" + "slices" "github.com/triageagent-dev/spot/internal/llm" "github.com/triageagent-dev/spot/internal/tools" @@ -18,6 +19,9 @@ type Steps struct { Complete func(req llm.Request) (llm.Response, error) // Call runs one tool call. A tool failure is a result, never an error. Call func(c llm.Block) (content string, isError bool) + // CallPastCap runs the answer a turn may still send once a cap is spent + // (tools.PastCap). Nil: past a cap nothing but the spot's own tools runs. + CallPastCap func(c llm.Block) (content string, isError bool) // Finished reports whether the model has called finish. Finished func() bool // Stopped says why the turn must end now (shutdown, time is up), or nil. @@ -100,7 +104,7 @@ func RunLoop(s Steps, c Caps, rq Request, first string, log *slog.Logger) (res R } continue } - if told && !onlyBuiltins(calls) { + if told && !onlyBuiltins(calls) && !hasAnswer(s, &res, calls) { // The model was told the cap was reached and still asks for tools. res.ToolLimit = true res.TokenLimit = res.ToolCalls < c.MaxToolCalls && overTokens(c, &res) @@ -207,11 +211,20 @@ func runTools(s Steps, c Caps, calls []llm.Block, res *Result) (out []llm.Block, continue } if text := limitText(c, res); text != "" && !tools.IsBuiltin(call.Name) { - refused = true - out[i] = llm.ToolResult(call.ID, text, true) + if !mayAnswer(s, res, call) { + refused = true + out[i] = llm.ToolResult(call.ID, text, true) + continue + } + res.answerTries++ + content, isErr := callTool(s.CallPastCap, call, res) + res.answered = !isErr + // With a try left, the turn does not end on an answer that did not go. + held = held || (isErr && res.answerTries < maxAnswerTries) + out[i] = llm.ToolResult(call.ID, content, isErr) continue } - content, isErr := callTool(s, call, res) + content, isErr := callTool(s.Call, call, res) held = held || (isErr && tools.Held(content)) out[i] = llm.ToolResult(call.ID, content, isErr) } @@ -223,7 +236,7 @@ func runTools(s Steps, c Caps, calls []llm.Block, res *Result) (out []llm.Block, out[i] = llm.ToolResult(call.ID, finishHeldText, true) continue } - content, isErr := callTool(s, call, res) + content, isErr := callTool(s.Call, call, res) out[i] = llm.ToolResult(call.ID, content, isErr) } return out, refused @@ -235,16 +248,29 @@ const finishHeldText = "not finished: a call in this step did not run (see its r "or, if you will not do it, say so plainly in your summary; do not report as done what did not run. Then call finish." // callTool runs one tool call of the model and counts it. -func callTool(s Steps, c llm.Block, res *Result) (content string, isErr bool) { +func callTool(run func(llm.Block) (string, bool), c llm.Block, res *Result) (content string, isErr bool) { if !json.Valid(c.Input) { content, isErr = "the tool input was not valid JSON", true } else { - content, isErr = s.Call(c) + content, isErr = run(c) } res.ToolCalls++ return content, isErr } +// maxAnswerTries is how often a turn past a cap may try to send its answer: +// once, and once more when that did not go, as for a wrong reply_to. +const maxAnswerTries = 2 + +// mayAnswer reports whether call is the answer a turn past a cap may still send. +func mayAnswer(s Steps, res *Result, call llm.Block) bool { + return s.CallPastCap != nil && !res.answered && res.answerTries < maxAnswerTries && tools.IsAnswer(call.Name, call.Input) +} + +func hasAnswer(s Steps, res *Result, calls []llm.Block) bool { + return slices.ContainsFunc(calls, func(c llm.Block) bool { return mayAnswer(s, res, c) }) +} + // overTokens reports whether the turn has spent its token cap. func overTokens(c Caps, res *Result) bool { return c.MaxTurnTokens > 0 && res.Usage.Billable() >= c.MaxTurnTokens diff --git a/internal/tools/tools.go b/internal/tools/tools.go index cc37127..9d25fc3 100644 --- a/internal/tools/tools.go +++ b/internal/tools/tools.go @@ -427,9 +427,11 @@ func (r *Registry) Call(ctx context.Context, name string, input json.RawMessage) r.mu.Lock() rt, ok := r.routes[name] s := r.sessions[rt.server] - held := ok && r.heldForRecall(rt) + past, _ := ctx.Value(pastCapKey{}).(bool) + past = past && rt.server == CoreServer && rt.tool == sayInWorkspace + held := ok && !past && r.heldForRecall(rt) gate := "" - if ok && !held { + if ok && !held && !past { gate = r.heldForPost(rt) } r.mu.Unlock() @@ -605,6 +607,32 @@ func inList(list []string, name string) bool { return false } +type pastCapKey struct{} + +// PastCap marks the context of the answer a turn may still send once a cap of +// the turn is spent. The gates that wait for a read or a note let that answer +// through, since the calls that would open them are refused by then. The check +// of what it replies to still applies. +func PastCap(ctx context.Context) context.Context { + return context.WithValue(ctx, pastCapKey{}, true) +} + +// IsAnswer reports whether a call answers a request in the spot's bus: +// say_in_workspace with the id it replies to, with or without a prefix the +// model added. +func IsAnswer(name string, input json.RawMessage) bool { + if i := strings.LastIndexAny(name, ":."); i >= 0 && i < len(name)-1 { + name = name[i+1:] + } + if name != sayInWorkspace && name != CoreServer+Sep+sayInWorkspace { + return false + } + var m struct { + ReplyTo string `json:"reply_to"` + } + return json.Unmarshal(input, &m) == nil && m.ReplyTo != "" +} + // IsFinish reports whether name is the spot's finish tool, with or without a // prefix the model added. func IsFinish(name string) bool { diff --git a/internal/tools/tools_test.go b/internal/tools/tools_test.go index e748dc8..8012ebd 100644 --- a/internal/tools/tools_test.go +++ b/internal/tools/tools_test.go @@ -581,6 +581,60 @@ func TestNothingIsPostedBeforeTheMemoryIsReadAndANoteWritten(t *testing.T) { } } +// The answer a turn sends past a cap does not wait for a read or a note, which +// are refused by then. What it replies to is still checked, and nothing else +// gets through. +func TestTheAnswerPastACapDoesNotWaitForTheGates(t *testing.T) { + url, _ := fakeServer(t) + r := newRegistry(t, url, func(o *Options) { + o.PostGate, o.RecallFirst = true, true + o.ReplyCheck = func(replyTo string) string { + if replyTo == "$wrong" { + return "not sent: wrong request" + } + return "" + } + o.Core.Allow = []string{"say_in_workspace", "comment_on_issue", "search_memory", "get_memory_context", "upsert_memory_item"} + }) + r.Begin() + if _, err := r.List(context.Background()); err != nil { + t.Fatal(err) + } + answer := json.RawMessage(`{"reply_to":"$ask","body":"found"}`) + if c, isErr := r.Call(context.Background(), "core__say_in_workspace", answer); !isErr { + t.Errorf("within the caps the gates hold: %q", c) + } + past := PastCap(context.Background()) + if c, isErr := r.Call(past, "core__say_in_workspace", json.RawMessage(`{"reply_to":"$wrong"}`)); !isErr || !strings.Contains(c, "wrong request") { + t.Errorf("the reply check: %q %v", c, isErr) + } + if c, isErr := r.Call(past, "core__say_in_workspace", answer); isErr || c != "say_in_workspace" { + t.Errorf("the answer past a cap: %q %v", c, isErr) + } + if c, isErr := r.Call(past, "core__comment_on_issue", nil); !isErr { + t.Errorf("only the answer is let through: %q", c) + } +} + +func TestIsAnswer(t *testing.T) { + reply := json.RawMessage(`{"reply_to":"$ask"}`) + for _, name := range []string{"core__say_in_workspace", "say_in_workspace", "default_api:core__say_in_workspace"} { + if !IsAnswer(name, reply) { + t.Errorf("%q with reply_to is an answer", name) + } + } + for name, in := range map[string]json.RawMessage{ + "core__say_in_workspace": json.RawMessage(`{"body":"news"}`), + "core__comment_on_issue": reply, + "kube__say_in_workspace": reply, + "say_in_workspace": json.RawMessage(`not json`), + } { + if IsAnswer(name, in) { + t.Errorf("%q %s is no answer", name, in) + } + } +} + func TestASearchOfTheNotesIsTheReadThePostGateWants(t *testing.T) { url, _ := fakeServer(t) r := newRegistry(t, url, func(o *Options) {