opencode-acp-provider 1.1.1 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -102,10 +102,29 @@ delegation and questions through the MCP bridge instead of a second hidden agent
102
102
  {
103
103
  "id": "claude",
104
104
  "command": ["claude-agent-acp"],
105
- "meta": { "claudeCode": { "options": { "disallowedTools": ["Task", "AskUserQuestion"] } } }
105
+ "meta": {
106
+ "claudeCode": {
107
+ "options": {
108
+ "disallowedTools": [
109
+ "Task", "AskUserQuestion",
110
+ "EnterPlanMode", "ExitPlanMode", "EnterWorktree", "ExitWorktree",
111
+ "ListAgents", "SendMessage",
112
+ "CronCreate", "CronDelete", "CronList", "ScheduleWakeup",
113
+ "PushNotification", "RemoteTrigger", "SendToProject", "SendToProjectContext", "DesignSync"
114
+ ]
115
+ }
116
+ }
117
+ }
106
118
  }
107
119
  ```
108
120
 
121
+ Beyond subagents and questions, this list drops tools that do nothing useful under an ACP host:
122
+ plan mode (approval turns into an auto-approved permission request; use OpenCode's plan agent),
123
+ native worktrees (edits move out of OpenCode's snapshots; use `worktree_create`), peer-session
124
+ messaging, scheduling (idle sessions and processes close, so schedules die silently, and a firing
125
+ one starts a turn nobody sent), and Claude app features (push notifications, remote triggers,
126
+ projects, design sync). claude.ai connectors stay available.
127
+
109
128
  The adapter accepts injected HTTP MCP servers, so `mcpTransport: "http"` works.
110
129
 
111
130
  ### Codex (`codex`)
@@ -115,11 +134,16 @@ The adapter accepts injected HTTP MCP servers, so `mcpTransport: "http"` works.
115
134
  "id": "codex",
116
135
  "command": ["codex-acp"],
117
136
  "env": {
118
- "CODEX_CONFIG": "{\"agents\":{\"enabled\":false},\"tools\":{\"experimental_request_user_input\":{\"enabled\":false}}}"
137
+ "CODEX_CONFIG": "{\"agents\":{\"enabled\":false},\"tools\":{\"experimental_request_user_input\":{\"enabled\":false}},\"features\":{\"goals\":false,\"tool_suggest\":false,\"image_generation\":false}}"
119
138
  }
120
139
  }
121
140
  ```
122
141
 
