opencode-acp-provider 0.0.0-stage → 1.1.0

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,311 @@
1
+ import type { SessionUpdate } from "./acp-client.ts"
2
+
3
+ /**
4
+ * ACP agents run their own tools and report the call through the protocol.
5
+ * 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.
8
+ */
9
+ export interface AcpToolState {
10
+ readonly id: string
11
+ name: string
12
+ kind?: string
13
+ title?: string
14
+ input: Record<string, unknown>
15
+ status: string
16
+ output?: string
17
+ isError: boolean
18
+ done: boolean
19
+ /** Internal calls (for example a "think" tool) that should not become cards. */
20
+ hidden?: boolean
21
+ }
22
+
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
177
+ }
178
+
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
+ }
201
+
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
+ }
215
+ }
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
+ }
235
+ }
236
+ return undefined
237
+ }
238
+
239
+ /**
240
+ * Fold one ACP `tool_call` / `tool_call_update` into the state of that call.
241
+ * Returns undefined for a call that already finished, so late updates cannot
242
+ * reopen a settled tool.
243
+ */
244
+ export function applyToolUpdate(update: SessionUpdate, states: Map<string, AcpToolState>): AcpToolState | undefined {
245
+ const id = text(update.toolCallId)
246
+ if (!id) return undefined
247
+ const existing = states.get(id)
248
+ 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
+ if (existing?.hidden) return undefined
254
+ if (!existing && kind === "think") {
255
+ states.set(id, {
256
+ id,
257
+ name: "tool",
258
+ kind,
259
+ input: {},
260
+ status: "completed",
261
+ isError: false,
262
+ done: true,
263
+ hidden: true,
264
+ })
265
+ return undefined
266
+ }
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}`
284
+ }
285
+ }
286
+ if (name === "edit" && input.oldString === undefined) {
287
+ // Agents that send no edit fields in `rawInput` still report the change as
288
+ // 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
+ }
295
+ }
296
+ const delta = terminalOutputDelta(update)
297
+ const streamed = delta === undefined ? existing?.output : clip(`${existing?.output ?? ""}${delta}`)
298
+ const state: AcpToolState = {
299
+ id,
300
+ name,
301
+ kind,
302
+ title,
303
+ input,
304
+ status,
305
+ isError: status === "failed",
306
+ done: status === "completed" || status === "failed",
307
+ output: outputOf(update) ?? streamed,
308
+ }
309
+ states.set(id, state)
310
+ return state
311
+ }
@@ -0,0 +1,20 @@
1
+ import { basename } from "node:path"
2
+
3
+ /**
4
+ * The executable a launch command runs, without its directory or a script
5
+ * suffix, so a Windows shim and the bare name compare the same way.
6
+ */
7
+ export function executableName(command: string | string[]) {
8
+ const argv = Array.isArray(command) ? command : [command]
9
+ return basename(argv[0] ?? "")
10
+ .toLowerCase()
11
+ .replace(/\.(?:exe|cmd|bat|js|mjs|cjs)$/, "")
12
+ }
13
+
14
+ /** True when the command starts Command Code. */
15
+ export function isCmdCommand(command: string | string[]) {
16
+ const executable = executableName(command)
17
+ if (["cmd", "cmdc", "commandcode", "command-code"].includes(executable)) return true
18
+ if (!["node", "bun"].includes(executable) || !Array.isArray(command)) return false
19
+ return /\/command-code\/dist\/(?:index|cli)\.mjs$/.test((command[1] ?? "").replace(/\\/g, "/"))
20
+ }