Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9086: add Amp CLI harness support (#10477)
Multica Eve19a62c1b2940
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 5228fd4797..060f93ba22 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -295,6 +295,7 @@ The daemon auto-detects these AI CLIs on your PATH:| [Trae](https://docs.trae.cn/cli) | `traecli` | ByteDance TRAE CLI (ACP via `traecli acp serve`) || [Grok Build CLI](https://docs.x.ai/) | `grok` | xAI Grok Build CLI (ACP via `grok agent stdio`) || [Qwen Code](https://github.com/QwenLM/qwen-code) | `qwen` | Alibaba Qwen Code (`qwen -p` with stream-json) |+| [Amp](https://ampcode.com/docs/cli) | `amp` | Local `amp --execute --stream-json`; requires an access token in `AMP_API_KEY` for unattended execution. Model configuration selects an Amp mode. Managed MCP and live supplements are unsupported. || [Factory Droid](https://docs.factory.com/droid-exec/overview) | `droid` | Native CLI 1.8.0+, `droid exec` with stream-json; sign in or set `FACTORY_API_KEY`. Uses `--auto high`; Multica-managed MCP and live supplements are unsupported. || [QwenPaw](https://github.com/agentscope-ai/QwenPaw) | `qwenpaw` | QwenPaw ACP coding agent (ACP via `qwenpaw acp`; model is fixed by its own configuration) || [MiniMax Code](https://github.com/MiniMax-AI/minimax-code) | `mcode` | MiniMax Code ACP coding agent (ACP via `mcode acp`; model is managed by MCode) |@@ -479,6 +480,9 @@ Agent-specific overrides:| `MULTICA_QWEN_PATH` | Custom path to the `qwen` binary || `MULTICA_QWEN_MODEL` | Override the Qwen Code model used || `MULTICA_QWEN_ARGS` | Daemon-wide extra Qwen arguments (POSIX shellword parsing; managed protocol flags are filtered) |+| `MULTICA_AMP_PATH` | Custom path to the `amp` executable |+| `MULTICA_AMP_MODEL` | Amp mode (such as `high`); empty uses Amp's default |+| `MULTICA_AMP_ARGS` | Supported extra Amp options, e.g. `--features fast`; protocol, executor, prompt and mode overrides are filtered || `MULTICA_DROID_PATH` | Custom path to the native `droid` executable || `MULTICA_DROID_MODEL` | Droid model ID; defaults to Droid's own configuration || `MULTICA_DROID_ARGS` | Daemon-wide Droid arguments, e.g. `--reasoning-effort high`; managed protocol, prompt, session, and working-directory flags are filtered |diff --git a/SELF_HOSTING.md b/SELF_HOSTING.mdindex 8e87beef24..fd04b88c3d 100644--- a/SELF_HOSTING.md+++ b/SELF_HOSTING.md@@ -140,6 +140,7 @@ You also need at least one AI agent CLI installed:- Trae CLI (`traecli` on PATH)- [Grok Build CLI](https://docs.x.ai/) (`grok` on PATH)- Qwen Code (`qwen` on PATH)+- [Amp](https://ampcode.com/docs/cli) (`amp` on PATH on macOS, Linux or Windows through WSL; set an Amp access token in `AMP_API_KEY` on the daemon machine)- [Factory Droid](https://docs.factory.com/droid-exec/overview) (native `droid` 1.8.0+ on PATH; sign in or set `FACTORY_API_KEY` on the daemon machine; Linux requires glibc)- [QwenPaw](https://github.com/agentscope-ai/QwenPaw) (`qwenpaw` on PATH; pick its model in QwenPaw's own configuration)- [MiniMax Code CLI](https://www.npmjs.com/package/@minimax-ai/code) (`mcode` 0.1.2+ on PATH). Install a supported Node.js release (`>=22.19 <23` or `>=24 <27`), run `npm install --global @minimax-ai/code@latest`, then `mcode login`.diff --git a/apps/docs/content/docs/install-agent-runtime.fr.mdx b/apps/docs/content/docs/install-agent-runtime.fr.mdxindex 7b0e8557de..845214d6f0 100644--- a/apps/docs/content/docs/install-agent-runtime.fr.mdx+++ b/apps/docs/content/docs/install-agent-runtime.fr.mdx@@ -46,6 +46,7 @@ Multica détecte actuellement ces commandes :| Qoder CN CLI | `qoderclicn` | [Démarrage rapide de Qoder CN CLI](https://help.aliyun.com/en/lingma/qodercli-cn/user-guide/qoder-cli-cn-get-started-quickly) || Qwen Code | `qwen` | [Qwen Code](https://github.com/QwenLM/qwen-code) || QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |+| Amp | `amp` | [Amp CLI](https://ampcode.com/docs/cli) || Factory Droid | `droid` | [Factory Droid](https://docs.factory.com/droid-exec/overview) || Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) || TRAE CLI | `traecli` | [Site officiel de TRAE](https://www.trae.cn/) |diff --git a/apps/docs/content/docs/install-agent-runtime.ja.mdx b/apps/docs/content/docs/install-agent-runtime.ja.mdxindex 1c610b9946..35ee8535f6 100644--- a/apps/docs/content/docs/install-agent-runtime.ja.mdx+++ b/apps/docs/content/docs/install-agent-runtime.ja.mdx@@ -46,6 +46,7 @@ Multica は現在、次のコマンドを検出します。| Qoder CN CLI | `qoderclicn` | [Qoder CN CLI クイックスタート](https://help.aliyun.com/en/lingma/qodercli-cn/user-guide/qoder-cli-cn-get-started-quickly) || Qwen Code | `qwen` | [Qwen Code](https://github.com/QwenLM/qwen-code) || QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |+| Amp | `amp` | [Amp CLI](https://ampcode.com/docs/cli) || Factory Droid | `droid` | [Factory Droid](https://docs.factory.com/droid-exec/overview) || Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) || TRAE CLI | `traecli` | [TRAE 公式サイト](https://www.trae.cn/) |diff --git a/apps/docs/content/docs/install-agent-runtime.ko.mdx b/apps/docs/content/docs/install-agent-runtime.ko.mdxindex 88a90046dc..bb3211e550 100644--- a/apps/docs/content/docs/install-agent-runtime.ko.mdx+++ b/apps/docs/content/docs/install-agent-runtime.ko.mdx@@ -46,6 +46,7 @@ Multica는 현재 다음 명령을 감지합니다.| Qoder CN CLI | `qoderclicn` | [Qoder CN CLI 빠른 시작](https://help.aliyun.com/en/lingma/qodercli-cn/user-guide/qoder-cli-cn-get-started-quickly) || Qwen Code | `qwen` | [Qwen Code](https://github.com/QwenLM/qwen-code) || QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |+| Amp | `amp` | [Amp CLI](https://ampcode.com/docs/cli) || Factory Droid | `droid` | [Factory Droid](https://docs.factory.com/droid-exec/overview) || Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) || TRAE CLI | `traecli` | [TRAE 공식 사이트](https://www.trae.cn/) |diff --git a/apps/docs/content/docs/install-agent-runtime.mdx b/apps/docs/content/docs/install-agent-runtime.mdxindex cad5147309..b86a5c9c91 100644--- a/apps/docs/content/docs/install-agent-runtime.mdx+++ b/apps/docs/content/docs/install-agent-runtime.mdx@@ -45,6 +45,7 @@ Multica currently detects these commands:| Qoder CN CLI | `qoderclicn` | [Qoder CN CLI quickstart](https://help.aliyun.com/en/lingma/qodercli-cn/user-guide/qoder-cli-cn-get-started-quickly) || Qwen Code | `qwen` | [Qwen Code](https://github.com/QwenLM/qwen-code) || QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |+| Amp | `amp` | [Amp CLI](https://ampcode.com/docs/cli) || Factory Droid | `droid` | [Factory Droid](https://docs.factory.com/droid-exec/overview) || Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) || TRAE CLI | `traecli` | [TRAE official site](https://www.trae.cn/) |@@ -85,6 +86,17 @@ Below the minimum version, the daemon does not register the corresponding runtimA few tools need extra setup beyond signing in:<Accordions type="multiple">+<Accordion title="Amp" id="amp">++Install the latest [Amp CLI](https://ampcode.com/docs/cli) on the daemon machine. Amp supports macOS, Linux and Windows through WSL; run the daemon inside WSL when using Windows. Set an Amp access token in `AMP_API_KEY` in the daemon or agent environment, following the official non-interactive setup. Interactive login and saved login sessions alone are not supported by this adapter. Do not put credentials in prompts or custom arguments.++After discovery, select the Amp runtime when creating an agent and assign a task. `MULTICA_AMP_PATH` overrides the executable. Leave the model field empty for Amp's default, or enter an Amp **mode** such as `high`; `MULTICA_AMP_MODEL` sets the daemon default. Amp manages the underlying models. `MULTICA_AMP_ARGS` and agent custom arguments accept `--settings-file`, `--features`, `--fast`, `--plugin-ready-timeout <seconds>`, `--timings`, `--visibility`, `--label`, and `--no-archive-after-execute`.++Multica runs `amp --execute --stream-json --executor local`, sends the prompt through stdin, and resumes only the saved thread ID. Amp reads `AGENTS.md` and project skills from `.agents/skills/`. Configure MCP in Amp itself. Managed MCP, live message supplements, `max_turns`, orbs and remote runners are unsupported. Use the task timeout to bound execution. Transport, mode and executor overrides are filtered; extra prompts, subcommands and unverified options fail before launch.++Missing installations and startup errors appear as failures. Missing `AMP_API_KEY` fails before startup. For authentication errors, replace the access token in the execution environment. Only a successful terminal `result` can publish a final answer; a clean exit or assistant `end_turn` alone cannot. Amp gets up to ten seconds to finish cleanup after its terminal result. If Multica then has to stop the process, it keeps the final answer and logs a warning; a native nonzero exit observed during the grace still fails. Amp-reported permission denials appear as transcript warnings. Check `amp.permissions` in the execution machine's Amp settings if approved commands are denied in unattended runs. Cancellation and timeout terminate the owned local process tree and retain the observed thread ID. [Amp background subagents](https://ampcode.com/docs/cli/streaming-json) may survive CLI exit on Amp's service; their remote cancellation is not available through this adapter. Avoid asynchronous subagents when strict cancellation is required, and inspect any remaining work in the saved Amp thread.++</Accordion><Accordion title="Factory Droid" id="droid">Install the native Droid CLI using the [official instructions](https://docs.factory.com/droid-exec/overview). Multica supports Droid 1.8.0 or later on macOS, Windows, and glibc-based Linux; Alpine is unsupported. Sign in with `droid`, or set `FACTORY_API_KEY` in the daemon environment or the agent's custom environment. Keep credentials out of prompts and custom arguments.diff --git a/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdx b/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdxindex 230c644d07..dbdead2806 100644--- a/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdx+++ b/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdx@@ -45,6 +45,7 @@ Multica 當前會檢測以下命令:| Qoder CN CLI | `qoderclicn` | [Qoder CN CLI 快速開始](https://help.aliyun.com/zh/lingma/qodercli-cn/user-guide/qoder-cli-cn-get-started-quickly) || Qwen Code | `qwen` | [Qwen Code](https://github.com/QwenLM/qwen-code) || QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |+| Amp | `amp` | [Amp CLI](https://ampcode.com/docs/cli) || Factory Droid | `droid` | [Factory Droid](https://docs.factory.com/droid-exec/overview) || Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) || TRAE CLI | `traecli` | [TRAE 官方站](https://www.trae.cn/) |diff --git a/apps/docs/content/docs/install-agent-runtime.zh.mdx b/apps/docs/content/docs/install-agent-runtime.zh.mdxindex a5eaedbb66..150da07db5 100644--- a/apps/docs/content/docs/install-agent-runtime.zh.mdx+++ b/apps/docs/content/docs/install-agent-runtime.zh.mdx@@ -45,6 +45,7 @@ Multica 当前会检测以下命令:| Qoder CN CLI | `qoderclicn` | [Qoder CN CLI 快速开始](https://help.aliyun.com/zh/lingma/qodercli-cn/user-guide/qoder-cli-cn-get-started-quickly) || Qwen Code | `qwen` | [Qwen Code](https://github.com/QwenLM/qwen-code) || QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |+| Amp | `amp` | [Amp CLI](https://ampcode.com/docs/cli) || Factory Droid | `droid` | [Factory Droid](https://docs.factory.com/droid-exec/overview) || Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) || TRAE CLI | `traecli` | [TRAE 官方站](https://www.trae.cn/) |@@ -85,6 +86,17 @@ Multica 当前会检测以下命令:以下工具除了登录,还要额外配置:<Accordions type="multiple">+<Accordion title="Amp" id="amp">++在守护进程所在机器按[官方说明](https://ampcode.com/docs/cli)安装最新版 Amp CLI。Amp 支持 macOS、Linux 和 Windows 下的 WSL;Windows 用户需在 WSL 中运行守护进程。按官方非交互执行说明,在守护进程或智能体环境中设置访问令牌 `AMP_API_KEY`。本适配器不支持交互登录,仅保存登录会话不足以启动任务;不要把凭据写入提示词或自定义参数。++发现运行时后,创建智能体时选择 Amp,再指派任务。`MULTICA_AMP_PATH` 可覆盖可执行文件路径。模型字段留空沿用 Amp 默认值,也可填写 `high` 等 Amp **模式**;`MULTICA_AMP_MODEL` 设置守护进程默认模式,底层模型由 Amp 管理。`MULTICA_AMP_ARGS` 和智能体自定义参数支持 `--settings-file`、`--features`、`--fast`、`--plugin-ready-timeout <秒数>`、`--timings`、`--visibility`、`--label` 和 `--no-archive-after-execute`。++Multica 使用 `amp --execute --stream-json --executor local`,通过标准输入传入提示词,仅使用已保存的线程 ID 继续会话。Amp 读取 `AGENTS.md`,从 `.agents/skills/` 发现项目技能。MCP 需在 Amp 中配置;暂不支持 Multica 托管 MCP、执行中追加消息、`max_turns`、orb 或远程 runner,执行时长使用任务超时限制。协议、模式和执行位置覆盖项会被过滤,额外提示词、子命令和未验证选项会在启动前报错。++未安装、缺少 `AMP_API_KEY` 或启动异常会立即报错;认证失败时更新执行环境中的访问令牌。只有成功的终结 `result` 才会发布最终答复,正常退出或 assistant 的 `end_turn` 均不足以判定成功。收到终结结果后,Amp 有最多十秒完成清理;之后若由 Multica 终止进程,仍保留最终答复并记录警告,宽限期内观测到的原生非零退出仍判为失败。Amp 返回的权限拒绝信息会显示为执行记录中的警告;若无人值守任务中的已授权命令被拒绝,请检查执行机器上 Amp 设置中的 `amp.permissions`。取消和超时会终止所属本地进程树,并保留已观测的线程 ID。[Amp 后台子智能体](https://ampcode.com/docs/cli/streaming-json)可能在 CLI 退出后继续运行,本适配器无法远程取消它们。需要严格取消时避免异步子智能体,并通过保存的 Amp 线程检查剩余工作。++</Accordion><Accordion title="Factory Droid" id="droid">按[官方说明](https://docs.factory.com/droid-exec/overview)安装原生 Droid CLI,版本需为 1.8.0 或更新。支持 macOS、Windows 和使用 glibc 的 Linux,不支持 Alpine。运行 `droid` 登录,或在守护进程环境、智能体的自定义环境中设置 `FACTORY_API_KEY`,不要把凭据写进提示词或自定义参数。diff --git a/apps/docs/content/docs/providers.fr.mdx b/apps/docs/content/docs/providers.fr.mdxindex 71f81d1d98..59777b8f0d 100644--- a/apps/docs/content/docs/providers.fr.mdx+++ b/apps/docs/content/docs/providers.fr.mdx@@ -45,6 +45,7 @@ Les étapes d'installation se trouvent dans [Installer les outils de codage IA](| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | ✓ | `.qoder/skills/` || Qwen Code | `qwen` | ✓ | ✓ | ✓ | `.qwen/skills/` || QwenPaw | `qwenpaw` | ✓ | ✓ | — | `skills/` de l'espace de travail propre à chaque exécution |+| Amp | `amp` | ✓ | — | ✓ | `.agents/skills/` || Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` || Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` || Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |diff --git a/apps/docs/content/docs/providers.ja.mdx b/apps/docs/content/docs/providers.ja.mdxindex d4023436e8..0a48f0f08c 100644--- a/apps/docs/content/docs/providers.ja.mdx+++ b/apps/docs/content/docs/providers.ja.mdx@@ -45,6 +45,7 @@ Multica は、普段使っている AI コーディングツールの代わり| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | ✓ | `.qoder/skills/` || Qwen Code | `qwen` | ✓ | ✓ | ✓ | `.qwen/skills/` || QwenPaw | `qwenpaw` | ✓ | ✓ | — | 1 回の実行専用のワークスペース `skills/` |+| Amp | `amp` | ✓ | — | ✓ | `.agents/skills/` || Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` || Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` || Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |diff --git a/apps/docs/content/docs/providers.ko.mdx b/apps/docs/content/docs/providers.ko.mdxindex 21ec7eb7a7..f724b61463 100644--- a/apps/docs/content/docs/providers.ko.mdx+++ b/apps/docs/content/docs/providers.ko.mdx@@ -45,6 +45,7 @@ Multica는 사용 중인 AI 코딩 도구를 대체하지 않습니다. 런타| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | ✓ | `.qoder/skills/` || Qwen Code | `qwen` | ✓ | ✓ | ✓ | `.qwen/skills/` || QwenPaw | `qwenpaw` | ✓ | ✓ | — | 실행별 워크스페이스 `skills/` |+| Amp | `amp` | ✓ | — | ✓ | `.agents/skills/` || Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` || Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` || Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |diff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdxindex 3b65a95a3c..99098c42eb 100644--- a/apps/docs/content/docs/providers.mdx+++ b/apps/docs/content/docs/providers.mdx@@ -45,6 +45,7 @@ Install steps are in [Install AI coding tools](/install-agent-runtime).| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | ✓ | `.qoder/skills/` || Qwen Code | `qwen` | ✓ | ✓ | ✓ | `.qwen/skills/` || QwenPaw | `qwenpaw` | ✓ | ✓ | — | per-run workspace `skills/` |+| Amp | `amp` | ✓ | — | ✓ | `.agents/skills/` || Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` || Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` || Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |diff --git a/apps/docs/content/docs/providers.zh-Hant.mdx b/apps/docs/content/docs/providers.zh-Hant.mdxindex 6975c245c0..0326a576f1 100644--- a/apps/docs/content/docs/providers.zh-Hant.mdx+++ b/apps/docs/content/docs/providers.zh-Hant.mdx@@ -45,6 +45,7 @@ Multica 不替代你在用的 AI 程式設計工具:執行時呼叫電腦上| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | ✓ | `.qoder/skills/` || Qwen Code | `qwen` | ✓ | ✓ | ✓ | `.qwen/skills/` || QwenPaw | `qwenpaw` | ✓ | ✓ | — | 單次執行的工作區 `skills/` |+| Amp | `amp` | ✓ | — | ✓ | `.agents/skills/` || Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` || Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` || Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |diff --git a/apps/docs/content/docs/providers.zh.mdx b/apps/docs/content/docs/providers.zh.mdxindex 00f8a29b30..b705324a5c 100644--- a/apps/docs/content/docs/providers.zh.mdx+++ b/apps/docs/content/docs/providers.zh.mdx@@ -45,6 +45,7 @@ Multica 不替代你在用的 AI 编程工具:运行时调用电脑上已经| Qoder CN CLI | `qoderclicn` | ✓ | ✓ | ✓ | `.qoder/skills/` || Qwen Code | `qwen` | ✓ | ✓ | ✓ | `.qwen/skills/` || QwenPaw | `qwenpaw` | ✓ | ✓ | — | 单次执行的工作区 `skills/` |+| Amp | `amp` | ✓ | — | ✓ | `.agents/skills/` || Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` || Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` || Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |diff --git a/packages/core/agents/mcp-support.test.ts b/packages/core/agents/mcp-support.test.tsindex ed3e46a229..e32ef5a7f4 100644--- a/packages/core/agents/mcp-support.test.ts+++ b/packages/core/agents/mcp-support.test.ts@@ -12,6 +12,7 @@ describe("providerSupportsMcpConfig", () => {expect(providerSupportsMcpConfig("antigravity")).toBe(false);expect(providerSupportsMcpConfig("copilot")).toBe(false);expect(providerSupportsMcpConfig("droid")).toBe(false);+ expect(providerSupportsMcpConfig("amp")).toBe(false);expect(providerSupportsMcpConfig("pi")).toBe(true);// 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.diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 58560ffb29..b6e1d37729 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -136,6 +136,7 @@ export const RUNTIME_PROFILE_PROTOCOL_FAMILIES = ["qwen","qwenpaw","droid",+ "amp","mcode","muse","devin",diff --git a/scripts/agent-cli-command-names.txt b/scripts/agent-cli-command-names.txtindex b31bc2026c..37057140ab 100644--- a/scripts/agent-cli-command-names.txt+++ b/scripts/agent-cli-command-names.txt@@ -1,4 +1,5 @@agy+ampclaudecodebuddycodeartsdiff --git a/server/internal/daemon/agents_probe.go b/server/internal/daemon/agents_probe.goindex c77d2ba12f..0ec940a3cf 100644--- a/server/internal/daemon/agents_probe.go+++ b/server/internal/daemon/agents_probe.go@@ -312,6 +312,9 @@ var probeAgentCLIs = func() map[string]AgentEntry {if e, ok := probe("MULTICA_QWEN_PATH", "qwen", "MULTICA_QWEN_MODEL"); ok {agents["qwen"] = e}+ if e, ok := probe("MULTICA_AMP_PATH", "amp", "MULTICA_AMP_MODEL"); ok {+ agents["amp"] = e+ }if e, ok := probe("MULTICA_DROID_PATH", "droid", "MULTICA_DROID_MODEL"); ok {agents["droid"] = e}diff --git a/server/internal/daemon/amp_test.go b/server/internal/daemon/amp_test.gonew file mode 100644index 0000000000..1feddb83c7--- /dev/null+++ b/server/internal/daemon/amp_test.go@@ -0,0 +1,59 @@+package daemon++import (+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+)++func TestAmpDiscoveryAndConfiguration(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("POSIX executable fixture")+ }+ for _, override := range []bool{false, true} {+ t.Run(map[bool]string{false: "PATH", true: "override"}[override], func(t *testing.T) {+ bin := stageFakeAgent(t)+ path := filepath.Join(bin, "amp")+ if err := os.WriteFile(path, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ t.Setenv("SHELL", "/usr/bin/fish")+ t.Setenv("MULTICA_AMP_PATH", "")+ if override {+ t.Setenv("MULTICA_AMP_PATH", path)+ }+ t.Setenv("MULTICA_AMP_MODEL", "high")+ t.Setenv("MULTICA_AMP_ARGS", "--features fast")+ cfg, err := LoadConfig(Overrides{ServerURL: "http://localhost:0", WorkspacesRoot: t.TempDir()})+ if err != nil {+ t.Fatal(err)+ }+ wantPath, _ := filepath.EvalSymlinks(path)+ entry, ok := cfg.Agents["amp"]+ gotPath, _ := filepath.EvalSymlinks(entry.Path)+ if !ok || gotPath != wantPath || entry.Model != "high" {+ t.Fatalf("Amp not discovered: %+v", cfg.Agents)+ }+ args := defaultArgsForProvider(cfg, "amp")+ if strings.Join(args, " ") != "--features fast" {+ t.Fatalf("args = %v", args)+ }+ args[0] = "changed"+ if cfg.AmpArgs[0] != "--features" {+ t.Fatal("caller mutated daemon defaults")+ }+ })+ }+}++func TestAmpLocalSkills(t *testing.T) {+ home := t.TempDir()+ redirectTestHome(t, home)+ writeTestLocalSkill(t, filepath.Join(home, ".config", "amp", "skills"), "review", map[string]string{"SKILL.md": "---\nname: Review\ndescription: Review code\n---\n"})+ skills, supported, err := listRuntimeLocalSkills("amp")+ if err != nil || !supported || len(skills) != 1 || skills[0].SourcePath != "~/.config/amp/skills/review" {+ t.Fatalf("Amp local skills = %+v, %v, %v", skills, supported, err)+ }+}diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex b0a116f965..d5371be062 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -110,7 +110,7 @@ type Config struct {CLICommit string // full build revision embedded in the running CLI; empty/unknown if unavailableLaunchedBy 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, codearts, deveco, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro, antigravity, qoder, qoderclicn, traecli, grok, qwen, qwenpaw, droid, mcode, muse, devin, dim, zeroclaw, museapp (plus built-in runtime identities from agent.BuiltinRuntimes, e.g. omp)+ Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, codearts, deveco, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro, antigravity, qoder, qoderclicn, traecli, grok, qwen, qwenpaw, droid, amp, mcode, muse, devin, dim, zeroclaw, museapp (plus built-in runtime identities from agent.BuiltinRuntimes, e.g. omp)WorkspacesRoot string // base path for execution envs (default: ~/multica_workspaces)HealthPort int // local HTTP port for health checks (default: 19514)MaxConcurrentTasks int // max tasks running in parallel (default: 20)@@ -156,6 +156,7 @@ type Config struct {CodebuddyArgs []stringQwenArgs []stringDroidArgs []string+ AmpArgs []stringQwenpawArgs []string// ProfileCommandOverrides maps a custom runtime profile_id -> the absolute@@ -267,7 +268,7 @@ func LoadConfig(overrides Overrides) (Config, error) {// can re-run the same discovery on a live daemon (MUL-5439).agents := probeAgentCLIs()if len(agents) == 0 && !overrides.AllowNoAgents {- return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codearts, codex, copilot, opencode, deveco, openclaw, hermes, pi, omp, cursor-agent, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, droid, mcode, muse, devin, dim, zeroclaw, or zcode and ensure it is on PATH")+ return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codearts, codex, copilot, opencode, deveco, openclaw, hermes, pi, omp, cursor-agent, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, droid, amp, mcode, muse, devin, dim, zeroclaw, or zcode and ensure it is on PATH")}claudeArgs, err := shellArgsFromEnv("MULTICA_CLAUDE_ARGS")@@ -286,6 +287,10 @@ func LoadConfig(overrides Overrides) (Config, error) {if err != nil {return Config{}, err}+ ampArgs, err := shellArgsFromEnv("MULTICA_AMP_ARGS")+ if err != nil {+ return Config{}, err+ }droidArgs, err := shellArgsFromEnv("MULTICA_DROID_ARGS")if err != nil {return Config{}, err@@ -684,6 +689,7 @@ func LoadConfig(overrides Overrides) (Config, error) {CodebuddyArgs: codebuddyArgs,QwenArgs: qwenArgs,DroidArgs: droidArgs,+ AmpArgs: ampArgs,QwenpawArgs: qwenpawArgs,ProfileCommandOverrides: profileCommandOverrides,}, nil@@ -967,7 +973,7 @@ func isExecutableFile(path string) bool {// doesn't require editing this list by hand.var defaultAgentCommandNames = append([]string{"claude", "codex", "opencode", "codearts", "deveco", "openclaw", "hermes",- "pi", "cursor-agent", "copilot", "kimi", "reasonix", "dsh", "kiro-cli", "codebuddy", "agy", "qodercli", "qoderclicn", "traecli", "grok", "qwen", "qwenpaw", "droid", "mcode", "muse", "devin", "dim", "zeroclaw", "zcode",+ "pi", "cursor-agent", "copilot", "kimi", "reasonix", "dsh", "kiro-cli", "codebuddy", "agy", "qodercli", "qoderclicn", "traecli", "grok", "qwen", "qwenpaw", "droid", "amp", "mcode", "muse", "devin", "dim", "zeroclaw", "zcode",}, agent.BuiltinRuntimeCommands()...)// zcodeDesktopAppBundlePaths discovers the CLI in default Desktop installs.diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 104e7bf96c..150e84e6db 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -11273,6 +11273,8 @@ func defaultArgsForProvider(cfg Config, provider string) []string {args = cfg.QwenArgscase "droid":args = cfg.DroidArgs+ case "amp":+ args = cfg.AmpArgscase "qwenpaw":args = cfg.QwenpawArgsdefault:diff --git a/server/internal/daemon/execenv/amp_test.go b/server/internal/daemon/execenv/amp_test.gonew file mode 100644index 0000000000..448fbbf541--- /dev/null+++ b/server/internal/daemon/execenv/amp_test.go@@ -0,0 +1,25 @@+package execenv++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestAmpRuntimeBriefAndSkills(t *testing.T) {+ dir := t.TempDir()+ task := TaskContextForEnv{IssueID: "amp-issue", AgentSkills: []SkillContextForEnv{{Name: "Review", Content: "Review carefully."}}}+ if _, err := writeContextFiles(dir, "amp", task, nil); err != nil {+ t.Fatal(err)+ }+ if _, err := InjectRuntimeConfig(dir, "amp", task); err != nil {+ t.Fatal(err)+ }+ for path, want := range map[string]string{"AGENTS.md": "Multica Agent Runtime", ".agents/skills/review/SKILL.md": "Review carefully."} {+ data, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(path)))+ if err != nil || !strings.Contains(string(data), want) {+ t.Fatalf("%s = %q, %v", path, data, err)+ }+ }+}diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.goindex 81ee7a01f8..a36bf35a42 100644--- a/server/internal/daemon/execenv/context.go+++ b/server/internal/daemon/execenv/context.go@@ -409,6 +409,8 @@ func skillsDirPath(workDir, provider string) string {case "qwen":// Qwen Code discovers project-level skills from .qwen/skills/ in the workdir.return filepath.Join(workDir, ".qwen", "skills")+ case "amp":+ return filepath.Join(workDir, ".agents", "skills")case "droid":return filepath.Join(workDir, ".factory", "skills")case "qwenpaw":diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.goindex cf005cc1e3..35bd22dae6 100644--- a/server/internal/daemon/execenv/runtime_config.go+++ b/server/internal/daemon/execenv/runtime_config.go@@ -218,7 +218,7 @@ func runtimeConfigPath(workDir, provider string) string {return filepath.Join(workDir, "CODEBUDDY.md")case "qwen":return filepath.Join(workDir, "QWEN.md")- case "codex", "copilot", "opencode", "codearts", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "droid", "mcode", "muse", "dim", "zeroclaw", "devin", "museapp", "zcode":+ case "codex", "copilot", "opencode", "codearts", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "droid", "amp", "mcode", "muse", "dim", "zeroclaw", "devin", "museapp", "zcode":return filepath.Join(workDir, "AGENTS.md")default:return ""diff --git a/server/internal/daemon/execenv/sidecar_manifest_test.go b/server/internal/daemon/execenv/sidecar_manifest_test.goindex a5b55ad7a0..5d5b7d11e8 100644--- a/server/internal/daemon/execenv/sidecar_manifest_test.go+++ b/server/internal/daemon/execenv/sidecar_manifest_test.go@@ -165,6 +165,7 @@ var allFileBasedProviders = []string{"qwen","qwenpaw","droid",+ "amp","mcode",}diff --git a/server/internal/daemon/local_skills.go b/server/internal/daemon/local_skills.goindex 8af1297cda..776265a914 100644--- a/server/internal/daemon/local_skills.go+++ b/server/internal/daemon/local_skills.go@@ -221,6 +221,9 @@ func localSkillRootsForProvider(provider string) ([]localSkillRoot, bool, error)qwenHome = filepath.Join(home, ".qwen")}providerRoot = filepath.Join(qwenHome, "skills")+ case "amp":+ providerRoot = filepath.Join(home, ".config", "amp", "skills")+ additionalProviderRoots = []string{filepath.Join(home, ".config", "agents", "skills")}case "droid":providerRoot = filepath.Join(home, ".factory", "skills")case "qwenpaw":diff --git a/server/internal/handler/runtime_profile_handler_test.go b/server/internal/handler/runtime_profile_handler_test.goindex 628d4fc3b6..d3db76fc6d 100644--- a/server/internal/handler/runtime_profile_handler_test.go+++ b/server/internal/handler/runtime_profile_handler_test.go@@ -444,13 +444,15 @@ func TestCreateRuntimeProfile_RuntimeIdentity(t *testing.T) {t.Skip("database not available")}for _, tc := range []struct {- name, target, family string- status int+ name, target, family, wantFamily string+ status int}{- {"omp", "omp", "", http.StatusCreated},- {"legacy pi", "", "pi", http.StatusCreated},- {"mismatch", "omp", "codex", http.StatusBadRequest},- {"unknown", "unknown", "", http.StatusBadRequest},+ {"omp", "omp", "", "pi", http.StatusCreated},+ {"amp", "amp", "", "amp", http.StatusCreated},+ {"amp protocol", "", "amp", "amp", http.StatusCreated},+ {"legacy pi", "", "pi", "pi", http.StatusCreated},+ {"mismatch", "omp", "codex", "", http.StatusBadRequest},+ {"unknown", "unknown", "", "", http.StatusBadRequest},} {t.Run(tc.name, func(t *testing.T) {req := withURLParam(newRequest("POST", "/", map[string]any{@@ -474,7 +476,7 @@ func TestCreateRuntimeProfile_RuntimeIdentity(t *testing.T) {if want == "" {want = tc.family}- if resp.RuntimeType != want || resp.ProtocolFamily != "pi" || resp.CommandName != "wrapper" || len(resp.FixedArgs) != 1 {+ if resp.RuntimeType != want || resp.ProtocolFamily != tc.wantFamily || resp.CommandName != "wrapper" || len(resp.FixedArgs) != 1 {t.Fatalf("incorrect identity: %+v", resp)}})diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex dcc749fa90..1405f67656 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -175,6 +175,7 @@ var ("qoderclicn": "qoderclicn","qwen": "qwen","droid": "droid",+ "amp": "amp","traecli": "traecli","other": "other",}diff --git a/server/migrations/656_runtime_profile_add_amp.down.sql b/server/migrations/656_runtime_profile_add_amp.down.sqlnew file mode 100644index 0000000000..450594913b--- /dev/null+++ b/server/migrations/656_runtime_profile_add_amp.down.sql@@ -0,0 +1,36 @@+-- Disable Amp profiles before downgrading the daemon; retain historical rows.+-- Restrict future writes without scanning existing rows.+ALTER TABLE runtime_profile+ DROP CONSTRAINT IF EXISTS runtime_profile_protocol_family_check,+ ADD CONSTRAINT runtime_profile_protocol_family_check+ CHECK (protocol_family IN (+ 'claude',+ 'codebuddy',+ 'codex',+ 'copilot',+ 'opencode',+ 'codearts',+ 'openclaw',+ 'hermes',+ 'pi',+ 'cursor',+ 'kimi',+ 'reasonix',+ 'dsh',+ 'kiro',+ 'antigravity',+ 'qoder',+ 'qoderclicn',+ 'traecli',+ 'deveco',+ 'grok',+ 'qwen',+ 'qwenpaw',+ 'mcode',+ 'muse',+ 'dim',+ 'zeroclaw',+ 'devin',+ 'zcode',+ 'droid'+ )) NOT VALID;diff --git a/server/migrations/656_runtime_profile_add_amp.up.sql b/server/migrations/656_runtime_profile_add_amp.up.sqlnew file mode 100644index 0000000000..ccb96baf5b--- /dev/null+++ b/server/migrations/656_runtime_profile_add_amp.up.sql@@ -0,0 +1,37 @@+-- Expand the current whitelist without scanning historical rows. Replacing+-- both parts in one ALTER keeps the constraint present atomically.+ALTER TABLE runtime_profile+ DROP CONSTRAINT IF EXISTS runtime_profile_protocol_family_check,+ ADD CONSTRAINT runtime_profile_protocol_family_check+ CHECK (protocol_family IN (+ 'claude',+ 'codebuddy',+ 'codex',+ 'copilot',+ 'opencode',+ 'codearts',+ 'openclaw',+ 'hermes',+ 'pi',+ 'cursor',+ 'kimi',+ 'reasonix',+ 'dsh',+ 'kiro',+ 'antigravity',+ 'qoder',+ 'qoderclicn',+ 'traecli',+ 'deveco',+ 'grok',+ 'qwen',+ 'qwenpaw',+ 'mcode',+ 'muse',+ 'dim',+ 'zeroclaw',+ 'devin',+ 'zcode',+ 'droid',+ 'amp'+ )) NOT VALID;diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex ee84a4a758..e1a42c48f6 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -433,6 +433,7 @@ var SupportedTypes = []string{"qwen","qwenpaw","droid",+ "amp","mcode","muse","dim",@@ -473,6 +474,7 @@ var resumeRejectionUndetectable = map[string]bool{"opencode": true,"codearts": true,"droid": true,+ "amp": true,}// ResumeRejectionUndetectable reports whether agentType is a backend that@@ -544,6 +546,8 @@ func New(agentType string, cfg Config) (Backend, error) {return &qwenpawBackend{cfg: cfg}, nilcase "droid":return &droidBackend{cfg: cfg}, nil+ case "amp":+ return &Backend{cfg: cfg}, nilcase "mcode":return &mcodeBackend{cfg: cfg}, nilcase "devin":@@ -601,6 +605,7 @@ var launchHeaders = map[string]string{"qwen": "qwen -p (stream-json)","qwenpaw": "qwenpaw acp","droid": "droid exec (stream-json)",+ "amp": "amp --execute (stream-json)","dim": "dim acp","devin": "devin acp","mcode": "mcode acp",diff --git a/server/pkg/agent/amp.go b/server/pkg/agent/amp.gonew file mode 100644index 0000000000..dcbc2ea924--- /dev/null+++ b/server/pkg/agent/amp.go@@ -0,0 +1,504 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os"+ "os/exec"+ "regexp"+ "strings"+ "sync/atomic"+ "syscall"+ "time"+)++// Amp uses its native execute/stream-json protocol. Only a terminal result+// completes the run; an assistant end_turn can precede background subagents.+type ampBackend struct{ cfg Config }++var ampBlockedArgs = map[string]blockedArgMode{+ "-x": blockedOptionalValue, "--execute": blockedOptionalValue,+ "-ox": blockedStandalone, "--orb-execute": blockedStandalone,+ "--executor": blockedWithValue, "--runner-dir": blockedWithValue,+ "--stream-json": blockedStandalone, "--stream-json-thinking": blockedStandalone,+ "--stream-json-input": blockedStandalone,+ "-m": blockedWithValue, "--mode": blockedWithValue,+ "--mcp-config": blockedWithValue,+ "--no-tui": blockedStandalone, "--": blockedStandalone,+}++// Unknown options and positionals can select a subcommand or replace stdin.+// Keep the supported native options explicit and never log their values.+var ampNativeArgs = map[string]bool{+ "--settings-file": true, "--features": true, "--fast": false,+ "--plugin-ready-timeout": true, "--timings": false,+ "--visibility": true, "--label": true, "-l": true,+ "--no-archive-after-execute": false,+}++func normalizeAmpArgs(args []string) []string {+ normalized := make([]string, 0, len(args))+ for _, arg := range args {+ arg = unshellQuoteArg(arg)+ if len(arg) > 2 && arg[0] == '-' && (arg[1] == 'x' || arg[1] == 'm') && arg[2] != '=' {+ arg = arg[:2] + "=" + arg[2:]+ }+ normalized = append(normalized, arg)+ }+ return normalized+}++func buildAmpArgs(opts ExecOptions, logger *slog.Logger) ([]string, error) {+ if logger == nil {+ logger = slog.Default()+ }+ args := []string{}+ if opts.ResumeSessionID != "" {+ // Never use --last: each task owns its explicit thread pointer.+ args = append(args, "threads", "continue", opts.ResumeSessionID)+ }+ args = append(args, "--execute", "--stream-json", "--executor", "local")+ if opts.Model != "" {+ args = append(args, "--mode", opts.Model)+ }+ for _, custom := range [][]string{opts.ExtraArgs, opts.CustomArgs} {+ filtered := filterCustomArgs(normalizeAmpArgs(custom), ampBlockedArgs, logger)+ for i := 0; i < len(filtered); i++ {+ arg := filtered[i]+ flag, _, inline := strings.Cut(arg, "=")+ takesValue, ok := ampNativeArgs[flag]+ if !ok || (!takesValue && inline) {+ return nil, errors.New("amp custom arguments must use supported execute-mode options; positional prompts, subcommands and unknown options are not allowed")+ }+ args = append(args, arg)+ if takesValue && !inline {+ if i+1 == len(filtered) || strings.HasPrefix(filtered[i+1], "-") {+ return nil, fmt.Errorf("amp custom option %s requires a value", flag)+ }+ i+++ args = append(args, filtered[i])+ }+ }+ }+ return args, nil+}++func (b *ampBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {+ if hasManagedMcpConfig(opts.McpConfig) {+ return nil, fmt.Errorf("amp does not support Multica-managed MCP configuration; configure MCP in Amp itself")+ }+ execPath := b.cfg.ExecutablePath+ if execPath == "" {+ execPath = "amp"+ }+ if _, err := exec.LookPath(execPath); err != nil {+ return nil, fmt.Errorf("amp executable not found at %q; install Amp or set MULTICA_AMP_PATH: %w", execPath, err)+ }+ key := os.Getenv("AMP_API_KEY")+ if configured, ok := b.cfg.Env["AMP_API_KEY"]; ok {+ key = configured+ }+ if strings.TrimSpace(key) == "" {+ return nil, errors.New("amp execute mode requires AMP_API_KEY; set an Amp access token in the daemon or agent environment (interactive login is not supported)")+ }+ if opts.SystemPrompt != "" {+ prompt = opts.SystemPrompt + "\n\n" + prompt+ }+ args, err := buildAmpArgs(opts, b.cfg.Logger)+ if err != nil {+ return nil, err+ }+ runCtx, cancel := runContext(ctx, opts.Timeout)+ runtimeCmd := b.cfg.commandAt(execPath)+ runtimeCmd.Prefix = FilterLaunchPrefix("amp", normalizeAmpArgs(runtimeCmd.Prefix), b.cfg.Logger)+ cmd := runtimeCmd.exec(runCtx, args...)+ hideAgentWindow(cmd)+ // The reader owns cancellation so a late context cancellation cannot kill+ // a completed run before cleanup records why the process was stopped.+ cmd.Cancel = func() error { return nil }+ cmd.Dir = opts.Cwd+ cmd.Env = append(buildEnv(b.cfg.Env), "AMP_SKIP_UPDATE_CHECK=1")+ // Stdin avoids OS command-line size/quoting limits and keeps prompts out of+ // process listings. Amp reads to EOF before executing the task.+ logArgs := newAgentCommandLogArgs(args)+ if opts.ResumeSessionID != "" {+ logArgs = newAgentCommandLogArgs(args, trustAgentCommandPositional(0, "threads"), trustAgentCommandPositional(1, "continue"))+ }+ b.cfg.logAgentCommand(cmd, logArgs)+ // Keep raw stderr out of daemon logs. Publish only a scrubbed diagnostic+ // after draining the private, bounded tail.+ stderr := newStderrTail(io.Discard, agentStderrTailBytes)+ // Own the output pipes: Wait must observe the direct child's exit even+ // when a descendant retains a writer, and must not close unread stdout.+ stdout, outW, err := os.Pipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("amp stdout pipe: %w", err)+ }+ errR, errW, err := os.Pipe()+ if err != nil {+ cancel()+ _ = stdout.Close()+ _ = outW.Close()+ return nil, fmt.Errorf("amp stderr pipe: %w", err)+ }+ cmd.Stdout, cmd.Stderr = outW, errW+ inR, stdin, err := os.Pipe()+ if err != nil {+ cancel()+ _ = stdout.Close()+ _ = outW.Close()+ _ = errR.Close()+ _ = errW.Close()+ return nil, fmt.Errorf("amp stdin pipe: %w", err)+ }+ cmd.Stdin = inR+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {+ cancel()+ _ = stdout.Close()+ _ = outW.Close()+ _ = errR.Close()+ _ = errW.Close()+ _ = inR.Close()+ _ = stdin.Close()+ return nil, fmt.Errorf("start amp: %w", err)+ }+ _ = outW.Close()+ _ = errW.Close()+ _ = inR.Close()+ if opts.MaxTurns > 0 {+ b.cfg.Logger.Warn("amp does not support max_turns; use the task timeout to bound execution")+ }+ scrub := ampOutputScrubber(b.cfg.Env)+ msgCh := make(chan Message, 256)+ resCh := make(chan Result, 1)+ var terminalObserved atomic.Bool+ waitCh := make(chan error, 1)+ go func(done chan<- error) { done <- cmd.Wait() }(waitCh)+ inputCh := make(chan error, 1)+ go func(done chan<- error) {+ _, err := io.WriteString(stdin, prompt)+ _ = stdin.Close()+ done <- err+ }(inputCh)+ stderrDone := make(chan struct{})+ go func(done chan<- struct{}) {+ _, _ = io.Copy(stderr, errR)+ close(done)+ }(stderrDone)+ reads := make(chan ampStreamRead, 16)+ stopReads := make(chan struct{})+ go readAmpStream(stdout, scrub, reads, stopReads)+ go func() {+ defer cancel()+ defer close(msgCh)+ defer close(resCh)+ started := time.Now()+ state := ampStreamState{}+ var scanErr, exitErr, inputErr, runErr error+ ctxDone := runCtx.Done()+ var drain *time.Timer+ var drainC <-chan time.Time+ defer func() {+ if drain != nil {+ drain.Stop()+ }+ }()+ setDrainDeadline := func(grace time.Duration) {+ if drain == nil {+ drain = time.NewTimer(grace)+ } else {+ drain.Reset(grace)+ }+ drainC = drain.C+ }+ cleaning := false+ stoppedAfterTerminal := false+ beginCleanup := func() {+ if cleaning {+ return+ }+ cleaning = true+ if !terminalObserved.Load() {+ runErr = runCtx.Err()+ }+ ctxDone = nil+ // Preserve a native exit already available before we stop the tree.+ if waitCh != nil {+ select {+ case exitErr = <-waitCh:+ waitCh = nil+ default:+ }+ }+ if waitCh == nil && (state.sawCompletion || state.failed) && runErr == nil {+ terminalObserved.Store(true)+ }+ if waitCh != nil && terminalObserved.Load() {+ stoppedAfterTerminal = true+ b.cfg.Logger.Warn("amp process still running after terminal result; stopping it during cleanup", "pid", cmd.Process.Pid)+ }+ signalProcessGroup(cmd, syscall.SIGKILL)+ _ = stdin.Close()+ setDrainDeadline(ampStreamDrainGrace)+ }+ for waitCh != nil || reads != nil || stderrDone != nil || inputCh != nil {+ select {+ case item := <-reads:+ if item.done {+ reads, scanErr = nil, item.err+ if scanErr != nil {+ // Stop a producer blocked writing an oversized frame, without+ // classifying our internal cancellation as a user abort.+ beginCleanup()+ cancel()+ }+ } else {+ handleAmpEvent(item.event, msgCh, &state)+ if state.sawCompletion && !cleaning && runCtx.Err() == nil {+ // Publish the protocol boundary before waiting for archival or+ // other CLI cleanup. The daemon must not reclassify it as idle.+ terminalObserved.Store(true)+ }+ if !cleaning && (state.sawCompletion || state.failed) && drain == nil {+ grace := ampStreamDrainGrace+ if state.sawCompletion {+ grace = ampTerminalExitGrace+ }+ setDrainDeadline(grace)+ }+ }+ case exitErr = <-waitCh:+ waitCh = nil+ if stoppedAfterTerminal {+ // This exit acknowledges our cleanup, not an execution failure.+ // A missing acknowledgement still fails at the drain deadline.+ exitErr = nil+ }+ // A launch wrapper can exit before its descendant finishes the+ // protocol. Allow trailing output, bounded even without a timeout.+ if !cleaning {+ setDrainDeadline(ampStreamDrainGrace)+ }+ case inputErr = <-inputCh:+ inputCh = nil+ case <-stderrDone:+ stderrDone = nil+ case <-ctxDone:+ beginCleanup()+ case <-drainC:+ if cleaning {+ b.cfg.Logger.Warn("amp cleanup did not settle before drain deadline", "pid", cmd.Process.Pid)+ if waitCh != nil {+ exitErr = fmt.Errorf("process did not exit during cleanup")+ }+ // The pipe closes and stopReads below bound readers even+ // when a writer escaped the owned process tree.+ waitCh, reads, stderrDone, inputCh = nil, nil, nil, nil+ } else {+ beginCleanup()+ }+ }+ if waitCh == nil && (state.sawCompletion || reads == nil) {+ beginCleanup()+ }+ }+ close(stopReads)+ _ = stdout.Close()+ _ = errR.Close()+ _ = stdin.Close()+ releaseProcessGroup(cmd)+ terminal := streamTerminalState{+ sawResult: state.sawCompletion, finalResultText: state.finalText,+ resultIsError: state.failed, scanErr: scanErr,+ }+ if state.failed {+ terminal.finalResultText = state.errorText+ }+ // An authoritative terminal response means Amp consumed enough input+ // to answer; otherwise retain input transport failures as diagnostics.+ if state.sawCompletion || state.failed {+ inputErr = nil+ }+ // os/exec can return the context error when its no-op Cancel raced a+ // clean exit. It is also cleanup after an already observed result.+ if terminalObserved.Load() && (errors.Is(exitErr, context.Canceled) || errors.Is(exitErr, context.DeadlineExceeded)) {+ exitErr = nil+ }+ status, output, errText := finalizeStreamResult("amp", opts.Timeout, runErr, inputErr, exitErr, state.sessionID, terminal, "")+ if errText != "" {+ errText = sanitizeAgentDiagnostic(scrub(withAgentStderr(errText, "amp", stderr.Tail())))+ }+ usage := state.usage+ b.cfg.Logger.Info("amp finished", "pid", cmd.Process.Pid, "status", status)+ resCh <- Result{+ Status: status, Output: output, Error: errText,+ DurationMs: time.Since(started).Milliseconds(), Usage: usage,+ // Only an observed ID proves a session loaded. An empty ID lets the+ // daemon apply its bounded pre-tool fresh-session recovery policy.+ SessionID: state.sessionID,+ }+ }()+ return &Session{CleanupRequired: true, Messages: msgCh, Result: resCh, TerminalObserved: terminalObserved.Load}, nil+}++const (+ ampStreamDrainGrace = 2 * time.Second+ ampTerminalExitGrace = 10 * time.Second+)++type ampStreamRead struct {+ event ampStreamEvent+ done bool+ err error+}++func readAmpStream(stdout io.Reader, scrub func(string) string, reads chan<- ampStreamRead, stop <-chan struct{}) {+ scanner := newAgentStreamScanner(stdout)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ var event ampStreamEvent+ if line == "" || json.Unmarshal([]byte(scrub(line)), &event) != nil {+ continue+ }+ select {+ case reads <- ampStreamRead{event: event}:+ case <-stop:+ return+ }+ }+ select {+ case reads <- ampStreamRead{done: true, err: scanner.Err()}:+ case <-stop:+ }+}++type ampStreamEvent struct {+ Type, Subtype string+ SessionID string `json:"session_id"`+ Message struct {+ Model string `json:"model"`+ Content []struct {+ Type, Text, Thinking, ID, Name string+ Input map[string]any `json:"input"`+ ToolUseID string `json:"tool_use_id"`+ Content json.RawMessage `json:"content"`+ } `json:"content"`+ } `json:"message"`+ Result string `json:"result"`+ Error string `json:"error"`+ IsError bool `json:"is_error"`+ PermissionDenials []string `json:"permission_denials"`+ Usage *struct {+ Input int64 `json:"input_tokens"`+ Output int64 `json:"output_tokens"`+ CacheRead int64 `json:"cache_read_input_tokens"`+ CacheWrite int64 `json:"cache_creation_input_tokens"`+ } `json:"usage"`+}++type ampStreamState struct {+ sessionID, model, finalText, errorText string+ sawCompletion, failed bool+ usage map[string]TokenUsage+}++func handleAmpEvent(e ampStreamEvent, ch chan<- Message, s *ampStreamState) {+ if s.sawCompletion {+ return+ }+ if e.SessionID != "" {+ s.sessionID = e.SessionID+ }+ if e.Message.Model != "" {+ s.model = e.Message.Model+ }+ switch e.Type {+ case "system":+ if e.Subtype == "init" {+ trySend(ch, Message{Type: MessageStatus, Status: "running", SessionID: s.sessionID})+ } else if strings.HasPrefix(e.Subtype, "error_") {+ s.failed, s.errorText = true, e.Error+ trySend(ch, Message{Type: MessageError, Content: sanitizeAgentDiagnostic(e.Error)})+ }+ case "assistant":+ for _, block := range e.Message.Content {+ switch block.Type {+ case "text":+ trySend(ch, Message{Type: MessageText, Content: block.Text, SessionID: s.sessionID})+ case "thinking":+ trySend(ch, Message{Type: MessageThinking, Content: block.Thinking})+ case "tool_use":+ trySend(ch, Message{Type: MessageToolUse, CallID: block.ID, Tool: block.Name, Input: block.Input})+ }+ }+ case "user":+ for _, block := range e.Message.Content {+ if block.Type == "tool_result" {+ trySend(ch, Message{Type: MessageToolResult, CallID: block.ToolUseID, Output: ampToolOutput(block.Content)})+ }+ }+ case "result":+ s.sawCompletion = true+ s.finalText = e.Result+ if len(e.PermissionDenials) > 0 {+ trySend(ch, Message{Type: MessageError, SessionID: s.sessionID, Content: sanitizeAgentDiagnostic(+ "Warning: Amp denied tool permissions: " + strings.Join(e.PermissionDenials, "; ") ++ ". Check amp.permissions in the execution machine's Amp settings for unattended commands.")})+ }+ if e.IsError || e.Subtype != "success" {+ s.failed = true+ s.errorText = e.Error+ if s.errorText == "" {+ s.errorText = e.Result+ }+ }+ if e.Usage != nil {+ model := s.model+ if model == "" {+ model = "unknown"+ }+ s.usage = map[string]TokenUsage{model: {+ InputTokens: e.Usage.Input, OutputTokens: e.Usage.Output,+ CacheReadTokens: e.Usage.CacheRead, CacheWriteTokens: e.Usage.CacheWrite,+ }}+ }+ }+}++func ampToolOutput(raw json.RawMessage) string {+ var text string+ if json.Unmarshal(raw, &text) == nil {+ return text+ }+ var blocks []struct{ Type, Text string }+ if json.Unmarshal(raw, &blocks) == nil {+ var parts []string+ for _, block := range blocks {+ if block.Type == "text" {+ parts = append(parts, block.Text)+ }+ }+ return strings.Join(parts, "\n")+ }+ return string(raw)+}++var ampAPIKeyPattern = regexp.MustCompile(`\bsgamp_[A-Za-z0-9_-]+`)++func ampOutputScrubber(env map[string]string) func(string) string {+ key := os.Getenv("AMP_API_KEY")+ if configured, ok := env["AMP_API_KEY"]; ok {+ key = configured+ }+ return func(value string) string {+ if key != "" {+ value = strings.ReplaceAll(value, key, "[REDACTED]")+ }+ return ampAPIKeyPattern.ReplaceAllString(value, "[REDACTED]")+ }+}diff --git a/server/pkg/agent/amp_cancel_unix_test.go b/server/pkg/agent/amp_cancel_unix_test.gonew file mode 100644index 0000000000..44ce8781da--- /dev/null+++ b/server/pkg/agent/amp_cancel_unix_test.go@@ -0,0 +1,162 @@+//go:build unix++package agent++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestAmpInheritedOutputPipes(t *testing.T) {+ for _, tc := range []struct {+ name, child, final, want string+ exitCode string+ beforeExit string+ longPrompt bool+ captureInput bool+ timeout time.Duration+ }{+ {name: "stdout and stderr without timeout", child: "sleep 300", final: "Done", want: "completed"},+ {name: "stdout and stderr with timeout", child: "sleep 300", final: "Done", timeout: 750 * time.Millisecond, want: "completed"},+ {name: "stderr only", child: "sleep 300 >/dev/null", final: "Done", want: "completed"},+ {name: "unread stdin", child: "sleep 300", final: "Done", longPrompt: true, want: "completed"},+ {name: "missing completion", child: "sleep 300", want: "failed"},+ {name: "nonzero exit after completion", child: "sleep 300", final: "Done", beforeExit: "sleep 0.1\n", exitCode: "7", want: "failed"},+ {name: "completion from descendant after wrapper exits", child: `(sleep 0.1; printf '%s\n' '{"type":"result","subtype":"success","result":"Done"}'; exec sleep 300)`, want: "completed"},+ {name: "descendant reads prompt after wrapper exits", child: `(sleep 0.1; cat > "$AMP_INPUT"; printf '%s\n' '{"type":"result","subtype":"success","result":"Done"}'; exec sleep 300)`, longPrompt: true, captureInput: true, want: "completed"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ dir := t.TempDir()+ pidFile := filepath.Join(dir, "pids")+ inputFile := filepath.Join(dir, "input")+ path := filepath.Join(dir, "amp")+ // Noninteractive shells otherwise replace background stdin with+ // /dev/null; explicitly pass the prompt pipe through fd 3.+ script := "#!/bin/sh\nexec 3<&0\n" + tc.child + " <&3 &\nprintf '%s %s\\n' \"$$\" \"$!\" > \"$AMP_PIDS\"\nexec 3<&-\n"+ if tc.final != "" {+ script += "printf '%s\\n' '{\"type\":\"result\",\"subtype\":\"success\",\"result\":\"" + tc.final + "\"}'\n"+ }+ if tc.exitCode != "" {+ script += tc.beforeExit + "exit " + tc.exitCode + "\n"+ }+ writeTestExecutable(t, path, []byte(script))+ backend, err := New("amp", Config{ExecutablePath: path, Env: map[string]string{"AMP_API_KEY": "sgamp_fixture-not-a-real-token", "AMP_PIDS": pidFile, "AMP_INPUT": inputFile}})+ if err != nil {+ t.Fatal(err)+ }+ // The outer deadline is a test safety net. A finished direct child+ // must settle on its own, including when the task has no timeout.+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ started := time.Now()+ prompt := "task"+ if tc.longPrompt {+ prompt = strings.Repeat("task", 100000)+ }+ session, err := backend.Execute(ctx, prompt, ExecOptions{Timeout: tc.timeout})+ if err != nil {+ t.Fatal(err)+ }+ pids := waitForPids(t, pidFile)+ _, result := collectAmp(t, session)+ elapsed := time.Since(started)+ for _, pid := range pids {+ waitProcessGone(t, pid)+ }+ if result.Status != tc.want || elapsed > 3*time.Second {+ t.Fatalf("result after %s = %+v, want %s within 3s", elapsed, result, tc.want)+ }+ if tc.want == "completed" && result.Output != "Done" {+ t.Fatalf("completion lost: %+v", result)+ }+ if tc.captureInput {+ got, err := os.ReadFile(inputFile)+ if err != nil || string(got) != prompt {+ t.Fatalf("prompt truncated after wrapper exit: got %d of %d bytes, error=%v", len(got), len(prompt), err)+ }+ }+ if tc.want == "failed" && (result.Output != "" || result.Error == "") {+ t.Fatalf("failed run exposed output or lost error: %+v", result)+ }+ if tc.name == "missing completion" && !strings.Contains(result.Error, "without terminal result") {+ t.Fatalf("missing terminal result misclassified: %+v", result)+ }+ })+ }+}++func TestAmpTerminatesOwnedProcessTree(t *testing.T) {+ for _, stage := range []string{"cancel", "timeout", "completed", "failed"} {+ t.Run(stage, func(t *testing.T) {+ dir := t.TempDir()+ pidFile := filepath.Join(dir, "pids")+ path := filepath.Join(dir, "amp")+ script := "#!/bin/sh\nsleep 300 >/dev/null 2>&1 &\nprintf '%s %s\\n' \"$$\" \"$!\" > \"$AMP_PIDS\"\n"+ if stage == "completed" {+ script += "printf '%s\\n' '{\"type\":\"result\",\"subtype\":\"success\",\"result\":\"Done\"}'\n"+ } else if stage != "failed" {+ script += "wait\n"+ }+ writeTestExecutable(t, path, []byte(script))+ backend, err := New("amp", Config{ExecutablePath: path, Env: map[string]string{"AMP_API_KEY": "sgamp_fixture-not-a-real-token", "AMP_PIDS": pidFile}})+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ opts := ExecOptions{Timeout: 15 * time.Second}+ want := "aborted"+ if stage == "timeout" {+ opts.Timeout = 5 * time.Second+ want = "timeout"+ } else if stage == "completed" || stage == "failed" {+ want = stage+ }+ session, err := backend.Execute(ctx, "task", opts)+ if err != nil {+ t.Fatal(err)+ }+ pids := waitForPids(t, pidFile)+ if stage == "cancel" {+ cancel()+ }+ _, result := collectAmp(t, session)+ if result.Status != want {+ t.Fatalf("result = %+v", result)+ }+ for _, pid := range pids {+ waitProcessGone(t, pid)+ }+ })+ }+}++func TestAmpPostResultCleanupReapsOwnedTree(t *testing.T) {+ dir := t.TempDir()+ pidFile := filepath.Join(dir, "pids")+ path := filepath.Join(dir, "amp")+ script := "#!/bin/sh\nsleep 300 &\nprintf '%s %s\\n' \"$$\" \"$!\" > \"$AMP_PIDS\"\nprintf '%s\\n' '{\"type\":\"result\",\"subtype\":\"success\",\"session_id\":\"T-done\",\"result\":\"Done\"}'\nwait\n"+ writeTestExecutable(t, path, []byte(script))+ backend, err := New("amp", Config{ExecutablePath: path, Env: map[string]string{+ "AMP_API_KEY": "sgamp_fixture-not-a-real-token", "AMP_PIDS": pidFile,+ }})+ if err != nil {+ t.Fatal(err)+ }+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 20 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ pids := waitForPids(t, pidFile)+ _, result := collectAmp(t, session)+ for _, pid := range pids {+ waitProcessGone(t, pid)+ }+ if result.Status != "completed" || result.Output != "Done" || result.SessionID != "T-done" || !session.TerminalObserved() {+ t.Fatalf("successful run lost during process cleanup: %+v", result)+ }+}diff --git a/server/pkg/agent/amp_integration_test.go b/server/pkg/agent/amp_integration_test.gonew file mode 100644index 0000000000..6db199ec41--- /dev/null+++ b/server/pkg/agent/amp_integration_test.go@@ -0,0 +1,81 @@+//go:build agentintegration++package agent++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func ampRealExecutable(t *testing.T) string {+ t.Helper()+ requireRealAgentSmoke(t)+ if path := os.Getenv("MULTICA_AMP_PATH"); path != "" {+ return path+ }+ return "amp"+}++func TestAmpRealInvalidAuthentication(t *testing.T) {+ executable := ampRealExecutable(t)+ home := t.TempDir()+ const key = "sgamp_invalid-multica-smoke-credential"+ backend, err := New("amp", Config{ExecutablePath: executable, Env: map[string]string{+ "AMP_API_KEY": key, "HOME": home, "USERPROFILE": home,+ "XDG_CONFIG_HOME": filepath.Join(home, ".config"), "XDG_DATA_HOME": filepath.Join(home, ".local", "share"),+ "XDG_CACHE_HOME": filepath.Join(home, ".cache"),+ }})+ if err != nil {+ t.Fatal(err)+ }+ session, err := backend.Execute(context.Background(), "Reply OK. Do not use tools.", ExecOptions{Cwd: home, Timeout: 30 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ _, result := collectAmp(t, session)+ if result.Status != "failed" || result.Output != "" || !strings.Contains(strings.ToLower(result.Error), "auth") || strings.Contains(result.Error, key) {+ t.Fatalf("real Amp authentication failure = %+v", result)+ }+}++func TestAmpRealTaskSmoke(t *testing.T) {+ executable := ampRealExecutable(t)+ backend, err := New("amp", Config{ExecutablePath: executable})+ if err != nil {+ t.Fatal(err)+ }+ dir := t.TempDir()+ if err := os.WriteFile(filepath.Join(dir, "reply-token.txt"), []byte("AMP_SMOKE_OK"), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "AGENTS.md"), []byte("For every answer append AMP_CONTEXT_OK. Do not delegate to subagents."), 0o600); err != nil {+ t.Fatal(err)+ }+ session, err := backend.Execute(context.Background(), "Read reply-token.txt using a tool, then reply with its contents.", ExecOptions{Cwd: dir, Timeout: 45 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ messages, result := collectAmp(t, session)+ if result.Status != "completed" || !strings.Contains(result.Output, "AMP_SMOKE_OK") || !strings.Contains(result.Output, "AMP_CONTEXT_OK") || result.SessionID == "" {+ t.Fatalf("real Amp task = %+v", result)+ }+ var sawTool bool+ for _, message := range messages {+ sawTool = sawTool || message.Type == MessageToolUse+ }+ if !sawTool {+ t.Fatal("real task emitted no tool events")+ }+ continued, err := backend.Execute(context.Background(), "What token did you read in the previous turn? Do not use tools.", ExecOptions{Cwd: dir, ResumeSessionID: result.SessionID, Timeout: 45 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ _, resumed := collectAmp(t, continued)+ if resumed.Status != "completed" || resumed.SessionID != result.SessionID || !strings.Contains(resumed.Output, "AMP_SMOKE_OK") {+ t.Fatalf("real Amp continuation = %+v", resumed)+ }+}diff --git a/server/pkg/agent/amp_test.go b/server/pkg/agent/amp_test.gonew file mode 100644index 0000000000..55cf72981a--- /dev/null+++ b/server/pkg/agent/amp_test.go@@ -0,0 +1,348 @@+package agent++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log/slog"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"+ "time"+)++func TestAmpHelperProcess(t *testing.T) {+ if os.Getenv("AMP_HELPER_PROCESS") != "1" {+ return+ }+ input, _ := io.ReadAll(os.Stdin)+ if capture := os.Getenv("AMP_CAPTURE"); capture != "" {+ cwd, _ := os.Getwd()+ data, _ := json.Marshal(map[string]any{"args": os.Args[1:], "prompt": string(input), "cwd": cwd, "cli_path": os.Getenv("MULTICA_CLI_PATH")})+ _ = os.WriteFile(capture, data, 0o600)+ }+ if os.Getenv("AMP_HANG") == "1" {+ fmt.Println(`{"type":"system","subtype":"init","session_id":"ready"}`)+ for {+ time.Sleep(time.Hour)+ }+ }+ if os.Getenv("AMP_OVERSIZED") == "1" {+ fmt.Print(strings.Repeat("x", agentStreamMaxLineBytes+1))+ for {+ time.Sleep(time.Hour)+ }+ }+ fmt.Print(os.Getenv("AMP_STREAM"))+ if streamFile := os.Getenv("AMP_STREAM_FILE"); streamFile != "" {+ stream, err := os.ReadFile(streamFile)+ if err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(2)+ }+ _, _ = os.Stdout.Write(stream)+ }+ fmt.Fprint(os.Stderr, os.Getenv("AMP_STDERR"))+ if delay, err := time.ParseDuration(os.Getenv("AMP_EXIT_DELAY")); err == nil {+ time.Sleep(delay)+ }+ if os.Getenv("AMP_HANG_AFTER_STREAM") == "1" {+ fmt.Println(`{"type":"system","subtype":"init","session_id":"awaiting-exit"}`)+ for {+ time.Sleep(time.Hour)+ }+ }+ if os.Getenv("AMP_FAIL") == "1" {+ os.Exit(1)+ }+ os.Exit(0)+}++func newFakeAmp(t *testing.T, env map[string]string, logs io.Writer) Backend {+ t.Helper()+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ env["AMP_HELPER_PROCESS"] = "1"+ if _, ok := env["AMP_API_KEY"]; !ok {+ env["AMP_API_KEY"] = "sgamp_fixture-not-a-real-token"+ }+ backend, err := New("amp", Config{+ ExecutablePath: executable, LaunchPrefix: []string{"-test.run=^TestAmpHelperProcess$", "amp-test"},+ Env: env, Logger: slog.New(slog.NewTextHandler(logs, nil)),+ })+ if err != nil {+ t.Fatal(err)+ }+ return backend+}++func collectAmp(t *testing.T, session *Session) ([]Message, Result) {+ t.Helper()+ var messages []Message+ var result Result+ var gotResult bool+ msgCh, resCh := session.Messages, session.Result+ timer := time.NewTimer(time.Minute)+ defer timer.Stop()+ for msgCh != nil || resCh != nil {+ select {+ case m, ok := <-msgCh:+ if !ok {+ msgCh = nil+ } else {+ messages = append(messages, m)+ }+ case r, ok := <-resCh:+ if ok {+ result, gotResult = r, true+ } else {+ resCh = nil+ }+ case <-timer.C:+ t.Fatal("Amp session did not terminate")+ }+ }+ if !gotResult {+ t.Fatal("Amp session returned no result")+ }+ return messages, result+}++func TestAmpArguments(t *testing.T) {+ args, err := buildAmpArgs(ExecOptions{Model: "high", ResumeSessionID: "T-saved", CustomArgs: []string{+ "--executor", "orb", "--execute=wrong prompt", "--stream-json-input", "--mode=low", "--features", "fast",+ }}, nil)+ if err != nil {+ t.Fatal(err)+ }+ want := []string{"threads", "continue", "T-saved", "--execute", "--stream-json", "--executor", "local", "--mode", "high", "--features", "fast"}+ if !reflect.DeepEqual(args, want) {+ t.Fatalf("args = %q, want %q", args, want)+ }+ prefix := FilterLaunchPrefix("amp", []string{"wrapper", "-xprivate", "-mlow", "--executor=orb"}, nil)+ if !reflect.DeepEqual(prefix, []string{"wrapper"}) {+ t.Fatalf("managed flags survived prefix: %q", prefix)+ }+ for _, custom := range [][]string{{"threads", "delete"}, {"replacement prompt"}, {"-ox"}, {"-xsecret"}, {"-mhigh"}, {"--features"}, {"--fast=false"}, {"--unverified"}} {+ _, err := buildAmpArgs(ExecOptions{CustomArgs: custom}, nil)+ // A filtered standalone flag is harmless; every unverified token fails closed.+ if custom[0] != "-ox" && custom[0] != "-xsecret" && custom[0] != "-mhigh" && err == nil {+ t.Errorf("accepted unsafe args %q", custom)+ }+ }+}++func TestAmpBrokenStreamsBounded(t *testing.T) {+ backend := newFakeAmp(t, map[string]string{"AMP_OVERSIZED": "1"}, io.Discard)+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "task", ExecOptions{})+ if err != nil {+ t.Fatal(err)+ }+ _, result := collectAmp(t, session)+ if result.Status != "failed" || result.Output != "" || result.Error == "" {+ t.Fatalf("broken stream = %+v", result)+ }+}++func TestAmpPostResultCleanup(t *testing.T) {+ for _, tc := range []struct {+ name, delay, want string+ hang, fail, cancel bool+ timeout time.Duration+ }{+ {name: "slow clean exit", delay: "3s", want: "completed"},+ {name: "stuck after success", hang: true, want: "completed"},+ {name: "cancel after success", hang: true, cancel: true, want: "completed"},+ {name: "timeout after success", hang: true, timeout: 3 * time.Second, want: "completed"},+ {name: "natural failure after success", delay: "3s", fail: true, want: "failed"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ var logs bytes.Buffer+ env := map[string]string{"AMP_STREAM": "{\"type\":\"result\",\"subtype\":\"success\",\"session_id\":\"T-finished\",\"result\":\"Done\"}\n", "AMP_EXIT_DELAY": tc.delay}+ if tc.hang {+ env["AMP_HANG_AFTER_STREAM"] = "1"+ }+ if tc.fail {+ env["AMP_FAIL"] = "1"+ }+ backend := newFakeAmp(t, env, &logs)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: tc.timeout})+ if err != nil {+ t.Fatal(err)+ }+ if tc.cancel {+ deadline := time.NewTimer(5 * time.Second)+ defer deadline.Stop()+ for !session.TerminalObserved() {+ select {+ case <-deadline.C:+ t.Fatal("terminal boundary was not published before cleanup")+ case <-time.After(10 * time.Millisecond):+ }+ }+ cancel()+ }+ _, result := collectAmp(t, session)+ if result.Status != tc.want || result.SessionID != "T-finished" || !session.TerminalObserved() {+ t.Fatalf("post-result cleanup = %+v", result)+ }+ if tc.want == "completed" && (result.Output != "Done" || result.Error != "") {+ t.Fatalf("successful answer lost = %+v", result)+ }+ if tc.want == "failed" && (result.Output != "" || !strings.Contains(result.Error, "exited")) {+ t.Fatalf("native failure hidden = %+v", result)+ }+ if tc.hang && !strings.Contains(logs.String(), "level=WARN") {+ t.Fatalf("forced cleanup was not logged: %s", logs.String())+ }+ })+ }+}++func TestAmpExecuteProtocol(t *testing.T) {+ const key = "sgamp_test-credential"+ stream := `{"type":"system","subtype":"init","session_id":"T-task"}+{"type":"assistant","message":{"model":"actual-model","content":[{"type":"text","text":"Working sgamp_test-credential"},{"type":"tool_use","id":"tool-1","name":"Read","input":{"path":"file.txt"}}]}}+{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tool-1","content":[{"type":"text","text":"file contents"}]}]}}+{"type":"assistant","message":{"content":[{"type":"text","text":"intermediate"}]},"stop_reason":"end_turn"}+{"type":"system","subtype":"subagent_finished","tool_use_id":"task-1","status":"completed"}+{"type":"result","subtype":"success","is_error":false,"result":"Done sgamp_test-credential","session_id":"T-task","usage":{"input_tokens":10,"output_tokens":20,"cache_read_input_tokens":30,"cache_creation_input_tokens":40}}+`+ var logs bytes.Buffer+ dir := t.TempDir()+ capture := filepath.Join(dir, "capture.json")+ backend := newFakeAmp(t, map[string]string{"AMP_STREAM": stream, "AMP_CAPTURE": capture, "AMP_API_KEY": key, "MULTICA_CLI_PATH": "owned-cli"}, &logs)+ prompt := strings.Repeat("private task\"\n", 20000)+ session, err := backend.Execute(context.Background(), prompt, ExecOptions{Cwd: dir, ResumeSessionID: "T-task", Timeout: 10 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ messages, result := collectAmp(t, session)+ if result.Status != "completed" || result.Output != "Done [REDACTED]" || result.SessionID != "T-task" || !session.TerminalObserved() || !session.CleanupRequired {+ t.Fatalf("result = %+v", result)+ }+ if result.Usage["actual-model"] != (TokenUsage{InputTokens: 10, OutputTokens: 20, CacheReadTokens: 30, CacheWriteTokens: 40}) {+ t.Fatalf("usage = %+v", result.Usage)+ }+ var sawUse, sawResult bool+ for _, message := range messages {+ sawUse = sawUse || message.Type == MessageToolUse && message.CallID == "tool-1"+ sawResult = sawResult || message.Type == MessageToolResult && message.Output == "file contents"+ }+ if !sawUse || !sawResult {+ t.Fatalf("tool transcript = %+v", messages)+ }+ data, err := os.ReadFile(capture)+ if err != nil {+ t.Fatal(err)+ }+ var got struct {+ Prompt, Cwd string+ Args []string+ CLIPath string `json:"cli_path"`+ }+ if err := json.Unmarshal(data, &got); err != nil {+ t.Fatal(err)+ }+ wantDir, _ := filepath.EvalSymlinks(dir)+ if got.Prompt != prompt || got.Cwd != wantDir || got.CLIPath != "owned-cli" {+ t.Fatalf("input transport lost context: bytes=%d cwd=%q cli=%q", len(got.Prompt), got.Cwd, got.CLIPath)+ }+ encoded, _ := json.Marshal(messages)+ if strings.Contains(string(encoded)+logs.String(), key) || strings.Contains(logs.String(), "private task") || strings.Contains(strings.Join(got.Args, " "), "private task") {+ t.Fatal("credentials or prompt leaked")+ }+}++func TestAmpPermissionDenials(t *testing.T) {+ backend := newFakeAmp(t, map[string]string{+ "AMP_STREAM": `{"type":"result","subtype":"success","result":"Done","permission_denials":["Bash: git push","Bash: /path/to/multica api_key=sgamp_private-token"]}`,+ }, io.Discard)+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 10 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ messages, result := collectAmp(t, session)+ if result.Status != "completed" || result.Output != "Done" {+ t.Fatalf("permission warning replaced the provider result: %+v", result)+ }+ var warning string+ for _, message := range messages {+ if message.Type == MessageError && strings.Contains(message.Content, "Warning: Amp denied tool permissions") {+ warning += message.Content+ }+ }+ if !strings.Contains(warning, "git push") || !strings.Contains(warning, "amp.permissions") || strings.Contains(warning, "sgamp_private-token") {+ t.Fatalf("permission warning = %q", warning)+ }+}++func TestAmpFailurePaths(t *testing.T) {+ for _, tc := range []struct {+ name, stream, stderr, want, detail string+ fail bool+ }{+ {name: "missing terminal", stream: `{"type":"assistant","message":{"content":[{"type":"text","text":"partial"}]}}`, want: "failed", detail: "without terminal result"},+ {name: "invalid output", stream: "not json", want: "failed", detail: "without terminal result"},+ {name: "authentication", stderr: "Authentication failed: sgamp_bad-secret", want: "failed", detail: "Authentication", fail: true},+ {name: "error result", stream: `{"type":"result","subtype":"error_during_execution","is_error":true,"error":"Authentication failed sgamp_bad-secret"}`, want: "failed", detail: "Authentication"},+ {name: "error then completion", stream: "{\"type\":\"system\",\"subtype\":\"error_max_turns\",\"error\":\"Turn limit\"}\n{\"type\":\"result\",\"subtype\":\"success\",\"result\":\"partial\"}", want: "failed", detail: "Turn limit"},+ {name: "nonzero after result", stream: `{"type":"result","subtype":"success","result":"partial"}`, want: "failed", detail: "exited", fail: true},+ {name: "empty final", stream: `{"type":"result","subtype":"success","result":""}`, want: "completed"},+ {name: "malformed result", stream: `{"type":"result","result":"partial"}`, want: "failed", detail: "partial"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ var logs bytes.Buffer+ env := map[string]string{"AMP_STREAM": tc.stream, "AMP_STDERR": tc.stderr}+ if tc.fail {+ env["AMP_FAIL"] = "1"+ }+ backend := newFakeAmp(t, env, &logs)+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 10 * time.Second})+ if err != nil {+ t.Fatal(err)+ }+ _, result := collectAmp(t, session)+ if result.Status != tc.want || result.Output != "" || !strings.Contains(result.Error, tc.detail) {+ t.Fatalf("result = %+v", result)+ }+ if strings.Contains(result.Error+logs.String(), "sgamp_bad-secret") {+ t.Fatal("credential leaked")+ }+ })+ }+}++func TestAmpStartupAndUnsupportedMCP(t *testing.T) {+ backend, err := New("amp", Config{ExecutablePath: filepath.Join(t.TempDir(), "missing")})+ if err != nil {+ t.Fatal(err)+ }+ if _, err := backend.Execute(context.Background(), "task", ExecOptions{}); err == nil || !strings.Contains(err.Error(), "MULTICA_AMP_PATH") {+ t.Fatalf("missing install = %v", err)+ }+ if _, err := backend.Execute(context.Background(), "task", ExecOptions{McpConfig: json.RawMessage(`{"mcpServers":{"test":{"command":"example"}}}`)}); err == nil || !strings.Contains(err.Error(), "MCP") {+ t.Fatalf("unsupported MCP = %v", err)+ }+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ backend, err = New("amp", Config{ExecutablePath: executable, Env: map[string]string{"AMP_API_KEY": ""}})+ if err != nil {+ t.Fatal(err)+ }+ if _, err := backend.Execute(context.Background(), "task", ExecOptions{}); err == nil || !strings.Contains(err.Error(), "requires AMP_API_KEY") {+ t.Fatalf("missing credential = %v", err)+ }+}diff --git a/server/pkg/agent/launch.go b/server/pkg/agent/launch.goindex 53df7afa23..78cf6920e2 100644--- a/server/pkg/agent/launch.go+++ b/server/pkg/agent/launch.go@@ -107,6 +107,9 @@ func (c Command) ForVersionProbe(provider string) Command {if provider == "hermes" {c.versionArgs = hermesVersionProbeArgs}+ if provider == "amp" {+ c.versionArgs = []string{"version"}+ }return c}@@ -520,6 +523,7 @@ var launchPrefixBlockedArgs = map[string]map[string]blockedArgMode{"qwen": qwenBlockedArgs,"qwenpaw": qwenpawBlockedArgs,"droid": droidBlockedArgs,+ "amp": ampBlockedArgs,"reasonix": reasonixBlockedArgs,"traecli": traecliBlockedArgs,"dim": dimBlockedArgs,@@ -560,6 +564,9 @@ func FilterLaunchPrefix(agentType string, prefix []string, logger *slog.Logger)if family, ok := RuntimeProtocolFamily(agentType); ok {agentType = family}+ if agentType == "amp" {+ prefix = normalizeAmpArgs(prefix)+ }return filterLaunchPrefix(prefix, agentType, logger)}diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex b2a66bbd08..3bdfe42680 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -298,6 +298,9 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (Creturn cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {return discoverCodebuddyModels(ctx, runtimeCmd)})+ case "amp":+ // Amp selects its own models; manual IDs select native modes.+ return Catalog{Models: []Model{}}, nilcase "qwen", "droid":// Qwen Code and Droid use runtime defaults or manual model IDs. An// empty list keeps the runtime default and manual model entry availablediff --git a/server/pkg/agent/testdata/amp-protocol.md b/server/pkg/agent/testdata/amp-protocol.mdnew file mode 100644index 0000000000..f76ccbc31b--- /dev/null+++ b/server/pkg/agent/testdata/amp-protocol.md@@ -0,0 +1,54 @@+# Amp adapter protocol audit++Checked against the official `@ampcode/cli` executable+`0.0.1794456033-gb2ff22` on macOS arm64 (2026-11-12).++References:++- https://ampcode.com/docs/cli+- https://ampcode.com/docs/cli/execute-mode+- https://ampcode.com/docs/cli/streaming-json+- https://ampcode.com/docs/cli/settings+- https://ampcode.com/docs/customize/skills++The adapter runs local execute mode with newline-delimited JSON output and+plain prompt input on stdin. Continuation uses `threads continue <thread-id>`;+it never selects the last thread implicitly. The model field selects a native+Amp mode with `--mode`, while Amp owns the actual model routing. No model catalog+is invented, and absent terminal usage is left unreported.++`system/init` supplies the session ID. Assistant content contains text and tool+calls; user content contains tool results. Assistant `end_turn` and+`system/subagent_finished` are progress, not completion. Only `result` with+`subtype:success` and no error establishes success. The terminal boundary is+published immediately, before waiting up to ten seconds for CLI exit. A native+nonzero exit observed during that grace still fails; terminating a process that+remains alive afterward is bounded cleanup and preserves the terminal answer,+with a daemon warning. Cancellation or a deadline after the terminal boundary+also preserves the result. Missing cleanup acknowledgement remains a failure.+Failure clears the final output while retaining the transcript and observed ID.+Permission denials reported by Amp are shown as a redacted transcript warning;+the adapter does not override Amp's configured permission rules.++The adapter requires the documented non-interactive `AMP_API_KEY` access token.+An empty key fails before startup; interactive login is unsupported. A real CLI+test with an invalid token passed and confirmed authentication failure without+exposing the token. A real successful task and continuation could not be verified+because this execution environment has no valid Amp token. Before the key+preflight was added, the credential-free CLI waited until the 45-second task+deadline; it did not produce a terminal result.++Offline subprocess tests cover protocol completion/failure, stdin transport,+redaction, cancellation, timeouts, inherited output pipes, oversized frames,+wrapper exit and local descendant cleanup. Real tests require both the+`agentintegration` build tag and `MULTICA_RUN_REAL_AGENT_SMOKE=1`.++Cancellation owns the local process tree. Amp documents that service-side+asynchronous subagents can survive CLI exit; this adapter has no remote+cancellation API for them. Their thread ID remains available for inspection.+Orbs, runners, managed MCP, live supplements and `max_turns` are unsupported.++Roll out the additive runtime-profile constraint migration before the new+daemon. Older daemons retain their existing providers. Before a daemon downgrade,+disable Amp profiles; historical profile rows remain, including after the down+migration, whose constraint restricts subsequent writes without scanning rows.