Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(protocol): generate the protocol schema from the types

thinhlpg82ae405f9c07
diff --git a/.github/workflows/rust-check.yml b/.github/workflows/rust-check.yml
index 080a06a9a..d8d8bf59a 100644
--- a/.github/workflows/rust-check.yml
+++ b/.github/workflows/rust-check.yml
@@ -121,6 +121,53 @@ jobs:
cargo test --locked --manifest-path src-tauri/Cargo.toml \
--no-default-features --features cli --lib -- --test-threads=1
+ # The deliverable of the schema work is this guard, not the file: a protocol
+ # shape that changes without regenerating leaves every consumer validating
+ # against a document that no longer describes the channel. The unit test in
+ # core::cli::protocol_schema compares the types against the file; this runs the
+ # command a human would, in the CLI's own feature set, and prints the diff.
+ schema:
+ name: protocol schema
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
+
+ - uses: dtolnay/rust-toolchain@stable
+
+ - uses: Swatinem/rust-cache@v2
+ with:
+ workspaces: src-tauri
+ key: protocol-schema
+ # Branches restore but never save: one 3.5GB cache set on main
+ # rather than one per branch, which is what breached the 10GB cap.
+ save-if: ${{ github.ref == 'refs/heads/main' }}
+
+ # --locked: the generated document is a function of the locked schemars,
+ # so the only thing that may move it is a commit.
+ - name: Regenerate the protocol schema
+ run: |
+ cd src-tauri/jan-cli
+ cargo run --quiet --locked --no-default-features --features cli \
+ --bin jan -- cli agent schema --out ../../protocol/schema.json
+
+ - name: Fail on drift
+ run: |
+ if git diff --exit-code -- protocol/schema.json; then
+ echo "protocol/schema.json matches the types"
+ exit 0
+ fi
+ echo "::error title=protocol drift::protocol/schema.json no longer matches the protocol types"
+ {
+ echo "## protocol drift"
+ echo
+ echo '```diff'
+ git diff -- protocol/schema.json
+ echo '```'
+ echo
+ echo 'Run `make protocol-schema` and commit the result.'
+ } >> "$GITHUB_STEP_SUMMARY"
+ exit 1
+
# Each plugin and src-tauri/utils is its own workspace, so checking the app
# crate compiles them as path dependencies but never lints them. No --locked
# here: Cargo.lock is gitignored and only some of these crates commit one.
diff --git a/Makefile b/Makefile
index 5bbd3f87c..75fb007e8 100644
--- a/Makefile
+++ b/Makefile
@@ -154,6 +154,15 @@ test-rust: stub-resources
cargo test --locked --manifest-path src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
cargo test --locked --manifest-path src-tauri/utils/Cargo.toml
+# protocol/schema.json is committed, and core::cli::protocol_schema fails when it
+# no longer matches the types that define the channel. This is the fix for that
+# failure, not an optional extra: change a protocol type, run this, commit both.
+# `cd` rather than `--manifest-path` because jan-cli is its own workspace and its
+# .cargo/config.toml is what points the build at src-tauri/target. The feature
+# set matches build-cli, so this does not compile a second configuration.
+protocol-schema:
+ cd src-tauri/jan-cli && cargo run --quiet --locked --no-default-features --features cli --bin jan -- cli agent schema --out ../../protocol/schema.json
+
test: test-prepare install-rust-targets
yarn build:mlx-server
$(MAKE) build-cli
diff --git a/protocol/schema.json b/protocol/schema.json
new file mode 100644
index 000000000..627f0b36d
--- /dev/null
+++ b/protocol/schema.json
@@ -0,0 +1,1119 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "title": "Jan agent protocol v1",
+ "description": "Every record a `jan cli agent run` writes to stdout, and every line a client may write to stdin. The `x-protocol-version` keyword names the contract version this document describes.",
+ "type": "object",
+ "properties": {
+ "output": {
+ "description": "Records a run writes to stdout. The first is `init`, and the last is\n`result`; everything between them is a `StreamEvent` or a\nCLI-minted record.",
+ "$ref": "#/$defs/OutputRecord"
+ },
+ "input": {
+ "description": "Lines a client may write to stdin. What this run accepts is reported by\n`init`'s `input_kinds`, which is empty when the run reads no stdin.",
+ "$ref": "#/$defs/InputLine"
+ }
+ },
+ "required": [
+ "output",
+ "input"
+ ],
+ "$defs": {
+ "OutputRecord": {
+ "description": "Any record a run writes to stdout.",
+ "anyOf": [
+ {
+ "$ref": "#/$defs/StreamEvent"
+ },
+ {
+ "$ref": "#/$defs/Init"
+ },
+ {
+ "$ref": "#/$defs/RunResult"
+ },
+ {
+ "$ref": "#/$defs/PermissionDecisionRecord"
+ },
+ {
+ "$ref": "#/$defs/InputErrorRecord"
+ }
+ ]
+ },
+ "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": "#/$defs/StreamEvent"
+ },
+ "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"
+ },
+ "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"
+ ]
+ }
+ ]
+ },
+ "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
+ }
+ }
+ },
+ "Init": {
+ "description": "The first record of a `--output-format stream-json` channel, and the only\none a client may require before any other.\n\nIt exists because the rest of the stream is unversioned and unaddressable: a\nconsumer sees events and nothing else, so it cannot tell which contract it\nis reading, whose run it is watching, or what it is allowed to send back.\nThose are the questions a handshake answers, and a consumer that has to\ninfer them from a side channel (a CLI flag it passed, a config file it read)\nis one refactor away from being wrong.\n\nField names are snake_case like the rest of this channel -- the event tags\nand the envelope's `session_id`/`stop_reason` set that convention, so the\nhandshake follows it rather than introducing a second one for two fields.\n\nThe compatibility rule for what a client may assume:\n\n- a v1 client may rely on `protocol_version`, `session_id` and `model`\n always being present;\n- fields may be added without a version bump, so a client ignores unknown\n ones and unknown tags rather than failing;\n- a tag is never renamed and never removed within v1;\n- behaviour beyond v1 is asserted against `protocol_version`, not assumed.",
+ "type": "object",
+ "properties": {
+ "type": {
+ "description": "The record's tag. A consumer switches on it, so the schema states the\nvalue rather than leaving it an open string.",
+ "type": "string",
+ "const": "init"
+ },
+ "protocol_version": {
+ "description": "[`PROTOCOL_VERSION`](crate::core::agent::events::PROTOCOL_VERSION) at\nthe time of the run, so a client can refuse a channel it cannot read\ninstead of misreading it.",
+ "type": "integer",
+ "format": "uint32",
+ "minimum": 0
+ },
+ "session_id": {
+ "description": "The thread this run saves under. Minted before the first turn rather\nthan at save time, so a client learns the id from the stream: the same\nid `--resume` takes. A run that produces no completion saves nothing,\nand its terminal envelope reports `session_id: null` -- which is how a\nclient tells this id apart from one that now exists on disk.\n\nThe envelope reports the short form (the first 8 characters) it has\nalways reported; this is the same id, unabbreviated.",
+ "type": "string"
+ },
+ "model": {
+ "description": "The model this run dispatches to, as the envelope reports it.",
+ "type": "string"
+ },
+ "cwd": {
+ "description": "The project root the run's tools are confined to, absolute. `null` for\na caller that built the run's arguments without one -- every CLI run\nresolves a root before the run starts -- so the field never names a\ndirectory that is not the one the tools are confined to.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "tools": {
+ "description": "The tool names this run advertises, in the order the request carries\nthem. Order matters to the consumer: it is the prefix of the request a\nprovider caches on, so a set that reorders between runs is a cache miss\n(see the tool-ordering note in `upstream.rs`).",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "input_kinds": {
+ "description": "What `--input-format stream-json` accepts from this client, as message\n`type` tags. Empty when the run does not read stdin at all, which is\nthe honest answer for a read-only stream: nothing can be sent back.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "type",
+ "protocol_version",
+ "session_id",
+ "model",
+ "tools",
+ "input_kinds"
+ ]
+ },
+ "RunResult": {
+ "description": "The envelope itself. A struct rather than a `json!` literal so the fields\nserialize in declaration order: `serde_json`'s map is sorted, which would\nprint this contract alphabetically and bury `result` in the middle.",
+ "type": "object",
+ "properties": {
+ "type": {
+ "description": "The record's tag. A consumer switches on it, so the schema states the\nvalue rather than leaving it an open string.",
+ "type": "string",
+ "const": "result"
+ },
+ "protocol_version": {
+ "description": "The same contract version `init` carries, so a `--output-format json`\ncaller -- which never sees an init record -- can still pin what it is\nreading. Additive: a consumer that does not know the field ignores it.",
+ "type": "integer",
+ "format": "uint32",
+ "minimum": 0
+ },
+ "is_error": {
+ "type": "boolean"
+ },
+ "result": {
+ "type": "string"
+ },
+ "stop_reason": {
+ "type": "string"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/RunError"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "session_id": {
+ "description": "`null` when nothing was persisted, which is any run that failed before\nproducing a completion: there is no session to resume.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "model": {
+ "type": "string"
+ },
+ "num_turns": {
+ "type": "integer",
+ "format": "uint32",
+ "minimum": 0
+ },
+ "duration_ms": {
+ "type": "integer",
+ "format": "uint64",
+ "minimum": 0
+ },
+ "usage": {
+ "$ref": "#/$defs/ReportUsage"
+ }
+ },
+ "required": [
+ "type",
+ "protocol_version",
+ "is_error",
+ "result",
+ "stop_reason",
+ "model",
+ "num_turns",
+ "duration_ms",
+ "usage"
+ ]
+ },
+ "RunError": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "message"
+ ]
+ },
+ "ReportUsage": {
+ "type": "object",
+ "properties": {
+ "prompt_tokens": {
+ "type": "integer",
+ "format": "uint64",
+ "minimum": 0
+ },
+ "completion_tokens": {
+ "type": "integer",
+ "format": "uint64",
+ "minimum": 0
+ },
+ "total_tokens": {
+ "type": "integer",
+ "format": "uint64",
+ "minimum": 0
+ },
+ "cached_tokens": {
+ "description": "`null` on a route that reports no cache fields at all; `0` when it\nreported zero reads. Piped consumers branch on the difference.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 0
+ },
+ "cache_write_tokens": {
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 0
+ },
+ "estimated_cost_usd": {
+ "type": [
+ "number",
+ "null"
+ ],
+ "format": "double"
+ }
+ },
+ "required": [
+ "prompt_tokens",
+ "completion_tokens",
+ "total_tokens"
+ ]
+ },
+ "PermissionDecisionRecord": {
+ "description": "How the CLI answered a [`StreamEvent::PermissionRequest`]. The loop does not\nemit this: the decision is made here, and without it a piped consumer sees\nthe request and never learns that the run was denied.",
+ "type": "object",
+ "properties": {
+ "type": {
+ "description": "The record's tag. A consumer switches on it, so the schema states the\nvalue rather than leaving it an open string.",
+ "type": "string",
+ "const": "permission_decision"
+ },
+ "request_id": {
+ "type": "string"
+ },
+ "decision": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "request_id",
+ "decision"
+ ]
+ },
+ "InputErrorRecord": {
+ "description": "A rejected input line, reported on stdout. Deliberately *not* a\n[`StreamEvent::Error`](crate::core::agent::events::StreamEvent::Error): the\nreport folds that into the run's outcome, so a typo in one line would mark\nan otherwise successful run as failed.",
+ "type": "object",
+ "properties": {
+ "type": {
+ "description": "The record's tag. A consumer switches on it, so the schema states the\nvalue rather than leaving it an open string.",
+ "type": "string",
+ "const": "input_error"
+ },
+ "message": {
+ "type": "string"
+ },
+ "line": {
+ "description": "The line that was rejected, so the client can match it to what it wrote.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "message",
+ "line"
+ ]
+ },
+ "InputLine": {
+ "description": "One input line, as the wire shape: the three [`INPUT_KINDS`], with the fields\neach carries. The wire shape is a serde type rather than a hand-rolled walk\nover a `Value` so the protocol schema can be derived from it -- `jan cli\nagent schema` publishes this shape, and a hand-written copy of it would be\ncorrect only until the parser moved.\n\nThe `type` field is read separately, before deserializing: an unknown kind is\nreported against [`INPUT_KINDS`], which is the list `init` advertises.",
+ "oneOf": [
+ {
+ "description": "A follow-up turn for the run in flight.",
+ "type": "object",
+ "properties": {
+ "text": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string",
+ "const": "user"
+ }
+ },
+ "required": [
+ "type",
+ "text"
+ ]
+ },
+ {
+ "description": "Stop the run; the terminal envelope still reports what it had produced.",
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "const": "abort"
+ }
+ },
+ "required": [
+ "type"
+ ]
+ },
+ {
+ "description": "The answer to a `permission_request` this run emitted.",
+ "type": "object",
+ "properties": {
+ "request_id": {
+ "type": "string"
+ },
+ "decision": {
+ "$ref": "#/$defs/InputDecision"
+ },
+ "type": {
+ "type": "string",
+ "const": "permission"
+ }
+ },
+ "required": [
+ "type",
+ "request_id",
+ "decision"
+ ]
+ }
+ ]
+ },
+ "InputDecision": {
+ "description": "The decisions a client may answer a `permission_request` with: the wire\nvocabulary, which [`parse_input_line`] maps onto the tool gate's own enum.",
+ "type": "string",
+ "enum": [
+ "allow_once",
+ "allow_always",
+ "deny"
+ ]
+ }
+ },
+ "x-protocol-version": 1
+}
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 113d5d379..8ea0225fb 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -52,6 +52,7 @@ dependencies = [
"reqwest 0.13.4",
"rfd 0.15.4",
"rmcp",
+ "schemars 1.2.1",
"serde",
"serde_json",
"serde_yaml",
@@ -7709,6 +7710,7 @@ dependencies = [
"percent-encoding",
"png 0.17.16",
"regex",
+ "schemars 1.2.1",
"serde",
"serde_json",
"serde_yaml",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index ff9c50175..5446ed9f3 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -108,6 +108,10 @@ serde_json = "1.0"
[dependencies]
dirs = "6.0.0"
+# The protocol types derive JSON Schema from themselves: `jan cli agent schema`
+# is generated, never hand-written, so a consumer validates against the types
+# rather than against a copy of them.
+schemars = "1"
async-trait = "0.1"
env = "1.0.1"
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs", optional = true }
diff --git a/src-tauri/jan-cli/Cargo.lock b/src-tauri/jan-cli/Cargo.lock
index f2d4a8beb..df6946ba9 100644
--- a/src-tauri/jan-cli/Cargo.lock
+++ b/src-tauri/jan-cli/Cargo.lock
@@ -49,6 +49,7 @@ dependencies = [
"reqwest 0.12.28",
"reqwest 0.13.5",
"rmcp",
+ "schemars 1.2.2",
"serde",
"serde_json",
"serde_yaml",
@@ -5115,6 +5116,7 @@ dependencies = [
"percent-encoding",
"png 0.17.16",
"regex",
+ "schemars 1.2.2",
"serde",
"serde_json",
"serde_yaml",
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rs
index d74c77b0b..ec3af6287 100644
--- a/src-tauri/jan-cli/src/main.rs
+++ b/src-tauri/jan-cli/src/main.rs
@@ -448,6 +448,13 @@ enum AgentCommands {
#[command(flatten)]
providers: ProviderArgs,
},
+ /// Print the protocol's JSON Schema, generated from the types that define
+ /// the channel (see `protocol/schema.json`)
+ Schema {
+ /// 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
@@ -946,6 +953,9 @@ async fn handle_agent(cmd: AgentCommands) {
Err(e) => Err(e),
}
}
+ // No project and no provider: the schema comes from the types alone, so
+ // it is the same document on any machine and in any directory.
+ AgentCommands::Schema { out } => app_lib::core::cli::protocol_schema::run(out.as_deref()),
};
if let Err(e) = result {
eprintln!("Error: {e}");
@@ -1421,6 +1431,35 @@ mod tests {
.is_err());
}
+ /// `schema` is the one `cli agent` subcommand with no project and no
+ /// provider: it prints a document derived from the types alone.
+ #[test]
+ fn schema_parses_with_and_without_an_output_path() {
+ let cli = Cli::parse_from(["jan", "cli", "agent", "schema"]);
+ let Some(Commands::Cli {
+ cmd:
+ CliCommands::Agent {
+ cmd: AgentCommands::Schema { out },
+ },
+ }) = cli.command
+ else {
+ panic!("expected `cli agent schema`");
+ };
+ assert_eq!(out, None);
+
+ let cli = Cli::parse_from(["jan", "cli", "agent", "schema", "--out", "protocol/schema.json"]);
+ let Some(Commands::Cli {
+ cmd:
+ CliCommands::Agent {
+ cmd: AgentCommands::Schema { out },
+ },
+ }) = cli.command
+ else {
+ panic!("expected `cli agent schema --out`");
+ };
+ assert_eq!(out.as_deref(), Some(std::path::Path::new("protocol/schema.json")));
+ }
+
#[test]
fn update_command_parses() {
let cli = Cli::parse_from(["jan", "update"]);
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml
index 6fe53c581..c6f9e2276 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml
@@ -50,6 +50,9 @@ glob = "0.3"
percent-encoding = "2"
ignore = "0.4"
regex = "1"
+# `MonitorSnapshot` travels inside a `StreamEvent`, so the protocol schema
+# reaches it: the type derives its own schema rather than being mirrored.
+schemars = "1"
similar = "2.6"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
index 1595c2901..2f3c8d916 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
@@ -115,7 +115,9 @@ pub struct MonitorUpdate {
}
/// Display-only view of one active monitor, for a status panel.
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[derive(
+ Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
+)]
#[serde(rename_all = "camelCase")]
pub struct MonitorSnapshot {
pub monitor_id: String,
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index 4c8e91de3..648c24b41 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -17,10 +17,12 @@
pub const PROTOCOL_VERSION: u32 = 1;
/// `Deserialize` as well as `Serialize`: a consumer validates what it received
-/// against these shapes (and, for a future `jan cli agent schema`, generates its
-/// own types from them), so the wire has to survive a round trip, not just a
-/// write. `#[serde(tag = "type")]` keeps the tag on both sides.
-#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
+/// against these shapes, and `JsonSchema` is what `jan cli agent schema`
+/// publishes them as -- a consumer generates its own types from
+/// `protocol/schema.json` rather than copying this declaration. The wire has to
+/// survive a round trip, not just a write, so `#[serde(tag = "type")]` keeps the
+/// tag on both sides.
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StreamEvent {
/// A streamed content delta from the model.
@@ -223,7 +225,7 @@ pub enum StreamEvent {
/// across the plan, and its blackboard file) and 1-based phase number. Carried by
/// [`StreamEvent::SubagentPlan`] so a consumer can show it waiting on the phase
/// before it.
-#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct PendingSubagent {
pub name: String,
pub phase: u32,
@@ -299,7 +301,7 @@ fn arg_name(args: &serde_json::Value) -> String {
.unwrap_or_default()
}
-#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
+#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct Usage {
pub prompt_tokens: Option<u64>,
pub completion_tokens: Option<u64>,
diff --git a/src-tauri/src/core/agent/interaction.rs b/src-tauri/src/core/agent/interaction.rs
index ae5e60312..ce816f4a5 100644
--- a/src-tauri/src/core/agent/interaction.rs
+++ b/src-tauri/src/core/agent/interaction.rs
@@ -9,12 +9,12 @@ use tokio::sync::{oneshot, Mutex};
const OTHER_LABEL: &str = "Other (type your own)";
static NEXT_ASK_ID: AtomicU64 = AtomicU64::new(1);
-#[derive(Clone, Debug, Deserialize, Serialize)]
+#[derive(Clone, Debug, Deserialize, Serialize, schemars::JsonSchema)]
pub struct AskRequest {
pub(crate) questions: Vec<Question>,
}
-#[derive(Clone, Debug, Deserialize, Serialize)]
+#[derive(Clone, Debug, Deserialize, Serialize, schemars::JsonSchema)]
pub(crate) struct Question {
pub id: String,
pub question: String,
@@ -25,7 +25,7 @@ pub(crate) struct Question {
pub recommended: Option<usize>,
}
-#[derive(Clone, Debug, Deserialize, Serialize)]
+#[derive(Clone, Debug, Deserialize, Serialize, schemars::JsonSchema)]
pub(crate) struct OptionItem {
pub label: String,
#[serde(default)]
diff --git a/src-tauri/src/core/agent/todo.rs b/src-tauri/src/core/agent/todo.rs
index dd38bcfce..47ae316bc 100644
--- a/src-tauri/src/core/agent/todo.rs
+++ b/src-tauri/src/core/agent/todo.rs
@@ -9,7 +9,7 @@ use std::sync::Arc;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TodoStatus {
Pending,
@@ -18,7 +18,7 @@ pub enum TodoStatus {
Abandoned,
}
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct TodoItem {
pub content: String,
pub status: TodoStatus,
@@ -33,7 +33,7 @@ impl TodoItem {
}
}
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct TodoPhase {
pub name: String,
pub tasks: Vec<TodoItem>,
@@ -48,7 +48,7 @@ pub fn new_registry() -> TodoRegistry {
Arc::new(Mutex::new(TodoList::default()))
}
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct TodoList {
pub phases: Vec<TodoPhase>,
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 513cfec95..28cf5b406 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -15,6 +15,8 @@ pub mod mcp_serve;
mod model_capabilities;
pub mod model_catalog;
mod path_refs;
+/// `jan cli agent schema`: the protocol's JSON Schema, generated from the types.
+pub mod protocol_schema;
pub mod run_report;
pub mod providers;
mod secret_input;
diff --git a/src-tauri/src/core/cli/protocol_schema.rs b/src-tauri/src/core/cli/protocol_schema.rs
new file mode 100644
index 000000000..749d3b80f
--- /dev/null
+++ b/src-tauri/src/core/cli/protocol_schema.rs
@@ -0,0 +1,287 @@
+//! The protocol as a JSON Schema document, derived from the types themselves.
+//!
+//! Every consumer of this channel -- the ACP adapter (#347), the SDKs, any
+//! client -- otherwise re-declares what it reads and writes. A re-declaration is
+//! correct until the types move, and nothing says when they did. `jan cli agent
+//! schema` publishes what the types say instead, and the committed copy is
+//! diffed in CI, so a schema-affecting change cannot land without the file
+//! moving with it.
+//!
+//! The document has two root properties:
+//!
+//! - `output`: the records a run writes to stdout, in the order they can appear;
+//! - `input`: the lines a client may write to stdin.
+//!
+//! Determinism is a requirement rather than a nicety: the file is committed and
+//! CI fails on a diff, so regenerating an unchanged protocol has to be
+//! byte-identical. What that rests on:
+//!
+//! - **Order** comes from the declarations. Variants appear in the order the
+//! enums declare them and fields in the order the structs do; object keys are
+//! sorted by `serde_json`, which is also what prints every other JSON artifact
+//! here. Nothing iterates a hash map on the way out, and a test regenerates
+//! twice in one process to say so.
+//! - **Doc comments are part of the document**: `schemars` turns each one into
+//! the `description` of the type, variant or field it documents. Rewording a
+//! comment on a protocol type is a schema change, and the guard treats it as
+//! one -- which is the intended reading, since that prose is what a consumer
+//! reading the schema has instead of the Rust source.
+//! - **The draft** is whatever `schemars` emits, and the document states it in
+//! `$schema` (`draft 2020-12` today). Pinning the string by hand would let the
+//! file claim a draft the generator does not implement; stating what was
+//! generated keeps a draft change a reviewable diff.
+//! - **The generator version** is pinned by the committed `Cargo.lock`
+//! (`src-tauri/Cargo.lock`), and CI regenerates with `--locked`. A `schemars`
+//! update that changes the output therefore shows up as a diff to review
+//! rather than as a silently different document. The failure mode is a noisy
+//! pull request, never a wrong artifact.
+//!
+//! `x-protocol-version` carries [`PROTOCOL_VERSION`]: a consumer pins the
+//! contract it validates against, and a schema for a later version is a
+//! different file, not a silently wider one.
+
+use std::path::Path;
+
+use crate::core::agent::events::{StreamEvent, PROTOCOL_VERSION};
+use crate::core::cli::run_report::{Init, PermissionDecisionRecord, RunResult};
+use crate::core::cli::stream_input::{InputErrorRecord, InputLine};
+
+/// The schema of every record a run may write to stdout: the agent loop's own
+/// stream, plus the four records the CLI mints around it. `untagged` because
+/// this union is not itself on the wire -- each record carries its own `type`.
+// Nothing constructs this union: it exists so the schema can name the set, and
+// each variant's `JsonSchema` impl is what the document uses.
+#[allow(dead_code)]
+#[derive(serde::Serialize, schemars::JsonSchema)]
+#[serde(untagged)]
+#[schemars(description = "Any record a run writes to stdout.")]
+enum OutputRecord<'a> {
+ Event(StreamEvent),
+ Init(Init),
+ Result(RunResult),
+ PermissionDecision(PermissionDecisionRecord<'a>),
+ InputError(InputErrorRecord<'a>),
+}
+
+/// The document's root. A struct rather than an assembled object so each
+/// direction is described by the type that defines it, and so the schema's own
+/// `$defs` name those types.
+// Nothing constructs the root either: the two fields are the document's two
+// properties, and are read by `schema_for!` rather than by code.
+#[allow(dead_code)]
+#[derive(schemars::JsonSchema)]
+#[schemars(
+ title = "Jan agent protocol v1",
+ description = "Every record a `jan cli agent run` writes to stdout, and every line a client may write to stdin. The `x-protocol-version` keyword names the contract version this document describes."
+)]
+struct Protocol<'a> {
+ /// Records a run writes to stdout. The first is `init`, and the last is
+ /// `result`; everything between them is a `StreamEvent` or a
+ /// CLI-minted record.
+ output: OutputRecord<'a>,
+ /// Lines a client may write to stdin. What this run accepts is reported by
+ /// `init`'s `input_kinds`, which is empty when the run reads no stdin.
+ input: InputLine,
+}
+
+/// The document as a JSON value: `schema_for!`'s root, plus the one keyword
+/// schemars does not emit. A custom keyword rather than a `const` on each
+/// record's field: it describes the document as a whole, and draft 2020-12
+/// ignores keywords it does not know.
+fn root() -> serde_json::Value {
+ let mut root = serde_json::to_value(schemars::schema_for!(Protocol<'static>))
+ .expect("a schema serializes to JSON");
+ root.as_object_mut()
+ .expect("schemars' root schema is an object")
+ .insert(
+ "x-protocol-version".to_string(),
+ serde_json::json!(PROTOCOL_VERSION),
+ );
+ root
+}
+
+/// The schema document: pretty-printed JSON with a trailing newline, so it
+/// diffs as text and ends the way every other file in the tree does.
+pub(crate) fn document() -> String {
+ let mut text = serde_json::to_string_pretty(&root()).expect("a schema prints as JSON");
+ text.push('\n');
+ text
+}
+
+/// Write the schema to `out`, or print it when there is no file to write.
+///
+/// `out` is what CI and `make protocol-schema` use, which also keeps cargo's own
+/// build noise off stdout.
+pub fn run(out: Option<&Path>) -> Result<(), String> {
+ let document = document();
+ match out {
+ Some(path) => std::fs::write(path, document)
+ .map_err(|e| format!("could not write {}: {e}", path.display())),
+ None => {
+ print!("{document}");
+ Ok(())
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The committed file, which CI diffs against a fresh generation.
+ const COMMITTED: &str = include_str!("../../../../protocol/schema.json");
+
+ /// The file is committed, so regenerating an unchanged protocol 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!(document(), document());
+ }
+
+ /// The guard the whole issue is about. Without it the file is a snapshot
+ /// that is right on the day it lands.
+ #[test]
+ fn the_committed_schema_matches_the_types() {
+ let generated = document();
+ if generated == COMMITTED {
+ return;
+ }
+ let first = generated
+ .lines()
+ .zip(COMMITTED.lines())
+ .position(|(a, b)| a != b)
+ .unwrap_or(0);
+ panic!(
+ "protocol/schema.json no longer matches the protocol types; run \
+ `make protocol-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 document describes the whole channel and nothing else. A record
+ /// family the document omits is a consumer that cannot validate it; a tag it
+ /// invents is a promise nothing keeps.
+ ///
+ /// Both sides are counted against the sources that already define them: the
+ /// loop against `sample_events`, which the event tests pin to every declared
+ /// variant, and the CLI's own records against instances of those records.
+ #[test]
+ fn the_document_describes_exactly_the_channel() {
+ let json = root();
+ let defs = json["$defs"]
+ .as_object()
+ .expect("derived schemas keep their named types in $defs")
+ .clone();
+
+ // Every record a run can print, tagged: 24 loop events plus the four the
+ // CLI mints around them.
+ let mut documented: Vec<String> = defs["OutputRecord"]["anyOf"]
+ .as_array()
+ .expect("the output union lists its record families")
+ .iter()
+ .flat_map(|branch| {
+ let name = branch["$ref"]
+ .as_str()
+ .and_then(|r| r.strip_prefix("#/$defs/"))
+ .unwrap_or_else(|| panic!("a record family is not a $ref: {branch}"));
+ tagged_consts(&defs[name], name)
+ })
+ .collect();
+ documented.sort();
+ documented.dedup();
+
+ let mut emitted: Vec<String> = crate::core::agent::events::tests::sample_events()
+ .iter()
+ .map(|(name, ev)| {
+ serde_json::to_value(ev).unwrap()["type"]
+ .as_str()
+ .unwrap_or_else(|| panic!("{name} has no tag"))
+ .to_string()
+ })
+ .chain(minted_tags())
+ .collect();
+ emitted.sort();
+
+ assert_eq!(documented, emitted);
+
+ // Input tags come from the same list `init.input_kinds` advertises, so
+ // the document cannot offer a message kind the run refuses.
+ let mut documented: Vec<String> = tagged_consts(&defs["InputLine"], "InputLine");
+ documented.sort();
+ let mut advertised: Vec<String> = crate::core::cli::stream_input::INPUT_KINDS
+ .iter()
+ .map(|k| k.to_string())
+ .collect();
+ advertised.sort();
+ assert_eq!(documented, advertised);
+
+ assert_eq!(
+ json["x-protocol-version"],
+ serde_json::json!(PROTOCOL_VERSION)
+ );
+ }
+
+ /// The four tags the CLI mints around the loop, read off instances of the
+ /// records that mint them rather than off their names.
+ fn minted_tags() -> Vec<String> {
+ use crate::core::cli::run_report::{Init, PermissionDecisionRecord, RunReport};
+ use crate::core::cli::stream_input::InputErrorRecord;
+
+ // The envelope is only ever built by `RunReport::finish`, which is what
+ // `jan cli agent run` prints: its tag comes from there, not from a name.
+ let report = RunReport::default().finish(None, None, "stub-model", 1, None);
+ [
+ serde_json::to_value(Init::new(
+ "session",
+ "stub-model",
+ None,
+ Vec::new(),
+ Vec::new(),
+ ))
+ .unwrap(),
+ serde_json::to_value(report).unwrap(),
+ serde_json::to_value(PermissionDecisionRecord::new(
+ "req",
+ tauri_plugin_agent_tools::tools::gate::PermissionDecision::AllowOnce,
+ ))
+ .unwrap(),
+ serde_json::to_value(InputErrorRecord::new("unknown type 'x'", "{}")).unwrap(),
+ ]
+ .iter()
+ .map(|record| {
+ record["type"]
+ .as_str()
+ .unwrap_or_else(|| panic!("a minted record has no tag: {record}"))
+ .to_string()
+ })
+ .collect()
+ }
+
+ /// Every `"type": {"const": "..."}` in a schema: how a `#[serde(tag =
+ /// "type")]` enum states its variants, and how the CLI's records state the
+ /// tag they are built with. A schema with neither is a shape whose
+ /// discriminator a consumer cannot switch on, so it is an error rather than
+ /// an empty list.
+ fn tagged_consts(schema: &serde_json::Value, what: &str) -> Vec<String> {
+ if let Some(tag) = schema["properties"]["type"]["const"].as_str() {
+ return vec![tag.to_string()];
+ }
+ let branches = schema["oneOf"]
+ .as_array()
+ .or_else(|| schema["anyOf"].as_array())
+ .unwrap_or_else(|| panic!("{what} has no branches and no tag const"));
+ branches
+ .iter()
+ .map(|branch| {
+ branch["properties"]["type"]["const"]
+ .as_str()
+ .unwrap_or_else(|| panic!("a {what} branch has no `type` const: {branch}"))
+ .to_string()
+ })
+ .collect()
+ }
+}
diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rs
index 52f93358b..604629154 100644
--- a/src-tauri/src/core/cli/run_report.rs
+++ b/src-tauri/src/core/cli/run_report.rs
@@ -72,9 +72,12 @@ pub(crate) fn ndjson_line<T: serde::Serialize>(value: &T) -> Option<String> {
/// How the CLI answered a [`StreamEvent::PermissionRequest`]. The loop does not
/// emit this: the decision is made here, and without it a piped consumer sees
/// the request and never learns that the run was denied.
-#[derive(serde::Serialize)]
+#[derive(serde::Serialize, schemars::JsonSchema)]
pub(crate) struct PermissionDecisionRecord<'a> {
+ /// The record's tag. A consumer switches on it, so the schema states the
+ /// value rather than leaving it an open string.
#[serde(rename = "type")]
+ #[schemars(extend("const" = "permission_decision"))]
kind: &'static str,
request_id: &'a str,
decision: &'static str,
@@ -229,9 +232,12 @@ StreamEvent::TurnUsage { usage } => {
/// ones and unknown tags rather than failing;
/// - a tag is never renamed and never removed within v1;
/// - behaviour beyond v1 is asserted against `protocol_version`, not assumed.
-#[derive(serde::Serialize)]
+#[derive(serde::Serialize, schemars::JsonSchema)]
pub(crate) struct Init {
+ /// The record's tag. A consumer switches on it, so the schema states the
+ /// value rather than leaving it an open string.
#[serde(rename = "type")]
+ #[schemars(extend("const" = "init"))]
kind: &'static str,
/// [`PROTOCOL_VERSION`](crate::core::agent::events::PROTOCOL_VERSION) at
/// the time of the run, so a client can refuse a channel it cannot read
@@ -287,9 +293,12 @@ impl Init {
/// The envelope itself. A struct rather than a `json!` literal so the fields
/// serialize in declaration order: `serde_json`'s map is sorted, which would
/// print this contract alphabetically and bury `result` in the middle.
-#[derive(serde::Serialize)]
+#[derive(serde::Serialize, schemars::JsonSchema)]
pub(crate) struct RunResult {
+ /// The record's tag. A consumer switches on it, so the schema states the
+ /// value rather than leaving it an open string.
#[serde(rename = "type")]
+ #[schemars(extend("const" = "result"))]
kind: &'static str,
/// The same contract version `init` carries, so a `--output-format json`
/// caller -- which never sees an init record -- can still pin what it is
@@ -309,13 +318,13 @@ pub(crate) struct RunResult {
usage: ReportUsage,
}
-#[derive(serde::Serialize)]
+#[derive(serde::Serialize, schemars::JsonSchema)]
struct RunError {
code: String,
message: String,
}
-#[derive(serde::Serialize)]
+#[derive(serde::Serialize, schemars::JsonSchema)]
struct ReportUsage {
prompt_tokens: u64,
completion_tokens: u64,
diff --git a/src-tauri/src/core/cli/stream_input.rs b/src-tauri/src/core/cli/stream_input.rs
index a0fcd0600..7781a1172 100644
--- a/src-tauri/src/core/cli/stream_input.rs
+++ b/src-tauri/src/core/cli/stream_input.rs
@@ -61,6 +61,48 @@ pub(crate) enum InputMessage {
},
}
+/// One input line, as the wire shape: the three [`INPUT_KINDS`], with the fields
+/// each carries. The wire shape is a serde type rather than a hand-rolled walk
+/// over a `Value` so the protocol schema can be derived from it -- `jan cli
+/// agent schema` publishes this shape, and a hand-written copy of it would be
+/// correct only until the parser moved.
+///
+/// The `type` field is read separately, before deserializing: an unknown kind is
+/// reported against [`INPUT_KINDS`], which is the list `init` advertises.
+#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub(crate) enum InputLine {
+ /// A follow-up turn for the run in flight.
+ User { text: String },
+ /// Stop the run; the terminal envelope still reports what it had produced.
+ Abort,
+ /// The answer to a `permission_request` this run emitted.
+ Permission {
+ request_id: String,
+ decision: InputDecision,
+ },
+}
+
+/// 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)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum InputDecision {
+ AllowOnce,
+ AllowAlways,
+ Deny,
+}
+
+impl From<InputDecision> for PermissionDecision {
+ fn from(decision: InputDecision) -> Self {
+ match decision {
+ InputDecision::AllowOnce => PermissionDecision::AllowOnce,
+ InputDecision::AllowAlways => PermissionDecision::AllowAlways,
+ InputDecision::Deny => PermissionDecision::Deny,
+ }
+ }
+}
+
/// Parse one NDJSON line. The error is what the client is told on the stream,
/// so it names the offending value rather than just the expected shape.
pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {
@@ -69,46 +111,27 @@ pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {
let Some(kind) = value.get("type").and_then(|v| v.as_str()) else {
return Err("missing string field 'type'".to_string());
};
- match kind {
- "user" => {
- let text = value
- .get("text")
- .and_then(|v| v.as_str())
- .ok_or_else(|| "'user' needs a string field 'text'".to_string())?;
+ if !INPUT_KINDS.contains(&kind) {
+ return Err(format!(
+ "unknown type '{kind}' ({})",
+ INPUT_KINDS.join(", ")
+ ));
+ }
+ match serde_json::from_value::<InputLine>(value).map_err(|e| e.to_string())? {
+ InputLine::User { text } => {
if text.trim().is_empty() {
return Err("'user' text is empty".to_string());
}
- Ok(InputMessage::User(text.to_string()))
+ Ok(InputMessage::User(text))
}
- "abort" => Ok(InputMessage::Abort),
- "permission" => {
- let request_id = value
- .get("request_id")
- .and_then(|v| v.as_str())
- .ok_or_else(|| "'permission' needs a string field 'request_id'".to_string())?;
- let decision = value
- .get("decision")
- .and_then(|v| v.as_str())
- .ok_or_else(|| "'permission' needs a string field 'decision'".to_string())?;
- let decision = match decision {
- "allow_once" => PermissionDecision::AllowOnce,
- "allow_always" => PermissionDecision::AllowAlways,
- "deny" => PermissionDecision::Deny,
- other => {
- return Err(format!(
- "unknown decision '{other}' (allow_once, allow_always, deny)"
- ))
- }
- };
- Ok(InputMessage::Permission {
- request_id: request_id.to_string(),
- decision,
- })
- }
- other => Err(format!(
- "unknown type '{other}' ({})",
- INPUT_KINDS.join(", ")
- )),
+ InputLine::Abort => Ok(InputMessage::Abort),
+ InputLine::Permission {
+ request_id,
+ decision,
+ } => Ok(InputMessage::Permission {
+ request_id,
+ decision: decision.into(),
+ }),
}
}
@@ -116,9 +139,12 @@ pub(crate) fn parse_input_line(line: &str) -> Result<InputMessage, String> {
/// [`StreamEvent::Error`](crate::core::agent::events::StreamEvent::Error): the
/// report folds that into the run's outcome, so a typo in one line would mark
/// an otherwise successful run as failed.
-#[derive(serde::Serialize)]
+#[derive(serde::Serialize, schemars::JsonSchema)]
pub(crate) struct InputErrorRecord<'a> {
+ /// The record's tag. A consumer switches on it, so the schema states the
+ /// value rather than leaving it an open string.
#[serde(rename = "type")]
+ #[schemars(extend("const" = "input_error"))]
kind: &'static str,
message: &'a str,
/// The line that was rejected, so the client can match it to what it wrote.
@@ -250,13 +276,13 @@ mod tests {
("not json at all", "not JSON"),
(r#"{"text":"hi"}"#, "missing string field 'type'"),
(r#"{"type":"steer","text":"hi"}"#, "unknown type 'steer'"),
- (r#"{"type":"user"}"#, "string field 'text'"),
+ (r#"{"type":"user"}"#, "missing field `text`"),
(r#"{"type":"user","text":" "}"#, "is empty"),
- (r#"{"type":"permission","decision":"deny"}"#, "'request_id'"),
- (r#"{"type":"permission","request_id":"p"}"#, "'decision'"),
+ (r#"{"type":"permission","decision":"deny"}"#, "missing field `request_id`"),
+ (r#"{"type":"permission","request_id":"p"}"#, "missing field `decision`"),
(
r#"{"type":"permission","request_id":"p","decision":"maybe"}"#,
- "unknown decision 'maybe'",
+ "unknown variant `maybe`, expected one of `allow_once`, `allow_always`, `deny`",
),
] {
let err = parse_input_line(line).expect_err(line);