opencode-acp-provider 1.1.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/acp-tools.ts CHANGED
@@ -1,10 +1,28 @@
1
+ import { randomUUID } from "node:crypto"
1
2
  import type { SessionUpdate } from "./acp-client.ts"
3
+ import { resolveAntigravity } from "./acp-tools/antigravity.ts"
4
+ import { resolveClaude } from "./acp-tools/claude.ts"
5
+ import { resolveCodex } from "./acp-tools/codex.ts"
6
+ import { resolveCommandCode } from "./acp-tools/command-code.ts"
7
+ import { resolveFallback } from "./acp-tools/fallback.ts"
8
+ import {
9
+ clip,
10
+ diffsOf,
11
+ extractOutput,
12
+ locationPath,
13
+ record,
14
+ terminalOutputDelta,
15
+ text,
16
+ todowriteTodos,
17
+ type AgentId,
18
+ type ToolContext,
19
+ } from "./acp-tools/shared.ts"
2
20
 
3
21
  /**
4
22
  * ACP agents run their own tools and report the call through the protocol.
5
23
  * OpenCode can only draw a native tool card if the tool is named like one of
6
- * its own tools and carries the matching input shape, so translate the ACP
7
- * call into that shape here. Anything unknown stays a generic tool.
24
+ * its own tools and carries the matching input shape, so each agent's resolver
25
+ * translates the ACP call into that shape. Anything unknown stays a generic card.
8
26
  */