142
+ `features` turns off Codex goals (use OpenCode's goal loop), plugin-install suggestions, and image
143
+ generation (the plugin forwards text only). To drop individual ChatGPT apps, add
144
+ `"apps":{"<connector_id>":{"enabled":false}}`; the ids are in
145
+ `~/.codex/cache/codex_apps_tools/*.json` (`connector_id`).
146
+
123
147
  Codex drops injected HTTP MCP servers, so keep the stdio transport. It does not advertise `/compact`,
124
148
  so a manual `/compact` reports that it cannot compact on request.
125
149
 
@@ -148,7 +172,8 @@ Ships its own ACP stdio server, so it needs no adapter package:
148
172
  with the server's `mode` option. Permission requests in `default` mode go through `autoApprove`.
149
173
  - **Native tools.** `agy` keeps `ask_question` plus its own subagent family (`invoke_subagent`,
150
174
  `define_subagent`, `manage_subagents`, `swarm`, `run_workflow`). ACP has no question method, so
151
- `ask_question` prints the question into the turn and ends, which looks like a stalled prompt. Its
175
+ `ask_question` prints the question into the turn and ends, which looks like a stalled prompt.
176
+ `send_message` only talks to its native subagents, and `schedule` timers die with idle sessions. Its
152
177
  `permissions` block cannot gate these (it covers only `read_file`, `write_file`, `read_url`,
153
178
  `execute_url`, `command`, and `mcp`), so deny them by tool name in `~/.gemini/config/hooks.json`
154
179
  (every workspace) or `<workspace>/.agents/hooks.json`:
@@ -158,7 +183,7 @@ Ships its own ACP stdio server, so it needs no adapter package:
158
183
  "opencode-orchestration": {
159
184
  "PreToolUse": [
160
185
  {
161
- "matcher": "ask_question|invoke_subagent|define_subagent|manage_subagents|swarm|run_workflow",
186
+ "matcher": "ask_question|invoke_subagent|define_subagent|manage_subagents|swarm|run_workflow|send_message|schedule",
162
187
  "hooks": [
163
188
  {
164
189
  "command": "echo '{\"decision\":\"deny\",\"reason\":\"Use the OpenCode question and subagent tools instead.\"}'"
@@ -355,7 +380,7 @@ Restarting the service refreshes discovery. Slash commands are still discovered
355
380
  | `outputLimit` | Output limit advertised for ACP models. Defaults to `32000`. |
356
381
  | `initTimeoutMs` | How long one agent may take to initialize. Defaults to `20000`; a failed server is retried in the background under the same bound. |
357
382
  | `requestTimeoutMs` | Timeout for the ACP handshake and control calls such as `session/new`. Defaults to `15000`; raise it for agents that start slowly. |
358
- | `promptTimeoutMs` | How long one ACP turn may run. Defaults to `1800000` (30 minutes); `0` disables the cap. |
383
+ | `promptTimeoutMs` | How long one ACP turn may run, and how long a session stays busy waiting for a command the agent left running in the background. Defaults to `1800000` (30 minutes); `0` disables the cap. |
359
384
  | `toolCallDisplay` | `inline` (default) shows finished ACP tool calls as transcript lines on the fallback chat-completions route when OpenCode cannot render native tool cards; `off` hides them. |
360
385
  | `mcp` | Expose OpenCode tools to ACP agents through the MCP bridge. Defaults to `true`. |
361
386
  | `commands` | Register the agents' own slash commands as namespaced OpenCode commands. Defaults to `true`. See [Commands](#commands). |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-acp-provider",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "OpenCode plugin that acts as an Agent Client Protocol (ACP) client and exposes registered ACP agents as model providers.",
5
5
  "type": "module",
6
6
  "exports": {
package/src/acp-client.ts CHANGED
@@ -291,6 +291,13 @@ export class AcpClient {
291
291
  return owner === undefined || session.owner === undefined || session.owner === owner
292
292
  }
293
293
 
294
+ /** The `agentInfo.name` the agent reported at `initialize`, such as `@agentclientprotocol/codex-acp`. */
295
+ get agentName(): string | undefined {
296
+ const info = this.handshake?.agentInfo
297
+ const name = info && typeof info === "object" ? (info as { name?: unknown }).name : undefined
298
+ return typeof name === "string" ? name : undefined
299
+ }
300
+
294
301
  /** Spawn the agent and run the ACP initialize handshake, restarting if it died. */
295
302
  start(): Promise<AgentHandshake> {
296
303
  if (this.disposed) return Promise.reject(new AcpError("ACP client stopped"))
@@ -356,6 +363,11 @@ export class AcpClient {
356
363
  clientCapabilities: {
357
364
  fs: { readTextFile: true, writeTextFile: true },
358
365
  terminal: false,
366
+ // Command output arrives as `_meta.terminal_output_delta` chunks, and
367
+ // a command's terminal stays open until it ends. That is how a
368
+ // command the agent sent to the background is told apart from a
369
+ // finished one: claude-agent-acp reports both as `completed`.
370
+ _meta: { terminal_output_delta: true },
359
371
  },
360
372
  clientInfo: { name: "opencode", version: "2" },
361
373
  },
@@ -1,9 +1,11 @@
1
+ import type { SessionUpdate } from "../acp-client.ts"
1
2
  import type { ResolvedTool, ToolContext } from "./shared.ts"
2
3
  import {
3
4
  booleanOf,
4
5
  commandOf,
5
6
  editInput,
6
7
  executeInput,
8
+ extractOutput,
7
9
  finiteNumber,
8
10
  firstText,
9
11
  globInput,
@@ -133,3 +135,20 @@ export function resolveCommandCode(ctx: ToolContext): ResolvedTool | undefined {
133
135
  if (title === "ask_user_question") return unchanged("ask_user_question")
134
136
  return undefined
135
137
  }
138
+
139
+ const BACKGROUND_STARTED = "Started shell command in the background."
140
+
141
+ /**
142
+ * The task a Command Code shell call left running in the background. Command
143
+ * Code reports the start only as result text (`Task: …` and `PID: …` lines)
144
+ * and sends nothing when the command ends, so the process id is the only way
145
+ * to tell that it still runs.
146
+ */
147
+ export function commandCodeBackgroundTask(update: SessionUpdate): { taskId: string; pid: number } | undefined {
148
+ if (text(update.status) !== "completed") return undefined
149
+ const output = extractOutput(update)
150
+ if (!output?.startsWith(BACKGROUND_STARTED)) return undefined
151
+ const taskId = /^Task: (\S+)$/m.exec(output)?.[1]
152
+ const pid = Number(/^PID: (\d+)$/m.exec(output)?.[1])
153
+ return taskId && Number.isInteger(pid) && pid > 0 ? { taskId, pid } : undefined
154
+ }
@@ -101,9 +101,40 @@ export function diffsOf(update: SessionUpdate): DiffItem[] {
101
101
  return diffs
102
102
  }
103
103
 
104
- /** codex-acp streams shell and read output through `_meta` rather than `content`. */
105
- export function terminalOutputDelta(update: SessionUpdate): string | undefined {
106
- return literal(record(record(update._meta)?.terminal_output_delta)?.data)
104
+ /**
105
+ * Agents stream command output through the `_meta` terminal extension rather
106
+ * than `content`: `terminal_output_delta` appends to what the terminal showed,
107
+ * and `terminal_output` replaces it.
108
+ */
109
+ export function terminalOutputChunk(update: SessionUpdate): { data: string; replace: boolean } | undefined {
110
+ const meta = record(update._meta)
111
+ const delta = literal(record(meta?.terminal_output_delta)?.data)
112
+ if (delta !== undefined) return { data: delta, replace: false }
113
+ const whole = literal(record(meta?.terminal_output)?.data)
114
+ return whole === undefined ? undefined : { data: whole, replace: true }
115
+ }
116
+
117
+ /**
118
+ * Whether the update opens (`terminal_info`) or closes (`terminal_exit`) the
119
+ * call's display terminal. A command that went to the background reports its
120
+ * tool call `completed` but keeps its terminal open until the command ends.
121
+ */
122
+ export function terminalEvents(update: SessionUpdate): { opened: boolean; exited: boolean } {
123
+ const meta = record(update._meta)
124
+ return { opened: record(meta?.terminal_info) !== undefined, exited: record(meta?.terminal_exit) !== undefined }
125
+ }
126
+
127
+ /**
128
+ * The call's status, including the end of a background command: claude-agent-acp
129
+ * reports it as a bare `terminal_exit` on the original call, with no status.
130
+ */
131
+ export function toolUpdateStatus(update: SessionUpdate): string | undefined {
132
+ const status = text(update.status)
133
+ if (status) return status
134
+ const exit = record(record(update._meta)?.terminal_exit)
135
+ if (!exit) return undefined
136
+ const code = exit.exit_code
137
+ return typeof code === "number" && code !== 0 ? "failed" : "completed"
107
138
  }
108
139
 
109
140
  /** OpenCode's question tool is the only ACP tool name with a known native card. */
package/src/acp-tools.ts CHANGED
@@ -11,9 +11,11 @@ import {
11
11
  extractOutput,
12
12
  locationPath,
13
13
  record,
14
- terminalOutputDelta,
14
+ terminalEvents,
15
+ terminalOutputChunk,
15
16
  text,
16
17
  todowriteTodos,
18
+ toolUpdateStatus,
17
19
  type AgentId,
18
20
  type ToolContext,
19
21
  } from "./acp-tools/shared.ts"
@@ -45,6 +47,8 @@ interface CallMeta {
45
47
  rawInput?: Record<string, unknown>
46
48
  /** The call streamed terminal output, which outranks a structured `rawOutput`. */
47
49
  streamedTerminal?: boolean
50
+ /** The call's display terminal is open: its command still runs, even after a `completed` status. */
51
+ terminalOpen?: boolean
48
52
  }
49
53
 
50
54
  const callMeta = new WeakMap<Map<string, AcpToolState>, Map<string, CallMeta>>()
@@ -157,18 +161,27 @@ export function applyToolUpdate(update: SessionUpdate, states: Map<string, AcpTo
157
161
  input.newString = diff.newText
158
162
  }
159
163
 
160
- const delta = terminalOutputDelta(update)
161
- const streamedTerminal = Boolean(meta?.streamedTerminal || delta !== undefined)
162
- const streamed = delta === undefined ? existing?.output : clip(`${existing?.output ?? ""}${delta}`)
164
+ const chunk = terminalOutputChunk(update)
165
+ const streamedTerminal = Boolean(meta?.streamedTerminal || chunk !== undefined)
166
+ const streamed =
167
+ chunk === undefined
168
+ ? existing?.output
169
+ : clip(chunk.replace ? chunk.data : `${existing?.output ?? ""}${chunk.data}`)
170
+ const terminal = terminalEvents(update)
171
+ const terminalOpen = (Boolean(meta?.terminalOpen) || terminal.opened) && !terminal.exited
163
172
 
164
173
  metaFor(states).set(id, {
165
174
  agent: resolved.agent,
166
175
  rawName: resolved.rawName,
167
176
  rawInput: effectiveRaw,
168
177
  streamedTerminal,
178
+ terminalOpen,
169
179
  })
170
180
 
171
- const status = text(update.status) ?? existing?.status ?? "pending"
181
+ const reported = toolUpdateStatus(update) ?? existing?.status ?? "pending"
182
+ // A completed call whose terminal is still open went to the background: it
183
+ // runs on until the terminal exits.
184
+ const status = reported === "completed" && terminalOpen ? "in_progress" : reported
172
185
  const state: AcpToolState = {
173
186
  id,
174
187
  name,
@@ -33,8 +33,10 @@ src/agents/
33
33
 
34
34
  ### `no-native-orchestration.ts`
35
35
 
36
- Removes the native `agent`, `agent_output`, and `ask_user_question`
37
- tools from the main loop. Command Code's permission rules cannot block the `agent` tool (its docs
36
+ Removes the native `agent`, `agent_output`, and `ask_user_question` tools from the main loop, along
37
+ with tools an ACP host cannot use: plan mode (`enter_plan_mode`, `exit_plan_mode`, `plan_review`),
38
+ worktrees (`enter_worktree`, `exit_worktree`), scheduling (`cron_create`, `cron_delete`,
39
+ `cron_list`, `schedule_wakeup`), and artifact publishing (`artifact_publish`, `artifact_manage`). Command Code's permission rules cannot block the `agent` tool (its docs
38
40
  mark it as always allowed), so the mod uses `cmd.setActiveTools` to remove it from the model's schema
39
41
  and `beforeToolCall` to refuse any call that still arrives.
40
42
 
@@ -3,7 +3,7 @@ import { isCmdCommand } from "../../agent-command.ts"
3
3
 
4
4
  const mod = (name: string) => fileURLToPath(new URL(`./mods/${name}`, import.meta.url))
5
5
 
6
- /** Hides cmd's native `agent`/`ask_user_question` tools so the MCP bridge's tools are used. */
6
+ /** Hides cmd's native orchestration, question, plan, worktree, scheduling, and artifact tools inside ACP. */
7
7
  export const CMD_ORCHESTRATION_MOD = mod("no-native-orchestration.ts")
8
8
  /** Registers OPENCODE_ACP_PROVIDER_SKILL_DIR with cmd, because `cmd acp` ignores `--skill`. */
9
9
  export const CMD_SKILL_MOD = mod("opencode-skills.ts")
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Disable Command Code's native orchestration and question tools inside `cmd acp`.
2
+ * Disable Command Code's native tools that OpenCode replaces or cannot host inside `cmd acp`.
3
3
  *
4
4
  * Command Code exposes `agent` and `agent_output` to the main loop. Inside an
5
5
  * ACP host such as OpenCode those duplicate the orchestrator, which already
@@ -12,19 +12,47 @@
12
12
  * showing OpenCode's question UI. The agent should call the host's MCP
13
13
  * `question` tool instead.
14
14
  *
15
+ * The rest have no place under an ACP host:
16
+ * - Plan mode (`enter_plan_mode`, `exit_plan_mode`, `plan_review`): approval
17
+ * becomes an auto-approved permission request and the review panel lives in
18
+ * cmd's own TUI. OpenCode has its own plan agent.
19
+ * - Worktrees (`enter_worktree`, `exit_worktree`): moving the session out of
20
+ * the OpenCode location hides its edits from OpenCode's snapshots. The host
21
+ * exposes `worktree_create` instead.
22
+ * - Scheduling (`cron_*`, `schedule_wakeup`): pooled ACP sessions and agent
23
+ * processes close when idle, so schedules die silently, and a firing one
24
+ * starts a turn the user never sent.
25
+ * - Artifacts (`artifact_publish`, `artifact_manage`): publish to Command
26
+ * Code's hosting, unrelated to OpenCode.
27
+ *
15
28
  * Loaded automatically by the plugin (src/agents/cmd/index.ts) on any `cmd ... acp`
16
29
  * command while the MCP bridge is enabled. `--safe-mode` disables it.
17
30
  */
18
31
  import type { ModApi } from "@commandcode/harness"
19
32
 
20
- const DISABLED = new Set(["agent", "agent_output", "ask_user_question"])
33
+ const REASONS: Record<string, string> = {
34
+ agent: "Native subagents are disabled. Use the host's own subagent tool instead.",
35
+ agent_output: "Native subagents are disabled. Use the host's own subagent tool instead.",
36
+ ask_user_question: "Native questions are disabled. Use the host's MCP `question` tool instead.",
37
+ enter_plan_mode: "Plan mode is disabled inside OpenCode. Plan in the conversation instead.",
38
+ exit_plan_mode: "Plan mode is disabled inside OpenCode. Plan in the conversation instead.",
39
+ plan_review: "Plan mode is disabled inside OpenCode. Plan in the conversation instead.",
40
+ enter_worktree: "Native worktrees are disabled. Use the host's MCP `worktree_create` tool instead.",
41
+ exit_worktree: "Native worktrees are disabled. Use the host's MCP `worktree_create` tool instead.",
42
+ cron_create: "Scheduling is disabled inside OpenCode.",
43
+ cron_delete: "Scheduling is disabled inside OpenCode.",
44
+ cron_list: "Scheduling is disabled inside OpenCode.",
45
+ schedule_wakeup: "Scheduling is disabled inside OpenCode.",
46
+ artifact_publish: "Artifact publishing is disabled inside OpenCode.",
47
+ artifact_manage: "Artifact publishing is disabled inside OpenCode.",
48
+ }
21
49
 
22
50
  export default function (cmd: ModApi) {
23
51
  const hide = () => {
24
52
  // Base the filter on the *active* tools, not every registered tool: another
25
53
  // mod may already have disabled something, and getAllTools would re-enable it.
26
54
  const active = cmd.getActiveTools()
27
- const next = active.filter((name) => !DISABLED.has(name))
55
+ const next = active.filter((name) => !Object.hasOwn(REASONS, name))
28
56
  if (next.length !== active.length) cmd.setActiveTools(next)
29
57
  }
30
58
 
@@ -41,14 +69,8 @@ export default function (cmd: ModApi) {
41
69
  },
42
70
  // Fail closed if a call slips through the schema filter.
43
71
  beforeToolCall({ toolName }) {
44
- if (!DISABLED.has(toolName)) return undefined
45
- return {
46
- block: true,
47
- additionalContext:
48
- toolName === "ask_user_question"
49
- ? "Native questions are disabled. Use the host's MCP `question` tool instead."
50
- : "Native subagents are disabled. Use the host's own subagent tool instead.",
51
- }
72
+ if (!Object.hasOwn(REASONS, toolName)) return undefined
73
+ return { block: true, additionalContext: REASONS[toolName] }
52
74
  },
53
75
  })
54
76
  }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Keeps an OpenCode session running while its ACP agent still has background
3
+ * work, so the session shows as busy rather than idle.
4
+ *
5
+ * OpenCode awaits the `experimental.idle` hook inside the session's execution
6
+ * and admits input that arrives meanwhile into that same execution. Holding the
7
+ * hook until the agent's background command finishes therefore keeps the
8
+ * session active, and the wake-up message for the finished command continues
9
+ * it without the session ever going idle.
10
+ */
11
+
12
+ export interface BackgroundHoldOptions {
13
+ /**
14
+ * Ids of the session's ACP background work that has not finished: running
15
+ * background tools, and wake-ups that no turn has picked up yet.
16
+ */
17
+ pending: (sessionID: string) => string[]
18
+ /** Whether the session runs on an ACP provider of this plugin. */
19
+ owns: (sessionID: string) => Promise<boolean>
20
+ /** OpenCode's event stream, to release the hold when the session gets input or is interrupted. */
21
+ subscribe?: (signal: AbortSignal) => AsyncIterable<{ type: string; data?: { sessionID?: unknown } }>
22
+ /** How often to check whether the background work finished. */
23
+ pollMs?: number
24
+ /** Longest one hold may last; `0` disables the cap. */
25
+ maxHoldMs?: number
26
+ }
27
+
28
+ const DEFAULT_POLL_MS = 500
29
+ const DEFAULT_MAX_HOLD_MS = 30 * 60_000
30
+
31
+ /** Input reached the session: a user prompt, a wake-up, or a subagent's result. */
32
+ const INBOX_ENQUEUED = "session.inbox.enqueued"
33
+ const INTERRUPTED = "session.execution.interrupted"
34
+
35
+ interface Hold {
36
+ ids: string[]
37
+ release: () => void
38
+ }
39
+
40
+ export function createBackgroundHold(options: BackgroundHoldOptions) {
41
+ const pollMs = options.pollMs ?? DEFAULT_POLL_MS
42
+ const maxHoldMs = options.maxHoldMs ?? DEFAULT_MAX_HOLD_MS
43
+ const holds = new Map<string, Set<Hold>>()
44
+ // Work the user chose not to wait for: they interrupted the hold. It is not
45
+ // held for again, so stopping the session sticks.
46
+ const declined = new Map<string, Set<string>>()
47
+ const controller = new AbortController()
48
+
49
+ const releaseAll = (sessionID: string, decline: boolean) => {
50
+ const active = holds.get(sessionID)
51
+ if (!active) return
52
+ for (const hold of [...active]) {
53
+ if (decline) {
54
+ const set = declined.get(sessionID) ?? new Set()
55
+ for (const id of hold.ids) set.add(id)
56
+ declined.set(sessionID, set)
57
+ }
58
+ hold.release()
59
+ }
60
+ }
61
+
62
+ if (options.subscribe) {
63
+ void (async () => {
64
+ try {
65
+ for await (const event of options.subscribe!(controller.signal)) {
66
+ if (controller.signal.aborted) break
67
+ const sessionID = event.data?.sessionID
68
+ if (typeof sessionID !== "string") continue
69
+ if (event.type === INBOX_ENQUEUED) releaseAll(sessionID, false)
70
+ else if (event.type === INTERRUPTED) releaseAll(sessionID, true)
71
+ }
72
+ } catch {
73
+ // The stream ends on dispose; holds still end by polling or the cap.
74
+ }
75
+ })()
76
+ }
77
+
78
+ /** The session's pending work that the user has not declined to wait for. */
79
+ const awaited = (sessionID: string) => {
80
+ const ids = options.pending(sessionID)
81
+ const skip = declined.get(sessionID)
82
+ if (!skip) return ids
83
+ // Forget declined work once it finishes, so the set stays bounded.
84
+ for (const id of skip) if (!ids.includes(id)) skip.delete(id)
85
+ if (skip.size === 0) declined.delete(sessionID)
86
+ return ids.filter((id) => !skip.has(id))
87
+ }
88
+
89
+ return {
90
+ /** The `experimental.idle` hook: resolves once the session may go idle. */
91
+ async idle(event: { sessionID: string }): Promise<void> {
92
+ const sessionID = event.sessionID
93
+ if (controller.signal.aborted || awaited(sessionID).length === 0) return
94
+ if (!(await options.owns(sessionID).catch(() => false))) return
95
+ const ids = awaited(sessionID)
96
+ if (ids.length === 0 || controller.signal.aborted) return
97
+
98
+ await new Promise<void>((resolve) => {
99
+ let poll: ReturnType<typeof setInterval> | undefined
100
+ let cap: ReturnType<typeof setTimeout> | undefined
101
+ const hold: Hold = {
102
+ ids,
103
+ release: () => {
104
+ clearInterval(poll)
105
+ clearTimeout(cap)
106
+ const active = holds.get(sessionID)
107
+ active?.delete(hold)
108
+ if (active?.size === 0) holds.delete(sessionID)
109
+ resolve()
110
+ },
111
+ }
112
+ const active = holds.get(sessionID) ?? new Set()
113
+ active.add(hold)
114
+ holds.set(sessionID, active)
115
+
116
+ poll = setInterval(() => {
117
+ if (controller.signal.aborted || awaited(sessionID).length === 0) hold.release()
118
+ }, pollMs)
119
+ poll.unref?.()
120
+ if (maxHoldMs > 0 && Number.isFinite(maxHoldMs)) {
121
+ cap = setTimeout(() => hold.release(), maxHoldMs)
122
+ cap.unref?.()
123
+ }
124
+ })
125
+ },
126
+ dispose() {
127
+ controller.abort()
128
+ for (const sessionID of [...holds.keys()]) releaseAll(sessionID, false)
129
+ },
130
+ }
131
+ }
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@ import { createShim } from "./shim.ts"
17
17
  import { boundedMessages, historyLimits, recentConversation, textOf } from "./prompt.ts"
18
18
  import { createAcpLanguageModel } from "./language-model.ts"
19
19
  import { createMcpServer } from "./mcp-server.ts"
20
+ import { createBackgroundHold } from "./background-hold.ts"
20
21
  import { createSteering, type LocalService } from "./steering.ts"
21
22
  import { createSkillMirror } from "./skills.ts"
22
23
  import { createCommandBridge } from "./commands.ts"
@@ -92,6 +93,8 @@ function storedSessionKey(poolKey: string) {
92
93
  /**
93
94
  * Resolve an ACP continuation token when OpenCode is running a turn prompted by
94
95
  * a background-completion synthetic message rather than a new user prompt.
96
+ * A wake queued behind another pending message is left for a normal prompt, so
97
+ * only a lone user message at the turn boundary can attach a continuation.
95
98
  */
96
99
  function continuationTokenOf(
97
100
  messages: ReadonlyArray<{
@@ -102,16 +105,21 @@ function continuationTokenOf(
102
105
  sessionID: string,
103
106
  manager: Pick<AcpServerManager, "findContinuationByText">,
104
107
  ): string | undefined {
108
+ let pending: (typeof messages)[number] | undefined
105
109
  for (let i = messages.length - 1; i >= 0; i--) {
106
110
  const message = messages[i]
107
111
  if (!message) continue
108
- if (message.role === "assistant") return undefined
112
+ if (message.role === "assistant" || message.role === "tool") break
109
113
  if (message.role !== "user") continue
110
- const token = message.metadata?.source === "acp-background" ? message.metadata.acpContinuation : undefined
111
- if (typeof token === "string" && token) return token
112
- return sessionID ? manager.findContinuationByText(sessionID, textOf(message)) : undefined
114
+ if (!textOf(message).trim()) continue
115
+ // More than one pending message means the turn is not only the wake.
116
+ if (pending) return undefined
117
+ pending = message
113
118
  }
114
- return undefined
119
+ if (!pending) return undefined
120
+ const token = pending.metadata?.source === "acp-background" ? pending.metadata.acpContinuation : undefined
121
+ if (typeof token === "string" && token) return token
122
+ return sessionID ? manager.findContinuationByText(sessionID, textOf(pending)) : undefined
115
123
  }
116
124
 
117
125
 
@@ -511,8 +519,10 @@ export default Plugin.define({
511
519
  throw error
512
520
  }
513
521
 
522
+ let backgroundHold: ReturnType<typeof createBackgroundHold> | undefined
514
523
  const cleanup = async () => {
515
524
  disposed = true
525
+ backgroundHold?.dispose()
516
526
  continuations.clear()
517
527
  for (const timer of retryTimers) clearTimeout(timer)
518
528
  retryTimers.clear()
@@ -685,6 +695,28 @@ export default Plugin.define({
685
695
  })
686
696
  registrations.push(await ctx.session.hook("prompt", steer))
687
697
 
698
+ // The session stays busy while its agent's background command runs, and
699
+ // the command's wake-up continues that same execution.
700
+ backgroundHold = createBackgroundHold({
701
+ pending: (sessionID) => manager.pendingBackgroundWork(sessionID),
702
+ owns: async (sessionID) => {
703
+ if (typeof ctx.session.get !== "function") return true
704
+ const session = await ctx.session.get({ sessionID: sessionID as any })
705
+ return serverForProvider.has(session?.model?.providerID ?? "")
706
+ },
707
+ subscribe:
708
+ typeof ctx.event?.subscribe === "function"
709
+ ? (signal) =>
710
+ ctx.event.subscribe({
711
+ types: ["session.inbox.enqueued", "session.execution.interrupted"],
712
+ signal,
713
+ }) as AsyncIterable<{ type: string; data?: { sessionID?: unknown } }>
714
+ : undefined,
715
+ maxHoldMs: options.promptTimeoutMs,
716
+ })
717
+ const hold = backgroundHold
718
+ registrations.push(await ctx.session.hook("experimental.idle", (event) => hold.idle(event)))
719
+
688
720
  // Hooks must be in place before models become selectable. Discovery then
689
721
  // runs in parallel without holding up OpenCode or neighboring providers.
690
722
  // A cached provider keeps its registration when an attempt fails; the
@@ -16,8 +16,38 @@ let protocolVersion = null
16
16
  let buffer = ""
17
17
  const aborters = new Map()
18
18
 
19
+ function extractErrorMessage(error, seen) {
20
+ if (error === null || error === undefined) return undefined
21
+ if (typeof error === "string") return error.trim() ? error : undefined
22
+ if (typeof error !== "object") {
23
+ try {
24
+ return String(error)
25
+ } catch {
26
+ return undefined
27
+ }
28
+ }
29
+ if (seen.has(error)) return undefined
30
+ seen.add(error)
31
+ if (typeof error.message === "string" && error.message.trim()) return error.message
32
+ if (error.cause !== undefined) {
33
+ const caused = extractErrorMessage(error.cause, seen)
34
+ if (caused) return caused
35
+ }
36
+ if (typeof error.name === "string" && error.name.trim()) return error.name
37
+ try {
38
+ const text = String(error).trim()
39
+ return text && text !== "[object Object]" ? text : undefined
40
+ } catch {
41
+ return undefined
42
+ }
43
+ }
44
+
45
+ function errorMessage(error) {
46
+ return extractErrorMessage(error, new Set()) ?? "Unknown error"
47
+ }
48
+
19
49
  process.stdout.on("error", (error) => {
20
- process.stderr.write(`mcp-bridge: stdout failed: ${error.message}\n`)
50
+ process.stderr.write(`mcp-bridge: stdout failed: ${errorMessage(error)}\n`)
21
51
  process.exit(1)
22
52
  })
23
53
  process.stderr.on("error", () => process.exit(1))
@@ -95,7 +125,7 @@ async function handle(message) {
95
125
  try {
96
126
  await post(message)
97
127
  } catch (error) {
98
- log(error instanceof Error ? error.message : String(error))
128
+ log(errorMessage(error))
99
129
  }
100
130
  return
101
131
  }
@@ -117,7 +147,7 @@ async function handle(message) {
117
147
  write({
118
148
  jsonrpc: "2.0",
119
149
  id: message.id,
120
- error: { code: -32000, message: error instanceof Error ? error.message : String(error) },
150
+ error: { code: -32000, message: errorMessage(error) },
121
151
  })
122
152
  } finally {
123
153
  aborters.delete(message.id)
@@ -145,6 +175,6 @@ process.stdin.on("data", (chunk) => {
145
175
  process.stdin.on("end", () => process.exit(0))
146
176
  process.stdin.on("close", () => process.exit(0))
147
177
  process.stdin.on("error", (error) => {
148
- log(error.message)
178
+ log(errorMessage(error))
149
179
  process.exit(1)
150
180
  })
package/src/mcp-server.ts CHANGED
@@ -866,12 +866,19 @@ async function buildTools(
866
866
  },
867
867
  {
868
868
  name: "worktree_create",
869
- description: "Create a git worktree for the calling session's project and return its directory. Pass `from` to start it at a specific commit or ref. Mirrors worktree.create.",
869
+ description:
870
+ "Create a detached git worktree for the calling session's project and return its directory. Defaults to the project's canonical checkout HEAD; pass `from` for another existing checkout/worktree directory or `branch` for an existing starting ref (commit, branch, or tag). Mirrors worktree.create.",
870
871
  inputSchema: objectSchema({
871
- from: stringSchema("Commit, branch, or tag to start from. Defaults to the project's current HEAD."),
872
- branch: stringSchema("Branch for the worktree."),
873
- name: stringSchema("Name for the worktree; used to pick its directory."),
874
- directory: stringSchema("Requested directory. The worktree strategy may choose another; use the returned directory."),
872
+ from: stringSchema(
873
+ "Absolute path of an existing checkout or worktree directory to start from. Defaults to the project's canonical checkout. Do not pass a commit SHA or ref here; use `branch` for refs.",
874
+ ),
875
+ branch: stringSchema(
876
+ "Existing git ref (commit SHA, branch, or tag) to start the detached worktree at, not the name of a new branch to create.",
877
+ ),
878
+ name: stringSchema("Name for the worktree; used to pick its directory name."),
879
+ directory: stringSchema(
880
+ "Parent directory for the new worktree. Uses the project's configured worktree directory or OpenCode's default if omitted; the strategy may choose another, so use the returned directory.",
881
+ ),
875
882
  }),
876
883
  call: async (args, signal) => {
877
884
  await assertPermission(ctx, sessionKey, "worktree", "*", "create", signal)
@@ -934,7 +941,8 @@ async function assertPermission(
934
941
  } as any)
935
942
  } catch (error) {
936
943
  if (signal.aborted) throw error
937
- const message = error instanceof Error && error.message ? `: ${error.message}` : ""
944
+ const detail = errorMessage(error)
945
+ const message = detail !== "Error" && detail !== "Unknown error" ? `: ${detail}` : ""
938
946
  const scope = target === "*" ? "" : ` on ${target}`
939
947
  throw new Error(`Permission denied: ${action} ${operation}${scope}${message}`)
940
948
  }
package/src/prompt.ts CHANGED
@@ -50,6 +50,10 @@ const speaker = (message: ChatMessage) => message.role === "assistant" ? "Assist
50
50
  * Keep the current turn intact, plus the suffix needed to reconstruct bounded
51
51
  * replay. One extra history character lets the shim detect truncation without
52
52
  * losing the original clipping or sending the whole oldest retained message.
53
+ *
54
+ * OpenCode drains every message queued while it was busy after the last
55
+ * assistant reply, so a turn can be several consecutive user messages. All of
56
+ * them are the current turn and none of them may be clipped or dropped.
53
57
  */
54
58
  export function boundedMessages<T extends ChatMessage>(
55
59
  messages: readonly T[],
@@ -57,14 +61,16 @@ export function boundedMessages<T extends ChatMessage>(
57
61
  includeSystem: boolean,
58
62
  ): Array<{ message: T; text: string }> {
59
63
  const kept: Array<{ message: T; text: string }> = []
60
- let latest = false
64
+ let phase: "tail" | "current-user" | "history" = "tail"
65
+ // A tool-only assistant turn has no text to replay, but it still separates
66
+ // trailing user messages from older history. Hold it back until some older
67
+ // history is kept, so no dangling blank assistant message is emitted.
68
+ let boundary: T | undefined
61
69
  let turns = 0
62
70
  let budget = limits.chars > 0 ? limits.chars + 1 : 0
63
71
  for (let i = messages.length - 1; i >= 0; i--) {
64
72
  const message = messages[i]
65
73
  if (!message) continue
66
- const historyFull = turns >= limits.turns || budget <= 0
67
- if (latest && historyFull && !includeSystem) break
68
74
  if (message.role === "system") {
69
75
  if (includeSystem) {
70
76
  const text = textOf(message)
@@ -72,14 +78,39 @@ export function boundedMessages<T extends ChatMessage>(
72
78
  }
73
79
  continue
74
80
  }
75
- if (!conversational(message) || (latest && historyFull)) continue
81
+ if (phase === "history" && (turns >= limits.turns || budget <= 0) && !includeSystem) break
82
+ if (!conversational(message)) {
83
+ // A tool result ends the assistant turn that follows the current user.
84
+ if (phase === "current-user") phase = "history"
85
+ continue
86
+ }
76
87
  const text = textOf(message)
77
- if (!text.trim()) continue
78
- if (!latest) {
88
+ if (phase === "tail") {
89
+ if (!text.trim()) continue
79
90
  kept.push({ message, text })
80
- latest = true
91
+ phase = message.role === "user" ? "current-user" : "history"
92
+ continue
93
+ }
94
+ if (phase === "current-user") {
95
+ if (message.role === "user") {
96
+ if (text.trim()) kept.push({ message, text })
97
+ continue
98
+ }
99
+ phase = "history"
100
+ }
101
+ const historyFull = turns >= limits.turns || budget <= 0
102
+ if (historyFull) {
103
+ if (!includeSystem) break
81
104
  continue
82
105
  }
106
+ if (!text.trim()) {
107
+ if (message.role === "assistant" && turns === 0 && !boundary) boundary = message
108
+ continue
109
+ }
110
+ if (boundary) {
111
+ kept.push({ message: boundary, text: "" })
112
+ boundary = undefined
113
+ }
83
114
  const tail = text.length > budget ? text.slice(-budget) : text
84
115
  // The visible prefix is clipped away; it keeps a whitespace-only tail
85
116
  // from being mistaken for an originally empty turn by the shim.
@@ -91,7 +122,10 @@ export function boundedMessages<T extends ChatMessage>(
91
122
  }
92
123
 
93
124
  function historyText(turns: Array<{ message: ChatMessage; text: string }>, chars: number) {
94
- const text = turns.map(({ message, text }) => `${speaker(message)}${text}`).join("\n\n")
125
+ const text = turns
126
+ .filter(({ text }) => text.trim())
127
+ .map(({ message, text }) => `${speaker(message)}${text}`)
128
+ .join("\n\n")
95
129
  return text.length > chars ? `[...earlier history omitted...]\n\n${text.slice(-chars)}` : text
96
130
  }
97
131
 
@@ -106,7 +140,10 @@ export function recentConversation(messages: ChatMessage[], limits: HistoryLimit
106
140
  export function buildPrompts(messages: ChatMessage[], limits: HistoryLimits, includeSystem: boolean) {
107
141
  const turns = boundedMessages(messages, limits, includeSystem)
108
142
  const conversation = turns.filter(({ message }) => conversational(message))
109
- const latest = conversation.pop()?.text ?? ""
143
+ // Every trailing user message is part of the same turn; send them together.
144
+ const pending: string[] = []
145
+ while (conversation.at(-1)?.message.role === "user") pending.unshift(conversation.pop()!.text)
146
+ const latest = pending.length ? pending.join("\n\n") : conversation.pop()?.text ?? ""
110
147
  const history = historyText(conversation, limits.chars)
111
148
  const system = turns.filter(({ message }) => message.role === "system").map(({ text }) => text).join("\n\n")
112
149
  return {
@@ -12,7 +12,8 @@ import {
12
12
  import { AgentPool, type AgentLaunch, type AgentLease, type AgentSubscriber } from "./agent-pool.ts"
13
13
  import { applyCmdMods } from "./agents/cmd/index.ts"
14
14
  import { isCmdCommand } from "./agent-command.ts"
15
- import { commandOf, record, text } from "./acp-tools/shared.ts"
15
+ import { commandCodeBackgroundTask } from "./acp-tools/command-code.ts"
16
+ import { commandOf, record, terminalEvents, text, toolUpdateStatus } from "./acp-tools/shared.ts"
16
17
  import { effortLevels, inventoryKey, type AcpCatalog } from "./inventory.ts"
17
18
  import { runSetup } from "./setup.ts"
18
19
  import {
@@ -182,6 +183,12 @@ interface PooledSession {
182
183
  mcpRelease?: () => void
183
184
  /** Tools started in an earlier turn that had not settled when that turn returned. */
184
185
  backgroundTools: Map<string, TrackedBackgroundTool>
186
+ /**
187
+ * Processes the agent left running whose end it never reports (Command
188
+ * Code's background shell tasks), by task id. Only the process id tells
189
+ * whether one still runs.
190
+ */
191
+ backgroundProcesses: Map<string, number>
185
192
  /** Autonomous post-turn continuation currently streaming for this session, if any. */
186
193
  activeUnsolicited?: UnsolicitedTurn
187
194
  activeUnsolicitedTools?: Map<string, TurnToolRecord>
@@ -196,6 +203,18 @@ interface TrackedBackgroundTool extends BackgroundToolRecord {
196
203
 
197
204
  interface TurnToolRecord extends TrackedBackgroundTool {
198
205
  terminal: boolean
206
+ /** The call's display terminal is open, so its command still runs. */
207
+ terminalOpen: boolean
208
+ }
209
+
210
+ /**
211
+ * A call's `_meta` without its terminal events, so a later remapped update
212
+ * cannot replay the output or exit of the call that started it.
213
+ */
214
+ function withoutTerminalMeta(meta: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
215
+ if (!meta) return undefined
216
+ const { terminal_info, terminal_output, terminal_output_delta, terminal_exit, ...rest } = meta
217
+ return Object.keys(rest).length ? rest : undefined
199
218
  }
200
219
 
201
220
  export interface AcpUnsolicitedTurnInfo {
@@ -231,6 +250,20 @@ const MAX_TURN_FAILURES = 3
231
250
  const COMMAND_SNAPSHOT_TIMEOUT_MS = 2_000
232
251
  const SWEEP_INTERVAL_MS = 60_000
233
252
  const MAX_BACKGROUND_TOOLS = 64
253
+ /** The `agentInfo.name` of codex-acp. */
254
+ const CODEX_AGENT = "@agentclientprotocol/codex-acp"
255
+ /** How long to wait for an answer from an agent that does not answer background completions. */
256
+ const NO_REPLY_AWAIT_MS = 1_500
257
+
258
+ /** Whether process `pid` still exists. `EPERM` means it does, under another user. */
259
+ function processRuns(pid: number): boolean {
260
+ try {
261
+ process.kill(pid, 0)
262
+ return true
263
+ } catch (error) {
264
+ return (error as NodeJS.ErrnoException).code === "EPERM"
265
+ }
266
+ }
234
267
 
235
268
  export class AcpServerManager {
236
269
  readonly servers = new Map<string, AcpServerState>()
@@ -613,6 +646,7 @@ export class AcpServerManager {
613
646
  pooled.history = "fresh"
614
647
  pooled.selection = selection
615
648
  pooled.backgroundTools.clear()
649
+ pooled.backgroundProcesses.clear()
616
650
  if (lease) {
617
651
  pooled.mcpRelease?.()
618
652
  pooled.mcpServers = lease.servers
@@ -1066,6 +1100,7 @@ export class AcpServerManager {
1066
1100
  broken: false,
1067
1101
  mcpRelease: lease?.release,
1068
1102
  backgroundTools: new Map(),
1103
+ backgroundProcesses: new Map(),
1069
1104
  pendingContinuations: new Map(),
1070
1105
  }
1071
1106
  this.pools.set(poolKey, created)
@@ -1198,6 +1233,7 @@ export class AcpServerManager {
1198
1233
  pooled.activeUnsolicited = undefined
1199
1234
  pooled.activeUnsolicitedTools = undefined
1200
1235
  pooled.backgroundTools.clear()
1236
+ pooled.backgroundProcesses.clear()
1201
1237
  const error = new Error(`ACP session ${pooled.sessionId} was closed`)
1202
1238
  for (const turn of turns) turn.fail(error)
1203
1239
  pooled.mcpRelease?.()
@@ -1211,6 +1247,23 @@ export class AcpServerManager {
1211
1247
  )
1212
1248
  }
1213
1249
 
1250
+ /**
1251
+ * Ids of this OpenCode session's unfinished ACP background work: tools still
1252
+ * running after their turn returned, and wake-ups no turn has attached yet.
1253
+ */
1254
+ pendingBackgroundWork(sessionKey: string): string[] {
1255
+ const ids: string[] = []
1256
+ for (const pooled of this.pools.values()) {
1257
+ if (pooled.key !== sessionKey || pooled.broken) continue
1258
+ ids.push(...pooled.backgroundTools.keys(), ...pooled.pendingContinuations.keys())
1259
+ for (const [taskId, pid] of pooled.backgroundProcesses) {
1260
+ if (processRuns(pid)) ids.push(`process:${taskId}`)
1261
+ else pooled.backgroundProcesses.delete(taskId)
1262
+ }
1263
+ }
1264
+ return ids
1265
+ }
1266
+
1214
1267
  /** Find an unattached continuation token matching a synthetic wake-up message's text. */
1215
1268
  findContinuationByText(sessionKey: string, promptText: string): string | undefined {
1216
1269
  for (const pooled of this.pools.values()) {
@@ -1263,15 +1316,17 @@ export class AcpServerManager {
1263
1316
 
1264
1317
  private trackAndRemapUpdate(
1265
1318
  pooled: PooledSession,
1266
- update: SessionUpdate,
1319
+ incoming: SessionUpdate,
1267
1320
  turnTools: Map<string, TurnToolRecord>,
1268
1321
  ): SessionUpdate {
1269
- if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") return update
1270
- const rawId = text(update.toolCallId)
1271
- if (!rawId) return update
1272
-
1273
- const status = text(update.status)
1274
- const terminal = status === "completed" || status === "failed"
1322
+ if (incoming.sessionUpdate !== "tool_call" && incoming.sessionUpdate !== "tool_call_update") return incoming
1323
+ const rawId = text(incoming.toolCallId)
1324
+ if (!rawId) return incoming
1325
+
1326
+ // A bare `terminal_exit` ends the call, so give it the status it implies.
1327
+ const status = toolUpdateStatus(incoming)
1328
+ const update = status && !text(incoming.status) ? { ...incoming, status } : incoming
1329
+ const settled = status === "completed" || status === "failed"
1275
1330
  const incomingRaw = record(update.rawInput)
1276
1331
  const hasIncomingRaw = incomingRaw !== undefined && Object.keys(incomingRaw).length > 0
1277
1332
  const name = text(update.name)
@@ -1279,32 +1334,49 @@ export class AcpServerManager {
1279
1334
  const kind = text(update.kind)
1280
1335
  const meta = record(update._meta)
1281
1336
  const command = commandOf(incomingRaw?.CommandLine ?? incomingRaw?.command)
1337
+ const events = terminalEvents(update)
1282
1338
 
1283
1339
  const background = pooled.backgroundTools.get(rawId)
1284
1340
  if (background) {
1285
1341
  const mergedRaw = hasIncomingRaw ? incomingRaw : background.rawInput
1342
+ // The agent-native fields of the first call (such as Claude's tool name)
1343
+ // keep the result on the same card type.
1344
+ const mergedMeta = background.meta || meta ? { ...background.meta, ...meta } : undefined
1286
1345
  const remapped: SessionUpdate = {
1287
1346
  ...update,
1288
1347
  toolCallId: `${rawId}:result`,
1289
1348
  ...(!name && background.name ? { name: background.name } : {}),
1290
1349
  ...(!title && background.title ? { title: background.title } : {}),
1291
1350
  ...(!kind && background.kind ? { kind: background.kind } : {}),
1292
- ...(!meta && background.meta ? { _meta: background.meta } : {}),
1351
+ ...(mergedMeta ? { _meta: mergedMeta } : {}),
1293
1352
  ...(mergedRaw ? { rawInput: mergedRaw } : {}),
1294
1353
  }
1295
- if (terminal) pooled.backgroundTools.delete(rawId)
1354
+ if (settled) pooled.backgroundTools.delete(rawId)
1296
1355
  return remapped
1297
1356
  }
1298
1357
 
1358
+ const task = commandCodeBackgroundTask(update)
1359
+ if (task) {
1360
+ while (pooled.backgroundProcesses.size >= MAX_BACKGROUND_TOOLS) {
1361
+ const oldest = pooled.backgroundProcesses.keys().next().value
1362
+ if (oldest === undefined) break
1363
+ pooled.backgroundProcesses.delete(oldest)
1364
+ }
1365
+ pooled.backgroundProcesses.set(task.taskId, task.pid)
1366
+ }
1367
+
1299
1368
  const prior = turnTools.get(rawId)
1369
+ const terminalOpen = (Boolean(prior?.terminalOpen) || events.opened) && !events.exited
1300
1370
  turnTools.set(rawId, {
1301
1371
  name: name ?? prior?.name,
1302
1372
  title: title ?? prior?.title,
1303
1373
  kind: kind ?? prior?.kind,
1304
- meta: meta ?? prior?.meta,
1374
+ meta: withoutTerminalMeta(meta) ?? prior?.meta,
1305
1375
  command: command ?? prior?.command,
1306
1376
  rawInput: hasIncomingRaw ? incomingRaw : prior?.rawInput,
1307
- terminal: terminal || Boolean(prior?.terminal),
1377
+ terminalOpen,
1378
+ // A completed call whose terminal is still open went to the background.
1379
+ terminal: status === "failed" || (status === "completed" && !terminalOpen) || Boolean(prior?.terminal),
1308
1380
  })
1309
1381
  return update
1310
1382
  }
@@ -1351,12 +1423,19 @@ export class AcpServerManager {
1351
1423
 
1352
1424
  const rawId = text(update.toolCallId)
1353
1425
  const background = rawId ? pooled.backgroundTools.get(rawId) : undefined
1354
- const { description, text: summaryText } = unsolicitedSummary(update, background, agentName(state.config))
1355
1426
  const turnTools = new Map<string, TurnToolRecord>()
1427
+ const mapped = this.trackAndRemapUpdate(pooled, update, turnTools)
1428
+ const { description, text: summaryText } = unsolicitedSummary(mapped, background, agentName(state.config))
1356
1429
  const turn = new UnsolicitedTurn({
1357
1430
  description,
1358
1431
  text: summaryText,
1359
- timing: { maxTurnMs: this.promptTimeoutMs, ...this.unsolicitedTiming },
1432
+ timing: {
1433
+ maxTurnMs: this.promptTimeoutMs,
1434
+ // Codex reports a background command's end but never answers it on
1435
+ // its own, so a long wait for its reply only keeps the session busy.
1436
+ ...(pooled.client.agentName === CODEX_AGENT ? { awaitingResponseMs: NO_REPLY_AWAIT_MS } : {}),
1437
+ ...this.unsolicitedTiming,
1438
+ },
1360
1439
  onSettled: (result) => {
1361
1440
  if (pooled.activeUnsolicited === turn) {
1362
1441
  pooled.activeUnsolicited = undefined
@@ -1377,7 +1456,7 @@ export class AcpServerManager {
1377
1456
  pooled.pendingContinuations.set(turn.token, turn)
1378
1457
  pooled.lastUsed = Date.now()
1379
1458
 
1380
- turn.push(this.trackAndRemapUpdate(pooled, update, turnTools))
1459
+ turn.push(mapped)
1381
1460
  this.onUnsolicited?.({
1382
1461
  server: state.config.id,
1383
1462
  sessionKey: pooled.key,
@@ -1527,6 +1606,7 @@ export class AcpServerManager {
1527
1606
  pooled.activeUnsolicited = undefined
1528
1607
  pooled.activeUnsolicitedTools = undefined
1529
1608
  pooled.backgroundTools.clear()
1609
+ pooled.backgroundProcesses.clear()
1530
1610
  for (const turn of turns) turn.dispose()
1531
1611
  pooled.mcpRelease?.()
1532
1612
  pooled.client.cancelTurn(pooled.sessionId, this)
package/src/util.ts CHANGED
@@ -62,9 +62,67 @@ export function agentName(config: { name?: string; id: string }) {
62
62
  return (config.name ?? config.id).replace(/\s*\(ACP\)$/, "")
63
63
  }
64
64
 
65
+ function nonEmptyString(value: unknown): string | undefined {
66
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined
67
+ }
68
+
69
+ function extractErrorMessage(error: unknown, seen: Set<unknown>): string | undefined {
70
+ if (error === null || error === undefined) return undefined
71
+ if (typeof error === "string") return nonEmptyString(error)
72
+ if (typeof error !== "object") return String(error)
73
+ if (seen.has(error)) return undefined
74
+ seen.add(error)
75
+
76
+ const record = error as Record<string, unknown>
77
+ const direct = nonEmptyString(record.message)
78
+ if (direct) return direct
79
+
80
+ const data = record.data
81
+ if (data && typeof data === "object") {
82
+ const nested = nonEmptyString((data as Record<string, unknown>).message)
83
+ if (nested) return nested
84
+ }
85
+
86
+ if ("cause" in record && record.cause !== undefined) {
87
+ const caused = extractErrorMessage(record.cause, seen)
88
+ if (caused) return caused
89
+ }
90
+
91
+ if ("error" in record && record.error !== undefined) {
92
+ const inner = extractErrorMessage(record.error, seen)
93
+ if (inner) return inner
94
+ }
95
+
96
+ if (Array.isArray(record.errors)) {
97
+ const parts = record.errors
98
+ .map((item) => extractErrorMessage(item, seen))
99
+ .filter((item): item is string => Boolean(item))
100
+ if (parts.length) return parts.join("; ")
101
+ }
102
+
103
+ const tag = nonEmptyString(record._tag) ?? nonEmptyString(record.name)
104
+ if (tag) return tag
105
+
106
+ try {
107
+ const text = String(error).trim()
108
+ if (text && text !== "[object Object]") return text
109
+ } catch {
110
+ // null-prototype or otherwise unconvertible
111
+ }
112
+
113
+ try {
114
+ const json = JSON.stringify(error)
115
+ if (json && json !== "{}") return json
116
+ } catch {
117
+ // circular or otherwise unserializable
118
+ }
119
+
120
+ return undefined
121
+ }
122
+
65
123
  /** The message of a thrown value, whatever was thrown. */
66
- export function errorMessage(error: unknown) {
67
- return error instanceof Error ? error.message : String(error)
124
+ export function errorMessage(error: unknown): string {
125
+ return extractErrorMessage(error, new Set()) ?? "Unknown error"
68
126
  }
69
127
 
70
128
  /** Listen on an ephemeral loopback port and return it. */