Skip to content

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

Go

feat(agent): add ByteDance TRAE CLI (traecli) as an ACP backend (#4724)

Xisheng Parker Zhao4b9ea4aa684d
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 0aea5e1537..29924109f1 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -150,6 +150,7 @@ The daemon auto-detects these AI CLIs on your PATH:
| Kimi | `kimi` | Moonshot coding agent |
| Kiro CLI | `kiro-cli` | Kiro ACP coding agent |
| [Qoder CLI](https://docs.qoder.com/) | `qodercli` | Qoder ACP coding agent |
+| [Trae](https://docs.trae.cn/cli) | `traecli` | ByteDance TRAE CLI (ACP via `traecli acp serve`) |
You need at least one installed. The daemon registers each detected CLI as an available runtime.
@@ -223,6 +224,8 @@ Agent-specific overrides:
| `MULTICA_KIRO_MODEL` | Override the Kiro model used |
| `MULTICA_QODER_PATH` | Custom path to the `qodercli` binary |
| `MULTICA_QODER_MODEL` | Override the Qoder model used |
+| `MULTICA_TRAECLI_PATH` | Custom path to the `traecli` binary |
+| `MULTICA_TRAECLI_MODEL` | Override the Trae model used (a model id from your logged-in traecli catalog, e.g. `Doubao-Seed-2.1-Pro`) |
The daemon launches Qoder as `qodercli --yolo --acp`, matching Qoder’s ACP “bypass permissions” mode so tool runs do not block on interactive approval in headless runs.
diff --git a/README.md b/README.md
index c26674451c..afba5732bd 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@ Turn coding agents into real teammates — assign tasks, track progress, compoun
Multica turns coding agents into real teammates. Assign issues to an agent like you'd assign to a colleague — they'll pick up the work, write code, report blockers, and update statuses autonomously.
-No more copy-pasting prompts. No more babysitting runs. Your agents show up on the board, participate in conversations, and compound reusable skills over time. Think of it as open-source infrastructure for managed agents — vendor-neutral, self-hosted, and designed for human + AI teams. Works with **Claude Code**, **Codex**, **GitHub Copilot CLI**, **OpenClaw**, **OpenCode**, **Hermes**, **Gemini**, **Pi**, **Cursor Agent**, **Kimi**, **Kiro CLI**, and **Qoder CLI**.
+No more copy-pasting prompts. No more babysitting runs. Your agents show up on the board, participate in conversations, and compound reusable skills over time. Think of it as open-source infrastructure for managed agents — vendor-neutral, self-hosted, and designed for human + AI teams. Works with **Claude Code**, **Codex**, **GitHub Copilot CLI**, **OpenClaw**, **OpenCode**, **Hermes**, **Gemini**, **Pi**, **Cursor Agent**, **Kimi**, **Kiro CLI**, **Qoder CLI**, and **Trae**.
For larger teams, Squads add a stable routing layer: assign work to a group led by an agent, and the leader delegates to the right member.
@@ -115,7 +115,7 @@ multica setup # Connect to Multica Cloud, log in, start daemon
multica setup # Configure, authenticate, and start the daemon
```
-The daemon runs in the background and auto-detects agent CLIs (`claude`, `codex`, `copilot`, `openclaw`, `opencode`, `hermes`, `gemini`, `pi`, `cursor-agent`, `kimi`, `kiro-cli`, `agy`, `qodercli`) on your PATH.
+The daemon runs in the background and auto-detects agent CLIs (`claude`, `codex`, `copilot`, `openclaw`, `opencode`, `hermes`, `gemini`, `pi`, `cursor-agent`, `kimi`, `kiro-cli`, `agy`, `qodercli`, `traecli`) on your PATH.
### 2. Verify your runtime
@@ -125,7 +125,7 @@ Open your workspace in the Multica web app. Navigate to **Settings → Runtimes*
### 3. Create an agent
-Go to **Settings → Agents** and click **New Agent**. Pick the runtime you just connected and choose a provider (Claude Code, Codex, GitHub Copilot CLI, OpenClaw, OpenCode, Hermes, Gemini, Pi, Cursor Agent, Kimi, Kiro CLI, Antigravity, or Qoder CLI). Give your agent a name — this is how it will appear on the board, in comments, and in assignments.
+Go to **Settings → Agents** and click **New Agent**. Pick the runtime you just connected and choose a provider (Claude Code, Codex, GitHub Copilot CLI, OpenClaw, OpenCode, Hermes, Gemini, Pi, Cursor Agent, Kimi, Kiro CLI, Antigravity, Qoder CLI, or Trae). Give your agent a name — this is how it will appear on the board, in comments, and in assignments.
### 4. Assign your first task
diff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdx
index 67492dda9d..49a627dbaa 100644
--- a/apps/docs/content/docs/providers.mdx
+++ b/apps/docs/content/docs/providers.mdx
@@ -1,11 +1,11 @@
---
title: AI coding tools matrix
-description: Multica supports 13 AI coding tools; they implement the same interface, but the capability details diverge significantly.
+description: Multica supports 14 AI coding tools; they implement the same interface, but the capability details diverge significantly.
---
import { Callout } from "fumadocs-ui/components/callout";
-Multica ships with built-in support for **13 AI coding tools**. They all implement the same interface — queue, dispatch, execute, return results — so you can drive any of them from the same Multica board. **But the capability details diverge significantly**: whether session resumption actually works, whether MCP is supported, where skill files live, how models are selected. This page is the full matrix.
+Multica ships with built-in support for **14 AI coding tools**. They all implement the same interface — queue, dispatch, execute, return results — so you can drive any of them from the same Multica board. **But the capability details diverge significantly**: whether session resumption actually works, whether MCP is supported, where skill files live, how models are selected. This page is the full matrix.
For guidance on picking a tool when creating an agent, see [Creating and configuring agents](/agents-create).
@@ -26,6 +26,7 @@ For guidance on picking a tool when creating an agent, see [Creating and configu
| **OpenClaw** | Open source | ✅ | ✅ | `.agent_context/skills/` (fallback) | Bound to the agent, can't be switched per task |
| **Pi** | Inflection AI | ✅ (session is a file path) | ❌ | `.pi/skills/` | Dynamic discovery |
| **Qoder** | Alibaba | ✅ | ✅ | `.qoder/skills/` | Dynamic discovery |
+| **Trae** | ByteDance | ✅ (ACP `session/load`) | ✅ | `.traecli/skills/` | Dynamic discovery |
## What each tool is for
@@ -89,13 +90,26 @@ From Inflection AI, minimalist. **Session resumption is unusual** — the sessio
From Alibaba. An agentic coding CLI. Uses the ACP protocol over stdio (shares a transport with Hermes, Kimi, and Kiro CLI). Session resumption works through ACP `session/resume`, MCP config is passed through ACP `mcpServers`, model selection is discovered dynamically, and skills are copied into `.qoder/skills/` for native discovery.
+### Trae
+
+From ByteDance — the official **TRAE CLI** (`traecli`, documented at [docs.trae.cn/cli](https://docs.trae.cn/cli); this is the product paired with the Trae IDE, **not** the open-source `bytedance/trae-agent`). traecli is ACP-native, so Multica drives it over the standard ACP JSON-RPC transport via `traecli acp serve --yolo`, exactly like Kiro and Qoder — `--yolo` puts it in bypass-permissions mode so headless runs don't block on tool-approval prompts.
+
+- **Session resumption works** through ACP `session/load` (traecli advertises `loadSession: true` from `initialize`).
+- **Model selection is dynamic**: the model catalog is discovered from `session/new` (`models.availableModels`) and switched per task via `session/set_model`. Set the daemon-wide default with `MULTICA_TRAECLI_MODEL`.
+- **MCP is supported** — config is passed through ACP `mcpServers`; traecli advertises `mcpCapabilities: {http, sse}`, and unsupported transports are filtered out before `session/new`.
+- **Authentication** is traecli's own enterprise login: run `traecli` once interactively to complete the browser login (the token persists in `~/.trae` + the OS keyring). The IDE login is separate — logging into the Trae IDE does **not** log in the CLI.
+- **Skills** are written to `.traecli/skills/` (project) for native discovery; global skills live in `~/.traecli/skills`.
+- The Multica runtime brief is also inlined into the prompt (traecli has no `--system-prompt` flag and reads project rules from `.trae/rules/`, not `AGENTS.md`), so the workflow instructions reach the agent regardless.
+
+> The capabilities above were captured from the real `traecli` v0.120.42 binary: `initialize` → `loadSession:true` + `mcpCapabilities{http,sse}`; `session/new` → `result.sessionId` + `models.availableModels`; `session/prompt` streams `session/update` notifications with `sessionUpdate: agent_message_chunk`.
+
## Session resumption: who really supports it
The session resumption mechanism is covered in [Tasks](/tasks#can-a-task-continue-from-the-previous-context). **Every supported tool resumes sessions** — pass the resume id and the task continues from the previous context. The one quirk is Pi, whose resume id is a session file path on disk rather than a string id (see [Pi](#pi) above).
## MCP configuration: provider-specific support
-**Of the 13 tools, ten consume `mcp_config`: Claude Code, CodeBuddy, Codex, Cursor, Hermes, Kimi, Kiro CLI, OpenCode, OpenClaw, and Qoder**. The other three accept the field but **ignore it** — no error, no warning, the config just has no effect.
+**Of the 14 tools, eleven consume `mcp_config`: Claude Code, CodeBuddy, Codex, Cursor, Hermes, Kimi, Kiro CLI, OpenCode, OpenClaw, Qoder, and Trae**. The other three (Antigravity, Copilot, Pi) accept the field but **ignore it** — no error, no warning, the config just has no effect.
The runtime paths are provider-specific: Claude Code and CodeBuddy receive it through `--mcp-config` paired with `--strict-mcp-config`; Codex writes a daemon-managed `mcp_servers` block into the per-task `$CODEX_HOME/config.toml`; Cursor writes `.cursor/mcp.json` plus per-task project approvals under `CURSOR_DATA_DIR`; Hermes, Kimi, Kiro CLI, and Qoder receive ACP `mcpServers`; OpenCode receives inline config through `OPENCODE_CONFIG_CONTENT`; OpenClaw receives `mcp.servers` through Multica's per-task config wrapper. OpenCode's path does **not** rewrite the project's `opencode.json`.
diff --git a/packages/core/agents/mcp-support.ts b/packages/core/agents/mcp-support.ts
index c1e352f25a..6190d04013 100644
--- a/packages/core/agents/mcp-support.ts
+++ b/packages/core/agents/mcp-support.ts
@@ -14,6 +14,7 @@ const MCP_SUPPORTED_PROVIDERS = new Set([
"kiro",
"opencode",
"openclaw",
+ "traecli",
]);
export function providerSupportsMcpConfig(provider: string | undefined | null): boolean {
diff --git a/packages/views/runtimes/components/provider-logo.tsx b/packages/views/runtimes/components/provider-logo.tsx
index 11846b9ac9..0b4c95e654 100644
--- a/packages/views/runtimes/components/provider-logo.tsx
+++ b/packages/views/runtimes/components/provider-logo.tsx
@@ -247,6 +247,17 @@ function KiroLogo({ className }: { className: string }) {
);
}
+// Trae (ByteDance) — official mark, recreated from the official Trae icon and
+// recolored to brand green on transparent. Embedded as a data URI (same
+// approach as the Hermes logo) so the exact official artwork is used rather
+// than a hand-drawn approximation.
+const TRAE_ICON =
+ "data:image/png;base64,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";
+
+function TraeLogo({ className }: { className: string }) {
+ return <img src={TRAE_ICON} alt="Trae" className={className} />;
+}
+
export function ProviderLogo({
provider,
className = "h-4 w-4",
@@ -281,6 +292,8 @@ export function ProviderLogo({
return <QoderLogo className={className} />;
case "antigravity":
return <AntigravityLogo className={className} />;
+ case "traecli":
+ return <TraeLogo className={className} />;
default:
return <Monitor className={className} />;
}
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index f433fc36e5..06139c99cf 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -80,7 +80,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, kiro, antigravity, qoder
+ Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, kiro, antigravity, qoder, traecli
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)
@@ -304,8 +304,15 @@ func LoadConfig(overrides Overrides) (Config, error) {
Model: strings.TrimSpace(os.Getenv("MULTICA_QODER_MODEL")),
}
}
+ // ByteDance official TRAE CLI (the `traecli` binary from https://docs.trae.cn/cli),
+ // driven over ACP via `traecli acp serve --yolo`. MULTICA_TRAECLI_MODEL seeds
+ // the daemon-wide default model (a model id from the user's logged-in traecli
+ // catalog).
+ if e, ok := probe("MULTICA_TRAECLI_PATH", "traecli", "MULTICA_TRAECLI_MODEL"); ok {
+ agents["traecli"] = e
+ }
if len(agents) == 0 {
- return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor-agent, kimi, kiro-cli, agy, or qodercli and ensure it is on PATH")
+ return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor-agent, kimi, kiro-cli, agy, qodercli, or traecli and ensure it is on PATH")
}
claudeArgs, err := shellArgsFromEnv("MULTICA_CLAUDE_ARGS")
@@ -654,7 +661,7 @@ func shellArgsFromEnv(name string) ([]string, error) {
// invocation, instead of paying the cost-per-miss.
var defaultAgentCommandNames = []string{
"claude", "codex", "opencode", "openclaw", "hermes",
- "pi", "cursor-agent", "copilot", "kimi", "kiro-cli", "codebuddy", "agy",
+ "pi", "cursor-agent", "copilot", "kimi", "kiro-cli", "codebuddy", "agy", "traecli",
}
var codexDesktopAppBundlePaths = func() []string {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 90455396c6..7e11d0ad14 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -930,7 +930,7 @@ func (d *Daemon) registerRuntimesForWorkspace(ctx context.Context, workspaceID s
}
d.setAgentVersion(name, version)
d.logger.Debug("agent version detected", "name", name, "version", version, "path", entry.Path)
- displayName := strings.ToUpper(name[:1]) + name[1:]
+ displayName := providerDisplayName(name)
if d.cfg.DeviceName != "" {
displayName = fmt.Sprintf("%s (%s)", displayName, d.cfg.DeviceName)
}
@@ -3218,9 +3218,27 @@ func gcMetaForTask(task Task) (execenv.GCMeta, bool) {
return meta, true
}
+// runtimeDisplayNameOverrides maps a provider key to the human-facing runtime
+// name when simple title-casing would read awkwardly. Providers not listed
+// here fall back to capitalizing the key (claude → "Claude", codex → "Codex").
+var runtimeDisplayNameOverrides = map[string]string{
+ "traecli": "Trae",
+}
+
+// providerDisplayName returns the human-facing runtime name for a provider key.
+func providerDisplayName(name string) string {
+ if name == "" {
+ return name
+ }
+ if friendly, ok := runtimeDisplayNameOverrides[name]; ok {
+ return friendly
+ }
+ return strings.ToUpper(name[:1]) + name[1:]
+}
+
func providerNeedsInlineSystemPrompt(provider string) bool {
switch provider {
- case "openclaw", "kiro", "kimi":
+ case "openclaw", "kiro", "kimi", "traecli":
return true
default:
return false
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 3128f9ac5e..325d85c0d4 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -272,6 +272,7 @@ func TestProviderNeedsInlineSystemPrompt(t *testing.T) {
{provider: "hermes", want: false},
{provider: "kiro", want: true},
{provider: "kimi", want: true},
+ {provider: "traecli", want: true},
{provider: "codex", want: false},
{provider: "claude", want: false},
}
diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.go
index de96488333..d6fabff745 100644
--- a/server/internal/daemon/execenv/context.go
+++ b/server/internal/daemon/execenv/context.go
@@ -219,6 +219,11 @@ func skillsDirPath(workDir, provider string) string {
// Qoder CLI discovers project-level skills under .qoder/skills/.
// See https://docs.qoder.com/cli/Skills.md
return filepath.Join(workDir, ".qoder", "skills")
+ case "traecli":
+ // Official TRAE CLI discovers project-level skills from .traecli/skills/
+ // in the workdir (global skills live in ~/.traecli/skills). See
+ // https://docs.trae.cn/cli_skills
+ return filepath.Join(workDir, ".traecli", "skills")
case "antigravity":
// Antigravity (`agy`) auto-discovers workspace-level skills from
// .agents/skills/ in the workdir. The CLI inherits Gemini CLI's
diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.go
index 51328f1b84..3ca31bca7a 100644
--- a/server/internal/daemon/execenv/runtime_config.go
+++ b/server/internal/daemon/execenv/runtime_config.go
@@ -168,6 +168,7 @@ func formatProjectResource(r ProjectResourceForEnv) string {
// For Kiro: writes {workDir}/AGENTS.md (Kiro CLI reads AGENTS.md natively; skills auto-discovered from project skills dirs)
// For Qoder: writes {workDir}/AGENTS.md (skills discovered from .qoder/skills/, user-level ~/.qoder/skills is unaffected)
// For Antigravity: writes {workDir}/AGENTS.md (agy CLI reads AGENTS.md natively; skills discovered natively from .agents/skills/ — see https://antigravity.google/docs/gcli-migration)
+// For Traecli: writes {workDir}/AGENTS.md (traecli reads .trae/rules/ not AGENTS.md, so the brief is delivered inline via providerNeedsInlineSystemPrompt; the file is written for parity/visibility only)
func InjectRuntimeConfig(workDir, provider string, ctx TaskContextForEnv) (string, error) {
content := buildMetaSkillContent(provider, ctx)
path := runtimeConfigPath(workDir, provider)
@@ -187,7 +188,7 @@ func runtimeConfigPath(workDir, provider string) string {
switch provider {
case "claude", "codebuddy":
return filepath.Join(workDir, "CLAUDE.md")
- case "codex", "copilot", "opencode", "openclaw", "hermes", "pi", "cursor", "kimi", "kiro", "antigravity", "qoder":
+ case "codex", "copilot", "opencode", "openclaw", "hermes", "pi", "cursor", "kimi", "kiro", "antigravity", "qoder", "traecli":
return filepath.Join(workDir, "AGENTS.md")
default:
return ""
@@ -750,7 +751,7 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {
case "claude", "codebuddy":
// Claude/CodeBuddy discovers skills natively from .claude/skills/ — just list names.
b.WriteString("You have the following skills installed (discovered automatically):\n\n")
- case "codex", "copilot", "opencode", "openclaw", "pi", "cursor", "kimi", "kiro", "qoder", "antigravity":
+ case "codex", "copilot", "opencode", "openclaw", "pi", "cursor", "kimi", "kiro", "qoder", "antigravity", "traecli":
// Codex, Copilot, OpenCode, OpenClaw, Pi, Cursor, Kimi, Kiro, Qoder,
// and Antigravity discover skills natively from their respective paths.
// For OpenClaw, the daemon also writes a per-task openclaw-config.json
diff --git a/server/internal/daemon/local_skills.go b/server/internal/daemon/local_skills.go
index 4f7956abfc..8de9ae1c17 100644
--- a/server/internal/daemon/local_skills.go
+++ b/server/internal/daemon/local_skills.go
@@ -128,6 +128,10 @@ func localSkillRootsForProvider(provider string) ([]localSkillRoot, bool, error)
providerRoot = filepath.Join(home, ".cursor", "skills")
case "kiro":
providerRoot = filepath.Join(home, ".kiro", "skills")
+ case "traecli":
+ // Official TRAE CLI global skills live in ~/.traecli/skills.
+ // See https://docs.trae.cn/cli_skills
+ providerRoot = filepath.Join(home, ".traecli", "skills")
case "antigravity":
// agy inherits Gemini CLI's global skill root; see
// https://antigravity.google/docs/gcli-migration ("Global skills").
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index c2a5beaccb..223b43a7c6 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -133,7 +133,7 @@ type Config struct {
}
// New creates a Backend for the given agent type.
-// Supported types: "claude", "codebuddy", "codex", "copilot", "opencode", "openclaw", "hermes", "pi", "cursor", "kimi", "kiro", "antigravity", "qoder".
+// Supported types: "claude", "codebuddy", "codex", "copilot", "opencode", "openclaw", "hermes", "pi", "cursor", "kimi", "kiro", "antigravity", "qoder", "traecli".
//
// SupportedTypes is the canonical whitelist of agent types eligible to back a
// custom runtime profile. It MUST stay in lockstep with the
@@ -200,8 +200,10 @@ func New(agentType string, cfg Config) (Backend, error) {
return &antigravityBackend{cfg: cfg}, nil
case "qoder":
return &qoderBackend{cfg: cfg}, nil
+ case "traecli":
+ return &traecliBackend{cfg: cfg}, nil
default:
- return nil, fmt.Errorf("unknown agent type: %q (supported: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, kiro, antigravity, qoder)", agentType)
+ return nil, fmt.Errorf("unknown agent type: %q (supported: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, pi, cursor, kimi, kiro, antigravity, qoder, traecli)", agentType)
}
}
@@ -230,6 +232,7 @@ var launchHeaders = map[string]string{
"opencode": "opencode run (json)",
"pi": "pi (json mode)",
"qoder": "qodercli --acp",
+ "traecli": "traecli acp serve",
}
// LaunchHeader returns the user-visible launch skeleton for agentType, or an
diff --git a/server/pkg/agent/agent_test.go b/server/pkg/agent/agent_test.go
index 69ffaacdce..5ec17c2cc6 100644
--- a/server/pkg/agent/agent_test.go
+++ b/server/pkg/agent/agent_test.go
@@ -175,7 +175,7 @@ func TestLaunchHeaderCoversAllSupportedBackends(t *testing.T) {
// entry to launchHeaders in agent.go and extend this list.
supported := []string{
"antigravity", "claude", "codebuddy", "codex", "copilot", "cursor",
- "hermes", "kimi", "kiro", "openclaw", "opencode", "pi", "qoder",
+ "hermes", "kimi", "kiro", "openclaw", "opencode", "pi", "qoder", "traecli",
}
for _, t_ := range supported {
if header := LaunchHeader(t_); header == "" {
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index 652d88cf45..af0e50d513 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -108,6 +108,13 @@ func ListModels(ctx context.Context, providerType, executablePath string) ([]Mod
return cachedDiscovery(providerType, func() ([]Model, error) {
return discoverAntigravityModels(ctx, executablePath)
})
+ case "traecli":
+ // Official TRAE CLI is ACP-native: it returns its model catalog from
+ // session/new. Enumerate it on demand like the other ACP backends
+ // (requires a logged-in traecli; falls back to manual entry on error).
+ return cachedDiscovery(providerType, func() ([]Model, error) {
+ return discoverTraecliModels(ctx, executablePath)
+ })
case "cursor":
return cachedDiscovery(providerType, func() ([]Model, error) {
return discoverCursorModels(ctx, executablePath)
@@ -303,6 +310,19 @@ func codexStaticModels() []Model {
}
}
+// discoverTraecliModels spins up a throwaway `traecli acp serve --yolo` process
+// and parses the model catalog traecli returns from session/new (same shape as
+// Kiro/Qoder). The official TRAE CLI must be logged in for the catalog to be
+// non-empty; on any failure the caller falls back to the manual-entry field.
+func discoverTraecliModels(ctx context.Context, executablePath string) ([]Model, error) {
+ return discoverACPModels(ctx, executablePath, acpDiscoveryProvider{
+ defaultBin: "traecli",
+ clientName: "multica-model-discovery",
+ tmpdirPrefix: "multica-traecli-discovery-",
+ acpArgs: []string{"acp", "serve", "--yolo"},
+ })
+}
+
// cursorStaticModels is a minimal fallback used when
// `cursor-agent --list-models` isn't available (binary missing,
// offline, etc). The real catalog is fetched dynamically because
diff --git a/server/pkg/agent/traecli.go b/server/pkg/agent/traecli.go
new file mode 100644
index 0000000000..568d415b9d
--- /dev/null
+++ b/server/pkg/agent/traecli.go
@@ -0,0 +1,439 @@
+package agent
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "os/exec"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// traecliBlockedArgs are flags hardcoded by the daemon that must not be
+// overridden by user-configured custom_args. `acp` and `serve` are the
+// protocol subcommand/action; `-y`/`--yolo` is daemon-owned so headless ACP
+// always runs in bypass-permissions mode (the official traecli gates non-read
+// tools behind a permission prompt otherwise — see
+// https://docs.trae.cn/cli_permission-mode). `--print`/`-p` and
+// `--output-format` would switch the binary out of ACP into print mode and
+// break the daemon↔traecli transport, and `--permission-mode` is owned by the
+// daemon via --yolo.
+var traecliBlockedArgs = map[string]blockedArgMode{
+ "acp": blockedStandalone,
+ "serve": blockedStandalone,
+ "-y": blockedStandalone,
+ "--yolo": blockedStandalone,
+ "-p": blockedStandalone,
+ "--print": blockedStandalone,
+ "--output-format": blockedWithValue,
+ "--permission-mode": blockedWithValue,
+}
+
+// traecliBackend implements Backend by spawning `traecli acp serve --yolo` and
+// communicating via the standard ACP (Agent Client Protocol) JSON-RPC 2.0
+// transport over stdin/stdout.
+//
+// This targets ByteDance's official TRAE CLI (the `traecli` binary documented
+// at https://docs.trae.cn/cli — NOT the open-source bytedance/trae-agent
+// `trae-cli`, which has no ACP transport). traecli is ACP-native: it advertises
+// `loadSession: true` and `mcpCapabilities: {http, sse}` from `initialize`,
+// returns its model catalog from `session/new`, and supports `session/load`
+// (resume), `session/set_model`, and `session/prompt`. That lets the existing
+// Hermes/Kimi/Kiro/Qoder ACP client (hermesClient) drive it with only
+// provider-specific launch args and tool-name normalization.
+//
+// The `initialize` capabilities above were captured from the real traecli
+// v0.120.42 binary; the streaming gate mirrors the other ACP backends so
+// history replay flushed during session setup does not corrupt the streamed
+// output.
+type traecliBackend struct {
+ cfg Config
+}
+
+var traecliReaderDrainGrace = 2 * time.Second
+
+// traecliMessageStream serializes sends and the final close so a late stdout
+// reader (traecli may keep the process and its pipes open briefly after
+// session/prompt returns) cannot send on a closed channel. Mirrors qoder.
+type traecliMessageStream struct {
+ ch chan Message
+ mu sync.Mutex
+ closed bool
+}
+
+func newTraecliMessageStream(size int) *traecliMessageStream {
+ return &traecliMessageStream{ch: make(chan Message, size)}
+}
+
+func (s *traecliMessageStream) send(msg Message) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.closed {
+ return
+ }
+ trySend(s.ch, msg)
+}
+
+func (s *traecliMessageStream) close() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.closed {
+ return
+ }
+ s.closed = true
+ close(s.ch)
+}
+
+func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
+ execPath := b.cfg.ExecutablePath
+ if execPath == "" {
+ execPath = "traecli"
+ }
+ if _, err := exec.LookPath(execPath); err != nil {
+ return nil, fmt.Errorf("traecli 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("traecli: invalid mcp_config: %w", err)
+ }
+
+ timeout := opts.Timeout
+ runCtx, cancel := runContext(ctx, timeout)
+
+ traecliArgs := append(
+ []string{"acp", "serve", "--yolo"},
+ filterCustomArgs(opts.CustomArgs, traecliBlockedArgs, b.cfg.Logger)...,
+ )
+ cmd := exec.CommandContext(runCtx, execPath, traecliArgs...)
+ hideAgentWindow(cmd)
+ b.cfg.Logger.Info("agent command", "exec", execPath, "args", traecliArgs)
+ 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("traecli stdout pipe: %w", err)
+ }
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("traecli stdin pipe: %w", err)
+ }
+ // StderrPipe + an explicit copier give us a join point (`stderrDone`) that
+ // fires before the failure-promotion decision; see the matching comment in
+ // hermes.go for why the io.MultiWriter form races with stopReason=end_turn
+ // under load.
+ providerErr := newACPProviderErrorSniffer("traecli")
+ stderr, err := cmd.StderrPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("traecli stderr pipe: %w", err)
+ }
+
+ if err := cmd.Start(); err != nil {
+ cancel()
+ return nil, fmt.Errorf("start traecli: %w", err)
+ }
+
+ stderrSink := io.MultiWriter(newLogWriter(b.cfg.Logger, "[traecli:stderr] "), providerErr)
+ stderrDone := make(chan struct{})
+ go func() {
+ defer close(stderrDone)
+ _, _ = io.Copy(stderrSink, stderr)
+ }()
+
+ b.cfg.Logger.Info("traecli acp started", "pid", cmd.Process.Pid, "cwd", opts.Cwd)
+
+ msgStream := newTraecliMessageStream(256)
+ resCh := make(chan Result, 1)
+
+ var outputMu sync.Mutex
+ var output strings.Builder
+ var streamingCurrentTurn atomic.Bool
+
+ promptDone := make(chan hermesPromptResult, 1)
+
+ c := &hermesClient{
+ cfg: b.cfg,
+ stdin: stdin,
+ pending: make(map[int]*pendingRPC),
+ pendingTools: make(map[string]*pendingToolCall),
+ acceptNotification: func(string) bool {
+ return streamingCurrentTurn.Load()
+ },
+ onMessage: func(msg Message) {
+ if !streamingCurrentTurn.Load() {
+ return
+ }
+ if msg.Type == MessageToolUse {
+ msg.Tool = kimiToolNameFromTitle(msg.Tool)
+ }
+ if msg.Type == MessageText {
+ outputMu.Lock()
+ output.WriteString(msg.Content)
+ outputMu.Unlock()
+ }
+ msgStream.send(msg)
+ },
+ onPromptDone: func(result hermesPromptResult) {
+ if !streamingCurrentTurn.Load() {
+ return
+ }
+ select {
+ case promptDone <- result:
+ default:
+ }
+ },
+ }
+
+ readerDone := make(chan struct{})
+ go func() {
+ defer close(readerDone)
+ scanner := bufio.NewScanner(stdout)
+ scanner.Buffer(make([]byte, 0, 1024*1024), 10*1024*1024)
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" {
+ continue
+ }
+ c.handleLine(line)
+ }
+ c.closeAllPending(fmt.Errorf("traecli process exited"))
+ }()
+
+ go func() {
+ defer cancel()
+ defer msgStream.close()
+ defer close(resCh)
+ defer func() {
+ stdin.Close()
+ _ = cmd.Wait()
+ }()
+
+ startTime := time.Now()
+ finalStatus := "completed"
+ var finalError string
+ var sessionID string
+ 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("traecli initialize failed: %v", err)
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
+ return
+ }
+
+ // Drop MCP entries whose remote transport the runtime didn't advertise
+ // (traecli advertises mcpCapabilities {http, sse}). See hermes.go for
+ // why sending an unsupported transport tanks the whole session/new.
+ mcpServers = filterACPMcpServersByCapability(mcpServers, extractACPMcpCapabilities(initResult), "traecli", b.cfg.Logger)
+
+ cwd := opts.Cwd
+ if cwd == "" {
+ cwd = "."
+ }
+
+ if opts.ResumeSessionID != "" {
+ // traecli advertises loadSession:true, so resume goes through the
+ // standard ACP session/load (same as Kiro).
+ result, err := c.request(runCtx, "session/load", map[string]any{
+ "cwd": cwd,
+ "sessionId": opts.ResumeSessionID,
+ "mcpServers": mcpServers,
+ })
+ if err != nil {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("traecli session/load failed: %v", err)
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
+ return
+ }
+ var changed bool
+ sessionID, changed = resolveResumedSessionID(opts.ResumeSessionID, result)
+ if changed {
+ b.cfg.Logger.Warn("agent returned a different session id on resume — original was likely lost; continuing with the new id",
+ "backend", "traecli",
+ "requested", opts.ResumeSessionID,
+ "actual", sessionID,
+ )
+ }
+ if effectiveModel == "" {
+ effectiveModel = extractACPCurrentModelID(result)
+ }
+ } else {
+ result, err := c.request(runCtx, "session/new", map[string]any{
+ "cwd": cwd,
+ "mcpServers": mcpServers,
+ })
+ if err != nil {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("traecli session/new failed: %v", err)
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
+ return
+ }
+ sessionID = extractACPSessionID(result)
+ if sessionID == "" {
+ finalStatus = "failed"
+ finalError = "traecli session/new returned no session ID"
+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}
+ return
+ }
+ if effectiveModel == "" {
+ effectiveModel = extractACPCurrentModelID(result)
+ }
+ }
+
+ c.sessionID = sessionID
+ b.cfg.Logger.Info("traecli session created", "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("traecli set_session_model failed", "error", err, "requested_model", opts.Model)
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("traecli could not switch to model %q: %v", opts.Model, err)
+ if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {
+ b.cfg.Logger.Warn("resumed session not found at set_model time; clearing session id so the daemon retries fresh",
+ "backend", "traecli",
+ "session_id", sessionID,
+ )
+ sessionID = ""
+ }
+ resCh <- Result{
+ Status: finalStatus,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ SessionID: sessionID,
+ }
+ return
+ }
+ b.cfg.Logger.Info("traecli session model set", "model", opts.Model)
+ }
+
+ userText := prompt
+ if opts.SystemPrompt != "" {
+ userText = opts.SystemPrompt + "\n\n---\n\n" + prompt
+ }
+
+ streamingCurrentTurn.Store(true)
+ _, err = c.request(runCtx, "session/prompt", map[string]any{
+ "sessionId": sessionID,
+ "prompt": []map[string]any{
+ {"type": "text", "text": userText},
+ },
+ })
+ if err != nil {
+ if runCtx.Err() == context.DeadlineExceeded {
+ finalStatus = "timeout"
+ finalError = fmt.Sprintf("traecli timed out after %s", timeout)
+ } else if runCtx.Err() == context.Canceled {
+ finalStatus = "aborted"
+ finalError = "execution cancelled"
+ } else {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("traecli session/prompt failed: %v", err)
+ if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {
+ b.cfg.Logger.Warn("resumed session not found at prompt time; clearing session id so the daemon retries fresh",
+ "backend", "traecli",
+ "session_id", sessionID,
+ )
+ sessionID = ""
+ }
+ }
+ } else {
+ select {
+ case pr := <-promptDone:
+ if pr.stopReason == "cancelled" {
+ finalStatus = "aborted"
+ finalError = "traecli cancelled the prompt"
+ }
+ c.usageMu.Lock()
+ c.usage.InputTokens += pr.usage.InputTokens
+ c.usage.OutputTokens += pr.usage.OutputTokens
+ c.usage.CacheReadTokens += pr.usage.CacheReadTokens
+ c.usageMu.Unlock()
+ default:
+ }
+ }
+
+ duration := time.Since(startTime)
+ b.cfg.Logger.Info("traecli finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
+
+ stdin.Close()
+ cancel()
+
+ // traecli ACP may keep the process — and the stdout/stderr pipes — open
+ // briefly after session/prompt returns. The prompt response is already
+ // terminal, so bound the drain: wait for the stdout reader and the
+ // stderr copier, but no longer than the grace window (CommandContext
+ // cancellation tears the process down). Draining stderr is what makes
+ // the provider-error promotion below see a terminal marker.
+ drainCtx, drainCancel := context.WithTimeout(context.Background(), traecliReaderDrainGrace)
+ select {
+ case <-readerDone:
+ case <-drainCtx.Done():
+ }
+ select {
+ case <-stderrDone:
+ case <-drainCtx.Done():
+ }
+ drainCancel()
+ // Flip the gate before the defer closes msgStream; a late reader that
+ // already passed the gate is serialized by traecliMessageStream so the
+ // late send is dropped instead of panicking.
+ streamingCurrentTurn.Store(false)
+
+ outputMu.Lock()
+ finalOutput := output.String()
+ outputMu.Unlock()
+
+ // Promote completed→failed when stderr or the agent text stream show a
+ // terminal upstream-LLM failure (HTTP 4xx / rate-limit / expired token).
+ // Mirrors hermes/kimi/kiro/qoder.
+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, finalOutput, providerErr)
+
+ c.usageMu.Lock()
+ u := c.usage
+ c.usageMu.Unlock()
+
+ var usageMap map[string]TokenUsage
+ if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 {
+ 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,
+ Usage: usageMap,
+ }
+ }()
+
+ return &Session{Messages: msgStream.ch, Result: resCh}, nil
+}
diff --git a/server/pkg/agent/traecli_test.go b/server/pkg/agent/traecli_test.go
new file mode 100644
index 0000000000..79ec768c55
--- /dev/null
+++ b/server/pkg/agent/traecli_test.go
@@ -0,0 +1,348 @@
+package agent
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "log/slog"
+)
+
+func TestNewReturnsTraecliBackend(t *testing.T) {
+ t.Parallel()
+ b, err := New("traecli", Config{ExecutablePath: "/nonexistent/traecli"})
+ if err != nil {
+ t.Fatalf("New(traecli) error: %v", err)
+ }
+ if _, ok := b.(*traecliBackend); !ok {
+ t.Fatalf("expected *traecliBackend, got %T", b)
+ }
+}
+
+// fakeTraecliACPScript impersonates the official `traecli acp serve` for unit
+// tests. It speaks the SAME wire format the real traecli v0.120.42 emits
+// (captured live): method "session/update" with an "update.sessionUpdate"
+// discriminator (agent_thought_chunk / agent_message_chunk), session/new
+// returning result.sessionId + models.availableModels [{modelId,name,
+// description}], and session/prompt returning {stopReason:end_turn}.
+func fakeTraecliACPScript() string {
+ return `#!/bin/sh
+if [ -n "$TRAECLI_ARGS_FILE" ]; then
+ for arg in "$@"; do
+ printf '%s\n' "$arg" >> "$TRAECLI_ARGS_FILE"
+ done
+fi
+while IFS= read -r line; do
+ if [ -n "$TRAECLI_REQUESTS_FILE" ]; then
+ printf '%s\n' "$line" >> "$TRAECLI_REQUESTS_FILE"
+ fi
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true}}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_new","models":{"availableModels":[{"modelId":"Doubao-Seed-2.1-Pro","name":"Doubao-Seed-2.1-Pro","description":""},{"modelId":"GLM-5.2","name":"GLM-5.2","description":""}]}}}\n' "$id"
+ ;;
+ *'"method":"session/load"'*)
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_loaded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"history replay ignored"}}}}\n'
+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
+ ;;
+ *'"method":"session/set_model"'*)
+ case "$line" in
+ *bogus-model*)
+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32602,"message":"model not available: bogus-model"}}\n' "$id"
+ exit 0
+ ;;
+ *)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
+ ;;
+ esac
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"thinking about it"}}}}\n'
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"tool_call","toolCallId":"tc-1","name":"Shell","status":"pending","parameters":{"command":"echo hi"}}}}\n'
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"tool_call_update","toolCallId":"tc-1","status":"completed","name":"Shell","output":"hi\\n"}}}\n'
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"pong"}}}}\n'
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+func TestTraecliBackendStreamsAndCompletes(t *testing.T) {
+ t.Parallel()
+ fakePath := filepath.Join(t.TempDir(), "traecli")
+ writeTestExecutable(t, fakePath, []byte(fakeTraecliACPScript()))
+
+ backend, err := New("traecli", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new traecli backend: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "say pong", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ var messages []Message
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ for m := range session.Messages {
+ messages = append(messages, m)
+ }
+ }()
+ result := <-session.Result
+ <-done
+
+ if result.Status != "completed" {
+ t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Output, "pong") {
+ t.Fatalf("output = %q, want it to contain the assistant message 'pong'", result.Output)
+ }
+ if result.SessionID != "ses_new" {
+ t.Fatalf("session id = %q, want ses_new", result.SessionID)
+ }
+ // The agent_message_chunk must surface as MessageText; the tool_call must
+ // surface as a MessageToolUse normalized to a canonical tool name.
+ var sawText, sawToolUse bool
+ for _, m := range messages {
+ if m.Type == MessageText && strings.Contains(m.Content, "pong") {
+ sawText = true
+ }
+ if m.Type == MessageToolUse && m.Tool == "terminal" {
+ sawToolUse = true
+ }
+ }
+ if !sawText {
+ t.Error("expected a MessageText carrying the assistant 'pong'")
+ }
+ if !sawToolUse {
+ t.Errorf("expected the Shell tool_call to normalize to 'terminal'; messages=%+v", messages)
+ }
+}
+
+func TestTraecliBlockedArgsFiltering(t *testing.T) {
+ t.Parallel()
+ tempDir := t.TempDir()
+ argsFile := filepath.Join(tempDir, "argv.txt")
+ fakePath := filepath.Join(tempDir, "traecli")
+ writeTestExecutable(t, fakePath, []byte(fakeTraecliACPScript()))
+
+ backend, err := New("traecli", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.Default(),
+ Env: map[string]string{"TRAECLI_ARGS_FILE": argsFile},
+ })
+ if err != nil {
+ t.Fatalf("new traecli backend: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "task", ExecOptions{
+ Timeout: 5 * time.Second,
+ // Users must not be able to strip ACP mode, switch to print mode,
+ // override the permission mode, or duplicate the subcommand.
+ CustomArgs: []string{"acp", "serve", "--yolo", "-p", "--output-format", "json", "--permission-mode", "default", "--add-dir", "/tmp/extra"},
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ <-session.Result
+
+ raw, err := os.ReadFile(argsFile)
+ if err != nil {
+ t.Fatalf("read args file: %v", err)
+ }
+ lines := strings.Split(strings.TrimSpace(string(raw)), "\n")
+ wantPrefix := []string{"acp", "serve", "--yolo"}
+ if len(lines) < len(wantPrefix) {
+ t.Fatalf("expected at least %d args, got %d: %q", len(wantPrefix), len(lines), lines)
+ }
+ for i, want := range wantPrefix {
+ if lines[i] != want {
+ t.Fatalf("arg[%d] = %q, want %q (full: %q)", i, lines[i], want, lines)
+ }
+ }
+ // The hardcoded prefix must appear exactly once each.
+ joined := strings.Join(lines, " ")
+ for _, once := range []string{"acp", "serve", "--yolo"} {
+ if c := countTokens(lines, once); c != 1 {
+ t.Errorf("expected exactly one %q, got %d (full: %q)", once, c, joined)
+ }
+ }
+ for _, blocked := range []string{"-p", "--output-format", "json", "--permission-mode", "default"} {
+ for _, got := range lines {
+ if got == blocked {
+ t.Errorf("blocked custom arg %q survived filtering: %q", blocked, lines)
+ }
+ }
+ }
+ // An allowed custom arg must survive.
+ if !strings.Contains(joined, "--add-dir /tmp/extra") {
+ t.Errorf("expected allowed custom arg --add-dir to survive, got %q", joined)
+ }
+}
+
+func countTokens(lines []string, tok string) int {
+ n := 0
+ for _, l := range lines {
+ if l == tok {
+ n++
+ }
+ }
+ return n
+}
+
+func TestTraecliSetModelFailureFailsTask(t *testing.T) {
+ t.Parallel()
+ fakePath := filepath.Join(t.TempDir(), "traecli")
+ writeTestExecutable(t, fakePath, []byte(fakeTraecliACPScript()))
+
+ backend, err := New("traecli", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new traecli backend: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "task", ExecOptions{Model: "bogus-model", Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ result := <-session.Result
+ if result.Status != "failed" {
+ t.Fatalf("expected failed on set_model error, got %q", result.Status)
+ }
+ if !strings.Contains(result.Error, `could not switch to model "bogus-model"`) {
+ t.Errorf("expected error to name the model, got %q", result.Error)
+ }
+ if !strings.Contains(result.Error, "model not available") {
+ t.Errorf("expected upstream message surfaced, got %q", result.Error)
+ }
+}
+
+func TestTraecliUsesSessionLoadForResume(t *testing.T) {
+ t.Parallel()
+ tempDir := t.TempDir()
+ requestsFile := filepath.Join(tempDir, "requests.jsonl")
+ fakePath := filepath.Join(tempDir, "traecli")
+ writeTestExecutable(t, fakePath, []byte(fakeTraecliACPScript()))
+
+ backend, err := New("traecli", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.Default(),
+ Env: map[string]string{"TRAECLI_REQUESTS_FILE": requestsFile},
+ })
+ if err != nil {
+ t.Fatalf("new traecli backend: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "continue", ExecOptions{
+ ResumeSessionID: "ses_existing",
+ Timeout: 5 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("expected completed, got %q (error=%q)", result.Status, result.Error)
+ }
+ if result.SessionID != "ses_existing" {
+ t.Fatalf("session id = %q, want ses_existing", result.SessionID)
+ }
+ raw, err := os.ReadFile(requestsFile)
+ if err != nil {
+ t.Fatalf("read requests: %v", err)
+ }
+ requests := string(raw)
+ if !strings.Contains(requests, `"method":"session/load"`) {
+ t.Fatalf("expected session/load on resume, got:\n%s", requests)
+ }
+ if strings.Contains(requests, `"method":"session/resume"`) {
+ t.Fatalf("traecli must use session/load (loadSession:true), not session/resume:\n%s", requests)
+ }
+}
+
+// TestTraecliRealACPSmoke drives the REAL official `traecli acp serve` binary
+// end-to-end when it is installed and logged in. It is the live counterpart to
+// the fake-ACP tests above: it proves the backend's initialize → session/new →
+// session/prompt flow works against the actual binary and the user's account.
+//
+// Skipped automatically when traecli is not on PATH or the session cannot be
+// created (not logged in), so CI — which has neither — stays green. Run locally
+// with a logged-in traecli to exercise it.
+func TestTraecliRealACPSmoke(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping real-binary smoke test in -short mode")
+ }
+ path, err := exec.LookPath("traecli")
+ if err != nil {
+ t.Skip("traecli not on PATH; skipping real-binary smoke test")
+ }
+
+ backend, err := New("traecli", Config{ExecutablePath: path, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new traecli backend: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "Reply with exactly one word: pong. Do not use any tools.", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 80 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result := <-session.Result:
+ // "session/new" panics on a NOT-logged-in traecli (no models); treat
+ // that as a skip so the test only fails for real protocol regressions.
+ if result.Status == "failed" && strings.Contains(result.Error, "session/new") {
+ t.Skipf("traecli not logged in (session/new failed): %v", result.Error)
+ }
+ if result.Status != "completed" {
+ t.Fatalf("real traecli run did not complete: status=%q error=%q", result.Status, result.Error)
+ }
+ if !strings.Contains(strings.ToLower(result.Output), "pong") {
+ t.Fatalf("expected real traecli output to contain 'pong', got %q", result.Output)
+ }
+ if result.SessionID == "" {
+ t.Error("expected a non-empty session id from real traecli")
+ }
+ t.Logf("real traecli smoke OK: session=%s output=%q", result.SessionID, result.Output)
+ case <-time.After(90 * time.Second):
+ t.Fatal("timeout waiting for real traecli result")
+ }
+}