Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agent): add ZeroClaw as a native ACP runtime (MUL-6511) (#7351)
Danila Katalshov8a5a6adbf722
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 8dbf140417..1d03e636b6 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -235,7 +235,7 @@ API key と base URL の両方が空の場合、このレイヤーは無効に| `MULTICA_AGENT_TEMP_BASE` | `/tmp`(Linux/macOS) | Linux/macOS 専用。作業ごとのプライベート一時ディレクトリの親ディレクトリ。既存かつ書き込み可能な絶対パスである必要があり、無効な値の場合は `/tmp` にフォールバックせず作業の開始に失敗します。短いパスを選んでください。子ツールがその配下に AF_UNIX ソケットを作成する場合があり、`sun_path` の上限は Linux で 108 バイト、macOS で 104 バイトです || `MULTICA_KEEP_ENV_AFTER_TASK` | `false` | デバッグ用にタスクディレクトリを保持 |-各 AI コーディングツールは `MULTICA_<PROVIDER>_PATH` でコマンドパスを上書きでき、モデル上書き対応ツールでは `MULTICA_<PROVIDER>_MODEL` も利用できます。QwenPaw と MiniMax Code にはモデル変数がなく、MiniMax Code のパス変数は `MULTICA_MCODE_PATH` です。詳しくは [AI コーディングツール比較](/providers#モデルの取得元) を参照してください。DeepSeek Harness は `MULTICA_DSH_PATH` と `MULTICA_DSH_MODEL` に対応しています(値は dsh のモデルカタログにあるモデル ID、例: `deepseek-official/deepseek-chat`)。マシン全体のデフォルト引数 `MULTICA_<PROVIDER>_ARGS` は、現在 Claude Code、Codex、CodeBuddy、Qwen Code、QwenPaw の 5 ツールに対応しています。対応する変数は `MULTICA_CLAUDE_ARGS`、`MULTICA_CODEX_ARGS`、`MULTICA_CODEBUDDY_ARGS`、`MULTICA_QWEN_ARGS`、`MULTICA_QWENPAW_ARGS` です。例:+各 AI コーディングツールは `MULTICA_<PROVIDER>_PATH` でコマンドパスを上書きでき、モデル上書き対応ツールでは `MULTICA_<PROVIDER>_MODEL` も利用できます。QwenPaw と MiniMax Code にはモデル変数がなく、MiniMax Code のパス変数は `MULTICA_MCODE_PATH` です。詳しくは [AI コーディングツール比較](/providers#モデルの取得元) を参照してください。DeepSeek Harness は `MULTICA_DSH_PATH` と `MULTICA_DSH_MODEL` に対応しています(値は dsh のモデルカタログにあるモデル ID、例: `deepseek-official/deepseek-chat`)。ZeroClaw は `MULTICA_ZEROCLAW_PATH` に対応しますが、モデル変数はありません。モデルは ZeroClaw のエージェント設定で管理します。マシン全体のデフォルト引数 `MULTICA_<PROVIDER>_ARGS` は、現在 Claude Code、Codex、CodeBuddy、Qwen Code、QwenPaw の 5 ツールに対応しています。対応する変数は `MULTICA_CLAUDE_ARGS`、`MULTICA_CODEX_ARGS`、`MULTICA_CODEBUDDY_ARGS`、`MULTICA_QWEN_ARGS`、`MULTICA_QWENPAW_ARGS` です。例:```dotenvMULTICA_CLAUDE_PATH=/opt/bin/claudediff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex 48d6873107..fa2a7e4e77 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -235,7 +235,7 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스| `MULTICA_AGENT_TEMP_BASE` | `/tmp`(Linux/macOS) | Linux/macOS 전용. 작업별 비공개 임시 디렉터리의 상위 디렉터리입니다. 기존의 쓰기 가능한 절대 경로여야 하며, 값이 잘못되면 `/tmp`로 대체하지 않고 작업 시작에 실패합니다. 짧은 경로를 선택하세요. 하위 도구가 그 아래에 AF_UNIX 소켓을 만들 수 있으며 `sun_path` 제한은 Linux에서 108바이트, macOS에서 104바이트입니다 || `MULTICA_KEEP_ENV_AFTER_TASK` | `false` | 디버깅을 위해 실행 태스크 디렉터리 유지 |-각 AI 코딩 도구는 `MULTICA_<PROVIDER>_PATH`로 명령 경로를 덮어쓸 수 있으며 모델 재정의를 지원하는 도구는 `MULTICA_<PROVIDER>_MODEL`도 사용할 수 있습니다. QwenPaw와 MiniMax Code에는 모델 변수가 없고 MiniMax Code의 경로 변수는 `MULTICA_MCODE_PATH`입니다. 자세한 내용은 [AI 코딩 도구 비교](/providers#모델-출처)를 참고하세요. DeepSeek Harness는 `MULTICA_DSH_PATH`와 `MULTICA_DSH_MODEL`을 지원합니다(값은 dsh 모델 카탈로그의 모델 ID, 예: `deepseek-official/deepseek-chat`). 컴퓨터 전체 기본 인수 `MULTICA_<PROVIDER>_ARGS`는 현재 Claude Code, Codex, CodeBuddy, Qwen Code, QwenPaw 다섯 도구를 지원합니다. 해당 변수는 `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, `MULTICA_QWENPAW_ARGS`입니다. 예시:+각 AI 코딩 도구는 `MULTICA_<PROVIDER>_PATH`로 명령 경로를 덮어쓸 수 있으며 모델 재정의를 지원하는 도구는 `MULTICA_<PROVIDER>_MODEL`도 사용할 수 있습니다. QwenPaw와 MiniMax Code에는 모델 변수가 없고 MiniMax Code의 경로 변수는 `MULTICA_MCODE_PATH`입니다. 자세한 내용은 [AI 코딩 도구 비교](/providers#모델-출처)를 참고하세요. DeepSeek Harness는 `MULTICA_DSH_PATH`와 `MULTICA_DSH_MODEL`을 지원합니다(값은 dsh 모델 카탈로그의 모델 ID, 예: `deepseek-official/deepseek-chat`). ZeroClaw는 `MULTICA_ZEROCLAW_PATH`를 지원하지만 모델 변수는 없습니다. 모델은 ZeroClaw의 에이전트 설정에서 관리합니다. 컴퓨터 전체 기본 인수 `MULTICA_<PROVIDER>_ARGS`는 현재 Claude Code, Codex, CodeBuddy, Qwen Code, QwenPaw 다섯 도구를 지원합니다. 해당 변수는 `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, `MULTICA_QWENPAW_ARGS`입니다. 예시:```dotenvMULTICA_CLAUDE_PATH=/opt/bin/claudediff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 7f474b6b4f..3d54717f18 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -235,7 +235,7 @@ The variables below are read on the computer that runs your agents, not in the A| `MULTICA_AGENT_TEMP_BASE` | `/tmp` (Linux/macOS) | Linux/macOS only. Parent directory for private per-task temp dirs; must be an existing, writable absolute directory, and an invalid value fails task startup instead of falling back to `/tmp`. Pick a short path — child tools may bind AF_UNIX sockets under it, and `sun_path` is limited to 108 bytes on Linux and 104 on macOS || `MULTICA_KEEP_ENV_AFTER_TASK` | `false` | Keep task directories for debugging |-Each AI coding tool accepts `MULTICA_<PROVIDER>_PATH` and `MULTICA_<PROVIDER>_MODEL` to override the command path and default model. QwenPaw and MiniMax Code have no model variable because Multica never sends them a model; MiniMax Code's path variable is `MULTICA_MCODE_PATH` — see [AI coding tools comparison](/providers#model-sources). DeepSeek Harness supports `MULTICA_DSH_PATH` and `MULTICA_DSH_MODEL` (a model id from the dsh catalog, e.g. `deepseek-official/deepseek-chat`). Dim supports `MULTICA_DIM_PATH` and `MULTICA_DIM_MODEL` (a model id from the dim catalog). Machine-wide default arguments via `MULTICA_<PROVIDER>_ARGS` are currently supported for five tools: Claude Code, Codex, CodeBuddy, Qwen Code, and QwenPaw. The variables are `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, and `MULTICA_QWENPAW_ARGS`. For example:+Each AI coding tool accepts `MULTICA_<PROVIDER>_PATH` and `MULTICA_<PROVIDER>_MODEL` to override the command path and default model. QwenPaw and MiniMax Code have no model variable because Multica never sends them a model; MiniMax Code's path variable is `MULTICA_MCODE_PATH` — see [AI coding tools comparison](/providers#model-sources). DeepSeek Harness supports `MULTICA_DSH_PATH` and `MULTICA_DSH_MODEL` (a model id from the dsh catalog, e.g. `deepseek-official/deepseek-chat`). Dim supports `MULTICA_DIM_PATH` and `MULTICA_DIM_MODEL` (a model id from the dim catalog). ZeroClaw supports `MULTICA_ZEROCLAW_PATH` but has no model variable; its agent profile owns the model selection. Machine-wide default arguments via `MULTICA_<PROVIDER>_ARGS` are currently supported for five tools: Claude Code, Codex, CodeBuddy, Qwen Code, and QwenPaw. The variables are `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, and `MULTICA_QWENPAW_ARGS`. For example:```dotenvMULTICA_CLAUDE_PATH=/opt/bin/claudediff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 54efc2e866..7870252b8c 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -235,7 +235,7 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游| `MULTICA_AGENT_TEMP_BASE` | `/tmp`(Linux/macOS) | 仅适用于 Linux/macOS。私有 task 临时目录的父目录;必须是现有、可写的绝对路径,无效值会使 task 启动失败,不会回退到 `/tmp`。请选择较短的路径——子工具可能会在其中绑定 AF_UNIX socket;Linux 的 `sun_path` 上限为 108 字节,macOS 为 104 字节 || `MULTICA_KEEP_ENV_AFTER_TASK` | `false` | 保留执行任务目录用于调试 |-各 AI 编程工具可以使用 `MULTICA_<PROVIDER>_PATH` 覆盖命令路径;支持模型覆盖的工具还可以使用 `MULTICA_<PROVIDER>_MODEL`。QwenPaw 和 MiniMax Code 没有模型变量,因为 Multica 不会向它们传模型;MiniMax Code 的路径变量是 `MULTICA_MCODE_PATH`。详见 [AI 编程工具对比](/providers#模型来源)。DeepSeek Harness 支持 `MULTICA_DSH_PATH` 和 `MULTICA_DSH_MODEL`(取值为 dsh 模型目录中的模型 id,例如 `deepseek-official/deepseek-chat`)。全机默认参数 `MULTICA_<PROVIDER>_ARGS` 目前支持 Claude Code、Codex、CodeBuddy、Qwen Code 和 QwenPaw 五款工具。对应变量是 `MULTICA_CLAUDE_ARGS`、`MULTICA_CODEX_ARGS`、`MULTICA_CODEBUDDY_ARGS`、`MULTICA_QWEN_ARGS` 和 `MULTICA_QWENPAW_ARGS`。例如:+各 AI 编程工具可以使用 `MULTICA_<PROVIDER>_PATH` 覆盖命令路径;支持模型覆盖的工具还可以使用 `MULTICA_<PROVIDER>_MODEL`。QwenPaw 和 MiniMax Code 没有模型变量,因为 Multica 不会向它们传模型;MiniMax Code 的路径变量是 `MULTICA_MCODE_PATH`。详见 [AI 编程工具对比](/providers#模型来源)。DeepSeek Harness 支持 `MULTICA_DSH_PATH` 和 `MULTICA_DSH_MODEL`(取值为 dsh 模型目录中的模型 id,例如 `deepseek-official/deepseek-chat`)。ZeroClaw 支持 `MULTICA_ZEROCLAW_PATH`,但没有模型变量;模型由 ZeroClaw 的智能体配置管理。全机默认参数 `MULTICA_<PROVIDER>_ARGS` 目前支持 Claude Code、Codex、CodeBuddy、Qwen Code 和 QwenPaw 五款工具。对应变量是 `MULTICA_CLAUDE_ARGS`、`MULTICA_CODEX_ARGS`、`MULTICA_CODEBUDDY_ARGS`、`MULTICA_QWEN_ARGS` 和 `MULTICA_QWENPAW_ARGS`。例如:```dotenvMULTICA_CLAUDE_PATH=/opt/bin/claudediff --git a/packages/core/agents/mcp-support.test.ts b/packages/core/agents/mcp-support.test.tsindex 21b6d7fb92..d650c6f948 100644--- a/packages/core/agents/mcp-support.test.ts+++ b/packages/core/agents/mcp-support.test.ts@@ -29,6 +29,9 @@ describe("providerSupportsMcpConfig", () => {expect(providerSupportsMcpConfig("antigravity")).toBe(false);expect(providerSupportsMcpConfig("copilot")).toBe(false);expect(providerSupportsMcpConfig("pi")).toBe(false);+ // ZeroClaw's ACP server never reads `params.mcpServers` — MCP lives in+ // ZeroClaw's own config-dir, so a value saved here could not be honoured.+ expect(providerSupportsMcpConfig("zeroclaw")).toBe(false);expect(providerSupportsMcpConfig(undefined)).toBe(false);expect(providerSupportsMcpConfig(null)).toBe(false);});diff --git a/packages/core/runtimes/display.test.ts b/packages/core/runtimes/display.test.tsindex 6c46ad1114..7336181587 100644--- a/packages/core/runtimes/display.test.ts+++ b/packages/core/runtimes/display.test.ts@@ -107,6 +107,13 @@ describe("runtimeDisplayLabel", () => {provider: "mcode",}),).toBe("box (MiniMax Code)");+ expect(+ runtimeDisplayLabel({+ name: "ZeroClaw (host)",+ custom_name: "box",+ provider: "zeroclaw",+ }),+ ).toBe("box (ZeroClaw)");});it("first-letter-capitalizes non-overridden slugs, matching the daemon", () => {diff --git a/packages/core/runtimes/display.ts b/packages/core/runtimes/display.tsindex f49fc0e23a..4b7545a9a5 100644--- a/packages/core/runtimes/display.ts+++ b/packages/core/runtimes/display.ts@@ -37,7 +37,7 @@ export function runtimeDisplayLabel(* (server/internal/daemon/daemon.go): the daemon bakes that display name into* `name` for the no-alias case (for example, "Trae (host)"), so the aliased label has to use* the exact same names or the two paths drift apart (#5260). `qoderclicn`,- * `dsh`, `traecli`, `qwen`, `qwenpaw`, and `mcode` need overrides today — every other provider is a+ * `dsh`, `traecli`, `qwen`, `qwenpaw`, `mcode`, and `zeroclaw` need overrides today — every other provider is a* first-letter capitalization of its slug on both sides. Keep in sync with the daemon map.*/const PROVIDER_DISPLAY_NAMES: Record<string, string> = {@@ -48,6 +48,7 @@ const PROVIDER_DISPLAY_NAMES: Record<string, string> = {qwenpaw: "QwenPaw",mcode: "MiniMax Code",omp: "Oh-My-Pi",+ zeroclaw: "ZeroClaw",};/**diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 891b28043e..d797672f2e 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -130,6 +130,7 @@ export const RUNTIME_PROFILE_PROTOCOL_FAMILIES = ["qwen","qwenpaw","mcode",+ "zeroclaw",] as const;export type RuntimeProtocolFamily =diff --git a/packages/views/runtimes/components/provider-logo.test.tsx b/packages/views/runtimes/components/provider-logo.test.tsxindex 8e98972c0d..d8002cd944 100644--- a/packages/views/runtimes/components/provider-logo.test.tsx+++ b/packages/views/runtimes/components/provider-logo.test.tsx@@ -92,4 +92,20 @@ describe("ProviderLogo", () => {expect(path?.getAttribute("d")).toContain("ZM11.0587 8.88053");expect(logo?.classList.contains("runtime-logo")).toBe(true);});++ it("renders the ZeroClaw placeholder mark instead of the generic fallback", () => {+ const { container } = render(+ <ProviderLogo provider="zeroclaw" className="runtime-logo" />,+ );++ const logo = container.querySelector("svg");++ // No official ZeroClaw asset has been sourced yet, so this pins the+ // deliberate placeholder mark (three strokes) rather than the generic+ // <Monitor /> fallback that unknown providers get.+ expect(logo?.getAttribute("viewBox")).toBe("0 0 24 24");+ expect(logo?.getAttribute("stroke")).toBe("currentColor");+ expect(logo?.querySelectorAll("path").length).toBe(3);+ expect(logo?.classList.contains("runtime-logo")).toBe(true);+ });});diff --git a/packages/views/runtimes/components/provider-logo.tsx b/packages/views/runtimes/components/provider-logo.tsxindex 695d354aab..229abe81af 100644--- a/packages/views/runtimes/components/provider-logo.tsx+++ b/packages/views/runtimes/components/provider-logo.tsx@@ -345,6 +345,28 @@ function DimLogo({ className }: { className: string }) {return <img src={staticAssetSrc(dimLogo)} alt="" aria-hidden className={className} />;}+// ZeroClaw — no official brand asset has been sourced for this runtime yet+// (multica-ai/multica#1543), so this is a deliberately simple placeholder+// mark (three claw-scratch strokes) rather than a claimed "official" logo.+// currentColor keeps it legible in both themes; swap for a real asset once+// ZeroClaw ships one, following the DimLogo <img> pattern.+function ZeroClawLogo({ className }: { className: string }) {+ return (+ <svg+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ className={className}+ >+ <path d="M5 5l4 14" />+ <path d="M12 5l2 14" />+ <path d="M19 5l-4 14" />+ </svg>+ );+}+export function ProviderLogo({provider,className = "h-4 w-4",@@ -400,6 +422,8 @@ export function ProviderLogo({return <DshLogo className={className} />;case "dim":return <DimLogo className={className} />;+ case "zeroclaw":+ return <ZeroClawLogo className={className} />;default:return <Monitor className={className} />;}diff --git a/scripts/agent-cli-command-names.txt b/scripts/agent-cli-command-names.txtindex 2887a0766b..1b364dcd12 100644--- a/scripts/agent-cli-command-names.txt+++ b/scripts/agent-cli-command-names.txt@@ -22,3 +22,4 @@ qwenqwenpawreasonixtraecli+zeroclawdiff --git a/server/internal/daemon/agents_probe.go b/server/internal/daemon/agents_probe.goindex 3efdabb80f..8c5bbdb803 100644--- a/server/internal/daemon/agents_probe.go+++ b/server/internal/daemon/agents_probe.go@@ -269,6 +269,15 @@ var probeAgentCLIs = func() map[string]AgentEntry {if e, ok := probe("MULTICA_MCODE_PATH", "mcode", ""); ok {agents["mcode"] = e}+ // ZeroClaw (`zeroclaw`) is a Rust-based generic agent CLI, driven over+ // ACP via `zeroclaw acp`. It takes no model env var: its ACP server has no+ // `session/set_model` and no handler reads a model param, so the model+ // comes from ZeroClaw's own agent profile and ExecOptions.Model can never+ // be applied — see ModelSelectionSupported. Reading one here would only+ // advertise a knob that silently does nothing.+ if e, ok := probe("MULTICA_ZEROCLAW_PATH", "zeroclaw", ""); ok {+ agents["zeroclaw"] = e+ }return agents}diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 707bbd726a..dc3813ec70 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -106,7 +106,7 @@ type Config struct {CLIVersion string // multica CLI version (e.g. "0.1.13")LaunchedBy string // "desktop" when spawned by the Electron app, empty for standaloneProfile string // profile name (empty = default)- Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro, antigravity, qoder, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, dim (plus built-in runtime identities from agent.BuiltinRuntimes, e.g. omp)+ Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro, antigravity, qoder, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, dim, zeroclaw (plus built-in runtime identities from agent.BuiltinRuntimes, e.g. omp)WorkspacesRoot string // base path for execution envs (default: ~/multica_workspaces)KeepEnvAfterTask bool // preserve env after task for debuggingHealthPort int // local HTTP port for health checks (default: 19514)@@ -253,7 +253,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, codex, copilot, opencode, deveco, openclaw, hermes, pi, omp, cursor-agent, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, or dim and ensure it is on PATH")+ return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codex, copilot, opencode, deveco, openclaw, hermes, pi, omp, cursor-agent, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, dim, or zeroclaw and ensure it is on PATH")}claudeArgs, err := shellArgsFromEnv("MULTICA_CLAUDE_ARGS")@@ -880,7 +880,7 @@ func isExecutableFile(path string) bool {// doesn't require editing this list by hand.var defaultAgentCommandNames = append([]string{"claude", "codex", "opencode", "deveco", "openclaw", "hermes",- "pi", "cursor-agent", "copilot", "kimi", "reasonix", "dsh", "kiro-cli", "codebuddy", "agy", "qodercli", "qoderclicn", "traecli", "grok", "qwen", "qwenpaw", "mcode", "dim",+ "pi", "cursor-agent", "copilot", "kimi", "reasonix", "dsh", "kiro-cli", "codebuddy", "agy", "qodercli", "qoderclicn", "traecli", "grok", "qwen", "qwenpaw", "mcode", "dim", "zeroclaw",}, agent.BuiltinRuntimeCommands()...)// codexDesktopAppBundlePaths returns candidate macOS app-bundle locations fordiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex e4f7cc4904..2cd125222b 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -5639,6 +5639,7 @@ var runtimeDisplayNameOverrides = map[string]string{"qwen": "Qwen Code","qwenpaw": "QwenPaw","mcode": "MiniMax Code",+ "zeroclaw": "ZeroClaw",}func init() {diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.goindex 84ae34b1ba..a51178da75 100644--- a/server/internal/daemon/execenv/runtime_config.go+++ b/server/internal/daemon/execenv/runtime_config.go@@ -214,7 +214,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", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "mcode", "dim":+ case "codex", "copilot", "opencode", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "mcode", "dim", "zeroclaw":return filepath.Join(workDir, "AGENTS.md")default:return ""diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.goindex eae740dbff..f658a7f951 100644--- a/server/internal/daemon/execenv/runtime_config_test.go+++ b/server/internal/daemon/execenv/runtime_config_test.go@@ -997,6 +997,7 @@ func TestInjectRuntimeConfigPreservesUserContent(t *testing.T) {{"reasonix", "AGENTS.md"},{"dsh", "AGENTS.md"},{"dim", "AGENTS.md"},+ {"zeroclaw", "AGENTS.md"},{"kiro", "AGENTS.md"},{"antigravity", "AGENTS.md"},{"qwen", "QWEN.md"},@@ -1375,6 +1376,7 @@ func TestCleanupRuntimeConfigByProvider(t *testing.T) {{"reasonix", "AGENTS.md"},{"dsh", "AGENTS.md"},{"dim", "AGENTS.md"},+ {"zeroclaw", "AGENTS.md"},{"kiro", "AGENTS.md"},{"antigravity", "AGENTS.md"},{"qwen", "QWEN.md"},diff --git a/server/internal/daemon/execenv/sidecar_manifest_test.go b/server/internal/daemon/execenv/sidecar_manifest_test.goindex 1d1a344623..75c5ab2546 100644--- a/server/internal/daemon/execenv/sidecar_manifest_test.go+++ b/server/internal/daemon/execenv/sidecar_manifest_test.go@@ -157,6 +157,7 @@ var allFileBasedProviders = []string{"reasonix","dsh","dim",+ "zeroclaw","kiro","antigravity","qwen",diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex e4dcf70000..8043ee6286 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -151,6 +151,7 @@ var ("reasonix": "reasonix","dim": "dim","mcode": "mcode",+ "zeroclaw": "zeroclaw","multica_agent": "multica_agent","openclaw": "openclaw","opencode": "opencode",diff --git a/server/internal/metrics/labels_test.go b/server/internal/metrics/labels_test.goindex 8b0402d248..a8e3d67b04 100644--- a/server/internal/metrics/labels_test.go+++ b/server/internal/metrics/labels_test.go@@ -24,6 +24,7 @@ func TestNormalizeRuntimeProviderRecognizesKnownProviders(t *testing.T) {{input: "Reasonix", want: "reasonix"},{input: "DSH", want: "dsh"},{input: "Dim", want: "dim"},+ {input: "ZeroClaw", want: "zeroclaw"},}for _, tt := range tests {if got := NormalizeRuntimeProvider(tt.input); got != tt.want {diff --git a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.mdindex ee4e6299c8..2ebf2817c4 100644--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md+++ b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md@@ -173,18 +173,25 @@ explicit model fail closed because the effective config.toml model is unknown.### model vs custom_args`model` is a first-class persisted column the daemon reads directly.-`custom_args` are raw provider CLI args. The CLI help notes that some providers-(codex app-server, openclaw) reject `--model` inside `custom_args` — but that is-documented CLI guidance, not a server-enforced invariant; nothing in the create-handler inspects `custom_args` for a model flag. Pi is stricter at invocation-time: `--thinking` in `custom_args` is filtered because the first-class-`thinking_level` field owns that flag and must be the only source of its value.+`custom_args` are normally raw provider CLI args. The CLI help notes that some+providers (codex app-server, openclaw) reject `--model` inside `custom_args` —+but that is documented CLI guidance, not a server-enforced invariant; nothing+in the create handler inspects `custom_args` for a model flag. Provider+backends may consume protocol selectors before launch:++- Pi filters `--thinking` because the first-class `thinking_level` field owns+ that flag and must be its only source.+- ZeroClaw consumes `--agent <alias>` / `--agent-alias <alias>` (including+ `=value` forms) and sends the value as the ACP `session/new.agentAlias`+ parameter. `zeroclaw acp` has no such CLI flag. Set one of these custom args+ when ZeroClaw has multiple agents and no `[acp].default_agent`; omit it for a+ sole-agent config so ZeroClaw can auto-select that agent.Never put credentials or other secrets in `custom_args`. Daemon command logs-redact argument values, but the values still live in the provider process's-argv and may be visible to other local processes through `ps` or `/proc`. Put-provider credentials in `custom_env` instead, using its stdin or 0600 file-input where possible.+redact argument values, but values that a backend does not consume still live+in the provider process's argv and may be visible to other local processes+through `ps` or `/proc`. Put provider credentials in `custom_env` instead,+using its stdin or 0600 file input where possible.## Env & secretsdiff --git a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.mdindex ef89c8bf02..60821f3bbe 100644--- a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md+++ b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md@@ -120,7 +120,8 @@ go test ./internal/service -run TestBuiltinSkillsConformToTemplate| Workspace skills FIRST | 1115 | `skills := h.TaskService.LoadAgentSkills(...)` || Built-ins appended | 1116 | `skills = append(skills, h.TaskService.BuiltinSkills()...)` || Runtime payload | `daemon.go` `TaskAgentData` | Carries `Instructions`, `Skills`, `CustomEnv`, `CustomArgs`, `Model`, `ThinkingLevel`, `ServiceTier`, and `McpConfig`; metadata-only fields remain absent |-| `custom_args` argv and safe launch log | `internal/daemon/daemon.go` `ExecOptions.CustomArgs`; `pkg/agent/launch.go` `Config.logAgentCommand` | Custom args reach the provider process argv. Launch logs preserve flag names but redact inline values and positional/value tokens; OS process-list exposure remains, so credentials belong in `custom_env`. |+| `custom_args` argv and safe launch log | `internal/daemon/daemon.go` `ExecOptions.CustomArgs`; `pkg/agent/launch.go` `Config.logAgentCommand` | Custom args normally reach the provider process argv. Launch logs preserve flag names but redact inline values and positional/value tokens; OS process-list exposure remains, so credentials belong in `custom_env`. |+| ZeroClaw agent alias pseudo-args | `pkg/agent/zeroclaw.go` `takeZeroclawAgentAlias` / `zeroclawBlockedArgs` | `--agent` and `--agent-alias` (separate or `=value`) are consumed from `custom_args` and sent as `session/new.agentAlias`; neither token reaches argv because `zeroclaw acp` rejects those CLI flags. Omit the selector for sole-agent auto-selection; use it when multiple agents exist without `[acp].default_agent`. |## Skill loading — `server/internal/service/task.go`diff --git a/server/migrations/403_runtime_profile_add_zeroclaw.down.sql b/server/migrations/403_runtime_profile_add_zeroclaw.down.sqlnew file mode 100644index 0000000000..6f0f014806--- /dev/null+++ b/server/migrations/403_runtime_profile_add_zeroclaw.down.sql@@ -0,0 +1,31 @@+-- Restore the pre-403 whitelist (including dim from migration 370).+-- Existing ZeroClaw rows remain valid because the replacement constraint is+-- NOT VALID, but new ZeroClaw profiles are blocked.+ALTER TABLE runtime_profile DROP CONSTRAINT IF EXISTS runtime_profile_protocol_family_check;++ALTER TABLE runtime_profile ADD CONSTRAINT runtime_profile_protocol_family_check+ CHECK (protocol_family IN (+ 'claude',+ 'codebuddy',+ 'codex',+ 'copilot',+ 'opencode',+ 'openclaw',+ 'hermes',+ 'pi',+ 'cursor',+ 'kimi',+ 'reasonix',+ 'dsh',+ 'kiro',+ 'antigravity',+ 'qoder',+ 'qoderclicn',+ 'traecli',+ 'deveco',+ 'grok',+ 'qwen',+ 'qwenpaw',+ 'mcode',+ 'dim'+ )) NOT VALID;diff --git a/server/migrations/403_runtime_profile_add_zeroclaw.up.sql b/server/migrations/403_runtime_profile_add_zeroclaw.up.sqlnew file mode 100644index 0000000000..db23fd37cf--- /dev/null+++ b/server/migrations/403_runtime_profile_add_zeroclaw.up.sql@@ -0,0 +1,32 @@+-- Add ZeroClaw as a first-party ACP protocol family. NOT VALID preserves+-- historical-row tolerance while enforcing the expanded whitelist for new rows.+-- The whitelist includes dim (added by migration 370) and zeroclaw.+ALTER TABLE runtime_profile DROP CONSTRAINT IF EXISTS runtime_profile_protocol_family_check;++ALTER TABLE runtime_profile ADD CONSTRAINT runtime_profile_protocol_family_check+ CHECK (protocol_family IN (+ 'claude',+ 'codebuddy',+ 'codex',+ 'copilot',+ 'opencode',+ 'openclaw',+ 'hermes',+ 'pi',+ 'cursor',+ 'kimi',+ 'reasonix',+ 'dsh',+ 'kiro',+ 'antigravity',+ 'qoder',+ 'qoderclicn',+ 'traecli',+ 'deveco',+ 'grok',+ 'qwen',+ 'qwenpaw',+ 'mcode',+ 'dim',+ 'zeroclaw'+ )) NOT VALID;diff --git a/server/pkg/agent/acp_deliverable_test.go b/server/pkg/agent/acp_deliverable_test.goindex 38b50de8a3..59418fac6a 100644--- a/server/pkg/agent/acp_deliverable_test.go+++ b/server/pkg/agent/acp_deliverable_test.go@@ -168,6 +168,7 @@ var acpDeliverableCases = []acpDeliverableCase{{backend: "kimi", binary: "kimi", notification: "session/update"},{backend: "reasonix", binary: "reasonix", notification: "session/update"},{backend: "dim", binary: "dim", notification: "session/update"},+ {backend: "zeroclaw", binary: "zeroclaw", notification: "session/update"},{backend: "traecli", binary: "traecli", notification: "session/update"},{backend: "grok", binary: "grok", notification: "session/update"},{backend: "mcode", binary: "mcode", notification: "session/update"},diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 27e5f72270..8a4ed83ada 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -243,7 +243,7 @@ type Result struct {// Config configures a Backend instance.type Config struct {- ExecutablePath string // path to CLI binary (claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, dim)+ ExecutablePath string // path to CLI binary (claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, dim, zeroclaw)CLIVersion string // detected version paired with ExecutablePath; observation only, never used to choose behaviorEnv map[string]string // extra environment variablesLogger *slog.Logger@@ -287,7 +287,7 @@ type Config struct {// add deveco, migration 179 to add grok, migration 202 to add qwen,// migration 242 to add qoderclicn, migration 253 to add qwenpaw,// migration 254 to add reasonix, migration 313 to add dsh, migration 327 to-// add mcode): a+// add mcode, migration 370 to add dim, migration 403 to add zeroclaw): a// custom runtime profile may only// be based on a backend Multica officially supports.// qoder and qoderclicn share the same ACP backend; keeping both provider keys@@ -321,6 +321,7 @@ var SupportedTypes = []string{"qwenpaw","mcode","dim",+ "zeroclaw",}// IsSupportedType reports whether agentType is in the SupportedTypes whitelist.@@ -421,6 +422,8 @@ func New(agentType string, cfg Config) (Backend, error) {return &qwenpawBackend{cfg: cfg}, nilcase "mcode":return &mcodeBackend{cfg: cfg}, nil+ case "zeroclaw":+ return &zeroclawBackend{cfg: cfg}, nildefault:return nil, fmt.Errorf("unknown agent type: %q (supported: %s)", agentType, strings.Join(SupportedTypes, ", "))}@@ -466,6 +469,7 @@ var launchHeaders = map[string]string{"qwenpaw": "qwenpaw acp","dim": "dim acp","mcode": "mcode acp",+ "zeroclaw": "zeroclaw acp",}// LaunchHeader returns the user-visible launch skeleton for agentType, or andiff --git a/server/pkg/agent/agent_supported_types_test.go b/server/pkg/agent/agent_supported_types_test.goindex 8a5637d9a4..d1b5f8b6fb 100644--- a/server/pkg/agent/agent_supported_types_test.go+++ b/server/pkg/agent/agent_supported_types_test.go@@ -41,7 +41,7 @@ func TestSupportedTypesMatchesMigrationWhitelist(t *testing.T) {"opencode": true, "deveco": true, "openclaw": true, "hermes": true,"pi": true, "cursor": true, "kimi": true, "reasonix": true, "dsh": true, "kiro": true, "antigravity": true,"qoder": true, "qoderclicn": true, "traecli": true, "grok": true, "qwen": true, "qwenpaw": true, "mcode": true,- "dim": true,+ "dim": true, "zeroclaw": true,}if len(SupportedTypes) != len(want) {t.Fatalf("SupportedTypes has %d entries, migration whitelist has %d; keep them in lockstep", len(SupportedTypes), len(want))diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex 3a5932baf2..ecbd267792 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -1350,15 +1350,19 @@ func (e *acpRPCError) Error() string {// (Internal error), Kiro puts "No session found with id ..." in// `data` under -32603, and kimi-cli raises invalid_params (-32602)// with {"session_id": "Session not found"} in `data` for every-// unknown-session path (src/kimi_cli/acp/server.py), while Reasonix says-// "session/resume: unknown session <id>" under -32602 — so neither the-// code nor one runtime's exact wording is discriminating and both are matched.+// unknown-session path (src/kimi_cli/acp/server.py), Reasonix says+// "session/resume: unknown session <id>" under -32602, and ZeroClaw defines+// its own SESSION_NOT_FOUND = -32000 in the implementation-defined range+// (zeroclaw-api/src/jsonrpc.rs) — so neither the code nor one runtime's exact+// wording is discriminating and all of them are matched. The wording check+// still carries the decision: -32000 is a generic server-error code, and a+// transient failure reported under it must not read as a lost session.func isACPSessionNotFound(err error) bool {var rpcErr *acpRPCErrorif !errors.As(err, &rpcErr) {return false}- if rpcErr.Code != -32603 && rpcErr.Code != -32602 && rpcErr.Code != -32002 {+ if rpcErr.Code != -32603 && rpcErr.Code != -32602 && rpcErr.Code != -32002 && rpcErr.Code != -32000 {return false}text := strings.ToLower(rpcErr.Message + " " + rpcErr.Data)diff --git a/server/pkg/agent/launch.go b/server/pkg/agent/launch.goindex 898a73e7c4..563d5d45d7 100644--- a/server/pkg/agent/launch.go+++ b/server/pkg/agent/launch.go@@ -322,6 +322,7 @@ var launchPrefixBlockedArgs = map[string]map[string]blockedArgMode{"reasonix": reasonixBlockedArgs,"traecli": traecliBlockedArgs,"dim": dimBlockedArgs,+ "zeroclaw": zeroclawBlockedArgs,}// FilterLaunchPrefix is the exported form for callers outside this package —diff --git a/server/pkg/agent/launch_test.go b/server/pkg/agent/launch_test.goindex 99fef998fa..66a59163d0 100644--- a/server/pkg/agent/launch_test.go+++ b/server/pkg/agent/launch_test.go@@ -131,7 +131,7 @@ func TestNewFiltersLaunchPrefixOnce(t *testing.T) {func TestLaunchPrefixReachesACPFamilies(t *testing.T) {t.Parallel()- for _, family := range []string{"kimi", "hermes", "kiro", "reasonix", "qwenpaw", "dim"} {+ for _, family := range []string{"kimi", "hermes", "kiro", "reasonix", "qwenpaw", "dim", "zeroclaw"} {t.Run(family, func(t *testing.T) {t.Parallel()cfg := Config{LaunchPrefix: []string{"start", "q36"}, Logger: slog.Default()}@@ -661,6 +661,30 @@ func TestDimLaunchPrefixFiltersBlockedFlags(t *testing.T) {}}+// TestZeroclawLaunchPrefixFiltersBlockedFlags proves the ZeroClaw+// launch-prefix safety policy: allowed positional tokens reach the command+// ahead of the hardcoded `acp` subcommand, while protocol-breaking flags+// (--help, -h, login, --login, --auth, acp) are stripped.+func TestZeroclawLaunchPrefixFiltersBlockedFlags(t *testing.T) {+ t.Parallel()++ // Allowed positional prefix tokens survive and precede `acp`.+ cfg := Config{LaunchPrefix: []string{"start", "q36"}, Logger: slog.Default()}+ argv := cfg.commandAt("wrapper").Argv("acp")+ if idx := prefixIndex(argv, []string{"start", "q36", "acp"}); idx != 0 {+ t.Fatalf("zeroclaw: allowed prefix must precede the acp subcommand, got %v", argv)+ }++ // Protocol-breaking flags are removed from the prefix.+ got := filterLaunchPrefix(+ []string{"start", "--help", "--login", "--auth", "-h", "q36"},+ "zeroclaw", slog.Default())+ want := []string{"start", "q36"}+ if strings.Join(got, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("zeroclaw: blocked flags must be stripped, got %v, want %v", got, want)+ }+}+// TestHermesLaunchArgvMatchesBackendAssembly is the root of the second-round// Hermes finding: the daemon must resolve the profile from the argv the backend// actually builds, not from a concatenation that leaves out `acp`.diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex 243671fd89..60279fb10a 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -264,6 +264,13 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (Creturn cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {return discoverDimModels(ctx, runtimeCmd)})+ case "zeroclaw":+ // ZeroClaw's ACP server advertises no catalog: session/new answers+ // exactly {sessionId, workspaceDir} (verified against 0.8.4), and it+ // has no session-scoped model selection to consume one anyway — see+ // ModelSelectionSupported. Return an empty list rather than spawning+ // an ACP subprocess that can only ever come back empty.+ return Catalog{Models: []Model{}}, nildefault:return Catalog{}, fmt.Errorf("unknown agent type: %q", providerType)}@@ -367,7 +374,7 @@ func QualifyModelID(catalog Catalog, model string) (string, bool) {// dropdown plus a silently-ignored manual-entry field.func ModelSelectionSupported(providerType string) bool {switch providerType {- case "qwenpaw", "mcode":+ case "qwenpaw", "mcode", "zeroclaw":// QwenPaw's `session/set_model` persists to agent.json at the agent// scope, not the session scope. Calling it would mutate the user's// shared, persistent agent config. Model override is therefore@@ -375,7 +382,11 @@ func ModelSelectionSupported(providerType string) bool {// the agent profile. If QwenPaw makes model selection session-scoped// upstream, this can be reverted to `true`. MCode similarly exposes no// model option through ACP, so its runtime configuration remains the- // source of truth.+ // source of truth. ZeroClaw goes further: `session/set_model` is not in+ // its ACP dispatch table at all (0.8.4 answers -32601) and no handler+ // reads a model param, so the model comes from the ZeroClaw agent+ // profile (`agents.<alias>.model_provider`) and nothing Multica sends+ // can change it.return falsedefault:return truediff --git a/server/pkg/agent/version.go b/server/pkg/agent/version.goindex 0995624d70..6f5d488b68 100644--- a/server/pkg/agent/version.go+++ b/server/pkg/agent/version.go@@ -11,13 +11,14 @@ import (// MinVersions defines the minimum required CLI version for each agent type.// Versions below these will be rejected during daemon registration.var MinVersions = map[string]string{- "claude": "2.0.0",- "codex": "0.100.0", // app-server --listen stdio:// added in 0.100.0- "copilot": "1.0.0", // --output-format json envelope stable from 1.0.x- "grok": "0.2.89", // ACP + authenticate/session-load/set_model/MCP and --effort thinking flag- "qwen": "0.20.0", // stream-json protocol captured and verified against Qwen Code 0.20.0- "dim": "0.3.10", // cross-run session/load: per-process lock releases on graceful exit- "mcode": "0.1.2", // ACP v1 session/new, prompt, MCP capability forwarding+ "claude": "2.0.0",+ "codex": "0.100.0", // app-server --listen stdio:// added in 0.100.0+ "copilot": "1.0.0", // --output-format json envelope stable from 1.0.x+ "grok": "0.2.89", // ACP + authenticate/session-load/set_model/MCP and --effort thinking flag+ "qwen": "0.20.0", // stream-json protocol captured and verified against Qwen Code 0.20.0+ "dim": "0.3.10", // cross-run session/load: per-process lock releases on graceful exit+ "mcode": "0.1.2", // ACP v1 session/new, prompt, MCP capability forwarding+ "zeroclaw": "0.8.0", // persistent ACP sessions and session/resume were added in 0.8.0}// MinQuickCreateCLIVersion gates the agent-create (quick-create) flow againstdiff --git a/server/pkg/agent/version_test.go b/server/pkg/agent/version_test.goindex 3346364e8a..d2f8628d09 100644--- a/server/pkg/agent/version_test.go+++ b/server/pkg/agent/version_test.go@@ -181,6 +181,10 @@ func TestCheckMinVersion(t *testing.T) {{"dim", "0.3.9", true},{"mcode", "0.1.2", false},{"mcode", "mcode 0.1.1", true},+ {"zeroclaw", "zeroclaw 0.8.4", false},+ {"zeroclaw", "0.8.0", false},+ {"zeroclaw", "0.7.5", true},+ {"zeroclaw", "invalid", true},{"dim", "0.2.99", true},{"dim", "invalid", true},{"unknown", "1.0.0", false},diff --git a/server/pkg/agent/zeroclaw.go b/server/pkg/agent/zeroclaw.gonew file mode 100644index 0000000000..9f5e2b5465--- /dev/null+++ b/server/pkg/agent/zeroclaw.go@@ -0,0 +1,602 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os/exec"+ "strings"+ "sync"+ "sync/atomic"+ "time"+)++// zeroclawBlockedArgs are flags hardcoded by the daemon that must not be+// overridden by user-configured custom_args. `acp` is the protocol+// subcommand that drives the ACP JSON-RPC transport; overriding it would+// break the daemon↔ZeroClaw communication contract. `--help`/`-h` and the+// login/auth flags would switch the CLI into a mode that never starts the+// ACP server.+//+// `--agent` / `--agent-alias` are blocked because `zeroclaw acp` has no such+// flag — clap aborts the process with `error: unexpected argument '--agent'+// found`. takeZeroclawAgentAlias consumes them out of custom_args before this+// filter runs and forwards the value as the session/new `agentAlias` param+// instead; these entries stop a copy arriving through any other path (a+// runtime launch prefix) from reaching argv.+var zeroclawBlockedArgs = map[string]blockedArgMode{+ "acp": blockedStandalone,+ "--help": blockedStandalone,+ "-h": blockedStandalone,+ "login": blockedStandalone,+ "auth": blockedStandalone,+ "--login": blockedStandalone,+ "--auth": blockedStandalone,+ "--agent": blockedWithValue,+ "--agent-alias": blockedWithValue,+}++// takeZeroclawAgentAlias consumes the ZeroClaw agent alias from custom_args+// and returns it with the remaining arguments.+//+// ZeroClaw binds every ACP session to an agent alias, resolved in this order:+// the session/new `agentAlias` param, `[acp].default_agent`, then auto-select+// when the config holds exactly one `[agents.<alias>]` entry. With none of+// those, session/new fails with -32602. The alias cannot travel on argv (see+// zeroclawBlockedArgs), so custom_args is the only operator-facing channel and+// the value is lifted out here.+//+// Both `--agent x` and `--agent=x` are accepted, `--agent-alias` is the long+// spelling, and the last occurrence wins so a per-agent entry can override a+// runtime-wide one. An empty or whitespace-only value counts as unset:+// ZeroClaw trims and drops empty aliases the same way, and sending one would+// forfeit its auto-select.+func takeZeroclawAgentAlias(args []string) (string, []string) {+ if len(args) == 0 {+ return "", args+ }+ alias := ""+ rest := make([]string, 0, len(args))+ for i := 0; i < len(args); i++ {+ arg := unshellQuoteArg(args[i])+ flag, value := arg, ""+ hasInlineValue := false+ if idx := strings.Index(arg, "="); idx > 0 {+ flag, value, hasInlineValue = arg[:idx], arg[idx+1:], true+ }+ if flag != "--agent" && flag != "--agent-alias" {+ rest = append(rest, args[i])+ continue+ }+ if !hasInlineValue {+ if i+1 >= len(args) {+ continue+ }+ i+++ value = unshellQuoteArg(args[i])+ }+ alias = strings.TrimSpace(value)+ }+ return alias, rest+}++// zeroclawResumeSupported reads the capability ZeroClaw derives from whether+// its persistent session store opened successfully. A read-only or unwritable+// config directory leaves resume absent even on a new-enough binary.+func zeroclawResumeSupported(result json.RawMessage) bool {+ var r struct {+ AgentCapabilities struct {+ SessionCapabilities struct {+ Resume *struct{} `json:"resume"`+ } `json:"sessionCapabilities"`+ } `json:"agentCapabilities"`+ }+ return json.Unmarshal(result, &r) == nil && r.AgentCapabilities.SessionCapabilities.Resume != nil+}++// selectZeroclawPermissionOption keeps ordinary single-use tool approvals on+// the shared ACP policy, but fails closed for ZeroClaw's legacy structured+// question bridge. That bridge labels every answer `choice-N` with+// allow_once, so generic auto-approval would silently answer every question+// with the first choice. Returning ok=false makes the shared transport send a+// protocol error: even the option marked reject_once is still mapped back to+// a real answer by ZeroClaw, so selecting it would silently choose the last+// answer rather than reject the question.+func selectZeroclawPermissionOption(params json.RawMessage) (optionID string, grant bool, ok bool) {+ var p struct {+ Options []acpPermissionOption `json:"options"`+ }+ if json.Unmarshal(params, &p) != nil {+ return "", false, false+ }++ isLegacyChoice := len(p.Options) >= 2+ for _, opt := range p.Options {+ if !strings.HasPrefix(opt.OptionID, "choice-") {+ isLegacyChoice = false+ break+ }+ }+ if !isLegacyChoice {+ return selectACPPermissionOption(params)+ }+ return "", false, false+}++// zeroclawSessionNewErrorMessage turns ZeroClaw's agent-selection failure into+// something an operator can act on.+//+// session/new demands `agentAlias` whenever the config does not hold exactly+// one agent — including the zero-agent case, where it asks for the alias of an+// entry that does not exist yet — and no CLI flag can supply one, so the bare+// RPC error leaves no route forward.+func zeroclawSessionNewErrorMessage(err error) string {+ base := fmt.Sprintf("zeroclaw session/new failed: %v", err)+ var rpcErr *acpRPCError+ if !errors.As(err, &rpcErr) || !strings.Contains(rpcErr.Message, "agentAlias") {+ return base+ }+ return base + " — ZeroClaw auto-selects an agent only when its config holds exactly one [agents.<alias>] entry." ++ " Configure the agent you want, then name it with `--agent <alias>` in this runtime's custom args" ++ " or set `[acp].default_agent` in ZeroClaw's config."+}++// zeroclawBackend implements Backend by spawning `zeroclaw acp` and+// communicating via the standard ACP (Agent Client Protocol) JSON-RPC 2.0+// transport over stdin/stdout.+//+// ZeroClaw is a Rust-based, single-binary generic agent runtime (see+// multica-ai/multica#1543). Its ACP server exposes the same protocol+// surface that Hermes/Kimi/Reasonix/Dim/Traecli/Grok/QwenPaw/MCode use, so+// the backend reuses the shared hermesClient ACP transport — only the+// binary, the session bootstrap, and the tool-name extraction differ.+//+// Verified against a real ZeroClaw 0.8.4 binary driven over stdio. That+// handshake is not vanilla ACP, and the departures below are what this file+// is shaped around:+//+// - The dispatch table is initialize and session/{new,load,resume,close,+// prompt,stop,cancel,event|update}. There is no `session/set_model` — it+// answers -32601 — and no handler reads a model param at all. The model+// belongs to the ZeroClaw agent profile (`agents.<alias>.model_provider`+// → `[providers.models.<type>.<alias>].model`) and cannot be selected per+// session, so ModelSelectionSupported opts ZeroClaw out. The+// `initialize._meta.zeroclaw.defaultModel` value is process-global (the+// first configured provider model), not the model for the alias later+// selected by session/new, so it is not used for usage attribution.+// - session/new returns exactly {sessionId, workspaceDir}: no model+// catalog, no currentModelId, so there is nothing to discover.+// - session/new requires `agentAlias` unless exactly one agent is+// configured or `[acp].default_agent` is set. See takeZeroclawAgentAlias.+// - Resume goes through session/resume, not session/load: load replays the+// whole retained transcript back as session/update notifications, which+// would re-emit prior turns as this turn's output.+// - No handler reads `params.mcpServers`. MCP is operator-side only,+// configured in ZeroClaw's own config-dir.+// - Its SESSION_NOT_FOUND is a custom -32000; see isACPSessionNotFound.+//+// MinVersions requires ZeroClaw 0.8.0+, the first stable release with+// persistent ACP sessions and session/resume. No permission-preset injection+// or separate authenticate step is needed: initialize returns an empty+// `authMethods` and the handshake asks for nothing further.+type zeroclawBackend struct {+ cfg Config+}++var (+ zeroclawReaderDrainGrace = 2 * time.Second+ zeroclawNotificationQuietTime = 250 * time.Millisecond+)++// zeroclawMessageStream serializes sends and the final close so a late+// stdout reader cannot send on a closed channel. Mirrors dim/grok/traecli.+type zeroclawMessageStream struct {+ ch chan Message+ mu sync.Mutex+ closed bool+}++func newZeroclawMessageStream(size int) *zeroclawMessageStream {+ return &zeroclawMessageStream{ch: make(chan Message, size)}+}++func (s *zeroclawMessageStream) send(msg Message) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.closed {+ return+ }+ trySend(s.ch, msg)+}++func (s *zeroclawMessageStream) close() {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.closed {+ return+ }+ s.closed = true+ close(s.ch)+}++func (b *zeroclawBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {+ execPath := b.cfg.ExecutablePath+ if execPath == "" {+ execPath = "zeroclaw"+ }+ if _, err := exec.LookPath(execPath); err != nil {+ return nil, fmt.Errorf("zeroclaw executable not found at %q: %w", execPath, err)+ }++ // ZeroClaw discards client-supplied MCP servers: none of its session/new,+ // session/load or session/resume handlers reads `params.mcpServers`, and+ // enabling `agents.<alias>.acp_enable_mcp` initialises that agent's OWN+ // `mcp_bundles`, not ours. MCP therefore lives entirely in ZeroClaw's+ // config-dir. providerSupportsMcpConfig hides the MCP tab for this+ // runtime, so reaching here means a value saved before that — warn and+ // continue rather than bricking the task over config we cannot honour.+ if len(opts.McpConfig) > 0 {+ b.cfg.Logger.Warn("zeroclaw ignores MCP servers supplied by Multica; its ACP server reads MCP only from its own config-dir ([[mcp.servers]] + [mcp_bundles.*] + agents.<alias>.mcp_bundles with acp_enable_mcp = true)",+ "backend", "zeroclaw",+ )+ }++ timeout := opts.Timeout+ runCtx, cancel := runContext(ctx, timeout)++ agentAlias, customArgs := takeZeroclawAgentAlias(opts.CustomArgs)+ zeroclawArgs := append([]string{"acp"}, filterCustomArgs(customArgs, zeroclawBlockedArgs, b.cfg.Logger)...)++ cmd := b.cfg.commandAt(execPath).exec(runCtx, zeroclawArgs...)+ hideAgentWindow(cmd)+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(zeroclawArgs, trustAgentCommandPositional(0, "acp")))+ if opts.Cwd != "" {+ cmd.Dir = opts.Cwd+ }+ cmd.Env = buildEnv(b.cfg.Env)++ stdout, err := cmd.StdoutPipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("zeroclaw stdout pipe: %w", err)+ }+ stdin, err := cmd.StdinPipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("zeroclaw 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+ // io.MultiWriter form races with stopReason=end_turn under load.+ providerErr := newACPProviderErrorSniffer("zeroclaw")+ stderr, err := cmd.StderrPipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("zeroclaw stderr pipe: %w", err)+ }++ if err := cmd.Start(); err != nil {+ cancel()+ return nil, fmt.Errorf("start zeroclaw: %w", err)+ }++ stderrSink := io.MultiWriter(newLogWriter(b.cfg.Logger, "[zeroclaw:stderr] "), providerErr)+ stderrDone := make(chan struct{})+ go func() {+ defer close(stderrDone)+ _, _ = io.Copy(stderrSink, stderr)+ }()++ b.cfg.Logger.Info("zeroclaw acp started", "pid", cmd.Process.Pid, "cwd", opts.Cwd)++ msgStream := newZeroclawMessageStream(256)+ resCh := make(chan Result, 1)++ // ZeroClaw streams interim narration and the final answer as the same+ // agent_message_chunk type; the tracker keeps only the post-tool-call+ // block for Result.Output while retaining the full text for error+ // detection.+ var deliverable acpDeliverableTracker+ // streamingCurrentTurn gates every session update so that anything the+ // runtime pushes outside our turn is dropped instead of landing in the+ // deliverable. It must default to false: ZeroClaw flushes the frames that+ // matter here — session/load's transcript replay — before it answers the+ // request that triggered them, so the gate has to be closed from process+ // start. Flipped to true only just before session/prompt is sent.+ var streamingCurrentTurn atomic.Bool++ promptDone := make(chan hermesPromptResult, 1)+ activity := make(chan struct{}, 1)++ c := &hermesClient{+ cfg: b.cfg,+ stdin: stdin,+ pending: make(map[int]*pendingRPC),+ pendingTools: make(map[string]*pendingToolCall),+ selectPermission: selectZeroclawPermissionOption,+ acceptNotification: func(string) bool {+ return streamingCurrentTurn.Load()+ },+ onActivity: func() {+ select {+ case activity <- struct{}{}:+ default:+ }+ },+ onMessage: func(msg Message) {+ if !streamingCurrentTurn.Load() {+ return+ }+ if msg.Type == MessageToolUse {+ // Re-normalise tool titles the same way kimi/traecli/grok/dim+ // do so the UI sees consistent snake_case names.+ msg.Tool = kimiToolNameFromTitle(msg.Tool)+ }+ deliverable.observe(msg)+ msgStream.send(msg)+ },+ onPromptDone: func(result hermesPromptResult) {+ if !streamingCurrentTurn.Load() {+ return+ }+ select {+ case promptDone <- result:+ default:+ }+ },+ }++ 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("zeroclaw process exited"))+ }()++ go func() {+ defer cancel()+ defer msgStream.close()+ defer close(resCh)+ defer func() {+ stdin.Close()+ _ = cmd.Wait()+ }()++ startTime := time.Now()+ finalStatus := "completed"+ var finalError string+ var sessionID string+ // Set when the ACP runtime refuses the session we asked to+ // resume. Only that is curable by starting a fresh session, so+ // handshake/network failures below must leave it false.+ var resumeRejected bool+ var effectiveModel string++ // Keep elicitation absent: this headless client cannot collect a user's+ // form response. ZeroClaw's legacy structured-choice bridge is handled+ // fail-closed by selectZeroclawPermissionOption instead.+ initResult, err := c.request(runCtx, "initialize", map[string]any{+ "protocolVersion": 1,+ "clientInfo": map[string]any{+ "name": "multica-agent-sdk",+ "version": "0.2.0",+ },+ "clientCapabilities": map[string]any{},+ })+ if err != nil {+ finalStatus = "failed"+ finalError = fmt.Sprintf("zeroclaw initialize failed: %v", err)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }++ cwd := opts.Cwd+ if cwd == "" {+ cwd = "."+ }++ if opts.ResumeSessionID != "" && !zeroclawResumeSupported(initResult) {+ b.cfg.Logger.Warn("zeroclaw persistence is unavailable; the daemon will retry from a rebuilt fresh-session context",+ "backend", "zeroclaw",+ "requested_session", opts.ResumeSessionID,+ )+ resumeRejected = true+ resCh <- Result{+ Status: "failed",+ Error: "zeroclaw session/resume unavailable: initialize did not advertise sessionCapabilities.resume",+ DurationMs: time.Since(startTime).Milliseconds(),+ ResumeRejected: resumeRejected,+ }+ return+ }++ if opts.ResumeSessionID != "" {+ // session/resume, not session/load. Both restore the transcript+ // into the agent and both answer a bare `{}`, but load also+ // replays every retained message back to us as session/update+ // notifications, so a resumed turn would re-emit the previous+ // answer as its own output.+ result, err := c.request(runCtx, "session/resume", map[string]any{+ "sessionId": opts.ResumeSessionID,+ })+ if err != nil {+ if isACPSessionNotFound(err) {+ b.cfg.Logger.Warn("zeroclaw resumed session not found; the daemon will retry fresh",+ "backend", "zeroclaw",+ "requested_session", opts.ResumeSessionID,+ )+ resumeRejected = true+ resCh <- Result{Status: "failed", Error: fmt.Sprintf("zeroclaw session/resume failed: %v", err), DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}+ return+ }+ finalStatus = "failed"+ finalError = fmt.Sprintf("zeroclaw session/resume failed: %v", err)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}+ return+ }+ var changed bool+ sessionID, changed = resolveResumedSessionID(opts.ResumeSessionID, result)+ if changed {+ b.cfg.Logger.Warn("zeroclaw returned a different session id on resume — original was likely lost; continuing with the new id",+ "backend", "zeroclaw",+ "requested", opts.ResumeSessionID,+ "actual", sessionID,+ )+ }+ } else {+ // mcpServers stays empty on purpose: ZeroClaw never reads it.+ // agentAlias is omitted unless the operator named one — sending a+ // guess would forfeit ZeroClaw's sole-agent auto-select and turn a+ // working single-agent install into `Unknown agent`.+ params := map[string]any{+ "cwd": cwd,+ "mcpServers": []any{},+ }+ if agentAlias != "" {+ params["agentAlias"] = agentAlias+ }+ result, err := c.request(runCtx, "session/new", params)+ if err != nil {+ if runCtx.Err() == context.DeadlineExceeded {+ finalStatus = "timeout"+ finalError = fmt.Sprintf("zeroclaw timed out during session/new: %v", timeout)+ } else if runCtx.Err() == context.Canceled {+ finalStatus = "aborted"+ finalError = fmt.Sprintf("zeroclaw aborted: %v", err)+ } else {+ finalStatus = "failed"+ finalError = zeroclawSessionNewErrorMessage(err)+ }+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }+ sessionID = extractACPSessionID(result)+ if sessionID == "" {+ finalStatus = "failed"+ finalError = "zeroclaw session/new returned no session ID"+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }+ }++ c.sessionID = sessionID+ // Early session pin so a cancelled run still preserves resume pointer.+ msgStream.send(Message{Type: MessageStatus, Status: "running", SessionID: sessionID})+ b.cfg.Logger.Info("zeroclaw session ready", "session_id", sessionID)++ userText := prompt+ if opts.SystemPrompt != "" {+ userText = opts.SystemPrompt + "\n\n---\n\n" + prompt+ }++ streamingCurrentTurn.Store(true)+ _, err = c.request(runCtx, "session/prompt", map[string]any{+ "sessionId": sessionID,+ "prompt": []map[string]any{+ {"type": "text", "text": userText},+ },+ })+ if err != nil {+ if runCtx.Err() == context.DeadlineExceeded {+ finalStatus = "timeout"+ finalError = fmt.Sprintf("zeroclaw timed out after %s", timeout)+ } else if runCtx.Err() == context.Canceled {+ finalStatus = "aborted"+ finalError = "execution cancelled"+ } else {+ finalStatus = "failed"+ finalError = fmt.Sprintf("zeroclaw session/prompt failed: %v", err)+ if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ b.cfg.Logger.Warn("resumed session not found at prompt time; clearing session id so the daemon retries fresh",+ "backend", "zeroclaw",+ "session_id", sessionID,+ )+ sessionID = ""+ resumeRejected = true+ }+ }+ } else {+ select {+ case pr := <-promptDone:+ if pr.stopReason == "cancelled" {+ finalStatus = "aborted"+ finalError = "zeroclaw cancelled the prompt"+ }+ effectiveModel = pr.modelID+ c.mergeUsage(pr.usage)+ default:+ }+ // Give the stdout reader a bounded chance to consume notifications+ // zeroclaw may emit just after session/prompt returns+ // (agent_message_chunk, usage updates). Closing stdin at the+ // response boundary otherwise races the reader and truncates the+ // final text — the same race fixed for hermes/dim/grok.+ waitForACPNotificationQuiescence(runCtx, activity, readerDone, zeroclawNotificationQuietTime, zeroclawReaderDrainGrace)+ }++ duration := time.Since(startTime)+ b.cfg.Logger.Info("zeroclaw finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())++ stdin.Close()+ cancel()++ // ZeroClaw's ACP server may keep the process — and the stdout/stderr+ // pipes — open briefly after session/prompt returns. Bound the drain.+ drainCtx, drainCancel := context.WithTimeout(context.Background(), zeroclawReaderDrainGrace)+ select {+ case <-readerDone:+ case <-drainCtx.Done():+ }+ select {+ case <-stderrDone:+ case <-drainCtx.Done():+ }+ drainCancel()+ streamingCurrentTurn.Store(false)++ finalOutput, providerErrorOutput := deliverable.result()++ // Promote completed→failed when stderr or the agent text stream show a+ // terminal upstream-LLM failure (auth / rate-limit / HTTP 4xx). It reads+ // the full text stream, not the deliverable, so a give-up turn that+ // lands before a tool call stays visible.+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)++ u := c.accumulatedUsage()++ // ZeroClaw 0.8.4 reports no token counts over ACP — its prompt result+ // is {sessionId, stopReason, content} — so usageMap stays nil today. If+ // a later response reports usage without a per-turn model id, keep it+ // under "unknown": initialize.defaultModel is process-global and can+ // belong to a different agent alias.+ var usageMap map[string]TokenUsage+ if acpUsagePresent(u) {+ model := effectiveModel+ if model == "" {+ model = "unknown"+ }+ usageMap = map[string]TokenUsage{model: u}+ }++ resCh <- Result{+ Status: finalStatus,+ Output: finalOutput,+ Error: finalError,+ DurationMs: duration.Milliseconds(),+ SessionID: sessionID,+ ResumeRejected: resumeRejected,+ Usage: usageMap,+ }+ }()++ return &Session{Messages: msgStream.ch, Result: resCh}, nil+}diff --git a/server/pkg/agent/zeroclaw_test.go b/server/pkg/agent/zeroclaw_test.gonew file mode 100644index 0000000000..1229fcdd2e--- /dev/null+++ b/server/pkg/agent/zeroclaw_test.go@@ -0,0 +1,866 @@+package agent++import (+ "context"+ "encoding/json"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestNewReturnsZeroclawBackend(t *testing.T) {+ t.Parallel()+ b, err := New("zeroclaw", Config{ExecutablePath: "/nonexistent/zeroclaw"})+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }+ if _, ok := b.(*zeroclawBackend); !ok {+ t.Fatalf("expected *zeroclawBackend, got %T", b)+ }+}++// fakeZeroclawACPScript impersonates `zeroclaw acp` for unit tests. Unlike a+// generic ACP fake, this one reproduces the frames a real ZeroClaw 0.8.4+// binary was observed to send, because several of the bugs this suite guards+// against were shipped by a fake that answered more generously than the+// runtime does:+//+// - initialize carries the model id in `_meta.zeroclaw.defaultModel` and+// advertises no remote MCP transports.+// - session/new returns {sessionId, workspaceDir} and nothing else — no+// model catalog, no currentModelId.+// - session/resume returns a bare `{}`; ZeroClaw dispatches no+// session/set_model at all, so that request must fall through to the+// -32601 default arm exactly as it does on the wire.+// - an unknown session is ZeroClaw's custom -32000 SESSION_NOT_FOUND, not a+// JSON-RPC standard code.+//+// ZEROCLAW_STALE_REPLAY makes session/resume push a historical+// agent_message_chunk before answering, which is what session/load does for+// real and what the turn gate has to swallow.+func fakeZeroclawACPScript() string {+ return `#!/bin/sh+while IFS= read -r line; do+ if [ -n "$ZEROCLAW_REQUESTS_FILE" ]; then+ printf '%s\n' "$line" >> "$ZEROCLAW_REQUESTS_FILE"+ fi+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"_meta":{"zeroclaw":{"defaultModel":"llama3.2","maxSessions":10,"sessionTimeoutSecs":3600}},"agentInfo":{"name":"zeroclaw-acp","version":"0.8.4"},"authMethods":[],"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":false,"sse":false},"sessionCapabilities":{"close":{},"resume":{}}}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ if [ -n "$ZEROCLAW_REQUIRE_AGENT_ALIAS" ]; then+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32602,"message":"session/new requires ` + "`agentAlias`" + ` (alias of a configured [agents.<alias>] entry)"}}\n' "$id"+ exit 0+ fi+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_zeroclaw_new","workspaceDir":"/tmp"}}\n' "$id"+ ;;+ *'"method":"session/resume"'*)+ if [ -n "$ZEROCLAW_SESSION_NOT_FOUND" ]; then+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32000,"message":"Session not found: ses_gone"}}\n' "$id"+ exit 0+ fi+ if [ -n "$ZEROCLAW_STALE_REPLAY" ]; then+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_existing","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"STALE PRIOR ANSWER"}}}}\n'+ fi+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_existing","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"CURRENT ANSWER"}}}}\n'+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":10,"outputTokens":20,"cacheReadTokens":3,"cacheWriteTokens":2,"costUsdTicks":900}}}\n' "$id"+ ;;+ *)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"Method not found"}}\n' "$id"+ ;;+ esac+done+`+}++func writeFakeZeroclawScript(t *testing.T, script string) string {+ t.Helper()+ dir := t.TempDir()+ bin := filepath.Join(dir, "zeroclaw")+ if err := os.WriteFile(bin, []byte(script), 0755); err != nil {+ t.Fatalf("write fake zeroclaw: %v", err)+ }+ return bin+}++// TestZeroclawSessionNew covers the fresh-session happy path: initialize,+// session/new, session/prompt, and a completed result carrying the new+// session id. initialize.defaultModel is deliberately not used for usage:+// it is the process-global first provider model, not the model selected by+// the agent alias bound during session/new.+func TestZeroclawSessionNew(t *testing.T) {+ t.Parallel()+ bin := writeFakeZeroclawScript(t, fakeZeroclawACPScript())++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ ctx := context.Background()+ session, err := b.Execute(ctx, "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }++ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }+ if result.SessionID != "ses_zeroclaw_new" {+ t.Fatalf("expected sessionID ses_zeroclaw_new, got %q", result.SessionID)+ }+ if _, ok := result.Usage["unknown"]; !ok {+ t.Fatalf("expected usage without a per-turn model id to stay unknown, got %+v", result.Usage)+ }+}++// TestZeroclawPromptModelMetadataControlsUsageAttribution proves the prompt+// result is authoritative when a future ZeroClaw reports a per-turn model id.+func TestZeroclawPromptModelMetadataControlsUsageAttribution(t *testing.T) {+ t.Parallel()+ script := strings.Replace(+ fakeZeroclawACPScript(),+ `"result":{"stopReason":"end_turn","usage":{`,+ `"result":{"stopReason":"end_turn","_meta":{"modelId":"selected-model"},"usage":{`,+ 1,+ )+ if !strings.Contains(script, `"modelId":"selected-model"`) {+ t.Fatal("fake script rewrite failed: prompt model metadata not inserted")+ }+ bin := writeFakeZeroclawScript(t, script)++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{ExecutablePath: bin, Logger: logger})+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ session, err := b.Execute(context.Background(), "test prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }+ if _, ok := result.Usage["selected-model"]; !ok {+ t.Fatalf("expected usage attributed to prompt model metadata, got %+v", result.Usage)+ }+}++// TestZeroclawResumeUsesSessionResume covers the resume happy path: a+// follow-up run with ResumeSessionID set uses session/resume and reports+// ResumeRejected=false.+//+// session/load is explicitly forbidden here. Both methods restore the+// transcript into the agent, but load also replays every retained message back+// to the client as session/update notifications, so resuming through it would+// feed the previous answer into this turn's deliverable.+func TestZeroclawResumeUsesSessionResume(t *testing.T) {+ t.Parallel()+ bin := writeFakeZeroclawScript(t, fakeZeroclawACPScript())+ reqFile := filepath.Join(t.TempDir(), "requests.txt")++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ Env: map[string]string{"ZEROCLAW_REQUESTS_FILE": reqFile},+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ ctx := context.Background()+ session, err := b.Execute(ctx, "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ ResumeSessionID: "ses_existing",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }++ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }+ // session/resume returns a bare {}, so resolveResumedSessionID falls back+ // to the requested id.+ if result.SessionID != "ses_existing" {+ t.Fatalf("expected sessionID ses_existing (fallback from resume), got %q", result.SessionID)+ }+ if result.ResumeRejected {+ t.Fatal("expected ResumeRejected=false on successful resume")+ }++ raw, err := os.ReadFile(reqFile)+ if err != nil {+ t.Fatalf("read requests file: %v", err)+ }+ requests := string(raw)+ if !strings.Contains(requests, `"method":"session/resume"`) {+ t.Fatalf("expected session/resume on resume, got requests:\n%s", requests)+ }+ resumeFrame := findRecordedFrame(t, reqFile, "session/resume")+ resumeParams, _ := resumeFrame["params"].(map[string]any)+ if len(resumeParams) != 1 || resumeParams["sessionId"] != "ses_existing" {+ t.Fatalf("session/resume must send only the session id ZeroClaw reads, got %#v", resumeParams)+ }+ assertNoRecordedFrame(t, reqFile, "session/load")+ if strings.Contains(requests, `"method":"session/new"`) {+ t.Fatalf("resume must not call session/new, got requests:\n%s", requests)+ }+}++// TestZeroclawResumeCapabilityUnavailableReportsRejection covers ZeroClaw's+// read-only/unwritable persistence fallback. In that mode initialize omits+// sessionCapabilities.resume. Report positive rejection evidence so the+// daemon owns the fresh retry, continuity notice, prompt rebuild, runtime+// config rewrite, and retirement of the abandoned session id.+func TestZeroclawResumeCapabilityUnavailableReportsRejection(t *testing.T) {+ t.Parallel()+ script := strings.Replace(+ fakeZeroclawACPScript(),+ `"sessionCapabilities":{"close":{},"resume":{}}`,+ `"sessionCapabilities":{"close":{}}`,+ 1,+ )+ if strings.Contains(script, `"resume":{}`) {+ t.Fatal("fake script rewrite failed: resume capability still present")+ }+ bin := writeFakeZeroclawScript(t, script)+ reqFile := filepath.Join(t.TempDir(), "requests.txt")++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ Env: map[string]string{"ZEROCLAW_REQUESTS_FILE": reqFile},+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ session, err := b.Execute(context.Background(), "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ ResumeSessionID: "ses_existing",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "failed" || !result.ResumeRejected || result.SessionID != "" {+ t.Fatalf("expected failed resume rejection without a replacement session, got status=%q session=%q rejected=%v error=%q", result.Status, result.SessionID, result.ResumeRejected, result.Error)+ }+ if !strings.Contains(result.Error, "session/resume unavailable") {+ t.Fatalf("expected an actionable resume-unavailable error, got %q", result.Error)+ }+ assertNoRecordedFrame(t, reqFile, "session/resume")+ assertNoRecordedFrame(t, reqFile, "session/new")+}++// TestZeroclawResumeDropsReplayedHistory pins the reason resume switched off+// session/load. Even when the runtime pushes a historical+// agent_message_chunk before answering the resume request, the turn gate must+// swallow it: it belongs to a prior turn, and appending it would republish the+// previous answer as this run's output and re-emit it to the UI.+func TestZeroclawResumeDropsReplayedHistory(t *testing.T) {+ t.Parallel()+ bin := writeFakeZeroclawScript(t, fakeZeroclawACPScript())++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ Env: map[string]string{"ZEROCLAW_STALE_REPLAY": "1"},+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ session, err := b.Execute(context.Background(), "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ ResumeSessionID: "ses_existing",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }++ var streamed []string+ for msg := range session.Messages {+ if msg.Type == MessageText {+ streamed = append(streamed, msg.Content)+ }+ }++ result := <-session.Result+ if result.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }+ if strings.Contains(result.Output, "STALE PRIOR ANSWER") {+ t.Fatalf("replayed history leaked into Result.Output: %q", result.Output)+ }+ if !strings.Contains(result.Output, "CURRENT ANSWER") {+ t.Fatalf("expected the current turn's answer in Result.Output, got %q", result.Output)+ }+ for _, content := range streamed {+ if strings.Contains(content, "STALE PRIOR ANSWER") {+ t.Fatalf("replayed history was re-sent to the UI: %v", streamed)+ }+ }+}++// TestZeroclawResumeNotFound covers the resume-not-found path: session/resume+// fails with ZeroClaw's custom -32000 SESSION_NOT_FOUND and the backend+// reports ResumeRejected=true so the daemon retries fresh.+func TestZeroclawResumeNotFound(t *testing.T) {+ t.Parallel()+ bin := writeFakeZeroclawScript(t, fakeZeroclawACPScript())++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ Env: map[string]string{"ZEROCLAW_SESSION_NOT_FOUND": "1"},+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ ctx := context.Background()+ session, err := b.Execute(ctx, "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ ResumeSessionID: "ses_gone",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }++ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "failed" {+ t.Fatalf("expected failed, got status=%q error=%q", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "session/resume failed") {+ t.Fatalf("expected session/resume failed error, got %q", result.Error)+ }+ if !result.ResumeRejected {+ t.Fatal("expected ResumeRejected=true on session not found — ZeroClaw reports it as -32000, which isACPSessionNotFound must recognise")+ }+}++func TestZeroclawBlockedArgs(t *testing.T) {+ t.Parallel()+ if _, ok := zeroclawBlockedArgs["acp"]; !ok {+ t.Fatal("expected acp to be in zeroclawBlockedArgs")+ }+ if zeroclawBlockedArgs["acp"] != blockedStandalone {+ t.Fatalf("expected acp to be blockedStandalone, got %v", zeroclawBlockedArgs["acp"])+ }+ for _, flag := range []string{"--help", "-h", "login", "auth", "--login", "--auth"} {+ if _, ok := zeroclawBlockedArgs[flag]; !ok {+ t.Fatalf("expected %s to be in zeroclawBlockedArgs", flag)+ }+ }+}++func TestSelectZeroclawPermissionOptionRejectsLegacyChoice(t *testing.T) {+ t.Parallel()++ question := json.RawMessage(`{"options":[{"optionId":"choice-0","kind":"allow_once"},{"optionId":"choice-1","kind":"allow_once"},{"optionId":"choice-2","kind":"reject_once"}]}`)+ optionID, grant, ok := selectZeroclawPermissionOption(question)+ if ok || grant || optionID != "" {+ t.Fatalf("legacy choices must return no selectable outcome, got option=%q grant=%v ok=%v", optionID, grant, ok)+ }+ questionWithoutReject := json.RawMessage(`{"options":[{"optionId":"choice-0","kind":"allow_once"},{"optionId":"choice-1","kind":"allow_once"}]}`)+ if optionID, grant, ok := selectZeroclawPermissionOption(questionWithoutReject); ok || grant || optionID != "" {+ t.Fatalf("legacy choices without an offered reject must return no selectable outcome, got option=%q grant=%v ok=%v", optionID, grant, ok)+ }++ toolApproval := json.RawMessage(`{"options":[{"optionId":"allow-once","kind":"allow_once"},{"optionId":"reject-once","kind":"reject_once"}]}`)+ optionID, grant, ok = selectZeroclawPermissionOption(toolApproval)+ if !ok || !grant || optionID != "allow-once" {+ t.Fatalf("ordinary tool approval must keep the shared single-use grant policy, got option=%q grant=%v ok=%v", optionID, grant, ok)+ }+}++// TestZeroclawLegacyChoiceReturnsProtocolErrorThroughClient pins the backend+// wiring, not just the selector helper. The fake waits for the response to the+// same session/request_permission shape ZeroClaw uses for structured ask_user,+// then mirrors ZeroClaw's prompt failure after the client returns -32603.+func TestZeroclawLegacyChoiceReturnsProtocolErrorThroughClient(t *testing.T) {+ t.Parallel()+ script := `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"sessionCapabilities":{"resume":{}}}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_choice","workspaceDir":"/tmp"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","id":"zc-out-0","method":"session/request_permission","params":{"sessionId":"ses_choice","options":[{"optionId":"choice-0","kind":"allow_once"},{"optionId":"choice-1","kind":"allow_once"},{"optionId":"choice-2","kind":"reject_once"}]}}\n'+ IFS= read -r answer+ case "$answer" in+ *'"code":-32603'*) ;;+ *) exit 2 ;;+ esac+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32000,"message":"ACP request_permission failed: no auto-selectable permission option offered"}}\n' "$id"+ ;;+ *)+ exit 3+ ;;+ esac+done+`+ bin := writeFakeZeroclawScript(t, script)+ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{ExecutablePath: bin, Logger: logger})+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ session, err := b.Execute(context.Background(), "choose", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ for range session.Messages {+ }+ result := <-session.Result+ if result.Status != "failed" || !strings.Contains(result.Error, "ACP request_permission failed") {+ t.Fatalf("expected the legacy choice to fail through the protocol error, got status=%q error=%q", result.Status, result.Error)+ }+}++func TestZeroclawListModels(t *testing.T) {+ t.Parallel()+ // ZeroClaw's session/new advertises no catalog and it has no+ // session-scoped model selection to consume one, so ListModels must+ // return an empty catalog WITHOUT spawning a discovery subprocess.+ //+ // Point it at a real, executable fake that records its own invocation: a+ // non-existent path cannot guard this, because the removed discovery+ // helper also returned an empty catalog when the binary was missing.+ dir := t.TempDir()+ marker := filepath.Join(dir, "invoked")+ bin := writeFakeZeroclawScript(t, "#!/bin/sh\ntouch '"+marker+"'\nexit 0\n")++ cat, err := ListModels(context.Background(), "zeroclaw", Command{Path: bin})+ if err != nil {+ t.Fatalf("zeroclaw ListModels should not error, got: %v", err)+ }+ if len(cat.Models) != 0 {+ t.Fatalf("zeroclaw ListModels should return empty catalog, got %d models", len(cat.Models))+ }+ if _, err := os.Stat(marker); err == nil {+ t.Fatal("zeroclaw ListModels executed the CLI; it must return an empty catalog without spawning a discovery subprocess")+ }+}++func TestZeroclawModelSelectionUnsupported(t *testing.T) {+ t.Parallel()+ if ModelSelectionSupported("zeroclaw") {+ t.Fatal("ModelSelectionSupported(zeroclaw) should return false — its ACP server has no session/set_model and no handler reads a model param, so the model comes from the ZeroClaw agent profile")+ }+ // Other providers should remain supported.+ if !ModelSelectionSupported("claude") {+ t.Fatal("ModelSelectionSupported(claude) should remain true")+ }+}++// TestZeroclawDoesNotAttemptModelSelection is the regression for the shipped+// bug: the backend used to send session/set_model whenever opts.Model was set+// and fail the whole run on its error. ZeroClaw dispatches no such method —+// the real binary answers -32601, which the fake reproduces through its+// default arm — so a configured model turned every run into a hard failure+// before session/prompt was ever sent.+func TestZeroclawDoesNotAttemptModelSelection(t *testing.T) {+ t.Parallel()+ bin := writeFakeZeroclawScript(t, fakeZeroclawACPScript())+ reqFile := filepath.Join(t.TempDir(), "requests.txt")++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ Env: map[string]string{"ZEROCLAW_REQUESTS_FILE": reqFile},+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ session, err := b.Execute(context.Background(), "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ Model: "zeroclaw-large",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }++ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "completed" {+ t.Fatalf("a configured model must not fail the run, got status=%q error=%q", result.Status, result.Error)+ }+ assertNoRecordedFrame(t, reqFile, "session/set_model")+ // The requested model is ignored, and initialize's process-global default+ // may belong to another alias, so neither is safe for attribution.+ if _, ok := result.Usage["unknown"]; !ok {+ t.Fatalf("expected usage without a per-turn model id to stay unknown, got %+v", result.Usage)+ }+}++// TestZeroclawDoesNotForwardMcpServers pins that a saved mcp_config never+// reaches the wire. ZeroClaw reads MCP only from its own config-dir — no ACP+// handler looks at `params.mcpServers` — so forwarding would be theatre, and+// the failure must stay non-fatal because a stale value must not brick a task.+func TestZeroclawDoesNotForwardMcpServers(t *testing.T) {+ t.Parallel()+ bin := writeFakeZeroclawScript(t, fakeZeroclawACPScript())+ reqFile := filepath.Join(t.TempDir(), "requests.txt")++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ Env: map[string]string{"ZEROCLAW_REQUESTS_FILE": reqFile},+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ session, err := b.Execute(context.Background(), "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ McpConfig: json.RawMessage(`{"mcpServers":{"probe-stdio":{"command":"/bin/sh","args":["-c","true"]},` ++ `"probe-http":{"type":"http","url":"http://127.0.0.1:59999/mcp"}}}`),+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }++ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "completed" {+ t.Fatalf("a stale mcp_config must not fail the run, got status=%q error=%q", result.Status, result.Error)+ }++ frame := findRecordedFrame(t, reqFile, "session/new")+ params, _ := frame["params"].(map[string]any)+ servers, ok := params["mcpServers"].([]any)+ if !ok {+ t.Fatalf("session/new must carry a spec-shaped mcpServers array, got %#v", params["mcpServers"])+ }+ if len(servers) != 0 {+ t.Fatalf("session/new must send an empty mcpServers array, got %#v", servers)+ }+ raw, err := os.ReadFile(reqFile)+ if err != nil {+ t.Fatalf("read requests file: %v", err)+ }+ for _, name := range []string{"probe-stdio", "probe-http"} {+ if strings.Contains(string(raw), name) {+ t.Fatalf("MCP server %q leaked onto the wire:\n%s", name, raw)+ }+ }+}++// TestZeroclawSessionNewOmitsAgentAliasWhenUnset guards ZeroClaw's+// sole-agent auto-select. When the operator configured no alias the key must+// be absent entirely: a hardcoded guess such as "default" turns a working+// single-agent install into `Unknown agent \`default\“.+func TestZeroclawSessionNewOmitsAgentAliasWhenUnset(t *testing.T) {+ t.Parallel()+ bin := writeFakeZeroclawScript(t, fakeZeroclawACPScript())+ reqFile := filepath.Join(t.TempDir(), "requests.txt")++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ Env: map[string]string{"ZEROCLAW_REQUESTS_FILE": reqFile},+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ // A whitespace-only alias counts as unset, matching ZeroClaw's own+ // trim-and-drop-empty handling of the param.+ session, err := b.Execute(context.Background(), "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ CustomArgs: []string{"--agent", " "},+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ for range session.Messages {+ }+ if result := <-session.Result; result.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }++ frame := findRecordedFrame(t, reqFile, "session/new")+ params, _ := frame["params"].(map[string]any)+ if _, ok := params["agentAlias"]; ok {+ t.Fatalf("session/new must omit agentAlias when none is configured, got %#v", params)+ }+}++// TestZeroclawSessionNewSendsConfiguredAgentAlias covers the multi-agent+// case. `zeroclaw acp` has no --agent flag — clap aborts on one — so the alias+// is lifted out of custom_args and travels as a session/new param instead.+func TestZeroclawSessionNewSendsConfiguredAgentAlias(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ args []string+ }{+ {name: "separate value", args: []string{"--agent", "myagent"}},+ {name: "inline value", args: []string{"--agent=myagent"}},+ {name: "long spelling", args: []string{"--agent-alias", "myagent"}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ bin := writeFakeZeroclawScript(t, fakeZeroclawACPScript())+ reqFile := filepath.Join(t.TempDir(), "requests.txt")++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ Env: map[string]string{"ZEROCLAW_REQUESTS_FILE": reqFile},+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ session, err := b.Execute(context.Background(), "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ CustomArgs: tc.args,+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ for range session.Messages {+ }+ if result := <-session.Result; result.Status != "completed" {+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)+ }++ frame := findRecordedFrame(t, reqFile, "session/new")+ params, _ := frame["params"].(map[string]any)+ if got := params["agentAlias"]; got != "myagent" {+ t.Fatalf("expected agentAlias=myagent on session/new, got %#v", params)+ }+ })+ }+}++// TestZeroclawAgentAliasNeverReachesArgv is the other half of the alias+// plumbing: `zeroclaw acp --agent x` dies at clap argument parsing, so the+// tokens must be consumed, not forwarded.+func TestZeroclawAgentAliasNeverReachesArgv(t *testing.T) {+ t.Parallel()+ alias, rest := takeZeroclawAgentAlias([]string{"--log-level", "debug", "--agent", "myagent", "--verbose"})+ if alias != "myagent" {+ t.Fatalf("expected alias myagent, got %q", alias)+ }+ want := []string{"--log-level", "debug", "--verbose"}+ if strings.Join(rest, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("expected the alias tokens to be consumed, got %v want %v", rest, want)+ }++ // A copy arriving through any other path must still be stripped rather+ // than crashing the CLI.+ for _, flag := range []string{"--agent", "--agent-alias"} {+ if zeroclawBlockedArgs[flag] != blockedWithValue {+ t.Fatalf("expected %s to be blockedWithValue in zeroclawBlockedArgs", flag)+ }+ }+}++// TestZeroclawSessionNewMissingAliasErrorIsActionable covers the install+// ZeroClaw refuses outright: 2+ agents (or none) with no [acp].default_agent.+// The bare RPC error names a param that has no CLI flag, so the backend has to+// say where the alias can actually come from.+func TestZeroclawSessionNewMissingAliasErrorIsActionable(t *testing.T) {+ t.Parallel()+ bin := writeFakeZeroclawScript(t, fakeZeroclawACPScript())++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ Env: map[string]string{"ZEROCLAW_REQUIRE_AGENT_ALIAS": "1"},+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ session, err := b.Execute(context.Background(), "test prompt", ExecOptions{Cwd: t.TempDir()})+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }+ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "failed" {+ t.Fatalf("expected failed, got status=%q error=%q", result.Status, result.Error)+ }+ for _, want := range []string{"--agent", "acp].default_agent"} {+ if !strings.Contains(result.Error, want) {+ t.Fatalf("expected the error to mention %q, got %q", want, result.Error)+ }+ }+}++// TestZeroclawTimeout tests that a context timeout during session/new is+// reported as status=timeout. The fake script responds to initialize+// immediately, then sleeps 30s on session/new so the 5s context deadline+// expires during the session/new RPC.+func TestZeroclawTimeout(t *testing.T) {+ t.Parallel()++ script := `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ sleep 30+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_late"}}\n' "$id"+ ;;+ *)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"method not found"}}\n' "$id"+ ;;+ esac+done`++ bin := writeFakeZeroclawScript(t, script)++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ session, err := b.Execute(ctx, "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }++ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "timeout" {+ t.Fatalf("expected timeout, got status=%q error=%q", result.Status, result.Error)+ }+}++// TestZeroclawSessionResumeTransientError verifies that a transient+// network/handshake error on session/resume does NOT set ResumeRejected=true,+// matching the invariant documented in grok.go and qwenpaw_test.go.+//+// The code here is -32000, the same one ZeroClaw uses for SESSION_NOT_FOUND,+// so this also pins that isACPSessionNotFound still decides on the wording:+// recognising the code alone would throw away a live session on a rate limit.+func TestZeroclawSessionResumeTransientError(t *testing.T) {+ t.Parallel()++ script := `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"resume":{}}}}}\n' "$id"+ ;;+ *'"method":"session/resume"'*)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32000,"message":"rate limit exceeded"}}\n' "$id"+ exit 0+ ;;+ *)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"method not found"}}\n' "$id"+ ;;+ esac+done+`+ bin := writeFakeZeroclawScript(t, script)++ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))+ b, err := New("zeroclaw", Config{+ ExecutablePath: bin,+ Logger: logger,+ })+ if err != nil {+ t.Fatalf("New(zeroclaw) error: %v", err)+ }++ ctx := context.Background()+ session, err := b.Execute(ctx, "test prompt", ExecOptions{+ Cwd: t.TempDir(),+ ResumeSessionID: "ses_transient",+ })+ if err != nil {+ t.Fatalf("Execute error: %v", err)+ }++ for range session.Messages {+ }++ result := <-session.Result+ if result.Status != "failed" {+ t.Fatalf("expected failed, got status=%q error=%q", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "session/resume failed") {+ t.Fatalf("expected session/resume failed error, got %q", result.Error)+ }+ if result.ResumeRejected {+ t.Fatal("expected ResumeRejected=false on transient resume error")+ }+}