Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7686: feat(runtime): add native ZCode protocol support (#9514)
Light Zhao2115a513a375
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 9c9ca125bc..f560765d40 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -279,6 +279,7 @@ The daemon auto-detects these AI CLIs on your PATH:| [Codex](https://github.com/openai/codex) | `codex` | OpenAI's coding agent || [GitHub Copilot CLI](https://docs.github.com/en/copilot) | `copilot` | GitHub's coding agent (model routed by your GitHub entitlement) || OpenCode | `opencode` | Open-source coding agent |+| [ZCode](https://zcode.z.ai/) | `zcode` / ZCode Desktop | Native NDJSON app-server, sessions, model discovery, thinking levels, MCP and yolo execution || OpenClaw | `openclaw` | Open-source coding agent || Hermes | `hermes` | Nous Research coding agent || [Pi](https://pi.dev/) | `pi` | Pi coding agent |diff --git a/README.md b/README.mdindex 0dc574cfd2..e61ca4c57a 100644--- a/README.md+++ b/README.md@@ -192,6 +192,7 @@ authenticated — 26 of them today — so switching providers is a dropdown, not| DeepSeek Harness | `dsh` | Oh-My-Pi | `omp` || MiniMax Code | `mcode` | Dim | `dim` || Huawei Cloud CodeArts | `codearts` | ZeroClaw | `zeroclaw` |+| ZCode | `zcode` / ZCode Desktop | | |Installing and authenticating them: [Install an agent runtime](https://multica.ai/docs/install-agent-runtime) ·[Providers](https://multica.ai/docs/providers)diff --git a/apps/docs/content/docs/install-agent-runtime.mdx b/apps/docs/content/docs/install-agent-runtime.mdxindex 7b79eb16a2..132827fe08 100644--- a/apps/docs/content/docs/install-agent-runtime.mdx+++ b/apps/docs/content/docs/install-agent-runtime.mdx@@ -36,6 +36,7 @@ Multica currently detects these commands:| Kiro CLI | `kiro-cli` | [Install Kiro CLI](https://kiro.dev/docs/cli/installation/) || MiniMax Code | `mcode` | [Install MiniMax Code CLI](https://www.npmjs.com/package/@minimax-ai/code) || Muse Code | `muse` | [Install Muse Code](https://dev.meta.ai/docs/muse-code) |+| ZCode | `zcode` / ZCode Desktop | [ZCode](https://zcode.z.ai/) || OpenClaw | `openclaw` | [Install OpenClaw](https://docs.openclaw.ai/install) || OpenCode | `opencode` | [OpenCode quickstart](https://opencode.ai/en/docs) || Pi coding agent | `pi` | [Pi coding agent](https://github.com/earendil-works/pi) |@@ -215,3 +216,5 @@ If the tool shows as online but runs still fail, open the issue's run record to- [Create and configure an agent](/agents-create) — select the runtime you just connected.- [Daemon and runtimes](/daemon-runtimes) — online status, concurrency, and custom runtimes.- [AI coding tools comparison](/providers) — compare what each tool can do in Multica.++ZCode Desktop on macOS is discovered from its application bundle. Install Node.js and enable a working API connection in the desktop app. Model and reasoning choices are supplied by ZCode itself; see [the runtime comparison](/providers#zcode).diff --git a/apps/docs/content/docs/install-agent-runtime.zh.mdx b/apps/docs/content/docs/install-agent-runtime.zh.mdxindex 93638b1ca3..f830cfd87c 100644--- a/apps/docs/content/docs/install-agent-runtime.zh.mdx+++ b/apps/docs/content/docs/install-agent-runtime.zh.mdx@@ -36,7 +36,7 @@ Multica 当前会检测以下命令:| Kiro CLI | `kiro-cli` | [安装 Kiro CLI](https://kiro.dev/docs/cli/installation/) || MiniMax Code | `mcode` | [安装 MiniMax Code CLI](https://www.npmjs.com/package/@minimax-ai/code) || Muse Code | `muse` | [安装 Muse Code](https://dev.meta.ai/docs/muse-code) |-| Devin CLI | `devin` | [安装 Devin CLI](https://docs.devin.ai/cli/quickstart)(3000.3.22+);本机 ACP,先运行 `devin auth login` |+| ZCode | `zcode` / ZCode Desktop | [ZCode](https://zcode.z.ai/) || OpenClaw | `openclaw` | [安装 OpenClaw](https://docs.openclaw.ai/install) || OpenCode | `opencode` | [OpenCode 快速开始](https://opencode.ai/en/docs) || Pi coding agent | `pi` | [Pi coding agent](https://github.com/earendil-works/pi) |@@ -48,6 +48,7 @@ Multica 当前会检测以下命令:| Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) || TRAE CLI | `traecli` | [TRAE 官方站](https://www.trae.cn/) || Dim | `dim` | [DimCode](https://dimagent.cn/docs/cli) |+| Devin CLI | `devin` | [安装 Devin CLI](https://docs.devin.ai/cli/quickstart)(3000.3.22+);本机 ACP,先运行 `devin auth login` || ZeroClaw | `zeroclaw` | [ZeroClaw 快速开始](https://github.com/zeroclaw-labs/zeroclaw/blob/master/docs/book/src/getting-started/quickstart.md#install) |"受支持"表示 Multica 能够调用对应 CLI,不代表 Multica 会替你提供该工具的账号、订阅或模型额度。@@ -209,3 +210,5 @@ multica daemon restart- [创建和配置智能体](/agents-create) — 选择刚刚连接的运行时。- [守护进程与运行时](/daemon-runtimes) — 了解在线状态、并发和自定义运行时。- [AI 编程工具对照](/providers) — 比较各工具在 Multica 中的能力。++ZCode Desktop 的 macOS 应用包可被自动发现;请同时安装 Node.js,并在桌面端启用可用的 API 连接。模型与思考强度由 ZCode 原生目录提供。详见[运行时对照](/providers#zcode)。diff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdxindex 0aa55c2cc0..89d4cb0a83 100644--- a/apps/docs/content/docs/providers.mdx+++ b/apps/docs/content/docs/providers.mdx@@ -49,6 +49,7 @@ Install steps are in [Install AI coding tools](/install-agent-runtime).| Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` || Dim | `dim` | ✓ | ✓ | ✓ | — || ZeroClaw | `zeroclaw` | ✓ | — | — | — |+| ZCode | `zcode` / ZCode Desktop | ✓ | ✓ | ✓ | `.zcode/skills/` |"Multica-managed MCP" means you can define MCP servers in the agent configuration and Multica passes them to the tool before a run. The column only says whether Multica can configure it for you, not whether the tool has other ways to configure MCP.@@ -113,3 +114,10 @@ For creating and binding skills, see [Skills](/skills).- [Create and configure an agent](/agents-create) — model and thinking-effort settings.- [Install AI coding tools](/install-agent-runtime) — install and detection steps.- [Daemon and runtimes](/daemon-runtimes) — runtime registration and concurrency.++## ZCode++ZCode uses its native NDJSON `app-server` protocol for session creation, resumption, cancellation, model discovery, thinking levels, and MCP. Tasks run in yolo mode without interactive tool approval. Reasoning choices come from the runtime model catalog; creating an agent preserves the selected model's default level.++On macOS the daemon also discovers ZCode Desktop's bundled Node entry point; Node.js must be installed. Enabled desktop API-key/Coding Plan connections are imported into a process-private temporary provider configuration, which is removed on exit without changing the original files. Start Plan identity tokens are not API keys and this account-authentication path is not supported. Configure a working API connection in ZCode Desktop if discovery returns no models.+diff --git a/apps/docs/content/docs/providers.zh.mdx b/apps/docs/content/docs/providers.zh.mdxindex 38e6148321..e6a7f17e8d 100644--- a/apps/docs/content/docs/providers.zh.mdx+++ b/apps/docs/content/docs/providers.zh.mdx@@ -49,6 +49,7 @@ Multica 不替代你在用的 AI 编程工具:运行时调用电脑上已经| Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` || Dim | `dim` | ✓ | ✓ | ✓ | — || ZeroClaw | `zeroclaw` | ✓ | — | — | — |+| ZCode | `zcode` / ZCode Desktop | ✓ | ✓ | ✓ | `.zcode/skills/` |"Multica 管理 MCP"指可以在智能体配置中填写 MCP server,由 Multica 在执行前传给对应工具。这一列只说明 Multica 能否代为配置,不说明工具自身有没有别的 MCP 配置方式。@@ -113,3 +114,9 @@ Codex、Hermes 和 OpenClaw 的处理稍有不同:- [创建和配置智能体](/agents-create) — 模型与思考强度设置。- [安装 AI 编程工具](/install-agent-runtime) — 安装与检测步骤。- [守护进程与运行时](/daemon-runtimes) — 运行时注册与并发。++## ZCode++ZCode 使用原生 NDJSON `app-server` 协议,支持会话创建、续接、取消、模型发现、思考强度和 MCP。任务通过 yolo 模式执行,无需等待交互式工具审批。每个模型的思考档位来自运行时目录,创建智能体时会保留对应默认值。++macOS 可自动发现 ZCode Desktop 内置的 Node 入口;需要本机已安装 Node.js。运行时读取桌面端已启用的 API-key/Coding Plan 连接,为当前进程生成独占临时配置,退出后删除,原配置不变。Start Plan 登录身份令牌不作为 API key 导入,目前不支持这条账号鉴权路径。若模型列表为空,请先在桌面端配置一个可用的 API 连接。diff --git a/apps/web/features/landing/i18n/en.ts b/apps/web/features/landing/i18n/en.tsindex 67c997c3e5..55a3d47d04 100644--- a/apps/web/features/landing/i18n/en.ts+++ b/apps/web/features/landing/i18n/en.ts@@ -104,7 +104,7 @@ export function createEnDict(label: "RUNTIMES",title: "One dashboard for all your compute",description:- "Local daemons and cloud runtimes, managed from a single panel. Real-time monitoring of online/offline status, usage charts, and activity heatmaps. Auto-detects 28 supported coding tools on your machine.",+ "Local daemons and cloud runtimes, managed from a single panel. Real-time monitoring of online/offline status, usage charts, and activity heatmaps. Auto-detects 29 supported coding tools on your machine.",cards: [{title: "Unified runtime panel",@@ -119,7 +119,7 @@ export function createEnDict({title: "Auto-detection on first run",description:- "Multica scans for 28 supported coding tools \u2014 Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, and ZeroClaw \u2014 and registers a runtime for each one it finds.",+ "Multica scans for 29 supported coding tools \u2014 Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, and ZeroClaw, ZCode \u2014 and registers a runtime for each one it finds.",},],},@@ -139,7 +139,7 @@ export function createEnDict({title: "Install the CLI & connect your machine",description:- "Run multica setup \u2014 it walks you through OAuth, starts the daemon, and scans for the 28 supported coding tools (Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, ZeroClaw). Whichever ones you already have installed get registered as runtimes automatically.",+ "Run multica setup \u2014 it walks you through OAuth, starts the daemon, and scans for the 29 supported coding tools (Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, ZeroClaw, ZCode). Whichever ones you already have installed get registered as runtimes automatically.",},{title: "Create your first agent",@@ -196,7 +196,7 @@ export function createEnDict({question: "What coding agents does Multica support?",answer:- "Multica supports 28 coding tools out of the box: Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, and ZeroClaw. The daemon auto-detects whichever CLIs you already have installed and registers a runtime for each one. Since the source code is public, you can also add your own backends. Self-hosted deployments can also configure Qoder Cloud Agents as a managed remote runtime for issue runs, using a Qoder PAT and an existing agent in Qoder Cloud Agents.",+ "Multica supports 29 coding tools out of the box: Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, ZeroClaw, and ZCode. The daemon auto-detects whichever CLIs you already have installed and registers a runtime for each one. Since the source code is public, you can also add your own backends. Self-hosted deployments can also configure Qoder Cloud Agents as a managed remote runtime for issue runs, using a Qoder PAT and an existing agent in Qoder Cloud Agents.",},{question: "Do I need to self-host, or is there a cloud version?",diff --git a/apps/web/features/landing/i18n/ja.ts b/apps/web/features/landing/i18n/ja.tsindex b34504c9eb..dfb170f0a1 100644--- a/apps/web/features/landing/i18n/ja.ts+++ b/apps/web/features/landing/i18n/ja.ts@@ -121,7 +121,7 @@ export function createJaDict({title: "初回起動時に自動検出",description:- "Multica は Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Devin CLI、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw という28種類の対応ツールをスキャンし、見つかったものをそれぞれランタイムとして登録します。",+ "Multica は Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Devin CLI、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw、ZCode という29種類の対応ツールをスキャンし、見つかったものをそれぞれランタイムとして登録します。",},],},@@ -142,7 +142,7 @@ export function createJaDict({title: "CLI をインストールしてマシンを接続",description:- "multica setup を実行すると、OAuth の手順を案内し、デーモンを起動し、28種類の対応コーディングツール(Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Devin CLI、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw)をスキャンします。すでにインストール済みのものは、自動的にランタイムとして登録されます。",+ "multica setup を実行すると、OAuth の手順を案内し、デーモンを起動し、29種類の対応コーディングツール(Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Devin CLI、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw, ZCode)をスキャンします。すでにインストール済みのものは、自動的にランタイムとして登録されます。",},{title: "最初のエージェントを作成",@@ -197,7 +197,7 @@ export function createJaDict({question: "Multica はどのコーディングエージェントに対応していますか?",answer:- "Multica は、Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Devin CLI、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw の28種類のコーディングツールに標準対応しています。デーモンが、すでにインストール済みの CLI を自動検出し、それぞれをランタイムとして登録します。ソースコードが公開されているので、独自のバックエンドを追加することもできます。 セルフホストでは、Qoder PAT と Qoder Cloud Agents の既存エージェントを使い、タスク実行用のマネージドリモートランタイムとして Qoder Cloud Agents を設定できます。",+ "Multica は、Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Devin CLI、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw, ZCode の29種類のコーディングツールに標準対応しています。デーモンが、すでにインストール済みの CLI を自動検出し、それぞれをランタイムとして登録します。ソースコードが公開されているので、独自のバックエンドを追加することもできます。 セルフホストでは、Qoder PAT と Qoder Cloud Agents の既存エージェントを使い、タスク実行用のマネージドリモートランタイムとして Qoder Cloud Agents を設定できます。",},{question: "セルフホストが必須ですか、それともクラウド版もありますか?",diff --git a/apps/web/features/landing/i18n/ko.ts b/apps/web/features/landing/i18n/ko.tsindex 533b644903..40c164df99 100644--- a/apps/web/features/landing/i18n/ko.ts+++ b/apps/web/features/landing/i18n/ko.ts@@ -121,7 +121,7 @@ export function createKoDict({title: "처음 실행할 때 자동 등록",description:- "Multica는 Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, ZeroClaw 등 28개 지원 도구를 스캔해 이미 설치된 것을 런타임으로 자동 등록합니다.",+ "Multica는 Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, ZeroClaw, ZCode 등 29개 지원 도구를 스캔해 이미 설치된 것을 런타임으로 자동 등록합니다.",},],},@@ -197,7 +197,7 @@ export function createKoDict({question: "Multica는 어떤 코딩 에이전트를 지원하나요?",answer:- "Multica는 Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, ZeroClaw 등 28개 코딩 도구를 기본 지원합니다. 데몬이 이미 설치된 CLI를 자동으로 찾아 각각 런타임으로 등록합니다. 소스 코드가 공개되어 있으므로 직접 백엔드를 추가할 수도 있습니다. 셀프 호스팅에서는 Qoder PAT와 Qoder Cloud Agents의 기존 에이전트를 사용하여 태스크 실행용 관리형 원격 런타임으로 Qoder Cloud Agents를 설정할 수 있습니다.",+ "Multica는 Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Devin CLI, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, ZeroClaw, ZCode 등 29개 코딩 도구를 기본 지원합니다. 데몬이 이미 설치된 CLI를 자동으로 찾아 각각 런타임으로 등록합니다. 소스 코드가 공개되어 있으므로 직접 백엔드를 추가할 수도 있습니다. 셀프 호스팅에서는 Qoder PAT와 Qoder Cloud Agents의 기존 에이전트를 사용하여 태스크 실행용 관리형 원격 런타임으로 Qoder Cloud Agents를 설정할 수 있습니다.",},{question: "셀프 호스팅만 가능한가요, 클라우드 버전도 있나요?",diff --git a/apps/web/features/landing/i18n/zh.ts b/apps/web/features/landing/i18n/zh.tsindex ae8471c533..1795a142ad 100644--- a/apps/web/features/landing/i18n/zh.ts+++ b/apps/web/features/landing/i18n/zh.ts@@ -104,7 +104,7 @@ export function createZhDict(label: "\u8fd0\u884c\u65f6",title: "\u4e00\u4e2a\u63a7\u5236\u53f0\u7ba1\u7406\u6240\u6709\u7b97\u529b",description:- "\u672c\u5730\u5b88\u62a4\u8fdb\u7a0b\u548c\u4e91\u7aef\u8fd0\u884c\u65f6\uff0c\u5728\u540c\u4e00\u4e2a\u9762\u677f\u4e2d\u7ba1\u7406\u3002\u5b9e\u65f6\u76d1\u63a7\u5728\u7ebf/\u79bb\u7ebf\u72b6\u6001\u3001\u4f7f\u7528\u91cf\u56fe\u8868\u548c\u6d3b\u52a8\u70ed\u529b\u56fe\u3002\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 28 \u6b3e\u652f\u6301\u7684 AI \u7f16\u7a0b\u5de5\u5177\u3002",+ "\u672c\u5730\u5b88\u62a4\u8fdb\u7a0b\u548c\u4e91\u7aef\u8fd0\u884c\u65f6\uff0c\u5728\u540c\u4e00\u4e2a\u9762\u677f\u4e2d\u7ba1\u7406\u3002\u5b9e\u65f6\u76d1\u63a7\u5728\u7ebf/\u79bb\u7ebf\u72b6\u6001\u3001\u4f7f\u7528\u91cf\u56fe\u8868\u548c\u6d3b\u52a8\u70ed\u529b\u56fe\u3002\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 29 \u6b3e\u652f\u6301\u7684 AI \u7f16\u7a0b\u5de5\u5177\u3002",cards: [{title: "\u7edf\u4e00\u8fd0\u884c\u65f6\u9762\u677f",@@ -119,7 +119,7 @@ export function createZhDict({title: "\u9996\u6b21\u542f\u52a8\u81ea\u52a8\u6ce8\u518c",description:- "Multica \u626b\u63cf\u672c\u673a\u7684 28 \u6b3e\u652f\u6301\u7684 AI \u7f16\u7a0b\u5de5\u5177\u2014\u2014Antigravity\u3001Claude Code\u3001CodeBuddy\u3001CodeArts\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Devin CLI\u3001Dim\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001MiniMax Code\u3001Muse Code\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u3001ZeroClaw\u2014\u2014\u5e76\u4e3a\u6bcf\u6b3e\u5df2\u5b89\u88c5\u7684\u5de5\u5177\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002",+ "Multica \u626b\u63cf\u672c\u673a\u7684 29 \u6b3e\u652f\u6301\u7684 AI \u7f16\u7a0b\u5de5\u5177\u2014\u2014Antigravity\u3001Claude Code\u3001CodeBuddy\u3001CodeArts\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Devin CLI\u3001Dim\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001MiniMax Code\u3001Muse Code\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u3001ZeroClaw、ZCode\u2014\u2014\u5e76\u4e3a\u6bcf\u6b3e\u5df2\u5b89\u88c5\u7684\u5de5\u5177\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002",},],},@@ -139,7 +139,7 @@ export function createZhDict({title: "\u5b89\u88c5 CLI \u5e76\u8fde\u63a5\u4f60\u7684\u673a\u5668",description:- "运行 multica setup——它会引导你完成 OAuth 登录、启动守护进程、并扫描 28 款支持的 AI 编程工具(Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Devin CLI、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw)。本机已安装的工具会被自动注册成运行时。",+ "运行 multica setup——它会引导你完成 OAuth 登录、启动守护进程、并扫描 29 款支持的 AI 编程工具(Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Devin CLI、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw、ZCode)。本机已安装的工具会被自动注册成运行时。",},{title: "\u521b\u5efa\u4f60\u7684\u7b2c\u4e00\u4e2a 智能体",@@ -196,7 +196,7 @@ export function createZhDict({question: "Multica \u652f\u6301\u54ea\u4e9b\u7f16\u7801 智能体\uff1f",answer:- "Multica \u5f00\u7bb1\u5373\u7528\u652f\u6301 28 \u6b3e AI \u7f16\u7a0b\u5de5\u5177\uff1aAntigravity\u3001Claude Code\u3001CodeBuddy\u3001CodeArts\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Devin CLI\u3001Dim\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001MiniMax Code\u3001Muse Code\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u3001ZeroClaw\u3002\u5b88\u62a4\u8fdb\u7a0b\u4f1a\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 CLI \u5e76\u4e3a\u6bcf\u6b3e\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002因为源码公开,你也可以自己添加后端。 自托管部署还可以使用 Qoder PAT 和 Qoder Cloud Agents 中已有的智能体,将 Qoder Cloud Agents 配置为执行任务的托管远端运行时。",+ "Multica \u5f00\u7bb1\u5373\u7528\u652f\u6301 29 \u6b3e AI \u7f16\u7a0b\u5de5\u5177\uff1aAntigravity\u3001Claude Code\u3001CodeBuddy\u3001CodeArts\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Devin CLI\u3001Dim\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001MiniMax Code\u3001Muse Code\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u3001ZeroClaw、ZCode\u3002\u5b88\u62a4\u8fdb\u7a0b\u4f1a\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 CLI \u5e76\u4e3a\u6bcf\u6b3e\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002因为源码公开,你也可以自己添加后端。 自托管部署还可以使用 Qoder PAT 和 Qoder Cloud Agents 中已有的智能体,将 Qoder Cloud Agents 配置为执行任务的托管远端运行时。",},{question: "\u9700\u8981\u81ea\u6258\u7ba1\u5417\uff0c\u8fd8\u662f\u6709\u4e91\u7248\u672c\uff1f",diff --git a/packages/core/agents/mcp-support.test.ts b/packages/core/agents/mcp-support.test.tsindex ca590579b2..39748b6ccb 100644--- a/packages/core/agents/mcp-support.test.ts+++ b/packages/core/agents/mcp-support.test.ts@@ -6,6 +6,7 @@ describe("providerSupportsMcpConfig", () => {it("accepts a provider whose runtime consumes mcp_config", () => {expect(providerSupportsMcpConfig("claude")).toBe(true);expect(providerSupportsMcpConfig("devin")).toBe(true);+ expect(providerSupportsMcpConfig("zcode")).toBe(true);});it("rejects providers whose runtime ignores mcp_config", () => {expect(providerSupportsMcpConfig("antigravity")).toBe(false);diff --git a/packages/core/agents/mcp-support.ts b/packages/core/agents/mcp-support.tsindex 7b244a2900..d6f23ce512 100644--- a/packages/core/agents/mcp-support.ts+++ b/packages/core/agents/mcp-support.ts@@ -29,6 +29,7 @@ const MCP_SUPPORTED_PROVIDERS = new Set(["traecli","dim","omp",+ "zcode",]);export function providerSupportsMcpConfig(provider: string | undefined | null): boolean {diff --git a/packages/core/runtimes/display.test.ts b/packages/core/runtimes/display.test.tsindex d454b1f930..7487941ffc 100644--- a/packages/core/runtimes/display.test.ts+++ b/packages/core/runtimes/display.test.ts@@ -121,6 +121,13 @@ describe("runtimeDisplayLabel", () => {provider: "zeroclaw",}),).toBe("box (ZeroClaw)");+ expect(+ runtimeDisplayLabel({+ name: "ZCode (host)",+ custom_name: "box",+ provider: "zcode",+ }),+ ).toBe("box (ZCode)");});it("first-letter-capitalizes non-overridden slugs, matching the daemon", () => {diff --git a/packages/core/runtimes/display.ts b/packages/core/runtimes/display.tsindex 70d4215553..4bedbfc4d0 100644--- a/packages/core/runtimes/display.ts+++ b/packages/core/runtimes/display.ts@@ -52,6 +52,7 @@ const PROVIDER_DISPLAY_NAMES: Record<string, string> = {muse: "Muse Code",omp: "Oh-My-Pi",zeroclaw: "ZeroClaw",+ zcode: "ZCode",};/**diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 41246a6950..a569f8b2ea 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -139,6 +139,7 @@ export const RUNTIME_PROFILE_PROTOCOL_FAMILIES = ["muse","devin","zeroclaw",+ "zcode",] as const;export type RuntimeProtocolFamily =diff --git a/packages/views/agents/components/inspector/model-capability.ts b/packages/views/agents/components/inspector/model-capability.tsindex ce73f1f656..fa88f84f1e 100644--- a/packages/views/agents/components/inspector/model-capability.ts+++ b/packages/views/agents/components/inspector/model-capability.ts@@ -36,3 +36,15 @@ export function findModelCapabilityEntry((entry) => modelIdForCapabilityLookup(provider, entry.id) === lookupId,);}++/**+ * Providers whose protocol refuses a reasoning-capable model selection that+ * carries no level: zcode's session/create answers -32603 "Reasoning level is+ * required" (verified against the 0.16.9 binary), so the empty+ * "no override / follow CLI config" thinking_level is not a launchable state+ * there. The UI must persist an explicit level — the catalog's+ * `default_level` stands in until the user picks one.+ */+export function thinkingLevelRequiredForProvider(provider: string): boolean {+ return provider === "zcode";+}diff --git a/packages/views/agents/components/inspector/model-change-cleanup.test.ts b/packages/views/agents/components/inspector/model-change-cleanup.test.tsindex e6de0f2fb9..c9f9844f3e 100644--- a/packages/views/agents/components/inspector/model-change-cleanup.test.ts+++ b/packages/views/agents/components/inspector/model-change-cleanup.test.ts@@ -38,6 +38,20 @@ const CLAUDE_MEDIUM_ONLY: RuntimeModel = {thinking: { supported_levels: [{ value: "medium", label: "Medium" }] },};+// zcode's registry always pairs levels with a default; the composite id shape+// matches what discovery reports (providerId/modelId).+const ZCODE_GLM: RuntimeModel = {+ id: "zai-api/GLM-5.3",+ label: "GLM-5.3",+ thinking: {+ supported_levels: [+ { value: "low", label: "low" },+ { value: "max", label: "max" },+ ],+ default_level: "max",+ },+};+describe("buildModelChangeUpdate (MUL-5390)", () => {it("clears overrides the new model does not advertise", () => {expect(@@ -168,4 +182,59 @@ describe("buildModelChangeUpdate (MUL-5390)", () => {}),).toEqual({ model: "gpt-5.4-mini" });});++ // zcode's session/create rejects a reasoning-capable selection without an+ // explicit level, so an empty stored level must never survive a model change.+ it("prefills the catalog default for zcode when no level is stored", () => {+ expect(+ buildModelChangeUpdate({+ provider: "zcode",+ model: "zai-api/GLM-5.3",+ thinkingLevel: "",+ serviceTier: "",+ catalog: [ZCODE_GLM],+ }),+ ).toEqual({ model: "zai-api/GLM-5.3", thinking_level: "max" });+ });++ it("resolves an unsupported zcode level to the catalog default, not empty", () => {+ expect(+ buildModelChangeUpdate({+ provider: "zcode",+ model: "zai-api/GLM-5.3",+ thinkingLevel: "ultra",+ serviceTier: "",+ catalog: [ZCODE_GLM],+ }),+ ).toEqual({ model: "zai-api/GLM-5.3", thinking_level: "max" });+ });++ it("keeps a still-supported zcode level on model change", () => {+ expect(+ buildModelChangeUpdate({+ provider: "zcode",+ model: "zai-api/GLM-5.3",+ thinkingLevel: "low",+ serviceTier: "",+ catalog: [ZCODE_GLM],+ }),+ ).toEqual({ model: "zai-api/GLM-5.3" });+ });++ it("leaves a zcode level unset when the catalog carries no default", () => {+ expect(+ buildModelChangeUpdate({+ provider: "zcode",+ model: "zai-api/GLM-5.3",+ thinkingLevel: "",+ serviceTier: "",+ catalog: [+ {+ ...ZCODE_GLM,+ thinking: { supported_levels: ZCODE_GLM.thinking!.supported_levels },+ },+ ],+ }),+ ).toEqual({ model: "zai-api/GLM-5.3" });+ });});diff --git a/packages/views/agents/components/inspector/model-change-cleanup.ts b/packages/views/agents/components/inspector/model-change-cleanup.tsindex 9adf519982..09d01b6b35 100644--- a/packages/views/agents/components/inspector/model-change-cleanup.ts+++ b/packages/views/agents/components/inspector/model-change-cleanup.ts@@ -1,5 +1,8 @@import type { RuntimeModel } from "@multica/core/types";-import { findModelCapabilityEntry } from "./model-capability";+import {+ findModelCapabilityEntry,+ thinkingLevelRequiredForProvider,+} from "./model-capability";/*** The exact per-model catalog for the agent's runtime, or `null` when it is not@@ -34,6 +37,12 @@ export type ModelChangeUpdate = {* be checked here) leave the stored values untouched — they stay visible in the* inspector so the user can clear them explicitly.*+ * Providers that require an explicit level (zcode) are the one exception to+ * "clear and leave empty": an empty level is not a launchable state there, so+ * the model's advertised `default_level` is what a cleared or never-set value+ * resolves to, keeping the change runnable without inventing a preference the+ * catalog did not state.+ ** Both clears travel with the model in ONE request: a second follow-up write* would leave a window where the agent is persisted with a model/tier* combination the UI never intended.@@ -46,7 +55,14 @@ export function buildModelChangeUpdate(input: {catalog: ModelCatalog;}): ModelChangeUpdate {const update: ModelChangeUpdate = { model: input.model };- if (!input.thinkingLevel && !input.serviceTier) return update;+ const needsThinkingDefault = thinkingLevelRequiredForProvider(input.provider);+ if (+ !input.thinkingLevel &&+ !input.serviceTier &&+ !needsThinkingDefault+ ) {+ return update;+ }if (input.catalog === null || !input.model) return update;const entry = findModelCapabilityEntry(@@ -56,10 +72,20 @@ export function buildModelChangeUpdate(input: {);if (!entry) return update;+ const thinkingDefault = needsThinkingDefault+ ? entry.thinking?.default_level+ : undefined;+const supportsThinking = (entry.thinking?.supported_levels ?? []).some((level) => level.value === input.thinkingLevel,);- if (input.thinkingLevel && !supportsThinking) update.thinking_level = "";+ if (input.thinkingLevel && !supportsThinking) {+ update.thinking_level = thinkingDefault ?? "";+ } else if (!input.thinkingLevel && thinkingDefault) {+ // No stored level: for providers that require one, the catalog default is+ // the value "no override" actually resolves to.+ update.thinking_level = thinkingDefault;+ }const supportsTier =(entry.service_tiers ?? []).some((tier) => tier.id === input.serviceTier) ||diff --git a/packages/views/agents/components/inspector/thinking-picker.tsx b/packages/views/agents/components/inspector/thinking-picker.tsxindex 4953a1ae06..841fa8051b 100644--- a/packages/views/agents/components/inspector/thinking-picker.tsx+++ b/packages/views/agents/components/inspector/thinking-picker.tsx@@ -30,6 +30,7 @@ export function ThinkingPicker({value,levels,canEdit = true,+ allowClear = true,variant = "chip",showLabel = true,onChange,@@ -43,6 +44,8 @@ export function ThinkingPicker({levels: RuntimeModelThinkingLevel[];/** When false, render a static read-only display and skip the popover. */canEdit?: boolean;+ /** ZCode requires an explicit reasoning level for reasoning-capable models. */+ allowClear?: boolean;variant?: "chip" | "field";showLabel?: boolean;onChange: (next: string) => Promise<void> | void;@@ -171,7 +174,7 @@ export function ThinkingPicker({</PickerItem>))}- {value && (+ {value && allowClear && (<TooltipHint label={t(($) => $.pickers.thinking_clear_title)}><buttontype="button"diff --git a/packages/views/agents/components/inspector/thinking-prop-row.test.tsx b/packages/views/agents/components/inspector/thinking-prop-row.test.tsxindex f8f78f3da8..24fa9a9f1e 100644--- a/packages/views/agents/components/inspector/thinking-prop-row.test.tsx+++ b/packages/views/agents/components/inspector/thinking-prop-row.test.tsx@@ -236,6 +236,15 @@ describe("ThinkingPropRow", () => {expect(onChange).toHaveBeenCalledWith("");});+ it("lets a ZCode model without reasoning metadata clear an old level", async () => {+ mockInitiateListModels.mockResolvedValue(listResult([NO_THINKING_MODEL]));+ const { onChange } = renderRow({ provider: "zcode", model: NO_THINKING_MODEL.id, value: "max" });+ await screen.findByText("max");+ fireEvent.click(screen.getByRole("button"));+ fireEvent.click(await screen.findByRole("button", { name: "Follow CLI config" }));+ expect(onChange).toHaveBeenCalledWith("");+ });+it("renders the row with the matched label when the model still advertises the value", async () => {renderRow({ value: "high" });diff --git a/packages/views/agents/components/inspector/thinking-prop-row.tsx b/packages/views/agents/components/inspector/thinking-prop-row.tsxindex 9b8fd5b086..1ccd9e3e95 100644--- a/packages/views/agents/components/inspector/thinking-prop-row.tsx+++ b/packages/views/agents/components/inspector/thinking-prop-row.tsx@@ -8,7 +8,10 @@ import { PropRow } from "../../../common/prop-row";import { SettingsRow } from "../../../settings/components/settings-layout";import { useT } from "../../../i18n";import { ThinkingPicker } from "./thinking-picker";-import { findModelCapabilityEntry } from "./model-capability";+import {+ findModelCapabilityEntry,+ thinkingLevelRequiredForProvider,+} from "./model-capability";/*** Thinking row for the agent inspector. Hidden when the active model has@@ -63,6 +66,7 @@ export function ThinkingPropRow({value={value}levels={levels}canEdit={canEdit}+ allowClear={levels.length === 0 || !thinkingLevelRequiredForProvider(provider)}onChange={onChange}/></PropRow>@@ -106,6 +110,7 @@ export function ThinkingSettingField({value={value}levels={levels}canEdit={canEdit}+ allowClear={levels.length === 0 || !thinkingLevelRequiredForProvider(provider)}onChange={onChange}/></SettingsRow>diff --git a/packages/views/agents/create/agent-configuration-panel.tsx b/packages/views/agents/create/agent-configuration-panel.tsxindex 25bffd0616..a947ba08b3 100644--- a/packages/views/agents/create/agent-configuration-panel.tsx+++ b/packages/views/agents/create/agent-configuration-panel.tsx@@ -1,6 +1,9 @@"use client";import { useEffect, useRef, type ReactNode } from "react";+import {useQuery} from "@tanstack/react-query";+import {runtimeModelsOptions} from "@multica/core/runtimes";+import {findModelCapabilityEntry,thinkingLevelRequiredForProvider} from "../components/inspector/model-capability";import {AGENT_DESCRIPTION_MAX_LENGTH,applyDraftModelChange,@@ -436,6 +439,15 @@ export function AgentExecutionOverrides({}) {const { t } = useT("agents");const runtimeOnline = runtime?.status === "online";+ const modelsQuery = useQuery(runtimeModelsOptions(runtimeOnline && thinkingLevelRequiredForProvider(runtime?.provider ?? "") ? runtime?.id ?? null : null));+ useEffect(() => {+ if (disabled || !thinkingLevelRequiredForProvider(runtime?.provider ?? "")) return;+ if (draft.thinkingLevel || !draft.model || !modelsQuery.isSuccess || !modelsQuery.data?.supported) return;+ const entry = findModelCapabilityEntry(modelsQuery.data.models, draft.model, runtime?.provider ?? "");+ const level = entry?.thinking?.default_level ?? entry?.thinking?.supported_levels[0]?.value;+ if (level) onChange({ ...draft, thinkingLevel: level });+ }, [disabled, draft, modelsQuery.data, modelsQuery.isSuccess, onChange, runtime?.provider]);+return (<><ThinkingSettingFielddiff --git a/packages/views/agents/create/agent-execution-overrides.test.tsx b/packages/views/agents/create/agent-execution-overrides.test.tsxindex 3633ce79a2..dafe223a37 100644--- a/packages/views/agents/create/agent-execution-overrides.test.tsx+++ b/packages/views/agents/create/agent-execution-overrides.test.tsx@@ -122,6 +122,25 @@ describe("AgentExecutionOverrides", () => {afterEach(cleanup);+ it("prefills ZCode's advertised reasoning level without changing other providers", async () => {+ const model: RuntimeModel = {+ id: "desktop/glm", label: "GLM",+ thinking: {+ default_level: "max",+ supported_levels: [{ value: "high", label: "High" }, { value: "max", label: "Max" }],+ },+ };+ mockInitiateListModels.mockResolvedValue(listResult([model]));+ mockGetListModelsResult.mockResolvedValue(listResult([model]));+ const { onChange } = renderOverrides({+ runtime: { ...ONLINE_RUNTIME, provider: "zcode" },+ draft: { ...baseDraft, model: model.id },+ });+ await waitFor(() => expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({ model: model.id, thinkingLevel: "max" }),+ ));+ });+it("offers Speed for a model whose catalog advertises a tier", async () => {const { onChange } = renderOverrides();diff --git a/packages/views/runtimes/components/provider-logo.tsx b/packages/views/runtimes/components/provider-logo.tsxindex 47b3f09c97..a9b960b952 100644--- a/packages/views/runtimes/components/provider-logo.tsx+++ b/packages/views/runtimes/components/provider-logo.tsx@@ -386,6 +386,27 @@ function ZeroClawLogo({ className }: { className: string }) {);}+// Minimal placeholder until ZCode ships an official mark; currentColor keeps+// it legible in both themes. Swap for a real asset when one exists, following+// the DimLogo <img> pattern.+function ZCodeLogo({ className }: { className: string }) {+ return (+ <svg+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className={className}+ >+ <path d="M5 5h14" />+ <path d="M19 19H5" />+ <path d="M19 5L5 19" />+ </svg>+ );+}+export function ProviderLogo({provider,className = "h-4 w-4",@@ -450,6 +471,8 @@ export function ProviderLogo({return <DimLogo className={className} />;case "zeroclaw":return <ZeroClawLogo className={className} />;+ case "zcode":+ return <ZCodeLogo className={className} />;default:return <Monitor className={className} />;}diff --git a/scripts/agent-cli-command-names.txt b/scripts/agent-cli-command-names.txtindex 92a79c0677..69eeb88e31 100644--- a/scripts/agent-cli-command-names.txt+++ b/scripts/agent-cli-command-names.txt@@ -26,3 +26,4 @@ qwenpawreasonixtraeclizeroclaw+zcodediff --git a/server/internal/daemon/agents_probe.go b/server/internal/daemon/agents_probe.goindex 775c8de0e3..3cb3d31140 100644--- a/server/internal/daemon/agents_probe.go+++ b/server/internal/daemon/agents_probe.go@@ -340,6 +340,19 @@ var probeAgentCLIs = func() map[string]AgentEntry {if e, ok := probe("MULTICA_ZEROCLAW_PATH", "zeroclaw", ""); ok {agents["zeroclaw"] = e}+ if e, ok := probe("MULTICA_ZCODE_PATH", "zcode", "MULTICA_ZCODE_MODEL"); ok {+ agents["zcode"] = e+ } else if strings.TrimSpace(os.Getenv("MULTICA_ZCODE_PATH")) == "" {+ for _, candidate := range zcodeDesktopAppBundlePaths() {+ if executableCandidate(candidate) {+ agents["zcode"] = AgentEntry{+ Path: candidate, Command: "zcode",+ Model: os.Getenv("MULTICA_ZCODE_MODEL"),+ }+ break+ }+ }+ }return agents}diff --git a/server/internal/daemon/agents_probe_zcode_bundle_test.go b/server/internal/daemon/agents_probe_zcode_bundle_test.gonew file mode 100644index 0000000000..86caf46512--- /dev/null+++ b/server/internal/daemon/agents_probe_zcode_bundle_test.go@@ -0,0 +1,50 @@+package daemon++import (+ "os"+ "path/filepath"+ "runtime"+ "testing"+)++func TestProbeAgentCLIsDiscoversZCodeAppBundle(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("the ZCode app-bundle fallback is a macOS layout")+ }+ origBundlePaths := zcodeDesktopAppBundlePaths+ t.Cleanup(func() { zcodeDesktopAppBundlePaths = origBundlePaths })+ bundle := filepath.Join(t.TempDir(), "ZCode.app", "Contents", "Resources", "glm", "zcode.cjs")+ if err := os.MkdirAll(filepath.Dir(bundle), 0o755); err != nil {+ t.Fatal(err)+ }+ // A Node script with the executable bit — exactly what the app bundle+ // ships, and what executableCandidate requires on Unix.+ if err := os.WriteFile(bundle, []byte("#!/usr/bin/env node\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ zcodeDesktopAppBundlePaths = func() []string { return []string{bundle} }++ origResolve := resolveAgentsViaLoginShell+ t.Cleanup(func() { resolveAgentsViaLoginShell = origResolve })+ resolveAgentsViaLoginShell = func([]string) map[string]string { return map[string]string{} }+ resetShellResolveCacheForTest(t)++ t.Setenv("HOME", t.TempDir())+ t.Setenv("USERPROFILE", t.TempDir())+ t.Setenv("PATH", t.TempDir())+ t.Setenv("MULTICA_ZCODE_PATH", "")++ entry, ok := probeAgentCLIs()["zcode"]+ if !ok {+ t.Fatal("ZCode was not discovered from its app-bundle fallback path")+ }+ if filepath.Clean(entry.Path) != filepath.Clean(bundle) {+ t.Fatalf("ZCode path = %q, want %q", entry.Path, bundle)+ }+ if entry.Command != "zcode" {+ t.Fatalf("unexpected ZCode entry: %+v", entry)+ }+ if got := providerDisplayName("zcode"); got != "ZCode" {+ t.Fatalf("ZCode display name = %q, want ZCode", got)+ }+}diff --git a/server/internal/daemon/agents_probe_zcode_test.go b/server/internal/daemon/agents_probe_zcode_test.gonew file mode 100644index 0000000000..b9f97000a8--- /dev/null+++ b/server/internal/daemon/agents_probe_zcode_test.go@@ -0,0 +1,65 @@+package daemon++import (+ "os"+ "path/filepath"+ "runtime"+ "testing"+)++// TestDefaultAgentCommandNamesIncludeZcode keeps the shell-fallback probe+// list in lockstep with the MULTICA_ZCODE_PATH probe: without the bare+// command name, a zcode CLI on PATH would only be found via the env override.+func TestDefaultAgentCommandNamesIncludeZcode(t *testing.T) {+ for _, name := range defaultAgentCommandNames {+ if name == "zcode" {+ return+ }+ }+ t.Fatal(`defaultAgentCommandNames does not include "zcode"`)+}++// TestProbeAgentCLIsDiscoversZcodeViaEnvOverride covers the ZCode probe:+// a fake binary wired through MULTICA_ZCODE_PATH registers the "zcode"+// provider, and MULTICA_ZCODE_MODEL seeds the daemon-wide default model —+// ZCode supports per-turn modelSelection on session/send, so unlike zeroclaw+// its probe reads a model env var (see agents_probe.go).+func TestProbeAgentCLIsDiscoversZcodeViaEnvOverride(t *testing.T) {+ fakeDir := t.TempDir()+ name := "zcode-fake"+ content := []byte("#!/bin/sh\nexit 0\n")+ if runtime.GOOS == "windows" {+ name = "zcode-fake.cmd"+ content = []byte("@echo off\r\nexit /b 0\r\n")+ }+ executable := filepath.Join(fakeDir, name)+ if err := os.WriteFile(executable, content, 0o755); err != nil {+ t.Fatal(err)+ }++ origResolve := resolveAgentsViaLoginShell+ t.Cleanup(func() { resolveAgentsViaLoginShell = origResolve })+ resolveAgentsViaLoginShell = func([]string) map[string]string { return map[string]string{} }+ resetShellResolveCacheForTest(t)++ t.Setenv("PATH", t.TempDir())+ t.Setenv("MULTICA_ZCODE_PATH", executable)+ t.Setenv("MULTICA_ZCODE_MODEL", "zai/glm-5.3")++ entry, ok := probeAgentCLIs()["zcode"]+ if !ok {+ t.Fatal("zcode was not discovered via MULTICA_ZCODE_PATH")+ }+ if filepath.Clean(entry.Path) != filepath.Clean(executable) {+ t.Fatalf("zcode path = %q, want %q", entry.Path, executable)+ }+ // With a MULTICA_*_PATH override, Command mirrors the override value (see+ // probe()'s envOrDefault), unlike the bare-command-name path used by the+ // omp/pi test.+ if entry.Command != executable {+ t.Fatalf("zcode command = %q, want %q", entry.Command, executable)+ }+ if entry.Model != "zai/glm-5.3" {+ t.Fatalf("zcode model = %q, want %q", entry.Model, "zai/glm-5.3")+ }+}diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex c185ae75a8..696c588249 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -265,7 +265,7 @@ func LoadConfig(overrides Overrides) (Config, error) {// can re-run the same discovery on a live daemon (MUL-5439).agents := probeAgentCLIs()if len(agents) == 0 && !overrides.AllowNoAgents {- return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codearts, codex, copilot, opencode, deveco, openclaw, hermes, pi, omp, cursor-agent, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, muse, devin, dim, or zeroclaw and ensure it is on PATH")+ return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codearts, codex, copilot, opencode, deveco, openclaw, hermes, pi, omp, cursor-agent, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, muse, devin, dim, zeroclaw, or zcode and ensure it is on PATH")}claudeArgs, err := shellArgsFromEnv("MULTICA_CLAUDE_ARGS")@@ -969,9 +969,22 @@ func isExecutableFile(path string) bool {// doesn't require editing this list by hand.var defaultAgentCommandNames = append([]string{"claude", "codex", "opencode", "codearts", "deveco", "openclaw", "hermes",- "pi", "cursor-agent", "copilot", "kimi", "reasonix", "dsh", "kiro-cli", "codebuddy", "agy", "qodercli", "qoderclicn", "traecli", "grok", "qwen", "qwenpaw", "mcode", "muse", "devin", "dim", "zeroclaw",+ "pi", "cursor-agent", "copilot", "kimi", "reasonix", "dsh", "kiro-cli", "codebuddy", "agy", "qodercli", "qoderclicn", "traecli", "grok", "qwen", "qwenpaw", "mcode", "muse", "devin", "dim", "zeroclaw", "zcode",}, agent.BuiltinRuntimeCommands()...)+// zcodeDesktopAppBundlePaths discovers the CLI in default Desktop installs.+var zcodeDesktopAppBundlePaths = func() []string {+ if runtime.GOOS != "darwin" {+ return nil+ }+ const bundle = "ZCode.app/Contents/Resources/glm/zcode.cjs"+ paths := []string{filepath.Join("/Applications", bundle)}+ if home, err := os.UserHomeDir(); err == nil {+ paths = append(paths, filepath.Join(home, "Applications", bundle))+ }+ return paths+}+// codexDesktopAppBundlePaths returns candidate macOS app-bundle locations for// the bundled Codex CLI. OpenAI relocated the Desktop app from Codex.app to// ChatGPT.app (#5205), then nested the CLI under Resources/codex-cli/bindiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex d3c9c4c79b..be02339f23 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -2096,6 +2096,12 @@ func (d *Daemon) run(ctx context.Context, healthLn net.Listener) error {logFields = append(logFields, "profile", d.cfg.Profile)}d.logger.Info("starting daemon", logFields...)+ // Sweep orphaned ZCode provider credential snapshots left by a prior+ // crash/SIGKILL (prepareZcodeRuntimeEnv writes 0600 files under+ // $TMPDIR/multica-zcode-providers-*; normal exits remove them in defer).+ if n := agent.CleanupStaleZcodeProviderSnapshots(); n > 0 {+ d.logger.Info("removed stale ZCode provider credential snapshots", "count", n)+ }d.logger.Debug("daemon config resolved","daemon_id", d.cfg.DaemonID,"device_name", d.cfg.DeviceName,@@ -6528,6 +6534,7 @@ var runtimeDisplayNameOverrides = map[string]string{"qwenpaw": "QwenPaw","mcode": "MiniMax Code","muse": "Muse Code",+ "zcode": "ZCode","zeroclaw": "ZeroClaw",}diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.goindex e6d9d0691a..835dd34f7a 100644--- a/server/internal/daemon/execenv/context.go+++ b/server/internal/daemon/execenv/context.go@@ -418,6 +418,8 @@ func skillsDirPath(workDir, provider string) string {return filepath.Join(workDir, ".minimax", "skills")case "devin":return filepath.Join(workDir, ".devin", "skills")+ case "zcode":+ return filepath.Join(workDir, ".zcode", "skills")case "muse":// Muse's native project root: https://meta-models.github.io/muse-code-sdk/next/guides/extend/skills/return filepath.Join(workDir, ".agents", "skills")diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.goindex 3e26ad650c..041b16f2a5 100644--- a/server/internal/daemon/execenv/runtime_config.go+++ b/server/internal/daemon/execenv/runtime_config.go@@ -218,7 +218,7 @@ func runtimeConfigPath(workDir, provider string) string {return filepath.Join(workDir, "CODEBUDDY.md")case "qwen":return filepath.Join(workDir, "QWEN.md")- case "codex", "copilot", "opencode", "codearts", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "mcode", "muse", "dim", "zeroclaw", "devin":+ case "codex", "copilot", "opencode", "codearts", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "mcode", "muse", "dim", "zeroclaw", "devin", "zcode":return filepath.Join(workDir, "AGENTS.md")default:return ""diff --git a/server/internal/daemon/local_skills.go b/server/internal/daemon/local_skills.goindex 12fc40af99..5179afdd19 100644--- a/server/internal/daemon/local_skills.go+++ b/server/internal/daemon/local_skills.go@@ -254,6 +254,8 @@ func localSkillRootsForProvider(provider string) ([]localSkillRoot, bool, error)configHome = filepath.Join(home, ".config")}providerRoot = filepath.Join(configHome, "muse", "skills")+ case "zcode":+ providerRoot = filepath.Join(home, ".zcode", "skills")default:return nil, false, nil}diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex 4981604ad4..f727c2aa22 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -79,6 +79,7 @@ var agentGitExcludePatterns = []string{".codebuddy",".pi",".omp",+ ".zcode",}const repoCacheGitTimeout = 10 * time.Minutediff --git a/server/internal/handler/agent_zcode_test.go b/server/internal/handler/agent_zcode_test.gonew file mode 100644index 0000000000..5961ef370f--- /dev/null+++ b/server/internal/handler/agent_zcode_test.go@@ -0,0 +1,39 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestCreateAgentZcodeAcceptsDiscoveredThinkingLevel(t *testing.T) {+ if testHandler == nil {+ t.Skip("requires isolated test database")+ }+ runtimeID := createProviderRuntime(t, "zcode")+ response := httptest.NewRecorder()+ testHandler.CreateAgent(response, newRequest(http.MethodPost, "/api/agents", map[string]any{+ "name": "zcode-thinking-regression",+ "runtime_id": runtimeID,+ "model": "multica-desktop:example/glm",+ "visibility": "private",+ "thinking_level": "max",+ "max_concurrent_tasks": 1,+ }))+ if response.Code != http.StatusCreated {+ t.Fatalf("create ZCode agent: status=%d body=%s", response.Code, response.Body.String())+ }+ var result struct {+ ID string `json:"id"`+ ThinkingLevel string `json:"thinking_level"`+ }+ if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _, _ = testPool.Exec(context.Background(), "DELETE FROM agent WHERE id=$1", result.ID) })+ if result.ThinkingLevel != "max" {+ t.Fatalf("stored reasoning level = %q", result.ThinkingLevel)+ }+}diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex 811fd589e5..83ef783135 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -164,6 +164,7 @@ var ("mcode": "mcode","muse": "muse","zeroclaw": "zeroclaw",+ "zcode": "zcode","multica_agent": "multica_agent","openclaw": "openclaw","opencode": "opencode",diff --git a/server/migrations/610_runtime_profile_add_zcode.down.sql b/server/migrations/610_runtime_profile_add_zcode.down.sqlnew file mode 100644index 0000000000..f97485be52--- /dev/null+++ b/server/migrations/610_runtime_profile_add_zcode.down.sql@@ -0,0 +1,35 @@+-- Restore the pre-ZCode whitelist (includes Devin). NOT VALID leaves+-- historical ZCode rows readable while preventing new ZCode profiles+-- after a database rollback.+ALTER TABLE runtime_profile+ DROP CONSTRAINT IF EXISTS runtime_profile_protocol_family_check,+ ADD CONSTRAINT runtime_profile_protocol_family_check+ CHECK (protocol_family IN (+ 'claude',+ 'codebuddy',+ 'codex',+ 'copilot',+ 'opencode',+ 'codearts',+ 'openclaw',+ 'hermes',+ 'pi',+ 'cursor',+ 'kimi',+ 'reasonix',+ 'dsh',+ 'kiro',+ 'antigravity',+ 'qoder',+ 'qoderclicn',+ 'traecli',+ 'deveco',+ 'grok',+ 'qwen',+ 'qwenpaw',+ 'mcode',+ 'muse',+ 'dim',+ 'zeroclaw',+ 'devin'+ )) NOT VALID;diff --git a/server/migrations/610_runtime_profile_add_zcode.up.sql b/server/migrations/610_runtime_profile_add_zcode.up.sqlnew file mode 100644index 0000000000..f0468ca829--- /dev/null+++ b/server/migrations/610_runtime_profile_add_zcode.up.sql@@ -0,0 +1,35 @@+-- Expand the current whitelist without scanning historical rows. Replacing+-- both parts in one ALTER keeps the constraint present atomically.+ALTER TABLE runtime_profile+ DROP CONSTRAINT IF EXISTS runtime_profile_protocol_family_check,+ ADD CONSTRAINT runtime_profile_protocol_family_check+ CHECK (protocol_family IN (+ 'claude',+ 'codebuddy',+ 'codex',+ 'copilot',+ 'opencode',+ 'codearts',+ 'openclaw',+ 'hermes',+ 'pi',+ 'cursor',+ 'kimi',+ 'reasonix',+ 'dsh',+ 'kiro',+ 'antigravity',+ 'qoder',+ 'qoderclicn',+ 'traecli',+ 'deveco',+ 'grok',+ 'qwen',+ 'qwenpaw',+ 'mcode',+ 'muse',+ 'dim',+ 'zeroclaw',+ 'devin',+ 'zcode'+ )) NOT VALID;diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex a70829ca05..44c0448339 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -423,6 +423,7 @@ var SupportedTypes = []string{"dim","devin","zeroclaw",+ "zcode",}// IsSupportedType reports whether agentType is in the SupportedTypes whitelist.@@ -532,6 +533,8 @@ func New(agentType string, cfg Config) (Backend, error) {return &museBackend{cfg: cfg}, nilcase "zeroclaw":return &zeroclawBackend{cfg: cfg}, nil+ case "zcode":+ return &zcodeBackend{cfg: cfg}, nildefault:return nil, fmt.Errorf("unknown agent type: %q (supported: %s)", agentType, strings.Join(SupportedTypes, ", "))}@@ -581,6 +584,7 @@ var launchHeaders = map[string]string{"mcode": "mcode acp","muse": "muse serve (msp)","zeroclaw": "zeroclaw acp",+ "zcode": "zcode app-server",}// LaunchHeader returns the user-visible launch skeleton for agentType, or andiff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex b3c3af4047..347cd7b556 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -1582,8 +1582,18 @@ func detectCLIVersion(ctx context.Context, runtimeCmd Command) (string, error) {// present. See salvageProbeAnswer.//// Built through runtimeCmd.exec so a custom runtime's fixed_args prefix is- // still applied (MUL-6260).- cmd := runtimeCmd.exec(ctx, "--version")+ // still applied (MUL-6260). Desktop ZCode ships as a Node .cjs/.mjs bundle;+ // those must go through chooseZcodeInvocation (node + script) the same way+ // Execute does, with a clear error when node is missing from PATH.+ var cmd *exec.Cmd+ if isNodeScriptPath(runtimeCmd.Path) {+ if err := requireNodeForZcodeScript(runtimeCmd.Path); err != nil {+ return "", err+ }+ cmd, _, _ = runtimeCmd.execVia(ctx, chooseZcodeInvocation, runtimeCmd.Path, []string{"--version"}, runtimeCmd.logger)+ } else {+ cmd = runtimeCmd.exec(ctx, "--version")+ }hideAgentWindow(cmd)cmd.WaitDelay = probeWaitDelaydata, err := outputOwned(cmd, runtimeCmd.logger)diff --git a/server/pkg/agent/launch.go b/server/pkg/agent/launch.goindex a7009234dd..9a101c67b7 100644--- a/server/pkg/agent/launch.go+++ b/server/pkg/agent/launch.go@@ -470,6 +470,7 @@ var launchPrefixBlockedArgs = map[string]map[string]blockedArgMode{"dim": dimBlockedArgs,"devin": devinBlockedArgs,"zeroclaw": zeroclawBlockedArgs,+ "zcode": zcodeBlockedArgs,}// ValidateCustomArgs rejects arguments that the runtime always discards at launch.diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex 2311b9e549..df66ade37a 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -341,6 +341,18 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C// ModelSelectionSupported. Return an empty list rather than spawning// an ACP subprocess that can only ever come back empty.return Catalog{Models: []Model{}}, nil+ case "zcode":+ // ZCode has no model-catalog command or RPC — the catalog lives only+ // inside a running session's snapshot (settings.model.available,+ // assembled from the logged-in account's provider registry). Discovery+ // spawns a throwaway app-server, creates a deferred draft session and+ // reads the snapshot (discoverZcodeModels, modelled on+ // discoverTraecliModels); any failure degrades to the empty catalog so+ // the UI keeps manual entry in the composite `providerId/modelId`+ // format (see splitZcodeModelSelection).+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discoverZcodeModels(ctx, runtimeCmd)+ })default:return Catalog{}, fmt.Errorf("unknown agent type: %q", providerType)}@@ -442,6 +454,11 @@ func QualifyModelID(catalog Catalog, model string) (string, bool) {// a model-less runtime can opt out in one place, which makes the UI// render a disabled "Managed by runtime" picker instead of an empty// dropdown plus a silently-ignored manual-entry field.+//+// zcode deliberately stays out of the false list: it supports model selection+// end-to-end, but its selection string is the composite `providerId/modelId`+// (the runtime's own picker format, model-selection.ts), split by the backend+// in splitZcodeModelSelection.func ModelSelectionSupported(providerType string) bool {switch providerType {case "qwenpaw", "mcode", "zeroclaw":diff --git a/server/pkg/agent/thinking.go b/server/pkg/agent/thinking.goindex a37a3acef2..39bf4645ce 100644--- a/server/pkg/agent/thinking.go+++ b/server/pkg/agent/thinking.go@@ -1000,6 +1000,7 @@ var thinkingDynamicCatalogProviders = map[string]bool{"grok": true,"opencode": true,"kimi": true,+ "zcode": true,}// acpCatalogThinkingProviders are the ACP runtimes that discover their effortdiff --git a/server/pkg/agent/version.go b/server/pkg/agent/version.goindex 76677a0d43..3a55b9b890 100644--- a/server/pkg/agent/version.go+++ b/server/pkg/agent/version.go@@ -27,6 +27,7 @@ var MinVersions = map[string]string{"muse": "1.4.10", // MSP stable surface: session/start, turn/start, item stream"devin": "3000.3.22", // devin acp --model was introduced in 3000.3.22"zeroclaw": "0.8.0", // persistent ACP sessions and session/resume were added in 0.8.0+ "zcode": "0.16.0", // native NDJSON app-server protocol// opencode: honors TMPDIR/TMP/TEMP from 1.1.54. Earlier builds ignore all// three when their embedded Bun runtime extracts a native module, writing// into the shared system temp dir whatever the daemon exports — one 4-8 MBdiff --git a/server/pkg/agent/zcode.go b/server/pkg/agent/zcode.gonew file mode 100644index 0000000000..5023ad5c28--- /dev/null+++ b/server/pkg/agent/zcode.go@@ -0,0 +1,1486 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os/exec"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "sync/atomic"+ "time"+)++// zcodeProtocolErrorSessionUnavailable is the structured error code the+// ZCode Protocol server raises when session/resume cannot find the requested+// session ("Session not found: ...", zcodeProtocolErrorCodes,+// packages/shared/src/zcode-protocol/index.ts). It is the only signal this+// backend maps to Result.ResumeRejected: the transcript is gone and only a+// fresh session can cure the run.+const zcodeProtocolErrorSessionUnavailable = -32004++const (+ // defaultZcodeHandshakeTimeout bounds the startup RPCs (session/create,+ // session/resume, session/subscribe, session/send). Matches the Codex+ // app-server default: NDJSON over stdio answers in milliseconds once the+ // Node CLI is up, but first-run cold starts pay module-load time.+ defaultZcodeHandshakeTimeout = 30 * time.Second+ // defaultZcodeInterruptGrace bounds how long the backend waits for+ // `turn.completed` with resultType "cancelled" after session/stop before+ // killing the process tree. Codex's measured interrupt-acknowledgement+ // P99 was 15ms (codex_interrupt_latency_integration_test.go); two seconds+ // keeps more than 100x headroom over the observed worst completion.+ defaultZcodeInterruptGrace = 2 * time.Second+)++// zcodeBlockedArgs are flags and subcommands hardcoded by the daemon that+// must not be overridden by user-configured custom_args or a runtime launch+// prefix. `app-server`/`agent-server` select the protocol subcommand+// (apps/zcode-cli/packages/cli/src/arguments.ts isProtocolServerInvocation+// only classifies those positionals as a protocol server); `--prepare-storage`+// is a one-shot storage bootstrap mode, not a server mode; `--surface`+// rewrites telemetry identity; `--prompt`/`-p`, `tui`, `version`,+// `--version`/`-v`, `--help`/`-h` switch out of server mode entirely+// (isProtocolServerInvocation would no longer classify the invocation as a+// protocol server).+var zcodeBlockedArgs = map[string]blockedArgMode{+ "app-server": blockedStandalone,+ "agent-server": blockedStandalone,+ "--prepare-storage": blockedStandalone,+ "--surface": blockedWithValue,+ "--prompt": blockedWithValue,+ "-p": blockedWithValue,+ "tui": blockedStandalone,+ "version": blockedStandalone,+ "--version": blockedStandalone,+ "-v": blockedStandalone,+ "--help": blockedStandalone,+ "-h": blockedStandalone,+}++// zcodeBackend implements Backend by spawning `zcode app-server` and speaking+// the ZCode Protocol: newline-delimited JSON over stdio, with server-pushed+// `session/event` notifications and server-originated requests+// (interaction/requestPermission). Verified against the zcode 0.16.x source+// tree (packages/shared/src/zcode-protocol/index.ts); no initialize handshake+// exists — readiness is the first response to session/create.+//+// Wire-framing notes the implementation depends on:+//+// - Frames are one JSON object per line, but the wire schema+// (zcodeProtocolMessageSchema, index.ts:327-333) is strict and has NO+// `jsonrpc` member: client requests are {id, method, params}, responses+// {id, result|error}, notifications {method, params}. Sending a+// JSON-RPC-2.0 `jsonrpc:"2.0"` member would fail the server's strict+// parse, and the request would be dropped with a -32600 frame instead of+// dispatched.+// - Streaming text arrives as `model.streaming` events (kind:+// text_delta/reasoning_delta, payload carries assistantMessageId and+// partId). The `part.delta` event type exists in the schema but+// mapSessionEventType has no branch that produces it, so it never appears+// on the session/event stream.+// - `message.upserted` is emitted for user, assistant AND system messages+// with no role field on the payload (session-mapper.ts maps+// UserMessage/AssistantMessage/SystemMessage onto it), so every upserted+// event goes through the role discrimination in zcodeRoleFilter before it+// may reach the transcript.+type zcodeBackend struct {+ cfg Config+}++// zcodeMessageStream serializes sends and the final close so a late stdout+// reader cannot send on a closed channel. Mirrors zeroclaw/dim/grok.+type zcodeMessageStream struct {+ ch chan Message+ mu sync.Mutex+ closed bool+}++func newZcodeMessageStream(size int) *zcodeMessageStream {+ return &zcodeMessageStream{ch: make(chan Message, size)}+}++func (s *zcodeMessageStream) send(msg Message) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.closed {+ return+ }+ trySend(s.ch, msg)+}++func (s *zcodeMessageStream) close() {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.closed {+ return+ }+ s.closed = true+ close(s.ch)+}++func (b *zcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {+ execPath := b.cfg.ExecutablePath+ if execPath == "" {+ execPath = "zcode"+ }+ lookedUp, err := exec.LookPath(execPath)+ if err != nil {+ return nil, fmt.Errorf("zcode executable not found at %q: %w", execPath, err)+ }+ if err := requireNodeForZcodeScript(lookedUp); err != nil {+ return nil, err+ }+ runtimeEnv, cleanupConfig, err := prepareZcodeRuntimeEnv(lookedUp, buildEnv(b.cfg.Env))+ if err != nil {+ return nil, err+ }+ configOwnedBySession := false+ defer func() {+ if !configOwnedBySession {+ cleanupConfig()+ }+ }()++ timeout := opts.Timeout+ runCtx, cancel := runContext(ctx, timeout)+ // The process outlives runCtx on daemon cancellation: session/stop must+ // still reach a live server during the interrupt grace, so the command+ // runs on a detached context that cleanup stops explicitly (same shape as+ // codex executeOnce's processCtx).+ processCtx, stopProcess := context.WithCancel(context.WithoutCancel(runCtx))++ zcodeArgs := append([]string{"app-server"}, filterCustomArgs(opts.CustomArgs, zcodeBlockedArgs, b.cfg.Logger)...)+ cmd, _, _ := b.cfg.commandAt(execPath).execVia(processCtx, chooseZcodeInvocation, lookedUp, zcodeArgs, b.cfg.Logger)+ hideAgentWindow(cmd)+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(zcodeArgs, trustAgentCommandPositional(0, "app-server")))+ if opts.Cwd != "" {+ cmd.Dir = opts.Cwd+ }+ cmd.Env = runtimeEnv+ // The app-server is a long-lived process; give cmd.Wait a bounded window+ // after the context is cancelled so descendants that inherit the output+ // pipes cannot hang cleanup forever (same shape as codexProcessWaitDelay).+ cmd.WaitDelay = 10 * time.Second++ stdout, err := cmd.StdoutPipe()+ if err != nil {+ cancel()+ stopProcess()+ return nil, fmt.Errorf("zcode stdout pipe: %w", err)+ }+ stdin, err := cmd.StdinPipe()+ if err != nil {+ cancel()+ stopProcess()+ return nil, fmt.Errorf("zcode stdin pipe: %w", err)+ }+ // StderrPipe + an explicit copier give us a join point (`stderrDone`) that+ // fires before the failure-promotion decision; see hermes.go for why the+ // copy-goroutine form races less than relying on cmd.Stderr under load.+ // The bounded tail feeds error messages when the CLI exits before+ // emitting a structured error.+ stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[zcode:stderr] "), agentStderrTailBytes)+ stderr, err := cmd.StderrPipe()+ if err != nil {+ cancel()+ stopProcess()+ return nil, fmt.Errorf("zcode stderr pipe: %w", err)+ }++ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {+ cancel()+ stopProcess()+ return nil, fmt.Errorf("start zcode: %w", err)+ }++ stderrDone := make(chan struct{})+ go func() {+ defer close(stderrDone)+ _, _ = io.Copy(stderrBuf, stderr)+ }()++ b.cfg.Logger.Info("zcode app-server started", "pid", cmd.Process.Pid, "cwd", opts.Cwd)++ msgStream := newZcodeMessageStream(256)+ resCh := make(chan Result, 1)++ // streamingCurrentTurn gates every session/event so anything the runtime+ // pushes outside our turn — create/subscribe replays, resume transcripts —+ // is dropped instead of landing in the transcript. It must default to+ // false: the server can flush replayed events before it answers the+ // request that triggered them. Flipped to true only just before+ // session/send, and paired with the subscribe acknowledgement's eventSeq+ // baseline as a second guard.+ var streamingCurrentTurn atomic.Bool+ var terminalObserved atomic.Bool++ // The turn input is built before the client so the user-echo+ // discriminator (plan §1.3.1 rule 2) can match it: the backend sends+ // exactly one turn input per run, and the continuity-notice prefix rides+ // in that exact string when the caller supplied one (same contract as+ // codex — the daemon owns the wording and leaves it empty when the prompt+ // already carries the notice).+ userText := prompt+ if opts.ResumeContinuityNotice != "" {+ userText = opts.ResumeContinuityNotice + "\n\n" + prompt+ }+ roleFilter := newZcodeRoleFilter(userText)++ // An empty thinking level is the picker's "Default" — "let the runtime+ // decide". Every other backend implements that by simply omitting the+ // effort flag; zcode cannot: its create rejects a reasoning-capable+ // selection without options.reasoningLevel. So the runtime's decision is+ // resolved here, through the same chain its own client uses (catalog+ // defaultLevel, else the first advertised level — see+ // zcodeResolveThinkingLevel). Resume first uses its authoritative saved+ // model selection below before consulting a new model's catalog default.+ effectiveThinking := opts.ThinkingLevel+ if effectiveThinking == "" && opts.ResumeSessionID == "" {+ if _, _, ok := splitZcodeModelSelection(opts.Model); ok {+ effectiveThinking = zcodeResolveThinkingLevel(ctx, b.cfg.commandAt(execPath), opts.Model)+ if effectiveThinking != "" && b.cfg.Logger != nil {+ b.cfg.Logger.Info("zcode: empty thinking level; using the model's advertised default",+ "backend", "zcode", "model", opts.Model, "thinking_level", effectiveThinking)+ }+ }+ }++ terminalCh := make(chan zcodeTurnOutcome, 4)+ // Delta accounting for the plan §2.5 reconcile. Only the stdout reader+ // goroutine (handleLine → onEvent) touches these, so plain variables are+ // safe: the plan correlates upserted events to the active assistant message+ // by arrival order, and a new assistantMessageId resets the accumulation.+ var activeAssistantID string+ var deltaText strings.Builder++ c := &zcodeClient{+ cfg: b.cfg,+ stdin: stdin,+ pending: make(map[int]*pendingRPC),+ processDone: make(chan struct{}),+ }+ c.onEvent = func(ev zcodeSessionEvent) {+ // Double gate: the in-turn flag plus the subscribe baseline seq.+ if !streamingCurrentTurn.Load() || ev.Seq < c.eventBaseline() {+ return+ }+ switch ev.Type {+ case "turn.completed", "turn.failed":+ out := zcodeParseTurnOutcome(ev)+ if out.terminal {+ terminalObserved.Store(true)+ trySendTerminal(terminalCh, out)+ }+ return+ case "model.streaming":+ var p struct {+ Kind string `json:"kind"`+ Delta string `json:"delta"`+ AssistantMessageID string `json:"assistantMessageId"`+ PartID string `json:"partId"`+ }+ if json.Unmarshal(ev.Payload, &p) != nil {+ return+ }+ switch p.Kind {+ case "text_delta":+ if p.AssistantMessageID != "" && p.AssistantMessageID != activeAssistantID {+ activeAssistantID = p.AssistantMessageID+ deltaText.Reset()+ }+ deltaText.WriteString(p.Delta)+ msgStream.send(Message{Type: MessageText, Content: p.Delta})+ case "reasoning_delta":+ msgStream.send(Message{Type: MessageThinking, Content: p.Delta})+ default:+ // start/finish/error, text_*/reasoning_* boundary frames and+ // tool_input_* previews are ignored: tool lifecycle arrives+ // via tool.updated with authoritative payloads.+ }+ return+ case "message.upserted":+ var p zcodeUpsertedPayload+ if json.Unmarshal(ev.Payload, &p) != nil {+ return+ }+ if !roleFilter.deliver(p) {+ b.cfg.Logger.Debug("zcode message.upserted excluded by role discrimination")+ return+ }+ // The authoritative snapshot reconciles the streamed deltas. The+ // transcript is append-only, so a verbatim match emits nothing, a+ // prefix match emits only the missing suffix, and a divergence+ // falls back to one corrective full text (plan §2.5).+ delivered := deltaText.String()+ switch {+ case p.Content == delivered:+ case strings.HasPrefix(p.Content, delivered):+ if suffix := p.Content[len(delivered):]; suffix != "" {+ msgStream.send(Message{Type: MessageText, Content: suffix})+ }+ default:+ msgStream.send(Message{Type: MessageText, Content: p.Content})+ }+ deltaText.Reset()+ return+ }+ if msg, ok := zcodeEventToMessage(ev); ok {+ msgStream.send(msg)+ }+ }++ readerDone := make(chan struct{})+ go func() {+ defer close(readerDone)+ scanner := newAgentStreamScanner(stdout)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ c.handleLine(line)+ }+ c.closeAllPending(fmt.Errorf("zcode process exited"))+ }()++ configOwnedBySession = true+ go func() {+ defer cleanupConfig()+ defer cancel()+ defer stopProcess()+ defer msgStream.close()+ defer close(resCh)+ defer func() {+ stdin.Close()+ stopProcess()+ _ = cmd.Wait()+ releaseProcessGroup(cmd)+ }()++ startTime := time.Now()+ finalStatus := "completed"+ var finalError string+ var finalOutput string+ var sessionID string+ // Set only when the server structurally refuses the resume+ // (-32004 sessionUnavailable). Handshake/transport failures keep it+ // false: they are not curable by a fresh session, per the+ // Result.ResumeRejected contract in agent.go.+ var resumeRejected bool++ handshakeTimeout := opts.HandshakeTimeout+ if handshakeTimeout == 0 {+ handshakeTimeout = defaultZcodeHandshakeTimeout+ }++ classifyStartupFailure := func(err error, what string) (string, string) {+ switch {+ case ctx.Err() != nil:+ return "aborted", "execution cancelled"+ case errors.Is(runCtx.Err(), context.DeadlineExceeded):+ return "timeout", fmt.Sprintf("zcode timed out during %s: %v", what, err)+ default:+ return "failed", fmt.Sprintf("zcode %s failed: %v", what, err)+ }+ }++ // 1. session/create or session/resume.+ // 2. Early session pin so a cancelled run still preserves the resume+ // pointer.+ // 3. session/subscribe — the legacy session/event stream only flows+ // once deliveryKind is set (server-operations.ts subscribeSession).+ // 4. session/send — returns immediately; the turn streams as events.+ if opts.ResumeSessionID != "" {+ // Desktop 0.17.0's session/resume schema is strict: an unknown+ // "mode" key is rejected with -32602 (Unrecognized key: "mode")+ // and the resume hard-fails. session/create already pins mode+ // "yolo", and the server restores that persisted mode on resume+ // (verified against the Desktop 3.16.3 bundled CLI), so the key+ // must be omitted here. session/create and model discovery still+ // send it — those methods accept it.+ params := map[string]any{+ "sessionId": opts.ResumeSessionID,+ }+ if opts.ThinkingLevel != "" {+ params["thoughtLevel"] = opts.ThinkingLevel+ }+ if mcpServers, err := buildZcodeMcpServers(opts.McpConfig, b.cfg.Logger); err != nil {+ resCh <- Result{Status: "failed", Error: fmt.Sprintf("zcode mcp_config parse failed: %v", err), DurationMs: time.Since(startTime).Milliseconds(), SessionID: opts.ResumeSessionID}+ return+ } else if len(mcpServers) > 0 {+ // Cold resume rebuilds the runtime from scratch, so MCP+ // servers must be re-injected exactly like session/create.+ params["mcpServers"] = mcpServers+ }+ result, err := c.request(runCtx, "session/resume", params, handshakeTimeout)+ if err != nil {+ if zcodeIsSessionUnavailable(err) {+ b.cfg.Logger.Warn("zcode resumed session not found; the daemon will retry fresh",+ "backend", "zcode",+ "requested_session", opts.ResumeSessionID,+ )+ resCh <- Result{+ Status: "failed",+ Error: fmt.Sprintf("zcode session/resume failed: %v", err),+ DurationMs: time.Since(startTime).Milliseconds(),+ SessionID: opts.ResumeSessionID,+ ResumeRejected: true,+ }+ return+ }+ status, msg := classifyStartupFailure(err, "session/resume")+ resCh <- Result{+ Status: status,+ Error: withAgentStderr(msg, "zcode", stderrBuf.Tail()),+ DurationMs: time.Since(startTime).Milliseconds(),+ SessionID: opts.ResumeSessionID,+ }+ return+ }+ sessionID = zcodeSessionIDFromSnapshot(result)+ if sessionID == "" {+ sessionID = opts.ResumeSessionID+ }+ if effectiveThinking == "" {+ effectiveThinking = zcodeSavedThinkingLevel(result, opts.Model)+ if effectiveThinking == "" {+ effectiveThinking = zcodeResolveThinkingLevel(runCtx, b.cfg.commandAt(execPath), opts.Model)+ }+ }+ } else {+ cwd := opts.Cwd+ if cwd == "" {+ cwd = "."+ }+ params := map[string]any{+ "workspace": map[string]any{+ "workspacePath": cwd,+ // TaskID is unique per task, which is all workspaceKey+ // needs: it scopes storage/identity for the session. The+ // server enforces a non-empty key (-32602 on the strict+ // workspace ref schema, caught by the real-binary smoke+ // test), so callers without a task id — direct API use,+ // integration tests — fall back to the resolved workspace+ // directory: stable per checkout, which matches the key's+ // identity role.+ "workspaceKey": zcodeWorkspaceKey(b.cfg.TaskID, cwd),+ },+ // "immediate" is required for cross-run resume: deferred+ // sessions stay drafts that never enter the session store+ // (server-operations.ts reconcileRecordPersistence).+ "persistence": "immediate",+ // Headless execution cannot answer permission prompts. "yolo"+ // auto-approves; any interaction/requestPermission that still+ // arrives is answered deny by the client (fail-closed).+ "mode": "yolo",+ }+ if providerID, modelID, ok := splitZcodeModelSelection(opts.Model); ok {+ params["model"] = zcodeModelSelection(providerID, modelID, effectiveThinking)+ }+ if effectiveThinking != "" {+ params["thoughtLevel"] = effectiveThinking+ }+ if mcpServers, err := buildZcodeMcpServers(opts.McpConfig, b.cfg.Logger); err != nil {+ resCh <- Result{Status: "failed", Error: fmt.Sprintf("zcode mcp_config parse failed: %v", err), DurationMs: time.Since(startTime).Milliseconds()}+ return+ } else if len(mcpServers) > 0 {+ params["mcpServers"] = mcpServers+ }+ result, err := c.request(runCtx, "session/create", params, handshakeTimeout)+ if err != nil {+ status, msg := classifyStartupFailure(err, "session/create")+ resCh <- Result{+ Status: status,+ Error: withAgentStderr(msg, "zcode", stderrBuf.Tail()),+ DurationMs: time.Since(startTime).Milliseconds(),+ }+ return+ }+ sessionID = zcodeSessionIDFromSnapshot(result)+ if sessionID == "" {+ resCh <- Result{+ Status: "failed",+ Error: withAgentStderr("zcode session/create returned no sessionId", "zcode", stderrBuf.Tail()),+ DurationMs: time.Since(startTime).Milliseconds(),+ }+ return+ }+ }++ // Early session pin so a cancelled run still preserves resume pointer.+ msgStream.send(Message{Type: MessageStatus, Status: "running", SessionID: sessionID})+ b.cfg.Logger.Info("zcode session ready", "session_id", sessionID)++ // Subscribe before sending so the baseline seq covers everything the+ // server may flush around session/send. The subscribe response's+ // eventSeq is the lowest seq this client may trust.+ subSeq, err := c.subscribe(runCtx, sessionID, handshakeTimeout)+ if err != nil {+ status, msg := classifyStartupFailure(err, "session/subscribe")+ resCh <- Result{+ Status: status,+ Error: withAgentStderr(msg, "zcode", stderrBuf.Tail()),+ DurationMs: time.Since(startTime).Milliseconds(),+ SessionID: sessionID,+ }+ return+ }+ c.setEventBaseline(subSeq)++ sendParams := map[string]any{+ "sessionId": sessionID,+ "content": userText,+ }+ if providerID, modelID, ok := splitZcodeModelSelection(opts.Model); ok {+ sendParams["modelSelection"] = zcodeModelSelection(providerID, modelID, effectiveThinking)+ }++ streamingCurrentTurn.Store(true)+ if _, err := c.request(runCtx, "session/send", sendParams, handshakeTimeout); err != nil {+ status, msg := classifyStartupFailure(err, "session/send")+ resCh <- Result{+ Status: status,+ Error: withAgentStderr(msg, "zcode", stderrBuf.Tail()),+ DurationMs: time.Since(startTime).Milliseconds(),+ SessionID: sessionID,+ }+ return+ }++ // The turn now streams as session/event notifications. Wait for the+ // terminal event, a daemon cancellation (session/stop then a bounded+ // grace), or the hard run deadline (kill immediately — the plan+ // deliberately does not interrupt-then-wait on the wall clock).+ interruptGrace := opts.TurnInterruptTimeout+ if interruptGrace == 0 {+ interruptGrace = defaultZcodeInterruptGrace+ }+ outcome, stopped := c.awaitTurn(runCtx, terminalCh, sessionID, interruptGrace)+ if stopped {+ finalStatus = "aborted"+ finalError = "execution cancelled"+ if outcome.terminal {+ // The server landed a proper turn completion inside the stop+ // grace window; trust it over the blanket aborted label.+ terminalObserved.Store(true)+ finalStatus = outcome.status()+ finalOutput = outcome.output+ finalError = outcome.errorText+ }+ } else if outcome.terminal {+ finalStatus = outcome.status()+ finalOutput = outcome.output+ finalError = outcome.errorText+ } else if errors.Is(runCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil {+ finalStatus = "timeout"+ finalError = fmt.Sprintf("zcode timed out after %s", timeout)+ } else if ctx.Err() != nil {+ finalStatus = "aborted"+ finalError = "execution cancelled"+ } else {+ // stdout EOF or process exit without a terminal event.+ finalStatus = "failed"+ finalError = withAgentStderr("zcode process exited before the turn completed", "zcode", stderrBuf.Tail())+ }++ terminalObserved.Store(true)+ duration := time.Since(startTime)+ b.cfg.Logger.Info("zcode finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())++ stdin.Close()+ cancel()+ stopProcess()++ // The app-server may keep the pipes open briefly after the terminal+ // event. Bound the drain so cleanup cannot hang.+ drainCtx, drainCancel := context.WithTimeout(context.Background(), defaultZcodeInterruptGrace)+ select {+ case <-readerDone:+ case <-drainCtx.Done():+ }+ select {+ case <-stderrDone:+ case <-drainCtx.Done():+ }+ drainCancel()+ streamingCurrentTurn.Store(false)++ var usageMap map[string]TokenUsage+ if outcome.terminal {+ if usage, ok := zcodeUsageFromSummary(outcome.usageRaw); ok {+ model := opts.Model+ if _, _, ok := splitZcodeModelSelection(opts.Model); !ok {+ model = "unknown"+ }+ usageMap = map[string]TokenUsage{model: usage}+ }+ }++ resCh <- Result{+ Status: finalStatus,+ Output: finalOutput,+ Error: finalError,+ DurationMs: duration.Milliseconds(),+ SessionID: sessionID,+ ResumeRejected: resumeRejected,+ Usage: usageMap,+ }+ }()++ return &Session{+ Messages: msgStream.ch,+ Result: resCh,+ TerminalObserved: terminalObserved.Load,+ }, nil+}++// awaitTurn blocks until the turn reaches a terminal event, the process dies,+// or the run context is done. On daemon cancellation (context cancelled while+// the run deadline has not expired) it first sends session/stop and waits+// interruptGrace for the cancelled turn to land; on hard-deadline expiry it+// returns immediately — the process tree is killed by cmd.Cancel and the plan+// deliberately does not interrupt-then-wait on the wall clock. The second+// return value reports whether the stop path ran, so the caller maps the+// outcome to aborted unless the server reported a proper completion.+func (c *zcodeClient) awaitTurn(runCtx context.Context, terminalCh chan zcodeTurnOutcome, sessionID string, interruptGrace time.Duration) (zcodeTurnOutcome, bool) {+ select {+ case out := <-terminalCh:+ return out, false+ case <-c.processDone:+ return zcodeTurnOutcome{}, false+ case <-runCtx.Done():+ if !errors.Is(runCtx.Err(), context.Canceled) {+ return zcodeTurnOutcome{}, false+ }+ // Daemon/task cancellation: give the server a bounded chance to land+ // a resultType:"cancelled" completion via session/stop. The request+ // runs on a detached context because runCtx is already cancelled.+ stopCtx, stopCancel := context.WithTimeout(context.WithoutCancel(runCtx), interruptGrace)+ defer stopCancel()+ _, _ = c.request(stopCtx, "session/stop", map[string]any{"sessionId": sessionID}, interruptGrace)+ graceTimer := time.NewTimer(interruptGrace)+ defer graceTimer.Stop()+ select {+ case out := <-terminalCh:+ return out, true+ case <-graceTimer.C:+ return zcodeTurnOutcome{}, true+ }+ }+}++// zcodeTurnOutcome is the parsed terminal event for the current turn.+type zcodeTurnOutcome struct {+ terminal bool+ resultType string+ output string+ errorText string+ usageRaw json.RawMessage+}++func (o zcodeTurnOutcome) status() string {+ if !o.terminal {+ return "failed"+ }+ switch o.resultType {+ case "success":+ return "completed"+ case "cancelled":+ // User interruption is a normal end mapped to aborted (plan §2.5).+ return "aborted"+ default:+ // error_max_turns / error_max_budget / error_during_execution /+ // error_max_tool_calls and any unknown future value.+ return "failed"+ }+}++func trySendTerminal(ch chan zcodeTurnOutcome, out zcodeTurnOutcome) {+ select {+ case ch <- out:+ default:+ }+}++// zcodeParseTurnOutcome extracts the fields the backend needs from+// turn.completed / turn.failed payloads. Unknown shapes parse to a non-+// terminal outcome so a malformed event can never strand the run (the+// context/process branches of awaitTurn still fire).+func zcodeParseTurnOutcome(ev zcodeSessionEvent) zcodeTurnOutcome {+ switch ev.Type {+ case "turn.completed":+ var p struct {+ Response string `json:"response"`+ ResultType string `json:"resultType"`+ Usage json.RawMessage `json:"usage"`+ }+ if json.Unmarshal(ev.Payload, &p) != nil {+ return zcodeTurnOutcome{}+ }+ out := zcodeTurnOutcome{terminal: true, resultType: p.ResultType, output: p.Response, usageRaw: p.Usage}+ if p.ResultType != "success" && p.ResultType != "cancelled" {+ out.errorText = fmt.Sprintf("zcode turn completed with resultType %q", p.ResultType)+ }+ return out+ case "turn.failed":+ var p struct {+ Error struct {+ Message string `json:"message"`+ Code string `json:"code"`+ Retryable bool `json:"retryable"`+ Attribution *struct {+ Source string `json:"source"`+ ProviderErrorCode string `json:"providerErrorCode"`+ Retryable bool `json:"retryable"`+ } `json:"attribution"`+ } `json:"error"`+ }+ if json.Unmarshal(ev.Payload, &p) != nil {+ return zcodeTurnOutcome{}+ }+ out := zcodeTurnOutcome{terminal: true, resultType: "error_during_execution", errorText: p.Error.Message}+ if p.Error.Message == "" {+ out.errorText = "zcode turn failed"+ }+ if p.Error.Code != "" {+ out.errorText += fmt.Sprintf(" (code %s)", p.Error.Code)+ }+ if p.Error.Attribution != nil && p.Error.Attribution.ProviderErrorCode != "" {+ out.errorText += fmt.Sprintf(" (provider code %s)", p.Error.Attribution.ProviderErrorCode)+ }+ if p.Error.Retryable || (p.Error.Attribution != nil && (p.Error.Attribution.Retryable || p.Error.Attribution.Source == "network")) {+ // Surface the retryable hint for the platform's retry+ // classification without inventing a bespoke error type (plan §2.5).+ out.errorText += "; provider reports the failure as retryable"+ }+ return out+ }+ return zcodeTurnOutcome{}+}++// zcodeSessionEvent is the subset of the session/event envelope+// (zcodeEventEnvelopeSchema, index.ts:1037-1047) this backend consumes.+// Parsing is deliberately lenient: unknown fields are ignored, because the+// server's own payloads are strict and evolve.+type zcodeSessionEvent struct {+ Type string `json:"type"`+ SessionID string `json:"sessionId"`+ TurnID string `json:"turnId"`+ Seq int64 `json:"seq"`+ Payload json.RawMessage `json:"payload"`+}++// zcodeEventToMessage maps one stateless non-terminal session/event to a+// Message per plan §1.3. model.streaming and message.upserted are deliberately+// NOT handled here: both need per-run state (the delta accumulator and the+// role filter) and are dispatched in Execute's onEvent closure. Unknown event+// types yield no message.+func zcodeEventToMessage(ev zcodeSessionEvent) (Message, bool) {+ switch ev.Type {+ case "turn.started":+ return Message{Type: MessageStatus, Status: "running"}, true+ case "tool.updated":+ var p struct {+ Kind string `json:"kind"`+ ToolCallID string `json:"toolCallId"`+ ToolName string `json:"toolName"`+ Input json.RawMessage `json:"input"`+ Result *struct {+ Content string `json:"content"`+ } `json:"result"`+ Error *struct {+ Message string `json:"message"`+ } `json:"error"`+ }+ if json.Unmarshal(ev.Payload, &p) != nil || p.ToolCallID == "" {+ return Message{}, false+ }+ switch p.Kind {+ case "scheduled", "started":+ input := map[string]any{}+ if len(p.Input) > 0 {+ _ = json.Unmarshal(p.Input, &input)+ }+ return Message{Type: MessageToolUse, Tool: p.ToolName, CallID: p.ToolCallID, Input: input}, true+ case "result":+ if p.Result == nil {+ return Message{}, false+ }+ return Message{Type: MessageToolResult, Tool: p.ToolName, CallID: p.ToolCallID, Output: p.Result.Content}, true+ case "error":+ if p.Error == nil {+ return Message{}, false+ }+ return Message{Type: MessageToolResult, Tool: p.ToolName, CallID: p.ToolCallID, Output: p.Error.Message}, true+ default:+ // progress/batch/raw are ignored for MVP (plan §1.3).+ return Message{}, false+ }+ default:+ // session.updated, checkpoint.created, streamRecovery.updated,+ // permission.requested (answered deny at the transport), part.*,+ // userInput.* etc. are ignored for MVP.+ return Message{}, false+ }+}++// zcodeUpsertedPayload mirrors zcodeMessageUpsertedEventPayloadSchema+// (index.ts:1271-1279). It carries no role and no message id.+type zcodeUpsertedPayload struct {+ Content string `json:"content"`+ Attachments []json.RawMessage `json:"attachments"`+ ToolCalls []json.RawMessage `json:"toolCalls"`+ Type string `json:"type"`+ CompactBoundary json.RawMessage `json:"compactBoundary"`+}++// zcodeRoleFilter implements the plan §1.3.1 layered discrimination for+// message.upserted events. It is stateful per run: the backend sends exactly+// one turn input, so the user echo is a single known string.+//+// Rules (first match wins, an excluded event only logs):+//+// 1. system: payload has `type` ("init"|"compact_boundary"|"interrupted") or+// a compactBoundary → drop. The only wire form with an explicit marker.+// 2. user echo: content equals this run's full sent input exactly → drop,+// first match only. Exact (not prefix) matching avoids dropping an+// assistant answer that quotes the prompt; a second occurrence of the+// same content is delivered (prefer over-delivering to losing assistant+// text).+// 3. assistant: payload has toolCalls (AssistantMessagePayload only) →+// deliver. Presence, not count: an empty array is still assistant.+// 4. fallback: bare {content} → deliver as assistant. User payloads may+// carry optional attachments and are otherwise shape-identical, so the+// source offers no stronger signal; over-delivering a duplicate text is+// cheaper than dropping the assistant's answer.+type zcodeRoleFilter struct {+ sentInput string+ firstEchoMatched bool+}++func newZcodeRoleFilter(sentInput string) *zcodeRoleFilter {+ return &zcodeRoleFilter{sentInput: sentInput}+}++func (f *zcodeRoleFilter) deliver(p zcodeUpsertedPayload) bool {+ if p.Type != "" || len(p.CompactBoundary) > 0 {+ return false // rule 1: system+ }+ if p.Content == f.sentInput && !f.firstEchoMatched {+ f.firstEchoMatched = true+ return false // rule 2: user echo, first occurrence only+ }+ if p.ToolCalls != nil {+ return true // rule 3: assistant (toolCalls present)+ }+ return true // rule 4: fallback delivers+}++// zcodeClient is the ZCode Protocol transport: newline-delimited JSON over+// stdio. Wire frames carry no `jsonrpc` member (see zcodeBackend's doc).+type zcodeClient struct {+ cfg Config++ stdin io.Writer++ mu sync.Mutex+ nextID int+ pending map[int]*pendingRPC+ processDone chan struct{}+ processErr error++ // baselineSeq is the subscribe acknowledgement's eventSeq: events with a+ // smaller seq were emitted before this client subscribed and are replay.+ baselineSeq int64+ baselineSet bool++ onEvent func(zcodeSessionEvent)+}++// eventBaseline returns the seq floor for events this client accepts. Before+// the subscribe acknowledgement lands it returns the maximum int64 so the+// Execute-side gate rejects everything.+func (c *zcodeClient) eventBaseline() int64 {+ c.mu.Lock()+ defer c.mu.Unlock()+ if !c.baselineSet {+ return int64(^uint64(0) >> 1)+ }+ return c.baselineSeq+}++func (c *zcodeClient) setEventBaseline(seq int64) {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.baselineSeq = seq+ c.baselineSet = true+}++// request sends one client→server request and waits for its response.+// timeout > 0 bounds the wait independent of ctx.+func (c *zcodeClient) request(ctx context.Context, method string, params any, timeout time.Duration) (json.RawMessage, error) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ requestCtx := ctx+ cancelRequest := func() {}+ if timeout > 0 {+ requestCtx, cancelRequest = context.WithTimeout(ctx, timeout)+ }+ defer cancelRequest()++ c.mu.Lock()+ if c.processErr != nil {+ err := c.processErr+ c.mu.Unlock()+ return nil, err+ }+ c.nextID+++ id := c.nextID+ pr := &pendingRPC{ch: make(chan rpcResult, 1), method: method}+ c.pending[id] = pr+ c.mu.Unlock()++ msg := map[string]any{+ "id": id,+ "method": method,+ "params": params,+ }+ data, err := json.Marshal(msg)+ if err != nil {+ c.mu.Lock()+ delete(c.pending, id)+ c.mu.Unlock()+ return nil, err+ }+ data = append(data, '\n')+ written := make(chan error, 1)+ go func() {+ _, writeErr := c.stdin.Write(data)+ written <- writeErr+ }()+ select {+ case err = <-written:+ case <-requestCtx.Done():+ // Closing the owned pipe unblocks a write when the child has stopped+ // reading. The execution owner then terminates and reaps the tree.+ if closer, ok := c.stdin.(io.Closer); ok {+ _ = closer.Close()+ }+ err = requestCtx.Err()+ }+ if err != nil {+ c.mu.Lock()+ delete(c.pending, id)+ c.mu.Unlock()+ return nil, fmt.Errorf("write %s: %w", method, err)+ }++ select {+ case res := <-pr.ch:+ return res.result, res.err+ case <-c.processDone:+ select {+ case res := <-pr.ch:+ return res.result, res.err+ default:+ }+ c.mu.Lock()+ delete(c.pending, id)+ err := c.processErr+ c.mu.Unlock()+ if requestCtx.Err() != nil {+ return nil, fmt.Errorf("%s aborted: %w", method, requestCtx.Err())+ }+ if err == nil {+ err = fmt.Errorf("zcode process exited during %s", method)+ }+ return nil, err+ case <-requestCtx.Done():+ c.mu.Lock()+ delete(c.pending, id)+ c.mu.Unlock()+ return nil, fmt.Errorf("%s aborted: %w", method, requestCtx.Err())+ }+}++// subscribe registers the desktop-continuous delivery and returns the event+// seq baseline. Without it the server never pushes session/event+// (server-operations.ts gates the push on record.deliveryKind).+func (c *zcodeClient) subscribe(ctx context.Context, sessionID string, timeout time.Duration) (int64, error) {+ result, err := c.request(ctx, "session/subscribe", map[string]any{+ "sessionId": sessionID,+ "deliveryKind": "desktop-continuous",+ }, timeout)+ if err != nil {+ return 0, err+ }+ var r struct {+ EventSeq int64 `json:"eventSeq"`+ }+ if json.Unmarshal(result, &r) != nil {+ return 0, fmt.Errorf("session/subscribe returned no eventSeq")+ }+ return r.EventSeq, nil+}++// zcodeRPCError mirrors the server's error object on a response frame.+type zcodeRPCError struct {+ Code int `json:"code"`+ Message string `json:"message"`+}++func (e *zcodeRPCError) Error() string {+ return fmt.Sprintf("rpc error %d: %s", e.Code, e.Message)+}++// zcodeIsSessionUnavailable reports whether err is the server's structured+// "Session not found" rejection (-32004), the only resume failure a fresh+// session can cure.+func zcodeIsSessionUnavailable(err error) bool {+ var rpcErr *zcodeRPCError+ if err != nil && errors.As(err, &rpcErr) && rpcErr != nil {+ return rpcErr.Code == zcodeProtocolErrorSessionUnavailable+ }+ return false+}++func (c *zcodeClient) respond(id json.RawMessage, result any) {+ c.writeFrame(map[string]any{"id": json.RawMessage(id), "result": result})+}++// zcodeRuntimePreferencesDefaults answers the server-originated+// session/requestRuntimePreferences request: a real app-server asks for the+// host's runtime preferences while serving session/create and treats a silent+// client as a hard failure (-32022 after its 15s timeout, verified against+// the 0.16.9 binary). Every member except nativeSearchEnhancementsEnabled+// carries a schema default; the values mirror a plain headless host — no+// native search integration, no memory, auto-resolving ask-user questions+// (there is no UI to answer them), and the current default budget strategy.+func zcodeRuntimePreferencesDefaults() map[string]any {+ return map[string]any{+ "nativeSearchEnhancementsEnabled": false,+ "memoryEnabled": false,+ "askUserQuestionAutoResolutionEnabled": true,+ "modelContextBudgetStrategy": "preflight-v1",+ }+}++// zcodeWriteReverseResult / zcodeWriteReverseUnsupported are the standalone+// (non-client) reverse-request answers used by model discovery, which owns+// its stdin rather than a zcodeClient.+func zcodeWriteReverseResult(w io.Writer, id json.RawMessage, result any) {+ data, err := json.Marshal(map[string]any{"id": json.RawMessage(id), "result": result})+ if err != nil {+ return+ }+ data = append(data, '\n')+ _, _ = w.Write(data)+}++// zcodeWriteReverseUnsupported / zcodeWriteReverseError answer a server-+// originated request the standalone (non-client) discovery loop cannot+// handle. The wire schema (zcodeProtocolMessageSchema) is strict about the+// response shape {id, result|error}: the error must sit at the top level,+// not nested inside result.+func zcodeWriteReverseUnsupported(w io.Writer, id json.RawMessage, method string) {+ zcodeWriteReverseError(w, id, -32601, fmt.Sprintf("method not supported by multica: %s", method))+}++func zcodeWriteReverseError(w io.Writer, id json.RawMessage, code int, message string) {+ data, err := json.Marshal(map[string]any{+ "id": json.RawMessage(id),+ "error": map[string]any{"code": code, "message": message},+ })+ if err != nil {+ return+ }+ data = append(data, '\n')+ _, _ = w.Write(data)+}++func (c *zcodeClient) respondError(id json.RawMessage, code int, message string) {+ c.writeFrame(map[string]any{+ "id": json.RawMessage(id),+ "error": map[string]any{+ "code": code,+ "message": message,+ },+ })+}++func (c *zcodeClient) writeFrame(msg map[string]any) {+ data, err := json.Marshal(msg)+ if err != nil {+ return+ }+ data = append(data, '\n')+ _, _ = c.stdin.Write(data)+}++func (c *zcodeClient) closeAllPending(err error) {+ c.mu.Lock()+ if c.processErr == nil {+ c.processErr = err+ }+ select {+ case <-c.processDone:+ // Already closed.+ default:+ close(c.processDone)+ }+ pending := c.pending+ c.pending = make(map[int]*pendingRPC)+ c.mu.Unlock()+ for _, pr := range pending {+ select {+ case pr.ch <- rpcResult{err: err}:+ default:+ }+ }+}++// handleLine dispatches one wire frame. Three shapes reach here:+// - {id, method, params}: a server-originated request. interaction/+// requestPermission is answered {"decision":"deny"} fail-closed (the+// headless client cannot approve); session/requestRuntimePreferences is+// answered with zcodeRuntimePreferencesDefaults (an unanswered request+// fails session/create with -32022 after its 15s timeout); every other+// method gets -32601.+// - {id, result|error}: a response to one of our requests.+// - {method, params}: a notification; only session/event is consumed.+func (c *zcodeClient) handleLine(line string) {+ var msg struct {+ ID json.RawMessage `json:"id"`+ Method string `json:"method"`+ Params json.RawMessage `json:"params"`+ Result json.RawMessage `json:"result"`+ Error *zcodeRPCError `json:"error"`+ }+ if err := json.Unmarshal([]byte(line), &msg); err != nil {+ if c.cfg.Logger != nil {+ c.cfg.Logger.Debug("zcode unparseable frame", "line", truncateZcodeLogLine(line))+ }+ return+ }+ hasID := len(msg.ID) > 0 && string(msg.ID) != "null"+ switch {+ case hasID && msg.Method != "":+ // Server-originated request.+ switch msg.Method {+ case "interaction/requestPermission":+ c.respond(msg.ID, map[string]any{"decision": "deny"})+ case "session/requestRuntimePreferences":+ c.respond(msg.ID, zcodeRuntimePreferencesDefaults())+ default:+ c.respondError(msg.ID, -32601, fmt.Sprintf("method not supported by multica: %s", msg.Method))+ }+ case hasID:+ // Response to one of our requests. Our ids are plain ints.+ var id int+ if json.Unmarshal(msg.ID, &id) != nil {+ return+ }+ c.mu.Lock()+ pr, ok := c.pending[id]+ if ok {+ delete(c.pending, id)+ }+ c.mu.Unlock()+ if !ok {+ return+ }+ if msg.Error != nil {+ trySendRPC(pr, nil, msg.Error)+ } else {+ trySendRPC(pr, msg.Result, nil)+ }+ case msg.Method != "":+ // Notification.+ if msg.Method != "session/event" {+ if c.cfg.Logger != nil {+ c.cfg.Logger.Debug("zcode notification ignored", "method", msg.Method)+ }+ return+ }+ var ev zcodeSessionEvent+ if json.Unmarshal(msg.Params, &ev) != nil {+ return+ }+ if c.onEvent != nil {+ c.onEvent(ev)+ }+ }+}++// trySendRPC resolves one pending request. A nil rpcErr must yield a nil+// error interface value: storing a typed-nil *zcodeRPCError would make+// rpcResult.err a non-nil interface whose "%v" renders "<nil>" and whose+// errors.As match dereferences to a nil pointer downstream.+func trySendRPC(pr *pendingRPC, result json.RawMessage, rpcErr *zcodeRPCError) {+ var err error+ if rpcErr != nil {+ err = rpcErr+ }+ select {+ case pr.ch <- rpcResult{result: result, err: err}:+ default:+ }+}++func truncateZcodeLogLine(line string) string {+ if len(line) <= 512 {+ return line+ }+ return line[:512]+}++// zcodeSessionIDFromSnapshot extracts result.session.sessionId from a+// session/create or session/resume snapshot. The field is `sessionId` —+// zcodeSessionInfoSchema has no `id` member (zcode-protocol-legacy-types.ts).+func zcodeSessionIDFromSnapshot(result json.RawMessage) string {+ var snap struct {+ Session struct {+ SessionID string `json:"sessionId"`+ } `json:"session"`+ }+ if json.Unmarshal(result, &snap) != nil {+ return ""+ }+ return snap.Session.SessionID+}++// splitZcodeModelSelection splits Multica's persisted agent.model string into+// the ZCode {providerId, modelId} pair. The composite form is the runtime's+// own picker format (model-selection.ts formatModelPickerValue), and its+// execution entry rejects a selection without a provider. A string without a+// slash is therefore NOT force-qualified: the backend omits the model and+// lets the runtime default take over rather than fabricate a providerId.+func splitZcodeModelSelection(model string) (providerID, modelID string, ok bool) {+ model = strings.TrimSpace(model)+ if model == "" {+ return "", "", false+ }+ idx := strings.Index(model, "/")+ if idx <= 0 || idx == len(model)-1 {+ return "", "", false+ }+ return model[:idx], model[idx+1:], true+}++// zcodeModelSelection builds the session/create `model` and session/send+// `modelSelection` payload. Reasoning-capable models (e.g. GLM-5.3-Flash)+// reject the selection with "Reasoning level is required" unless+// options.reasoningLevel carries one of the model's advertised levels, so a+// non-empty thinking level rides inside the selection rather than relying on+// the top-level thoughtLevel param (which the server skips when unknown).+func zcodeModelSelection(providerID, modelID, thinkingLevel string) map[string]any {+ selection := map[string]any{+ "providerId": providerID,+ "modelId": modelID,+ }+ if thinkingLevel != "" {+ selection["options"] = map[string]any{+ "reasoningLevel": thinkingLevel,+ }+ }+ return selection+}++func zcodeSavedThinkingLevel(snapshot json.RawMessage, selectedModel string) string {+ var state struct {+ Settings struct {+ Model struct {+ Current struct {+ ProviderID string `json:"providerId"`+ ModelID string `json:"modelId"`+ Options struct {+ ReasoningLevel string `json:"reasoningLevel"`+ } `json:"options"`+ } `json:"current"`+ } `json:"model"`+ } `json:"settings"`+ }+ if json.Unmarshal(snapshot, &state) != nil {+ return ""+ }+ current := state.Settings.Model.Current+ if selectedModel != current.ProviderID+"/"+current.ModelID {+ return ""+ }+ return current.Options.ReasoningLevel+}++// zcodeWorkspaceKey resolves the session/create workspaceKey: the task id+// when the caller carries one, otherwise the resolved workspace directory —+// the strict schema rejects an empty key, and a per-directory key preserves+// the value's identity role for task-less callers (integration tests, direct+// API use).+func zcodeWorkspaceKey(taskID, cwd string) string {+ if taskID != "" {+ return taskID+ }+ if abs, err := filepath.Abs(cwd); err == nil {+ return abs+ }+ return cwd+}++// buildZcodeMcpServers converts Multica's canonical mcp_config JSON into the+// ZCode Protocol mcpServers array. Same parsing skeleton and alt-key+// tolerance as buildACPMcpServers, but the output is built for zcode's strict+// schema (index.ts zcodeProtocolMcpServerSchema): stdio entries carry+// {name, command, args, env}, remote entries {name, type, url, headers}, with+// env/headers as {name,value} pair arrays. Fields the schema does not know+// must never leak through — a strict parse of the whole request would fail.+func buildZcodeMcpServers(raw json.RawMessage, logger *slog.Logger) ([]any, error) {+ trimmed := []byte(strings.TrimSpace(string(raw)))+ if len(trimmed) == 0 || string(trimmed) == "null" {+ return []any{}, nil+ }+ var parsed struct {+ McpServers map[string]json.RawMessage `json:"mcpServers"`+ }+ if err := json.Unmarshal(trimmed, &parsed); err != nil {+ return nil, fmt.Errorf("parse mcp_config json: %w", err)+ }+ if len(parsed.McpServers) == 0 {+ // Alt-key tolerance matches the ACP builder: runtime-native config+ // files sometimes nest under `servers` (jcode/Kiro) instead of the+ // canonical `mcpServers`.+ var alt struct {+ Servers map[string]json.RawMessage `json:"servers"`+ }+ if json.Unmarshal(trimmed, &alt) == nil && len(alt.Servers) > 0 {+ parsed.McpServers = alt.Servers+ if logger != nil {+ logger.Warn("mcp_config used a non-canonical top-level key; accepted via alt-key tolerance", "backend", "zcode")+ }+ }+ }+ names := make([]string, 0, len(parsed.McpServers))+ for name := range parsed.McpServers {+ names = append(names, name)+ }+ sort.Strings(names)++ out := make([]any, 0, len(names))+ for _, name := range names {+ entry, err := convertZcodeMcpServer(name, parsed.McpServers[name])+ if err != nil {+ if logger != nil {+ logger.Warn("skipping invalid mcp_config entry", "backend", "zcode", "name", name, "error", err)+ }+ continue+ }+ out = append(out, entry)+ }+ return out, nil+}++// convertZcodeMcpServer converts one canonical MCP entry into zcode's wire+// shape. Entries with neither command nor url are skipped with an error so a+// single bad entry cannot fail the launch.+func convertZcodeMcpServer(name string, raw json.RawMessage) (map[string]any, error) {+ var entry struct {+ Type string `json:"type"`+ Command string `json:"command"`+ Args []string `json:"args"`+ Env map[string]string `json:"env"`+ URL string `json:"url"`+ Headers map[string]string `json:"headers"`+ }+ if err := json.Unmarshal(raw, &entry); err != nil {+ return nil, fmt.Errorf("parse entry: %w", err)+ }++ command := strings.TrimSpace(entry.Command)+ url := strings.TrimSpace(entry.URL)++ if command != "" {+ args := entry.Args+ if args == nil {+ args = []string{}+ }+ envArr := make([]map[string]any, 0, len(entry.Env))+ for _, k := range sortedStringMapKeys(entry.Env) {+ envArr = append(envArr, map[string]any{"name": k, "value": entry.Env[k]})+ }+ return map[string]any{+ "name": name,+ "command": command,+ "args": args,+ "env": envArr,+ }, nil+ }++ if url != "" {+ t := strings.ToLower(strings.TrimSpace(entry.Type))+ switch t {+ case "sse":+ t = "sse"+ case "", "http", "streamable-http", "http_streamable":+ // Unknown remote transports degrade to http; zcode's schema only+ // accepts "http" | "sse".+ t = "http"+ default:+ t = "http"+ }+ headerArr := make([]map[string]any, 0, len(entry.Headers))+ for _, k := range sortedStringMapKeys(entry.Headers) {+ headerArr = append(headerArr, map[string]any{"name": k, "value": entry.Headers[k]})+ }+ return map[string]any{+ "name": name,+ "type": t,+ "url": url,+ "headers": headerArr,+ }, nil+ }++ return nil, fmt.Errorf("entry has neither command nor url")+}++// zcodeUsageFromSummary maps a turn-level ModelUsageSummary+// (apps/zcode-cli/packages/contracts/src/model/index.ts) onto TokenUsage.+//+// The four TokenUsage counters are mutually exclusive (agent.go): input must+// not include cache reads/writes and output includes reasoning. zcode's usage+// store treats inputTokens as total input with cache as a breakdown+// (usage-stats-builder.ts), so the cache portions are subtracted here; output+// gains the reasoning tokens for the same reason. Semantics of the turn-level+// summary are verified against 0.16.9 source only — the smoke test calibrates.+// Flooring a negative input at zero keeps a mis-proportioned summary from+// producing nonsense counters.+func zcodeUsageFromSummary(raw json.RawMessage) (TokenUsage, bool) {+ if len(raw) == 0 {+ return TokenUsage{}, false+ }+ var u struct {+ InputTokens int64 `json:"inputTokens"`+ OutputTokens int64 `json:"outputTokens"`+ CacheReadTokens int64 `json:"cacheReadTokens"`+ CacheWriteTokens int64 `json:"cacheWriteTokens"`+ ReasoningTokens int64 `json:"reasoningTokens"`+ }+ if err := json.Unmarshal(raw, &u); err != nil {+ return TokenUsage{}, false+ }+ input := u.InputTokens - u.CacheReadTokens - u.CacheWriteTokens+ if input < 0 {+ input = 0+ }+ usage := TokenUsage{+ InputTokens: input,+ OutputTokens: u.OutputTokens + u.ReasoningTokens,+ CacheReadTokens: u.CacheReadTokens,+ CacheWriteTokens: u.CacheWriteTokens,+ }+ return usage, true+}diff --git a/server/pkg/agent/zcode_discovery_lifecycle_test.go b/server/pkg/agent/zcode_discovery_lifecycle_test.gonew file mode 100644index 0000000000..40b6464652--- /dev/null+++ b/server/pkg/agent/zcode_discovery_lifecycle_test.go@@ -0,0 +1,42 @@+//go:build !windows++package agent++import (+ "bytes"+ "context"+ "runtime/pprof"+ "strings"+ "testing"+ "time"+)++func TestZcodeModelDiscoveryReapsCommandWatchers(t *testing.T) {+ watchers := func() int {+ t.Helper()+ var profile bytes.Buffer+ if err := pprof.Lookup("goroutine").WriteTo(&profile, 2); err != nil {+ t.Fatal(err)+ }+ return strings.Count(profile.String(), "os/exec.(*Cmd).watchCtx(")+ }+ before := watchers()+ bin := writeFakeZcodeScript(t, fakeZcodeDiscoveryScript)+ for range 12 {+ catalog, err := discoverZcodeModels(context.Background(), NewCommand(bin, nil))+ if err != nil || len(catalog.Models) != 2 {+ t.Fatalf("discovery=%+v err=%v", catalog, err)+ }+ }+ deadline := time.Now().Add(time.Second)+ for {+ after := watchers()+ if after <= before+1 {+ return+ }+ if time.Now().After(deadline) {+ t.Fatalf("CommandContext watchers leaked across repeated discovery: before=%d after=%d", before, after)+ }+ time.Sleep(10 * time.Millisecond)+ }+}diff --git a/server/pkg/agent/zcode_integration_test.go b/server/pkg/agent/zcode_integration_test.gonew file mode 100644index 0000000000..3b3d29d5c9--- /dev/null+++ b/server/pkg/agent/zcode_integration_test.go@@ -0,0 +1,150 @@+//go:build agentintegration++package agent++import (+ "context"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// TestZcodeRealProtocolSmoke drives the real `zcode app-server` end-to-end.+//+// It validates the daemon contract against a live ZCode CLI process:+// - `zcode app-server` starts and answers session/create+// - a prompt turn completes with a non-empty session id+// - the agent can execute a shell command and write a sentinel file+// (session/create pins mode=yolo, so no interactive permission prompt+// blocks the turn)+//+// Gated by MULTICA_RUN_REAL_AGENT_SMOKE=1 per AGENTS.md. The CLI is+// discovered from MULTICA_ZCODE_PATH (which may directly name the desktop bundle+// zcode.cjs entry point) or+// `zcode` on PATH, and requires a configured API connection.+func TestZcodeRealProtocolSmoke(t *testing.T) {+ requireRealAgentSmoke(t)+ if testing.Short() {+ t.Skip("skipping real-binary smoke test in -short mode")+ }++ path := os.Getenv("MULTICA_ZCODE_PATH")+ if path == "" {+ discovered, err := exec.LookPath("zcode")+ if err != nil {+ t.Skip("zcode not on PATH and MULTICA_ZCODE_PATH unset; skipping real-binary smoke test")+ }+ path = discovered+ }++ if version, err := exec.Command(path, "--version").CombinedOutput(); err == nil {+ t.Logf("zcode version: %s", strings.TrimSpace(string(version)))+ } else {+ t.Logf("zcode version unavailable: %v", err)+ }++ backend, err := New("zcode", Config{+ ExecutablePath: path,+ Logger: slog.Default(),+ })+ if err != nil {+ t.Fatalf("new zcode backend: %v", err)+ }++ cwd := t.TempDir()+ sentinel := filepath.Join(cwd, "sentinel.txt")++ ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)+ defer cancel()++ // A headless app-server session has no runtime default model — a+ // modelless create succeeded but the turn failed with CONFIGURATION_ERROR+ // "Select a model before continuing" — so pick one from the real catalog.+ // The registry's provider ids are account-shaped and cannot be guessed:+ // three hardcoded attempts (account:zai-start-plan,+ // account:zai-individual-coding-plan) all answered "Provider Registry 中+ // 不存在 Model", which is exactly what discovery exists to answer.+ // Override with MULTICA_ZCODE_SMOKE_MODEL for a specific pick.+ model := os.Getenv("MULTICA_ZCODE_SMOKE_MODEL")+ thinkingLevel := ""+ if model == "" {+ catalog, err := ListModels(ctx, "zcode", NewCommand(path, nil))+ if err != nil {+ t.Fatalf("discover zcode models: %v", err)+ }+ if len(catalog.Models) == 0 {+ t.Fatal("zcode model discovery returned no models; is the CLI logged in?")+ }+ for _, m := range catalog.Models {+ // Prefer a reasoning-capable model: zcode rejects its selection+ // with "Reasoning level is required" unless options.reasoningLevel+ // carries one of the model's advertised levels, and a reasoning+ // smoke exercises that contract end-to-end.+ if m.Thinking == nil || len(m.Thinking.SupportedLevels) == 0 {+ continue+ }+ model = m.ID+ thinkingLevel = m.Thinking.DefaultLevel+ if thinkingLevel == "" {+ thinkingLevel = m.Thinking.SupportedLevels[0].Value+ }+ break+ }+ if model == "" {+ model = catalog.Models[0].ID+ }+ t.Logf("smoke model from discovery: %s (thinking level %q)", model, thinkingLevel)+ } else {+ thinkingLevel = "low"+ }++ // Prompt the agent to write a sentinel file. This is the real execution+ // proof: under mode=yolo the shell tool auto-approves, so success confirms+ // session/create, the prompt turn and the event stream all work against+ // the live protocol server. Reasoning-capable models reject their+ // selection without options.reasoningLevel, so the smoke pins the+ // discovered model's own default thinking level.+ session, err := backend.Execute(ctx,+ "Use your shell/exec tool to run: echo zcode-exec-ok > sentinel.txt — then reply with exactly: done",+ ExecOptions{+ Cwd: cwd,+ Model: model,+ ThinkingLevel: thinkingLevel,+ Timeout: 170 * time.Second,+ },+ )+ if err != nil {+ t.Fatalf("execute: %v", err)+ }++ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result := <-session.Result:+ if result.Status != "completed" {+ t.Fatalf("real zcode run did not complete: status=%q error=%q", result.Status, result.Error)+ }+ if result.SessionID == "" {+ t.Error("expected a non-empty session id from real zcode")+ } else {+ t.Logf("zcode session id: %s", result.SessionID)+ }+ case <-ctx.Done():+ t.Fatal("timed out waiting for the real zcode run to finish")+ }++ content, err := os.ReadFile(sentinel)+ if err != nil {+ t.Fatalf("sentinel file not written by real zcode: %v", err)+ }+ if strings.TrimSpace(string(content)) != "zcode-exec-ok" {+ t.Fatalf("sentinel content mismatch: %q", strings.TrimSpace(string(content)))+ }+}diff --git a/server/pkg/agent/zcode_invocation.go b/server/pkg/agent/zcode_invocation.gonew file mode 100644index 0000000000..b310eab5d7--- /dev/null+++ b/server/pkg/agent/zcode_invocation.go@@ -0,0 +1,61 @@+package agent++import (+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+)++// chooseZcodeInvocation selects the actual program (argv[0]) and the full argv+// to spawn a ZCode run.+//+// ZCode ships as a Node bundle (zcode.cjs) inside the desktop app rather than+// as a native binary, so a resolved .cjs/.mjs path runs under `node`. Callers+// (Execute, model discovery, --version probes) must ensure `node` is on PATH+// before spawning — see requireNodeForZcodeScript. Shims and native builds+// pass through unchanged.+func chooseZcodeInvocation(execName, lookedUp string, args []string, _ *slog.Logger) (string, []string) {+ if isNodeScriptPath(lookedUp) {+ return "node", append([]string{lookedUp}, args...)+ }+ return execName, args+}++func isNodeScriptPath(path string) bool {+ return strings.HasSuffix(path, ".cjs") || strings.HasSuffix(path, ".mjs")+}++// requireNodeForZcodeScript reports a clear error when a Desktop .cjs/.mjs+// entry needs Node.js on PATH and none is resolvable. Native/shim paths pass.+func requireNodeForZcodeScript(lookedUp string) error {+ if !isNodeScriptPath(lookedUp) {+ return nil+ }+ if _, err := exec.LookPath("node"); err != nil {+ return fmt.Errorf("ZCode Desktop requires Node.js on PATH to run %s, but node was not found; install Node.js or ensure the daemon inherits a PATH that includes it", filepath.Base(lookedUp))+ }+ return nil+}++// zcodeRuntimeEnv supplies the companion config shipped in the Desktop app.+// The bundled CLI's relative lookup does not cover Resources/glm in 0.17.+// Explicit environment configuration always wins.+func zcodeRuntimeEnv(executable string, env []string) []string {+ const key = "ZCODE_BUILTIN_PROVIDER_CONFIG_FILE"+ for _, entry := range env {+ if strings.HasPrefix(entry, key+"=") {+ return env+ }+ }+ if !isNodeScriptPath(executable) {+ return env+ }+ config := filepath.Join(filepath.Dir(executable), "..", "config", "provider", "zcode-builtin.json")+ if info, err := os.Stat(config); err == nil && info.Mode().IsRegular() {+ return append(append([]string(nil), env...), key+"="+config)+ }+ return env+}diff --git a/server/pkg/agent/zcode_lifecycle_test.go b/server/pkg/agent/zcode_lifecycle_test.gonew file mode 100644index 0000000000..bbf1694900--- /dev/null+++ b/server/pkg/agent/zcode_lifecycle_test.go@@ -0,0 +1,127 @@+//go:build !windows++package agent++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "testing"+ "time"+)++func TestZcodeHandshakeFailureClosesOwnedProcess(t *testing.T) {+ root := t.TempDir()+ pidfile := filepath.Join(root, "pid")+ script := "#!/usr/bin/python3\nimport os,time\nopen(" + fmt.Sprintf("%q", pidfile) + ",'w').write(str(os.getpid()))\ntime.sleep(60)\n"+ bin := filepath.Join(root, "zcode")+ if err := os.WriteFile(bin, []byte(script), 0700); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if !t.Failed() {+ return+ }+ raw, _ := os.ReadFile(pidfile)+ pid, _ := strconv.Atoi(strings.TrimSpace(string(raw)))+ if pid > 0 {+ p, _ := os.FindProcess(pid)+ _ = p.Kill()+ }+ })+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ session, err := newZcodeTestBackend(t, bin).Execute(ctx, "hello", ExecOptions{Cwd: root, HandshakeTimeout: 50 * time.Millisecond})+ if err != nil {+ t.Fatal(err)+ }+ select {+ case result := <-session.Result:+ t.Logf("terminal status=%s error=%s", result.Status, result.Error)+ case <-time.After(time.Second):+ t.Fatal("no handshake terminal result")+ }+ select {+ case _, open := <-session.Messages:+ if open {+ t.Fatal("unexpected message")+ }+ case <-time.After(400 * time.Millisecond):+ t.Fatal("message channel stays open after terminal handshake failure: owned process was not stopped before Wait")+ }+}++func TestZcodeBlockedPromptWriteHonorsTimeout(t *testing.T) {+ root := t.TempDir()+ pidfile := filepath.Join(root, "pid")+ script := `#!/usr/bin/python3+import os,sys,json,time+open(` + fmt.Sprintf("%q", pidfile) + `,'w').write(str(os.getpid()))+for n in range(2):+ req=json.loads(sys.stdin.readline())+ result={'session':{'sessionId':'fake_blocked'}} if req['method']=='session/create' else {'eventSeq':0}+ print(json.dumps({'id':req['id'],'result':result}),flush=True)+time.sleep(60)+`+ bin := filepath.Join(root, "zcode")+ if err := os.WriteFile(bin, []byte(script), 0700); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if !t.Failed() {+ return+ }+ raw, _ := os.ReadFile(pidfile)+ pid, _ := strconv.Atoi(strings.TrimSpace(string(raw)))+ if pid > 0 {+ p, _ := os.FindProcess(pid)+ _ = p.Kill()+ }+ })+ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), strings.Repeat("x", 1<<20), ExecOptions{Cwd: root, Timeout: 2 * time.Second, HandshakeTimeout: 5 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ select {+ case result := <-session.Result:+ if result.Status != "timeout" {+ t.Fatalf("status=%s error=%s", result.Status, result.Error)+ }+ case <-time.After(3500 * time.Millisecond):+ t.Fatal("hard timeout did not stop session/send blocked on stdin.Write")+ }+}++func TestZcodeResumedReasoningModelRetainsLevel(t *testing.T) {+ script := `#!/usr/bin/python3+import sys,json+for line in sys.stdin:+ req=json.loads(line); method=req.get('method'); params=req.get('params',{})+ if method=='session/resume':+ result={'session':{'sessionId':'saved'},'settings':{'model':{'current':{'providerId':'zai','modelId':'m','options':{'reasoningLevel':'max'}}}}}+ elif method=='session/subscribe':+ result={'eventSeq':0}+ elif method=='session/send':+ if not params.get('modelSelection',{}).get('options',{}).get('reasoningLevel'):+ print(json.dumps({'id':req['id'],'error':{'code':-32603,'message':'Reasoning level is required for zai/m'}}),flush=True)+ continue+ result={}+ else:+ result={}+ print(json.dumps({'id':req['id'],'result':result}),flush=True)+ if method=='session/send':+ print(json.dumps({'method':'session/event','params':{'type':'turn.completed','seq':1,'sessionId':'saved','payload':{'response':'ok','resultType':'success'}}}),flush=True)+`+ bin := writeFakeZcodeScript(t, script)+ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "continue", ExecOptions{Cwd: t.TempDir(), Model: "zai/m", ResumeSessionID: "saved", Timeout: 3 * time.Second, HandshakeTimeout: 2 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ _, result := collectZcodeSession(t, session)+ if result.Status != "completed" {+ t.Fatalf("resume did not preserve existing reasoning level: status=%s error=%s", result.Status, result.Error)+ }+}diff --git a/server/pkg/agent/zcode_models.go b/server/pkg/agent/zcode_models.gonew file mode 100644index 0000000000..b421f1352b--- /dev/null+++ b/server/pkg/agent/zcode_models.go@@ -0,0 +1,296 @@+package agent++import (+ "bufio"+ "context"+ "encoding/json"+ "io"+ "os"+ "os/exec"+ "strings"+ "syscall"+ "time"+)++// defaultZcodeDiscoveryTimeout bounds one throwaway app-server spawn during+// model discovery. The dominant cost is the Node CLI's cold module load (the+// same first-run latency the execution handshake pays), so it mirrors+// defaultZcodeHandshakeTimeout.+const defaultZcodeDiscoveryTimeout = 30 * time.Second++// discoverZcodeModels reads ZCode's real model catalog. The CLI has no+// models/list command or RPC — the catalog only exists inside a session+// snapshot (settings.model.available, assembled from the provider registry,+// i.e. the logged-in account). Discovery therefore spawns a throwaway+// app-server, creates a `persistence:"deferred"` draft session — deferred+// drafts never enter the session store (zcodeSessionService.createSession),+// so discovery leaves no residue — and reads the snapshot, modelled on+// discoverACPModels' process handling. Any failure degrades to the empty+// catalog so the UI keeps manual entry in the `providerId/modelId` format+// (splitZcodeModelSelection).+func discoverZcodeModels(ctx context.Context, runtimeCmd Command) (Catalog, error) {+ empty := Catalog{Models: []Model{}}+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "zcode"+ }+ lookedUp, err := exec.LookPath(runtimeCmd.Path)+ if err != nil {+ return empty, nil+ }+ if err := requireNodeForZcodeScript(lookedUp); err != nil {+ return empty, err+ }+ runtimeEnv, cleanupConfig, err := prepareZcodeRuntimeEnv(lookedUp, os.Environ())+ if err != nil {+ return empty, err+ }+ defer cleanupConfig()++ runCtx, cancel := context.WithTimeout(ctx, defaultZcodeDiscoveryTimeout)+ defer cancel()++ // The discovery session's workspace is a temp dir: the server treats the+ // process cwd as the workspace, and running inside a real checkout would+ // both pollute it and pick up its dotenv (design doc §6 R8).+ tmp, err := os.MkdirTemp("", "multica-zcode-discovery-")+ if err != nil {+ return empty, nil+ }+ defer os.RemoveAll(tmp)++ cmd, _, _ := runtimeCmd.execVia(runCtx, chooseZcodeInvocation, lookedUp, []string{"app-server"}, runtimeCmd.logger)+ hideAgentWindow(cmd)+ cmd.Dir = tmp+ cmd.Env = runtimeEnv+ // stderr noise from a discovery spawn helps nobody; the daemon re-runs+ // discovery on demand and the empty-catalog fallback is already silent.+ cmd.Stderr = io.Discard+ cmd.WaitDelay = 2 * time.Second+ stdin, err := cmd.StdinPipe()+ if err != nil {+ return empty, nil+ }+ stdout, err := cmd.StdoutPipe()+ if err != nil {+ stdin.Close()+ return empty, nil+ }+ if err := startOwnedProcessTree(cmd, runtimeCmd.logger); err != nil {+ return empty, nil+ }+ // This probe runs on every uncached catalog read, so a leaked app-server+ // here accumulates; always reap the whole tree (same contract as+ // discoverACPModels).+ defer func() {+ _ = stdin.Close()+ signalProcessGroup(cmd, syscall.SIGKILL)+ // Wait also consumes CommandContext watchers and closes its pipes.+ _ = cmd.Wait()+ releaseProcessGroup(cmd)+ }()++ // Wire frames carry no `jsonrpc` member — the server's strict schema+ // rejects it (see zcodeBackend's doc). Sending one would fail the whole+ // create, so this loop deliberately does not reuse the ACP framing.+ params := map[string]any{+ "workspace": map[string]any{+ "workspacePath": tmp,+ // The strict schema rejects an empty key; the temp dir is+ // stable for the lifetime of the throwaway session, which is+ // all the key's identity role needs here.+ "workspaceKey": tmp,+ },+ "persistence": "deferred",+ "mode": "yolo",+ }+ frame, err := json.Marshal(map[string]any{+ "id": 1,+ "method": "session/create",+ "params": params,+ })+ if err != nil {+ return empty, nil+ }+ frame = append(frame, '\n')+ if _, err := stdin.Write(frame); err != nil {+ return empty, nil+ }++ scanner := bufio.NewScanner(stdout)+ scanner.Buffer(make([]byte, 0, 1024*1024), 4*1024*1024)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ var msg struct {+ ID json.RawMessage `json:"id"`+ Method string `json:"method"`+ Result json.RawMessage `json:"result"`+ Error *zcodeRPCError `json:"error"`+ }+ if json.Unmarshal([]byte(line), &msg) != nil {+ continue+ }+ if len(msg.ID) > 0 && string(msg.ID) != "null" && msg.Method != "" {+ // Server-originated request. A real app-server asks for the+ // client's runtime preferences during session/create+ // (session/requestRuntimePreferences); leaving it unanswered is a+ // guaranteed -32022 after its 15s timeout, so answer with the+ // schema defaults (nativeSearchEnhancementsEnabled is the only+ // member without one). Everything else gets the shared reverse+ // handling.+ if msg.Method == "session/requestRuntimePreferences" {+ zcodeWriteReverseResult(stdin, msg.ID, zcodeRuntimePreferencesDefaults())+ continue+ }+ zcodeWriteReverseUnsupported(stdin, msg.ID, msg.Method)+ continue+ }+ // Notifications (startup/storage*, state.updated, session/event+ // replays) are skipped: only the response to our create carries the+ // snapshot.+ if len(msg.ID) == 0 || string(msg.ID) == "null" || string(msg.ID) != "1" {+ continue+ }+ if msg.Error != nil {+ if runtimeCmd.logger != nil {+ runtimeCmd.logger.Debug("zcode model discovery create rejected",+ "backend", "zcode", "code", msg.Error.Code, "message", msg.Error.Message)+ }+ return empty, nil+ }+ catalog, ok := zcodeCatalogFromSnapshot(msg.Result)+ if !ok {+ if runtimeCmd.logger != nil {+ runtimeCmd.logger.Debug("zcode model discovery found no catalog in create snapshot",+ "backend", "zcode",+ "result_keys", strings.Join(acpResultTopLevelKeys(msg.Result), ","))+ }+ return empty, nil+ }+ return catalog, nil+ }+ if err := scanner.Err(); err != nil && runtimeCmd.logger != nil {+ runtimeCmd.logger.Debug("zcode model discovery stream ended", "backend", "zcode", "error", err)+ }+ return empty, nil+}++// zcodeResolveThinkingLevel resolves the level an empty thinking_level ("let+// the runtime decide") actually resolves to. zcode is the one protocol with no+// implicit default — session/create rejects a reasoning-capable selection+// without options.reasoningLevel — so the runtime's decision has to be made+// here. The chain mirrors the CLI's own resolution (zcode-agent-model-state+// current ?? defaultLevel ?? available[0]): the model's advertised+// defaultLevel, else its first supported level. Hardcoding a token instead+// would break the day the registry's dynamic vocabulary changes. A missing+// catalog or entry returns "" — the server's own "Reasoning level is required"+// is then the clearest diagnosis, and no fabricated token is sent.+func zcodeResolveThinkingLevel(ctx context.Context, runtimeCmd Command, model string) string {+ providerID, modelID, ok := splitZcodeModelSelection(model)+ if !ok {+ return ""+ }+ catalog, err := ListModels(ctx, "zcode", runtimeCmd)+ if err != nil {+ return ""+ }+ want := providerID + "/" + modelID+ for _, m := range catalog.Models {+ if m.ID != want || m.Thinking == nil || len(m.Thinking.SupportedLevels) == 0 {+ continue+ }+ if m.Thinking.DefaultLevel != "" {+ return m.Thinking.DefaultLevel+ }+ return m.Thinking.SupportedLevels[0].Value+ }+ return ""+}++// zcodeModelOption mirrors the subset of zcodeModelOptionSchema+// (zcode-protocol index.ts:795-810) the catalog mapping consumes. Parsing is+// lenient: the server's own payloads are strict and evolve, so unknown fields+// are ignored and absent optionals degrade instead of failing the catalog.+type zcodeModelOption struct {+ Ref struct {+ ProviderID string `json:"providerId"`+ ModelID string `json:"modelId"`+ } `json:"ref"`+ Label string `json:"label"`+ Reasoning *struct {+ Levels []struct {+ Value string `json:"value"`+ Label string `json:"label"`+ Description string `json:"description"`+ } `json:"levels"`+ DefaultLevel string `json:"defaultLevel"`+ } `json:"reasoning"`+ DisabledReason string `json:"disabledReason"`+}++// zcodeCatalogFromSnapshot maps a session/create snapshot onto a Catalog.+// IDs use the runtime's own picker format `providerId/modelId` — the same+// string splitZcodeModelSelection turns back into a selection, so a picked+// entry round-trips into session/create's model param unchanged. Entries with+// a disabledReason land in Unavailable rather than Models: the registry named+// them but will not run them on this account, and UnavailableModel carries the+// runtime's own remedy copy. The second return reports whether the snapshot+// carried a parsable settings.model at all; an absent or malformed one is+// schema drift and must not be mistaken for an empty registry.+func zcodeCatalogFromSnapshot(result json.RawMessage) (Catalog, bool) {+ // Pointers distinguish a missing settings.model (schema drift, ok=false)+ // from a present-but-empty one (a genuinely empty registry): encoding/json+ // silently zero-fills absent fields, so value structs cannot tell the two+ // apart.+ var snap struct {+ Settings *struct {+ Model *struct {+ Current *struct {+ ProviderID string `json:"providerId"`+ ModelID string `json:"modelId"`+ } `json:"current"`+ Available []zcodeModelOption `json:"available"`+ } `json:"model"`+ } `json:"settings"`+ }+ if json.Unmarshal(result, &snap) != nil || snap.Settings == nil || snap.Settings.Model == nil {+ return Catalog{}, false+ }+ currentRef := ""+ if c := snap.Settings.Model.Current; c != nil && c.ProviderID != "" && c.ModelID != "" {+ currentRef = c.ProviderID + "/" + c.ModelID+ }+ models := []Model{}+ unavailable := []UnavailableModel{}+ for _, opt := range snap.Settings.Model.Available {+ if opt.Ref.ProviderID == "" || opt.Ref.ModelID == "" {+ continue+ }+ id := opt.Ref.ProviderID + "/" + opt.Ref.ModelID+ label := opt.Label+ if label == "" {+ label = opt.Ref.ModelID+ }+ if opt.DisabledReason != "" {+ unavailable = append(unavailable, UnavailableModel{ID: id, Label: label, Reason: opt.DisabledReason})+ continue+ }+ m := Model{ID: id, Label: label, Provider: opt.Ref.ProviderID}+ // Default is a display badge only: the registry's current selection,+ // which for a fresh account session is its preferred model.+ if id == currentRef {+ m.Default = true+ }+ if opt.Reasoning != nil && len(opt.Reasoning.Levels) > 0 {+ levels := make([]ThinkingLevel, 0, len(opt.Reasoning.Levels))+ for _, l := range opt.Reasoning.Levels {+ levels = append(levels, ThinkingLevel{Value: l.Value, Label: l.Label, Description: l.Description})+ }+ m.Thinking = &ModelThinking{SupportedLevels: levels, DefaultLevel: opt.Reasoning.DefaultLevel}+ }+ models = append(models, m)+ }+ return Catalog{Models: models, Unavailable: unavailable}, true+}diff --git a/server/pkg/agent/zcode_runtime_config.go b/server/pkg/agent/zcode_runtime_config.gonew file mode 100644index 0000000000..a82b125413--- /dev/null+++ b/server/pkg/agent/zcode_runtime_config.go@@ -0,0 +1,229 @@+package agent++import (+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "sort"+ "strings"+)++const (+ zcodePersonalConfigEnv = "ZCODE_PERSONAL_PROVIDER_CONFIG_FILE"+ zcodeProvidersTempPrefix = "multica-zcode-providers-"+)++type zcodeDesktopProvider struct {+ Name string `json:"name"`+ Kind string `json:"kind"`+ Enabled *bool `json:"enabled"`+ Headers map[string]string `json:"headers"`+ Options struct {+ APIKey string `json:"apiKey"`+ BaseURL string `json:"baseURL"`+ Headers map[string]string `json:"headers"`+ } `json:"options"`+ Models map[string]struct {+ Limit struct {+ Context int64 `json:"context"`+ } `json:"limit"`+ } `json:"models"`+}++func zcodeEnvValue(env []string, key string) string {+ for _, entry := range env {+ if strings.HasPrefix(entry, key+"=") {+ return strings.TrimPrefix(entry, key+"=")+ }+ }+ return ""+}++func readZcodeConfig(path string, into any) error {+ file, err := os.Open(path)+ if err != nil {+ return err+ }+ defer file.Close()+ data, err := io.ReadAll(io.LimitReader(file, (2<<20)+1))+ if err != nil {+ return err+ }+ if len(data) > 2<<20 {+ return fmt.Errorf("ZCode provider config exceeds 2 MiB")+ }+ return json.Unmarshal(data, into)+}++// prepareZcodeRuntimeEnv adapts Desktop's enabled API-key connections into a+// private, process-owned native provider repository snapshot under the process+// temp dir (multica-zcode-providers-*). It reads Desktop's enabled connections+// to build that snapshot, but never edits Desktop's repositories or converts+// Start Plan identity tokens into API keys. Explicit native repositories remain+// authoritative. Call CleanupStaleZcodeProviderSnapshots on daemon startup so+// crash leftovers do not linger.+func prepareZcodeRuntimeEnv(executable string, env []string) ([]string, func(), error) {+ noop := func() {}+ if zcodeEnvValue(env, zcodePersonalConfigEnv) != "" {+ return zcodeRuntimeEnv(executable, env), noop, nil+ }+ builtin := filepath.Join(filepath.Dir(executable), "..", "config", "provider", "zcode-builtin.json")+ if !isNodeScriptPath(executable) {+ return env, noop, nil+ }+ if info, err := os.Stat(builtin); err != nil || !info.Mode().IsRegular() {+ return env, noop, nil+ }+ base := zcodeEnvValue(env, "ZCODE_DATA_BASE_DIR")+ if base == "" {+ var err error+ base, err = os.UserHomeDir()+ if err != nil {+ return nil, noop, err+ }+ }+ root := filepath.Join(base, ".zcode", "v2")+ var desktop struct {+ Providers map[string]zcodeDesktopProvider `json:"provider"`+ }+ err := readZcodeConfig(filepath.Join(root, "config.json"), &desktop)+ if err != nil && !errors.Is(err, os.ErrNotExist) {+ return nil, noop, fmt.Errorf("read ZCode Desktop connections: %w", err)+ }+ native := map[string]any{"schemaVersion": 1, "config": map[string]any{}}+ err = readZcodeConfig(filepath.Join(root, "provider_config.json"), &native)+ if err != nil && !errors.Is(err, os.ErrNotExist) {+ return nil, noop, fmt.Errorf("read ZCode native provider repository: %w", err)+ }+ config, ok := native["config"].(map[string]any)+ if !ok {+ return nil, noop, fmt.Errorf("ZCode native provider repository has no config object")+ }+ group := func(key string) map[string]any {+ if value, ok := config[key].(map[string]any); ok {+ return value+ }+ value := map[string]any{}+ config[key] = value+ return value+ }+ providers, models := group("providerConfigRules"), group("modelConfigRules")+ providerRules, _ := providers["providerRules"].([]any)+ modelRules, _ := models["providerModelRules"].([]any)+ order, _ := config["providerOrder"].([]any)+ if providerRules == nil {+ providerRules = []any{}+ }+ if modelRules == nil {+ modelRules = []any{}+ }+ if order == nil {+ order = []any{}+ }+ sourceIDs := make([]string, 0, len(desktop.Providers))+ for id := range desktop.Providers {+ sourceIDs = append(sourceIDs, id)+ }+ sort.Strings(sourceIDs)+ for _, sourceID := range sourceIDs {+ provider := desktop.Providers[sourceID]+ if provider.Enabled == nil || !*provider.Enabled || strings.TrimSpace(provider.Options.APIKey) == "" || len(provider.Models) == 0 {+ continue+ }+ if strings.HasPrefix(sourceID, "builtin:") && strings.Contains(sourceID, "start-plan") {+ continue+ }+ providerID := "multica-desktop:" + sourceID+ ids := make([]string, 0, len(provider.Models))+ for id := range provider.Models {+ ids = append(ids, id)+ }+ sort.Strings(ids)+ apiType := "openai-chat-completions"+ switch provider.Kind {+ case "anthropic":+ apiType = "anthropic-messages"+ case "openai":+ apiType = "openai-responses"+ }+ api := map[string]any{"type": apiType}+ if provider.Options.BaseURL != "" {+ api["baseUrl"] = provider.Options.BaseURL+ }+ headers := map[string]string{}+ for key, value := range provider.Headers {+ headers[key] = value+ }+ for key, value := range provider.Options.Headers {+ headers[key] = value+ }+ if len(headers) > 0 {+ api["headers"] = headers+ }+ rule := map[string]any{"providerId": providerID, "config": map[string]any{+ "group": "standard-personal", "access": map[string]any{"type": "api-key", "apiKey": provider.Options.APIKey},+ "api": api, "personalModelIds": ids, "modelOrder": ids,+ }}+ if provider.Name != "" {+ rule["providerName"] = provider.Name+ }+ providerRules = append(providerRules, rule)+ order = append(order, providerID)+ for _, id := range ids {+ modelConfig := map[string]any{"enabled": true}+ if contextWindow := provider.Models[id].Limit.Context; contextWindow > 0 {+ modelConfig["properties"] = map[string]any{"contextWindow": contextWindow}+ }+ modelRules = append(modelRules, map[string]any{"providerId": providerID, "modelId": id, "config": modelConfig})+ }+ }+ providers["providerRules"], models["providerModelRules"], config["providerOrder"] = providerRules, modelRules, order+ if _, present := models["manualProviderModelRules"]; !present {+ models["manualProviderModelRules"] = []any{}+ }+ data, err := json.Marshal(native)+ if err != nil {+ return nil, noop, fmt.Errorf("encode process-owned ZCode provider repository: %w", err)+ }+ temp, err := os.MkdirTemp("", zcodeProvidersTempPrefix)+ if err != nil {+ return nil, noop, err+ }+ cleanup := func() { _ = os.RemoveAll(temp) }+ file := filepath.Join(temp, "providers.json")+ if err := os.WriteFile(file, data, 0o600); err != nil {+ cleanup()+ return nil, noop, err+ }+ env = zcodeRuntimeEnv(executable, env)+ return append(env, zcodePersonalConfigEnv+"="+file), cleanup, nil+}++// CleanupStaleZcodeProviderSnapshots removes orphaned process-private provider+// repository directories left under the process temp dir when a prior daemon+// exited without running the per-session cleanup defer (crash / SIGKILL).+// Best-effort: failures to remove individual matches are ignored; the count of+// removed directories is returned for logging.+func CleanupStaleZcodeProviderSnapshots() int {+ matches, err := filepath.Glob(filepath.Join(os.TempDir(), zcodeProvidersTempPrefix+"*"))+ if err != nil {+ return 0+ }+ removed := 0+ for _, dir := range matches {+ info, err := os.Stat(dir)+ if err != nil || !info.IsDir() {+ continue+ }+ if !strings.HasPrefix(filepath.Base(dir), zcodeProvidersTempPrefix) {+ continue+ }+ if err := os.RemoveAll(dir); err == nil {+ removed+++ }+ }+ return removed+}diff --git a/server/pkg/agent/zcode_runtime_config_test.go b/server/pkg/agent/zcode_runtime_config_test.gonew file mode 100644index 0000000000..b0c037d02a--- /dev/null+++ b/server/pkg/agent/zcode_runtime_config_test.go@@ -0,0 +1,139 @@+package agent++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestZcodeDesktopProviderRepositoryIsPrivateAndDoesNotModifyUserConfig(t *testing.T) {+ base := t.TempDir()+ executable := filepath.Join(base, "ZCode.app", "Contents", "Resources", "glm", "zcode.cjs")+ builtin := filepath.Join(filepath.Dir(executable), "..", "config", "provider", "zcode-builtin.json")+ if err := os.MkdirAll(filepath.Dir(builtin), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(builtin, []byte("{}"), 0o600); err != nil {+ t.Fatal(err)+ }+ configRoot := filepath.Join(base, ".zcode", "v2")+ if err := os.MkdirAll(configRoot, 0o700); err != nil {+ t.Fatal(err)+ }+ source := []byte(`{"provider":{+ "builtin:bigmodel-coding-plan":{"enabled":true,"kind":"anthropic","options":{"apiKey":"test-secret","baseURL":"https://example.invalid"},"models":{"m":{"limit":{"context":12000}}}},+ "builtin:bigmodel-start-plan":{"enabled":true,"options":{"apiKey":"identity-token"},"models":{"m":{}}},+ "disabled":{"enabled":false,"options":{"apiKey":"disabled-secret"},"models":{"m":{}}}+ }}`)+ file := filepath.Join(configRoot, "config.json")+ if err := os.WriteFile(file, source, 0o600); err != nil {+ t.Fatal(err)+ }+ native := []byte(`{"schemaVersion":1,"config":{"providerConfigRules":{"providerRules":[{"providerId":"existing"}]},"modelConfigRules":{"providerModelRules":[]}}}`)+ nativePath := filepath.Join(configRoot, "provider_config.json")+ if err := os.WriteFile(nativePath, native, 0o600); err != nil {+ t.Fatal(err)+ }+ env, cleanup, err := prepareZcodeRuntimeEnv(executable, []string{"ZCODE_DATA_BASE_DIR=" + base})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(cleanup)+ snapshot := zcodeEnvValue(env, zcodePersonalConfigEnv)+ if snapshot == "" || snapshot == nativePath {+ t.Fatal("expected a separate process-owned snapshot")+ }+ info, err := os.Stat(snapshot)+ if err != nil {+ t.Fatal(err)+ }+ if info.Mode().Perm() != 0o600 {+ t.Fatalf("provider snapshot mode = %v", info.Mode())+ }+ data, err := os.ReadFile(snapshot)+ if err != nil {+ t.Fatal(err)+ }+ var parsed struct {+ Config struct {+ Providers struct {+ Rules []json.RawMessage `json:"providerRules"`+ } `json:"providerConfigRules"`+ } `json:"config"`+ }+ if err := json.Unmarshal(data, &parsed); err != nil {+ t.Fatal(err)+ }+ if len(parsed.Config.Providers.Rules) != 2 || !strings.Contains(string(data), "test-secret") || strings.Contains(string(data), "identity-token") || strings.Contains(string(data), "disabled-secret") {+ t.Fatal("snapshot must preserve native providers and import only enabled API connections")+ }+ if after, _ := os.ReadFile(file); string(after) != string(source) {+ t.Fatal("Desktop source was modified")+ }+ if after, _ := os.ReadFile(nativePath); string(after) != string(native) {+ t.Fatal("native repository was modified")+ }+ cleanup()+ if _, err := os.Stat(snapshot); !os.IsNotExist(err) {+ t.Fatal("provider snapshot was not removed")+ }+}++func TestZcodeExplicitProviderRepositoryRemainsAuthoritative(t *testing.T) {+ env := []string{zcodePersonalConfigEnv + "=/explicit/providers.json", "ZCODE_BUILTIN_PROVIDER_CONFIG_FILE=/explicit/builtin.json"}+ got, cleanup, err := prepareZcodeRuntimeEnv("/app/zcode.cjs", env)+ if err != nil {+ t.Fatal(err)+ }+ defer cleanup()+ if strings.Join(got, "\n") != strings.Join(env, "\n") {+ t.Fatal("explicit repository was replaced")+ }+}++func TestCleanupStaleZcodeProviderSnapshotsRemovesLeftovers(t *testing.T) {+ base := t.TempDir()+ t.Setenv("TMPDIR", base)+ // os.TempDir on Unix reads TMPDIR; recreate the leftover layout.+ leftover := filepath.Join(base, zcodeProvidersTempPrefix+"orphan123")+ if err := os.MkdirAll(leftover, 0o700); err != nil {+ t.Fatal(err)+ }+ secret := filepath.Join(leftover, "providers.json")+ if err := os.WriteFile(secret, []byte(`{"apiKey":"x"}`), 0o600); err != nil {+ t.Fatal(err)+ }+ // Unrelated temp dir must survive.+ keep := filepath.Join(base, "unrelated-temp")+ if err := os.MkdirAll(keep, 0o700); err != nil {+ t.Fatal(err)+ }+ removed := CleanupStaleZcodeProviderSnapshots()+ if removed != 1 {+ t.Fatalf("removed = %d, want 1", removed)+ }+ if _, err := os.Stat(leftover); !os.IsNotExist(err) {+ t.Fatalf("leftover still present: %v", err)+ }+ if _, err := os.Stat(keep); err != nil {+ t.Fatalf("unrelated dir was removed: %v", err)+ }+}++func TestRequireNodeForZcodeScript(t *testing.T) {+ if err := requireNodeForZcodeScript("/usr/local/bin/zcode"); err != nil {+ t.Fatalf("native path should pass: %v", err)+ }+ origPath := os.Getenv("PATH")+ t.Cleanup(func() { os.Setenv("PATH", origPath) })+ t.Setenv("PATH", t.TempDir()) // empty of node+ err := requireNodeForZcodeScript("/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs")+ if err == nil {+ t.Fatal("expected error when node is missing")+ }+ if !strings.Contains(err.Error(), "Node.js") || !strings.Contains(err.Error(), "node was not found") {+ t.Fatalf("error = %q, want clear Node.js message", err)+ }+}diff --git a/server/pkg/agent/zcode_test.go b/server/pkg/agent/zcode_test.gonew file mode 100644index 0000000000..a52a63dff1--- /dev/null+++ b/server/pkg/agent/zcode_test.go@@ -0,0 +1,1280 @@+package agent++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"+)++// The fakes below are minimal `zcode app-server` implementations written as+// shell scripts (same pattern as the zeroclaw/ACP fakes): they read NDJSON+// frames from stdin, dispatch on the method, and write NDJSON frames to+// stdout. Nothing here resolves or executes a user-installed zcode CLI —+// ExecutablePath always points at a test-created script, per the package's+// testing contract.++const fakeZcodeSessionID = "ses_zcode_fake"++func zcodeTestLogger() *slog.Logger {+ return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+}++// writeFakeZcodeScript materialises script as an executable named "zcode" in+// a temp dir and returns its path.+func writeFakeZcodeScript(t *testing.T, script string) string {+ t.Helper()+ dir := t.TempDir()+ bin := filepath.Join(dir, "zcode")+ if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {+ t.Fatalf("write fake zcode: %v", err)+ }+ return bin+}++func newZcodeTestBackend(t *testing.T, bin string) Backend {+ t.Helper()+ b, err := New("zcode", Config{+ ExecutablePath: bin,+ Logger: zcodeTestLogger(),+ TaskID: "task-1",+ })+ if err != nil {+ t.Fatalf("New(zcode) error: %v", err)+ }+ return b+}++// collectZcodeSession drains Messages concurrently and returns them together+// with the final Result.+func collectZcodeSession(t *testing.T, s *Session) ([]Message, Result) {+ t.Helper()+ var (+ mu sync.Mutex+ msgs []Message+ wg sync.WaitGroup+ )+ wg.Add(1)+ go func() {+ defer wg.Done()+ for msg := range s.Messages {+ mu.Lock()+ msgs = append(msgs, msg)+ mu.Unlock()+ }+ }()+ res := <-s.Result+ wg.Wait()+ return msgs, res+}++func zcodeTextMessages(msgs []Message) []string {+ var out []string+ for _, m := range msgs {+ if m.Type == MessageText {+ out = append(out, m.Content)+ }+ }+ return out+}++// zcodeEventFrame renders one scripted `printf` line that pushes a+// session/event notification with the given seq/type/payload.+func zcodeEventFrame(seq int, evType, payload string) string {+ return fmt.Sprintf(" printf '{\"method\":\"session/event\",\"params\":{\"type\":\"%s\",\"seq\":%d,\"sessionId\":\"%s\",\"payload\":%s}}\\n'\n", evType, seq, fakeZcodeSessionID, payload)+}++// fakeZcodeHappyScript answers session/create, session/subscribe and+// session/send; before send it replays events with seqs below the subscribe+// baseline (replay-gate fixture); after the send acknowledgement it streams+// the scripted `postSend` frames verbatim (each must already be a full NDJSON+// line, usually from zcodeEventFrame). Unknown requests get -32603.+func fakeZcodeHappyScript(postSend string) string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/create"'*)+ printf '{"id":%s,"result":{"protocol":{"name":"ZCode Protocol","version":1},"session":{"sessionId":"` + fakeZcodeSessionID + `"}}}\n' "$id"+ # Replay frames pushed before the client subscribed: seqs below the+ # subscribe baseline, dropped by the gate.+ printf '{"method":"session/event","params":{"type":"turn.started","seq":1,"sessionId":"` + fakeZcodeSessionID + `","payload":{"turnNumber":0}}}\n'+ printf '{"method":"session/event","params":{"type":"model.streaming","seq":2,"sessionId":"` + fakeZcodeSessionID + `","payload":{"kind":"text_delta","delta":"REPLAY","assistantMessageId":"m_replay","partId":"p1"}}}\n'+ printf '{"method":"session/event","params":{"type":"message.upserted","seq":3,"sessionId":"` + fakeZcodeSessionID + `","payload":{"content":"REPLAY ANSWER","toolCalls":[]}}}\n'+ ;;+ *'"method":"session/subscribe"'*)+ printf '{"id":%s,"result":{"sessionId":"` + fakeZcodeSessionID + `","eventSeq":5,"events":[]}}\n' "$id"+ ;;+ *'"method":"session/send"'*)+ printf '{"id":%s,"result":{"sessionId":"` + fakeZcodeSessionID + `","accepted":true,"stateRevision":7}}\n' "$id"+` + postSend + ` ;;+ *'"method":"session/stop"'*)+ printf '{"id":%s,"result":{}}\n' "$id"+ ;;+ *)+ if [ -n "$id" ]; then+ printf '{"id":%s,"error":{"code":-32603,"message":"internal error"}}\n' "$id"+ fi+ ;;+ esac+done+`+}++// TestZcodeHappyPath covers T1: create → subscribe → send → streamed deltas,+// tool frames and a successful terminal event with usage.+func TestZcodeHappyPath(t *testing.T) {+ t.Parallel()+ postSend := zcodeEventFrame(6, "turn.started", `{"turnNumber":1}`) ++ zcodeEventFrame(7, "model.streaming", `{"kind":"text_delta","delta":"Hello ","assistantMessageId":"m1","partId":"p1"}`) ++ zcodeEventFrame(8, "model.streaming", `{"kind":"text_delta","delta":"world","assistantMessageId":"m1","partId":"p1"}`) ++ zcodeEventFrame(9, "tool.updated", `{"kind":"scheduled","toolCallId":"t1","toolName":"bash","input":{"cmd":"ls"}}`) ++ zcodeEventFrame(10, "tool.updated", `{"kind":"result","toolCallId":"t1","toolName":"bash","result":{"content":"file.txt"}}`) ++ zcodeEventFrame(11, "turn.completed", `{"response":"Final answer","resultType":"success","tokenCount":0,"toolCallCount":1,"duration":12,"usage":{"inputTokens":100,"outputTokens":40,"cacheReadTokens":20,"cacheWriteTokens":10,"reasoningTokens":15}}`)+ bin := writeFakeZcodeScript(t, fakeZcodeHappyScript(postSend))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ Model: "zai/glm-5.3",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ msgs, res := collectZcodeSession(t, session)++ if res.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", res.Status, res.Error)+ }+ if res.Output != "Final answer" {+ t.Fatalf("expected output %q, got %q", "Final answer", res.Output)+ }+ if res.SessionID != fakeZcodeSessionID {+ t.Fatalf("expected session id %q, got %q", fakeZcodeSessionID, res.SessionID)+ }+ // TerminalObserved must be published by the time Result is in hand.+ if session.TerminalObserved == nil || !session.TerminalObserved() {+ t.Fatal("expected TerminalObserved to be true before Result was delivered")+ }+ // Usage mapping per plan §1.5: input excludes cache (100-20-10), output+ // includes reasoning (40+15).+ usage, ok := res.Usage["zai/glm-5.3"]+ if !ok {+ t.Fatalf("expected usage keyed by model, got %+v", res.Usage)+ }+ if usage.InputTokens != 70 || usage.OutputTokens != 55 || usage.CacheReadTokens != 20 || usage.CacheWriteTokens != 10 {+ t.Fatalf("unexpected usage mapping: %+v", usage)+ }++ texts := zcodeTextMessages(msgs)+ if len(texts) != 2 || texts[0] != "Hello " || texts[1] != "world" {+ t.Fatalf("expected the two streamed deltas, got %q", texts)+ }+ var sawToolUse, sawToolResult bool+ for _, m := range msgs {+ if m.Type == MessageToolUse && m.CallID == "t1" && m.Tool == "bash" {+ sawToolUse = true+ }+ if m.Type == MessageToolResult && m.CallID == "t1" && m.Output == "file.txt" {+ sawToolResult = true+ }+ }+ if !sawToolUse || !sawToolResult {+ t.Fatalf("expected tool use and result messages, got %+v", msgs)+ }+}++// TestZcodeReplayFramesDropped covers T16: events pushed before the send (and+// with seqs below the subscribe baseline) never reach Messages.+func TestZcodeReplayFramesDropped(t *testing.T) {+ t.Parallel()+ postSend := zcodeEventFrame(6, "turn.completed", `{"response":"done","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}`)+ bin := writeFakeZcodeScript(t, fakeZcodeHappyScript(postSend))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "test prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ msgs, res := collectZcodeSession(t, session)+ if res.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", res.Status, res.Error)+ }+ for _, m := range msgs {+ if m.Type == MessageText && (m.Content == "REPLAY" || m.Content == "REPLAY ANSWER") {+ t.Fatalf("replay frame leaked into transcript: %+v", m)+ }+ }+}++// TestZcodeUpsertedReconcile covers T2: deltas for one assistant message+// followed by the authoritative upserted snapshot produce no duplicate text.+func TestZcodeUpsertedReconcile(t *testing.T) {+ t.Parallel()+ postSend := zcodeEventFrame(6, "model.streaming", `{"kind":"text_delta","delta":"Hello ","assistantMessageId":"m1","partId":"p1"}`) ++ zcodeEventFrame(7, "model.streaming", `{"kind":"text_delta","delta":"world","assistantMessageId":"m1","partId":"p1"}`) ++ zcodeEventFrame(8, "message.upserted", `{"content":"Hello world","toolCalls":[]}`) ++ zcodeEventFrame(9, "turn.completed", `{"response":"Hello world","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}`)+ bin := writeFakeZcodeScript(t, fakeZcodeHappyScript(postSend))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "test prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ msgs, res := collectZcodeSession(t, session)+ if res.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", res.Status, res.Error)+ }+ texts := zcodeTextMessages(msgs)+ if len(texts) != 2 || texts[0] != "Hello " || texts[1] != "world" {+ t.Fatalf("expected exactly the two deltas without duplication, got %q", texts)+ }+}++// TestZcodeUpsertedSuffixAndDivergence covers plan §2.5's other reconcile+// branches: a prefix-matched authoritative snapshot emits only the missing+// suffix; a divergent snapshot falls back to a corrective full text.+func TestZcodeUpsertedSuffixAndDivergence(t *testing.T) {+ t.Parallel()+ postSend := zcodeEventFrame(6, "model.streaming", `{"kind":"text_delta","delta":"Hello","assistantMessageId":"m1","partId":"p1"}`) ++ zcodeEventFrame(7, "message.upserted", `{"content":"Hello world","toolCalls":[]}`) ++ // New assistant message: deltas diverge from the next snapshot.+ zcodeEventFrame(8, "model.streaming", `{"kind":"text_delta","delta":"drift","assistantMessageId":"m2","partId":"p1"}`) ++ zcodeEventFrame(9, "message.upserted", `{"content":"authoritative","toolCalls":[]}`) ++ zcodeEventFrame(10, "turn.completed", `{"response":"authoritative","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}`)+ bin := writeFakeZcodeScript(t, fakeZcodeHappyScript(postSend))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "test prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ msgs, res := collectZcodeSession(t, session)+ if res.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", res.Status, res.Error)+ }+ texts := zcodeTextMessages(msgs)+ // The transcript is append-only: the "Hello" delta, the " world" suffix+ // reconciled from the prefix-matched snapshot, then the divergent "drift"+ // delta stays (it cannot be retracted) and the corrective authoritative+ // full text follows — mirroring codex's delta-then-reconcile behaviour.+ want := []string{"Hello", " world", "drift", "authoritative"}+ if len(texts) != len(want) {+ t.Fatalf("expected %q, got %q", want, texts)+ }+ for i := range want {+ if texts[i] != want[i] {+ t.Fatalf("expected %q, got %q", want, texts)+ }+ }+ if res.Output != "authoritative" {+ t.Fatalf("expected authoritative Output, got %q", res.Output)+ }+}++// TestZcodeResumeSuccess covers T3.+func TestZcodeResumeSuccess(t *testing.T) {+ t.Parallel()+ script := `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/resume"'*)+ printf '{"id":%s,"result":{"session":{"sessionId":"ses_old"}}}\n' "$id"+ printf '{"method":"session/event","params":{"type":"session.resumed","seq":2,"sessionId":"ses_old","payload":{"directory":"/tmp","messageCount":3}}}\n'+ ;;+ *'"method":"session/subscribe"'*)+ printf '{"id":%s,"result":{"sessionId":"ses_old","eventSeq":5,"events":[]}}\n' "$id"+ ;;+ *'"method":"session/send"'*)+ printf '{"id":%s,"result":{"sessionId":"ses_old","accepted":true,"stateRevision":2}}\n' "$id"+` + zcodeEventFrame(6, "turn.completed", `{"response":"resumed answer","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":2}`) + ` ;;+ *'"method":"session/stop"'*)+ printf '{"id":%s,"result":{}}\n' "$id"+ ;;+ esac+done+`+ bin := writeFakeZcodeScript(t, script)++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "next prompt", ExecOptions{+ Cwd: t.TempDir(),+ ResumeSessionID: "ses_old",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ msgs, res := collectZcodeSession(t, session)+ if res.Status != "completed" || res.Output != "resumed answer" {+ t.Fatalf("expected completed resumed answer, got status=%q output=%q error=%q", res.Status, res.Output, res.Error)+ }+ if res.SessionID != "ses_old" {+ t.Fatalf("expected session id preserved, got %q", res.SessionID)+ }+ if res.ResumeRejected {+ t.Fatal("expected ResumeRejected=false on a successful resume")+ }+ if got := zcodeTextMessages(msgs); len(got) != 0 {+ t.Fatalf("expected no message.upserted content from resume, got %+v", msgs)+ }+}++// TestZcodeResumeRejected covers T4: -32004 on resume is positive evidence of+// a rejected resume, with the session id preserved.+func TestZcodeResumeRejected(t *testing.T) {+ t.Parallel()+ script := `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/resume"'*)+ printf '{"id":%s,"error":{"code":-32004,"message":"Session not found: ses_gone"}}\n' "$id"+ ;;+ esac+done+`+ bin := writeFakeZcodeScript(t, script)++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "prompt", ExecOptions{+ Cwd: t.TempDir(),+ ResumeSessionID: "ses_gone",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ _, res := collectZcodeSession(t, session)+ if res.Status != "failed" {+ t.Fatalf("expected failed, got %q", res.Status)+ }+ if !res.ResumeRejected {+ t.Fatal("expected ResumeRejected=true for -32004")+ }+ if res.SessionID != "ses_gone" {+ t.Fatalf("expected session id preserved for daemon gating, got %q", res.SessionID)+ }+}++// TestZcodeResumeInternalErrorNotRejection covers T5: a -32603 on resume must+// NOT set ResumeRejected — only the structured rejection code may.+func TestZcodeResumeInternalErrorNotRejection(t *testing.T) {+ t.Parallel()+ script := `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/resume"'*)+ printf '{"id":%s,"error":{"code":-32603,"message":"internal error"}}\n' "$id"+ ;;+ esac+done+`+ bin := writeFakeZcodeScript(t, script)++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "prompt", ExecOptions{+ Cwd: t.TempDir(),+ ResumeSessionID: "ses_old",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ _, res := collectZcodeSession(t, session)+ if res.Status != "failed" {+ t.Fatalf("expected failed, got %q", res.Status)+ }+ if res.ResumeRejected {+ t.Fatal("expected ResumeRejected=false for a non-rejection failure")+ }+}++// TestZcodeCancelViaStop covers T6: daemon cancellation sends session/stop+// and maps the cancelled completion to aborted.+func TestZcodeCancelViaStop(t *testing.T) {+ t.Parallel()+ script := `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/create"'*)+ printf '{"id":%s,"result":{"session":{"sessionId":"` + fakeZcodeSessionID + `"}}}\n' "$id"+ ;;+ *'"method":"session/subscribe"'*)+ printf '{"id":%s,"result":{"sessionId":"` + fakeZcodeSessionID + `","eventSeq":5,"events":[]}}\n' "$id"+ ;;+ *'"method":"session/send"'*)+ printf '{"id":%s,"result":{"sessionId":"` + fakeZcodeSessionID + `","accepted":true,"stateRevision":7}}\n' "$id"+ # Stay silent: the turn hangs until the daemon cancels.+ ;;+ *'"method":"session/stop"'*)+ printf '{"id":%s,"result":{}}\n' "$id"+` + zcodeEventFrame(6, "turn.completed", `{"response":"","resultType":"cancelled","tokenCount":0,"toolCallCount":0,"duration":5}`) + ` ;;+ esac+done+`+ bin := writeFakeZcodeScript(t, script)++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ session, err := newZcodeTestBackend(t, bin).Execute(ctx, "prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ done := make(chan Result, 1)+ go func() {+ for range session.Messages {+ }+ done <- <-session.Result+ }()+ time.Sleep(200 * time.Millisecond) // let the send land+ cancel()+ select {+ case res := <-done:+ if res.Status != "aborted" {+ t.Fatalf("expected aborted, got status=%q error=%q", res.Status, res.Error)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timed out waiting for the cancelled result")+ }+}++// TestZcodeHardTimeout covers T7: a silent turn dies with status timeout.+func TestZcodeHardTimeout(t *testing.T) {+ t.Parallel()+ bin := writeFakeZcodeScript(t, fakeZcodeHappyScript(""))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "prompt", ExecOptions{+ Cwd: t.TempDir(),+ Timeout: 300 * time.Millisecond,+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ _, res := collectZcodeSession(t, session)+ if res.Status != "timeout" {+ t.Fatalf("expected timeout, got status=%q error=%q", res.Status, res.Error)+ }+}++// TestZcodeTurnFailed covers T8.+func TestZcodeTurnFailed(t *testing.T) {+ t.Parallel()+ postSend := zcodeEventFrame(6, "turn.failed", `{"error":{"type":"provider","message":"provider exploded","retryable":false},"turnPhase":"executing"}`)+ bin := writeFakeZcodeScript(t, fakeZcodeHappyScript(postSend))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ _, res := collectZcodeSession(t, session)+ if res.Status != "failed" {+ t.Fatalf("expected failed, got %q", res.Status)+ }+ if !strings.Contains(res.Error, "provider exploded") {+ t.Fatalf("expected error to carry the failure message, got %q", res.Error)+ }+}++// TestZcodeTurnFailedRetryableHint covers plan §2.5's retryable surfacing.+func TestZcodeTurnFailedRetryableHint(t *testing.T) {+ t.Parallel()+ postSend := zcodeEventFrame(6, "turn.failed", `{"error":{"type":"provider","message":"boom","attribution":{"source":"network"}},"turnPhase":"executing"}`)+ bin := writeFakeZcodeScript(t, fakeZcodeHappyScript(postSend))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ _, res := collectZcodeSession(t, session)+ if !strings.Contains(res.Error, "retryable") {+ t.Fatalf("expected a retryable hint in the error, got %q", res.Error)+ }+}++// TestZcodePermissionAndUnknownReverseRequests covers T9 + T10 at the+// transport level: interaction/requestPermission is denied fail-closed and an+// unknown server-originated request is answered with -32601.+func TestZcodePermissionAndUnknownReverseRequests(t *testing.T) {+ t.Parallel()+ var buf bytes.Buffer+ c := &zcodeClient{stdin: &buf, pending: make(map[int]*pendingRPC), processDone: make(chan struct{})}++ c.handleLine(`{"id":"server-1","method":"interaction/requestPermission","params":{"toolCallId":"t1"}}`)+ if !strings.Contains(buf.String(), `"decision":"deny"`) {+ t.Fatalf("expected a deny response, got %q", buf.String())+ }++ // A real app-server asks this during session/create; an unanswered+ // request fails the create with -32022 after its 15s timeout, so the+ // client must answer with the schema defaults.+ buf.Reset()+ c.handleLine(`{"id":"server-2","method":"session/requestRuntimePreferences","params":{"sessionId":"ses","scope":"runtime-materialization"}}`)+ if !strings.Contains(buf.String(), `"nativeSearchEnhancementsEnabled":false`) ||+ !strings.Contains(buf.String(), `"modelContextBudgetStrategy":"preflight-v1"`) {+ t.Fatalf("expected runtime-preferences defaults, got %q", buf.String())+ }++ buf.Reset()+ c.handleLine(`{"id":"server-3","method":"workspace/generateText","params":{}}`)+ if !strings.Contains(buf.String(), "-32601") {+ t.Fatalf("expected -32601 for an unsupported reverse request, got %q", buf.String())+ }++ // Notifications other than session/event are ignored without effect.+ buf.Reset()+ c.handleLine(`{"method":"startup/storageState","params":{}}`)+ c.handleLine(`{"method":"state.updated","params":{}}`)+ if buf.String() != "" {+ t.Fatalf("expected no response to plain notifications, got %q", buf.String())+ }+}++// TestZcodeUnknownNotificationDoesNotBreakFlow covers T10 end-to-end.+func TestZcodeUnknownNotificationDoesNotBreakFlow(t *testing.T) {+ t.Parallel()+ postSend := ` printf '{"method":"mcpResourceSamples","params":{}}\n'+ printf '{"id":"srv-9","method":"interaction/browserList","params":{}}\n'+` + zcodeEventFrame(6, "turn.completed", `{"response":"ok","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}`)+ bin := writeFakeZcodeScript(t, fakeZcodeHappyScript(postSend))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ _, res := collectZcodeSession(t, session)+ if res.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", res.Status, res.Error)+ }+}++// TestZcodeStderrFailurePromotion covers T15: a CLI that dies before the+// handshake completes fails the run with the stderr tail attached.+func TestZcodeStderrFailurePromotion(t *testing.T) {+ t.Parallel()+ bin := writeFakeZcodeScript(t, `#!/bin/sh+echo "zcode: authentication failed: invalid api key" >&2+exit 1+`)++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ _, res := collectZcodeSession(t, session)+ if res.Status != "failed" {+ t.Fatalf("expected failed, got %q", res.Status)+ }+ if !strings.Contains(res.Error, "authentication failed") {+ t.Fatalf("expected the stderr tail in the error, got %q", res.Error)+ }+}++// TestZcodeThinkingDeltas covers T19: reasoning deltas map to MessageThinking.+func TestZcodeThinkingDeltas(t *testing.T) {+ t.Parallel()+ postSend := zcodeEventFrame(6, "model.streaming", `{"kind":"reasoning_delta","delta":"thinking...","assistantMessageId":"m1","partId":"r1"}`) ++ zcodeEventFrame(7, "turn.completed", `{"response":"done","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}`)+ bin := writeFakeZcodeScript(t, fakeZcodeHappyScript(postSend))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ msgs, res := collectZcodeSession(t, session)+ if res.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", res.Status, res.Error)+ }+ sawThinking := false+ for _, m := range msgs {+ if m.Type == MessageThinking && m.Content == "thinking..." {+ sawThinking = true+ }+ if m.Type == MessageText {+ t.Fatalf("expected no MessageText without text deltas, got %+v", m)+ }+ }+ if !sawThinking {+ t.Fatalf("expected a thinking message, got %+v", msgs)+ }+}++// TestZcodeModelSelectionSplit covers T14.+func TestZcodeModelSelectionSplit(t *testing.T) {+ t.Parallel()+ provider, model, ok := splitZcodeModelSelection("zai/glm-5.3")+ if !ok || provider != "zai" || model != "glm-5.3" {+ t.Fatalf("expected zai/glm-5.3 split, got %q/%q ok=%v", provider, model, ok)+ }+ if _, _, ok := splitZcodeModelSelection("glm-5.3"); ok {+ t.Fatal("expected a bare id to be rejected (no fabricated providerId)")+ }+ if _, _, ok := splitZcodeModelSelection(""); ok {+ t.Fatal("expected an empty model to be rejected")+ }+ if _, _, ok := splitZcodeModelSelection("/glm"); ok {+ t.Fatal("expected an empty provider to be rejected")+ }+}++// TestZcodeBlockedArgs covers T12.+func TestZcodeBlockedArgs(t *testing.T) {+ t.Parallel()+ got := filterCustomArgs([]string{+ "--flag", "app-server", "--surface", "cli", "-p", "hi", "tui", "--prompt=x", "version",+ "--version", "-v", "--keep-me",+ }, zcodeBlockedArgs, zcodeTestLogger())+ want := []string{"--flag", "--keep-me"}+ if len(got) != len(want) {+ t.Fatalf("expected %v, got %v", want, got)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("expected %v, got %v", want, got)+ }+ }+}++// TestZcodeMcpServerConversion covers T11: canonical and alt-key configs both+// map to the {name,value} pair-array shape, and invalid entries are skipped.+func TestZcodeMcpServerConversion(t *testing.T) {+ t.Parallel()+ t.Run("canonical stdio and remote", func(t *testing.T) {+ out, err := buildZcodeMcpServers(json.RawMessage(`{"mcpServers":{"fs":{"command":"npx","args":["-y","fs"],"env":{"TOKEN":"secret"}},"web":{"type":"sse","url":"https://mcp.example/sse","headers":{"X-Key":"k"}}}}`), zcodeTestLogger())+ if err != nil {+ t.Fatalf("buildZcodeMcpServers error: %v", err)+ }+ if len(out) != 2 {+ t.Fatalf("expected 2 entries, got %d: %+v", len(out), out)+ }+ stdio, ok := out[0].(map[string]any)+ if !ok || stdio["command"] != "npx" {+ t.Fatalf("expected stdio entry first, got %+v", out[0])+ }+ env, ok := stdio["env"].([]map[string]any)+ if !ok || len(env) != 1 || env[0]["name"] != "TOKEN" || env[0]["value"] != "secret" {+ t.Fatalf("expected {name,value} env pairs, got %+v", stdio["env"])+ }+ remote, ok := out[1].(map[string]any)+ if !ok || remote["type"] != "sse" || remote["url"] != "https://mcp.example/sse" {+ t.Fatalf("expected remote entry second, got %+v", out[1])+ }+ })+ t.Run("alt-key servers", func(t *testing.T) {+ out, err := buildZcodeMcpServers(json.RawMessage(`{"servers":{"fs":{"command":"npx"}}}`), zcodeTestLogger())+ if err != nil || len(out) != 1 {+ t.Fatalf("expected 1 entry via alt-key tolerance, got %d entries err=%v", len(out), err)+ }+ })+ t.Run("invalid json", func(t *testing.T) {+ if _, err := buildZcodeMcpServers(json.RawMessage(`{`), zcodeTestLogger()); err == nil {+ t.Fatal("expected an error")+ }+ })+ t.Run("entry without command or url skipped", func(t *testing.T) {+ out, err := buildZcodeMcpServers(json.RawMessage(`{"mcpServers":{"bad":{},"good":{"command":"run"}}}`), zcodeTestLogger())+ if err != nil || len(out) != 1 {+ t.Fatalf("expected the bad entry skipped, got %d entries err=%v", len(out), err)+ }+ })+}++// TestZcodeVersionGate covers T13.+func TestZcodeVersionGate(t *testing.T) {+ t.Parallel()+ if err := CheckMinVersion("zcode", "0.16.9"); err != nil {+ t.Fatalf("expected 0.16.9 to pass, got %v", err)+ }+ if err := CheckMinVersion("zcode", "0.15.2"); err == nil {+ t.Fatal("expected 0.15.2 to be rejected below the 0.16.0 floor")+ }+}++// TestZcodeRoleFilter covers T17/T18 discrimination rules.+func TestZcodeRoleFilter(t *testing.T) {+ t.Parallel()+ f := newZcodeRoleFilter("the full prompt text")++ // ① user echo (exact full sent input): dropped, first occurrence only.+ if f.deliver(zcodeUpsertedPayload{Content: "the full prompt text"}) {+ t.Fatal("expected the user echo to be dropped")+ }+ // ① assistant re-quoting the prompt verbatim: delivered (second occurrence).+ if !f.deliver(zcodeUpsertedPayload{Content: "the full prompt text"}) {+ t.Fatal("expected a second occurrence of the same content to be delivered")+ }+ // ② system payloads: dropped by type or compactBoundary.+ if f.deliver(zcodeUpsertedPayload{Type: "init", Content: "hi"}) {+ t.Fatal("expected a system init message to be dropped")+ }+ if f.deliver(zcodeUpsertedPayload{Type: "compact_boundary", Content: "c"}) {+ t.Fatal("expected a compact boundary message to be dropped")+ }+ if f.deliver(zcodeUpsertedPayload{CompactBoundary: json.RawMessage(`{}`), Content: "c"}) {+ t.Fatal("expected a compactBoundary payload to be dropped")+ }+ // ③ toolCalls presence marks assistant (even an empty array).+ if !f.deliver(zcodeUpsertedPayload{Content: "answer", ToolCalls: []json.RawMessage{}}) {+ t.Fatal("expected an assistant payload with toolCalls to be delivered")+ }+ // ④ fallback: bare content is delivered.+ if !f.deliver(zcodeUpsertedPayload{Content: "bare answer"}) {+ t.Fatal("expected a bare content payload to be delivered")+ }+ // Exact matching only: a string that merely extends the input is not an echo.+ f2 := newZcodeRoleFilter("the full prompt")+ if !f2.deliver(zcodeUpsertedPayload{Content: "the full prompt text"}) {+ t.Fatal("expected exact matching to leave a longer assistant text alone")+ }+}++// TestZcodeNewConstructionLockstep proves New can construct the zcode backend+// and that Execute with a missing executable fails fast without spawning.+func TestZcodeNewConstructionLockstep(t *testing.T) {+ if !IsKnownThinkingValue("zcode", "max") || !IsKnownThinkingValue("zcode", "future-level") || IsKnownThinkingValue("zcode", "bad level;") {+ t.Fatal("ZCode must accept safe dynamic reasoning tokens at the server boundary")+ }++ t.Parallel()+ b, err := New("zcode", Config{ExecutablePath: missingAgentExecutable(t, "zcode"), Logger: zcodeTestLogger()})+ if err != nil {+ t.Fatalf("New(zcode) error: %v", err)+ }+ if _, ok := b.(*zcodeBackend); !ok {+ t.Fatalf("expected *zcodeBackend, got %T", b)+ }+ if _, err := b.Execute(context.Background(), "p", ExecOptions{}); err == nil {+ t.Fatal("expected Execute to fail for a missing executable")+ } else if !errors.Is(err, exec.ErrNotFound) && !strings.Contains(err.Error(), "not found") {+ t.Fatalf("unexpected error shape: %v", err)+ }+}++// TestZcodeWorkspaceKeyFallback covers the real-binary smoke finding: the+// strict workspace ref schema rejects an empty workspaceKey with -32602, so a+// backend without a TaskID must still send a non-empty key on session/create.+func TestZcodeWorkspaceKeyFallback(t *testing.T) {+ t.Parallel()+ if got := zcodeWorkspaceKey("task-9", "/tmp/w"); got != "task-9" {+ t.Fatalf("expected the task id to win, got %q", got)+ }+ got := zcodeWorkspaceKey("", "relative/dir")+ if !filepath.IsAbs(got) {+ t.Fatalf("expected an absolute fallback key, got %q", got)+ }+ if !strings.HasSuffix(got, "relative/dir") {+ t.Fatalf("expected the fallback key to resolve the cwd, got %q", got)+ }+}++// TestZcodeCreateSendsNonEmptyWorkspaceKey drives a fake server that captures+// the raw session/create frame and asserts the workspace key is non-empty —+// the exact validation the real CLI enforced in the first smoke run.+func TestZcodeCreateSendsNonEmptyWorkspaceKey(t *testing.T) {+ capture := filepath.Join(t.TempDir(), "create.txt")+ t.Setenv("ZCODE_CAPTURE", capture)+ bin := writeFakeZcodeScript(t, `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/create"'*)+ printf '%s\n' "$line" >> "$ZCODE_CAPTURE"+ printf '{"id":%s,"result":{"protocol":{"name":"ZCode Protocol","version":1},"session":{"sessionId":"`+fakeZcodeSessionID+`"}}}\n' "$id"+ ;;+ *'"method":"session/subscribe"'*)+ printf '{"id":%s,"result":{"sessionId":"`+fakeZcodeSessionID+`","eventSeq":5,"events":[]}}\n' "$id"+ ;;+ *'"method":"session/send"'*)+ printf '{"id":%s,"result":{"sessionId":"`+fakeZcodeSessionID+`","accepted":true,"stateRevision":7}}\n' "$id"+`+zcodeEventFrame(6, "turn.completed", `{"response":"done","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}`)+` ;;+ esac+done+`)+ b, err := New("zcode", Config{+ ExecutablePath: bin,+ Logger: zcodeTestLogger(),+ // Deliberately no TaskID: the fallback path is what the smoke test hit.+ })+ if err != nil {+ t.Fatalf("New(zcode) error: %v", err)+ }+ cwd := t.TempDir()+ session, err := b.Execute(context.Background(), "p", ExecOptions{Cwd: cwd})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ if _, res := collectZcodeSession(t, session); res.Status != "completed" {+ t.Fatalf("expected completed, got %q error=%q", res.Status, res.Error)+ }+ raw, err := os.ReadFile(capture)+ if err != nil {+ t.Fatalf("session/create frame not captured: %v", err)+ }+ var frame struct {+ Params struct {+ Workspace struct {+ WorkspaceKey string `json:"workspaceKey"`+ } `json:"workspace"`+ } `json:"params"`+ }+ if err := json.Unmarshal(raw, &frame); err != nil {+ t.Fatalf("parse captured frame: %v", err)+ }+ if frame.Params.Workspace.WorkspaceKey == "" {+ t.Fatal("session/create carried an empty workspaceKey")+ }+}++// TestZcodeModelSelectionReasoningLevel covers the real-binary smoke finding:+// reasoning-capable models reject session/create with "Reasoning level is+// required" unless the selection carries options.reasoningLevel, so a+// non-empty thinking level must ride inside both the create `model` and the+// send `modelSelection` payloads.+func TestZcodeModelSelectionReasoningLevel(t *testing.T) {+ t.Parallel()+ with := zcodeModelSelection("zai-api", "GLM-5.3-Flash", "low")+ opts, ok := with["options"].(map[string]any)+ if !ok || opts["reasoningLevel"] != "low" {+ t.Fatalf("expected options.reasoningLevel=low, got %+v", with["options"])+ }+ without := zcodeModelSelection("zai-api", "GLM-5.3", "")+ if _, ok := without["options"]; ok {+ t.Fatalf("expected no options for an empty thinking level, got %+v", without)+ }+}++// TestZcodeCreateSendCarryReasoningLevel drives a fake server that captures+// the raw session/create and session/send frames and asserts both carry+// options.reasoningLevel — the exact validation the real CLI enforced when the+// smoke run selected GLM-5.3-Flash without a reasoning level.+func TestZcodeCreateSendCarryReasoningLevel(t *testing.T) {+ captureDir := t.TempDir()+ createCapture := filepath.Join(captureDir, "create.txt")+ sendCapture := filepath.Join(captureDir, "send.txt")+ t.Setenv("ZCODE_CREATE_CAPTURE", createCapture)+ t.Setenv("ZCODE_SEND_CAPTURE", sendCapture)+ bin := writeFakeZcodeScript(t, `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/create"'*)+ printf '%s\n' "$line" >> "$ZCODE_CREATE_CAPTURE"+ printf '{"id":%s,"result":{"protocol":{"name":"ZCode Protocol","version":1},"session":{"sessionId":"`+fakeZcodeSessionID+`"}}}\n' "$id"+ ;;+ *'"method":"session/subscribe"'*)+ printf '{"id":%s,"result":{"sessionId":"`+fakeZcodeSessionID+`","eventSeq":5,"events":[]}}\n' "$id"+ ;;+ *'"method":"session/send"'*)+ printf '%s\n' "$line" >> "$ZCODE_SEND_CAPTURE"+ printf '{"id":%s,"result":{"sessionId":"`+fakeZcodeSessionID+`","accepted":true,"stateRevision":7}}\n' "$id"+`+zcodeEventFrame(6, "turn.completed", `{"response":"done","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}`)+` ;;+ esac+done+`)+ b, err := New("zcode", Config{+ ExecutablePath: bin,+ Logger: zcodeTestLogger(),+ TaskID: "task-1",+ })+ if err != nil {+ t.Fatalf("New(zcode) error: %v", err)+ }+ session, err := b.Execute(context.Background(), "p", ExecOptions{+ Cwd: t.TempDir(),+ Model: "zai-api/GLM-5.3-Flash",+ ThinkingLevel: "low",+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ if _, res := collectZcodeSession(t, session); res.Status != "completed" {+ t.Fatalf("expected completed, got %q error=%q", res.Status, res.Error)+ }++ assertReasoningLevel := func(path string) {+ t.Helper()+ raw, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("captured frame missing (%s): %v", path, err)+ }+ var frame struct {+ Params struct {+ Model zcodeSelectionJSON `json:"model"`+ SendSel zcodeSelectionJSON `json:"modelSelection"`+ } `json:"params"`+ }+ if err := json.Unmarshal(raw, &frame); err != nil {+ t.Fatalf("parse captured frame: %v", err)+ }+ sel := frame.Params.Model+ if sel.ProviderID == "" {+ sel = frame.Params.SendSel+ }+ if sel.ProviderID == "" {+ t.Fatalf("%s carried neither model nor modelSelection: %s", path, raw)+ }+ if sel.ProviderID != "zai-api" || sel.ModelID != "GLM-5.3-Flash" {+ t.Fatalf("%s unexpected selection: %+v", path, sel)+ }+ if sel.Options.ReasoningLevel != "low" {+ t.Fatalf("%s missing options.reasoningLevel=low: %+v", path, sel.Options)+ }+ }+ assertReasoningLevel(createCapture)+ assertReasoningLevel(sendCapture)+}++// zcodeSelectionJSON mirrors the wire shape of the create `model` / send+// `modelSelection` payload for capture-based assertions.+type zcodeSelectionJSON struct {+ ProviderID string `json:"providerId"`+ ModelID string `json:"modelId"`+ Options struct {+ ReasoningLevel string `json:"reasoningLevel"`+ } `json:"options"`+}++// fakeZcodeDiscoveryScript answers one session/create with a snapshot whose+// settings.model.available carries a reasoning-capable current model, a bare+// second model and a disabled third. Before the response it pushes the+// control-frame notifications a real server emits and — like the real 0.16.9+// app-server, verified live — a session/requestRuntimePreferences reverse+// request that must be answered or the create fails with -32022 after its+// 15s timeout. Every received frame is appended to $ZCODE_DISCOVERY_CAPTURE+// for wire assertions.+const fakeZcodeDiscoveryScript = `#!/bin/sh+while IFS= read -r line; do+ printf '%s\n' "$line" >> "$ZCODE_DISCOVERY_CAPTURE"+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/create"'*)+ printf '{"method":"startup/storagePath","params":{"path":"/tmp/storage"}}\n'+ printf '{"method":"state.updated","params":{"state":"ready"}}\n'+ printf '{"id":101,"method":"session/requestRuntimePreferences","params":{"sessionId":"ses_pending","scope":"runtime-materialization"}}\n'+ # A real server materializes the runtime from the preferences answer+ # before completing the create, so wait for it — this also pins the+ # client's answer into the capture before the response can end the run.+ IFS= read -r prefs_answer+ printf '%s\n' "$prefs_answer" >> "$ZCODE_DISCOVERY_CAPTURE"+ printf '{"id":%s,"result":{"protocol":{"name":"ZCode Protocol","version":1},"session":{"sessionId":"ses_disc"},"settings":{"model":{"current":{"providerId":"zai-api","modelId":"GLM-5.3-Flash"},"available":[{"ref":{"providerId":"zai-api","modelId":"GLM-5.3-Flash"},"label":"GLM-5.3-Flash","contextWindow":200000,"reasoning":{"levels":[{"value":"low","label":"Low"},{"value":"high","label":"High","description":"Deeper reasoning"}],"defaultLevel":"low"}},{"ref":{"providerId":"zai-api","modelId":"GLM-5.3"},"label":"GLM-5.3"},{"ref":{"providerId":"zai-api","modelId":"GLM-5.3-Air"},"label":"GLM-5.3-Air","disabledReason":"requires a coding plan"}]}},"projection":{},"runtime":{},"messages":[]}}\n' "$id"+ ;;+ *)+ if [ -n "$id" ]; then+ printf '{"id":%s,"error":{"code":-32601,"message":"method not supported"}}\n' "$id"+ fi+ ;;+ esac+done+`++// TestZcodeModelDiscovery covers the discovery happy path: the catalog maps+// settings.model.available onto composite `providerId/modelId` ids, the+// registry's current selection badges Default, per-model reasoning levels+// become the thinking catalog (which is what makes the UI render the thinking+// picker for zcode), and disabled entries land in Unavailable with the+// runtime's own reason. The captured create frame pins the wire contract:+// no `jsonrpc` member (the strict schema rejects one) and a deferred draft+// session so discovery leaves nothing in the session store.+func TestZcodeModelDiscovery(t *testing.T) {+ capture := filepath.Join(t.TempDir(), "create.txt")+ t.Setenv("ZCODE_DISCOVERY_CAPTURE", capture)+ bin := writeFakeZcodeScript(t, fakeZcodeDiscoveryScript)++ catalog, err := discoverZcodeModels(context.Background(), NewCommand(bin, nil))+ if err != nil {+ t.Fatalf("discoverZcodeModels error: %v", err)+ }+ if len(catalog.Models) != 2 {+ t.Fatalf("expected 2 runnable models, got %d: %+v", len(catalog.Models), catalog.Models)+ }+ flash := catalog.Models[0]+ if flash.ID != "zai-api/GLM-5.3-Flash" || flash.Provider != "zai-api" || flash.Label != "GLM-5.3-Flash" {+ t.Fatalf("unexpected first model: %+v", flash)+ }+ if !flash.Default {+ t.Fatal("expected the registry's current selection to carry the Default badge")+ }+ if flash.Thinking == nil || len(flash.Thinking.SupportedLevels) != 2 ||+ flash.Thinking.DefaultLevel != "low" ||+ flash.Thinking.SupportedLevels[0].Value != "low" ||+ flash.Thinking.SupportedLevels[1].Value != "high" ||+ flash.Thinking.SupportedLevels[1].Description != "Deeper reasoning" {+ t.Fatalf("unexpected thinking catalog: %+v", flash.Thinking)+ }+ if second := catalog.Models[1]; second.ID != "zai-api/GLM-5.3" || second.Default || second.Thinking != nil {+ t.Fatalf("unexpected second model: %+v", second)+ }+ if len(catalog.Unavailable) != 1 ||+ catalog.Unavailable[0].ID != "zai-api/GLM-5.3-Air" ||+ catalog.Unavailable[0].Reason != "requires a coding plan" {+ t.Fatalf("unexpected unavailable list: %+v", catalog.Unavailable)+ }+ if !catalog.Verified() {+ t.Fatal("a discovered catalog must be Verified")+ }++ raw, err := os.ReadFile(capture)+ if err != nil {+ t.Fatalf("captured create frame missing: %v", err)+ }+ if strings.Contains(string(raw), `"jsonrpc"`) {+ t.Fatalf("zcode wire frames must not carry a jsonrpc member: %s", raw)+ }+ if !strings.Contains(string(raw), `"persistence":"deferred"`) {+ t.Fatalf("discovery must create a deferred draft session: %s", raw)+ }+ // The capture also records the client's answer to the server's+ // requestRuntimePreferences reverse request: it must carry the schema+ // defaults, or a real app-server fails the create with -32022.+ var prefsAnswer struct {+ ID int `json:"id"`+ Result struct {+ NativeSearchEnhancementsEnabled bool `json:"nativeSearchEnhancementsEnabled"`+ MemoryEnabled bool `json:"memoryEnabled"`+ AskUserQuestionAutoResolutionEnabled bool `json:"askUserQuestionAutoResolutionEnabled"`+ ModelContextBudgetStrategy string `json:"modelContextBudgetStrategy"`+ } `json:"result"`+ }+ if err := json.Unmarshal([]byte(strings.SplitN(string(raw), "\n", 2)[1]), &prefsAnswer); err != nil {+ t.Fatalf("expected the runtime-preferences answer as the second captured frame: %v\n%s", err, raw)+ }+ if prefsAnswer.ID != 101 ||+ prefsAnswer.Result.NativeSearchEnhancementsEnabled ||+ prefsAnswer.Result.MemoryEnabled ||+ !prefsAnswer.Result.AskUserQuestionAutoResolutionEnabled ||+ prefsAnswer.Result.ModelContextBudgetStrategy != "preflight-v1" {+ t.Fatalf("unexpected runtime-preferences answer: %+v", prefsAnswer)+ }+}++// TestZcodeModelDiscoveryDegradesToEmpty covers the failure paths: a missing+// binary, a server that dies mid-conversation, and a create rejection (an+// unauthenticated account) all yield the empty catalog without an error, so+// the UI keeps manual model entry instead of surfacing a discovery failure.+func TestZcodeModelDiscoveryDegradesToEmpty(t *testing.T) {+ cases := map[string]struct{ bin, script string }{+ "missing binary": {filepath.Join(t.TempDir(), "missing-zcode"), ""},+ "garbage then exit": {"", `#!/bin/sh+read -r line+printf 'not json at all\n'+exit 0+`},+ "create rejected": {"", `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ printf '{"id":%s,"error":{"code":-32603,"message":"not logged in"}}\n' "$id"+done+`},+ }+ for name, tc := range cases {+ t.Run(name, func(t *testing.T) {+ bin := tc.bin+ if bin == "" {+ bin = writeFakeZcodeScript(t, tc.script)+ }+ catalog, err := discoverZcodeModels(context.Background(), NewCommand(bin, nil))+ if err != nil {+ t.Fatalf("discovery failures must degrade, got error: %v", err)+ }+ if len(catalog.Models) != 0 || catalog.Verified() {+ t.Fatalf("expected an empty unverified catalog, got %+v", catalog)+ }+ })+ }+}++// TestZcodeCatalogFromSnapshotAbsentSettings pins the drift signal: a+// snapshot whose settings.model is missing must report ok=false so the+// caller treats it as schema drift, not as an empty registry.+func TestZcodeCatalogFromSnapshotAbsentSettings(t *testing.T) {+ if _, ok := zcodeCatalogFromSnapshot(json.RawMessage(`{"session":{"sessionId":"ses_x"}}`)); ok {+ t.Fatal("a snapshot without settings.model must not parse as a catalog")+ }+ if _, ok := zcodeCatalogFromSnapshot(json.RawMessage(`not json`)); ok {+ t.Fatal("malformed snapshot must not parse as a catalog")+ }+ empty, ok := zcodeCatalogFromSnapshot(json.RawMessage(`{"settings":{"model":{"available":[]}}}`))+ if !ok || len(empty.Models) != 0 {+ t.Fatalf("an empty registry is a valid empty catalog: ok=%v models=%d", ok, len(empty.Models))+ }+}++// zcodeThinkingDefaultScript serves both halves of an empty-thinking-level+// launch: the discovery create (persistence deferred) answers a catalog whose+// single GLM entry carries the given reasoning fields, and the execution+// create is captured for assertion. resume/subscribe/send complete the run.+// The reasoning JSON is spliced as its own single-quoted shell region+// (” at both seams) so its double quotes survive the parser.+func zcodeThinkingDefaultScript(reasoning string) string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/create"'*)+ case "$line" in+ *'"persistence":"deferred"'*)+ printf '{"id":%s,"result":{"session":{"sessionId":"ses_disc"},"settings":{"model":{"current":{"providerId":"zai-api","modelId":"GLM-5.3"},"available":[{"ref":{"providerId":"zai-api","modelId":"GLM-5.3"},"label":"GLM-5.3","reasoning":''` + reasoning + `''}]}}}}\n' "$id"+ ;;+ *)+ printf '%s\n' "$line" >> "$ZCODE_EXEC_CREATE_CAPTURE"+ printf '{"id":%s,"result":{"protocol":{"name":"ZCode Protocol","version":1},"session":{"sessionId":"ses_run"}}}\n' "$id"+ ;;+ esac+ ;;+ *'"method":"session/subscribe"'*)+ printf '{"id":%s,"result":{"sessionId":"ses_run","eventSeq":5,"events":[]}}\n' "$id"+ ;;+ *'"method":"session/send"'*)+ printf '{"id":%s,"result":{"sessionId":"ses_run","accepted":true,"stateRevision":7}}\n' "$id"+ printf '{"method":"session/event","params":{"type":"turn.completed","seq":6,"sessionId":"ses_run","payload":{"response":"done","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}}}\n'+ ;;+ *)+ if [ -n "$id" ]; then+ printf '{"id":%s,"error":{"code":-32601,"message":"method not supported"}}\n' "$id"+ fi+ ;;+ esac+done+`+}++// TestZcodeEmptyThinkingLevelResolvesDefault is the regression for the+// saved-with-"Default" launch failure: an agent with a zcode model and an+// empty thinking_level died at session/create with -32603 "Reasoning level is+// required" — the empty level means "let the runtime decide", and zcode has+// no implicit default, so the decision must be resolved from the model's own+// catalog the same way its client does: defaultLevel first, else the first+// advertised level.+func TestZcodeEmptyThinkingLevelResolvesDefault(t *testing.T) {+ // Registry shape observed live: levels low/high, defaultLevel max.+ withDefault := `{"levels":[{"value":"low","label":"low"},{"value":"max","label":"max"}],"defaultLevel":"max"}`+ // Same levels without a defaultLevel: zcode's own client falls back to+ // the first available level.+ withoutDefault := `{"levels":[{"value":"low","label":"low"},{"value":"max","label":"max"}]}`++ for name, tc := range map[string]struct {+ reasoning string+ want string+ }{+ "catalog default level": {withDefault, "max"},+ "first advertised level": {withoutDefault, "low"},+ } {+ t.Run(name, func(t *testing.T) {+ createCapture := filepath.Join(t.TempDir(), "exec-create.txt")+ t.Setenv("ZCODE_EXEC_CREATE_CAPTURE", createCapture)+ bin := writeFakeZcodeScript(t, zcodeThinkingDefaultScript(tc.reasoning))++ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "p", ExecOptions{+ Cwd: t.TempDir(),+ Model: "zai-api/GLM-5.3",+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ if _, res := collectZcodeSession(t, session); res.Status != "completed" {+ t.Fatalf("expected completed, got %q error=%q", res.Status, res.Error)+ }++ raw, err := os.ReadFile(createCapture)+ if err != nil {+ t.Fatalf("captured execution create missing: %v", err)+ }+ var frame struct {+ Params struct {+ Model zcodeSelectionJSON `json:"model"`+ } `json:"params"`+ }+ if err := json.Unmarshal(raw, &frame); err != nil {+ t.Fatalf("parse captured create: %v\n%s", err, raw)+ }+ if frame.Params.Model.Options.ReasoningLevel != tc.want {+ t.Fatalf("expected reasoningLevel=%q on the create, got %+v\n%s", tc.want, frame.Params.Model, raw)+ }+ })+ }+}++// TestZcodeResumeOmitsMode captures the session/resume frame and asserts+// mode is absent. Desktop 0.17.0 rejects the key with -32602; session/create+// pins mode "yolo" and the server restores that persisted mode on resume.+func TestZcodeResumeOmitsMode(t *testing.T) {+ capture := filepath.Join(t.TempDir(), "resume.txt")+ t.Setenv("ZCODE_RESUME_CAPTURE", capture)+ bin := writeFakeZcodeScript(t, `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"session/resume"'*)+ printf '%s\n' "$line" >> "$ZCODE_RESUME_CAPTURE"+ printf '{"id":%s,"result":{"session":{"sessionId":"ses_old"}}}\n' "$id"+ ;;+ *'"method":"session/subscribe"'*)+ printf '{"id":%s,"result":{"sessionId":"ses_old","eventSeq":5,"events":[]}}\n' "$id"+ ;;+ *'"method":"session/send"'*)+ printf '{"id":%s,"result":{"sessionId":"ses_old","accepted":true,"stateRevision":2}}\n' "$id"+`+zcodeEventFrame(6, "turn.completed", `{"response":"ok","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}`)+` ;;+ esac+done+`)+ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "next", ExecOptions{+ Cwd: t.TempDir(),+ ResumeSessionID: "ses_old",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ if _, res := collectZcodeSession(t, session); res.Status != "completed" {+ t.Fatalf("expected completed, got %q error=%q", res.Status, res.Error)+ }+ raw, err := os.ReadFile(capture)+ if err != nil {+ t.Fatalf("session/resume frame not captured: %v", err)+ }+ var frame struct {+ Params map[string]json.RawMessage `json:"params"`+ }+ if err := json.Unmarshal(raw, &frame); err != nil {+ t.Fatalf("parse captured frame: %v", err)+ }+ if _, ok := frame.Params["mode"]; ok {+ t.Fatalf("session/resume must omit mode (Desktop 0.17.0 rejects it with -32602); frame=%s", raw)+ }+ sessionID := strings.Trim(string(frame.Params["sessionId"]), `"`)+ if sessionID != "ses_old" {+ t.Fatalf("session/resume sessionId = %q, want ses_old; frame=%s", sessionID, raw)+ }+}++// TestZcodeExecuteRequiresNodeForDesktopBundle asserts Execute fails with a+// clear Node.js message when the resolved path is a .cjs Desktop entry and+// node is absent from PATH — not the vague exec: "node": not found form.+func TestZcodeExecuteRequiresNodeForDesktopBundle(t *testing.T) {+ dir := t.TempDir()+ script := filepath.Join(dir, "zcode.cjs")+ if err := os.WriteFile(script, []byte("console.log('noop')\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PATH", dir) // no node binary+ b, err := New("zcode", Config{+ ExecutablePath: script,+ Logger: zcodeTestLogger(),+ TaskID: "task-1",+ })+ if err != nil {+ t.Fatalf("New(zcode): %v", err)+ }+ _, err = b.Execute(context.Background(), "hi", ExecOptions{Cwd: t.TempDir()})+ if err == nil {+ t.Fatal("expected Execute to fail when node is missing")+ }+ if !strings.Contains(err.Error(), "Node.js") || !strings.Contains(err.Error(), "node was not found") {+ t.Fatalf("error = %q, want clear Node.js message", err)+ }+ if strings.Contains(err.Error(), `exec: "node": executable file not found`) {+ t.Fatalf("error still uses vague exec form: %v", err)+ }+}