Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): host tool contract - capabilities, validation, images, RPC verbs (#386) (#9053)
Akarshan Biswascc4927cff78f
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdxindex 3cc46d4f6..fa8a061ea 100644--- a/docs/src/pages/docs/agent/cli.mdx+++ b/docs/src/pages/docs/agent/cli.mdx@@ -110,7 +110,8 @@ jan cli agent run --max-turns 5 --max-session-tokens 20000 "triage the build fai| `--provider`, `--api-key` | Credential overrides for this run || `--output-format <FORMAT>` | `text` (default) streams the answer; `json` prints one result object; `stream-json` prints one JSON event per line || `--input-format <FORMAT>` | `text` (default) ignores stdin; `stream-json` reads client messages while the run is in flight. Requires `--output-format stream-json` |-| `--host-tools <FILE>` | JSON file declaring tools **the client executes**, as a list of `{"name", "description", "parameters"}`. The model calls them as `host__<name>`; each call arrives as a `tool_request` on stdout and must be answered with a `tool_result` on stdin, so this requires `--input-format stream-json`. Validated before the run starts |+| `--host-tools <FILE>` | JSON file declaring tools **the client executes**, as a list of `{"name", "description", "parameters", "capability"}`. The model calls them as `host__<name>` (see [name mapping](#host-tools)); each call arrives as a `tool_request` on stdout and must be answered with a `tool_result` on stdin, so this requires `--input-format stream-json`. Validated before the run starts |+| `--host-gate` | The host approves its own tool calls: the run raises no `permission_request` for any host tool, whatever its capability. Built-in tools are unaffected. Requires `--host-tools` |<Callout type="info">`run` takes a positional task, so a space-separated `--resume ID` would swallow it. Write the value@@ -207,6 +208,7 @@ thing that can answer a permission request and it needs to be reading them.| Follow-up turn with an image | `{"type":"user","content":[{"type":"text","text":"what changed here?"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgo..."}}]}` || Permission answer | `{"type":"permission","request_id":"perm-1","decision":"allow_once"}` || Host tool result | `{"type":"tool_result","request_id":"host-1","content":"{\"ok\":true}","is_error":false}` |+| Host tool result with an image | `{"type":"tool_result","request_id":"host-2","content":[{"type":"text","text":"front camera"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgo..."}}],"details":{"exposure":12}}` || Stop the run | `{"type":"abort"}` |A follow-up joins the run at the next turn boundary. A `user` message carries either `text` or@@ -227,29 +229,101 @@ line cannot end a healthy run.#### Host toolsA host tool is one the **client** implements: a device only the host can reach, an editor's own-buffer, anything whose state does not live in this process. Declare the set with `--host-tools`,-and the run advertises each to the model as `host__<name>`.+buffer, anything whose state does not live in this process. Declare the set with `--host-tools`:++```json+[+ {"name": "camera", "description": "Grab a frame.", "capability": "read"},+ {"name": "yam.move_ee_ik", "description": "Move the arm.", "capability": "actuator",+ "parameters": {"type": "object", "properties": {"joints": {"type": "array", "items": {"type": "number"}, "minItems": 6}}, "required": ["joints"]}}+]+```++Each tool is advertised to the model as `host__<name>`. A name that is not ASCII letters, digits,+`_` and `-`, contains `__`, or would make the advertised name longer than 64 characters is+**mapped** rather than refused: other characters become `_`, and an 8-hex-digit hash of the+original name is appended so names that sanitize alike stay distinct. `yam.move_ee_ik` is+advertised as `host__yam_move_ee_ik_<hash>`. The mapping is deterministic, and `init.tool_specs`+shows the name the model will call. Still refused: an empty name, a name with a control character,+a built-in's name (`bash`, `read`, ...), and two declarations that land on the same advertised name.When the model calls one, the run emits a `tool_request` and waits:```json-{"type":"tool_request","request_id":"host-1","tool_name":"robot_arm_move","args":{"position":"bin"}}+{"type":"tool_request","request_id":"host-1","tool_name":"yam.move_ee_ik","args":{"joints":[0,0,0,0,0,0]}}```-`tool_name` is the name **you declared**, not the `host__`-prefixed one the model calls: you-dispatch on the name you chose. Answer it with a `tool_result` carrying the same `request_id`.-`content` is a string and is required even for a failure -- set `is_error: true` and put the reason-in `content`, which reaches the model as the tool's error. Each `request_id` is answerable once.+`tool_name` is the name **you declared**, never the advertised one: you dispatch on the name you+chose. A call made by a subagent carries that subagent's `run_id` as well; a main-run request has+none. Answer either with a `tool_result` carrying the same `request_id`.++Before a request is emitted, the call's arguments are checked against the tool's `parameters`. A+call that breaks the schema never reaches you; the model is told+`ERROR: arguments for host tool '<name>' do not match its schema: /joints: expected at least 6 items, got 3`+and can try again. The check covers `type`, `properties`, `required`, `additionalProperties`,+`items`, `minItems`, `maxItems`, `enum`, `const`, `minLength`, `maxLength`, `minimum`, `maximum`,+`exclusiveMinimum`, `exclusiveMaximum` and `pattern`; any other keyword is ignored, never failed.++`content` is required even for a failure -- set `is_error: true` and put the reason in `content`,+which reaches the model as the tool's error. It is either a string or a content-part array of+`text` and `image_url` parts, held to the same caps as a `user` message. The parts are kept as the+tool message, in order, in the session transcript; the `tool_result` event carries only their text+(or `(image)` for an image alone).++<a id="tool-result-images"></a>Where an image lands on the provider request depends on the provider's API:++| Provider API | Tool image goes |+|---|---|+| OpenAI-compatible (`/chat/completions`, local servers, most gateways) | Tool message carries the text; the images lead the next user turn, each labeled with the call it answers |+| Anthropic Messages | Inside the call's `tool_result` block, as `image` blocks |+| Google Gemini 3+ | Nested in the call's `functionResponse.parts` as `inlineData` |+| Google Gemini 2.x and earlier | Beside the `functionResponse`, in the same turn |+| OpenAI Responses | In the `function_call_output`'s item list, as `input_image` |++Gemini accepts only inline (`data:`) images in a tool result; a remote image URL there is dropped. An+image in the transcript is re-sent on every later request of the session, and it is **not counted**+by the context indicator or auto-compaction (an image's token cost depends on its resolution and+the provider). A tool that returns a frame every turn should keep images small, or return a+fresh frame only when asked.++An optional `details` object is for your own display: it is **never sent to the model**, and the+run echoes it as a record right after that call's `tool_result`:++```json+{"type":"tool_details","id":"call_7","details":{"exposure":12}}+```-A host tool is gated exactly as an MCP tool is: prompted rather than auto-approved (its-`permission_request` carries `prompt_kind: "mcp"`, the class for any opaque third-party-capability, naming the qualified `host__<name>`), withheld entirely in read-only plan mode, and-subject to the same deny list. The `init` handshake echoes the schemas actually advertised in-`tool_specs`, so a tool you declared but that is missing there was withheld by policy and will-never be called.+`details` are run-scoped: they are not saved with the thread, so a resumed session has the tool+result but not its details. Keep anything your UI needs after a resume on your side, keyed by the+call `id`.++A result over a cap is an `input_error` and the request stays pending, so you can answer again.+Each `request_id` is answerable once; a late or repeated answer is an `input_error` naming it as not+pending.++`capability` decides how a call is treated:++| `capability` | Prompted | Plan mode | Several in one turn |+| --- | --- | --- | --- |+| `read` | never | advertised | run concurrently |+| `actuator` | always, even when the run auto-approves | withheld | one at a time |+| absent | unless the run auto-approves (the default; `--safe` turns it off) | withheld | one at a time |++A prompt is a `permission_request` with `prompt_kind: "mcp"`, naming the advertised+`host__<name>`. With `--host-gate` none is raised for any host tool, because your `tool_request`+handler is the gate. The deny list applies to every class. The `init` handshake echoes the schemas+actually advertised in `tool_specs`, so a tool you declared that is missing there was withheld by+policy and will never be called. Host tools are never served by `jan mcp serve`.++A request you should no longer answer is withdrawn with a record, printed before the final `result`:++```json+{"type":"tool_request_cancelled","request_id":"host-1","reason":"aborted"}+```-Because only the client can answer, a `tool_request` left unanswered when stdin closes is failed-rather than left to hang: the model is told the client is gone and the turn finishes.+`reason` is `aborted` after an `abort` message (the model is told the call was cancelled) and+`client_gone` when stdin closed first (it is told the client is gone). Either way the turn finishes+rather than hanging on an answer that cannot arrive.<Callout type="info">Closing stdin is not an abort -- the run finishes and still prints its `result`. But it does end the@@ -337,7 +411,7 @@ turn/completed -> {sessionId,turnId,The `item/*` payload contains the existing `StreamEvent` object unchanged. A client can also call `session/list`, `session/resume`, `session/fork`, `session/archive`, `turn/steer`, `turn/interrupt` and `permission/respond {requestId,decision}`. Session ids address this **process**, not another RPC process. `turn/interrupt` closes the turn with one `turn/completed` carrying `stopReason: "interrupted"`, and puts that record on the wire before it answers the request. A client that closes stdin ends the process, and the turn that is still running is closed with `stopReason: "interrupted"` before it exits. An outstanding permission request is never granted - closing the channel is not an approval, and the gate's fallback for a request that is dropped without an answer is denial. Only one turn is active per process; a second `turn/start` returns `-32001` with `data.retryable: true` rather than silently queueing it, and so does a `turn/start` arriving while the output queue has no room left for the terminal record - the turn is refused instead of accepted and then lost. `turn/completed.stopReason` is the turn's outcome (`completed`, `error`, `interrupted`), not the upstream finish reason: that one is the `stop_reason` inside `item/done`. Transport errors (`-32700` malformed JSON, `-32600` invalid request, `-32601` unknown method, `-32602` bad params) differ from an agent failure reported by `turn/completed` with `stopReason: "error"`.-Input frames are capped at 16 MiB and the writer queue holds at most 1025 records. If a client stops reading, the queue stops growing and the turn ends with a terminal overload outcome rather than the run accumulating deltas without bound; the process stays alive while the writer is blocked on the full stdout pipe, and that outcome is delivered as soon as the client reads again. The server exits when stdin closes, or when a later record finds the client gone. `--max-turns` is a one-shot flag rather than a session setting: an RPC turn runs until it finishes or a client sends `turn/interrupt`. `ephemeral: true` skips thread persistence. Host tool callbacks are **not implemented** on this RPC surface yet; `session/start` refuses a `tools` field rather than advertising it as supported. The `schema` command below documents the older `stream-json` channel, while `rpc-schema` describes this RPC envelope, accepted requests and event types. RPC clients use `turn/completed`, not the process exit code, to classify an individual turn.+Input frames are capped at 16 MiB and the writer queue holds at most 1025 records. If a client stops reading, the queue stops growing and the turn ends with a terminal overload outcome rather than the run accumulating deltas without bound; the process stays alive while the writer is blocked on the full stdout pipe, and that outcome is delivered as soon as the client reads again. The server exits when stdin closes, or when a later record finds the client gone. `--max-turns` is a one-shot flag rather than a session setting: an RPC turn runs until it finishes or a client sends `turn/interrupt`. `ephemeral: true` skips thread persistence. Host tools are declared on `session/start` (`tools`, `builtins`) and answered with `tool/respond`; see [Protocol](./protocol#rpc-host-tools). The `schema` command below documents the older `stream-json` channel, while `rpc-schema` describes this RPC envelope, accepted requests and event types. RPC clients use `turn/completed`, not the process exit code, to classify an individual turn.### `schema`diff --git a/docs/src/pages/docs/agent/protocol.mdx b/docs/src/pages/docs/agent/protocol.mdxindex 30d741a32..fbbb90e2d 100644--- a/docs/src/pages/docs/agent/protocol.mdx+++ b/docs/src/pages/docs/agent/protocol.mdx@@ -25,9 +25,10 @@ CLI run, start with the [Agent quickstart](/docs/agent/quickstart); for an embeddefinitions. Read its `protocol_version`, `envelope`, `requests`, `notifications` and `events`sections to navigate the artifact rather than copying field declarations from this page. Printit with `jan cli agent rpc-schema`, or write it with- `jan cli agent rpc-schema --out protocol/rpc-schema.json`. The implementation and artifact are in- [PR #9049](https://github.com/janhq/jan/pull/9049), which is in review, not released. See the- [CLI `rpc` section](/docs/agent/cli#rpc) for the proposed transport.+ `jan cli agent rpc-schema --out protocol/rpc-schema.json`. The transport merged in+ [PR #9049](https://github.com/janhq/jan/pull/9049) and is not in a release yet. See the+ [CLI `rpc` section](/docs/agent/cli#rpc) for the transport and [RPC host tools](#rpc-host-tools)+ below for host callbacks.Both artifacts are generated and checked for drift against their Rust source by the `protocolschema` job in `.github/workflows/rust-check.yml`, which regenerates both and fails the job on a@@ -45,9 +46,9 @@ publishing or deploying a client.| | `stream-json` | RPC | ACP || --- | --- | --- | --- |-| **Release state** | **Shipped** in `main` | **In review**, not released | **Planned**, no implementation |-| **Record reference** | Generated `protocol/schema.json` | Generated `protocol/rpc-schema.json`, committed on the PR #9049 branch | No ACP record artifact or implemented surface |-| **Evidence** | `src-tauri/src/core/cli/protocol_schema.rs:73-84,103-124`; `.github/workflows/rust-check.yml:130-176`; [PR #9023](https://github.com/janhq/jan/pull/9023) merged | `src-tauri/src/core/cli/rpc.rs:258-297`; `src-tauri/src/core/cli/rpc_schema.rs:87-106`; [PR #9049](https://github.com/janhq/jan/pull/9049) open, [#360](https://github.com/janhq/jan-internal/issues/360) open | [#347](https://github.com/janhq/jan-internal/issues/347) open; no ACP subcommand in `src-tauri/jan-cli/src/main.rs:443-521` |+| **Release state** | **Shipped** in `main` | **Merged** in `main`, not released | **Planned**, no implementation |+| **Record reference** | Generated `protocol/schema.json` | Generated `protocol/rpc-schema.json` | No ACP record artifact or implemented surface |+| **Evidence** | `src-tauri/src/core/cli/protocol_schema.rs:73-84,103-124`; `.github/workflows/rust-check.yml:130-176`; [PR #9023](https://github.com/janhq/jan/pull/9023) merged | `src-tauri/src/core/cli/rpc.rs:258-297`; `src-tauri/src/core/cli/rpc_schema.rs:87-106`; [PR #9049](https://github.com/janhq/jan/pull/9049) merged, [#360](https://github.com/janhq/jan-internal/issues/360) open | [#347](https://github.com/janhq/jan-internal/issues/347) open; no ACP subcommand in `src-tauri/jan-cli/src/main.rs:443-521` |A schema says which records a transport accepts or emits. A surface inventory would say whatthat surface *can* do, but the table above is an evidence-backed release snapshot, not a generated@@ -58,8 +59,82 @@ what **this RPC session** negotiated (`src-tauri/src/core/cli/rpc.rs:286-297`).`stream-json`'s `init` fields into RPC or treat a negotiated response as universal availability.<Callout type="warning">-RPC is implemented in an open PR, not a shipped CLI or SDK release. ACP remains planned. JavaScript-and Python SDK packages are not released ([#367](https://github.com/janhq/jan-internal/issues/367)),-and host-tool callbacks are not available ([#368](https://github.com/janhq/jan-internal/issues/368)).-Use the shipped `stream-json` transport if you need an integration today.+RPC is not in a shipped CLI or SDK release yet. ACP remains planned. JavaScript and Python SDK+packages are not released ([#367](https://github.com/janhq/jan-internal/issues/367)). Host tools+exist on both `stream-json` (`--host-tools`) and RPC (below).</Callout>++## RPC host tools++A host declares tools on `session/start`; the model calls them, Jan sends the call to the host,+and the host's answer becomes the model's tool message. Request and parameter shapes are in the+`requests` section of `protocol/rpc-schema.json`.++### Declaring tools++`session/start` accepts three optional fields next to `cwd`, `model` and `ephemeral`:++| Field | Default | Meaning |+| --- | --- | --- |+| `tools` | `[]` | Declarations `{name, description?, parameters?, capability?}`. `capability` is `read` or `actuator`; absent is opaque. |+| `builtins` | `true` | `false` advertises only the host tools: no built-ins, MCP, plugin, `ask`, `todo`, subagent or monitor tools. |+| `permissions` | `"jan"` | `"host"` means the host's callback is the gate: Jan never sends a `permission_request` for a host tool. Built-ins are unaffected. |++The result is `{sessionId, model, tools, toolSpecs}`. `tools` lists the names the next turn+advertises (with `builtins: false`, only the host tools). `toolSpecs` echoes the schemas of the+host tools that are actually advertised, so a host can compare them with what it sent and see a+tool that a deny list or Plan mode withheld. A declaration Jan refuses (reserved name, duplicate,+unknown key, non-object `parameters`) fails the whole call with `-32602` and+`data: {"kind": "invalid_tools"}`, and the message names the problem.++Host tools are advertised as `host__<name>`. Every other tool source has its own prefix+(`plugin__`, MCP server names) and duplicates within the host set are refused, so a host tool can+never shadow or be shadowed by another source. The host's own name is what it receives back.++### Answering calls++A call arrives as the notification `item/tool_request` with+`event: {request_id, tool_name, args, run_id?}`. `run_id` is set when a subagent made the call.+Answer it with:++```json+{"jsonrpc":"2.0","id":7,"method":"tool/respond","params":{+ "requestId":"host-1",+ "content":[{"type":"text","text":"frame captured"},+ {"type":"image_url","image_url":{"url":"data:image/png;base64,..."}}],+ "isError":false,+ "details":{"frame":7}}}+```++`content` is a string or an array of `text` / `image_url` parts, and images are held to the same+caps as a user message. The parts are kept, in order, as the tool message in the transcript; where+an image goes on the provider request depends on the provider's API (see+[tool result images](./cli#tool-result-images)). `details` is for the host's display only: Jan+emits it as `item/tool_details`, never sends it to the model, and does not persist it with the+thread. A reply for a request that is no longer pending (already answered, cancelled, or never+issued) fails with `-32602` and `data: {"kind": "not_pending"}`.++`turn/interrupt` withdraws every request the host still holds. For each one Jan sends+`item/tool_request_cancelled` with `reason: "interrupted"`, and all of them arrive before the+turn's `turn/completed`. When stdin closes, pending requests are cancelled the same way with+`reason: "client_gone"`, but those records are best effort.++### Changing a session between turns++| Method | Params | Result |+| --- | --- | --- |+| `session/tools/get` | `{sessionId}` | `{tools, toolSpecs}` |+| `session/tools/set` | `{sessionId, tools}` | `{tools, toolSpecs}`. Replaces the host set; refusals are `invalid_tools`. |+| `session/model/set` | `{sessionId, model}` | `{model}`. History, host tools, `builtins` and `permissions` are kept. |+| `session/reset` | `{sessionId}` | `{tools, toolSpecs}`. History is cleared; model and tools are kept. |++These four methods are refused while that session's turn is running: `-32001` with+`data: {"retryable": true, "kind": "turn_active"}`. Retry after `turn/completed`. (`session/fork`+and `session/archive` of a busy session, and a second `turn/start`, keep their plain retryable+`-32001`.) An unknown `sessionId` is `-32602`. `session/fork` copies the host+tools, `builtins` and `permissions`, but pending requests are never shared between sessions.+`session/list` entries include `hostTools`, the number of declared host tools.++Every mutating method is answered. A client that gets no answer, for example because the process+died, should treat the session as gone and close it. This fail-closed handling belongs to the SDK+or client, not the wire protocol.diff --git a/docs/src/pages/docs/agent/sdk.mdx b/docs/src/pages/docs/agent/sdk.mdxindex 557dfa9ff..8e384f754 100644--- a/docs/src/pages/docs/agent/sdk.mdx+++ b/docs/src/pages/docs/agent/sdk.mdx@@ -19,14 +19,15 @@ terminal, not for embedding an SDK.| --- | --- | --- || Use Jan interactively or run a one-shot CLI task | Available in the Jan CLI | [Agent quickstart](/docs/agent/quickstart) and [CLI reference](/docs/agent/cli) || Embed the current `stream-json` CLI transport | Shipped; your application owns the Jan process and stdin/stdout | [CLI `run` and `schema` reference](/docs/agent/cli#streaming-json-in-both-directions) and [generated record guide](/docs/agent/protocol) |-| Embed addressable sessions with RPC | Implemented in [PR #9049](https://github.com/janhq/jan/pull/9049), in review; not released | [CLI `rpc` reference](/docs/agent/cli#rpc) and [generated record guide](/docs/agent/protocol) for evaluating the proposed surface |+| Embed addressable sessions with RPC | Merged in [PR #9049](https://github.com/janhq/jan/pull/9049); not in a release yet | [CLI `rpc` reference](/docs/agent/cli#rpc) and [generated record guide](/docs/agent/protocol) |+| Let the model call tools your application runs | Available over `stream-json` (`--host-tools`) and RPC (`session/start` `tools`, `tool/respond`); not in a release yet | [RPC host tools](/docs/agent/protocol#rpc-host-tools) and [CLI `run` reference](/docs/agent/cli#streaming-json-in-both-directions) || Build a JavaScript or TypeScript app with the SDK | Planned; package not released ([#367](https://github.com/janhq/jan-internal/issues/367)) | Use `stream-json` now, or wait for the JS/TS SDK quickstart || Build a Python app with the SDK | Planned; package not released ([#367](https://github.com/janhq/jan-internal/issues/367)) | Use `stream-json` now, or wait for the Python SDK quickstart |<Callout type="warning">-No JavaScript or Python Jan Agent SDK package is installable yet. The RPC implementation is in-review, not a released SDK or a substitute for the shipped `stream-json` transport. Host-owned tool-callbacks are not available yet ([#368](https://github.com/janhq/jan-internal/issues/368)).+No JavaScript or Python Jan Agent SDK package is installable yet. RPC is merged but not in a+release, and it is a transport, not an SDK. Host tool callbacks work on both transports: declared,+correlated by request id, answered with text or content parts, and cancelled on interrupt.</Callout>## Guides and recipes on the way@@ -37,15 +38,16 @@ These are planned pages, not links to runnable examples or released APIs:| --- | --- | --- || JavaScript / TypeScript quickstart (`sdk-ts.mdx`) | First embedded turn, streamed outcome, one host tool, close | Released JS/TS SDK and host callbacks || Python quickstart (`sdk-python.mdx`) | Direct Python runtime, first turn, host tool, close without Node | Released Python SDK and host callbacks |-| Host tools (`sdk-tools.mdx`) | Callback validation, correlated results, permission and active tools | Host callback contract ([#368](https://github.com/janhq/jan-internal/issues/368)) |+| Host tools (`sdk-tools.mdx`) | Callback validation, correlated results, permission and active tools as SDK calls | Released SDKs (the wire contract is in [RPC host tools](/docs/agent/protocol#rpc-host-tools)) || Images (`sdk-images.mdx`) | Prompt images, image-bearing results and sampled capture | Corresponding runtime and SDK support || Runtime and failures (`sdk-runtime.mdx`) | Process ownership, shutdown, permission and recovery | Released SDK runtime contract || Migration (`sdk-migration.mdx`) | Moving an existing `stream-json` harness to an SDK | Released SDKs and feature parity || Examples (`sdk-examples.mdx`) | Task-based index of checked-in, verified recipes | Runnable released-SDK examples |For wire shapes you can inspect today, use the [generated protocol records](/docs/agent/protocol).-This page does not promise SDK install commands, versions, supported platforms or host callbacks-before the packages and runtime are released. Availability checked on 2026-09-24 against+This page does not promise SDK install commands, versions or supported platforms before the+packages are released. Availability checked on 2026-09-24 against[#367](https://github.com/janhq/jan-internal/issues/367),-[#368](https://github.com/janhq/jan-internal/issues/368) and+[#368](https://github.com/janhq/jan-internal/issues/368),+[#386](https://github.com/janhq/jan-internal/issues/386) and[PR #9049](https://github.com/janhq/jan/pull/9049); recheck at publication.diff --git a/protocol/rpc-schema.json b/protocol/rpc-schema.jsonindex f4617b156..78a5abb0e 100644--- a/protocol/rpc-schema.json+++ b/protocol/rpc-schema.json@@ -82,12 +82,91 @@"ephemeral": {"type": "boolean","default": false+ },+ "tools": {+ "description": "Host tools this session may call. Kept as raw values until declaration\nso a malformed entry is reported as `invalid_tools` with the reason,\nrather than as a generic params error that names nothing.",+ "type": "array",+ "items": {+ "$ref": "#/$defs/HostToolDeclSchema"+ },+ "default": []+ },+ "builtins": {+ "description": "`false` advertises only the host tools: no built-ins, MCP, plugin,\n`ask`, `todo`, subagent or monitor tools.",+ "type": "boolean",+ "default": true+ },+ "permissions": {+ "$ref": "#/$defs/PermissionOwner",+ "default": "jan"}},"additionalProperties": false,"required": ["cwd"- ]+ ],+ "$defs": {+ "HostToolDeclSchema": {+ "description": "The declaration shape, for the document only: the dispatcher parses the\nreal `HostToolDecl`, which lives outside this module and carries no schema.",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string",+ "default": ""+ },+ "parameters": {+ "description": "JSON Schema for the arguments, advertised to the model verbatim.",+ "type": [+ "object",+ "null"+ ],+ "additionalProperties": true,+ "default": null+ },+ "capability": {+ "anyOf": [+ {+ "$ref": "#/$defs/HostCapability"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ }+ },+ "additionalProperties": false,+ "required": [+ "name"+ ]+ },+ "HostCapability": {+ "description": "What a host says a tool does, which decides how the loop treats it.\nAbsent means opaque: prompted unless `auto_approve`, sequential, withheld in\nPlan mode -- the plugin/MCP default.",+ "oneOf": [+ {+ "description": "Observes without side effects (a camera, a sensor): never prompted,\nadvertised in Plan mode, and run concurrently with other reads.",+ "type": "string",+ "const": "read"+ },+ {+ "description": "Acts on the world: prompted even under `auto_approve` unless the host\nowns the gate, run sequentially, withheld in Plan mode.",+ "type": "string",+ "const": "actuator"+ }+ ]+ },+ "PermissionOwner": {+ "description": "Who gates host tool calls. `jan` prompts through `permission_request` the\nway any opaque tool is prompted; `host` means the host's own callback is\nthe gate, so Jan never asks about a host tool.",+ "type": "string",+ "enum": [+ "jan",+ "host"+ ]+ }+ }},"session/resume": {"$schema": "https://json-schema.org/draft/2020-12/schema",@@ -196,6 +275,172 @@"requestId","decision"]+ },+ "tool/respond": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "ToolRespondParams",+ "type": "object",+ "properties": {+ "requestId": {+ "type": "string"+ },+ "content": {+ "$ref": "#/$defs/ToolResultContent"+ },+ "isError": {+ "type": "boolean",+ "default": false+ },+ "details": {+ "description": "Host/UI-only data, echoed as `item/tool_details` and never sent to the\nmodel.",+ "type": [+ "object",+ "null"+ ],+ "additionalProperties": true,+ "default": null+ }+ },+ "additionalProperties": false,+ "required": [+ "requestId",+ "content"+ ],+ "$defs": {+ "ToolResultContent": {+ "description": "A host tool's answer: text, or OpenAI content parts (`text` / `image_url`\nwith a base64 `data:` URL) under the same caps as a user message.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "array",+ "items": true+ }+ ]+ }+ }+ },+ "session/tools/get": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "SessionIdParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "sessionId"+ ]+ },+ "session/tools/set": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "SessionToolsSetParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ },+ "tools": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/HostToolDeclSchema"+ }+ }+ },+ "additionalProperties": false,+ "required": [+ "sessionId",+ "tools"+ ],+ "$defs": {+ "HostToolDeclSchema": {+ "description": "The declaration shape, for the document only: the dispatcher parses the\nreal `HostToolDecl`, which lives outside this module and carries no schema.",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string",+ "default": ""+ },+ "parameters": {+ "description": "JSON Schema for the arguments, advertised to the model verbatim.",+ "type": [+ "object",+ "null"+ ],+ "additionalProperties": true,+ "default": null+ },+ "capability": {+ "anyOf": [+ {+ "$ref": "#/$defs/HostCapability"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ }+ },+ "additionalProperties": false,+ "required": [+ "name"+ ]+ },+ "HostCapability": {+ "description": "What a host says a tool does, which decides how the loop treats it.\nAbsent means opaque: prompted unless `auto_approve`, sequential, withheld in\nPlan mode -- the plugin/MCP default.",+ "oneOf": [+ {+ "description": "Observes without side effects (a camera, a sensor): never prompted,\nadvertised in Plan mode, and run concurrently with other reads.",+ "type": "string",+ "const": "read"+ },+ {+ "description": "Acts on the world: prompted even under `auto_approve` unless the host\nowns the gate, run sequentially, withheld in Plan mode.",+ "type": "string",+ "const": "actuator"+ }+ ]+ }+ }+ },+ "session/model/set": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "SessionModelSetParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ },+ "model": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "sessionId",+ "model"+ ]+ },+ "session/reset": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "SessionIdParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "sessionId"+ ]}},"notifications": {@@ -508,7 +753,7 @@]},{- "description": "A backgrounded subagent's own internal event, tagged with its run so a\nconsumer can attribute it to the right child even when several run\nconcurrently. `event` is a non-terminal child event (Token/Step/ToolCall/\nToolResult/PermissionRequest); the child's terminal Done/Error is never\nwrapped (its result is delivered via `await_subagent`).",+ "description": "A backgrounded subagent's own internal event, tagged with its run so a\nconsumer can attribute it to the right child even when several run\nconcurrently. `event` is a non-terminal child event (Token/Step/ToolCall/\nToolResult/PermissionRequest); the child's terminal Done/Error is never\nwrapped (its result is delivered via `await_subagent`).\n\nNever a `ToolRequest`: a client answers a request by `request_id` on\nstdin, and it is told nothing about this wrapper, so a nested request\nwould be unanswerable. A child's host tool call is routed to the root\nchannel unwrapped instead, attributed by `ToolRequest.run_id`.","type": "object","properties": {"run_id": {@@ -787,6 +1032,78 @@"prompt_kind","offers_always"]+ },+ {+ "description": "A host-registered tool was called and the run is waiting for the host to\nexecute it. The client replies with a `tool_result` line carrying this\n`request_id`; until it does, the turn is parked on this one call.\n\n`tool_name` is the name the *host* declared, not the `host__`-prefixed\nname the model calls: the host dispatches on the name it chose and never\nhas to know this layer's prefixing rule.",+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string"+ },+ "tool_name": {+ "type": "string"+ },+ "args": {+ "description": "The arguments the model produced, already parsed from the call's\nJSON string. Validated against nothing here -- the host owns the\nschema it declared and is the only party that can enforce it."+ },+ "run_id": {+ "description": "Which run raised the request: `None` for the main run, the child's\nrun id for a subagent. Attribution only -- the host answers by\n`request_id` alone, and a child's request is emitted unwrapped at\nthe top level so the same answer path serves both.",+ "type": [+ "string",+ "null"+ ]+ },+ "type": {+ "type": "string",+ "const": "tool_request"+ }+ },+ "required": [+ "type",+ "request_id",+ "tool_name",+ "args"+ ]+ },+ {+ "description": "A pending [`StreamEvent::ToolRequest`] was withdrawn: the host must not\nanswer it any more, and a late answer is reported as not pending.\n`reason` is `aborted` | `interrupted` | `client_gone`.",+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string"+ },+ "reason": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "tool_request_cancelled"+ }+ },+ "required": [+ "type",+ "request_id",+ "reason"+ ]+ },+ {+ "description": "Host/UI-only structured data a host tool returned alongside its result,\nemitted right after that call's [`StreamEvent::ToolResult`] (same `id`).\nNever sent to the model; a display may render it or ignore it.",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "details": true,+ "type": {+ "type": "string",+ "const": "tool_details"+ }+ },+ "required": [+ "type",+ "id",+ "details"+ ]}],"$defs": {diff --git a/protocol/schema.json b/protocol/schema.jsonindex 77ee953b7..f5fb7dd6b 100644--- a/protocol/schema.json+++ b/protocol/schema.json@@ -327,7 +327,7 @@]},{- "description": "A backgrounded subagent's own internal event, tagged with its run so a\nconsumer can attribute it to the right child even when several run\nconcurrently. `event` is a non-terminal child event (Token/Step/ToolCall/\nToolResult/PermissionRequest); the child's terminal Done/Error is never\nwrapped (its result is delivered via `await_subagent`).\n\nNever a `ToolRequest`: a client answers a request by `request_id` on\nstdin, and it is told nothing about this wrapper, so a nested request\nwould be unanswerable. `run_subagent` clears the child's host tool set\nrather than relying on this, which is why the case cannot arise.",+ "description": "A backgrounded subagent's own internal event, tagged with its run so a\nconsumer can attribute it to the right child even when several run\nconcurrently. `event` is a non-terminal child event (Token/Step/ToolCall/\nToolResult/PermissionRequest); the child's terminal Done/Error is never\nwrapped (its result is delivered via `await_subagent`).\n\nNever a `ToolRequest`: a client answers a request by `request_id` on\nstdin, and it is told nothing about this wrapper, so a nested request\nwould be unanswerable. A child's host tool call is routed to the root\nchannel unwrapped instead, attributed by `ToolRequest.run_id`.","type": "object","properties": {"run_id": {@@ -620,6 +620,13 @@"args": {"description": "The arguments the model produced, already parsed from the call's\nJSON string. Validated against nothing here -- the host owns the\nschema it declared and is the only party that can enforce it."},+ "run_id": {+ "description": "Which run raised the request: `None` for the main run, the child's\nrun id for a subagent. Attribution only -- the host answers by\n`request_id` alone, and a child's request is emitted unwrapped at\nthe top level so the same answer path serves both.",+ "type": [+ "string",+ "null"+ ]+ },"type": {"type": "string","const": "tool_request"@@ -631,6 +638,46 @@"tool_name","args"]+ },+ {+ "description": "A pending [`StreamEvent::ToolRequest`] was withdrawn: the host must not\nanswer it any more, and a late answer is reported as not pending.\n`reason` is `aborted` | `interrupted` | `client_gone`.",+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string"+ },+ "reason": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "tool_request_cancelled"+ }+ },+ "required": [+ "type",+ "request_id",+ "reason"+ ]+ },+ {+ "description": "Host/UI-only structured data a host tool returned alongside its result,\nemitted right after that call's [`StreamEvent::ToolResult`] (same `id`).\nNever sent to the model; a display may render it or ignore it.",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "details": true,+ "type": {+ "type": "string",+ "const": "tool_details"+ }+ },+ "required": [+ "type",+ "id",+ "details"+ ]}]},@@ -919,7 +966,7 @@]},"InputContentParts": {- "description": "The caps on a `user` message's content-part array, as `init` advertises them.\n\nA client that sends an image is sending bytes into a channel with no\nbackpressure, so the limits are part of the handshake rather than something\nto discover by being rejected. Each is the cap the parser enforces: this is\nthe same constant, not a copy of it.",+ "description": "The caps on a content-part array -- a `user` message's, and a `tool_result`'s,\nwhich is held to the same limits -- as `init` advertises them.\n\nA client that sends an image is sending bytes into a channel with no\nbackpressure, so the limits are part of the handshake rather than something\nto discover by being rejected. Each is the cap the parser enforces: this is\nthe same constant, not a copy of it.","type": "object","properties": {"mime_types": {@@ -1227,19 +1274,26 @@]},{- "description": "The answer to a `tool_request` this run emitted: the host executed the\ntool and this is its result, which becomes the model's tool message.\n\n`content` is required even for a failure. A tool message with nothing in\nit tells the model only that something happened, which is worse than a\nshort error.",+ "description": "The answer to a `tool_request` this run emitted: the host executed the\ntool and this is its result, which becomes the model's tool message.\n\n`content` is required even for a failure. A tool message with nothing in\nit tells the model only that something happened, which is worse than a\nshort error. It is either a string or an OpenAI content-part array\n(`text` and `image_url` parts, under the same caps as a `user` message),\nso a camera can hand the model a frame.\n\n`details` is any JSON object the host wants a display to have. It is\nnever sent to the model: the run echoes it as a `tool_details` record\nafter the `tool_result`, and that is all.","type": "object","properties": {"request_id": {"type": "string"},"content": {- "type": "string"+ "$ref": "#/$defs/ToolResultContent"},"is_error": {"type": "boolean","default": false},+ "details": {+ "type": [+ "object",+ "null"+ ],+ "additionalProperties": true+ },"type": {"type": "string","const": "tool_result"@@ -1261,6 +1315,18 @@"allow_always","deny"]+ },+ "ToolResultContent": {+ "description": "A `tool_result`'s `content`: a plain string, or a content-part array.",+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "array",+ "items": true+ }+ ]}},"x-protocol-version": 1diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 09bbd11ca..4b71bde12 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -476,12 +476,19 @@ enum AgentCommands {#[arg(long, value_enum, default_value_t = InputFormat::Text)]input_format: InputFormat,/// JSON file declaring tools this host executes: a list of- /// `{"name", "description", "parameters"}`. The model calls them as- /// `host__<name>`; each call arrives as a `tool_request` on stdout and+ /// `{"name", "description", "parameters", "capability"}`. The model+ /// calls them as `host__<name>` (a name outside `[A-Za-z0-9_-]` is+ /// mapped to a safe one); each call arrives as a `tool_request` on stdout and/// must be answered with a `tool_result` on stdin, so this requires/// `--input-format stream-json`#[arg(long, value_name = "FILE")]host_tools: Option<String>,+ /// The host approves its own tool calls: Jan raises no+ /// `permission_request` for any host tool (built-ins are unaffected).+ /// For a host whose `tool_request` handler is itself the approval+ /// step; requires `--host-tools`+ #[arg(long, requires = "host_tools")]+ host_gate: bool,},/// Run a single turn (debugging)Step {@@ -991,6 +998,7 @@ async fn handle_agent(cmd: AgentCommands) {output_format,input_format,host_tools,+ host_gate,} => {cli_agent_run(&project,@@ -1010,6 +1018,7 @@ async fn handle_agent(cmd: AgentCommands) {output_format,input_format,host_tools.as_deref(),+ host_gate,).await}@@ -1568,6 +1577,30 @@ mod tests {.is_err());}+ /// Parse `jan cli agent run <task> <extra...>` and pull out its host gate.+ fn parsed_host_gate(extra: &[&str]) -> bool {+ let mut argv = vec!["jan", "cli", "agent", "run", "task"];+ argv.extend_from_slice(extra);+ match Cli::parse_from(argv).command {+ Some(Commands::Cli {+ cmd:+ CliCommands::Agent {+ cmd: AgentCommands::Run { host_gate, .. },+ },+ }) => host_gate,+ _ => panic!("expected `cli agent run`"),+ }+ }++ /// The gate is only the host's when the host has tools to gate: without+ /// `--host-tools` the flag would silently do nothing, so clap refuses it.+ #[test]+ fn host_gate_is_off_by_default_and_requires_host_tools() {+ assert!(!parsed_host_gate(&["--host-tools", "tools.json"]));+ assert!(parsed_host_gate(&["--host-tools", "tools.json", "--host-gate"]));+ assert!(Cli::try_parse_from(["jan", "cli", "agent", "run", "task", "--host-gate"]).is_err());+ }+/// Parse `jan cli agent run <task> <extra...>` and pull out its output format.fn parsed_output_format(extra: &[&str]) -> OutputFormat {let mut argv = vec!["jan", "cli", "agent", "run", "task"];diff --git a/src-tauri/jan-cli/tests/agent_rpc.rs b/src-tauri/jan-cli/tests/agent_rpc.rsindex 501300c83..7450da546 100644--- a/src-tauri/jan-cli/tests/agent_rpc.rs+++ b/src-tauri/jan-cli/tests/agent_rpc.rs@@ -203,8 +203,8 @@ fn rpc_serves_a_session_lifecycle_after_the_handshake() {let project = scratch.join("project");let session_id = rpc.start_session(&project);- let incompatible = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":11,"method":"session/start","params":{"cwd":project,"model":"stub-model","tools":[{"name":"host_tool"}]}}));- assert_eq!(incompatible["error"]["code"], -32602);+ let unknown_option = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":11,"method":"session/start","params":{"cwd":project,"model":"stub-model","hostTools":[]}}));+ assert_eq!(unknown_option["error"]["code"], -32602);let invalid_image = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":12,"method":"turn/start","params":{"sessionId":session_id,"input":[{"type":"image_url","image_url":{"url":"data:image/bmp;base64,AA=="}}]}}));assert_eq!(invalid_image["error"]["code"], -32602);let unknown =@@ -480,3 +480,380 @@ fn closing_stdin_closes_the_active_turn() {assert!(rpc.child.wait().unwrap().success());let _ = std::fs::remove_dir_all(scratch);}++/// The model calls the declared host tool; its arguments satisfy the schema.+const HOST_TOOL_CALL: &str = concat!(+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",",+ "\"tool_calls\":[{\"index\":0,\"id\":\"call-1\",\"type\":\"function\",\"function\":",+ "{\"name\":\"host__robot_arm_move\",\"arguments\":\"{\\\"position\\\":\\\"bin\\\"}\"}}]},",+ "\"finish_reason\":null}]}\n\n",+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{},",+ "\"finish_reason\":\"tool_calls\"}],",+ "\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2,\"total_tokens\":7}}\n\n",+ "data: [DONE]\n\n",+);++/// Plain prose, which ends the turn.+const PROSE: &str = concat!(+ "data: {\"id\":\"stub-2\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",",+ "\"content\":\"the arm reached bin\"},\"finish_reason\":null}]}\n\n",+ "data: {\"id\":\"stub-2\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],",+ "\"usage\":{\"prompt_tokens\":9,\"completion_tokens\":4,\"total_tokens\":13}}\n\n",+ "data: [DONE]\n\n",+);++/// Serve `replies` in order, one per connection, repeating the last, and keep+/// every request body: what the model was sent is where a host tool's result+/// has to land for the round trip to mean anything.+fn scripted_provider(+ replies: &'static [&'static str],+) -> (String, std::sync::Arc<std::sync::Mutex<Vec<serde_json::Value>>>) {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}/v1", listener.local_addr().unwrap());+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let sink = std::sync::Arc::clone(&seen);+ std::thread::spawn(move || {+ for (index, connection) in listener.incoming().enumerate() {+ let Ok(mut stream) = connection else { break };+ stream+ .set_read_timeout(Some(Duration::from_secs(10)))+ .unwrap();+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut size = 0;+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {+ break;+ }+ if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") {+ size = n.trim().parse().unwrap_or(0);+ }+ }+ let mut request = vec![0; size];+ if std::io::Read::read_exact(&mut reader, &mut request).is_err() {+ continue;+ }+ sink.lock()+ .unwrap()+ .push(serde_json::from_slice(&request).unwrap_or(serde_json::Value::Null));+ let reply = replies[index.min(replies.len() - 1)];+ let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len());+ }+ });+ (url, seen)+}++/// One declared host tool, as a host would send it on `session/start`.+fn arm_tool() -> serde_json::Value {+ serde_json::json!({+ "name": "robot_arm_move",+ "description": "Move the arm.",+ "parameters": {+ "type": "object",+ "properties": {"position": {"type": "string"}},+ "required": ["position"]+ }+ })+}++/// A session over `tools`, gated by the host so no `permission_request`+/// interleaves with the host tool traffic under test.+fn start_host_session(+ rpc: &mut Rpc,+ cwd: &Path,+ tools: serde_json::Value,+ builtins: bool,+) -> serde_json::Value {+ let started = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/start","params":{+ "cwd":cwd,"model":"stub-model","tools":tools,"builtins":builtins,"permissions":"host"+ }}));+ assert!(started["result"]["sessionId"].is_string(), "{started}");+ started["result"].clone()+}++/// Read until the reply to request `id`, keeping the notifications passed on+/// the way so a test can assert their order.+fn reply_to(rpc: &mut Rpc, id: u64, seen: &mut Vec<serde_json::Value>) -> serde_json::Value {+ rpc.read_until(|record| {+ if record["id"] == id {+ return true;+ }+ seen.push(record.clone());+ false+ })+ .expect("the request is answered")+}++fn tool_request_id(rpc: &mut Rpc) -> String {+ let request = rpc+ .read_until(|record| record["method"] == "item/tool_request")+ .expect("the model's call reaches the host");+ assert_eq!(request["params"]["event"]["tool_name"], "robot_arm_move", "{request}");+ assert_eq!(request["params"]["event"]["args"]["position"], "bin", "{request}");+ request["params"]["event"]["request_id"]+ .as_str()+ .expect("a request id")+ .to_owned()+}++/// The whole host tool loop over RPC: declared on `session/start`, called by+/// the model, surfaced as `item/tool_request`, answered with content parts+/// through `tool/respond`, and carried into the model's next request.+#[test]+fn a_host_tool_round_trips_with_content_parts() {+ let scratch = scratch("host-round-trip");+ let home = scratch.join("home");+ let (url, seen) = scripted_provider(&[HOST_TOOL_CALL, PROSE]);+ configure(&home, &url);+ let mut rpc = Rpc::open(&home);+ rpc.handshake();+ let project = scratch.join("project");++ let started = start_host_session(&mut rpc, &project, serde_json::json!([arm_tool()]), true);+ assert_eq!(started["model"], "stub-model", "{started}");+ let tools = started["tools"].as_array().expect("advertised names");+ assert!(tools.iter().any(|t| t == "host__robot_arm_move"), "{started}");+ assert!(tools.iter().any(|t| t == "bash"), "built-ins stay by default: {started}");+ assert_eq!(started["toolSpecs"][0]["function"]["name"], "host__robot_arm_move");+ assert_eq!(started["toolSpecs"][0]["function"]["parameters"], arm_tool()["parameters"]);+ let session_id = started["sessionId"].as_str().unwrap().to_owned();++ let turn = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"turn/start","params":{"sessionId":session_id,"input":"move the arm"}}));+ assert!(turn["result"]["turnId"].is_string(), "{turn}");+ let request_id = tool_request_id(&mut rpc);++ let image = "data:image/png;base64,iVBORw0KGgo=";+ rpc.send(serde_json::json!({"jsonrpc":"2.0","id":5,"method":"tool/respond","params":{+ "requestId":request_id,+ "content":[{"type":"text","text":"frame captured"},{"type":"image_url","image_url":{"url":image}}],+ "details":{"frame":7}+ }}));+ let mut notes = Vec::new();+ let answered = reply_to(&mut rpc, 5, &mut notes);+ assert_eq!(answered["result"], serde_json::json!({}), "{answered}");+ let terminal = rpc+ .read_until(|record| {+ notes.push(record.clone());+ record["method"] == "turn/completed"+ })+ .expect("the turn completes");+ assert_eq!(terminal["params"]["stopReason"], "completed", "{terminal}");++ // The details are the host's: surfaced as their own event and nowhere else.+ assert!(+ notes.iter().any(|n| n["method"] == "item/tool_details"+ && n["params"]["event"]["details"]["frame"] == 7),+ "{notes:?}"+ );+ // The loop's tool message is the parts, verbatim and in order.+ let history = notes+ .iter()+ .rev()+ .find(|n| n["method"] == "item/messages_updated")+ .expect("the history is published");+ let tool_message = history["params"]["event"]["messages"]+ .as_array()+ .unwrap()+ .iter()+ .find(|m| m["role"] == "tool")+ .expect("a tool message")+ .clone();+ assert_eq!(tool_message["content"][0]["text"], "frame captured", "{tool_message}");+ assert_eq!(tool_message["content"][1]["image_url"]["url"], image, "{tool_message}");++ let requests = seen.lock().unwrap();+ assert_eq!(requests.len(), 2, "the result never reached the model");+ let wire = requests[1]["messages"].as_array().unwrap();+ let tool_at = wire+ .iter()+ .position(|m| m["role"] == "tool")+ .expect("the follow-up request carries the tool message");+ // A tool message is text on the wire (`genai` tool responses are+ // text-only), so the image rides in the user turn right after it.+ assert!(wire[tool_at].to_string().contains("frame captured"), "{}", wire[tool_at]);+ let carried = &wire[tool_at + 1];+ assert_eq!(carried["role"], "user", "{carried}");+ assert!(+ carried["content"]+ .as_array()+ .expect("a content-part array")+ .iter()+ .any(|p| p["image_url"]["url"] == image),+ "the host's image reached the model: {carried}"+ );+ assert!(+ !requests[1].to_string().contains("\"frame\":7"),+ "details must never reach the model: {}",+ requests[1]+ );+ drop(requests);++ rpc.close();+ let _ = std::fs::remove_dir_all(scratch);+}++/// A host that names its tool after a built-in has misunderstood whose+/// implementation runs, and is told so before any session exists.+#[test]+fn a_reserved_host_tool_name_is_refused_as_invalid_tools() {+ let scratch = scratch("host-reserved");+ let home = scratch.join("home");+ configure(&home, &provider(1, 0));+ let mut rpc = Rpc::open(&home);+ rpc.handshake();+ let project = scratch.join("project");++ let refused = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/start","params":{"cwd":project,"model":"stub-model","tools":[{"name":"bash"}]}}));+ assert_eq!(refused["error"]["code"], -32602, "{refused}");+ assert_eq!(refused["error"]["data"]["kind"], "invalid_tools", "{refused}");+ assert!(refused["error"]["message"].as_str().unwrap().contains("reserved"), "{refused}");+ // A malformed entry is the same kind, naming where it is.+ let typo = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"session/start","params":{"cwd":project,"model":"stub-model","tools":[{"name":"x","capability":"write"}]}}));+ assert_eq!(typo["error"]["data"]["kind"], "invalid_tools", "{typo}");+ assert!(typo["error"]["message"].as_str().unwrap().contains("tools[0]"), "{typo}");+ let listed = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":5,"method":"session/list","params":{}}));+ assert_eq!(listed["result"]["sessions"], serde_json::json!([]), "{listed}");++ rpc.close();+ let _ = std::fs::remove_dir_all(scratch);+}++/// The running turn has already built its request from the session's tools,+/// model and history, so changing them mid-turn is refused as retryable; once+/// the turn ends the change applies and `session/tools/get` shows it.+#[test]+fn session_mutations_wait_for_the_active_turn() {+ let scratch = scratch("host-mutation");+ let home = scratch.join("home");+ let (url, _seen) = scripted_provider(&[HOST_TOOL_CALL, PROSE]);+ configure(&home, &url);+ let mut rpc = Rpc::open(&home);+ rpc.handshake();+ let project = scratch.join("project");+ let started = start_host_session(&mut rpc, &project, serde_json::json!([arm_tool()]), true);+ let session_id = started["sessionId"].as_str().unwrap().to_owned();++ let turn = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"turn/start","params":{"sessionId":session_id,"input":"move the arm"}}));+ assert!(turn["result"]["turnId"].is_string(), "{turn}");+ // Parked on the host: the turn is certainly still active.+ let request_id = tool_request_id(&mut rpc);++ let camera = serde_json::json!([{"name":"camera","capability":"read"}]);+ let mut notes = Vec::new();+ for (id, method, params) in [+ (5, "session/tools/set", serde_json::json!({"sessionId":session_id,"tools":camera})),+ (6, "session/model/set", serde_json::json!({"sessionId":session_id,"model":"stub-model"})),+ (7, "session/reset", serde_json::json!({"sessionId":session_id})),+ ] {+ rpc.send(serde_json::json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}));+ let refused = reply_to(&mut rpc, id, &mut notes);+ assert_eq!(refused["error"]["code"], -32001, "{method}: {refused}");+ assert_eq!(refused["error"]["data"]["kind"], "turn_active", "{method}: {refused}");+ assert_eq!(refused["error"]["data"]["retryable"], true, "{method}: {refused}");+ }+ let unknown = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":8,"method":"session/tools/get","params":{"sessionId":"nope"}}));+ assert_eq!(unknown["error"]["code"], -32602, "{unknown}");++ rpc.send(serde_json::json!({"jsonrpc":"2.0","id":9,"method":"tool/respond","params":{"requestId":request_id,"content":"moved"}}));+ let answered = reply_to(&mut rpc, 9, &mut notes);+ assert_eq!(answered["result"], serde_json::json!({}), "{answered}");+ rpc.read_until(|record| record["method"] == "turn/completed")+ .expect("the turn completes");++ let set = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":10,"method":"session/tools/set","params":{"sessionId":session_id,"tools":camera}}));+ let tools = set["result"]["tools"].as_array().expect("advertised names");+ assert!(tools.iter().any(|t| t == "host__camera"), "{set}");+ assert!(!tools.iter().any(|t| t == "host__robot_arm_move"), "the set is replaced: {set}");+ let got = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":11,"method":"session/tools/get","params":{"sessionId":session_id}}));+ assert_eq!(got["result"], set["result"], "{got}");+ let model = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":12,"method":"session/model/set","params":{"sessionId":session_id,"model":"stub-model"}}));+ assert_eq!(model["result"], serde_json::json!({"model":"stub-model"}), "{model}");+ let after_model = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":13,"method":"session/tools/get","params":{"sessionId":session_id}}));+ assert_eq!(after_model["result"], set["result"], "a model switch keeps the host tools: {after_model}");+ let reset = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":14,"method":"session/reset","params":{"sessionId":session_id}}));+ assert_eq!(reset["result"], set["result"], "a reset keeps the tools: {reset}");++ rpc.close();+ let _ = std::fs::remove_dir_all(scratch);+}++/// `builtins: false` is a session that exposes the host's tools and nothing+/// else, which the provider's request is the only honest witness of.+#[test]+fn builtins_false_advertises_only_host_tools() {+ let scratch = scratch("host-only");+ let home = scratch.join("home");+ let (url, seen) = scripted_provider(&[PROSE]);+ configure(&home, &url);+ let mut rpc = Rpc::open(&home);+ rpc.handshake();+ let project = scratch.join("project");+ let started = start_host_session(&mut rpc, &project, serde_json::json!([arm_tool()]), false);+ assert_eq!(started["tools"], serde_json::json!(["host__robot_arm_move"]), "{started}");+ let session_id = started["sessionId"].as_str().unwrap().to_owned();++ rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"turn/start","params":{"sessionId":session_id,"input":"hi"}}));+ let terminal = rpc+ .read_until(|record| record["method"] == "turn/completed")+ .expect("the turn completes");+ assert_eq!(terminal["params"]["stopReason"], "completed", "{terminal}");++ let requests = seen.lock().unwrap();+ let names: Vec<&str> = requests[0]["tools"]+ .as_array()+ .expect("the request advertises tools")+ .iter()+ .filter_map(|tool| tool["function"]["name"].as_str())+ .collect();+ assert_eq!(names, ["host__robot_arm_move"], "{}", requests[0]);+ drop(requests);++ rpc.close();+ let _ = std::fs::remove_dir_all(scratch);+}++/// An interrupt withdraws what the host still holds, and says so before the+/// turn's terminal record; an answer after that has nothing to resolve.+#[test]+fn interrupting_withdraws_pending_host_requests() {+ let scratch = scratch("host-interrupt");+ let home = scratch.join("home");+ let (url, _seen) = scripted_provider(&[HOST_TOOL_CALL, PROSE]);+ configure(&home, &url);+ let mut rpc = Rpc::open(&home);+ rpc.handshake();+ let project = scratch.join("project");+ let started = start_host_session(&mut rpc, &project, serde_json::json!([arm_tool()]), true);+ let session_id = started["sessionId"].as_str().unwrap().to_owned();++ rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"turn/start","params":{"sessionId":session_id,"input":"move the arm"}}));+ let request_id = tool_request_id(&mut rpc);++ rpc.send(serde_json::json!({"jsonrpc":"2.0","id":5,"method":"turn/interrupt","params":{"sessionId":session_id}}));+ let mut notes = Vec::new();+ let acknowledged = reply_to(&mut rpc, 5, &mut notes);+ assert_eq!(acknowledged["result"], serde_json::json!({}), "{acknowledged}");+ let cancelled = notes+ .iter()+ .position(|n| n["method"] == "item/tool_request_cancelled")+ .unwrap_or_else(|| panic!("no cancellation record: {notes:?}"));+ assert_eq!(notes[cancelled]["params"]["event"]["request_id"], request_id);+ assert_eq!(notes[cancelled]["params"]["event"]["reason"], "interrupted");+ let completed = notes+ .iter()+ .position(|n| n["method"] == "turn/completed")+ .unwrap_or_else(|| panic!("no terminal record: {notes:?}"));+ assert!(cancelled < completed, "{notes:?}");+ assert_eq!(notes[completed]["params"]["stopReason"], "interrupted");++ let late = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":6,"method":"tool/respond","params":{"requestId":request_id,"content":"too late"}}));+ assert_eq!(late["error"]["code"], -32602, "{late}");+ assert_eq!(late["error"]["data"]["kind"], "not_pending", "{late}");++ rpc.close();+ let _ = std::fs::remove_dir_all(scratch);+}diff --git a/src-tauri/jan-cli/tests/stream_json_host_tools.rs b/src-tauri/jan-cli/tests/stream_json_host_tools.rsindex b99d51c44..b4e767611 100644--- a/src-tauri/jan-cli/tests/stream_json_host_tools.rs+++ b/src-tauri/jan-cli/tests/stream_json_host_tools.rs@@ -453,3 +453,246 @@ fn a_reserved_name_is_refused_before_the_run_starts() {records[0]);}++/// The model calls `host__camera` with no arguments.+const CAMERA_CALL: &str = concat!(+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",",+ "\"tool_calls\":[{\"index\":0,\"id\":\"call-1\",\"type\":\"function\",\"function\":",+ "{\"name\":\"host__camera\",\"arguments\":\"{}\"}}]},",+ "\"finish_reason\":null}]}\n\n",+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{},",+ "\"finish_reason\":\"tool_calls\"}],",+ "\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2,\"total_tokens\":7}}\n\n",+ "data: [DONE]\n\n",+);++/// The model calls the *mapped* wire name of the dotted `yam.move_ee_ik`:+/// sanitized stem plus the first 8 hex chars of sha256("yam.move_ee_ik").+const MAPPED_CALL: &str = concat!(+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",",+ "\"tool_calls\":[{\"index\":0,\"id\":\"call-1\",\"type\":\"function\",\"function\":",+ "{\"name\":\"host__yam_move_ee_ik_c68bc455\",\"arguments\":\"{}\"}}]},",+ "\"finish_reason\":null}]}\n\n",+ "data: {\"id\":\"stub-1\",\"object\":\"chat.completion.chunk\",\"created\":1,",+ "\"model\":\"stub-model\",\"choices\":[{\"index\":0,\"delta\":{},",+ "\"finish_reason\":\"tool_calls\"}],",+ "\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2,\"total_tokens\":7}}\n\n",+ "data: [DONE]\n\n",+);++/// Run a duplex session, answering every `tool_request` with `answer(request)`,+/// and return every record up to and including the final `result`.+fn drive(+ scratch: &Scratch,+ decl: &str,+ answer: impl Fn(&serde_json::Value) -> serde_json::Value,+) -> (Vec<serde_json::Value>, Output) {+ let decl = scratch.declare(decl);+ let mut child = scratch.spawn_duplex(decl.to_str().expect("utf-8 path"));+ let mut stdin = child.stdin.take().expect("piped stdin");+ let stdout = BufReader::new(child.stdout.take().expect("piped stdout"));+ let mut seen = Vec::new();+ for line in stdout.lines() {+ let Ok(line) = line else { break };+ let Ok(msg) = serde_json::from_str::<serde_json::Value>(&line) else {+ continue;+ };+ let kind = msg["type"].as_str().unwrap_or_default().to_string();+ if kind == "tool_request" {+ writeln!(stdin, "{}", answer(&msg)).expect("answer the request");+ stdin.flush().expect("flush the answer");+ }+ seen.push(msg);+ if kind == "result" {+ break;+ }+ }+ drop(stdin);+ (seen, child.wait_with_output().expect("collect the run"))+}++/// A host answers with content parts: they become the tool message, while+/// `details` goes to the client as `tool_details` and never into a provider+/// request.+///+/// The provider sees the parts' text as the tool message and the image in the+/// user turn right after it: `genai`'s tool response is text-only, so the+/// bridge carries a tool's image there (`genai_bridge::flush_tool_images`).+/// The details never leave the host's side.+#[test]+fn host_result_parts_reach_the_model_and_details_do_not() {+ let scratch = Scratch::new("parts");+ let (url, seen) = stub_provider(&[CAMERA_CALL, ANSWER]);+ scratch.configure(&url);+ let (records, out) = drive(+ &scratch,+ r#"[{"name":"camera","description":"Grab a frame.","capability":"read"}]"#,+ |request| {+ serde_json::json!({+ "type": "tool_result",+ "request_id": request["request_id"],+ "content": [+ { "type": "text", "text": "front camera" },+ { "type": "image_url",+ "image_url": { "url": "data:image/png;base64,QUJD" } }+ ],+ "details": { "marker": "DETAILS-ONLY-FOR-THE-HOST" }+ })+ },+ );+ assert!(+ out.status.success(),+ "the run did not end cleanly: {}",+ String::from_utf8_lossy(&out.stderr)+ );++ let requests = seen.lock().expect("request log");+ assert_eq!(requests.len(), 2, "the result never reached a second turn");+ let body: serde_json::Value =+ serde_json::from_str(&requests[1]).expect("the follow-up request is JSON");+ let tool_message = body["messages"]+ .as_array()+ .expect("messages")+ .iter()+ .find(|m| m["role"] == "tool")+ .expect("a tool message in the follow-up")+ .clone();+ assert_eq!(+ tool_message["content"], "front camera",+ "the parts' text is the tool message: {tool_message}"+ );+ let messages = body["messages"].as_array().expect("messages");+ let tool_at = messages.iter().position(|m| m["role"] == "tool").expect("tool");+ let carried = &messages[tool_at + 1];+ assert_eq!(carried["role"], "user", "the image follows the tool message: {body}");+ assert!(+ carried["content"]+ .as_array()+ .expect("a content-part array")+ .iter()+ .any(|p| p["image_url"]["url"] == "data:image/png;base64,QUJD"),+ "the host's image reached the provider: {carried}"+ );+ assert!(+ !requests.iter().any(|r| r.contains("DETAILS-ONLY-FOR-THE-HOST")),+ "details leaked into a provider request"+ );++ // The client sees the text summary on `tool_result`, then the details.+ let tags: Vec<&str> = records.iter().filter_map(|r| r["type"].as_str()).collect();+ let result_at = tags.iter().position(|t| *t == "tool_result").expect("tool_result");+ assert_eq!(tags[result_at + 1], "tool_details", "{tags:?}");+ assert_eq!(records[result_at]["content"], "front camera");+ assert_eq!(+ records[result_at + 1]["details"]["marker"],+ "DETAILS-ONLY-FOR-THE-HOST"+ );+}++/// R14: a dotted host name is advertised under a provider-safe wire name, the+/// model calls that, and the host is asked under the name it declared.+#[test]+fn a_dotted_host_name_round_trips_through_its_wire_name() {+ let scratch = Scratch::new("dotted");+ let (url, seen) = stub_provider(&[MAPPED_CALL, ANSWER]);+ scratch.configure(&url);+ let (records, out) = drive(+ &scratch,+ r#"[{"name":"yam.move_ee_ik","description":"Move the arm."}]"#,+ |request| {+ serde_json::json!({+ "type": "tool_result",+ "request_id": request["request_id"],+ "content": "moved",+ })+ },+ );+ assert!(+ out.status.success(),+ "the run did not end cleanly: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ let init = records.iter().find(|r| r["type"] == "init").expect("init");+ assert_eq!(+ init["tool_specs"][0]["function"]["name"], "host__yam_move_ee_ik_c68bc455",+ "{init}"+ );+ let request = records+ .iter()+ .find(|r| r["type"] == "tool_request")+ .expect("the mapped call reached the host");+ assert_eq!(request["tool_name"], "yam.move_ee_ik", "{request}");+ assert!(request.get("run_id").is_none(), "a main-run request has no run_id");+ let requests = seen.lock().expect("request log");+ assert_eq!(requests.len(), 2);+ assert!(requests[1].contains("moved"), "{}", requests[1]);+}++/// A refused `tool_result` does not consume the request: the client is told+/// with an `input_error`, the call stays pending, and a corrected line settles+/// it. Getting a line wrong must cost the host a retry, not the whole turn.+#[test]+fn a_refused_result_leaves_the_request_pending_for_a_retry() {+ let scratch = Scratch::new("retry");+ let (url, seen) = stub_provider(&[CAMERA_CALL, ANSWER]);+ scratch.configure(&url);+ let decl = scratch.declare(r#"[{"name":"camera","description":"Grab a frame.","capability":"read"}]"#);+ let mut child = scratch.spawn_duplex(decl.to_str().expect("utf-8 path"));+ let mut stdin = child.stdin.take().expect("piped stdin");+ let stdout = BufReader::new(child.stdout.take().expect("piped stdout"));+ let mut records = Vec::new();+ let mut request_id = None;+ for line in stdout.lines() {+ let Ok(line) = line else { break };+ let Ok(msg) = serde_json::from_str::<serde_json::Value>(&line) else {+ continue;+ };+ let kind = msg["type"].as_str().unwrap_or_default().to_string();+ if kind == "tool_request" {+ request_id = Some(msg["request_id"].clone());+ // An unsupported part: refused as a whole, before it can resolve+ // the call.+ let bad = serde_json::json!({+ "type": "tool_result",+ "request_id": msg["request_id"],+ "content": [{ "type": "audio", "data": "AAAA" }],+ });+ writeln!(stdin, "{bad}").expect("send the bad result");+ stdin.flush().expect("flush");+ }+ if kind == "input_error" {+ let good = serde_json::json!({+ "type": "tool_result",+ "request_id": request_id.clone().expect("the request came first"),+ "content": "RETRIED-FRAME",+ });+ writeln!(stdin, "{good}").expect("send the corrected result");+ stdin.flush().expect("flush");+ }+ records.push(msg);+ if kind == "result" {+ break;+ }+ }+ drop(stdin);+ let out = child.wait_with_output().expect("collect the run");+ assert!(+ out.status.success(),+ "the run did not end cleanly: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ let tags: Vec<&str> = records.iter().filter_map(|r| r["type"].as_str()).collect();+ let refused = tags.iter().position(|t| *t == "input_error").expect("the bad line was refused");+ let settled = tags.iter().position(|t| *t == "tool_result").expect("the retry settled the call");+ assert!(refused < settled, "{tags:?}");+ assert!(+ !tags.contains(&"tool_request_cancelled"),+ "a refused line must not withdraw the request: {tags:?}"+ );+ let requests = seen.lock().expect("request log");+ assert_eq!(requests.len(), 2, "the turn never resumed");+ assert!(requests[1].contains("RETRIED-FRAME"), "{}", requests[1]);+}diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex bab86a896..d16f5c009 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -136,8 +136,8 @@ pub enum StreamEvent {////// Never a `ToolRequest`: a client answers a request by `request_id` on/// stdin, and it is told nothing about this wrapper, so a nested request- /// would be unanswerable. `run_subagent` clears the child's host tool set- /// rather than relying on this, which is why the case cannot arise.+ /// would be unanswerable. A child's host tool call is routed to the root+ /// channel unwrapped instead, attributed by `ToolRequest.run_id`.Subagent {run_id: String,name: String,@@ -252,6 +252,23 @@ pub enum StreamEvent {/// JSON string. Validated against nothing here -- the host owns the/// schema it declared and is the only party that can enforce it.args: serde_json::Value,+ /// Which run raised the request: `None` for the main run, the child's+ /// run id for a subagent. Attribution only -- the host answers by+ /// `request_id` alone, and a child's request is emitted unwrapped at+ /// the top level so the same answer path serves both.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ run_id: Option<String>,+ },+ /// A pending [`StreamEvent::ToolRequest`] was withdrawn: the host must not+ /// answer it any more, and a late answer is reported as not pending.+ /// `reason` is `aborted` | `interrupted` | `client_gone`.+ ToolRequestCancelled { request_id: String, reason: String },+ /// Host/UI-only structured data a host tool returned alongside its result,+ /// emitted right after that call's [`StreamEvent::ToolResult`] (same `id`).+ /// Never sent to the model; a display may render it or ignore it.+ ToolDetails {+ id: String,+ details: serde_json::Value,},}@@ -590,6 +607,21 @@ pub(crate) mod tests {request_id: "host-1".into(),tool_name: "observe".into(),args: serde_json::json!({ "camera": "front" }),+ run_id: Some("run-1".into()),+ },+ ),+ (+ "ToolRequestCancelled",+ StreamEvent::ToolRequestCancelled {+ request_id: "host-1".into(),+ reason: "aborted".into(),+ },+ ),+ (+ "ToolDetails",+ StreamEvent::ToolDetails {+ id: "t1".into(),+ details: serde_json::json!({ "pose": [0, 1] }),},),]@@ -625,7 +657,9 @@ pub(crate) mod tests {| StreamEvent::Done { .. }| StreamEvent::Error { .. }| StreamEvent::PermissionRequest { .. }- | StreamEvent::ToolRequest { .. } => {}+ | StreamEvent::ToolRequest { .. }+ | StreamEvent::ToolRequestCancelled { .. }+ | StreamEvent::ToolDetails { .. } => {}}}@@ -828,6 +862,51 @@ pub(crate) mod tests {);}+ /// `run_id` is additive: a main-run request serializes exactly as it did+ /// before the field existed, so a v1 host sees no change.+ #[test]+ fn host_tool_events_serialize_to_wire_shape() {+ let main = serde_json::to_value(StreamEvent::ToolRequest {+ request_id: "host-1".into(),+ tool_name: "observe".into(),+ args: json!({}),+ run_id: None,+ })+ .unwrap();+ assert_eq!(+ main,+ json!({ "type": "tool_request", "request_id": "host-1", "tool_name": "observe", "args": {} })+ );+ let old: StreamEvent = serde_json::from_value(main).expect("no run_id reads back");+ assert!(matches!(old, StreamEvent::ToolRequest { run_id: None, .. }));++ let child = serde_json::to_value(StreamEvent::ToolRequest {+ request_id: "host-2".into(),+ tool_name: "observe".into(),+ args: json!({}),+ run_id: Some("sub-1".into()),+ })+ .unwrap();+ assert_eq!(child["run_id"], "sub-1");++ assert_eq!(+ serde_json::to_value(StreamEvent::ToolRequestCancelled {+ request_id: "host-1".into(),+ reason: "aborted".into(),+ })+ .unwrap(),+ json!({ "type": "tool_request_cancelled", "request_id": "host-1", "reason": "aborted" })+ );+ assert_eq!(+ serde_json::to_value(StreamEvent::ToolDetails {+ id: "c1".into(),+ details: json!({ "k": 1 }),+ })+ .unwrap(),+ json!({ "type": "tool_details", "id": "c1", "details": { "k": 1 } })+ );+ }+#[test]fn subagent_bracket_events_serialize_to_wire_shape() {let start = serde_json::to_value(StreamEvent::SubagentStart {diff --git a/src-tauri/src/core/agent/genai_bridge.rs b/src-tauri/src/core/agent/genai_bridge.rsindex e48a44b9c..0997b24b3 100644--- a/src-tauri/src/core/agent/genai_bridge.rs+++ b/src-tauri/src/core/agent/genai_bridge.rs@@ -228,6 +228,8 @@ fn messages_from_body(let mut system: Option<String> = None;let mut out: Vec<ChatMessage> = Vec::with_capacity(raw.len());+ // Images from the current run of tool messages, waiting for the run to end.+ let mut tool_images: Vec<ContentPart> = Vec::new();for msg in raw {let role = msg@@ -235,6 +237,11 @@ fn messages_from_body(.and_then(|v| v.as_str()).ok_or("Each message must include a string 'role'")?;let content = msg.get("content");+ // A user turn right after the run takes the images itself (see the+ // user arm); any other role closes the run with its own carrier.+ if !matches!(role, "tool" | "user") {+ flush_tool_images(&mut out, &mut tool_images);+ }match role {"system" | "developer" => {@@ -252,6 +259,13 @@ fn messages_from_body(.and_then(|v| v.as_str()).unwrap_or_default().to_string();+ let images = content_images(content);+ if !images.is_empty() {+ tool_images.push(ContentPart::Text(format!(+ "[image output of tool call {call_id}]"+ )));+ tool_images.extend(images);+ }out.push(ChatMessage::new(ChatRole::Tool,ToolResponse::new(call_id, content_text(content)),@@ -292,20 +306,100 @@ fn messages_from_body(parts.into_iter().collect::<MessageContent>(),));}- // Everything else is a user turn. Multimodal content-part arrays are- // flattened to their text; images are not yet forwarded (see below).+ // Everything else is a user turn. A content-part array keeps its+ // images in place; a text-only one stays a plain string, which is+ // what the adapters serialize it as anyway._ => {- out.push(ChatMessage::new(- ChatRole::User,- content_text(content),- ));+ let mut parts = content_parts(content);+ // Pending tool images lead this turn rather than forming one+ // of their own, so two user turns never sit back to back.+ if role == "user" && !tool_images.is_empty() {+ let mut carried = std::mem::take(&mut tool_images);+ carried.append(&mut parts);+ parts = carried;+ }+ let message = if parts.iter().all(ContentPart::is_text) {+ MessageContent::from(content_text(content))+ } else {+ MessageContent::from(parts)+ };+ out.push(ChatMessage::new(ChatRole::User, message));}}}+ flush_tool_images(&mut out, &mut tool_images);Ok((system, out))}+/// Emit the images a run of tool messages produced as one user message.+///+/// `genai`'s `ToolResponse` carries only a string, so an image a tool returned+/// (a `read` of a PNG, a host camera frame) cannot ride in its tool message.+/// It goes in a user turn right after the run instead: after, not between, the+/// tool messages, because OpenAI rejects any message interleaved with the+/// replies to one assistant turn's calls. Each image is labeled with the call+/// it answers so a batch of several stays attributable.+///+/// The carrier is only ever followed by an assistant turn or the end of the+/// request: a user turn that follows the run absorbs the images instead+/// (see the user arm of [`messages_from_body`]). That matters to adapters+/// that demand alternating roles, like genai's Anthropic one, which, unlike+/// `server::converters`, does not merge adjacent user turns. The agent+/// sends `api_type: None` down this path today, but nothing here relies on+/// it.+fn flush_tool_images(out: &mut Vec<ChatMessage>, pending: &mut Vec<ContentPart>) {+ if pending.is_empty() {+ return;+ }+ let parts = std::mem::take(pending);+ out.push(ChatMessage::new(ChatRole::User, MessageContent::from(parts)));+}++/// The parts of an OpenAI `content` field in order: text and images. Anything+/// else (audio, a malformed image) is skipped rather than failing the request,+/// matching how the text-only path always treated unknown parts.+fn content_parts(content: Option<&serde_json::Value>) -> Vec<ContentPart> {+ match content {+ Some(serde_json::Value::String(s)) => vec![ContentPart::Text(s.clone())],+ Some(serde_json::Value::Array(parts)) => parts+ .iter()+ .filter_map(|p| match p.get("type").and_then(|t| t.as_str()) {+ Some("text") => p+ .get("text")+ .and_then(|t| t.as_str())+ .map(|t| ContentPart::Text(t.to_string())),+ Some("image_url") => image_part(p),+ _ => None,+ })+ .collect(),+ _ => Vec::new(),+ }+}++/// Only the image parts of a `content` field.+fn content_images(content: Option<&serde_json::Value>) -> Vec<ContentPart> {+ content_parts(content)+ .into_iter()+ .filter(ContentPart::is_binary)+ .collect()+}++/// One OpenAI `image_url` part as a `genai` binary. A `data:` URL becomes inline+/// base64 so every adapter can re-encode it natively (Anthropic and Gemini do+/// not accept data URLs); any other URL is passed through as a URL.+fn image_part(part: &serde_json::Value) -> Option<ContentPart> {+ let url = part.get("image_url")?.get("url")?.as_str()?;+ match url.strip_prefix("data:") {+ Some(rest) => {+ let (mime, data) = rest.split_once(";base64,")?;+ (!mime.is_empty() && !data.is_empty())+ .then(|| ContentPart::from_binary_base64(mime, data, None))+ }+ None => Some(ContentPart::from_binary_url("image/*", url, None)),+ }+}+/// Text of an OpenAI `content` field: a bare string, or the concatenated `text`/// parts of a multimodal array. Non-text parts (`image_url`) are skipped.fn content_text(content: Option<&serde_json::Value>) -> String {@@ -891,6 +985,7 @@ async fn run_once(#[cfg(test)]mod tests {use super::*;+ use genai::chat::{Binary, BinarySource};use serde_json::json;/// The trailing slash is load-bearing: `Url::join` would otherwise replace@@ -1076,8 +1171,20 @@ mod tests {);}+ /// The image's base64 payload, when `part` is an inline image.+ fn inline_image(part: &ContentPart) -> Option<(&str, &str)> {+ match part {+ ContentPart::Binary(Binary {+ content_type,+ source: BinarySource::Base64(data),+ ..+ }) => Some((content_type.as_str(), data.as_ref())),+ _ => None,+ }+ }+#[test]- fn multimodal_content_parts_are_flattened_to_their_text() {+ fn user_content_parts_keep_their_images_in_order() {let body = json!({"model": "m","messages": [{@@ -1091,14 +1198,126 @@ mod tests {});let (_, req) = chat_request_from_body(&body).unwrap();let parts: Vec<&ContentPart> = req.messages[0].content.iter().collect();+ assert_eq!(parts.len(), 3, "{parts:?}");+ assert!(matches!(parts[0], ContentPart::Text(t) if t == "look: "));+ assert_eq!(inline_image(parts[1]), Some(("image/png", "AAA")));+ assert!(matches!(parts[2], ContentPart::Text(t) if t == "what is it?"));+ }++ #[test]+ fn a_remote_image_url_is_forwarded_as_a_url() {+ let body = json!({+ "model": "m",+ "messages": [{+ "role": "user",+ "content": [+ { "type": "image_url", "image_url": { "url": "https://x.test/a.jpg" } }+ ]+ }]+ });+ let (_, req) = chat_request_from_body(&body).unwrap();+ let parts: Vec<&ContentPart> = req.messages[0].content.iter().collect();assert!(- parts- .iter()- .any(|p| matches!(p, ContentPart::Text(t) if t == "look: what is it?")),- "text parts joined: {parts:?}"+ matches!(parts[0], ContentPart::Binary(Binary { source: BinarySource::Url(u), .. })+ if u == "https://x.test/a.jpg"),+ "{parts:?}");}+ /// `ToolResponse.content` is a string, so a tool's image cannot ride in+ /// the tool message. It follows the run of tool messages, never between+ /// them (that would split the replies to one assistant turn's calls, which+ /// OpenAI rejects), and a user turn right after absorbs it, so no two user+ /// turns sit back to back for an adapter that demands alternation.+ #[test]+ fn tool_images_lead_the_next_user_turn() {+ let body = json!({+ "model": "m",+ "messages": [+ { "role": "assistant", "content": "", "tool_calls": [+ { "id": "c1", "type": "function", "function": { "name": "cam", "arguments": "{}" } },+ { "id": "c2", "type": "function", "function": { "name": "ls", "arguments": "{}" } }+ ]},+ { "role": "tool", "tool_call_id": "c1", "content": [+ { "type": "text", "text": "frame" },+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,QUJD" } }+ ]},+ { "role": "tool", "tool_call_id": "c2", "content": "a.txt" },+ { "role": "user", "content": "next" }+ ]+ });+ let (_, req) = chat_request_from_body(&body).unwrap();+ let roles: Vec<_> = req.messages.iter().map(|m| format!("{:?}", m.role)).collect();+ assert_eq!(roles, ["Assistant", "Tool", "Tool", "User"]);+ let tool: Vec<&ContentPart> = req.messages[1].content.iter().collect();+ assert!(+ matches!(tool[0], ContentPart::ToolResponse(tr) if tr.call_id == "c1" && tr.content == "frame"),+ "the tool message keeps its text: {tool:?}"+ );+ let user: Vec<&ContentPart> = req.messages[3].content.iter().collect();+ assert!(+ matches!(user[0], ContentPart::Text(t) if t.contains("c1")),+ "the image is labeled with the call it answers: {user:?}"+ );+ assert_eq!(inline_image(user[1]), Some(("image/png", "QUJD")));+ assert!(matches!(user[2], ContentPart::Text(t) if t == "next"), "{user:?}");+ }++ /// With no user turn to absorb them, the images get their own carrier,+ /// and the assistant turn after it keeps the roles alternating.+ #[test]+ fn tool_images_without_a_following_user_turn_get_a_carrier() {+ let body = json!({+ "model": "m",+ "messages": [+ { "role": "assistant", "content": "", "tool_calls": [+ { "id": "c1", "type": "function", "function": { "name": "cam", "arguments": "{}" } }+ ]},+ { "role": "tool", "tool_call_id": "c1", "content": [+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,QUJD" } }+ ]},+ { "role": "assistant", "content": "a red square" }+ ]+ });+ let (_, req) = chat_request_from_body(&body).unwrap();+ let roles: Vec<_> = req.messages.iter().map(|m| format!("{:?}", m.role)).collect();+ assert_eq!(roles, ["Assistant", "Tool", "User", "Assistant"]);+ }++ #[test]+ fn a_trailing_tool_image_is_still_forwarded() {+ let body = json!({+ "model": "m",+ "messages": [+ { "role": "tool", "tool_call_id": "c1", "content": [+ { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,QUJD" } }+ ]}+ ]+ });+ let (_, req) = chat_request_from_body(&body).unwrap();+ assert_eq!(req.messages.len(), 2);+ let carried: Vec<&ContentPart> = req.messages[1].content.iter().collect();+ assert_eq!(inline_image(carried[1]), Some(("image/jpeg", "QUJD")));+ }++ #[test]+ fn a_malformed_image_part_is_dropped_not_fatal() {+ let body = json!({+ "model": "m",+ "messages": [{+ "role": "user",+ "content": [+ { "type": "text", "text": "hi" },+ { "type": "image_url", "image_url": { "url": "data:image/png,notbase64" } },+ { "type": "image_url" }+ ]+ }]+ });+ let (_, req) = chat_request_from_body(&body).unwrap();+ let parts: Vec<&ContentPart> = req.messages[0].content.iter().collect();+ assert_eq!(parts.len(), 1, "{parts:?}");+ }+#[test]fn non_standard_params_ride_through_extra_body() {let body = json!({diff --git a/src-tauri/src/core/agent/host_schema.rs b/src-tauri/src/core/agent/host_schema.rsnew file mode 100644index 000000000..a1f73a921--- /dev/null+++ b/src-tauri/src/core/agent/host_schema.rs@@ -0,0 +1,674 @@+//! Pure helpers behind host tools: argument validation against the host's+//! declared schema, and the mapping from a host's tool name to the function+//! name a provider will accept.++use serde_json::{Map, Value};+use sha2::{Digest, Sha256};++/// Nesting past this depth is accepted unjudged. A host schema is untrusted+/// input, and a recursive walk over an arbitrarily deep one would overflow the+/// stack; no real tool argument is nested this deep.+const MAX_DEPTH: usize = 64;++/// Hex characters of the name hash appended to a mapped wire name.+const HASH_LEN: usize = 8;++/// Check a tool call's arguments against the schema its host declared.+///+/// This runs before the host is asked to execute anything, so the constraints+/// a host wrote into its schema (a robot arm's `minItems: 6` joints, a+/// `maximum: 1` speed) are actually enforced and a malformed call goes back to+/// the model as an error instead of reaching hardware. Providers do not+/// enforce the schema they are sent, and a host cannot be assumed to either.+///+/// The supported subset is `type` (a name or an array of names; `integer`+/// accepts any whole number, `number` accepts integers), `properties`,+/// `required`, `additionalProperties` (`false` or a schema), `items` (a+/// schema), `minItems`, `maxItems`, `enum`, `const`, `minLength`, `maxLength`+/// (in characters), `minimum`, `maximum`, `exclusiveMinimum`,+/// `exclusiveMaximum` (numeric form) and `pattern` (an unanchored `regex`+/// search; an invalid pattern is ignored). Boolean schemas are honored. Every+/// other keyword (`format`, `$ref`, `oneOf`, ...) is ignored: an unsupported+/// keyword must never make a valid call fail, so the validator only ever errs+/// on something it understood.+///+/// The error names the first failure as `<json pointer>: <reason>`, with `/`+/// for the root, e.g. `/joints: expected at least 6 items, got 3`.+pub(crate) fn validate(schema: &Value, value: &Value) -> Result<(), String> {+ let mut path = Vec::new();+ check(schema, value, &mut path, 0).map_err(|reason| format!("{}: {reason}", pointer(&path)))+}++/// Map a host's tool name to the function name advertised to the provider.+///+/// Providers only accept function names matching `[A-Za-z0-9_-]{1,64}`, while+/// hosts such as Robot Studio use dotted names (`yam.move_ee_ik`). A name that+/// is already safe, has no `__` (the qualifier separator) and fits `max_len`+/// with its prefix is returned as `prefix + name` unchanged, so existing hosts+/// see no difference. Anything else is sanitized (characters outside+/// `[A-Za-z0-9-]` become `_`, runs collapse, edges are trimmed, an empty result+/// becomes `tool`) and suffixed with `_` and the first 8 hex characters of the+/// SHA-256 of the original name, truncating the stem to fit. The hash keeps+/// names that sanitize alike (`a.b`, `a b`) distinct, and the mapping is+/// deterministic, so the same host gets the same names on every run.+///+/// Refused: an empty or whitespace-only name, a name with a control character,+/// and a `max_len` too small to hold the prefix, a one-character stem and the+/// hash.+pub(crate) fn wire_name(name: &str, max_len: usize, prefix: &str) -> Result<String, String> {+ if name.trim().is_empty() {+ return Err("host tool name must not be empty".to_string());+ }+ if name.chars().any(char::is_control) {+ return Err(format!("host tool name {name:?} contains a control character"));+ }+ let safe = !name.contains("__")+ && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');+ if safe && prefix.len() + name.len() <= max_len {+ return Ok(format!("{prefix}{name}"));+ }+ let budget = max_len+ .checked_sub(prefix.len() + 1 + HASH_LEN)+ .filter(|b| *b > 0)+ .ok_or_else(|| format!("host tool name {name:?} cannot be mapped into {max_len} characters"))?;++ let mut stem = String::with_capacity(name.len());+ for c in name.chars() {+ let c = if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' };+ if !(c == '_' && stem.ends_with('_')) {+ stem.push(c);+ }+ }+ let mut stem = stem.trim_matches('_').to_string();+ if stem.is_empty() {+ stem.push_str("tool");+ }+ // The stem is ASCII, so a byte cut is a char cut. Re-trim: a cut landing just+ // after a '_' would otherwise meet the hash separator as `__`.+ stem.truncate(budget);+ let stem = stem.trim_end_matches('_');++ let digest = Sha256::digest(name.as_bytes());+ let hash: String = digest.iter().take(HASH_LEN / 2).map(|b| format!("{b:02x}")).collect();+ Ok(format!("{prefix}{stem}_{hash}"))+}++fn pointer(path: &[String]) -> String {+ if path.is_empty() {+ return "/".to_string();+ }+ path.iter().map(|seg| format!("/{}", seg.replace('~', "~0").replace('/', "~1"))).collect()+}++fn check(schema: &Value, value: &Value, path: &mut Vec<String>, depth: usize) -> Result<(), String> {+ if depth > MAX_DEPTH {+ return Ok(());+ }+ let schema = match schema {+ Value::Bool(true) => return Ok(()),+ Value::Bool(false) => return Err("no value is allowed here".to_string()),+ Value::Object(map) => map,+ // Not a schema at all; nothing it could constrain.+ _ => return Ok(()),+ };++ check_type(schema, value)?;+ if let Some(Value::Array(options)) = schema.get("enum") {+ if !options.iter().any(|o| json_eq(o, value)) {+ return Err(format!("must be one of {}", Value::Array(options.clone())));+ }+ }+ if let Some(expected) = schema.get("const") {+ if !json_eq(expected, value) {+ return Err(format!("must equal {expected}"));+ }+ }++ match value {+ Value::Number(n) => check_number(schema, n.as_f64().unwrap_or(f64::NAN)),+ Value::String(s) => check_string(schema, s),+ Value::Array(items) => check_array(schema, items, path, depth),+ Value::Object(props) => check_object(schema, props, path, depth),+ _ => Ok(()),+ }+}++fn type_name(value: &Value) -> &'static str {+ match value {+ Value::Null => "null",+ Value::Bool(_) => "boolean",+ Value::Number(_) if is_integer(value) => "integer",+ Value::Number(_) => "number",+ Value::String(_) => "string",+ Value::Array(_) => "array",+ Value::Object(_) => "object",+ }+}++/// JSON Schema counts `3.0` as an integer: the type is about the value, not+/// how it was spelled.+fn is_integer(value: &Value) -> bool {+ match value {+ Value::Number(n) => {+ n.is_i64() || n.is_u64() || n.as_f64().is_some_and(|f| f.is_finite() && f.fract() == 0.0)+ }+ _ => false,+ }+}++fn matches_type(name: &str, value: &Value) -> bool {+ match name {+ "integer" => is_integer(value),+ "number" => value.is_number(),+ other => type_name(value) == other,+ }+}++fn check_type(schema: &Map<String, Value>, value: &Value) -> Result<(), String> {+ let names: Vec<&str> = match schema.get("type") {+ Some(Value::String(name)) => vec![name.as_str()],+ Some(Value::Array(names)) => names.iter().filter_map(Value::as_str).collect(),+ _ => return Ok(()),+ };+ if names.is_empty() || names.iter().any(|n| matches_type(n, value)) {+ return Ok(());+ }+ Err(format!("expected {}, got {}", names.join(" or "), type_name(value)))+}++/// `enum`/`const` equality: numbers compare by value, so `1` equals `1.0` as+/// JSON Schema requires, where `Value`'s own `==` would tell them apart.+fn json_eq(a: &Value, b: &Value) -> bool {+ match (a, b) {+ (Value::Number(x), Value::Number(y)) => {+ if let (Some(x), Some(y)) = (x.as_i64(), y.as_i64()) {+ return x == y;+ }+ if let (Some(x), Some(y)) = (x.as_u64(), y.as_u64()) {+ return x == y;+ }+ x.as_f64() == y.as_f64()+ }+ (Value::Array(x), Value::Array(y)) => {+ x.len() == y.len() && x.iter().zip(y).all(|(x, y)| json_eq(x, y))+ }+ (Value::Object(x), Value::Object(y)) => {+ x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| json_eq(v, w)))+ }+ _ => a == b,+ }+}++fn check_number(schema: &Map<String, Value>, n: f64) -> Result<(), String> {+ // Only the numeric form of each bound; the draft-4 boolean `exclusive*`+ // modifiers are not numbers and so are skipped like any unknown keyword.+ let bound = |key: &str| schema.get(key).and_then(|v| v.as_f64().map(|f| (f, v)));+ if let Some((min, raw)) = bound("minimum") {+ if n < min {+ return Err(format!("must be >= {raw}"));+ }+ }+ if let Some((max, raw)) = bound("maximum") {+ if n > max {+ return Err(format!("must be <= {raw}"));+ }+ }+ if let Some((min, raw)) = bound("exclusiveMinimum") {+ if n <= min {+ return Err(format!("must be > {raw}"));+ }+ }+ if let Some((max, raw)) = bound("exclusiveMaximum") {+ if n >= max {+ return Err(format!("must be < {raw}"));+ }+ }+ Ok(())+}++fn check_string(schema: &Map<String, Value>, s: &str) -> Result<(), String> {+ let len = s.chars().count() as u64;+ if let Some(min) = schema.get("minLength").and_then(Value::as_u64) {+ if len < min {+ return Err(format!("expected at least {min} characters, got {len}"));+ }+ }+ if let Some(max) = schema.get("maxLength").and_then(Value::as_u64) {+ if len > max {+ return Err(format!("expected at most {max} characters, got {len}"));+ }+ }+ if let Some(pattern) = schema.get("pattern").and_then(Value::as_str) {+ // A pattern the regex crate cannot compile (a lookaround, say) is the+ // host's dialect, not a bad call; skip it rather than refuse every call.+ if let Ok(re) = regex::Regex::new(pattern) {+ if !re.is_match(s) {+ return Err(format!("does not match pattern '{pattern}'"));+ }+ }+ }+ Ok(())+}++fn check_array(+ schema: &Map<String, Value>,+ items: &[Value],+ path: &mut Vec<String>,+ depth: usize,+) -> Result<(), String> {+ let len = items.len() as u64;+ if let Some(min) = schema.get("minItems").and_then(Value::as_u64) {+ if len < min {+ return Err(format!("expected at least {min} items, got {len}"));+ }+ }+ if let Some(max) = schema.get("maxItems").and_then(Value::as_u64) {+ if len > max {+ return Err(format!("expected at most {max} items, got {len}"));+ }+ }+ // Only the single-schema form; the tuple form (an array) is outside the subset.+ if let Some(item_schema @ (Value::Object(_) | Value::Bool(_))) = schema.get("items") {+ for (i, item) in items.iter().enumerate() {+ path.push(i.to_string());+ check(item_schema, item, path, depth + 1)?;+ path.pop();+ }+ }+ Ok(())+}++fn check_object(+ schema: &Map<String, Value>,+ props: &Map<String, Value>,+ path: &mut Vec<String>,+ depth: usize,+) -> Result<(), String> {+ if let Some(Value::Array(required)) = schema.get("required") {+ if let Some(missing) = required.iter().filter_map(Value::as_str).find(|k| !props.contains_key(*k)) {+ return Err(format!("missing required property '{missing}'"));+ }+ }+ let declared = schema.get("properties").and_then(Value::as_object);+ if let Some(declared) = declared {+ for (key, sub) in declared {+ if let Some(v) = props.get(key) {+ path.push(key.clone());+ check(sub, v, path, depth + 1)?;+ path.pop();+ }+ }+ }+ // `additionalProperties` is judged relative to `patternProperties` too, which+ // is outside the subset; without it we cannot tell what counts as extra.+ if schema.contains_key("patternProperties") {+ return Ok(());+ }+ let extra_schema = match schema.get("additionalProperties") {+ Some(s @ (Value::Object(_) | Value::Bool(false))) => s,+ _ => return Ok(()),+ };+ for (key, v) in props {+ if declared.is_some_and(|d| d.contains_key(key)) {+ continue;+ }+ path.push(key.clone());+ if extra_schema == &Value::Bool(false) {+ return Err("property is not allowed".to_string());+ }+ check(extra_schema, v, path, depth + 1)?;+ path.pop();+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn err(schema: Value, value: Value) -> String {+ validate(&schema, &value).expect_err("expected a validation failure")+ }++ fn ok(schema: Value, value: Value) {+ if let Err(e) = validate(&schema, &value) {+ panic!("expected {value} to satisfy {schema}, got: {e}");+ }+ }++ #[test]+ fn type_string_and_mismatch() {+ ok(json!({"type": "string"}), json!("x"));+ assert_eq!(err(json!({"type": "string"}), json!(1)), "/: expected string, got integer");+ assert_eq!(err(json!({"type": "object"}), json!([])), "/: expected object, got array");+ assert_eq!(err(json!({"type": "boolean"}), json!(null)), "/: expected boolean, got null");+ }++ #[test]+ fn integer_is_a_number_but_not_vice_versa() {+ ok(json!({"type": "number"}), json!(3));+ ok(json!({"type": "number"}), json!(3.5));+ ok(json!({"type": "integer"}), json!(3));+ ok(json!({"type": "integer"}), json!(-3));+ // JSON Schema counts a number with a zero fractional part as an integer.+ ok(json!({"type": "integer"}), json!(3.0));+ assert_eq!(err(json!({"type": "integer"}), json!(3.5)), "/: expected integer, got number");+ }++ #[test]+ fn type_may_be_an_array_of_types() {+ let s = json!({"type": ["string", "null"]});+ ok(s.clone(), json!("x"));+ ok(s.clone(), json!(null));+ assert_eq!(err(s, json!(1)), "/: expected string or null, got integer");+ }++ #[test]+ fn required_names_the_missing_property() {+ let s = json!({"type": "object", "required": ["target"]});+ assert_eq!(err(s.clone(), json!({})), "/: missing required property 'target'");+ ok(s, json!({"target": 1}));+ }++ #[test]+ fn properties_recurse_with_a_pointer() {+ let s = json!({"type": "object", "properties": {"speed": {"type": "number", "maximum": 1}}});+ assert_eq!(err(s.clone(), json!({"speed": 2})), "/speed: must be <= 1");+ assert_eq!(err(s.clone(), json!({"speed": "x"})), "/speed: expected number, got string");+ ok(s, json!({"speed": 0.5}));+ }++ #[test]+ fn nested_pointers_include_array_indices() {+ let s = json!({"properties": {"a": {"items": {"properties": {"b": {"type": "string"}}}}}});+ assert_eq!(err(s, json!({"a": [{"b": "x"}, {"b": 2}]})), "/a/1/b: expected string, got integer");+ }++ #[test]+ fn pointer_segments_are_escaped() {+ let s = json!({"properties": {"a/b~c": {"type": "string"}}});+ assert_eq!(err(s, json!({"a/b~c": 1})), "/a~1b~0c: expected string, got integer");+ }++ #[test]+ fn additional_properties_false_refuses_extras() {+ let s = json!({"properties": {"a": {}}, "additionalProperties": false});+ assert_eq!(err(s.clone(), json!({"a": 1, "extra": 2})), "/extra: property is not allowed");+ ok(s, json!({"a": 1}));+ }++ #[test]+ fn additional_properties_schema_applies_to_extras_only() {+ let s = json!({"properties": {"a": {"type": "string"}}, "additionalProperties": {"type": "integer"}});+ ok(s.clone(), json!({"a": "x", "b": 1}));+ assert_eq!(err(s, json!({"a": "x", "b": "y"})), "/b: expected integer, got string");+ }++ #[test]+ fn additional_properties_true_or_absent_allows_extras() {+ ok(json!({"properties": {"a": {}}}), json!({"b": 1}));+ ok(json!({"properties": {"a": {}}, "additionalProperties": true}), json!({"b": 1}));+ }++ #[test]+ fn additional_properties_is_skipped_when_pattern_properties_exist() {+ // patternProperties is outside the subset; judging extras without it would+ // refuse keys the host meant to allow.+ ok(+ json!({"patternProperties": {"^x": {}}, "additionalProperties": false}),+ json!({"x1": 1}),+ );+ }++ #[test]+ fn items_min_items_and_max_items() {+ let s = json!({"properties": {"joints": {"type": "array", "items": {"type": "number"}, "minItems": 6, "maxItems": 7}}});+ assert_eq!(err(s.clone(), json!({"joints": [1, 2, 3]})), "/joints: expected at least 6 items, got 3");+ assert_eq!(+ err(s.clone(), json!({"joints": [1, 2, 3, 4, 5, 6, 7, 8]})),+ "/joints: expected at most 7 items, got 8"+ );+ assert_eq!(+ err(s.clone(), json!({"joints": [1, 2, 3, 4, 5, "x"]})),+ "/joints/5: expected number, got string"+ );+ ok(s, json!({"joints": [1, 2, 3, 4, 5, 6]}));+ }++ #[test]+ fn enum_and_const() {+ let s = json!({"enum": ["a", "b"]});+ ok(s.clone(), json!("a"));+ assert_eq!(err(s, json!("c")), "/: must be one of [\"a\",\"b\"]");+ ok(json!({"const": 5}), json!(5));+ assert_eq!(err(json!({"const": 5}), json!(6)), "/: must equal 5");+ }++ #[test]+ fn enum_and_const_compare_numbers_by_value() {+ ok(json!({"enum": [1, 2]}), json!(1.0));+ ok(json!({"const": 1.0}), json!(1));+ ok(json!({"const": {"a": [1]}}), json!({"a": [1.0]}));+ }++ #[test]+ fn string_lengths_count_chars_not_bytes() {+ let s = json!({"minLength": 2, "maxLength": 3});+ ok(s.clone(), json!("\u{e9}\u{e9}\u{e9}"));+ assert_eq!(err(s.clone(), json!("\u{e9}")), "/: expected at least 2 characters, got 1");+ assert_eq!(err(s, json!("abcd")), "/: expected at most 3 characters, got 4");+ }++ #[test]+ fn numeric_bounds() {+ assert_eq!(err(json!({"minimum": 0}), json!(-1)), "/: must be >= 0");+ ok(json!({"minimum": 0}), json!(0));+ ok(json!({"maximum": 1}), json!(1));+ assert_eq!(err(json!({"exclusiveMinimum": 0}), json!(0)), "/: must be > 0");+ ok(json!({"exclusiveMinimum": 0}), json!(0.1));+ assert_eq!(err(json!({"exclusiveMaximum": 1.5}), json!(1.5)), "/: must be < 1.5");+ ok(json!({"exclusiveMaximum": 1.5}), json!(1));+ }++ #[test]+ fn draft4_boolean_exclusive_bounds_are_ignored() {+ // Only the numeric form is in the subset; the draft-4 boolean form must+ // not break a schema that also carries a plain bound.+ ok(json!({"maximum": 1, "exclusiveMaximum": true}), json!(1));+ }++ #[test]+ fn pattern_is_an_unanchored_search() {+ let s = json!({"pattern": "b+"});+ ok(s.clone(), json!("abbc"));+ assert_eq!(err(s, json!("ac")), "/: does not match pattern 'b+'");+ ok(json!({"pattern": "^a$"}), json!("a"));+ assert!(validate(&json!({"pattern": "^a$"}), &json!("ab")).is_err());+ }++ #[test]+ fn an_invalid_pattern_is_ignored() {+ ok(json!({"pattern": "(unclosed"}), json!("anything"));+ }++ #[test]+ fn keywords_only_apply_to_their_own_type() {+ // minLength says nothing about a number, minimum nothing about a string.+ ok(json!({"minLength": 5, "minimum": 10, "minItems": 3, "required": ["a"]}), json!(1.0e9));+ ok(json!({"minimum": 10}), json!("short"));+ ok(json!({"required": ["a"]}), json!([]));+ }++ #[test]+ fn unknown_keywords_are_ignored() {+ ok(+ json!({+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$ref": "#/definitions/nowhere",+ "title": "t",+ "description": "d",+ "format": "email",+ "x-vendor": {"anything": true},+ "type": "string"+ }),+ json!("not an email"),+ );+ }++ #[test]+ fn boolean_schemas() {+ ok(json!(true), json!({"a": 1}));+ assert_eq!(err(json!(false), json!(1)), "/: no value is allowed here");+ let s = json!({"properties": {"x": false}});+ assert_eq!(err(s.clone(), json!({"x": 1})), "/x: no value is allowed here");+ ok(s, json!({}));+ }++ #[test]+ fn a_non_object_schema_constrains_nothing() {+ ok(json!(null), json!(1));+ ok(json!("string"), json!(1));+ }++ #[test]+ fn the_first_failure_is_reported() {+ let s = json!({"type": "object", "required": ["a", "b"]});+ assert_eq!(err(s, json!({})), "/: missing required property 'a'");+ }++ #[test]+ fn deep_nesting_does_not_overflow() {+ // A schema and value nested far past the cap: validation stops judging at+ // the cap rather than recursing until the stack runs out. An uncapped+ // walk would reach the leaf and fail, so Ok proves the cap. (Not deeper:+ // serde_json's own Drop of a Value recurses and would overflow first.)+ let mut schema = json!({"type": "string"});+ let mut value = json!(1);+ for _ in 0..500 {+ schema = json!({"items": schema});+ value = json!([value]);+ }+ assert!(validate(&schema, &value).is_ok());+ }++ #[test]+ fn nesting_within_the_cap_is_still_checked() {+ let mut schema = json!({"type": "string"});+ let mut value = json!(1);+ for _ in 0..10 {+ schema = json!({"items": schema});+ value = json!([value]);+ }+ assert!(validate(&schema, &value).is_err());+ }++ const P: &str = "host__";++ fn is_wire_safe(s: &str) -> bool {+ !s.is_empty() && s.len() <= 64 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')+ }++ #[test]+ fn a_safe_name_is_prefixed_unchanged() {+ assert_eq!(wire_name("observe", 64, P).unwrap(), "host__observe");+ assert_eq!(wire_name("move-ee_ik2", 64, P).unwrap(), "host__move-ee_ik2");+ let exact = "a".repeat(64 - P.len());+ assert_eq!(wire_name(&exact, 64, P).unwrap(), format!("{P}{exact}"));+ }++ #[test]+ fn a_dotted_name_is_sanitized_and_hashed() {+ let got = wire_name("yam.move_ee_ik", 64, P).unwrap();+ let (stem, hash) = got.rsplit_once('_').unwrap();+ assert_eq!(stem, "host__yam_move_ee_ik");+ assert_eq!(hash.len(), 8);+ assert!(hash.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));+ assert!(is_wire_safe(&got));+ }++ #[test]+ fn the_hash_is_sha256_of_the_original_name() {+ // sha256("yam.move_ee_ik"), first 4 bytes.+ use sha2::{Digest, Sha256};+ let digest = Sha256::digest("yam.move_ee_ik".as_bytes());+ let hex: String = digest[..4].iter().map(|b| format!("{b:02x}")).collect();+ assert_eq!(wire_name("yam.move_ee_ik", 64, P).unwrap(), format!("host__yam_move_ee_ik_{hex}"));+ }++ #[test]+ fn unsafe_names_map_to_wire_safe_names() {+ for name in ["has space", "unicode\u{e9}", "a__b", "__lead", "trail__", "a...b", "-dash-"] {+ let got = wire_name(name, 64, P).unwrap();+ assert!(is_wire_safe(&got), "{name:?} -> {got:?}");+ assert!(got.starts_with(P), "{got}");+ assert!(!got[P.len()..].contains("__"), "{name:?} -> {got:?}");+ assert!(!got[P.len()..].starts_with('_'), "{name:?} -> {got:?}");+ }+ assert!(wire_name("has space", 64, P).unwrap().starts_with("host__has_space_"));+ assert!(wire_name("unicode\u{e9}", 64, P).unwrap().starts_with("host__unicode_"));+ assert!(wire_name("a__b", 64, P).unwrap().starts_with("host__a_b_"));+ }++ #[test]+ fn mapping_is_deterministic() {+ assert_eq!(wire_name("a.b", 64, P).unwrap(), wire_name("a.b", 64, P).unwrap());+ }++ #[test]+ fn names_that_sanitize_alike_stay_distinct() {+ let a = wire_name("a.b", 64, P).unwrap();+ let b = wire_name("a b", 64, P).unwrap();+ let c = wire_name("a__b", 64, P).unwrap();+ assert_ne!(a, b);+ assert_ne!(a, c);+ assert_ne!(b, c);+ assert!(a.starts_with("host__a_b_") && b.starts_with("host__a_b_"));+ }++ #[test]+ fn an_over_long_name_is_truncated_and_hashed() {+ let long = "x".repeat(100);+ let got = wire_name(&long, 64, P).unwrap();+ assert_eq!(got.len(), 64);+ assert!(is_wire_safe(&got));+ let other = wire_name(&format!("{long}y"), 64, P).unwrap();+ assert_ne!(got, other);+ // One past the safe limit is hashed too.+ let just_over = "a".repeat(64 - P.len() + 1);+ assert!(wire_name(&just_over, 64, P).unwrap().len() <= 64);+ }++ #[test]+ fn truncation_never_leaves_a_double_underscore() {+ // The cut lands right after a '_' in the stem; the join must not become '__'.+ let budget = 64 - P.len() - 9;+ let name = format!("{}.b{}", "a".repeat(budget - 1), "c".repeat(20));+ let got = wire_name(&name, 64, P).unwrap();+ assert!(!got[P.len()..].contains("__"), "{got}");+ assert!(got.len() <= 64);+ }++ #[test]+ fn a_name_with_nothing_safe_uses_a_placeholder_stem() {+ let got = wire_name("...", 64, P).unwrap();+ assert!(got.starts_with("host__tool_"), "{got}");+ assert_eq!(got.len(), "host__tool_".len() + 8);+ assert_ne!(got, wire_name("___", 64, P).unwrap());+ }++ #[test]+ fn empty_and_control_names_are_refused() {+ assert!(wire_name("", 64, P).is_err());+ assert!(wire_name(" ", 64, P).is_err());+ assert!(wire_name("a\nb", 64, P).is_err());+ assert!(wire_name("a\u{7f}b", 64, P).is_err());+ assert!(wire_name("a\u{0}", 64, P).is_err());+ }++ #[test]+ fn a_budget_too_small_for_the_hash_is_refused() {+ assert!(wire_name("a.b", P.len() + 9, P).is_err());+ assert!(wire_name("a.b", P.len() + 10, P).is_ok());+ }+}diff --git a/src-tauri/src/core/agent/host_tools.rs b/src-tauri/src/core/agent/host_tools.rsindex 0a92dd15b..72d51709c 100644--- a/src-tauri/src/core/agent/host_tools.rs+++ b/src-tauri/src/core/agent/host_tools.rs@@ -15,12 +15,22 @@//! the same reason: exactly one answer per request, and a client that goes away//! must not park a turn forever.//!-//! What this module does not do is decide policy. A host tool is treated-//! exactly as a plugin or MCP tool is -- prompted rather than auto-allowed, and-//! withheld entirely in read-only Plan mode -- because its capability is just as-//! opaque from here. That default is the shipped answer to "what class does an-//! undeclared tool land in", and a host tool that mutates the physical world is-//! the case it was written for.+//! What this module does not do is decide policy. An undeclared host tool is+//! treated exactly as a plugin or MCP tool is -- prompted rather than+//! auto-allowed, and withheld entirely in read-only Plan mode -- because its+//! capability is just as opaque from here. A host that knows better says so+//! with [`HostCapability`]: `read` opts a sensor into the read-only class,+//! `actuator` opts a tool out of `auto_approve`. The loop applies the class;+//! this module only carries it.+//!+//! Two things it does own. Names: a host's own name (`yam.move_ee_ik`) is+//! kept for `tool_request`, while the model is shown a provider-safe wire+//! name -- `host__<name>` when the name is already safe, otherwise a sanitized+//! stem plus a short hash of the original (see+//! [`host_schema::wire_name`](crate::core::agent::host_schema::wire_name)).+//! And arguments: [`HostTool::validate`] checks a call against the declared+//! schema before the host is asked, because neither the provider nor every+//! host can be relied on to enforce it.use std::collections::HashMap;use std::sync::atomic::{AtomicU64, Ordering};@@ -43,6 +53,7 @@ pub const NAME_PREFIX: &str = "host__";/// Cap on the advertised `host__<name>` name. Several providers reject a/// function name past 64 characters, and they reject the *request* rather than/// just the tool, so one over-long name would break every call in the run.+/// A longer name is hashed into this budget rather than refused.const MAX_NAME_LEN: usize = 64;/// Cap on how many tools one host may declare. Generous next to any real tool@@ -57,7 +68,16 @@ static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1);/// without ending the turn.#[derive(Clone, Debug, Eq, PartialEq)]pub(crate) struct HostToolResult {+ /// The text summary: what hooks, the `tool_result` event and the `ERROR: `+ /// prefix see. When `parts` is given this is its text parts joined by+ /// newlines, so a consumer that only reads text loses nothing but images.pub content: String,+ /// OpenAI content parts (`text` / `image_url`), passed verbatim and in order+ /// as the model's tool message. `None` means the message is `content`.+ pub parts: Option<Vec<serde_json::Value>>,+ /// Host/UI-only structured data. Never sent to the model: it is emitted as+ /// a `tool_details` event so a display can render it, and that is all.+ pub details: Option<serde_json::Value>,pub is_error: bool,}@@ -66,6 +86,10 @@ pub(crate) struct HostToolResult {pub(crate) enum HostToolError {/// The client disconnected, or the run ended, before answering.ClientGone,+ /// The run withdrew the request (abort, interrupt) before the host+ /// answered. Distinct from `ClientGone` so the model is told the call was+ /// cancelled rather than that the host vanished.+ Cancelled,}pub(crate) type HostToolOutcome = Result<HostToolResult, HostToolError>;@@ -99,7 +123,11 @@ pub(crate) async fn respond(.lock().await.remove(request_id)- .ok_or_else(|| format!("no host tool request '{request_id}' is pending"))?;+ .ok_or_else(|| {+ format!(+ "no host tool request '{request_id}' is pending (answered, cancelled, or never issued)"+ )+ })?;sender.send(outcome).map_err(|_| format!("host tool request '{request_id}' is no longer pending"))@@ -108,21 +136,60 @@ pub(crate) async fn respond(/// Fail one pending call closed. Used for a request raised *after* the client/// left: `strand_all` runs once when stdin closes, so a later call would/// otherwise wait on a reader that no longer exists.-pub(crate) async fn strand(registry: &HostToolRegistry, request_id: &str) {+///+/// Returns whether the request was still pending, so the caller emits a+/// cancellation record only for a request this call actually released.+pub(crate) async fn strand(registry: &HostToolRegistry, request_id: &str) -> bool {let sender = registry.lock().await.remove(request_id);- if let Some(sender) = sender {- let _ = sender.send(Err(HostToolError::ClientGone));+ match sender {+ Some(sender) => {+ let _ = sender.send(Err(HostToolError::ClientGone));+ true+ }+ None => false,}}/// Fail every pending call closed. Called when the client's stdin closes: a/// host that cannot answer must not leave the turn parked on a reply that can-/// never arrive.-pub(crate) async fn strand_all(registry: &HostToolRegistry) {+/// never arrive. Returns the released request ids (sorted, so records come out+/// in a stable order) for the caller to report.+pub(crate) async fn strand_all(registry: &HostToolRegistry) -> Vec<String> {+ release_all(registry, HostToolError::ClientGone).await+}++/// Withdraw every pending call: the run was aborted or interrupted while the+/// host still held requests. Same draining as `strand_all`, but the model is+/// told the call was cancelled. Returns the released ids.+pub(crate) async fn cancel_all(registry: &HostToolRegistry) -> Vec<String> {+ release_all(registry, HostToolError::Cancelled).await+}++async fn release_all(registry: &HostToolRegistry, error: HostToolError) -> Vec<String> {let pending = std::mem::take(&mut *registry.lock().await);- for (_, sender) in pending {- let _ = sender.send(Err(HostToolError::ClientGone));+ let mut ids = Vec::with_capacity(pending.len());+ for (id, sender) in pending {+ let _ = sender.send(Err(error.clone()));+ ids.push(id);}+ ids.sort();+ ids+}++/// What a host says a tool does, which decides how the loop treats it.+/// Absent means opaque: prompted unless `auto_approve`, sequential, withheld in+/// Plan mode -- the plugin/MCP default.+#[derive(+ Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, schemars::JsonSchema,+)]+#[serde(rename_all = "snake_case")]+pub enum HostCapability {+ /// Observes without side effects (a camera, a sensor): never prompted,+ /// advertised in Plan mode, and run concurrently with other reads.+ Read,+ /// Acts on the world: prompted even under `auto_approve` unless the host+ /// owns the gate, run sequentially, withheld in Plan mode.+ Actuator,}/// One tool as the host declares it.@@ -146,6 +213,9 @@ pub struct HostToolDecl {/// JSON Schema for the tool's arguments, passed to the provider verbatim.#[serde(default)]pub parameters: Option<serde_json::Value>,+ /// How the loop should treat calls to this tool; absent is opaque.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub capability: Option<HostCapability>,/// Every key that is none of the above, kept only so `declare` can refuse/// it by name. Never serialized back: a declaration this process re-emits/// is the set it accepted, which by then has no unknown keys.@@ -156,7 +226,8 @@ pub struct HostToolDecl {/// A registered host tool.#[derive(Clone, Debug, PartialEq, Serialize)]pub struct HostTool {- /// The name the model calls, already prefixed (`host__<name>`).+ /// The name the model calls: `host__<name>` for a provider-safe name, and+ /// otherwise the mapped `host__<sanitized>_<hash>` wire name.pub qualified_name: String,/// The name the *host* used. `tool_request` carries this, not the qualified/// name: the host asked for `observe` and must be able to dispatch on@@ -164,9 +235,21 @@ pub struct HostTool {pub name: String,pub description: String,pub parameters: serde_json::Value,+ /// The declared class; `None` is opaque. See [`HostCapability`].+ #[serde(skip_serializing_if = "Option::is_none")]+ pub capability: Option<HostCapability>,}impl HostTool {+ /// Check a call's arguments against the declared `parameters`, before the+ /// host is asked to run it. See [`host_schema::validate`] for the subset;+ /// the error is `<json pointer>: <reason>`.+ ///+ /// [`host_schema::validate`]: crate::core::agent::host_schema::validate+ pub fn validate(&self, args: &serde_json::Value) -> Result<(), String> {+ crate::core::agent::host_schema::validate(&self.parameters, args)+ }+/// The OpenAI tool schema advertised for this tool.////// The host's `parameters` are embedded unchanged. That is deliberate and it@@ -193,8 +276,8 @@ impl HostTool {#[derive(Clone, Debug, PartialEq)]pub enum DeclError {EmptyName,+ /// The name cannot be mapped to a wire name; carries the mapper's reason.UnsafeName(String),- NameTooLong(String),Reserved(String),Duplicate(String),NonObjectSchema(String),@@ -206,14 +289,7 @@ impl std::fmt::Display for DeclError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {DeclError::EmptyName => write!(f, "a host tool has an empty name"),- DeclError::UnsafeName(n) => write!(- f,- "host tool name '{n}' must be ASCII letters, digits, '_' or '-' and cannot contain '__'"- ),- DeclError::NameTooLong(n) => write!(- f,- "host tool name '{n}' is too long: '{NAME_PREFIX}{n}' exceeds {MAX_NAME_LEN} characters"- ),+ DeclError::UnsafeName(reason) => write!(f, "{reason}"),DeclError::Reserved(n) => {write!(f, "host tool name '{n}' is reserved by a built-in tool")}@@ -228,7 +304,7 @@ impl std::fmt::Display for DeclError {),DeclError::UnknownKey(n, key) => write!(f,- "host tool '{n}' has an unknown field '{key}' (expected name, description, parameters)"+ "host tool '{n}' has an unknown field '{key}' (expected name, description, parameters, capability)"),}}@@ -296,13 +372,12 @@ impl HostToolSet {if let Some(key) = entry.unknown.keys().next() {return Err(DeclError::UnknownKey(name, key.clone()));}- if !is_safe_name(&name) {- return Err(DeclError::UnsafeName(name));- }- let qualified_name = format!("{NAME_PREFIX}{name}");- if qualified_name.len() > MAX_NAME_LEN {- return Err(DeclError::NameTooLong(name));- }+ // R14: a dotted or otherwise provider-unsafe name is mapped to a+ // wire name rather than refused, so a host need not keep its own+ // mapping table; `name` stays what the host dispatches on.+ let qualified_name =+ crate::core::agent::host_schema::wire_name(&name, MAX_NAME_LEN, NAME_PREFIX)+ .map_err(DeclError::UnsafeName)?;// A host tool is prefixed, so it cannot collide with a built-in on// the wire. The check is on the *bare* name anyway: a host that// registers `bash` or `read` has almost certainly misunderstood@@ -311,6 +386,9 @@ impl HostToolSet {if is_reserved(&name) {return Err(DeclError::Reserved(name));}+ // Mapped names are hashed, so two different names meet here only+ // when a safe name spells out another's mapping; either way the+ // model could not tell them apart.if set.get(&qualified_name).is_some() {return Err(DeclError::Duplicate(name));}@@ -323,6 +401,7 @@ impl HostToolSet {name,description: entry.description.trim().to_string(),parameters,+ capability: entry.capability,});}Ok(set)@@ -343,18 +422,6 @@ fn is_reserved(name: &str) -> bool {|| crate::core::agent::subagent::is_subagent_tool(name)}-/// Host tool names are restricted to what every provider accepts in a function-/// name and what cannot be confused with the `__` qualifier separator. A host-/// whose internal name is outside this set maps it on its own side and maps it-/// back on the result, which is what the reference consumer already does.-fn is_safe_name(name: &str) -> bool {- !name.is_empty()- && !name.contains("__")- && name- .chars()- .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')-}-#[cfg(test)]mod tests {use super::*;@@ -365,6 +432,7 @@ mod tests {name: name.to_string(),description: "does a thing".to_string(),parameters: None,+ capability: None,unknown: Default::default(),}}@@ -404,6 +472,7 @@ mod tests {name: "move_arm".to_string(),description: "move".to_string(),parameters: Some(parameters.clone()),+ capability: None,unknown: Default::default(),}]).expect("declares");@@ -496,15 +565,37 @@ mod tests {}}+ /// R14: a name no provider would accept is mapped, not refused. The model+ /// calls the wire name; the host keeps dispatching on the name it chose.#[test]- fn an_unsafe_name_is_refused() {+ fn an_unsafe_name_is_mapped() {for name in ["yam.move_ee_ik", "has space", "unicode\u{00e9}", "a__b"] {- assert_eq!(- HostToolSet::declare(vec![decl(name)]),- Err(DeclError::UnsafeName(name.to_string())),- "'{name}' must be refused"+ let set = HostToolSet::declare(vec![decl(name)])+ .unwrap_or_else(|e| panic!("'{name}' must be mapped: {e}"));+ let tool = &set.all()[0];+ assert_eq!(tool.name, name);+ let wire = tool.qualified_name.strip_prefix(NAME_PREFIX).expect("prefixed");+ assert!(!wire.contains("__"), "{wire}");+ assert!(+ wire.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),+ "{wire}");+ assert!(set.is_host_tool(&tool.qualified_name));}+ let set = HostToolSet::declare(vec![decl("yam.move_ee_ik")]).expect("declares");+ assert!(+ set.all()[0].qualified_name.starts_with("host__yam_move_ee_ik_"),+ "{}",+ set.all()[0].qualified_name+ );+ }++ #[test]+ fn a_name_with_a_control_character_is_refused() {+ assert!(matches!(+ HostToolSet::declare(vec![decl("bad\u{7}name")]),+ Err(DeclError::UnsafeName(_))+ ));}#[test]@@ -515,12 +606,50 @@ mod tests {);}+ /// Past the provider limit the name is hashed into it rather than refused.#[test]- fn an_over_long_name_is_refused() {+ fn an_over_long_name_is_mapped_within_the_limit() {let long = "t".repeat(MAX_NAME_LEN);+ let set = HostToolSet::declare(vec![decl(&long)]).expect("mapped");+ let tool = &set.all()[0];+ assert_eq!(tool.name, long);+ assert!(tool.qualified_name.len() <= MAX_NAME_LEN, "{}", tool.qualified_name);+ }++ /// Two names that differ only in characters the mapping drops still get+ /// distinct wire names; the one real collision -- a safe name spelled the+ /// same as another's mapping -- is refused as a duplicate.+ #[test]+ fn a_wire_name_collision_is_a_duplicate() {+ let set = HostToolSet::declare(vec![decl("a.b"), decl("a b")]).expect("distinct");+ assert_ne!(set.all()[0].qualified_name, set.all()[1].qualified_name);+ let mapped = HostToolSet::declare(vec![decl("a.b")]).expect("declares").all()[0]+ .qualified_name+ .strip_prefix(NAME_PREFIX)+ .expect("prefixed")+ .to_string();assert_eq!(- HostToolSet::declare(vec![decl(&long)]),- Err(DeclError::NameTooLong(long))+ HostToolSet::declare(vec![decl("a.b"), decl(&mapped)]),+ Err(DeclError::Duplicate(mapped))+ );+ }++ #[test]+ fn validate_checks_the_declared_schema() {+ let set = HostToolSet::declare(vec![HostToolDecl {+ parameters: Some(json!({+ "type": "object",+ "properties": { "n": { "type": "integer" } },+ "required": ["n"]+ })),+ ..decl("count")+ }])+ .expect("declares");+ let tool = &set.all()[0];+ assert_eq!(tool.validate(&json!({ "n": 3 })), Ok(()));+ assert_eq!(+ tool.validate(&json!({})),+ Err("/: missing required property 'n'".to_string()));}@@ -530,6 +659,7 @@ mod tests {name: "observe".to_string(),description: String::new(),parameters: Some(json!("string")),+ capability: None,unknown: Default::default(),}]);assert_eq!(err, Err(DeclError::NonObjectSchema("observe".to_string())));@@ -541,6 +671,8 @@ mod tests {let (id, receiver) = register(®istry).await;let result = HostToolResult {content: "ok".to_string(),+ parts: None,+ details: None,is_error: false,};respond(®istry, &id, Ok(result.clone()))@@ -551,6 +683,8 @@ mod tests {// reported, rather than overwriting a result the run already used.assert!(respond(®istry, &id, Ok(HostToolResult {content: "again".to_string(),+ parts: None,+ details: None,is_error: false,})).await@@ -567,4 +701,81 @@ mod tests {Err(HostToolError::ClientGone));}++ /// The caller emits one cancellation record per released id, so the ids+ /// must come back -- and only the ones that were actually pending.+ #[tokio::test]+ async fn strand_all_returns_the_ids_it_released() {+ let registry = new_registry();+ let (a, ra) = register(®istry).await;+ let (b, rb) = register(®istry).await;+ let mut expected = vec![a, b];+ expected.sort();+ assert_eq!(strand_all(®istry).await, expected);+ assert_eq!(ra.await.expect("delivered"), Err(HostToolError::ClientGone));+ assert_eq!(rb.await.expect("delivered"), Err(HostToolError::ClientGone));+ // Nothing left: a second drain releases nothing and reports nothing.+ assert!(strand_all(®istry).await.is_empty());+ }++ #[tokio::test]+ async fn strand_reports_whether_it_released_the_request() {+ let registry = new_registry();+ let (id, receiver) = register(®istry).await;+ assert!(strand(®istry, &id).await);+ assert_eq!(+ receiver.await.expect("delivered"),+ Err(HostToolError::ClientGone)+ );+ assert!(!strand(®istry, &id).await, "already released");+ }++ #[tokio::test]+ async fn cancel_all_withdraws_pending_calls_as_cancelled() {+ let registry = new_registry();+ let (id, receiver) = register(®istry).await;+ assert_eq!(cancel_all(®istry).await, vec![id.clone()]);+ assert_eq!(+ receiver.await.expect("delivered"),+ Err(HostToolError::Cancelled)+ );+ // A late reply names the request and says why it might be gone.+ let err = respond(®istry, &id, Ok(HostToolResult {+ content: "late".to_string(),+ parts: None,+ details: None,+ is_error: false,+ }))+ .await+ .expect_err("nothing pending");+ assert_eq!(+ err,+ format!("no host tool request '{id}' is pending (answered, cancelled, or never issued)")+ );+ }++ #[test]+ fn a_declared_capability_is_carried_onto_the_tool() {+ let decls: Vec<HostToolDecl> = serde_json::from_str(+ r#"[{"name":"camera","capability":"read"},+ {"name":"arm","capability":"actuator"},+ {"name":"plain"}]"#,+ )+ .expect("parses");+ let set = HostToolSet::declare(decls).expect("declares");+ assert_eq!(set.all()[0].capability, Some(HostCapability::Read));+ assert_eq!(set.all()[1].capability, Some(HostCapability::Actuator));+ assert_eq!(set.all()[2].capability, None);+ // An unknown class is a parse error, not a silent opaque default.+ assert!(serde_json::from_str::<HostToolDecl>(+ r#"{"name":"x","capability":"write"}"#+ )+ .is_err());+ }++ #[test]+ fn the_unknown_key_message_lists_capability() {+ let msg = DeclError::UnknownKey("x".to_string(), "k".to_string()).to_string();+ assert!(msg.contains("capability"), "{msg}");+ }}diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 4072aaa4b..d6b593dc0 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -78,6 +78,18 @@ pub(crate) struct OrchestrationArgs {pub host_tools: crate::core::agent::host_tools::HostToolSet,#[cfg(feature = "cli")]pub host_tool_requests: crate::core::agent::host_tools::HostToolRegistry,+ /// The host's own callback is the permission gate for its tools: Jan never+ /// emits a `permission_request` for a host tool, whatever its capability.+ /// Built-ins are unaffected. Inherited by children with the tool set.+ #[cfg(feature = "cli")]+ pub host_owns_gate: bool,+ /// Where this run's `tool_request`s go when it is not the run the client+ /// reads: the root events sender and this run's id. A subagent's own+ /// events reach stdout wrapped in `Subagent { .. }`, a shape no client may+ /// answer, so its requests bypass that channel and are emitted unwrapped,+ /// attributed by `run_id`. `None` for the main run.+ #[cfg(feature = "cli")]+ pub host_tool_route: Option<(mpsc::UnboundedSender<StreamEvent>, String)>,/// Present only when a client can render and answer structured questions.pub ask_requests: Option<crate::core::agent::interaction::AskRegistry>,/// Session's canonical todo list. Present for the top-level run only;@@ -168,6 +180,12 @@ pub(crate) struct ToolOutcome {pub content: String,pub diff: Option<String>,pub images: Vec<tauri_plugin_agent_tools::tools::ImageContentPart>,+ /// Content parts a host tool returned. When set they *are* the tool+ /// message, verbatim and in order; `content` is then only the text summary+ /// for hooks and the `tool_result` event.+ pub parts: Option<Vec<serde_json::Value>>,+ /// Host/UI-only data, emitted as `tool_details` and never sent to the model.+ pub details: Option<serde_json::Value>,}impl ToolOutcome {@@ -177,10 +195,48 @@ impl ToolOutcome {content,diff: None,images: Vec::new(),+ parts: None,+ details: None,}}}+/// What a host tool call produced: the text summary, the content parts that+/// replace it on the wire when the host sent any, and the display-only details.+#[cfg(feature = "cli")]+type HostCallResult = (String, Option<Vec<serde_json::Value>>, Option<serde_json::Value>);++/// The gate class of one host tool call, from its declared capability and+/// whether the host owns the gate.+// Off the headless build there are no host tools, so only `Opaque` is built.+#[cfg_attr(not(feature = "cli"), allow(dead_code))]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum HostGate {+ /// Declared `read`: never prompted, allowed in Plan mode, concurrent.+ Read,+ /// The host's callback is the gate: never prompted here, sequential.+ Host,+ /// Declared `actuator`: prompted even under `auto_approve`, sequential.+ Actuator,+ /// Undeclared: prompted unless `auto_approve`, sequential.+ Opaque,+}++/// Mark a failed host result's content parts the way a failed text result is+/// marked, so the model can tell an error from an answer: the first text part+/// gains the `ERROR: ` prefix, or one is put in front when there is none.+#[cfg(feature = "cli")]+fn mark_parts_as_error(mut parts: Vec<serde_json::Value>) -> Vec<serde_json::Value> {+ let first_text = parts+ .iter_mut()+ .find(|p| p.get("type").and_then(|t| t.as_str()) == Some("text"));+ match first_text.and_then(|p| p.get_mut("text")) {+ Some(serde_json::Value::String(text)) => text.insert_str(0, "ERROR: "),+ _ => parts.insert(0, serde_json::json!({ "type": "text", "text": "ERROR" })),+ }+ parts+}+/// One background ping. `text` is what reaches the model as a `<SYSTEM>`/// reminder; `headline`, when set, is shown to the user at delivery as/// [`StreamEvent::Notice`]. Subagent completions carry no headline -- their@@ -433,6 +489,12 @@ struct CompositeToolInvoker {host_tools: crate::core::agent::host_tools::HostToolSet,#[cfg(feature = "cli")]host_tool_requests: crate::core::agent::host_tools::HostToolRegistry,+ /// See [`OrchestrationArgs::host_owns_gate`].+ #[cfg(feature = "cli")]+ host_owns_gate: bool,+ /// See [`OrchestrationArgs::host_tool_route`].+ #[cfg(feature = "cli")]+ host_tool_route: Option<(mpsc::UnboundedSender<StreamEvent>, String)>,/// `context` answers and failure notices raised by hooks during this run,/// drained into `<SYSTEM>` reminders alongside the monitor's. `Arc` because/// the tool-event hooks fire inside the toolset and report through a sink@@ -881,17 +943,56 @@ impl CompositeToolInvoker {}}+ /// How the gate treats a call to host tool `name`. Off the headless build+ /// there are no host tools, so the answer is never consulted there.+ fn host_gate(&self, name: &str) -> HostGate {+ #[cfg(feature = "cli")]+ {+ use crate::core::agent::host_tools::HostCapability;+ let capability = self.host_tools.get(name).and_then(|t| t.capability);+ match capability {+ // Plan mode and concurrency follow the capability even when+ // the host owns the gate; only the prompt is the host's.+ Some(HostCapability::Read) => HostGate::Read,+ _ if self.host_owns_gate => HostGate::Host,+ Some(HostCapability::Actuator) => HostGate::Actuator,+ None => HostGate::Opaque,+ }+ }+ #[cfg(not(feature = "cli"))]+ {+ let _ = name;+ HostGate::Opaque+ }+ }++ /// Ask the user about a host tool call, honoring a thread-scoped "allow+ /// always" the user already gave for it.+ async fn approve_host_tool(&self, name: &str) -> bool {+ if self.grants.lock().unwrap().covers_mcp(name) {+ return true;+ }+ match self.prompt_mcp_permission(name).await {+ PermissionDecision::AllowOnce => true,+ PermissionDecision::AllowAlways => {+ self.grants.lock().unwrap().grant_mcp(name);+ true+ }+ PermissionDecision::Deny => false,+ }+ }+/// Hand a host tool call to the client and wait for its answer.///- /// The returned string is what the model sees, in every outcome: a host- /// that fails, or one that goes away mid-call, still produces a tool- /// message. An unanswered call would otherwise leave the conversation with- /// an assistant turn whose call is never resolved, which is not a state the- /// run can be resumed from.+ /// The returned text is what the model sees, in every outcome, unless the+ /// host answered with content parts: a host that fails, or one that goes+ /// away mid-call, still produces a tool message. An unanswered call would+ /// otherwise leave the conversation with an assistant turn whose call is+ /// never resolved, which is not a state the run can be resumed from.#[cfg(feature = "cli")]- async fn call_host_tool(&self, name: &str, args: &serde_json::Value) -> String {+ async fn call_host_tool(&self, name: &str, args: &serde_json::Value) -> HostCallResult {let Some(tool) = self.host_tools.get(name) else {- return format!("ERROR: host tool '{name}' is not registered");+ return (format!("ERROR: host tool '{name}' is not registered"), None, None);};// The same hook bracket the plugin path fires, for the same reason: a// host tool is still a tool call, and a PreToolUse policy that could@@ -908,29 +1009,62 @@ impl CompositeToolInvoker {).await{- return hook_denied_msg(name, &reason);+ return (hook_denied_msg(name, &reason), None, None);+ }+ // After the hook, so a policy sees every attempted call, and before+ // the request exists, so the host -- possibly driving hardware --+ // never receives arguments its own schema forbids.+ if let Err(why) = tool.validate(args) {+ return (+ format!(+ "ERROR: arguments for host tool '{}' do not match its schema: {why}",+ tool.name+ ),+ None,+ None,+ );}let (request_id, receiver) =crate::core::agent::host_tools::register(&self.host_tool_requests).await;// The host declared `observe` and dispatches on `observe`; the `host__`- // prefix is this layer's business, not the host's.- let _ = self.events.send(StreamEvent::ToolRequest {+ // prefix is this layer's business, not the host's. A child's request+ // goes to the root channel unwrapped, so the client answers it exactly+ // as it answers the main run's.+ let (sink, run_id) = match &self.host_tool_route {+ Some((sender, run_id)) => (sender, Some(run_id.clone())),+ None => (&self.events, None),+ };+ let _ = sink.send(StreamEvent::ToolRequest {request_id: request_id.clone(),tool_name: tool.name.clone(),args: args.clone(),+ run_id,});- let content = match receiver.await {+ let (content, parts, details) = match receiver.await {Ok(Ok(result)) => {if result.is_error {- format!("ERROR: {}", result.content)+ let parts = result.parts.map(mark_parts_as_error);+ (format!("ERROR: {}", result.content), parts, result.details)} else {- result.content+ (result.content, result.parts, result.details)}}+ Ok(Err(crate::core::agent::host_tools::HostToolError::Cancelled)) => {+ self.host_tool_requests.lock().await.remove(&request_id);+ (+ format!("ERROR: host tool '{}' was cancelled before it answered", tool.name),+ None,+ None,+ )+ }// Stranded by a closed pipe, or the sender dropped with the run.Ok(Err(crate::core::agent::host_tools::HostToolError::ClientGone)) | Err(_) => {self.host_tool_requests.lock().await.remove(&request_id);- format!("ERROR: host tool '{}' was not answered: the client is gone", tool.name)+ (+ format!("ERROR: host tool '{}' was not answered: the client is gone", tool.name),+ None,+ None,+ )}};self.fire_hooks(@@ -941,7 +1075,7 @@ impl CompositeToolInvoker {},).await;- content+ (content, parts, details)}/// Prompt the user to approve an MCP tool call, mirroring the built-in gate.@@ -1521,6 +1655,10 @@ impl ToolInvoker for CompositeToolInvoker {// that prompts, writes, execs, or dispatches stays sequential so// permission prompts don't interleave and writes can't race.let mut read_futures = Vec::new();+ // Host tools declared `read`: auto-allowed like the built-in reads and+ // run concurrently with each other once the gating pass is over.+ #[cfg(feature = "cli")]+ let mut host_read_calls: Vec<(String, String, serde_json::Value)> = Vec::new();for tc in tool_calls {let name = tc.get("function")@@ -1609,18 +1747,20 @@ impl ToolInvoker for CompositeToolInvoker {out.push(ToolOutcome::plain(id, content));continue;}- // Host tools execute in the client, not here. Dispatched on the- // same terms as a plugin or MCP tool -- opaque capability, so- // prompted and withheld in Plan mode -- but the call leaves the- // process instead of running in it. `is_host_tool` is constant- // `false` off the headless build, which has no client to ask.+ // Host tools execute in the client, not here. The call leaves the+ // process instead of running in it, and the host's declared+ // capability decides the gate (see `host_gate`). `is_host_tool` is+ // constant `false` off the headless build, which has no client.if self.is_host_tool(name) {let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();- if self.run_mode == crate::core::agent::plan::RunMode::Plan {+ let gate = self.host_gate(name);+ if self.run_mode == crate::core::agent::plan::RunMode::Plan+ && gate != HostGate::Read+ {out.push(ToolOutcome::plain(id, plan_mode_read_only_msg(name)));continue;}@@ -1637,16 +1777,25 @@ impl ToolInvoker for CompositeToolInvoker {.and_then(|v| v.as_str()).and_then(|s| serde_json::from_str(s).ok()).unwrap_or(serde_json::Value::Object(Default::default()));- let approved = self.auto_approve- || self.grants.lock().unwrap().covers_mcp(name)- || match self.prompt_mcp_permission(name).await {- PermissionDecision::AllowOnce => true,- PermissionDecision::AllowAlways => {- self.grants.lock().unwrap().grant_mcp(name);- true- }- PermissionDecision::Deny => false,- };+ // A read is deferred and joined with the other auto-allowed+ // reads below, so two camera frames do not wait on each other.+ // `self` is borrowed by the future, which is why these are+ // collected here and only driven after this loop is done.+ #[cfg(feature = "cli")]+ if gate == HostGate::Read {+ host_read_calls.push((id, name.to_string(), args));+ continue;+ }+ let approved = match gate {+ HostGate::Read | HostGate::Host => true,+ // An actuator is prompted even under `auto_approve`: that+ // is the whole point of declaring one. A session grant+ // still covers it, since the user said so explicitly.+ HostGate::Actuator => self.approve_host_tool(name).await,+ HostGate::Opaque => {+ self.auto_approve || self.approve_host_tool(name).await+ }+ };if !approved {out.push(ToolOutcome::plain(id,@@ -1655,15 +1804,21 @@ impl ToolInvoker for CompositeToolInvoker {continue;}#[cfg(feature = "cli")]- let content = self.call_host_tool(name, &args).await;+ {+ let (content, parts, details) = self.call_host_tool(name, &args).await;+ out.push(ToolOutcome {+ parts,+ details,+ ..ToolOutcome::plain(id, content)+ });+ }// Unreachable off the headless build, where `is_host_tool` is// constant `false`.#[cfg(not(feature = "cli"))]- let content = {+ {let _ = &args;- String::new()- };- out.push(ToolOutcome::plain(id, content));+ out.push(ToolOutcome::plain(id, String::new()));+ }continue;}// Plugin-declared tools are dispatched ahead of the MCP fallback:@@ -1895,10 +2050,9 @@ impl ToolInvoker for CompositeToolInvoker {.with_hooks(&hooks, planning, Some(hook_sink));let (text, diff, images) = execute_builtin_with_diff(tool, &args, &ctx).await;ToolOutcome {- id,- content: text,diff,images: images.unwrap_or_default(),+ ..ToolOutcome::plain(id, text)}});continue;@@ -1992,15 +2146,26 @@ impl ToolInvoker for CompositeToolInvoker {}};out.push(ToolOutcome {- id,- content: text,diff,images: images.unwrap_or_default(),+ ..ToolOutcome::plain(id, text)});}if !read_futures.is_empty() {out.extend(futures::future::join_all(read_futures).await);}+ #[cfg(feature = "cli")]+ if !host_read_calls.is_empty() {+ let calls = host_read_calls.iter().map(|(id, name, args)| async move {+ let (content, parts, details) = self.call_host_tool(name, args).await;+ ToolOutcome {+ parts,+ details,+ ..ToolOutcome::plain(id.clone(), content)+ }+ });+ out.extend(futures::future::join_all(calls).await);+ }if !mcp_calls.is_empty() {let results = self.mcp.invoke(&mcp_calls).await?;for outcome in &results {@@ -2305,12 +2470,18 @@ fn advertise_local_tools(openai_tools.push(crate::core::agent::todo::todo_tool_schema());}// Host tools run in the client, not here, so they need no project root --- // like `ask` and `todo` they are advertised independent of that gate. What- // they do share with plugin and MCP tools is an opaque capability, so they- // are withheld entirely in read-only Plan mode and honor the deny list.+ // like `ask` and `todo` they are advertised independent of that gate. An+ // undeclared or actuator tool shares the plugin/MCP treatment and is+ // withheld in read-only Plan mode; one the host declared `read` stays.+ // Every one honors the deny list.#[cfg(feature = "cli")]- if !planning {+ {for tool in host_tools.all() {+ let is_read =+ tool.capability == Some(crate::core::agent::host_tools::HostCapability::Read);+ if planning && !is_read {+ continue;+ }if permissions.is_denied(&tool.qualified_name) {continue;}@@ -2611,6 +2782,10 @@ async fn orchestrate_inner(host_tools,#[cfg(feature = "cli")]host_tool_requests,+ #[cfg(feature = "cli")]+ host_owns_gate,+ #[cfg(feature = "cli")]+ host_tool_route,ask_requests,todo_registry,system_prompt_override,@@ -2980,6 +3155,10 @@ async fn orchestrate_inner(host_tools: host_tools.clone(),#[cfg(feature = "cli")]host_tool_requests: host_tool_requests.clone(),+ #[cfg(feature = "cli")]+ host_owns_gate: *host_owns_gate,+ #[cfg(feature = "cli")]+ host_tool_route: host_tool_route.clone(),hook_notices_queue: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),bg_shells: session_bg_shells.clone().unwrap_or_default(),};@@ -4148,6 +4327,8 @@ async fn run_turn_cycle(content,diff,images,+ parts,+ details,} = outcome;// A `bash` call that exits non-zero isn't prefixed "ERROR" (that// convention is reserved for hard tool failures the model must@@ -4168,11 +4349,23 @@ async fn run_turn_cycle(is_error,diff: diff.clone(),});+ // Display-only, and after the result so a consumer can attach it+ // to a row it has already drawn. Never reaches the transcript.+ if let Some(details) = details {+ let _ = events.send(StreamEvent::ToolDetails {+ id: id.clone(),+ details,+ });+ }// A `read` of an image carries OpenAI `image_url` content parts; the// tool message is then a content-part array (text note first, the// image parts after) so a vision model sees the image. Other results- // stay plain text, preserving the standard tool protocol.- let wire_content = if images.is_empty() {+ // stay plain text, preserving the standard tool protocol. A host+ // that answered with content parts chose the message itself, so+ // its parts go out verbatim.+ let wire_content = if let Some(parts) = parts {+ serde_json::Value::Array(parts)+ } else if images.is_empty() {serde_json::Value::String(content.clone())} else {let mut parts = vec![serde_json::json!({@@ -5171,13 +5364,14 @@ mod tests {.unwrap_or("").to_string();ToolOutcome {- id,- content: "Read image pic.png (image/png, 10 bytes)".to_string(),- diff: None,images: vec![tauri_plugin_agent_tools::tools::ImageContentPart {data_url: "data:image/png;base64,QUJD".to_string(),name: "pic.png".to_string(),}],+ ..ToolOutcome::plain(+ id,+ "Read image pic.png (image/png, 10 bytes)".to_string(),+ )}}).collect())@@ -5224,6 +5418,99 @@ mod tests {assert_eq!(content[1]["image_url"]["detail"], "auto");}+ /// A host tool that answered with content parts chose the tool message+ /// itself: the parts go out verbatim and in order. Its details are for the+ /// host's display only, so they arrive as a `tool_details` event right+ /// after the result and never appear in what the model is sent.+ #[tokio::test]+ async fn host_parts_are_the_tool_message_and_details_stay_off_the_wire() {+ let (tx, mut rx) = mpsc::unbounded_channel();+ let model = MockModel::new(vec![+ tool_call_completion(),+ json!({ "choices": [{ "message": { "content": "final answer" }, "finish_reason": "stop" }] }),+ ]);+ struct PartsTool;+ #[async_trait]+ impl ToolInvoker for PartsTool {+ async fn invoke(+ &self,+ tool_calls: &[serde_json::Value],+ ) -> Result<Vec<ToolOutcome>, String> {+ Ok(tool_calls+ .iter()+ .map(|tc| ToolOutcome {+ parts: Some(vec![+ json!({ "type": "image_url", "image_url": { "url": "data:image/png;base64,QUJD" } }),+ json!({ "type": "text", "text": "after the image" }),+ ]),+ details: Some(json!({ "secret_pose": [1, 2, 3] })),+ ..ToolOutcome::plain(+ tc["id"].as_str().unwrap_or("").to_string(),+ "after the image".to_string(),+ )+ })+ .collect())+ }+ }+ let mut budget = SessionBudget::new(None);+ run_turn_cycle(+ &tx,+ &json!({}),+ "m",+ &[],+ Transcript::from_history(vec![json!({ "role": "user", "content": "hi" })]),+ None,+ true,+ 8,+ &mut budget,+ &model,+ &PartsTool,+ crate::core::agent::plan::RunMode::Normal,+ None,+ None,+ None,+ None,+ )+ .await+ .unwrap();++ let requests = model.requests.lock().unwrap();+ let tool_msg = requests[1]["messages"]+ .as_array()+ .unwrap()+ .iter()+ .find(|m| m["role"] == "tool")+ .cloned()+ .expect("a tool message");+ assert_eq!(+ tool_msg["content"],+ json!([+ { "type": "image_url", "image_url": { "url": "data:image/png;base64,QUJD" } },+ { "type": "text", "text": "after the image" },+ ])+ );+ assert!(+ !requests[1].to_string().contains("secret_pose"),+ "details must never reach the model"+ );++ let mut seen = Vec::new();+ while let Ok(ev) = rx.try_recv() {+ match ev {+ StreamEvent::ToolResult { id, content, .. } => seen.push(format!("result {id} {content}")),+ StreamEvent::ToolDetails { id, details } => seen.push(format!("details {id} {details}")),+ _ => {}+ }+ }+ assert_eq!(+ seen,+ [+ "result call_1 after the image".to_string(),+ r#"details call_1 {"secret_pose":[1,2,3]}"#.to_string(),+ ]+ );+ }+/// The reported incident, end to end: mid-run, the model emits a tool/// call whose arguments are a JSON string literal containing JSON. The/// call is never executed, and the poisoned turn never reaches a later@@ -7227,6 +7514,10 @@ mod tests {host_tools: crate::core::agent::host_tools::HostToolSet::new(),#[cfg(feature = "cli")]host_tool_requests: crate::core::agent::host_tools::new_registry(),+ #[cfg(feature = "cli")]+ host_owns_gate: false,+ #[cfg(feature = "cli")]+ host_tool_route: None,hook_notices_queue: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),bg_shells: std::sync::Arc::new(crate::core::agent::bg_shell::BackgroundShells::default(),@@ -7626,6 +7917,7 @@ mod tests {request_id,tool_name,args,+ ..} = ev{match reply {@@ -7672,6 +7964,7 @@ mod tests {name: n.to_string(),description: String::new(),parameters: None,+ capability: None,unknown: Default::default(),}).collect(),@@ -7679,6 +7972,436 @@ mod tests {.expect("the test names are valid")}+ /// A host tool set whose entries each declare a capability.+ #[cfg(feature = "cli")]+ fn host_tool_set_with(+ tools: &[(&str, Option<crate::core::agent::host_tools::HostCapability>)],+ ) -> crate::core::agent::host_tools::HostToolSet {+ crate::core::agent::host_tools::HostToolSet::declare(+ tools+ .iter()+ .map(|(n, capability)| crate::core::agent::host_tools::HostToolDecl {+ name: n.to_string(),+ description: String::new(),+ parameters: None,+ capability: *capability,+ unknown: Default::default(),+ })+ .collect(),+ )+ .expect("the test names are valid")+ }++ #[cfg(feature = "cli")]+ fn host_ok(content: &str) -> crate::core::agent::host_tools::HostToolResult {+ crate::core::agent::host_tools::HostToolResult {+ content: content.to_string(),+ parts: None,+ details: None,+ is_error: false,+ }+ }++ /// Answers every `tool_request` with `content` and every permission+ /// prompt with `decision`, recording what it saw: the request tool names+ /// and the prompted tool names. Ends when the invoker's sender drops.+ #[cfg(feature = "cli")]+ fn answering_host(+ invoker: &CompositeToolInvoker,+ mut events: mpsc::UnboundedReceiver<StreamEvent>,+ decision: PermissionDecision,+ ) -> tokio::task::JoinHandle<(Vec<String>, Vec<String>)> {+ let registry = invoker.host_tool_requests.clone();+ let permissions = invoker.permission_requests.clone();+ tokio::spawn(async move {+ let mut asked = Vec::new();+ let mut prompted = Vec::new();+ while let Some(ev) = events.recv().await {+ match ev {+ StreamEvent::ToolRequest {+ request_id,+ tool_name,+ ..+ } => {+ crate::core::agent::host_tools::respond(+ ®istry,+ &request_id,+ Ok(host_ok("done")),+ )+ .await+ .expect("pending");+ asked.push(tool_name);+ }+ StreamEvent::PermissionRequest {+ request_id,+ tool_name,+ ..+ } => {+ if let Some(tx) = permissions.lock().await.remove(&request_id) {+ let _ = tx.send(decision);+ }+ prompted.push(tool_name);+ }+ _ => {}+ }+ }+ (asked, prompted)+ })+ }++ /// A `read` host tool is the sensor case: no prompt even with+ /// `auto_approve` off, and two calls in one batch are in flight together.+ /// The stub host answers only once it holds *both* requests, so a+ /// sequential dispatch would deadlock here (bounded by the timeout).+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn read_host_tools_run_concurrently_without_a_prompt() {+ use crate::core::agent::host_tools::HostCapability;+ let root = hooks_root("hosttoolread");+ let (mut invoker, mut events) = host_invoker(+ root.clone(),+ host_tool_set_with(&[("camera", Some(HostCapability::Read))]),+ );+ invoker.auto_approve = false;+ let registry = invoker.host_tool_requests.clone();+ let host = tokio::spawn(async move {+ let mut pending = Vec::new();+ while let Some(ev) = events.recv().await {+ match ev {+ StreamEvent::ToolRequest { request_id, .. } => pending.push(request_id),+ StreamEvent::PermissionRequest { tool_name, .. } => {+ panic!("a read host tool was prompted: {tool_name}")+ }+ _ => {}+ }+ if pending.len() == 2 {+ for (i, id) in pending.iter().enumerate() {+ crate::core::agent::host_tools::respond(+ ®istry,+ id,+ Ok(host_ok(&format!("frame {i}"))),+ )+ .await+ .expect("pending");+ }+ return pending;+ }+ }+ panic!("only {} requests arrived", pending.len());+ });++ let mut first = hooked_tool_call("host__camera", "{}");+ first["id"] = json!("c1");+ let mut second = hooked_tool_call("host__camera", "{}");+ second["id"] = json!("c2");+ let out = tokio::time::timeout(+ std::time::Duration::from_secs(10),+ invoker.invoke(&[first, second]),+ )+ .await+ .expect("both reads were in flight together")+ .unwrap();+ let pending = host.await.expect("the stub host ran");+ assert_eq!(pending.len(), 2);+ let mut ids: Vec<&str> = out.iter().map(|o| o.id.as_str()).collect();+ ids.sort_unstable();+ assert_eq!(ids, ["c1", "c2"]);+ assert!(out.iter().all(|o| o.content.starts_with("frame ")));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Plan mode is read-only, and a host tool declared `read` is exactly that,+ /// so it stays both advertised and callable; the others are withheld.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_read_host_tool_is_available_in_plan_mode() {+ use crate::core::agent::host_tools::HostCapability;+ let set = host_tool_set_with(&[+ ("camera", Some(HostCapability::Read)),+ ("arm", Some(HostCapability::Actuator)),+ ("opaque", None),+ ]);+ let mut tools = Vec::new();+ advertise_local_tools(+ &mut tools,+ None,+ &ToolPermissions::allow_all(),+ None,+ crate::core::agent::plan::RunMode::Plan,+ false,+ 1,+ false,+ false,+ &set,+ );+ let names: Vec<&str> = tools+ .iter()+ .filter_map(|t| t["function"]["name"].as_str())+ .collect();+ assert_eq!(names, ["host__camera"]);++ let root = hooks_root("hosttoolreadplan");+ let (mut invoker, events) = host_invoker(root.clone(), set);+ invoker.run_mode = crate::core::agent::plan::RunMode::Plan;+ let host = answering_host(&invoker, events, PermissionDecision::Deny);+ let out = invoker+ .invoke(&[hooked_tool_call("host__camera", "{}")])+ .await+ .unwrap();+ assert_eq!(out[0].content, "done");+ let out = invoker+ .invoke(&[hooked_tool_call("host__arm", "{}")])+ .await+ .unwrap();+ assert!(out[0].content.contains("plan_mode_read_only"), "{}", out[0].content);+ drop(invoker);+ let (asked, prompted) = host.await.expect("the stub host ran");+ assert_eq!(asked, ["camera"]);+ assert!(prompted.is_empty(), "{prompted:?}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Declaring an actuator is how a host opts a tool out of `auto_approve`:+ /// the user is asked every time, and a denial never reaches the host.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn an_actuator_host_tool_is_prompted_even_under_auto_approve() {+ use crate::core::agent::host_tools::HostCapability;+ let root = hooks_root("hosttoolactuator");+ let (invoker, events) = host_invoker(+ root.clone(),+ host_tool_set_with(&[("arm", Some(HostCapability::Actuator)), ("opaque", None)]),+ );+ assert!(invoker.auto_approve);+ let host = answering_host(&invoker, events, PermissionDecision::Deny);+ let out = invoker+ .invoke(&[hooked_tool_call("host__arm", "{}")])+ .await+ .unwrap();+ assert_eq!(out[0].content, "ERROR: tool 'host__arm' denied by user");+ // The undeclared tool keeps today's behaviour: auto-approved.+ let out = invoker+ .invoke(&[hooked_tool_call("host__opaque", "{}")])+ .await+ .unwrap();+ assert_eq!(out[0].content, "done");+ drop(invoker);+ let (asked, prompted) = host.await.expect("the stub host ran");+ assert_eq!(prompted, ["host__arm"]);+ assert_eq!(asked, ["opaque"]);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// With the host owning the gate its callback is the only prompt: Jan+ /// raises no `permission_request` for any host tool class, even with+ /// `auto_approve` off.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_host_that_owns_the_gate_is_never_prompted_for() {+ use crate::core::agent::host_tools::HostCapability;+ let root = hooks_root("hosttoolhostgate");+ let (mut invoker, events) = host_invoker(+ root.clone(),+ host_tool_set_with(&[("arm", Some(HostCapability::Actuator)), ("opaque", None)]),+ );+ invoker.auto_approve = false;+ invoker.host_owns_gate = true;+ let host = answering_host(&invoker, events, PermissionDecision::Deny);+ let out = invoker+ .invoke(&[+ hooked_tool_call("host__arm", "{}"),+ hooked_tool_call("host__opaque", "{}"),+ ])+ .await+ .unwrap();+ assert!(out.iter().all(|o| o.content == "done"));+ drop(invoker);+ let (asked, prompted) = host.await.expect("the stub host ran");+ assert!(prompted.is_empty(), "{prompted:?}");+ assert_eq!(asked, ["arm", "opaque"]);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A child's host call goes out on the root sender, unwrapped, with its+ /// run id; nothing reaches the child's own channel, which the forwarder+ /// would wrap into a shape no client may answer.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_routed_host_call_is_emitted_unwrapped_with_its_run_id() {+ let root = hooks_root("hosttoolroute");+ let (mut invoker, mut own_events) = host_invoker(root.clone(), host_tool_set(&["observe"]));+ let (route_tx, mut route_rx) = mpsc::unbounded_channel();+ invoker.host_tool_route = Some((route_tx, "sub-7".to_string()));+ let registry = invoker.host_tool_requests.clone();+ let host = tokio::spawn(async move {+ match route_rx.recv().await {+ Some(StreamEvent::ToolRequest {+ request_id,+ tool_name,+ run_id,+ ..+ }) => {+ crate::core::agent::host_tools::respond(®istry, &request_id, Ok(host_ok("seen")))+ .await+ .expect("pending in the shared registry");+ (tool_name, run_id)+ }+ other => panic!("expected a tool_request, got {other:?}"),+ }+ });+ let out = invoker+ .invoke(&[hooked_tool_call("host__observe", "{}")])+ .await+ .unwrap();+ assert_eq!(out[0].content, "seen");+ assert_eq!(+ host.await.expect("the stub host ran"),+ ("observe".to_string(), Some("sub-7".to_string()))+ );+ while let Ok(ev) = own_events.try_recv() {+ assert!(+ !matches!(ev, StreamEvent::ToolRequest { .. }),+ "the request must not enter the child's own channel"+ );+ }+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A withdrawn request still settles the call, and the model is told it+ /// was cancelled rather than that the host vanished.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_cancelled_host_call_tells_the_model_so() {+ let root = hooks_root("hosttoolcancel");+ let (invoker, mut events) = host_invoker(root.clone(), host_tool_set(&["observe"]));+ let registry = invoker.host_tool_requests.clone();+ let host = tokio::spawn(async move {+ while let Some(ev) = events.recv().await {+ if let StreamEvent::ToolRequest { request_id, .. } = ev {+ let released = crate::core::agent::host_tools::cancel_all(®istry).await;+ assert_eq!(released, vec![request_id]);+ return;+ }+ }+ });+ let out = invoker+ .invoke(&[hooked_tool_call("host__observe", "{}")])+ .await+ .unwrap();+ host.await.expect("the stub host ran");+ assert_eq!(+ out[0].content,+ "ERROR: host tool 'observe' was cancelled before it answered"+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The host's schema is enforced before the host is asked: a call with too+ /// few joints goes back to the model as an error naming the path, and the+ /// host never sees a `tool_request` for it.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn arguments_that_break_the_host_schema_never_reach_the_host() {+ let root = hooks_root("hosttoolvalidate");+ let set = crate::core::agent::host_tools::HostToolSet::declare(vec![+ crate::core::agent::host_tools::HostToolDecl {+ name: "move_arm".to_string(),+ description: String::new(),+ parameters: Some(json!({+ "type": "object",+ "properties": {+ "joints": { "type": "array", "items": { "type": "number" }, "minItems": 6 }+ },+ "required": ["joints"]+ })),+ capability: None,+ unknown: Default::default(),+ },+ ])+ .expect("declares");+ let (invoker, events) = host_invoker(root.clone(), set);+ let host = answering_host(&invoker, events, PermissionDecision::AllowOnce);+ let out = invoker+ .invoke(&[hooked_tool_call("host__move_arm", r#"{"joints":[1,2,3]}"#)])+ .await+ .unwrap();+ assert_eq!(+ out[0].content,+ "ERROR: arguments for host tool 'move_arm' do not match its schema: \+ /joints: expected at least 6 items, got 3"+ );+ // A valid call still goes through, so the refusal above was the schema.+ let out = invoker+ .invoke(&[hooked_tool_call("host__move_arm", r#"{"joints":[1,2,3,4,5,6]}"#)])+ .await+ .unwrap();+ assert_eq!(out[0].content, "done");+ drop(invoker);+ let (asked, _) = host.await.expect("the stub host ran");+ assert_eq!(asked, ["move_arm"], "only the valid call reached the host");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A dotted host name is advertised under its mapped wire name, and the+ /// host is asked under the name it declared.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_mapped_host_name_is_requested_under_its_original_name() {+ let root = hooks_root("hosttoolmapped");+ let set = host_tool_set(&["yam.move_ee_ik"]);+ let wire = set.all()[0].qualified_name.clone();+ assert!(wire.starts_with("host__yam_move_ee_ik_"), "{wire}");+ let (invoker, events) = host_invoker(root.clone(), set);+ let host = answering_host(&invoker, events, PermissionDecision::AllowOnce);+ let out = invoker.invoke(&[hooked_tool_call(&wire, "{}")]).await.unwrap();+ assert_eq!(out[0].content, "done");+ drop(invoker);+ let (asked, _) = host.await.expect("the stub host ran");+ assert_eq!(asked, ["yam.move_ee_ik"]);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Parts and details a host answers with survive dispatch onto the+ /// outcome; a failed result's parts carry the error marker too.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn host_parts_and_details_reach_the_outcome() {+ let root = hooks_root("hosttoolparts");+ let (invoker, events) = host_invoker(root.clone(), host_tool_set(&["camera"]));+ let parts = vec![+ json!({ "type": "text", "text": "front camera" }),+ json!({ "type": "image_url", "image_url": { "url": "data:image/png;base64,QUJD" } }),+ ];+ let host = stub_host(+ invoker.host_tool_requests.clone(),+ events,+ Ok(crate::core::agent::host_tools::HostToolResult {+ content: "front camera".to_string(),+ parts: Some(parts.clone()),+ details: Some(json!({ "exposure": 12 })),+ is_error: false,+ }),+ );+ let out = invoker+ .invoke(&[hooked_tool_call("host__camera", "{}")])+ .await+ .unwrap();+ host.await.expect("the stub host ran");+ assert_eq!(out[0].content, "front camera");+ assert_eq!(out[0].parts.as_deref(), Some(parts.as_slice()));+ assert_eq!(out[0].details, Some(json!({ "exposure": 12 })));++ assert_eq!(+ mark_parts_as_error(parts.clone())[0],+ json!({ "type": "text", "text": "ERROR: front camera" })+ );+ assert_eq!(+ mark_parts_as_error(vec![parts[1].clone()])[0],+ json!({ "type": "text", "text": "ERROR" })+ );+ let _ = std::fs::remove_dir_all(&root);+ }+/// R1 end to end: the call leaves as a `tool_request` carrying the host's/// own name, and the host's answer comes back as the tool message content.#[cfg(feature = "cli")]@@ -7691,6 +8414,8 @@ mod tests {events,Ok(crate::core::agent::host_tools::HostToolResult {content: "two cameras, both clear".to_string(),+ parts: None,+ details: None,is_error: false,}),);@@ -7724,6 +8449,8 @@ mod tests {events,Ok(crate::core::agent::host_tools::HostToolResult {content: "arm is estopped".to_string(),+ parts: None,+ details: None,is_error: true,}),);diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex 3d9fdc659..0c47d1cd0 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -32,6 +32,9 @@ pub mod hooks_config;// that could answer a `tool_request`.#[cfg(feature = "cli")]pub mod host_tools;+// Only host tools consume these helpers, so they share host_tools' gate.+#[cfg(feature = "cli")]+pub mod host_schema;pub mod interaction;pub mod r#loop;pub mod memory;diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 585eb14ff..eb793a512 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -1295,17 +1295,17 @@ async fn run_subagent(// above), so it has no registry to share; clearing this keeps it from// inheriting the parent session's by accident.child_args.subagent_bg = None;- // Host tools are the client's to execute, and a client answers a- // `tool_request` it can see. A child's events reach stdout wrapped in- // `Subagent { .. }`, a shape no client is told it may answer, so a child- // that inherited the set would raise a request nobody could resolve: the- // strand guard matches only a top-level request, and the turn would park.- // A child therefore advertises no host tools at all, for the same reason- // `ask_requests` is cleared above -- no client is attached to a child run.+ // Host tools are the client's to execute, and a client answers only a+ // `tool_request` it can see at the top level. A child's own events reach+ // stdout wrapped in `Subagent { .. }`, a shape no client may answer, so the+ // child keeps the parent's tool set, gate and -- crucially -- the *same*+ // request registry, but emits its requests on the parent's sender instead,+ // unwrapped and attributed by `run_id`. `events` is the root channel here+ // (children cannot nest), so the printer's strand guard and the stdin+ // reader see a child's request exactly as they see the main run's.#[cfg(feature = "cli")]{- child_args.host_tools = crate::core::agent::host_tools::HostToolSet::new();- child_args.host_tool_requests = crate::core::agent::host_tools::new_registry();+ child_args.host_tool_route = Some((events.clone(), run_id.clone()));}let body = child_body(&resolved, &description, &parent);@@ -3148,6 +3148,8 @@ mod tests {permission_requests: Arc::new(tokio::sync::Mutex::new(HashMap::new())),host_tools: crate::core::agent::host_tools::HostToolSet::new(),host_tool_requests: crate::core::agent::host_tools::new_registry(),+ host_owns_gate: false,+ host_tool_route: None,ask_requests: None,todo_registry: None,system_prompt_override: None,@@ -4042,8 +4044,9 @@ mod tests {/// forwarder is a *negative* match: anything not explicitly held back is/// forwarded, so a nested `ToolRequest` would be handed to a client that is/// told nothing about the wrapper and could not answer it. Nothing here- /// filters that shape, which is exactly why `run_subagent` clears the- /// child's host tool set instead: the request is never raised at all.+ /// filters that shape, which is exactly why a child's host calls never+ /// enter its own channel: `run_subagent` routes them to the root sender+ /// (`host_tool_route`), unwrapped.#[test]fn a_nested_tool_request_would_reach_the_parent_unfiltered() {use crate::core::agent::events::StreamEvent;@@ -4052,9 +4055,10 @@ mod tests {request_id: "host-1".to_string(),tool_name: "robot_arm_move".to_string(),args: serde_json::json!({}),+ run_id: None,}),- "the forwarder does not hold back a nested tool_request, so a child \- must never own host tools in the first place"+ "the forwarder does not hold back a nested tool_request, so a child's \+ request must be routed around it");}diff --git a/src-tauri/src/core/cli/contract_conformance.rs b/src-tauri/src/core/cli/contract_conformance.rsindex be3586dd8..d966f1a9c 100644--- a/src-tauri/src/core/cli/contract_conformance.rs+++ b/src-tauri/src/core/cli/contract_conformance.rs@@ -112,8 +112,9 @@ const HOST_TO_SESSION: &[InputRow] = &[contract: "tool_result",here: Some("tool_result"),// The contract answers with the tool's own `result` JSON under the- // request's `id`; this build takes `request_id` with a `content` string- // and an `is_error` flag, the shape a model tool message takes.+ // request's `id`; this build takes `request_id` with `content` (a string+ // or a content-part array), an `is_error` flag and optional `details`,+ // the shape a model tool message takes.fields: &[("id", "\"call-7\""), ("result", "{\"ok\":true}")],},];@@ -152,14 +153,18 @@ const SESSION_TO_HOST: &[OutputRow] = &[},OutputRow {contract: "tool_request",- here: None,+ here: Some("tool_request"),+ // The contract's `id` / `name` are `request_id` / `tool_name` here;+ // `tool_name` is the host's own declared name, not the wire name the+ // model called. `run_id` attributes a subagent's call and is absent+ // for the main run, so a main-run request is unchanged on the wire.contract_requires: &[("id", "\"call-7\""),("name", "\"observe\""),("args", "{}"),],- build_produces: &[],- optional: &[],+ build_produces: &["request_id", "tool_name", "args", "run_id"],+ optional: &["run_id"],},OutputRow {contract: "turn_count",@@ -204,8 +209,9 @@ const SESSION_TO_HOST: &[OutputRow] = &[contract: "tool_end",here: Some("tool_result"),// R11 wants a failure flag (carried as `is_error`) and structured- // `details` (absent). `content` being a `String` is R2's gap as much as- // a naming one: an image-bearing result cannot be expressed here.+ // `details`, which travel as a separate `tool_details` record right+ // after this one rather than on it. `content` stays the text summary;+ // a host result's image parts go to the model, not onto this event.contract_requires: &[("name", "\"command\""),("error", "null"),@@ -320,6 +326,8 @@ fn the_implemented_host_rows_parse_as_their_own_kind() {request_id: "call-7".to_string(),result: crate::core::agent::host_tools::HostToolResult {content: "ok".to_string(),+ parts: None,+ details: None,is_error: false,},},@@ -362,17 +370,27 @@ fn every_unimplemented_host_row_is_refused_by_name() {/// Rows the build does not emit are not events yet.///-/// Probed with the contract's own message, so the row stops failing here the-/// moment a variant lands and the table has to move with it.+/// Probed by *tag*, not merely by whether the contract's message parses: a+/// variant that lands under the contract's tag with different field names still+/// refuses the contract's probe, but with a missing- or invalid-field error+/// rather than an unknown variant. Only the unknown-variant refusal means the+/// tag is genuinely free, so anything else fails loudly and the table has to+/// move with the code.#[test]fn every_unimplemented_session_row_is_not_an_event_yet() {for row in SESSION_TO_HOST.iter().filter(|r| r.here.is_none()) {let message = probe(row.contract, row.contract_requires);- if let Ok(event) = serde_json::from_value::<StreamEvent>(message) {- panic!(+ match serde_json::from_value::<StreamEvent>(message) {+ Ok(event) => panic!("'{}' is now an event ({event:?}) - move this row in SESSION_TO_HOST",row.contract- );+ ),+ Err(e) => assert!(+ e.to_string().contains("unknown variant"),+ "'{}' is already a StreamEvent tag (refused as: {e}) - move this row in \+ SESSION_TO_HOST and record what the build produces",+ row.contract+ ),}}}@@ -412,6 +430,12 @@ fn every_implemented_session_row_carries_exactly_the_fields_claimed() {// and not in `optional`.full.then(super::run_report::InputContentParts::current),)),+ "tool_request" => serde_json::to_value(StreamEvent::ToolRequest {+ request_id: "host-1".to_string(),+ tool_name: "observe".to_string(),+ args: serde_json::json!({}),+ run_id: full.then(|| "sub-1".to_string()),+ }),"step" => serde_json::to_value(StreamEvent::Step { index: 2, max: 0 }),"token" => serde_json::to_value(StreamEvent::Token {text: "hi".to_string(),diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex fb45acb60..107c60d53 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1082,6 +1082,7 @@ pub async fn cli_agent_run(format: OutputFormat,input_format: InputFormat,host_tools: Option<&str>,+ host_gate: bool,) -> Result<(), String> {run_agent_loop(project,@@ -1094,6 +1095,7 @@ pub async fn cli_agent_run(format,input_format,host_tools,+ host_gate,).await}@@ -1120,6 +1122,7 @@ pub async fn cli_agent_step(// `step` is a debugging path with no client on stdin, so there is// nothing that could execute a host tool.None,+ false,).await}@@ -1150,6 +1153,8 @@ fn build_cli_orchestration_args(permission_requests,host_tools,host_tool_requests,+ host_owns_gate: false,+ host_tool_route: None,ask_requests: None,todo_registry: None,system_prompt_override: None,@@ -1882,6 +1887,7 @@ async fn run_agent_loop(format: OutputFormat,input_format: InputFormat,host_tools: Option<&str>,+ host_gate: bool,) -> Result<(), String> {// A duplex run switches off both of the CLI's own answer paths, so the// client is the only thing that can resolve a permission request -- and it@@ -1908,6 +1914,11 @@ async fn run_agent_loop(// Declared before anything is spent: a malformed or unacceptable tool// set is the host's own mistake, and finding out at the first call --// mid-task, after paid requests -- is worse than refusing to start.+ // Handing the gate to a host that declared no tools would be a no-op+ // the caller probably did not mean; say so rather than ignore it.+ if host_gate && host_tools.is_none() {+ return Err("--host-gate requires --host-tools".to_string());+ }match host_tools {Some(path) => {if !input_format.is_stream_json() {@@ -1980,6 +1991,9 @@ async fn run_agent_loop(// run rather than per project: the same session config serves a run with// them and one without.args.host_tools = host_tools;+ // `--host-gate`: the host's own callback is the approval step, so Jan+ // raises no `permission_request` for a host tool of any class.+ args.host_owns_gate = host_gate;// Block until active MCP servers connect, so tools (collected once per run)// are present on the first turn.@@ -2028,18 +2042,23 @@ async fn run_agent_loop(let input = input_format.is_stream_json().then(|| Arc::new(StreamInput::default()));+ // Created before the reader so it can report the host requests it releases+ // on the same channel as the run's events: the printer then orders those+ // records before the final result, which it prints only once every sender+ // (the reader's included) has dropped.+ let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();let reader = input.as_ref().map(|input| {spawn_input_reader(Arc::clone(input),Arc::clone(&permission_requests),Arc::clone(&args.host_tool_requests),+ tx.clone(),format,)});let client = input.clone();let host_tool_requests = Arc::clone(&args.host_tool_requests);- let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();// The report is folded in both formats from the same stream the printer// reads, so the JSON envelope can never disagree with the text output.let printer = tokio::spawn(async move {@@ -2064,7 +2083,17 @@ async fn run_agent_loop(// would park forever.if let StreamEvent::ToolRequest { request_id, .. } = &ev {if !duplex {- crate::core::agent::host_tools::strand(&host_tool_requests, request_id).await;+ // The request is already on stdout, so its withdrawal is+ // too; printed here because this task is the stream's order.+ if crate::core::agent::host_tools::strand(&host_tool_requests, request_id)+ .await+ {+ let cancelled = request_cancelled(request_id, CANCEL_CLIENT_GONE);+ report.observe(&cancelled);+ if format.is_stream_json() {+ print_json_line(&cancelled);+ }+ }continue;}}@@ -2095,6 +2124,12 @@ async fn run_agent_loop(if let Some(reader) = reader {reader.abort();}+ // A request still registered now belongs to a call the run dropped (it+ // failed or stopped mid-batch); nothing will await its answer, so the host+ // is told to stop working on it before the result record closes the stream.+ for id in crate::core::agent::host_tools::cancel_all(&args.host_tool_requests).await {+ let _ = tx.send(request_cancelled(&id, CANCEL_ABORTED));+ }let aborted = outcome.is_none();let result = outcome.unwrap_or_else(|| Err(ABORTED_BY_CLIENT.to_string()));drop(tx);@@ -2272,6 +2307,14 @@ async fn run_steered(let outcome = tokio::select! {result = run_orchestration_steered(tx, body, args, Some(&steering_tx)) => Some(result),_ = input.aborted() => {+ // A host still holding a request must be told to drop it: the run+ // it would answer is gone. Released here, not by the reader, so+ // the records land before `done` and cannot race the reader's+ // shutdown; `cancel_all` rather than `strand_all` so a child still+ // awaiting one is told it was cancelled, not that the host left.+ for id in crate::core::agent::host_tools::cancel_all(&args.host_tool_requests).await {+ let _ = tx.send(request_cancelled(&id, CANCEL_ABORTED));+ }// The loop emits its own terminal event; an abort pre-empts it, so// the report is given one here or it would read as a clean stop.let _ = tx.send(StreamEvent::Done {@@ -2285,6 +2328,18 @@ async fn run_steered(outcome}+/// `tool_request_cancelled` reasons this surface raises: the client stopped the+/// run, or it can no longer answer (stdin closed).+const CANCEL_ABORTED: &str = "aborted";+const CANCEL_CLIENT_GONE: &str = "client_gone";++fn request_cancelled(request_id: &str, reason: &str) -> StreamEvent {+ StreamEvent::ToolRequestCancelled {+ request_id: request_id.to_string(),+ reason: reason.to_string(),+ }+}+/// What a client line asks the reader to do next.#[derive(Debug, PartialEq, Eq)]enum InputFlow {@@ -2437,18 +2492,24 @@ fn read_bounded_line<R: std::io::BufRead>(/// only thing that can answer a permission request or run a host tool, though,/// so the exit is latched and anything already waiting is released -- see/// [`strand_pending_permissions`] and-/// [`crate::core::agent::host_tools::strand_all`].+/// [`crate::core::agent::host_tools::strand_all`]. Each released host request+/// is reported on `events` as `tool_request_cancelled`.+///+/// An `abort` leaves the host requests alone: the run's abort path withdraws+/// them itself, as `aborted` rather than `client_gone`.async fn read_input_lines(mut lines: mpsc::UnboundedReceiver<ClientLine>,input: Arc<StreamInput>,registry: PermissionRegistry,host_tools: crate::core::agent::host_tools::HostToolRegistry,+ events: mpsc::UnboundedSender<StreamEvent>,format: OutputFormat,) {let targets = InputTargets {permissions: ®istry,host_tools: &host_tools,};+ let mut aborted = false;while let Some(line) = lines.recv().await {if line.oversized {report_input_error(@@ -2469,7 +2530,10 @@ async fn read_input_lines(print_json_line(&PermissionDecisionRecord::new(&request_id, decision));}}- Ok(InputFlow::Stop) => break,+ Ok(InputFlow::Stop) => {+ aborted = true;+ break;+ }Err(message) => report_input_error(format, &message, &line),}}@@ -2477,9 +2541,14 @@ async fn read_input_lines(// otherwise be recorded as the client's to answer and find no reader.input.mark_client_gone();strand_pending_permissions(®istry, format).await;+ if aborted {+ return;+ }// A host tool call cannot be answered by anyone else, so a parked turn is// released with a typed failure rather than waiting on a dead pipe.- crate::core::agent::host_tools::strand_all(&host_tools).await;+ for id in crate::core::agent::host_tools::strand_all(&host_tools).await {+ let _ = events.send(request_cancelled(&id, CANCEL_CLIENT_GONE));+ }}/// Name the follow-ups the run ended before reaching. Queued turns are joined@@ -2521,6 +2590,7 @@ fn spawn_input_reader(input: Arc<StreamInput>,registry: PermissionRegistry,host_tools: crate::core::agent::host_tools::HostToolRegistry,+ events: mpsc::UnboundedSender<StreamEvent>,format: OutputFormat,) -> tokio::task::JoinHandle<()> {tokio::spawn(read_input_lines(@@ -2528,6 +2598,7 @@ fn spawn_input_reader(input,registry,host_tools,+ events,format,))}@@ -2802,6 +2873,11 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry, duplex: boo"\x1b[33m[host tool] '{tool_name}' - awaiting '{request_id}' on stdin\x1b[0m");}+ StreamEvent::ToolRequestCancelled { request_id, reason } => {+ eprintln!("\x1b[2m[host tool] '{request_id}' cancelled ({reason})\x1b[0m");+ }+ // Structured data for a host's own display; text output has none.+ StreamEvent::ToolDetails { .. } => {}}}@@ -2875,6 +2951,7 @@ mod tests {Arc::clone(&input),Arc::clone(®istry),crate::core::agent::host_tools::new_registry(),+ mpsc::unbounded_channel().0,OutputFormat::Json,).await;@@ -2946,6 +3023,8 @@ mod tests {answer.await.expect("the run's tool wait is answered"),Ok(crate::core::agent::host_tools::HostToolResult {content: "moved".to_string(),+ parts: None,+ details: None,is_error: false,}));@@ -2976,6 +3055,7 @@ mod tests {Arc::clone(&input),Arc::clone(®istry),crate::core::agent::host_tools::new_registry(),+ mpsc::unbounded_channel().0,OutputFormat::StreamJson,).await;@@ -2999,15 +3079,17 @@ mod tests {let input = Arc::new(StreamInput::default());let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));let host_tools = crate::core::agent::host_tools::new_registry();- let (_id, answer) = crate::core::agent::host_tools::register(&host_tools).await;+ let (id, answer) = crate::core::agent::host_tools::register(&host_tools).await;let (lines_tx, lines) = mpsc::unbounded_channel::<ClientLine>();drop(lines_tx);+ let (events_tx, mut events) = mpsc::unbounded_channel();read_input_lines(lines,Arc::clone(&input),Arc::clone(®istry),Arc::clone(&host_tools),+ events_tx,OutputFormat::StreamJson,).await;@@ -3017,6 +3099,100 @@ mod tests {Err(crate::core::agent::host_tools::HostToolError::ClientGone));assert!(host_tools.lock().await.is_empty());+ // The host is told, on the run's own stream, which request it lost.+ assert_eq!(+ serde_json::to_value(events.recv().await.expect("a record")).unwrap(),+ serde_json::json!({+ "type": "tool_request_cancelled",+ "request_id": id,+ "reason": "client_gone"+ })+ );+ assert!(events.recv().await.is_none(), "one record per released request");+ }++ /// An `abort` stops the reader but leaves host requests to the run's abort+ /// path, which withdraws them as `aborted`; releasing them here as well+ /// would report the same request twice under two reasons.+ #[tokio::test]+ async fn an_abort_leaves_host_requests_to_the_run() {+ let input = Arc::new(StreamInput::default());+ let host_tools = crate::core::agent::host_tools::new_registry();+ let (id, _answer) = crate::core::agent::host_tools::register(&host_tools).await;+ let (lines_tx, lines) = mpsc::unbounded_channel();+ lines_tx+ .send(ClientLine {+ text: r#"{"type":"abort"}"#.to_string(),+ oversized: false,+ })+ .expect("reader is alive");+ drop(lines_tx);+ let (events_tx, mut events) = mpsc::unbounded_channel();+ read_input_lines(+ lines,+ Arc::clone(&input),+ Arc::new(Mutex::new(HashMap::new())),+ Arc::clone(&host_tools),+ events_tx,+ OutputFormat::StreamJson,+ )+ .await;+ assert!(events.recv().await.is_none());+ assert!(host_tools.lock().await.contains_key(&id));+ // What the abort path then does: the host is told, and a reply the+ // host was already writing is refused as no longer pending.+ let released = crate::core::agent::host_tools::cancel_all(&host_tools).await;+ assert_eq!(released, vec![id.clone()]);+ let late = format!(r#"{{"type":"tool_result","request_id":"{id}","content":"late"}}"#);+ let targets = InputTargets {+ permissions: &Arc::new(Mutex::new(HashMap::new())),+ host_tools: &host_tools,+ };+ let err = apply_input_line(&late, &input, &targets)+ .await+ .expect_err("nothing pending");+ assert!(err.contains("is pending (answered, cancelled, or never issued)"), "{err}");+ }++ /// An over-cap tool result is refused as a line, and the request is still+ /// pending: the host can shrink the image and answer again.+ #[tokio::test]+ async fn an_over_cap_tool_result_leaves_the_request_pending() {+ let input = StreamInput::default();+ let host_tools = crate::core::agent::host_tools::new_registry();+ let (id, answer) = crate::core::agent::host_tools::register(&host_tools).await;+ let permissions: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let targets = InputTargets {+ permissions: &permissions,+ host_tools: &host_tools,+ };+ let big = "A".repeat((stream_input::MAX_IMAGE_BYTES + 3) / 3 * 4);+ let line = serde_json::json!({+ "type": "tool_result",+ "request_id": id,+ "content": [{ "type": "image_url",+ "image_url": { "url": format!("data:image/png;base64,{big}") } }]+ })+ .to_string();+ let err = apply_input_line(&line, &input, &targets)+ .await+ .expect_err("over the cap");+ assert!(err.contains("byte cap"), "{err}");+ assert!(host_tools.lock().await.contains_key(&id), "still pending");+ let retry = serde_json::json!({+ "type": "tool_result",+ "request_id": id,+ "content": [{ "type": "text", "text": "smaller" }],+ "details": { "retry": 1 }+ })+ .to_string();+ assert_eq!(+ apply_input_line(&retry, &input, &targets).await,+ Ok(InputFlow::Continue)+ );+ let result = answer.await.expect("delivered").expect("answered");+ assert_eq!(result.content, "smaller");+ assert_eq!(result.details, Some(serde_json::json!({ "retry": 1 })));}/// The other half of the same wedge, and the sharper half: a request raised@@ -3061,6 +3237,7 @@ mod tests {format,InputFormat::StreamJson,None,+ false,).await.expect_err("the pairing is required");@@ -3096,6 +3273,7 @@ mod tests {Arc::clone(&input),registry,crate::core::agent::host_tools::new_registry(),+ mpsc::unbounded_channel().0,OutputFormat::Json,).await;diff --git a/src-tauri/src/core/cli/rpc.rs b/src-tauri/src/core/cli/rpc.rsindex 9eda4e237..f28ed82b7 100644--- a/src-tauri/src/core/cli/rpc.rs+++ b/src-tauri/src/core/cli/rpc.rs@@ -10,12 +10,14 @@ use tokio::task::JoinHandle;use super::providers::ProviderOverrides;use super::rpc_schema::{- InitializeParams, PermissionResponseParams, SessionIdParams, SessionStartParams,- TurnStartParams, TurnSteerParams,+ InitializeParams, PermissionOwner, PermissionResponseParams, SessionIdParams,+ SessionModelSetParams, SessionStartParams, SessionToolsSetParams, ToolRespondParams,+ ToolResultContent, TurnStartParams, TurnSteerParams,};use super::stream_input::{parse_input_line, MAX_LINE_BYTES};use super::{agent_dir_for, cli_save_thread, prepare_agent_session, AgentSession, SessionFlags};use crate::core::agent::events::{StreamEvent, PROTOCOL_VERSION};+use crate::core::agent::host_tools::{HostToolDecl, HostToolResult, HostToolSet};use crate::core::agent::r#loop::{run_orchestration_steered, SteeringRequest};const OUTPUT_CAPACITY: usize = 1025; // 1024 ordinary records and one reserved terminal outcome.@@ -27,6 +29,9 @@ struct Session {id: String,turns: u32,ephemeral: bool,+ /// `false` restricts every turn to the host tools, through the same+ /// per-request `allowed_tools` allowlist an API caller uses.+ builtins: bool,}struct ActiveTurn {@@ -55,10 +60,141 @@ fn response(id: &Value, result: Value) -> Value {}fn error(id: &Value, code: i32, message: &str) -> Value {- let data = (code == -32001).then(|| json!({"retryable":true}));+ let data = if code == -32001 { json!({"retryable":true}) } else { Value::Null };+ error_data(id, code, message, data)+}++fn error_data(id: &Value, code: i32, message: &str, data: Value) -> Value {json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message,"data":data}})}+/// A verb that would change what the running turn reads (its tools, model or+/// history) is refused rather than applied mid-turn: the turn has already+/// built its request from the old state, so the change would take effect at+/// an arbitrary point in it.+fn turn_active(id: &Value) -> Value {+ error_data(+ id,+ -32001,+ "this session has an active turn; retry after turn/completed",+ json!({"retryable":true,"kind":"turn_active"}),+ )+}++fn invalid_tools(id: &Value, message: &str) -> Value {+ error_data(id, -32602, message, json!({"kind":"invalid_tools"}))+}++const UNKNOWN_SESSION: &str = "unknown sessionId";++/// Parse and declare a host tool set. Entries arrive as raw values so a bad+/// one is reported with its index and reason under `invalid_tools`, not as a+/// generic params error.+fn declare_tools(entries: Vec<Value>) -> Result<HostToolSet, String> {+ let decls = entries+ .into_iter()+ .enumerate()+ .map(|(index, entry)| {+ serde_json::from_value::<HostToolDecl>(entry).map_err(|e| format!("tools[{index}]: {e}"))+ })+ .collect::<Result<Vec<_>, _>>()?;+ HostToolSet::declare(decls).map_err(|e| e.to_string())+}++fn host_names(set: &HostToolSet) -> Vec<String> {+ set.all().iter().map(|tool| tool.qualified_name.clone()).collect()+}++/// What the session's next turn advertises, and the host schemas among it.+/// Filtered to the advertised set the way the stream-json `init` record is:+/// a host tool withheld by a deny list or Plan mode is not echoed, so the+/// host can see the suppression instead of waiting for a call.+async fn tools_view(session: &Session) -> Value {+ let args = &session.agent.args;+ let advertised = crate::core::agent::r#loop::context_advertised_tools(+ &args.mcp_servers,+ &args.mcp_settings,+ &args.permissions,+ args.project_root.as_deref(),+ args.run_mode,+ args.subagents_enabled,+ args.max_parallel_subagents,+ args.ask_requests.is_some(),+ args.todo_registry.is_some(),+ &args.host_tools,+ )+ .await;+ let mut tools: Vec<String> = advertised+ .iter()+ .filter_map(|tool| tool["function"]["name"].as_str().map(str::to_owned))+ .collect();+ if !session.builtins {+ tools.retain(|name| args.host_tools.is_host_tool(name));+ }+ let specs: Vec<Value> = args+ .host_tools+ .schemas()+ .into_iter()+ .filter(|spec| {+ spec["function"]["name"]+ .as_str()+ .is_some_and(|name| tools.iter().any(|t| t == name))+ })+ .collect();+ json!({"tools":tools,"toolSpecs":specs})+}++/// Validate a content-part tool result with the same checks the stream-json+/// `tool_result` uses, returning its text summary.+fn check_result_parts(parts: &[Value]) -> Result<String, String> {+ super::stream_input::check_content_parts(parts, "tool_result")?;+ Ok(super::stream_input::summarize_parts(parts))+}++fn host_result(params: ToolRespondParams) -> Result<(String, HostToolResult), String> {+ let ToolRespondParams { request_id, content, is_error, details } = params;+ let (content, parts) = match content {+ ToolResultContent::Text(text) => (text, None),+ ToolResultContent::Parts(parts) => (check_result_parts(&parts)?, Some(parts)),+ };+ Ok((+ request_id,+ HostToolResult { content, parts, details: details.map(Value::Object), is_error },+ ))+}++/// Release every host request the turn still holds and tell the client which+/// ones it must no longer answer, before the turn's terminal record.+///+/// `client_gone` (stdin closed) is best effort: the client may have stopped+/// reading too, and waiting on it would keep the process alive forever. An+/// interrupt comes from a client that is reading, so its records are owed.+async fn release_host_requests(+ session: Option<&Session>,+ turn: &ActiveTurn,+ reason: &str,+ out: &mpsc::Sender<Value>,+) -> Result<(), String> {+ let Some(session) = session else { return Ok(()) };+ let registry = &session.agent.args.host_tool_requests;+ let released = if reason == "client_gone" {+ crate::core::agent::host_tools::strand_all(registry).await+ } else {+ crate::core::agent::host_tools::cancel_all(registry).await+ };+ for request_id in released {+ let event = StreamEvent::ToolRequestCancelled { request_id, reason: reason.to_owned() };+ let wire = serde_json::to_value(&event).map_err(|e| e.to_string())?;+ let params = json!({"sessionId":turn.session_id,"turnId":turn.turn_id,"event":wire});+ if reason == "client_gone" {+ let _ = notify(out, "item/tool_request_cancelled", params);+ } else {+ send_reply(out, json!({"jsonrpc":"2.0","method":"item/tool_request_cancelled","params":params})).await?;+ }+ }+ Ok(())+}+fn send(out: &mpsc::Sender<Value>, record: Value) -> Result<(), String> {out.try_send(record).map_err(|_| "RPC output queue is full or closed".to_owned())@@ -158,7 +294,10 @@ fn start_turn(.try_reserve_owned().map_err(|_| "RPC output queue is full; retry after draining notifications".to_owned())?;session.history.push(json!({"role":"user","content":input}));- let body = session.agent.body(json!(session.history));+ let mut body = session.agent.body(json!(session.history));+ if !session.builtins {+ body["allowed_tools"] = json!(host_names(&session.agent.args.host_tools));+ }let args = session.agent.args.clone();let (events, receiver) = mpsc::channel(64);let (steering_tx, mut steering_rx) = mpsc::unbounded_channel::<SteeringRequest>();@@ -212,6 +351,27 @@ fn start_turn(})}+/// A new agent for `source`'s project, on `model` or the one it has, carrying+/// its host tools and gate. History and registry are the caller's to decide.+fn rebuild_agent(source: &Session, model: Option<String>) -> Result<AgentSession, String> {+ let project = source+ .agent+ .args+ .project_root+ .as_deref()+ .ok_or_else(|| "session has no project root".to_owned())?;+ let mut agent = prepare_agent_session(+ &project.to_string_lossy(),+ Some(model.unwrap_or_else(|| source.agent.model.clone())),+ ProviderOverrides::default(),+ SessionFlags { require_model: true, ..Default::default() },+ None,+ )?;+ agent.args.host_tools = source.agent.args.host_tools.clone();+ agent.args.host_owns_gate = source.agent.args.host_owns_gate;+ Ok(agent)+}+fn finish_turn(sessions: &mut HashMap<String, Session>,turn: ActiveTurn,@@ -337,22 +497,106 @@ pub async fn serve() -> Result<(), String> {match serde_json::from_value::<SessionStartParams>(params.clone()) {Err(_) => error(&id, -32602, "session/start requires cwd and supported options"),Ok(start) if !std::path::Path::new(&start.cwd).is_dir() => error(&id, -32602, "cwd is not a directory"),- Ok(start) => match prepare_agent_session(&start.cwd, start.model, ProviderOverrides::default(), SessionFlags { require_model: true, ..Default::default() }, None) {+ // Declared before the session is built: a tool set the+ // host got wrong is refused before anything is spent.+ Ok(start) => match declare_tools(start.tools) {+ Err(message) => invalid_tools(&id, &message),+ Ok(host_tools) => match prepare_agent_session(&start.cwd, start.model, ProviderOverrides::default(), SessionFlags { require_model: true, ..Default::default() }, None) {+ Ok(mut agent) => {+ agent.args.host_tools = host_tools;+ agent.args.host_owns_gate = start.permissions == PermissionOwner::Host;+ let sid = uuid::Uuid::new_v4().to_string();+ let session = Session { agent, history: Vec::new(), id: sid.clone(), turns: 0, ephemeral: start.ephemeral, builtins: start.builtins };+ let mut result = tools_view(&session).await;+ result["sessionId"] = json!(sid);+ result["model"] = json!(session.agent.model);+ sessions.insert(sid.clone(), session);+ response(&id, result)+ }+ Err(message) => error(&id, -32602, &message),+ },+ },+ }+ }+ "session/tools/get" => match serde_json::from_value::<SessionIdParams>(params.clone()) {+ Err(_) => error(&id, -32602, "session/tools/get requires sessionId"),+ Ok(SessionIdParams { session_id: sid }) => match sessions.get(&sid) {+ Some(session) => response(&id, tools_view(session).await),+ None => error(&id, -32602, UNKNOWN_SESSION),+ },+ },+ "session/tools/set" => match serde_json::from_value::<SessionToolsSetParams>(params.clone()) {+ Err(_) => error(&id, -32602, "session/tools/set requires sessionId and tools"),+ Ok(set) if !sessions.contains_key(&set.session_id) => error(&id, -32602, UNKNOWN_SESSION),+ Ok(set) if active.as_ref().is_some_and(|t| t.session_id == set.session_id) => turn_active(&id),+ Ok(set) => match declare_tools(set.tools) {+ Err(message) => invalid_tools(&id, &message),+ Ok(host_tools) => {+ let session = sessions.get_mut(&set.session_id).expect("checked");+ session.agent.args.host_tools = host_tools;+ response(&id, tools_view(session).await)+ }+ },+ },+ "session/model/set" => match serde_json::from_value::<SessionModelSetParams>(params.clone()) {+ Err(_) => error(&id, -32602, "session/model/set requires sessionId and model"),+ Ok(set) if !sessions.contains_key(&set.session_id) => error(&id, -32602, UNKNOWN_SESSION),+ Ok(set) if active.as_ref().is_some_and(|t| t.session_id == set.session_id) => turn_active(&id),+ Ok(set) if set.model.trim().is_empty() => error(&id, -32602, "model must not be empty"),+ Ok(set) => {+ let session = sessions.get_mut(&set.session_id).expect("checked");+ match rebuild_agent(session, Some(set.model)) {Ok(agent) => {- let sid = uuid::Uuid::new_v4().to_string();- sessions.insert(sid.clone(), Session { agent, history: Vec::new(), id: sid.clone(), turns: 0, ephemeral: start.ephemeral });- response(&id, json!({"sessionId":sid}))+ // The same registry: nothing is pending between+ // turns, and keeping it keeps one per session.+ let registry = Arc::clone(&session.agent.args.host_tool_requests);+ session.agent = agent;+ session.agent.args.host_tool_requests = registry;+ response(&id, json!({"model":session.agent.model}))}Err(message) => error(&id, -32602, &message),- },+ }}- }+ },+ "session/reset" => match serde_json::from_value::<SessionIdParams>(params.clone()) {+ Err(_) => error(&id, -32602, "session/reset requires sessionId"),+ Ok(SessionIdParams { session_id: sid }) if !sessions.contains_key(&sid) => error(&id, -32602, UNKNOWN_SESSION),+ Ok(SessionIdParams { session_id: sid }) if active.as_ref().is_some_and(|t| t.session_id == sid) => turn_active(&id),+ Ok(SessionIdParams { session_id: sid }) => {+ let session = sessions.get_mut(&sid).expect("checked");+ session.history.clear();+ response(&id, tools_view(session).await)+ }+ },+ "tool/respond" => match serde_json::from_value::<ToolRespondParams>(params.clone()) {+ Err(_) => error(&id, -32602, "tool/respond requires requestId and content (a string or content parts)"),+ Ok(respond) => match host_result(respond) {+ Err(message) => error(&id, -32602, &message),+ Ok((request_id, result)) => {+ // Only the active turn can be waiting on a host: a+ // reply with no turn running is as late as one for a+ // request that was already answered.+ let registry = active+ .as_ref()+ .and_then(|turn| sessions.get(&turn.session_id))+ .map(|session| Arc::clone(&session.agent.args.host_tool_requests));+ let answered = match registry {+ Some(registry) => crate::core::agent::host_tools::respond(®istry, &request_id, Ok(result)).await,+ None => Err(format!("no host tool request '{request_id}' is pending (answered, cancelled, or never issued)")),+ };+ match answered {+ Ok(()) => response(&id, json!({})),+ Err(message) => error_data(&id, -32602, &message, json!({"kind":"not_pending"})),+ }+ }+ },+ },// Takes no params, so the only shape it accepts is none: an// object, or the omitted-params `null` JSON-RPC allows.// As a list request it is also the one method where a// scalar in place of params is a client bug worth naming."session/list" => match params {- Value::Object(_) | Value::Null => response(&id, json!({"sessions":sessions.values().map(|s| json!({"id":s.id,"model":s.agent.model,"turns":s.turns})).collect::<Vec<_>>()})),+ Value::Object(_) | Value::Null => response(&id, json!({"sessions":sessions.values().map(|s| json!({"id":s.id,"model":s.agent.model,"turns":s.turns,"hostTools":s.agent.args.host_tools.len()})).collect::<Vec<_>>()})),_ => error(&id, -32602, "session/list takes no params"),},"session/resume" => match serde_json::from_value::<SessionIdParams>(params.clone()) {@@ -369,19 +613,15 @@ pub async fn serve() -> Result<(), String> {}Ok(SessionIdParams { session_id: sid }) if sessions.contains_key(&sid) => {let source = sessions.get(&sid).expect("checked");- let project = source.agent.args.project_root.as_deref().ok_or_else(|| "session has no project root".to_owned());- match project.and_then(|project| prepare_agent_session(- &project.to_string_lossy(),- Some(source.agent.model.clone()),- ProviderOverrides::default(),- SessionFlags { require_model: true, ..Default::default() },- None,- )) {+ // A fresh registry (from the rebuild): the fork is its+ // own session, and a reply must never cross into it.+ match rebuild_agent(source, None) {Ok(agent) => {let fork = uuid::Uuid::new_v4().to_string();let history = source.history.clone();let ephemeral = source.ephemeral;- sessions.insert(fork.clone(), Session { agent, history, id: fork.clone(), turns: 0, ephemeral });+ let builtins = source.builtins;+ sessions.insert(fork.clone(), Session { agent, history, id: fork.clone(), turns: 0, ephemeral, builtins });response(&id, json!({"sessionId":fork}))}Err(message) => error(&id, -32602, &message),@@ -447,6 +687,7 @@ pub async fn serve() -> Result<(), String> {if let Some(session) = sessions.get_mut(&sid) {session.agent.permission_requests.lock().await.clear();}+ release_host_requests(sessions.get(&sid), &turn, "interrupted", &out).await?;finish_turn(&mut sessions, turn, Err("interrupted".to_owned()), true)?;response(&id, json!({}))}@@ -515,6 +756,7 @@ pub async fn serve() -> Result<(), String> {}if let Some(turn) = active {turn.runner.abort();+ release_host_requests(sessions.get(&turn.session_id), &turn, "client_gone", &out).await?;// stdin closing is not stdout closing: a client that asked the process// to end but keeps reading still gets the record that says its turn// ended, which is the one thing it cannot infer from the channel@@ -533,6 +775,7 @@ pub async fn serve() -> Result<(), String> {#[cfg(test)]mod tests {use super::*;+ use crate::core::cli::stream_input::{MAX_IMAGES, MAX_IMAGE_BYTES};#[tokio::test]async fn event_forwarder_stops_receiving_when_its_bounded_queue_is_full() {@@ -548,4 +791,89 @@ mod tests {assert!(forward.await.unwrap().unwrap_err().contains("overloaded"));assert!(upstream.send(StreamEvent::Parked).is_err(), "events should stop at the bounded boundary");}++ fn image(decoded: usize) -> Value {+ let payload = "A".repeat(decoded.div_ceil(3) * 4);+ json!({"type":"image_url","image_url":{"url":format!("data:image/png;base64,{payload}")}})+ }++ fn respond_params(content: Value) -> ToolRespondParams {+ serde_json::from_value(json!({"requestId":"host-1","content":content})).expect("parses")+ }++ #[test]+ fn a_text_result_is_the_whole_answer() {+ let (id, result) = host_result(respond_params(json!("moved"))).unwrap();+ assert_eq!(id, "host-1");+ assert_eq!(result, HostToolResult { content: "moved".into(), parts: None, details: None, is_error: false });+ }++ /// Parts pass through verbatim; the text summary is what hooks and the+ /// `tool_result` event see.+ #[test]+ fn a_parts_result_keeps_its_parts_and_summarizes_its_text() {+ let parts = json!([{"type":"text","text":"a"},image(3),{"type":"text","text":"b"}]);+ let params: ToolRespondParams = serde_json::from_value(json!({+ "requestId":"host-1","content":parts,"isError":true,"details":{"k":1}+ })).unwrap();+ let (_, result) = host_result(params).unwrap();+ assert_eq!(result.content, "a\nb");+ assert_eq!(Value::Array(result.parts.unwrap()), parts);+ assert_eq!(result.details, Some(json!({"k":1})));+ assert!(result.is_error);+ }++ #[test]+ fn result_parts_are_held_to_the_user_message_caps() {+ // Unpadded base64 decodes in whole 3-byte groups, so the largest image+ // at the cap is its largest multiple of 3.+ let at_cap = MAX_IMAGE_BYTES / 3 * 3;+ assert!(check_result_parts(&[image(at_cap)]).is_ok());+ assert!(check_result_parts(&[image(at_cap + 3)]).unwrap_err().contains("byte cap"));+ assert!(check_result_parts(&vec![image(3); MAX_IMAGES + 1]).unwrap_err().contains("images"));+ assert!(check_result_parts(&vec![image(at_cap); 3]).unwrap_err().contains("total"));+ assert!(check_result_parts(&[]).is_err());+ assert!(check_result_parts(&[json!({"type":"text","text":" "})]).is_err());+ assert!(check_result_parts(&[json!({"type":"audio"})]).unwrap_err().contains("audio"));+ let bmp = json!({"type":"image_url","image_url":{"url":"data:image/bmp;base64,AA=="}});+ assert!(check_result_parts(&[bmp]).is_err());+ }++ #[test]+ fn content_that_is_neither_text_nor_parts_is_a_params_error() {+ assert!(serde_json::from_value::<ToolRespondParams>(json!({"requestId":"h","content":7})).is_err());+ assert!(serde_json::from_value::<ToolRespondParams>(json!({"requestId":"h"})).is_err());+ }++ #[test]+ fn a_declaration_error_names_the_entry_or_the_rule() {+ let set = declare_tools(vec![json!({"name":"camera","capability":"read"})]).unwrap();+ assert_eq!(host_names(&set), ["host__camera"]);+ assert!(declare_tools(vec![json!({"name":"bash"})]).unwrap_err().contains("reserved"));+ assert!(declare_tools(vec![json!({"name":"a"}), json!(3)]).unwrap_err().starts_with("tools[1]"));+ assert!(declare_tools(Vec::new()).unwrap().is_empty());+ }++ #[test]+ fn session_start_defaults_keep_today_s_behaviour() {+ let start: SessionStartParams = serde_json::from_value(json!({"cwd":"/"})).unwrap();+ assert!(start.tools.is_empty() && start.builtins);+ assert_eq!(start.permissions, PermissionOwner::Jan);+ let host: SessionStartParams = serde_json::from_value(json!({"cwd":"/","permissions":"host","builtins":false})).unwrap();+ assert_eq!(host.permissions, PermissionOwner::Host);+ assert!(!host.builtins);+ assert!(serde_json::from_value::<SessionStartParams>(json!({"cwd":"/","permissions":"nobody"})).is_err());+ }++ #[test]+ fn mutation_refusals_carry_their_kind() {+ let busy = turn_active(&json!(1));+ assert_eq!(busy["error"]["code"], -32001);+ assert_eq!(busy["error"]["data"], json!({"retryable":true,"kind":"turn_active"}));+ let bad = invalid_tools(&json!(1), "x");+ assert_eq!(bad["error"]["data"], json!({"kind":"invalid_tools"}));+ // The plain helper is unchanged: -32001 is retryable, others carry no data.+ assert_eq!(error(&json!(1), -32001, "m")["error"]["data"], json!({"retryable":true}));+ assert!(error(&json!(1), -32602, "m")["error"]["data"].is_null());+ }}diff --git a/src-tauri/src/core/cli/rpc_schema.rs b/src-tauri/src/core/cli/rpc_schema.rsindex 88c40185a..8e1ac3ab6 100644--- a/src-tauri/src/core/cli/rpc_schema.rs+++ b/src-tauri/src/core/cli/rpc_schema.rs@@ -38,6 +38,85 @@ pub struct SessionStartParams {pub model: Option<String>,#[serde(default)]pub ephemeral: bool,+ /// Host tools this session may call. Kept as raw values until declaration+ /// so a malformed entry is reported as `invalid_tools` with the reason,+ /// rather than as a generic params error that names nothing.+ #[serde(default)]+ #[schemars(with = "Vec<HostToolDeclSchema>")]+ pub tools: Vec<serde_json::Value>,+ /// `false` advertises only the host tools: no built-ins, MCP, plugin,+ /// `ask`, `todo`, subagent or monitor tools.+ #[serde(default = "builtins_default")]+ pub builtins: bool,+ #[serde(default)]+ pub permissions: PermissionOwner,+}++fn builtins_default() -> bool {+ true+}++/// Who gates host tool calls. `jan` prompts through `permission_request` the+/// way any opaque tool is prompted; `host` means the host's own callback is+/// the gate, so Jan never asks about a host tool.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum PermissionOwner {+ #[default]+ Jan,+ Host,+}++/// The declaration shape, for the document only: the dispatcher parses the+/// real `HostToolDecl`, which lives outside this module and carries no schema.+#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+pub struct HostToolDeclSchema {+ pub name: String,+ #[serde(default)]+ pub description: String,+ /// JSON Schema for the arguments, advertised to the model verbatim.+ #[serde(default)]+ pub parameters: Option<serde_json::Map<String, serde_json::Value>>,+ #[serde(default)]+ pub capability: Option<crate::core::agent::host_tools::HostCapability>,+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct SessionToolsSetParams {+ pub session_id: String,+ #[schemars(with = "Vec<HostToolDeclSchema>")]+ pub tools: Vec<serde_json::Value>,+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct SessionModelSetParams {+ pub session_id: String,+ pub model: String,+}++/// A host tool's answer: text, or OpenAI content parts (`text` / `image_url`+/// with a base64 `data:` URL) under the same caps as a user message.+#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(untagged)]+pub enum ToolResultContent {+ Text(String),+ Parts(Vec<serde_json::Value>),+}++#[derive(Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct ToolRespondParams {+ pub request_id: String,+ pub content: ToolResultContent,+ #[serde(default)]+ pub is_error: bool,+ /// Host/UI-only data, echoed as `item/tool_details` and never sent to the+ /// model.+ #[serde(default)]+ pub details: Option<serde_json::Map<String, serde_json::Value>>,}#[derive(Serialize, Deserialize, JsonSchema)]@@ -100,7 +179,12 @@ pub fn document() -> serde_json::Value {"turn/start": schemars::schema_for!(TurnStartParams),"turn/steer": schemars::schema_for!(TurnSteerParams),"turn/interrupt": schemars::schema_for!(SessionIdParams),- "permission/respond": schemars::schema_for!(PermissionResponseParams)+ "permission/respond": schemars::schema_for!(PermissionResponseParams),+ "tool/respond": schemars::schema_for!(ToolRespondParams),+ "session/tools/get": schemars::schema_for!(SessionIdParams),+ "session/tools/set": schemars::schema_for!(SessionToolsSetParams),+ "session/model/set": schemars::schema_for!(SessionModelSetParams),+ "session/reset": schemars::schema_for!(SessionIdParams)},"notifications": schemars::schema_for!(RpcNotification),"events": schemars::schema_for!(crate::core::agent::events::StreamEvent)@@ -195,8 +279,13 @@ mod tests {"session/archive","session/fork","session/list",+ "session/model/set",+ "session/reset","session/resume","session/start",+ "session/tools/get",+ "session/tools/set",+ "tool/respond","turn/interrupt","turn/start","turn/steer",diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rsindex 3a48adcff..a10043b22 100644--- a/src-tauri/src/core/cli/run_report.rs+++ b/src-tauri/src/core/cli/run_report.rs@@ -15,7 +15,8 @@//! `tool_output_delta`, `tool_result`, `subagent_start`, `subagent_queued`,//! `subagent_end`, `subagent_plan`, `subagent`, `notice`, `monitors`,//! `parked`, `messages_updated`, `ask_request`, `ask_resolved`, `todo_update`,-//! `turn_usage`, `done`, `error`, `permission_request`, `tool_request`. Four tags are minted by+//! `turn_usage`, `done`, `error`, `permission_request`, `tool_request`,+//! `tool_request_cancelled`, `tool_details`. Four tags are minted by//! the CLI rather than by the loop: `init`, `permission_decision`, `result` and//! `input_error`. `init` is the handshake a client reads before any other record//! (see [`Init`]); `permission_decision` reports how this CLI answered a gated@@ -303,7 +304,8 @@ pub(crate) struct Init {input_content_parts: Option<InputContentParts>,}-/// The caps on a `user` message's content-part array, as `init` advertises them.+/// The caps on a content-part array -- a `user` message's, and a `tool_result`'s,+/// which is held to the same limits -- as `init` advertises them.////// A client that sends an image is sending bytes into a channel with no/// backpressure, so the limits are part of the handshake rather than somethingdiff --git a/src-tauri/src/core/cli/stream_input.rs b/src-tauri/src/core/cli/stream_input.rsindex d392134af..ded78ab47 100644--- a/src-tauri/src/core/cli/stream_input.rs+++ b/src-tauri/src/core/cli/stream_input.rs@@ -26,6 +26,9 @@//! run ([`super::user_message`] holds the shape both paths build). Parts are//! passed through verbatim; the caps below are what a line is measured against//! first, because an unbounded channel is a denial of service on the run.+//! A `tool_result` may answer with the same content-part array, under the same+//! caps, plus a `details` object that is echoed for displays and never sent to+//! the model.use crate::core::agent::host_tools::HostToolResult;use std::collections::VecDeque;@@ -133,15 +136,49 @@ pub(crate) enum InputLine {////// `content` is required even for a failure. A tool message with nothing in/// it tells the model only that something happened, which is worse than a- /// short error.+ /// short error. It is either a string or an OpenAI content-part array+ /// (`text` and `image_url` parts, under the same caps as a `user` message),+ /// so a camera can hand the model a frame.+ ///+ /// `details` is any JSON object the host wants a display to have. It is+ /// never sent to the model: the run echoes it as a `tool_details` record+ /// after the `tool_result`, and that is all.ToolResult {request_id: String,- content: String,+ content: ToolResultContent,#[serde(default)]is_error: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ details: Option<serde_json::Map<String, serde_json::Value>>,},}+/// A `tool_result`'s `content`: a plain string, or a content-part array.+#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]+#[serde(untagged, expecting = "'content' to be a string or a content-part array")]+pub(crate) enum ToolResultContent {+ Text(String),+ Parts(Vec<serde_json::Value>),+}++/// What a text-only reader of a parts result sees: hooks, the `tool_result`+/// event and the `ERROR: ` prefix all work on text, so an image-only answer+/// still needs a line that says something arrived.+const IMAGE_ONLY_SUMMARY: &str = "(image)";++pub(crate) fn summarize_parts(parts: &[serde_json::Value]) -> String {+ let texts: Vec<&str> = parts+ .iter()+ .filter(|p| p.get("type").and_then(|v| v.as_str()) == Some("text"))+ .filter_map(|p| p.get("text").and_then(|v| v.as_str()))+ .collect();+ if texts.is_empty() {+ IMAGE_ONLY_SUMMARY.to_string()+ } else {+ texts.join("\n")+ }+}+/// The decisions a client may answer a `permission_request` with: the wire/// vocabulary, which [`parse_input_line`] maps onto the tool gate's own enum.#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]@@ -187,7 +224,7 @@ pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {Ok(InputMessage::User(text))}(None, Some(parts)) => {- check_user_content(&parts)?;+ check_content_parts(&parts, "user")?;Ok(InputMessage::UserParts(parts))}},@@ -203,23 +240,41 @@ pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {request_id,content,is_error,- } => Ok(InputMessage::ToolResult {- request_id,- result: HostToolResult { content, is_error },- }),+ details,+ } => {+ // Checked before the request is touched: an over-cap answer is+ // refused as a line, and the request stays pending for a retry.+ let (content, parts) = match content {+ ToolResultContent::Text(text) => (text, None),+ ToolResultContent::Parts(parts) => {+ check_content_parts(&parts, "tool_result")?;+ (summarize_parts(&parts), Some(parts))+ }+ };+ Ok(InputMessage::ToolResult {+ request_id,+ result: HostToolResult {+ content,+ parts,+ details: details.map(serde_json::Value::Object),+ is_error,+ },+ })+ }}}-/// Validate a client's content-part array before it is queued.+/// Validate a client's content-part array before it is queued. `label` is the+/// input kind it arrived on (`user`, `tool_result`), for the error text.////// The parts are passed through verbatim afterwards -- the shape is the model's,/// and re-encoding it here would be a second place to get it wrong -- so this is/// where every refusal lives: a part type that is not `text` or `image_url`, a/// part missing the field its type requires, an image type outside/// [`IMAGE_MIME_TYPES`](super::user_message::IMAGE_MIME_TYPES), and each cap.-fn check_user_content(parts: &[serde_json::Value]) -> Result<(), String> {+pub(crate) fn check_content_parts(parts: &[serde_json::Value], label: &str) -> Result<(), String> {if parts.is_empty() {- return Err("'user' content is empty".to_string());+ return Err(format!("'{label}' content is empty"));}let mut images = 0usize;let mut image_bytes = 0usize;@@ -273,7 +328,7 @@ fn check_user_content(parts: &[serde_json::Value]) -> Result<(), String> {}}if !has_text && images == 0 {- return Err("'user' content carries neither text nor an image".to_string());+ return Err(format!("'{label}' content carries neither text nor an image"));}Ok(())}@@ -421,6 +476,8 @@ mod tests {request_id: "host-1".to_string(),result: HostToolResult {content: "3 joints moved".to_string(),+ parts: None,+ details: None,is_error: false,},}@@ -440,12 +497,100 @@ mod tests {request_id: "host-2".to_string(),result: HostToolResult {content: "arm is estopped".to_string(),+ parts: None,+ details: None,is_error: true,},});}+ /// A host answers with parts the way a client sends a `user` image: the+ /// parts are carried verbatim for the model, the text summary is what+ /// text-only readers see, and `details` rides along untouched.+ #[test]+ fn a_tool_result_may_carry_parts_and_details() {+ let line = r#"{"type":"tool_result","request_id":"host-3","content":[+ {"type":"text","text":"front camera"},+ {"type":"image_url","image_url":{"url":"data:image/png;base64,QUJD"}},+ {"type":"text","text":"exposure ok"}+ ],"details":{"exposure":12,"frames":[1,2]}}"#;+ let InputMessage::ToolResult { request_id, result } = parse_input_line(line).expect(line)+ else {+ panic!("expected a tool result");+ };+ assert_eq!(request_id, "host-3");+ assert_eq!(result.content, "front camera\nexposure ok");+ let parts = result.parts.expect("parts carried");+ assert_eq!(parts.len(), 3);+ assert_eq!(parts[1]["image_url"]["url"], "data:image/png;base64,QUJD");+ assert_eq!(+ result.details,+ Some(serde_json::json!({ "exposure": 12, "frames": [1, 2] }))+ );+ assert!(!result.is_error);+ }++ /// An image with no text still leaves hooks and the `tool_result` event+ /// something to show.+ #[test]+ fn an_image_only_tool_result_has_a_placeholder_summary() {+ let line = r#"{"type":"tool_result","request_id":"h","content":[+ {"type":"image_url","image_url":{"url":"data:image/png;base64,QUJD"}}+ ]}"#;+ let InputMessage::ToolResult { result, .. } = parse_input_line(line).expect(line) else {+ panic!("expected a tool result");+ };+ assert_eq!(result.content, IMAGE_ONLY_SUMMARY);+ assert_eq!(result.parts.map(|p| p.len()), Some(1));+ assert_eq!(result.details, None);+ }++ /// The `user` caps apply to a tool result, and the refusal names the kind+ /// it came in on so a host can tell which of its lines was wrong.+ #[test]+ fn tool_result_parts_are_held_to_the_user_caps() {+ let image = |bytes: usize| -> serde_json::Value {+ let payload = "A".repeat(bytes / 3 * 4);+ serde_json::json!({+ "type": "image_url",+ "image_url": { "url": format!("data:image/png;base64,{payload}") }+ })+ };+ let result = |content: serde_json::Value| {+ serde_json::json!({ "type": "tool_result", "request_id": "h", "content": content })+ .to_string()+ };+ let err = parse_input_line(&result(serde_json::json!([image(MAX_IMAGE_BYTES + 3)])))+ .expect_err("over the per-image cap");+ assert!(err.contains("over the 5242880 byte cap"), "{err}");+ let err = parse_input_line(&result(serde_json::json!(vec![image(3); MAX_IMAGES + 1])))+ .expect_err("over the image count");+ assert!(err.contains("more than 8 images"), "{err}");+ for (content, marker) in [+ (serde_json::json!([]), "'tool_result' content is empty"),+ (+ serde_json::json!([{ "type": "text", "text": " " }]),+ "'tool_result' content carries neither text nor an image",+ ),+ (+ serde_json::json!([{ "type": "audio" }]),+ "unsupported content part 'audio'",+ ),+ (serde_json::json!(7), "'content' to be a string or a content-part array"),+ ] {+ let err = parse_input_line(&result(content.clone())).expect_err("refused");+ assert!(err.contains(marker), "{content}: {err} lacks {marker}");+ }+ // `details` is an object or nothing: a bare value has no keys for a+ // display to render, so it is refused rather than wrapped.+ let err = parse_input_line(+ r#"{"type":"tool_result","request_id":"h","content":"x","details":5}"#,+ )+ .expect_err("details must be an object");+ assert!(err.contains("expected a map"), "{err}");+ }+/// The advertised kinds and the accepted ones are one list. A kind the/// parser takes but the handshake never names is a capability no client can/// discover; one it names but cannot parse is a lie a client acts on. Thediff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 9acb61b9e..3173a4e8b 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -5549,7 +5549,9 @@ impl App {// The TUI is that host's opposite number -- there is no peer on// stdin to execute a callback -- so it never declares them and// cannot receive this.- StreamEvent::ToolRequest { .. } => {}+ StreamEvent::ToolRequest { .. }+ | StreamEvent::ToolRequestCancelled { .. }+ | StreamEvent::ToolDetails { .. } => {}// The loop auto-answered a timed-out ask; drop its now-dead prompt.// A user answer clears the queue in `resolve_front_ask` instead, so// this only fires for the timeout path.@@ -25259,6 +25261,8 @@ mod tests {)),host_tools: crate::core::agent::host_tools::HostToolSet::new(),host_tool_requests: crate::core::agent::host_tools::new_registry(),+ host_owns_gate: false,+ host_tool_route: None,ask_requests: None,todo_registry: None,system_prompt_override: None,diff --git a/src-tauri/src/core/mcp/server/tests.rs b/src-tauri/src/core/mcp/server/tests.rsindex 8395ac0d9..478d675ed 100644--- a/src-tauri/src/core/mcp/server/tests.rs+++ b/src-tauri/src/core/mcp/server/tests.rs@@ -125,6 +125,19 @@ async fn unserved_tool_is_refused_without_running() {assert!(!dir.path().join("out.txt").exists());}+/// Host tools execute in the client that declared them for one run; Jan's+/// MCP server serves only built-ins, so a `host__` name is never offered,+/// even with every opt-in on.+#[test]+fn host_tools_are_never_served() {+ let mut opts = options(&PathBuf::from("."));+ opts.served.allow_write = true;+ opts.served.allow_exec = true;+ let server = JanToolServer::new(opts);+ assert!(!tool_names(&server).iter().any(|n| n.starts_with("host__")));+ assert!(!ServedTools::default().is_served("host__observe"));+}+#[tokio::test]async fn unknown_tool_is_refused() {let dir = tempfile::tempdir().expect("tempdir");diff --git a/src-tauri/src/core/server/converters.rs b/src-tauri/src/core/server/converters.rsindex 95a17f4aa..de627ca8e 100644--- a/src-tauri/src/core/server/converters.rs+++ b/src-tauri/src/core/server/converters.rs@@ -219,6 +219,34 @@ fn chatgpt_account_id(token: &str) -> Option<String> {.map(str::to_string)}+/// An image carried by an OpenAI `image_url` content part, in the two forms+/// every native API distinguishes: inline bytes, or a URL the provider fetches.+#[derive(Debug, PartialEq)]+enum ImageSource<'a> {+ Base64 { mime: &'a str, data: &'a str },+ Url(&'a str),+}++/// The images of a chat message `content`, in order. A malformed part is+/// skipped, the same way [`message_text`] skips any part it cannot read.+fn message_images(content: &Value) -> Vec<ImageSource<'_>> {+ let Value::Array(parts) = content else {+ return Vec::new();+ };+ parts+ .iter()+ .filter(|p| p.get("type").and_then(|t| t.as_str()) == Some("image_url"))+ .filter_map(|p| p.get("image_url")?.get("url")?.as_str())+ .filter_map(|url| match url.strip_prefix("data:") {+ Some(rest) => {+ let (mime, data) = rest.split_once(";base64,")?;+ (!mime.is_empty() && !data.is_empty()).then_some(ImageSource::Base64 { mime, data })+ }+ None => Some(ImageSource::Url(url)),+ })+ .collect()+}+/// Extract plain text from a chat message `content` (string or content-part array).fn message_text(content: &Value) -> String {match content {@@ -232,6 +260,24 @@ fn message_text(content: &Value) -> String {}}+/// A content-part array as Responses input items: the text first, then each+/// image. Responses takes a data URL and a remote URL in the same field.+fn responses_parts(content: &Value, images: Vec<ImageSource<'_>>) -> Vec<Value> {+ let text = message_text(content);+ let mut items = Vec::with_capacity(images.len() + 1);+ if !text.is_empty() {+ items.push(json!({"type": "input_text", "text": text}));+ }+ items.extend(images.into_iter().map(|image| {+ let url = match image {+ ImageSource::Base64 { mime, data } => format!("data:{mime};base64,{data}"),+ ImageSource::Url(url) => url.to_string(),+ };+ json!({"type": "input_image", "image_url": url})+ }));+ items+}+impl UpstreamConverter for OpenAIResponsesConverter {fn upstream_path(&self, _body: &Value) -> String {if self.oauth {@@ -274,10 +320,19 @@ impl UpstreamConverter for OpenAIResponsesConverter {"system" | "developer" => instructions.push(message_text(&content)),"tool" => {// Chat tool result -> Responses function_call_output item.+ // An output with images is the item-list form, which+ // is where Responses reads a tool's media; a text-only+ // one stays a string, as before.+ let images = message_images(&content);+ let output = if images.is_empty() {+ json!(message_text(&content))+ } else {+ Value::Array(responses_parts(&content, images))+ };input_items.push(json!({"type": "function_call_output","call_id": msg.get("tool_call_id").cloned().unwrap_or(Value::Null),- "output": message_text(&content),+ "output": output,}));}"assistant" if msg.get("tool_calls").is_some() => {@@ -297,7 +352,15 @@ impl UpstreamConverter for OpenAIResponsesConverter {input_items.push(json!({"role": "assistant", "content": text}));}}- _ => input_items.push(json!({"role": role, "content": message_text(&content)})),+ _ => {+ let images = message_images(&content);+ let content = if images.is_empty() {+ json!(message_text(&content))+ } else {+ Value::Array(responses_parts(&content, images))+ };+ input_items.push(json!({"role": role, "content": content}));+ }}}}@@ -589,6 +652,21 @@ fn convert_gemini_usage(usage: Option<&Value>) -> Value {})}+/// Whether the requested model reads media nested in `functionResponse.parts`,+/// which Gemini added with its 3 series. The name is the only signal the+/// converter has, so an unrecognized name gets the sibling-part form that+/// every Gemini model accepts.+fn gemini_reads_function_response_parts(body: &Value) -> bool {+ let Some(model) = body.get("model").and_then(|m| m.as_str()) else {+ return false;+ };+ let name = model.rsplit('/').next().unwrap_or(model);+ name.strip_prefix("gemini-")+ .and_then(|rest| rest.split(['.', '-']).next())+ .and_then(|major| major.parse::<u32>().ok())+ .is_some_and(|major| major >= 3)+}+impl UpstreamConverter for GoogleGenerateContentConverter {fn upstream_path(&self, body: &Value) -> String {let model = body.get("model").and_then(|m| m.as_str()).unwrap_or("");@@ -664,12 +742,50 @@ impl UpstreamConverter for GoogleGenerateContentConverter {.ok().filter(|v: &Value| v.is_object()).unwrap_or_else(|| json!({"result": text}));- contents.push(json!({- "role": "user",- "parts": [{"functionResponse": {"name": name, "response": response}}]+ let mut function_response = json!({"name": name, "response": response});+ let mut parts: Vec<Value> = Vec::new();+ // `functionResponse.parts` takes inline bytes only, and+ // only Gemini 3+ reads it. Earlier models get the image+ // as a sibling part of the same turn instead, which is+ // the form they accept.+ let images: Vec<Value> = message_images(&content)+ .into_iter()+ .filter_map(|image| match image {+ ImageSource::Base64 { mime, data } => {+ Some(json!({"inlineData": {"mimeType": mime, "data": data}}))+ }+ ImageSource::Url(_) => None,+ })+ .collect();+ let nested = gemini_reads_function_response_parts(body);+ if nested && !images.is_empty() {+ function_response["parts"] = Value::Array(images.clone());+ }+ parts.push(json!({"functionResponse": function_response}));+ if !nested {+ parts.extend(images);+ }+ contents.push(json!({"role": "user", "parts": parts}));+ }+ _ => {+ let mut parts: Vec<Value> = Vec::new();+ let text = message_text(&content);+ let images = message_images(&content);+ if !text.is_empty() || images.is_empty() {+ parts.push(json!({"text": text}));+ }+ parts.extend(images.into_iter().map(|image| match image {+ ImageSource::Base64 { mime, data } => {+ json!({"inlineData": {"mimeType": mime, "data": data}})+ }+ // A URL carries no MIME type; Gemini requires one,+ // and JPEG is the common default for photos.+ ImageSource::Url(url) => json!({"fileData": {+ "mimeType": "image/jpeg", "fileUri": url,+ }}),}));+ contents.push(json!({"role": "user", "parts": parts}));}- _ => contents.push(json!({"role": "user", "parts": [{"text": message_text(&content)}]})),}}}@@ -1004,6 +1120,26 @@ fn anthropic_cache_tokens(usage: Option<&Value>) -> (Option<i64>, Option<i64>) {)}+/// A content-part array as Anthropic blocks: the text first, then each image.+fn anthropic_blocks(content: &Value, images: Vec<ImageSource<'_>>) -> Vec<Value> {+ let text = message_text(content);+ let mut blocks = Vec::with_capacity(images.len() + 1);+ if !text.is_empty() {+ blocks.push(json!({"type": "text", "text": text}));+ }+ blocks.extend(images.into_iter().map(|image| match image {+ ImageSource::Base64 { mime, data } => json!({+ "type": "image",+ "source": {"type": "base64", "media_type": mime, "data": data},+ }),+ ImageSource::Url(url) => json!({+ "type": "image",+ "source": {"type": "url", "url": url},+ }),+ }));+ blocks+}+/// Append `blocks` to the last message when it shares `role`, else start a new/// one. Anthropic rejects consecutive same-role messages, so tool results and/// adjacent turns must be merged.@@ -1126,21 +1262,34 @@ impl UpstreamConverter for AnthropicMessagesConverter {push_merged(&mut messages, "assistant", blocks);}"tool" => {+ // A result with images uses the block-list form of+ // `tool_result.content`, which is where Anthropic reads+ // a tool's media; a text-only one stays a string.+ let images = message_images(&content);+ let result = if images.is_empty() {+ json!(message_text(&content))+ } else {+ Value::Array(anthropic_blocks(&content, images))+ };push_merged(&mut messages,"user",vec![json!({"type": "tool_result","tool_use_id": msg.get("tool_call_id").cloned().unwrap_or(Value::Null),- "content": message_text(&content),+ "content": result,})],);}- _ => push_merged(- &mut messages,- "user",- vec![json!({"type": "text", "text": message_text(&content)})],- ),+ _ => {+ let images = message_images(&content);+ let blocks = if images.is_empty() {+ vec![json!({"type": "text", "text": message_text(&content)})]+ } else {+ anthropic_blocks(&content, images)+ };+ push_merged(&mut messages, "user", blocks);+ }}}}@@ -1465,6 +1614,26 @@ fn convert_usage(usage: Option<&Value>) -> Value {mod tests {use super::*;+ #[test]+ fn message_images_reads_inline_and_remote_images_and_skips_the_rest() {+ let content = json!([+ {"type": "text", "text": "a"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},+ {"type": "image_url", "image_url": {"url": "https://x.test/a.jpg"}},+ {"type": "image_url", "image_url": {"url": "data:image/png,notbase64"}},+ {"type": "image_url"},+ {"type": "input_audio"}+ ]);+ assert_eq!(+ message_images(&content),+ vec![+ ImageSource::Base64 { mime: "image/png", data: "AAAA" },+ ImageSource::Url("https://x.test/a.jpg"),+ ]+ );+ assert!(message_images(&json!("plain")).is_empty());+ }+#[test]fn parses_a_single_event_in_one_chunk() {let mut acc = SseAccumulator::new();@@ -1570,6 +1739,43 @@ mod openai_responses_tests {assert_eq!(out["reasoning"], json!({"effort": "high", "summary": "auto"}));}+ /// A camera frame from a tool, and a pasted image from the user, both+ /// reach Responses in its own item forms; text-only content is unchanged.+ #[test]+ fn request_carries_tool_and_user_images() {+ let body = json!({+ "model": "gpt-5",+ "messages": [+ {"role": "user", "content": [+ {"type": "text", "text": "what is this"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,BBBB"}}+ ]},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": "call_1", "type": "function", "function": {"name": "cam", "arguments": "{}"}}+ ]},+ {"role": "tool", "tool_call_id": "call_1", "content": [+ {"type": "text", "text": "front camera"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+ ]}+ ]+ });+ let input = conv().convert_request(&body)["input"].clone();+ assert_eq!(+ input[0]["content"],+ json!([+ {"type": "input_text", "text": "what is this"},+ {"type": "input_image", "image_url": "data:image/png;base64,BBBB"}+ ])+ );+ assert_eq!(+ input[2]["output"],+ json!([+ {"type": "input_text", "text": "front camera"},+ {"type": "input_image", "image_url": "data:image/png;base64,AAAA"}+ ])+ );+ }+#[test]fn request_flattens_tools_and_maps_tool_messages() {let body = json!({@@ -1881,6 +2087,73 @@ mod google_generate_content_tests {assert_eq!(out["toolConfig"], json!({"functionCallingConfig": {"mode": "ANY"}}));}+ fn image_tool_body(model: &str) -> Value {+ json!({+ "model": model,+ "messages": [+ {"role": "user", "content": [+ {"type": "text", "text": "what is this"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,BBBB"}}+ ]},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": "c1", "type": "function", "function": {"name": "cam", "arguments": "{}"}}+ ]},+ {"role": "tool", "tool_call_id": "c1", "content": [+ {"type": "text", "text": "front camera"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+ ]}+ ]+ })+ }++ #[test]+ fn a_user_image_becomes_inline_data() {+ let out = conv().convert_request(&image_tool_body("gemini-2.5-pro"));+ assert_eq!(+ out["contents"][0]["parts"],+ json!([+ {"text": "what is this"},+ {"inlineData": {"mimeType": "image/png", "data": "BBBB"}}+ ])+ );+ }++ /// Gemini 3 reads a tool's media nested in its `functionResponse`.+ #[test]+ fn a_gemini_3_tool_image_nests_in_the_function_response() {+ let out = conv().convert_request(&image_tool_body("models/gemini-3-flash-preview"));+ let parts = out["contents"][2]["parts"].as_array().unwrap();+ assert_eq!(parts.len(), 1, "{parts:?}");+ assert_eq!(parts[0]["functionResponse"]["name"], json!("cam"));+ assert_eq!(parts[0]["functionResponse"]["response"], json!({"result": "front camera"}));+ assert_eq!(+ parts[0]["functionResponse"]["parts"],+ json!([{"inlineData": {"mimeType": "image/png", "data": "AAAA"}}])+ );+ }++ /// Earlier models ignore nested parts, so the image rides beside the+ /// response in the same turn.+ #[test]+ fn an_older_gemini_tool_image_is_a_sibling_part() {+ let out = conv().convert_request(&image_tool_body("gemini-2.5-pro"));+ let parts = out["contents"][2]["parts"].as_array().unwrap();+ assert!(parts[0]["functionResponse"].get("parts").is_none(), "{parts:?}");+ assert_eq!(parts[1], json!({"inlineData": {"mimeType": "image/png", "data": "AAAA"}}));+ }++ #[test]+ fn gemini_generation_is_read_from_the_model_name() {+ let reads = |m: &str| gemini_reads_function_response_parts(&json!({"model": m}));+ assert!(reads("gemini-3-pro"));+ assert!(reads("gemini-3.1-flash"));+ assert!(reads("models/gemini-3.8-flash"));+ assert!(!reads("gemini-2.5-pro"));+ assert!(!reads("gemini-1.5-flash"));+ assert!(!reads("gemma-3-27b"));+ assert!(!reads("some-alias"));+ }+#[test]fn tool_result_wraps_non_json_content() {let body = json!({@@ -2116,6 +2389,58 @@ mod anthropic_messages_tests {assert_eq!(sys[1]["cache_control"], json!({"type": "ephemeral"}));}+ /// The reviewer's probe, inverted: a tool's image lands inside its+ /// `tool_result`, a user image as an `image` block, and the tool and user+ /// turns still coalesce into one user message.+ #[test]+ fn request_carries_tool_and_user_images() {+ let body = json!({+ "model": "claude-sonnet-4",+ "messages": [+ {"role": "user", "content": "go"},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": "call_1", "type": "function", "function": {"name": "host__camera", "arguments": "{}"}}+ ]},+ {"role": "tool", "tool_call_id": "call_1", "content": [+ {"type": "text", "text": "front camera"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+ ]},+ {"role": "user", "content": [+ {"type": "text", "text": "what is this"},+ {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,BBBB"}}+ ]}+ ]+ });+ let msgs = conv().convert_request(&body)["messages"].clone();+ assert_eq!(msgs.as_array().unwrap().len(), 3, "{msgs}");+ assert_eq!(+ msgs[2]["content"],+ json!([+ {"type": "tool_result", "tool_use_id": "call_1", "content": [+ {"type": "text", "text": "front camera"},+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}}+ ]},+ {"type": "text", "text": "what is this"},+ {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "BBBB"}}+ ])+ );+ }++ #[test]+ fn a_remote_image_is_a_url_source() {+ let body = json!({+ "model": "claude-sonnet-4",+ "messages": [{"role": "user", "content": [+ {"type": "image_url", "image_url": {"url": "https://x.test/a.jpg"}}+ ]}]+ });+ let msgs = conv().convert_request(&body)["messages"].clone();+ assert_eq!(+ msgs[0]["content"],+ json!([{"type": "image", "source": {"type": "url", "url": "https://x.test/a.jpg"}}])+ );+ }+#[test]fn request_merges_consecutive_tool_results_into_one_user_message() {let body = json!({