From 3e2086ae9f225834737a98c6f87631c653c579cf Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 08:11:06 +0100 Subject: [PATCH 01/14] feat(ag-ui): support frontend tools A client offers tools in RunAgentInput.tools; the model calls them like any other tool and the application runs them. Step 4 of AG-UI support (#5119). - The tools of a run are offered to the thread's agent (entry agent and its handoff targets), not to sub-agents. A name that is already a tool of those agents is rejected with 400. - A frontend call streams START, ARGS and END without a result; the run ends with RUN_FINISHED, outcome success and pendingToolCallIds. - The next run sends tool messages, stored as tool results (error set maps to an error result); it needs no new user message. A result may sit after its call's message rather than at the end, as @ag-ui/client places it. A pending call a run leaves unanswered gets an error result, streamed and logged. - A turn mixing a frontend call and an approval pauses on the interrupt; the resume carries the tool messages. Cancelling an expired interrupt leaves the frontend call pending unless it is answered. - The thread stores the wire IDs of its calls, so a pending call can be answered after a restart. Wire IDs are unique on the thread: a call ID the model reuses in a later run (call_0) gets a suffix, since @ag-ui/client merges calls that share an ID. Records name the agent of each call, as every agent numbers its own, and a failed run stores its calls too. - The server runs no frontend call: the safety mode neither asks, denies nor skips hooks for it. Permission deny rules and pre_tool_use hooks apply. - The dispatcher decides client calls before the other calls of a batch: a refused frontend call streams its error before an approval pauses the run, and the client gets its calls whichever call asks first. Closes #5119 Signed-off-by: deka --- docs/configuration/hooks/index.md | 7 +- docs/configuration/permissions/index.md | 4 +- docs/features/ag-ui/index.md | 117 ++- pkg/agui/frontend_tools.go | 238 ++++++ pkg/agui/frontend_tools_test.go | 799 +++++++++++++++++++ pkg/agui/helpers_test.go | 9 +- pkg/agui/input.go | 195 ++++- pkg/agui/interop_test.go | 195 ++++- pkg/agui/server.go | 88 +- pkg/agui/server_test.go | 17 +- pkg/agui/translator.go | 125 ++- pkg/runtime/client_tools_test.go | 134 ++++ pkg/runtime/hooks.go | 6 +- pkg/runtime/loop.go | 57 ++ pkg/runtime/toolexec/client_executed_test.go | 131 +++ pkg/runtime/toolexec/dispatcher.go | 58 +- pkg/session/branch.go | 1 + pkg/session/session.go | 5 + pkg/tools/tools.go | 4 + 19 files changed, 2099 insertions(+), 91 deletions(-) create mode 100644 pkg/agui/frontend_tools.go create mode 100644 pkg/agui/frontend_tools_test.go create mode 100644 pkg/runtime/client_tools_test.go create mode 100644 pkg/runtime/toolexec/client_executed_test.go diff --git a/docs/configuration/hooks/index.md b/docs/configuration/hooks/index.md index f32df0d680..16a688a8ba 100644 --- a/docs/configuration/hooks/index.md +++ b/docs/configuration/hooks/index.md @@ -31,7 +31,7 @@ Docker Agent dispatches the following hook events: | Event | When it fires | Can block? | | --------------------------- | --------------------------------------------------------------------------------- | ---------- | -| `pre_tool_use` | Default lane: approval helper when the safety mode asks; also vetoes delegation wrappers in balanced; skipped on other auto-approved calls | Yes | +| `pre_tool_use` | Default lane: approval helper when the safety mode asks; also vetoes delegation wrappers in balanced and AG-UI frontend tool calls under every mode; skipped on other auto-approved calls | Yes | | `tool_input_transform` | Before tool guards, permission rules, and safety classification, including auto-approved calls | Yes | | `prompt_file_guard` | Before loaded or retained prompt-file instructions enter storage or a model request | Yes | | `skill_content_guard` | After reading skill text, before expansion or delivery | Yes | @@ -444,7 +444,7 @@ In addition to the common fields, each event ships its own payload: | `user_steering_messages_submit` | `steering_messages` — the drained steering messages, in submission order | | `user_followup_submit` | `prompt` — the text of the dequeued follow-up message | | `turn_start` | _none_ (just the common fields) | -| `turn_end` | `agent_name`, `reason` — one of `normal`, `continue`, `steered`, `error`, `canceled`, `hook_blocked`, `loop_detected` | +| `turn_end` | `agent_name`, `reason` — one of `normal`, `continue`, `steered`, `error`, `canceled`, `hook_blocked`, `loop_detected`, `client_tool_calls` | | `before_llm_call` | `iteration` — 1-based run-loop iteration counter (the model call this hook is gating), `model_id` | | `after_llm_call` | `agent_name`, `stop_response`, `last_user_message`, `model_id`, `usage`, `cost` | | `session_end` | `reason` — `stream_ended` | @@ -477,7 +477,7 @@ Notes: - For [harness agents](../../features/harnesses/index.md), `cost` is the harness's own reported total for the call rather than a computed price, and is present only when the harness reported a non-zero cost (some harnesses, e.g. `codex`, report token counts but no cost — those turns carry `usage` with `cost` absent, even though the recorded message stores `0`). - `after_llm_call` fires for **every** model call, including calls made inside sub-sessions (transferred tasks, background agents, skills). For those, `session_id` is the sub-session's id. Summing `cost` across `after_llm_call` events therefore captures **all** spend, including sub-sessions (and even sub-sessions that error before their cost is persisted). Do **not** add a separately-queried session cost total on top: the runtime's own total already recurses into and includes completed sub-session spend, so combining the two double-counts. Pick one source — the summed hook costs — as the authoritative ledger. - `context_limit` is `0` when the model definition is unavailable (treat `0` as "unknown", not as a real limit). -- `approval_decision` is one of `allow`, `deny`, `canceled`. `approval_source` is a stable classifier of which step decided (e.g. `yolo`, `session_permissions_allow`, `session_permissions_deny`, `team_permissions_allow`, `team_permissions_deny`, `pre_tool_use_hook_allow`, `pre_tool_use_hook_deny`, `tool_input_transform_deny`, `tool_guard_deny`, `readonly_hint`, `user_approved`, `user_approved_session`, `user_approved_safe`, `user_approved_tool`, `user_rejected`, `context_canceled`). +- `approval_decision` is one of `allow`, `deny`, `canceled`. `approval_source` is a stable classifier of which step decided (e.g. `yolo`, `session_permissions_allow`, `session_permissions_deny`, `team_permissions_allow`, `team_permissions_deny`, `pre_tool_use_hook_allow`, `pre_tool_use_hook_deny`, `tool_input_transform_deny`, `tool_guard_deny`, `readonly_hint`, `client_executed`, `user_approved`, `user_approved_session`, `user_approved_safe`, `user_approved_tool`, `user_rejected`, `context_canceled`). ## Hook Output @@ -990,6 +990,7 @@ The `reason` field classifies the exit: | `canceled` | Context was cancelled (e.g. Ctrl+C) | | `hook_blocked` | `before_llm_call` or `post_tool_use` denied the call | | `loop_detected` | The consecutive-tool-call loop detector terminated the turn | +| `client_tool_calls` | The model called tools the client application runs (AG-UI frontend tools): the run stops for the client to answer them | `turn_end` is observational — the result is ignored. Use it to time turns, accumulate per-turn metrics (token usage, tool counts), or notify external observability pipelines symmetrically with `turn_start`. diff --git a/docs/configuration/permissions/index.md b/docs/configuration/permissions/index.md index 932669cb0e..1a9865b99d 100644 --- a/docs/configuration/permissions/index.md +++ b/docs/configuration/permissions/index.md @@ -317,9 +317,9 @@ Permissions work alongside [hooks](../hooks/index.md). The evaluation order is: 4. Check **deny** patterns — if matched, tool is blocked 5. Check **allow** patterns — if matched, tool is auto-approved 6. Check **ask** patterns — if matched, the user is prompted directly, skipping the default `pre_tool_use` lane -7. If no rule matched, apply the **[safety mode](#safety-modes)** to the call's safety label — may auto-approve (or, under `restricted`, deny) +7. If no rule matched, apply the **[safety mode](#safety-modes)** to the call's safety label — may auto-approve (or, under `restricted`, deny). A call the client application runs (an [AG-UI frontend tool](../../features/ag-ui/index.md#frontend-tools)) is routed to "ask" instead 8. On a mode "ask", run **pre_tool_use hooks** — hooks can allow, deny, or ask -9. If no decision, **ask user** for confirmation +9. If no decision, **ask user** for confirmation; a call the client application runs is handed to it without a prompt Default-lane hooks only see calls the mode routed to "ask"; they cannot override deny decisions or explicit `ask:` rules. If they rewrite arguments, mandatory checks and permission rules are evaluated again before execution. A new ask during this recheck requires fresh confirmation; earlier grants cannot bypass it. See [tool phases](../hooks/index.md#tool-phases-transform-guard-approve). diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index 39a052fa0d..f79b67e874 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -21,9 +21,9 @@ TypeScript, Python, Go and more. You don't write protocol code. > [!WARNING] > **Early AG-UI support** > -> This release covers a streaming chat and, through interrupts, tool approval -> (`--tool-approval`) and MCP elicitation (`--elicitation`). Frontend tools, -> shared state and attachments are not implemented yet. See +> This release covers a streaming chat, [frontend tools](#frontend-tools) and, +> through interrupts, tool approval (`--tool-approval`) and MCP elicitation +> (`--elicitation`). Shared state and attachments are not implemented yet. See > [Current limitations](#current-limitations). ## Usage @@ -112,9 +112,10 @@ Each AG-UI thread is a Docker Agent session. that differ only by case must not share them on a case-insensitive filesystem. Events carry the `threadId` the client sent. - **The server-side session is the source of truth.** AG-UI clients resend the - whole conversation on every run. The server reads only the user messages - that end `messages` and ignores the rest of that history, including system, - assistant and tool messages. + whole conversation on every run. The server reads only the messages that end + `messages` (user messages, and the results of + [frontend tools](#frontend-tools)) and ignores the rest of that history, + including system and assistant messages. - A user message is identified by its `id`. Among the user messages that end `messages`, those up to the last one the thread already holds are history; the ones after it are new. @@ -125,8 +126,9 @@ Each AG-UI thread is a Docker Agent session. `ag-ui.batches`), so any of them resent later is history. - A prompt a hook blocked stays in the thread but never reaches the model: later runs leave it out of the history they send. -- A run needs something to answer: a request without a new user message is - rejected with `400 Bad Request` (`no new user message for this thread`). The +- A run needs something to answer: a request without a new user message or + frontend tool result is rejected with `400 Bad Request` + (`no new user message for this thread`). The exception is a thread that still ends on a prompt, because its last run stored no output (it failed, or a hook blocked the prompt): resending the same messages submits that prompt again. It goes through the @@ -161,8 +163,8 @@ tightened to the server's policy, never relaxed. Notes: -- Tools run on the server. Tool events show progress; the client is not asked - to execute anything. +- Tools run on the server, except the [frontend tools](#frontend-tools) the + client offers. Events of server tools show progress. - The server ends every message, tool call and step it started before `RUN_FINISHED` or `RUN_ERROR`. Nothing follows either of them. - Every tool call has a `TOOL_CALL_RESULT` before `RUN_FINISHED`, so a client @@ -170,12 +172,15 @@ Notes: withdrew was never executed: its result is `(retracted: the call was not executed)`. The exception is a run paused on an [interrupt](#tool-approval-interrupts): its calls without a result get it in - the resumed run. -- A `toolCallId` names one call within the run and the runs that resume it. Models whose tool calls are - parsed from text reuse IDs from one turn to the next (`call_0`): a reused ID - gets a suffix (`call_0-2`). + the resumed run. The other exception is a call to a + [frontend tool](#frontend-tools): the client runs it. +- A `toolCallId` names one call of the thread. Models reuse IDs from one turn + to the next (`call_0` for tool calls parsed from text): a reused ID gets a + suffix (`call_0-2`), since `@ag-ui/client` merges calls that share an ID. - `RUN_FINISHED` means the run completed normally, or paused on an interrupt - when it carries `outcome: {"type": "interrupt"}`. A run that was cut short + when it carries `outcome: {"type": "interrupt"}`. A run that leaves calls to + frontend tools for the client to run carries + `outcome: {"type": "success", "pendingToolCallIds": [...]}`. A run that was cut short ends with `RUN_ERROR`, whose `code` is: - `canceled` for a run canceled on the server. A client that disconnects cancels its run and receives nothing more. @@ -202,14 +207,14 @@ nothing: the same `threadId` still accepts a valid request. | ---------------- | ------------------------------------------------------------------------- | | `threadId` | Required, at most 256 bytes. Starts with a letter or digit and contains only letters, digits, `.`, `_` and `-` (a UUID qualifies). | | `runId` | Required, at most 256 bytes. | -| `messages` | Every message needs an `id` of at most 256 bytes and a known `role`. The history must end with at least one user message; those trailing user messages need distinct `id`s and non-empty text content (a string, or a list of `text` parts). The content of earlier messages is not read. | -| `tools` | Must be empty: frontend tools are not supported. | +| `messages` | Every message needs an `id` of at most 256 bytes and a known `role`. The history must end with at least one user message, or with tool results in the last turn. Trailing user messages need distinct `id`s and non-empty text content (a string, or a list of `text` parts). Tool results of the last turn (since the user messages that started it) need a `toolCallId` (distinct, at most 256 bytes) and text content; `error`, when set, must be a string. The `toolCallId` must name a call of the thread. The content of earlier messages is not read. | +| `tools` | At most 128 tools, 256 KiB in all. Each tool is an object with a `name` of 1 to 64 letters, digits, `_` or `-`, distinct and not the name of a tool of the entry agent or of its handoff targets; a `description` of at most 8 KiB; and `parameters`, absent or a JSON schema with `"type": "object"`. See [Frontend tools](#frontend-tools). | | `state` | Must be empty (`null`, `{}`): shared state is not supported. | | `resume` | Only with `--tool-approval` or `--elicitation`, to resolve interrupts: see [Tool approval](#tool-approval-interrupts) and [Elicitation](#elicitation-interrupts). Each entry needs an `interruptId` (distinct, at most 256 bytes) and a `status` of `resolved`, with a `payload` matching the interrupt's `responseSchema`, or `cancelled`, without a `payload`. | | `context`, `forwardedProps` | Accepted and ignored. | -`tools` and `state` are rejected rather than silently ignored, so a client -finds out immediately that a feature it relies on is missing. So is `resume` +`state` is rejected rather than silently ignored, so a client finds out +immediately that a feature it relies on is missing. So is `resume` when the server runs with neither `--tool-approval` nor `--elicitation`. A request with `resume` does not need to end with a user message. @@ -285,6 +290,12 @@ client approve it instead (see below). Likewise, an elicitation request from an MCP server is declined unless `--elicitation` lets the client answer it (see [Elicitation](#elicitation-interrupts)). +The policy applies to the tools the server runs. Calls to +[frontend tools](#frontend-tools) are the application's to run: they are not +asked for approval, but permission deny rules and `pre_tool_use` hooks apply +to them under every policy. They are decided before the other calls of their +batch, so a refusal streams before an approval of the batch pauses the run. + ## Tool approval (interrupts) With `--tool-approval`, a tool call that would ask for confirmation pauses the @@ -519,6 +530,69 @@ Rules: - The interrupt carries no `toolCallId`: MCP does not say which call raised the request. +## Frontend tools + +A client offers tools that run in the application, such as a date picker or a +confirmation dialog, in the `tools` field of `RunAgentInput`. The model calls +them like any other tool; the application runs the call and sends its result +in the next run. + +- **Who gets them.** The tools of a run are offered to the agent the thread + runs: the entry agent and the agents it hands off to. Sub-agents reached + through `transfer_task` and background agents don't get them. A tool name + that is already a tool of one of those agents is rejected with + `400 Bad Request`. +- **Per run.** The thread does not store the tools: send them on every run that + offers them. +- **The call.** The run streams `TOOL_CALL_START`, `TOOL_CALL_ARGS` and + `TOOL_CALL_END`, but no `TOOL_CALL_RESULT`. Calls to server tools in the + same turn run as usual. The run then ends with `RUN_FINISHED` and + `outcome: {"type": "success", "pendingToolCallIds": ["", ...]}`, + without calling the model again. +- **The result.** The next run sends the result as a `tool` message whose + `toolCallId` is the call's, after the assistant message of the call (the + reference client inserts it there, before the messages of later calls). Set `error` to report + a failed call: the model sees the content followed by the error. The run + needs no new user message, and the model continues the turn. Results the + thread already holds, resent as history, are ignored. A `toolCallId` the + thread does not know, or a call that is no longer pending, is rejected with + `400 Bad Request`. +- **No answer.** A run that sends a new user message without the result of a + pending call gives that call the error result + `the application did not answer this tool call`, streamed as its + `TOOL_CALL_RESULT` at the start of the run, and logs a warning with the + thread and call IDs. The model is never called with a call left without a + result. +- **Restart.** The thread stores the `toolCallId` of each call it streamed + (session attribute `ag-ui.tool-calls`): a pending call can be answered after + a server restart. +- **Turn end.** A turn that stops for frontend calls reports the + `client_tool_calls` reason to [`turn_end` hooks](../../configuration/hooks/index.md). + +### Safety + +The server does not run a frontend call, so it never asks for approval and +the [tool safety](#tool-safety) policy, which weighs what the server runs, +neither denies it nor skips its hooks: running it is the application's +decision. Under every policy, a permission deny rule and `pre_tool_use` hooks +still refuse it. A refused call gets an error `TOOL_CALL_RESULT` in the stream +and is not pending. + +### With tool approval + +When a turn has a frontend call and a call that needs approval, the run +pauses on the interrupt (`outcome: {"type": "interrupt"}`, without +`pendingToolCallIds`). The frontend call has ended in that run: send its +result with the `resume`. A resume without it gives the call the error result +above. An invalid result leaves the run paused, so a valid resume still +works. The same holds for an [elicitation](#elicitation-interrupts) in the +turn. A refused frontend call got its error result before the pause: it is +not pending, and a result sent for it is ignored. + +If the interrupt expired and the client cancels it, the frontend call stays +the client's to answer, unless the cancelling request carries its result: the +run lists it in `pendingToolCallIds`. + ## Current limitations - **Interrupts don't survive a restart.** Paused runs are held in memory. @@ -530,7 +604,10 @@ Rules: running tool asks for (a command embedded in a skill) is not held. - **No messages snapshot.** No `MESSAGES_SNAPSHOT` is sent before an interrupt; the client keeps the history it streamed. -- **No frontend tools.** A non-empty `tools` field is rejected. +- **Frontend tools are for the thread's agent.** Sub-agents and background + agents don't get them, and a call is answered by the next run only. +- **Tool call records grow with the thread.** The thread keeps the wire ID of + every call it streamed, so that IDs stay unique; they are never pruned. - **No shared state.** `STATE_SNAPSHOT` and `STATE_DELTA` are never sent, and a non-empty `state` is rejected. - **Text only.** Images and other attachments in user messages are rejected. diff --git a/pkg/agui/frontend_tools.go b/pkg/agui/frontend_tools.go new file mode 100644 index 0000000000..8ac0f07b78 --- /dev/null +++ b/pkg/agui/frontend_tools.go @@ -0,0 +1,238 @@ +package agui + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "slices" + + "github.com/docker/docker-agent/pkg/agent" + "github.com/docker/docker-agent/pkg/chat" + "github.com/docker/docker-agent/pkg/session" + "github.com/docker/docker-agent/pkg/tools" +) + +const ( + // callsAttribute holds the tool calls of the last run that streamed any: + // a later run maps the wire IDs the client answers to runtime calls. + callsAttribute = "ag-ui.tool-calls" + + unansweredToolResult = "the application did not answer this tool call" +) + +// errStoreAnswers is a failure to store tool results: the run does not start. +var errStoreAnswers = errors.New("failed to store the tool results") + +// storedCalls returns the tool calls the thread recorded. +func storedCalls(sess *session.Session) []callRecord { + raw, ok := sess.AttributesSnapshot()[callsAttribute] + if !ok { + return nil + } + var records []callRecord + if err := json.Unmarshal([]byte(raw), &records); err != nil { + slog.Warn("Ignoring unreadable AG-UI tool calls", "session_id", sess.ID, "error", err) + } + return records +} + +// trackCalls gives the run of tr the wire IDs of the thread and stores its +// calls. Wire IDs are unique on the thread: @ag-ui/client merges a call into +// an earlier message with the same ID. +func (s *server) trackCalls(ctx context.Context, tr *translator, sess *session.Session) { + for _, r := range storedCalls(sess) { + tr.wireIDs[r.Wire] = true + } + tr.saveCalls = s.callSaver(ctx, sess) +} + +// callSaver adds the calls of a run to those of its session, in memory and +// in the store: the runtime may save the session again after the run. +func (s *server) callSaver(ctx context.Context, sess *session.Session) func([]callRecord) error { + ctx = context.WithoutCancel(ctx) + return func(records []callRecord) error { + // A resumed run stores the calls of its paused run again. + kept := slices.DeleteFunc(storedCalls(sess), func(r callRecord) bool { + return slices.ContainsFunc(records, func(n callRecord) bool { return n.Wire == r.Wire }) + }) + raw, err := json.Marshal(append(kept, records...)) + if err != nil { + return err + } + sess.SetAttribute(callsAttribute, string(raw)) + return s.store.UpdateSession(ctx, sess.Clone()) + } +} + +// pendingCall is a frontend call that waits for the client's result. +type pendingCall struct { + wire string + id string + name string + agent string +} + +// answers are the tool results of a run, matched against the frontend calls +// pending on the thread. +type answers struct { + // results answer every pending call, in call order: an unanswered call + // gets an error. + results []*session.Message + unanswered []pendingCall + // answered lists the wire IDs of the pending calls the client answered. + answered []string + // given counts the pending calls the client answered. + given int + // history: the input had tool messages, all already stored. + history bool +} + +// matchToolResults maps the tool messages of the input to the frontend calls +// pending on the thread: those of its last assistant message without a result. +// It changes nothing. +func matchToolResults(sess *session.Session, results []toolMessage) (*answers, error) { + pending, _, stored := pendingFrontendCalls(sess) + byWire := make(map[string]callRecord) + for _, r := range storedCalls(sess) { + byWire[r.Wire] = r + } + + given := make(map[string]toolMessage) + for _, m := range results { + r, known := byWire[m.toolCallID] + isPending := known && slices.ContainsFunc(pending, func(p pendingCall) bool { return p.wire == m.toolCallID }) + switch { + case isPending: + given[m.toolCallID] = m + case known && (!r.Frontend || stored[r.ID]), !known && stored[m.toolCallID]: + // A result already stored, resent as history. + case !known: + return nil, fmt.Errorf("messages: tool call %q is unknown on this thread", m.toolCallID) + default: + return nil, fmt.Errorf("messages: tool call %q is not pending", m.toolCallID) + } + } + + out := &answers{given: len(given), history: len(results) > 0 && len(given) == 0} + for _, p := range pending { + m, ok := given[p.wire] + if !ok { + out.unanswered = append(out.unanswered, p) + out.results = append(out.results, frontendResult(p.agent, p.id, unansweredToolResult, true)) + continue + } + out.answered = append(out.answered, p.wire) + out.results = append(out.results, frontendResult(p.agent, p.id, m.content, m.isError)) + } + return out, nil +} + +func frontendResult(agentName, callID, content string, isError bool) *session.Message { + return session.NewAgentMessage(agentName, &chat.Message{ + Role: chat.MessageRoleTool, + ToolCallID: callID, + Content: content, + IsError: isError, + }) +} + +// pendingFrontendCalls returns the frontend calls of the last assistant +// message of the thread that have no result, the runtime IDs of those that +// have one, and the IDs of every stored tool result. +func pendingFrontendCalls(sess *session.Session) (pending []pendingCall, answered, stored map[string]bool) { + answered, stored = make(map[string]bool), make(map[string]bool) + // Sub-sessions hold no frontend call: their results are in the records. + msgs := sess.OwnMessages() + last := -1 + for i, m := range msgs { + switch m.Message.Role { + case chat.MessageRoleAssistant: + last = i + clear(answered) + case chat.MessageRoleTool: + answered[m.Message.ToolCallID] = true + stored[m.Message.ToolCallID] = true + } + } + if last < 0 { + return nil, answered, stored + } + // A runtime ID may come back in a later turn: the latest record wins. + owner := msgs[last].AgentName + frontend := make(map[string]string) + for _, r := range storedCalls(sess) { + switch { + case r.Agent != owner: + case r.Frontend: + frontend[r.ID] = r.Wire + default: + delete(frontend, r.ID) + } + } + for _, tc := range msgs[last].Message.ToolCalls { + if wire, ok := frontend[tc.ID]; ok && !answered[tc.ID] { + pending = append(pending, pendingCall{wire: wire, id: tc.ID, name: tc.Function.Name, agent: owner}) + } + } + return pending, answered, stored +} + +// storeAnswers adds tool results to the session and the store. +func (s *server) storeAnswers(ctx context.Context, sess *session.Session, threadID string, a *answers) error { + for _, p := range a.unanswered { + // Never the content: tool results may hold anything. + slog.WarnContext(ctx, "AG-UI frontend tool call left unanswered", "thread_id", threadID, "tool_call_id", p.wire, "tool", p.name) + } + for _, m := range a.results { + if _, err := s.store.AddMessage(context.WithoutCancel(ctx), sess.ID, m); err != nil { + slog.ErrorContext(ctx, "Failed to store AG-UI tool result", "thread_id", threadID, "error", err) + return errStoreAnswers + } + sess.AddMessage(m) + } + return nil +} + +// checkToolNames rejects a frontend tool named like a tool of an agent that +// runs in the thread's session: the entry agent and its handoff targets. +func (s *server) checkToolNames(ctx context.Context, frontend []tools.Tool) (int, error) { + if len(frontend) == 0 { + return 0, nil + } + entry, err := s.team.AgentOrDefault(s.agentName) + if err != nil { + return http.StatusInternalServerError, err + } + taken := make(map[string]string) + seen := map[*agent.Agent]bool{entry: true} + queue := []*agent.Agent{entry} + for len(queue) > 0 { + a := queue[0] + queue = queue[1:] + list, err := a.Tools(ctx) + if err != nil { + slog.ErrorContext(ctx, "Failed to list agent tools", "agent", a.Name(), "error", err) + return http.StatusInternalServerError, errors.New("failed to list the tools of the agent") + } + for _, t := range list { + if _, ok := taken[t.Name]; !ok { + taken[t.Name] = a.Name() + } + } + for _, h := range a.Handoffs() { + if !seen[h] { + seen[h] = true + queue = append(queue, h) + } + } + } + for i, t := range frontend { + if owner, ok := taken[t.Name]; ok { + return http.StatusBadRequest, fmt.Errorf("tools[%d]: name %q is a tool of agent %q", i, t.Name, owner) + } + } + return 0, nil +} diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go new file mode 100644 index 0000000000..5999f38157 --- /dev/null +++ b/pkg/agui/frontend_tools_test.go @@ -0,0 +1,799 @@ +package agui + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dagent "github.com/docker/docker-agent/pkg/agent" + "github.com/docker/docker-agent/pkg/chat" + "github.com/docker/docker-agent/pkg/config/latest" + "github.com/docker/docker-agent/pkg/hooks" + "github.com/docker/docker-agent/pkg/permissions" + "github.com/docker/docker-agent/pkg/runtime" + "github.com/docker/docker-agent/pkg/session" + "github.com/docker/docker-agent/pkg/session/sqlitestore" + "github.com/docker/docker-agent/pkg/team" + "github.com/docker/docker-agent/pkg/tools" + "github.com/docker/docker-agent/pkg/tools/builtin/transfertask" +) + +var pickDate = map[string]any{ + "name": "pick_date", + "description": "Ask the user for a date", + "parameters": map[string]any{"type": "object", "properties": map[string]any{"after": map[string]any{"type": "string"}}}, +} + +func userMsg(id, content string) map[string]any { + return map[string]any{"id": id, "role": "user", "content": content} +} + +// assistantCall is the assistant message the reference client builds for a +// started call: its ID is the call's. +func assistantCall(callID, name string) map[string]any { + return map[string]any{"id": callID, "role": "assistant", "toolCalls": []map[string]any{{ + "id": callID, "type": "function", "function": map[string]any{"name": name, "arguments": "{}"}, + }}} +} + +func toolMsg(callID, content string) map[string]any { + return map[string]any{"id": callID + "-answer", "role": "tool", "toolCallId": callID, "content": content} +} + +// frontendInput builds a RunAgentInput that offers pick_date. +func frontendInput(threadID, runID string, messages ...map[string]any) string { + return inputWith(threadID, runID, []any{pickDate}, nil, messages...) +} + +func inputWith(threadID, runID string, offered []any, resume []map[string]any, messages ...map[string]any) string { + in := map[string]any{"threadId": threadID, "runId": runID, "messages": messages, "tools": offered} + if resume != nil { + in["resume"] = resume + } + body, err := json.Marshal(in) + if err != nil { + panic(err) + } + return string(body) +} + +// calls streams the given calls in one turn. +func calls(tcs ...tools.ToolCall) []chat.MessageStreamResponse { + return []chat.MessageStreamResponse{ + delta(chat.MessageDelta{ToolCalls: tcs}), + {Choices: []chat.MessageStreamChoice{{Index: 0, FinishReason: chat.FinishReasonToolCalls}}}, + } +} + +func call(id, name, args string) tools.ToolCall { + return tools.ToolCall{ID: id, Type: "function", Function: tools.FunctionCall{Name: name, Arguments: args}} +} + +// toolResults returns the tool results the n-th model call received. +func (p *scriptedProvider) toolResults(n int) []string { + p.mu.Lock() + defer p.mu.Unlock() + + var out []string + for _, m := range p.calls[n] { + if m.Role == chat.MessageRoleTool { + line := m.ToolCallID + ": " + m.Content + if m.IsError { + line += " (error)" + } + out = append(out, line) + } + } + return out +} + +func (p *scriptedProvider) offeredTo(n int) []string { + p.mu.Lock() + defer p.mu.Unlock() + return p.offered[n] +} + +func pendingOf(t *testing.T, events []wireEvent) []any { + t.Helper() + + require.NotEmpty(t, events) + last := events[len(events)-1] + require.Equal(t, "RUN_FINISHED", last.kind()) + outcome, ok := last["outcome"].(map[string]any) + require.True(t, ok, "RUN_FINISHED has no outcome: %v", last) + assert.Equal(t, "success", outcome["type"]) + assert.NotContains(t, outcome, "interrupts") + return outcome["pendingToolCallIds"].([]any) +} + +func storedMessages(t *testing.T, server *testServer) int { + t.Helper() + + sess, err := server.store.GetSession(t.Context(), sessionIDFor("thread-1")) + require.NoError(t, err) + return len(sess.GetAllMessages()) +} + +func TestFrontendTools_CallIsLeftToTheClient(t *testing.T) { + t.Parallel() + + prov := script(toolCall("pick_date", `{"after":`, `"today"}`), text("Booked")) + server := startServer(t, singleAgentTeam(prov), session.NewInMemorySessionStore(), RunOptions{}) + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book a table"))) + require.Equal(t, http.StatusOK, status, body) + assert.Equal(t, []string{ + "RUN_STARTED runId=run-1 threadId=thread-1", + "TOOL_CALL_START toolCallId=call-1 toolCallName=pick_date", + `TOOL_CALL_ARGS delta={"after": toolCallId=call-1`, + `TOOL_CALL_ARGS delta="today"} toolCallId=call-1`, + "TOOL_CALL_END toolCallId=call-1", + "RUN_FINISHED outcome=map[pendingToolCallIds:[call-1] type:success] runId=run-1 threadId=thread-1", + }, render(events)) + assert.Equal(t, []any{"call-1"}, pendingOf(t, events)) + assert.Equal(t, []string{"call-1"}, pendingToolCalls(events)) + assert.Equal(t, []string{"pick_date"}, prov.offeredTo(0)) + assert.Equal(t, 1, prov.callCount()) + + // The next run brings the result and no prompt. + assert.Equal(t, []string{ + "RUN_STARTED runId=run-2 threadId=thread-1", + "TEXT_MESSAGE_START messageId=m1 role=assistant", + "TEXT_MESSAGE_CONTENT delta=Booked messageId=m1", + "TEXT_MESSAGE_END messageId=m1", + "RUN_FINISHED runId=run-2 threadId=thread-1", + }, server.run(t, frontendInput("thread-1", "run-2", + userMsg("u1", "Book a table"), assistantCall("call-1", "pick_date"), toolMsg("call-1", "2026-12-25")))) + assert.Equal(t, []string{"call-1: 2026-12-25"}, prov.toolResults(1)) + assert.Equal(t, []string{"user: Book a table", "assistant: "}, prov.conversation(1)) +} + +func TestFrontendTools_ErrorResult(t *testing.T) { + t.Parallel() + + prov := script(toolCall("pick_date", `{}`), text("Never mind")) + server := startServer(t, singleAgentTeam(prov), session.NewInMemorySessionStore(), RunOptions{}) + server.run(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book a table"))) + + answer := toolMsg("call-1", "") + answer["error"] = "the user closed the picker" + server.run(t, frontendInput("thread-1", "run-2", userMsg("u1", "Book a table"), assistantCall("call-1", "pick_date"), answer)) + assert.Equal(t, []string{"call-1: Error: the user closed the picker (error)"}, prov.toolResults(1)) +} + +func TestFrontendTools_TwoCallsInOneTurn(t *testing.T) { + t.Parallel() + + prov := script(calls(call("c1", "pick_date", `{}`), call("c2", "pick_date", `{"after":"c1"}`)), text("Booked")) + server := startServer(t, singleAgentTeam(prov), session.NewInMemorySessionStore(), RunOptions{}) + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Two dates"))) + require.Equal(t, http.StatusOK, status, body) + assert.Equal(t, []any{"c1", "c2"}, pendingOf(t, events)) + assert.Equal(t, 1, prov.callCount()) + + // Answered in another order, stored in call order. + server.run(t, frontendInput("thread-1", "run-2", userMsg("u1", "Two dates"), + assistantCall("c1", "pick_date"), assistantCall("c2", "pick_date"), + toolMsg("c2", "2026-12-26"), toolMsg("c1", "2026-12-25"))) + assert.Equal(t, []string{"c1: 2026-12-25", "c2: 2026-12-26"}, prov.toolResults(1)) +} + +func TestFrontendTools_WithAServerTool(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c1", "pick_date", `{}`), call("c2", "lookup", `{}`)), text("Booked")) + server := startServer(t, singleAgentTeam(prov, dagent.WithTools(echoTool(&executions))), session.NewInMemorySessionStore(), RunOptions{}) + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + lines := render(events) + require.Len(t, lines, 9, lines) + assert.Equal(t, []string{ + "RUN_STARTED runId=run-1 threadId=thread-1", + "TOOL_CALL_START toolCallId=c1 toolCallName=pick_date", + "TOOL_CALL_ARGS delta={} toolCallId=c1", + "TOOL_CALL_START toolCallId=c2 toolCallName=lookup", + "TOOL_CALL_ARGS delta={} toolCallId=c2", + }, lines[:5]) + // The dispatcher may run c2 before or after it hands c1 to the client. + assert.ElementsMatch(t, []string{ + "TOOL_CALL_END toolCallId=c2", + "TOOL_CALL_RESULT content=sunny messageId=c2-result role=tool toolCallId=c2", + "TOOL_CALL_END toolCallId=c1", + }, lines[5:8]) + assert.Less(t, slices.Index(lines, "TOOL_CALL_END toolCallId=c2"), slices.Index(lines, "TOOL_CALL_RESULT content=sunny messageId=c2-result role=tool toolCallId=c2")) + assert.Equal(t, "RUN_FINISHED outcome=map[pendingToolCallIds:[c1] type:success] runId=run-1 threadId=thread-1", lines[8]) + assert.EqualValues(t, 1, executions.Load()) + + // The client resends the server's result as history. + server.run(t, frontendInput("thread-1", "run-2", userMsg("u1", "Book"), + assistantCall("c1", "pick_date"), assistantCall("c2", "lookup"), + toolMsg("c2", "sunny"), toolMsg("c1", "2026-12-25"))) + assert.Equal(t, []string{"c2: sunny", "c1: 2026-12-25"}, prov.toolResults(1)) + assert.EqualValues(t, 1, executions.Load()) +} + +// @ag-ui/client places a result after the message of its call, before the +// messages of the turn's later calls. +func TestFrontendTools_AnswerBeforeALaterCall(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c1", "pick_date", `{}`), call("c2", "lookup", `{}`)), text("Booked"), text("Done")) + server := startServer(t, singleAgentTeam(prov, dagent.WithTools(echoTool(&executions))), session.NewInMemorySessionStore(), RunOptions{}) + server.run(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + + history := []map[string]any{ + userMsg("u1", "Book"), + assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25"), + assistantCall("c2", "lookup"), toolMsg("c2", "sunny"), + } + server.run(t, frontendInput("thread-1", "run-2", history...)) + assert.ElementsMatch(t, []string{"c1: 2026-12-25", "c2: sunny"}, prov.toolResults(1)) + + // A new turn: the tool messages of the previous one are history. + history = append(history, map[string]any{"id": "a1", "role": "assistant", "content": "Booked"}, userMsg("u2", "Thanks")) + server.run(t, frontendInput("thread-1", "run-3", history...)) + assert.Equal(t, 3, prov.callCount()) + assert.EqualValues(t, 1, executions.Load()) + + // An unknown result in the new turn is still refused. + status, _, body := server.post(t, frontendInput("thread-1", "run-4", append(history, map[string]any{"id": "a2", "role": "assistant", "content": "Done"}, userMsg("u3", "Again"), toolMsg("c9", "x"))...)) + assert.Equal(t, http.StatusBadRequest, status) + assert.Contains(t, body, `tool call \"c9\" is unknown on this thread`) +} + +// A turn with a call needing approval pauses on the interrupt: the frontend +// call is answered with the resume. +func TestFrontendTools_WithAnApproval(t *testing.T) { + t.Parallel() + + for name, tc := range map[string]struct { + answers []map[string]any + early []string + want []string + }{ + "answered": {[]map[string]any{toolMsg("c1", "2026-12-25")}, nil, []string{"c1: 2026-12-25", "c2: sunny"}}, + "unanswered": { + nil, + []string{"TOOL_CALL_RESULT content=" + unansweredToolResult + " messageId=c1-result role=tool toolCallId=c1"}, + []string{"c1: " + unansweredToolResult + " (error)", "c2: sunny"}, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c1", "pick_date", `{}`), call("c2", "lookup", `{}`)), text("Booked")) + server := approvalServer(t, prov, sqliteStore(t), echoTool(&executions)) + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + interrupt := interruptOf(t, events) + assert.Equal(t, "c2", interrupt["toolCallId"]) + assert.NotContains(t, events[len(events)-1]["outcome"], "pendingToolCallIds") + assert.Equal(t, 1, prov.callCount()) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date"), assistantCall("c2", "lookup")} + resume := []map[string]any{resolved(interrupt["id"].(string), decision("approve"))} + // The server answers the call the client left: the client sees its result. + want := append(append([]string{"RUN_STARTED runId=run-2 threadId=thread-1"}, tc.early...), + "TOOL_CALL_RESULT content=sunny messageId=c2-result role=tool toolCallId=c2", + "TEXT_MESSAGE_START messageId=m1 role=assistant", + "TEXT_MESSAGE_CONTENT delta=Booked messageId=m1", + "TEXT_MESSAGE_END messageId=m1", + "RUN_FINISHED runId=run-2 threadId=thread-1", + ) + assert.Equal(t, want, server.run(t, inputWith("thread-1", "run-2", []any{pickDate}, resume, append(history, tc.answers...)...))) + assert.Equal(t, tc.want, prov.toolResults(1)) + assert.EqualValues(t, 1, executions.Load()) + }) + } +} + +// An invalid answer to a resume leaves the run parked. +func TestFrontendTools_InvalidResumeAnswerLeavesTheRunParked(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c1", "pick_date", `{}`), call("c2", "lookup", `{}`)), text("Booked")) + server := approvalServer(t, prov, session.NewInMemorySessionStore(), echoTool(&executions)) + + _, events, _ := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + resume := []map[string]any{resolved(interruptOf(t, events)["id"].(string), decision("approve"))} + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date"), assistantCall("c2", "lookup")} + + status, _, body := server.post(t, inputWith("thread-1", "run-2", []any{pickDate}, resume, append(history, toolMsg("c9", "x"))...)) + assert.Equal(t, http.StatusBadRequest, status) + assert.Contains(t, body, `tool call \"c9\" is unknown on this thread`) + assert.Zero(t, executions.Load()) + + lines := server.run(t, inputWith("thread-1", "run-2", []any{pickDate}, resume, append(history, toolMsg("c1", "2026-12-25"))...)) + assert.Equal(t, "RUN_FINISHED runId=run-2 threadId=thread-1", lines[len(lines)-1], lines) + assert.Equal(t, []string{"c1: 2026-12-25", "c2: sunny"}, prov.toolResults(1)) +} + +// The XML fallback numbers the calls of every turn from call_0: the +// frontend call reuses the ID of the server call before it. +func TestFrontendTools_ReusedCallID(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + xmlCall := func(name string) []chat.MessageStreamResponse { + return text(`{"name":"` + name + `","arguments":{}}`) + } + prov := script(xmlCall("lookup"), xmlCall("pick_date"), text("Booked")) + server := startServer(t, singleAgentTeam(prov, dagent.WithTools(echoTool(&executions))), session.NewInMemorySessionStore(), RunOptions{}) + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + assert.Equal(t, []any{"call_0-2"}, pendingOf(t, events)) + + server.run(t, frontendInput("thread-1", "run-2", userMsg("u1", "Book"), + assistantCall("call_0", "lookup"), toolMsg("call_0", "sunny"), + assistantCall("call_0-2", "pick_date"), toolMsg("call_0-2", "2026-12-25"))) + assert.Equal(t, []string{"call_0: sunny", "call_0: 2026-12-25"}, prov.toolResults(2)) +} + +func TestFrontendTools_PendingCallSurvivesRestart(t *testing.T) { + t.Parallel() + + dbPath := filepath.Join(t.TempDir(), "session.db") + prov := script(calls(call("c1", "pick_date", `{}`)), calls(call("c1", "pick_date", `{}`)), text("Booked")) + + store, err := sqlitestore.New(t.Context(), dbPath) + require.NoError(t, err) + before := startServer(t, singleAgentTeam(prov), store, RunOptions{}) + _, events, _ := before.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + assert.Equal(t, []any{"c1"}, pendingOf(t, events)) + require.NoError(t, store.Close()) + + reopened, err := sqlitestore.New(t.Context(), dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = reopened.Close() }) + after := startServer(t, singleAgentTeam(prov), reopened, RunOptions{}) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25")} + _, events, _ = after.post(t, frontendInput("thread-1", "run-2", history...)) + assert.Equal(t, []string{"c1: 2026-12-25"}, prov.toolResults(1)) + // The wire IDs used before the restart stay taken. + require.Equal(t, []any{"c1-2"}, pendingOf(t, events)) + + after.run(t, frontendInput("thread-1", "run-3", append(history, assistantCall("c1-2", "pick_date"), toolMsg("c1-2", "2026-12-26"))...)) + assert.Equal(t, []string{"c1: 2026-12-25", "c1: 2026-12-26"}, prov.toolResults(2)) +} + +func TestFrontendTools_RejectsInvalidAnswers(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c1", "pick_date", `{}`)), text("Booked")) + server := startServer(t, singleAgentTeam(prov, dagent.WithTools(echoTool(&executions))), sqliteStore(t), RunOptions{}) + server.run(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + stored := storedMessages(t, server) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date")} + lookup := map[string]any{"name": "lookup"} + for name, tc := range map[string]struct { + body string + want string + }{ + "unknown call": {frontendInput("thread-1", "run-2", append(history, toolMsg("c9", "x"))...), `tool call \"c9\" is unknown on this thread`}, + "tool of the agent": {inputWith("thread-1", "run-2", []any{lookup}, nil, append(history, toolMsg("c1", "x"))...), `tools[0]: name \"lookup\" is a tool of agent \"root\"`}, + "no answer, no prompt": {frontendInput("thread-1", "run-2", history...), "must end with a user message or tool results"}, + "answer on a new thread": { + frontendInput("thread-2", "run-2", append(history, toolMsg("c1", "x"))...), `tool call \"c1\" is unknown on this thread`, + }, + } { + t.Run(name, func(t *testing.T) { + status, _, body := server.post(t, tc.body) + assert.Equal(t, http.StatusBadRequest, status) + assert.Contains(t, body, tc.want) + }) + } + + assert.Equal(t, stored, storedMessages(t, server)) + assert.Equal(t, 1, prov.callCount()) + _, err := server.store.GetSession(t.Context(), sessionIDFor("thread-2")) + require.Error(t, err) + + server.run(t, frontendInput("thread-1", "run-2", append(history, toolMsg("c1", "2026-12-25"))...)) + assert.Equal(t, []string{"c1: 2026-12-25"}, prov.toolResults(1)) + + // Resent once answered, the result is history: it is not stored twice. + stored = storedMessages(t, server) + status, _, body := server.post(t, frontendInput("thread-1", "run-3", append(history, toolMsg("c1", "2026-12-25"))...)) + assert.Equal(t, http.StatusBadRequest, status) + assert.Contains(t, body, "no new user message") + assert.Equal(t, stored, storedMessages(t, server)) +} + +// A failed run stores its calls too: the client resends the results it got, +// under wire IDs the thread made unique. +func TestFrontendTools_FailedRunKeepsItsCalls(t *testing.T) { + t.Parallel() + + var prov *scriptedProvider + failing := tools.Tool{ + Name: "lookup", + Parameters: map[string]any{}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + prov.setErr(assert.AnError) + return tools.ResultSuccess("sunny"), nil + }, + } + prov = script(calls(call("c1", "pick_date", `{}`)), calls(call("c1", "lookup", `{}`)), text("Booked")) + server := startServer(t, singleAgentTeam(prov, dagent.WithTools(failing)), session.NewInMemorySessionStore(), RunOptions{}) + server.run(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25")} + failed := server.run(t, frontendInput("thread-1", "run-2", history...)) + require.Contains(t, failed, "TOOL_CALL_RESULT content=sunny messageId=c1-2-result role=tool toolCallId=c1-2") + require.True(t, strings.HasPrefix(failed[len(failed)-1], "RUN_ERROR"), failed) + + prov.setErr(nil) + history = append(history, assistantCall("c1-2", "lookup"), map[string]any{"id": "c1-2-result", "role": "tool", "toolCallId": "c1-2", "content": "sunny"}, userMsg("u2", "Retry")) + retried := server.run(t, frontendInput("thread-1", "run-3", history...)) + assert.Equal(t, "RUN_FINISHED runId=run-3 threadId=thread-1", retried[len(retried)-1]) +} + +// A run that stored the results but failed before any output can be retried +// with the same input. +func TestFrontendTools_RetryAfterAFailedRun(t *testing.T) { + t.Parallel() + + prov := script(calls(call("c1", "pick_date", `{}`)), text("Booked")) + server := startServer(t, singleAgentTeam(prov), sqliteStore(t), RunOptions{}) + server.run(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + + answer := frontendInput("thread-1", "run-2", userMsg("u1", "Book"), assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25")) + prov.setErr(assert.AnError) + failed := server.run(t, answer) + assert.True(t, strings.HasPrefix(failed[len(failed)-1], "RUN_ERROR"), failed) + + prov.setErr(nil) + retried := server.run(t, answer) + assert.Equal(t, "RUN_FINISHED runId=run-2 threadId=thread-1", retried[len(retried)-1]) + assert.Equal(t, []string{"c1: 2026-12-25"}, prov.toolResults(2)) +} + +// Not parallel: it swaps the process-global default logger. +func TestFrontendTools_UnansweredCallGetsAnError(t *testing.T) { + var logs bytes.Buffer + prev := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) + t.Cleanup(func() { slog.SetDefault(prev) }) + + prov := script(calls(call("c1", "pick_date", `{"secret":"s3cr3t"}`)), text("Sure")) + server := startServer(t, singleAgentTeam(prov), session.NewInMemorySessionStore(), RunOptions{}) + server.run(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + + lines := server.run(t, frontendInput("thread-1", "run-2", userMsg("u1", "Book"), assistantCall("c1", "pick_date"), userMsg("u2", "Forget it"))) + // The client learns the result the server gave its call. + assert.Equal(t, []string{ + "RUN_STARTED runId=run-2 threadId=thread-1", + "TOOL_CALL_RESULT content=" + unansweredToolResult + " messageId=c1-result role=tool toolCallId=c1", + }, lines[:2]) + assert.Equal(t, []string{"c1: " + unansweredToolResult + " (error)"}, prov.toolResults(1)) + assert.Equal(t, []string{"user: Book", "assistant: ", "user: Forget it"}, prov.conversation(1)) + + out := logs.String() + assert.Contains(t, out, "AG-UI frontend tool call left unanswered") + assert.Contains(t, out, "thread_id=thread-1") + assert.Contains(t, out, "tool_call_id=c1") + assert.NotContains(t, out, "s3cr3t") +} + +// Deny rules and pre_tool_use hooks apply to frontend calls: a refused call +// gets an error result in the stream and is not pending. +func TestFrontendTools_RefusedCallIsNotPending(t *testing.T) { + t.Parallel() + + const hookName = "test-refuse-pick-date" + refuse := func(context.Context, *hooks.Input, []string) (*hooks.Output, error) { + return &hooks.Output{HookSpecificOutput: &hooks.HookSpecificOutput{ + HookEventName: hooks.EventPreToolUse, + PermissionDecision: hooks.DecisionDeny, + PermissionDecisionReason: "not today", + }}, nil + } + for name, tc := range map[string]struct { + team func(*scriptedProvider) *team.Team + runtime func() []runtime.Opt + want string + }{ + "deny rule": { + team: func(prov *scriptedProvider) *team.Team { + root := dagent.New("root", "test", dagent.WithModel(prov)) + return team.New(team.WithAgents(root), team.WithPermissions(permissions.NewCheckerFromRules(nil, nil, []string{"pick_date"}))) + }, + want: "denied", + }, + "pre_tool_use hook": { + team: func(prov *scriptedProvider) *team.Team { + config := &latest.HooksConfig{PreToolUse: []latest.HookMatcherConfig{{Matcher: ".*", Hooks: []latest.HookDefinition{{Type: "builtin", Command: hookName}}}}} + return singleAgentTeam(prov, dagent.WithHooks(config)) + }, + runtime: func() []runtime.Opt { + registry := hooks.NewRegistry() + if err := registry.RegisterBuiltin(hookName, refuse); err != nil { + panic(err) + } + return []runtime.Opt{runtime.WithHooksRegistry(registry)} + }, + want: "not today", + }, + } { + for _, policy := range servedPolicies { + t.Run(name+"/"+string(policy), func(t *testing.T) { + t.Parallel() + + prov := script(calls(call("c1", "pick_date", `{}`)), text("Fine")) + server := startServerWithSafety(t, tc.team(prov), session.NewInMemorySessionStore(), policy, RunOptions{}) + server.srv.runtimeOpts = tc.runtime + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + lines := render(events) + assert.Contains(t, toolResult(t, lines), "toolCallId=c1") + assert.Contains(t, toolResult(t, lines), tc.want) + assert.Equal(t, "RUN_FINISHED runId=run-1 threadId=thread-1", lines[len(lines)-1]) + assert.Empty(t, pendingToolCalls(events)) + assert.Equal(t, 2, prov.callCount()) + }) + } + } +} + +var servedPolicies = []session.SafetyPolicy{ + session.SafetyPolicyRestricted, session.SafetyPolicyStrict, + session.SafetyPolicyBalanced, session.SafetyPolicyAutonomous, +} + +// The policy weighs what the server runs: under any of them, including the +// default restricted, a frontend call is left to the client unasked. +func TestFrontendTools_LeftToTheClientUnderEveryPolicy(t *testing.T) { + t.Parallel() + + for _, policy := range servedPolicies { + for _, approval := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/approval=%v", policy, approval), func(t *testing.T) { + t.Parallel() + + prov := script(calls(call("c1", "pick_date", `{}`)), text("Fine")) + server := startServerWithSafety(t, singleAgentTeam(prov), session.NewInMemorySessionStore(), policy, RunOptions{ToolApproval: approval}) + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + lines := render(events) + assert.Equal(t, "RUN_FINISHED outcome=map[pendingToolCallIds:[c1] type:success] runId=run-1 threadId=thread-1", lines[len(lines)-1], lines) + assert.Equal(t, 1, prov.callCount()) + }) + } + } +} + +func TestFrontendTools_NotOfferedToSubAgents(t *testing.T) { + t.Parallel() + + childProv := script(text("found it")) + child := dagent.New("researcher", "You research", dagent.WithModel(childProv)) + rootProv := script(toolCall("transfer_task", `{"agent":"researcher","task":"dig"}`), text("done")) + root := dagent.New("root", "You delegate", dagent.WithModel(rootProv), dagent.WithSubAgents(child), dagent.WithToolSets(transfertask.New())) + server := startServer(t, team.New(team.WithAgents(root, child)), session.NewInMemorySessionStore(), RunOptions{}) + + server.run(t, frontendInput("thread-1", "run-1", userMsg("u1", "Research"))) + assert.Contains(t, rootProv.offeredTo(0), "pick_date") + assert.NotContains(t, childProv.offeredTo(0), "pick_date") +} + +// Every agent numbers its parsed calls from call_0: a sub-agent's call with +// the ID of the root's frontend call leaves the latter pending. +func TestFrontendTools_SubAgentReusesTheCallID(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + childProv := script(calls(call("call_0", "lookup", `{}`)), text("found it")) + child := dagent.New("researcher", "You research", dagent.WithModel(childProv), dagent.WithTools(echoTool(&executions))) + rootProv := script(calls(call("call_0", "pick_date", `{}`), call("call_1", "transfer_task", `{"agent":"researcher","task":"dig"}`)), text("Booked")) + root := dagent.New("root", "You delegate", dagent.WithModel(rootProv), dagent.WithSubAgents(child), dagent.WithToolSets(transfertask.New())) + server := startServer(t, team.New(team.WithAgents(root, child)), session.NewInMemorySessionStore(), RunOptions{}) + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + require.Equal(t, []any{"call_0"}, pendingOf(t, events)) + require.EqualValues(t, 1, executions.Load()) + + server.run(t, frontendInput("thread-1", "run-2", userMsg("u1", "Book"), + assistantCall("call_0", "pick_date"), toolMsg("call_0", "2026-12-25"))) + assert.Contains(t, rootProv.toolResults(1), "call_0: 2026-12-25") +} + +// Handoff targets run in the thread's session: they get the frontend tools, +// and a frontend tool cannot take the name of one of theirs. +func TestFrontendTools_HandoffTargets(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + target := dagent.New("booker", "You book", dagent.WithModel(script(text("booked"))), dagent.WithTools(echoTool(&executions))) + root := dagent.New("root", "You route", dagent.WithModel(script(text("hi"))), dagent.WithHandoffs(target)) + server := startServer(t, team.New(team.WithAgents(root, target)), session.NewInMemorySessionStore(), RunOptions{}) + + status, _, body := server.post(t, inputWith("thread-1", "run-1", []any{map[string]any{"name": "lookup"}}, nil, userMsg("u1", "Book"))) + assert.Equal(t, http.StatusBadRequest, status) + assert.Contains(t, body, `tools[0]: name \"lookup\" is a tool of agent \"booker\"`) +} + +// Cancelling an expired interrupt: the frontend call of its turn is answered +// with the cancel, or stays the client's to answer. +func TestFrontendTools_CancelledExpiredInterrupt(t *testing.T) { + t.Parallel() + + // The runtime stores its own result for the call the drain canceled. + const canceledC2 = "c2: The tool call was canceled by the user. (error)" + const abandonedC2 = "TOOL_CALL_RESULT content=" + abandonedToolResult + " messageId=c2-result role=tool toolCallId=c2" + for name, tc := range map[string]struct { + answers []map[string]any + want []string + results []string + }{ + "answered": { + answers: []map[string]any{toolMsg("c1", "2026-12-25")}, + want: []string{ + "RUN_STARTED runId=run-2 threadId=thread-1", + abandonedC2, + "TEXT_MESSAGE_START messageId=m1 role=assistant", + "TEXT_MESSAGE_CONTENT delta=Booked messageId=m1", + "TEXT_MESSAGE_END messageId=m1", + "RUN_FINISHED runId=run-2 threadId=thread-1", + }, + results: []string{canceledC2, "c1: 2026-12-25"}, + }, + "unanswered": { + want: []string{ + "RUN_STARTED runId=run-2 threadId=thread-1", + abandonedC2, + "RUN_FINISHED outcome=map[pendingToolCallIds:[c1] type:success] runId=run-2 threadId=thread-1", + }, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c1", "pick_date", `{}`), call("c2", "lookup", `{}`)), text("Booked")) + server := approvalServer(t, prov, session.NewInMemorySessionStore(), echoTool(&executions)) + + _, events, _ := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + id := interruptOf(t, events)["id"].(string) + server.srv.approvals.evictExpired(time.Now().Add(defaultApprovalTTL + time.Minute)) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date"), assistantCall("c2", "lookup")} + assert.Equal(t, tc.want, server.run(t, inputWith("thread-1", "run-2", []any{pickDate}, []map[string]any{cancelled(id)}, append(history, tc.answers...)...))) + if tc.results != nil { + assert.Equal(t, tc.results, prov.toolResults(1)) + return + } + assert.Equal(t, 1, prov.callCount()) + + // The client answers it later. + server.run(t, frontendInput("thread-1", "run-3", append(history, toolMsg("c1", "2026-12-25"))...)) + assert.Equal(t, []string{canceledC2, "c1: 2026-12-25"}, prov.toolResults(1)) + assert.Zero(t, executions.Load()) + }) + } +} + +// The interrupt comes before the frontend call is dispatched: the resume +// carries its answer before the runtime hands it to the client. +func TestFrontendTools_ApprovalBeforeTheFrontendCall(t *testing.T) { + t.Parallel() + + for name, tc := range map[string]struct { + answers []map[string]any + want []string + }{ + // The client's answer is stored with the resume, before c2 runs. + "answered": {[]map[string]any{toolMsg("c1", "2026-12-25")}, []string{"c1: 2026-12-25", "c2: sunny"}}, + "unanswered": {nil, []string{"c1: " + unansweredToolResult + " (error)", "c2: sunny"}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c2", "lookup", `{}`), call("c1", "pick_date", `{}`)), text("Booked")) + server := approvalServer(t, prov, sqliteStore(t), echoTool(&executions)) + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + interrupt := interruptOf(t, events) + require.Equal(t, "c2", interrupt["toolCallId"], body) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c2", "lookup"), assistantCall("c1", "pick_date")} + resume := []map[string]any{resolved(interrupt["id"].(string), decision("approve"))} + lines := server.run(t, inputWith("thread-1", "run-2", []any{pickDate}, resume, append(history, tc.answers...)...)) + assert.Equal(t, "RUN_FINISHED runId=run-2 threadId=thread-1", lines[len(lines)-1]) + assert.Equal(t, tc.want, prov.toolResults(1)) + assert.EqualValues(t, 1, executions.Load()) + assert.Equal(t, 2, prov.callCount()) + }) + } +} + +// A deny rule refuses a frontend call before the approval of its batch +// pauses the run: an answer the resume sends anyway is history. +func TestFrontendTools_DeniedCallBeforeAnApproval(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c2", "lookup", `{}`), call("c1", "pick_date", `{}`)), text("Booked")) + root := dagent.New("root", "test", dagent.WithModel(prov), dagent.WithTools(echoTool(&executions))) + tm := team.New(team.WithAgents(root), team.WithPermissions(permissions.NewCheckerFromRules(nil, nil, []string{"pick_date"}))) + server := startServerWithSafety(t, tm, sqliteStore(t), session.SafetyPolicyStrict, RunOptions{ToolApproval: true}) + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + interrupt := interruptOf(t, events) + require.Equal(t, "c2", interrupt["toolCallId"], body) + denied := "TOOL_CALL_RESULT content=Tool 'pick_date' is denied by permissions configuration. messageId=c1-result role=tool toolCallId=c1" + assert.Contains(t, render(events), denied) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c2", "lookup"), assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25")} + resume := []map[string]any{resolved(interrupt["id"].(string), decision("approve"))} + assert.Equal(t, []string{ + "RUN_STARTED runId=run-2 threadId=thread-1", + "TOOL_CALL_RESULT content=sunny messageId=c2-result role=tool toolCallId=c2", + "TEXT_MESSAGE_START messageId=m1 role=assistant", + "TEXT_MESSAGE_CONTENT delta=Booked messageId=m1", + "TEXT_MESSAGE_END messageId=m1", + "RUN_FINISHED runId=run-2 threadId=thread-1", + }, server.run(t, inputWith("thread-1", "run-2", []any{pickDate}, resume, history...))) + assert.Equal(t, []string{"c1: Tool 'pick_date' is denied by permissions configuration. (error)", "c2: sunny"}, prov.toolResults(1)) +} + +// A batch with a frontend call pauses on the elicitation of a tool that runs: +// the resume answers both. +func TestFrontendTools_WithAnElicitation(t *testing.T) { + t.Parallel() + + for name, tc := range map[string]struct { + answers []map[string]any + want []string + }{ + "answered": {[]map[string]any{toolMsg("c1", "2026-12-25")}, []string{"c1: 2026-12-25", `c2: accept {"name":"Ada"}`}}, + "unanswered": {nil, []string{"c1: " + unansweredToolResult + " (error)", `c2: accept {"name":"Ada"}`}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + prov := script(calls(call("c2", "ask", `{}`), call("c1", "pick_date", `{}`)), text("Booked")) + server := elicitationServer(t, prov, true, askTool(formParams())) + // The frontend call must not hold the pause until the hold expires. + server.srv.approvals.hold = time.Hour + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + interrupt := interruptOf(t, events) + require.Equal(t, "input_required", interrupt["reason"], body) + assert.Contains(t, render(events), "TOOL_CALL_END toolCallId=c1") + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c2", "ask"), assistantCall("c1", "pick_date")} + resume := []map[string]any{resolved(interrupt["id"].(string), elicitationAnswerOf("accept", map[string]any{"name": "Ada"}))} + lines := server.run(t, inputWith("thread-1", "run-2", []any{pickDate}, resume, append(history, tc.answers...)...)) + assert.Contains(t, lines, `TOOL_CALL_RESULT content=accept {"name":"Ada"} messageId=c2-result role=tool toolCallId=c2`) + assert.Equal(t, "RUN_FINISHED runId=run-2 threadId=thread-1", lines[len(lines)-1], lines) + assert.ElementsMatch(t, tc.want, prov.toolResults(1)) + }) + } +} diff --git a/pkg/agui/helpers_test.go b/pkg/agui/helpers_test.go index 872897c477..c9d4f8de76 100644 --- a/pkg/agui/helpers_test.go +++ b/pkg/agui/helpers_test.go @@ -57,6 +57,8 @@ type scriptedProvider struct { streams [][]chat.MessageStreamResponse err error calls [][]chat.Message + // offered are the tool names each call received. + offered [][]string } func script(streams ...[]chat.MessageStreamResponse) *scriptedProvider { @@ -65,11 +67,16 @@ func script(streams ...[]chat.MessageStreamResponse) *scriptedProvider { func (p *scriptedProvider) ID() modelsdev.ID { return modelsdev.NewID("test", "mock-model") } -func (p *scriptedProvider) CreateChatCompletionStream(_ context.Context, messages []chat.Message, _ []tools.Tool) (chat.MessageStream, error) { +func (p *scriptedProvider) CreateChatCompletionStream(_ context.Context, messages []chat.Message, offered []tools.Tool) (chat.MessageStream, error) { p.mu.Lock() defer p.mu.Unlock() p.calls = append(p.calls, messages) + names := make([]string, 0, len(offered)) + for _, t := range offered { + names = append(names, t.Name) + } + p.offered = append(p.offered, names) if p.err != nil { return nil, p.err } diff --git a/pkg/agui/input.go b/pkg/agui/input.go index 35ac776ae2..97f2529c6c 100644 --- a/pkg/agui/input.go +++ b/pkg/agui/input.go @@ -12,6 +12,7 @@ import ( "github.com/ag-ui-protocol/ag-ui/sdks/community/go/pkg/core/types" "github.com/docker/docker-agent/pkg/toolapproval" + "github.com/docker/docker-agent/pkg/tools" ) const maxIDLength = 256 @@ -43,16 +44,30 @@ type resumeEntry struct { elicitation *elicitationAnswer } +// toolMessage is a tool result the client sent in the last turn: the answer +// to a frontend tool call, or history. +type toolMessage struct { + // toolCallID is the wire ID of the call. + toolCallID string + content string + isError bool +} + // runInput is a validated RunAgentInput. type runInput struct { threadID string runID string // newMessages are the user messages that end the client history. newMessages []userMessage - resume []resumeEntry + // toolResults are the tool messages of the last turn: after the user + // messages that started it. + toolResults []toolMessage + // tools are the frontend tools of the run. + tools []tools.Tool + resume []resumeEntry } -// decodeRunInput reads and validates a RunAgentInput; tools and state are rejected. +// decodeRunInput reads and validates a RunAgentInput; state is rejected. func decodeRunInput(body io.Reader) (*runInput, error) { dec := json.NewDecoder(body) var raw json.RawMessage @@ -86,8 +101,9 @@ func decodeRunInput(body io.Reader) (*runInput, error) { if err := validateID("runId", in.RunID); err != nil { return nil, err } - if len(in.Tools) > 0 { - return nil, errors.New("tools: frontend tools are not supported") + frontendTools, err := decodeTools(raw) + if err != nil { + return nil, err } if !isEmptyValue(in.State) { return nil, errors.New("state: shared state is not supported") @@ -97,8 +113,9 @@ func decodeRunInput(body io.Reader) (*runInput, error) { return nil, err } - // The session is the source of truth: only the trailing user messages are read. - var tail []int + // The session is the source of truth: only the trailing user messages, + // and the tool messages of the last turn, are read. + var tail, results []int for i, m := range in.Messages { if m.ID == "" { return nil, fmt.Errorf("messages[%d]: id is required", i) @@ -109,15 +126,25 @@ func decodeRunInput(body io.Reader) (*runInput, error) { if !slices.Contains(knownRoles, m.Role) { return nil, fmt.Errorf("messages[%d]: unknown role %q", i, m.Role) } - if m.Role != types.RoleUser { + switch m.Role { + case types.RoleUser: + tail = append(tail, i) + case types.RoleTool: + // The client adds its answers after the calls it ran. + results = append(results, i) + case types.RoleAssistant: + if len(tail) > 0 { + // User messages started a new turn. + results = results[:0] + } + tail = tail[:0] + default: tail = tail[:0] - continue } - tail = append(tail, i) } // A resume answers an interrupt: the history ends on the paused tool call. - if len(tail) == 0 && len(resume) == 0 { - return nil, errors.New("messages: the history must end with a user message") + if len(tail) == 0 && len(results) == 0 && len(resume) == 0 { + return nil, errors.New("messages: the history must end with a user message or tool results") } messages := make([]userMessage, 0, len(tail)) @@ -135,7 +162,122 @@ func decodeRunInput(body io.Reader) (*runInput, error) { messages = append(messages, userMessage{id: m.ID, text: text}) } - return &runInput{threadID: in.ThreadID, runID: in.RunID, newMessages: messages, resume: resume}, nil + toolResults, err := decodeToolMessages(in.Messages, results) + if err != nil { + return nil, err + } + + return &runInput{ + threadID: in.ThreadID, runID: in.RunID, + newMessages: messages, toolResults: toolResults, tools: frontendTools, resume: resume, + }, nil +} + +// decodeToolMessages validates the tool messages at indexes. Clients place a +// result after the message of its call, not necessarily at the end. +func decodeToolMessages(msgs []types.Message, indexes []int) ([]toolMessage, error) { + out := make([]toolMessage, 0, len(indexes)) + seen := make(map[string]bool, len(indexes)) + for _, i := range indexes { + m := msgs[i] + if err := validateID(fmt.Sprintf("messages[%d].toolCallId", i), m.ToolCallID); err != nil { + return nil, err + } + if seen[m.ToolCallID] { + return nil, fmt.Errorf("messages[%d]: duplicate result for tool call %q", i, m.ToolCallID) + } + seen[m.ToolCallID] = true + text, err := contentText(m.Content) + if err != nil { + return nil, fmt.Errorf("messages[%d]: %w", i, err) + } + result := toolMessage{toolCallID: m.ToolCallID, content: text, isError: m.Error != ""} + if result.isError { + result.content = strings.TrimSpace(text + "\n\n" + "Error: " + m.Error) + } + if strings.TrimSpace(result.content) == "" { + result.content = emptyToolResult + } + out = append(out, result) + } + return out, nil +} + +const ( + maxFrontendTools = 128 + maxToolDescriptionSize = 8 << 10 + maxToolsSize = 256 << 10 +) + +// A name every provider accepts. +var toolNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) + +// frontendTool is a tool of RunAgentInput.tools. Metadata is ignored. +type frontendTool struct { + Name string `json:"name"` + Description string `json:"description"` + Parameters json.RawMessage `json:"parameters"` +} + +// decodeTools validates the frontend tools of a RunAgentInput. Whether a name +// collides with a tool of the agent is checked against the team. +func decodeTools(raw json.RawMessage) ([]tools.Tool, error) { + var body struct { + Tools []json.RawMessage `json:"tools"` + } + if err := json.Unmarshal(raw, &body); err != nil { + return nil, fmt.Errorf("tools: %w", err) + } + if len(body.Tools) > maxFrontendTools { + return nil, fmt.Errorf("tools: at most %d tools are accepted", maxFrontendTools) + } + size := 0 + out := make([]tools.Tool, 0, len(body.Tools)) + seen := make(map[string]bool, len(body.Tools)) + for i, entry := range body.Tools { + size += len(entry) + if size > maxToolsSize { + return nil, fmt.Errorf("tools: the tools are larger than %d bytes", maxToolsSize) + } + if trimmed := strings.TrimSpace(string(entry)); !strings.HasPrefix(trimmed, "{") { + return nil, fmt.Errorf("tools[%d]: must be an object", i) + } + var ft frontendTool + if err := json.Unmarshal(entry, &ft); err != nil { + return nil, fmt.Errorf("tools[%d]: %w", i, err) + } + if !toolNamePattern.MatchString(ft.Name) { + return nil, fmt.Errorf("tools[%d]: name must be 1 to 64 letters, digits, '_' or '-'", i) + } + if seen[ft.Name] { + return nil, fmt.Errorf("tools[%d]: duplicate name %q", i, ft.Name) + } + seen[ft.Name] = true + if len(ft.Description) > maxToolDescriptionSize { + return nil, fmt.Errorf("tools[%d]: description is longer than %d bytes", i, maxToolDescriptionSize) + } + params, err := toolParameters(ft.Parameters) + if err != nil { + return nil, fmt.Errorf("tools[%d].parameters: %w", i, err) + } + out = append(out, tools.Tool{Name: ft.Name, Description: ft.Description, Parameters: params}) + } + return out, nil +} + +// toolParameters reads a JSON schema for an object; absent means no parameters. +func toolParameters(raw json.RawMessage) (any, error) { + if len(raw) == 0 || string(raw) == "null" { + return nil, nil + } + var schema map[string]any + if err := json.Unmarshal(raw, &schema); err != nil || schema == nil { + return nil, errors.New("must be a JSON schema object") + } + if schema["type"] != "object" { + return nil, errors.New(`type must be "object"`) + } + return schema, nil } var resumeDecisions = []string{toolapproval.Approve, toolapproval.ApproveInContext, toolapproval.Reject} @@ -241,13 +383,24 @@ func isEmptyValue(v any) bool { return false } -// userText extracts the text of a user message. Content is either a string or -// a list of parts; only text parts are supported. +// userText extracts the text of a user message, which must not be empty. func userText(content any) (string, error) { - var text string + text, err := contentText(content) + if err != nil { + return "", err + } + if strings.TrimSpace(text) == "" { + return "", errors.New("user message content is empty") + } + return text, nil +} + +// contentText extracts the text of a message. Content is either a string or +// a list of parts; only text parts are supported. +func contentText(content any) (string, error) { switch value := content.(type) { case string: - text = value + return value, nil case []any: var parts []string for i, item := range value { @@ -264,13 +417,9 @@ func userText(content any) (string, error) { } parts = append(parts, partText) } - text = strings.Join(parts, "\n") + return strings.Join(parts, "\n"), nil case nil: - default: - return "", errors.New("content must be a string or a list of text parts") + return "", nil } - if strings.TrimSpace(text) == "" { - return "", errors.New("user message content is empty") - } - return text, nil + return "", errors.New("content must be a string or a list of text parts") } diff --git a/pkg/agui/interop_test.go b/pkg/agui/interop_test.go index 498ce452cc..60dc7f1c59 100644 --- a/pkg/agui/interop_test.go +++ b/pkg/agui/interop_test.go @@ -140,7 +140,8 @@ func TestInterop_SDKClientResolvesInterrupt(t *testing.T) { // referenceClient follows the resume rules of the reference @ag-ui/client // (AbstractAgent.onInitialize): the thread's pending interrupts must all be // covered, and an expired one only by a cancelled entry. It derives pending -// tool calls across runs as that client does: started without a result. +// tool calls across runs as that client does: those RUN_FINISHED lists, else +// started without a result. It builds the history as its default apply does. type referenceClient struct { t *testing.T client *sse.Client @@ -149,6 +150,8 @@ type referenceClient struct { pendingInterrupts []types.Interrupt started []string answered map[string]bool + listed []string + messages []types.Message } func newReferenceClient(t *testing.T, url string) *referenceClient { @@ -179,7 +182,9 @@ func (c *referenceClient) run(input types.RunAgentInput) ([]events.Event, error) return nil, err } frames, errs, err := c.client.Stream(sse.StreamOptions{Context: t.Context(), Payload: input}) - require.NoError(t, err) + if err != nil { + return nil, err + } decoder := events.NewEventDecoder(nil) var decoded []events.Event for frame := range frames { @@ -195,23 +200,72 @@ func (c *referenceClient) run(input types.RunAgentInput) ([]events.Event, error) return nil, err } require.NoError(t, events.ValidateSequence(decoded)) + c.messages = input.Messages for _, event := range decoded { - switch e := event.(type) { - case *events.ToolCallStartEvent: - c.started = append(c.started, e.ToolCallID) - case *events.ToolCallResultEvent: - c.answered[e.ToolCallID] = true - case *events.RunFinishedEvent: - c.pendingInterrupts = nil - if e.Outcome != nil && e.Outcome.Type == events.RunFinishedOutcomeTypeInterrupt { - c.pendingInterrupts = e.Outcome.Interrupts - } - } + c.apply(event) } return decoded, nil } +// apply updates the client's state as the reference client does. +func (c *referenceClient) apply(event events.Event) { + switch e := event.(type) { + case *events.TextMessageStartEvent: + c.messages = append(c.messages, types.Message{ID: e.MessageID, Role: types.RoleAssistant}) + case *events.TextMessageContentEvent: + if i := c.message(e.MessageID); i >= 0 { + content, _ := c.messages[i].ContentString() + c.messages[i].Content = content + e.Delta + } + case *events.ToolCallStartEvent: + c.started = append(c.started, e.ToolCallID) + // Without a parent, the call gets an assistant message of its own. + c.messages = append(c.messages, types.Message{ID: e.ToolCallID, Role: types.RoleAssistant, ToolCalls: []types.ToolCall{{ + ID: e.ToolCallID, Type: "function", Function: types.FunctionCall{Name: e.ToolCallName}, + }}}) + case *events.ToolCallArgsEvent: + if i := c.message(e.ToolCallID); i >= 0 { + c.messages[i].ToolCalls[0].Function.Arguments += e.Delta + } + case *events.ToolCallResultEvent: + c.addResult(types.Message{ID: e.MessageID, Role: types.RoleTool, Content: e.Content, ToolCallID: e.ToolCallID}) + case *events.RunFinishedEvent: + c.pendingInterrupts, c.listed = nil, nil + if e.Outcome != nil && e.Outcome.Type == events.RunFinishedOutcomeTypeInterrupt { + c.pendingInterrupts = e.Outcome.Interrupts + } + if e.Outcome != nil { + c.listed = e.Outcome.PendingToolCallIDs + } + } +} + +func (c *referenceClient) message(id string) int { + return slices.IndexFunc(c.messages, func(m types.Message) bool { return m.ID == id }) +} + +// answer adds the application's result of a frontend call. +func (c *referenceClient) answer(toolCallID, content string) { + c.addResult(types.Message{ID: toolCallID + "-answer", Role: types.RoleTool, Content: content, ToolCallID: toolCallID}) +} + +// addResult places a tool result after the message of its call, as +// @ag-ui/client does: not necessarily at the end of the history. +func (c *referenceClient) addResult(result types.Message) { + c.answered[result.ToolCallID] = true + at := len(c.messages) + if i := slices.IndexFunc(c.messages, func(m types.Message) bool { + return slices.ContainsFunc(m.ToolCalls, func(tc types.ToolCall) bool { return tc.ID == result.ToolCallID }) + }); i >= 0 { + at = i + 1 + } + c.messages = slices.Insert(c.messages, at, result) +} + func (c *referenceClient) pendingToolCalls() []string { + if len(c.listed) > 0 { + return slices.DeleteFunc(slices.Clone(c.listed), func(id string) bool { return c.answered[id] }) + } var pending []string for _, id := range c.started { if !c.answered[id] { @@ -276,3 +330,118 @@ func TestInterop_ReferenceClientMovesPastAnExpiredInterrupt(t *testing.T) { assert.Equal(t, 2, prov.callCount()) assert.Equal(t, "assistant: Still here", server.transcript(t)[len(server.transcript(t))-1]) } + +var sdkPickDate = types.Tool{ + Name: "pick_date", + Description: "Ask the user for a date", + Parameters: map[string]any{"type": "object", "properties": map[string]any{"after": map[string]any{"type": "string"}}}, +} + +// The reference client runs a frontend call next to a server call: it +// learns which call is its own from RUN_FINISHED, and the history it builds +// with the answer is accepted as is. +func TestInterop_ReferenceClientAnswersAFrontendCall(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c1", "pick_date", `{}`), call("c2", "lookup", `{}`)), text("Booked")) + server := startServer(t, singleAgentTeam(prov, dagent.WithTools(echoTool(&executions))), session.NewInMemorySessionStore(), RunOptions{}) + client := newReferenceClient(t, server.url) + + offered := []types.Tool{sdkPickDate} + history := []types.Message{{ID: "u1", Role: types.RoleUser, Content: "Book"}} + _, err := client.run(types.RunAgentInput{ThreadID: "thread-1", RunID: "run-1", Messages: history, Tools: offered}) + require.NoError(t, err) + assert.Equal(t, []string{"c1"}, client.pendingToolCalls()) + assert.EqualValues(t, 1, executions.Load()) + + client.answer("c1", "2026-12-25") + assert.Empty(t, client.pendingToolCalls()) + _, err = client.run(types.RunAgentInput{ThreadID: "thread-1", RunID: "run-2", Messages: client.messages, Tools: offered}) + require.NoError(t, err) + assert.Empty(t, client.pendingToolCalls()) + assert.ElementsMatch(t, []string{"c1: 2026-12-25", "c2: sunny"}, prov.toolResults(1)) + assert.Equal(t, "Booked", lastContent(t, client.messages)) + assert.EqualValues(t, 1, executions.Load()) + + // The whole history again has nothing new. + _, err = client.run(types.RunAgentInput{ThreadID: "thread-1", RunID: "run-3", Messages: client.messages, Tools: offered}) + require.ErrorContains(t, err, "400") + assert.Equal(t, 2, prov.callCount()) +} + +// The model reuses a call ID in later runs: @ag-ui/client merges a call into +// an earlier message with the same ID, so wire IDs are unique on the thread. +func TestInterop_ReusedCallIDAcrossRuns(t *testing.T) { + t.Parallel() + + pick := calls(call("c1", "pick_date", `{}`)) + for name, tc := range map[string]struct { + prov *scriptedProvider + newTurns bool + }{ + "same turn": {script(pick, pick, pick, text("Booked")), false}, + "new turns": {script(pick, text("Booked"), pick, text("Booked"), pick, text("Booked")), true}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + server := startServer(t, singleAgentTeam(tc.prov), session.NewInMemorySessionStore(), RunOptions{}) + client := newReferenceClient(t, server.url) + offered := []types.Tool{sdkPickDate} + client.messages = []types.Message{{ID: "u1", Role: types.RoleUser, Content: "Book"}} + + var pending, answers []string + for run := 1; len(answers) < 3; run++ { + require.LessOrEqual(t, run, 6, "pending %v", pending) + _, err := client.run(types.RunAgentInput{ThreadID: "thread-1", RunID: fmt.Sprintf("run-%d", run), Messages: client.messages, Tools: offered}) + require.NoError(t, err) + ids := client.pendingToolCalls() + if len(ids) == 0 { + require.True(t, tc.newTurns) + client.messages = append(client.messages, types.Message{ID: fmt.Sprintf("u%d", run+1), Role: types.RoleUser, Content: "Again"}) + continue + } + require.Len(t, ids, 1) + pending = append(pending, ids[0]) + answers = append(answers, fmt.Sprintf("c1: answer-%d", len(answers)+1)) + client.answer(ids[0], fmt.Sprintf("answer-%d", len(answers))) + } + _, err := client.run(types.RunAgentInput{ThreadID: "thread-1", RunID: "run-last", Messages: client.messages, Tools: offered}) + require.NoError(t, err) + + assert.Equal(t, []string{"c1", "c1-2", "c1-3"}, pending) + assert.Equal(t, answers, tc.prov.toolResults(tc.prov.callCount()-1)) + assert.Equal(t, "Booked", lastContent(t, client.messages)) + }) + } +} + +func lastContent(t *testing.T, messages []types.Message) string { + t.Helper() + require.NotEmpty(t, messages) + content, _ := messages[len(messages)-1].ContentString() + return content +} + +// The SDK decodes the outcome a frontend call ends a run with, and the +// sequence passes its validator. +func TestInterop_SDKClientDecodesPendingToolCalls(t *testing.T) { + t.Parallel() + + prov := script(toolCall("pick_date", `{"after":"today"}`), text("Booked")) + server := startServer(t, singleAgentTeam(prov), session.NewInMemorySessionStore(), RunOptions{}) + client := newReferenceClient(t, server.url) + + decoded, err := client.run(types.RunAgentInput{ + ThreadID: "thread-1", RunID: "run-1", Tools: []types.Tool{sdkPickDate}, + Messages: []types.Message{{ID: "u1", Role: types.RoleUser, Content: "Book"}}, + }) + require.NoError(t, err) + finished, ok := decoded[len(decoded)-1].(*events.RunFinishedEvent) + require.True(t, ok) + require.NotNil(t, finished.Outcome) + assert.Equal(t, events.RunFinishedOutcomeTypeSuccess, finished.Outcome.Type) + assert.Equal(t, []string{"call-1"}, finished.Outcome.PendingToolCallIDs) + assert.False(t, slices.ContainsFunc(decoded, func(e events.Event) bool { return e.Type() == events.EventTypeToolCallResult })) +} diff --git a/pkg/agui/server.go b/pkg/agui/server.go index aea2df6ca9..6e01889e81 100644 --- a/pkg/agui/server.go +++ b/pkg/agui/server.go @@ -298,6 +298,9 @@ func (s *server) handleRun(c echo.Context) error { if len(in.resume) > 0 && !s.approvals.interrupting() { return writeError(c, http.StatusBadRequest, "resume: no interrupt is ever raised: tool approval is disabled on this server, and so is elicitation") } + if status, err := s.checkToolNames(c.Request().Context(), in.tools); err != nil { + return writeError(c, status, err.Error()) + } if !s.beginRun() { return writeError(c, http.StatusServiceUnavailable, "the server is shutting down") @@ -355,11 +358,11 @@ func (s *server) handleRun(c echo.Context) error { } } - if abandoning && len(in.newMessages) == 0 { + if abandoning && len(in.newMessages) == 0 && len(in.toolResults) == 0 { writeAbandoned(c, in, sessionID, abandoned) return nil } - sess, err := s.resolveSession(ctx, sessionID, in) + sess, answered, err := s.resolveSession(ctx, sessionID, in) switch { case errors.Is(err, errThreadUnavailable): return writeError(c, http.StatusConflict, err.Error()) @@ -368,6 +371,10 @@ func (s *server) handleRun(c echo.Context) error { return nil case errors.Is(err, errNoNewMessage): return writeError(c, http.StatusBadRequest, err.Error()) + case errors.As(err, new(*inputError)): + return writeError(c, http.StatusBadRequest, err.Error()) + case errors.Is(err, errStoreAnswers): + return writeError(c, http.StatusInternalServerError, err.Error()) case err != nil: slog.ErrorContext(ctx, "Failed to resolve AG-UI session", "thread_id", in.threadID, "error", err) return writeError(c, http.StatusInternalServerError, "failed to load the thread") @@ -400,6 +407,8 @@ func (s *server) handleRun(c echo.Context) error { if abandoning { tr = newAbandonTranslator(sess.ID, in.threadID, in.runID, abandoned) } + s.trackCalls(ctx, tr, sess) + tr.stored(answered) s.stream(c, run, tr, in) return nil } @@ -440,6 +449,11 @@ func (s *server) resumeRun(c echo.Context, in *runInput) (bool, error) { if err := s.checkNoNewMessage(ctx, in); err != nil { return false, writeResumeError(c, err) } + // The parked session recorded the calls of its run when it paused. + answered, err := matchToolResults(run.sess, in.toolResults) + if err != nil { + return false, writeError(c, http.StatusBadRequest, err.Error()) + } if taken, expired := s.approvals.take(run, time.Now()); !taken { if expired { run.cancelAndDrain() @@ -475,12 +489,21 @@ func (s *server) resumeRun(c echo.Context, in *runInput) (bool, error) { } run.sess.AppendPermissionAllow(run.approval.grant) } + // Before the run goes on: the batch ends once its frontend calls have a result. + if err := s.storeAnswers(ctx, run.sess, in.threadID, answered); err != nil { + if !s.approvals.park(run) { + run.cancelAndDrain() + } + return false, writeError(c, http.StatusInternalServerError, "failed to store the tool results: the interrupt is still pending, retry the resume") + } resumed := "" if run.approval != nil { run.rt.Resume(ctx, req) resumed = run.approval.toolCallID } tr := newResumeTranslator(run.sess.ID, in.threadID, in.runID, *run.pendingCalls, resumed) + s.trackCalls(ctx, tr, run.sess) + tr.stored(answered) for _, id := range lost { // Other answers were delivered: AG-UI has the run go on without an // entry it cannot use, and warn. The tool reports its own result. @@ -546,10 +569,10 @@ func (s *server) closeRuntime(ctx context.Context, rt runtime.Runtime, threadID // resolveSession returns the session of the thread, ending on the prompt of // the run, and creates it for an unknown threadId. -func (s *server) resolveSession(ctx context.Context, sessionID string, in *runInput) (*session.Session, error) { +func (s *server) resolveSession(ctx context.Context, sessionID string, in *runInput) (*session.Session, *answers, error) { a, err := s.team.AgentOrDefault(s.agentName) if err != nil { - return nil, err + return nil, nil, err } limits := []session.Opt{ session.WithMaxIterations(a.MaxIterations()), @@ -563,9 +586,28 @@ func (s *server) resolveSession(ctx context.Context, sessionID string, in *runIn case err == nil: // Some stores hand out their own object: never append to it directly. sess := stored.Clone() - prompt, err := nextPrompt(sess, in.newMessages) + answered, err := matchToolResults(sess, in.toolResults) if err != nil { - return nil, err + return nil, nil, &inputError{err} + } + prompt, err := nextPrompt(sess, in.newMessages) + switch { + case err == nil: + case !errors.Is(err, errNoNewMessage): + return nil, nil, err + case answered.given > 0: + // The results are what the run answers. + case answered.history && len(answered.results) == 0 && endsOnToolResult(sess): + // A retry of a run that stored its results but no output. + default: + return nil, nil, err + } + if prompt == nil && answered.given == 0 { + // A retry: nothing to store, and nothing left unanswered. + answered = &answers{} + } + if err := s.storeAnswers(ctx, sess, in.threadID, answered); err != nil { + return nil, nil, err } hideRejectedPrompts(sess) @@ -577,21 +619,30 @@ func (s *server) resolveSession(ctx context.Context, sessionID string, in *runIn sess.NonInteractive = true sess.ToolApproval = s.approvals.enabled sess.SendUserMessage = true - sess.AddMessage(prompt) - return sess, nil + sess.ClientTools = in.tools + if prompt != nil { + sess.AddMessage(prompt) + } + return sess, answered, nil case !errors.Is(err, session.ErrNotFound): - return nil, fmt.Errorf("look up AG-UI session: %w", err) + return nil, nil, fmt.Errorf("look up AG-UI session: %w", err) } // The ID may belong to a session created through another entry point. switch _, err := s.store.GetSession(ctx, sessionID); { case err == nil: - return nil, errThreadUnavailable + return nil, nil, errThreadUnavailable case !errors.Is(err, session.ErrNotFound): - return nil, fmt.Errorf("check AG-UI threadId: %w", err) + return nil, nil, fmt.Errorf("check AG-UI threadId: %w", err) } + if len(in.toolResults) > 0 { + return nil, nil, &inputError{fmt.Errorf("messages: tool call %q is unknown on this thread", in.toolResults[0].toolCallID)} + } + if len(in.newMessages) == 0 { + return nil, nil, errNoNewMessage + } sess := session.New(append(limits, session.WithID(sessionID), session.WithOrigin(sessionOrigin), @@ -600,9 +651,22 @@ func (s *server) resolveSession(ctx context.Context, sessionID string, in *runIn session.WithToolApproval(s.approvals.enabled), session.WithWorkingDir(s.workingDir), )...) + sess.ClientTools = in.tools rememberBatch(sess, in.newMessages) sess.AddMessage(promptOf(in.newMessages)) - return sess, nil + return sess, &answers{}, nil +} + +// inputError is input the thread's state refuses. +type inputError struct{ error } + +func (e *inputError) Unwrap() error { return e.error } + +// endsOnToolResult reports whether the last message of the thread is a tool +// result. +func endsOnToolResult(sess *session.Session) bool { + msgs := sess.OwnMessages() + return len(msgs) > 0 && msgs[len(msgs)-1].Message.Role == chat.MessageRoleTool } // nextPrompt returns the prompt of a run on a stored thread. The runtime diff --git a/pkg/agui/server_test.go b/pkg/agui/server_test.go index f3194430b3..e9558823f7 100644 --- a/pkg/agui/server_test.go +++ b/pkg/agui/server_test.go @@ -664,7 +664,22 @@ func TestRun_RejectsInvalidInput(t *testing.T) { "duplicate message id": {`{"threadId":"t","runId":"r","messages":[` + user + `,` + user + `]}`, "messages[1]: duplicate id"}, "mistyped threadId": {`{"threadId":7,"runId":"r","messages":[` + user + `]}`, "invalid RunAgentInput"}, "missing runId": {`{"threadId":"t","messages":[` + user + `]}`, "runId is required"}, - "frontend tools": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"confirm","description":"d","parameters":{}}]}`, "frontend tools are not supported"}, + "null tool": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[null]}`, "tools[0]: must be an object"}, + "scalar tool": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[7]}`, "invalid RunAgentInput"}, + "unnamed tool": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"description":"d"}]}`, "tools[0]: name must be"}, + "bad tool name": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"pick date"}]}`, "tools[0]: name must be"}, + "long tool name": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"` + strings.Repeat("x", 65) + `"}]}`, "tools[0]: name must be"}, + "duplicate tool": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a"},{"name":"a"}]}`, `tools[1]: duplicate name \"a\"`}, + "long tool description": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","description":"` + strings.Repeat("x", maxToolDescriptionSize+1) + `"}]}`, "description is longer"}, + "untyped parameters": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":{}}]}`, `tools[0].parameters: type must be \"object\"`}, + "array parameters": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":{"type":"array"}}]}`, `type must be \"object\"`}, + "scalar parameters": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":"object"}]}`, "tools[0].parameters: must be a JSON schema object"}, + "too many tools": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[` + strings.Repeat(`{"name":"a"},`, maxFrontendTools) + `{"name":"a"}]}`, "at most"}, + "unknown tool call": {`{"threadId":"t","runId":"r","messages":[{"id":"r1","role":"tool","toolCallId":"c1","content":"ok"}]}`, `tool call \"c1\" is unknown on this thread`}, + "tool result without call": {`{"threadId":"t","runId":"r","messages":[{"id":"r1","role":"tool","content":"ok"}]}`, "messages[0].toolCallId is required"}, + "duplicate tool result": {`{"threadId":"t","runId":"r","messages":[{"id":"r1","role":"tool","toolCallId":"c1","content":"ok"},{"id":"r2","role":"tool","toolCallId":"c1","content":"ok"}]}`, `messages[1]: duplicate result for tool call \"c1\"`}, + "mistyped tool error": {`{"threadId":"t","runId":"r","messages":[{"id":"r1","role":"tool","toolCallId":"c1","content":"ok","error":true}]}`, "invalid RunAgentInput"}, + "binary tool result": {`{"threadId":"t","runId":"r","messages":[{"id":"r1","role":"tool","toolCallId":"c1","content":[{"type":"image","source":{"type":"url","value":"https://example.com/a.png"}}]}]}`, "only text content is supported"}, "mistyped tools": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":"confirm"}`, "invalid RunAgentInput"}, "shared state": {`{"threadId":"t","runId":"r","messages":[` + user + `],"state":{"count":1}}`, "shared state is not supported"}, "scalar state": {`{"threadId":"t","runId":"r","messages":[` + user + `],"state":3}`, "shared state is not supported"}, diff --git a/pkg/agui/translator.go b/pkg/agui/translator.go index 100c400a9b..2ad8356901 100644 --- a/pkg/agui/translator.go +++ b/pkg/agui/translator.go @@ -3,6 +3,7 @@ package agui import ( "cmp" "fmt" + "log/slog" "slices" "uuid" @@ -47,6 +48,8 @@ type invocation struct { running bool // result is what the call returned after its run was parked. result string + // frontend: the client runs the call and sends its result in a later run. + frontend bool } // toolCallKey names a runtime call: sub-agents number their calls too. @@ -81,6 +84,26 @@ type translator struct { calls []*invocation wireIDs map[string]bool steps []string + + // resolved are frontend calls of the paused run whose result the resume + // stored: their dispatch streams nothing. + resolved map[toolCallKey]bool + // onStart are results the server stored before the run, streamed first. + onStart []*invocation + + // saveCalls stores the calls of the run before its terminal event, so a + // later run maps the wire IDs the client answers. Nil stores nothing. + saveCalls func([]callRecord) error + saved bool +} + +// callRecord is a tool call a run streamed, as the thread stores it. +type callRecord struct { + Wire string `json:"wire"` + // Agent and ID are the runtime call: each agent numbers its own calls. + Agent string `json:"agent"` + ID string `json:"id"` + Frontend bool `json:"frontend,omitempty"` } // streamedMessage tracks one kind of streamed message (text or reasoning). @@ -143,7 +166,14 @@ func newResumeTranslator(sessionID, threadID, runID string, paused pausedCalls, for _, id := range paused.wireIDs { t.wireIDs[id] = true } + t.resolved = make(map[toolCallKey]bool) for _, p := range paused.pending { + if p.frontend { + // The client answers it with the resume: no result streams. + t.resolved[p.key] = true + t.calls = append(t.calls, &invocation{key: p.key, id: p.id, state: toolCallAnswered, frontend: true}) + continue + } call := &invocation{key: p.key, id: p.id, state: toolCallEnded, running: p.running || p.id == resumed, result: p.result} t.toolCalls[p.key] = call t.calls = append(t.calls, call) @@ -156,9 +186,43 @@ func newResumeTranslator(sessionID, threadID, runID string, paused pausedCalls, func newAbandonTranslator(sessionID, threadID, runID string, paused pausedCalls) *translator { t := newResumeTranslator(sessionID, threadID, runID, paused, "") t.abandoning = true + for _, call := range t.calls { + if call.frontend { + // Still the client's to answer, unless the run stores a result. + call.state = toolCallEnded + } + } return t } +// stored streams the answers stored before the run: the client's need no +// result, the calls it left get theirs. +func (t *translator) stored(a *answers) { + for _, wire := range a.answered { + if idx := slices.IndexFunc(t.calls, func(c *invocation) bool { return c.id == wire }); idx >= 0 { + t.calls[idx].state = toolCallAnswered + } + } + for _, p := range a.unanswered { + t.answerOnStart(p.wire, p.agent, p.id, unansweredToolResult) + } +} + +// answerOnStart streams content as the result of the call wire, stored before +// the run: a call of the paused run, or of an earlier run on the thread. +func (t *translator) answerOnStart(wire, agent, id, content string) { + idx := slices.IndexFunc(t.calls, func(c *invocation) bool { return c.id == wire }) + if idx < 0 { + // Not in toolCalls: the runtime may reuse its ID in this run. + t.wireIDs[wire] = true + t.calls = append(t.calls, &invocation{key: toolCallKey{agent, id}, id: wire}) + idx = len(t.calls) - 1 + } + call := t.calls[idx] + call.state, call.result = toolCallEnded, content + t.onStart = append(t.onStart, call) +} + // record keeps the result of a pending call that ran, from the events of its // parked run as it is drained. func (p *pausedCalls) record(event runtime.Event) { @@ -211,7 +275,7 @@ func (t *translator) wireID(agent, id string) string { func (t *translator) unansweredCalls() (running, idle int) { for _, call := range t.calls { switch { - case call.state == toolCallAnswered: + case call.state == toolCallAnswered, call.frontend: case call.running: running++ default: @@ -288,14 +352,23 @@ func (t *translator) translate(event runtime.Event) []events.Event { if call == nil { out, call = t.startToolCall(out, e.AgentName, id, e.ToolCall.Function.Name) } + // Known before the call is dispatched: an interrupt may come first. + if e.ToolDefinition != nil && e.ToolDefinition.ClientExecuted { + call.frontend = true + } if call.state == toolCallOpen && e.ToolCall.Function.Arguments != "" { out = append(out, events.NewToolCallArgsEvent(call.id, e.ToolCall.Function.Arguments)) } case *runtime.ToolCallEvent: + if key := (toolCallKey{e.AgentName, e.ToolCall.ID}); t.resolved[key] { + delete(t.resolved, key) + break + } out = t.dispatchToolCall(e.AgentName, e.ToolCall) if call := t.invocation(e.AgentName, e.ToolCall.ID); call != nil { - call.running = true + call.frontend = e.ToolDefinition.ClientExecuted + call.running = !call.frontend } case *runtime.ToolCallConfirmationEvent: @@ -365,7 +438,7 @@ func (t *translator) stop(reason string, finish chat.FinishReason) []events.Even return t.fail("run canceled", errorCodeCanceled) case runtime.TurnEndReasonError: return t.failWithLastError("run failed", errorCodeFailed) - case runtime.TurnEndReasonNormal: + case runtime.TurnEndReasonNormal, runtime.TurnEndReasonClientToolCalls: // The runtime ends a truncated or refused answer as a normal turn. switch finish { case chat.FinishReasonLength: @@ -396,31 +469,69 @@ func (t *translator) start(out []events.Event) []events.Event { } if t.abandoning { for _, call := range t.calls { + if call.frontend && call.result == "" { + continue + } out = t.answerToolCall(out, call, cmp.Or(call.result, abandonedToolResult)) } } + for _, call := range t.onStart { + out = t.answerToolCall(out, call, call.result) + } return out } func (t *translator) finish() []events.Event { out := t.closeMessages(t.start(nil)) - // A successful run leaves no call for the client to answer. + // A successful run leaves no call for the client to answer but its own. + var pending []string for _, call := range t.calls { + if call.frontend && call.state != toolCallAnswered { + pending = append(pending, call.id) + continue + } out = t.answerToolCall(out, call, missingToolResult) } + if err := t.save(); err != nil { + // The next run could not map the answers: the run did not succeed. + return append(out, t.fail("failed to store the tool calls of the run", errorCodeFailed)...) + } out = t.closeAll(out) // The run went on after this error. if t.lastError != nil { out = append(out, events.NewCustomEvent(customEventPrefix+t.lastError.Type, events.WithValue(t.lastError))) } t.done = true - return append(out, events.NewRunFinishedEvent(t.threadID, t.runID)) + if len(pending) == 0 { + return append(out, events.NewRunFinishedEvent(t.threadID, t.runID)) + } + return append(out, events.NewRunFinishedEventWithOptions(t.threadID, t.runID, events.WithOutcome(events.RunFinishedOutcome{ + Type: events.RunFinishedOutcomeTypeSuccess, + PendingToolCallIDs: pending, + }))) +} + +// save stores the calls the run streamed, if it streamed any, once. +func (t *translator) save() error { + if t.saveCalls == nil || len(t.calls) == 0 || t.saved { + return nil + } + t.saved = true + records := make([]callRecord, len(t.calls)) + for i, call := range t.calls { + records[i] = callRecord{Wire: call.id, Agent: call.key.agent, ID: call.key.id, Frontend: call.frontend} + } + return t.saveCalls(records) } // interrupt ends the run paused on in. Its pending tool calls are ended but // get no result: the resumed run sends them. func (t *translator) interrupt(interrupts []types.Interrupt) []events.Event { out := t.closeAll(t.start(nil)) + if err := t.save(); err != nil { + // The answers to its frontend calls could not be mapped after a restart. + slog.Warn("Failed to store the AG-UI tool calls of an interrupted run", "thread_id", t.threadID, "error", err) + } if t.lastError != nil { out = append(out, events.NewCustomEvent(customEventPrefix+t.lastError.Type, events.WithValue(t.lastError))) } @@ -429,6 +540,10 @@ func (t *translator) interrupt(interrupts []types.Interrupt) []events.Event { } func (t *translator) fail(message, code string) []events.Event { + // The client keeps the calls it saw, and may send their results again. + if err := t.save(); err != nil { + slog.Warn("Failed to store the AG-UI tool calls of a failed run", "thread_id", t.threadID, "error", err) + } out := t.closeAll(t.start(nil)) t.done = true return append(out, events.NewRunErrorEvent(message, events.WithErrorCode(code), events.WithRunID(t.runID))) diff --git a/pkg/runtime/client_tools_test.go b/pkg/runtime/client_tools_test.go new file mode 100644 index 0000000000..b126b57fef --- /dev/null +++ b/pkg/runtime/client_tools_test.go @@ -0,0 +1,134 @@ +package runtime + +import ( + "context" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/agent" + "github.com/docker/docker-agent/pkg/chat" + "github.com/docker/docker-agent/pkg/session" + "github.com/docker/docker-agent/pkg/team" + "github.com/docker/docker-agent/pkg/tools" +) + +// clientToolsProvider is a queueProvider that keeps what each call was sent. +type clientToolsProvider struct { + queueProvider + + mu sync.Mutex + requests [][]chat.Message + offered [][]tools.Tool +} + +func (p *clientToolsProvider) CreateChatCompletionStream(ctx context.Context, msgs []chat.Message, ts []tools.Tool) (chat.MessageStream, error) { + p.mu.Lock() + p.requests = append(p.requests, msgs) + p.offered = append(p.offered, ts) + p.mu.Unlock() + return p.queueProvider.CreateChatCompletionStream(ctx, msgs, ts) +} + +// A turn that calls a client tool and a server tool runs the server tool, +// records no result for the client call and stops for the client to answer; +// the next run sends the model the answer it was given. +func TestRunStream_ClientToolCallsEndTheRun(t *testing.T) { + t.Parallel() + + ran := 0 + serverTool := tools.Tool{ + Name: "lookup", + Parameters: map[string]any{"type": "object"}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + ran++ + return tools.ResultSuccess("found"), nil + }, + } + prov := &clientToolsProvider{queueProvider: queueProvider{id: "test/mock-model", streams: []chat.MessageStream{ + newStreamBuilder(). + AddToolCallName("c1", "pick_date").AddToolCallArguments("c1", `{}`). + AddToolCallName("s1", "lookup").AddToolCallArguments("s1", `{}`). + AddToolCallStopWithUsage(1, 1).Build(), + newStreamBuilder().AddContent("done").AddStopWithUsage(1, 1).Build(), + }}} + root := agent.New("root", "test", agent.WithModel(prov), + agent.WithToolSets(newStubToolSet(nil, []tools.Tool{serverTool}, nil))) + rt, err := NewLocalRuntime(t.Context(), team.New(team.WithAgents(root)), WithSessionCompaction(false), WithModelStore(mockModelStore{})) + require.NoError(t, err) + + sess := session.New(session.WithUserMessage("when?")) + sess.NonInteractive = true + sess.ToolsApproved = true + sess.ClientTools = []tools.Tool{ + {Name: "pick_date", Description: "Ask the user for a date"}, + {Name: "lookup", Description: "shadowed by the agent tool"}, + } + + var stopped *StreamStoppedEvent + var clientCalls []string + for ev := range rt.RunStream(t.Context(), sess) { + switch e := ev.(type) { + case *ErrorEvent: + t.Fatalf("unexpected error event: %s", e.Error) + case *ToolCallEvent: + if e.ToolDefinition.ClientExecuted { + clientCalls = append(clientCalls, e.ToolCall.ID) + } + case *ToolCallResponseEvent: + assert.NotEqual(t, "c1", e.ToolCallID, "the client answers its call") + case *StreamStoppedEvent: + stopped = e + } + } + + require.NotNil(t, stopped) + assert.Equal(t, TurnEndReasonClientToolCalls, stopped.Reason) + assert.Equal(t, []string{"c1"}, clientCalls) + assert.Equal(t, 1, ran, "the server tool of the batch runs") + require.Len(t, prov.offered, 1) + assert.Equal(t, []string{"lookup", "pick_date"}, toolNames(prov.offered[0])) + assert.NotNil(t, prov.offered[0][0].Handler, "the agent tool keeps its name") + assert.Equal(t, map[string]any{"type": "object", "properties": map[string]any{}}, prov.offered[0][1].Parameters) + + var results []string + for _, m := range sess.GetAllMessages() { + if m.Message.Role == chat.MessageRoleTool { + results = append(results, m.Message.ToolCallID) + } + } + assert.Equal(t, []string{"s1"}, results) + + sess.AddMessage(session.NewAgentMessage("root", &chat.Message{ + Role: chat.MessageRoleTool, ToolCallID: "c1", Content: "2026-12-25", + })) + for ev := range rt.RunStream(t.Context(), sess) { + if e, ok := ev.(*StreamStoppedEvent); ok { + stopped = e + } + } + assert.Equal(t, TurnEndReasonNormal, stopped.Reason) + require.Len(t, prov.requests, 2) + var answer *chat.Message + for i, m := range prov.requests[1] { + if m.Role == chat.MessageRoleTool && m.ToolCallID == "c1" { + answer = &prov.requests[1][i] + } + assert.NotEqual(t, "No result provided", m.Content) + } + require.NotNil(t, answer) + assert.Equal(t, "2026-12-25", answer.Content) +} + +// Client tools are offered to the session they were given to only. +func TestClientTools_NotOfferedToSubSessions(t *testing.T) { + t.Parallel() + + parent := session.New() + parent.ClientTools = []tools.Tool{{Name: "pick_date"}} + child := session.New(session.WithParentID(parent.ID)) + assert.Empty(t, child.ClientTools) + assert.Empty(t, appendClientTools(nil, child.ClientTools)) +} diff --git a/pkg/runtime/hooks.go b/pkg/runtime/hooks.go index 168e73cb92..0290b7b84e 100644 --- a/pkg/runtime/hooks.go +++ b/pkg/runtime/hooks.go @@ -158,7 +158,7 @@ func (r *LocalRuntime) executeTurnStartHooks(ctx context.Context, sess *session. } // Reason values reported in [hooks.Input.Reason] when [hooks.EventTurnEnd] -// fires. The same values (including the exported trio below, plus +// fires. The same values (including the exported ones below, plus // hook_blocked/loop_detected/budget_exceeded) are also reported verbatim in // [StreamStoppedEvent.Reason] — loop.go passes its turnEndReason* // classification straight through to StreamStopped. The runtime guarantees @@ -178,6 +178,10 @@ const ( // still-"normal" exit to canceled when ctx is done; a cancelled model // call may report "error" instead. TurnEndReasonCanceled = "canceled" + // TurnEndReasonClientToolCalls — the model called client-executed + // tools ([session.Session.ClientTools]): the run stops, leaving their + // calls for the client application to answer in a later run. + TurnEndReasonClientToolCalls = "client_tool_calls" ) // The remaining turnEndReason values below also end up in diff --git a/pkg/runtime/loop.go b/pkg/runtime/loop.go index 0f116490be..9b768457cf 100644 --- a/pkg/runtime/loop.go +++ b/pkg/runtime/loop.go @@ -1243,6 +1243,11 @@ func (r *LocalRuntime) runTools(ctx context.Context, t *turn, answer *modelAnswe return turnExit, turnEndReasonHookBlocked, true } + // Before the steered messages: the client answers its calls first. + if awaitsClient(sess, dispatchCalls, agentTools, messageCountBeforeTools) { + return turnExit, TurnEndReasonClientToolCalls, true + } + // Record completed tool work for the next turn's empty-reply warning. ls.PrevTurnMadeToolCalls = len(answer.Calls) > 0 @@ -1261,6 +1266,34 @@ func (r *LocalRuntime) runTools(ctx context.Context, t *turn, answer *modelAnswe return turnContinue, "", false } +// awaitsClient reports whether a call of the batch to a client-executed tool +// has no result yet: the client application answers it in a later run. The +// result may also come while the batch runs, e.g. with a tool approval. +func awaitsClient(sess *session.Session, calls []tools.ToolCall, agentTools []tools.Tool, since int) bool { + client := make(map[string]bool) + for _, t := range agentTools { + if t.ClientExecuted { + client[t.Name] = true + } + } + if len(client) == 0 { + return false + } + answered := make(map[string]bool) + own := sess.OwnMessages() + for _, m := range own[min(since, len(own)):] { + if m.Message.Role == chat.MessageRoleTool { + answered[m.Message.ToolCallID] = true + } + } + for _, tc := range calls { + if client[tc.Function.Name] && !answered[tc.ID] { + return true + } + } + return false +} + // afterAnswer runs what follows an answer the model stopped on: structured // output enforcement, stop hooks, a completion route or forced handoff, then // input queued meanwhile. It returns whether the loop goes on and the reason @@ -1592,6 +1625,7 @@ func (r *LocalRuntime) getTools(ctx context.Context, sess *session.Session, a *a // collision with the reserved internal tool or an uncompilable schema // must fail the turn loudly, not mask one of the two tools. agentTools, err = appendStructuredOutputTool(agentTools, sess, a) + agentTools = appendClientTools(agentTools, sess.ClientTools) } if err != nil { slog.ErrorContext(ctx, "Failed to get agent tools", "agent", a.Name(), "error", err) @@ -1605,6 +1639,29 @@ func (r *LocalRuntime) getTools(ctx context.Context, sess *session.Session, a *a return agentTools, nil } +// appendClientTools offers the session's client-executed tools. A tool of +// the agent keeps its name: a client tool never shadows it. +func appendClientTools(agentTools, client []tools.Tool) []tools.Tool { + if len(client) == 0 { + return agentTools + } + taken := make(map[string]bool, len(agentTools)) + for _, t := range agentTools { + taken[t.Name] = true + } + for _, t := range client { + if taken[t.Name] { + continue + } + t.ClientExecuted = true + if t.Parameters == nil { + t.Parameters = map[string]any{"type": "object", "properties": map[string]any{}} + } + agentTools = append(agentTools, t) + } + return agentTools +} + // configureToolsetHandlers installs stable request-scoped dispatchers. func (r *LocalRuntime) configureToolsetHandlers(a *agent.Agent) { for _, toolset := range a.ToolSets() { diff --git a/pkg/runtime/toolexec/client_executed_test.go b/pkg/runtime/toolexec/client_executed_test.go new file mode 100644 index 0000000000..b083f6998d --- /dev/null +++ b/pkg/runtime/toolexec/client_executed_test.go @@ -0,0 +1,131 @@ +package toolexec_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/agent" + "github.com/docker/docker-agent/pkg/hooks" + "github.com/docker/docker-agent/pkg/runtime/toolexec" + "github.com/docker/docker-agent/pkg/session" + "github.com/docker/docker-agent/pkg/tools" +) + +func clientCall() []tools.ToolCall { + return []tools.ToolCall{{ID: "c1", Function: tools.FunctionCall{Name: "pick_date", Arguments: `{}`}}} +} + +var clientTool = tools.Tool{Name: "pick_date", ClientExecuted: true} + +// A client-executed call is handed over without a prompt, even where every +// other call would be asked about or denied for lack of a user. +func TestDispatcher_ClientExecutedCallIsDeferredWithoutApproval(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + sess func() *session.Session + }{ + {"interactive", func() *session.Session { return session.New() }}, + {"non-interactive", func() *session.Session { + s := session.New() + s.NonInteractive = true + return s + }}, + {"non-interactive with tool approval", func() *session.Session { + s := session.New() + s.NonInteractive = true + s.ToolApproval = true + return s + }}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + a := newAgent() + hd := &stubHookDispatcher{} + d := &toolexec.Dispatcher{ + AgentFor: func(*session.Session) *agent.Agent { return a }, + Hooks: hd, + } + em := &captureEmitter{} + sess := tc.sess() + + d.Process(t.Context(), sess, clientCall(), []tools.Tool{clientTool}, em) + + require.Len(t, em.calls, 1) + assert.Equal(t, "c1", em.calls[0].ID) + assert.Empty(t, em.responses, "the client answers the call") + assert.Empty(t, em.confirmations) + assert.Empty(t, sess.OwnMessages(), "no result is recorded") + assert.Equal(t, []approvalRecord{{Decision: "allow", Source: toolexec.ApprovalSourceClientExecuted}}, hd.approvals) + }) + } +} + +func TestDispatcher_ClientExecutedCallHonoursDenyRules(t *testing.T) { + t.Parallel() + a := newAgent() + d := &toolexec.Dispatcher{ + AgentFor: func(*session.Session) *agent.Agent { return a }, + Permissions: func(*session.Session) []toolexec.NamedChecker { + return []toolexec.NamedChecker{{Checker: newDenyChecker("pick_date"), Source: "test policy"}} + }, + } + em := &captureEmitter{} + + d.Process(t.Context(), session.New(), clientCall(), []tools.Tool{clientTool}, em) + + assert.Empty(t, em.calls) + require.Len(t, em.responses, 1) + assert.True(t, em.responses[0].IsError) + assert.Contains(t, em.responses[0].Output, "denied by test policy") +} + +// The safety mode weighs what the server runs: it neither denies a +// client-executed call nor skips the pre_tool_use hooks for it. +var everyPolicy = []session.SafetyPolicy{ + "", session.SafetyPolicyStrict, session.SafetyPolicyBalanced, + session.SafetyPolicyRestricted, session.SafetyPolicyAutonomous, +} + +func TestDispatcher_ClientExecutedCallIsNotDeniedByTheMode(t *testing.T) { + t.Parallel() + for _, policy := range everyPolicy { + t.Run(string(policy), func(t *testing.T) { + t.Parallel() + a := newAgent() + d := &toolexec.Dispatcher{AgentFor: func(*session.Session) *agent.Agent { return a }} + em := &captureEmitter{} + + d.Process(t.Context(), session.New(session.WithSafetyPolicy(policy), session.WithNonInteractive(true)), clientCall(), []tools.Tool{clientTool}, em) + + require.Len(t, em.calls, 1) + assert.Empty(t, em.responses) + }) + } +} + +func TestDispatcher_ClientExecutedCallHonoursPreToolUseDeny(t *testing.T) { + t.Parallel() + for _, policy := range everyPolicy { + t.Run(string(policy), func(t *testing.T) { + t.Parallel() + a := newAgent() + hd := &stubHookDispatcher{on: map[hooks.EventType]*hooks.Result{ + hooks.EventPreToolUse: {Allowed: false, Decision: hooks.DecisionDeny, Message: "not today"}, + }} + d := &toolexec.Dispatcher{ + AgentFor: func(*session.Session) *agent.Agent { return a }, + Hooks: hd, + } + em := &captureEmitter{} + + d.Process(t.Context(), session.New(session.WithSafetyPolicy(policy)), clientCall(), []tools.Tool{clientTool}, em) + + assert.Empty(t, em.calls) + require.Len(t, em.responses, 1) + assert.True(t, em.responses[0].IsError) + }) + } +} diff --git a/pkg/runtime/toolexec/dispatcher.go b/pkg/runtime/toolexec/dispatcher.go index f425078995..314de100ae 100644 --- a/pkg/runtime/toolexec/dispatcher.go +++ b/pkg/runtime/toolexec/dispatcher.go @@ -76,6 +76,9 @@ const ( // this guard the dispatcher would block on the Resume channel // forever. ApprovalSourceNonInteractiveDeny = "non_interactive_deny" + // ApprovalSourceClientExecuted is recorded when a call the safety mode + // asks about is handed to the client application that runs it. + ApprovalSourceClientExecuted = "client_executed" ) // CallOutcome captures the verdicts of a single tool invocation as @@ -362,7 +365,7 @@ func (d *Dispatcher) Process(ctx context.Context, sess *session.Session, calls [ defer cancelBatch(nil) var stopOnce sync.Once - outcomes := concurrent.MapSlice(calls, func(tc tools.ToolCall) CallOutcome { + run := func(tc tools.ToolCall) CallOutcome { c := d.newCall(sess, em, a, tc, toolByName) outcome := c.run(batchCtx) switch { @@ -372,7 +375,12 @@ func (d *Dispatcher) Process(ctx context.Context, sess *session.Session, calls [ stopOnce.Do(func() { cancelBatch(errBatchStoppedByHook) }) } return outcome - }) + } + // Client calls first: the client gets them, or their refusal, before an + // approval of the batch pauses the run. + client, server := splitClientCalls(calls, toolByName) + outcomes := concurrent.MapSlice(client, run) + outcomes = append(outcomes, concurrent.MapSlice(server, run)...) for _, outcome := range outcomes { if outcome.StopRun { @@ -382,6 +390,17 @@ func (d *Dispatcher) Process(ctx context.Context, sess *session.Session, calls [ return false, "" } +func splitClientCalls(calls []tools.ToolCall, toolByName map[string]tools.Tool) (client, server []tools.ToolCall) { + for _, tc := range calls { + if toolByName[tc.Function.Name].ClientExecuted { + client = append(client, tc) + } else { + server = append(server, tc) + } + } + return client, server +} + // newCall assembles a [call] for a single tool invocation, looking up the // referenced tool in the agent's toolset. When the tool isn't found, the // call is marked unavailable and tool.Name is set to the requested name @@ -563,7 +582,10 @@ func (c *call) process(ctx context.Context) CallOutcome { // Pick the executor declared by the resolved tool definition. Names are // model-facing identifiers and never grant access to host-owned handlers. var runTool func() CallOutcome - if c.tool.RuntimeHandler != "" { + switch { + case c.tool.ClientExecuted: + runTool = c.deferToClient + case c.tool.RuntimeHandler != "": handler, ok := c.d.Handlers[c.tool.RuntimeHandler] if !ok { msg := fmt.Sprintf("Runtime handler %q is unavailable.", c.tool.RuntimeHandler) @@ -574,13 +596,12 @@ func (c *call) process(ctx context.Context) CallOutcome { runTool = func() CallOutcome { return c.runHandler(ctx, handler) } - } else { - if c.tool.Handler == nil { - msg := fmt.Sprintf("Tool %q has no handler.", c.tool.Name) - c.errorResponse(ctx, msg) - span.SetStatus(codes.Error, msg) - return CallOutcome{} - } + case c.tool.Handler == nil: + msg := fmt.Sprintf("Tool %q has no handler.", c.tool.Name) + c.errorResponse(ctx, msg) + span.SetStatus(codes.Error, msg) + return CallOutcome{} + default: runTool = func() CallOutcome { return c.runToolset(ctx) } @@ -629,6 +650,11 @@ func (c *call) approveAndRun(ctx context.Context, runTool func() CallOutcome) Ca // Stage 1: custom rules + (mode × label) table. decision := c.permissionDecision() + if c.tool.ClientExecuted && decision.Reason == ReasonMode { + // The mode weighs what the server runs; the client runs this call. + // Explicit rules and pre_tool_use hooks still apply. + decision.Outcome = OutcomeAsk + } switch decision.Outcome { case OutcomeAllow: @@ -992,6 +1018,11 @@ func (c *call) confirmationMutex() *sync.Mutex { // preempting --yolo, and letting a policy-level permission_request // hook auto-allow the call would unwind that protection. func (c *call) askUser(ctx context.Context, runTool func() CallOutcome) CallOutcome { + if c.tool.ClientExecuted { + // The client application runs the call: nobody is asked twice. + c.notifyApproval(ctx, ApprovalDecisionAllow, ApprovalSourceClientExecuted) + return runTool() + } var hookMeta map[string]string if !c.mandatoryAsk() && (c.preYoloResult == nil || c.preYoloResult.Decision != hooks.DecisionAsk) { outcome, handled, meta := c.runPermissionRequestHook(ctx, runTool) @@ -1499,6 +1530,13 @@ func (c *call) postHook(ctx context.Context, res *tools.ToolCallResult) (stop bo return true, result.Message } +// deferToClient hands the call to the client application, which answers it +// in a later run: no result is recorded. +func (c *call) deferToClient() CallOutcome { + c.em.EmitToolCall(c.tc, c.tool, c.a.Name()) + return CallOutcome{} +} + func (c *call) startOutOfBand() { if c.started { return diff --git a/pkg/session/branch.go b/pkg/session/branch.go index 206868acd6..b16d9f0b24 100644 --- a/pkg/session/branch.go +++ b/pkg/session/branch.go @@ -109,6 +109,7 @@ func (s *Session) Clone() *Session { ExcludedTools: slices.Clone(s.ExcludedTools), AllowedTools: slices.Clone(s.AllowedTools), ExtraToolSets: slices.Clone(s.ExtraToolSets), + ClientTools: slices.Clone(s.ClientTools), DisableStructuredOutput: s.DisableStructuredOutput, AgentName: s.AgentName, allowAgentHandoffs: s.allowAgentHandoffs, diff --git a/pkg/session/session.go b/pkg/session/session.go index 05a9f43ab1..313a79cf82 100644 --- a/pkg/session/session.go +++ b/pkg/session/session.go @@ -428,6 +428,11 @@ type Session struct { // filter (the skill explicitly asked for them). ExtraToolSets []tools.ToolSet `json:"-"` + // ClientTools are tools the client application runs, offered to the + // agents of this session only: sub-sessions do not inherit them. An agent + // tool of the same name wins. Not persisted: set per run. + ClientTools []tools.Tool `json:"-"` + // DisableStructuredOutput, when true, exempts this session from tool-mode // structured-output enforcement: the internal output tool is not offered // and plain-text finals are accepted. Used by fork-mode skill diff --git a/pkg/tools/tools.go b/pkg/tools/tools.go index b47f92fdf7..a52e91bfbd 100644 --- a/pkg/tools/tools.go +++ b/pkg/tools/tools.go @@ -182,6 +182,10 @@ type Tool struct { //nolint:recvcheck // JSON marshaling needs a value receiver // and its toolsets can; the runtime may auto-approve the launch, while the // MCP surface must not advertise an agent containing one as read-only. Delegation bool `json:"-"` + // ClientExecuted marks a tool the client application runs: the runtime + // asks no approval, records no result and ends the turn once the calls + // of its batch have run, leaving the client to answer. + ClientExecuted bool `json:"-"` // AllowRepeatedCalls exempts successful calls from duplicate-loop detection. AllowRepeatedCalls bool `json:"-"` AddDescriptionParameter bool `json:"-"` From b59a0b81dfc692b46f03e84a2b3e220521046b7f Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 10:00:42 +0100 Subject: [PATCH 02/14] fix(ag-ui): harden frontend tool input and resume ordering - Store frontend tool results first on resume, so a failed store leaves no grant persisted and no elicitation answer delivered, and the same resume replayed goes through. - Reject frontend tool names that collide with the agent's catalog tools or with the reserved structured output tool. - Compile tool parameter schemas at the boundary (invalid schemas and remote $refs get a 400) and accept an empty schema as no parameters, as AG-UI specifies. - Document that ask rules don't prompt for client-executed calls and that allow/ask rules skip pre_tool_use hooks for them. Signed-off-by: deka --- docs/configuration/permissions/index.md | 2 +- docs/features/ag-ui/index.md | 13 +- pkg/agui/frontend_tools.go | 3 +- pkg/agui/frontend_tools_test.go | 196 +++++++++++++++++++++++- pkg/agui/input.go | 20 ++- pkg/agui/server.go | 19 ++- pkg/agui/server_test.go | 7 +- 7 files changed, 238 insertions(+), 22 deletions(-) diff --git a/docs/configuration/permissions/index.md b/docs/configuration/permissions/index.md index 1a9865b99d..31f7e35c43 100644 --- a/docs/configuration/permissions/index.md +++ b/docs/configuration/permissions/index.md @@ -316,7 +316,7 @@ Permissions work alongside [hooks](../hooks/index.md). The evaluation order is: 3. Run **`preempt_yolo` pre_tool_use hooks** — legacy mandatory checks, with their existing session-grant exception 4. Check **deny** patterns — if matched, tool is blocked 5. Check **allow** patterns — if matched, tool is auto-approved -6. Check **ask** patterns — if matched, the user is prompted directly, skipping the default `pre_tool_use` lane +6. Check **ask** patterns — if matched, the user is prompted directly, skipping the default `pre_tool_use` lane; a call the client application runs is handed to it without a prompt (step 9) 7. If no rule matched, apply the **[safety mode](#safety-modes)** to the call's safety label — may auto-approve (or, under `restricted`, deny). A call the client application runs (an [AG-UI frontend tool](../../features/ag-ui/index.md#frontend-tools)) is routed to "ask" instead 8. On a mode "ask", run **pre_tool_use hooks** — hooks can allow, deny, or ask 9. If no decision, **ask user** for confirmation; a call the client application runs is handed to it without a prompt diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index f79b67e874..d71ad9a58f 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -208,7 +208,7 @@ nothing: the same `threadId` still accepts a valid request. | `threadId` | Required, at most 256 bytes. Starts with a letter or digit and contains only letters, digits, `.`, `_` and `-` (a UUID qualifies). | | `runId` | Required, at most 256 bytes. | | `messages` | Every message needs an `id` of at most 256 bytes and a known `role`. The history must end with at least one user message, or with tool results in the last turn. Trailing user messages need distinct `id`s and non-empty text content (a string, or a list of `text` parts). Tool results of the last turn (since the user messages that started it) need a `toolCallId` (distinct, at most 256 bytes) and text content; `error`, when set, must be a string. The `toolCallId` must name a call of the thread. The content of earlier messages is not read. | -| `tools` | At most 128 tools, 256 KiB in all. Each tool is an object with a `name` of 1 to 64 letters, digits, `_` or `-`, distinct and not the name of a tool of the entry agent or of its handoff targets; a `description` of at most 8 KiB; and `parameters`, absent or a JSON schema with `"type": "object"`. See [Frontend tools](#frontend-tools). | +| `tools` | At most 128 tools, 256 KiB in all. Each tool is an object with a `name` of 1 to 64 letters, digits, `_` or `-`, distinct, not `__structured_output__` and not the name of a tool of the entry agent or of its handoff targets, catalog tools included; a `description` of at most 8 KiB; and `parameters`, absent, empty (no parameters, as when absent) or a valid JSON schema with `"type": "object"` whose `$ref`s stay in the document. See [Frontend tools](#frontend-tools). | | `state` | Must be empty (`null`, `{}`): shared state is not supported. | | `resume` | Only with `--tool-approval` or `--elicitation`, to resolve interrupts: see [Tool approval](#tool-approval-interrupts) and [Elicitation](#elicitation-interrupts). Each entry needs an `interruptId` (distinct, at most 256 bytes) and a `status` of `resolved`, with a `payload` matching the interrupt's `responseSchema`, or `cancelled`, without a `payload`. | | `context`, `forwardedProps` | Accepted and ignored. | @@ -540,8 +540,8 @@ in the next run. - **Who gets them.** The tools of a run are offered to the agent the thread runs: the entry agent and the agents it hands off to. Sub-agents reached through `transfer_task` and background agents don't get them. A tool name - that is already a tool of one of those agents is rejected with - `400 Bad Request`. + that is already a tool of one of those agents (catalog tools included) is + rejected with `400 Bad Request`. - **Per run.** The thread does not store the tools: send them on every run that offers them. - **The call.** The run streams `TOOL_CALL_START`, `TOOL_CALL_ARGS` and @@ -574,8 +574,11 @@ in the next run. The server does not run a frontend call, so it never asks for approval and the [tool safety](#tool-safety) policy, which weighs what the server runs, neither denies it nor skips its hooks: running it is the application's -decision. Under every policy, a permission deny rule and `pre_tool_use` hooks -still refuse it. A refused call gets an error `TOOL_CALL_RESULT` in the stream +decision. An `ask:` permission rule, a `pre_tool_use` hook that answers `ask` +and `permission_request` hooks don't prompt for it either. Under every policy, +a permission deny rule still refuses it, and so do `pre_tool_use` hooks unless +an `allow:` or `ask:` rule matched it (such a match skips them, as for any +tool). A refused call gets an error `TOOL_CALL_RESULT` in the stream and is not pending. ### With tool approval diff --git a/pkg/agui/frontend_tools.go b/pkg/agui/frontend_tools.go index 8ac0f07b78..14227f64ae 100644 --- a/pkg/agui/frontend_tools.go +++ b/pkg/agui/frontend_tools.go @@ -198,6 +198,7 @@ func (s *server) storeAnswers(ctx context.Context, sess *session.Session, thread // checkToolNames rejects a frontend tool named like a tool of an agent that // runs in the thread's session: the entry agent and its handoff targets. +// Catalog tools count whether or not a model of the agent can search them. func (s *server) checkToolNames(ctx context.Context, frontend []tools.Tool) (int, error) { if len(frontend) == 0 { return 0, nil @@ -212,7 +213,7 @@ func (s *server) checkToolNames(ctx context.Context, frontend []tools.Tool) (int for len(queue) > 0 { a := queue[0] queue = queue[1:] - list, err := a.Tools(ctx) + list, err := a.ToolsWithCatalog(ctx) if err != nil { slog.ErrorContext(ctx, "Failed to list agent tools", "agent", a.Name(), "error", err) return http.StatusInternalServerError, errors.New("failed to list the tools of the agent") diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index 5999f38157..67c2655171 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "log/slog" "net/http" @@ -99,10 +100,10 @@ func (p *scriptedProvider) toolResults(n int) []string { return out } -func (p *scriptedProvider) offeredTo(n int) []string { +func (p *scriptedProvider) firstOffer() []string { p.mu.Lock() defer p.mu.Unlock() - return p.offered[n] + return p.offered[0] } func pendingOf(t *testing.T, events []wireEvent) []any { @@ -144,7 +145,7 @@ func TestFrontendTools_CallIsLeftToTheClient(t *testing.T) { }, render(events)) assert.Equal(t, []any{"call-1"}, pendingOf(t, events)) assert.Equal(t, []string{"call-1"}, pendingToolCalls(events)) - assert.Equal(t, []string{"pick_date"}, prov.offeredTo(0)) + assert.Equal(t, []string{"pick_date"}, prov.firstOffer()) assert.Equal(t, 1, prov.callCount()) // The next run brings the result and no prompt. @@ -597,8 +598,8 @@ func TestFrontendTools_NotOfferedToSubAgents(t *testing.T) { server := startServer(t, team.New(team.WithAgents(root, child)), session.NewInMemorySessionStore(), RunOptions{}) server.run(t, frontendInput("thread-1", "run-1", userMsg("u1", "Research"))) - assert.Contains(t, rootProv.offeredTo(0), "pick_date") - assert.NotContains(t, childProv.offeredTo(0), "pick_date") + assert.Contains(t, rootProv.firstOffer(), "pick_date") + assert.NotContains(t, childProv.firstOffer(), "pick_date") } // Every agent numbers its parsed calls from call_0: a sub-agent's call with @@ -797,3 +798,188 @@ func TestFrontendTools_WithAnElicitation(t *testing.T) { }) } } + +// failingAnswerStore fails AddMessage for tool results while fail is set, +// and UpdateSession while failUpdate is set. +type failingAnswerStore struct { + session.Store + + fail atomic.Bool + failUpdate atomic.Bool +} + +func (s *failingAnswerStore) UpdateSession(ctx context.Context, sess *session.Session) error { + if s.failUpdate.Load() { + return errors.New("disk full") + } + return s.Store.UpdateSession(ctx, sess) +} + +func (s *failingAnswerStore) AddMessage(ctx context.Context, sessionID string, msg *session.Message) (int64, error) { + if s.fail.Load() && msg.Message.Role == chat.MessageRoleTool { + return 0, errors.New("disk full") + } + return s.Store.AddMessage(ctx, sessionID, msg) +} + +// Answers that cannot be stored leave the resume unapplied: no grant, no +// elicitation answer delivered, and the same resume replayed goes through. +func TestFrontendTools_AnswersNotStoredLeaveTheResumeUnapplied(t *testing.T) { + t.Parallel() + + t.Run("grant", func(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c2", "lookup", `{}`), call("c1", "pick_date", `{}`)), text("Booked")) + store := &failingAnswerStore{Store: sqliteStore(t)} + server := approvalServer(t, prov, store, echoTool(&executions)) + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + interrupt := interruptOf(t, events) + require.Equal(t, "c2", interrupt["toolCallId"], body) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c2", "lookup"), assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25")} + resume := []map[string]any{resolved(interrupt["id"].(string), decision("approve-in-context"))} + input := inputWith("thread-1", "run-2", []any{pickDate}, resume, history...) + + store.fail.Store(true) + status, _, body := server.post(t, input) + require.Equal(t, http.StatusInternalServerError, status, body) + assert.Contains(t, body, "still pending") + run, parked := server.srv.approvals.pending("thread-1") + require.True(t, parked) + assert.Empty(t, run.sess.Permissions) + stored, err := store.GetSession(t.Context(), sessionIDFor("thread-1")) + require.NoError(t, err) + assert.Empty(t, stored.Permissions) + assert.Zero(t, executions.Load()) + + store.fail.Store(false) + lines := server.run(t, input) + assert.Equal(t, "RUN_FINISHED runId=run-2 threadId=thread-1", lines[len(lines)-1]) + assert.EqualValues(t, 1, executions.Load()) + assert.Equal(t, []string{"c1: 2026-12-25", "c2: sunny"}, prov.toolResults(1)) + }) + + // The answers are stored before the grant fails: the replay finds them as + // history and each reaches the model once. + t.Run("grant after the answers", func(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c2", "lookup", `{}`), call("c1", "pick_date", `{}`)), text("Booked")) + store := &failingAnswerStore{Store: sqliteStore(t)} + server := approvalServer(t, prov, store, echoTool(&executions)) + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + interrupt := interruptOf(t, events) + require.Equal(t, "c2", interrupt["toolCallId"], body) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c2", "lookup"), assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25")} + resume := []map[string]any{resolved(interrupt["id"].(string), decision("approve-in-context"))} + input := inputWith("thread-1", "run-2", []any{pickDate}, resume, history...) + + store.failUpdate.Store(true) + status, _, body := server.post(t, input) + require.Equal(t, http.StatusInternalServerError, status, body) + assert.Contains(t, body, "failed to store the grant") + _, parked := server.srv.approvals.pending("thread-1") + require.True(t, parked) + assert.Zero(t, executions.Load()) + + store.failUpdate.Store(false) + lines := server.run(t, input) + assert.Equal(t, "RUN_FINISHED runId=run-2 threadId=thread-1", lines[len(lines)-1]) + assert.EqualValues(t, 1, executions.Load()) + assert.Equal(t, []string{"c1: 2026-12-25", "c2: sunny"}, prov.toolResults(1)) + }) + + t.Run("elicitation", func(t *testing.T) { + t.Parallel() + + prov := script(calls(call("c2", "ask", `{}`), call("c1", "pick_date", `{}`)), text("Booked")) + store := &failingAnswerStore{Store: session.NewInMemorySessionStore()} + server := startServer(t, singleAgentTeam(prov, dagent.WithTools(askTool(formParams()))), store, RunOptions{Elicitation: true}) + server.srv.approvals.hold = time.Hour + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + interrupt := interruptOf(t, events) + require.Equal(t, "input_required", interrupt["reason"], body) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c2", "ask"), assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25")} + resume := []map[string]any{resolved(interrupt["id"].(string), elicitationAnswerOf("accept", map[string]any{"name": "Ada"}))} + input := inputWith("thread-1", "run-2", []any{pickDate}, resume, history...) + + store.fail.Store(true) + status, _, body := server.post(t, input) + require.Equal(t, http.StatusInternalServerError, status, body) + _, parked := server.srv.approvals.pending("thread-1") + require.True(t, parked) + + store.fail.Store(false) + _, events, body = server.post(t, input) + lines := render(events) + assert.Contains(t, lines, `TOOL_CALL_RESULT content=accept {"name":"Ada"} messageId=c2-result role=tool toolCallId=c2`, body) + assert.NotContains(t, strings.Join(lines, "\n"), "answered after its tool stopped waiting") + assert.Equal(t, "RUN_FINISHED runId=run-2 threadId=thread-1", lines[len(lines)-1], lines) + assert.ElementsMatch(t, []string{"c1: 2026-12-25", `c2: accept {"name":"Ada"}`}, prov.toolResults(1)) + }) +} + +// The schemas AG-UI clients build are accepted: zod-to-json-schema (draft-07), +// zod 4 (2020-12), and an empty schema, which means no parameters. +func TestFrontendTools_AcceptsClientSchemas(t *testing.T) { + t.Parallel() + + prov := script(text("Hi")) + server := startServer(t, singleAgentTeam(prov), session.NewInMemorySessionStore(), RunOptions{}) + + var offered []any + for name, raw := range map[string]string{ + "zod3": `{"type":"object","properties":{"city":{"type":"string"},"days":{"type":"array","items":{"type":"number","minimum":1}},` + + `"home":{"type":"object","properties":{"x":{"type":"string"}}},"work":{"$ref":"#/properties/home"}},` + + `"required":["city"],"additionalProperties":false,"$schema":"http://json-schema.org/draft-07/schema#"}`, + "zod4": `{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"unit":{"type":"string","enum":["c","f"]},` + + `"note":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["unit"],"additionalProperties":false}`, + "zod3defs": `{"type":"object","properties":{"pair":{"type":"array","minItems":2,"maxItems":2,"items":[{"type":"string"},{"type":"number"}]},` + + `"a":{"$ref":"#/definitions/addr"},"b":{"type":["string","null"]}},"definitions":{"addr":{"type":"object"}},` + + `"$schema":"http://json-schema.org/draft-07/schema#"}`, + "zod4defs": `{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://app.example/tool.json","type":"object",` + + `"properties":{"pair":{"type":"array","prefixItems":[{"type":"string"},{"type":"number"}]},"a":{"$ref":"#/$defs/addr"},` + + `"c":{"const":"x"},"d":{"type":"string","format":"date-time"}},"$defs":{"addr":{"type":"object"}}}`, + "extension": `{"type":"object","properties":{"x":{"type":"string","nullable":true,"x-ui":"picker"}}}`, + "empty": `{}`, + } { + var params map[string]any + require.NoError(t, json.Unmarshal([]byte(raw), ¶ms)) + offered = append(offered, map[string]any{"name": name, "description": name, "parameters": params}) + } + + status, _, body := server.post(t, inputWith("thread-1", "run-1", offered, nil, userMsg("u1", "Hi"))) + require.Equal(t, http.StatusOK, status, body) + assert.Subset(t, prov.firstOffer(), []string{"zod3", "zod3defs", "zod4", "zod4defs", "extension", "empty"}) +} + +// catalogToolSet lists no tool: its tools are reached through hosted tool +// search only. +type catalogToolSet struct{ catalog []tools.Tool } + +func (catalogToolSet) Tools(context.Context) ([]tools.Tool, error) { return nil, nil } + +func (c catalogToolSet) CatalogTools(context.Context) ([]tools.Tool, error) { return c.catalog, nil } + +// A catalog tool is a tool of the agent too, searchable or not by its model: +// the runtime would otherwise drop the frontend tool that takes its name. +func TestFrontendTools_RejectsACatalogToolName(t *testing.T) { + t.Parallel() + + prov := script(text("Hi")) + root := dagent.New("root", "test", dagent.WithModel(prov), dagent.WithToolSets(catalogToolSet{catalog: []tools.Tool{{Name: "deploy", Description: "d"}}})) + server := startServer(t, team.New(team.WithAgents(root)), session.NewInMemorySessionStore(), RunOptions{}) + + status, _, body := server.post(t, inputWith("thread-1", "run-1", []any{map[string]any{"name": "deploy"}}, nil, userMsg("u1", "Hi"))) + assert.Equal(t, http.StatusBadRequest, status) + assert.Contains(t, body, `tools[0]: name \"deploy\" is a tool of agent \"root\"`) + assert.Zero(t, prov.callCount()) +} diff --git a/pkg/agui/input.go b/pkg/agui/input.go index 97f2529c6c..4ebc63aba5 100644 --- a/pkg/agui/input.go +++ b/pkg/agui/input.go @@ -10,9 +10,11 @@ import ( "strings" "github.com/ag-ui-protocol/ag-ui/sdks/community/go/pkg/core/types" + "github.com/google/jsonschema-go/jsonschema" "github.com/docker/docker-agent/pkg/toolapproval" "github.com/docker/docker-agent/pkg/tools" + "github.com/docker/docker-agent/pkg/tools/builtin/structuredoutput" ) const maxIDLength = 256 @@ -249,6 +251,9 @@ func decodeTools(raw json.RawMessage) ([]tools.Tool, error) { if !toolNamePattern.MatchString(ft.Name) { return nil, fmt.Errorf("tools[%d]: name must be 1 to 64 letters, digits, '_' or '-'", i) } + if ft.Name == structuredoutput.ToolName { + return nil, fmt.Errorf("tools[%d]: name %q is reserved", i, ft.Name) + } if seen[ft.Name] { return nil, fmt.Errorf("tools[%d]: duplicate name %q", i, ft.Name) } @@ -265,7 +270,10 @@ func decodeTools(raw json.RawMessage) ([]tools.Tool, error) { return out, nil } -// toolParameters reads a JSON schema for an object; absent means no parameters. +// toolParameters reads a JSON schema for an object. Absent or empty means no +// parameters: AG-UI gives both the same meaning. The schema is compiled here +// rather than refused by the provider after the thread changed; remote $refs +// do not compile (no loader). func toolParameters(raw json.RawMessage) (any, error) { if len(raw) == 0 || string(raw) == "null" { return nil, nil @@ -274,9 +282,19 @@ func toolParameters(raw json.RawMessage) (any, error) { if err := json.Unmarshal(raw, &schema); err != nil || schema == nil { return nil, errors.New("must be a JSON schema object") } + if len(schema) == 0 { + return nil, nil + } if schema["type"] != "object" { return nil, errors.New(`type must be "object"`) } + var compiled jsonschema.Schema + if err := json.Unmarshal(raw, &compiled); err != nil { + return nil, fmt.Errorf("invalid JSON schema: %w", err) + } + if _, err := compiled.Resolve(nil); err != nil { + return nil, fmt.Errorf("invalid JSON schema: %w", err) + } return schema, nil } diff --git a/pkg/agui/server.go b/pkg/agui/server.go index 6e01889e81..c4e458c875 100644 --- a/pkg/agui/server.go +++ b/pkg/agui/server.go @@ -462,7 +462,17 @@ func (s *server) resumeRun(c echo.Context, in *runInput) (bool, error) { return s.noPendingInterrupt(c, in) } - // Before the grant: a resume rejected here changes nothing. + // First: the only step a replay of this resume finds done (the results + // are then history), so a failure leaves nothing acted on. + if err := s.storeAnswers(ctx, run.sess, in.threadID, answered); err != nil { + if !s.approvals.park(run) { + run.cancelAndDrain() + } + return false, writeError(c, http.StatusInternalServerError, "failed to store the tool results: the interrupt is still pending, retry the resume") + } + + // Before the grant: a resume rejected here leaves only the answers stored, + // which its replay finds as history. lost, delivered := run.answerElicitations(in.resume) if len(lost) > 0 && !delivered { if !s.approvals.park(run) { @@ -489,13 +499,6 @@ func (s *server) resumeRun(c echo.Context, in *runInput) (bool, error) { } run.sess.AppendPermissionAllow(run.approval.grant) } - // Before the run goes on: the batch ends once its frontend calls have a result. - if err := s.storeAnswers(ctx, run.sess, in.threadID, answered); err != nil { - if !s.approvals.park(run) { - run.cancelAndDrain() - } - return false, writeError(c, http.StatusInternalServerError, "failed to store the tool results: the interrupt is still pending, retry the resume") - } resumed := "" if run.approval != nil { run.rt.Resume(ctx, req) diff --git a/pkg/agui/server_test.go b/pkg/agui/server_test.go index e9558823f7..b45499ba62 100644 --- a/pkg/agui/server_test.go +++ b/pkg/agui/server_test.go @@ -671,7 +671,12 @@ func TestRun_RejectsInvalidInput(t *testing.T) { "long tool name": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"` + strings.Repeat("x", 65) + `"}]}`, "tools[0]: name must be"}, "duplicate tool": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a"},{"name":"a"}]}`, `tools[1]: duplicate name \"a\"`}, "long tool description": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","description":"` + strings.Repeat("x", maxToolDescriptionSize+1) + `"}]}`, "description is longer"}, - "untyped parameters": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":{}}]}`, `tools[0].parameters: type must be \"object\"`}, + "untyped parameters": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":{"properties":{}}}]}`, `tools[0].parameters: type must be \"object\"`}, + "reserved tool name": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"__structured_output__"}]}`, `tools[0]: name \"__structured_output__\" is reserved`}, + "mistyped properties": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":{"type":"object","properties":"x"}}]}`, "tools[0].parameters: invalid JSON schema"}, + "mistyped required": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":{"type":"object","required":5}}]}`, "tools[0].parameters: invalid JSON schema"}, + "dangling $ref": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":{"type":"object","properties":{"b":{"$ref":"#/definitions/nope"}}}}]}`, "tools[0].parameters: invalid JSON schema"}, + "remote $ref": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":{"type":"object","properties":{"b":{"$ref":"http://127.0.0.1:1/b.json"}}}}]}`, "tools[0].parameters: invalid JSON schema"}, "array parameters": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":{"type":"array"}}]}`, `type must be \"object\"`}, "scalar parameters": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[{"name":"a","parameters":"object"}]}`, "tools[0].parameters: must be a JSON schema object"}, "too many tools": {`{"threadId":"t","runId":"r","messages":[` + user + `],"tools":[` + strings.Repeat(`{"name":"a"},`, maxFrontendTools) + `{"name":"a"}]}`, "at most"}, From 2308d0b65fa2b9439f7a7da6d3d4ad63a5b5acbd Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 14:29:42 +0100 Subject: [PATCH 03/14] fix(ag-ui): keep deny rules for frontend calls behind a mandatory ask Addresses review comment https://github.com/docker/docker-agent/pull/5122#discussion_r4799691823. Signed-off-by: deka --- pkg/runtime/toolexec/client_executed_test.go | 40 ++++++++++++++++++++ pkg/runtime/toolexec/dispatcher.go | 9 ++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/pkg/runtime/toolexec/client_executed_test.go b/pkg/runtime/toolexec/client_executed_test.go index b083f6998d..a9a0e44449 100644 --- a/pkg/runtime/toolexec/client_executed_test.go +++ b/pkg/runtime/toolexec/client_executed_test.go @@ -82,6 +82,46 @@ func TestDispatcher_ClientExecutedCallHonoursDenyRules(t *testing.T) { assert.Contains(t, em.responses[0].Output, "denied by test policy") } +// A mandatory ask enters the approval prompt before the permission rules: +// the client shortcut must not turn it into an allow over a matching deny. +func TestDispatcher_ClientExecutedCallMandatoryAsk(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + cfg *hooks.Config + denied bool + }{ + {"preempt ask with deny rule", &hooks.Config{PreToolUse: preemptYolo(hook(bVerdict, "ask", "needs a human"))}, true}, + {"tool_guard ask with deny rule", &hooks.Config{ToolGuard: matchAll(hook(bVerdict, "ask", "needs a human"))}, true}, + {"preempt ask without deny rule", &hooks.Config{PreToolUse: preemptYolo(hook(bVerdict, "ask", "needs a human"))}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + hd, _ := newPhaseHooks(t, tc.cfg) + d := newDispatcher(hd, nil) + if tc.denied { + d.Permissions = func(*session.Session) []toolexec.NamedChecker { + return []toolexec.NamedChecker{{Checker: newDenyChecker("pick_date"), Source: "test policy"}} + } + } + em := &captureEmitter{} + + d.Process(t.Context(), session.New(session.WithSafetyPolicy(session.SafetyPolicyAutonomous)), clientCall(), []tools.Tool{clientTool}, em) + + assert.Empty(t, em.confirmations) + if !tc.denied { + require.Len(t, em.calls, 1, "the client gets the call") + assert.Empty(t, em.responses) + return + } + assert.Empty(t, em.calls, "a denied call never reaches the client") + require.Len(t, em.responses, 1) + assert.True(t, em.responses[0].IsError) + assert.Contains(t, em.responses[0].Output, "denied by test policy") + }) + } +} + // The safety mode weighs what the server runs: it neither denies a // client-executed call nor skips the pre_tool_use hooks for it. var everyPolicy = []session.SafetyPolicy{ diff --git a/pkg/runtime/toolexec/dispatcher.go b/pkg/runtime/toolexec/dispatcher.go index 314de100ae..ed1b6ec4f4 100644 --- a/pkg/runtime/toolexec/dispatcher.go +++ b/pkg/runtime/toolexec/dispatcher.go @@ -1019,7 +1019,14 @@ func (c *call) confirmationMutex() *sync.Mutex { // hook auto-allow the call would unwind that protection. func (c *call) askUser(ctx context.Context, runTool func() CallOutcome) CallOutcome { if c.tool.ClientExecuted { - // The client application runs the call: nobody is asked twice. + // The client application runs the call: nobody is asked twice. A + // mandatory ask reaches here before the rules: an explicit deny still + // wins, the mode does not weigh it (see approveAndRun). + if decision := c.permissionDecision(); decision.Outcome == OutcomeDeny && decision.Reason == ReasonChecker { + c.notifyApproval(ctx, ApprovalDecisionDeny, denySourceForDecision(decision)) + c.errorResponse(ctx, denyErrorMessage(decision, c.tc.Function.Name)) + return CallOutcome{} + } c.notifyApproval(ctx, ApprovalDecisionAllow, ApprovalSourceClientExecuted) return runTool() } From 1934f346424827554549caff55658deb2a626ad5 Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 14:31:30 +0100 Subject: [PATCH 04/14] fix(ag-ui): stream frontend call arguments after the hooks rewrite them Addresses review comment https://github.com/docker/docker-agent/pull/5122#discussion_r4799691812. Signed-off-by: deka --- docs/features/ag-ui/index.md | 5 ++- pkg/agui/frontend_tools_test.go | 58 ++++++++++++++++++++++++++++----- pkg/agui/translator.go | 11 +++++-- 3 files changed, 63 insertions(+), 11 deletions(-) diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index d71ad9a58f..17896a071e 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -545,7 +545,10 @@ in the next run. - **Per run.** The thread does not store the tools: send them on every run that offers them. - **The call.** The run streams `TOOL_CALL_START`, `TOOL_CALL_ARGS` and - `TOOL_CALL_END`, but no `TOOL_CALL_RESULT`. Calls to server tools in the + `TOOL_CALL_END`, but no `TOOL_CALL_RESULT`. `TOOL_CALL_ARGS` comes once the + call is dispatched, with the arguments `tool_input_transform` and + `pre_tool_use` hooks let through: the model's original arguments never + reach the client. Calls to server tools in the same turn run as usual. The run then ends with `RUN_FINISHED` and `outcome: {"type": "success", "pendingToolCallIds": ["", ...]}`, without calling the model again. diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index 67c2655171..a91a771d99 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -138,8 +138,8 @@ func TestFrontendTools_CallIsLeftToTheClient(t *testing.T) { assert.Equal(t, []string{ "RUN_STARTED runId=run-1 threadId=thread-1", "TOOL_CALL_START toolCallId=call-1 toolCallName=pick_date", - `TOOL_CALL_ARGS delta={"after": toolCallId=call-1`, - `TOOL_CALL_ARGS delta="today"} toolCallId=call-1`, + // Held until the hooks let the call through. + `TOOL_CALL_ARGS delta={"after":"today"} toolCallId=call-1`, "TOOL_CALL_END toolCallId=call-1", "RUN_FINISHED outcome=map[pendingToolCallIds:[call-1] type:success] runId=run-1 threadId=thread-1", }, render(events)) @@ -206,16 +206,14 @@ func TestFrontendTools_WithAServerTool(t *testing.T) { assert.Equal(t, []string{ "RUN_STARTED runId=run-1 threadId=thread-1", "TOOL_CALL_START toolCallId=c1 toolCallName=pick_date", - "TOOL_CALL_ARGS delta={} toolCallId=c1", "TOOL_CALL_START toolCallId=c2 toolCallName=lookup", "TOOL_CALL_ARGS delta={} toolCallId=c2", - }, lines[:5]) - // The dispatcher may run c2 before or after it hands c1 to the client. - assert.ElementsMatch(t, []string{ + // The client's call is dispatched first, with its arguments. + "TOOL_CALL_ARGS delta={} toolCallId=c1", + "TOOL_CALL_END toolCallId=c1", "TOOL_CALL_END toolCallId=c2", "TOOL_CALL_RESULT content=sunny messageId=c2-result role=tool toolCallId=c2", - "TOOL_CALL_END toolCallId=c1", - }, lines[5:8]) + }, lines[:8]) assert.Less(t, slices.Index(lines, "TOOL_CALL_END toolCallId=c2"), slices.Index(lines, "TOOL_CALL_RESULT content=sunny messageId=c2-result role=tool toolCallId=c2")) assert.Equal(t, "RUN_FINISHED outcome=map[pendingToolCallIds:[c1] type:success] runId=run-1 threadId=thread-1", lines[8]) assert.EqualValues(t, 1, executions.Load()) @@ -560,6 +558,50 @@ func TestFrontendTools_RefusedCallIsNotPending(t *testing.T) { } } +// The client runs a frontend call with the arguments the hooks let through: +// the model's original value never reaches the wire. +func TestFrontendTools_ClientGetsRewrittenArguments(t *testing.T) { + t.Parallel() + + const hookName = "test-redact-after" + for name, config := range map[string]*latest.HooksConfig{ + "tool_input_transform": {ToolInputTransform: []latest.HookMatcherConfig{{Matcher: ".*", Hooks: []latest.HookDefinition{{Type: "builtin", Command: hookName}}}}}, + "pre_tool_use": {PreToolUse: []latest.HookMatcherConfig{{Matcher: ".*", Hooks: []latest.HookDefinition{{Type: "builtin", Command: hookName}}}}}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + // Streamed as deltas: the secret arrives before any hook runs. + prov := script(toolCall("pick_date", `{"after":`, `"secret-value"}`), text("Booked")) + server := startServerWithSafety(t, singleAgentTeam(prov, dagent.WithHooks(config)), session.NewInMemorySessionStore(), session.SafetyPolicyBalanced, RunOptions{}) + server.srv.runtimeOpts = func() []runtime.Opt { + registry := hooks.NewRegistry() + err := registry.RegisterBuiltin(hookName, func(_ context.Context, in *hooks.Input, _ []string) (*hooks.Output, error) { + return &hooks.Output{HookSpecificOutput: &hooks.HookSpecificOutput{ + HookEventName: in.HookEventName, + UpdatedInput: map[string]any{"after": "REDACTED"}, + }}, nil + }) + if err != nil { + panic(err) + } + return []runtime.Opt{runtime.WithHooksRegistry(registry)} + } + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + assert.NotContains(t, body, "secret-value") + assert.Equal(t, []string{ + "RUN_STARTED runId=run-1 threadId=thread-1", + "TOOL_CALL_START toolCallId=call-1 toolCallName=pick_date", + `TOOL_CALL_ARGS delta={"after":"REDACTED"} toolCallId=call-1`, + "TOOL_CALL_END toolCallId=call-1", + "RUN_FINISHED outcome=map[pendingToolCallIds:[call-1] type:success] runId=run-1 threadId=thread-1", + }, render(events)) + }) + } +} + var servedPolicies = []session.SafetyPolicy{ session.SafetyPolicyRestricted, session.SafetyPolicyStrict, session.SafetyPolicyBalanced, session.SafetyPolicyAutonomous, diff --git a/pkg/agui/translator.go b/pkg/agui/translator.go index 2ad8356901..78c5027f3d 100644 --- a/pkg/agui/translator.go +++ b/pkg/agui/translator.go @@ -356,7 +356,8 @@ func (t *translator) translate(event runtime.Event) []events.Event { if e.ToolDefinition != nil && e.ToolDefinition.ClientExecuted { call.frontend = true } - if call.state == toolCallOpen && e.ToolCall.Function.Arguments != "" { + // A frontend call's arguments wait for dispatch: hooks may rewrite them. + if call.state == toolCallOpen && !call.frontend && e.ToolCall.Function.Arguments != "" { out = append(out, events.NewToolCallArgsEvent(call.id, e.ToolCall.Function.Arguments)) } @@ -365,7 +366,13 @@ func (t *translator) translate(event runtime.Event) []events.Event { delete(t.resolved, key) break } - out = t.dispatchToolCall(e.AgentName, e.ToolCall) + if call := t.invocation(e.AgentName, e.ToolCall.ID); call != nil && call.frontend && call.state == toolCallOpen { + // The arguments the hooks let through, the only ones the client sees. + if args := e.ToolCall.Function.Arguments; args != "" { + out = append(out, events.NewToolCallArgsEvent(call.id, args)) + } + } + out = append(out, t.dispatchToolCall(e.AgentName, e.ToolCall)...) if call := t.invocation(e.AgentName, e.ToolCall.ID); call != nil { call.frontend = e.ToolDefinition.ClientExecuted call.running = !call.frontend From bebcd54784f21d45c39e480b94e70cf7f1b51351 Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 14:32:32 +0100 Subject: [PATCH 05/14] fix(ag-ui): check frontend tool names against forced handoff and routing targets Addresses review comment https://github.com/docker/docker-agent/pull/5122#discussion_r4799691832. Signed-off-by: deka --- docs/features/ag-ui/index.md | 11 ++++++----- pkg/agui/frontend_tools.go | 24 ++++++++++++++++++++++-- pkg/agui/frontend_tools_test.go | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index 17896a071e..de91c0f1dc 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -208,7 +208,7 @@ nothing: the same `threadId` still accepts a valid request. | `threadId` | Required, at most 256 bytes. Starts with a letter or digit and contains only letters, digits, `.`, `_` and `-` (a UUID qualifies). | | `runId` | Required, at most 256 bytes. | | `messages` | Every message needs an `id` of at most 256 bytes and a known `role`. The history must end with at least one user message, or with tool results in the last turn. Trailing user messages need distinct `id`s and non-empty text content (a string, or a list of `text` parts). Tool results of the last turn (since the user messages that started it) need a `toolCallId` (distinct, at most 256 bytes) and text content; `error`, when set, must be a string. The `toolCallId` must name a call of the thread. The content of earlier messages is not read. | -| `tools` | At most 128 tools, 256 KiB in all. Each tool is an object with a `name` of 1 to 64 letters, digits, `_` or `-`, distinct, not `__structured_output__` and not the name of a tool of the entry agent or of its handoff targets, catalog tools included; a `description` of at most 8 KiB; and `parameters`, absent, empty (no parameters, as when absent) or a valid JSON schema with `"type": "object"` whose `$ref`s stay in the document. See [Frontend tools](#frontend-tools). | +| `tools` | At most 128 tools, 256 KiB in all. Each tool is an object with a `name` of 1 to 64 letters, digits, `_` or `-`, distinct, not `__structured_output__` and not the name of a tool of an agent the thread's session can reach (the entry agent, its `handoffs`, `force_handoff` and `routing` targets, transitively), catalog tools included; a `description` of at most 8 KiB; and `parameters`, absent, empty (no parameters, as when absent) or a valid JSON schema with `"type": "object"` whose `$ref`s stay in the document. See [Frontend tools](#frontend-tools). | | `state` | Must be empty (`null`, `{}`): shared state is not supported. | | `resume` | Only with `--tool-approval` or `--elicitation`, to resolve interrupts: see [Tool approval](#tool-approval-interrupts) and [Elicitation](#elicitation-interrupts). Each entry needs an `interruptId` (distinct, at most 256 bytes) and a `status` of `resolved`, with a `payload` matching the interrupt's `responseSchema`, or `cancelled`, without a `payload`. | | `context`, `forwardedProps` | Accepted and ignored. | @@ -538,10 +538,11 @@ them like any other tool; the application runs the call and sends its result in the next run. - **Who gets them.** The tools of a run are offered to the agent the thread - runs: the entry agent and the agents it hands off to. Sub-agents reached - through `transfer_task` and background agents don't get them. A tool name - that is already a tool of one of those agents (catalog tools included) is - rejected with `400 Bad Request`. + runs: the entry agent and the agents the session moves to through + `handoffs`, `force_handoff` or `routing`. Sub-agents reached through + `transfer_task` and background agents don't get them. A tool name that is + already a tool of one of those agents (catalog tools included) is rejected + with `400 Bad Request`. - **Per run.** The thread does not store the tools: send them on every run that offers them. - **The call.** The run streams `TOOL_CALL_START`, `TOOL_CALL_ARGS` and diff --git a/pkg/agui/frontend_tools.go b/pkg/agui/frontend_tools.go index 14227f64ae..66546037f9 100644 --- a/pkg/agui/frontend_tools.go +++ b/pkg/agui/frontend_tools.go @@ -197,7 +197,8 @@ func (s *server) storeAnswers(ctx context.Context, sess *session.Session, thread } // checkToolNames rejects a frontend tool named like a tool of an agent that -// runs in the thread's session: the entry agent and its handoff targets. +// runs in the thread's session: the entry agent and every agent it may hand +// the session to. // Catalog tools count whether or not a model of the agent can search them. func (s *server) checkToolNames(ctx context.Context, frontend []tools.Tool) (int, error) { if len(frontend) == 0 { @@ -223,7 +224,7 @@ func (s *server) checkToolNames(ctx context.Context, frontend []tools.Tool) (int taken[t.Name] = a.Name() } } - for _, h := range a.Handoffs() { + for _, h := range s.routeTargets(a) { if !seen[h] { seen[h] = true queue = append(queue, h) @@ -237,3 +238,22 @@ func (s *server) checkToolNames(ctx context.Context, frontend []tools.Tool) (int } return 0, nil } + +// routeTargets returns the agents a may switch the thread's session to: +// handoffs, its forced handoff and its routing targets. +func (s *server) routeTargets(a *agent.Agent) []*agent.Agent { + targets := slices.Clone(a.Handoffs()) + if f := a.ForceHandoff(); f != nil { + targets = append(targets, f) + } + routing := a.Routing() + for _, name := range append(slices.Clone(routing.AllowedAgents), routing.DefaultAgent) { + if name == "" { + continue + } + if t, err := s.team.Agent(name); err == nil { + targets = append(targets, t) + } + } + return targets +} diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index a91a771d99..b387b9ad90 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -681,6 +681,38 @@ func TestFrontendTools_HandoffTargets(t *testing.T) { assert.Contains(t, body, `tools[0]: name \"lookup\" is a tool of agent \"booker\"`) } +// A forced handoff or a route also moves the thread's session to another +// agent: its tools take precedence over a frontend tool of the same name. +func TestFrontendTools_RouteTargets(t *testing.T) { + t.Parallel() + + for name, opt := range map[string]func(target *dagent.Agent) dagent.Opt{ + "force_handoff": dagent.WithForceHandoff, + "routing": func(*dagent.Agent) dagent.Opt { + return dagent.WithRouting(dagent.Routing{AllowedAgents: []string{"booker"}}) + }, + "default route": func(*dagent.Agent) dagent.Opt { return dagent.WithRouting(dagent.Routing{DefaultAgent: "booker"}) }, + "two hops apart": func(target *dagent.Agent) dagent.Opt { + return dagent.WithHandoffs(dagent.New("relay", "You relay", dagent.WithForceHandoff(target))) + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + target := dagent.New("booker", "You book", dagent.WithModel(script(text("booked"))), dagent.WithTools(echoTool(&executions))) + rootProv := script(text("hi")) + root := dagent.New("root", "You route", dagent.WithModel(rootProv), opt(target)) + server := startServer(t, team.New(team.WithAgents(root, target)), session.NewInMemorySessionStore(), RunOptions{}) + + status, _, body := server.post(t, inputWith("thread-1", "run-1", []any{map[string]any{"name": "lookup"}}, nil, userMsg("u1", "Book"))) + assert.Equal(t, http.StatusBadRequest, status) + assert.Contains(t, body, `tools[0]: name \"lookup\" is a tool of agent \"booker\"`) + assert.Zero(t, rootProv.callCount()) + }) + } +} + // Cancelling an expired interrupt: the frontend call of its turn is answered // with the cancel, or stays the client's to answer. func TestFrontendTools_CancelledExpiredInterrupt(t *testing.T) { From 044b7d1b6ef7c6cce49da96880468af5e6d918fc Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 14:34:27 +0100 Subject: [PATCH 06/14] fix(ag-ui): keep an expired interrupt until its cancel is accepted Addresses review comment https://github.com/docker/docker-agent/pull/5122#discussion_r4799691874. Signed-off-by: deka --- docs/features/ag-ui/index.md | 4 +++- pkg/agui/approval.go | 29 ++++++++++++++++++++++------- pkg/agui/frontend_tools_test.go | 23 +++++++++++++++++++++++ pkg/agui/server.go | 5 ++++- 4 files changed, 52 insertions(+), 9 deletions(-) diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index de91c0f1dc..598efe6f29 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -598,7 +598,9 @@ not pending, and a result sent for it is ignored. If the interrupt expired and the client cancels it, the frontend call stays the client's to answer, unless the cancelling request carries its result: the -run lists it in `pendingToolCallIds`. +run lists it in `pendingToolCallIds`. A cancelling request that is rejected +leaves the interrupt as it was, so its corrected retry still reports the +calls the interrupt left without a result. ## Current limitations diff --git a/pkg/agui/approval.go b/pkg/agui/approval.go index b52b330183..bf99f12f00 100644 --- a/pkg/agui/approval.go +++ b/pkg/agui/approval.go @@ -291,10 +291,11 @@ func (a *approvals) expiredID(threadID, id string) bool { return ok && slices.Contains(e.ids, id) } -// takeAbandoned removes the interrupts of threadID that entries abandon, if -// they expired, and returns the calls they left unanswered and the entries -// naming no interrupt the server knows. -func (a *approvals) takeAbandoned(threadID string, entries []resumeEntry) (pausedCalls, []string) { +// abandonedOf returns the calls the expired interrupts of threadID that +// entries abandon left unanswered, and the entries naming no interrupt the +// server knows. The interrupts stay until dropAbandoned: a request rejected +// later leaves them for its retry. +func (a *approvals) abandonedOf(threadID string, entries []resumeEntry) (pausedCalls, []string) { a.mu.Lock() defer a.mu.Unlock() e, ok := a.expired[threadID] @@ -307,12 +308,26 @@ func (a *approvals) takeAbandoned(threadID string, entries []resumeEntry) (pause } unknown = append(unknown, entry.interruptID) } - if len(unknown) < len(entries) { - delete(a.expired, threadID) - } return pending, unknown } +// dropAbandoned removes the expired interrupts of threadID that entries +// abandon, once the request abandoning them is accepted. +func (a *approvals) dropAbandoned(threadID string, entries []resumeEntry) { + a.mu.Lock() + defer a.mu.Unlock() + e, ok := a.expired[threadID] + if !ok { + return + } + for _, entry := range entries { + if slices.Contains(e.ids, entry.interruptID) { + delete(a.expired, threadID) + return + } + } +} + // take removes run from the registry, if it is still parked and not past its // expiry: the caller then owns it. An expired run is expired instead, and // the caller must drain it. diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index b387b9ad90..5337d6cec2 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -773,6 +773,29 @@ func TestFrontendTools_CancelledExpiredInterrupt(t *testing.T) { } } +// A cancel rejected for an invalid result leaves the expired interrupt to +// its corrected retry, which still reports the calls it abandoned. +func TestFrontendTools_RejectedCancelKeepsTheExpiredInterrupt(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c1", "pick_date", `{}`), call("c2", "lookup", `{}`)), text("Booked")) + server := approvalServer(t, prov, session.NewInMemorySessionStore(), echoTool(&executions)) + + _, events, _ := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + id := interruptOf(t, events)["id"].(string) + server.srv.approvals.evictExpired(time.Now().Add(defaultApprovalTTL + time.Minute)) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date"), assistantCall("c2", "lookup")} + status, _, body := server.post(t, inputWith("thread-1", "run-2", []any{pickDate}, []map[string]any{cancelled(id)}, append(history, toolMsg("zz", "2026-12-25"))...)) + require.Equal(t, http.StatusBadRequest, status, body) + + lines := server.run(t, inputWith("thread-1", "run-3", []any{pickDate}, []map[string]any{cancelled(id)}, append(history, toolMsg("c1", "2026-12-25"))...)) + assert.Contains(t, lines, "TOOL_CALL_RESULT content="+abandonedToolResult+" messageId=c2-result role=tool toolCallId=c2") + assert.Equal(t, "RUN_FINISHED runId=run-3 threadId=thread-1", lines[len(lines)-1]) + assert.Zero(t, executions.Load()) +} + // The interrupt comes before the frontend call is dispatched: the resume // carries its answer before the runtime hands it to the client. func TestFrontendTools_ApprovalBeforeTheFrontendCall(t *testing.T) { diff --git a/pkg/agui/server.go b/pkg/agui/server.go index c4e458c875..5e45cd04ee 100644 --- a/pkg/agui/server.go +++ b/pkg/agui/server.go @@ -351,7 +351,7 @@ func (s *server) handleRun(c echo.Context) error { var abandoned pausedCalls if abandoning { var unknown []string - abandoned, unknown = s.approvals.takeAbandoned(in.threadID, in.resume) + abandoned, unknown = s.approvals.abandonedOf(in.threadID, in.resume) for _, id := range unknown { // Lost in a restart, or already abandoned: nothing waits for it. slog.WarnContext(ctx, "Ignoring a cancelled AG-UI interrupt the server does not know", "thread_id", in.threadID, "interrupt_id", id) @@ -359,6 +359,7 @@ func (s *server) handleRun(c echo.Context) error { } if abandoning && len(in.newMessages) == 0 && len(in.toolResults) == 0 { + s.approvals.dropAbandoned(in.threadID, in.resume) writeAbandoned(c, in, sessionID, abandoned) return nil } @@ -367,6 +368,7 @@ func (s *server) handleRun(c echo.Context) error { case errors.Is(err, errThreadUnavailable): return writeError(c, http.StatusConflict, err.Error()) case errors.Is(err, errNoNewMessage) && abandoning: + s.approvals.dropAbandoned(in.threadID, in.resume) writeAbandoned(c, in, sessionID, abandoned) return nil case errors.Is(err, errNoNewMessage): @@ -405,6 +407,7 @@ func (s *server) handleRun(c echo.Context) error { run.gate = gate tr := newTranslator(sess.ID, in.threadID, in.runID) if abandoning { + s.approvals.dropAbandoned(in.threadID, in.resume) tr = newAbandonTranslator(sess.ID, in.threadID, in.runID, abandoned) } s.trackCalls(ctx, tr, sess) From d9d3980b8ed329605b962f7885b14d90ad08eb9b Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 14:35:50 +0100 Subject: [PATCH 07/14] fix(ag-ui): accept suffixed tool call IDs of threads without call records Addresses review comment https://github.com/docker/docker-agent/pull/5122#discussion_r4799691857. Signed-off-by: deka --- docs/features/ag-ui/index.md | 4 +++- pkg/agui/frontend_tools.go | 17 +++++++++++++- pkg/agui/frontend_tools_test.go | 40 +++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 2 deletions(-) diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index 598efe6f29..a1abfada40 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -558,7 +558,9 @@ in the next run. reference client inserts it there, before the messages of later calls). Set `error` to report a failed call: the model sees the content followed by the error. The run needs no new user message, and the model continues the turn. Results the - thread already holds, resent as history, are ignored. A `toolCallId` the + thread already holds, resent as history, are ignored, including those of + threads from earlier versions, which kept no `ag-ui.tool-calls` records + (a suffixed `call_0-2` stands for the stored `call_0`). A `toolCallId` the thread does not know, or a call that is no longer pending, is rejected with `400 Bad Request`. - **No answer.** A run that sends a new user message without the result of a diff --git a/pkg/agui/frontend_tools.go b/pkg/agui/frontend_tools.go index 66546037f9..17b0f5489a 100644 --- a/pkg/agui/frontend_tools.go +++ b/pkg/agui/frontend_tools.go @@ -8,6 +8,8 @@ import ( "log/slog" "net/http" "slices" + "strconv" + "strings" "github.com/docker/docker-agent/pkg/agent" "github.com/docker/docker-agent/pkg/chat" @@ -107,7 +109,7 @@ func matchToolResults(sess *session.Session, results []toolMessage) (*answers, e switch { case isPending: given[m.toolCallID] = m - case known && (!r.Frontend || stored[r.ID]), !known && stored[m.toolCallID]: + case known && (!r.Frontend || stored[r.ID]), !known && (stored[m.toolCallID] || stored[legacyBase(m.toolCallID)]): // A result already stored, resent as history. case !known: return nil, fmt.Errorf("messages: tool call %q is unknown on this thread", m.toolCallID) @@ -130,6 +132,19 @@ func matchToolResults(sess *session.Session, results []toolMessage) (*answers, e return out, nil } +// legacyBase returns the runtime ID behind a wire ID suffixed by a server that +// kept no tool call records ("call_0" for "call_0-2"), or wire itself. +func legacyBase(wire string) string { + i := strings.LastIndexByte(wire, '-') + if i <= 0 { + return wire + } + if n, err := strconv.Atoi(wire[i+1:]); err != nil || n < 2 || strconv.Itoa(n) != wire[i+1:] { + return wire + } + return wire[:i] +} + func frontendResult(agentName, callID, content string, isError bool) *session.Message { return session.NewAgentMessage(agentName, &chat.Message{ Role: chat.MessageRoleTool, diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index 5337d6cec2..77f5f439cf 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -773,6 +773,46 @@ func TestFrontendTools_CancelledExpiredInterrupt(t *testing.T) { } } +// A thread from a server that kept no tool call records still continues: a +// reused ID it suffixed comes back as history. +func TestFrontendTools_LegacyThreadWithSuffixedIDs(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("call_0", "lookup", `{}`)), calls(call("call_0", "lookup", `{}`)), text("done"), calls(call("c9", "lookup", `{}`)), text("again"), text("more")) + store := session.NewInMemorySessionStore() + server := startServer(t, singleAgentTeam(prov, dagent.WithTools(echoTool(&executions))), store, RunOptions{}) + + lines := server.run(t, frontendInput("thread-1", "run-1", userMsg("u1", "Look"))) + require.Contains(t, lines, "TOOL_CALL_START toolCallId=call_0-2 toolCallName=lookup") + stored, err := store.GetSession(t.Context(), sessionIDFor("thread-1")) + require.NoError(t, err) + stored.DeleteAttribute(callsAttribute) + require.NoError(t, store.UpdateSession(t.Context(), stored)) + + history := []map[string]any{ + userMsg("u1", "Look"), + assistantCall("call_0", "lookup"), toolMsg("call_0", "sunny"), + assistantCall("call_0-2", "lookup"), toolMsg("call_0-2", "sunny"), + } + server.run(t, frontendInput("thread-1", "run-2", append(history, userMsg("u2", "Again"))...)) + // Once the thread has records again. + stored, err = store.GetSession(t.Context(), sessionIDFor("thread-1")) + require.NoError(t, err) + require.Contains(t, stored.AttributesSnapshot(), callsAttribute) + history = append(history, userMsg("u2", "Again"), assistantCall("c9", "lookup"), toolMsg("c9", "sunny")) + lines = server.run(t, frontendInput("thread-1", "run-3", append(history, userMsg("u3", "More"))...)) + assert.Equal(t, "RUN_FINISHED runId=run-3 threadId=thread-1", lines[len(lines)-1]) + assert.Equal(t, 6, prov.callCount()) + + // An ID the thread never had is still refused. + for _, id := range []string{"nope-2", "call_1-2", "call_0-1", "call_0-02"} { + status, _, body := server.post(t, frontendInput("thread-1", "run-4", append(history, toolMsg(id, "x"), userMsg("u4", "Last"))...)) + assert.Equal(t, http.StatusBadRequest, status, id) + assert.Contains(t, body, "is unknown on this thread", id) + } +} + // A cancel rejected for an invalid result leaves the expired interrupt to // its corrected retry, which still reports the calls it abandoned. func TestFrontendTools_RejectedCancelKeepsTheExpiredInterrupt(t *testing.T) { From 78a9d2891fb54c8bf2813e80c0f1e801ed2e887c Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 14:37:24 +0100 Subject: [PATCH 08/14] fix(ag-ui): continue an answered turn with the agent that made the call Addresses review comment https://github.com/docker/docker-agent/pull/5122#discussion_r4799691847. Signed-off-by: deka --- docs/features/ag-ui/index.md | 3 +- pkg/agui/frontend_tools.go | 13 ++++++ pkg/agui/frontend_tools_test.go | 70 +++++++++++++++++++++++++++++++++ pkg/agui/server.go | 17 +++++++- 4 files changed, 101 insertions(+), 2 deletions(-) diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index a1abfada40..ae1bdf8a5d 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -557,7 +557,8 @@ in the next run. `toolCallId` is the call's, after the assistant message of the call (the reference client inserts it there, before the messages of later calls). Set `error` to report a failed call: the model sees the content followed by the error. The run - needs no new user message, and the model continues the turn. Results the + needs no new user message, and the agent that made the call continues the + turn, also after a handoff; a new user message starts at the entry agent. Results the thread already holds, resent as history, are ignored, including those of threads from earlier versions, which kept no `ag-ui.tool-calls` records (a suffixed `call_0-2` stands for the stored `call_0`). A `toolCallId` the diff --git a/pkg/agui/frontend_tools.go b/pkg/agui/frontend_tools.go index 17b0f5489a..63b67ad5a8 100644 --- a/pkg/agui/frontend_tools.go +++ b/pkg/agui/frontend_tools.go @@ -90,6 +90,9 @@ type answers struct { given int // history: the input had tool messages, all already stored. history bool + // agent continues the turn when the run has no new prompt: the agent + // whose calls the results answer. + agent string } // matchToolResults maps the tool messages of the input to the frontend calls @@ -145,6 +148,16 @@ func legacyBase(wire string) string { return wire[:i] } +// turnAgent returns the agent of the last assistant message of the thread. +func turnAgent(sess *session.Session) string { + for _, m := range slices.Backward(sess.OwnMessages()) { + if m.Message.Role == chat.MessageRoleAssistant { + return m.AgentName + } + } + return "" +} + func frontendResult(agentName, callID, content string, isError bool) *session.Message { return session.NewAgentMessage(agentName, &chat.Message{ Role: chat.MessageRoleTool, diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index 77f5f439cf..99313247e2 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -28,6 +28,7 @@ import ( "github.com/docker/docker-agent/pkg/session/sqlitestore" "github.com/docker/docker-agent/pkg/team" "github.com/docker/docker-agent/pkg/tools" + "github.com/docker/docker-agent/pkg/tools/builtin/handoff" "github.com/docker/docker-agent/pkg/tools/builtin/transfertask" ) @@ -681,6 +682,75 @@ func TestFrontendTools_HandoffTargets(t *testing.T) { assert.Contains(t, body, `tools[0]: name \"lookup\" is a tool of agent \"booker\"`) } +// The agent a handoff moved the thread to gets the result of its call: the +// run that answers it does not start again at the entry agent. +func TestFrontendTools_AnswerAfterAHandoff(t *testing.T) { + t.Parallel() + + bookerProv := script(calls(call("c1", "pick_date", `{}`)), text("Booked"), text("Rebooked")) + booker := dagent.New("booker", "You book", dagent.WithModel(bookerProv)) + rootProv := script(calls(call("h1", "handoff", `{"agent":"booker"}`)), text("Hello again")) + root := dagent.New("root", "You route", dagent.WithModel(rootProv), dagent.WithToolSets(handoff.New()), dagent.WithHandoffs(booker)) + server := startServer(t, team.New(team.WithAgents(root, booker)), session.NewInMemorySessionStore(), RunOptions{}) + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + require.Equal(t, []any{"c1"}, pendingOf(t, events)) + require.Equal(t, 1, rootProv.callCount()) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("h1", "handoff"), toolMsg("h1", "ok"), assistantCall("c1", "pick_date")} + lines := server.run(t, frontendInput("thread-1", "run-2", append(history, toolMsg("c1", "2026-12-25"))...)) + assert.Contains(t, lines, "TEXT_MESSAGE_CONTENT delta=Booked messageId=m1") + assert.Equal(t, 1, rootProv.callCount(), "the entry agent is not called") + assert.Contains(t, bookerProv.toolResults(1), "c1: 2026-12-25") + + // A new user message starts at the entry agent again. + history = append(history, toolMsg("c1", "2026-12-25")) + server.run(t, frontendInput("thread-1", "run-3", append(history, userMsg("u2", "Thanks"))...)) + assert.Equal(t, 2, rootProv.callCount()) + assert.Equal(t, 2, bookerProv.callCount()) +} + +// A routed thread too: the answer goes to the agent the route picked. +func TestFrontendTools_AnswerAfterARoute(t *testing.T) { + t.Parallel() + + const hookName = "test-route-to-booker" + var routes atomic.Int32 + bookerProv := script(calls(call("c1", "pick_date", `{}`)), text("Booked")) + booker := dagent.New("booker", "You book", dagent.WithModel(bookerProv)) + rootProv := script(text("unused")) + root := dagent.New("root", "You route", dagent.WithModel(rootProv), + dagent.WithRouting(dagent.Routing{AllowedAgents: []string{"booker"}}), + dagent.WithHooks(&latest.HooksConfig{BeforeAgentRun: latest.HookDefinitions{{Type: "builtin", Command: hookName}}})) + server := startServer(t, team.New(team.WithAgents(root, booker)), session.NewInMemorySessionStore(), RunOptions{}) + server.srv.runtimeOpts = func() []runtime.Opt { + registry := hooks.NewRegistry() + err := registry.RegisterBuiltin(hookName, func(context.Context, *hooks.Input, []string) (*hooks.Output, error) { + routes.Add(1) + return &hooks.Output{HookSpecificOutput: &hooks.HookSpecificOutput{ + HookEventName: hooks.EventBeforeAgentRun, + Transition: &hooks.Transition{Action: hooks.TransitionActionRoute, Agent: "booker"}, + }}, nil + }) + if err != nil { + panic(err) + } + return []runtime.Opt{runtime.WithHooksRegistry(registry)} + } + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + require.Equal(t, []any{"c1"}, pendingOf(t, events), body) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date")} + lines := server.run(t, frontendInput("thread-1", "run-2", append(history, toolMsg("c1", "2026-12-25"))...)) + assert.Contains(t, lines, "TEXT_MESSAGE_CONTENT delta=Booked messageId=m1") + assert.Contains(t, bookerProv.toolResults(1), "c1: 2026-12-25") + assert.Zero(t, rootProv.callCount()) + assert.EqualValues(t, 1, routes.Load()) +} + // A forced handoff or a route also moves the thread's session to another // agent: its tools take precedence over a frontend tool of the same name. func TestFrontendTools_RouteTargets(t *testing.T) { diff --git a/pkg/agui/server.go b/pkg/agui/server.go index 5e45cd04ee..a7b7a954b2 100644 --- a/pkg/agui/server.go +++ b/pkg/agui/server.go @@ -384,7 +384,7 @@ func (s *server) handleRun(c echo.Context) error { gate := &pauseGate{sessionID: sess.ID} opts := []runtime.Opt{ - runtime.WithCurrentAgent(s.agentName), + runtime.WithCurrentAgent(s.runAgent(answered)), runtime.WithModelsDevFallback(embedded.Snapshot), runtime.WithSessionStore(s.store), // Same tracer scope as the CLI, or runtime spans are no-ops. @@ -416,6 +416,17 @@ func (s *server) handleRun(c echo.Context) error { return nil } +// runAgent returns the agent a run starts with: the entry agent, or the agent +// whose turn the run continues. +func (s *server) runAgent(a *answers) string { + if a.agent != "" { + if _, err := s.team.Agent(a.agent); err == nil { + return a.agent + } + } + return s.agentName +} + // startRun starts the run of sess. It keeps the values of the request (trace) // but not its cancellation, so a parked run survives the request; stream // binds it to the request while it streams. @@ -612,6 +623,10 @@ func (s *server) resolveSession(ctx context.Context, sessionID string, in *runIn // A retry: nothing to store, and nothing left unanswered. answered = &answers{} } + if prompt == nil { + // A handoff moved only the previous runtime's agent. + answered.agent = turnAgent(sess) + } if err := s.storeAnswers(ctx, sess, in.threadID, answered); err != nil { return nil, nil, err } From 6a5148ecab6380efc5d14816dc2b547d2d946a78 Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 14:43:09 +0100 Subject: [PATCH 09/14] fix(ag-ui): let a retry finish a partly stored batch of tool results Addresses review comments https://github.com/docker/docker-agent/pull/5122#discussion_r4799691884 and https://github.com/docker/docker-agent/pull/5122#discussion_r4799691898. Signed-off-by: deka --- docs/features/ag-ui/index.md | 4 +- pkg/agui/frontend_tools.go | 47 ++++++++++---- pkg/agui/frontend_tools_test.go | 112 +++++++++++++++++++++++++++++++- pkg/agui/server.go | 2 +- pkg/agui/translator.go | 3 + 5 files changed, 150 insertions(+), 18 deletions(-) diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index ae1bdf8a5d..24d13aa964 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -569,7 +569,9 @@ in the next run. `the application did not answer this tool call`, streamed as its `TOOL_CALL_RESULT` at the start of the run, and logs a warning with the thread and call IDs. The model is never called with a call left without a - result. + result. If storing the results fails, the request gets `500` and its + identical retry completes it: a result an earlier attempt stored is + streamed when the request does not carry it. - **Restart.** The thread stores the `toolCallId` of each call it streamed (session attribute `ag-ui.tool-calls`): a pending call can be answered after a server restart. diff --git a/pkg/agui/frontend_tools.go b/pkg/agui/frontend_tools.go index 63b67ad5a8..9b989a8ec7 100644 --- a/pkg/agui/frontend_tools.go +++ b/pkg/agui/frontend_tools.go @@ -75,13 +75,16 @@ type pendingCall struct { id string name string agent string + // result is the stored result of a call that has one. + result string } // answers are the tool results of a run, matched against the frontend calls // pending on the thread. type answers struct { - // results answer every pending call, in call order: an unanswered call - // gets an error. + // results answer every pending call: an unanswered call gets an error. + // The client's answers come last, so a failed write always leaves one of + // them pending for the retry. results []*session.Message unanswered []pendingCall // answered lists the wire IDs of the pending calls the client answered. @@ -93,13 +96,16 @@ type answers struct { // agent continues the turn when the run has no new prompt: the agent // whose calls the results answer. agent string + // restream lists the calls of the turn whose stored result the client + // may not have: an earlier attempt stored it, then failed. + restream []pendingCall } // matchToolResults maps the tool messages of the input to the frontend calls // pending on the thread: those of its last assistant message without a result. // It changes nothing. func matchToolResults(sess *session.Session, results []toolMessage) (*answers, error) { - pending, _, stored := pendingFrontendCalls(sess) + pending, done, stored := pendingFrontendCalls(sess) byWire := make(map[string]callRecord) for _, r := range storedCalls(sess) { byWire[r.Wire] = r @@ -122,6 +128,7 @@ func matchToolResults(sess *session.Session, results []toolMessage) (*answers, e } out := &answers{given: len(given), history: len(results) > 0 && len(given) == 0} + var clientResults []*session.Message for _, p := range pending { m, ok := given[p.wire] if !ok { @@ -130,7 +137,13 @@ func matchToolResults(sess *session.Session, results []toolMessage) (*answers, e continue } out.answered = append(out.answered, p.wire) - out.results = append(out.results, frontendResult(p.agent, p.id, m.content, m.isError)) + clientResults = append(clientResults, frontendResult(p.agent, p.id, m.content, m.isError)) + } + out.results = append(out.results, clientResults...) + for _, p := range done { + if !slices.ContainsFunc(results, func(m toolMessage) bool { return m.toolCallID == p.wire }) { + out.restream = append(out.restream, p) + } } return out, nil } @@ -168,10 +181,10 @@ func frontendResult(agentName, callID, content string, isError bool) *session.Me } // pendingFrontendCalls returns the frontend calls of the last assistant -// message of the thread that have no result, the runtime IDs of those that -// have one, and the IDs of every stored tool result. -func pendingFrontendCalls(sess *session.Session) (pending []pendingCall, answered, stored map[string]bool) { - answered, stored = make(map[string]bool), make(map[string]bool) +// message of the thread that have no result, those that have one, and the IDs +// of every stored tool result. +func pendingFrontendCalls(sess *session.Session) (pending, done []pendingCall, stored map[string]bool) { + answered, stored := make(map[string]string), make(map[string]bool) // Sub-sessions hold no frontend call: their results are in the records. msgs := sess.OwnMessages() last := -1 @@ -181,12 +194,12 @@ func pendingFrontendCalls(sess *session.Session) (pending []pendingCall, answere last = i clear(answered) case chat.MessageRoleTool: - answered[m.Message.ToolCallID] = true + answered[m.Message.ToolCallID] = m.Message.Content stored[m.Message.ToolCallID] = true } } if last < 0 { - return nil, answered, stored + return nil, nil, stored } // A runtime ID may come back in a later turn: the latest record wins. owner := msgs[last].AgentName @@ -201,11 +214,19 @@ func pendingFrontendCalls(sess *session.Session) (pending []pendingCall, answere } } for _, tc := range msgs[last].Message.ToolCalls { - if wire, ok := frontend[tc.ID]; ok && !answered[tc.ID] { - pending = append(pending, pendingCall{wire: wire, id: tc.ID, name: tc.Function.Name, agent: owner}) + wire, ok := frontend[tc.ID] + if !ok { + continue + } + call := pendingCall{wire: wire, id: tc.ID, name: tc.Function.Name, agent: owner} + if result, has := answered[tc.ID]; has { + call.result = result + done = append(done, call) + continue } + pending = append(pending, call) } - return pending, answered, stored + return pending, done, stored } // storeAnswers adds tool results to the session and the store. diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index 99313247e2..8a20b7552d 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -1006,12 +1006,15 @@ func TestFrontendTools_WithAnElicitation(t *testing.T) { } } -// failingAnswerStore fails AddMessage for tool results while fail is set, -// and UpdateSession while failUpdate is set. +// failingAnswerStore fails AddMessage for tool results while fail is set, or +// past the inserts allowed while limited is set, and UpdateSession while +// failUpdate is set. type failingAnswerStore struct { session.Store fail atomic.Bool + limited atomic.Bool + allowed atomic.Int32 failUpdate atomic.Bool } @@ -1023,7 +1026,7 @@ func (s *failingAnswerStore) UpdateSession(ctx context.Context, sess *session.Se } func (s *failingAnswerStore) AddMessage(ctx context.Context, sessionID string, msg *session.Message) (int64, error) { - if s.fail.Load() && msg.Message.Role == chat.MessageRoleTool { + if msg.Message.Role == chat.MessageRoleTool && (s.fail.Load() || s.limited.Load() && s.allowed.Add(-1) < 0) { return 0, errors.New("disk full") } return s.Store.AddMessage(ctx, sessionID, msg) @@ -1102,6 +1105,36 @@ func TestFrontendTools_AnswersNotStoredLeaveTheResumeUnapplied(t *testing.T) { assert.Equal(t, []string{"c1: 2026-12-25", "c2: sunny"}, prov.toolResults(1)) }) + // The answer left out is stored before the grant fails: the retry still + // streams its result, once. + t.Run("grant after an omitted answer", func(t *testing.T) { + t.Parallel() + + var executions atomic.Int32 + prov := script(calls(call("c2", "lookup", `{}`), call("c1", "pick_date", `{}`)), text("Booked")) + store := &failingAnswerStore{Store: sqliteStore(t)} + server := approvalServer(t, prov, store, echoTool(&executions)) + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + interrupt := interruptOf(t, events) + require.Equal(t, "c2", interrupt["toolCallId"], body) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c2", "lookup"), assistantCall("c1", "pick_date")} + resume := []map[string]any{resolved(interrupt["id"].(string), decision("approve-in-context"))} + input := inputWith("thread-1", "run-2", []any{pickDate}, resume, history...) + + store.failUpdate.Store(true) + status, _, body := server.post(t, input) + require.Equal(t, http.StatusInternalServerError, status, body) + store.failUpdate.Store(false) + + lines := server.run(t, input) + assert.Equal(t, "RUN_FINISHED runId=run-2 threadId=thread-1", lines[len(lines)-1]) + results := slices.DeleteFunc(toolResults(lines), func(l string) bool { return !strings.Contains(l, "toolCallId=c1") }) + assert.Equal(t, []string{"TOOL_CALL_RESULT content=" + unansweredToolResult + " messageId=c1-result role=tool toolCallId=c1"}, results) + assert.Equal(t, []string{"c1: " + unansweredToolResult + " (error)", "c2: sunny"}, prov.toolResults(1)) + }) + t.Run("elicitation", func(t *testing.T) { t.Parallel() @@ -1134,6 +1167,79 @@ func TestFrontendTools_AnswersNotStoredLeaveTheResumeUnapplied(t *testing.T) { }) } +// A write of the results that fails part way leaves a request its identical +// retry completes: each result reaches the model, and the client, once. +func TestFrontendTools_PartlyStoredAnswers(t *testing.T) { + t.Parallel() + + for _, answered := range []string{"c1", "c2"} { + for _, allowed := range []int32{0, 1} { + t.Run(fmt.Sprintf("%s answered, %d stored", answered, allowed), func(t *testing.T) { + t.Parallel() + + omitted := map[string]string{"c1": "c2", "c2": "c1"}[answered] + prov := script(calls(call("c1", "pick_date", `{}`), call("c2", "pick_date", `{}`)), text("Booked")) + store := &failingAnswerStore{Store: sqliteStore(t)} + server := startServer(t, singleAgentTeam(prov), store, RunOptions{}) + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, []any{"c1", "c2"}, pendingOf(t, events), body) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date"), assistantCall("c2", "pick_date")} + input := frontendInput("thread-1", "run-2", append(history, toolMsg(answered, "2026-12-25"))...) + store.allowed.Store(allowed) + store.limited.Store(true) + status, _, body := server.post(t, input) + require.Equal(t, http.StatusInternalServerError, status, body) + store.limited.Store(false) + + lines := server.run(t, input) + assert.Equal(t, "RUN_FINISHED runId=run-2 threadId=thread-1", lines[len(lines)-1]) + assert.Equal(t, []string{"TOOL_CALL_RESULT content=" + unansweredToolResult + " messageId=" + omitted + "-result role=tool toolCallId=" + omitted}, toolResults(lines)) + assert.ElementsMatch(t, []string{answered + ": 2026-12-25", omitted + ": " + unansweredToolResult + " (error)"}, prov.toolResults(1)) + }) + } + } +} + +// A refused call has a stored result while its sibling waits: a request with +// nothing new is still refused, and the refusal the client holds is not sent +// again. +func TestFrontendTools_RefusedSiblingIsNotARetry(t *testing.T) { + t.Parallel() + + confirm := map[string]any{"name": "confirm", "description": "Ask the user to confirm"} + prov := script(calls(call("c1", "confirm", `{}`), call("c2", "pick_date", `{}`)), text("Booked")) + root := dagent.New("root", "test", dagent.WithModel(prov)) + server := startServer(t, team.New(team.WithAgents(root), team.WithPermissions(permissions.NewCheckerFromRules(nil, nil, []string{"confirm"}))), session.NewInMemorySessionStore(), RunOptions{}) + offered := []any{pickDate, confirm} + + _, events, body := server.post(t, inputWith("thread-1", "run-1", offered, nil, userMsg("u1", "Book"))) + require.Equal(t, []any{"c2"}, pendingOf(t, events), body) + refusal := toolResult(t, render(events)) + require.Contains(t, refusal, "toolCallId=c1") + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "confirm"), toolMsg("c1", "denied"), assistantCall("c2", "pick_date")} + status, _, body := server.post(t, inputWith("thread-1", "run-2", offered, nil, history...)) + assert.Equal(t, http.StatusBadRequest, status, body) + + lines := server.run(t, inputWith("thread-1", "run-3", offered, nil, append(history, toolMsg("c2", "2026-12-25"))...)) + assert.Empty(t, toolResults(lines)) + assert.Equal(t, "RUN_FINISHED runId=run-3 threadId=thread-1", lines[len(lines)-1]) + assert.Contains(t, prov.toolResults(1), "c2: 2026-12-25") +} + +// toolResults returns the TOOL_CALL_RESULT lines of a rendered stream. +func toolResults(lines []string) []string { + var out []string + for _, l := range lines { + if strings.HasPrefix(l, "TOOL_CALL_RESULT ") { + out = append(out, l) + } + } + return out +} + // The schemas AG-UI clients build are accepted: zod-to-json-schema (draft-07), // zod 4 (2020-12), and an empty schema, which means no parameters. func TestFrontendTools_AcceptsClientSchemas(t *testing.T) { diff --git a/pkg/agui/server.go b/pkg/agui/server.go index a7b7a954b2..380337e21d 100644 --- a/pkg/agui/server.go +++ b/pkg/agui/server.go @@ -621,7 +621,7 @@ func (s *server) resolveSession(ctx context.Context, sessionID string, in *runIn } if prompt == nil && answered.given == 0 { // A retry: nothing to store, and nothing left unanswered. - answered = &answers{} + answered = &answers{restream: answered.restream} } if prompt == nil { // A handoff moved only the previous runtime's agent. diff --git a/pkg/agui/translator.go b/pkg/agui/translator.go index 78c5027f3d..f5a9f92e16 100644 --- a/pkg/agui/translator.go +++ b/pkg/agui/translator.go @@ -206,6 +206,9 @@ func (t *translator) stored(a *answers) { for _, p := range a.unanswered { t.answerOnStart(p.wire, p.agent, p.id, unansweredToolResult) } + for _, p := range a.restream { + t.answerOnStart(p.wire, p.agent, p.id, p.result) + } } // answerOnStart streams content as the result of the call wire, stored before From 6153687ab27f0857f40412d0eb137e49bcb807c6 Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 14:49:25 +0100 Subject: [PATCH 10/14] test(ag-ui): replay frontend tool runs through @ag-ui/client A manual check in examples/ag-ui/replay, pinned to @ag-ui/client 1.0.5 and run with AGUI_TS_REPLAY=1; it is skipped otherwise. The examples walk skips node_modules. Signed-off-by: deka --- examples/ag-ui/replay/.gitignore | 1 + examples/ag-ui/replay/package-lock.json | 151 ++++++++++++++++++++++++ examples/ag-ui/replay/package.json | 8 ++ examples/ag-ui/replay/replay.mjs | 54 +++++++++ pkg/agui/ts_replay_test.go | 35 ++++++ pkg/config/examples_test.go | 3 + 6 files changed, 252 insertions(+) create mode 100644 examples/ag-ui/replay/.gitignore create mode 100644 examples/ag-ui/replay/package-lock.json create mode 100644 examples/ag-ui/replay/package.json create mode 100644 examples/ag-ui/replay/replay.mjs create mode 100644 pkg/agui/ts_replay_test.go diff --git a/examples/ag-ui/replay/.gitignore b/examples/ag-ui/replay/.gitignore new file mode 100644 index 0000000000..c2658d7d1b --- /dev/null +++ b/examples/ag-ui/replay/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/examples/ag-ui/replay/package-lock.json b/examples/ag-ui/replay/package-lock.json new file mode 100644 index 0000000000..1a87b5af66 --- /dev/null +++ b/examples/ag-ui/replay/package-lock.json @@ -0,0 +1,151 @@ +{ + "name": "ag-ui-replay", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ag-ui-replay", + "dependencies": { + "@ag-ui/client": "1.0.5" + } + }, + "node_modules/@ag-ui/client": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@ag-ui/client/-/client-1.0.5.tgz", + "integrity": "sha512-p+j69TEs9vN8JHlBEQYVNgHuTnWYCWRGWpSxk6cuamQ3POdhp3Nf0pf6cTit1P827rOf22ypdbR+M5pbvqlD9A==", + "license": "MIT", + "dependencies": { + "@ag-ui/core": "1.0.5", + "@ag-ui/encoder": "1.0.5", + "@ag-ui/proto": "1.0.5", + "@types/uuid": "^10.0.0", + "compare-versions": "^6.1.1", + "fast-json-patch": "^3.1.1", + "rxjs": "7.8.1", + "untruncate-json": "^0.0.1", + "uuid": "^11.1.0" + }, + "peerDependencies": { + "zod": "^3.25.18 || ^4.0.0" + } + }, + "node_modules/@ag-ui/core": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@ag-ui/core/-/core-1.0.5.tgz", + "integrity": "sha512-W7xg7E/bVco3svYxZCp3CMqJ6/fB15U7yAaMS3mhLCwwlJXFzZJ/bGwMqnNrx6Afmj1WmnjFKzliYds+KFXMMQ==", + "license": "MIT", + "peerDependencies": { + "zod": "^3.25.18 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@ag-ui/encoder": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@ag-ui/encoder/-/encoder-1.0.5.tgz", + "integrity": "sha512-SKg5jOF2FCVMcl1nSNlk4hZdX9jV5Jg2nce5+jxY7lLSsMkBNMXvEpxZdQ1oWef3YI8OJCyB3cADUI3eyzplhA==", + "license": "MIT", + "dependencies": { + "@ag-ui/core": "1.0.5", + "@ag-ui/proto": "1.0.5" + }, + "peerDependencies": { + "zod": "^3.25.18 || ^4.0.0" + } + }, + "node_modules/@ag-ui/proto": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@ag-ui/proto/-/proto-1.0.5.tgz", + "integrity": "sha512-HFtYEapXepL3VtCkN2YS1KO5wndjJ8+86d3Qag3EeGp1EKxljZW/hRWN3HiILUTVI5cJ3CqGXBycE1/IAKQsGA==", + "license": "MIT", + "dependencies": { + "@ag-ui/core": "1.0.5", + "@bufbuild/protobuf": "^2.2.5", + "@protobuf-ts/protoc": "^2.11.1" + }, + "peerDependencies": { + "zod": "^3.25.18 || ^4.0.0" + } + }, + "node_modules/@bufbuild/protobuf": { + "version": "2.17.0", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.17.0.tgz", + "integrity": "sha512-hcPkSz6D7MiTU/5VBBhK+kxaYDoOdQ6yJRFJ3kS8Nydp+VZXfg1vrpABKPNod8bXMufsVCmiUJVIKFzCzta4uw==", + "license": "(Apache-2.0 AND BSD-3-Clause)" + }, + "node_modules/@protobuf-ts/protoc": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@protobuf-ts/protoc/-/protoc-2.11.1.tgz", + "integrity": "sha512-mUZJaV0daGO6HUX90o/atzQ6A7bbN2RSuHtdwo8SSF2Qoe3zHwa4IHyCN1evftTeHfLmdz+45qo47sL+5P8nyg==", + "license": "Apache-2.0", + "bin": { + "protoc": "protoc.js" + } + }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "license": "MIT" + }, + "node_modules/compare-versions": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz", + "integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==", + "license": "MIT" + }, + "node_modules/fast-json-patch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/fast-json-patch/-/fast-json-patch-3.1.2.tgz", + "integrity": "sha512-Dhr5mVii8hIvjkp0Xdrun9B3GlXe3j+L4Ymv8J0h3Di996xoBi8qSDQ/sqSNKZd1NEqx55ZfcseG1MphW7MkHg==", + "license": "MIT" + }, + "node_modules/rxjs": { + "version": "7.8.1", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", + "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD" + }, + "node_modules/untruncate-json": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/untruncate-json/-/untruncate-json-0.0.1.tgz", + "integrity": "sha512-4W9enDK4X1y1s2S/Rz7ysw6kDuMS3VmRjMFg7GZrNO+98OSe+x5Lh7PKYoVjy3lW/1wmhs6HW0lusnQRHgMarA==", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", + "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/examples/ag-ui/replay/package.json b/examples/ag-ui/replay/package.json new file mode 100644 index 0000000000..4d5665e931 --- /dev/null +++ b/examples/ag-ui/replay/package.json @@ -0,0 +1,8 @@ +{ + "name": "ag-ui-replay", + "private": true, + "type": "module", + "dependencies": { + "@ag-ui/client": "1.0.5" + } +} diff --git a/examples/ag-ui/replay/replay.mjs b/examples/ag-ui/replay/replay.mjs new file mode 100644 index 0000000000..c05f61681d --- /dev/null +++ b/examples/ag-ui/replay/replay.mjs @@ -0,0 +1,54 @@ +// Replays frontend tool runs through @ag-ui/client against the server at argv[2]. +import assert from "node:assert/strict"; +import { HttpAgent } from "@ag-ui/client"; + +const url = process.argv[2]; +const tools = [{ name: "pick_date", description: "Ask the user for a date", parameters: { type: "object", properties: {} } }]; +const agent = new HttpAgent({ url, threadId: "thread-ts" }); +agent.messages = [{ id: "u1", role: "user", content: "Book" }]; + +async function run(runId) { + const out = { pending: [], text: "", outcome: undefined }; + await agent.runAgent({ runId, tools }, { + onRunFinishedEvent: ({ outcome, pendingToolCallIds }) => { + out.outcome = outcome; + out.pending = pendingToolCallIds ?? []; + }, + onRunErrorEvent: ({ event }) => assert.fail(`${runId}: ${event.message}`), + onTextMessageContentEvent: ({ event }) => { out.text += event.delta; }, + }); + return out; +} + +function answer(ids, content) { + for (const id of ids) agent.messages.push({ id: `${id}-answer`, role: "tool", toolCallId: id, content }); +} + +// The call is left to the client, then answered in the next run. +const first = await run("run-1"); +assert.deepEqual(first.pending, ["c1"]); +const call = agent.messages.find((m) => m.role === "assistant" && m.toolCalls?.some((c) => c.id === "c1")); +assert.ok(call, "the client keeps the pending call"); +answer(first.pending, "2026-12-25"); + +// The model reuses its call ID: the client gets a distinct wire ID. +const second = await run("run-2"); +assert.deepEqual(second.pending, ["c1-2"]); +answer(second.pending, "2026-12-26"); + +const third = await run("run-3"); +assert.deepEqual(third.pending, []); +assert.equal(third.text, "Booked"); + +// Nothing left to answer: a history-only run is refused. +await assert.rejects(run("run-4")); + +// A new turn reuses the call ID again. +agent.messages.push({ id: "u2", role: "user", content: "Again" }); +const fourth = await run("run-5"); +assert.deepEqual(fourth.pending, ["c1-3"]); +answer(fourth.pending, "2026-12-27"); +const fifth = await run("run-6"); +assert.deepEqual(fifth.pending, []); +assert.equal(fifth.text, "Done"); +console.log("ok"); diff --git a/pkg/agui/ts_replay_test.go b/pkg/agui/ts_replay_test.go new file mode 100644 index 0000000000..b059da4fc5 --- /dev/null +++ b/pkg/agui/ts_replay_test.go @@ -0,0 +1,35 @@ +package agui + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/session" +) + +// TestTSReplay replays frontend tool runs through @ag-ui/client; see +// examples/ag-ui/README.md. +func TestTSReplay(t *testing.T) { + if os.Getenv("AGUI_TS_REPLAY") == "" { + t.Skip("set AGUI_TS_REPLAY=1 to replay through @ag-ui/client") + } + node, err := exec.LookPath("node") + require.NoError(t, err) + + prov := script(calls(call("c1", "pick_date", `{}`)), calls(call("c1", "pick_date", `{}`)), text("Booked"), calls(call("c1", "pick_date", `{}`)), text("Done")) + server := startServer(t, singleAgentTeam(prov), session.NewInMemorySessionStore(), RunOptions{}) + + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + out, err := exec.CommandContext(ctx, node, filepath.Join("..", "..", "examples", "ag-ui", "replay", "replay.mjs"), server.url).CombinedOutput() + require.NoError(t, err, string(out)) + assert.Equal(t, []string{"c1: 2026-12-25", "c1: 2026-12-26"}, prov.toolResults(2)) + assert.Contains(t, prov.toolResults(4), "c1: 2026-12-27") +} diff --git a/pkg/config/examples_test.go b/pkg/config/examples_test.go index 46e96b4829..6b9600daee 100644 --- a/pkg/config/examples_test.go +++ b/pkg/config/examples_test.go @@ -52,6 +52,9 @@ func collectExamples(t *testing.T) []string { if err != nil { return err } + if d.IsDir() && d.Name() == "node_modules" { + return filepath.SkipDir + } if !d.IsDir() { ext := filepath.Ext(path) if ext == ".yaml" || ext == ".hcl" { From 2ecd4a56fc30adc7b88cfe223555545e90019de9 Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 15:02:48 +0100 Subject: [PATCH 11/14] docs(ag-ui): try frontend tools on the demo page Signed-off-by: deka --- examples/ag-ui/README.md | 29 ++++++++- examples/ag-ui/index.html | 131 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 155 insertions(+), 5 deletions(-) diff --git a/examples/ag-ui/README.md b/examples/ag-ui/README.md index 4c859e1be8..2b63ea6c94 100644 --- a/examples/ag-ui/README.md +++ b/examples/ag-ui/README.md @@ -12,6 +12,8 @@ the event sequence the server sends. ## Files - `index.html`: the page. No build step, no dependency to install. +- `replay/`: a scripted replay of frontend tool runs through the same + client, see [Replay through `@ag-ui/client`](#replay-through-ag-uiclient). - `agent.yaml`: the agent served to the page. It is not in the repository (`agent.yaml` files are git-ignored): create it as shown below. @@ -19,7 +21,7 @@ the event sequence the server sends. Create `examples/ag-ui/agent.yaml`. This small team (an assistant and a poet) produces every kind of event the server sends: text, reasoning, tool calls -and steps. +and steps. Its instruction also uses the frontend tools the page offers. ```yaml models: @@ -37,6 +39,8 @@ agents: Use the think tool before answering a question that needs several steps. Hand every request for a poem, a haiku or a rhyme to the poet, then give its text to the user unchanged. + To book something, call get_browser_context for the user's time zone, + ask for the date with pick_date, and call confirm before booking. sub_agents: [poet] toolsets: - type: think @@ -89,6 +93,8 @@ requests. | Say hello | `TEXT_MESSAGE_START` / `CONTENT` / `END`: the answer is streamed. | | Ask something that needs several steps | A collapsed **Reasoning** block (`REASONING_*`) and a `think` tool call (`TOOL_CALL_*`). | | "Write a haiku about containers" | A `transfer_task` tool call, then `STEP_STARTED` / `STEP_FINISHED` around the poet's answer. | +| With **Frontend tools** checked, "Book me a table for dinner" | The page offers `pick_date`, `confirm` and `get_browser_context` in `tools`. The run ends with `RUN_FINISHED` and `pendingToolCallIds`: the page answers `get_browser_context` itself, shows a date picker and Yes/No buttons, then sends the results in the next run, which the agent continues. | +| Ignore the date picker and send a new message | The server gives the call the error result `the application did not answer this tool call` (`TOOL_CALL_RESULT` at the start of the run). | | Ask for a long text, then **Stop** | The client closes the connection, which cancels the run on the server. | | Reload the page and ask "what did I say before?" | The thread ID is kept, and the conversation is stored on the server: the agent remembers. | | **New thread** | A fresh conversation, in a new server-side session. | @@ -105,6 +111,27 @@ Tools run on the server under the `restricted` safety policy unless `--safety` says otherwise. The guide has the details: [AG-UI Protocol](../../docs/features/ag-ui/index.md). +Frontend tools go to the root agent only: the poet, reached through +`transfer_task`, doesn't get them. The guide covers the details: +[Frontend tools](../../docs/features/ag-ui/index.md#frontend-tools). + +## Replay through `@ag-ui/client` + +`replay/replay.mjs` replays frontend tool runs through `@ag-ui/client`, +pinned to 1.0.5 with a lockfile, against a test server whose model is +scripted: no API key needed. It checks what the client derives from the +stream (pending calls, the call ID reused over rounds and turns, the final +text, a refused history-only run) and exits non-zero on the first failed +assertion. It is run by hand, not in CI: + +```console +$ npm ci --prefix examples/ag-ui/replay +$ AGUI_TS_REPLAY=1 go test -run TestTSReplay ./pkg/agui/ +``` + +`TestTSReplay` (`pkg/agui/ts_replay_test.go`) starts the server, runs the +script with `node` and checks the results the model got. + ## Without a browser ```console diff --git a/examples/ag-ui/index.html b/examples/ag-ui/index.html index 122b334af6..191e0ac91d 100644 --- a/examples/ag-ui/index.html +++ b/examples/ag-ui/index.html @@ -49,6 +49,9 @@ .tool b { font-family: var(--mono); } .tool pre { margin: 4px 0 0; font: 11px/1.4 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; max-height: 140px; overflow-y: auto; } .tool .result { border-top: 1px solid var(--line); margin-top: 6px; padding-top: 4px; } + .ask { align-self: flex-start; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; background: var(--tool); border: 1px solid var(--accent); border-radius: 8px; padding: 8px 10px; } + .ask.done { border-color: var(--line); color: var(--muted); } + label.inline { flex-direction: row; align-items: center; gap: 4px; align-self: center; font-size: 12px; } .step { align-self: center; font-size: 11px; color: var(--muted); } .error { align-self: stretch; background: var(--error-bg); color: var(--error); border-radius: 8px; padding: 8px 12px; } .error code { font-family: var(--mono); font-weight: 600; } @@ -68,13 +71,14 @@

Docker Agent · AG-UI demo

+ idle

Conversation

-

Send a message to start a run. The thread lives on the server: after a reload, keep the same thread ID and the agent still remembers the conversation. Try “Write a haiku about containers” to see a hand-over to the poet.

+

Send a message to start a run. The thread lives on the server: after a reload, keep the same thread ID and the agent still remembers the conversation. Try “Write a haiku about containers” to see a hand-over to the poet, or, with frontend tools on, “Book me a table for dinner” to have the agent ask through the page.

@@ -109,6 +113,70 @@

AG-UI events

$("thread").value = stored("thread", crypto.randomUUID()); store("thread", $("thread").value); +$("offer-tools").checked = stored("tools", "true") === "true"; + +// Frontend tools: the agent calls them, the page runs them and sends the +// result in the next run. Each one returns its answer, or waits for the user. +const frontendTools = { + pick_date: { + description: "Ask the user to pick a date in the page. Returns the date as YYYY-MM-DD.", + parameters: { type: "object", properties: { question: { type: "string", description: "What the date is for" } }, required: ["question"] }, + ask: (args, answer) => { + const date = el("input"); + date.type = "date"; + const ok = el("button", "primary", "Send date"); + ok.type = "button"; + ok.onclick = () => date.value && answer(date.value); + return [args.question ?? "Pick a date", date, ok]; + }, + }, + confirm: { + description: "Ask the user to confirm an action in the page. Returns \"yes\" or \"no\".", + parameters: { type: "object", properties: { message: { type: "string", description: "What to confirm" } }, required: ["message"] }, + ask: (args, answer) => { + const yes = el("button", "primary", "Yes"); + const no = el("button", "", "No"); + yes.type = no.type = "button"; + yes.onclick = () => answer("yes"); + no.onclick = () => answer("no"); + return [args.message ?? "Confirm?", yes, no]; + }, + }, + get_browser_context: { + description: "Returns the user's time zone, language and local time, from the browser.", + parameters: { type: "object", properties: {} }, + run: () => JSON.stringify({ + timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, + language: navigator.language, + localTime: new Date().toString(), + }), + }, +}; + +function offeredTools() { + if (!$("offer-tools").checked) return []; + return Object.entries(frontendTools).map(([name, { description, parameters }]) => ({ name, description, parameters })); +} + +// The calls waiting for the user: a new message sends the answers already +// given, and the server gives the others an error result. +let waiting = null; + +function addResults({ ids, results }) { + // A result follows its call's message, before any later message. + for (const id of ids.filter((id) => results.has(id))) { + const at = messages.findIndex((m) => m.toolCalls?.some((c) => c.id === id)); + messages.splice(at + 1, 0, { id: crypto.randomUUID(), role: "tool", toolCallId: id, content: results.get(id) }); + } +} + +function closeWidgets() { + for (const widget of waiting?.widgets ?? []) { + widget.classList.add("done"); + widget.querySelectorAll("button, input").forEach((n) => { n.disabled = true; }); + } +} + // What the client believes the history is. The server only reads the user // messages that end it, and keeps its own copy of everything else. let messages = []; @@ -179,8 +247,9 @@

AG-UI events

toolCalls.get(event.toolCallId)?.args.append(event.delta); break; case "TOOL_CALL_RESULT": { - const call = toolCalls.get(event.toolCallId); - if (call) call.card.append(el("pre", "result", event.content)); + // A call of an earlier run: a frontend call the page left unanswered. + const call = toolCalls.get(event.toolCallId) ?? { card: addToChat(el("div", "tool", `Result of ${event.toolCallId}`)) }; + call.card.append(el("pre", "result", event.content)); break; } case "STEP_STARTED": @@ -220,11 +289,13 @@

AG-UI events

setStatus("running…", "running"); let outcome = "finished"; + let pending = []; const render = renderer(); try { - await agent.runAgent({ runId }, { + await agent.runAgent({ runId, tools: offeredTools() }, { onEvent: ({ event }) => { if (event.type === "RUN_ERROR") outcome = event.code ?? "failed"; + if (event.type === "RUN_FINISHED") pending = event.outcome?.pendingToolCallIds ?? []; render(event); }, }); @@ -242,6 +313,49 @@

AG-UI events

setRunning(false); setStatus(outcome, outcome === "finished" ? "" : "failed"); $("retry").disabled = outcome === "finished"; + if (outcome === "finished" && pending.length > 0) answerCalls(pending); +} + +// Runs the pending frontend calls, then sends every result in one run. +function answerCalls(ids) { + const calls = new Map(messages.flatMap((m) => m.toolCalls ?? []).map((c) => [c.id, c])); + const current = { ids, results: new Map(), widgets: [] }; + const { results } = current; + waiting = current; + const send = () => { + if (waiting !== current || results.size < ids.length) return; + waiting = null; + addResults(current); + run(); + }; + setStatus(`waiting for ${ids.length} answer(s)`, "running"); + for (const id of ids) { + const call = calls.get(id); + const tool = frontendTools[call?.function.name]; + let args = {}; + try { args = JSON.parse(call?.function.arguments || "{}"); } catch {} + const answer = (content) => { + if (results.has(id)) return; + results.set(id, content); + logLine("", "answer", `${id}: ${content}`); + if (results.size < ids.length) setStatus(`waiting for ${ids.length - results.size} answer(s)`, "running"); + send(); + }; + if (!tool) { + answer(JSON.stringify({ error: `unknown tool ${call?.function.name}` })); + } else if (tool.run) { + answer(tool.run(args)); + } else { + const widget = addToChat(el("div", "ask")); + widget.append(...tool.ask(args, (content) => { + widget.classList.add("done"); + widget.querySelectorAll("button, input").forEach((n) => { n.disabled = true; }); + widget.append(` → ${content}`); + answer(content); + })); + current.widgets.push(widget); + } + } } $("composer").addEventListener("submit", (event) => { @@ -249,6 +363,11 @@

AG-UI events

const text = $("prompt").value.trim(); if (!text || running) return; $("prompt").value = ""; + if (waiting) { + closeWidgets(); + addResults(waiting); + waiting = null; + } messages = [...messages, { id: crypto.randomUUID(), role: "user", content: text }]; addToChat(el("div", "msg user", text)); run(); @@ -272,12 +391,16 @@

AG-UI events

if (running) return; $("thread").value = crypto.randomUUID(); store("thread", $("thread").value); + closeWidgets(); + waiting = null; messages = []; $("chat").replaceChildren(); $("retry").disabled = true; setStatus("idle"); }); +$("offer-tools").addEventListener("change", () => store("tools", $("offer-tools").checked)); + $("clear-log").addEventListener("click", () => $("log").replaceChildren()); From b9d382349573c97ae3e6a2ca154fa0e2f7a6544a Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 16:26:23 +0100 Subject: [PATCH 12/14] fix(ag-ui): classify a streamed tool call under its dispatched name A malformed name the runtime repairs before dispatch is now repaired before its partial call is emitted, so a frontend call's raw arguments wait for the hooks and the client sees only the canonical name. Addresses review comment https://github.com/docker/docker-agent/pull/5122#discussion_r4801467181. Signed-off-by: deka --- pkg/agui/frontend_tools_test.go | 64 ++++++++++++++++++--------------- pkg/runtime/loop.go | 11 ++++-- pkg/runtime/streaming.go | 10 +++--- 3 files changed, 51 insertions(+), 34 deletions(-) diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index 8a20b7552d..2009ba2d3c 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -569,38 +569,46 @@ func TestFrontendTools_ClientGetsRewrittenArguments(t *testing.T) { "tool_input_transform": {ToolInputTransform: []latest.HookMatcherConfig{{Matcher: ".*", Hooks: []latest.HookDefinition{{Type: "builtin", Command: hookName}}}}}, "pre_tool_use": {PreToolUse: []latest.HookMatcherConfig{{Matcher: ".*", Hooks: []latest.HookDefinition{{Type: "builtin", Command: hookName}}}}}, } { - t.Run(name, func(t *testing.T) { - t.Parallel() + // The runtime repairs a malformed name before dispatch. + for _, streamed := range []string{"pick_date", `pick_date" after="secret-value`} { + t.Run(name+"/"+streamed, func(t *testing.T) { + t.Parallel() + testClientGetsRewrittenArguments(t, hookName, config, streamed) + }) + } + } +} - // Streamed as deltas: the secret arrives before any hook runs. - prov := script(toolCall("pick_date", `{"after":`, `"secret-value"}`), text("Booked")) - server := startServerWithSafety(t, singleAgentTeam(prov, dagent.WithHooks(config)), session.NewInMemorySessionStore(), session.SafetyPolicyBalanced, RunOptions{}) - server.srv.runtimeOpts = func() []runtime.Opt { - registry := hooks.NewRegistry() - err := registry.RegisterBuiltin(hookName, func(_ context.Context, in *hooks.Input, _ []string) (*hooks.Output, error) { - return &hooks.Output{HookSpecificOutput: &hooks.HookSpecificOutput{ - HookEventName: in.HookEventName, - UpdatedInput: map[string]any{"after": "REDACTED"}, - }}, nil - }) - if err != nil { - panic(err) - } - return []runtime.Opt{runtime.WithHooksRegistry(registry)} - } +func testClientGetsRewrittenArguments(t *testing.T, hookName string, config *latest.HooksConfig, streamed string) { + t.Helper() - status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) - require.Equal(t, http.StatusOK, status, body) - assert.NotContains(t, body, "secret-value") - assert.Equal(t, []string{ - "RUN_STARTED runId=run-1 threadId=thread-1", - "TOOL_CALL_START toolCallId=call-1 toolCallName=pick_date", - `TOOL_CALL_ARGS delta={"after":"REDACTED"} toolCallId=call-1`, - "TOOL_CALL_END toolCallId=call-1", - "RUN_FINISHED outcome=map[pendingToolCallIds:[call-1] type:success] runId=run-1 threadId=thread-1", - }, render(events)) + // Streamed as deltas: the secret arrives before any hook runs. + prov := script(toolCall(streamed, `{"after":`, `"secret-value"}`), text("Booked")) + server := startServerWithSafety(t, singleAgentTeam(prov, dagent.WithHooks(config)), session.NewInMemorySessionStore(), session.SafetyPolicyBalanced, RunOptions{}) + server.srv.runtimeOpts = func() []runtime.Opt { + registry := hooks.NewRegistry() + err := registry.RegisterBuiltin(hookName, func(_ context.Context, in *hooks.Input, _ []string) (*hooks.Output, error) { + return &hooks.Output{HookSpecificOutput: &hooks.HookSpecificOutput{ + HookEventName: in.HookEventName, + UpdatedInput: map[string]any{"after": "REDACTED"}, + }}, nil }) + if err != nil { + panic(err) + } + return []runtime.Opt{runtime.WithHooksRegistry(registry)} } + + status, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, http.StatusOK, status, body) + assert.NotContains(t, body, "secret-value") + assert.Equal(t, []string{ + "RUN_STARTED runId=run-1 threadId=thread-1", + "TOOL_CALL_START toolCallId=call-1 toolCallName=pick_date", + `TOOL_CALL_ARGS delta={"after":"REDACTED"} toolCallId=call-1`, + "TOOL_CALL_END toolCallId=call-1", + "RUN_FINISHED outcome=map[pendingToolCallIds:[call-1] type:success] runId=run-1 threadId=thread-1", + }, render(events)) } var servedPolicies = []session.SafetyPolicy{ diff --git a/pkg/runtime/loop.go b/pkg/runtime/loop.go index 9b768457cf..52c19e0b76 100644 --- a/pkg/runtime/loop.go +++ b/pkg/runtime/loop.go @@ -1464,8 +1464,7 @@ func (r *LocalRuntime) recordAssistantMessage( // in conversation history. calls := res.Calls for i, tc := range calls { - if !validToolNameRe.MatchString(tc.Function.Name) { - safe := sanitizeToolCallName(tc.Function.Name) + if safe := canonicalToolName(tc.Function.Name); safe != tc.Function.Name { slog.WarnContext(ctx, "Sanitizing malformed tool call name", "agent", a.Name(), "original", tc.Function.Name, @@ -1589,6 +1588,14 @@ func sanitizeToolCallName(name string) string { return name } +// canonicalToolName is the name a call is recorded and dispatched under. +func canonicalToolName(name string) string { + if validToolNameRe.MatchString(name) { + return name + } + return sanitizeToolCallName(name) +} + // usageHasTokens reports whether any billable tokens were recorded for a turn. // Used to suppress the missing-price warning for empty/no-op turns. func usageHasTokens(usage *chat.Usage) bool { diff --git a/pkg/runtime/streaming.go b/pkg/runtime/streaming.go index fcd5321612..f6d313b409 100644 --- a/pkg/runtime/streaming.go +++ b/pkg/runtime/streaming.go @@ -220,8 +220,8 @@ func handleStream(ctx context.Context, cancelStream context.CancelCauseFunc, str fullContent.Reset() fullContent.WriteString(textBefore) for _, tc := range toolCalls { - toolDef := toolDefMap[tc.Function.Name] - events.Emit(PartialToolCall(tc, toolDef, a.Name())) + tc.Function.Name = canonicalToolName(tc.Function.Name) + events.Emit(PartialToolCall(tc, toolDefMap[tc.Function.Name], a.Name())) } } @@ -363,17 +363,19 @@ mainLoop: // on every token. if tc.Function.Name != "" && (learningName || delta.Function.Arguments != "") { if !emittedPartial[delta.ID] || delta.Function.Arguments != "" { + // Named as dispatch will name it: the definition says whether the call is the client's. + name := canonicalToolName(tc.Function.Name) partial := tools.ToolCall{ ID: tc.ID, Type: tc.Type, Function: tools.FunctionCall{ - Name: tc.Function.Name, + Name: name, Arguments: delta.Function.Arguments, }, } toolDef := tools.Tool{} if !emittedPartial[delta.ID] { - toolDef = toolDefMap[tc.Function.Name] + toolDef = toolDefMap[name] } events.Emit(PartialToolCall(partial, toolDef, a.Name())) emittedPartial[delta.ID] = true From 4f674c9871d2fe512a2aa68b672f4be579527312 Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 16:28:50 +0100 Subject: [PATCH 13/14] fix(ag-ui): reserve the wire IDs of threads without call records A thread stored before call records gets its calls' possible wire IDs (X, X-2, ...) reserved, so a new call reusing a runtime ID never takes an ID the client already holds. Addresses review comment https://github.com/docker/docker-agent/pull/5122#discussion_r4801467201. Signed-off-by: deka --- docs/features/ag-ui/index.md | 4 +- pkg/agui/frontend_tools.go | 25 ++++++++++++ pkg/agui/frontend_tools_test.go | 70 ++++++++++++++++++++++++++------- 3 files changed, 83 insertions(+), 16 deletions(-) diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index 24d13aa964..74bfeabdaf 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -174,8 +174,8 @@ Notes: [interrupt](#tool-approval-interrupts): its calls without a result get it in the resumed run. The other exception is a call to a [frontend tool](#frontend-tools): the client runs it. -- A `toolCallId` names one call of the thread. Models reuse IDs from one turn - to the next (`call_0` for tool calls parsed from text): a reused ID gets a +- A `toolCallId` names one call of the thread, threads from earlier versions + included. Models reuse IDs from one turn to the next (`call_0` for tool calls parsed from text): a reused ID gets a suffix (`call_0-2`), since `@ag-ui/client` merges calls that share an ID. - `RUN_FINISHED` means the run completed normally, or paused on an interrupt when it carries `outcome: {"type": "interrupt"}`. A run that leaves calls to diff --git a/pkg/agui/frontend_tools.go b/pkg/agui/frontend_tools.go index 9b989a8ec7..f52fc541ee 100644 --- a/pkg/agui/frontend_tools.go +++ b/pkg/agui/frontend_tools.go @@ -48,9 +48,34 @@ func (s *server) trackCalls(ctx context.Context, tr *translator, sess *session.S for _, r := range storedCalls(sess) { tr.wireIDs[r.Wire] = true } + for _, wire := range legacyWireIDs(sess) { + tr.wireIDs[wire] = true + } tr.saveCalls = s.callSaver(ctx, sess) } +// legacyWireIDs returns the wire IDs a server without call records may have +// streamed for the calls of the thread: X for the first call X of a run, then +// X-2, X-3... Counting over the whole thread covers every run. +func legacyWireIDs(sess *session.Session) []string { + seen := make(map[string]int) + var out []string + for _, m := range sess.GetAllMessages() { + for _, tc := range m.Message.ToolCalls { + if tc.ID == "" { + continue + } + seen[tc.ID]++ + if n := seen[tc.ID]; n == 1 { + out = append(out, tc.ID) + } else { + out = append(out, fmt.Sprintf("%s-%d", tc.ID, n)) + } + } + } + return out +} + // callSaver adds the calls of a run to those of its session, in memory and // in the store: the runtime may save the session again after the run. func (s *server) callSaver(ctx context.Context, sess *session.Session) func([]callRecord) error { diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index 2009ba2d3c..f6bb559cce 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -15,6 +15,7 @@ import ( "testing" "time" + "github.com/ag-ui-protocol/ag-ui/sdks/community/go/pkg/core/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -852,12 +853,14 @@ func TestFrontendTools_CancelledExpiredInterrupt(t *testing.T) { } // A thread from a server that kept no tool call records still continues: a -// reused ID it suffixed comes back as history. +// reused ID it suffixed comes back as history, and a new call never takes a +// wire ID the client already holds. func TestFrontendTools_LegacyThreadWithSuffixedIDs(t *testing.T) { t.Parallel() var executions atomic.Int32 - prov := script(calls(call("call_0", "lookup", `{}`)), calls(call("call_0", "lookup", `{}`)), text("done"), calls(call("c9", "lookup", `{}`)), text("again"), text("more")) + // The first frontend call after the upgrade reuses call_0. + prov := script(calls(call("call_0", "lookup", `{}`)), calls(call("call_0", "lookup", `{}`)), text("done"), calls(call("call_0", "pick_date", `{}`)), text("again"), text("more")) store := session.NewInMemorySessionStore() server := startServer(t, singleAgentTeam(prov, dagent.WithTools(echoTool(&executions))), store, RunOptions{}) @@ -868,29 +871,68 @@ func TestFrontendTools_LegacyThreadWithSuffixedIDs(t *testing.T) { stored.DeleteAttribute(callsAttribute) require.NoError(t, store.UpdateSession(t.Context(), stored)) - history := []map[string]any{ - userMsg("u1", "Look"), - assistantCall("call_0", "lookup"), toolMsg("call_0", "sunny"), - assistantCall("call_0-2", "lookup"), toolMsg("call_0-2", "sunny"), + client := newReferenceClient(t, server.url) + offered := []types.Tool{sdkPickDate} + legacyCall := func(id string) types.Message { + return types.Message{ID: id, Role: types.RoleAssistant, ToolCalls: []types.ToolCall{{ID: id, Type: "function", Function: types.FunctionCall{Name: "lookup", Arguments: "{}"}}}} + } + client.messages = []types.Message{ + {ID: "u1", Role: types.RoleUser, Content: "Look"}, + legacyCall("call_0"), + {ID: "call_0-answer", Role: types.RoleTool, Content: "sunny", ToolCallID: "call_0"}, + legacyCall("call_0-2"), + {ID: "call_0-2-answer", Role: types.RoleTool, Content: "sunny", ToolCallID: "call_0-2"}, + {ID: "u2", Role: types.RoleUser, Content: "Again"}, } - server.run(t, frontendInput("thread-1", "run-2", append(history, userMsg("u2", "Again"))...)) - // Once the thread has records again. - stored, err = store.GetSession(t.Context(), sessionIDFor("thread-1")) + _, err = client.run(types.RunAgentInput{ThreadID: "thread-1", RunID: "run-2", Messages: client.messages, Tools: offered}) require.NoError(t, err) - require.Contains(t, stored.AttributesSnapshot(), callsAttribute) - history = append(history, userMsg("u2", "Again"), assistantCall("c9", "lookup"), toolMsg("c9", "sunny")) - lines = server.run(t, frontendInput("thread-1", "run-3", append(history, userMsg("u3", "More"))...)) - assert.Equal(t, "RUN_FINISHED runId=run-3 threadId=thread-1", lines[len(lines)-1]) + pending := client.pendingToolCalls() + require.Equal(t, []string{"call_0-3"}, pending) + // Each call keeps a message of its own on the client. + for _, id := range []string{"call_0", "call_0-2", "call_0-3"} { + assert.Equal(t, 1, countFunc(client.messages, func(m types.Message) bool { + return slices.ContainsFunc(m.ToolCalls, func(tc types.ToolCall) bool { return tc.ID == id }) + }), id) + } + client.answer(pending[0], "2026-12-25") + _, err = client.run(types.RunAgentInput{ThreadID: "thread-1", RunID: "run-3", Messages: client.messages, Tools: offered}) + require.NoError(t, err) + results := prov.toolResults(prov.callCount() - 1) + assert.Equal(t, "call_0: 2026-12-25", results[len(results)-1]) + assert.Equal(t, "again", lastContent(t, client.messages)) + + client.messages = append(client.messages, types.Message{ID: "u3", Role: types.RoleUser, Content: "More"}) + _, err = client.run(types.RunAgentInput{ThreadID: "thread-1", RunID: "run-4", Messages: client.messages, Tools: offered}) + require.NoError(t, err) + assert.Equal(t, "more", lastContent(t, client.messages)) assert.Equal(t, 6, prov.callCount()) + assert.EqualValues(t, 2, executions.Load()) // An ID the thread never had is still refused. + history := []map[string]any{ + userMsg("u1", "Look"), + assistantCall("call_0", "lookup"), toolMsg("call_0", "sunny"), + assistantCall("call_0-2", "lookup"), toolMsg("call_0-2", "sunny"), + userMsg("u2", "Again"), + assistantCall("call_0-3", "pick_date"), toolMsg("call_0-3", "2026-12-25"), + } for _, id := range []string{"nope-2", "call_1-2", "call_0-1", "call_0-02"} { - status, _, body := server.post(t, frontendInput("thread-1", "run-4", append(history, toolMsg(id, "x"), userMsg("u4", "Last"))...)) + status, _, body := server.post(t, frontendInput("thread-1", "run-5", append(history, toolMsg(id, "x"), userMsg("u4", "Last"))...)) assert.Equal(t, http.StatusBadRequest, status, id) assert.Contains(t, body, "is unknown on this thread", id) } } +func countFunc[T any](s []T, f func(T) bool) int { + n := 0 + for _, v := range s { + if f(v) { + n++ + } + } + return n +} + // A cancel rejected for an invalid result leaves the expired interrupt to // its corrected retry, which still reports the calls it abandoned. func TestFrontendTools_RejectedCancelKeepsTheExpiredInterrupt(t *testing.T) { From 54907584c103a69ff8cad2521161187c6da965d1 Mon Sep 17 00:00:00 2001 From: deka Date: Fri, 4 Dec 2026 16:38:46 +0100 Subject: [PATCH 14/14] fix(ag-ui): keep the routing activation when answering frontend tool calls A run that only answers client-executed calls takes up the saved routing invocation instead of starting a new one, so the calling agent's before_agent_run hook does not fire again. New user input still starts a new invocation. Addresses review comment 4801467222. Signed-off-by: deka --- docs/features/ag-ui/index.md | 4 +- pkg/agui/frontend_tools_test.go | 192 ++++++++++++++++++++++++++++++++ pkg/agui/server.go | 1 + pkg/runtime/loop.go | 2 +- pkg/runtime/routing.go | 57 +++++++++- pkg/session/branch.go | 1 + pkg/session/session.go | 5 + 7 files changed, 259 insertions(+), 3 deletions(-) diff --git a/docs/features/ag-ui/index.md b/docs/features/ag-ui/index.md index 74bfeabdaf..610cba39b3 100644 --- a/docs/features/ag-ui/index.md +++ b/docs/features/ag-ui/index.md @@ -558,7 +558,9 @@ in the next run. reference client inserts it there, before the messages of later calls). Set `error` to report a failed call: the model sees the content followed by the error. The run needs no new user message, and the agent that made the call continues the - turn, also after a handoff; a new user message starts at the entry agent. Results the + turn, also after a handoff or a route: its routing invocation goes on, so + `before_agent_run` does not fire again. A new user message starts at the + entry agent, under a new invocation. Results the thread already holds, resent as history, are ignored, including those of threads from earlier versions, which kept no `ag-ui.tool-calls` records (a suffixed `call_0-2` stands for the stored `call_0`). A `toolCallId` the diff --git a/pkg/agui/frontend_tools_test.go b/pkg/agui/frontend_tools_test.go index f6bb559cce..1aa2847874 100644 --- a/pkg/agui/frontend_tools_test.go +++ b/pkg/agui/frontend_tools_test.go @@ -760,6 +760,198 @@ func TestFrontendTools_AnswerAfterARoute(t *testing.T) { assert.EqualValues(t, 1, routes.Load()) } +// The calling agent was reached after another agent completed: the run that +// answers its calls keeps its routing activation, so its before_agent_run +// hook, which saw the previous output, does not run again and route away. +func TestFrontendTools_AnswerKeepsTheRoutingActivation(t *testing.T) { + t.Parallel() + + const toBooker, bookerBefore = "test-route-to-booker", "test-booker-before" + var activations atomic.Int32 + var previous []string + registry := func() []runtime.Opt { + registry := hooks.NewRegistry() + err := errors.Join( + registry.RegisterBuiltin(toBooker, func(context.Context, *hooks.Input, []string) (*hooks.Output, error) { + return &hooks.Output{HookSpecificOutput: &hooks.HookSpecificOutput{ + HookEventName: hooks.EventAfterAgentComplete, + Transition: &hooks.Transition{Action: hooks.TransitionActionRoute, Agent: "booker"}, + }}, nil + }), + registry.RegisterBuiltin(bookerBefore, func(_ context.Context, in *hooks.Input, _ []string) (*hooks.Output, error) { + activations.Add(1) + previous = append(previous, in.PreviousOutput) + if in.PreviousOutput != "" { + return nil, nil + } + // Without the previous output, the request goes back to root. + return &hooks.Output{HookSpecificOutput: &hooks.HookSpecificOutput{ + HookEventName: hooks.EventBeforeAgentRun, + Transition: &hooks.Transition{Action: hooks.TransitionActionRoute, Agent: "root"}, + }}, nil + }), + ) + if err != nil { + panic(err) + } + return []runtime.Opt{runtime.WithHooksRegistry(registry)} + } + + pick := func(id string) []chat.MessageStreamResponse { return calls(call(id, "pick_date", `{}`)) } + rootProv := script(text("draft"), text("draft again")) + bookerProv := script(pick("c1"), pick("c2"), text("Booked"), text("Booked again")) + newTeam := func() *team.Team { + booker := dagent.New("booker", "You book", dagent.WithModel(bookerProv), + dagent.WithRouting(dagent.Routing{AllowedAgents: []string{"root"}}), + dagent.WithHooks(&latest.HooksConfig{BeforeAgentRun: latest.HookDefinitions{{Type: "builtin", Command: bookerBefore}}})) + root := dagent.New("root", "You draft", dagent.WithModel(rootProv), + dagent.WithRouting(dagent.Routing{AllowedAgents: []string{"booker"}}), + dagent.WithHooks(&latest.HooksConfig{AfterAgentComplete: latest.HookDefinitions{{Type: "builtin", Command: toBooker}}})) + return team.New(team.WithAgents(root, booker)) + } + dbPath := filepath.Join(t.TempDir(), "session.db") + store, err := sqlitestore.New(t.Context(), dbPath) + require.NoError(t, err) + before := startServer(t, newTeam(), store, RunOptions{}) + before.srv.runtimeOpts = registry + + _, events, body := before.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, []any{"c1"}, pendingOf(t, events), body) + require.NoError(t, store.Close()) + + // Taken up after a restart. + reopened, err := sqlitestore.New(t.Context(), dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = reopened.Close() }) + server := startServer(t, newTeam(), reopened, RunOptions{}) + server.srv.runtimeOpts = registry + + // A failed continuation is retried with the same activation. + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25")} + bookerProv.setErr(assert.AnError) + failed := server.run(t, frontendInput("thread-1", "run-2", history...)) + require.True(t, strings.HasPrefix(failed[len(failed)-1], "RUN_ERROR"), failed) + bookerProv.setErr(nil) + _, events, body = server.post(t, frontendInput("thread-1", "run-2", history...)) + require.Equal(t, []any{"c2"}, pendingOf(t, events), body) + assert.Equal(t, "c1: 2026-12-25", bookerProv.toolResults(bookerProv.callCount() - 1)[0]) + + // A second pause in the same invocation. + history = append(history, assistantCall("c2", "pick_date"), toolMsg("c2", "2026-12-26")) + lines := server.run(t, frontendInput("thread-1", "run-3", history...)) + assert.Contains(t, lines, "TEXT_MESSAGE_CONTENT delta=Booked messageId=m1") + assert.Equal(t, []string{"c1: 2026-12-25", "c2: 2026-12-26"}, bookerProv.toolResults(bookerProv.callCount()-1)) + assert.EqualValues(t, 1, activations.Load()) + assert.Equal(t, 1, rootProv.callCount()) + + // New input starts a new invocation. + server.run(t, frontendInput("thread-1", "run-4", append(history, userMsg("u2", "Again"))...)) + assert.EqualValues(t, 2, activations.Load()) + assert.Equal(t, []string{"draft", "draft again"}, previous) + assert.Equal(t, 2, rootProv.callCount()) +} + +// The same after a handoff in a routed thread: neither agent's before_agent_run +// runs again for the answer. +func TestFrontendTools_AnswerAfterARoutedHandoff(t *testing.T) { + t.Parallel() + + const rootBefore, bookerBefore = "test-root-before", "test-booker-before" + var rootRuns, bookerRuns atomic.Int32 + bookerProv := script(calls(call("c1", "pick_date", `{}`)), text("Booked")) + booker := dagent.New("booker", "You book", dagent.WithModel(bookerProv), + dagent.WithHooks(&latest.HooksConfig{BeforeAgentRun: latest.HookDefinitions{{Type: "builtin", Command: bookerBefore}}})) + rootProv := script(calls(call("h1", "handoff", `{"agent":"booker"}`))) + root := dagent.New("root", "You route", dagent.WithModel(rootProv), dagent.WithToolSets(handoff.New()), dagent.WithHandoffs(booker), + dagent.WithHooks(&latest.HooksConfig{BeforeAgentRun: latest.HookDefinitions{{Type: "builtin", Command: rootBefore}}})) + server := startServer(t, team.New(team.WithAgents(root, booker)), sqliteStore(t), RunOptions{}) + server.srv.runtimeOpts = func() []runtime.Opt { + registry := hooks.NewRegistry() + count := func(n *atomic.Int32) hooks.BuiltinFunc { + return func(context.Context, *hooks.Input, []string) (*hooks.Output, error) { + n.Add(1) + return nil, nil + } + } + if err := errors.Join(registry.RegisterBuiltin(rootBefore, count(&rootRuns)), registry.RegisterBuiltin(bookerBefore, count(&bookerRuns))); err != nil { + panic(err) + } + return []runtime.Opt{runtime.WithHooksRegistry(registry)} + } + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, []any{"c1"}, pendingOf(t, events), body) + require.EqualValues(t, 1, rootRuns.Load()) + require.EqualValues(t, 1, bookerRuns.Load()) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("h1", "handoff"), toolMsg("h1", "ok"), assistantCall("c1", "pick_date"), toolMsg("c1", "2026-12-25")} + lines := server.run(t, frontendInput("thread-1", "run-2", history...)) + assert.Contains(t, lines, "TEXT_MESSAGE_CONTENT delta=Booked messageId=m1") + assert.Contains(t, bookerProv.toolResults(1), "c1: 2026-12-25") + assert.Equal(t, 1, rootProv.callCount()) + assert.EqualValues(t, 1, rootRuns.Load()) + assert.EqualValues(t, 1, bookerRuns.Load()) +} + +// New input ends the paused invocation in the store too: a retry of its failed +// run, which offered no frontend tool, does not take the old one up. +func TestFrontendTools_NewInputDropsThePausedActivation(t *testing.T) { + t.Parallel() + + const toBooker, bookerBefore = "test-route-to-booker", "test-booker-before" + var invocations []string + var bookerProv *scriptedProvider + failing := tools.Tool{ + Name: "lookup", + Parameters: map[string]any{}, + Handler: func(context.Context, tools.ToolCall, tools.Runtime) (*tools.ToolCallResult, error) { + bookerProv.setErr(assert.AnError) + return tools.ResultSuccess("sunny"), nil + }, + } + bookerProv = script(calls(call("c1", "pick_date", `{}`)), calls(call("l1", "lookup", `{}`)), text("Booked")) + booker := dagent.New("booker", "You book", dagent.WithModel(bookerProv), dagent.WithTools(failing), + dagent.WithHooks(&latest.HooksConfig{BeforeAgentRun: latest.HookDefinitions{{Type: "builtin", Command: bookerBefore}}})) + root := dagent.New("root", "You route", dagent.WithModel(script()), + dagent.WithRouting(dagent.Routing{AllowedAgents: []string{"booker"}}), + dagent.WithHooks(&latest.HooksConfig{BeforeAgentRun: latest.HookDefinitions{{Type: "builtin", Command: toBooker}}})) + server := startServer(t, team.New(team.WithAgents(root, booker)), sqliteStore(t), RunOptions{}) + server.srv.runtimeOpts = func() []runtime.Opt { + registry := hooks.NewRegistry() + err := errors.Join( + registry.RegisterBuiltin(toBooker, func(context.Context, *hooks.Input, []string) (*hooks.Output, error) { + return &hooks.Output{HookSpecificOutput: &hooks.HookSpecificOutput{ + HookEventName: hooks.EventBeforeAgentRun, + Transition: &hooks.Transition{Action: hooks.TransitionActionRoute, Agent: "booker"}, + }}, nil + }), + registry.RegisterBuiltin(bookerBefore, func(_ context.Context, in *hooks.Input, _ []string) (*hooks.Output, error) { + invocations = append(invocations, in.InvocationID) + return nil, nil + }), + ) + if err != nil { + panic(err) + } + return []runtime.Opt{runtime.WithHooksRegistry(registry)} + } + + _, events, body := server.post(t, frontendInput("thread-1", "run-1", userMsg("u1", "Book"))) + require.Equal(t, []any{"c1"}, pendingOf(t, events), body) + + history := []map[string]any{userMsg("u1", "Book"), assistantCall("c1", "pick_date"), userMsg("u2", "Never mind, look it up")} + failed := server.run(t, inputWith("thread-1", "run-2", nil, nil, history...)) + require.True(t, strings.HasPrefix(failed[len(failed)-1], "RUN_ERROR"), failed) + + bookerProv.setErr(nil) + history = append(history, assistantCall("l1", "lookup"), map[string]any{"id": "l1-result", "role": "tool", "toolCallId": "l1", "content": "sunny"}) + retried := server.run(t, inputWith("thread-1", "run-3", nil, nil, history...)) + assert.Equal(t, "RUN_FINISHED runId=run-3 threadId=thread-1", retried[len(retried)-1]) + // A new invocation, not the one paused in run-1. + require.Len(t, invocations, 3) + assert.NotContains(t, invocations[:2], invocations[2]) +} + // A forced handoff or a route also moves the thread's session to another // agent: its tools take precedence over a frontend tool of the same name. func TestFrontendTools_RouteTargets(t *testing.T) { diff --git a/pkg/agui/server.go b/pkg/agui/server.go index 380337e21d..a27fde379c 100644 --- a/pkg/agui/server.go +++ b/pkg/agui/server.go @@ -626,6 +626,7 @@ func (s *server) resolveSession(ctx context.Context, sessionID string, in *runIn if prompt == nil { // A handoff moved only the previous runtime's agent. answered.agent = turnAgent(sess) + sess.ContinuesTurn = true } if err := s.storeAnswers(ctx, sess, in.threadID, answered); err != nil { return nil, nil, err diff --git a/pkg/runtime/loop.go b/pkg/runtime/loop.go index 52c19e0b76..677c08df9d 100644 --- a/pkg/runtime/loop.go +++ b/pkg/runtime/loop.go @@ -313,7 +313,7 @@ func (r *LocalRuntime) runStreamLoop(ctx context.Context, sess *session.Session, // pick the agent that actually runs, before anything is prepared for it. var route *routeState if starting { - route = r.beginRouting(sess) + route = r.startRouting(ctx, sess) } else { route = resume.State.Route } diff --git a/pkg/runtime/routing.go b/pkg/runtime/routing.go index a20b9c5109..e24a14394b 100644 --- a/pkg/runtime/routing.go +++ b/pkg/runtime/routing.go @@ -2,6 +2,7 @@ package runtime import ( "context" + "encoding/json" "fmt" "log/slog" "strconv" @@ -104,6 +105,59 @@ func (r *LocalRuntime) beginRouting(sess *session.Session) *routeState { return newRouteState(sess) } +// routeAttribute keeps the routing activation of a session that offers +// client-executed tools: the run that continues the turn with their answers +// takes it up instead of starting a new invocation. +const routeAttribute = "runtime.route" + +// savedRoute is a routing activation as a later run takes it up. +type savedRoute struct { + Route *routeState `json:"route"` + // Agent is the session's route agent, "" at the entry agent. + Agent string `json:"agent,omitempty"` +} + +// startRouting returns the routing state a starting run begins with: the +// saved activation for a run that continues the turn, otherwise a new +// invocation, which drops any saved one. +func (r *LocalRuntime) startRouting(ctx context.Context, sess *session.Session) *routeState { + raw, saved := sess.AttributesSnapshot()[routeAttribute] + if saved && sess.ContinuesTurn { + var s savedRoute + if err := json.Unmarshal([]byte(raw), &s); err == nil && s.Route != nil { + sess.SetRouted() + sess.SetRouteAgent(s.Agent) + return s.Route + } + slog.WarnContext(ctx, "Ignoring unreadable routing activation", "session_id", sess.ID) + } + if saved { + sess.DeleteAttribute(routeAttribute) + r.persistRoute(ctx, sess) + } + return r.beginRouting(sess) +} + +// saveRoute keeps the activation of a session whose turn may end on calls the +// client answers in a later run, as soon as it changes. +func (r *LocalRuntime) saveRoute(ctx context.Context, sess *session.Session, route *routeState) { + if route == nil || len(sess.ClientTools) == 0 || sess.IsSubSession() { + return + } + raw, err := json.Marshal(savedRoute{Route: route, Agent: sess.RouteAgent()}) + if err != nil || sess.AttributesSnapshot()[routeAttribute] == string(raw) { + return + } + sess.SetAttribute(routeAttribute, string(raw)) + r.persistRoute(ctx, sess) +} + +func (r *LocalRuntime) persistRoute(ctx context.Context, sess *session.Session) { + if err := r.sessionStore.UpdateSession(context.WithoutCancel(ctx), sess); err != nil { + slog.WarnContext(ctx, "Failed to persist the routing activation", "session_id", sess.ID, "error", err) + } +} + // restartRouting starts a new invocation at the entry agent for input that // arrived while the previous one was running. func (r *LocalRuntime) restartRouting(sess *session.Session, ls *loopState) { @@ -141,11 +195,12 @@ func (r *LocalRuntime) activateAgent(ctx context.Context, sess *session.Session, return a, stop } if next == nil { - return a, nil + break } r.applyRoute(ctx, sess, a, next, route, string(hooks.EventBeforeAgentRun), result, events) a = next } + r.saveRoute(ctx, sess, route) return a, nil } diff --git a/pkg/session/branch.go b/pkg/session/branch.go index b16d9f0b24..fbad00cc19 100644 --- a/pkg/session/branch.go +++ b/pkg/session/branch.go @@ -110,6 +110,7 @@ func (s *Session) Clone() *Session { AllowedTools: slices.Clone(s.AllowedTools), ExtraToolSets: slices.Clone(s.ExtraToolSets), ClientTools: slices.Clone(s.ClientTools), + ContinuesTurn: s.ContinuesTurn, DisableStructuredOutput: s.DisableStructuredOutput, AgentName: s.AgentName, allowAgentHandoffs: s.allowAgentHandoffs, diff --git a/pkg/session/session.go b/pkg/session/session.go index 313a79cf82..675127040d 100644 --- a/pkg/session/session.go +++ b/pkg/session/session.go @@ -433,6 +433,11 @@ type Session struct { // tool of the same name wins. Not persisted: set per run. ClientTools []tools.Tool `json:"-"` + // ContinuesTurn marks a run that continues the last turn without new user + // input (answers to client-executed calls, or the retry of a run that + // stored them): it keeps that turn's routing activation. Not persisted. + ContinuesTurn bool `json:"-"` + // DisableStructuredOutput, when true, exempts this session from tool-mode // structured-output enforcement: the internal output tool is not offered // and plain-text finals are accepted. Used by fork-mode skill