opencode-acp-provider 1.0.0 → 1.1.1

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/src/shim.ts CHANGED
@@ -2,7 +2,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht
2
2
  import { randomUUID } from "node:crypto"
3
3
  import type { AcpServerManager } from "./server-manager.ts"
4
4
  import type { SessionUpdate } from "./acp-client.ts"
5
- import { applyToolUpdate, type AcpToolState } from "./acp-tools.ts"
5
+ import { applyToolUpdate, planToToolState, type AcpToolState } from "./acp-tools.ts"
6
6
  import { buildPrompts, historyLimits, isAuxiliaryRequest, type ChatMessage } from "./prompt.ts"
7
7
  import { BodyTooLargeError, endFailedResponse, errorMessage, listenLocal, readBody } from "./util.ts"
8
8
 
@@ -72,43 +72,30 @@ function finishReason(stopReason: string) {
72
72
  return "stop"
73
73
  }
74
74
 
75
- interface ToolCallState {
76
- title: string
77
- kind?: string
78
- status: string
79
- shown: boolean
75
+ function toolCallLabel(state: AcpToolState) {
76
+ let detail = ""
77
+ for (const key of ["command", "path", "query", "url", "pattern", "id", "code"]) {
78
+ const value = state.input[key]
79
+ if (typeof value === "string" && value.trim()) {
80
+ detail = truncate(value.trim(), 120)
81
+ break
82
+ }
83
+ }
84
+ if (!detail) detail = state.title ? truncate(state.title, 120) : ""
85
+ return !detail || detail.toLowerCase().startsWith(state.name.toLowerCase())
86
+ ? detail || state.name
87
+ : `${state.name}: ${detail}`
80
88
  }
81
89
 
82
90
  /**
83
91
  * ACP agents execute their own tools, so there is no OpenCode tool part to
84
92
  * render. Show each finished tool call as a compact transcript line instead.
85
93
  */
86
- function toolCallLine(update: SessionUpdate, states: Map<string, ToolCallState>) {
87
- const id = typeof update.toolCallId === "string" ? update.toolCallId : undefined
88
- if (!id) return ""
89
- const state = states.get(id) ?? { title: "tool", status: "pending", shown: false }
90
- if (typeof update.title === "string" && update.title.trim()) state.title = update.title.trim()
91
- if (typeof update.kind === "string" && update.kind) state.kind = update.kind
92
- if (typeof update.status === "string" && update.status) state.status = update.status
93
- states.set(id, state)
94
- if (state.shown || (state.status !== "completed" && state.status !== "failed")) return ""
95
- state.shown = true
96
- const kind = state.kind === "execute" ? "shell" : state.kind ?? "tool"
97
- const icon = state.status === "failed" ? "✗" : "✓"
98
- const detail = toolDetail(update) || state.title
99
- const label = detail.toLowerCase().startsWith(kind.toLowerCase()) ? detail : `${kind}: ${detail}`
100
- return `\n\n> ${icon} ${label}\n\n`
101
- }
102
-
103
- function toolDetail(update: SessionUpdate) {
104
- const raw = update.rawInput
105
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
106
- for (const key of ["command", "path", "file_path", "query", "url", "pattern"]) {
107
- const value = (raw as Record<string, unknown>)[key]
108
- if (typeof value === "string" && value.trim()) return truncate(value.trim(), 120)
109
- }
110
- }
111
- return ""
94
+ function toolCallLine(update: SessionUpdate, states: Map<string, AcpToolState>) {
95
+ const state = applyToolUpdate(update, states)
96
+ if (!state?.done) return ""
97
+ const icon = state.isError ? "✗" : "✓"
98
+ return `\n\n> ${icon} ${toolCallLabel(state)}\n\n`
112
99
  }
113
100
 
114
101
  function truncate(text: string, max: number) {
@@ -215,7 +202,13 @@ export async function createShim(options: ShimOptions) {
215
202
  // render native tool cards; the OpenAI-compatible route keeps inline lines.
216
203
  const structuredTools = req.headers["x-acp-tool-events"] === "1"
217
204
  const prompt = buildPrompts(messages, limits, auxiliary || options.includeSystem === true)
218
- if (!prompt.fresh.trim()) {
205
+ const continuationHeader = req.headers["x-acp-continuation"]
206
+ let continuation =
207
+ !auxiliary && typeof continuationHeader === "string" && continuationHeader ? continuationHeader : undefined
208
+ if (!continuation && !auxiliary && key && typeof manager.findContinuationByText === "function") {
209
+ continuation = manager.findContinuationByText(key, prompt.reused)
210
+ }
211
+ if (!continuation && !prompt.fresh.trim()) {
219
212
  sendError(res, 400, "Empty prompt")
220
213
  return
221
214
  }
@@ -263,7 +256,6 @@ export async function createShim(options: ShimOptions) {
263
256
  let firstChunkAt: number | undefined
264
257
  let firstThoughtAt: number | undefined
265
258
  const startedAt = Math.round(performance.now())
266
- const toolCalls = new Map<string, ToolCallState>()
267
259
  const acpTools = new Map<string, AcpToolState>()
268
260
  try {
269
261
  const result = await manager.run({
@@ -273,6 +265,7 @@ export async function createShim(options: ShimOptions) {
273
265
  prompt,
274
266
  key,
275
267
  sessionKey: key,
268
+ continuation,
276
269
  signal: controller.signal,
277
270
  onUpdate: (update: SessionUpdate) => {
278
271
  if (update.sessionUpdate === "agent_thought_chunk" && update.content?.type === "text") {
@@ -312,16 +305,63 @@ export async function createShim(options: ShimOptions) {
312
305
  })
313
306
  }
314
307
  } else if (toolCallDisplay) {
315
- const line = toolCallLine(update, toolCalls)
308
+ const line = toolCallLine(update, acpTools)
316
309
  if (line) {
317
310
  emitted += line
318
311
  writeChunk({ content: line })
319
312
  }
320
313
  }
314
+ } else if (update.sessionUpdate === "plan") {
315
+ if (structuredTools) {
316
+ const state = planToToolState(update)
317
+ if (state) {
318
+ writeChunk({
319
+ _acp_tool: {
320
+ id: state.id,
321
+ name: state.name,
322
+ kind: state.kind,
323
+ title: state.title,
324
+ status: state.status,
325
+ input: state.input,
326
+ output: state.output,
327
+ isError: state.isError,
328
+ done: state.done,
329
+ },
330
+ })
331
+ }
332
+ }
321
333
  }
322
334
  },
323
335
  })
324
336
 
337
+ // Tools left running when a prompt returns normally were backgrounded by the agent.
338
+ if (result.stopReason !== "cancelled") {
339
+ for (const state of acpTools.values()) {
340
+ if (state.done || state.hidden) continue
341
+ if (structuredTools) {
342
+ const note = state.name === "shell" ? "Running in background." : "Still running in background."
343
+ const output = state.output ? `${state.output}\n${note}` : note
344
+ writeChunk({
345
+ _acp_tool: {
346
+ id: state.id,
347
+ name: state.name,
348
+ kind: state.kind,
349
+ title: state.title,
350
+ status: "running",
351
+ input: state.input,
352
+ output,
353
+ isError: false,
354
+ done: true,
355
+ },
356
+ })
357
+ } else if (toolCallDisplay) {
358
+ const line = `\n\n> ⋯ ${toolCallLabel(state)} (running in background)\n\n`
359
+ emitted += line
360
+ writeChunk({ content: line })
361
+ }
362
+ }
363
+ }
364
+
325
365
  if (!emitted && result.text) {
326
366
  emitted = result.text
327
367
  writeChunk({ content: result.text })
@@ -0,0 +1,388 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import type { PromptResult, SessionUpdate } from "./acp-client.ts"
3
+ import { commandOf, record, text } from "./acp-tools/shared.ts"
4
+
5
+ export interface UnsolicitedTimingOptions {
6
+ /** Wait after a background or follow-up tool completes before the model starts responding. */
7
+ awaitingResponseMs?: number
8
+ /** Wait between thought chunks or plan updates. */
9
+ thinkingIdleMs?: number
10
+ /** Wait after a thought-only `usage_update` before concluding no tool or answer follows. */
11
+ thoughtUsageMs?: number
12
+ /** Fallback idle wait after `agent_message_chunk` if the agent emits no `usage_update`. */
13
+ messageIdleMs?: number
14
+ /** Grace window after `agent_message_chunk` + `usage_update` before settling. */
15
+ postUsageMs?: number
16
+ /** Hard safety cap on an unsolicited turn (`0` disables). */
17
+ maxTurnMs?: number
18
+ /** How long a settled unattached turn stays buffered for OpenCode to attach. */
19
+ orphanTtlMs?: number
20
+ }
21
+
22
+ const DEFAULT_TIMING: Required<UnsolicitedTimingOptions> = {
23
+ awaitingResponseMs: 60_000,
24
+ thinkingIdleMs: 30_000,
25
+ thoughtUsageMs: 15_000,
26
+ messageIdleMs: 3_000,
27
+ postUsageMs: 750,
28
+ maxTurnMs: 30 * 60_000,
29
+ orphanTtlMs: 60_000,
30
+ }
31
+
32
+ export interface BackgroundToolRecord {
33
+ name?: string
34
+ title?: string
35
+ command?: string
36
+ rawInput?: Record<string, unknown>
37
+ }
38
+
39
+ export type UnsolicitedPhase =
40
+ | "awaiting-response"
41
+ | "tool-running"
42
+ | "streaming"
43
+ | "post-usage"
44
+ | "settled"
45
+
46
+ /**
47
+ * Only substantive post-turn agent output or tool progress wakes the OpenCode
48
+ * session. Metadata updates (`session_info_update`, `available_commands_update`,
49
+ * `config_option_update`, `current_mode_update`, standalone `usage_update`) can
50
+ * arrive asynchronously after `end_turn` and must not trigger a synthetic turn.
51
+ */
52
+ export function isUnsolicitedActivity(update: SessionUpdate): boolean {
53
+ switch (update.sessionUpdate) {
54
+ case "agent_message_chunk":
55
+ case "agent_thought_chunk":
56
+ return (
57
+ update.content?.type === "text" &&
58
+ typeof update.content.text === "string" &&
59
+ update.content.text.length > 0
60
+ )
61
+ case "tool_call":
62
+ case "tool_call_update":
63
+ return true
64
+ case "plan":
65
+ return Array.isArray(update.entries)
66
+ default:
67
+ return false
68
+ }
69
+ }
70
+
71
+ function truncateSummary(value: string, max = 80): string {
72
+ return value.length > max ? `${value.slice(0, max - 1)}…` : value
73
+ }
74
+
75
+ /** Build the user-visible summary for the synthetic message waking OpenCode. */
76
+ export function unsolicitedSummary(
77
+ update: SessionUpdate,
78
+ backgroundTool?: BackgroundToolRecord,
79
+ agentLabel?: string,
80
+ ): { description: string; text: string } {
81
+ if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
82
+ const raw = record(update.rawInput) ?? backgroundTool?.rawInput
83
+ const detail =
84
+ commandOf(raw?.CommandLine ?? raw?.command) ??
85
+ backgroundTool?.command ??
86
+ text(update.title) ??
87
+ backgroundTool?.title
88
+ const prefix = update.status === "failed" ? "Background command failed" : "Background command finished"
89
+ const description = detail ? `${prefix}: ${truncateSummary(detail)}` : prefix
90
+ return { description, text: description }
91
+ }
92
+ const description = agentLabel ? `${agentLabel} background task finished` : "Background task finished"
93
+ return { description, text: description }
94
+ }
95
+
96
+ function isClaudeTaskNotificationEnd(update: SessionUpdate): boolean {
97
+ if (update.cost === undefined) return false
98
+ const origin = record(record(update._meta)?.["_claude/origin"])
99
+ return origin?.kind === "task-notification"
100
+ }
101
+
102
+ export interface UnsolicitedTurnOptions {
103
+ description: string
104
+ text: string
105
+ timing?: UnsolicitedTimingOptions
106
+ onSettled?: (result: PromptResult) => void
107
+ onExpire?: () => void
108
+ }
109
+
110
+ /**
111
+ * Buffers and tracks the lifecycle of one autonomous post-turn ACP continuation
112
+ * (such as a background shell completion and the agent's reaction), because ACP
113
+ * delivers unsolicited `session/update` notifications without a closing RPC reply.
114
+ */
115
+ export class UnsolicitedTurn {
116
+ readonly token = randomUUID()
117
+ readonly description: string
118
+ readonly text: string
119
+
120
+ private readonly timing: Required<UnsolicitedTimingOptions>
121
+ private readonly onSettled?: (result: PromptResult) => void
122
+ private readonly onExpire?: () => void
123
+ private readonly buffered: SessionUpdate[] = []
124
+ private readonly activeTools = new Set<string>()
125
+ private readonly donePromise: Promise<PromptResult>
126
+ private doneResolve!: (result: PromptResult) => void
127
+ private doneReject!: (error: Error) => void
128
+
129
+ private phase: UnsolicitedPhase = "awaiting-response"
130
+ private currentIdleMs = 0
131
+ private subscriber?: (update: SessionUpdate) => void
132
+ private _attached = false
133
+ private settled = false
134
+ private stopReason = "end_turn"
135
+ private accumulatedText = ""
136
+ private failure?: Error
137
+ private stepHasMessage = false
138
+ private pendingPermissions = 0
139
+ private idleTimer?: ReturnType<typeof setTimeout>
140
+ private maxTimer?: ReturnType<typeof setTimeout>
141
+ private orphanTimer?: ReturnType<typeof setTimeout>
142
+
143
+ constructor(options: UnsolicitedTurnOptions) {
144
+ this.description = options.description
145
+ this.text = options.text
146
+ this.timing = { ...DEFAULT_TIMING, ...options.timing }
147
+ this.onSettled = options.onSettled
148
+ this.onExpire = options.onExpire
149
+ this.donePromise = new Promise<PromptResult>((resolve, reject) => {
150
+ this.doneResolve = resolve
151
+ this.doneReject = reject
152
+ })
153
+ // Rejections while unattached are observed on attach() via `this.failure`.
154
+ this.donePromise.catch(() => {})
155
+
156
+ if (this.timing.maxTurnMs > 0 && Number.isFinite(this.timing.maxTurnMs)) {
157
+ this.maxTimer = setTimeout(() => this.finish("end_turn"), this.timing.maxTurnMs)
158
+ this.maxTimer.unref?.()
159
+ }
160
+ }
161
+
162
+ get attached(): boolean {
163
+ return this._attached
164
+ }
165
+
166
+ push(update: SessionUpdate): void {
167
+ if (this.settled) return
168
+
169
+ if (
170
+ update.sessionUpdate === "agent_message_chunk" &&
171
+ update.content?.type === "text" &&
172
+ typeof update.content.text === "string"
173
+ ) {
174
+ this.accumulatedText += update.content.text
175
+ }
176
+
177
+ if (this._attached) this.subscriber?.(update)
178
+ else this.buffered.push(update)
179
+
180
+ this.advance(update)
181
+ }
182
+
183
+ permissionStarted(): void {
184
+ if (this.settled) return
185
+ this.pendingPermissions += 1
186
+ this.clearIdleTimer()
187
+ }
188
+
189
+ permissionEnded(): void {
190
+ this.pendingPermissions = Math.max(0, this.pendingPermissions - 1)
191
+ if (this.settled || this.pendingPermissions > 0 || this.activeTools.size > 0) return
192
+ this.armIdleTimer(this.currentIdleMs)
193
+ }
194
+
195
+ async attach(
196
+ onUpdate?: (update: SessionUpdate) => void,
197
+ signal?: AbortSignal,
198
+ onAbort?: () => void,
199
+ ): Promise<PromptResult> {
200
+ this._attached = true
201
+ this.clearOrphanTimer()
202
+
203
+ for (const update of this.buffered.splice(0)) onUpdate?.(update)
204
+
205
+ if (this.settled) {
206
+ if (this.failure) throw this.failure
207
+ return { stopReason: this.stopReason, text: this.accumulatedText }
208
+ }
209
+
210
+ if (signal?.aborted) {
211
+ onAbort?.()
212
+ this.cancel()
213
+ return { stopReason: "cancelled", text: this.accumulatedText }
214
+ }
215
+
216
+ this.subscriber = onUpdate
217
+ return await new Promise<PromptResult>((resolve, reject) => {
218
+ const onSignalAbort = () => {
219
+ onAbort?.()
220
+ this.cancel()
221
+ }
222
+ signal?.addEventListener("abort", onSignalAbort, { once: true })
223
+ this.donePromise.then(
224
+ (result) => {
225
+ signal?.removeEventListener("abort", onSignalAbort)
226
+ resolve(result)
227
+ },
228
+ (error) => {
229
+ signal?.removeEventListener("abort", onSignalAbort)
230
+ reject(error)
231
+ },
232
+ )
233
+ })
234
+ }
235
+
236
+ finish(stopReason = "end_turn"): void {
237
+ if (this.settled) return
238
+ this.settled = true
239
+ this.phase = "settled"
240
+ this.stopReason = stopReason
241
+ this.clearTimers()
242
+ this.subscriber = undefined
243
+ const result: PromptResult = { stopReason, text: this.accumulatedText }
244
+ this.onSettled?.(result)
245
+ this.doneResolve(result)
246
+ if (!this._attached && this.timing.orphanTtlMs > 0 && Number.isFinite(this.timing.orphanTtlMs)) {
247
+ this.orphanTimer = setTimeout(() => {
248
+ this.orphanTimer = undefined
249
+ this.onExpire?.()
250
+ }, this.timing.orphanTtlMs)
251
+ this.orphanTimer.unref?.()
252
+ }
253
+ }
254
+
255
+ cancel(): void {
256
+ this.finish("cancelled")
257
+ }
258
+
259
+ fail(error: Error): void {
260
+ if (this.settled) return
261
+ this.settled = true
262
+ this.phase = "settled"
263
+ this.failure = error
264
+ this.clearTimers()
265
+ this.subscriber = undefined
266
+ this.onSettled?.({ stopReason: "end_turn", text: this.accumulatedText })
267
+ if (this._attached) {
268
+ this.doneReject(error)
269
+ } else if (this.timing.orphanTtlMs > 0 && Number.isFinite(this.timing.orphanTtlMs)) {
270
+ this.orphanTimer = setTimeout(() => {
271
+ this.orphanTimer = undefined
272
+ this.onExpire?.()
273
+ }, this.timing.orphanTtlMs)
274
+ this.orphanTimer.unref?.()
275
+ }
276
+ }
277
+
278
+ dispose(): void {
279
+ this.clearTimers()
280
+ this.clearOrphanTimer()
281
+ this.subscriber = undefined
282
+ if (this.settled) return
283
+ this.settled = true
284
+ this.phase = "settled"
285
+ this.stopReason = "cancelled"
286
+ this.doneResolve({ stopReason: "cancelled", text: this.accumulatedText })
287
+ }
288
+
289
+ private advance(update: SessionUpdate): void {
290
+ switch (update.sessionUpdate) {
291
+ case "tool_call":
292
+ case "tool_call_update": {
293
+ const id = typeof update.toolCallId === "string" ? update.toolCallId : undefined
294
+ const status = typeof update.status === "string" ? update.status : undefined
295
+ const terminal = status === "completed" || status === "failed"
296
+ if (terminal) {
297
+ if (id) this.activeTools.delete(id)
298
+ this.stepHasMessage = false
299
+ if (this.activeTools.size > 0 || this.pendingPermissions > 0) {
300
+ this.enterPhase("tool-running", 0)
301
+ } else {
302
+ this.enterPhase("awaiting-response", this.timing.awaitingResponseMs)
303
+ }
304
+ } else {
305
+ if (id) this.activeTools.add(id)
306
+ this.stepHasMessage = false
307
+ this.enterPhase("tool-running", 0)
308
+ }
309
+ return
310
+ }
311
+ case "agent_thought_chunk": {
312
+ if (
313
+ update.content?.type === "text" &&
314
+ typeof update.content.text === "string" &&
315
+ update.content.text.length > 0
316
+ ) {
317
+ this.activeTools.clear()
318
+ this.enterPhase("streaming", this.pendingPermissions > 0 ? 0 : this.timing.thinkingIdleMs)
319
+ }
320
+ return
321
+ }
322
+ case "agent_message_chunk": {
323
+ if (
324
+ update.content?.type === "text" &&
325
+ typeof update.content.text === "string" &&
326
+ update.content.text.length > 0
327
+ ) {
328
+ this.activeTools.clear()
329
+ this.stepHasMessage = true
330
+ this.enterPhase("streaming", this.pendingPermissions > 0 ? 0 : this.timing.messageIdleMs)
331
+ }
332
+ return
333
+ }
334
+ case "plan": {
335
+ if (Array.isArray(update.entries) && this.activeTools.size === 0 && this.pendingPermissions === 0) {
336
+ this.enterPhase("streaming", this.timing.thinkingIdleMs)
337
+ }
338
+ return
339
+ }
340
+ case "usage_update": {
341
+ if (this.activeTools.size > 0 || this.pendingPermissions > 0) return
342
+ if (isClaudeTaskNotificationEnd(update)) {
343
+ this.enterPhase("post-usage", Math.min(50, this.timing.postUsageMs))
344
+ } else if (this.stepHasMessage) {
345
+ this.enterPhase("post-usage", this.timing.postUsageMs)
346
+ } else {
347
+ this.enterPhase("awaiting-response", this.timing.thoughtUsageMs)
348
+ }
349
+ return
350
+ }
351
+ default:
352
+ return
353
+ }
354
+ }
355
+
356
+ private enterPhase(phase: UnsolicitedPhase, idleMs: number): void {
357
+ this.phase = phase
358
+ this.currentIdleMs = idleMs
359
+ this.armIdleTimer(idleMs)
360
+ }
361
+
362
+ private armIdleTimer(ms: number): void {
363
+ this.clearIdleTimer()
364
+ if (this.settled || !(ms > 0) || !Number.isFinite(ms)) return
365
+ this.idleTimer = setTimeout(() => this.finish("end_turn"), ms)
366
+ this.idleTimer.unref?.()
367
+ }
368
+
369
+ private clearIdleTimer(): void {
370
+ if (!this.idleTimer) return
371
+ clearTimeout(this.idleTimer)
372
+ this.idleTimer = undefined
373
+ }
374
+
375
+ private clearOrphanTimer(): void {
376
+ if (!this.orphanTimer) return
377
+ clearTimeout(this.orphanTimer)
378
+ this.orphanTimer = undefined
379
+ }
380
+
381
+ private clearTimers(): void {
382
+ this.clearIdleTimer()
383
+ if (this.maxTimer) {
384
+ clearTimeout(this.maxTimer)
385
+ this.maxTimer = undefined
386
+ }
387
+ }
388
+ }