opencode-acp-provider 1.1.2 → 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 +1 -1
- package/package.json +1 -1
- package/src/acp-client.ts +12 -0
- package/src/acp-tools/command-code.ts +19 -0
- package/src/acp-tools/shared.ts +34 -3
- package/src/acp-tools.ts +18 -5
- package/src/background-hold.ts +131 -0
- package/src/index.ts +25 -0
- package/src/server-manager.ts +95 -15
package/README.md
CHANGED
|
@@ -380,7 +380,7 @@ Restarting the service refreshes discovery. Slash commands are still discovered
|
|
|
380
380
|
| `outputLimit` | Output limit advertised for ACP models. Defaults to `32000`. |
|
|
381
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. |
|
|
382
382
|
| `requestTimeoutMs` | Timeout for the ACP handshake and control calls such as `session/new`. Defaults to `15000`; raise it for agents that start slowly. |
|
|
383
|
-
| `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. |
|
|
384
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. |
|
|
385
385
|
| `mcp` | Expose OpenCode tools to ACP agents through the MCP bridge. Defaults to `true`. |
|
|
386
386
|
| `commands` | Register the agents' own slash commands as namespaced OpenCode commands. Defaults to `true`. See [Commands](#commands). |
|
package/package.json
CHANGED
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
|
+
}
|
package/src/acp-tools/shared.ts
CHANGED
|
@@ -101,9 +101,40 @@ export function diffsOf(update: SessionUpdate): DiffItem[] {
|
|
|
101
101
|
return diffs
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
/**
|
|
105
|
-
|
|
106
|
-
|
|
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
|
-
|
|
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
|
|
161
|
-
const streamedTerminal = Boolean(meta?.streamedTerminal ||
|
|
162
|
-
const streamed =
|
|
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
|
|
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,
|
|
@@ -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"
|
|
@@ -518,8 +519,10 @@ export default Plugin.define({
|
|
|
518
519
|
throw error
|
|
519
520
|
}
|
|
520
521
|
|
|
522
|
+
let backgroundHold: ReturnType<typeof createBackgroundHold> | undefined
|
|
521
523
|
const cleanup = async () => {
|
|
522
524
|
disposed = true
|
|
525
|
+
backgroundHold?.dispose()
|
|
523
526
|
continuations.clear()
|
|
524
527
|
for (const timer of retryTimers) clearTimeout(timer)
|
|
525
528
|
retryTimers.clear()
|
|
@@ -692,6 +695,28 @@ export default Plugin.define({
|
|
|
692
695
|
})
|
|
693
696
|
registrations.push(await ctx.session.hook("prompt", steer))
|
|
694
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
|
+
|
|
695
720
|
// Hooks must be in place before models become selectable. Discovery then
|
|
696
721
|
// runs in parallel without holding up OpenCode or neighboring providers.
|
|
697
722
|
// A cached provider keeps its registration when an attempt fails; the
|
package/src/server-manager.ts
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
1319
|
+
incoming: SessionUpdate,
|
|
1267
1320
|
turnTools: Map<string, TurnToolRecord>,
|
|
1268
1321
|
): SessionUpdate {
|
|
1269
|
-
if (
|
|
1270
|
-
const rawId = text(
|
|
1271
|
-
if (!rawId) return
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
const
|
|
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
|
-
...(
|
|
1351
|
+
...(mergedMeta ? { _meta: mergedMeta } : {}),
|
|
1293
1352
|
...(mergedRaw ? { rawInput: mergedRaw } : {}),
|
|
1294
1353
|
}
|
|
1295
|
-
if (
|
|
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
|
-
|
|
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: {
|
|
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(
|
|
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)
|