Skip to content

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

Go

MUL-5959: feat(agent): add Dim (DimCode) ACP runtime (#6675)

scotarese1be1625cb3b
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index fb98f9ddaf..601a91c042 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -214,9 +214,11 @@ The daemon auto-detects these AI CLIs on your PATH:
| OpenClaw | `openclaw` | Open-source coding agent |
| Hermes | `hermes` | Nous Research coding agent |
| [Pi](https://pi.dev/) | `pi` | Pi coding agent |
+| Oh-My-Pi | `omp` | Oh-My-Pi coding agent (Pi fork) |
| [Cursor Agent](https://cursor.com/) | `cursor-agent` | Cursor's headless coding agent |
| Kimi | `kimi` | Moonshot coding agent |
| [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) | `reasonix` | DeepSeek-focused ACP coding agent (run `reasonix setup` first) |
+| Dim | `dim` | DimCode ACP coding agent (speaks the ACP protocol via `dim acp`) |
| Kiro CLI | `kiro-cli` | Kiro ACP coding agent |
| [Qoder CLI](https://docs.qoder.com/) | `qodercli` | Qoder ACP coding agent |
| [Qoder CN CLI](https://help.aliyun.com/en/lingma/qodercli-cn/product-overview/what-is-qoder-cli-cn) | `qoderclicn` | Qoder CN ACP coding agent |
@@ -318,6 +320,8 @@ Agent-specific overrides:
| `MULTICA_KIMI_MODEL` | Override the Kimi model used |
| `MULTICA_REASONIX_PATH` | Custom path to the `reasonix` binary |
| `MULTICA_REASONIX_MODEL` | Override the Reasonix model used |
+| `MULTICA_DIM_PATH` | Custom path to the `dim` binary |
+| `MULTICA_DIM_MODEL` | Override the Dim model used |
| `MULTICA_KIRO_PATH` | Custom path to the `kiro-cli` binary |
| `MULTICA_KIRO_MODEL` | Override the Kiro model used |
| `MULTICA_QODER_PATH` | Custom path to the `qodercli` binary |
@@ -344,7 +348,7 @@ The daemon launches Qwen Code as `qwen -p <prompt> --output-format stream-json`.
#### `mcp_config` on ACP runtimes
-ACP-family runtimes — Hermes, Kimi, Kiro, Grok, Qoder, Reasonix, Trae, QwenPaw, MiniMax Code, and any custom runtime profile whose `protocol_family` is one of them — receive MCP servers **over the ACP session protocol**, not through a config file. The daemon translates the agent's `mcp_config` into ACP's `McpServer` array and sends it with `session/new`, and again with that runtime's resume request (`session/resume` on Hermes, Kimi, Qoder and Reasonix; `session/load` on Kiro, Grok, Trae and QwenPaw) so a resumed task keeps the same tools. MiniMax Code 0.1.2 advertises no session-loading capability, so a later run falls back to a fresh session.
+ACP-family runtimes — Hermes, Kimi, Kiro, Grok, Qoder, Reasonix, Trae, QwenPaw, MiniMax Code, Dim, and any custom runtime profile whose `protocol_family` is one of them — receive MCP servers **over the ACP session protocol**, not through a config file. The daemon translates the agent's `mcp_config` into ACP's `McpServer` array and sends it with `session/new`, and again with that runtime's resume request (`session/resume` on Hermes, Kimi, Qoder and Reasonix; `session/load` on Kiro, Grok, Trae, QwenPaw and Dim) so a resumed task keeps the same tools. MiniMax Code 0.1.2 advertises no session-loading capability, so a later run falls back to a fresh session.
Nothing is written to the runtime's own config file, and the runtime's own file is not read or merged. `~/.hermes/…`, `~/.jcode/mcp.json` and the like stay untouched; an agent's servers travel with its tasks instead of being installed per machine.
diff --git a/README.md b/README.md
index 88e0eda6f7..199c1505ee 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@
Multica is an open-source workspace where you assign work to AI coding agents the way you'd
assign it to a teammate — they pick up the issue, report progress, raise blockers, and hand it
-back for review. Self-hostable, works with 20 agent CLIs, no lock-in.
+back for review. Self-hostable, works with 23 agent CLIs, no lock-in.
[![CI](https://github.com/multica-ai/multica/actions/workflows/ci.yml/badge.svg)](https://github.com/multica-ai/multica/actions/workflows/ci.yml)
[![Release](https://img.shields.io/github/v/release/multica-ai/multica?style=flat)](https://github.com/multica-ai/multica/releases)
@@ -52,7 +52,7 @@ issue — so nobody reconstructs context, and nothing ships without a human sayi
*Claude Code, Codex, Cursor, Kimi — you don't pick one. You hire them all.*
-- **[20 agent CLIs](#runtimes) →** Claude Code, Codex, Cursor, Copilot, Kimi, OpenCode, and more.
+- **[23 agent CLIs](#runtimes) →** Claude Code, Codex, Cursor, Copilot, Kimi, OpenCode, and more.
- **[Agents as teammates](https://multica.ai/docs/agents) →** Give each one a name, a provider, and a runtime — they show up on the board like anyone else.
- **[Squads](https://multica.ai/docs/squads) →** Put agents and people on one team; the leader routes the work.
- **[Skills](https://multica.ai/docs/skills) →** Turn a solved problem into a playbook every agent reuses.
@@ -163,6 +163,7 @@ authenticated, so switching providers is a dropdown, not a migration.
| Reasonix | `reasonix` | Trae CLI | `traecli` |
| DeepSeek Harness | `dsh` | Oh-My-Pi | `omp` |
| MiniMax Code | `mcode` | — | — |
+| Dim | `dim` | | |
Installing and authenticating them: [Install an agent runtime](https://multica.ai/docs/install-agent-runtime) ·
[Providers](https://multica.ai/docs/providers)
@@ -203,7 +204,7 @@ Installing and authenticating them: [Install an agent runtime](https://multica.a
│ spawns
┌──────┴───────────────────────────────┐
│ Claude Code · Codex · Cursor · … │
- │ (any of the 20 runtimes above) │
+ │ (any of the 23 runtimes above) │
└──────────────────────────────────────┘
```
@@ -214,7 +215,7 @@ Installing and authenticating them: [Install an agent runtime](https://multica.a
| Mobile | Expo / React Native (iOS) |
| Backend | Go (Chi router, sqlc, gorilla/websocket) |
| Database | PostgreSQL 17 with pgvector |
-| Agent runtime | Local daemon executing any of the 20 agent CLIs above |
+| Agent runtime | Local daemon executing any of the 23 agent CLIs above |
---
diff --git a/README.zh.md b/README.zh.md
index 144f0a769e..4499b2f788 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -11,7 +11,7 @@
**智能体,也在看板上。**
Multica 是一个开源的团队工作区。你像给同事派活一样,把任务交给 AI 编码智能体——它自己接手、边做边
-汇报、卡住了主动说,做完交回来给你审。可自部署,支持 20 种智能体 CLI,不绑定任何厂商。
+汇报、卡住了主动说,做完交回来给你审。可自部署,支持 23 种智能体 CLI,不绑定任何厂商。
[![CI](https://github.com/multica-ai/multica/actions/workflows/ci.yml/badge.svg)](https://github.com/multica-ai/multica/actions/workflows/ci.yml)
[![Release](https://img.shields.io/github/v/release/multica-ai/multica?style=flat)](https://github.com/multica-ai/multica/releases)
@@ -49,7 +49,7 @@ diff,全都挂在同一个任务下——没人需要重新捋一遍上下文
*Claude Code、Codex、Cursor、Kimi——不用挑一个,全都招进来。*
-- **[20 种智能体 CLI](#运行时) →** Claude Code、Codex、Cursor、Copilot、Kimi、OpenCode 等等。
+- **[23 种智能体 CLI](#运行时) →** Claude Code、Codex、Cursor、Copilot、Kimi、OpenCode 等等。
- **[智能体也是队友](https://multica.ai/docs/agents) →** 起个名字、选个提供方、配台运行时,它就上了看板,跟其他同事没两样。
- **[小队](https://multica.ai/docs/squads) →** 人和智能体混编成队,leader 决定谁来接活。
- **[Skills](https://multica.ai/docs/skills) →** 解决过一次的问题沉淀下来,全团队的智能体都能复用。
@@ -155,6 +155,7 @@ Multica 不自带模型。它驱动的是你本来就装好、登录好的那些
| Qwen Code | `qwen` | QwenPaw | `qwenpaw` |
| Reasonix | `reasonix` | Trae CLI | `traecli` |
| DeepSeek Harness | `dsh` | Oh-My-Pi | `omp` |
+| Dim | `dim` | | |
怎么装、怎么登录:[安装智能体运行时](https://multica.ai/docs/install-agent-runtime) ·
[AI 编程工具对照](https://multica.ai/docs/providers)
@@ -194,7 +195,7 @@ Multica 不自带模型。它驱动的是你本来就装好、登录好的那些
│ 拉起
┌──────┴───────────────────────────────┐
│ Claude Code · Codex · Cursor · … │
- │ (上面 20 种运行时里的任意一种) │
+ │ (上面 23 种运行时里的任意一种) │
└──────────────────────────────────────┘
```
@@ -205,7 +206,7 @@ Multica 不自带模型。它驱动的是你本来就装好、登录好的那些
| 移动端 | Expo / React Native (iOS) |
| 后端 | Go (Chi router, sqlc, gorilla/websocket) |
| 数据库 | PostgreSQL 17 + pgvector |
-| 智能体运行时 | 本地守护进程拉起上面 20 种智能体 CLI 中的任意一个 |
+| 智能体运行时 | 本地守护进程拉起上面 23 种智能体 CLI 中的任意一个 |
---
diff --git a/SELF_HOSTING.md b/SELF_HOSTING.md
index f8a3a61bab..89ad599cb3 100644
--- a/SELF_HOSTING.md
+++ b/SELF_HOSTING.md
@@ -122,6 +122,7 @@ You also need at least one AI agent CLI installed:
- [Cursor Agent](https://cursor.com/) (`cursor-agent` on PATH)
- Kimi (`kimi` on PATH)
- [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) (`reasonix` on PATH; run `reasonix setup` first)
+- Dim (`dim` on PATH)
- Kiro CLI (`kiro-cli` on PATH)
- Qoder CLI (`qodercli` on PATH)
- Qoder CN CLI (`qoderclicn` on PATH)
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 561aca00d6..7d6ebfb1ec 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -228,7 +228,7 @@ The variables below are read on the computer that runs your agents, not in the A
| `MULTICA_AGENT_TEMP_BASE` | `/tmp` (Linux/macOS) | Linux/macOS only. Parent directory for private per-task temp dirs; must be an existing, writable absolute directory, and an invalid value fails task startup instead of falling back to `/tmp`. Pick a short path — child tools may bind AF_UNIX sockets under it, and `sun_path` is limited to 108 bytes on Linux and 104 on macOS |
| `MULTICA_KEEP_ENV_AFTER_TASK` | `false` | Keep task directories for debugging |
-Each AI coding tool accepts `MULTICA_<PROVIDER>_PATH` and, when model overrides are supported, `MULTICA_<PROVIDER>_MODEL`. QwenPaw and MiniMax Code have no model variable because Multica never sends them a model; MiniMax Code's path variable is `MULTICA_MCODE_PATH` — see [AI coding tools comparison](/providers#model-sources). DeepSeek Harness supports `MULTICA_DSH_PATH` and `MULTICA_DSH_MODEL` (a model id from the dsh catalog, e.g. `deepseek-official/deepseek-chat`). Machine-wide default arguments via `MULTICA_<PROVIDER>_ARGS` are currently supported for five tools: Claude Code, Codex, CodeBuddy, Qwen Code, and QwenPaw. The variables are `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, and `MULTICA_QWENPAW_ARGS`. For example:
+Each AI coding tool accepts `MULTICA_<PROVIDER>_PATH` and `MULTICA_<PROVIDER>_MODEL` to override the command path and default model. QwenPaw and MiniMax Code have no model variable because Multica never sends them a model; MiniMax Code's path variable is `MULTICA_MCODE_PATH` — see [AI coding tools comparison](/providers#model-sources). DeepSeek Harness supports `MULTICA_DSH_PATH` and `MULTICA_DSH_MODEL` (a model id from the dsh catalog, e.g. `deepseek-official/deepseek-chat`). Dim supports `MULTICA_DIM_PATH` and `MULTICA_DIM_MODEL` (a model id from the dim catalog). Machine-wide default arguments via `MULTICA_<PROVIDER>_ARGS` are currently supported for five tools: Claude Code, Codex, CodeBuddy, Qwen Code, and QwenPaw. The variables are `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, and `MULTICA_QWENPAW_ARGS`. For example:
```dotenv
MULTICA_CLAUDE_PATH=/opt/bin/claude
diff --git a/apps/docs/content/docs/install-agent-runtime.ja.mdx b/apps/docs/content/docs/install-agent-runtime.ja.mdx
index be18dde68c..738ce2db38 100644
--- a/apps/docs/content/docs/install-agent-runtime.ja.mdx
+++ b/apps/docs/content/docs/install-agent-runtime.ja.mdx
@@ -38,6 +38,7 @@ Multica は現在、次のコマンドを検出します。
| QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |
| Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) |
| TRAE CLI | `traecli` | [TRAE 公式サイト](https://www.trae.cn/) |
+| Dim | `dim` | [DimCode](https://dimcode.ai) |
ここでの「対応」とは、Multica が該当する CLI を呼び出せるという意味です。そのツールのアカウント、サブスクリプション、モデルの利用枠を Multica が提供するわけではありません。
diff --git a/apps/docs/content/docs/install-agent-runtime.ko.mdx b/apps/docs/content/docs/install-agent-runtime.ko.mdx
index 8da6431300..86e730a4e4 100644
--- a/apps/docs/content/docs/install-agent-runtime.ko.mdx
+++ b/apps/docs/content/docs/install-agent-runtime.ko.mdx
@@ -38,6 +38,7 @@ Multica는 현재 다음 명령을 감지합니다.
| QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |
| Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) |
| TRAE CLI | `traecli` | [TRAE 공식 사이트](https://www.trae.cn/) |
+| Dim | `dim` | [DimCode](https://dimcode.ai) |
"지원됨"은 Multica가 해당 CLI를 호출할 수 있다는 뜻이며 Multica가 도구의 계정, 구독, 모델 사용량을 제공한다는 뜻은 아닙니다.
diff --git a/apps/docs/content/docs/install-agent-runtime.mdx b/apps/docs/content/docs/install-agent-runtime.mdx
index dc1ce88f51..e9a191ad93 100644
--- a/apps/docs/content/docs/install-agent-runtime.mdx
+++ b/apps/docs/content/docs/install-agent-runtime.mdx
@@ -38,6 +38,7 @@ Multica currently detects these commands:
| QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |
| Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) |
| TRAE CLI | `traecli` | [TRAE official site](https://www.trae.cn/) |
+| Dim | `dim` | [DimCode](https://dimcode.ai) |
"Supported" means Multica can invoke that CLI. It does not mean Multica provides the tool's account, subscription, or model quota for you.
diff --git a/apps/docs/content/docs/install-agent-runtime.zh.mdx b/apps/docs/content/docs/install-agent-runtime.zh.mdx
index d34b76f2e1..a29606da44 100644
--- a/apps/docs/content/docs/install-agent-runtime.zh.mdx
+++ b/apps/docs/content/docs/install-agent-runtime.zh.mdx
@@ -38,6 +38,7 @@ Multica 当前会检测以下命令:
| QwenPaw | `qwenpaw` | [QwenPaw](https://github.com/agentscope-ai/QwenPaw) |
| Reasonix | `reasonix` | [Reasonix](https://github.com/esengine/DeepSeek-Reasonix) |
| TRAE CLI | `traecli` | [TRAE 官方站](https://www.trae.cn/) |
+| Dim | `dim` | [DimCode](https://dimcode.ai) |
"受支持"表示 Multica 能够调用对应 CLI,不代表 Multica 会替你提供该工具的账号、订阅或模型额度。
diff --git a/apps/docs/content/docs/providers.ja.mdx b/apps/docs/content/docs/providers.ja.mdx
index 673894c418..91538bc743 100644
--- a/apps/docs/content/docs/providers.ja.mdx
+++ b/apps/docs/content/docs/providers.ja.mdx
@@ -43,6 +43,7 @@ Multica は、普段使っている AI コーディングツールの代わり
| QwenPaw | `qwenpaw` | ✓ | ✓ | 1 回の実行専用のワークスペース `skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | `.traecli/skills/` |
+| Dim | `dim` | ✓ | ✓ | — |
「Multica による MCP 管理」とは、エージェント設定に MCP server を入力し、Multica が実行前にその設定を対応ツールへ渡せることを意味します。そのツールにほかの MCP 設定方法がない、という意味ではありません。
diff --git a/apps/docs/content/docs/providers.ko.mdx b/apps/docs/content/docs/providers.ko.mdx
index ec24e5aa5b..312319440d 100644
--- a/apps/docs/content/docs/providers.ko.mdx
+++ b/apps/docs/content/docs/providers.ko.mdx
@@ -43,6 +43,7 @@ Multica는 사용 중인 AI 코딩 도구를 대체하지 않습니다. 런타
| QwenPaw | `qwenpaw` | ✓ | ✓ | 실행별 워크스페이스 `skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | `.traecli/skills/` |
+| Dim | `dim` | ✓ | ✓ | — |
"Multica의 MCP 관리"는 에이전트 설정에 MCP server를 입력하면 Multica가 실행 전에 해당 도구로 전달할 수 있다는 뜻입니다. 도구 자체에 다른 MCP 설정 방법이 없다는 뜻은 아닙니다.
diff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdx
index d40abcd1e9..82d22bf91c 100644
--- a/apps/docs/content/docs/providers.mdx
+++ b/apps/docs/content/docs/providers.mdx
@@ -43,6 +43,7 @@ Install steps are in [Install AI coding tools](/install-agent-runtime).
| QwenPaw | `qwenpaw` | ✓ | ✓ | per-task workspace `skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | `.traecli/skills/` |
+| Dim | `dim` | ✓ | ✓ | — |
"Multica-managed MCP" means you can define MCP servers in the agent configuration and Multica passes them to the tool before a run. It does not mean the tool has no other way to configure MCP.
diff --git a/apps/docs/content/docs/providers.zh.mdx b/apps/docs/content/docs/providers.zh.mdx
index 3275b56e02..744cbab199 100644
--- a/apps/docs/content/docs/providers.zh.mdx
+++ b/apps/docs/content/docs/providers.zh.mdx
@@ -43,6 +43,7 @@ Multica 不会替代你使用的 AI 编程工具。运行时会调用电脑上
| QwenPaw | `qwenpaw` | ✓ | ✓ | 单次执行的工作区 `skills/` |
| Reasonix | `reasonix` | ✓ | ✓ | `.reasonix/skills/` |
| Trae CLI | `traecli` | ✓ | ✓ | `.traecli/skills/` |
+| Dim | `dim` | ✓ | ✓ | — |
"Multica 管理 MCP" 表示你可以在智能体配置中填写 MCP server,由 Multica 在执行前传给对应工具。它不代表该工具本身没有其他 MCP 配置方式。
diff --git a/apps/web/features/landing/i18n/en.ts b/apps/web/features/landing/i18n/en.ts
index 6beec9f3c8..e5cc1954e2 100644
--- a/apps/web/features/landing/i18n/en.ts
+++ b/apps/web/features/landing/i18n/en.ts
@@ -101,7 +101,7 @@ export function createEnDict(allowSignup: boolean): LandingDict {
label: "RUNTIMES",
title: "One dashboard for all your compute",
description:
- "Local daemons and cloud runtimes, managed from a single panel. Real-time monitoring of online/offline status, usage charts, and activity heatmaps. Auto-detects 22 supported coding tools on your machine.",
+ "Local daemons and cloud runtimes, managed from a single panel. Real-time monitoring of online/offline status, usage charts, and activity heatmaps. Auto-detects 23 supported coding tools on your machine.",
cards: [
{
title: "Unified runtime panel",
@@ -116,7 +116,7 @@ export function createEnDict(allowSignup: boolean): LandingDict {
{
title: "Auto-detection on first run",
description:
- "Multica scans for 22 supported coding tools \u2014 Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, and Trae CLI \u2014 and registers a runtime for each one it finds.",
+ "Multica scans for 23 supported coding tools \u2014 Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Dim, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, and Trae CLI \u2014 and registers a runtime for each one it finds.",
},
],
},
@@ -136,7 +136,7 @@ export function createEnDict(allowSignup: boolean): LandingDict {
{
title: "Install the CLI & connect your machine",
description:
- "Run multica setup \u2014 it walks you through OAuth, starts the daemon, and scans for the 22 supported coding tools (Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI). Whichever ones you already have installed get registered as runtimes automatically.",
+ "Run multica setup \u2014 it walks you through OAuth, starts the daemon, and scans for the 23 supported coding tools (Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Dim, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI). Whichever ones you already have installed get registered as runtimes automatically.",
},
{
title: "Create your first agent",
@@ -192,7 +192,7 @@ export function createEnDict(allowSignup: boolean): LandingDict {
{
question: "What coding agents does Multica support?",
answer:
- "Multica supports 22 coding tools out of the box: Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, and Trae CLI. The daemon auto-detects whichever CLIs you already have installed and registers a runtime for each one. Since it's open source, you can also add your own backends.",
+ "Multica supports 23 coding tools out of the box: Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Dim, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, and Trae CLI. The daemon auto-detects whichever CLIs you already have installed and registers a runtime for each one. Since it's open source, you can also add your own backends.",
},
{
question: "Do I need to self-host, or is there a cloud version?",
diff --git a/apps/web/features/landing/i18n/ja.ts b/apps/web/features/landing/i18n/ja.ts
index 8eb442b556..ea41d7b40d 100644
--- a/apps/web/features/landing/i18n/ja.ts
+++ b/apps/web/features/landing/i18n/ja.ts
@@ -118,7 +118,7 @@ export function createJaDict(allowSignup: boolean): LandingDict {
{
title: "初回起動時に自動検出",
description:
- "Multica は Antigravity、Claude Code、CodeBuddy、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Grok、Hermes、Kimi、Kiro CLI、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI という22種類の対応ツールをスキャンし、見つかったものをそれぞれランタイムとして登録します。",
+ "Multica は Antigravity、Claude Code、CodeBuddy、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Dim、Grok、Hermes、Kimi、Kiro CLI、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI という23種類の対応ツールをスキャンし、見つかったものをそれぞれランタイムとして登録します。",
},
],
},
@@ -139,7 +139,7 @@ export function createJaDict(allowSignup: boolean): LandingDict {
{
title: "CLI をインストールしてマシンを接続",
description:
- "multica setup を実行すると、OAuth の手順を案内し、デーモンを起動し、22種類の対応コーディングツール(Antigravity、Claude Code、CodeBuddy、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Grok、Hermes、Kimi、Kiro CLI、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI)をスキャンします。すでにインストール済みのものは、自動的にランタイムとして登録されます。",
+ "multica setup を実行すると、OAuth の手順を案内し、デーモンを起動し、23種類の対応コーディングツール(Antigravity、Claude Code、CodeBuddy、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Dim、Grok、Hermes、Kimi、Kiro CLI、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI)をスキャンします。すでにインストール済みのものは、自動的にランタイムとして登録されます。",
},
{
title: "最初のエージェントを作成",
@@ -193,7 +193,7 @@ export function createJaDict(allowSignup: boolean): LandingDict {
{
question: "Multica はどのコーディングエージェントに対応していますか?",
answer:
- "Multica は、Antigravity、Claude Code、CodeBuddy、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Grok、Hermes、Kimi、Kiro CLI、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI の22種類のコーディングツールに標準対応しています。デーモンが、すでにインストール済みの CLI を自動検出し、それぞれをランタイムとして登録します。オープンソースなので、独自のバックエンドを追加することもできます。",
+ "Multica は、Antigravity、Claude Code、CodeBuddy、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Dim、Grok、Hermes、Kimi、Kiro CLI、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI の23種類のコーディングツールに標準対応しています。デーモンが、すでにインストール済みの CLI を自動検出し、それぞれをランタイムとして登録します。オープンソースなので、独自のバックエンドを追加することもできます。",
},
{
question: "セルフホストが必須ですか、それともクラウド版もありますか?",
diff --git a/apps/web/features/landing/i18n/ko.ts b/apps/web/features/landing/i18n/ko.ts
index b159192f75..1c4a7e1a9d 100644
--- a/apps/web/features/landing/i18n/ko.ts
+++ b/apps/web/features/landing/i18n/ko.ts
@@ -118,7 +118,7 @@ export function createKoDict(allowSignup: boolean): LandingDict {
{
title: "처음 실행할 때 자동 등록",
description:
- "Multica는 Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI 등 22개 지원 도구를 스캔해 이미 설치된 것을 런타임으로 자동 등록합니다.",
+ "Multica는 Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Dim, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI 등 23개 지원 도구를 스캔해 이미 설치된 것을 런타임으로 자동 등록합니다.",
},
],
},
@@ -193,7 +193,7 @@ export function createKoDict(allowSignup: boolean): LandingDict {
{
question: "Multica는 어떤 코딩 에이전트를 지원하나요?",
answer:
- "Multica는 Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI 등 22개 코딩 도구를 기본 지원합니다. 데몬이 이미 설치된 CLI를 자동으로 찾아 각각 런타임으로 등록합니다. 오픈소스이므로 직접 백엔드를 추가할 수도 있습니다.",
+ "Multica는 Antigravity, Claude Code, CodeBuddy, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Dim, Grok, Hermes, Kimi, Kiro CLI, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI 등 23개 코딩 도구를 기본 지원합니다. 데몬이 이미 설치된 CLI를 자동으로 찾아 각각 런타임으로 등록합니다. 오픈소스이므로 직접 백엔드를 추가할 수도 있습니다.",
},
{
question: "셀프 호스팅만 가능한가요, 클라우드 버전도 있나요?",
diff --git a/apps/web/features/landing/i18n/zh.ts b/apps/web/features/landing/i18n/zh.ts
index f4b6afa1b0..e882f6a5ca 100644
--- a/apps/web/features/landing/i18n/zh.ts
+++ b/apps/web/features/landing/i18n/zh.ts
@@ -101,7 +101,7 @@ export function createZhDict(allowSignup: boolean): LandingDict {
label: "\u8fd0\u884c\u65f6",
title: "\u4e00\u4e2a\u63a7\u5236\u53f0\u7ba1\u7406\u6240\u6709\u7b97\u529b",
description:
- "\u672c\u5730\u5b88\u62a4\u8fdb\u7a0b\u548c\u4e91\u7aef\u8fd0\u884c\u65f6\uff0c\u5728\u540c\u4e00\u4e2a\u9762\u677f\u4e2d\u7ba1\u7406\u3002\u5b9e\u65f6\u76d1\u63a7\u5728\u7ebf/\u79bb\u7ebf\u72b6\u6001\u3001\u4f7f\u7528\u91cf\u56fe\u8868\u548c\u6d3b\u52a8\u70ed\u529b\u56fe\u3002\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 22 \u6b3e\u652f\u6301\u7684 AI \u7f16\u7a0b\u5de5\u5177\u3002",
+ "\u672c\u5730\u5b88\u62a4\u8fdb\u7a0b\u548c\u4e91\u7aef\u8fd0\u884c\u65f6\uff0c\u5728\u540c\u4e00\u4e2a\u9762\u677f\u4e2d\u7ba1\u7406\u3002\u5b9e\u65f6\u76d1\u63a7\u5728\u7ebf/\u79bb\u7ebf\u72b6\u6001\u3001\u4f7f\u7528\u91cf\u56fe\u8868\u548c\u6d3b\u52a8\u70ed\u529b\u56fe\u3002\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 23 \u6b3e\u652f\u6301\u7684 AI \u7f16\u7a0b\u5de5\u5177\u3002",
cards: [
{
title: "\u7edf\u4e00\u8fd0\u884c\u65f6\u9762\u677f",
@@ -116,7 +116,7 @@ export function createZhDict(allowSignup: boolean): LandingDict {
{
title: "\u9996\u6b21\u542f\u52a8\u81ea\u52a8\u6ce8\u518c",
description:
- "Multica \u626b\u63cf\u672c\u673a\u7684 22 \u6b3e\u652f\u6301\u7684 AI \u7f16\u7a0b\u5de5\u5177\u2014\u2014Antigravity\u3001Claude Code\u3001CodeBuddy\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u2014\u2014\u5e76\u4e3a\u6bcf\u6b3e\u5df2\u5b89\u88c5\u7684\u5de5\u5177\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002",
+ "Multica \u626b\u63cf\u672c\u673a\u7684 23 \u6b3e\u652f\u6301\u7684 AI \u7f16\u7a0b\u5de5\u5177\u2014\u2014Antigravity\u3001Claude Code\u3001CodeBuddy\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Dim\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u2014\u2014\u5e76\u4e3a\u6bcf\u6b3e\u5df2\u5b89\u88c5\u7684\u5de5\u5177\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002",
},
],
},
@@ -136,7 +136,7 @@ export function createZhDict(allowSignup: boolean): LandingDict {
{
title: "\u5b89\u88c5 CLI \u5e76\u8fde\u63a5\u4f60\u7684\u673a\u5668",
description:
- "运行 multica setup——它会引导你完成 OAuth 登录、启动守护进程、并扫描 22 款支持的 AI 编程工具(Antigravity、Claude Code、CodeBuddy、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Grok、Hermes、Kimi、Kiro CLI、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI)。本机已安装的工具会被自动注册成运行时。",
+ "运行 multica setup——它会引导你完成 OAuth 登录、启动守护进程、并扫描 23 款支持的 AI 编程工具(Antigravity、Claude Code、CodeBuddy、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Dim、Grok、Hermes、Kimi、Kiro CLI、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI)。本机已安装的工具会被自动注册成运行时。",
},
{
title: "\u521b\u5efa\u4f60\u7684\u7b2c\u4e00\u4e2a 智能体",
@@ -192,7 +192,7 @@ export function createZhDict(allowSignup: boolean): LandingDict {
{
question: "Multica \u652f\u6301\u54ea\u4e9b\u7f16\u7801 智能体\uff1f",
answer:
- "Multica \u5f00\u7bb1\u5373\u7528\u652f\u6301 22 \u6b3e AI \u7f16\u7a0b\u5de5\u5177\uff1aAntigravity\u3001Claude Code\u3001CodeBuddy\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u3002\u5b88\u62a4\u8fdb\u7a0b\u4f1a\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 CLI \u5e76\u4e3a\u6bcf\u6b3e\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002\u56e0\u4e3a\u5f00\u6e90\uff0c\u4f60\u4e5f\u53ef\u4ee5\u81ea\u5df1\u6dfb\u52a0\u540e\u7aef\u3002",
+ "Multica \u5f00\u7bb1\u5373\u7528\u652f\u6301 23 \u6b3e AI \u7f16\u7a0b\u5de5\u5177\uff1aAntigravity\u3001Claude Code\u3001CodeBuddy\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Dim\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u3002\u5b88\u62a4\u8fdb\u7a0b\u4f1a\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 CLI \u5e76\u4e3a\u6bcf\u6b3e\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002\u56e0\u4e3a\u5f00\u6e90\uff0c\u4f60\u4e5f\u53ef\u4ee5\u81ea\u5df1\u6dfb\u52a0\u540e\u7aef\u3002",
},
{
question: "\u9700\u8981\u81ea\u6258\u7ba1\u5417\uff0c\u8fd8\u662f\u6709\u4e91\u7248\u672c\uff1f",
diff --git a/packages/core/agents/mcp-support.test.ts b/packages/core/agents/mcp-support.test.ts
index 83ebbbaf4b..21b6d7fb92 100644
--- a/packages/core/agents/mcp-support.test.ts
+++ b/packages/core/agents/mcp-support.test.ts
@@ -21,6 +21,7 @@ describe("providerSupportsMcpConfig", () => {
expect(providerSupportsMcpConfig("qwenpaw")).toBe(true);
expect(providerSupportsMcpConfig("traecli")).toBe(true);
expect(providerSupportsMcpConfig("grok")).toBe(true);
+ expect(providerSupportsMcpConfig("dim")).toBe(true);
expect(providerSupportsMcpConfig("mcode")).toBe(true);
});
diff --git a/packages/core/agents/mcp-support.ts b/packages/core/agents/mcp-support.ts
index d763b6d854..8961333c7a 100644
--- a/packages/core/agents/mcp-support.ts
+++ b/packages/core/agents/mcp-support.ts
@@ -24,6 +24,7 @@ const MCP_SUPPORTED_PROVIDERS = new Set([
"qwenpaw",
"mcode",
"traecli",
+ "dim",
]);
export function providerSupportsMcpConfig(provider: string | undefined | null): boolean {
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index b17edd6fc4..891b28043e 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -120,6 +120,7 @@ export const RUNTIME_PROFILE_PROTOCOL_FAMILIES = [
"kimi",
"reasonix",
"dsh",
+ "dim",
"kiro",
"antigravity",
"qoder",
diff --git a/packages/views/runtimes/components/dim-logo.png b/packages/views/runtimes/components/dim-logo.png
new file mode 100644
index 0000000000..dd717e1949
Binary files /dev/null and b/packages/views/runtimes/components/dim-logo.png differ
diff --git a/packages/views/runtimes/components/provider-logo.test.tsx b/packages/views/runtimes/components/provider-logo.test.tsx
index 77256c1a51..8e98972c0d 100644
--- a/packages/views/runtimes/components/provider-logo.test.tsx
+++ b/packages/views/runtimes/components/provider-logo.test.tsx
@@ -23,6 +23,17 @@ describe("ProviderLogo", () => {
expect(logo?.classList.contains("runtime-logo")).toBe(true);
});
+ it("renders the dedicated Dim mark", () => {
+ const { container } = render(<ProviderLogo provider="dim" className="runtime-logo" />);
+
+ const logo = container.querySelector("img");
+ const logoSrc = decodeURIComponent(logo?.getAttribute("src") ?? "");
+
+ expect(logo?.getAttribute("alt")).toBe("");
+ expect(logoSrc).toContain("dim-logo.png");
+ expect(logo?.classList.contains("runtime-logo")).toBe(true);
+ });
+
it("renders the dedicated Qwen Code mark", () => {
const { container } = render(<ProviderLogo provider="qwen" className="runtime-logo" />);
diff --git a/packages/views/runtimes/components/provider-logo.tsx b/packages/views/runtimes/components/provider-logo.tsx
index cb5cf5bbbc..695d354aab 100644
--- a/packages/views/runtimes/components/provider-logo.tsx
+++ b/packages/views/runtimes/components/provider-logo.tsx
@@ -2,6 +2,7 @@ import { useId } from "react";
import { Monitor } from "lucide-react";
import qwenLogo from "./qwen-logo.svg";
import reasonixLogo from "./reasonix-logo.svg";
+import dimLogo from "./dim-logo.png";
// Next.js exposes static imports as objects while Vite exposes URL strings.
// Normalize both shapes here so shared provider logos work in web and desktop.
@@ -337,6 +338,13 @@ function DshLogo({ className }: { className: string }) {
);
}
+// Dim (DimCode) — official app icon from the DimAgent desktop client
+// (/opt/DimAgent/resources/build/icon.png), resized to 128px for crisp
+// rendering at small sizes.
+function DimLogo({ className }: { className: string }) {
+ return <img src={staticAssetSrc(dimLogo)} alt="" aria-hidden className={className} />;
+}
+
export function ProviderLogo({
provider,
className = "h-4 w-4",
@@ -390,6 +398,8 @@ export function ProviderLogo({
return <McodeLogo className={className} />;
case "dsh":
return <DshLogo className={className} />;
+ case "dim":
+ return <DimLogo className={className} />;
default:
return <Monitor className={className} />;
}
diff --git a/scripts/agent-cli-command-names.txt b/scripts/agent-cli-command-names.txt
index 1340b2dccc..2887a0766b 100644
--- a/scripts/agent-cli-command-names.txt
+++ b/scripts/agent-cli-command-names.txt
@@ -5,19 +5,20 @@ codex
copilot
cursor-agent
deveco
+dim
dsh
grok
hermes
kimi
kiro-cli
+mcode
omp
openclaw
opencode
pi
-qwen
qodercli
qoderclicn
+qwen
+qwenpaw
reasonix
traecli
-qwenpaw
-mcode
diff --git a/server/internal/daemon/agents_probe.go b/server/internal/daemon/agents_probe.go
index dac64c6e6c..3efdabb80f 100644
--- a/server/internal/daemon/agents_probe.go
+++ b/server/internal/daemon/agents_probe.go
@@ -258,6 +258,12 @@ var probeAgentCLIs = func() map[string]AgentEntry {
if e, ok := probe("MULTICA_QWENPAW_PATH", "qwenpaw", ""); ok {
agents["qwenpaw"] = e
}
+ // Dim (`dim`) is the DimCode CLI agent, driven over ACP via `dim acp`.
+ // MULTICA_DIM_MODEL seeds the daemon-wide default (a model id from the
+ // user's logged-in dim catalog).
+ if e, ok := probe("MULTICA_DIM_PATH", "dim", "MULTICA_DIM_MODEL"); ok {
+ agents["dim"] = e
+ }
// MiniMax Code (`mcode`) exposes an ACP v1 server through `mcode acp`.
// Model selection is owned by the MCode runtime, so there is no model env.
if e, ok := probe("MULTICA_MCODE_PATH", "mcode", ""); ok {
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index 8c884d1961..e84fb88486 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -95,7 +95,7 @@ type Config struct {
CLIVersion string // multica CLI version (e.g. "0.1.13")
LaunchedBy string // "desktop" when spawned by the Electron app, empty for standalone
Profile string // profile name (empty = default)
- Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro, antigravity, qoder, qoderclicn, traecli, grok, qwen, qwenpaw, mcode (plus built-in runtime identities from agent.BuiltinRuntimes, e.g. omp)
+ Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro, antigravity, qoder, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, dim (plus built-in runtime identities from agent.BuiltinRuntimes, e.g. omp)
WorkspacesRoot string // base path for execution envs (default: ~/multica_workspaces)
KeepEnvAfterTask bool // preserve env after task for debugging
HealthPort int // local HTTP port for health checks (default: 19514)
@@ -240,7 +240,7 @@ func LoadConfig(overrides Overrides) (Config, error) {
// can re-run the same discovery on a live daemon (MUL-5439).
agents := probeAgentCLIs()
if len(agents) == 0 && !overrides.AllowNoAgents {
- return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codex, copilot, opencode, deveco, openclaw, hermes, pi, omp, cursor-agent, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, or mcode and ensure it is on PATH")
+ return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codex, copilot, opencode, deveco, openclaw, hermes, pi, omp, cursor-agent, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, or dim and ensure it is on PATH")
}
claudeArgs, err := shellArgsFromEnv("MULTICA_CLAUDE_ARGS")
@@ -832,7 +832,7 @@ func isExecutableFile(path string) bool {
// doesn't require editing this list by hand.
var defaultAgentCommandNames = append([]string{
"claude", "codex", "opencode", "deveco", "openclaw", "hermes",
- "pi", "cursor-agent", "copilot", "kimi", "reasonix", "dsh", "kiro-cli", "codebuddy", "agy", "qodercli", "qoderclicn", "traecli", "grok", "qwen", "qwenpaw", "mcode",
+ "pi", "cursor-agent", "copilot", "kimi", "reasonix", "dsh", "kiro-cli", "codebuddy", "agy", "qodercli", "qoderclicn", "traecli", "grok", "qwen", "qwenpaw", "mcode", "dim",
}, agent.BuiltinRuntimeCommands()...)
// codexDesktopAppBundlePaths returns candidate macOS app-bundle locations for
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.go
index 7f275bd70c..faad1ef6b5 100644
--- a/server/internal/daemon/execenv/execenv_test.go
+++ b/server/internal/daemon/execenv/execenv_test.go
@@ -1810,6 +1810,39 @@ func TestInjectRuntimeConfigAntigravity(t *testing.T) {
}
}
+// TestInjectRuntimeConfigDim verifies that the runtime brief is delivered to
+// Dim via AGENTS.md (review #1/#6). Dim reads AGENTS.md from the session cwd,
+// so InjectRuntimeConfig must write the brief there.
+func TestInjectRuntimeConfigDim(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+
+ ctx := TaskContextForEnv{
+ IssueID: "test-issue-id",
+ AgentSkills: []SkillContextForEnv{{Name: "Coding", Content: "Write good code."}},
+ }
+
+ if _, err := InjectRuntimeConfig(dir, "dim", ctx); err != nil {
+ t.Fatalf("InjectRuntimeConfig failed: %v", err)
+ }
+
+ content, err := os.ReadFile(filepath.Join(dir, "AGENTS.md"))
+ if err != nil {
+ t.Fatalf("failed to read AGENTS.md: %v", err)
+ }
+
+ s := string(content)
+ if !strings.Contains(s, "Multica Agent Runtime") {
+ t.Error("AGENTS.md missing meta skill header")
+ }
+ if !strings.Contains(s, "coding") {
+ t.Error("AGENTS.md missing skill name")
+ }
+ if !strings.Contains(s, "discovered automatically") {
+ t.Error("AGENTS.md for Dim should advertise native skill discovery")
+ }
+}
+
// TestWriteContextFilesAntigravityNativeSkills pins that skills for the
// antigravity provider land in {workDir}/.agents/skills/<slug>/, matching the
// CLI's native workspace discovery path (Gemini CLI lineage).
diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.go
index 1d48f19410..84ae34b1ba 100644
--- a/server/internal/daemon/execenv/runtime_config.go
+++ b/server/internal/daemon/execenv/runtime_config.go
@@ -214,7 +214,7 @@ func runtimeConfigPath(workDir, provider string) string {
return filepath.Join(workDir, "CODEBUDDY.md")
case "qwen":
return filepath.Join(workDir, "QWEN.md")
- case "codex", "copilot", "opencode", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "mcode":
+ case "codex", "copilot", "opencode", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "mcode", "dim":
return filepath.Join(workDir, "AGENTS.md")
default:
return ""
diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.go
index 407b0f5e87..1c1133ccbc 100644
--- a/server/internal/daemon/execenv/runtime_config_test.go
+++ b/server/internal/daemon/execenv/runtime_config_test.go
@@ -947,6 +947,7 @@ func TestInjectRuntimeConfigPreservesUserContent(t *testing.T) {
{"kimi", "AGENTS.md"},
{"reasonix", "AGENTS.md"},
{"dsh", "AGENTS.md"},
+ {"dim", "AGENTS.md"},
{"kiro", "AGENTS.md"},
{"antigravity", "AGENTS.md"},
{"qwen", "QWEN.md"},
@@ -1324,6 +1325,7 @@ func TestCleanupRuntimeConfigByProvider(t *testing.T) {
{"kimi", "AGENTS.md"},
{"reasonix", "AGENTS.md"},
{"dsh", "AGENTS.md"},
+ {"dim", "AGENTS.md"},
{"kiro", "AGENTS.md"},
{"antigravity", "AGENTS.md"},
{"qwen", "QWEN.md"},
diff --git a/server/internal/daemon/execenv/sidecar_manifest_test.go b/server/internal/daemon/execenv/sidecar_manifest_test.go
index c0ac86df9f..1d1a344623 100644
--- a/server/internal/daemon/execenv/sidecar_manifest_test.go
+++ b/server/internal/daemon/execenv/sidecar_manifest_test.go
@@ -156,6 +156,7 @@ var allFileBasedProviders = []string{
"kimi",
"reasonix",
"dsh",
+ "dim",
"kiro",
"antigravity",
"qwen",
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index 56db51f68e..83e398cf10 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -147,6 +147,8 @@ var (
"kiro": "kiro",
"kimi": "kimi",
"reasonix": "reasonix",
+ "dim": "dim",
+ "mcode": "mcode",
"multica_agent": "multica_agent",
"openclaw": "openclaw",
"opencode": "opencode",
diff --git a/server/internal/metrics/labels_test.go b/server/internal/metrics/labels_test.go
index 3246b2ac24..8b0402d248 100644
--- a/server/internal/metrics/labels_test.go
+++ b/server/internal/metrics/labels_test.go
@@ -23,6 +23,7 @@ func TestNormalizeRuntimeProviderRecognizesKnownProviders(t *testing.T) {
{input: "TraeCLI", want: "traecli"},
{input: "Reasonix", want: "reasonix"},
{input: "DSH", want: "dsh"},
+ {input: "Dim", want: "dim"},
}
for _, tt := range tests {
if got := NormalizeRuntimeProvider(tt.input); got != tt.want {
diff --git a/server/migrations/370_runtime_profile_add_dim.down.sql b/server/migrations/370_runtime_profile_add_dim.down.sql
new file mode 100644
index 0000000000..375f677689
--- /dev/null
+++ b/server/migrations/370_runtime_profile_add_dim.down.sql
@@ -0,0 +1,30 @@
+-- Restore the pre-370 whitelist (including mcode from migration 342).
+-- Existing Dim rows remain valid because the replacement constraint is NOT
+-- VALID, but new Dim profiles are blocked.
+ALTER TABLE runtime_profile DROP CONSTRAINT IF EXISTS runtime_profile_protocol_family_check;
+
+ALTER TABLE runtime_profile ADD CONSTRAINT runtime_profile_protocol_family_check
+ CHECK (protocol_family IN (
+ 'claude',
+ 'codebuddy',
+ 'codex',
+ 'copilot',
+ 'opencode',
+ 'openclaw',
+ 'hermes',
+ 'pi',
+ 'cursor',
+ 'kimi',
+ 'reasonix',
+ 'dsh',
+ 'kiro',
+ 'antigravity',
+ 'qoder',
+ 'qoderclicn',
+ 'traecli',
+ 'deveco',
+ 'grok',
+ 'qwen',
+ 'qwenpaw',
+ 'mcode'
+ )) NOT VALID;
diff --git a/server/migrations/370_runtime_profile_add_dim.up.sql b/server/migrations/370_runtime_profile_add_dim.up.sql
new file mode 100644
index 0000000000..aa732f874a
--- /dev/null
+++ b/server/migrations/370_runtime_profile_add_dim.up.sql
@@ -0,0 +1,31 @@
+-- Add Dim as a first-party ACP protocol family. NOT VALID preserves
+-- historical-row tolerance while enforcing the expanded whitelist for new rows.
+-- The whitelist includes dsh (added by migration 313) and dim.
+ALTER TABLE runtime_profile DROP CONSTRAINT IF EXISTS runtime_profile_protocol_family_check;
+
+ALTER TABLE runtime_profile ADD CONSTRAINT runtime_profile_protocol_family_check
+ CHECK (protocol_family IN (
+ 'claude',
+ 'codebuddy',
+ 'codex',
+ 'copilot',
+ 'opencode',
+ 'openclaw',
+ 'hermes',
+ 'pi',
+ 'cursor',
+ 'kimi',
+ 'reasonix',
+ 'dsh',
+ 'kiro',
+ 'antigravity',
+ 'qoder',
+ 'qoderclicn',
+ 'traecli',
+ 'deveco',
+ 'grok',
+ 'qwen',
+ 'qwenpaw',
+ 'mcode',
+ 'dim'
+ )) NOT VALID;
diff --git a/server/pkg/agent/acp_deliverable_test.go b/server/pkg/agent/acp_deliverable_test.go
index 8ebebc7409..38b50de8a3 100644
--- a/server/pkg/agent/acp_deliverable_test.go
+++ b/server/pkg/agent/acp_deliverable_test.go
@@ -167,6 +167,7 @@ var acpDeliverableCases = []acpDeliverableCase{
{backend: "hermes", binary: "hermes", notification: "session/update"},
{backend: "kimi", binary: "kimi", notification: "session/update"},
{backend: "reasonix", binary: "reasonix", notification: "session/update"},
+ {backend: "dim", binary: "dim", notification: "session/update"},
{backend: "traecli", binary: "traecli", notification: "session/update"},
{backend: "grok", binary: "grok", notification: "session/update"},
{backend: "mcode", binary: "mcode", notification: "session/update"},
@@ -224,7 +225,7 @@ while IFS= read -r line; do
id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
case "$line" in
*'"method":"initialize"'*)
- printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"authMethods":[{"id":"cached_token","name":"Cached login"},{"id":"xai.api_key","name":"API key"}],"agentCapabilities":{"loadSession":true}}}\n' "$id"
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"authMethods":[{"id":"cached_token","name":"Cached login"},{"id":"xai.api_key","name":"API key"}],"agentInfo":{"name":"fake","version":"0.3.10"},"agentCapabilities":{"loadSession":true}}}\n' "$id"
;;
*'"method":"authenticate"'*)
printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
@@ -232,6 +233,15 @@ while IFS= read -r line; do
*'"method":"session/new"'*)
printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_deliverable"}}\n' "$id"
;;
+ *'"method":"session/set_config_option"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
+ ;;
+ *'"method":"session/set_model"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
+ ;;
+ *'"method":"session/close"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
+ ;;
*'"method":"session/prompt"'*)
pre='` + acpDeliverableNarration + `'
if [ -n "$ACP_PRE_TOOL_TEXT" ]; then
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index fcf41f4ee1..27e5f72270 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -243,7 +243,7 @@ type Result struct {
// Config configures a Backend instance.
type Config struct {
- ExecutablePath string // path to CLI binary (claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode)
+ ExecutablePath string // path to CLI binary (claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, dim)
CLIVersion string // detected version paired with ExecutablePath; observation only, never used to choose behavior
Env map[string]string // extra environment variables
Logger *slog.Logger
@@ -320,6 +320,7 @@ var SupportedTypes = []string{
"qwen",
"qwenpaw",
"mcode",
+ "dim",
}
// IsSupportedType reports whether agentType is in the SupportedTypes whitelist.
@@ -402,6 +403,8 @@ func New(agentType string, cfg Config) (Backend, error) {
return &reasonixBackend{cfg: cfg}, nil
case "dsh":
return &dshBackend{cfg: cfg}, nil
+ case "dim":
+ return &dimBackend{cfg: cfg}, nil
case "kiro":
return &kiroBackend{cfg: cfg}, nil
case "antigravity":
@@ -461,6 +464,7 @@ var launchHeaders = map[string]string{
"grok": "grok agent stdio",
"qwen": "qwen -p (stream-json)",
"qwenpaw": "qwenpaw acp",
+ "dim": "dim acp",
"mcode": "mcode acp",
}
diff --git a/server/pkg/agent/agent_supported_types_test.go b/server/pkg/agent/agent_supported_types_test.go
index 8f59e73581..8a5637d9a4 100644
--- a/server/pkg/agent/agent_supported_types_test.go
+++ b/server/pkg/agent/agent_supported_types_test.go
@@ -41,6 +41,7 @@ func TestSupportedTypesMatchesMigrationWhitelist(t *testing.T) {
"opencode": true, "deveco": true, "openclaw": true, "hermes": true,
"pi": true, "cursor": true, "kimi": true, "reasonix": true, "dsh": true, "kiro": true, "antigravity": true,
"qoder": true, "qoderclicn": true, "traecli": true, "grok": true, "qwen": true, "qwenpaw": true, "mcode": true,
+ "dim": true,
}
if len(SupportedTypes) != len(want) {
t.Fatalf("SupportedTypes has %d entries, migration whitelist has %d; keep them in lockstep", len(SupportedTypes), len(want))
diff --git a/server/pkg/agent/dim.go b/server/pkg/agent/dim.go
new file mode 100644
index 0000000000..3aad72bf01
--- /dev/null
+++ b/server/pkg/agent/dim.go
@@ -0,0 +1,681 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "os/exec"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+)
+
+// dimBlockedArgs are flags hardcoded by the daemon that must not be
+// overridden by user-configured custom_args. `acp` is the protocol
+// subcommand that drives the ACP JSON-RPC transport; overriding it
+// would break the daemon↔Dim communication contract. `--auth-setup`
+// and `--remote` switch the CLI into modes that never start the ACP
+// server (interactive login / removed remote flow).
+var dimBlockedArgs = map[string]blockedArgMode{
+ "acp": blockedStandalone,
+ "--auth-setup": blockedStandalone,
+ "--remote": blockedStandalone,
+ "--help": blockedStandalone,
+ "-h": blockedStandalone,
+}
+
+// dimBackend implements Backend by spawning `dim acp` and
+// communicating via the standard ACP (Agent Client Protocol) JSON-RPC 2.0
+// over stdin/stdout.
+//
+// Dim (dimcode) exposes its agent loop over ACP through the `dim acp`
+// subcommand. The protocol surface matches the shared hermesClient ACP
+// transport used by Hermes/Kimi/Kiro/Traecli/QwenPaw — only the binary,
+// the session bootstrap, and the tool-name extraction differ.
+//
+// Notable contract with Dim's ACP server:
+// - `initialize` advertises no authMethods, so no `authenticate` step is
+// needed; the CLI uses the user's existing Dim OAuth login.
+// - `session/new` requires an absolute cwd (relative paths are rejected).
+// - The ACP server hardcodes a read-only permission preset at session
+// creation, which would silently deny every file write and process
+// spawn. The backend therefore issues `session/set_config_option`
+// (permission → full-access, mode → agent) right after session/new so
+// Multica agents can do real work. A resumed session retains these
+// settings across `session/load`, so set_config_option is re-applied on
+// both fresh and resumed sessions (idempotent). Model override is handled through the standard
+// `session/set_model` RPC; the model catalog is advertised by
+// `session/new` under models.availableModels / configOptions.
+// - `session/load` resumes a prior session across processes: dim 0.3.10+
+// releases its per-process session lock within ~5s of the owning process
+// exiting, so a follow-up run in a fresh `dim acp` process can continue
+// the conversation. Earlier 0.3.x builds bound sessions to the creating
+// process permanently; on those the load fails and ResumeRejected lets
+// the daemon retry fresh.
+// - Tool names are already lowercase ("write", "read", "exec"); the
+// shared kimiToolNameFromTitle normalisation keeps the UI identifiers
+// stable.
+type dimBackend struct {
+ cfg Config
+}
+
+var (
+ dimReaderDrainGrace = 2 * time.Second
+ dimNotificationQuietTime = 250 * time.Millisecond
+ // dimProcessWaitTimeout bounds how long the deferred cleanup waits for
+ // the child to exit after cancel+stdin-close before force-killing it. A
+ // child that ignores both should not be able to hang Result delivery.
+ dimProcessWaitTimeout = 5 * time.Second
+ // dimSessionCloseTimeout bounds the best-effort session/close sent before
+ // tearing down the process. It is deliberately short so a stuck close
+ // cannot delay Result delivery; the next run's session/load is still safe
+ // because dim releases the lock on its own after ~5s.
+ dimSessionCloseTimeout = 2 * time.Second
+ // dimSessionLoadRetryAttempts bounds the number of retries when
+ // session/load reports "held by another process" — the prior process's
+ // lock has not been released yet. With graceful session/close this is
+ // rare (the lock releases immediately), but a force-killed process can
+ // take up to ~5s. The retry loop covers that window instead of silently
+ // starting a fresh session and losing the conversation.
+ dimSessionLoadRetryAttempts = 3
+ dimSessionLoadRetryDelay = 2 * time.Second
+)
+
+// dimMinVersion is the minimum dim version that supports cross-run session
+// resume via session/load. Earlier builds bind sessions to the creating
+// process permanently.
+const dimMinVersion = "0.3.10"
+
+// extractACPAgentVersion pulls agentInfo.version out of an initialize
+// response. Returns "" if the field is absent (e.g. an older runtime that
+// does not report it).
+func extractACPAgentVersion(result json.RawMessage) string {
+ var resp struct {
+ AgentInfo struct {
+ Version string `json:"version"`
+ } `json:"agentInfo"`
+ }
+ if err := json.Unmarshal(result, &resp); err != nil {
+ return ""
+ }
+ return resp.AgentInfo.Version
+}
+
+// dimVersionSupported reports whether the dim version meets the minimum
+// required for cross-run session resume. Uses semver-ish comparison
+// (major.minor.patch). Fail-closed: an empty or non-parseable version is
+// rejected (returns false) rather than assumed supported, so a runtime that
+// cannot prove it is >= 0.3.10 is blocked from session resume (review #3).
+func dimVersionSupported(version string) bool {
+ version = strings.TrimPrefix(version, "v")
+ parts := strings.Split(version, ".")
+ if len(parts) < 3 {
+ return false // unparseable — fail-closed, do not assume supported
+ }
+ var maj, min, pat int
+ if _, err := fmt.Sscanf(parts[0], "%d", &maj); err != nil {
+ return false
+ }
+ if _, err := fmt.Sscanf(parts[1], "%d", &min); err != nil {
+ return false
+ }
+ // patch may have a suffix (e.g. "10-beta"); Sscanf stops at the first
+ // non-digit, which is what we want.
+ if _, err := fmt.Sscanf(parts[2], "%d", &pat); err != nil {
+ return false
+ }
+ var reqMaj, reqMin, reqPat int
+ fmt.Sscanf(dimMinVersion, "%d.%d.%d", &reqMaj, &reqMin, &reqPat)
+ if maj != reqMaj {
+ return maj > reqMaj
+ }
+ if min != reqMin {
+ return min > reqMin
+ }
+ return pat >= reqPat
+}
+
+// dimMessageStream serializes sends and the final close so a late stdout
+// reader cannot send on a closed channel. Mirrors grok/traecli/qoder.
+type dimMessageStream struct {
+ ch chan Message
+ mu sync.Mutex
+ closed bool
+}
+
+func newDimMessageStream(size int) *dimMessageStream {
+ return &dimMessageStream{ch: make(chan Message, size)}
+}
+
+func (s *dimMessageStream) send(msg Message) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.closed {
+ return
+ }
+ trySend(s.ch, msg)
+}
+
+func (s *dimMessageStream) close() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.closed {
+ return
+ }
+ s.closed = true
+ close(s.ch)
+}
+
+func (b *dimBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
+ execPath := b.cfg.ExecutablePath
+ if execPath == "" {
+ execPath = "dim"
+ }
+ if _, err := exec.LookPath(execPath); err != nil {
+ return nil, fmt.Errorf("dim executable not found at %q: %w", execPath, err)
+ }
+
+ // Translate the agent's mcp_config (Claude-style object of objects) into
+ // the array shape ACP session/new and session/load expect. Fail closed on
+ // malformed JSON so the launch surfaces the real error instead of silently
+ // dropping every MCP server.
+ mcpServers, err := buildACPMcpServers(opts.McpConfig, b.cfg.Logger)
+ if err != nil {
+ return nil, fmt.Errorf("dim: invalid mcp_config: %w", err)
+ }
+
+ timeout := opts.Timeout
+ runCtx, cancel := runContext(ctx, timeout)
+
+ dimArgs := append([]string{"acp"}, filterCustomArgs(opts.CustomArgs, dimBlockedArgs, b.cfg.Logger)...)
+
+ cmd := b.cfg.commandAt(execPath).exec(runCtx, dimArgs...)
+ hideAgentWindow(cmd)
+ configureProcessGroup(cmd)
+ // Take over context cancellation: the default would SIGKILL only the
+ // leader the instant runCtx is done, orphaning descendants. We instead
+ // drive a group-wide SIGKILL from the deferred cleanup below. Returning
+ // nil keeps os/exec from racing us with its own kill.
+ cmd.Cancel = func() error { return nil }
+ cmd.WaitDelay = 10 * time.Second
+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(dimArgs, trustAgentCommandPositional(0, "acp")))
+ if opts.Cwd != "" {
+ cmd.Dir = opts.Cwd
+ }
+ cmd.Env = buildEnv(b.cfg.Env)
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("dim stdout pipe: %w", err)
+ }
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("dim stdin pipe: %w", err)
+ }
+ // StderrPipe + an explicit copier give us a join point (`stderrDone`) that
+ // fires before the failure-promotion decision; see hermes.go for why the
+ // io.MultiWriter form races with stopReason=end_turn under load.
+ providerErr := newACPProviderErrorSniffer("dim")
+ stderr, err := cmd.StderrPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("dim stderr pipe: %w", err)
+ }
+
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
+ cancel()
+ return nil, fmt.Errorf("start dim: %w", err)
+ }
+
+ stderrSink := io.MultiWriter(newLogWriter(b.cfg.Logger, "[dim:stderr] "), providerErr)
+ stderrDone := make(chan struct{})
+ go func() {
+ defer close(stderrDone)
+ _, _ = io.Copy(stderrSink, stderr)
+ }()
+
+ b.cfg.Logger.Info("dim acp started", "pid", cmd.Process.Pid, "cwd", opts.Cwd)
+
+ msgStream := newDimMessageStream(256)
+ resCh := make(chan Result, 1)
+
+ // Dim streams interim narration and the final answer as the same
+ // agent_message_chunk type; the tracker keeps only the post-tool-call
+ // block for Result.Output while retaining the full text for error
+ // detection.
+ var deliverable acpDeliverableTracker
+
+ promptDone := make(chan hermesPromptResult, 1)
+ activity := make(chan struct{}, 1)
+
+ c := &hermesClient{
+ cfg: b.cfg,
+ stdin: stdin,
+ pending: make(map[int]*pendingRPC),
+ pendingTools: make(map[string]*pendingToolCall),
+ onActivity: func() {
+ select {
+ case activity <- struct{}{}:
+ default:
+ }
+ },
+ onMessage: func(msg Message) {
+ if msg.Type == MessageToolUse {
+ // Re-normalise tool titles the same way kimi/traecli do so the
+ // UI sees consistent snake_case names ("write" → "write_file").
+ msg.Tool = kimiToolNameFromTitle(msg.Tool)
+ }
+ deliverable.observe(msg)
+ msgStream.send(msg)
+ },
+ onPromptDone: func(result hermesPromptResult) {
+ select {
+ case promptDone <- result:
+ default:
+ }
+ },
+ }
+
+ readerDone := make(chan struct{})
+ go func() {
+ defer close(readerDone)
+ scanner := newAgentStreamScanner(stdout)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" {
+ continue
+ }
+ c.handleLine(line)
+ }
+ c.closeAllPending(fmt.Errorf("dim process exited"))
+ }()
+
+ go func() {
+ defer cancel()
+ defer msgStream.close()
+ defer close(resCh)
+ // Cleanup ordering matters: cancel the run context first so
+ // exec.CommandContext kills the child if it is still alive, THEN
+ // close stdin and wait. The previous order (stdin.Close → cmd.Wait →
+ // cancel) left cancel() unreachable when a child ignored stdin EOF
+ // and never exited, hanging cmd.Wait() forever and never closing
+ // resCh. cmd.Wait is bounded so a still-stuck child cannot block the
+ // final Result either.
+ defer func() {
+ // Signal the entire process group (the agent CLI plus any tool
+ // subprocesses it spawned) BEFORE closing stdin. exec.
+ // CommandContext's cancel is disabled (cmd.Cancel returns nil)
+ // so we own all signalling. If we close stdin first, the shell
+ // exits on EOF and its process group dissolves before we can
+ // SIGKILL the descendants, orphaning them to PPID=1.
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ cancel()
+ stdin.Close()
+ waitDone := make(chan struct{})
+ go func() { _ = cmd.Wait(); close(waitDone) }()
+ select {
+ case <-waitDone:
+ case <-time.After(dimProcessWaitTimeout):
+ }
+ waitProcessGroupGone(cmd, dimProcessWaitTimeout)
+ // Release the Windows Job Object ownership handle (no-op on Unix)
+ // so the OS can finalize any processes that were attached to it.
+ releaseProcessGroup(cmd)
+ }()
+
+ startTime := time.Now()
+ finalStatus := "completed"
+ var finalError string
+ var sessionID string
+ // Set when the ACP runtime refuses the session we asked to
+ // resume. Only that is curable by starting a fresh session, so
+ // handshake/network failures below must leave it false.
+ var resumeRejected bool
+ effectiveModel := strings.TrimSpace(opts.Model)
+
+ initResult, err := c.request(runCtx, "initialize", map[string]any{
+ "protocolVersion": 1,
+ "clientInfo": map[string]any{
+ "name": "multica-agent-sdk",
+ "version": "0.2.0",
+ },
+ "clientCapabilities": map[string]any{},
+ })
+ if err != nil {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("dim initialize failed: %v", err)
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
+ return
+ }
+
+ // Require dim >= 0.3.10 (fail-closed): earlier builds bind sessions to
+ // the creating process permanently, so cross-run session/load fails with
+ // "held by another process" and follow-up runs lose context. 0.3.10
+ // releases the lock on graceful exit (session/close) or after ~5s. A
+ // version that is empty or cannot be parsed is rejected rather than
+ // assumed supported, so a runtime that cannot prove it is >= 0.3.10 is
+ // blocked from session resume (review #3).
+ dimVersion := extractACPAgentVersion(initResult)
+ if !dimVersionSupported(dimVersion) {
+ finalStatus = "failed"
+ if dimVersion == "" {
+ finalError = "dim did not report an agent version: cross-run session resume requires dim >= 0.3.10 (0.3.10+ releases the per-process session lock on exit); please upgrade dimcode"
+ } else {
+ finalError = fmt.Sprintf("dim %s is too old: cross-run session resume requires dim >= 0.3.10 (0.3.10+ releases the per-process session lock on exit); please upgrade dimcode", dimVersion)
+ }
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
+ return
+ }
+
+ // Drop MCP entries whose remote transport the runtime didn't advertise.
+ // See hermes.go for why sending an unsupported transport tanks session/new.
+ mcpServers = filterACPMcpServersByCapability(mcpServers, extractACPMcpCapabilities(initResult), "dim", b.cfg)
+
+ cwd := opts.Cwd
+ if cwd == "" {
+ cwd = "."
+ }
+
+ // Dim (dimcode 0.3.10+) releases its per-process session lock within
+ // ~5s of the owning process exiting (graceful close or SIGTERM), so a
+ // follow-up run in a fresh `dim acp` process can resume the prior
+ // session via the standard ACP `session/load`. Earlier 0.3.x builds
+ // bound sessions to the creating process permanently; on those the
+ // load fails with "held by another process" and ResumeRejected lets
+ // the daemon retry on a fresh session.
+ //
+ // A loaded session retains its permission/mode config (verified: a
+ // full-access session stays full-access after load), but
+ // set_config_option is re-applied on both fresh and resumed sessions
+ // to guard against a partially configured session being resumed
+ // (review #4).
+ var freshSession bool
+ var sessionResult json.RawMessage
+ if opts.ResumeSessionID != "" {
+ // Retry session/load when the prior process's lock has not been
+ // released yet ("held by another process"). With graceful
+ // session/close the lock releases immediately, but a force-killed
+ // process can take up to ~5s. Retry instead of silently starting
+ // a fresh session and losing the conversation (review #1).
+ var result json.RawMessage
+ var loadErr error
+ loadRetry:
+ for attempt := 0; attempt <= dimSessionLoadRetryAttempts; attempt++ {
+ result, loadErr = c.request(runCtx, "session/load", map[string]any{
+ "cwd": cwd,
+ "sessionId": opts.ResumeSessionID,
+ "mcpServers": mcpServers,
+ })
+ if loadErr == nil {
+ break
+ }
+ if isACPSessionNotFound(loadErr) {
+ break // session is gone — no point retrying
+ }
+ if !isACPHeldByProcess(loadErr) {
+ break // different error — let the normal failure path handle it
+ }
+ if attempt < dimSessionLoadRetryAttempts {
+ b.cfg.Logger.Warn("dim session/load: lock not yet released, retrying",
+ "backend", "dim",
+ "attempt", attempt+1,
+ "delay", dimSessionLoadRetryDelay.String(),
+ )
+ select {
+ case <-time.After(dimSessionLoadRetryDelay):
+ case <-runCtx.Done():
+ loadErr = fmt.Errorf("dim session/load cancelled: %w", runCtx.Err())
+ break loadRetry
+ }
+ }
+ }
+ err := loadErr
+ if err != nil {
+ if isACPSessionNotFound(err) {
+ b.cfg.Logger.Warn("dim resumed session not found; the daemon will retry fresh",
+ "backend", "dim",
+ "requested_session", opts.ResumeSessionID,
+ )
+ resumeRejected = true
+ resCh <- Result{Status: "failed", Error: fmt.Sprintf("dim session/load: %v", err), DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}
+ return
+ }
+ if runCtx.Err() == context.DeadlineExceeded {
+ finalStatus = "timeout"
+ finalError = fmt.Sprintf("dim timed out during session/load: %v", timeout)
+ } else if runCtx.Err() == context.Canceled {
+ finalStatus = "aborted"
+ finalError = fmt.Sprintf("dim aborted: %v", err)
+ } else {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("dim session/load failed: %v", err)
+ }
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}
+ return
+ }
+ var changed bool
+ sessionID, changed = resolveResumedSessionID(opts.ResumeSessionID, result)
+ sessionResult = result
+ if changed {
+ b.cfg.Logger.Warn("dim returned a different session id on resume — original was likely lost; continuing with the new id",
+ "backend", "dim",
+ "requested", opts.ResumeSessionID,
+ "actual", sessionID,
+ )
+ }
+ if effectiveModel == "" {
+ effectiveModel = extractACPCurrentModelID(result)
+ }
+ } else {
+ freshSession = true
+ result, err := c.request(runCtx, "session/new", map[string]any{
+ "cwd": cwd,
+ "mcpServers": mcpServers,
+ })
+ if err != nil {
+ if runCtx.Err() == context.DeadlineExceeded {
+ finalStatus = "timeout"
+ finalError = fmt.Sprintf("dim timed out during session/new: %v", timeout)
+ } else if runCtx.Err() == context.Canceled {
+ finalStatus = "aborted"
+ finalError = fmt.Sprintf("dim aborted: %v", err)
+ } else {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("dim session/new failed: %v", err)
+ }
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}
+ return
+ }
+ sessionID = extractACPSessionID(result)
+ sessionResult = result
+ if sessionID == "" {
+ finalStatus = "failed"
+ finalError = "dim session/new returned no session ID"
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), ResumeRejected: resumeRejected}
+ return
+ }
+ if effectiveModel == "" {
+ effectiveModel = extractACPCurrentModelID(result)
+ }
+ }
+
+ c.sessionID = sessionID
+ // Early session pin so a cancelled run still preserves resume pointer.
+ msgStream.send(Message{Type: MessageStatus, Status: "running", SessionID: sessionID})
+ b.cfg.Logger.Info("dim session ready", "session_id", sessionID, "resumed", !freshSession)
+
+ // Dim's ACP server hardcodes a read-only permission preset at session
+ // creation. Raise it to full-access and pin agent mode. This runs on
+ // BOTH fresh and resumed sessions (review #4): a resumed session whose
+ // first run failed partway through config would carry a half-configured
+ // state into the resume. set_config_option is idempotent. On failure we
+ // close the session and abort.
+ for _, cfgOpt := range []struct {
+ id string
+ value string
+ }{
+ {"permission", "full-access"},
+ {"mode", "agent"},
+ } {
+ if _, err := c.request(runCtx, "session/set_config_option", map[string]any{
+ "sessionId": sessionID,
+ "configId": cfgOpt.id,
+ "value": cfgOpt.value,
+ }); err != nil {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("dim could not set session config %s=%s: %v", cfgOpt.id, cfgOpt.value, err)
+ // Best-effort close so a partially configured session is not
+ // left behind for the next resume to inherit.
+ closeCtx, closeCancel := context.WithTimeout(context.Background(), dimSessionCloseTimeout)
+ _, _ = c.request(closeCtx, "session/close", map[string]any{"sessionId": sessionID})
+ closeCancel()
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), SessionID: sessionID, ResumeRejected: resumeRejected}
+ return
+ }
+ b.cfg.Logger.Info("dim session config set", "config", cfgOpt.id, "value", cfgOpt.value, "session_id", sessionID)
+ }
+
+ if opts.Model != "" {
+ if _, err := c.request(runCtx, "session/set_model", map[string]any{
+ "sessionId": sessionID,
+ "modelId": opts.Model,
+ }); err != nil {
+ b.cfg.Logger.Warn("dim set_session_model failed", "error", err, "requested_model", opts.Model)
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("dim could not switch to model %q: %v", opts.Model, err)
+ // Close the session so a partially configured one (permission/mode
+ // set, model not) is not left for the next resume to inherit.
+ closeCtx, closeCancel := context.WithTimeout(context.Background(), dimSessionCloseTimeout)
+ _, _ = c.request(closeCtx, "session/close", map[string]any{"sessionId": sessionID})
+ closeCancel()
+ resCh <- Result{
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
+ }
+ return
+ }
+ b.cfg.Logger.Info("dim session model set", "model", opts.Model)
+ }
+
+ // Apply the thinking level (if any) via the ACP session config. Dim
+ // advertises a `thought_level` configOption in session/new (auto/high/
+ // max), so it joins the acpCatalogThinkingProviders list. The effort
+ // option may depend on the current model, so apply it after set_model.
+ applyACPEffortOption(runCtx, c.request, "dim", b.cfg.Logger,
+ sessionID, sessionResult, opts.ThinkingLevel, opts.Model == "")
+
+ userText := prompt
+ if opts.SystemPrompt != "" {
+ userText = opts.SystemPrompt + "\n\n---\n\n" + prompt
+ }
+
+ _, err = c.request(runCtx, "session/prompt", map[string]any{
+ "sessionId": sessionID,
+ "prompt": []map[string]any{
+ {"type": "text", "text": userText},
+ },
+ })
+ if err != nil {
+ if runCtx.Err() == context.DeadlineExceeded {
+ finalStatus = "timeout"
+ finalError = fmt.Sprintf("dim timed out after %s", timeout)
+ } else if runCtx.Err() == context.Canceled {
+ finalStatus = "aborted"
+ finalError = "execution cancelled"
+ } else {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("dim session/prompt failed: %v", err)
+ }
+ } else {
+ // Check if we got a promptDone result from the response parsing
+ // (non-blocking — the response is parsed synchronously during
+ // c.request, so promptDone is usually already ready).
+ select {
+ case pr := <-promptDone:
+ if pr.stopReason == "cancelled" {
+ finalStatus = "aborted"
+ finalError = "dim cancelled the prompt"
+ }
+ if effectiveModel == "" {
+ effectiveModel = pr.modelID
+ }
+ c.mergeUsage(pr.usage)
+ default:
+ }
+ // Give the stdout reader a bounded chance to consume notifications
+ // dim may emit just after session/prompt returns (agent_message_chunk,
+ // usage updates). Closing stdin at the response boundary otherwise
+ // races the reader and truncates the final text — the same race
+ // fixed for hermes (TestHermesBackendDrainsLateFinalNotification).
+ waitForACPNotificationQuiescence(runCtx, activity, readerDone, dimNotificationQuietTime, dimReaderDrainGrace)
+ }
+
+ duration := time.Since(startTime)
+ b.cfg.Logger.Info("dim finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
+
+ // Best-effort session/close before tearing down the process: it lets
+ // dim release the per-process session lock promptly (the next run can
+ // resume immediately) instead of waiting for the 5s idle-release
+ // timeout. Bounded and best-effort — a miss just means the next run
+ // waits up to 5s for the lock.
+ if sessionID != "" {
+ closeCtx, closeCancel := context.WithTimeout(context.Background(), dimSessionCloseTimeout)
+ _, _ = c.request(closeCtx, "session/close", map[string]any{"sessionId": sessionID})
+ closeCancel()
+ }
+
+ stdin.Close()
+ cancel()
+
+ // Dim's ACP server may keep the process — and the stdout/stderr
+ // pipes — open briefly after session/prompt returns. Bound the drain.
+ drainCtx, drainCancel := context.WithTimeout(context.Background(), dimReaderDrainGrace)
+ select {
+ case <-readerDone:
+ case <-drainCtx.Done():
+ }
+ select {
+ case <-stderrDone:
+ case <-drainCtx.Done():
+ }
+ drainCancel()
+
+ finalOutput, providerErrorOutput := deliverable.result()
+
+ // Promote completed→failed when stderr or the agent text stream show a
+ // terminal upstream-LLM failure (auth / rate-limit / HTTP 4xx). It reads
+ // the full text stream, not the deliverable, so a give-up turn that
+ // lands before a tool call stays visible.
+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)
+
+ u := c.accumulatedUsage()
+
+ var usageMap map[string]TokenUsage
+ if acpUsagePresent(u) {
+ model := effectiveModel
+ if model == "" {
+ model = "unknown"
+ }
+ usageMap = map[string]TokenUsage{model: u}
+ }
+
+ resCh <- Result{
+ Status: finalStatus,
+ Output: finalOutput,
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: sessionID,
+ ResumeRejected: resumeRejected,
+ Usage: usageMap,
+ }
+ }()
+
+ return &Session{Messages: msgStream.ch, Result: resCh}, nil
+}
diff --git a/server/pkg/agent/dim_integration_test.go b/server/pkg/agent/dim_integration_test.go
new file mode 100644
index 0000000000..970d2c6649
--- /dev/null
+++ b/server/pkg/agent/dim_integration_test.go
@@ -0,0 +1,211 @@
+//go:build agentintegration
+
+package agent
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestDimRealACPSmoke drives the real `dim acp` binary end-to-end.
+//
+// It validates the full daemon contract against a live Dim (dimcode) process:
+// - `dim acp` starts and responds to ACP RPCs (initialize, session/new)
+// - session/set_config_option (permission=full-access, mode=agent) succeeds
+// - session/prompt returns a completed turn
+// - the agent can actually write a file under the injected full-access
+// permission (the whole point of raising permission from the read-only
+// default) — a sentinel file is written and read back
+//
+// This test is gated by MULTICA_RUN_REAL_AGENT_SMOKE=1 and requires `dim`
+// on PATH with an active Dim OAuth login. The RPCs it exercises are the ones
+// the execution path needs, verified against dimcode 0.3.10.
+func TestDimRealACPSmoke(t *testing.T) {
+ requireRealAgentSmoke(t)
+ if testing.Short() {
+ t.Skip("skipping real-binary smoke test in -short mode")
+ }
+
+ // Discover `dim` binary on PATH.
+ path, err := exec.LookPath("dim")
+ if err != nil {
+ t.Skip("dim not on PATH; skipping real-binary smoke test")
+ }
+
+ // Log CLI version.
+ if version, err := exec.Command(path, "version").CombinedOutput(); err == nil {
+ t.Logf("dim version: %s", strings.TrimSpace(string(version)))
+ } else {
+ t.Logf("dim version unavailable: %v (%s)", err, strings.TrimSpace(string(version)))
+ }
+
+ backend, err := New("dim", Config{
+ ExecutablePath: path,
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new dim backend: %v", err)
+ }
+
+ cwd := t.TempDir()
+ sentinel := filepath.Join(cwd, "sentinel.txt")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
+ defer cancel()
+
+ // Prompt the agent to write a sentinel file under full-access. This is
+ // the real permission proof: the read-only default would deny both the
+ // command execution and the file write, so success confirms
+ // set_config_option landed for permission=full-access AND mode=agent.
+ session, err := backend.Execute(ctx,
+ "Use your shell/exec tool to run: echo dim-exec-ok > sentinel.txt — then reply with exactly: done",
+ ExecOptions{
+ Cwd: cwd,
+ Timeout: 100 * time.Second,
+ },
+ )
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+
+ // Drain messages in background.
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result := <-session.Result:
+ if result.Status != "completed" {
+ t.Fatalf("real dim run did not complete: status=%q error=%q", result.Status, result.Error)
+ }
+ if result.SessionID == "" {
+ t.Error("expected a non-empty session id from real dim")
+ }
+ // The hard proof: the sentinel file must exist with the expected
+ // content. A permission failure would leave it absent.
+ data, readErr := os.ReadFile(sentinel)
+ if readErr != nil {
+ t.Fatalf("sentinel file was not written (permission=full-access not effective): %v", readErr)
+ }
+ if !strings.Contains(string(data), "dim-exec-ok") {
+ t.Fatalf("sentinel file content unexpected: %q", string(data))
+ }
+ t.Logf("real dim smoke OK: session=%s output=%q sentinel=%q", result.SessionID, result.Output, strings.TrimSpace(string(data)))
+
+ case <-time.After(120 * time.Second):
+ t.Fatal("timeout waiting for real dim result")
+ }
+}
+
+// TestDimRealCrossRunResume verifies cross-run session continuity against a
+// real `dim acp`: run A establishes conversation context (a secret token),
+// then a fresh run B in a new process resumes that session via session/load
+// and must be able to recall the token. This is the regression review #2
+// requires: run B uses context established only in run A.
+//
+// dim 0.3.10+ releases its per-process session lock within ~5s of the owning
+// process exiting, so the resume succeeds once run A's process has torn down.
+// Gated by MULTICA_RUN_REAL_AGENT_SMOKE=1 and requires `dim` on PATH with an
+// active Dim OAuth login.
+func TestDimRealCrossRunResume(t *testing.T) {
+ requireRealAgentSmoke(t)
+ if testing.Short() {
+ t.Skip("skipping real-binary smoke test in -short mode")
+ }
+
+ path, err := exec.LookPath("dim")
+ if err != nil {
+ t.Skip("dim not on PATH; skipping real-binary smoke test")
+ }
+
+ backend, err := New("dim", Config{
+ ExecutablePath: path,
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new dim backend: %v", err)
+ }
+
+ cwd := t.TempDir()
+ secret := "ZEBRA-91337"
+
+ // Run A: establish context by telling the agent a secret token.
+ runCtxA, cancelA := context.WithTimeout(context.Background(), 120*time.Second)
+ defer cancelA()
+ sessionA, err := backend.Execute(runCtxA,
+ "Remember this secret token: "+secret+". Reply with exactly: ok",
+ ExecOptions{
+ Cwd: cwd,
+ Timeout: 100 * time.Second,
+ },
+ )
+ if err != nil {
+ t.Fatalf("run A execute: %v", err)
+ }
+ go func() {
+ for range sessionA.Messages {
+ }
+ }()
+ var sessionID string
+ select {
+ case result := <-sessionA.Result:
+ if result.Status != "completed" {
+ t.Fatalf("run A did not complete: status=%q error=%q", result.Status, result.Error)
+ }
+ sessionID = result.SessionID
+ if sessionID == "" {
+ t.Fatal("run A returned no session id; cannot resume")
+ }
+ t.Logf("run A OK: session=%s", sessionID)
+ case <-time.After(120 * time.Second):
+ t.Fatal("timeout waiting for run A result")
+ }
+
+ // Run B starts immediately: dim 0.3.10+ releases the per-process session
+ // lock instantly when the prior run sent session/close (graceful exit), so
+ // no sleep is needed. The bounded retry in the backend covers the rare
+ // case where the lock has not been released yet.
+ t.Logf("run B starting immediately after run A...")
+
+ // Run B: resume run A's session and ask for the secret. The token was
+ // only ever mentioned in run A, so a correct resume recalls it.
+ runCtxB, cancelB := context.WithTimeout(context.Background(), 120*time.Second)
+ defer cancelB()
+ sessionB, err := backend.Execute(runCtxB,
+ "What was the secret token I told you? Reply with exactly the token and nothing else.",
+ ExecOptions{
+ Cwd: cwd,
+ Timeout: 100 * time.Second,
+ ResumeSessionID: sessionID,
+ },
+ )
+ if err != nil {
+ t.Fatalf("run B execute: %v", err)
+ }
+ go func() {
+ for range sessionB.Messages {
+ }
+ }()
+ select {
+ case result := <-sessionB.Result:
+ if result.Status != "completed" {
+ t.Fatalf("run B did not complete: status=%q error=%q", result.Status, result.Error)
+ }
+ if result.ResumeRejected {
+ t.Fatal("run B reported ResumeRejected=true; session/load should have succeeded after the release window")
+ }
+ if !strings.Contains(result.Output, secret) {
+ t.Fatalf("run B did not recall the secret from run A: output=%q (expected to contain %q)", result.Output, secret)
+ }
+ t.Logf("run B OK: cross-run continuity confirmed, session=%s output=%q", result.SessionID, result.Output)
+ case <-time.After(120 * time.Second):
+ t.Fatal("timeout waiting for run B result")
+ }
+}
diff --git a/server/pkg/agent/dim_test.go b/server/pkg/agent/dim_test.go
new file mode 100644
index 0000000000..1096baae8c
--- /dev/null
+++ b/server/pkg/agent/dim_test.go
@@ -0,0 +1,788 @@
+package agent
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+)
+
+func TestNewReturnsDimBackend(t *testing.T) {
+ t.Parallel()
+ b, err := New("dim", Config{ExecutablePath: "/nonexistent/dim"})
+ if err != nil {
+ t.Fatalf("New(dim) error: %v", err)
+ }
+ if _, ok := b.(*dimBackend); !ok {
+ t.Fatalf("expected *dimBackend, got %T", b)
+ }
+}
+
+func TestDimModelSelectionSupported(t *testing.T) {
+ t.Parallel()
+ // Dim's session/set_model is session-scoped, so model override works.
+ if !ModelSelectionSupported("dim") {
+ t.Fatal("ModelSelectionSupported(dim) should return true")
+ }
+}
+
+// fakeDimACPScript impersonates `dim acp` for unit tests. Dim 0.3.10+
+// releases its per-process session lock shortly after the owning process
+// exits, so a follow-up run resumes via the standard ACP session/load. This
+// fake answers session/load with a resumed session (retaining the requested
+// id, matching the real server which does not echo sessionId on load). It
+// records every request line to DIM_REQUESTS_FILE so tests can assert which
+// RPCs were (and were not) sent.
+func fakeDimACPScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ if [ -n "$DIM_REQUESTS_FILE" ]; then
+ printf '%s\n' "$line" >> "$DIM_REQUESTS_FILE"
+ fi
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ if [ -n "$DIM_INIT_FAIL_HANG" ]; then
+ # Spawn a descendant BEFORE sending the error response, so the PID
+ # file is written before the backend's cleanup race begins. Then
+ # ignore TERM and hang so the process does not exit on stdin EOF —
+ # exercises the force-kill process-group cleanup path.
+ trap '' TERM
+ sleep 60 &
+ child_pid=$!
+ if [ -n "$DIM_CHILD_PID_FILE" ]; then
+ printf '%s' "$child_pid" > "$DIM_CHILD_PID_FILE"
+ fi
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"initialize failed"}}\n' "$id"
+ wait
+ else
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentInfo":{"name":"dimcode","version":"0.3.10"},"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":false}}}}\n' "$id"
+ fi
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_dim_new","models":{"availableModels":[{"modelId":"dim/model-a","name":"Model A"}],"currentModelId":"dim/model-a"}}}\n' "$id"
+ ;;
+ *'"method":"session/load"'*)
+ # The real dim ACP server resumes the session and returns configOptions
+ # (no sessionId field — the id is the one the client requested). When
+ # DIM_LOAD_NOT_FOUND is set, emulate a session that no longer exists so
+ # tests can exercise the ResumeRejected path. When DIM_LOAD_HELD_N is set,
+ # return "held by another process" for the first N calls then succeed,
+ # exercising the bounded retry loop.
+ if [ -n "$DIM_LOAD_NOT_FOUND" ]; then
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32002,"message":"ACP session not found","data":{"sessionId":"ses_prior"}}}\n' "$id"
+ elif [ -n "$DIM_LOAD_HELD_N" ]; then
+ held_file="${DIM_REQUESTS_FILE}_held_counter"
+ count=0
+ if [ -f "$held_file" ]; then count=$(cat "$held_file"); fi
+ if [ "$count" -lt "$DIM_LOAD_HELD_N" ]; then
+ count=$((count + 1))
+ echo "$count" > "$held_file"
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Session held by another process","data":{"details":"held"}}}\n' "$id"
+ else
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"configOptions":[{"id":"permission","currentValue":"full-access"},{"id":"mode","currentValue":"agent"}],"models":{"currentModelId":"dim/model-a"}}}\n' "$id"
+ fi
+ elif [ -n "$DIM_LOAD_HELD_ALWAYS" ]; then
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Session held by another process","data":{"details":"held"}}}\n' "$id"
+ else
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"configOptions":[{"id":"permission","currentValue":"full-access"},{"id":"mode","currentValue":"agent"}],"models":{"currentModelId":"dim/model-a"}}}\n' "$id"
+ fi
+ ;;
+ *'"method":"session/set_config_option"'*)
+ if [ -n "$DIM_CONFIG_FAIL_ONCE" ] && [ ! -f "$DIM_CONFIG_FAIL_ONCE" ]; then
+ printf '%s' x > "$DIM_CONFIG_FAIL_ONCE"
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"config set failed"}}\n' "$id"
+ elif [ -n "$DIM_CONFIG_FAIL" ]; then
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"config set failed"}}\n' "$id"
+ else
+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
+ fi
+ ;;
+ *'"method":"session/set_model"'*)
+ if [ -n "$DIM_MODEL_FAIL" ]; then
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"set_model failed"}}\n' "$id"
+ else
+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
+ fi
+ ;;
+ *'"method":"session/prompt"'*)
+ # When DIM_PROMPT_NO_STOP is set, omit stopReason so extractPromptResult
+ # never fires onPromptDone — exercises the bounded final-notification
+ # wait (the backend must still complete, not hang on a missing notify).
+ if [ -n "$DIM_PROMPT_NO_STOP" ]; then
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"usage":{"inputTokens":10,"outputTokens":20}}}\n' "$id"
+ elif [ -n "$DIM_LATE_NOTIFICATION" ]; then
+ # Return the prompt response, then emit a late agent_message_chunk
+ # notification after a short delay — exercises the notification
+ # quiescence drain (the late text must survive into Result.Output).
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":10,"outputTokens":20}}}\n' "$id"
+ sleep 0.1
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"%s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late-answer"}}}}\n' "$DIM_SESSION_ID"
+ else
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":10,"outputTokens":20}}}\n' "$id"
+ fi
+ ;;
+ *'"method":"session/close"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
+ ;;
+ *)
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"method not found"}}\n' "$id"
+ ;;
+ esac
+done
+`
+}
+
+func writeFakeDimScript(t *testing.T, requestsFile string) string {
+ t.Helper()
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "dim")
+ if err := os.WriteFile(bin, []byte(fakeDimACPScript()), 0o755); err != nil {
+ t.Fatalf("write fake dim: %v", err)
+ }
+ return bin
+}
+
+func newDimTestBackend(t *testing.T, requestsFile string) Backend {
+ t.Helper()
+ return newDimTestBackendWithEnv(t, requestsFile, nil)
+}
+
+func newDimTestBackendWithEnv(t *testing.T, requestsFile string, extra map[string]string) Backend {
+ t.Helper()
+ bin := writeFakeDimScript(t, requestsFile)
+ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
+ env := map[string]string{"DIM_REQUESTS_FILE": requestsFile}
+ for k, v := range extra {
+ env[k] = v
+ }
+ b, err := New("dim", Config{
+ ExecutablePath: bin,
+ Logger: logger,
+ Env: env,
+ })
+ if err != nil {
+ t.Fatalf("New(dim) error: %v", err)
+ }
+ return b
+}
+
+func readDimRequests(t *testing.T, path string) string {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read dim requests: %v", err)
+ }
+ return string(data)
+}
+
+// TestDimSessionNew verifies the happy path: initialize → session/new →
+// set_config_option(permission/mode) → prompt, with a fresh session.
+func TestDimSessionNew(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackend(t, requestsFile)
+
+ ctx := context.Background()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("expected status=completed, got %q (error=%q)", result.Status, result.Error)
+ }
+ if result.SessionID != "ses_dim_new" {
+ t.Fatalf("expected session id ses_dim_new, got %q", result.SessionID)
+ }
+
+ reqs := readDimRequests(t, requestsFile)
+ if strings.Contains(reqs, "session/load") {
+ t.Fatal("backend must not send session/load on a fresh-session run")
+ }
+ // The ACP server hardcodes read-only permission; the backend must raise
+ // it to full-access and pin agent mode before the prompt.
+ if !strings.Contains(reqs, `"configId":"permission"`) || !strings.Contains(reqs, `"value":"full-access"`) {
+ t.Fatal("expected set_config_option permission=full-access")
+ }
+ if !strings.Contains(reqs, `"configId":"mode"`) || !strings.Contains(reqs, `"value":"agent"`) {
+ t.Fatal("expected set_config_option mode=agent")
+ }
+ if !strings.Contains(reqs, "session/prompt") {
+ t.Fatal("expected session/prompt")
+ }
+ // The backend must send session/close during teardown so dim releases the
+ // per-process session lock immediately (graceful exit), enabling the next
+ // run to resume without delay.
+ if !strings.Contains(reqs, "session/close") {
+ t.Fatal("expected session/close during teardown")
+ }
+}
+
+// TestDimResumeLoadsSession verifies that when the daemon asks to resume a
+// prior session, the backend resumes it via the standard ACP session/load,
+// reuses the resumed session id, and re-issues set_config_option (fail-closed
+// against a partially configured session — review #4). ResumeRejected must
+// stay false because the resume succeeded.
+func TestDimResumeLoadsSession(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackend(t, requestsFile)
+
+ ctx := context.Background()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ ResumeSessionID: "ses_prior",
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("expected status=completed, got %q (error=%q)", result.Status, result.Error)
+ }
+ if result.SessionID != "ses_prior" {
+ t.Fatalf("expected the resumed session id ses_prior, got %q", result.SessionID)
+ }
+ if result.ResumeRejected {
+ t.Fatal("ResumeRejected must be false when session/load succeeded")
+ }
+
+ reqs := readDimRequests(t, requestsFile)
+ if !strings.Contains(reqs, "session/load") {
+ t.Fatal("expected a session/load when a resume was requested")
+ }
+ if strings.Contains(reqs, "session/new") {
+ t.Fatal("backend must not send session/new when the resume succeeded")
+ }
+ // A resumed session is re-issued set_config_option (permission/mode) to
+ // guard against a partially configured session being resumed — see
+ // review #4. So set_config_option MUST appear after a successful load.
+ if !strings.Contains(reqs, "set_config_option") {
+ t.Fatal("set_config_option must be re-applied on a resumed session (fail-closed)")
+ }
+}
+
+// TestDimResumeNotFound verifies that when session/load reports the prior
+// session is gone (ACP -32002 session not found), the backend fails with
+// ResumeRejected=true so the daemon retries on a fresh session instead of
+// silently losing the conversation.
+func TestDimResumeNotFound(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{"DIM_LOAD_NOT_FOUND": "1"})
+
+ ctx := context.Background()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ ResumeSessionID: "ses_prior",
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ result := <-session.Result
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q", result.Status)
+ }
+ if !result.ResumeRejected {
+ t.Fatal("expected ResumeRejected=true when session/load reports not found")
+ }
+
+ reqs := readDimRequests(t, requestsFile)
+ if !strings.Contains(reqs, "session/load") {
+ t.Fatal("expected a session/load attempt")
+ }
+ if strings.Contains(reqs, "session/new") {
+ t.Fatal("backend must not fall through to session/new itself; the daemon owns the fresh retry")
+ }
+}
+
+// TestDimCleanupKillsHangingChild verifies the deferred cleanup force-kills the
+// entire process group — not just the direct child — when a child ignores stdin
+// EOF and SIGTERM after an early RPC failure, so Result still closes AND no
+// descendant is orphaned (review #2/#3). Without the group force-kill,
+// cmd.Wait() would hang forever and the sleep descendant would survive as a
+// PPID=1 orphan.
+func TestDimCleanupKillsHangingChild(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ requestsFile := filepath.Join(dir, "requests.jsonl")
+ childPidFile := filepath.Join(dir, "child_pid")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{
+ "DIM_INIT_FAIL_HANG": "1",
+ "DIM_CHILD_PID_FILE": childPidFile,
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 20 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ // Result must close within a bounded window — the group force-kill
+ // (bounded by dimProcessWaitTimeout) guarantees the hung child cannot
+ // block it.
+ select {
+ case result := <-session.Result:
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed from the initialize error, got %q", result.Status)
+ }
+ case <-time.After(dimProcessWaitTimeout + 15*time.Second):
+ t.Fatal("Result never closed: the hanging child was not force-killed within the cleanup timeout")
+ }
+
+ // The descendant (sleep 60) must be gone too — not orphaned to PPID=1.
+ // Give the PID file a moment to appear (the child is spawned after the
+ // error response is written).
+ deadline := time.Now().Add(5 * time.Second)
+ var pidStr string
+ for time.Now().Before(deadline) {
+ data, err := os.ReadFile(childPidFile)
+ if err == nil && len(data) > 0 {
+ pidStr = string(data)
+ break
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ if pidStr == "" {
+ t.Fatal("child PID file was never written; the fake did not spawn a descendant")
+ }
+ childPid, err := strconv.Atoi(strings.TrimSpace(pidStr))
+ if err != nil {
+ t.Fatalf("invalid child PID %q: %v", pidStr, err)
+ }
+ // Verify the descendant is no longer alive. Poll briefly because the
+ // group SIGKILL and the kernel's process-table reaping are asynchronous
+ // with respect to Result delivery.
+ proc, err := os.FindProcess(childPid)
+ if err != nil {
+ return // already reaped
+ }
+ goneDeadline := time.Now().Add(3 * time.Second)
+ for time.Now().Before(goneDeadline) {
+ if err := proc.Signal(syscall.Signal(0)); err != nil {
+ return // process is gone
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ t.Fatalf("descendant PID %d is still alive after cleanup: process group was not reaped", childPid)
+}
+
+// TestDimPromptMissingNotificationStillCompletes verifies the success path
+// does not hang when the runtime returns session/prompt without a stopReason
+// (so onPromptDone never fires). The bounded final-notification wait must
+// fall through and let Result close (review #3 success-path race).
+func TestDimPromptMissingNotificationStillCompletes(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{"DIM_PROMPT_NO_STOP": "1"})
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 20 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result := <-session.Result:
+ // The turn completed (session/prompt returned ok); the missing
+ // stopReason only means no usage/stopReason was captured. Status must
+ // still be completed, not hang or fail.
+ if result.Status != "completed" {
+ t.Fatalf("expected status=completed, got %q (error=%q)", result.Status, result.Error)
+ }
+ case <-time.After(dimNotificationQuietTime + 15*time.Second):
+ t.Fatal("Result never closed: the missing prompt notification was not bounded by the quiet-time wait")
+ }
+}
+
+// TestDimDrainsLateFinalNotificationAfterPromptResponse verifies that a
+// notification arriving just after the session/prompt response is not lost —
+// the activity-based quiescence drain gives the stdout reader time to consume
+// it before stdin is closed (review #3, the Dim equivalent of
+// TestHermesBackendDrainsLateFinalNotificationAfterPromptResponse).
+func TestDimDrainsLateFinalNotificationAfterPromptResponse(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{
+ "DIM_LATE_NOTIFICATION": "1",
+ "DIM_SESSION_ID": "ses_dim_new",
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 15 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result := <-session.Result:
+ if result.Status != "completed" {
+ t.Fatalf("expected status=completed, got %q (error=%q)", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Output, "late-answer") {
+ t.Fatalf("late notification was lost: expected output to contain %q, got %q", "late-answer", result.Output)
+ }
+ case <-time.After(20 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
+// TestDimConfigFailClosesSession verifies that when set_config_option fails,
+// the backend sends session/close before returning the error, so a partially
+// configured session is not left for the next resume to inherit without
+// full-access (review #4).
+func TestDimConfigFailClosesSession(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{"DIM_CONFIG_FAIL": "1"})
+
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 15 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q", result.Status)
+ }
+
+ reqs := readDimRequests(t, requestsFile)
+ // set_config_option must have been attempted.
+ if !strings.Contains(reqs, "set_config_option") {
+ t.Fatal("expected a set_config_option attempt")
+ }
+ // session/close must have been sent to clean up the partially configured
+ // session so it is not resumed later without full-access.
+ if !strings.Contains(reqs, "session/close") {
+ t.Fatal("expected session/close after config failure to prevent a partially configured resume")
+ }
+}
+
+// TestDimConfigFailThenResumeReestablishes verifies the "first setup fails →
+// next run resumes" path (review #4): when the first run's set_config_option
+// fails, session/close is sent; a second run that resumes the same session
+// re-applies set_config_option (fail-closed) and succeeds.
+func TestDimConfigFailThenResumeReestablishes(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ requestsFile := filepath.Join(dir, "requests.jsonl")
+ failFlag := filepath.Join(dir, "config_failed")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{
+ "DIM_CONFIG_FAIL_ONCE": failFlag,
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ // Run A: fresh session, set_config_option fails on the first call.
+ sessionA, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 20 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("execute A: %v", err)
+ }
+ go func() {
+ for range sessionA.Messages {
+ }
+ }()
+ resultA := <-sessionA.Result
+ if resultA.Status != "failed" {
+ t.Fatalf("run A: expected status=failed, got %q", resultA.Status)
+ }
+ if resultA.SessionID == "" {
+ t.Fatal("run A: expected a session id despite the config failure")
+ }
+
+ // Run B: resume the same session. set_config_option should succeed this
+ // time (DIM_CONFIG_FAIL_ONCE only fails once) and the run should complete.
+ sessionB, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 20 * time.Second,
+ ResumeSessionID: resultA.SessionID,
+ })
+ if err != nil {
+ t.Fatalf("execute B: %v", err)
+ }
+ go func() {
+ for range sessionB.Messages {
+ }
+ }()
+ resultB := <-sessionB.Result
+ if resultB.Status != "completed" {
+ t.Fatalf("run B: expected status=completed, got %q (error=%q)", resultB.Status, resultB.Error)
+ }
+ if resultB.ResumeRejected {
+ t.Fatal("run B: ResumeRejected should be false — the session was loadable after session/close")
+ }
+
+ // Verify run B re-applied set_config_option (fail-closed on resume).
+ reqs := readDimRequests(t, requestsFile)
+ if !strings.Contains(reqs, "session/load") {
+ t.Fatal("run B: expected session/load")
+ }
+ // set_config_option should appear at least 3 times: 1 failed in run A,
+ // 2 successful in run B (permission + mode).
+ count := strings.Count(reqs, "set_config_option")
+ if count < 3 {
+ t.Fatalf("expected at least 3 set_config_option calls (1 fail + 2 re-apply on resume), got %d", count)
+ }
+}
+
+// TestDimVersionSupported pins the fail-closed version gate (review #3): only
+// a parseable semver >= 0.3.10 is accepted. Empty, non-parseable, and
+// too-short versions are rejected so a runtime that cannot prove it meets the
+// minimum is blocked from session resume.
+func TestDimVersionSupported(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ version string
+ want bool
+ }{
+ {"0.3.10", true},
+ {"0.3.9", false},
+ {"0.4.0", true},
+ {"1.0.0", true},
+ {"", false},
+ {"abc", false},
+ {"0.3", false},
+ }
+ for _, tc := range cases {
+ if got := dimVersionSupported(tc.version); got != tc.want {
+ t.Errorf("dimVersionSupported(%q) = %v, want %v", tc.version, got, tc.want)
+ }
+ }
+}
+
+// TestDimSetModelFailClosesSession verifies that when session/set_model fails,
+// the backend sends session/close before returning the error, so a partially
+// configured session (permission/mode set, model not) is not left for the next
+// resume to inherit (review #5).
+func TestDimSetModelFailClosesSession(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{"DIM_MODEL_FAIL": "1"})
+
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Model: "some-model",
+ Timeout: 15 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ if result.Status != "failed" {
+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)
+ }
+
+ reqs := readDimRequests(t, requestsFile)
+ // session/set_model must have been attempted with the requested model.
+ if !strings.Contains(reqs, "session/set_model") {
+ t.Fatal("expected a session/set_model attempt")
+ }
+ if !strings.Contains(reqs, `"modelId":"some-model"`) {
+ t.Fatal("expected session/set_model to carry the requested model id")
+ }
+ // session/close must have been sent to clean up the partially configured
+ // session (permission/mode set, model not) so it is not resumed later.
+ if !strings.Contains(reqs, "session/close") {
+ t.Fatal("expected session/close after set_model failure to prevent a partially configured resume")
+ }
+ // The prompt must NOT have been sent — the model switch failed, so the
+ // turn aborts before session/prompt.
+ if strings.Contains(reqs, "session/prompt") {
+ t.Fatal("backend must not send session/prompt after set_model failure")
+ }
+}
+
+// TestDimSessionLoadRetrySucceeds verifies that session/load retries on
+// "held by another process" and eventually succeeds (review #4 round 4).
+func TestDimSessionLoadRetrySucceeds(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{
+ "DIM_LOAD_HELD_N": "2", // held for first 2 calls, succeeds on 3rd
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 50 * time.Second,
+ ResumeSessionID: "ses_prior",
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("expected status=completed, got %q (error=%q)", result.Status, result.Error)
+ }
+ if result.ResumeRejected {
+ t.Fatal("ResumeRejected must be false — retry succeeded")
+ }
+
+ reqs := readDimRequests(t, requestsFile)
+ loadCount := strings.Count(reqs, "session/load")
+ if loadCount < 3 {
+ t.Fatalf("expected at least 3 session/load attempts (2 held + 1 success), got %d", loadCount)
+ }
+ if strings.Contains(reqs, "session/new") {
+ t.Fatal("backend must not fall through to session/new when retry succeeds")
+ }
+}
+
+// TestDimSessionLoadRetryExhausted verifies that after exhausting retries on
+// "held by another process", the backend fails without falling through to
+// session/new (review #4 round 4).
+func TestDimSessionLoadRetryExhausted(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{
+ "DIM_LOAD_HELD_ALWAYS": "1",
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 50 * time.Second,
+ ResumeSessionID: "ses_prior",
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ result := <-session.Result
+ if result.Status != "failed" && result.Status != "timeout" {
+ t.Fatalf("expected status=failed or timeout, got %q", result.Status)
+ }
+
+ reqs := readDimRequests(t, requestsFile)
+ loadCount := strings.Count(reqs, "session/load")
+ // dimSessionLoadRetryAttempts=3, so 1 initial + 3 retries = 4 attempts
+ if loadCount != 4 {
+ t.Fatalf("expected exactly 4 session/load attempts (1 + 3 retries), got %d", loadCount)
+ }
+ if strings.Contains(reqs, "session/new") {
+ t.Fatal("backend must not fall through to session/new when retries are exhausted")
+ }
+}
+
+// TestDimSessionLoadRetryCancelled verifies that cancelling the context during
+// the retry delay aborts the loop without falling through to session/new
+// (review #4 round 4).
+func TestDimSessionLoadRetryCancelled(t *testing.T) {
+ t.Parallel()
+ requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")
+ b := newDimTestBackendWithEnv(t, requestsFile, map[string]string{
+ "DIM_LOAD_HELD_ALWAYS": "1",
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test prompt", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 50 * time.Second,
+ ResumeSessionID: "ses_prior",
+ })
+ if err != nil {
+ t.Fatalf("Execute error: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ // Wait for the first session/load request to appear, then cancel during
+ // the retry delay — this is deterministic rather than a fixed sleep.
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ if _, err := os.Stat(requestsFile); err == nil {
+ data, _ := os.ReadFile(requestsFile)
+ if strings.Contains(string(data), "session/load") {
+ break
+ }
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ cancel()
+
+ result := <-session.Result
+ if result.Status != "failed" && result.Status != "aborted" && result.Status != "timeout" {
+ t.Fatalf("expected status=failed/aborted/timeout, got %q", result.Status)
+ }
+
+ reqs := readDimRequests(t, requestsFile)
+ if strings.Contains(reqs, "session/new") {
+ t.Fatal("backend must not fall through to session/new when cancelled during retry")
+ }
+}
diff --git a/server/pkg/agent/dim_windows_test.go b/server/pkg/agent/dim_windows_test.go
new file mode 100644
index 0000000000..c52939bac6
--- /dev/null
+++ b/server/pkg/agent/dim_windows_test.go
@@ -0,0 +1,76 @@
+//go:build windows
+
+package agent
+
+import (
+ "context"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+// TestDimBackendUsesOwnedProcessTree verifies that the Dim backend starts its
+// child process through startOwnedProcessTree (Job Object on Windows) rather
+// than a plain cmd.Start, so tool descendants are captured and terminated by
+// the cleanup. This is a Dim-specific companion to
+// TestStartOwnedProcessTreeCapturesImmediateDescendants (review round 4 #1).
+func TestDimBackendUsesOwnedProcessTree(t *testing.T) {
+ spawnerExe, pidPath := buildDescendantSpawner(t)
+
+ // Create a fake dim binary: a batch file that spawns the descendant
+ // spawner (which writes its PID to pidPath) and then hangs, mimicking a
+ // real dim acp process that spawns tool subprocesses.
+ dir := t.TempDir()
+ fakeDim := filepath.Join(dir, "dim.bat")
+ script := "@echo off\r\n\"" + spawnerExe + "\" spawn\r\n:loop\r\nping -n 60 127.0.0.1 >nul\r\ngoto loop\r\n"
+ if err := os.WriteFile(fakeDim, []byte(script), 0o644); err != nil {
+ t.Fatalf("write fake dim: %v", err)
+ }
+
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ b, err := New("dim", Config{
+ ExecutablePath: fakeDim,
+ Logger: logger,
+ })
+ if err != nil {
+ t.Fatalf("New(dim): %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ session, err := b.Execute(ctx, "test", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 20 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ // Wait for the descendant to be spawned by the fake dim.
+ descendantPid := waitForDescendantPid(t, pidPath)
+ if !processStillRunning(descendantPid) {
+ t.Fatalf("descendant %d was not running; the test cannot prove anything", descendantPid)
+ }
+
+ // Drain the result — the deferred cleanup should terminate the whole tree
+ // via the Job Object attached by startOwnedProcessTree.
+ <-session.Result
+
+ // The descendant must be gone — the Job Object captured and killed it.
+ // Give the OS a moment to reap.
+ goneDeadline := time.Now().Add(3 * time.Second)
+ for time.Now().Before(goneDeadline) {
+ if !processStillRunning(descendantPid) {
+ return // success
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ t.Fatalf("descendant PID %d survived Dim cleanup; the process tree was not owned by a Job Object", descendantPid)
+}
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.go
index c366bf1912..1bb14918f4 100644
--- a/server/pkg/agent/hermes.go
+++ b/server/pkg/agent/hermes.go
@@ -1258,7 +1258,7 @@ func isACPSessionNotFound(err error) bool {
if !errors.As(err, &rpcErr) {
return false
}
- if rpcErr.Code != -32603 && rpcErr.Code != -32602 {
+ if rpcErr.Code != -32603 && rpcErr.Code != -32602 && rpcErr.Code != -32002 {
return false
}
text := strings.ToLower(rpcErr.Message + " " + rpcErr.Data)
@@ -1267,6 +1267,19 @@ func isACPSessionNotFound(err error) bool {
strings.Contains(text, "unknown session")
}
+// isACPHeldByProcess reports whether a session/load error means the session
+// is still locked by a prior process that has not released it yet. Dim < 0.3.10
+// reports this permanently; 0.3.10+ releases on graceful exit or after ~5s.
+// The caller retries a bounded number of times before giving up.
+func isACPHeldByProcess(err error) bool {
+ var rpcErr *acpRPCError
+ if !errors.As(err, &rpcErr) {
+ return false
+ }
+ text := strings.ToLower(rpcErr.Message + " " + rpcErr.Data)
+ return strings.Contains(text, "held by another process")
+}
+
// hermesResumeLostError is the fallback reason for a resumed session Hermes
// could not rebuild, used only when nothing more specific was captured.
const hermesResumeLostError = "hermes could not restore the resumed session; it refused the turn without running the agent"
diff --git a/server/pkg/agent/launch.go b/server/pkg/agent/launch.go
index 223b04bcb8..898a73e7c4 100644
--- a/server/pkg/agent/launch.go
+++ b/server/pkg/agent/launch.go
@@ -321,6 +321,7 @@ var launchPrefixBlockedArgs = map[string]map[string]blockedArgMode{
"qwenpaw": qwenpawBlockedArgs,
"reasonix": reasonixBlockedArgs,
"traecli": traecliBlockedArgs,
+ "dim": dimBlockedArgs,
}
// FilterLaunchPrefix is the exported form for callers outside this package —
diff --git a/server/pkg/agent/launch_test.go b/server/pkg/agent/launch_test.go
index ede0bc767f..99fef998fa 100644
--- a/server/pkg/agent/launch_test.go
+++ b/server/pkg/agent/launch_test.go
@@ -131,7 +131,7 @@ func TestNewFiltersLaunchPrefixOnce(t *testing.T) {
func TestLaunchPrefixReachesACPFamilies(t *testing.T) {
t.Parallel()
- for _, family := range []string{"kimi", "hermes", "kiro", "reasonix", "qwenpaw"} {
+ for _, family := range []string{"kimi", "hermes", "kiro", "reasonix", "qwenpaw", "dim"} {
t.Run(family, func(t *testing.T) {
t.Parallel()
cfg := Config{LaunchPrefix: []string{"start", "q36"}, Logger: slog.Default()}
@@ -636,6 +636,31 @@ func TestFilterLaunchPrefixConsumesBlockedFlagValue(t *testing.T) {
}
}
+// TestDimLaunchPrefixFiltersBlockedFlags proves the Dim launch-prefix safety
+// policy: allowed positional tokens reach the command ahead of the hardcoded
+// `acp` subcommand, while protocol-breaking flags (--help, --auth-setup,
+// --remote, -h, acp) are stripped. Without this the fixed_args regression
+// this round fixed could return silently.
+func TestDimLaunchPrefixFiltersBlockedFlags(t *testing.T) {
+ t.Parallel()
+
+ // Allowed positional prefix tokens survive and precede `acp`.
+ cfg := Config{LaunchPrefix: []string{"start", "q36"}, Logger: slog.Default()}
+ argv := cfg.commandAt("wrapper").Argv("acp")
+ if idx := prefixIndex(argv, []string{"start", "q36", "acp"}); idx != 0 {
+ t.Fatalf("dim: allowed prefix must precede the acp subcommand, got %v", argv)
+ }
+
+ // Protocol-breaking flags are removed from the prefix.
+ got := filterLaunchPrefix(
+ []string{"start", "--help", "--auth-setup", "--remote", "-h", "q36"},
+ "dim", slog.Default())
+ want := []string{"start", "q36"}
+ if strings.Join(got, "\x00") != strings.Join(want, "\x00") {
+ t.Fatalf("dim: blocked flags must be stripped, got %v, want %v", got, want)
+ }
+}
+
// TestHermesLaunchArgvMatchesBackendAssembly is the root of the second-round
// Hermes finding: the daemon must resolve the profile from the argv the backend
// actually builds, not from a concatenation that leaves out `acp`.
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index 06b7ce1777..e009816a9e 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -254,6 +254,14 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C
return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {
return discoverGrokModels(ctx, runtimeCmd)
})
+ case "dim":
+ // Dim (dimcode) is ACP-native (`dim acp`); its model catalog is
+ // advertised by session/new under models.availableModels. Enumeration
+ // requires a logged-in dim (OAuth); on any failure fall back to an
+ // empty catalog so the UI keeps manual entry available.
+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {
+ return discoverDimModels(ctx, runtimeCmd)
+ })
default:
return Catalog{}, fmt.Errorf("unknown agent type: %q", providerType)
}
@@ -2566,3 +2574,23 @@ func codebuddyStaticModels() []Model {
{ID: "deepseek-v3-2-volc-ioa", Label: "Deepseek V3 2 Volc IOA", Provider: "deepseek"},
}
}
+
+// discoverDimModels enumerates the model catalog from a Dim ACP session/new
+// handshake. Dim (dimcode) advertises models.availableModels; enumeration
+// requires a logged-in dim (OAuth). On any failure the caller falls back to
+// the manual-entry field.
+func discoverDimModels(ctx context.Context, runtimeCmd Command) (Catalog, error) {
+ models, err := discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{
+ defaultBin: "dim",
+ clientName: "multica-model-discovery",
+ tmpdirPrefix: "multica-dim-discovery-",
+ acpArgs: []string{"acp"},
+ })
+ if err != nil || len(models) == 0 {
+ if err != nil {
+ slog.Debug("dim model discovery failed; falling back to manual entry", "error", err)
+ }
+ return Catalog{Models: []Model{}, Fallback: true}, nil
+ }
+ return Catalog{Models: models}, nil
+}
diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.go
index 32cdb7b3bb..f0a78b3859 100644
--- a/server/pkg/agent/models_test.go
+++ b/server/pkg/agent/models_test.go
@@ -1868,3 +1868,42 @@ func TestCachedDiscovery(t *testing.T) {
t.Errorf("expected 1 underlying call due to cache, got %d", calls)
}
}
+
+// TestDiscoveryCacheKeyIsolatesByExecutable verifies that two different
+// executable paths for the same provider type produce different cache keys,
+// so a built-in and a custom Dim-compatible executable do not serve each
+// other's model catalog during the TTL.
+func TestDiscoveryCacheKeyIsolatesByExecutable(t *testing.T) {
+ key1 := discoveryCacheKey("dim", Command{Path: "/usr/bin/dim"})
+ key2 := discoveryCacheKey("dim", Command{Path: "/opt/custom/dim"})
+ if key1 == key2 {
+ t.Fatalf("different executables must produce different cache keys: both %q", key1)
+ }
+ keyEmpty := discoveryCacheKey("dim", Command{Path: ""})
+ if keyEmpty != "dim" {
+ t.Fatalf("empty executable should fall back to provider type, got %q", keyEmpty)
+ }
+ if keyEmpty == key1 {
+ t.Fatal("empty executable key must differ from a non-empty executable key")
+ }
+
+ calls := 0
+ fn := func() (Catalog, error) {
+ calls++
+ return Catalog{Models: []Model{{ID: "m"}}}, nil
+ }
+ modelCacheMu.Lock()
+ delete(modelCache, key1)
+ delete(modelCache, key2)
+ modelCacheMu.Unlock()
+
+ if _, err := cachedDiscovery(key1, fn); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cachedDiscovery(key2, fn); err != nil {
+ t.Fatal(err)
+ }
+ if calls != 2 {
+ t.Errorf("expected 2 underlying calls (one per executable), got %d", calls)
+ }
+}
diff --git a/server/pkg/agent/thinking.go b/server/pkg/agent/thinking.go
index 688f5c6ad0..815e14b309 100644
--- a/server/pkg/agent/thinking.go
+++ b/server/pkg/agent/thinking.go
@@ -825,6 +825,8 @@ var acpCatalogThinkingProviders = map[string]bool{
// version string: one provider, two binaries, and the session answers the
// capability question directly.
"hermes": true,
+ // dim (dimcode 0.3.10+): session/new advertises thought_level.
+ "dim": true,
}
// usesDynamicThinkingCatalog reports whether a provider's effort vocabulary is
diff --git a/server/pkg/agent/version.go b/server/pkg/agent/version.go
index 605ff7cc4f..0995624d70 100644
--- a/server/pkg/agent/version.go
+++ b/server/pkg/agent/version.go
@@ -16,6 +16,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
+ "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
}
diff --git a/server/pkg/agent/version_test.go b/server/pkg/agent/version_test.go
index 14a871e2e3..3346364e8a 100644
--- a/server/pkg/agent/version_test.go
+++ b/server/pkg/agent/version_test.go
@@ -175,8 +175,14 @@ func TestCheckMinVersion(t *testing.T) {
{"qwen", "0.20.0", false},
{"qwen", "qwen 0.20.1", false},
{"qwen", "0.19.9", true},
+ {"dim", "0.3.10", false},
+ {"dim", "0.3.11", false},
+ {"dim", "0.4.0", false},
+ {"dim", "0.3.9", true},
{"mcode", "0.1.2", false},
{"mcode", "mcode 0.1.1", true},
+ {"dim", "0.2.99", true},
+ {"dim", "invalid", true},
{"unknown", "1.0.0", false},
}
for _, tt := range tests {