Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): experimental `jan acp` Agent Client Protocol server (#9105)
Akarshan Biswas35711e8958f2
diff --git a/.github/workflows/rust-check.yml b/.github/workflows/rust-check.ymlindex 389915b3d..abcba37e7 100644--- a/.github/workflows/rust-check.yml+++ b/.github/workflows/rust-check.yml@@ -128,6 +128,13 @@ jobs:cargo test --locked --manifest-path src-tauri/jan-cli/Cargo.toml \--no-default-features --features cli --test agent_rpc+ # The experimental ACP server (`jan acp`), driven over stdio the way an+ # editor drives it, against a stub provider.+ - name: cargo test (ACP CLI)+ run: |+ cargo test --locked --manifest-path src-tauri/jan-cli/Cargo.toml \+ --no-default-features --features cli --test acp+# The ADK cookbook's runnable source, run with the runner's own# node and python3 against the jan binary this commit builds, plus the# check that every docs excerpt still matches the file it quotes.diff --git a/Makefile b/Makefileindex fd38356d6..2f515bae6 100644--- a/Makefile+++ b/Makefile@@ -166,7 +166,8 @@ protocol-schema:# 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/schema.json, and ACP (`jan acp`) uses the upstream+# ACP schema.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.jsondiff --git a/docs/src/pages/docs/agent/_meta.json b/docs/src/pages/docs/agent/_meta.jsonindex 1c12ff4ae..0dcbc9c58 100644--- a/docs/src/pages/docs/agent/_meta.json+++ b/docs/src/pages/docs/agent/_meta.json@@ -34,6 +34,7 @@"adk-tools": "Host Tools","adk-runtime": "Process & Failures","protocol": "Protocol Records",+ "acp": "Editors (ACP)","reference-separator": { "title": "Reference", "type": "separator" },"cli": "CLI"}diff --git a/docs/src/pages/docs/agent/acp.mdx b/docs/src/pages/docs/agent/acp.mdxnew file mode 100644index 000000000..5a077fda5--- /dev/null+++ b/docs/src/pages/docs/agent/acp.mdx@@ -0,0 +1,125 @@+---+title: Editors (ACP)+description: Drive Jan Agent from Zed, JetBrains and other editors over the Agent Client Protocol with the experimental `jan acp` server.+keywords: [Jan, Jan Agent, ACP, Agent Client Protocol, Zed, JetBrains, editor, IDE, external agent]+---++import { Callout } from 'nextra/components'++# Editors (ACP)++`jan acp` serves Jan Agent over the [Agent Client Protocol](https://agentclientprotocol.com)+(ACP), a JSON-RPC protocol that editors use to run coding agents. Once an editor is pointed at+`jan acp`, you can pick Jan in its agent panel, send prompts, and watch the answer, reasoning,+tool calls and plan stream in. The agent still uses Jan's own providers, tools and permissions.++<Callout type="warning">+`jan acp` is **experimental**. It's off by default, hidden from `jan --help`, and may change+between releases.+</Callout>++## Turn it on++Pick one of these. The environment variable takes precedence over the config file, so+`JAN_EXPERIMENTAL_ACP=0` turns it off again:++```bash+export JAN_EXPERIMENTAL_ACP=1 # per process+```++```toml+# ~/.jan/config.toml # every process+[experimental]+acp = true+```++If you run `jan acp` without turning it on, it prints how to enable it and exits with status 2.+It writes nothing to stdout.++Jan needs a working provider before any editor can use it. Run `jan login`, or+`jan config set --provider <name> --api-key <key> --base-url <url> --model <id>`. The model is+resolved the same way as in the TUI: `agent.toml`, then `default_model` in `~/.jan/config.toml`.++## Zed++Add Jan under `agent_servers` in Zed's `settings.json`:++```json+{+ "agent_servers": {+ "Jan": {+ "type": "custom",+ "command": "jan",+ "args": ["acp"],+ "env": { "JAN_EXPERIMENTAL_ACP": "1" }+ }+ }+}+```++Open the agent panel, start a new thread and choose **Jan**. To see the raw traffic, run+`dev: open acp logs`.++## JetBrains++In **AI Chat**, open the menu and choose **Add Custom Agent**. This opens `~/.jetbrains/acp.json`.+Add Jan there. Use the absolute path to the binary:++```json+{+ "agent_servers": {+ "Jan": {+ "command": "/absolute/path/to/jan",+ "args": ["acp"],+ "env": { "JAN_EXPERIMENTAL_ACP": "1" }+ }+ }+}+```++## What is supported++Jan speaks stable ACP protocol version **1**. It doesn't enable any draft or unstable features.++| ACP | Jan |+| --- | --- |+| `initialize` | Advertises `loadSession`, image and embedded-context prompts. Nothing else is advertised. |+| `authenticate` | Checks that a provider is configured. Clients that can run a terminal get a sign-in method that runs `jan acp --login`. |+| `session/new` | Opens a session in `cwd`, which must be absolute. The session id is a Jan thread id. MCP servers the editor passes over stdio are connected as well as the project's own. |+| `session/load` | Replays a saved thread, including ones started in the TUI or with `jan cli agent run`, then replies. Refused while that session has a prompt running. |+| `session/prompt` | Runs one turn. The reply's `stopReason` is `end_turn`, `max_tokens`, `max_turn_requests` (the session's cost ceiling was reached), `refusal` or `cancelled`. If the run fails, the error is shown in the reply text and the turn ends with `end_turn`. |+| `session/cancel` | Stops the turn. A tool call waiting for your permission never runs. The work done before the cancel is kept, so the next prompt continues from it. |+| `session/request_permission` | Sent for every gated tool call. You get **Allow**, **Always allow** where Jan offers it, and **Reject**. |++The session id is the thread id, so `jan --resume <id>` in the terminal opens a conversation that+you started in the editor.++How Jan's events appear in the editor:++| Jan | ACP `session/update` |+| --- | --- |+| Answer text / reasoning | `agent_message_chunk` / `agent_thought_chunk` |+| Tool call starts, runs, streams output, ends | `tool_call` then `tool_call_update` (`pending`, `in_progress`, `completed`, `failed`) |+| The `todo` list | `plan` |+| Token usage for a turn | `usage_update` |++These have no standard ACP update, so they are left out rather than sent through a made-up+extension: subagent progress (a subagent's permission prompts still reach you), notices,+compaction and retry status, and background monitors. The `ask` tool isn't offered in an ACP+session.++## Permissions++An ACP session always asks before writes, shell commands and MCP tool calls. It's never+auto-approved. It uses the same tool gate and project rules (`[tools]` in `agent.toml`) as the TUI.+If you reject a call, or cancel the prompt, the call is refused just as it would be in the terminal.+**Always allow** covers that tool for the rest of the session.++## Not yet supported++- Jan uses its own filesystem and shell tools. It doesn't read the editor's unsaved buffers or run+ commands in the editor's terminal, so `fs/*` and `terminal/*` are never requested.+- Editor MCP servers over HTTP or SSE are skipped. Only stdio servers are connected, alongside the+ servers set up for the project (see [MCP](/docs/agent/mcp)).+- There's no `session/set_mode` yet, so plan mode and model switching aren't available from the+ editor.diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdxindex 4f0aa5b4c..5655b3614 100644--- a/docs/src/pages/docs/agent/cli.mdx+++ b/docs/src/pages/docs/agent/cli.mdx@@ -508,7 +508,8 @@ byte-identical rather than a diff.Print the RPC surface as a JSON Schema document, generated from the Rust types that deserialize eachrequest. Like `schema`, no project and no provider are involved. It describes this surface only: the-`stream-json` records are in `protocol/schema.json`, and ACP has no document yet.+`stream-json` records are in `protocol/schema.json`, and ACP (`jan acp`) uses the+upstream [ACP schema](https://agentclientprotocol.com) rather than one of its own.```bashjan cli agent rpc-schema # stdout@@ -737,6 +738,20 @@ than blocking. On `http` the listener is loopback-only and every request must caSee [Serving Jan's own tools](/docs/agent/mcp#serving-jans-own-tools).+## `jan acp`++**Experimental.** Serves the agent over the [Agent Client Protocol](https://agentclientprotocol.com)+on stdio, so Zed, JetBrains and other ACP editors can run it. The command is hidden from `--help`+and is off unless you set `JAN_EXPERIMENTAL_ACP=1` or add `[experimental] acp = true` to+`~/.jan/config.toml`. Without either, it exits with status 2.++```bash+JAN_EXPERIMENTAL_ACP=1 jan acp # what an editor spawns+JAN_EXPERIMENTAL_ACP=1 jan acp --login # the sign-in an ACP client runs in a terminal+```++See [Editors (ACP)](/docs/agent/acp) for editor setup and the supported surface.+## `jan update`Update the binary to the latest build of the channel it was built for.@@ -759,6 +774,7 @@ doing anything. Re-run the installer with `--source` to rebuild.| `JAN_API_KEY` | API key for the target provider || `<PROVIDER>_API_KEY` | Per-provider key, e.g. `ANTHROPIC_API_KEY` || `JAN_INSTALL_DIR` | Install directory used by the install script |+| `JAN_EXPERIMENTAL_ACP` | `1` allows the experimental `jan acp` server; `0` blocks it even if `[experimental] acp` is set |## Using it in CIdiff --git a/docs/src/pages/docs/agent/protocol.mdx b/docs/src/pages/docs/agent/protocol.mdxindex 76cf5b158..dc928b5b2 100644--- a/docs/src/pages/docs/agent/protocol.mdx+++ b/docs/src/pages/docs/agent/protocol.mdx@@ -51,7 +51,8 @@ use that run's `init` record. These are not interchangeable capability inventori<Callout type="info">The current ADKs use RPC. If your binary has no `rpc` command, update the nightly runtime.-ACP is a separate, planned integration, not another name for either protocol.+ACP is a separate protocol for editors, not another name for either of these. See+[Editors (ACP)](/docs/agent/acp) for the experimental `jan acp` server.</Callout>See the [RPC command reference](/docs/agent/cli#rpc) for startup and session methods, anddiff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 5261bfa6f..cc0ce8d44 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -7,6 +7,7 @@ name = "Jan"version = "0.8.5"dependencies = ["aes-gcm",+ "agent-client-protocol","arboard","async-trait","base64 0.22.1",@@ -146,6 +147,56 @@ dependencies = ["subtle",]+[[package]]+name = "agent-client-protocol"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13f780597b2c88ab83d02509bcc3e86366751f86fa12114005e35c55ed691763"+dependencies = [+ "agent-client-protocol-derive",+ "agent-client-protocol-schema",+ "async-io",+ "async-process",+ "blocking",+ "futures",+ "futures-concurrency",+ "rustc-hash",+ "rustix",+ "schemars 1.2.1",+ "serde",+ "serde_json",+ "shell-words",+ "tracing",+ "uuid",+ "windows-sys 0.61.2",+]++[[package]]+name = "agent-client-protocol-derive"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4893bfb11e0e193aa5a64611a126ee87567acb1879556519c902722899229de"+dependencies = [+ "quote",+ "syn 3.0.5",+]++[[package]]+name = "agent-client-protocol-schema"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d595a79e1665d02c91c7dd1bedd118501e75cc0a3d5b1651b5150ec4c5c1e0d"+dependencies = [+ "anyhow",+ "derive_more",+ "schemars 1.2.1",+ "serde",+ "serde_json",+ "serde_with",+ "strum",+ "tracing",+]+[[package]]name = "ahash"version = "0.8.12"@@ -2531,6 +2582,19 @@ dependencies = ["futures-sink",]+[[package]]+name = "futures-concurrency"+version = "7.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6"+dependencies = [+ "fixedbitset 0.5.7",+ "futures-core",+ "futures-lite",+ "pin-project",+ "smallvec",+]+[[package]]name = "futures-core"version = "0.3.32"@@ -5358,6 +5422,26 @@ dependencies = ["siphasher 1.0.3",]+[[package]]+name = "pin-project"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"+dependencies = [+ "pin-project-internal",+]++[[package]]+name = "pin-project-internal"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]+[[package]]name = "pin-project-lite"version = "0.2.17"@@ -6831,6 +6915,12 @@ dependencies = ["windows-sys 0.60.2",]+[[package]]+name = "shell-words"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"+[[package]]name = "shlex"version = "2.0.1"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 3dff8e8e6..3289170d3 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -6,9 +6,11 @@ authors = ["Jan <[email protected]>"]license = "MIT"repository = "https://github.com/janhq/jan"edition = "2021"-# 1.85 is the floor: `genai` (the OpenAI upstream client) is edition 2024.-# Below that the previous floor was 1.82, for `Option::is_none_or` in agent/loop.rs.-rust-version = "1.85"+# 1.88 is the floor: `agent-client-protocol` (the experimental `jan acp`+# server) declares it. Before that, 1.85 was the floor because `genai` (the+# OpenAI upstream client) is edition 2024, and 1.82 before that, for+# `Option::is_none_or` in agent/loop.rs.+rust-version = "1.88"resolver = "2"default-run = "Jan-Desktop"@@ -100,7 +102,7 @@ test-tauri = ["deep-link","hardware",]-cli = ["dep:env_logger", "dep:indicatif", "dep:console", "dep:ratatui", "dep:unicode-width", "dep:pulldown-cmark", "dep:syntect", "dep:comfy-table", "dep:arboard", "dep:png"]+cli = ["dep:env_logger", "dep:agent-client-protocol", "dep:indicatif", "dep:console", "dep:ratatui", "dep:unicode-width", "dep:pulldown-cmark", "dep:syntect", "dep:comfy-table", "dep:arboard", "dep:png"][build-dependencies]tauri-build = { version = "2.0.2", features = [], optional = true }@@ -208,6 +210,10 @@ regex = "1"ignore = "0.4"clap = { version = "4", features = ["derive"] }env_logger = { version = "0.11", optional = true }+# The experimental `jan acp` server (core/cli/acp.rs). Stable ACP wire protocol+# v1 only: no `unstable_*` feature, since those are drafts a client may not+# have negotiated. The crate version is a library version, not the wire version.+agent-client-protocol = { version = "2.2.0", default-features = false, optional = true }indicatif = { version = "0.17", optional = true }console = { version = "0.15", optional = true }# The Secret Service backend must be `async-secret-service` (zbus, pure Rust),diff --git a/src-tauri/jan-cli/Cargo.lock b/src-tauri/jan-cli/Cargo.lockindex df6946ba9..678895105 100644--- a/src-tauri/jan-cli/Cargo.lock+++ b/src-tauri/jan-cli/Cargo.lock@@ -7,6 +7,7 @@ name = "Jan"version = "0.8.5"dependencies = ["aes-gcm",+ "agent-client-protocol","arboard","async-trait","base64 0.22.1",@@ -114,6 +115,56 @@ dependencies = ["subtle",]+[[package]]+name = "agent-client-protocol"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13f780597b2c88ab83d02509bcc3e86366751f86fa12114005e35c55ed691763"+dependencies = [+ "agent-client-protocol-derive",+ "agent-client-protocol-schema",+ "async-io",+ "async-process",+ "blocking",+ "futures",+ "futures-concurrency",+ "rustc-hash",+ "rustix",+ "schemars 1.2.2",+ "serde",+ "serde_json",+ "shell-words",+ "tracing",+ "uuid",+ "windows-sys 0.61.2",+]++[[package]]+name = "agent-client-protocol-derive"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4893bfb11e0e193aa5a64611a126ee87567acb1879556519c902722899229de"+dependencies = [+ "quote",+ "syn 3.0.5",+]++[[package]]+name = "agent-client-protocol-schema"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d595a79e1665d02c91c7dd1bedd118501e75cc0a3d5b1651b5150ec4c5c1e0d"+dependencies = [+ "anyhow",+ "derive_more",+ "schemars 1.2.2",+ "serde",+ "serde_json",+ "serde_with",+ "strum",+ "tracing",+]+[[package]]name = "ahash"version = "0.8.12"@@ -1752,6 +1803,19 @@ dependencies = ["futures-sink",]+[[package]]+name = "futures-concurrency"+version = "7.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6"+dependencies = [+ "fixedbitset 0.5.7",+ "futures-core",+ "futures-lite",+ "pin-project",+ "smallvec",+]+[[package]]name = "futures-core"version = "0.3.34"@@ -3594,6 +3658,26 @@ dependencies = ["siphasher",]+[[package]]+name = "pin-project"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"+dependencies = [+ "pin-project-internal",+]++[[package]]+name = "pin-project-internal"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "pin-project-lite"version = "0.2.17"@@ -4781,6 +4865,12 @@ dependencies = ["digest",]+[[package]]+name = "shell-words"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"+[[package]]name = "shlex"version = "2.0.1"diff --git a/src-tauri/jan-cli/Cargo.toml b/src-tauri/jan-cli/Cargo.tomlindex 014cfa344..56a4e71aa 100644--- a/src-tauri/jan-cli/Cargo.toml+++ b/src-tauri/jan-cli/Cargo.toml@@ -6,7 +6,8 @@ authors = ["Jan <[email protected]>"]license = "MIT"repository = "https://github.com/janhq/jan"edition = "2021"-rust-version = "1.85"+# Matches ../Cargo.toml: `agent-client-protocol` (behind `jan acp`) needs 1.88.+rust-version = "1.88"# A standalone crate (NOT a workspace member of ../Cargo.toml) so the Tauri# bundler never enumerates it as a bin target of the desktop app -- tauri-clidiff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 41c9ba4f1..2b86af6e1 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -270,6 +270,16 @@ enum Commands {#[command(subcommand)]cmd: McpServeCommands,},+ /// Experimental: serve the agent over the Agent Client Protocol (ACP) on+ /// stdio, for Zed, JetBrains and other ACP clients. Hidden until it+ /// graduates; needs JAN_EXPERIMENTAL_ACP=1 or `[experimental] acp = true`+ #[command(hide = true)]+ Acp {+ /// Sign in interactively and exit: what an ACP client runs for the+ /// terminal auth method `initialize` offers+ #[arg(long)]+ login: bool,+ },/// Update this binary to the latest build of the channel it was built for#[command(display_order = 8)]Update {@@ -762,6 +772,7 @@ async fn main() {command,Commands::Update { .. }| Commands::Mcp { .. }+ | Commands::Acp { .. }| Commands::Cli {cmd: CliCommands::Agent {cmd: AgentCommands::Rpc@@ -799,11 +810,37 @@ async fn main() {}Commands::Plugin { cmd } => handle_plugin(cmd).await,Commands::Mcp { cmd } => handle_mcp_serve(cmd).await,+ Commands::Acp { login } => handle_acp(login).await,Commands::Update { check, force } => handle_update(check, force).await,}app_lib::core::agent::otel::shutdown().await;}+// ── ACP server handler ─────────────────────────────────────────────────────++/// `jan acp`. Refused before anything reads stdin unless the experimental+/// opt-in is on, so a client pointed at it by mistake gets a clear error on+/// stderr and an exit rather than a half-open protocol channel.+async fn handle_acp(login: bool) {+ use app_lib::core::cli::acp;+ if !acp::enabled() {+ eprintln!("Error: {}", acp::DISABLED_MESSAGE);+ std::process::exit(2);+ }+ // The terminal auth method: the client relaunches `jan acp --login` in a+ // terminal it shows the user, and a zero exit means signed in.+ let result = if login {+ app_lib::core::cli::login::run_login(false).await+ } else {+ acp::serve().await+ };+ if let Err(e) = result {+ eprintln!("Error: {e}");+ app_lib::core::agent::otel::shutdown().await;+ std::process::exit(1);+ }+}+// ── MCP server handler ─────────────────────────────────────────────────────async fn handle_mcp_serve(cmd: McpServeCommands) {@@ -1686,6 +1723,17 @@ mod tests {assert_eq!(out.as_deref(), Some(std::path::Path::new("protocol/schema.json")));}+ #[test]+ fn acp_parses_and_stays_out_of_help() {+ let cli = Cli::parse_from(["jan", "acp"]);+ assert!(matches!(cli.command, Some(Commands::Acp { login: false })));+ let cli = Cli::parse_from(["jan", "acp", "--login"]);+ assert!(matches!(cli.command, Some(Commands::Acp { login: true })));+ // Experimental: callable, but not offered in `--help` until it graduates.+ let help = Cli::command().render_help().to_string();+ assert!(!help.contains("Agent Client Protocol"), "{help}");+ }+/// `rpc` and `rpc-schema` are the long-lived session transport and its/// generated artifact: neither involves a project or a provider, and/// `rpc-schema --out` is the only flag between them.diff --git a/src-tauri/jan-cli/tests/acp.rs b/src-tauri/jan-cli/tests/acp.rsnew file mode 100644index 000000000..d60d11ef9--- /dev/null+++ b/src-tauri/jan-cli/tests/acp.rs@@ -0,0 +1,479 @@+//! `jan acp` (experimental) through the real binary, driven the way an ACP+//! client drives it: LF-delimited JSON-RPC on stdin/stdout, against a stub+//! OpenAI-compatible provider on a loopback port.+//!+//! What is pinned here is what only the process boundary can show: the opt-in+//! gate, that stdout carries nothing but protocol frames (with debug logging+//! on), the `session/update` stream a prompt produces, a gate prompt answered+//! over `session/request_permission`, `session/load` replaying a saved thread+//! before it replies, and `session/cancel` ending a prompt as `cancelled`.++use std::io::{BufRead, BufReader, Read, Write};+use std::net::{TcpListener, TcpStream};+use std::path::PathBuf;+use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use std::time::Duration;++use serde_json::{json, Value};++fn chunk(delta: Value, finish: Option<&str>) -> String {+ let record = json!({+ "id":"stub","object":"chat.completion.chunk","created":1,"model":"stub-model",+ "choices":[{"index":0,"delta":delta,"finish_reason":finish}],+ "usage": finish.map(|_| json!({"prompt_tokens":5,"completion_tokens":2,"total_tokens":7})),+ });+ format!("data: {record}\n\n")+}++fn prose(text: &str) -> String {+ let mut out = chunk(json!({"role":"assistant","content":text}), None);+ out.push_str(&chunk(json!({}), Some("stop")));+ out.push_str("data: [DONE]\n\n");+ out+}++/// The model writes `note.txt`: a call the default gate prompts for.+fn write_call() -> String {+ let args = json!({"path":"note.txt","content":"hello"}).to_string();+ let mut out = chunk(+ json!({"role":"assistant","tool_calls":[{"index":0,"id":"call-1","type":"function",+ "function":{"name":"write","arguments":args}}]}),+ None,+ );+ out.push_str(&chunk(json!({}), Some("tool_calls")));+ out.push_str("data: [DONE]\n\n");+ out+}++/// The model reads `a.txt`: a call the default gate allows without asking.+fn read_call() -> String {+ let args = json!({"path":"a.txt"}).to_string();+ let mut out = chunk(+ json!({"role":"assistant","tool_calls":[{"index":0,"id":"call-r","type":"function",+ "function":{"name":"read","arguments":args}}]}),+ None,+ );+ out.push_str(&chunk(json!({}), Some("tool_calls")));+ out.push_str("data: [DONE]\n\n");+ out+}++/// Serve `replies` in order, one per request, repeating the last. A `None`+/// reply holds the connection open without answering, so a prompt stays in+/// flight until it is cancelled.+fn stub_provider(replies: Vec<Option<String>>) -> String {+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind the stub provider");+ let addr = listener.local_addr().expect("stub address");+ let replies = Arc::new(replies);+ let nth = Arc::new(AtomicUsize::new(0));+ std::thread::spawn(move || {+ for stream in listener.incoming() {+ let Ok(mut stream) = stream else { continue };+ let replies = Arc::clone(&replies);+ let nth = Arc::clone(&nth);+ std::thread::spawn(move || {+ drain_request(&mut stream);+ let i = nth.fetch_add(1, Ordering::SeqCst);+ match &replies[i.min(replies.len() - 1)] {+ Some(reply) => {+ let response = format!(+ "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",+ reply.len()+ );+ let _ = stream.write_all(response.as_bytes());+ let _ = stream.flush();+ }+ None => std::thread::sleep(Duration::from_secs(60)),+ }+ });+ }+ });+ format!("http://{addr}/v1")+}++fn drain_request(stream: &mut TcpStream) {+ let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));+ let mut buf: Vec<u8> = Vec::new();+ let mut part = [0u8; 4096];+ loop {+ match stream.read(&mut part) {+ Ok(0) | Err(_) => return,+ Ok(n) => buf.extend_from_slice(&part[..n]),+ }+ let Some(head) = buf.windows(4).position(|w| w == b"\r\n\r\n") else {+ continue;+ };+ let headers = String::from_utf8_lossy(&buf[..head]).to_ascii_lowercase();+ let want = headers+ .lines()+ .find_map(|line| line.strip_prefix("content-length:"))+ .and_then(|v| v.trim().parse::<usize>().ok())+ .unwrap_or(0);+ if buf.len() >= head + 4 + want {+ return;+ }+ }+}++/// A private home, data folder and project per test, removed on drop.+struct Scratch {+ root: PathBuf,+}++impl Scratch {+ fn new(name: &str) -> Self {+ let root = std::env::temp_dir().join(format!("jan-acp-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(root.join("home")).expect("home dir");+ std::fs::create_dir_all(root.join("project")).expect("project dir");+ Self { root }+ }++ fn project(&self) -> PathBuf {+ self.root.join("project")+ }++ fn command(&self, args: &[&str]) -> Command {+ let mut cmd = Command::new(env!("CARGO_BIN_EXE_jan"));+ cmd.args(args)+ .env("HOME", self.root.join("home"))+ .env("JAN_DATA_FOLDER", self.root.join("jan-data"))+ .env("JAN_CLI_NO_UPDATE_CHECK", "1")+ .env_remove("JAN_EXPERIMENTAL_ACP")+ .env_remove("JAN_API_KEY")+ .env_remove("OPENAI_API_KEY")+ .env_remove("ANTHROPIC_API_KEY");+ cmd+ }++ fn configure(&self, base_url: &str) {+ let out = self+ .command(&[+ "config", "set", "--provider", "stub", "--api-key", "test-key", "--base-url",+ base_url, "--model", "stub-model",+ ])+ .output()+ .expect("run `jan config set`");+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ }++ fn open(&self) -> Acp {+ let mut child = self+ .command(&["acp"])+ .env("JAN_EXPERIMENTAL_ACP", "1")+ // Debug logging on, so a stray log line on stdout breaks a frame.+ .env("RUST_LOG", "debug")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn `jan acp`");+ let input = child.stdin.take();+ let output = BufReader::new(child.stdout.take().expect("stdout"));+ Acp { child, input, output, next: 1 }+ }+}++impl Drop for Scratch {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.root);+ }+}++struct Acp {+ child: Child,+ input: Option<ChildStdin>,+ output: BufReader<ChildStdout>,+ next: u64,+}++impl Acp {+ fn send(&mut self, frame: Value) {+ let input = self.input.as_mut().expect("stdin is open");+ writeln!(input, "{frame}").unwrap();+ input.flush().unwrap();+ }++ /// Every stdout line must be a JSON-RPC 2.0 frame.+ fn read(&mut self) -> Value {+ let mut line = String::new();+ assert!(self.output.read_line(&mut line).unwrap() > 0, "the channel closed");+ let frame: Value = serde_json::from_str(&line)+ .unwrap_or_else(|e| panic!("non-protocol bytes on stdout ({e}): {line:?}"));+ assert_eq!(frame["jsonrpc"], "2.0", "{frame}");+ frame+ }++ fn request(&mut self, method: &str, params: Value) -> u64 {+ let id = self.next;+ self.next += 1;+ self.send(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}));+ id+ }++ /// Send a request and collect every frame up to and including its reply,+ /// answering any `session/request_permission` with `answer`.+ fn call(&mut self, method: &str, params: Value, answer: Option<&str>) -> (Value, Vec<Value>) {+ let id = self.request(method, params);+ let mut seen = Vec::new();+ loop {+ let frame = self.read();+ if frame["method"] == "session/request_permission" {+ let option = answer.expect("no permission prompt was expected");+ self.send(json!({"jsonrpc":"2.0","id":frame["id"],+ "result":{"outcome":{"outcome":"selected","optionId":option}}}));+ }+ if frame["id"] == json!(id) && frame.get("method").is_none() {+ return (frame, seen);+ }+ seen.push(frame);+ }+ }++ fn initialize(&mut self) -> Value {+ self.call(+ "initialize",+ json!({"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":true,"writeTextFile":true},"terminal":true},+ "clientInfo":{"name":"test","version":"1"}}),+ None,+ )+ .0+ }++ fn new_session(&mut self, cwd: &std::path::Path) -> String {+ let (reply, _) = self.call("session/new", json!({"cwd":cwd,"mcpServers":[]}), None);+ reply["result"]["sessionId"].as_str().unwrap_or_else(|| panic!("{reply}")).to_string()+ }++ fn close(mut self) {+ self.input.take();+ let status = self.child.wait().expect("wait for `jan acp`");+ assert!(status.success(), "{status}");+ }+}++/// Every thread id saved anywhere under `dir`: a thread is a directory holding+/// `messages.jsonl`, named by its id.+fn thread_ids(dir: &std::path::Path) -> Vec<String> {+ let mut out = Vec::new();+ for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {+ let path = entry.path();+ if path.is_dir() {+ if path.join("messages.jsonl").is_file() {+ out.push(entry.file_name().to_string_lossy().into_owned());+ }+ out.extend(thread_ids(&path));+ }+ }+ out+}++fn updates<'a>(frames: &'a [Value], tag: &str) -> Vec<&'a Value> {+ frames+ .iter()+ .filter(|f| f["method"] == "session/update" && f["params"]["update"]["sessionUpdate"] == tag)+ .map(|f| &f["params"]["update"])+ .collect()+}++#[test]+fn acp_is_refused_without_the_experimental_opt_in() {+ let scratch = Scratch::new("gate");+ let out = scratch.command(&["acp"]).stdin(Stdio::null()).output().expect("run `jan acp`");+ assert_eq!(out.status.code(), Some(2));+ assert!(out.stdout.is_empty(), "nothing on the protocol channel");+ assert!(String::from_utf8_lossy(&out.stderr).contains("JAN_EXPERIMENTAL_ACP"));+ let help = scratch.command(&["--help"]).output().expect("run `jan --help`");+ assert!(!String::from_utf8_lossy(&help.stdout).contains("acp"), "hidden from help");+}++#[test]+fn a_prompt_streams_updates_and_a_gated_write_asks_the_client() {+ let scratch = Scratch::new("prompt");+ scratch.configure(&stub_provider(vec![+ Some(prose("stub answer")),+ Some(write_call()),+ Some(prose("wrote it")),+ Some(write_call()),+ Some(prose("did not write")),+ ]));+ let project = scratch.project();+ let mut acp = scratch.open();+ let init = acp.initialize();+ assert_eq!(init["result"]["protocolVersion"], 1);+ assert_eq!(init["result"]["agentCapabilities"]["loadSession"], true);+ assert_eq!(init["result"]["authMethods"], json!([]));+ let sid = acp.new_session(&project);++ let (reply, frames) = acp.call(+ "session/prompt",+ json!({"sessionId":sid,"prompt":[{"type":"text","text":"hi"}]}),+ None,+ );+ assert_eq!(reply["result"]["stopReason"], "end_turn", "{reply}");+ let text: String = updates(&frames, "agent_message_chunk")+ .iter()+ .filter_map(|u| u["content"]["text"].as_str())+ .collect();+ assert_eq!(text, "stub answer");++ // Allowed: the call runs and the file lands.+ let (reply, frames) = acp.call(+ "session/prompt",+ json!({"sessionId":sid,"prompt":[{"type":"text","text":"write the note"}]}),+ Some("allow_once"),+ );+ assert_eq!(reply["result"]["stopReason"], "end_turn", "{reply}");+ assert!(!updates(&frames, "tool_call").is_empty(), "{frames:?}");+ let done = updates(&frames, "tool_call_update");+ assert!(done.iter().any(|u| u["status"] == "completed"), "{frames:?}");+ assert_eq!(std::fs::read_to_string(project.join("note.txt")).unwrap(), "hello");++ // Rejected: the same gate refuses the call, and nothing is written.+ std::fs::remove_file(project.join("note.txt")).unwrap();+ let (reply, frames) = acp.call(+ "session/prompt",+ json!({"sessionId":sid,"prompt":[{"type":"text","text":"write it again"}]}),+ Some("reject_once"),+ );+ assert_eq!(reply["result"]["stopReason"], "end_turn", "{reply}");+ assert!(!project.join("note.txt").exists(), "a rejected write must not run");+ assert!(!updates(&frames, "tool_call_update").is_empty());+ acp.close();++ // The conversation was saved under the session id, so a fresh process+ // can load it -- and replays it before replying.+ let mut acp = scratch.open();+ acp.initialize();+ let (reply, frames) = acp.call(+ "session/load",+ json!({"sessionId":sid,"cwd":project,"mcpServers":[]}),+ None,+ );+ assert!(reply.get("error").is_none(), "{reply}");+ let users: Vec<&str> = updates(&frames, "user_message_chunk")+ .iter()+ .filter_map(|u| u["content"]["text"].as_str())+ .collect();+ assert_eq!(users, ["hi", "write the note", "write it again"]);+ assert!(!updates(&frames, "agent_message_chunk").is_empty());+ assert!(!updates(&frames, "tool_call").is_empty());++ let (reply, _) = acp.call(+ "session/load",+ json!({"sessionId":"no-such-thread","cwd":project,"mcpServers":[]}),+ None,+ );+ assert!(reply.get("error").is_some(), "{reply}");+ acp.close();+}++/// A thread another surface wrote -- here a headless `jan cli agent run`, which+/// saves through the same store the TUI does, tool calls included -- loads+/// and replays, and the loaded session can be prompted.+#[test]+fn load_replays_a_thread_another_surface_saved() {+ let scratch = Scratch::new("foreign");+ scratch.configure(&stub_provider(vec![+ Some(read_call()),+ Some(prose("read it")),+ Some(prose("continued")),+ ]));+ let project = scratch.project();+ std::fs::write(project.join("a.txt"), "alpha").unwrap();+ let out = scratch+ .command(&["cli", "agent", "run", "--project", project.to_str().unwrap(), "--output-format", "json", "read a.txt"])+ .output()+ .expect("run `jan cli agent run`");+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ let report: Value = serde_json::from_slice(&out.stdout).expect("the json result");+ // The report abbreviates the id for a person; the store holds it whole,+ // and that is what a client that remembers a session holds.+ let short = report["session_id"].as_str().unwrap_or_else(|| panic!("{report}")).to_string();+ let sid = thread_ids(&scratch.root)+ .into_iter()+ .find(|id| id.starts_with(&short))+ .unwrap_or_else(|| panic!("no saved thread for {short}"));++ let mut acp = scratch.open();+ acp.initialize();+ let (reply, frames) = acp.call("session/load", json!({"sessionId":sid,"cwd":project,"mcpServers":[]}), None);+ assert!(reply.get("error").is_none(), "{reply}");+ let users: Vec<&str> = updates(&frames, "user_message_chunk")+ .iter()+ .filter_map(|u| u["content"]["text"].as_str())+ .collect();+ assert_eq!(users, ["read a.txt"]);+ let calls = updates(&frames, "tool_call");+ assert_eq!(calls.len(), 1, "{frames:?}");+ assert_eq!(calls[0]["toolCallId"], "call-r");+ let results = updates(&frames, "tool_call_update");+ assert!(results[0]["content"][0]["content"]["text"].as_str().unwrap().contains("alpha"), "{frames:?}");++ let (reply, _) = acp.call("session/prompt", json!({"sessionId":sid,"prompt":[{"type":"text","text":"go on"}]}), None);+ assert_eq!(reply["result"]["stopReason"], "end_turn", "{reply}");+ acp.close();+}++/// Cancelled while a gated call waits on the client: the prompt ends+/// `cancelled`, the open `session/request_permission` is withdrawn, the call+/// never runs, and the next prompt goes out on a well-formed history.+#[test]+fn cancel_during_a_pending_tool_call_neither_runs_it_nor_breaks_the_session() {+ let scratch = Scratch::new("cancel-tool");+ scratch.configure(&stub_provider(vec![Some(write_call()), Some(prose("after"))]));+ let project = scratch.project();+ let mut acp = scratch.open();+ acp.initialize();+ let sid = acp.new_session(&project);+ let id = acp.request("session/prompt", json!({"sessionId":sid,"prompt":[{"type":"text","text":"write"}]}));+ // Wait for the gate prompt, then cancel instead of answering it.+ loop {+ let frame = acp.read();+ if frame["method"] == "session/request_permission" {+ break;+ }+ }+ acp.send(json!({"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":sid}}));+ loop {+ let frame = acp.read();+ if frame["id"] == json!(id) {+ assert_eq!(frame["result"]["stopReason"], "cancelled", "{frame}");+ break;+ }+ }+ assert!(!project.join("note.txt").exists(), "a cancelled call must not run");++ let (reply, frames) = acp.call("session/prompt", json!({"sessionId":sid,"prompt":[{"type":"text","text":"again"}]}), None);+ assert_eq!(reply["result"]["stopReason"], "end_turn", "{reply}");+ let text: String = updates(&frames, "agent_message_chunk")+ .iter()+ .filter_map(|u| u["content"]["text"].as_str())+ .collect();+ assert_eq!(text, "after");+ acp.close();+}++#[test]+fn cancel_ends_an_in_flight_prompt_as_cancelled() {+ let scratch = Scratch::new("cancel");+ // The provider never answers, so the prompt is in flight until cancelled.+ scratch.configure(&stub_provider(vec![None]));+ let project = scratch.project();+ let mut acp = scratch.open();+ acp.initialize();+ let sid = acp.new_session(&project);+ let id = acp.request("session/prompt", json!({"sessionId":sid,"prompt":[{"type":"text","text":"hang"}]}));+ std::thread::sleep(Duration::from_millis(500));+ acp.send(json!({"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":sid}}));+ loop {+ let frame = acp.read();+ if frame["id"] == json!(id) {+ assert_eq!(frame["result"]["stopReason"], "cancelled", "{frame}");+ break;+ }+ }+ acp.close();+}diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex f5ab526d2..1ff18d503 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -70,6 +70,12 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# # to opt in; [] reads JAN.md only. A# # project's agent.toml [context] wins#+# [experimental] # features that may change or go away+# acp = true # allow `jan acp`, the Agent Client+# # Protocol server editors such as Zed+# # and JetBrains drive. Off by default;+# # JAN_EXPERIMENTAL_ACP wins over this+## [providers.my-provider]# api_key = "sk-..."# base_url = "https://api.example.com/v1"@@ -176,10 +182,30 @@ struct GlobalConfigToml {/// wins. See `project::context_fallback_files`.#[serde(default, skip_serializing_if = "Option::is_none")]context: Option<GlobalContextSection>,+ /// `[experimental]` -- opt-ins for surfaces whose contract is not settled+ /// yet. One table so every such switch is found in one place, and so+ /// graduating a feature is deleting its key rather than migrating it.+ #[serde(default, skip_serializing_if = "ExperimentalSection::is_empty")]+ experimental: ExperimentalSection,#[serde(default)]providers: HashMap<String, GlobalProviderEntry>,}+/// `[experimental]` in `~/.jan/config.toml`. Each key is `None` when unset,+/// which means off.+#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]+struct ExperimentalSection {+ /// `jan acp`, the Agent Client Protocol server.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ acp: Option<bool>,+}++impl ExperimentalSection {+ fn is_empty(&self) -> bool {+ self.acp.is_none()+ }+}+/// `[telemetry]` in `~/.jan/config.toml` or a project's `agent.toml`. Only the/// switch lives here: where the data goes is the standard `OTEL_*` env, so one/// collector setup serves every OpenTelemetry-speaking tool unchanged.@@ -333,6 +359,13 @@ pub(crate) fn telemetry_setting() -> Option<bool> {load_raw().ok().and_then(|config| config.telemetry.enabled)}+/// `[experimental].acp` in `~/.jan/config.toml`; `None` when unset. A malformed+/// file reads as unset, which is off: an experimental surface fails closed.+#[cfg(feature = "cli")]+pub(crate) fn experimental_acp_setting() -> Option<bool> {+ load_raw().ok().and_then(|config| config.experimental.acp)+}+/// Whether the TUI should track the mouse (`mouse` in `~/.jan/config.toml`),/// defaulting to on. A display preference must never block startup, so an/// unreadable or malformed config yields the default rather than an error.diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 39e129516..e923fbd2b 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -44,6 +44,23 @@ use tauri_plugin_agent_tools::tools::gate::{DenyReason, PermissionDecision};pub(crate) type PermissionRegistry =Arc<Mutex<HashMap<String, tokio::sync::oneshot::Sender<PermissionDecision>>>>;+/// Answer the pending prompt `request_id` with `decision`: the one place every+/// out-of-process surface (stream-json, RPC, ACP) settles a gate prompt.+/// Taking the sender makes a decision single-use, so `false` means the id was+/// already answered, cancelled, or never issued, and the caller reports it.+#[cfg(feature = "cli")]+pub(crate) async fn settle_permission(+ registry: &PermissionRegistry,+ request_id: &str,+ decision: PermissionDecision,+) -> bool {+ let Some(sender) = registry.lock().await.remove(request_id) else {+ return false;+ };+ let _ = sender.send(decision);+ true+}+static PERMISSION_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);fn next_permission_id() -> String {diff --git a/src-tauri/src/core/cli/acp.rs b/src-tauri/src/core/cli/acp.rsnew file mode 100644index 000000000..00e04ae9f--- /dev/null+++ b/src-tauri/src/core/cli/acp.rs@@ -0,0 +1,1348 @@+//! `jan acp` (experimental): the agent served over the Agent Client Protocol+//! (ACP, <https://agentclientprotocol.com>) on stdio, so editors such as Zed and+//! JetBrains can drive it.+//!+//! An adapter, not a second engine. A session is an [`AgentSession`] built by+//! the same `prepare_agent_session` every other surface uses, a prompt is one+//! `run_orchestration_steered` run, and the run's [`StreamEvent`]s are+//! translated into `session/update` notifications by [`TurnMap`]. A permission+//! prompt is answered through the session's own `PermissionRegistry`, so the+//! tool gate an editor drives is the gate the TUI drives, with no bypass.+//!+//! Pinned to stable ACP wire protocol version 1 (negotiated in `initialize`),+//! with no `unstable_*` crate feature. An event ACP has no standard update for+//! is dropped, never invented into the protocol; the full table is in+//! [`TurnMap::map`], whose match has no wildcard arm so a new `StreamEvent`+//! variant cannot slip past the decision.+//!+//! MCP servers a client passes in `session/new`/`session/load` are connected+//! alongside the project's own, over stdio (the transport every ACP agent must+//! support); HTTP and SSE are not advertised. Out of scope for this cut:+//! consuming the client's `fs/*` and `terminal/*` (Jan's own tools serve the+//! filesystem) and `session/set_mode`. Neither is advertised.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use agent_client_protocol::schema::v1::{+ AgentCapabilities, AuthMethod, AuthMethodTerminal, AuthenticateRequest, AuthenticateResponse,+ CancelNotification, ContentBlock, ContentChunk, EmbeddedResourceResource, Implementation,+ InitializeRequest, InitializeResponse, LoadSessionRequest, LoadSessionResponse, McpServer,+ NewSessionRequest, NewSessionResponse, PermissionOption, PermissionOptionKind, Plan,+ PlanEntry, PlanEntryPriority, PlanEntryStatus, PromptCapabilities, PromptRequest,+ PromptResponse, RequestPermissionOutcome, RequestPermissionRequest,+ SessionId, SessionNotification, SessionUpdate, StopReason, ToolCall, ToolCallContent,+ ToolCallLocation, ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields, ToolKind,+ UsageUpdate,+};+use agent_client_protocol::schema::ProtocolVersion;+use agent_client_protocol::{Agent, Client, ConnectionTo, Error, Responder, Stdio};+use serde_json::{json, Value};+use tauri_plugin_agent_tools::tools::gate::PermissionDecision;+use tokio::sync::Mutex;+use tokio_util::sync::CancellationToken;++use super::providers::ProviderOverrides;+use super::{+ adopt_turn_history, agent_dir_for, cli_read_messages_lenient, cli_save_thread,+ find_resume_thread, fold_interrupted_tools, is_user_turn, prepare_agent_session,+ rebuild_wire_history, thread_message_text, AgentSession, ResumeTarget, SessionFlags,+};+use crate::core::agent::events::StreamEvent;+use crate::core::agent::r#loop::{run_orchestration_steered, settle_permission};+use crate::core::agent::todo::{TodoList, TodoStatus};++/// The env var that switches the experimental server on. Any explicit value+/// wins over `[experimental].acp` in `~/.jan/config.toml`, so `=0` turns it off.+pub const ENABLE_ENV: &str = "JAN_EXPERIMENTAL_ACP";++/// Printed (to stderr) when `jan acp` runs without the opt-in.+pub const DISABLED_MESSAGE: &str = "`jan acp` is experimental and off by default. Enable it with \+ JAN_EXPERIMENTAL_ACP=1, or set `acp = true` under `[experimental]` in ~/.jan/config.toml.";++/// Whether `jan acp` may run: the env var, then the global config, then off.+pub fn enabled() -> bool {+ enabled_from(+ std::env::var(ENABLE_ENV).ok().as_deref(),+ crate::core::agent::global_config::experimental_acp_setting(),+ )+}++fn enabled_from(env: Option<&str>, config: Option<bool>) -> bool {+ env.and_then(crate::core::agent::otel::config::parse_flag)+ .or(config)+ .unwrap_or(false)+}++/// The argument a terminal-auth client appends to the configured `jan acp`+/// invocation to sign in (`jan acp --login`).+pub const LOGIN_ARG: &str = "--login";++const ALLOW_ONCE: &str = "allow_once";+const ALLOW_ALWAYS: &str = "allow_always";+const REJECT_ONCE: &str = "reject_once";++/// Accumulated tool output is kept to this many trailing bytes. `content` on a+/// `tool_call_update` replaces the whole list, so each delta resends the lot,+/// and an unbounded build log would be resent quadratically.+const OUTPUT_TAIL_BYTES: usize = 32 * 1024;++/// A tool result replayed by `session/load` is clipped to this many bytes: the+/// model keeps the full text in history, and the editor only needs the gist.+const REPLAY_RESULT_BYTES: usize = 8 * 1024;++struct Session {+ agent: AgentSession,+ history: Vec<Value>,+ cwd: PathBuf,+ /// Set from the moment a prompt is accepted until its thread is saved;+ /// `session/cancel` fires it, and `session/load` refuses to replace a+ /// session while it is set.+ turn: Option<CancellationToken>,+}++type Sessions = Arc<Mutex<HashMap<String, Session>>>;++/// Serve ACP on stdin/stdout until the client closes stdin. Stdout carries only+/// protocol frames; logs go to stderr.+pub async fn serve() -> Result<(), String> {+ let sessions: Sessions = Arc::new(Mutex::new(HashMap::new()));+ let (s_new, s_load, s_prompt, s_cancel) = (+ Arc::clone(&sessions),+ Arc::clone(&sessions),+ Arc::clone(&sessions),+ Arc::clone(&sessions),+ );+ // Every long handler hands its work to `cx.spawn`: the SDK dispatches one+ // message at a time, and a prompt that awaited inline would hold back the+ // `session/cancel` and permission replies it is waiting on.+ Agent+ .builder()+ .name("jan")+ .on_receive_request(+ async move |req: InitializeRequest, responder: Responder<InitializeResponse>, _cx| {+ responder.respond(initialize_response(&req))+ },+ agent_client_protocol::on_receive_request!(),+ )+ .on_receive_request(+ async move |_req: AuthenticateRequest, responder: Responder<AuthenticateResponse>, cx: ConnectionTo<Client>| {+ cx.spawn(async move {+ responder.respond_with_result(authenticate().await)+ })+ },+ agent_client_protocol::on_receive_request!(),+ )+ .on_receive_request(+ async move |req: NewSessionRequest, responder: Responder<NewSessionResponse>, cx: ConnectionTo<Client>| {+ let sessions = Arc::clone(&s_new);+ cx.spawn(async move {+ responder.respond_with_result(new_session(&sessions, req).await)+ })+ },+ agent_client_protocol::on_receive_request!(),+ )+ .on_receive_request(+ async move |req: LoadSessionRequest, responder: Responder<LoadSessionResponse>, cx: ConnectionTo<Client>| {+ let sessions = Arc::clone(&s_load);+ cx.clone().spawn(async move {+ // Replay and reply in one task: the spec requires every+ // replayed update to precede the response.+ responder.respond_with_result(load_session(&sessions, &cx, req).await)+ })+ },+ agent_client_protocol::on_receive_request!(),+ )+ .on_receive_request(+ async move |req: PromptRequest, responder: Responder<PromptResponse>, cx: ConnectionTo<Client>| {+ let sessions = Arc::clone(&s_prompt);+ cx.clone().spawn(async move {+ responder.respond_with_result(prompt(&sessions, &cx, req).await)+ })+ },+ agent_client_protocol::on_receive_request!(),+ )+ .on_receive_notification(+ async move |n: CancelNotification, _cx| {+ if let Some(Session { turn: Some(token), .. }) =+ s_cancel.lock().await.get(&*n.session_id.0)+ {+ token.cancel();+ }+ Ok(())+ },+ agent_client_protocol::on_receive_notification!(),+ )+ .connect_to(Stdio::new())+ .await+ .map_err(|e| format!("ACP connection failed: {e}"))+}++/// What Jan advertises. Only what is consumed: no client `fs`/`terminal`, no+/// MCP transports, so a client never assumes its unsaved buffers are read.+fn initialize_response(req: &InitializeRequest) -> InitializeResponse {+ // Echo a version this build speaks, else the latest it does; a client that+ // cannot speak it disconnects, as the spec prescribes.+ let version = req.protocol_version.min(ProtocolVersion::LATEST);+ // A terminal method may only be offered to a client that said it can run+ // one. It relaunches `jan acp --login`, the interactive sign-in.+ let auth_methods = if req.client_capabilities.auth.terminal {+ vec![AuthMethod::Terminal(+ AuthMethodTerminal::new("jan-login", "Sign in to Jan")+ .description("Opens `jan login` to sign in to Tokamak and save an API key".to_string())+ .args(vec![LOGIN_ARG.to_string()]),+ )]+ } else {+ Vec::new()+ };+ InitializeResponse::new(version)+ .agent_capabilities(+ AgentCapabilities::new().load_session(true).prompt_capabilities(+ PromptCapabilities::new().image(true).embedded_context(true),+ ),+ )+ .auth_methods(auth_methods)+ .agent_info(Implementation::new("jan", env!("CARGO_PKG_VERSION")))+}++/// Jan's credentials live in `~/.jan/config.toml`, filled by `jan login` or+/// `jan config set`, so authenticating is checking that one is usable.+async fn authenticate() -> Result<AuthenticateResponse, Error> {+ if super::providers::has_usable_provider(None) {+ Ok(AuthenticateResponse::new())+ } else {+ Err(auth_required("no provider is configured"))+ }+}++fn auth_required(detail: &str) -> Error {+ Error::auth_required().data(json!({+ "message": format!("{detail}: run `jan login`, or `jan config set --provider <name> --api-key <key> --base-url <url> --model <id>`"),+ }))+}++fn internal(message: impl Into<String>) -> Error {+ Error::internal_error().data(json!({"message": message.into()}))+}++fn invalid_params(message: impl Into<String>) -> Error {+ Error::invalid_params().data(json!({"message": message.into()}))+}++/// Run blocking work (thread-store reads and writes, session setup that reads+/// config files) off the async workers, so it can never stall+/// `session/cancel` or another session's stream.+async fn blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> Result<T, Error> {+ tokio::task::spawn_blocking(work)+ .await+ .map_err(|e| internal(format!("background task failed: {e}")))+}++fn checked_cwd(cwd: &Path) -> Result<PathBuf, Error> {+ if !cwd.is_absolute() {+ return Err(invalid_params("cwd must be an absolute path"));+ }+ if !cwd.is_dir() {+ return Err(invalid_params("cwd is not a directory"));+ }+ Ok(cwd.to_path_buf())+}++/// Build the engine handle for `cwd`, reporting the session under `id`, with+/// the client's MCP servers connected next to the project's.+async fn open_agent(cwd: &Path, id: &str, client_mcp: Vec<McpServer>) -> Result<AgentSession, Error> {+ let project = cwd.to_path_buf();+ let mut agent = blocking(move || {+ prepare_agent_session(+ &project.to_string_lossy(),+ None,+ ProviderOverrides::default(),+ // Gated: an editor surface asks before writes, shell and MCP calls,+ // which is what `session/request_permission` exists for.+ SessionFlags { require_model: true, ..Default::default() },+ None,+ )+ .map_err(|message| {+ if super::providers::has_usable_provider(Some(&project)) {+ internal(message)+ } else {+ auth_required(&message)+ }+ })+ })+ .await??;+ agent.args.session_id = Some(id.to_string());+ // The todo tool drives ACP's `plan` update, so an ACP session gets the+ // registry the TUI has and the headless run does not.+ agent.args.todo_registry = Some(crate::core::agent::todo::new_registry());+ // Tools are collected once per run, so the servers are awaited before the+ // first prompt can start one.+ if let Some(task) = agent.mcp_task.take() {+ if let Ok(outcome) = task.await {+ for failure in &outcome.failed {+ log::warn!("MCP: {failure}");+ }+ }+ }+ for server in client_mcp {+ let Some((name, config)) = client_mcp_config(server) else {+ continue;+ };+ // Best-effort, like the project's own servers: one that fails to start+ // costs its tools, not the session.+ if let Err(e) = super::mcp::connect(&name, &config, &agent.mcp_servers).await {+ log::warn!("ACP: client MCP server '{name}': {e}");+ }+ }+ Ok(agent)+}++/// A client MCP server in the shape `mcp_config.json` stores, so it connects+/// through the same code as a configured one. Only stdio: HTTP and SSE are not+/// advertised in `mcpCapabilities`, so a client that sends one anyway is+/// logged and skipped.+fn client_mcp_config(server: McpServer) -> Option<(String, Value)> {+ match server {+ McpServer::Stdio(stdio) => {+ let env: serde_json::Map<String, Value> =+ stdio.env.into_iter().map(|v| (v.name, Value::String(v.value))).collect();+ Some((+ stdio.name,+ json!({"command": stdio.command.to_string_lossy(), "args": stdio.args, "env": env}),+ ))+ }+ other => {+ log::warn!("ACP: skipping a client MCP server on an unadvertised transport: {other:?}");+ None+ }+ }+}++async fn new_session(sessions: &Sessions, req: NewSessionRequest) -> Result<NewSessionResponse, Error> {+ let cwd = checked_cwd(&req.cwd)?;+ // The session id is the thread id, unabbreviated, so `session/load`,+ // `/resume` and `--resume` all name the same conversation.+ let id = uuid::Uuid::new_v4().to_string();+ let agent = open_agent(&cwd, &id, req.mcp_servers).await?;+ sessions.lock().await.insert(+ id.clone(),+ Session { agent, history: Vec::new(), cwd, turn: None },+ );+ Ok(NewSessionResponse::new(SessionId::new(id)))+}++/// The wire history of the saved thread `id` under `agent_dir`, whichever+/// surface wrote it (TUI, headless run, RPC or ACP: all save through+/// `cli_save_thread`). Exact ids only: a prefix is a convenience for a person+/// typing, and a client that holds an id holds all of it.+fn read_thread(agent_dir: &Path, id: &str) -> Result<Vec<Value>, Error> {+ let found = find_resume_thread(agent_dir, &ResumeTarget::Id(id.to_string()))+ .ok()+ .filter(|thread| thread.get("id").and_then(Value::as_str) == Some(id));+ if found.is_none() {+ return Err(Error::resource_not_found(None).data(json!({"sessionId": id})));+ }+ let (messages, skipped) = cli_read_messages_lenient(agent_dir, id).map_err(internal)?;+ if skipped > 0 {+ log::warn!("ACP: skipped {skipped} unreadable message(s) loading {id}");+ }+ Ok(rebuild_wire_history(&messages))+}++fn busy() -> Error {+ Error::invalid_request().data(json!({"message": "session has a prompt running"}))+}++async fn load_session(+ sessions: &Sessions,+ cx: &ConnectionTo<Client>,+ req: LoadSessionRequest,+) -> Result<LoadSessionResponse, Error> {+ let cwd = checked_cwd(&req.cwd)?;+ let id = req.session_id.0.to_string();+ // A cheap early refusal; the check that counts is the one under the lock+ // below, since a prompt can start while this awaits.+ if sessions.lock().await.get(&id).is_some_and(|s| s.turn.is_some()) {+ return Err(busy());+ }+ let agent_dir = agent_dir_for(&cwd);+ let thread_id = id.clone();+ let history = blocking(move || read_thread(&agent_dir, &thread_id)).await??;+ let agent = open_agent(&cwd, &id, req.mcp_servers).await?;+ let updates = replay(&history, &cwd);+ {+ // Check and insert under one lock: a prompt accepted while the thread+ // was read would otherwise have its session replaced under it, and fold+ // its turn into the reloaded copy.+ let mut map = sessions.lock().await;+ if map.get(&id).is_some_and(|s| s.turn.is_some()) {+ return Err(busy());+ }+ map.insert(id, Session { agent, history, cwd, turn: None });+ }+ for update in updates {+ cx.send_notification(SessionNotification::new(req.session_id.clone(), update))?;+ }+ Ok(LoadSessionResponse::new())+}++/// The updates that redraw a saved conversation: what the user typed, what the+/// agent answered, and each tool call with its final result.+fn replay(history: &[Value], cwd: &Path) -> Vec<SessionUpdate> {+ let mut out = Vec::new();+ for message in history {+ match message.get("role").and_then(Value::as_str) {+ Some("user") if is_user_turn(message) => {+ let text = thread_message_text(message);+ if !text.is_empty() {+ out.push(SessionUpdate::UserMessageChunk(text_chunk(text)));+ }+ }+ Some("assistant") => {+ let text = thread_message_text(message);+ if !text.is_empty() {+ out.push(SessionUpdate::AgentMessageChunk(text_chunk(text)));+ }+ for call in message.get("tool_calls").and_then(Value::as_array).into_iter().flatten() {+ let id = call.get("id").and_then(Value::as_str).unwrap_or_default();+ let name = call.pointer("/function/name").and_then(Value::as_str).unwrap_or_default();+ let args = call+ .pointer("/function/arguments")+ .and_then(Value::as_str)+ .and_then(|raw| serde_json::from_str(raw).ok())+ .unwrap_or(Value::Null);+ out.push(SessionUpdate::ToolCall(+ ToolCall::new(id.to_string(), tool_title(name, &args))+ .kind(tool_kind(name))+ .status(ToolCallStatus::Completed)+ .locations(tool_locations(&args, cwd))+ .raw_input(args),+ ));+ }+ }+ Some("tool") => {+ let id = message.get("tool_call_id").and_then(Value::as_str).unwrap_or_default();+ let text = tail(&thread_message_text(message), REPLAY_RESULT_BYTES).to_string();+ out.push(SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(+ id.to_string(),+ ToolCallUpdateFields::new()+ .status(ToolCallStatus::Completed)+ .content(vec![ToolCallContent::from(text)]),+ )));+ }+ _ => {}+ }+ }+ out+}++/// The prompt's blocks as the engine's user content: a plain string when it is+/// all text, else OpenAI content parts, held to the caps every surface uses.+fn prompt_content(blocks: Vec<ContentBlock>) -> Result<Value, Error> {+ let mut parts = Vec::new();+ for block in blocks {+ match block {+ ContentBlock::Text(text) => parts.push(json!({"type":"text","text":text.text})),+ ContentBlock::Image(image) => parts.push(json!({+ "type":"image_url",+ "image_url": {"url": format!("data:{};base64,{}", image.mime_type, image.data), "detail":"auto"},+ })),+ // A link is the user pointing at something; the agent's own tools+ // can open it, so it goes in as a reference rather than contents.+ ContentBlock::ResourceLink(link) => {+ parts.push(json!({"type":"text","text":format!("[@{}]({})", link.name, link.uri)}))+ }+ ContentBlock::Resource(resource) => match resource.resource {+ EmbeddedResourceResource::TextResourceContents(text) => parts.push(json!({+ "type":"text",+ "text":format!("<context uri=\"{}\">\n{}\n</context>", text.uri, text.text),+ })),+ EmbeddedResourceResource::BlobResourceContents(blob) => parts.push(json!({+ "type":"text","text":format!("[@binary]({})", blob.uri),+ })),+ _ => return Err(invalid_params("unsupported embedded resource")),+ },+ // Audio is not advertised in `promptCapabilities`.+ _ => return Err(invalid_params("unsupported prompt content block")),+ }+ }+ if parts.iter().all(|p| p["type"] == "text") {+ let text = parts+ .iter()+ .filter_map(|p| p["text"].as_str())+ .collect::<Vec<_>>()+ .join("\n");+ if text.trim().is_empty() {+ return Err(invalid_params("prompt is empty"));+ }+ return Ok(Value::String(text));+ }+ super::stream_input::check_content_parts(&parts, "prompt").map_err(invalid_params)?;+ Ok(Value::Array(parts))+}++async fn prompt(+ sessions: &Sessions,+ cx: &ConnectionTo<Client>,+ req: PromptRequest,+) -> Result<PromptResponse, Error> {+ let sid = req.session_id.clone();+ let id = sid.0.to_string();+ let content = prompt_content(req.prompt)?;+ let token = CancellationToken::new();+ let (body, args, registry, cwd, window) = {+ let mut map = sessions.lock().await;+ let session = map+ .get_mut(&id)+ .ok_or_else(|| Error::resource_not_found(None).data(json!({"sessionId": id})))?;+ if session.turn.is_some() {+ return Err(Error::invalid_request().data(json!({"message": "a prompt is already running in this session"})));+ }+ session.turn = Some(token.clone());+ session.history.push(json!({"role":"user","content":content}));+ (+ session.agent.body(json!(session.history)),+ session.agent.args.clone(),+ Arc::clone(&session.agent.permission_requests),+ session.cwd.clone(),+ session.agent.limits.context_window,+ )+ };++ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ // The run owns the sender, so the event stream ends exactly when it does.+ let runner = tokio::spawn(async move {+ let tx = tx;+ run_orchestration_steered(&tx, &body, &args, None).await+ });+ let mut map = TurnMap::new(cwd, window);+ let mut asks = tokio::task::JoinSet::new();+ let cancelled = loop {+ tokio::select! {+ biased;+ _ = token.cancelled() => break true,+ Some(_) = asks.join_next(), if !asks.is_empty() => {}+ event = rx.recv() => {+ let Some(event) = event else { break false };+ crate::core::agent::otel::observe(&event);+ let mut gone = false;+ for out in map.map(event) {+ match out {+ Outbound::Update(update) => {+ gone |= cx.send_notification(SessionNotification::new(sid.clone(), update)).is_err();+ }+ Outbound::Permission(ask) => {+ asks.spawn(ask_permission(cx.clone(), sid.clone(), ask, Arc::clone(®istry)));+ }+ }+ }+ // A client that cannot be written to cannot answer either.+ if gone {+ break true;+ }+ }+ }+ };++ let result = if cancelled {+ // Dropping the run drops any tool call in flight; dropping the asks+ // sends `$/cancel_request` for each open prompt, and a dropped decision+ // sender reads as Deny to anything still waiting.+ runner.abort();+ asks.abort_all();+ registry.lock().await.clear();+ None+ } else {+ asks.abort_all();+ Some(runner.await.unwrap_or_else(|e| Err(format!("the run ended without an outcome: {e}"))))+ };++ // Settle the turn's history under the lock, but write it to disk after+ // dropping it: the lock is shared by every session and by+ // `session/cancel`. `turn` stays set until the save is done, so a+ // `session/load` cannot replace the session while its thread is written.+ let (agent_dir, model, history) = {+ let mut map_sessions = sessions.lock().await;+ let session = map_sessions.get_mut(&id).ok_or_else(|| internal("session vanished"))?;+ let completion = result.as_ref().and_then(|r| r.as_ref().ok());+ match completion {+ Some(completion) => adopt_turn_history(&mut session.history, map.history.take(), Some(completion)),+ None => map.settle_interrupted(&mut session.history),+ }+ (agent_dir_for(&session.cwd), session.agent.model.clone(), session.history.clone())+ };+ if !history.is_empty() {+ let thread_id = id.clone();+ let saved = blocking(move || cli_save_thread(&agent_dir, Some(&thread_id), &model, &history, None)).await;+ if let Err(message) = saved.and_then(|r| r.map_err(internal)) {+ log::warn!("ACP: could not save session {id}: {}", message.message);+ }+ }+ if let Some(session) = sessions.lock().await.get_mut(&id) {+ session.turn = None;+ }++ match result {+ None => Ok(PromptResponse::new(StopReason::Cancelled)),+ Some(Ok(_)) => Ok(PromptResponse::new(stop_reason(map.stop_reason.as_deref()))),+ // A failed run is not a failed request: the editor gets the turn's end+ // as `end_turn`, the reason as text it can show, and the log a copy.+ // A JSON-RPC error here would read to a client as a protocol fault.+ Some(Err(message)) => {+ log::warn!("ACP: run failed in session {id}: {message}");+ let _ = cx.send_notification(SessionNotification::new(+ sid,+ SessionUpdate::AgentMessageChunk(text_chunk(format!("\n\nError: {message}"))),+ ));+ Ok(PromptResponse::new(StopReason::EndTurn))+ }+ }+}++/// ACP's stop reason for the `Done` the run ended with. `Done` is the single+/// source: a stop reason is never inferred from the stream going quiet or+/// parsed from an error's text. ACP sessions set no turn cap, so the limit a+/// run can hit is the session's cost ceiling, which `Done` reports as+/// `budget_exceeded` -- a limit, not an error, hence `max_turn_requests`.+fn stop_reason(done: Option<&str>) -> StopReason {+ match done {+ Some("length") => StopReason::MaxTokens,+ Some("content_filter") => StopReason::Refusal,+ Some("budget_exceeded") => StopReason::MaxTurnRequests,+ _ => StopReason::EndTurn,+ }+}++/// Put one gate prompt to the client and settle it in the session's registry.+/// Anything but an allow option -- a reject, a cancelled outcome, an error, a+/// client that went away -- is Deny, which is what a dropped sender means too.+async fn ask_permission(+ cx: ConnectionTo<Client>,+ sid: SessionId,+ ask: PermissionAsk,+ registry: crate::core::agent::r#loop::PermissionRegistry,+) {+ let mut options = vec![PermissionOption::new(ALLOW_ONCE, "Allow", PermissionOptionKind::AllowOnce)];+ if ask.offers_always {+ options.push(PermissionOption::new(ALLOW_ALWAYS, "Always allow", PermissionOptionKind::AllowAlways));+ }+ options.push(PermissionOption::new(REJECT_ONCE, "Reject", PermissionOptionKind::RejectOnce));+ let reply = cx+ .send_request(RequestPermissionRequest::new(sid, ask.tool_call, options))+ .block_task()+ .await;+ let decision = match reply.map(|r| r.outcome) {+ Ok(RequestPermissionOutcome::Selected(selected)) => decision_for(&selected.option_id.0),+ _ => PermissionDecision::Deny,+ };+ // `false` is a prompt the cancel path already cleared: nothing waits on it.+ settle_permission(®istry, &ask.request_id, decision).await;+}++fn decision_for(option_id: &str) -> PermissionDecision {+ match option_id {+ ALLOW_ONCE => PermissionDecision::AllowOnce,+ ALLOW_ALWAYS => PermissionDecision::AllowAlways,+ _ => PermissionDecision::Deny,+ }+}++/// One gate prompt, as the client is to be asked it.+struct PermissionAsk {+ request_id: String,+ tool_call: ToolCallUpdate,+ offers_always: bool,+}++enum Outbound {+ Update(SessionUpdate),+ Permission(PermissionAsk),+}++#[derive(Default)]+struct CallState {+ name: String,+ /// A `tool_call` has gone out for it; later news is a `tool_call_update`.+ announced: bool,+ /// A result arrived; it can no longer be the call a prompt is about.+ finished: bool,+ /// A gate prompt was already matched to it.+ prompted: bool,+ output: String,+ /// The arguments, once whole, and the result: what a cancelled turn folds+ /// back into history.+ args: Option<Value>,+ result: Option<String>,+}++/// Per-turn translation state: which calls the client knows about, their+/// streamed output, and what the run said about how it ended.+struct TurnMap {+ cwd: PathBuf,+ context_window: u64,+ calls: HashMap<String, CallState>,+ /// Call ids in the order they were announced, for matching a gate prompt.+ order: Vec<String>,+ stop_reason: Option<String>,+ history: Option<Vec<Value>>,+ /// The prose streamed since the last published history, kept for a cancel.+ answer: String,+}++impl TurnMap {+ fn new(cwd: PathBuf, context_window: u64) -> Self {+ Self {+ cwd,+ context_window,+ calls: HashMap::new(),+ order: Vec::new(),+ stop_reason: None,+ history: None,+ answer: String::new(),+ }+ }++ /// Leave `history` as a well-formed conversation after a run stopped before+ /// it finished, the way the TUI does on Esc: the latest published history+ /// is adopted, the tool calls made since are folded in with their results+ /// (a call still in flight gets a placeholder), and the partial answer is+ /// kept. A turn that produced nothing is taken back out, so the next prompt+ /// does not put two user turns in a row on the wire -- the cancelled prompt+ /// neither ran nor counted.+ fn settle_interrupted(&mut self, history: &mut Vec<Value>) {+ adopt_turn_history(history, self.history.take(), None);+ let calls: Vec<(String, String, Value)> = self+ .order+ .iter()+ .filter_map(|id| {+ let call = self.calls.get(id)?;+ Some((id.clone(), call.name.clone(), call.args.clone()?))+ })+ .collect();+ let results: Vec<(String, String)> = self+ .calls+ .iter()+ .filter_map(|(id, call)| Some((id.clone(), call.result.clone()?)))+ .collect();+ let before = history.len();+ fold_interrupted_tools(history, &calls, &results);+ let answer = self.answer.trim();+ if !answer.is_empty() {+ history.push(json!({"role":"assistant","content":answer}));+ }+ if history.len() == before+ && history.last().is_some_and(|m| m.get("role").and_then(Value::as_str) == Some("user"))+ {+ history.pop();+ }+ }++ fn call(&mut self, id: &str, name: &str) -> &mut CallState {+ if !self.calls.contains_key(id) {+ self.order.push(id.to_string());+ }+ let call = self.calls.entry(id.to_string()).or_default();+ if call.name.is_empty() {+ call.name = name.to_string();+ }+ call+ }++ /// The `StreamEvent -> session/update` table. No wildcard arm: a variant+ /// added to `StreamEvent` fails the build here until it is decided.+ fn map(&mut self, event: StreamEvent) -> Vec<Outbound> {+ let update = |u| vec![Outbound::Update(u)];+ match event {+ StreamEvent::Token { text } => {+ self.answer.push_str(&text);+ update(SessionUpdate::AgentMessageChunk(text_chunk(text)))+ }+ StreamEvent::Reasoning { text } => update(SessionUpdate::AgentThoughtChunk(text_chunk(text))),+ StreamEvent::ToolCallStarted { id, name } => {+ let call = self.call(&id, &name);+ call.announced = true;+ update(SessionUpdate::ToolCall(+ ToolCall::new(id, name.clone()).kind(tool_kind(&name)).status(ToolCallStatus::Pending),+ ))+ }+ StreamEvent::ToolCall { id, name, args } => {+ let locations = tool_locations(&args, &self.cwd);+ let title = tool_title(&name, &args);+ let kind = tool_kind(&name);+ let call = self.call(&id, &name);+ call.args = Some(args.clone());+ if call.announced {+ update(SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(+ id,+ ToolCallUpdateFields::new()+ .title(title)+ .kind(kind)+ .status(ToolCallStatus::InProgress)+ .locations(locations)+ .raw_input(args),+ )))+ } else {+ // A provider that does not stream tool calls never sent+ // `ToolCallStarted`, so this is the call's first mention.+ call.announced = true;+ update(SessionUpdate::ToolCall(+ ToolCall::new(id, title)+ .kind(kind)+ .status(ToolCallStatus::InProgress)+ .locations(locations)+ .raw_input(args),+ ))+ }+ }+ StreamEvent::ToolOutputDelta { id, delta } => {+ let call = self.call(&id, "");+ call.output.push_str(&delta);+ let keep = tail(&call.output, OUTPUT_TAIL_BYTES).len();+ let cut = call.output.len() - keep;+ call.output.drain(..cut);+ let text = call.output.clone();+ update(SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(+ id,+ ToolCallUpdateFields::new().content(vec![ToolCallContent::from(text)]),+ )))+ }+ StreamEvent::ToolResult { id, content, is_error, diff } => {+ let call = self.call(&id, "");+ call.finished = true;+ call.result = Some(content.clone());+ let mut blocks = vec![ToolCallContent::from(content)];+ blocks.extend(diff.as_deref().map(diff_block));+ let status = if is_error { ToolCallStatus::Failed } else { ToolCallStatus::Completed };+ update(SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(+ id,+ ToolCallUpdateFields::new().status(status).content(blocks),+ )))+ }+ ask @ StreamEvent::PermissionRequest { .. } => {+ self.permission(ask, true).map(Outbound::Permission).into_iter().collect()+ }+ // A subagent shares its parent's permission registry, so its gate+ // prompts have to reach the client or the child waits forever. The+ // child's calls are not the parent's, so the prompt is never pinned+ // to one of the parent's cards. The rest of a child's stream has no+ // ACP home and is dropped.+ StreamEvent::Subagent { event, .. } => {+ self.permission(*event, false).map(Outbound::Permission).into_iter().collect()+ }+ StreamEvent::TodoUpdate { list } => update(SessionUpdate::Plan(plan(&list))),+ StreamEvent::TurnUsage { usage, .. } => {+ let used = usage.total_tokens.unwrap_or_else(|| {+ usage.prompt_tokens.unwrap_or(0) + usage.completion_tokens.unwrap_or(0)+ });+ if self.context_window == 0 || used == 0 {+ Vec::new()+ } else {+ update(SessionUpdate::UsageUpdate(UsageUpdate::new(used, self.context_window)))+ }+ }+ StreamEvent::MessagesUpdated { messages } => {+ // Everything streamed so far is in it, so a cancel from here on+ // folds only what comes after.+ self.history = Some(messages);+ self.answer.clear();+ Vec::new()+ }+ StreamEvent::Done { stop_reason, .. } => {+ self.stop_reason = Some(stop_reason);+ Vec::new()+ }+ // Partial JSON is not a valid `rawInput`; the whole arguments go+ // out with `ToolCall`.+ StreamEvent::ToolCallArgsDelta { .. }+ // The prompt's own response carries a failure.+ | StreamEvent::Error { .. }+ // Internal turn counter.+ | StreamEvent::Step { .. }+ // No standard ACP update, in stable or unstable: dropped rather+ // than carried in an invented extension.+ | StreamEvent::SubagentStart { .. }+ | StreamEvent::SubagentQueued { .. }+ | StreamEvent::SubagentEnd { .. }+ | StreamEvent::SubagentPlan { .. }+ // `ask` is not advertised in an ACP session (no ask registry).+ | StreamEvent::AskRequest { .. }+ | StreamEvent::AskResolved { .. }+ // Display-only, TUI-oriented, or diagnostics for other surfaces.+ | StreamEvent::Notice { .. }+ | StreamEvent::Compaction { .. }+ | StreamEvent::Retry { .. }+ | StreamEvent::Monitors { .. }+ | StreamEvent::Parked+ | StreamEvent::ToolDetails { .. }+ | StreamEvent::RequestProvenance { .. }+ // Host tools are an RPC/stream-json feature; none are declared here.+ | StreamEvent::ToolRequest { .. }+ | StreamEvent::ToolRequestCancelled { .. } => Vec::new(),+ }+ }++ /// Build the client's view of one gate prompt; `None` for any other event.+ /// The prompt names a tool but not the call, so with `match_calls` it is+ /// matched to the oldest open, unprompted call of that tool -- the gate+ /// prompts in call order. Without a match, or for a subagent's prompt, it+ /// stands on its own request id, which a client renders as a fresh card.+ fn permission(&mut self, event: StreamEvent, match_calls: bool) -> Option<PermissionAsk> {+ let StreamEvent::PermissionRequest {+ request_id, tool_name, capability, path, command, diff, offers_always, ..+ } = event+ else {+ return None;+ };+ let tool_name = tool_name.as_str();+ let matched = self+ .order+ .iter()+ .filter(|_| match_calls)+ .find(|id| {+ self.calls+ .get(*id)+ .is_some_and(|c| c.name == tool_name && !c.finished && !c.prompted)+ })+ .cloned();+ if let Some(id) = &matched {+ if let Some(call) = self.calls.get_mut(id) {+ call.prompted = true;+ }+ }+ let title = match (&command, &path) {+ (Some(command), _) => format!("{tool_name}: {command}"),+ (None, Some(path)) => format!("{tool_name} ({capability}) {path}"),+ (None, None) => format!("{tool_name} ({capability})"),+ };+ let mut fields = ToolCallUpdateFields::new().title(title).kind(tool_kind(tool_name));+ if let Some(path) = &path {+ fields = fields.locations(vec![ToolCallLocation::new(absolute(&self.cwd, path))]);+ }+ if let Some(diff) = diff {+ fields = fields.content(vec![diff_block(&diff)]);+ }+ Some(PermissionAsk {+ tool_call: ToolCallUpdate::new(matched.unwrap_or_else(|| request_id.clone()), fields),+ request_id,+ offers_always,+ })+ }+}++/// A unified diff as tool-call content, fenced so a client renders it as one.+fn diff_block(diff: &str) -> ToolCallContent {+ ToolCallContent::from(format!("```diff\n{diff}\n```"))+}++fn text_chunk(text: impl Into<String>) -> ContentChunk {+ ContentChunk::new(ContentBlock::from(text.into()))+}++/// The session todo list as an ACP plan: phases flattened in order. An+/// abandoned task is not work the plan still describes, so it is left out --+/// ACP has no status for it.+fn plan(list: &TodoList) -> Plan {+ let entries = list+ .phases+ .iter()+ .flat_map(|phase| phase.tasks.iter())+ .filter_map(|task| {+ let status = match task.status {+ TodoStatus::Pending => PlanEntryStatus::Pending,+ TodoStatus::InProgress => PlanEntryStatus::InProgress,+ TodoStatus::Completed => PlanEntryStatus::Completed,+ TodoStatus::Abandoned => return None,+ };+ Some(PlanEntry::new(task.content.clone(), PlanEntryPriority::Medium, status))+ })+ .collect();+ Plan::new(entries)+}++/// What kind of work a tool does, for the client's icon and grouping.+fn tool_kind(name: &str) -> ToolKind {+ match name {+ "read" | "ls" | "memory_read" | "memory_list" | "skill_read" | "skill_list" => ToolKind::Read,+ "edit" | "write" | "memory_write" | "skill_write" => ToolKind::Edit,+ "grep" | "find" => ToolKind::Search,+ "bash" => ToolKind::Execute,+ "web_fetch" | "web_search" => ToolKind::Fetch,+ "dispatch_subagent" | "todo" => ToolKind::Think,+ _ => ToolKind::Other,+ }+}++/// A short human title: the command for a shell call, the target for a path+/// or query, else the tool's name.+fn tool_title(name: &str, args: &Value) -> String {+ let arg = |key: &str| args.get(key).and_then(Value::as_str);+ match (arg("command"), arg("path"), arg("pattern").or(arg("query")).or(arg("url"))) {+ (Some(command), _, _) => command.to_string(),+ (None, Some(path), _) => format!("{name} {path}"),+ (None, None, Some(target)) => format!("{name} {target}"),+ _ => name.to_string(),+ }+}++fn tool_locations(args: &Value, cwd: &Path) -> Vec<ToolCallLocation> {+ args.get("path")+ .and_then(Value::as_str)+ .map(|path| vec![ToolCallLocation::new(absolute(cwd, path))])+ .unwrap_or_default()+}++/// ACP locations are absolute; a tool's `path` argument is project-relative.+fn absolute(cwd: &Path, path: &str) -> PathBuf {+ let path = Path::new(path);+ if path.is_absolute() {+ path.to_path_buf()+ } else {+ cwd.join(path)+ }+}++/// The last `max` bytes of `text`, cut on a char boundary.+fn tail(text: &str, max: usize) -> &str {+ if text.len() <= max {+ return text;+ }+ let mut start = text.len() - max;+ while !text.is_char_boundary(start) {+ start += 1;+ }+ &text[start..]+}++#[cfg(test)]+mod tests {+ use super::*;++ fn map() -> TurnMap {+ TurnMap::new(PathBuf::from("/work"), 1000)+ }++ fn wire(out: &Outbound) -> Value {+ match out {+ Outbound::Update(update) => serde_json::to_value(update).unwrap(),+ Outbound::Permission(ask) => json!({+ "permission": ask.request_id,+ "toolCall": serde_json::to_value(&ask.tool_call).unwrap(),+ "always": ask.offers_always,+ }),+ }+ }++ #[test]+ fn the_opt_in_is_off_by_default_and_the_env_wins() {+ assert!(!enabled_from(None, None));+ assert!(enabled_from(None, Some(true)));+ assert!(enabled_from(Some("1"), None));+ assert!(!enabled_from(Some("0"), Some(true)), "an explicit env value wins");+ assert!(enabled_from(Some("maybe"), Some(true)), "an unparseable value is no answer");+ assert!(!enabled_from(Some("maybe"), None));+ }++ /// Every sampled `StreamEvent` either maps to the update the table names+ /// or to nothing. The expected tag is spelled per variant, so a change to+ /// the table shows up here as a diff, not as silence.+ #[test]+ fn every_variant_maps_to_its_update_or_is_dropped() {+ for (variant, event) in crate::core::agent::events::tests::sample_events() {+ let mut map = map();+ // A result or a gate prompt is about a call the client was told of.+ map.map(StreamEvent::ToolCallStarted { id: "t1".into(), name: "read".into() });+ let out: Vec<Value> = map.map(event).iter().map(wire).collect();+ let expected: Option<&str> = match variant {+ "Token" => Some("agent_message_chunk"),+ "Reasoning" => Some("agent_thought_chunk"),+ "ToolCallStarted" => Some("tool_call"),+ "ToolCall" | "ToolOutputDelta" | "ToolResult" => Some("tool_call_update"),+ "TodoUpdate" => Some("plan"),+ "TurnUsage" => Some("usage_update"),+ "PermissionRequest" => Some("permission"),+ // Includes `Subagent`: the sample wraps a non-prompt event.+ _ => None,+ };+ match expected {+ Some("permission") => {+ assert_eq!(out.len(), 1, "{variant}: {out:?}");+ assert!(out[0].get("permission").is_some(), "{variant}: {out:?}");+ }+ Some(tag) => {+ assert_eq!(out.len(), 1, "{variant}: {out:?}");+ assert_eq!(out[0]["sessionUpdate"], tag, "{variant}: {out:?}");+ }+ None => assert!(out.is_empty(), "{variant} must be dropped, got {out:?}"),+ }+ }+ }++ #[test]+ fn a_subagent_gate_prompt_reaches_the_client() {+ let mut map = map();+ let out = map.map(StreamEvent::Subagent {+ run_id: "r".into(),+ name: "scout".into(),+ event: Box::new(StreamEvent::PermissionRequest {+ request_id: "perm-7".into(),+ tool_name: "bash".into(),+ capability: "exec".into(),+ path: None,+ command: Some("ls".into()),+ diff: None,+ prompt_kind: "exec".into(),+ offers_always: false,+ }),+ });+ let wire: Vec<Value> = out.iter().map(wire).collect();+ assert_eq!(wire.len(), 1);+ assert_eq!(wire[0]["permission"], "perm-7");+ assert_eq!(wire[0]["always"], false);+ // No announced call to match, so it stands on its own id.+ assert_eq!(wire[0]["toolCall"]["toolCallId"], "perm-7");+ }++ #[test]+ fn a_gate_prompt_attaches_to_the_oldest_open_call_of_its_tool() {+ let mut map = map();+ for id in ["a", "b"] {+ map.map(StreamEvent::ToolCall { id: id.into(), name: "write".into(), args: json!({"path":"x.txt"}) });+ }+ let ask = |map: &mut TurnMap, n: u8| {+ let out = map.map(StreamEvent::PermissionRequest {+ request_id: format!("perm-{n}"),+ tool_name: "write".into(),+ capability: "write".into(),+ path: Some("x.txt".into()),+ command: None,+ diff: Some("-a\n+b".into()),+ prompt_kind: "write".into(),+ offers_always: true,+ });+ wire(&out[0])+ };+ let first = ask(&mut map, 1);+ assert_eq!(first["toolCall"]["toolCallId"], "a");+ assert_eq!(first["toolCall"]["locations"][0]["path"], "/work/x.txt");+ assert!(first["toolCall"]["content"][0]["content"]["text"].as_str().unwrap().contains("+b"));+ assert_eq!(ask(&mut map, 2)["toolCall"]["toolCallId"], "b");+ }++ #[test]+ fn an_unstreamed_tool_call_is_announced_whole() {+ let mut map = map();+ let out = map.map(StreamEvent::ToolCall {+ id: "c".into(),+ name: "bash".into(),+ args: json!({"command":"cargo test"}),+ });+ let w = wire(&out[0]);+ assert_eq!(w["sessionUpdate"], "tool_call");+ assert_eq!(w["title"], "cargo test");+ assert_eq!(w["kind"], "execute");+ assert_eq!(w["status"], "in_progress");+ }++ #[test]+ fn a_failed_result_is_failed_and_the_done_reason_is_kept() {+ let mut map = map();+ map.map(StreamEvent::ToolCallStarted { id: "t".into(), name: "read".into() });+ let out = map.map(StreamEvent::ToolResult {+ id: "t".into(),+ content: "no such file".into(),+ is_error: true,+ diff: None,+ });+ assert_eq!(wire(&out[0])["status"], "failed");+ map.map(StreamEvent::Done { stop_reason: "length".into(), usage: None });+ assert_eq!(stop_reason(map.stop_reason.as_deref()), StopReason::MaxTokens);+ assert_eq!(stop_reason(Some("stop")), StopReason::EndTurn);+ assert_eq!(stop_reason(None), StopReason::EndTurn);+ }++ #[test]+ fn streamed_output_is_resent_whole_but_bounded() {+ let mut map = map();+ map.map(StreamEvent::ToolOutputDelta { id: "t".into(), delta: "ab".into() });+ let out = map.map(StreamEvent::ToolOutputDelta { id: "t".into(), delta: "cd".into() });+ assert_eq!(wire(&out[0])["content"][0]["content"]["text"], "abcd");+ let big = "x".repeat(OUTPUT_TAIL_BYTES + 10);+ let out = map.map(StreamEvent::ToolOutputDelta { id: "t".into(), delta: big });+ let text = wire(&out[0])["content"][0]["content"]["text"].as_str().unwrap().len();+ assert_eq!(text, OUTPUT_TAIL_BYTES);+ }++ #[test]+ fn an_abandoned_task_is_left_out_of_the_plan() {+ use crate::core::agent::todo::{TodoItem, TodoPhase};+ let list = TodoList {+ phases: vec![TodoPhase {+ name: "p".into(),+ tasks: vec![+ TodoItem { content: "a".into(), status: TodoStatus::Completed },+ TodoItem { content: "b".into(), status: TodoStatus::Abandoned },+ TodoItem { content: "c".into(), status: TodoStatus::InProgress },+ ],+ }],+ };+ let w = serde_json::to_value(plan(&list)).unwrap();+ assert_eq!(w["entries"].as_array().unwrap().len(), 2);+ assert_eq!(w["entries"][1]["status"], "in_progress");+ }++ #[test]+ fn initialize_advertises_only_what_is_consumed() {+ let req: InitializeRequest = serde_json::from_value(json!({+ "protocolVersion": 1,+ "clientCapabilities": {"fs":{"readTextFile":true,"writeTextFile":true},"terminal":true},+ }))+ .unwrap();+ let w = serde_json::to_value(initialize_response(&req)).unwrap();+ assert_eq!(w["protocolVersion"], 1);+ let caps = &w["agentCapabilities"];+ assert_eq!(caps["loadSession"], true);+ assert_eq!(caps["promptCapabilities"]["image"], true);+ assert_eq!(caps["promptCapabilities"]["audio"], false);+ // No MCP transport beyond the mandatory stdio baseline is claimed.+ assert_ne!(caps["mcpCapabilities"]["http"], true);+ assert_ne!(caps["mcpCapabilities"]["sse"], true);+ // No terminal auth method for a client that cannot run one.+ assert_eq!(w["authMethods"], json!([]));++ let future: InitializeRequest = serde_json::from_value(json!({+ "protocolVersion": 9,+ "clientCapabilities": {"auth":{"terminal":true}},+ }))+ .unwrap();+ let w = serde_json::to_value(initialize_response(&future)).unwrap();+ assert_eq!(w["protocolVersion"], 1, "answers with the version it speaks");+ assert_eq!(w["authMethods"][0]["type"], "terminal");+ assert_eq!(w["authMethods"][0]["args"], json!([LOGIN_ARG]));+ }++ #[test]+ fn prompt_blocks_become_engine_content() {+ let text = prompt_content(vec![ContentBlock::from("hi".to_string())]).unwrap();+ assert_eq!(text, json!("hi"));+ let blocks: Vec<ContentBlock> = serde_json::from_value(json!([+ {"type":"text","text":"look"},+ {"type":"image","mimeType":"image/png","data":"AAAA"},+ ]))+ .unwrap();+ let parts = prompt_content(blocks).unwrap();+ assert_eq!(parts[1]["image_url"]["url"], "data:image/png;base64,AAAA");+ let linked: Vec<ContentBlock> = serde_json::from_value(json!([+ {"type":"text","text":"see"},+ {"type":"resource","resource":{"uri":"file:///a.rs","text":"fn main(){}"}},+ ]))+ .unwrap();+ let joined = prompt_content(linked).unwrap();+ assert!(joined.as_str().unwrap().contains("<context uri=\"file:///a.rs\">"));+ assert!(prompt_content(vec![ContentBlock::from(" ".to_string())]).is_err());+ }++ #[test]+ fn replay_redraws_turns_and_tool_calls() {+ let history = vec![+ json!({"role":"user","content":"fix it"}),+ json!({"role":"assistant","content":"","tool_calls":[{"id":"c1","type":"function",+ "function":{"name":"read","arguments":"{\"path\":\"a.rs\"}"}}]}),+ json!({"role":"tool","tool_call_id":"c1","content":"fn a(){}"}),+ json!({"role":"assistant","content":"done"}),+ ];+ let tags: Vec<Value> = replay(&history, Path::new("/work"))+ .iter()+ .map(|u| serde_json::to_value(u).unwrap())+ .collect();+ let names: Vec<&str> = tags.iter().map(|t| t["sessionUpdate"].as_str().unwrap()).collect();+ assert_eq!(names, ["user_message_chunk", "tool_call", "tool_call_update", "agent_message_chunk"]);+ assert_eq!(tags[1]["locations"][0]["path"], "/work/a.rs");+ assert_eq!(tags[1]["status"], "completed");+ }++ #[test]+ fn an_allow_option_is_the_only_way_to_allow() {+ assert_eq!(decision_for(ALLOW_ONCE), PermissionDecision::AllowOnce);+ assert_eq!(decision_for(ALLOW_ALWAYS), PermissionDecision::AllowAlways);+ assert_eq!(decision_for(REJECT_ONCE), PermissionDecision::Deny);+ assert_eq!(decision_for("anything"), PermissionDecision::Deny);+ }++ #[test]+ fn a_client_stdio_mcp_server_maps_to_the_stored_config_shape() {+ let servers: Vec<McpServer> = serde_json::from_value(json!([+ {"name":"fs","command":"/bin/fs-mcp","args":["--stdio"],"env":[{"name":"K","value":"v"}]},+ {"type":"http","name":"web","url":"https://x","headers":[]},+ ]))+ .unwrap();+ let mapped: Vec<_> = servers.into_iter().filter_map(client_mcp_config).collect();+ assert_eq!(mapped.len(), 1, "an unadvertised transport is skipped");+ let (name, config) = &mapped[0];+ assert_eq!(name, "fs");+ assert_eq!(config, &json!({"command":"/bin/fs-mcp","args":["--stdio"],"env":{"K":"v"}}));+ let parsed = crate::core::mcp::models::extract_command_args(config).expect("connectable");+ assert_eq!(parsed.command, "/bin/fs-mcp");+ }++ #[test]+ fn the_stop_reason_comes_from_done_alone() {+ assert_eq!(stop_reason(Some("stop")), StopReason::EndTurn);+ assert_eq!(stop_reason(Some("tool_calls")), StopReason::EndTurn);+ assert_eq!(stop_reason(Some("length")), StopReason::MaxTokens);+ assert_eq!(stop_reason(Some("content_filter")), StopReason::Refusal);+ assert_eq!(stop_reason(Some("budget_exceeded")), StopReason::MaxTurnRequests);+ assert_eq!(stop_reason(None), StopReason::EndTurn);+ }++ #[test]+ fn a_subagent_prompt_is_not_pinned_to_a_parent_call() {+ let mut map = map();+ map.map(StreamEvent::ToolCall { id: "parent".into(), name: "bash".into(), args: json!({"command":"make"}) });+ let out = map.map(StreamEvent::Subagent {+ run_id: "r".into(),+ name: "scout".into(),+ event: Box::new(StreamEvent::PermissionRequest {+ request_id: "perm-9".into(),+ tool_name: "bash".into(),+ capability: "exec".into(),+ path: None,+ command: Some("rm -rf build".into()),+ diff: None,+ prompt_kind: "exec".into(),+ offers_always: false,+ }),+ });+ let w = wire(&out[0]);+ assert_eq!(w["toolCall"]["toolCallId"], "perm-9", "{w}");+ assert_eq!(w["toolCall"]["title"], "bash: rm -rf build");+ assert!(!map.calls["parent"].prompted, "the parent's card is left for its own prompt");+ }++ #[test]+ fn a_cancelled_turn_folds_its_work_into_a_well_formed_history() {+ let mut map = map();+ map.map(StreamEvent::ToolCall { id: "c1".into(), name: "read".into(), args: json!({"path":"a"}) });+ map.map(StreamEvent::ToolResult { id: "c1".into(), content: "A".into(), is_error: false, diff: None });+ map.map(StreamEvent::ToolCall { id: "c2".into(), name: "bash".into(), args: json!({"command":"sleep 9"}) });+ map.map(StreamEvent::Token { text: "partial".into() });+ let mut history = vec![json!({"role":"user","content":"go"})];+ map.settle_interrupted(&mut history);+ let roles: Vec<&str> = history.iter().map(|m| m["role"].as_str().unwrap()).collect();+ assert_eq!(roles, ["user", "assistant", "tool", "tool", "assistant"]);+ assert_eq!(history[2]["content"], "A");+ assert_eq!(history[3]["content"], super::super::MISSING_TOOL_RESULT, "in flight: placeholder");+ assert_eq!(history[4]["content"], "partial");+ }++ #[test]+ fn a_cancelled_turn_that_produced_nothing_is_taken_back() {+ let mut history = vec![+ json!({"role":"user","content":"earlier"}),+ json!({"role":"assistant","content":"ok"}),+ json!({"role":"user","content":"hang"}),+ ];+ map().settle_interrupted(&mut history);+ assert_eq!(history.len(), 2, "no dangling user turn: {history:?}");+ }+}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 9a5388acd..5543d832f 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -3,6 +3,7 @@//! This module is only compiled when the `cli` feature is enabled.mod agent_status;+pub mod acp;pub mod auth;pub mod brand;pub mod browser;@@ -2504,11 +2505,9 @@ async fn apply_input_line(// Taking the sender is what makes a decision single-use: a second// reply for the same id finds nothing and is reported, rather than// silently overwriting an answer the run already acted on.- let sender = registry.lock().await.remove(&request_id);- let Some(sender) = sender else {+ if !crate::core::agent::r#loop::settle_permission(registry, &request_id, decision).await {return Err(format!("no permission request '{request_id}' is pending"));- };- let _ = sender.send(decision);+ }Ok(InputFlow::Decided(request_id, decision))}InputMessage::ToolResult { request_id, result } => {@@ -2792,6 +2791,85 @@ async fn resolve_permission_silently(Some((request_id, decision))}+/// Fold a finished turn into a session's history: the engine's own rewrite of+/// the conversation (tool calls and results included) when it sent one, then+/// the final assistant text when the turn completed. The one rule every+/// multi-turn surface (RPC, ACP) keeps its history by.+pub(crate) fn adopt_turn_history(+ history: &mut Vec<serde_json::Value>,+ updated: Option<Vec<serde_json::Value>>,+ completion: Option<&serde_json::Value>,+) {+ if let Some(updated) = updated {+ *history = updated;+ }+ if let Some(text) = completion.and_then(completion_text) {+ history.push(serde_json::json!({"role":"assistant","content":text}));+ }+}++/// Fold the tool calls an interrupted turn made, and the results it got back,+/// into `history` in wire form, so the next prompt and a later resume see the+/// work that ran rather than only the prose around it. Shared by the surfaces+/// that can stop a run mid-way (the TUI's cancel and error paths, ACP's+/// `session/cancel`).+///+/// `calls` are `(id, name, args)` in the order they were made. A call that is+/// already in `history` is skipped: a run publishes `MessagesUpdated`+/// mid-turn on a compaction retry and the budget soft-stop, and a cancel is+/// often followed by a late event from the aborted task, so the fold can be+/// reached for calls already folded, and putting one exchange on the wire+/// twice invites a double execution. A call with no result (still in flight+/// when the run stopped) gets [`MISSING_TOOL_RESULT`], so the exchange stays+/// protocol-valid.+pub(crate) fn fold_interrupted_tools(+ history: &mut Vec<serde_json::Value>,+ calls: &[(String, String, serde_json::Value)],+ results: &[(String, String)],+) {+ let folded: std::collections::HashSet<&str> = history+ .iter()+ .filter_map(|m| m.get("tool_calls").and_then(|v| v.as_array()))+ .flatten()+ .filter_map(|tc| tc.get("id").and_then(|v| v.as_str()))+ .collect();+ let calls: Vec<&(String, String, serde_json::Value)> =+ calls.iter().filter(|(id, _, _)| !folded.contains(id.as_str())).collect();+ if calls.is_empty() {+ return;+ }+ let tool_calls: serde_json::Value = calls+ .iter()+ .map(|(id, name, args)| {+ serde_json::json!({+ "id": id,+ "type": "function",+ "function": { "name": name, "arguments": args.to_string() },+ })+ })+ .collect();+ history.push(serde_json::json!({+ "role": "assistant",+ "content": serde_json::Value::Null,+ "tool_calls": tool_calls,+ }));+ // Results follow the order of the `tool_calls` array, not the order they+ // finished: the loop dispatches calls concurrently, and a strict endpoint+ // cannot match out-of-order results to the calls above.+ for (id, _, _) in &calls {+ let content = results+ .iter()+ .find(|(rid, _)| rid == id)+ .map(|(_, c)| c.clone())+ .unwrap_or_else(|| MISSING_TOOL_RESULT.to_string());+ history.push(serde_json::json!({+ "role": "tool",+ "tool_call_id": id,+ "content": content,+ }));+ }+}+/// Assistant text of a chat-completion response, if any.fn completion_text(completion: &serde_json::Value) -> Option<String> {let text = completiondiff --git a/src-tauri/src/core/cli/rpc.rs b/src-tauri/src/core/cli/rpc.rsindex bfce65b60..99c2ba05d 100644--- a/src-tauri/src/core/cli/rpc.rs+++ b/src-tauri/src/core/cli/rpc.rs@@ -435,9 +435,7 @@ fn finish_turn(let session = sessions.get_mut(&session_id).ok_or("active session missing")?;- if let Some(history) = updated_history {- session.history = history;- }+ super::adopt_turn_history(&mut session.history, updated_history, result.as_ref().ok());let stop_reason = if interrupted {"interrupted"} else if result.is_ok() {@@ -450,25 +448,18 @@ fn finish_turn(} else {result.as_ref().err().cloned()};- if let Ok(completion) = &result {- if let Some(text) = super::completion_text(completion) {- session- .history- .push(json!({"role":"assistant","content":text}));- }- if !session.ephemeral {- if let Some(project) = session.agent.args.project_root.as_ref() {- if let Err(message) = cli_save_thread(- &agent_dir_for(project),- Some(&session.id),- &session.agent.model,- &session.history,- session.agent.args.host_system_prompt.as_ref().map(|prompt| {- json!({ super::SYSTEM_PROMPT_KEY: prompt })- }),- ) {- error_message = Some(format!("could not save session: {message}"));- }+ if result.is_ok() && !session.ephemeral {+ if let Some(project) = session.agent.args.project_root.as_ref() {+ if let Err(message) = cli_save_thread(+ &agent_dir_for(project),+ Some(&session.id),+ &session.agent.model,+ &session.history,+ session.agent.args.host_system_prompt.as_ref().map(|prompt| {+ json!({ super::SYSTEM_PROMPT_KEY: prompt })+ }),+ ) {+ error_message = Some(format!("could not save session: {message}"));}}}@@ -816,11 +807,11 @@ pub async fn serve() -> Result<(), String> {};if let Some(decision) = decision {let session = sessions.get(&turn.session_id).expect("active session");- match session.agent.permission_requests.lock().await.remove(&request_id) {- Some(sender) => { let _ = sender.send(decision); response(&id, json!({})) }+ match crate::core::agent::r#loop::settle_permission(&session.agent.permission_requests, &request_id, decision).await {+ true => response(&id, json!({})),// Typed like `tool/respond`'s: an id this session never// issued, or already settled, is not pending here.- None => error_data(&id, -32602, &format!("no permission request '{request_id}' is pending (answered, cancelled, or never issued)"), json!({"kind":"not_pending"})),+ false => error_data(&id, -32602, &format!("no permission request '{request_id}' is pending (answered, cancelled, or never issued)"), json!({"kind":"not_pending"})),}} else { error(&id, -32602, "invalid permission decision") }}diff --git a/src-tauri/src/core/cli/rpc_schema.rs b/src-tauri/src/core/cli/rpc_schema.rsindex 084944e13..0fa4000b4 100644--- a/src-tauri/src/core/cli/rpc_schema.rs+++ b/src-tauri/src/core/cli/rpc_schema.rs@@ -5,7 +5,8 @@//! 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.+//! the stream-json records are in that file, and ACP (`jan acp`)+//! uses the upstream ACP schema rather than one of its own.//!//! 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 thediff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex e3b03ad3e..84f330cc2 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -6646,25 +6646,11 @@ impl App {.rposition(|e| matches!(e, DisplayEntry::User { .. })).map(|i| i + 1).unwrap_or(0);- // `display_log` is not cleared by a cancel and the fold is reached from- // several terminal paths, so a call can already be in `history`: the- // backend publishes a mid-turn `MessagesUpdated` on a compaction retry- // and on the budget soft-stop, and a cancel is routinely followed by a- // late `Error` or stream close from the aborted task. Folding it twice- // puts the exchange on the wire twice, which invites a double execution- // and wastes context, so ids already folded are skipped.- let folded: std::collections::HashSet<&str> = self- .history- .iter()- .filter_map(|m| m.get("tool_calls").and_then(|v| v.as_array()))- .flatten()- .filter_map(|tc| tc.get("id").and_then(|v| v.as_str()))- .collect();let mut calls: Vec<(String, String, serde_json::Value)> = Vec::new();let mut results: Vec<(String, String)> = Vec::new();for entry in self.display_log.iter().skip(start) {match entry {- DisplayEntry::ToolCall { id, name, args } if !folded.contains(id.as_str()) => {+ DisplayEntry::ToolCall { id, name, args } => {calls.push((id.clone(), name.clone(), args.clone()));}DisplayEntry::ToolResult { id, content, .. } => {@@ -6673,43 +6659,7 @@ impl App {_ => {}}}- if calls.is_empty() {- return;- }- let tool_calls: serde_json::Value = calls- .iter()- .map(|(id, name, args)| {- serde_json::json!({- "id": id,- "type": "function",- "function": {- "name": name,- "arguments": args.to_string(),- }- })- })- .collect();- self.history.push(serde_json::json!({- "role": "assistant",- "content": serde_json::Value::Null,- "tool_calls": tool_calls,- }));- // Results are paired to the ids of the `tool_calls` array and emitted in- // its order, not in the order they finished: the loop dispatches calls- // concurrently, so an out-of-order or partial completion would otherwise- // hand a strict endpoint results it cannot match to the calls above.- for (id, _, _) in &calls {- let content = results- .iter()- .find(|(rid, _)| rid == id)- .map(|(_, c)| c.clone())- .unwrap_or_else(|| super::MISSING_TOOL_RESULT.to_string());- self.history.push(serde_json::json!({- "role": "tool",- "tool_call_id": id,- "content": content,- }));- }+ super::fold_interrupted_tools(&mut self.history, &calls, &results);}}@@ -7090,7 +7040,7 @@ pub(super) fn format_tokens(tokens: u64) -> String {// as noise. Same half-up tenths rule as the K branch, so no zero decimal.if tokens >= 1_000_000 {let tenths = (tokens + 50_000) / 100_000;- return if tenths % 10 == 0 {+ return if tenths.is_multiple_of(10) {format!("{}M", tenths / 10)} else {format!("{}.{}M", tenths / 10, tenths % 10)@@ -7098,7 +7048,7 @@ pub(super) fn format_tokens(tokens: u64) -> String {}// Tenths of a thousand, half-up. Exact for every u64 below ~1.8e15.let tenths = (tokens + 50) / 100;- if tokens < 10_000 && tenths % 10 != 0 {+ if tokens < 10_000 && !tenths.is_multiple_of(10) {format!("{}.{}K", tenths / 10, tenths % 10)} else {// 6.0K reads as noise; report it as 6K. Above 10K the decimal isdiff --git a/src-tauri/src/core/cli/user_message.rs b/src-tauri/src/core/cli/user_message.rsindex 8c7531853..4e3e4d18f 100644--- a/src-tauri/src/core/cli/user_message.rs+++ b/src-tauri/src/core/cli/user_message.rs@@ -115,7 +115,7 @@ pub(crate) fn data_url_mime_and_len(url: &str) -> Result<(&str, usize), String>/// the real size, which is what the caps are measured against: the line cap is a/// weak proxy for it, since base64 inflates whatever it encodes.pub(crate) fn base64_decoded_len(payload: &str) -> Result<usize, String> {- if payload.len() % 4 != 0 {+ if !payload.len().is_multiple_of(4) {return Err("base64 payload length is not a multiple of 4".to_string());}let padding = payload.bytes().rev().take_while(|b| *b == b'=').count();