opencode-acp-provider 1.1.0 → 1.1.2

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.
@@ -0,0 +1,436 @@
1
+ import type { SessionUpdate } from "../acp-client.ts"
2
+
3
+ /** The agent that produced a tool call, so a status-only update keeps its mapping. */
4
+ export type AgentId = "claude" | "antigravity" | "codex" | "command-code" | "fallback"
5
+
6
+ /** The file-level diff an ACP agent reports for an edit. */
7
+ export interface DiffItem {
8
+ path?: string
9
+ oldText: string | null | undefined
10
+ newText: string | undefined
11
+ kind?: "add" | "delete" | "update"
12
+ }
13
+
14
+ export interface ToolContext {
15
+ update: SessionUpdate
16
+ raw?: Record<string, unknown>
17
+ kind?: string
18
+ title?: string
19
+ topName?: string
20
+ locationPath?: string
21
+ diffs: DiffItem[]
22
+ priorAgent?: AgentId
23
+ priorRawName?: string
24
+ }
25
+
26
+ export interface ResolvedTool {
27
+ agent: AgentId
28
+ rawName?: string
29
+ name: string
30
+ input: Record<string, unknown>
31
+ }
32
+
33
+ export type PatchEntry =
34
+ | { kind: "add"; path: string; content: string }
35
+ | { kind: "delete"; path: string }
36
+ | { kind: "update"; path: string; moveTo?: string; chunks: Array<{ oldText: string; newText: string }> }
37
+
38
+ export function text(value: unknown): string | undefined {
39
+ return typeof value === "string" && value.trim() ? value.trim() : undefined
40
+ }
41
+
42
+ /** File contents must keep their exact whitespace: the edit card renders a diff. */
43
+ export function literal(value: unknown): string | undefined {
44
+ return typeof value === "string" ? value : undefined
45
+ }
46
+
47
+ export function record(value: unknown): Record<string, unknown> | undefined {
48
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined
49
+ }
50
+
51
+ export function firstText(...values: unknown[]): string | undefined {
52
+ for (const value of values) {
53
+ const found = text(value)
54
+ if (found) return found
55
+ }
56
+ return undefined
57
+ }
58
+
59
+ export function finiteNumber(value: unknown): number | undefined {
60
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined
61
+ }
62
+
63
+ export function booleanOf(value: unknown): boolean | undefined {
64
+ return typeof value === "boolean" ? value : undefined
65
+ }
66
+
67
+ /** Codex sends `["bash", "-lc", "ls"]`; Claude sends the command as a string. */
68
+ export function commandOf(value: unknown): string | undefined {
69
+ if (typeof value === "string") return text(value)
70
+ if (!Array.isArray(value)) return undefined
71
+ const parts = value.filter((item): item is string => typeof item === "string")
72
+ if (!parts.length) return undefined
73
+ if (parts.length === 3 && parts[0].endsWith("sh") && parts[1].startsWith("-")) return text(parts[2])
74
+ return text(parts.join(" "))
75
+ }
76
+
77
+ /** codex-acp reports the file path of a read call here instead of in `rawInput`. */
78
+ export function locationPath(update: SessionUpdate): string | undefined {
79
+ const locations = Array.isArray(update.locations) ? update.locations : []
80
+ for (const item of locations) {
81
+ const path = firstText(record(item)?.path)
82
+ if (path) return path
83
+ }
84
+ return undefined
85
+ }
86
+
87
+ export function diffsOf(update: SessionUpdate): DiffItem[] {
88
+ if (!Array.isArray(update.content)) return []
89
+ const diffs: DiffItem[] = []
90
+ for (const item of update.content) {
91
+ const entry = record(item)
92
+ if (!entry || entry.type !== "diff") continue
93
+ const kind = record(entry._meta)?.kind
94
+ diffs.push({
95
+ path: text(entry.path),
96
+ oldText: entry.oldText === null ? null : literal(entry.oldText),
97
+ newText: literal(entry.newText),
98
+ kind: kind === "add" || kind === "delete" || kind === "update" ? kind : undefined,
99
+ })
100
+ }
101
+ return diffs
102
+ }
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)
107
+ }
108
+
109
+ /** OpenCode's question tool is the only ACP tool name with a known native card. */
110
+ export function isOpencodeQuestionName(name: string | undefined): boolean {
111
+ return (
112
+ name === "mcp__opencode__question" ||
113
+ name === "mcp.opencode.question" ||
114
+ name === "mcp_opencode_question" ||
115
+ name === "opencode.question"
116
+ )
117
+ }
118
+
119
+ function compact(fields: Record<string, unknown>): Record<string, unknown> {
120
+ const input: Record<string, unknown> = {}
121
+ for (const [key, value] of Object.entries(fields)) {
122
+ if (value !== undefined) input[key] = value
123
+ }
124
+ return input
125
+ }
126
+
127
+ export function shellInput(fields: {
128
+ command?: string
129
+ workdir?: string
130
+ timeout?: number
131
+ background?: boolean
132
+ }): Record<string, unknown> {
133
+ return compact({ command: fields.command, workdir: fields.workdir, timeout: fields.timeout, background: fields.background })
134
+ }
135
+
136
+ export function readInput(fields: { path?: string; offset?: number; limit?: number }): Record<string, unknown> {
137
+ return compact({ path: fields.path, offset: fields.offset, limit: fields.limit })
138
+ }
139
+
140
+ export function grepInput(fields: {
141
+ pattern?: string
142
+ path?: string
143
+ include?: string
144
+ literal?: boolean
145
+ caseSensitive?: boolean
146
+ limit?: number
147
+ }): Record<string, unknown> {
148
+ return compact({
149
+ pattern: fields.pattern,
150
+ path: fields.path,
151
+ include: fields.include,
152
+ literal: fields.literal,
153
+ caseSensitive: fields.caseSensitive,
154
+ limit: fields.limit,
155
+ })
156
+ }
157
+
158
+ export function globInput(fields: {
159
+ pattern?: string
160
+ path?: string
161
+ hidden?: boolean
162
+ limit?: number
163
+ }): Record<string, unknown> {
164
+ return compact({ pattern: fields.pattern, path: fields.path, hidden: fields.hidden, limit: fields.limit })
165
+ }
166
+
167
+ export function webfetchInput(fields: {
168
+ url?: string
169
+ format?: "text" | "markdown" | "html"
170
+ timeout?: number
171
+ }): Record<string, unknown> {
172
+ // A webfetch card without a URL has nothing to show, and emitting `format`
173
+ // alone would draw an empty card for a streamed `rawInput: {}`.
174
+ if (fields.url === undefined) return {}
175
+ return compact({ url: fields.url, format: fields.format ?? "markdown", timeout: fields.timeout })
176
+ }
177
+
178
+ export function websearchInput(fields: { query?: string }): Record<string, unknown> {
179
+ return compact({ query: fields.query })
180
+ }
181
+
182
+ export function writeInput(fields: { path?: string; content?: string }): Record<string, unknown> {
183
+ return compact({ path: fields.path, content: fields.content })
184
+ }
185
+
186
+ export function editInput(fields: {
187
+ path?: string
188
+ oldString?: string
189
+ newString?: string
190
+ replaceAll?: boolean
191
+ }): Record<string, unknown> {
192
+ return compact({
193
+ path: fields.path,
194
+ oldString: fields.oldString,
195
+ newString: fields.newString,
196
+ replaceAll: fields.replaceAll,
197
+ })
198
+ }
199
+
200
+ export function patchInput(entries: PatchEntry[]): Record<string, unknown> {
201
+ return entries.length > 0 ? { patchText: buildPatchText(entries) } : {}
202
+ }
203
+
204
+ export function skillInput(fields: { id?: string }): Record<string, unknown> {
205
+ return compact({ id: fields.id })
206
+ }
207
+
208
+ export function questionInput(raw: Record<string, unknown> | undefined): Record<string, unknown> {
209
+ const questions = record(raw?.arguments)?.questions ?? raw?.questions
210
+ return questions !== undefined ? { questions } : {}
211
+ }
212
+
213
+ export function executeInput(fields: { code?: string }): Record<string, unknown> {
214
+ return compact({ code: fields.code })
215
+ }
216
+
217
+ type TodoStatus = "pending" | "in_progress" | "completed" | "cancelled"
218
+
219
+ /** Keep only the fields OpenCode's todowrite card renders. */
220
+ export function todowriteTodos(entries: unknown): Array<{ content: string; status: TodoStatus }> | undefined {
221
+ if (!Array.isArray(entries)) return undefined
222
+ const todos: Array<{ content: string; status: TodoStatus }> = []
223
+ for (const entry of entries) {
224
+ const item = record(entry)
225
+ if (!item || typeof item.content !== "string") continue
226
+ const status = item.status === "canceled" ? "cancelled" : item.status
227
+ todos.push({
228
+ content: item.content,
229
+ status:
230
+ status === "in_progress" || status === "completed" || status === "cancelled" ? status : "pending",
231
+ })
232
+ }
233
+ return todos
234
+ }
235
+
236
+ export function patchLines(value: string): string[] {
237
+ if (!value) return []
238
+ const normalized = value.replace(/\r\n/g, "\n")
239
+ return (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n")
240
+ }
241
+
242
+ /** Build the patch text OpenCode's patch tool parses. */
243
+ export function buildPatchText(entries: PatchEntry[]): string {
244
+ const lines = ["*** Begin Patch"]
245
+ for (const entry of entries) {
246
+ if (entry.kind === "add") {
247
+ lines.push(`*** Add File: ${entry.path}`)
248
+ for (const line of patchLines(entry.content)) lines.push(`+${line}`)
249
+ continue
250
+ }
251
+ if (entry.kind === "delete") {
252
+ lines.push(`*** Delete File: ${entry.path}`)
253
+ continue
254
+ }
255
+ lines.push(`*** Update File: ${entry.path}`)
256
+ if (entry.moveTo) lines.push(`*** Move to: ${entry.moveTo}`)
257
+ let emitted = 0
258
+ for (const chunk of entry.chunks) {
259
+ const oldLines = patchLines(chunk.oldText)
260
+ const newLines = patchLines(chunk.newText)
261
+ if (!oldLines.length && !newLines.length) continue
262
+ lines.push("@@")
263
+ for (const line of oldLines) lines.push(`-${line}`)
264
+ for (const line of newLines) lines.push(`+${line}`)
265
+ emitted += 1
266
+ }
267
+ // A hunk whose sides are both empty still needs a body line, otherwise
268
+ // OpenCode's parser rejects the whole update.
269
+ if (!emitted) {
270
+ lines.push("@@")
271
+ lines.push(" ")
272
+ }
273
+ }
274
+ lines.push("*** End Patch")
275
+ return lines.join("\n")
276
+ }
277
+
278
+ export const MAX_OUTPUT = 32_000
279
+
280
+ export function clip(value: string): string {
281
+ return value.length > MAX_OUTPUT ? `${value.slice(0, MAX_OUTPUT - 1)}…` : value
282
+ }
283
+
284
+ const ANTIGRAVITY_STATUS_PATTERNS = [
285
+ /^Command exited with code (\d+)\.?$/,
286
+ /^No output from the command\.?$/,
287
+ /^Background command is still running after /,
288
+ /^Command timed out:/,
289
+ /^Step was canceled/i,
290
+ ]
291
+
292
+ function isAntigravityStatusLine(line: string): boolean {
293
+ return ANTIGRAVITY_STATUS_PATTERNS.some((pattern) => pattern.test(line))
294
+ }
295
+
296
+ /**
297
+ * Antigravity foreground commands prefix output with `Created At:`, whereas
298
+ * late background completions begin directly with the status line (for
299
+ * example `Command exited with code 0.`).
300
+ */
301
+ export function hasAntigravityOutputHeader(raw: string): boolean {
302
+ const normalized = raw.replace(/\r\n/g, "\n")
303
+ if (normalized.startsWith("Created At:")) return true
304
+ const firstLine = normalized.split("\n", 1)[0]?.trim() ?? ""
305
+ return isAntigravityStatusLine(firstLine)
306
+ }
307
+
308
+ /**
309
+ * Antigravity prefixes command output with a "Created At:" header and a status
310
+ * line that belongs to the tool card, not the output. Strip it so the card shows
311
+ * only the command's own text.
312
+ */
313
+ export function stripAntigravityOutputHeader(raw: string): string {
314
+ const normalized = raw.replace(/\r\n/g, "\n")
315
+ const lines = normalized.split("\n")
316
+ let index = 0
317
+ if (normalized.startsWith("Created At:")) {
318
+ index = 1
319
+ if (lines[index]?.startsWith("Completed At:")) index++
320
+ } else if (!isAntigravityStatusLine(lines[0]?.trim() ?? "")) {
321
+ return raw
322
+ }
323
+
324
+ let statusLine: string | undefined
325
+ let isZeroExit = false
326
+ const candidate = lines[index]?.trim() ?? ""
327
+ const exit = candidate.match(/^Command exited with code (\d+)\.?$/)
328
+ if (exit) {
329
+ statusLine = candidate
330
+ isZeroExit = exit[1] === "0"
331
+ index++
332
+ } else if (isAntigravityStatusLine(candidate)) {
333
+ statusLine = candidate
334
+ index++
335
+ }
336
+
337
+ while (index < lines.length && lines[index].trim() === "") index++
338
+ const label = lines[index]?.trim()
339
+ if (label === "Command output:" || label === "Output:" || label === "Stdout:" || label === "Stderr:") index++
340
+
341
+ const body = lines.slice(index).join("\n").replace(/\n+$/, "")
342
+ if (statusLine && !isZeroExit) return body ? `${statusLine}\n${body}` : statusLine
343
+ return body
344
+ }
345
+
346
+ function textFromContent(content: unknown): string | undefined {
347
+ if (!Array.isArray(content)) return undefined
348
+ const parts: string[] = []
349
+ for (const item of content) {
350
+ const entry = record(item)
351
+ if (!entry || entry.type === "diff") continue
352
+ const nested = record(entry.content)
353
+ const value = firstText(entry.text, nested?.text, entry.output, entry.stdout)
354
+ if (value) parts.push(value)
355
+ }
356
+ return parts.length ? parts.join("\n") : undefined
357
+ }
358
+
359
+ /** Human-readable output from an ACP tool update, bounded for the card. */
360
+ export function extractOutput(
361
+ update: SessionUpdate,
362
+ options: { streamed?: string; streamedTerminal?: boolean; stripAntigravityHeader?: boolean } = {},
363
+ ): string | undefined {
364
+ const raw = update.rawOutput
365
+ const rawRecord = record(raw)
366
+ let resolved: string | undefined
367
+
368
+ if (typeof raw === "string") {
369
+ if (options.stripAntigravityHeader && hasAntigravityOutputHeader(raw)) {
370
+ return clip(stripAntigravityOutputHeader(raw))
371
+ }
372
+ if (raw.length > 0) return clip(raw)
373
+ }
374
+
375
+ if (rawRecord) {
376
+ if (
377
+ options.stripAntigravityHeader &&
378
+ typeof rawRecord.output === "string" &&
379
+ hasAntigravityOutputHeader(rawRecord.output)
380
+ ) {
381
+ return clip(stripAntigravityOutputHeader(rawRecord.output))
382
+ }
383
+ const direct =
384
+ text(rawRecord.output) ??
385
+ ([text(rawRecord.stdout), text(rawRecord.stderr)].filter(Boolean).join("\n") || undefined) ??
386
+ firstText(rawRecord.text, rawRecord.result, rawRecord.content) ??
387
+ textFromContent(rawRecord.content)
388
+ // MCP tool results arrive as `{ result: { content: [{ type: "text", text }] } }`.
389
+ const result = record(rawRecord.result)
390
+ const nested = result
391
+ ? firstText(result.output, result.text) ??
392
+ ([text(result.stdout), text(result.stderr)].filter(Boolean).join("\n") || undefined) ??
393
+ textFromContent(result.content)
394
+ : undefined
395
+ resolved =
396
+ direct ??
397
+ nested ??
398
+ (rawRecord.error !== undefined && rawRecord.error !== null
399
+ ? firstText(rawRecord.error, record(rawRecord.error)?.message)
400
+ : undefined)
401
+ }
402
+
403
+ if (Array.isArray(raw)) resolved = textFromContent(raw)
404
+ resolved ??= textFromContent(update.content)
405
+
406
+ if (resolved) {
407
+ const value = options.stripAntigravityHeader ? stripAntigravityOutputHeader(resolved) : resolved
408
+ return clip(value)
409
+ }
410
+
411
+ // Codex streams a command's stdout through terminal deltas, so a completion
412
+ // that only reports `{ exit_code: 0 }` must not replace the real output.
413
+ if (options.streamed !== undefined && options.streamedTerminal) return options.streamed
414
+
415
+ if (raw !== undefined && raw !== null && raw !== "") {
416
+ const target =
417
+ rawRecord &&
418
+ "result" in rawRecord &&
419
+ rawRecord.result !== undefined &&
420
+ rawRecord.result !== null &&
421
+ rawRecord.error == null
422
+ ? rawRecord.result
423
+ : raw
424
+ const targetRecord = record(target)
425
+ if (!targetRecord || Object.keys(targetRecord).length > 0) {
426
+ try {
427
+ const json = JSON.stringify(target, null, 2)
428
+ if (json) return clip(json)
429
+ } catch {
430
+ // fall through to the streamed output
431
+ }
432
+ }
433
+ }
434
+ if (options.streamed !== undefined) return options.streamed
435
+ return undefined
436
+ }