Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9085: add Factory Droid harness (#10399)

Multica Eve66e534d8e1d7
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 83e58497e4..5228fd4797 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) |
+| [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) |
| [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh` | DeepSeek Harness (`dsh --profile multica --stdio`; requires the Multica runtime profile to be installed; reads AGENTS.md and .dsh/skills/) |
@@ -478,6 +479,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_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 |
| `MULTICA_QWENPAW_PATH` | Custom path to the `qwenpaw` binary |
| `MULTICA_QWENPAW_ARGS` | Daemon-wide extra QwenPaw arguments (POSIX shellword parsing; managed protocol flags are filtered) |
| `MULTICA_MCODE_PATH` | Custom path to the `mcode` binary |
diff --git a/SELF_HOSTING.md b/SELF_HOSTING.md
index 63909ee37b..8e87beef24 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)
+- [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`.
- [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`dsh` on PATH with the Multica runtime profile installed; set `DEEPSEEK_API_KEY`)
diff --git a/apps/docs/content/docs/install-agent-runtime.fr.mdx b/apps/docs/content/docs/install-agent-runtime.fr.mdx
index 3db94598b1..f2f9fefe01 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) |
+| 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/) |
| Dim | `dim` | [DimCode](https://dimagent.cn/en/docs/cli) |
@@ -72,6 +73,7 @@ En dessous de la version minimale, le daemon n'enregistre pas le runtime corresp
| Copilot | 1.0.0 |
| Grok | 0.2.89 |
| Qwen Code | 0.20.0 |
+| Factory Droid | 1.8.0 |
| MiniMax Code | 0.1.2 |
| Muse Code | 1.4.10 |
| OpenCode | 1.1.54 |
diff --git a/apps/docs/content/docs/install-agent-runtime.ja.mdx b/apps/docs/content/docs/install-agent-runtime.ja.mdx
index 10ffa7fd8a..aca16f1eed 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) |
+| 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/) |
| Dim | `dim` | [DimCode](https://dimagent.cn/en/docs/cli) |
@@ -72,6 +73,7 @@ Multica は現在、次のコマンドを検出します。
| Copilot | 1.0.0 |
| Grok | 0.2.89 |
| Qwen Code | 0.20.0 |
+| Factory Droid | 1.8.0 |
| MiniMax Code | 0.1.2 |
| Muse Code | 1.4.10 |
| OpenCode | 1.1.54 |
diff --git a/apps/docs/content/docs/install-agent-runtime.ko.mdx b/apps/docs/content/docs/install-agent-runtime.ko.mdx
index 7f6cc19d8a..11c7848d75 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) |
+| 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/) |
| Dim | `dim` | [DimCode](https://dimagent.cn/en/docs/cli) |
@@ -72,6 +73,7 @@ Multica는 현재 다음 명령을 감지합니다.
| Copilot | 1.0.0 |
| Grok | 0.2.89 |
| Qwen Code | 0.20.0 |
+| Factory Droid | 1.8.0 |
| MiniMax Code | 0.1.2 |
| Muse Code | 1.4.10 |
| OpenCode | 1.1.54 |
diff --git a/apps/docs/content/docs/install-agent-runtime.mdx b/apps/docs/content/docs/install-agent-runtime.mdx
index 42b664ef5c..17a829e830 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) |
+| 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/) |
| Dim | `dim` | [DimCode](https://dimagent.cn/en/docs/cli) |
@@ -72,6 +73,7 @@ Below the minimum version, the daemon does not register the corresponding runtim
| Copilot | 1.0.0 |
| Grok | 0.2.89 |
| Qwen Code | 0.20.0 |
+| Factory Droid | 1.8.0 |
| MiniMax Code | 0.1.2 |
| Muse Code | 1.4.10 |
| OpenCode | 1.1.54 |
@@ -83,6 +85,21 @@ Below the minimum version, the daemon does not register the corresponding runtim
A few tools need extra setup beyond signing in:
<Accordions type="multiple">
+<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.
+
+After the daemon discovers `droid`, select the Droid runtime when creating an agent and assign it an issue. The run streams assistant and tool messages, then publishes the final response. Models use Droid's default unless you enter a model ID in Multica. Optional daemon overrides are `MULTICA_DROID_PATH`, `MULTICA_DROID_MODEL`, and `MULTICA_DROID_ARGS`. Reasoning effort can be set through custom arguments, such as `--reasoning-effort high`.
+
+Runs use `droid exec --output-format stream-json --auto high`, read `AGENTS.md`, and discover skills in `.factory/skills/`. Multica forwards a saved session ID for continuation in the same working directory. If continuation fails before Droid confirms a session or uses a tool, Multica may retry once with a fresh session; authentication and network failures keep the existing session without retrying.
+
+Custom arguments also accept Droid's tool filters, spec-mode settings, `--settings`, session tags, and `--disable-builtin-skills`. Configure MCP, hooks, plugins, custom Droids, and BYOK models in Droid itself. Multica does not manage that configuration or implement Mission orchestration, live message supplements, or `max_turns`; use the task timeout to bound execution. Transport, working-directory, model, session, and Mission overrides are filtered from custom arguments. Unknown options and extra positional prompts are rejected before startup. Native `stream-json` output is supported; the deprecated `stream-json` input mode is not used.
+
+Droid's command policy can still reject a task under `--auto high`; completed edits remain in the working tree after a failure. Use the [official permission-rule commands](https://docs.factory.com/autonomy-and-safety/permission-rules) to check your execution machine's policy before assigning unattended tasks.
+
+If Droid is missing, install it on the daemon machine or set `MULTICA_DROID_PATH` to its native executable. If authentication fails, sign in or replace the API key in the execution environment. Permission, provider, and protocol failures appear as failed runs; cancellation and timeout stop the owned process tree and report their respective final states. A clean exit without a completion event is a failure, and intermediate narration is never published as the final result.
+
+</Accordion>
<Accordion title="CodeArts" id="codearts">
Verify the non-interactive path with `codearts run --model provider/model "Reply OK"`, not only the TUI. The current CodeArts CLI can let a custom provider work in the TUI while `run`, `models`, and `serve` still require [`CODEARTS_CLI_AK` / `CODEARTS_CLI_SK`](https://support.huaweicloud.com/usermanual-cli/codeartsagent_cli_0026.html). Multica can discover custom models from `~/.codeartsdoer/codearts_cli.json` or `.jsonc`, but agent runs use `codearts run` and therefore follow its authorization requirements.
diff --git a/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdx b/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdx
index 088b6ee765..d59e25751a 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) |
+| 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/) |
| Dim | `dim` | [DimCode](https://dimagent.cn/docs/cli) |
@@ -72,6 +73,7 @@ Multica 當前會檢測以下命令:
| Copilot | 1.0.0 |
| Grok | 0.2.89 |
| Qwen Code | 0.20.0 |
+| Factory Droid | 1.8.0 |
| MiniMax Code | 0.1.2 |
| Muse Code | 1.4.10 |
| OpenCode | 1.1.54 |
diff --git a/apps/docs/content/docs/install-agent-runtime.zh.mdx b/apps/docs/content/docs/install-agent-runtime.zh.mdx
index e83bbc832c..71417b85da 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) |
+| 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/) |
| Dim | `dim` | [DimCode](https://dimagent.cn/docs/cli) |
@@ -72,6 +73,7 @@ Multica 当前会检测以下命令:
| Copilot | 1.0.0 |
| Grok | 0.2.89 |
| Qwen Code | 0.20.0 |
+| Factory Droid | 1.8.0 |
| MiniMax Code | 0.1.2 |
| Muse Code | 1.4.10 |
| OpenCode | 1.1.54 |
@@ -83,6 +85,21 @@ Multica 当前会检测以下命令:
以下工具除了登录,还要额外配置:
<Accordions type="multiple">
+<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`,不要把凭据写进提示词或自定义参数。
+
+守护进程发现 `droid` 后,创建智能体时选择 Droid 运行时,再指派一个任务。执行过程显示文本和工具输出,完成后回传最终结果。模型默认沿用 Droid 配置,也可在 Multica 手动填写模型 ID。守护进程支持 `MULTICA_DROID_PATH`、`MULTICA_DROID_MODEL`、`MULTICA_DROID_ARGS`;推理强度可通过自定义参数 `--reasoning-effort high` 设置。
+
+任务使用 `droid exec --output-format stream-json --auto high`,读取 `AGENTS.md`,从 `.factory/skills/` 发现 skill。后续执行会在同一工作目录传入会话 ID。若继续会话失败,且 Droid 尚未确认会话或调用工具,Multica 可尝试一次新会话;认证和网络错误会保留原会话,不会重试。
+
+自定义参数还支持 Droid 的工具过滤、规划模式配置、`--settings`、会话标签和 `--disable-builtin-skills`。MCP、hooks、plugins、自定义 Droid 和 BYOK 模型需在 Droid 中配置,Multica 不管理这些配置。暂不支持 Mission 编排、执行中追加消息或 `max_turns`;执行时长使用任务超时限制。自定义参数中的协议、工作目录、模型、会话和 Mission 覆盖项会被过滤;未知选项和额外的位置提示词会在启动前报错。使用的 `stream-json` 输出仍受支持,不涉及已弃用的 `stream-json` 输入模式。
+
+使用 `--auto high` 时,Droid 的命令策略仍可能拒绝执行;失败前已完成的文件修改会保留。指派无人值守任务前,可按[官方权限规则文档](https://docs.factory.com/autonomy-and-safety/permission-rules)检查执行机器上的策略。
+
+未发现运行时时,在守护进程所在机器安装 Droid,或用 `MULTICA_DROID_PATH` 指向原生可执行文件。认证失败时重新登录或更新执行环境中的 API key。权限、服务和协议错误会显示为失败;取消和超时会终止所属进程树并回传对应状态。没有完成事件的正常退出也会判为失败,中间说明文字不会作为最终结果发布。
+
+</Accordion>
<Accordion title="CodeArts" id="codearts">
用 `codearts run --model provider/model "只回复 OK"` 验证非交互模式,只验证 TUI 不够。当前 CodeArts CLI 可能允许自定义 provider 在 TUI 中工作,但 `run`、`models` 和 `serve` 仍要求配置 [`CODEARTS_CLI_AK` / `CODEARTS_CLI_SK`](https://support.huaweicloud.com/usermanual-cli/codeartsagent_cli_0026.html)。Multica 可以从 `~/.codeartsdoer/codearts_cli.json` 或 `.jsonc` 发现自定义模型,但每次运行都使用 `codearts run`,因此仍遵循该命令的授权要求。
diff --git a/apps/docs/content/docs/providers.fr.mdx b/apps/docs/content/docs/providers.fr.mdx
index 947bc4eecd..c446cc0af1 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 |
+| Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |
| Dim | `dim` | ✓ | ✓ | ✓ | — |
diff --git a/apps/docs/content/docs/providers.ja.mdx b/apps/docs/content/docs/providers.ja.mdx
index c3d21883a5..d8923aa93b 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/` |
+| Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |
| Dim | `dim` | ✓ | ✓ | ✓ | — |
diff --git a/apps/docs/content/docs/providers.ko.mdx b/apps/docs/content/docs/providers.ko.mdx
index f532ba1057..5cb5d0ca41 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/` |
+| Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |
| Dim | `dim` | ✓ | ✓ | ✓ | — |
diff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdx
index 42e00f0dc7..93893a7e4a 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/` |
+| Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |
| Dim | `dim` | ✓ | ✓ | ✓ | — |
diff --git a/apps/docs/content/docs/providers.zh-Hant.mdx b/apps/docs/content/docs/providers.zh-Hant.mdx
index f037f1e353..e174120cd4 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/` |
+| Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |
| Dim | `dim` | ✓ | ✓ | ✓ | — |
diff --git a/apps/docs/content/docs/providers.zh.mdx b/apps/docs/content/docs/providers.zh.mdx
index a0c327f3e3..eae6313841 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/` |
+| Factory Droid | `droid` | ✓ | — | ✓ | `.factory/skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | ✓ | `.traecli/skills/` |
| Dim | `dim` | ✓ | ✓ | ✓ | — |
diff --git a/packages/core/agents/mcp-support.test.ts b/packages/core/agents/mcp-support.test.ts
index 39748b6ccb..ed3e46a229 100644
--- a/packages/core/agents/mcp-support.test.ts
+++ b/packages/core/agents/mcp-support.test.ts
@@ -11,6 +11,7 @@ describe("providerSupportsMcpConfig", () => {
it("rejects providers whose runtime ignores mcp_config", () => {
expect(providerSupportsMcpConfig("antigravity")).toBe(false);
expect(providerSupportsMcpConfig("copilot")).toBe(false);
+ expect(providerSupportsMcpConfig("droid")).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.ts
index d978435077..58560ffb29 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -135,6 +135,7 @@ export const RUNTIME_PROFILE_PROTOCOL_FAMILIES = [
"grok",
"qwen",
"qwenpaw",
+ "droid",
"mcode",
"muse",
"devin",
diff --git a/scripts/agent-cli-command-names.txt b/scripts/agent-cli-command-names.txt
index 69eeb88e31..b31bc2026c 100644
--- a/scripts/agent-cli-command-names.txt
+++ b/scripts/agent-cli-command-names.txt
@@ -23,6 +23,7 @@ qodercli
qoderclicn
qwen
qwenpaw
+droid
reasonix
traecli
zeroclaw
diff --git a/server/internal/daemon/agents_probe.go b/server/internal/daemon/agents_probe.go
index fbec923b8b..c77d2ba12f 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_DROID_PATH", "droid", "MULTICA_DROID_MODEL"); ok {
+ agents["droid"] = e
+ }
// QwenPaw (`qwenpaw`) is the QwenPaw CLI agent, driven over ACP via
// `qwenpaw acp`. It takes no model env var: the backend never calls
// session/set_model (it would rewrite QwenPaw's shared agent config), so
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index 4369c21f0a..6a576ae273 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 unavailable
LaunchedBy string // "desktop" when spawned by the Electron app, empty for standalone
Profile 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, 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, 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)
@@ -155,6 +155,7 @@ type Config struct {
CodexArgs []string
CodebuddyArgs []string
QwenArgs []string
+ DroidArgs []string
QwenpawArgs []string
// ProfileCommandOverrides maps a custom runtime profile_id -> the absolute
@@ -266,7 +267,7 @@ func LoadConfig(overrides Overrides) (Config, error) {
// can re-run the same discovery on a live daemon (MUL-5439).
agents := probeAgentCLIs()
if len(agents) == 0 && !overrides.AllowNoAgents {
- return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codearts, codex, copilot, opencode, deveco, openclaw, hermes, pi, omp, cursor-agent, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, muse, devin, dim, 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, mcode, muse, devin, dim, zeroclaw, or zcode and ensure it is on PATH")
}
claudeArgs, err := shellArgsFromEnv("MULTICA_CLAUDE_ARGS")
@@ -285,6 +286,10 @@ func LoadConfig(overrides Overrides) (Config, error) {
if err != nil {
return Config{}, err
}
+ droidArgs, err := shellArgsFromEnv("MULTICA_DROID_ARGS")
+ if err != nil {
+ return Config{}, err
+ }
qwenpawArgs, err := shellArgsFromEnv("MULTICA_QWENPAW_ARGS")
if err != nil {
return Config{}, err
@@ -678,6 +683,7 @@ func LoadConfig(overrides Overrides) (Config, error) {
CodexArgs: codexArgs,
CodebuddyArgs: codebuddyArgs,
QwenArgs: qwenArgs,
+ DroidArgs: droidArgs,
QwenpawArgs: qwenpawArgs,
ProfileCommandOverrides: profileCommandOverrides,
}, nil
@@ -961,7 +967,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", "mcode", "muse", "devin", "dim", "zeroclaw", "zcode",
+ "pi", "cursor-agent", "copilot", "kimi", "reasonix", "dsh", "kiro-cli", "codebuddy", "agy", "qodercli", "qoderclicn", "traecli", "grok", "qwen", "qwenpaw", "droid", "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.go
index 420e8b27d3..6ecdd293f3 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -9612,7 +9612,7 @@ func shouldRetryWithFreshSession(result agent.Result, priorSessionID string, too
if !agent.ResumeRejectionUndetectable(provider) {
return false
}
- // antigravity, codearts, copilot, cursor, deveco and opencode scrape SessionID out
+ // antigravity, codearts, copilot, cursor, deveco, droid and opencode scrape SessionID out
// of stream output and have no rejection string captured anywhere, so an
// empty SessionID is the only thing they can offer. It proves no session
// was established this run, which is exactly what the gate relied on for
@@ -11271,6 +11271,8 @@ func defaultArgsForProvider(cfg Config, provider string) []string {
args = cfg.CodebuddyArgs
case "qwen":
args = cfg.QwenArgs
+ case "droid":
+ args = cfg.DroidArgs
case "qwenpaw":
args = cfg.QwenpawArgs
default:
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 6780b5f709..e0f57cf1c4 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -799,6 +799,9 @@ func TestProviderNeedsInlineSystemPrompt(t *testing.T) {
{provider: "qwen", want: false},
{provider: "codex", want: false},
{provider: "claude", want: false},
+ // Droid uses the task AGENTS.md; TestDroidRealAgentsMDCanary verifies
+ // native discovery independently of the optional adapter SystemPrompt.
+ {provider: "droid", want: false},
}
for _, tc := range cases {
@@ -3920,7 +3923,7 @@ func TestShouldRetryWithFreshSession_CompatPathIsBackendScoped(t *testing.T) {
// the compat path exists to catch.
result := agent.Result{Status: "failed", Error: "exit status 1"}
- undetectable := []string{"antigravity", "codearts", "copilot", "cursor", "deveco", "opencode"}
+ undetectable := []string{"antigravity", "codearts", "copilot", "cursor", "deveco", "droid", "opencode"}
for _, provider := range undetectable {
t.Run(provider+" retries", func(t *testing.T) {
t.Parallel()
diff --git a/server/internal/daemon/droid_resume_unix_test.go b/server/internal/daemon/droid_resume_unix_test.go
new file mode 100644
index 0000000000..3ca355acd5
--- /dev/null
+++ b/server/internal/daemon/droid_resume_unix_test.go
@@ -0,0 +1,108 @@
+//go:build unix
+
+package daemon
+
+import (
+ "bytes"
+ "context"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+)
+
+func TestRunTaskDroidResumeRecovery(t *testing.T) {
+ for _, tc := range []struct {
+ name, failure, event string
+ freshFails bool
+ wantAttempts int
+ }{
+ {name: "missing session retries fresh", failure: "Could not load session", wantAttempts: 2},
+ {name: "fresh failure stops after one retry", failure: "Could not load session", freshFails: true, wantAttempts: 2},
+ {name: "confirmed session prevents retry", failure: "Provider failed", event: `printf '%s\n' '{"type":"system","subtype":"init","session_id":"stale-session"}'`, wantAttempts: 1},
+ {name: "tool use prevents retry", failure: "Could not load session", event: `printf '%s\n' '{"type":"tool_call","id":"call-1","toolName":"Read","parameters":{}}'`, wantAttempts: 1},
+ {name: "authentication keeps existing session", failure: "Authentication failed: invalid API key", wantAttempts: 1},
+ {name: "network failure keeps existing session", failure: "connection refused", wantAttempts: 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ redirectTestHome(t, t.TempDir())
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", "")
+ dir := t.TempDir()
+ attemptFile := filepath.Join(dir, "attempts")
+ fakeBin := filepath.Join(dir, "droid")
+ script := `#!/bin/sh
+cat >/dev/null
+printf '%s\n' "$*" >> "$DROID_ATTEMPTS"
+case "$*" in
+ *--session-id*)
+` + tc.event + "\nprintf '%s\\n' '{\"type\":\"error\",\"message\":\"" + tc.failure + "\"}'\nexit 1\n;;\nesac\n"
+ if tc.freshFails {
+ script += "printf '%s\\n' '{\"type\":\"error\",\"message\":\"Fresh attempt failed\"}'\nexit 1\n"
+ } else {
+ script += "printf '%s\\n' '{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"fresh-session\"}' '{\"type\":\"completion\",\"finalText\":\"done\"}'\n"
+ }
+ writeTestExecutable(t, fakeBin, []byte(script))
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`{}`)) }))
+ defer srv.Close()
+ var logs bytes.Buffer
+ logger := slog.New(slog.NewTextHandler(&logs, nil))
+ d := &Daemon{
+ client: NewClient(srv.URL), logger: logger,
+ workspaces: make(map[string]*workspaceState), activeEnvRoots: make(map[string]int),
+ runtimeIndex: map[string]Runtime{"rt-droid": {ID: "rt-droid", Provider: "droid"}},
+ cfg: Config{WorkspacesRoot: t.TempDir(), AgentTimeout: 10 * time.Second, ServerBaseURL: srv.URL,
+ Agents: map[string]AgentEntry{"droid": {Path: fakeBin}}},
+ }
+ task := Task{
+ ID: "task-droid", WorkspaceID: "ws-droid", RuntimeID: "rt-droid", IssueID: "issue-droid",
+ AgentID: "agent-droid", AuthToken: "mat_droid_fixture", PriorSessionID: "stale-session",
+ Agent: &AgentData{ID: "agent-droid", Name: "droid-agent", CustomEnv: map[string]string{"DROID_ATTEMPTS": attemptFile}},
+ }
+ prior, err := execenv.Prepare(execenv.PrepareParams{
+ WorkspacesRoot: d.cfg.WorkspacesRoot, WorkspaceID: task.WorkspaceID,
+ TaskID: "prior-droid", Provider: "droid",
+ Task: execenv.TaskContextForEnv{AgentID: task.AgentID, IssueID: task.IssueID},
+ }, logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = prior.Cleanup(true) })
+ prior.ReleaseLock()
+ task.PriorWorkDir = prior.WorkDir
+ if _, ok := shouldReusePriorWorkdir(task, nil, d.cfg.WorkspacesRoot); !ok {
+ t.Fatal("fixture did not prepare a reusable session workdir")
+ }
+ result, err := d.runTask(context.Background(), task, "droid", 0, logger)
+ if err != nil {
+ t.Fatalf("runTask: %v", err)
+ }
+ attempts, err := os.ReadFile(attemptFile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lines := strings.Split(strings.TrimSpace(string(attempts)), "\n")
+ if len(lines) != tc.wantAttempts || !strings.Contains(lines[0], "--session-id stale-session") {
+ t.Fatalf("attempts = %q, want %d starting with resume; logs:\n%s", lines, tc.wantAttempts, logs.String())
+ }
+ if tc.wantAttempts == 2 {
+ if strings.Contains(lines[1], "--session-id") || result.RetiredSessionID != "stale-session" {
+ t.Fatalf("fresh attempt retained the stale session: attempts=%q result=%+v", lines, result)
+ }
+ if !tc.freshFails && (result.Status != "completed" || result.Comment != "done" || result.SessionID != "fresh-session") {
+ t.Fatalf("fresh retry result = %+v", result)
+ }
+ if tc.freshFails && result.Status != "blocked" {
+ t.Fatalf("failed fresh retry = %+v", result)
+ }
+ } else if result.Status != "blocked" || result.RetiredSessionID != "" {
+ t.Fatalf("non-retryable failure lost its disposition: %+v", result)
+ }
+ })
+ }
+}
diff --git a/server/internal/daemon/droid_test.go b/server/internal/daemon/droid_test.go
new file mode 100644
index 0000000000..f7476f9862
--- /dev/null
+++ b/server/internal/daemon/droid_test.go
@@ -0,0 +1,59 @@
+package daemon
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+func TestDroidDiscoveryAndConfiguration(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, "droid")
+ 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_DROID_PATH", "")
+ if override {
+ t.Setenv("MULTICA_DROID_PATH", path)
+ }
+ t.Setenv("MULTICA_DROID_MODEL", "custom:test")
+ t.Setenv("MULTICA_DROID_ARGS", "--reasoning-effort high")
+ 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["droid"]
+ gotPath, _ := filepath.EvalSymlinks(entry.Path)
+ if !ok || gotPath != wantPath || entry.Model != "custom:test" {
+ t.Fatalf("Droid not discovered: %+v", cfg.Agents)
+ }
+ args := defaultArgsForProvider(cfg, "droid")
+ if strings.Join(args, " ") != "--reasoning-effort high" {
+ t.Fatalf("args = %v", args)
+ }
+ args[0] = "changed"
+ if cfg.DroidArgs[0] != "--reasoning-effort" {
+ t.Fatal("caller mutated daemon defaults")
+ }
+ })
+ }
+}
+
+func TestDroidLocalSkills(t *testing.T) {
+ home := t.TempDir()
+ redirectTestHome(t, home)
+ writeTestLocalSkill(t, filepath.Join(home, ".factory", "skills"), "review", map[string]string{"SKILL.md": "---\nname: Review\ndescription: Review code\n---\n"})
+ skills, supported, err := listRuntimeLocalSkills("droid")
+ if err != nil || !supported || len(skills) != 1 || skills[0].SourcePath != "~/.factory/skills/review" {
+ t.Fatalf("Droid local skills = %+v, %v, %v", skills, supported, err)
+ }
+}
diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.go
index 835dd34f7a..81ee7a01f8 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 "droid":
+ return filepath.Join(workDir, ".factory", "skills")
case "qwenpaw":
// QwenPaw discovers workspace-level skills from <workDir>/skill_pool/.
// See get_workspace_skills_dir in QwenPaw's skill_system/store.py.
diff --git a/server/internal/daemon/execenv/droid_test.go b/server/internal/daemon/execenv/droid_test.go
new file mode 100644
index 0000000000..7f4888a806
--- /dev/null
+++ b/server/internal/daemon/execenv/droid_test.go
@@ -0,0 +1,25 @@
+package execenv
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestDroidRuntimeBriefAndSkills(t *testing.T) {
+ dir := t.TempDir()
+ task := TaskContextForEnv{IssueID: "droid-issue", AgentSkills: []SkillContextForEnv{{Name: "Review", Content: "Review carefully."}}}
+ if _, err := writeContextFiles(dir, "droid", task, nil); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := InjectRuntimeConfig(dir, "droid", task); err != nil {
+ t.Fatal(err)
+ }
+ for path, want := range map[string]string{"AGENTS.md": "Multica Agent Runtime", ".factory/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/runtime_config.go b/server/internal/daemon/execenv/runtime_config.go
index f72cf3c262..cf005cc1e3 100644
--- a/server/internal/daemon/execenv/runtime_config.go
+++ b/server/internal/daemon/execenv/runtime_config.go
@@ -218,7 +218,7 @@ func runtimeConfigPath(workDir, provider string) string {
return filepath.Join(workDir, "CODEBUDDY.md")
case "qwen":
return filepath.Join(workDir, "QWEN.md")
- case "codex", "copilot", "opencode", "codearts", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "mcode", "muse", "dim", "zeroclaw", "devin", "museapp", "zcode":
+ 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":
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.go
index a3e152a72d..a5b55ad7a0 100644
--- a/server/internal/daemon/execenv/sidecar_manifest_test.go
+++ b/server/internal/daemon/execenv/sidecar_manifest_test.go
@@ -164,6 +164,7 @@ var allFileBasedProviders = []string{
"antigravity",
"qwen",
"qwenpaw",
+ "droid",
"mcode",
}
diff --git a/server/internal/daemon/local_skills.go b/server/internal/daemon/local_skills.go
index 5179afdd19..8af1297cda 100644
--- a/server/internal/daemon/local_skills.go
+++ b/server/internal/daemon/local_skills.go
@@ -221,6 +221,8 @@ func localSkillRootsForProvider(provider string) ([]localSkillRoot, bool, error)
qwenHome = filepath.Join(home, ".qwen")
}
providerRoot = filepath.Join(qwenHome, "skills")
+ case "droid":
+ providerRoot = filepath.Join(home, ".factory", "skills")
case "qwenpaw":
// QWENPAW_WORKING_DIR (or legacy COPAW_WORKING_DIR) overrides
// QwenPaw's global ~/.qwenpaw directory, which owns settings,
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index cc6b91011b..dcc749fa90 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -174,6 +174,7 @@ var (
"qoder": "qoder",
"qoderclicn": "qoderclicn",
"qwen": "qwen",
+ "droid": "droid",
"traecli": "traecli",
"other": "other",
}
diff --git a/server/migrations/652_runtime_profile_add_droid.down.sql b/server/migrations/652_runtime_profile_add_droid.down.sql
new file mode 100644
index 0000000000..7b049f847e
--- /dev/null
+++ b/server/migrations/652_runtime_profile_add_droid.down.sql
@@ -0,0 +1,35 @@
+-- Remove Droid from future profile writes without scanning historical rows.
+-- Disable Droid profiles before downgrading the daemon; retain their 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'
+ )) NOT VALID;
diff --git a/server/migrations/652_runtime_profile_add_droid.up.sql b/server/migrations/652_runtime_profile_add_droid.up.sql
new file mode 100644
index 0000000000..aba6ca8860
--- /dev/null
+++ b/server/migrations/652_runtime_profile_add_droid.up.sql
@@ -0,0 +1,36 @@
+-- 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'
+ )) NOT VALID;
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index bff1b0de13..ee84a4a758 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -432,6 +432,7 @@ var SupportedTypes = []string{
"grok",
"qwen",
"qwenpaw",
+ "droid",
"mcode",
"muse",
"dim",
@@ -471,6 +472,7 @@ var resumeRejectionUndetectable = map[string]bool{
"deveco": true,
"opencode": true,
"codearts": true,
+ "droid": true,
}
// ResumeRejectionUndetectable reports whether agentType is a backend that
@@ -540,6 +542,8 @@ func New(agentType string, cfg Config) (Backend, error) {
return &qwenBackend{cfg: cfg}, nil
case "qwenpaw":
return &qwenpawBackend{cfg: cfg}, nil
+ case "droid":
+ return &droidBackend{cfg: cfg}, nil
case "mcode":
return &mcodeBackend{cfg: cfg}, nil
case "devin":
@@ -596,6 +600,7 @@ var launchHeaders = map[string]string{
"grok": "grok agent stdio",
"qwen": "qwen -p (stream-json)",
"qwenpaw": "qwenpaw acp",
+ "droid": "droid exec (stream-json)",
"dim": "dim acp",
"devin": "devin acp",
"mcode": "mcode acp",
diff --git a/server/pkg/agent/droid.go b/server/pkg/agent/droid.go
new file mode 100644
index 0000000000..b4b1a05177
--- /dev/null
+++ b/server/pkg/agent/droid.go
@@ -0,0 +1,482 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "regexp"
+ "strings"
+ "sync/atomic"
+ "syscall"
+ "time"
+)
+
+// Droid's one-shot stream-json protocol is distinct from Claude's: assistant
+// text is a message event, tools use camelCase fields, and completion is final.
+// Protocol fields were checked against the official Droid 1.8.0 executable.
+type droidBackend struct{ cfg Config }
+
+var droidBlockedArgs = map[string]blockedArgMode{
+ "exec": blockedStandalone,
+ "--": blockedStandalone,
+ "-o": blockedWithValue,
+ "--output-format": blockedWithValue,
+ "--input-format": blockedWithValue,
+ "-f": blockedWithValue,
+ "--file": blockedWithValue,
+ "--auto": blockedWithValue,
+ "--skip-permissions-unsafe": blockedStandalone,
+ "--cwd": blockedWithValue,
+ "-m": blockedWithValue,
+ "--model": blockedWithValue,
+ "-s": blockedWithValue,
+ "--session-id": blockedWithValue,
+ "--fork": blockedWithValue,
+ "--append-system-prompt": blockedWithValue,
+ "--append-system-prompt-file": blockedWithValue,
+ "-w": blockedOptionalValue,
+ "--worktree": blockedOptionalValue,
+ "--worktree-dir": blockedWithValue,
+ "--mission": blockedStandalone,
+ "--worker-model": blockedWithValue,
+ "--worker-reasoning-effort": blockedWithValue,
+ "--validator-model": blockedWithValue,
+ "--validator-reasoning-effort": blockedWithValue,
+ "--list-tools": blockedStandalone,
+ "-v": blockedStandalone,
+ "--version": blockedStandalone,
+ "-h": blockedStandalone,
+ "--help": blockedStandalone,
+}
+
+// Commander accepts attached short values (-otext, -fother.md). Normalize
+// those before the shared filter so they cannot replace our transport/prompt.
+func normalizeDroidArgs(args []string) []string {
+ normalized := make([]string, 0, len(args))
+ for _, arg := range args {
+ arg = unshellQuoteArg(arg)
+ if len(arg) > 2 && arg[0] == '-' && strings.ContainsRune("ofmsw", rune(arg[1])) && arg[2] != '=' {
+ arg = arg[:2] + "=" + arg[2:]
+ }
+ normalized = append(normalized, arg)
+ }
+ return normalized
+}
+
+// The one-shot CLI treats an unclaimed positional argument as a replacement
+// prompt. Track native option arity so custom configuration cannot shadow stdin.
+// Unknown options fail closed until their one-shot semantics are checked.
+var droidNativeArgs = map[string]bool{
+ "-r": true, "--reasoning-effort": true,
+ "--spec-model": true, "--spec-reasoning-effort": true,
+ "--only-tools": true, "--add-tools": true, "--remove-tools": true,
+ "--settings": true, "--tag": true, "--log-group-id": true,
+ "--use-spec": false, "--disable-builtin-skills": false,
+}
+
+func buildDroidArgs(opts ExecOptions, logger *slog.Logger) ([]string, error) {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ args := []string{"exec", "--output-format", "stream-json", "--auto", "high"}
+ if opts.Model != "" {
+ args = append(args, "--model", opts.Model)
+ }
+ if opts.ResumeSessionID != "" {
+ args = append(args, "--session-id", opts.ResumeSessionID)
+ }
+ for _, custom := range [][]string{opts.ExtraArgs, opts.CustomArgs} {
+ filtered := filterCustomArgs(normalizeDroidArgs(custom), droidBlockedArgs, logger)
+ for i := 0; i < len(filtered); i++ {
+ arg := filtered[i]
+ flag, _, inline := strings.Cut(arg, "=")
+ // Commander also accepts -rhigh and -r=high.
+ if strings.HasPrefix(arg, "-r") && !strings.HasPrefix(arg, "--") && len(arg) > 2 {
+ flag, inline = "-r", true
+ }
+ takesValue, ok := droidNativeArgs[flag]
+ if !ok {
+ return nil, errors.New("droid custom arguments must use supported one-shot options; positional prompts 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("droid custom option %s requires a value", flag)
+ }
+ i++
+ args = append(args, filtered[i])
+ }
+ }
+ }
+ return args, nil
+}
+
+func (b *droidBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
+ if hasManagedMcpConfig(opts.McpConfig) {
+ return nil, fmt.Errorf("droid does not support Multica-managed MCP configuration; configure MCP in Droid itself")
+ }
+ execPath := b.cfg.ExecutablePath
+ if execPath == "" {
+ execPath = "droid"
+ }
+ if _, err := exec.LookPath(execPath); err != nil {
+ return nil, fmt.Errorf("droid executable not found at %q; install Factory Droid or set MULTICA_DROID_PATH: %w", execPath, err)
+ }
+ args, err := buildDroidArgs(opts, b.cfg.Logger)
+ if err != nil {
+ return nil, err
+ }
+ runCtx, cancel := runContext(ctx, opts.Timeout)
+ var systemFile string
+ cleanupSystemPrompt := func() {
+ if systemFile != "" {
+ _ = os.Remove(systemFile)
+ }
+ }
+ startedProcess := false
+ defer func() {
+ if !startedProcess {
+ cleanupSystemPrompt()
+ }
+ }()
+ if opts.SystemPrompt != "" {
+ file, err := os.CreateTemp("", "multica-droid-system-*.md")
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("create droid system prompt file: %w", err)
+ }
+ systemFile = file.Name()
+ _, writeErr := io.WriteString(file, opts.SystemPrompt)
+ closeErr := file.Close()
+ if writeErr != nil || closeErr != nil {
+ cancel()
+ return nil, fmt.Errorf("write droid system prompt file: %w", errors.Join(writeErr, closeErr))
+ }
+ args = append(args, "--append-system-prompt-file", systemFile)
+ }
+ runtimeCmd := b.cfg.commandAt(execPath)
+ runtimeCmd.Prefix = FilterLaunchPrefix("droid", normalizeDroidArgs(runtimeCmd.Prefix), b.cfg.Logger)
+ cmd := runtimeCmd.exec(runCtx, args...)
+ hideAgentWindow(cmd)
+ cmd.Dir = opts.Cwd
+ cmd.Env = buildEnv(b.cfg.Env)
+ // Stdin avoids OS command-line size/quoting limits and keeps prompts out of
+ // process listings. Droid reads to EOF before executing the task.
+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args, trustAgentCommandPositional(0, "exec")))
+ // 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("droid stdout pipe: %w", err)
+ }
+ errR, errW, err := os.Pipe()
+ if err != nil {
+ cancel()
+ _ = stdout.Close()
+ _ = outW.Close()
+ return nil, fmt.Errorf("droid 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("droid 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 droid: %w", err)
+ }
+ startedProcess = true
+ _ = outW.Close()
+ _ = errW.Close()
+ _ = inR.Close()
+ if opts.MaxTurns > 0 {
+ b.cfg.Logger.Warn("droid does not support max_turns; use the task timeout to bound execution")
+ }
+ scrub := droidOutputScrubber(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 droidStreamRead, 16)
+ stopReads := make(chan struct{})
+ go readDroidStream(stdout, scrub, reads, stopReads)
+ go func() {
+ defer cancel()
+ defer close(msgCh)
+ defer close(resCh)
+ defer cleanupSystemPrompt()
+ started := time.Now()
+ state := droidStreamState{model: opts.Model}
+ 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() {
+ if drain == nil {
+ drain = time.NewTimer(droidStreamDrainGrace)
+ } else {
+ drain.Reset(droidStreamDrainGrace)
+ }
+ drainC = drain.C
+ }
+ cleaning := false
+ beginCleanup := func() {
+ if cleaning {
+ return
+ }
+ cleaning = true
+ // Preserve the outcome established before bounded cleanup. A later
+ // task deadline cannot erase a verified completion and process exit.
+ runErr = runCtx.Err()
+ ctxDone = nil
+ if waitCh == nil && (state.sawCompletion || state.failed) && runErr == nil {
+ terminalObserved.Store(true)
+ }
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ _ = stdin.Close()
+ setDrainDeadline()
+ }
+ 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 {
+ handleDroidEvent(item.event, msgCh, &state)
+ }
+ case exitErr = <-waitCh:
+ waitCh = nil
+ // A launch wrapper can exit before its descendant finishes the
+ // protocol. Allow trailing output, bounded even without a timeout.
+ if !cleaning {
+ setDrainDeadline()
+ }
+ case inputErr = <-inputCh:
+ inputCh = nil
+ case <-stderrDone:
+ stderrDone = nil
+ case <-ctxDone:
+ beginCleanup()
+ case <-drainC:
+ if cleaning {
+ b.cfg.Logger.Warn("droid 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 Droid consumed enough input
+ // to answer; otherwise retain input transport failures as diagnostics.
+ if state.sawCompletion || state.failed {
+ inputErr = nil
+ }
+ status, output, errText := finalizeStreamResult("droid", opts.Timeout, runErr, inputErr, exitErr, state.sessionID, terminal, "")
+ if errText != "" {
+ errText = sanitizeAgentDiagnostic(scrub(withAgentStderr(errText, "droid", stderr.Tail())))
+ }
+ var usage map[string]TokenUsage
+ if state.usage != nil {
+ model := state.model
+ if model == "" {
+ model = "unknown"
+ }
+ usage = map[string]TokenUsage{model: *state.usage}
+ }
+ b.cfg.Logger.Info("droid finished", "pid", cmd.Process.Pid, "status", status)
+ cleanupSystemPrompt()
+ 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{Messages: msgCh, Result: resCh, TerminalObserved: terminalObserved.Load}, nil
+}
+
+const droidStreamDrainGrace = 2 * time.Second
+
+type droidStreamRead struct {
+ event droidStreamEvent
+ done bool
+ err error
+}
+
+func readDroidStream(stdout io.Reader, scrub func(string) string, reads chan<- droidStreamRead, stop <-chan struct{}) {
+ scanner := newAgentStreamScanner(stdout)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ var event droidStreamEvent
+ if line == "" || json.Unmarshal([]byte(scrub(line)), &event) != nil {
+ continue
+ }
+ select {
+ case reads <- droidStreamRead{event: event}:
+ case <-stop:
+ return
+ }
+ }
+ select {
+ case reads <- droidStreamRead{done: true, err: scanner.Err()}:
+ case <-stop:
+ }
+}
+
+type droidStreamEvent struct {
+ Type string `json:"type"`
+ Subtype string `json:"subtype"`
+ Role string `json:"role"`
+ Text string `json:"text"`
+ Message string `json:"message"`
+ FinalText string `json:"finalText"`
+ SessionID string `json:"session_id"`
+ Model string `json:"model"`
+ ID string `json:"id"`
+ ToolName string `json:"toolName"`
+ Parameters map[string]any `json:"parameters"`
+ Value json.RawMessage `json:"value"`
+ Error json.RawMessage `json:"error"`
+ IsError bool `json:"isError"`
+ 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 droidStreamState struct {
+ sessionID, model, finalText, errorText string
+ sawCompletion, failed bool
+ usage *TokenUsage
+}
+
+func handleDroidEvent(e droidStreamEvent, ch chan<- Message, s *droidStreamState) {
+ if e.SessionID != "" {
+ s.sessionID = e.SessionID
+ }
+ if e.Model != "" {
+ s.model = e.Model
+ }
+ switch e.Type {
+ case "system":
+ if e.Subtype == "init" {
+ trySend(ch, Message{Type: MessageStatus, Status: "running", SessionID: s.sessionID})
+ }
+ case "message":
+ if e.Role == "assistant" && e.Text != "" {
+ trySend(ch, Message{Type: MessageText, Content: e.Text, SessionID: s.sessionID})
+ }
+ case "tool_call":
+ trySend(ch, Message{Type: MessageToolUse, Tool: e.ToolName, CallID: e.ID, Input: e.Parameters})
+ case "tool_result":
+ value := e.Value
+ if e.IsError {
+ value = e.Error
+ }
+ var output string
+ if json.Unmarshal(value, &output) != nil && len(value) > 0 {
+ output = string(value)
+ }
+ trySend(ch, Message{Type: MessageToolResult, CallID: e.ID, Output: output})
+ case "completion":
+ s.sawCompletion = true
+ s.finalText = e.FinalText
+ if e.Usage != nil {
+ s.usage = &TokenUsage{
+ InputTokens: e.Usage.Input, OutputTokens: e.Usage.Output,
+ CacheReadTokens: e.Usage.CacheRead, CacheWriteTokens: e.Usage.CacheWrite,
+ }
+ }
+ case "error":
+ // Droid 1.8.0 completion has no error flag: an earlier error event
+ // must remain authoritative even if a completion follows it.
+ s.failed = true
+ s.errorText = sanitizeAgentDiagnostic(e.Message)
+ if s.errorText == "" {
+ s.errorText = "droid execution failed without details"
+ }
+ trySend(ch, Message{Type: MessageError, Content: s.errorText})
+ }
+}
+
+var droidAPIKeyPattern = regexp.MustCompile(`\bfk-[A-Za-z0-9_-]{16,}\b`)
+
+func droidOutputScrubber(env map[string]string) func(string) string {
+ key := os.Getenv("FACTORY_API_KEY")
+ if configured, ok := env["FACTORY_API_KEY"]; ok {
+ key = configured
+ }
+ return func(value string) string {
+ if key != "" {
+ value = strings.ReplaceAll(value, key, "[REDACTED]")
+ }
+ return droidAPIKeyPattern.ReplaceAllString(value, "[REDACTED]")
+ }
+}
diff --git a/server/pkg/agent/droid_cancel_unix_test.go b/server/pkg/agent/droid_cancel_unix_test.go
new file mode 100644
index 0000000000..46b5e1293a
--- /dev/null
+++ b/server/pkg/agent/droid_cancel_unix_test.go
@@ -0,0 +1,136 @@
+//go:build unix
+
+package agent
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestDroidInheritedOutputPipes(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":"completion","finalText":"Done"}'; exec sleep 300)`, want: "completed"},
+ {name: "descendant reads prompt after wrapper exits", child: `(sleep 0.1; cat > "$DROID_INPUT"; printf '%s\n' '{"type":"completion","finalText":"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, "droid")
+ // 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' \"$$\" \"$!\" > \"$DROID_PIDS\"\nexec 3<&-\n"
+ if tc.final != "" {
+ script += "printf '%s\\n' '{\"type\":\"completion\",\"finalText\":\"" + tc.final + "\"}'\n"
+ }
+ if tc.exitCode != "" {
+ script += tc.beforeExit + "exit " + tc.exitCode + "\n"
+ }
+ writeTestExecutable(t, path, []byte(script))
+ backend, err := New("droid", Config{ExecutablePath: path, Env: map[string]string{"DROID_PIDS": pidFile, "DROID_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 := collectDroid(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 TestDroidTerminatesOwnedProcessTree(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, "droid")
+ script := "#!/bin/sh\nsleep 300 >/dev/null 2>&1 &\nprintf '%s %s\\n' \"$$\" \"$!\" > \"$DROID_PIDS\"\n"
+ if stage == "completed" {
+ script += "printf '%s\\n' '{\"type\":\"completion\",\"finalText\":\"Done\"}'\n"
+ } else if stage != "failed" {
+ script += "wait\n"
+ }
+ writeTestExecutable(t, path, []byte(script))
+ backend, err := New("droid", Config{ExecutablePath: path, Env: map[string]string{"DROID_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 := collectDroid(t, session)
+ if result.Status != want {
+ t.Fatalf("result = %+v", result)
+ }
+ for _, pid := range pids {
+ waitProcessGone(t, pid)
+ }
+ })
+ }
+}
diff --git a/server/pkg/agent/droid_integration_test.go b/server/pkg/agent/droid_integration_test.go
new file mode 100644
index 0000000000..f45b90395b
--- /dev/null
+++ b/server/pkg/agent/droid_integration_test.go
@@ -0,0 +1,106 @@
+//go:build agentintegration
+
+package agent
+
+import (
+ "context"
+ "crypto/rand"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// The marker is available only through native AGENTS.md discovery. Neither
+// the turn prompt nor SystemPrompt supplies it, and a tool read cannot pass.
+func TestDroidRealAgentsMDCanary(t *testing.T) {
+ requireRealAgentSmoke(t)
+ executable := os.Getenv("MULTICA_DROID_PATH")
+ if executable == "" {
+ executable = "droid"
+ }
+ backend, err := New("droid", Config{ExecutablePath: executable})
+ if err != nil {
+ t.Fatal(err)
+ }
+ cwd := t.TempDir()
+ canary := "DROID_AGENTS_" + rand.Text()
+ instructions := "When asked for the project instruction marker, reply with exactly " + canary + ". Do not use tools for that request.\n"
+ if err := os.WriteFile(filepath.Join(cwd, "AGENTS.md"), []byte(instructions), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(context.Background(), "Reply with the project instruction marker. Do not use tools or read files.", ExecOptions{Cwd: cwd, Timeout: 45 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ messages, result := collectDroid(t, session)
+ if result.Status != "completed" || strings.TrimSpace(result.Output) != canary || result.SessionID == "" {
+ t.Fatalf("real Droid AGENTS.md canary: %+v", result)
+ }
+ for _, message := range messages {
+ if message.Type == MessageToolUse || message.Type == MessageToolResult {
+ t.Fatal("AGENTS.md canary used a tool instead of native instruction discovery")
+ }
+ }
+}
+
+func TestDroidRealTaskSmoke(t *testing.T) {
+ requireRealAgentSmoke(t)
+ executable := os.Getenv("MULTICA_DROID_PATH")
+ if executable == "" {
+ executable = "droid"
+ }
+ backend, err := New("droid", Config{ExecutablePath: executable})
+ if err != nil {
+ t.Fatal(err)
+ }
+ cwd := t.TempDir()
+ if err := os.WriteFile(filepath.Join(cwd, "reply-token.txt"), []byte("DROID_SMOKE_OK"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(context.Background(), "Read reply-token.txt using a tool, then reply with exactly its full contents. Do not modify files.", ExecOptions{Cwd: cwd, Timeout: 45 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ messages, result := collectDroid(t, session)
+ if result.Status != "completed" || !strings.Contains(result.Output, "DROID_SMOKE_OK") || result.SessionID == "" {
+ t.Fatalf("real Droid task: %+v", result)
+ }
+ var sawTool bool
+ for _, m := range messages {
+ sawTool = sawTool || m.Type == MessageToolUse
+ }
+ if !sawTool {
+ t.Fatal("real Droid task emitted no tool events")
+ }
+ resumed, err := backend.Execute(context.Background(), "What exact token did the file in the previous turn contain? Reply with only that token, without using tools.", ExecOptions{Cwd: cwd, ResumeSessionID: result.SessionID, Timeout: 45 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, continuation := collectDroid(t, resumed)
+ if continuation.Status != "completed" || strings.TrimSpace(continuation.Output) != "DROID_SMOKE_OK" || continuation.SessionID != result.SessionID {
+ t.Fatalf("real Droid resume: %+v", continuation)
+ }
+}
+
+func TestDroidRealInvalidAuthentication(t *testing.T) {
+ requireRealAgentSmoke(t)
+ executable := os.Getenv("MULTICA_DROID_PATH")
+ if executable == "" {
+ executable = "droid"
+ }
+ const key = "fk-invalid-multica-smoke-credential"
+ backend, err := New("droid", Config{ExecutablePath: executable, Env: map[string]string{"FACTORY_API_KEY": key}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(context.Background(), "Reply OK. Do not use tools.", ExecOptions{Cwd: t.TempDir(), Timeout: 30 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, result := collectDroid(t, session)
+ if result.Status != "failed" || result.Output != "" || !strings.Contains(strings.ToLower(result.Error), "auth") || strings.Contains(result.Error, key) {
+ t.Fatalf("real Droid auth failure: %+v", result)
+ }
+}
diff --git a/server/pkg/agent/droid_test.go b/server/pkg/agent/droid_test.go
new file mode 100644
index 0000000000..8b6e02924e
--- /dev/null
+++ b/server/pkg/agent/droid_test.go
@@ -0,0 +1,448 @@
+package agent
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+// The test binary is the fake CLI on every platform; default tests never
+// discover or execute a user-installed Droid or access a Factory account.
+func TestDroidHelperProcess(t *testing.T) {
+ if os.Getenv("DROID_HELPER_PROCESS") != "1" {
+ return
+ }
+ input, _ := io.ReadAll(os.Stdin)
+ if capture := os.Getenv("DROID_CAPTURE"); capture != "" {
+ cwd, _ := os.Getwd()
+ var systemPrompt, systemFile string
+ var systemMode os.FileMode
+ for i, arg := range os.Args {
+ if arg == "--append-system-prompt-file" && i+1 < len(os.Args) {
+ systemFile = os.Args[i+1]
+ content, err := os.ReadFile(systemFile)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(2)
+ }
+ systemPrompt = string(content)
+ info, _ := os.Stat(systemFile)
+ systemMode = info.Mode().Perm()
+ }
+ }
+ data, _ := json.Marshal(map[string]any{"args": os.Args[1:], "prompt": string(input), "cwd": cwd,
+ "system_prompt": systemPrompt, "system_file": systemFile, "system_mode": systemMode})
+ _ = os.WriteFile(capture, data, 0o600)
+ }
+ if os.Getenv("DROID_HANG") == "1" {
+ fmt.Println(`{"type":"system","subtype":"init","session_id":"ready"}`)
+ for {
+ time.Sleep(time.Hour)
+ }
+ }
+ if os.Getenv("DROID_OVERSIZED") == "1" {
+ fmt.Print(strings.Repeat("x", agentStreamMaxLineBytes+1))
+ for {
+ time.Sleep(time.Hour)
+ }
+ }
+ fmt.Print(os.Getenv("DROID_STREAM"))
+ if streamFile := os.Getenv("DROID_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("DROID_STDERR"))
+ if os.Getenv("DROID_HANG_AFTER_STREAM") == "1" {
+ fmt.Println(`{"type":"system","subtype":"init","session_id":"awaiting-exit"}`)
+ for {
+ time.Sleep(time.Hour)
+ }
+ }
+ if os.Getenv("DROID_FAIL") == "1" {
+ os.Exit(1)
+ }
+ os.Exit(0)
+}
+
+func newFakeDroid(t *testing.T, env map[string]string, logs io.Writer) Backend {
+ t.Helper()
+ executable, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ env["DROID_HELPER_PROCESS"] = "1"
+ backend, err := New("droid", Config{
+ ExecutablePath: executable, LaunchPrefix: []string{"-test.run=^TestDroidHelperProcess$"},
+ Env: env, Logger: slog.New(slog.NewTextHandler(logs, nil)),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return backend
+}
+
+func isolateDroidSystemPromptFiles(t *testing.T) {
+ t.Helper()
+ dir := t.TempDir()
+ for _, key := range []string{"TMPDIR", "TMP", "TEMP"} {
+ t.Setenv(key, dir)
+ }
+ t.Cleanup(func() {
+ files, err := filepath.Glob(filepath.Join(dir, "multica-droid-system-*"))
+ if err != nil || len(files) != 0 {
+ t.Errorf("system prompt files remain after execution: %v (error: %v)", files, err)
+ }
+ })
+}
+
+func collectDroid(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("Droid session did not terminate")
+ }
+ }
+ if !gotResult {
+ t.Fatal("Droid session returned no result")
+ }
+ return messages, result
+}
+
+func TestDroidArgumentsProtectProtocol(t *testing.T) {
+ args, err := buildDroidArgs(ExecOptions{
+ Model: "chosen", ResumeSessionID: "saved",
+ ExtraArgs: []string{"--output-format", "text", "--remove-tools", "WebSearch", "-otext", "-fother.md", "-mother", "-sother", "-wother"},
+ CustomArgs: []string{"-o=json", "--input-format", "stream-jsonrpc", "--cwd", "/other", "--model=other", "--session-id=other", "-f", "other.md", "--auto", "low", "--skip-permissions-unsafe", "--fork=other", "--worktree", "branch", "--mission", "--worker-model", "other", "--worker-reasoning-effort=high", "--validator-model=other", "--validator-reasoning-effort", "high", "--version", "-v", "--help", "--list-tools", "--reasoning-effort", "high"},
+ }, slog.Default())
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{"exec", "--output-format", "stream-json", "--auto", "high", "--model", "chosen", "--session-id", "saved", "--remove-tools", "WebSearch", "--reasoning-effort", "high"}
+ if !reflect.DeepEqual(args, want) {
+ t.Fatalf("args = %q, want %q", args, want)
+ }
+ if prefix := FilterLaunchPrefix("droid", []string{"wrapper", "--file", "override", "--output-format=json"}, nil); !reflect.DeepEqual(prefix, []string{"wrapper"}) {
+ t.Fatalf("unsafe launch prefix survived: %v", prefix)
+ }
+}
+
+func TestDroidArgumentsPreserveNativeConfiguration(t *testing.T) {
+ custom := []string{"--reasoning-effort", "high", "-rmedium", "--spec-model=custom:spec", "--spec-reasoning-effort", "low", "--use-spec",
+ "--only-tools", "Read,Edit", "--add-tools=WebSearch", "--remove-tools", "Execute", "--settings", "./settings.json",
+ "--disable-builtin-skills", "--tag", "nightly", "--tag=review", "--log-group-id", "automation"}
+ args, err := buildDroidArgs(ExecOptions{CustomArgs: custom}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(args[5:], custom) {
+ t.Fatalf("native configuration changed: %q", args)
+ }
+}
+
+func TestDroidRejectsCustomPromptOverrides(t *testing.T) {
+ for _, args := range [][]string{
+ {"replace the task"},
+ {"--", "replace the task"},
+ {"--reasoning-effort", "high", "replace the task"},
+ {"--unknown-option", "replace the task"},
+ {"--reasoning-effort"},
+ {"--settings", "--tag", "nightly"},
+ } {
+ t.Run(strings.Join(args, " "), func(t *testing.T) {
+ for _, useExtra := range []bool{false, true} {
+ backend := newFakeDroid(t, map[string]string{"DROID_STREAM": `{"type":"completion","finalText":"wrong task"}`}, io.Discard)
+ opts := ExecOptions{CustomArgs: args}
+ if useExtra {
+ opts.CustomArgs, opts.ExtraArgs = nil, args
+ }
+ session, err := backend.Execute(context.Background(), "assigned task", opts)
+ if err == nil {
+ collectDroid(t, session)
+ t.Fatal("custom arguments could replace the task prompt")
+ }
+ }
+ })
+ }
+}
+
+func TestDroidExecuteStreamAndPrompt(t *testing.T) {
+ capture := filepath.Join(t.TempDir(), "capture.json")
+ stream, err := os.ReadFile("testdata/droid-1.8.0-protocol-example.jsonl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ backend := newFakeDroid(t, map[string]string{"DROID_STREAM": string(stream), "DROID_CAPTURE": capture}, io.Discard)
+ cwd := t.TempDir()
+ prompt := strings.Repeat("Unicode 中文 \"quoted\" $(literal)\n", 10000)
+ session, err := backend.Execute(context.Background(), prompt, ExecOptions{Cwd: cwd, SystemPrompt: "instructions", Model: "selected", ResumeSessionID: "saved", Timeout: 10 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ messages, result := collectDroid(t, session)
+ if result.Status != "completed" || result.Output != "Final answer" || result.SessionID != "session-example" {
+ t.Fatalf("result = %+v", result)
+ }
+ if got := result.Usage["actual-model"]; got.InputTokens != 42 || got.OutputTokens != 9 || got.CacheReadTokens != 4 || got.CacheWriteTokens != 3 {
+ t.Fatalf("usage = %+v", result.Usage)
+ }
+ var toolUse, toolResult bool
+ for _, m := range messages {
+ toolUse = toolUse || m.Type == MessageToolUse && m.CallID == "call-1" && m.Tool == "Read" && m.Input["file_path"] == "README.md"
+ toolResult = toolResult || m.Type == MessageToolResult && m.CallID == "call-1" && m.Output == "File contents"
+ }
+ if !toolUse || !toolResult {
+ t.Fatalf("tool events not mapped: %+v", messages)
+ }
+ data, err := os.ReadFile(capture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got struct {
+ Args []string `json:"args"`
+ Prompt string `json:"prompt"`
+ Cwd string `json:"cwd"`
+ SystemPrompt string `json:"system_prompt"`
+ SystemFile string `json:"system_file"`
+ SystemMode os.FileMode `json:"system_mode"`
+ }
+ if err := json.Unmarshal(data, &got); err != nil {
+ t.Fatal(err)
+ }
+ wantCwd, _ := filepath.EvalSymlinks(cwd)
+ if got.Prompt != prompt || got.SystemPrompt != "instructions" || got.Cwd != wantCwd || strings.Contains(strings.Join(got.Args, " "), "$(literal)") || !strings.Contains(strings.Join(got.Args, " "), "--session-id saved") {
+ t.Fatalf("prompt, workdir, or resume was not forwarded correctly")
+ }
+ if got.SystemFile == "" {
+ t.Fatal("system prompt was not passed through Droid's native system prompt file")
+ }
+ if _, err := os.Stat(got.SystemFile); !os.IsNotExist(err) {
+ t.Fatalf("system prompt file remains after execution: %v", err)
+ }
+ if runtime.GOOS != "windows" && got.SystemMode != 0o600 {
+ t.Fatalf("system prompt permissions = %o, want 600", got.SystemMode)
+ }
+}
+
+func TestDroidFailurePaths(t *testing.T) {
+ for _, tc := range []struct{ name, stream, stderr, fail, want string }{
+ {"missing completion", `{"type":"message","role":"assistant","text":"partial"}`, "", "", "without terminal result"},
+ {"execution error", "{\"type\":\"error\",\"message\":\"Permission rejected\"}\n{\"type\":\"completion\",\"finalText\":\"partial\"}\n", "", "", "Permission rejected"},
+ {"error after completion", "{\"type\":\"completion\",\"finalText\":\"partial\"}\n{\"type\":\"error\",\"message\":\"Permission rejected\"}\n", "", "", "Permission rejected"},
+ {"authentication", `{"type":"error","source":"cli","message":"Authentication failed. Set FACTORY_API_KEY"}`, "", "1", "Authentication failed"},
+ {"crash", `{"type":"completion","finalText":"partial"}`, "Process crashed", "1", "Process crashed"},
+ {"invalid protocol", "not json\n", "", "", "without terminal result"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ isolateDroidSystemPromptFiles(t)
+ b := newFakeDroid(t, map[string]string{"DROID_STREAM": tc.stream, "DROID_STDERR": tc.stderr, "DROID_FAIL": tc.fail}, io.Discard)
+ s, err := b.Execute(context.Background(), "task", ExecOptions{SystemPrompt: "private instructions", ResumeSessionID: "keep-session", Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, r := collectDroid(t, s)
+ if r.Status != "failed" || r.Output != "" || !strings.Contains(r.Error, tc.want) || r.ResumeRejected || r.SessionID != "" {
+ t.Fatalf("result = %+v", r)
+ }
+ })
+ }
+}
+
+func TestDroidResumeSessionIDRequiresObservedSession(t *testing.T) {
+ for _, tc := range []struct{ name, stream, wantSession string }{
+ {"not loaded", `{"type":"error","message":"Could not load session"}`, ""},
+ {"loaded before failure", "{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"loaded-session\"}\n{\"type\":\"error\",\"message\":\"Provider failed\"}\n", "loaded-session"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ backend := newFakeDroid(t, map[string]string{"DROID_STREAM": tc.stream, "DROID_FAIL": "1"}, io.Discard)
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{ResumeSessionID: "stale-session", Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, result := collectDroid(t, session)
+ if result.Status != "failed" || result.SessionID != tc.wantSession || result.ResumeRejected {
+ t.Fatalf("result = %+v, want observed session %q without guessing rejection", result, tc.wantSession)
+ }
+ })
+ }
+}
+
+func TestDroidCompletionRequiresProcessExit(t *testing.T) {
+ backend := newFakeDroid(t, map[string]string{
+ "DROID_STREAM": "{\"type\":\"completion\",\"finalText\":\"premature\"}\n",
+ "DROID_HANG_AFTER_STREAM": "1",
+ }, io.Discard)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: 10 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-session.Messages: // Emitted after completion: the parser has read both.
+ case <-time.After(5 * time.Second):
+ t.Fatal("fake Droid did not reach completion")
+ }
+ if session.TerminalObserved() {
+ t.Error("completion became authoritative before the process exited")
+ }
+ cancel()
+ _, result := collectDroid(t, session)
+ if result.Status != "aborted" || result.Output != "" || session.TerminalObserved() {
+ t.Fatalf("completion without a clean process exit was accepted: %+v", result)
+ }
+}
+
+func TestDroidDrainsLargeFinalOutput(t *testing.T) {
+ final := strings.Repeat("final 中文\n", 100000)
+ event, err := json.Marshal(map[string]string{"type": "completion", "finalText": final})
+ if err != nil {
+ t.Fatal(err)
+ }
+ streamFile := filepath.Join(t.TempDir(), "stream.jsonl")
+ if err := os.WriteFile(streamFile, event, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ backend := newFakeDroid(t, map[string]string{"DROID_STREAM_FILE": streamFile}, io.Discard)
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 10 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, result := collectDroid(t, session)
+ if result.Status != "completed" || result.Output != final || !session.TerminalObserved() {
+ t.Fatalf("final output truncated or misclassified: status=%s bytes=%d error=%s", result.Status, len(result.Output), result.Error)
+ }
+}
+
+func TestDroidCancellationAndTimeout(t *testing.T) {
+ for _, timeout := range []bool{false, true} {
+ t.Run(fmt.Sprint("timeout=", timeout), func(t *testing.T) {
+ isolateDroidSystemPromptFiles(t)
+ b := newFakeDroid(t, map[string]string{"DROID_HANG": "1"}, io.Discard)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ opts := ExecOptions{SystemPrompt: "private instructions", Timeout: 5 * time.Second}
+ want := "aborted"
+ if timeout {
+ opts.Timeout = 500 * time.Millisecond
+ want = "timeout"
+ }
+ s, err := b.Execute(ctx, "task", opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-s.Messages:
+ case <-time.After(3 * time.Second):
+ t.Fatal("fake Droid never started")
+ }
+ if !timeout {
+ cancel()
+ }
+ _, r := collectDroid(t, s)
+ if r.Status != want || r.Output != "" || r.Error == "" {
+ t.Fatalf("result = %+v", r)
+ }
+ })
+ }
+}
+
+func TestDroidSecretsNeverReachResultsOrLogs(t *testing.T) {
+ const secret = "opaque-factory-credential"
+ const systemPrompt = "private system instructions"
+ isolateDroidSystemPromptFiles(t)
+ var logs bytes.Buffer
+ b := newFakeDroid(t, map[string]string{
+ "FACTORY_API_KEY": secret,
+ "DROID_STREAM": "{\"type\":\"message\",\"role\":\"assistant\",\"text\":\"" + secret + "\"}\n{\"type\":\"error\",\"message\":\"Authentication failed: " + secret + " fk-12345678901234567890\"}\n",
+ "DROID_STDERR": secret, "DROID_FAIL": "1",
+ }, &logs)
+ s, err := b.Execute(context.Background(), "task", ExecOptions{SystemPrompt: systemPrompt, Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ messages, r := collectDroid(t, s)
+ visible := fmt.Sprint(messages, r, logs.String())
+ if strings.Contains(visible, secret) || strings.Contains(visible, systemPrompt) || strings.Contains(visible, "fk-12345678901234567890") || !strings.Contains(visible, "REDACTED") {
+ t.Fatalf("credentials not scrubbed: %s", visible)
+ }
+}
+
+func TestDroidMissingExecutableAndUnsupportedMCP(t *testing.T) {
+ b, err := New("droid", Config{ExecutablePath: missingAgentExecutable(t, "droid")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.Execute(context.Background(), "task", ExecOptions{}); err == nil || !strings.Contains(err.Error(), "MULTICA_DROID_PATH") {
+ t.Fatalf("missing executable error = %v", err)
+ }
+ if _, err := b.Execute(context.Background(), "task", ExecOptions{McpConfig: json.RawMessage(`{"mcpServers":{"example":{"command":"example"}}}`)}); err == nil || !strings.Contains(err.Error(), "managed MCP") {
+ t.Fatalf("MCP error = %v", err)
+ }
+}
+
+func TestDroidStartFailureAndEmptyCompletion(t *testing.T) {
+ isolateDroidSystemPromptFiles(t)
+ b := newFakeDroid(t, map[string]string{"DROID_STREAM": "{\"type\":\"message\",\"role\":\"assistant\",\"text\":\"Interim narration\"}\n{\"type\":\"completion\",\"finalText\":\"\"}\n"}, io.Discard)
+ if _, err := b.Execute(context.Background(), "task", ExecOptions{SystemPrompt: "private instructions", Cwd: filepath.Join(t.TempDir(), "missing")}); err == nil || !strings.Contains(err.Error(), "start droid") {
+ t.Fatalf("start error = %v", err)
+ }
+ s, err := b.Execute(context.Background(), "task", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, r := collectDroid(t, s)
+ if r.Status != "completed" || r.Output != "" {
+ t.Fatalf("interim text became the answer: %+v", r)
+ }
+ if CheckMinVersion("droid", "0.150.1") == nil || CheckMinVersion("droid", "1.8.0") != nil {
+ t.Fatal("Droid protocol version gate is not enforced")
+ }
+ if !ResumeRejectionUndetectable("droid") {
+ t.Fatal("Droid must not guess resume rejections")
+ }
+}
+
+func TestDroidOversizedEventStopsProducer(t *testing.T) {
+ b := newFakeDroid(t, map[string]string{"DROID_OVERSIZED": "1"}, io.Discard)
+ session, err := b.Execute(context.Background(), "task", ExecOptions{Timeout: 10 * time.Second})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, result := collectDroid(t, session)
+ if result.Status != "failed" || result.Output != "" || !strings.Contains(result.Error, "stdout read error") {
+ t.Fatalf("protocol failure was misreported: %+v", result)
+ }
+}
diff --git a/server/pkg/agent/launch.go b/server/pkg/agent/launch.go
index b9cd17d0ca..53df7afa23 100644
--- a/server/pkg/agent/launch.go
+++ b/server/pkg/agent/launch.go
@@ -519,6 +519,7 @@ var launchPrefixBlockedArgs = map[string]map[string]blockedArgMode{
"qoderclicn": qoderBlockedArgs,
"qwen": qwenBlockedArgs,
"qwenpaw": qwenpawBlockedArgs,
+ "droid": droidBlockedArgs,
"reasonix": reasonixBlockedArgs,
"traecli": traecliBlockedArgs,
"dim": dimBlockedArgs,
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index cc690f127f..8f3ebe2de6 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -291,8 +291,8 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C
return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {
return discoverCodebuddyModels(ctx, runtimeCmd)
})
- case "qwen":
- // Qwen Code has no account-independent headless model catalog. An
+ case "qwen", "droid":
+ // Qwen Code and Droid use runtime defaults or manual model IDs. An
// empty list keeps the runtime default and manual model entry available
// without advertising a Token-Plan-specific model to other accounts.
return Catalog{Models: []Model{}}, nil
diff --git a/server/pkg/agent/testdata/droid-1.8.0-protocol-example.jsonl b/server/pkg/agent/testdata/droid-1.8.0-protocol-example.jsonl
new file mode 100644
index 0000000000..1142f6c890
--- /dev/null
+++ b/server/pkg/agent/testdata/droid-1.8.0-protocol-example.jsonl
@@ -0,0 +1,6 @@
+{"type":"system","subtype":"init","session_id":"session-example","model":"actual-model"}
+{"type":"message","role":"assistant","id":"message-1","text":"Interim narration","session_id":"session-example"}
+{"type":"tool_call","id":"call-1","messageId":"message-1","toolId":"Read","toolName":"Read","parameters":{"file_path":"README.md"},"session_id":"session-example"}
+{"type":"tool_result","id":"call-1","messageId":"message-2","toolId":"Read","value":"File contents","isError":false,"session_id":"session-example"}
+{"type":"message","role":"assistant","id":"message-3","text":"Final answer","session_id":"session-example"}
+{"type":"completion","finalText":"Final answer","numTurns":2,"durationMs":100,"session_id":"session-example","usage":{"input_tokens":42,"output_tokens":9,"cache_read_input_tokens":4,"cache_creation_input_tokens":3}}
diff --git a/server/pkg/agent/testdata/droid-1.8.0-protocol.md b/server/pkg/agent/testdata/droid-1.8.0-protocol.md
new file mode 100644
index 0000000000..5f784ea599
--- /dev/null
+++ b/server/pkg/agent/testdata/droid-1.8.0-protocol.md
@@ -0,0 +1,18 @@
+Protocol evidence for the Droid adapter
+
+See the [capability audit](droid-capability-audit.md) for the full official-documentation checklist, native argument policy, configuration boundaries, and remaining acceptance checks.
+
+- Official native macOS arm64 Droid 1.8.0, downloaded from Factory's release endpoint. SHA-256: `c8dd0da4d01cc8c08f4f441c183a22bcf713bef17e82d8ba7a77ffd7899d06bc`, matched the vendor checksum.
+- `droid exec --help` verified stdin prompt input, stream-json output, model selection, session continuation, and autonomy flags.
+- An unauthenticated read-only invocation emitted `system/init`, then `error` with `source: "cli"` and `message: "Error: Authentication failed. Please log in using /login or set a valid FACTORY_API_KEY environment variable."`, and exited 1.
+- `droid-1.8.0-protocol-example.jsonl` is a **synthetic example**, not a successful account-backed capture. Its field names were checked against the stream-json serializer in the official executable and the [official headless documentation](https://docs.factory.com/droid-exec/overview). In particular, tool events use `id`, `toolName`, `parameters`, `value`, `isError`; completion uses `finalText` and does not carry an error flag. Earlier `error` events must remain failures.
+- Successful account-backed execution, resume, and real tool execution remain unverified without a Factory credential. The opt-in `TestDroidRealTaskSmoke` reads a file using a tool, checks the response, then resumes the same session to verify memory. Its local attempt failed at authentication before tool execution. `TestDroidRealInvalidAuthentication` passed through the adapter with the official binary, verifying the failed status and an empty final output.
+- The daemon leaves `SystemPrompt` empty for Droid and writes its runtime brief to task `AGENTS.md`. The adapter's optional system-prompt file support is not used by daemon task dispatch. Native instruction discovery is still unverified: opt-in `TestDroidRealAgentsMDCanary` places a random marker only in `AGENTS.md`, passes no inline instructions or marker in the turn prompt, and requires an exact response without any tool calls. It has not been run with a Factory account.
+
+Run only with an explicitly authorized test account:
+
+```sh
+MULTICA_RUN_REAL_AGENT_SMOKE=1 MULTICA_DROID_PATH=/path/to/droid go test -tags=agentintegration ./pkg/agent -run '^TestDroidReal(AgentsMDCanary|TaskSmoke)$' -count=1 -v
+```
+
+These tests access the real CLI only after the `agentintegration` build tag and `MULTICA_RUN_REAL_AGENT_SMOKE=1` gate. Default tests use the test executable as a fake CLI and have no Factory account dependency.
diff --git a/server/pkg/agent/testdata/droid-capability-audit.md b/server/pkg/agent/testdata/droid-capability-audit.md
new file mode 100644
index 0000000000..2b10e47cd0
--- /dev/null
+++ b/server/pkg/agent/testdata/droid-capability-audit.md
@@ -0,0 +1,57 @@
+# Droid capability audit
+
+Checked on 2026-11-12 against the [CLI overview](https://docs.factory.com/droid-cli/overview), its linked harness guides, and the official native macOS arm64 Droid 1.8.0 `exec --help`. This audits the local one-shot Multica harness; it does not claim parity with the Factory app or account-backed acceptance. Version, checksum, and protocol provenance are recorded in [the protocol evidence](droid-1.8.0-protocol.md).
+
+“Delegated” means Multica preserves Droid's environment, working directory, and configuration discovery. The feature is implemented by Droid and has not been exercised with an authenticated account here. The fake CLI tests verify Multica's boundaries, not Factory's implementation.
+
+## Execution and configuration contract
+
+The following flag inventory was checked against the installed 1.8.0 help, rather than a hardcoded model list.
+
+| Capability / flags | Multica behavior | Evidence or boundary |
+| --- | --- | --- |
+| Installation, version, discovery | Optional native CLI, minimum 1.8.0; `MULTICA_DROID_PATH`, `_MODEL`, `_ARGS` | `internal/daemon/droid_test.go`; older 0.150.1 is rejected. Windows execution and Linux execution remain untested. |
+| Login / `FACTORY_API_KEY` | Existing execution-machine login or custom environment | Authentication failure is surfaced; keys are scrubbed from stream messages, results, stderr diagnostics, and command logs. No credentials were installed or changed. |
+| Prompt / `-f`, `--file`, positional arguments | Task prompt uses stdin; file overrides are filtered, extra positional prompts and unknown options fail before startup | Native option arity is validated. Large Unicode/quoted prompts and wrapper-descendant stdin delivery are tested. |
+| `-o`, `--output-format`, `--input-format` | Own one-shot `stream-json` output; alternate transports are filtered | Assistant, tool, init, completion, usage and error mapping use the synthetic protocol fixture. Output `stream-json` remains supported; deprecated input `stream-json` is not used. |
+| `--auto`, `--skip-permissions-unsafe` | Own `--auto high`; custom overrides filtered | This supports unattended coding. Droid's command policy still applies; a failed task may have edited files. |
+| `-m`, `--model` | Own model from Multica, otherwise Droid default | Opaque public/custom IDs are forwarded; no static model catalog or automatic Thinking picker is advertised. |
+| `-r`, `--reasoning-effort` | Custom arguments pass through | Native model validates compatibility; BYOK reasoning is provider-controlled. |
+| `--use-spec`, `--spec-model`, `--spec-reasoning-effort` | Custom arguments pass through | Native planning behavior is delegated, not a separate Multica planning UI. |
+| `--only-tools`, `--add-tools`, `--remove-tools` | Custom arguments pass through | Includes native MCP selectors; does not provision an MCP server. |
+| `--settings`, `--disable-builtin-skills` | Custom arguments pass through | No rewriting of user settings or disabling of native policy. |
+| `--tag`, `--log-group-id` | Custom arguments pass through, repeated tags retained | Native metadata, not Multica task identity. |
+| `-s`, `--session-id` | Own prior session from the daemon; only observed IDs returned by adapter | End-to-end daemon fixture tests a missing session, exactly one fresh retry, fresh failure, confirmed session, tool use, auth and network failures. |
+| `--fork` | Filtered | A new fork must not replace the daemon's continuation identity. |
+| `--cwd`, `-w`, `--worktree`, `--worktree-dir` | Filtered; daemon owns working directory / worktree | Prevents execution outside the prepared task environment. |
+| `--append-system-prompt`, `--append-system-prompt-file` | Custom overrides filtered; an adapter caller's explicit `ExecOptions.SystemPrompt` uses an owned private file | The daemon leaves this field empty for Droid and delivers its brief through task `AGENTS.md`. Adapter tests cover private mode and cleanup; they do not prove native instruction discovery. |
+| `--mission`, `--worker-model`, `--worker-reasoning-effort`, `--validator-model`, `--validator-reasoning-effort` | Filtered | Factory Mission orchestration is outside the current per-turn process and result contract. |
+| `--list-tools`, `-h`, `--help`, `-v`, `--version` | Filtered from task arguments | Exit-only invocations cannot replace the task protocol. Discovery/version probes are separate. |
+| Runtime wrappers / custom argument forms | Launch prefix preserved, protected flags filtered there too | Short attached values, equals forms, extra args and agent custom args covered by adapter/daemon tests. |
+| Terminal result, stderr, cancellation | Completion plus clean root exit required; errors remain sticky; owned pipes and bounded descendant cleanup | Fake-process regression tests include inherited stdout/stderr, late completion/errors, root nonzero exit, missing completion, oversized frames and cancellation after completion. |
+| `max_turns`, live supplements | Unsupported; use task timeout | No unsupported CLI option is invented. Persistent JSON-RPC/ACP requires a separate transport implementation. |
+
+Execution reference: [Droid Exec](https://docs.factory.com/droid-exec/overview). Installation and sign-in: [Quickstart](https://docs.factory.com/droid-cli/quickstart). Model identifiers and BYOK: [Models](https://docs.factory.com/models), [BYOK](https://docs.factory.com/model-independence/byok). Current model names and defaults are intentionally not copied into the adapter.
+
+## Every capability named by the CLI overview
+
+| Overview capability | Audit result |
+| --- | --- |
+| Terminal / editor / tests / Git workflow | Multica invokes headless exec in its task cwd. Tools are mapped to existing task events. TUI keyboard controls, bash mode, slash-command menus and IDE integration remain native surfaces, not a Multica terminal emulator. See [CLI reference](https://docs.factory.com/droid-cli/cli-reference). |
+| Repository context / `AGENTS.md` | The daemon delivers its brief through task `AGENTS.md`, without duplicate inline injection. Existing content and brief stability are covered by execution-environment tests. Gated `TestDroidRealAgentsMDCanary` checks native discovery with a random marker absent from the user prompt and no inline instructions or tools; account-backed execution remains pending. See [AGENTS.md](https://docs.factory.com/harness/agents-md). |
+| Skills | Multica injects project skills into `.factory/skills` and discovers personal skills there. Native compatibility locations, builtin/plugin skills and progressive loading remain delegated; Multica does not claim to enumerate all native sources. See [Skills](https://docs.factory.com/harness/skills). |
+| Custom Droids | Existing project/personal `.factory/droids` definitions remain delegated. A native Task subagent is not a separately registered Multica agent; no promise to stream every child session's events. See [Custom Droids](https://docs.factory.com/harness/subagents). |
+| MCP / connected knowledge | Native `.factory/mcp.json` discovery and pre-authenticated servers are delegated. Multica-managed MCP configuration fails explicitly instead of being ignored or overwriting native files. Interactive OAuth must be completed on the execution machine. See [MCP](https://docs.factory.com/harness/mcp). |
+| Hooks | Existing native lifecycle hooks remain delegated; Multica neither installs nor manages them. See [Hooks](https://docs.factory.com/harness/hooks). |
+| Plugins | Existing native plugin bundles remain delegated; no marketplace installation occurs during discovery. See [Plugins](https://docs.factory.com/harness/plugins). |
+| Missions | Not integrated; mission and dependent worker/validator flags are filtered together. See [Missions](https://docs.factory.com/missions/overview). |
+| Headless scripts / CI / structured output | Implemented through one exec process per task turn. No long-lived raw JSON-RPC, ACP or SDK bridge is claimed. See execution contract above. |
+| Plans, edits, tests and review | Native task behavior; a successful completion is not proof that a project's tests passed. Agent output and tool events carry that evidence. Actual successful tool use still requires the account-backed acceptance below. |
+
+Related configuration was also checked: [settings](https://docs.factory.com/droid-cli/settings), [permission rules](https://docs.factory.com/autonomy-and-safety/permission-rules), [output styles](https://docs.factory.com/droid-cli/output-styles), and [Sessions API](https://docs.factory.com/api-reference/sessions). Native user/project settings, policy, output styles and cloud-sync preferences remain user-controlled. The local harness does not call the cloud Sessions API or claim cross-machine transcript migration. `ask` policies can stop headless execution even with `--auto high`; block rules remain enforced.
+
+## Remaining acceptance and rollout
+
+- The success fixture is synthetic. No genuine successful run, native tool call, continuation, native MCP/hooks/plugins/subagents, or running-app Droid assignment has been verified with a Factory account. Native `AGENTS.md` loading is also unverified; a passing fake-CLI test is not a canary result. The earlier real attempt stopped at authentication. Keep PR #10399 in draft until a credential owner completes `TestDroidRealAgentsMDCanary`, `TestDroidRealTaskSmoke`, and the running-app acceptance described in the PR.
+- Default tests use fake executables, temporary homes and local HTTP fixtures. No shared database, Factory account, production resource or user configuration was changed by this audit.
+- Migration 652 follows the rebased main's 651. The down whitelist matches main's last runtime-family whitelist exactly. Apply the additive migration before saving Droid profiles; retain it when rolling application binaries back. Disable Droid assignments before downgrading the daemon.
diff --git a/server/pkg/agent/version.go b/server/pkg/agent/version.go
index 3a55b9b890..a14a00d02c 100644
--- a/server/pkg/agent/version.go
+++ b/server/pkg/agent/version.go
@@ -22,6 +22,7 @@ var MinVersions = map[string]string{
"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
+ "droid": "1.8.0", // native exec stream-json envelope verified against the official executable
"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
"muse": "1.4.10", // MSP stable surface: session/start, turn/start, item stream