Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): commit the rpc schema artifact and check it for drift
thinhlpgbbe3f3e3649c
diff --git a/.github/workflows/rust-check.yml b/.github/workflows/rust-check.ymlindex d8d8bf59a..2b1048f64 100644--- a/.github/workflows/rust-check.yml+++ b/.github/workflows/rust-check.yml@@ -150,21 +150,30 @@ jobs:cargo run --quiet --locked --no-default-features --features cli \--bin jan -- cli agent schema --out ../../protocol/schema.json+ # The RPC artifact is the same kind of file for the other surface, and its+ # guard lives in this job rather than its own: one build, one cache, and+ # the two documents are regenerated by the same binary.+ - name: Regenerate the RPC schema+ run: |+ cd src-tauri/jan-cli+ cargo run --quiet --locked --no-default-features --features cli \+ --bin jan -- cli agent rpc-schema --out ../../protocol/rpc-schema.json+- name: Fail on driftrun: |- if git diff --exit-code -- protocol/schema.json; then- echo "protocol/schema.json matches the types"+ if git diff --exit-code -- protocol/schema.json protocol/rpc-schema.json; then+ echo "protocol/schema.json and protocol/rpc-schema.json match the types"exit 0fi- echo "::error title=protocol drift::protocol/schema.json no longer matches the protocol types"+ echo "::error title=protocol drift::a committed protocol schema no longer matches its types"{echo "## protocol drift"echoecho '```diff'- git diff -- protocol/schema.json+ git diff -- protocol/schema.json protocol/rpc-schema.jsonecho '```'echo- echo 'Run `make protocol-schema` and commit the result.'+ echo 'Run `make protocol-schema` / `make protocol-rpc-schema` and commit the result.'} >> "$GITHUB_STEP_SUMMARY"exit 1diff --git a/Makefile b/Makefileindex 75fb007e8..9496c6da1 100644--- a/Makefile+++ b/Makefile@@ -163,6 +163,13 @@ test-rust: stub-resourcesprotocol-schema:cd src-tauri/jan-cli && cargo run --quiet --locked --no-default-features --features cli --bin jan -- cli agent schema --out ../../protocol/schema.json+# The same guard for the RPC surface: protocol/rpc-schema.json is committed, and+# core::cli::rpc_schema fails when it no longer matches the types that define the+# envelope. It covers this surface only - stream-json records are in+# protocol/schema.json, and ACP has no document yet.+protocol-rpc-schema:+ cd src-tauri/jan-cli && cargo run --quiet --locked --no-default-features --features cli --bin jan -- cli agent rpc-schema --out ../../protocol/rpc-schema.json+test: test-prepare install-rust-targetsyarn build:mlx-server$(MAKE) build-clidiff --git a/protocol/rpc-schema.json b/protocol/rpc-schema.jsonnew file mode 100644index 000000000..f4617b156--- /dev/null+++ b/protocol/rpc-schema.json@@ -0,0 +1,1009 @@+{+ "protocol_version": 1,+ "envelope": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "RpcEnvelope",+ "type": "object",+ "properties": {+ "jsonrpc": {+ "type": "string"+ },+ "id": true,+ "method": {+ "type": "string"+ },+ "params": true+ },+ "required": [+ "jsonrpc",+ "method"+ ]+ },+ "requests": {+ "initialize": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "InitializeParams",+ "type": "object",+ "properties": {+ "protocolVersion": {+ "type": "integer",+ "format": "uint32",+ "minimum": 0+ },+ "clientInfo": {+ "$ref": "#/$defs/ClientInfo"+ },+ "capabilities": {+ "default": null+ }+ },+ "additionalProperties": false,+ "required": [+ "protocolVersion",+ "clientInfo"+ ],+ "$defs": {+ "ClientInfo": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "version": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "name",+ "version"+ ]+ }+ }+ },+ "session/list": {+ "type": "object",+ "properties": {}+ },+ "session/start": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "SessionStartParams",+ "type": "object",+ "properties": {+ "cwd": {+ "type": "string"+ },+ "model": {+ "type": [+ "string",+ "null"+ ]+ },+ "ephemeral": {+ "type": "boolean",+ "default": false+ }+ },+ "additionalProperties": false,+ "required": [+ "cwd"+ ]+ },+ "session/resume": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "SessionIdParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "sessionId"+ ]+ },+ "session/fork": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "SessionIdParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "sessionId"+ ]+ },+ "session/archive": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "SessionIdParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "sessionId"+ ]+ },+ "turn/start": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "TurnStartParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ },+ "input": true+ },+ "additionalProperties": false,+ "required": [+ "sessionId",+ "input"+ ]+ },+ "turn/steer": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "TurnSteerParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ },+ "input": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "sessionId",+ "input"+ ]+ },+ "turn/interrupt": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "SessionIdParams",+ "type": "object",+ "properties": {+ "sessionId": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "sessionId"+ ]+ },+ "permission/respond": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "PermissionResponseParams",+ "type": "object",+ "properties": {+ "requestId": {+ "type": "string"+ },+ "decision": {+ "type": "string"+ }+ },+ "additionalProperties": false,+ "required": [+ "requestId",+ "decision"+ ]+ }+ },+ "notifications": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "RpcNotification",+ "type": "object",+ "properties": {+ "jsonrpc": {+ "type": "string"+ },+ "method": {+ "type": "string"+ },+ "params": true+ },+ "required": [+ "jsonrpc",+ "method",+ "params"+ ]+ },+ "events": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "StreamEvent",+ "description": "`Deserialize` as well as `Serialize`: a consumer validates what it received\nagainst these shapes, and `JsonSchema` is what `jan cli agent schema`\npublishes them as -- a consumer generates its own types from\n`protocol/schema.json` rather than copying this declaration. The wire has to\nsurvive a round trip, not just a write, so `#[serde(tag = \"type\")]` keeps the\ntag on both sides.",+ "oneOf": [+ {+ "description": "A streamed content delta from the model.",+ "type": "object",+ "properties": {+ "text": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "token"+ }+ },+ "required": [+ "type",+ "text"+ ]+ },+ {+ "description": "A streamed reasoning delta, carried natively when the upstream exposes\nit as a dedicated field (`reasoning_content`). Display-only: reasoning\nnever joins the assistant `content` that is resent as history, and it\nmust never leak into piped stdout. Providers that instead inline\n`<think>` tags in `content` stream those through [`Token`]; consumers\nfall back to stripping the tags manually.",+ "type": "object",+ "properties": {+ "text": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "reasoning"+ }+ },+ "required": [+ "type",+ "text"+ ]+ },+ {+ "description": "A new orchestration turn began (`index` is 1-based; `max` is the turn\ncap, `0` when the run is unbounded, which is the normal case).",+ "type": "object",+ "properties": {+ "index": {+ "type": "integer",+ "format": "uint32",+ "minimum": 0+ },+ "max": {+ "type": "integer",+ "format": "uint32",+ "minimum": 0+ },+ "type": {+ "type": "string",+ "const": "step"+ }+ },+ "required": [+ "type",+ "index",+ "max"+ ]+ },+ {+ "description": "A tool call started streaming: emitted mid-stream the instant the model's\ntool-call `id` and `name` are known, before its arguments finish\nstreaming. Lets a consumer show an in-progress indicator during the\n(potentially long) argument-streaming window; the full [`ToolCall`] with\nparsed `args` follows once the completion is assembled.",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "tool_call_started"+ }+ },+ "required": [+ "type",+ "id",+ "name"+ ]+ },+ {+ "description": "A chunk of a tool call's raw JSON arguments, exactly as it arrived on the\nwire. Emitted between [`ToolCallStarted`] and [`ToolCall`] so a consumer\ncan render the arguments as they land -- the difference between a\nfeatureless spinner and a live preview while a large `write` streams.\n\nDeltas, not the accumulated buffer: re-sending the whole prefix on every\nchunk is quadratic in a file-sized argument. Consumers concatenate.\nThe result is *incomplete JSON* until [`ToolCall`] arrives; parse it\nleniently or not at all.",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "delta": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "tool_call_args_delta"+ }+ },+ "required": [+ "type",+ "id",+ "delta"+ ]+ },+ {+ "description": "The model requested a tool call. `args` is the parsed argument object\n(null if the model emitted non-JSON arguments).",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "args": true,+ "type": {+ "type": "string",+ "const": "tool_call"+ }+ },+ "required": [+ "type",+ "id",+ "name",+ "args"+ ]+ },+ {+ "description": "A chunk of a tool's output, as it is produced. Emitted between\n[`ToolCall`] and [`ToolResult`] so a consumer can show a command's output\nwhile it runs instead of only once it exits.\n\nDeltas, not the accumulated buffer, for the same reason as\n[`ToolCallArgsDelta`]: resending the prefix on every chunk is quadratic in\nthe output size. Chunks are raw fragments and may split a line.\n\nKeeps arriving after a `bash` call has backgrounded itself, so a\nlong-running job reports progress under the id of the call that started it.",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "delta": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "tool_output_delta"+ }+ },+ "required": [+ "type",+ "id",+ "delta"+ ]+ },+ {+ "description": "A tool finished. `is_error` reflects the upstream \"ERROR\" encoding.\n`diff` is display-only focused-change text (line-prefixed `-`/`+`) for\n`write`/`edit`; `None` for other tools.",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "content": {+ "type": "string"+ },+ "is_error": {+ "type": "boolean"+ },+ "diff": {+ "type": [+ "string",+ "null"+ ]+ },+ "type": {+ "type": "string",+ "const": "tool_result"+ }+ },+ "required": [+ "type",+ "id",+ "content",+ "is_error"+ ]+ },+ {+ "description": "A backgrounded subagent run began. `run_id` identifies the run so a\nconsumer can attribute concurrent children; brackets the child's wrapped\nevents with `SubagentEnd`.",+ "type": "object",+ "properties": {+ "run_id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "task": {+ "description": "The task the child was dispatched with -- its sole user message.\nCarried on the event rather than left for consumers to correlate\nback to the `dispatch_subagent` call: two dispatches can share a\n`subagent_name`, so matching on name alone is ambiguous.",+ "type": [+ "string",+ "null"+ ]+ },+ "type": {+ "type": "string",+ "const": "subagent_start"+ }+ },+ "required": [+ "type",+ "run_id",+ "name"+ ]+ },+ {+ "description": "A backgrounded subagent dispatch found the parent run's concurrency cap\n(`max_parallel_subagents`) exhausted and queued the child in FIFO order.\n`waiting` is the child's 1-based position in the queue (1 = next to\nstart). The child's `SubagentStart` follows once a slot frees; a queued\nchild aborted at parent teardown is closed by `SubagentEnd` like any\nother.",+ "type": "object",+ "properties": {+ "run_id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "task": {+ "type": [+ "string",+ "null"+ ]+ },+ "waiting": {+ "type": "integer",+ "format": "uint32",+ "minimum": 0+ },+ "type": {+ "type": "string",+ "const": "subagent_queued"+ }+ },+ "required": [+ "type",+ "run_id",+ "name",+ "waiting"+ ]+ },+ {+ "description": "A backgrounded subagent run finished (success or error). Pairs with the\n`SubagentStart` of the same `run_id`.",+ "type": "object",+ "properties": {+ "run_id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "error": {+ "description": "Why the child failed, when it did: the same reason the parent's\n`<SYSTEM>` completion ping carries. Carried on the event because a\nbackground child's answer never reaches a consumer -- only the model\nreads it -- so without this a failed run is indistinguishable from a\nclean one on screen. `None` for a clean finish, and for a child cut\noff at parent teardown, which is not its own failure.",+ "type": [+ "string",+ "null"+ ]+ },+ "type": {+ "type": "string",+ "const": "subagent_end"+ }+ },+ "required": [+ "type",+ "run_id",+ "name"+ ]+ },+ {+ "description": "The later phases of a phased dispatch, named up front so a consumer can\nshow their subagents as WAITING on an earlier phase before they start.\nEach pending subagent is promoted by its own `SubagentStart` (or\n`SubagentQueued`), matched by `name`, which is unique across a plan.\nDisplay-only and never journaled; emitted only by the top-level run\n(children cannot dispatch), so it is never wrapped in `Subagent`.",+ "type": "object",+ "properties": {+ "pending": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/PendingSubagent"+ }+ },+ "type": {+ "type": "string",+ "const": "subagent_plan"+ }+ },+ "required": [+ "type",+ "pending"+ ]+ },+ {+ "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`).",+ "type": "object",+ "properties": {+ "run_id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "event": {+ "$ref": "#"+ },+ "type": {+ "type": "string",+ "const": "subagent"+ }+ },+ "required": [+ "type",+ "run_id",+ "name",+ "event"+ ]+ },+ {+ "description": "The user-facing headline of a background ping the loop just delivered to\nthe model as a `<SYSTEM>` reminder (today: a `monitor` condition\nmatching). Emitted at delivery, not when the ping is queued, so the\ntranscript reads in the order the model saw things. Display-only and\ntransient, like notes: it is never journaled.",+ "type": "object",+ "properties": {+ "text": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "notice"+ }+ },+ "required": [+ "type",+ "text"+ ]+ },+ {+ "description": "The run's active file monitors, as a whole replacing the previous set.\nEmitted whenever the set changes (a `monitor` start or stop, a condition\nmatching, a monitor finishing), so a consumer keeps a live view without\nbookkeeping of its own. Display-only and never journaled. Not forwarded\nfrom a child: a child's monitors are its own.",+ "type": "object",+ "properties": {+ "monitors": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/MonitorSnapshot"+ }+ },+ "type": {+ "type": "string",+ "const": "monitors"+ }+ },+ "required": [+ "type",+ "monitors"+ ]+ },+ {+ "description": "The model has finished its turn and the loop is parked on background\nwork it started (a subagent still running, a monitor still watching).\nNothing is being generated until a ping resumes the run, which the next\n`Step` marks. Lets a consumer say \"watching\" rather than \"working\".",+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "parked"+ }+ },+ "required": [+ "type"+ ]+ },+ {+ "description": "The client should replace its session history with `messages` before\nsubsequent turns. Includes accepted prompt guidance in its original\nposition, but not a pending block from an unsuccessful request. Also\ncarries compacted history when the loop retries a context overflow.",+ "type": "object",+ "properties": {+ "messages": {+ "type": "array",+ "items": true+ },+ "type": {+ "type": "string",+ "const": "messages_updated"+ }+ },+ "required": [+ "type",+ "messages"+ ]+ },+ {+ "description": "The `ask` tool is waiting for structured interactive input. Carries the\n`ask_timeout_secs` deadline (seconds until the loop auto-selects the\nrecommended option) as `timeout_secs`, or `None` when no timeout is\nconfigured. It travels on the event so a client can render a countdown\nwithout re-reading config: the same value both arms the loop's timer and\ndrives the display, keeping the two in agreement.",+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string"+ },+ "request": {+ "$ref": "#/$defs/AskRequest"+ },+ "timeout_secs": {+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 0+ },+ "type": {+ "type": "string",+ "const": "ask_request"+ }+ },+ "required": [+ "type",+ "request_id",+ "request"+ ]+ },+ {+ "description": "An `ask` request the loop resolved without a user answer (it timed out\nand auto-selected). Tells a client showing the live prompt for\n`request_id` to dismiss it, since no `respond` from that client is\ncoming. User-driven answers never emit this: the client clears its own\nprompt as it responds.",+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "ask_resolved"+ }+ },+ "required": [+ "type",+ "request_id"+ ]+ },+ {+ "description": "The canonical todo list changed (tool mutation or user edit in the\nTUI). Carries the full resulting snapshot for reconstruction.",+ "type": "object",+ "properties": {+ "list": {+ "$ref": "#/$defs/TodoList"+ },+ "type": {+ "type": "string",+ "const": "todo_update"+ }+ },+ "required": [+ "type",+ "list"+ ]+ },+ {+ "description": "Token usage for a single upstream request, emitted as soon as that\nrequest completes rather than waiting for the run to finish.\n\n`Done` carries only the *last* request's usage, which is too late and\ntoo little for a live display: a turn that calls tools makes many\nrequests, and a subagent never emits `Done` into the parent stream at\nall. Consumers accumulate these to show context pressure, output\nvolume, and throughput while the work is still happening -- for the\nparent run and, via the [`Subagent`] bracket, for each child.",+ "type": "object",+ "properties": {+ "usage": {+ "$ref": "#/$defs/Usage"+ },+ "execution_id": {+ "description": "The provider's id for the execution that produced this usage, when\nit reported one. This is the handle a per-request billing lookup is\nkeyed by, so a consumer can ask what this one request actually\ncost rather than only what it estimates.\n\nA sibling of `usage` rather than a field inside it, because it is a\nbilling handle and not a token count. Absent on the default upstream\npath, which cannot see the response headers (see\n[`crate::core::agent::correlation`]); that is a limitation to report,\nnot a reason to synthesize one.",+ "type": [+ "string",+ "null"+ ]+ },+ "type": {+ "type": "string",+ "const": "turn_usage"+ }+ },+ "required": [+ "type",+ "usage"+ ]+ },+ {+ "description": "Terminal success: the model returned a final (tool-free) completion.",+ "type": "object",+ "properties": {+ "stop_reason": {+ "type": "string"+ },+ "usage": {+ "anyOf": [+ {+ "$ref": "#/$defs/Usage"+ },+ {+ "type": "null"+ }+ ]+ },+ "type": {+ "type": "string",+ "const": "done"+ }+ },+ "required": [+ "type",+ "stop_reason"+ ]+ },+ {+ "description": "Terminal failure (setup error, upstream/tool failure, or max_turns).",+ "type": "object",+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "const": "error"+ }+ },+ "required": [+ "type",+ "code",+ "message"+ ]+ },+ {+ "description": "The loop needs the user to approve a gated tool call. The client replies via\nthe `agent_permission_respond` command referencing `request_id`.",+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string"+ },+ "tool_name": {+ "type": "string"+ },+ "capability": {+ "type": "string"+ },+ "path": {+ "type": [+ "string",+ "null"+ ]+ },+ "command": {+ "description": "The shell command for exec prompts (drives the command-scoped\n\"allow always\" grant); `None` for non-exec tools.",+ "type": [+ "string",+ "null"+ ]+ },+ "diff": {+ "description": "Focused diff preview for `write`/`edit` prompts so the user sees the\nchange before approving; `None` for other tools.",+ "type": [+ "string",+ "null"+ ]+ },+ "prompt_kind": {+ "type": "string"+ },+ "offers_always": {+ "type": "boolean"+ },+ "type": {+ "type": "string",+ "const": "permission_request"+ }+ },+ "required": [+ "type",+ "request_id",+ "tool_name",+ "capability",+ "prompt_kind",+ "offers_always"+ ]+ }+ ],+ "$defs": {+ "PendingSubagent": {+ "description": "A subagent in a not-yet-started phase of a phased dispatch: its name (unique\nacross the plan, and its blackboard file) and 1-based phase number. Carried by\n[`StreamEvent::SubagentPlan`] so a consumer can show it waiting on the phase\nbefore it.",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "phase": {+ "type": "integer",+ "format": "uint32",+ "minimum": 0+ }+ },+ "required": [+ "name",+ "phase"+ ]+ },+ "MonitorSnapshot": {+ "description": "Display-only view of one active monitor, for a status panel.",+ "type": "object",+ "properties": {+ "monitorId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "script": {+ "type": "string"+ },+ "polls": {+ "type": "integer",+ "format": "uint64",+ "minimum": 0+ }+ },+ "required": [+ "monitorId",+ "name",+ "script",+ "polls"+ ]+ },+ "AskRequest": {+ "type": "object",+ "properties": {+ "questions": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/Question"+ }+ }+ },+ "required": [+ "questions"+ ]+ },+ "Question": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "question": {+ "type": "string"+ },+ "options": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/OptionItem"+ }+ },+ "multi": {+ "type": "boolean",+ "default": false+ },+ "recommended": {+ "type": [+ "integer",+ "null"+ ],+ "format": "uint",+ "minimum": 0,+ "default": null+ }+ },+ "required": [+ "id",+ "question",+ "options"+ ]+ },+ "OptionItem": {+ "type": "object",+ "properties": {+ "label": {+ "type": "string"+ },+ "description": {+ "type": [+ "string",+ "null"+ ],+ "default": null+ }+ },+ "required": [+ "label"+ ]+ },+ "TodoList": {+ "type": "object",+ "properties": {+ "phases": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/TodoPhase"+ }+ }+ },+ "required": [+ "phases"+ ]+ },+ "TodoPhase": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "tasks": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/TodoItem"+ }+ }+ },+ "required": [+ "name",+ "tasks"+ ]+ },+ "TodoItem": {+ "type": "object",+ "properties": {+ "content": {+ "type": "string"+ },+ "status": {+ "$ref": "#/$defs/TodoStatus"+ }+ },+ "required": [+ "content",+ "status"+ ]+ },+ "TodoStatus": {+ "type": "string",+ "enum": [+ "pending",+ "in_progress",+ "completed",+ "abandoned"+ ]+ },+ "Usage": {+ "type": "object",+ "properties": {+ "prompt_tokens": {+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 0+ },+ "completion_tokens": {+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 0+ },+ "total_tokens": {+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 0+ },+ "cached_tokens": {+ "description": "Prompt tokens served from the provider's prompt cache (a read/hit).\nOpenAI reports it under `prompt_tokens_details.cached_tokens`; Anthropic\nunder `cache_read_input_tokens`. A thrashing cache shows here as a low\nvalue against a high `prompt_tokens`.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 0+ },+ "cache_write_tokens": {+ "description": "Prompt tokens written into the provider cache this request (a write).\nOnly Anthropic bills this separately (`cache_creation_input_tokens`);\nabsent for providers that do not distinguish reads from writes.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 0+ }+ }+ }+ }+ }+}diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex c8133dab3..53d42bd62 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -512,8 +512,12 @@ enum AgentCommands {/// Serve addressable sessions over JSON-RPC on stdin/stdoutRpc,/// Print the RPC request and event schemas, generated from the types that- /// define the envelope- RpcSchema,+ /// define the envelope (see `protocol/rpc-schema.json`)+ RpcSchema {+ /// Write to this file instead of stdout+ #[arg(long)]+ out: Option<std::path::PathBuf>,+ },}/// Read/write the user-wide `~/.jan/config.toml` provider store. This is the@@ -1035,11 +1039,9 @@ async fn handle_agent(cmd: AgentCommands) {AgentCommands::Schema { out } => app_lib::core::cli::protocol_schema::run(out.as_deref()),AgentCommands::Rpc => app_lib::core::cli::rpc::serve().await,// Like `schema`: no project root and no provider are involved, so the- // document is the same one on any machine.- AgentCommands::RpcSchema => {- println!("{}", app_lib::core::cli::rpc_schema::document());- Ok(())- }+ // artifact is the same one on any machine. `--out` is what CI and+ // `make protocol-rpc-schema` use.+ AgentCommands::RpcSchema { out } => app_lib::core::cli::rpc_schema::run(out.as_deref()),};if let Err(e) = result {eprintln!("Error: {e}");@@ -1629,7 +1631,8 @@ mod tests {}/// `rpc` and `rpc-schema` are the long-lived session transport and its- /// generated schema: neither involves a project, a provider, or a flag.+ /// generated artifact: neither involves a project or a provider, and+ /// `rpc-schema --out` is the only flag between them.#[test]fn rpc_subcommands_parse() {let cli = Cli::parse_from(["jan", "cli", "agent", "rpc"]);@@ -1643,14 +1646,38 @@ mod tests {));let cli = Cli::parse_from(["jan", "cli", "agent", "rpc-schema"]);- assert!(matches!(- cli.command,- Some(Commands::Cli {- cmd: CliCommands::Agent {- cmd: AgentCommands::RpcSchema- }- })- ));+ let Some(Commands::Cli {+ cmd:+ CliCommands::Agent {+ cmd: AgentCommands::RpcSchema { out },+ },+ }) = cli.command+ else {+ panic!("expected `cli agent rpc-schema`");+ };+ assert_eq!(out, None);++ let cli = Cli::parse_from([+ "jan",+ "cli",+ "agent",+ "rpc-schema",+ "--out",+ "protocol/rpc-schema.json",+ ]);+ let Some(Commands::Cli {+ cmd:+ CliCommands::Agent {+ cmd: AgentCommands::RpcSchema { out },+ },+ }) = cli.command+ else {+ panic!("expected `cli agent rpc-schema --out`");+ };+ assert_eq!(+ out.as_deref(),+ Some(std::path::Path::new("protocol/rpc-schema.json"))+ );}/// Running out of turns while the model is still calling tools is the onediff --git a/src-tauri/src/core/cli/rpc_schema.rs b/src-tauri/src/core/cli/rpc_schema.rsindex c12a8f477..88c40185a 100644--- a/src-tauri/src/core/cli/rpc_schema.rs+++ b/src-tauri/src/core/cli/rpc_schema.rs@@ -1,5 +1,17 @@//! The typed request shapes accepted by the JSON-RPC dispatcher. Schemas are//! derived from the same types that deserialize incoming params.+//!+//! `jan cli agent rpc-schema` prints the document, and `--out` writes the copy+//! committed at `protocol/rpc-schema.json`, which CI regenerates and diffs: an+//! envelope change cannot land without the artifact moving with it. It is the+//! RPC counterpart of `protocol/schema.json`, and covers this surface only -+//! the stream-json records are in that file, and ACP has no document yet.+//!+//! Like that one, the document has to regenerate byte-identically: keys are+//! sorted by `serde_json`, nothing iterates a hash map on the way out, and the+//! order of the `requests` entries is the order written here.+use std::path::Path;+use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -78,6 +90,9 @@ pub fn document() -> serde_json::Value {"envelope": schemars::schema_for!(RpcEnvelope),"requests": {"initialize": schemars::schema_for!(InitializeParams),+ // No params, and the dispatcher reads none: an empty object rather+ // than an omission, so the artifact names every callable method.+ "session/list": serde_json::json!({"type": "object", "properties": {}}),"session/start": schemars::schema_for!(SessionStartParams),"session/resume": schemars::schema_for!(SessionIdParams),"session/fork": schemars::schema_for!(SessionIdParams),@@ -91,3 +106,101 @@ pub fn document() -> serde_json::Value {"events": schemars::schema_for!(crate::core::agent::events::StreamEvent)})}++/// The artifact as text: pretty-printed with a trailing newline, the way+/// `protocol/schema.json` is written, so both files diff the same way.+pub(crate) fn artifact() -> String {+ let mut text = serde_json::to_string_pretty(&document()).expect("a schema prints as JSON");+ text.push('\n');+ text+}++/// Write the artifact to `out`, or print the document when there is no file to+/// write. CI and `make protocol-rpc-schema` pass a path, which also keeps+/// cargo's own build noise off stdout.+pub fn run(out: Option<&Path>) -> Result<(), String> {+ let artifact = artifact();+ match out {+ Some(path) => std::fs::write(path, artifact)+ .map_err(|e| format!("could not write {}: {e}", path.display())),+ None => {+ print!("{artifact}");+ Ok(())+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The committed file, which CI diffs against a fresh generation.+ const COMMITTED: &str = include_str!("../../../../protocol/rpc-schema.json");++ /// The file is committed, so regenerating an unchanged envelope must not+ /// produce a diff: two runs in one process have to agree, which is also what+ /// rules out iteration over a hash map reaching the output.+ #[test]+ fn regenerating_the_schema_is_byte_identical() {+ assert_eq!(artifact(), artifact());+ }++ /// Without this the file is a snapshot that is right on the day it lands.+ #[test]+ fn the_committed_schema_matches_the_types() {+ let generated = artifact();+ if generated == COMMITTED {+ return;+ }+ let first = generated+ .lines()+ .zip(COMMITTED.lines())+ .position(|(a, b)| a != b)+ .unwrap_or(0);+ panic!(+ "protocol/rpc-schema.json no longer matches the RPC types; run \+ `make protocol-rpc-schema` and commit the result.\n\+ first difference at line {}:\n committed: {}\n generated: {}",+ first + 1,+ COMMITTED.lines().nth(first).unwrap_or("<end of file>"),+ generated.lines().nth(first).unwrap_or("<end of file>"),+ );+ }++ /// The verbs in the document are the surface a client may call, one entry+ /// each: a verb the dispatcher answers but the document omits is a client+ /// that cannot generate its call, and a verb the document invents is a+ /// promise nothing keeps. `initialized` is absent because it is a+ /// notification, not a request.+ ///+ /// The list is pinned by hand because the dispatcher is a `match` over+ /// literals rather than a table: a new verb has to change this test too,+ /// which is the point - the surface is a decision, not an accident of the+ /// match arms.+ #[test]+ fn the_document_names_the_request_surface() {+ let document = document();+ let mut documented: Vec<&str> = document["requests"]+ .as_object()+ .expect("the document lists its requests")+ .keys()+ .map(String::as_str)+ .collect();+ documented.sort_unstable();+ assert_eq!(+ documented,+ [+ "initialize",+ "permission/respond",+ "session/archive",+ "session/fork",+ "session/list",+ "session/resume",+ "session/start",+ "turn/interrupt",+ "turn/start",+ "turn/steer",+ ]+ );+ }+}