9
27
  export interface AcpToolState {
10
28
  readonly id: string
@@ -20,220 +38,41 @@ export interface AcpToolState {
20
38
  hidden?: boolean
21
39
  }
22
40
 
23
- const MAX_OUTPUT = 32_000
24
-
25
- function text(value: unknown): string | undefined {
26
- return typeof value === "string" && value.trim() ? value.trim() : undefined
27
- }
28
-
29
- /** File contents must keep their exact whitespace: the edit card renders a diff. */
30
- function literal(value: unknown): string | undefined {
31
- return typeof value === "string" ? value : undefined
32
- }
33
-
34
- function record(value: unknown): Record<string, unknown> | undefined {
35
- return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined
36
- }
37
-
38
- /** codex-acp reports the file path of a read call here instead of in `rawInput`. */
39
- function locationPath(update: SessionUpdate) {
40
- const locations = Array.isArray(update.locations) ? update.locations : []
41
- for (const item of locations) {
42
- const path = firstText(record(item)?.path)
43
- if (path) return path
44
- }
45
- return undefined
46
- }
47
-
48
- /** codex-acp streams shell and read output through `_meta` rather than `content`. */
49
- function terminalOutputDelta(update: SessionUpdate) {
50
- const data = record(record(update._meta)?.terminal_output_delta)?.data
51
- return typeof data === "string" ? data : undefined
52
- }
53
-
54
- function firstText(...values: unknown[]): string | undefined {
55
- for (const value of values) {
56
- const found = text(value)
57
- if (found) return found
58
- }
59
- return undefined
60
- }
61
-
62
- /** Codex sends `["bash", "-lc", "ls"]`; Claude sends the command as a string. */
63
- function commandOf(value: unknown): string | undefined {
64
- if (typeof value === "string") return text(value)
65
- if (!Array.isArray(value)) return undefined
66
- const parts = value.filter((item): item is string => typeof item === "string")
67
- if (!parts.length) return undefined
68
- if (parts.length === 3 && parts[0].endsWith("sh") && parts[1].startsWith("-")) return text(parts[2])
69
- return text(parts.join(" "))
70
- }
71
-
72
- function toolName(kind: string | undefined, title: string | undefined): string {
73
- switch (kind) {
74
- case "execute":
75
- return "shell"
76
- case "read":
77
- return "read"
78
- case "edit":
79
- if (title && /write|create/i.test(title)) return "write"
80
- return "edit"
81
- case "search":
82
- return title && /glob/i.test(title) ? "glob" : "grep"
83
- case "fetch":
84
- return "webfetch"
85
- default:
86
- return "tool"
87
- }
88
- }
89
-
90
- interface McpCall {
91
- server: string
92
- tool: string
93
- arguments?: Record<string, unknown>
94
- }
95
-
96
- /** Agents name MCP tools as `mcp__server__tool` or `mcp.server.tool`. */
97
- function parseMcpName(name: string): { server: string; tool: string } | undefined {
98
- if (name.startsWith("mcp__")) {
99
- const [server, ...rest] = name.slice(5).split("__")
100
- const tool = rest.join("__")
101
- if (server && tool) return { server, tool }
102
- }
103
- if (name.startsWith("mcp.")) {
104
- const [server, ...rest] = name.slice(4).split(".")
105
- const tool = rest.join(".")
106
- if (server && tool) return { server, tool }
107
- }
108
- return undefined
109
- }
110
-
111
- function mcpCall(
112
- update: SessionUpdate,
113
- raw: Record<string, unknown> | undefined,
114
- fallbackTitle?: string,
115
- ): McpCall | undefined {
116
- const meta = record(update._meta)
117
- if (meta?.is_mcp_tool_call === true && raw) {
118
- const server = firstText(raw.server)
119
- const tool = firstText(raw.tool)
120
- if (server && tool) return { server, tool, arguments: record(raw.arguments) }
121
- }
122
- const names = [
123
- firstText(update.name),
124
- firstText(update.title),
125
- fallbackTitle,
126
- firstText(record(record(meta?.claudeCode)?.toolName)),
127
- ]
128
- for (const name of names) {
129
- if (!name) continue
130
- const parsed = parseMcpName(name)
131
- if (parsed) return { ...parsed, arguments: raw }
132
- }
133
- return undefined
134
- }
135
-
136
- function normalize(name: string, raw: Record<string, unknown>, fallbackPath?: string) {
137
- const input: Record<string, unknown> = { ...raw }
138
- const path = firstText(raw.path, raw.file_path, raw.filePath, raw.file) ?? fallbackPath
139
- const command = commandOf(raw.command) ?? firstText(raw.cmd, raw.shell_command)
140
- const workdir = firstText(raw.workdir, raw.cwd, raw.working_directory)
141
- switch (name) {
142
- case "shell":
143
- if (command) input.command = command
144
- if (workdir) input.workdir = workdir
145
- break
146
- case "read":
147
- case "edit":
148
- case "write":
149
- if (path) input.path = path
150
- if (name === "edit") {
151
- const oldString =
152
- literal(raw.oldString) ?? literal(raw.old_string) ?? literal(raw.oldText) ?? literal(raw.old_text)
153
- const newString =
154
- literal(raw.newString) ?? literal(raw.new_string) ?? literal(raw.newText) ?? literal(raw.new_text)
155
- if (oldString !== undefined) input.oldString = oldString
156
- if (newString !== undefined) input.newString = newString
157
- }
158
- if (name === "write" && input.content === undefined) {
159
- const content = literal(raw.content)
160
- if (content !== undefined) input.content = content
161
- }
162
- break
163
- case "grep":
164
- case "glob": {
165
- const pattern = firstText(raw.pattern, raw.query, raw.glob)
166
- if (pattern) input.pattern = pattern
167
- if (path) input.path = path
168
- break
169
- }
170
- case "webfetch": {
171
- const url = firstText(raw.url, raw.uri)
172
- if (url) input.url = url
173
- break
174
- }
175
- }
176
- return input
41
+ /** What the first update of a call told us, so later updates keep the mapping. */
42
+ interface CallMeta {
43
+ agent: AgentId
44
+ rawName?: string
45
+ rawInput?: Record<string, unknown>
46
+ /** The call streamed terminal output, which outranks a structured `rawOutput`. */
47
+ streamedTerminal?: boolean
177
48
  }
178
49
 
179
- /** Human-readable output from an ACP tool update, bounded for the card. */
180
- function textFromContent(content: unknown): string | undefined {
181
- if (!Array.isArray(content)) return undefined
182
- const parts: string[] = []
183
- for (const item of content) {
184
- const entry = record(item)
185
- if (!entry) continue
186
- const nested = record(entry.content)
187
- const value = firstText(entry.text, nested?.text, entry.output, entry.stdout)
188
- if (value) {
189
- parts.push(value)
190
- continue
191
- }
192
- if (entry.type === "diff") {
193
- const path = firstText(entry.path)
194
- const oldText = typeof entry.oldText === "string" ? entry.oldText : undefined
195
- const newText = typeof entry.newText === "string" ? entry.newText : undefined
196
- parts.push([path, oldText && `-${oldText}`, newText && `+${newText}`].filter(Boolean).join("\n"))
197
- }
198
- }
199
- return parts.length ? parts.join("\n") : undefined
200
- }
50
+ const callMeta = new WeakMap<Map<string, AcpToolState>, Map<string, CallMeta>>()
201
51
 
202
- function outputOf(update: SessionUpdate): string | undefined {
203
- const raw = update.rawOutput
204
- if (typeof raw === "string") return clip(raw)
205
- const rawRecord = record(raw)
206
- if (rawRecord) {
207
- const value = firstText(rawRecord.output, rawRecord.stdout, rawRecord.text, rawRecord.result, rawRecord.content)
208
- if (value) return clip(value)
209
- // MCP tool results arrive as `{ result: { content: [{ type: "text", text }] } }`.
210
- const result = record(rawRecord.result)
211
- if (result) {
212
- const nested = firstText(result.output, result.stdout, result.text) ?? textFromContent(result.content)
213
- if (nested) return clip(nested)
214
- }
52
+ function metaFor(states: Map<string, AcpToolState>): Map<string, CallMeta> {
53
+ let meta = callMeta.get(states)
54
+ if (!meta) {
55
+ meta = new Map()
56
+ callMeta.set(states, meta)
215
57
  }
216
- const content = textFromContent(update.content)
217
- return content ? clip(content) : undefined
218
- }
219
-
220
- function clip(value: string) {
221
- return value.length > MAX_OUTPUT ? `${value.slice(0, MAX_OUTPUT - 1)}…` : value
222
- }
223
-
224
- /** The file-level diff an ACP agent reports for an edit. */
225
- function diffOf(update: SessionUpdate) {
226
- if (!Array.isArray(update.content)) return undefined
227
- for (const item of update.content) {
228
- const entry = record(item)
229
- if (!entry || entry.type !== "diff") continue
230
- return {
231
- path: text(entry.path),
232
- oldText: literal(entry.oldText),
233
- newText: literal(entry.newText),
234
- }
58
+ return meta
59
+ }
60
+
61
+ /** Agents report their todo list as a `plan` session update. */
62
+ export function planToToolState(update: SessionUpdate): AcpToolState | undefined {
63
+ if (update.sessionUpdate !== "plan") return undefined
64
+ const todos = todowriteTodos(update.entries)
65
+ if (!todos) return undefined
66
+ return {
67
+ id: `plan-${randomUUID()}`,
68
+ name: "todowrite",
69
+ kind: "think",
70
+ title: "Update todos",
71
+ input: { todos },
72
+ status: "completed",
73
+ isError: false,
74
+ done: true,
235
75
  }
236
- return undefined
237
76
  }
238
77
 
239
78
  /**
@@ -246,12 +85,32 @@ export function applyToolUpdate(update: SessionUpdate, states: Map<string, AcpTo
246
85
  if (!id) return undefined
247
86
  const existing = states.get(id)
248
87
  if (existing?.done) return undefined
249
- const kind = text(update.kind) ?? existing?.kind
250
- // `think` calls (for example codex's Guardian Review) are internal reasoning,
251
- // not actions on the workspace, and their raw input is not card-friendly.
252
- // Remember the id so later updates cannot surface the call as a generic card.
253
88
  if (existing?.hidden) return undefined
254
- if (!existing && kind === "think") {
89
+
90
+ const meta = metaFor(states).get(id)
91
+ const kind = text(update.kind) ?? existing?.kind
92
+ const title = text(update.title) ?? existing?.title
93
+ const incomingRaw = record(update.rawInput)
94
+ const hasIncomingRaw = incomingRaw !== undefined && Object.keys(incomingRaw).length > 0
95
+ const effectiveRaw = hasIncomingRaw ? incomingRaw : meta?.rawInput ?? incomingRaw
96
+ const diffs = diffsOf(update)
97
+ const ctx: ToolContext = {
98
+ update,
99
+ raw: effectiveRaw,
100
+ kind,
101
+ title,
102
+ topName: text(update.name),
103
+ locationPath: locationPath(update),
104
+ diffs,
105
+ priorAgent: meta?.agent,
106
+ priorRawName: meta?.rawName,
107
+ }
108
+
109
+ let resolved = resolveClaude(ctx) ?? resolveCodex(ctx) ?? resolveAntigravity(ctx) ?? resolveCommandCode(ctx)
110
+ if (!resolved && !existing && kind === "think") {
111
+ // `think` calls (for example codex's Guardian Review) are internal reasoning,
112
+ // not actions on the workspace, and their raw input is not card-friendly.
113
+ // Remember the id so later updates cannot surface the call as a generic card.
255
114
  states.set(id, {
256
115
  id,
257
116
  name: "tool",
@@ -264,37 +123,52 @@ export function applyToolUpdate(update: SessionUpdate, states: Map<string, AcpTo
264
123
  })
265
124
  return undefined
266
125
  }
267
- const title = text(update.title) ?? existing?.title
268
- const status = text(update.status) ?? existing?.status ?? "pending"
269
- const raw = record(update.rawInput)
270
- const mcp = mcpCall(update, raw, existing?.title)
271
- const name = existing?.name ?? (mcp ? "shell" : toolName(kind, title))
272
- const path = locationPath(update)
273
- const input = raw ? normalize(name, raw, path) : { ...(existing?.input ?? {}) }
274
- if (path && !input.path) input.path = path
275
- if (mcp) {
276
- // OpenCode's generic tool card has no detail view, so render the bridge call
277
- // as a console card where the command names the MCP tool and its arguments.
278
- const args = mcp.arguments
279
- const rendered = args && Object.keys(args).length ? ` ${JSON.stringify(args)}` : ""
280
- if (rendered) {
281
- input.command = `mcp.${mcp.server}.${mcp.tool}${rendered}`
282
- } else if (!input.command && (status === "completed" || status === "failed")) {
283
- input.command = `mcp.${mcp.server}.${mcp.tool}`
126
+ if (!resolved) {
127
+ if (existing && !hasIncomingRaw && diffs.length === 0) {
128
+ resolved = {
129
+ agent: meta?.agent ?? "fallback",
130
+ rawName: meta?.rawName,
131
+ name: existing.name,
132
+ input: { ...existing.input },
133
+ }
134
+ } else {
135
+ resolved = resolveFallback(ctx)
284
136
  }
137
+ } else if (
138
+ existing &&
139
+ !hasIncomingRaw &&
140
+ diffs.length === 0 &&
141
+ Object.keys(resolved.input).length === 0 &&
142
+ Object.keys(existing.input).length > 0
143
+ ) {
144
+ // A status/output-only update can hit a resolver path with no fields (for
145
+ // example a bare `webfetch` name); keep the input of the first call.
146
+ resolved = { ...resolved, name: existing.name, input: { ...existing.input } }
285
147
  }
286
- if (name === "edit" && input.oldString === undefined) {
148
+
149
+ const name = resolved.name
150
+ const input = { ...resolved.input }
151
+ if (name === "edit" && input.oldString === undefined && diffs[0]) {
287
152
  // Agents that send no edit fields in `rawInput` still report the change as
288
153
  // a diff, which is what the edit card renders.
289
- const diff = diffOf(update)
290
- if (diff) {
291
- if (diff.path && !input.path) input.path = diff.path
292
- if (diff.oldText !== undefined) input.oldString = diff.oldText
293
- if (diff.newText !== undefined) input.newString = diff.newText
294
- }
154
+ const diff = diffs[0]
155
+ if (diff.path && !input.path) input.path = diff.path
156
+ input.oldString = diff.oldText === null ? "" : diff.oldText
157
+ input.newString = diff.newText
295
158
  }
159
+
296
160
  const delta = terminalOutputDelta(update)
161
+ const streamedTerminal = Boolean(meta?.streamedTerminal || delta !== undefined)
297
162
  const streamed = delta === undefined ? existing?.output : clip(`${existing?.output ?? ""}${delta}`)
163
+
164
+ metaFor(states).set(id, {
165
+ agent: resolved.agent,
166
+ rawName: resolved.rawName,
167
+ rawInput: effectiveRaw,
168
+ streamedTerminal,
169
+ })
170
+
171
+ const status = text(update.status) ?? existing?.status ?? "pending"
298
172
  const state: AcpToolState = {
299
173
  id,
300
174
  name,
@@ -304,7 +178,11 @@ export function applyToolUpdate(update: SessionUpdate, states: Map<string, AcpTo
304
178
  status,
305
179
  isError: status === "failed",
306
180
  done: status === "completed" || status === "failed",
307
- output: outputOf(update) ?? streamed,
181
+ output: extractOutput(update, {
182
+ streamed,
183
+ streamedTerminal,
184
+ stripAntigravityHeader: resolved.agent === "antigravity" && resolved.rawName === "run_command",
185
+ }),
308
186
  }
309
187
  states.set(id, state)
310
188
  return state
@@ -4,7 +4,7 @@ import { basename } from "node:path"
4
4
  * The executable a launch command runs, without its directory or a script
5
5
  * suffix, so a Windows shim and the bare name compare the same way.
6
6
  */
7
- export function executableName(command: string | string[]) {
7
+ function executableName(command: string | string[]) {
8
8
  const argv = Array.isArray(command) ? command : [command]
9
9
  return basename(argv[0] ?? "")
10
10
  .toLowerCase()
package/src/agent-pool.ts CHANGED
@@ -3,6 +3,7 @@ import { createRequire } from "node:module"
3
3
  import { tmpdir } from "node:os"
4
4
  import { join } from "node:path"
5
5
  import { AcpClient } from "./acp-client.ts"
6
+ import type { AcpCatalog } from "./inventory.ts"
6
7
  import { errorMessage } from "./util.ts"
7
8
 
8
9
  /**
@@ -125,6 +126,8 @@ function launchKey(launch: AgentLaunch) {
125
126
  }
126
127
 
127
128
  export class AgentPool {
129
+ /** Discovery outlives individual clients and location leases. */
130
+ readonly catalogs = new Map<string, Promise<AcpCatalog>>()
128
131
  private readonly lingerMs: number
129
132
  private readonly spares: boolean
130
133
  private readonly tmpDir: string
@@ -280,6 +283,7 @@ export class AgentPool {
280
283
  const clients = [...this.knownClients()]
281
284
  const dirs = [...this.dirs]
282
285
  this.shared.clear()
286
+ this.catalogs.clear()
283
287
  for (const state of this.dedicatedStates.values()) {
284
288
  state.spare = undefined
285
289
  state.interest = 0
@@ -425,7 +429,7 @@ export class AgentPool {
425
429
 
426
430
  const POOLS = Symbol.for("opencode-acp-provider.agent-pools")
427
431
  /** Bump when AgentPool or AcpClient change incompatibly; copies only share a pool with the same ABI and version. */
428
- const AGENT_POOL_ABI = 1
432
+ const AGENT_POOL_ABI = 3
429
433
 
430
434
  const { version } = createRequire(import.meta.url)("../package.json") as { version: string }
431
435