opencode-acp-client 0.0.0-stage → 0.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.
- package/LICENSE +202 -0
- package/README.md +220 -2
- package/README.zh.md +199 -0
- package/dist/acp/capabilities.d.ts +168 -0
- package/dist/acp/capabilities.js +240 -0
- package/dist/acp/capabilities.js.map +1 -0
- package/dist/acp/client.d.ts +241 -0
- package/dist/acp/client.js +767 -0
- package/dist/acp/client.js.map +1 -0
- package/dist/acp/types.d.ts +228 -0
- package/dist/acp/types.js +23 -0
- package/dist/acp/types.js.map +1 -0
- package/dist/acp-replay.d.ts +60 -0
- package/dist/acp-replay.js +188 -0
- package/dist/acp-replay.js.map +1 -0
- package/dist/contract.d.ts +435 -0
- package/dist/contract.js +126 -0
- package/dist/contract.js.map +1 -0
- package/dist/daemons.d.ts +39 -0
- package/dist/daemons.js +112 -0
- package/dist/daemons.js.map +1 -0
- package/dist/index.d.ts +268 -0
- package/dist/index.js +1882 -0
- package/dist/index.js.map +1 -0
- package/dist/opencode-bin.d.ts +73 -0
- package/dist/opencode-bin.js +109 -0
- package/dist/opencode-bin.js.map +1 -0
- package/dist/project.d.ts +81 -0
- package/dist/project.js +230 -0
- package/dist/project.js.map +1 -0
- package/dist/server.d.ts +743 -0
- package/dist/server.js +5029 -0
- package/dist/server.js.map +1 -0
- package/dist/session-map.d.ts +89 -0
- package/dist/session-map.js +305 -0
- package/dist/session-map.js.map +1 -0
- package/dist/sessions-command.d.ts +70 -0
- package/dist/sessions-command.js +188 -0
- package/dist/sessions-command.js.map +1 -0
- package/dist/sse.d.ts +40 -0
- package/dist/sse.js +147 -0
- package/dist/sse.js.map +1 -0
- package/dist/state.d.ts +161 -0
- package/dist/state.js +135 -0
- package/dist/state.js.map +1 -0
- package/dist/subagent-sessions.d.ts +71 -0
- package/dist/subagent-sessions.js +107 -0
- package/dist/subagent-sessions.js.map +1 -0
- package/dist/translate/events.d.ts +231 -0
- package/dist/translate/events.js +1244 -0
- package/dist/translate/events.js.map +1 -0
- package/dist/upgrade.d.ts +56 -0
- package/dist/upgrade.js +162 -0
- package/dist/upgrade.js.map +1 -0
- package/package.json +66 -4
|
@@ -0,0 +1,1244 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACP → opencode event translation.
|
|
3
|
+
*
|
|
4
|
+
* This is the layer that decides *how the conversation looks*. ACP speaks in
|
|
5
|
+
* coarse "chunks" and tool calls; opencode renders messages made of typed
|
|
6
|
+
* parts. Getting this wrong does not throw — the agent streams happily and the
|
|
7
|
+
* UI simply stays empty — so it is worth reading carefully.
|
|
8
|
+
*
|
|
9
|
+
* Translation rules, and why:
|
|
10
|
+
*
|
|
11
|
+
* agent_message_chunk → append to a `text` part, emit `message.part.delta`
|
|
12
|
+
* followed by `message.part.updated` (the TUI uses the
|
|
13
|
+
* delta for streaming and the full part on re-render).
|
|
14
|
+
* agent_thought_chunk → same, as a `reasoning` part. Closing it matters:
|
|
15
|
+
* a never-closed reasoning part is a spinner that
|
|
16
|
+
* never stops.
|
|
17
|
+
* tool_call / _update → one `tool` part per `toolCallId`, status mapped from
|
|
18
|
+
* ACP's free-form status strings.
|
|
19
|
+
* plan → logged only; opencode v2 has no todo surface
|
|
20
|
+
* rather than a wall of text.
|
|
21
|
+
* user_message_chunk → dropped. The bridge already appended the user's
|
|
22
|
+
* message when `/prompt` was called; echoing it again
|
|
23
|
+
* duplicates the bubble.
|
|
24
|
+
*
|
|
25
|
+
* Anything unrecognised is ignored *by design* but logged, so a new ACP agent
|
|
26
|
+
* feature shows up as a log line instead of silence.
|
|
27
|
+
*/
|
|
28
|
+
import { EVENT } from '../contract.js';
|
|
29
|
+
import { UPDATE } from '../acp/types.js';
|
|
30
|
+
import { applyChildEvent, childCaption, isStillRunning, } from '../subagent-sessions.js';
|
|
31
|
+
/** Mirrors the single agent `/api/agent` advertises (ACP has no agent list). */
|
|
32
|
+
export class AcpTranslator {
|
|
33
|
+
state;
|
|
34
|
+
sink;
|
|
35
|
+
location;
|
|
36
|
+
log;
|
|
37
|
+
agentName;
|
|
38
|
+
onTitle;
|
|
39
|
+
/** Per session+message+kind cursor for the currently open streaming part. */
|
|
40
|
+
openParts = new Map();
|
|
41
|
+
/** Latest ACP usage per session, replayed on `session.step.ended`. */
|
|
42
|
+
lastTokens = new Map();
|
|
43
|
+
/** Context window the agent reported (`usage_update.size`), per session. */
|
|
44
|
+
lastContextSize = new Map();
|
|
45
|
+
/** Cumulative session cost, USD only (see applyUsage). */
|
|
46
|
+
lastCost = new Map();
|
|
47
|
+
/** toolCallId → part id, so updates target the same card. */
|
|
48
|
+
toolNames = new Map();
|
|
49
|
+
toolInputs = new Map();
|
|
50
|
+
toolParts = new Map();
|
|
51
|
+
/**
|
|
52
|
+
* Delegated runs per root session: the child's progress and the card that reports it.
|
|
53
|
+
* Fed by `opencode/session/child_update`; see `applyChildUpdate`.
|
|
54
|
+
*/
|
|
55
|
+
children = new Map();
|
|
56
|
+
/** The `task` card each child belongs to, and the description the agent gave it. */
|
|
57
|
+
childCards = new Map();
|
|
58
|
+
/**
|
|
59
|
+
* The metadata a `task` card must keep. `session.tool.success` rewrites a row's metadata
|
|
60
|
+
* from `toolMetadata(update)` — which is `{}` for an ACP frame with no `rawOutput.metadata`
|
|
61
|
+
* — so the delegated run's state would be wiped the moment the card completes, taking the
|
|
62
|
+
* client's `Background` badge with it. Merged back in at that point.
|
|
63
|
+
*/
|
|
64
|
+
childMeta = new Map();
|
|
65
|
+
/** Provisional assistant message id per session for the current turn. */
|
|
66
|
+
activeMessage = new Map();
|
|
67
|
+
/** Assistant rows whose `session.step.started` has been emitted. */
|
|
68
|
+
stepEmitted = new Set();
|
|
69
|
+
/** Prompt dispatch time per session, used as the step's `started`. */
|
|
70
|
+
turnStartedAt = new Map();
|
|
71
|
+
constructor(state, sink, location, log = () => { },
|
|
72
|
+
/** `initialize`'s `agentInfo.name`; opencode wants a name, not ours to invent. */
|
|
73
|
+
agentName = 'acp',
|
|
74
|
+
/**
|
|
75
|
+
* Called when the AGENT announces a title (`session_info_update`). The bridge
|
|
76
|
+
* persists it: the title is bidirectional (derived, agent, user), and the map must
|
|
77
|
+
* hold the latest name so a restore shows it. Optional so the translator stays
|
|
78
|
+
* usable without a map (tests).
|
|
79
|
+
*/
|
|
80
|
+
onTitle) {
|
|
81
|
+
this.state = state;
|
|
82
|
+
this.sink = sink;
|
|
83
|
+
this.location = location;
|
|
84
|
+
this.log = log;
|
|
85
|
+
this.agentName = agentName;
|
|
86
|
+
this.onTitle = onTitle;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Name the agent on rows created from now on.
|
|
90
|
+
*
|
|
91
|
+
* Needed because a translator can be created BEFORE its agent: a turn that could
|
|
92
|
+
* not start still renders its own failure, and it has no `agentInfo.name` to use
|
|
93
|
+
* yet (it reports the placeholder). Without this, every later row in that session
|
|
94
|
+
* — after a retry succeeded — kept saying `acp` in the footer instead of the
|
|
95
|
+
* agent's real name.
|
|
96
|
+
*/
|
|
97
|
+
/**
|
|
98
|
+
* Fold one event of a delegated run into the card that reports it.
|
|
99
|
+
*
|
|
100
|
+
* Two slots, both measured against opencode's `Subagent` component:
|
|
101
|
+
* • the caption — `input.description`, re-sent with `session.tool.called`, because the
|
|
102
|
+
* row's title is the only free text the client renders;
|
|
103
|
+
* • the `Background` badge — `metadata.status`, sent with `session.tool.progress`.
|
|
104
|
+
* The client shows it when the card is `completed` while `metadata.status` is
|
|
105
|
+
* `running` (`isBackgroundSubagent`), which is exactly a delegated run that
|
|
106
|
+
* returned its card and kept working.
|
|
107
|
+
*
|
|
108
|
+
* The card is matched by the CHILD's title against a `task` call whose input names it,
|
|
109
|
+
* or — when only one task is open — by that one. An unmatched child keeps accumulating
|
|
110
|
+
* progress and is applied as soon as a card appears.
|
|
111
|
+
*/
|
|
112
|
+
applyChildUpdate(record, event) {
|
|
113
|
+
const rootId = record.session.id;
|
|
114
|
+
const byChild = this.children.get(rootId) ?? new Map();
|
|
115
|
+
this.children.set(rootId, byChild);
|
|
116
|
+
const known = typeof event.childSessionId === 'string' ? byChild.get(event.childSessionId) : undefined;
|
|
117
|
+
const progress = applyChildEvent(known, event);
|
|
118
|
+
if (!progress)
|
|
119
|
+
return;
|
|
120
|
+
byChild.set(progress.childSessionId, progress);
|
|
121
|
+
const card = this.childCard(rootId, progress);
|
|
122
|
+
if (!card)
|
|
123
|
+
return;
|
|
124
|
+
const caption = childCaption(progress);
|
|
125
|
+
const text = caption ? `${card.original} (${caption})` : card.original;
|
|
126
|
+
const input = this.toolInputs.get(card.callId);
|
|
127
|
+
if (input && typeof input === 'object' && !Array.isArray(input)) {
|
|
128
|
+
input['description'] = text;
|
|
129
|
+
}
|
|
130
|
+
const partId = this.toolParts.get(card.callId);
|
|
131
|
+
const messageId = this.activeMessage.get(record.session.id);
|
|
132
|
+
if (!partId || !messageId)
|
|
133
|
+
return;
|
|
134
|
+
this.sink.emit({
|
|
135
|
+
type: EVENT.toolCalled,
|
|
136
|
+
data: {
|
|
137
|
+
sessionID: record.session.id,
|
|
138
|
+
assistantMessageID: messageId,
|
|
139
|
+
id: partId,
|
|
140
|
+
input: input ?? {},
|
|
141
|
+
executed: true,
|
|
142
|
+
state: undefined,
|
|
143
|
+
},
|
|
144
|
+
location: this.location,
|
|
145
|
+
});
|
|
146
|
+
// The `Background` badge. `tool.progress` only rewrites `metadata` while the client
|
|
147
|
+
// thinks the row is running, so this is what keeps a returned card marked as busy.
|
|
148
|
+
const nextMeta = {
|
|
149
|
+
...(this.childMeta.get(card.callId) ?? {}),
|
|
150
|
+
status: isStillRunning(progress) ? 'running' : 'completed',
|
|
151
|
+
subagent: progress.childSessionId,
|
|
152
|
+
};
|
|
153
|
+
this.childMeta.set(card.callId, nextMeta);
|
|
154
|
+
// The projection reads the STORED part, not the event stream: updating only the sink
|
|
155
|
+
// would leave `/api/session/:id/message` (and a reloaded transcript) without it.
|
|
156
|
+
this.updateToolMetadata(record, card.callId, partId, messageId, nextMeta);
|
|
157
|
+
this.sink.emit({
|
|
158
|
+
type: EVENT.toolProgress,
|
|
159
|
+
data: {
|
|
160
|
+
sessionID: record.session.id,
|
|
161
|
+
assistantMessageID: messageId,
|
|
162
|
+
id: partId,
|
|
163
|
+
metadata: { status: isStillRunning(progress) ? 'running' : 'completed', subagent: progress.childSessionId },
|
|
164
|
+
},
|
|
165
|
+
location: this.location,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
/** Replace the metadata of a stored tool part, keeping everything else. */
|
|
169
|
+
updateToolMetadata(record, callId, partId, messageId, metadata) {
|
|
170
|
+
const part = this.state.partsOf(record, messageId).find((candidate) => candidate.id === partId);
|
|
171
|
+
if (!part || part.type !== 'tool')
|
|
172
|
+
return;
|
|
173
|
+
const updated = { ...part, state: { ...part.state, metadata } };
|
|
174
|
+
this.state.upsertPart(record, messageId, updated);
|
|
175
|
+
this.emitPartUpdated(record, messageId, updated);
|
|
176
|
+
void callId;
|
|
177
|
+
}
|
|
178
|
+
/** Which `task` card reports this child. */
|
|
179
|
+
childCard(rootId, progress) {
|
|
180
|
+
const mapped = this.childCards.get(`${rootId}:${progress.childSessionId}`);
|
|
181
|
+
if (mapped)
|
|
182
|
+
return mapped;
|
|
183
|
+
const open = [];
|
|
184
|
+
for (const [callId, name] of this.toolNames) {
|
|
185
|
+
if (name !== 'task')
|
|
186
|
+
continue;
|
|
187
|
+
const input = this.toolInputs.get(callId);
|
|
188
|
+
const original = typeof input?.description === 'string' ? input.description : '';
|
|
189
|
+
// A title the agent put on both the card and the child is the strongest link.
|
|
190
|
+
if (progress.title && original.toLowerCase().includes(progress.title.toLowerCase())) {
|
|
191
|
+
const entry = { callId, original };
|
|
192
|
+
this.childCards.set(`${rootId}:${progress.childSessionId}`, entry);
|
|
193
|
+
return entry;
|
|
194
|
+
}
|
|
195
|
+
open.push({ callId, original });
|
|
196
|
+
}
|
|
197
|
+
// Exactly one open task: it has to be the one. More than one and we would be guessing,
|
|
198
|
+
// so the progress waits for a title match instead of landing on the wrong card.
|
|
199
|
+
if (open.length === 1) {
|
|
200
|
+
const entry = open[0];
|
|
201
|
+
this.childCards.set(`${rootId}:${progress.childSessionId}`, entry);
|
|
202
|
+
return entry;
|
|
203
|
+
}
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
setAgentName(name) {
|
|
207
|
+
// `acp` is this translator's own placeholder and `unknown` is what an agent that
|
|
208
|
+
// reported nothing gets: neither may overwrite a real name.
|
|
209
|
+
if (!name || name === 'acp' || name === 'unknown')
|
|
210
|
+
return;
|
|
211
|
+
this.agentName = name;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* While muted, `apply` drops every update. The one caller is the `/cd` re-load: the
|
|
215
|
+
* agent re-delivers the whole conversation over `session/load`, and those frames are
|
|
216
|
+
* the very rows the live transcript already holds. Without the mute they would pass
|
|
217
|
+
* through `ensureMessage` (apply() creates an assistant row when none is active) and
|
|
218
|
+
* render the entire history a second time.
|
|
219
|
+
*/
|
|
220
|
+
muted = false;
|
|
221
|
+
mute() {
|
|
222
|
+
this.muted = true;
|
|
223
|
+
}
|
|
224
|
+
unmute() {
|
|
225
|
+
this.muted = false;
|
|
226
|
+
}
|
|
227
|
+
/** Called when a prompt starts: opens the assistant message for the turn. */
|
|
228
|
+
beginTurn(record) {
|
|
229
|
+
// A fresh turn is neither cancelled nor interrupted until it says so.
|
|
230
|
+
record.interruptRequested = false;
|
|
231
|
+
const messageId = this.state.newId('msg');
|
|
232
|
+
const message = {
|
|
233
|
+
id: messageId,
|
|
234
|
+
sessionID: record.session.id,
|
|
235
|
+
role: 'assistant',
|
|
236
|
+
time: { created: Date.now() },
|
|
237
|
+
};
|
|
238
|
+
this.state.addMessage(record, message);
|
|
239
|
+
this.activeMessage.set(record.session.id, messageId);
|
|
240
|
+
this.turnStartedAt.set(record.session.id, Date.now());
|
|
241
|
+
this.stepEmitted.delete(messageId);
|
|
242
|
+
record.busy = true;
|
|
243
|
+
this.openParts.clear();
|
|
244
|
+
this.toolParts.clear();
|
|
245
|
+
this.sink.emit({
|
|
246
|
+
type: EVENT.turnWait,
|
|
247
|
+
data: { sessionID: record.session.id },
|
|
248
|
+
location: this.location,
|
|
249
|
+
});
|
|
250
|
+
this.sink.emit({
|
|
251
|
+
type: EVENT.sessionStatus,
|
|
252
|
+
data: { sessionID: record.session.id, status: 'busy' },
|
|
253
|
+
location: this.location,
|
|
254
|
+
});
|
|
255
|
+
this.sink.emit({
|
|
256
|
+
type: EVENT.messageUpdated,
|
|
257
|
+
data: { sessionID: record.session.id, messageID: messageId, role: 'assistant' },
|
|
258
|
+
location: this.location,
|
|
259
|
+
});
|
|
260
|
+
// The assistant row is created by `ensureStep()` on the FIRST visible part,
|
|
261
|
+
// not here: emitting it at prompt acceptance painted an empty row before the
|
|
262
|
+
// agent had produced anything (the extra blank line before the first reply).
|
|
263
|
+
this.sink.emit({
|
|
264
|
+
type: EVENT.executionStarted,
|
|
265
|
+
data: { sessionID: record.session.id },
|
|
266
|
+
location: this.location,
|
|
267
|
+
});
|
|
268
|
+
return messageId;
|
|
269
|
+
}
|
|
270
|
+
/** Emit `session.step.started` exactly once, immediately before the first part. */
|
|
271
|
+
ensureStep(record, messageId) {
|
|
272
|
+
if (this.stepEmitted.has(messageId))
|
|
273
|
+
return;
|
|
274
|
+
this.stepEmitted.add(messageId);
|
|
275
|
+
this.sink.emit({
|
|
276
|
+
type: EVENT.stepStarted,
|
|
277
|
+
data: {
|
|
278
|
+
sessionID: record.session.id,
|
|
279
|
+
assistantMessageID: messageId,
|
|
280
|
+
agent: this.agentName,
|
|
281
|
+
started: this.turnStartedAt.get(record.session.id) ?? Date.now(),
|
|
282
|
+
model: record.model
|
|
283
|
+
? { id: record.model.modelID, providerID: record.model.providerID }
|
|
284
|
+
: { id: 'unknown', providerID: 'acp' },
|
|
285
|
+
},
|
|
286
|
+
location: this.location,
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
/** Called when the prompt settles (normal or cancelled). */
|
|
290
|
+
endTurn(record, opts = {}) {
|
|
291
|
+
const messageId = this.activeMessage.get(record.session.id);
|
|
292
|
+
if (messageId)
|
|
293
|
+
this.ensureStep(record, messageId);
|
|
294
|
+
// A tool the agent never reported on must not outlive the turn: the UI shows
|
|
295
|
+
// a spinner for as long as the row says "running", and nothing else will ever
|
|
296
|
+
// update it once the turn is over.
|
|
297
|
+
this.closeOpenToolCalls(record, 'the turn ended before this tool reported a result');
|
|
298
|
+
// Close any part left open — an unclosed reasoning part is a stuck spinner.
|
|
299
|
+
if (messageId) {
|
|
300
|
+
// Close through the same path a tool boundary uses. The first version of this loop closed
|
|
301
|
+
// the stored part but emitted no `session.text.ended` here; a separate block then sent one
|
|
302
|
+
// `text.ended`/`reasoning.ended` taken from the *first* part of each kind. With more than
|
|
303
|
+
// one text part in a turn (intro, tools, summary) that event carried the intro while the
|
|
304
|
+
// client applies it to the *last* text entry, so the summary was overwritten with the intro
|
|
305
|
+
// and the screen showed the intro twice. Reusing closeOpenTextParts emits the event with the
|
|
306
|
+
// text of the part it actually closes.
|
|
307
|
+
this.closeOpenTextParts(record, messageId);
|
|
308
|
+
const message = this.state.getMessage(record, messageId);
|
|
309
|
+
if (message) {
|
|
310
|
+
if (opts.error) {
|
|
311
|
+
message.error = { name: 'AcpError', message: opts.error };
|
|
312
|
+
}
|
|
313
|
+
message.time = { ...message.time, completed: Date.now() };
|
|
314
|
+
this.sink.emit({
|
|
315
|
+
type: EVENT.messageUpdated,
|
|
316
|
+
data: { sessionID: record.session.id, messageID: messageId, completed: true },
|
|
317
|
+
location: this.location,
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
// Close the v2 execution envelope. The text/reasoning `ended` events were emitted by
|
|
322
|
+
// closeOpenTextParts above, each carrying the text of the part it closed.
|
|
323
|
+
const finishing = messageId ? this.state.getMessage(record, messageId) : undefined;
|
|
324
|
+
// `session.step.ended` is what puts cost/tokens on the assistant row; the
|
|
325
|
+
// sidebar's context meter reads them from there and shows nothing without
|
|
326
|
+
// them. `finish` mirrors the ACP stop reason.
|
|
327
|
+
if (messageId) {
|
|
328
|
+
const tokens = this.lastTokens.get(record.session.id) ?? {
|
|
329
|
+
input: 0,
|
|
330
|
+
output: 0,
|
|
331
|
+
reasoning: 0,
|
|
332
|
+
cache: { read: 0, write: 0 },
|
|
333
|
+
};
|
|
334
|
+
const step = opts.error ? EVENT.stepFailed : EVENT.stepEnded;
|
|
335
|
+
this.sink.emit({
|
|
336
|
+
type: step,
|
|
337
|
+
data: opts.error
|
|
338
|
+
? {
|
|
339
|
+
sessionID: record.session.id,
|
|
340
|
+
assistantMessageID: messageId,
|
|
341
|
+
error: { name: 'AcpError', message: opts.error },
|
|
342
|
+
finish: 'error',
|
|
343
|
+
}
|
|
344
|
+
: {
|
|
345
|
+
sessionID: record.session.id,
|
|
346
|
+
assistantMessageID: messageId,
|
|
347
|
+
finish: 'stop',
|
|
348
|
+
cost: this.lastCost.get(record.session.id) ?? 0,
|
|
349
|
+
tokens,
|
|
350
|
+
},
|
|
351
|
+
location: this.location,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
if (finishing) {
|
|
355
|
+
// Three outcomes, because the client's store switches on all three: it
|
|
356
|
+
// flips a session from running to idle on any of them, but records the
|
|
357
|
+
// matching `outcome` (`succeeded` / `failed` / `interrupted`). A cancelled
|
|
358
|
+
// turn reported as `succeeded` shows up in the UI as one that finished on
|
|
359
|
+
// its own — so the stop reason, not just "the turn ended", picks the event.
|
|
360
|
+
const outcome = opts.error
|
|
361
|
+
? EVENT.executionFailed
|
|
362
|
+
: opts.interrupted
|
|
363
|
+
? EVENT.executionInterrupted
|
|
364
|
+
: EVENT.executionSucceeded;
|
|
365
|
+
this.sink.emit({
|
|
366
|
+
type: outcome,
|
|
367
|
+
data: { sessionID: record.session.id, error: opts.error },
|
|
368
|
+
location: this.location,
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
const completedAt = Date.now();
|
|
372
|
+
record.busy = false;
|
|
373
|
+
record.session.time = { ...record.session.time, updated: completedAt, idle: completedAt };
|
|
374
|
+
record.session.outcome = opts.error
|
|
375
|
+
? 'failed'
|
|
376
|
+
: opts.interrupted
|
|
377
|
+
? 'interrupted'
|
|
378
|
+
: 'succeeded';
|
|
379
|
+
this.sink.emit({
|
|
380
|
+
type: EVENT.sessionIdle,
|
|
381
|
+
data: { sessionID: record.session.id },
|
|
382
|
+
location: this.location,
|
|
383
|
+
});
|
|
384
|
+
this.sink.emit({
|
|
385
|
+
type: EVENT.turnIdle,
|
|
386
|
+
data: { sessionID: record.session.id },
|
|
387
|
+
location: this.location,
|
|
388
|
+
});
|
|
389
|
+
this.sink.emit({
|
|
390
|
+
type: EVENT.sessionStatus,
|
|
391
|
+
data: { sessionID: record.session.id, status: 'idle' },
|
|
392
|
+
location: this.location,
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
/** Handle one ACP `session/update`. */
|
|
396
|
+
apply(record, update) {
|
|
397
|
+
if (this.muted)
|
|
398
|
+
return;
|
|
399
|
+
// ACP reserves `_meta` for extensions. Merge it (never overwrite) so an
|
|
400
|
+
// agent's keys survive, and keep it on the session: opencode's HTTP schemas
|
|
401
|
+
// have no field for it, so it is preserved rather than either dropped or
|
|
402
|
+
// invented into a surface that would ignore it.
|
|
403
|
+
const meta = update['_meta'];
|
|
404
|
+
if (meta && typeof meta === 'object' && !Array.isArray(meta)) {
|
|
405
|
+
record.meta = { ...record.meta, ...meta };
|
|
406
|
+
}
|
|
407
|
+
const messageId = this.activeMessage.get(record.session.id) ?? this.ensureMessage(record);
|
|
408
|
+
switch (update.sessionUpdate) {
|
|
409
|
+
case UPDATE.agentMessageChunk:
|
|
410
|
+
this.appendText(record, messageId, update, 'text');
|
|
411
|
+
return;
|
|
412
|
+
case UPDATE.agentThoughtChunk:
|
|
413
|
+
this.appendText(record, messageId, update, 'reasoning');
|
|
414
|
+
return;
|
|
415
|
+
case UPDATE.userMessageChunk:
|
|
416
|
+
// Already rendered when /prompt was accepted.
|
|
417
|
+
return;
|
|
418
|
+
case UPDATE.toolCall:
|
|
419
|
+
case UPDATE.toolCallUpdate:
|
|
420
|
+
this.applyToolCall(record, messageId, update);
|
|
421
|
+
return;
|
|
422
|
+
case UPDATE.plan:
|
|
423
|
+
this.applyPlan(record, update);
|
|
424
|
+
return;
|
|
425
|
+
case UPDATE.usageUpdate:
|
|
426
|
+
this.applyUsage(record, update);
|
|
427
|
+
return;
|
|
428
|
+
case UPDATE.sessionInfoUpdate: {
|
|
429
|
+
// The standard way a backend announces a session's title. It is the only
|
|
430
|
+
// title source left now that the the backend projection store is not read; a
|
|
431
|
+
// backend that never sends it leaves the directory basename in place.
|
|
432
|
+
const title = typeof update['title'] === 'string' ? update['title'].trim() : '';
|
|
433
|
+
if (!title || title === record.session.title)
|
|
434
|
+
return;
|
|
435
|
+
record.session.title = title;
|
|
436
|
+
// Marks the title as the agent's: the derived fallback must never replace
|
|
437
|
+
// it, and a later `session/list` lookup may refine it.
|
|
438
|
+
record.titleFromAgent = true;
|
|
439
|
+
this.onTitle?.(record);
|
|
440
|
+
this.log(`title from the backend: ${title}`);
|
|
441
|
+
this.sink.emit({
|
|
442
|
+
type: EVENT.sessionUpdated,
|
|
443
|
+
data: { session: record.session },
|
|
444
|
+
location: this.location,
|
|
445
|
+
});
|
|
446
|
+
// The TUI's store has a case for `session.renamed` and none for
|
|
447
|
+
// `session.updated`, so this is the frame that actually moves the title.
|
|
448
|
+
this.sink.emit({
|
|
449
|
+
type: EVENT.sessionRenamed,
|
|
450
|
+
data: { sessionID: record.session.id, title },
|
|
451
|
+
location: this.location,
|
|
452
|
+
});
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
case UPDATE.availableCommandsUpdate:
|
|
456
|
+
case UPDATE.currentModeUpdate:
|
|
457
|
+
// Not surfaced yet; log so it is visible rather than silent.
|
|
458
|
+
this.log(`ignoring ${update.sessionUpdate}`);
|
|
459
|
+
return;
|
|
460
|
+
default:
|
|
461
|
+
this.log(`unknown session/update: ${update.sessionUpdate}`);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Mark every tool call of this session that has not finished as cancelled.
|
|
466
|
+
*
|
|
467
|
+
* ACP: "The Client **SHOULD** preemptively mark all non-finished tool calls
|
|
468
|
+
* pertaining to the current turn as `cancelled` as soon as it sends the
|
|
469
|
+
* `session/cancel` notification."
|
|
470
|
+
*
|
|
471
|
+
* opencode has no `cancelled` tool state, so the terminal state it does have is
|
|
472
|
+
* used, carrying the reason as the tool's output. The point is the same either
|
|
473
|
+
* way: a row must not be left spinning while it waits for an update that the
|
|
474
|
+
* aborted turn will never send. Returns how many rows were closed.
|
|
475
|
+
*/
|
|
476
|
+
/**
|
|
477
|
+
* Close every tool call the agent left unfinished.
|
|
478
|
+
*
|
|
479
|
+
* Called on abort *and* at normal turn end: an agent may simply stop reporting
|
|
480
|
+
* on a call, and a tool row that still says "running" after the turn is over is
|
|
481
|
+
* a spinner that never stops. `reason` lands in the row's output, so the UI says
|
|
482
|
+
* why rather than just going red.
|
|
483
|
+
*/
|
|
484
|
+
closeOpenToolCalls(record, reason) {
|
|
485
|
+
let cancelled = 0;
|
|
486
|
+
for (const [messageId, parts] of record.parts) {
|
|
487
|
+
for (const part of parts) {
|
|
488
|
+
if (part.type !== 'tool')
|
|
489
|
+
continue;
|
|
490
|
+
if (part.state.status !== 'pending' && part.state.status !== 'running')
|
|
491
|
+
continue;
|
|
492
|
+
const output = reason;
|
|
493
|
+
const updated = {
|
|
494
|
+
...part,
|
|
495
|
+
state: {
|
|
496
|
+
...part.state,
|
|
497
|
+
status: 'error',
|
|
498
|
+
// The reason goes in `error` (what the client paints), not `output`
|
|
499
|
+
// (what the tool produced) — a cancelled `write` would otherwise show
|
|
500
|
+
// the file's content as the reason.
|
|
501
|
+
error: reason,
|
|
502
|
+
output: part.state.output,
|
|
503
|
+
time: { ...part.state.time, end: Date.now() },
|
|
504
|
+
},
|
|
505
|
+
};
|
|
506
|
+
this.state.upsertPart(record, messageId, updated);
|
|
507
|
+
this.emitPartUpdated(record, messageId, updated);
|
|
508
|
+
this.sink.emit({
|
|
509
|
+
type: EVENT.toolFailed,
|
|
510
|
+
data: {
|
|
511
|
+
sessionID: record.session.id,
|
|
512
|
+
assistantMessageID: messageId,
|
|
513
|
+
id: updated.id,
|
|
514
|
+
executed: true,
|
|
515
|
+
// Structured for the same reason as the failure event above.
|
|
516
|
+
error: { type: 'tool', message: reason },
|
|
517
|
+
metadata: {},
|
|
518
|
+
content: [],
|
|
519
|
+
},
|
|
520
|
+
location: this.location,
|
|
521
|
+
});
|
|
522
|
+
cancelled += 1;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return cancelled;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* ACP reports context usage as `{used, size}`. opencode tracks input/output
|
|
529
|
+
* separately, so map `used` onto `input` and keep the rest zeroed rather than
|
|
530
|
+
* inventing a split the agent never sent.
|
|
531
|
+
*/
|
|
532
|
+
applyUsage(record, update) {
|
|
533
|
+
const used = typeof update.used === 'number' ? update.used : 0;
|
|
534
|
+
const tokens = { input: used, output: 0, reasoning: 0, cache: { read: 0, write: 0 } };
|
|
535
|
+
// `used` is tokens in context; `size` is the window the percentage is drawn
|
|
536
|
+
// against. The TUI reads the window off the model's `limit.context`, so it is
|
|
537
|
+
// kept per session for `modelCatalog()` to serve.
|
|
538
|
+
if (typeof update.size === 'number' && update.size > 0) {
|
|
539
|
+
this.lastContextSize.set(record.session.id, update.size);
|
|
540
|
+
}
|
|
541
|
+
// ★ A context count cannot exceed its window. opencode's ACP adapter sends
|
|
542
|
+
// `used = input+output+reasoning+cache` for the whole agentic turn, which can
|
|
543
|
+
// be several times the window; treating it as "context" made the TUI show
|
|
544
|
+
// e.g. 3.0M (304%) for a 1M model. Keep the previous (plausible) row instead.
|
|
545
|
+
const size = this.lastContextSize.get(record.session.id);
|
|
546
|
+
if (size !== undefined && used > size) {
|
|
547
|
+
this.log(`[bridge] usage_update used=${used} exceeds size=${size}; not a context count, keeping the previous usage`);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
// The cost travels as `{amount, currency}` and is CUMULATIVE for the session.
|
|
551
|
+
// Our event field is a plain number; an amount in another currency would be a
|
|
552
|
+
// wrong number, so only USD is carried (the honest part of a currency-blind field).
|
|
553
|
+
const rawCost = update.cost;
|
|
554
|
+
let cost = 0;
|
|
555
|
+
if (rawCost && typeof rawCost === 'object' && !Array.isArray(rawCost)) {
|
|
556
|
+
const amount = rawCost.amount;
|
|
557
|
+
const currency = rawCost.currency;
|
|
558
|
+
if (typeof amount === 'number' && (currency === undefined || String(currency).toUpperCase() === 'USD')) {
|
|
559
|
+
cost = amount;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
this.lastCost.set(record.session.id, cost);
|
|
563
|
+
// Remembered so `session.step.ended` can carry the same numbers: the
|
|
564
|
+
// sidebar's context meter reads them off the assistant row, not off
|
|
565
|
+
// `session.usage.updated`.
|
|
566
|
+
this.lastTokens.set(record.session.id, tokens);
|
|
567
|
+
this.sink.emit({
|
|
568
|
+
type: EVENT.sessionUsageUpdated,
|
|
569
|
+
data: { sessionID: record.session.id, cost, tokens },
|
|
570
|
+
location: this.location,
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
/** The context window the agent reported for this session, if it sent one. */
|
|
574
|
+
contextWindowFor(sessionId) {
|
|
575
|
+
return this.lastContextSize.get(sessionId);
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* Usage from the prompt RESULT rather than a `usage_update` frame.
|
|
579
|
+
*
|
|
580
|
+
* opencode reports `{inputTokens, outputTokens, thoughtTokens, cachedReadTokens}` in the
|
|
581
|
+
* `session/prompt` response and never sends a `usage_update`; leaving the result's usage
|
|
582
|
+
* unread made the sidebar's context meter (which reads tokens off `session.step.ended`)
|
|
583
|
+
* and the footer show nothing. Call this before `endTurn`.
|
|
584
|
+
*/
|
|
585
|
+
recordPromptUsage(record, usage) {
|
|
586
|
+
if (!usage || typeof usage !== 'object')
|
|
587
|
+
return;
|
|
588
|
+
const raw = usage;
|
|
589
|
+
const number = (value) => typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
|
590
|
+
const tokens = {
|
|
591
|
+
input: number(raw.inputTokens),
|
|
592
|
+
output: number(raw.outputTokens),
|
|
593
|
+
reasoning: number(raw.thoughtTokens),
|
|
594
|
+
cache: { read: number(raw.cachedReadTokens), write: number(raw.cachedWriteTokens) },
|
|
595
|
+
};
|
|
596
|
+
if (tokens.input === 0 && tokens.output === 0 && tokens.reasoning === 0)
|
|
597
|
+
return;
|
|
598
|
+
// Same guard as usage_update: opencode can put a whole turn's processed
|
|
599
|
+
// tokens in the prompt result. That is not the current context; do not let it
|
|
600
|
+
// overwrite the last plausible row.
|
|
601
|
+
const size = this.lastContextSize.get(record.session.id);
|
|
602
|
+
const total = tokens.input + tokens.output + tokens.reasoning + tokens.cache.read + tokens.cache.write;
|
|
603
|
+
if (size !== undefined && total > size) {
|
|
604
|
+
this.log(`[bridge] prompt usage total=${total} exceeds size=${size}; not a context count, keeping the previous usage`);
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
this.lastTokens.set(record.session.id, tokens);
|
|
608
|
+
this.sink.emit({
|
|
609
|
+
type: EVENT.sessionUsageUpdated,
|
|
610
|
+
data: { sessionID: record.session.id, cost: 0, tokens },
|
|
611
|
+
location: this.location,
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
// ---------------------------------------------------------------- internals
|
|
615
|
+
ensureMessage(record) {
|
|
616
|
+
return this.beginTurn(record);
|
|
617
|
+
}
|
|
618
|
+
textOf(update) {
|
|
619
|
+
const content = update['content'];
|
|
620
|
+
if (typeof content === 'string')
|
|
621
|
+
return content;
|
|
622
|
+
// ★ 真实 ACP 形状:content 是【单个块对象】{type:'text', text} ✓
|
|
623
|
+
// 少了这条就会静默返回空串 ✗ → part 永远不产生 ✗ → 界面一片空白 ✓
|
|
624
|
+
// (单元测试抓到的 ✓)
|
|
625
|
+
if (content && typeof content === 'object' && !Array.isArray(content)) {
|
|
626
|
+
const block = content;
|
|
627
|
+
if (typeof block.text === 'string')
|
|
628
|
+
return block.text;
|
|
629
|
+
}
|
|
630
|
+
if (Array.isArray(content)) {
|
|
631
|
+
return content
|
|
632
|
+
.map((block) => {
|
|
633
|
+
const b = block;
|
|
634
|
+
return b.type === 'text' && typeof b.text === 'string' ? b.text : '';
|
|
635
|
+
})
|
|
636
|
+
.join('');
|
|
637
|
+
}
|
|
638
|
+
if (typeof update['text'] === 'string')
|
|
639
|
+
return update['text'];
|
|
640
|
+
return '';
|
|
641
|
+
}
|
|
642
|
+
closeOpenTextParts(record, messageId, except) {
|
|
643
|
+
const prefix = `${record.session.id}/${messageId}/`;
|
|
644
|
+
for (const [key, open] of [...this.openParts]) {
|
|
645
|
+
if (!key.startsWith(prefix))
|
|
646
|
+
continue;
|
|
647
|
+
const kind = key.slice(prefix.length);
|
|
648
|
+
if (kind === except)
|
|
649
|
+
continue;
|
|
650
|
+
const existing = this.state.findPart(record, open.partId);
|
|
651
|
+
if (existing && (existing.type === 'text' || existing.type === 'reasoning')) {
|
|
652
|
+
existing.time = { ...existing.time, end: Date.now() };
|
|
653
|
+
this.emitPartUpdated(record, messageId, existing);
|
|
654
|
+
this.sink.emit({
|
|
655
|
+
type: existing.type === 'text' ? EVENT.textEnded : EVENT.reasoningEnded,
|
|
656
|
+
data: existing.type === 'text'
|
|
657
|
+
? { sessionID: record.session.id, assistantMessageID: messageId, text: existing.text }
|
|
658
|
+
: { sessionID: record.session.id, assistantMessageID: messageId, text: existing.text },
|
|
659
|
+
location: this.location,
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
this.openParts.delete(key);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
appendText(record, messageId, update, kind) {
|
|
666
|
+
const text = this.textOf(update);
|
|
667
|
+
if (!text)
|
|
668
|
+
return;
|
|
669
|
+
this.ensureStep(record, messageId);
|
|
670
|
+
// A turn can end (prompt result) while the agent keeps streaming — dsh's
|
|
671
|
+
// background jobs do exactly that. The late part belongs in the history, but
|
|
672
|
+
// its `reasoning.started` would make the TUI show a "thinking" spinner on a
|
|
673
|
+
// completed message, which then vanishes (reported 2026-10-20). Record it with
|
|
674
|
+
// an end time and emit no reasoning UI events; late tool/text keep their
|
|
675
|
+
// static-history behaviour.
|
|
676
|
+
const late = !record.busy;
|
|
677
|
+
this.closeOpenTextParts(record, messageId, kind);
|
|
678
|
+
const key = `${record.session.id}/${messageId}/${kind}`;
|
|
679
|
+
let open = this.openParts.get(key);
|
|
680
|
+
if (!open) {
|
|
681
|
+
open = { partId: this.state.newId('prt'), text: '' };
|
|
682
|
+
this.openParts.set(key, open);
|
|
683
|
+
}
|
|
684
|
+
open.text += text;
|
|
685
|
+
const part = kind === 'text'
|
|
686
|
+
? {
|
|
687
|
+
id: open.partId,
|
|
688
|
+
sessionID: record.session.id,
|
|
689
|
+
messageID: messageId,
|
|
690
|
+
type: 'text',
|
|
691
|
+
text: open.text,
|
|
692
|
+
time: { start: Date.now() },
|
|
693
|
+
}
|
|
694
|
+
: {
|
|
695
|
+
id: open.partId,
|
|
696
|
+
sessionID: record.session.id,
|
|
697
|
+
messageID: messageId,
|
|
698
|
+
type: 'reasoning',
|
|
699
|
+
text: open.text,
|
|
700
|
+
// `late`: closed on arrival, so a reload renders it as static history
|
|
701
|
+
// instead of an active Thought row.
|
|
702
|
+
time: late ? { start: Date.now(), end: Date.now() } : { start: Date.now() },
|
|
703
|
+
};
|
|
704
|
+
const { created } = this.state.upsertPart(record, messageId, part);
|
|
705
|
+
if (late && kind === 'reasoning') {
|
|
706
|
+
if (created)
|
|
707
|
+
this.log('[bridge] late reasoning recorded without a UI event (the turn has ended)');
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
if (!created) {
|
|
711
|
+
// Delta first: the TUI appends from it and uses the full part to re-render.
|
|
712
|
+
this.sink.emit({
|
|
713
|
+
type: EVENT.messagePartDelta,
|
|
714
|
+
data: {
|
|
715
|
+
sessionID: record.session.id,
|
|
716
|
+
messageID: messageId,
|
|
717
|
+
partID: open.partId,
|
|
718
|
+
field: kind === 'text' ? 'text' : 'reasoning',
|
|
719
|
+
delta: text,
|
|
720
|
+
time: Date.now(),
|
|
721
|
+
},
|
|
722
|
+
location: this.location,
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
// opencode v2 events. `started` only on first sighting so the client
|
|
726
|
+
// creates the assistant content block exactly once.
|
|
727
|
+
if (created) {
|
|
728
|
+
this.sink.emit({
|
|
729
|
+
type: kind === 'text' ? EVENT.textStarted : EVENT.reasoningStarted,
|
|
730
|
+
data: {
|
|
731
|
+
sessionID: record.session.id,
|
|
732
|
+
assistantMessageID: messageId,
|
|
733
|
+
...(kind === 'reasoning' ? { state: {} } : {}),
|
|
734
|
+
},
|
|
735
|
+
location: this.location,
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
this.sink.emit({
|
|
739
|
+
type: kind === 'text' ? EVENT.textDelta : EVENT.reasoningDelta,
|
|
740
|
+
data: { sessionID: record.session.id, assistantMessageID: messageId, delta: text },
|
|
741
|
+
location: this.location,
|
|
742
|
+
});
|
|
743
|
+
this.emitPartUpdated(record, messageId, part);
|
|
744
|
+
}
|
|
745
|
+
applyToolCall(record, messageId, update) {
|
|
746
|
+
this.ensureStep(record, messageId);
|
|
747
|
+
const callId = String(update['toolCallId'] ?? '');
|
|
748
|
+
if (!callId)
|
|
749
|
+
return;
|
|
750
|
+
// The tool NAME is fixed at first sighting ("shell", "websearch"): the TUI picks
|
|
751
|
+
// the row component by it. A later title is the tool's argument ("echo hello"),
|
|
752
|
+
// so letting it overwrite the name turned a shell card into an unknown tool.
|
|
753
|
+
const knownName = this.toolNames.get(callId);
|
|
754
|
+
// ACP's `name` is "the optional programmatic name of the invoked tool"
|
|
755
|
+
// (`read_file`); `title` is prose ("Reading configuration file") and `kind` is the
|
|
756
|
+
// category. The client picks the row component from this, so a bridge that sends
|
|
757
|
+
// the title makes a `shell` row render as an unknown tool — "Writing command…".
|
|
758
|
+
const reported = update['name'];
|
|
759
|
+
const reportedName = typeof reported === 'string' && reported.length > 0
|
|
760
|
+
? reported
|
|
761
|
+
: String(update['title'] ?? update['kind'] ?? 'tool');
|
|
762
|
+
// ★ A delegated agent's card has to be recognisable as one.
|
|
763
|
+
//
|
|
764
|
+
// opencode's TUI renders a dedicated `Subagent` row — with a "Delegating…" pending
|
|
765
|
+
// label and a click that opens the child — only when the tool name is `task`
|
|
766
|
+
// (`canonicalToolName`: `if (name === "task") return "subagent"`). Everything else,
|
|
767
|
+
// including ACP's own `kind: "think"`, falls through to the generic card, so a user
|
|
768
|
+
// cannot tell a subagent from a shell command.
|
|
769
|
+
//
|
|
770
|
+
// Measured on every agent in our matrix, the word is the agent's OWN tool name:
|
|
771
|
+
// `dsh --profile acp` no `name`, `title: "subagent"` (title falls back to the tool
|
|
772
|
+
// name when there is no prose)
|
|
773
|
+
// `<profile>` `name: "subagent"`
|
|
774
|
+
// `opencode acp` no `name`, title falls back to its tool name (`"task"`)
|
|
775
|
+
// `claude-agent-acp` `name: "Agent"` / `"Task"` (its renderer checks exactly these
|
|
776
|
+
// two — `renderer.ts`, `toolUse.name === "Agent" || "Task"`)
|
|
777
|
+
// `codex-acp` titles its subagent activity `Start subagent <name>` /
|
|
778
|
+
// `Interact with subagent <name>` / `Interrupt …` / `Complete …`
|
|
779
|
+
// (`SubagentActivityReporter.ts`), while `name` stays the
|
|
780
|
+
// underlying tool (`exec_command`)
|
|
781
|
+
// Everything else is a bare noun and is matched as such. `codex-acp` is the one shape
|
|
782
|
+
// that has to be read out of the TITLE, and it is the ONE agent-gated branch in this
|
|
783
|
+
// file: `title` is prose everywhere else, and another adapter writing
|
|
784
|
+
// "Start subagent …" as a caption is not far-fetched. The gate uses the name the
|
|
785
|
+
// agent reported in `initialize` — not the launch command — so it survives `npx`,
|
|
786
|
+
// a local checkout path, or a wrapper script, and an adapter that renames itself is
|
|
787
|
+
// still matched by the `codex` stem.
|
|
788
|
+
const isCodex = /codex/i.test(this.agentName);
|
|
789
|
+
// The title is checked on its own, not only when `name` is missing: `codex-acp`
|
|
790
|
+
// sends `name: "exec_command"` WITH a subagent title, so a name-first chain would
|
|
791
|
+
// never look at it. Gated on the agent name so no other adapter's prose is read.
|
|
792
|
+
const title = typeof update['title'] === 'string' ? update['title'] : '';
|
|
793
|
+
const looksLikeSubagent = SUBAGENT_NAME.test(reportedName) || (isCodex && SUBAGENT_VERB_TITLE.test(title));
|
|
794
|
+
const name = knownName ?? (looksLikeSubagent ? 'task' : reportedName);
|
|
795
|
+
if (knownName === undefined)
|
|
796
|
+
this.toolNames.set(callId, name);
|
|
797
|
+
// Merge the input instead of replacing it. opencode's pending frame often carries
|
|
798
|
+
// only `{cwd}` and the command/query arrives with `in_progress`; publishing the
|
|
799
|
+
// pending snapshot made the TUI show "Writing command…" / "Searching web…" even
|
|
800
|
+
// after the tool finished (its row is only "complete" once input.command/query
|
|
801
|
+
// exists).
|
|
802
|
+
const raw = update['rawInput'];
|
|
803
|
+
const previous = this.toolInputs.get(callId);
|
|
804
|
+
const merged = raw === null || raw === undefined
|
|
805
|
+
? previous
|
|
806
|
+
: typeof raw === 'object' && !Array.isArray(raw) && previous && typeof previous === 'object' && !Array.isArray(previous)
|
|
807
|
+
? { ...previous, ...raw }
|
|
808
|
+
: raw;
|
|
809
|
+
// ACP's `rawInput` is free-form ("Any JSON value is accepted"), and the ACP `kind` is
|
|
810
|
+
// what names the category — but opencode's TUI renders a tool from ITS OWN input field
|
|
811
|
+
// names (`input.path` for read/edit, `input.command` for execute). An agent that says
|
|
812
|
+
// `kind: "read"` with `{file_path: …}` is perfectly conformant and still rendered as an
|
|
813
|
+
// empty "Preparing edit…"/"Reading file…" row, because `input.path` does not exist.
|
|
814
|
+
// So: when `kind` tells us the category, add the key the client reads, taking the value
|
|
815
|
+
// from whatever the agent did send. This looks at the AGENT'S KIND, never at a
|
|
816
|
+
// particular agent's field names — `file_path`, `filePath`, `path` all work.
|
|
817
|
+
const normalized = merged === undefined ? undefined : withClientInputKey(merged, update['kind'], update['title']);
|
|
818
|
+
if (merged !== undefined)
|
|
819
|
+
this.toolInputs.set(callId, merged);
|
|
820
|
+
const partId = this.toolParts.get(callId);
|
|
821
|
+
const existing = partId ? this.state.findPart(record, partId) : undefined;
|
|
822
|
+
const lastInput = existing?.type === 'tool' ? existing.state.input : undefined;
|
|
823
|
+
// ACP: "All fields except `toolCallId` are optional in updates. Only the fields being
|
|
824
|
+
// changed need to be included", and its own example is that an omitted `name` leaves the
|
|
825
|
+
// existing one unchanged. `status` on a `tool_call_update` is the same: omission means
|
|
826
|
+
// "unchanged", NOT the `pending` default that applies to the initial `tool_call`.
|
|
827
|
+
// Measured with `dsh --profile <profile>`, which sends the completed `rawInput` in a
|
|
828
|
+
// frame with no `status` at all: resetting there moved every finished tool backwards,
|
|
829
|
+
// back to the "Writing command…" placeholder with nothing to open.
|
|
830
|
+
// ★ "absent" and "null" are different things in ACP. The spec's rule that
|
|
831
|
+
// "omission and null are equivalent" is stated ONLY for `rawInput`/`rawOutput`; for every
|
|
832
|
+
// other field an update means "only the fields being changed need to be included", so an
|
|
833
|
+
// ABSENT key leaves the value alone while a present one — even `null` — replaces it.
|
|
834
|
+
// Zed models this explicitly (`MaybeUndefined::{Undefined, Null, Value}` in
|
|
835
|
+
// `acp/terminal_updates.rs`, pinned by `patch_preserves_omission_and_null`).
|
|
836
|
+
// Testing `=== undefined` conflated the two.
|
|
837
|
+
const namesStatus = Object.prototype.hasOwnProperty.call(update, 'status');
|
|
838
|
+
const status = !namesStatus && existing?.type === 'tool' ? existing.state.status : mapToolStatus(update['status']);
|
|
839
|
+
// A `pending` frame whose input is obviously partial (`{}` or only `cwd`) is a
|
|
840
|
+
// placeholder: opencode fills in the command/query with the next update. Creating
|
|
841
|
+
// the row now would freeze that placeholder into the TUI's card. Everything else
|
|
842
|
+
// creates immediately — including a pending tool with no input at all, which has
|
|
843
|
+
// nothing more to wait for.
|
|
844
|
+
if (!existing && status === 'pending' && isPartialToolInput(merged))
|
|
845
|
+
return;
|
|
846
|
+
let id = partId;
|
|
847
|
+
if (!id) {
|
|
848
|
+
this.closeOpenTextParts(record, messageId);
|
|
849
|
+
id = this.state.newId('prt');
|
|
850
|
+
this.toolParts.set(callId, id);
|
|
851
|
+
}
|
|
852
|
+
const part = {
|
|
853
|
+
id,
|
|
854
|
+
sessionID: record.session.id,
|
|
855
|
+
messageID: messageId,
|
|
856
|
+
type: 'tool',
|
|
857
|
+
callID: callId,
|
|
858
|
+
tool: name,
|
|
859
|
+
state: {
|
|
860
|
+
status,
|
|
861
|
+
input: merged,
|
|
862
|
+
output: existing?.type === 'tool' ? existing.state.output : undefined,
|
|
863
|
+
// A result frame says whether the call produced output or failed. ACP's
|
|
864
|
+
// `rawOutput.error` is the failure sentence; keeping it apart from `output` is
|
|
865
|
+
// what lets a reloaded failed call render as a failure (see `toolState`).
|
|
866
|
+
...(status === 'completed' ? { ...pickOutput(update) } : {}),
|
|
867
|
+
...(status === 'error' ? { error: toolError(update) ?? toolOutput(update) ?? 'tool failed' } : {}),
|
|
868
|
+
// A delegated run's state rides on the card (`metadata.status` is what the client's
|
|
869
|
+
// `Background` badge reads). Stored here so the projection and a reload keep it:
|
|
870
|
+
// `session.tool.success` rewrites the row's metadata from `toolMetadata(update)`,
|
|
871
|
+
// which is `{}` for an ACP frame, so it would otherwise be wiped on completion.
|
|
872
|
+
metadata: {
|
|
873
|
+
...toolMetadata(update),
|
|
874
|
+
...(this.childMeta.get(callId) ?? {}),
|
|
875
|
+
...(existing?.type === 'tool' ? (existing.state.metadata ?? {}) : {}),
|
|
876
|
+
},
|
|
877
|
+
// The LATEST title, not the first: dsh's early frames carry a generic one
|
|
878
|
+
// ("bash all commands") and the in_progress frame carries the real command.
|
|
879
|
+
// Keeping the first froze the generic caption into the card and into the
|
|
880
|
+
// reloaded projection.
|
|
881
|
+
title: typeof update['title'] === 'string'
|
|
882
|
+
? update['title']
|
|
883
|
+
: existing?.type === 'tool'
|
|
884
|
+
? existing.state.title
|
|
885
|
+
: undefined,
|
|
886
|
+
// ACP's `kind` decides the row's presentation for agents that never name the tool
|
|
887
|
+
// (`execute` → shell card). Recorded once, from the first frame that has it.
|
|
888
|
+
kind: typeof update['kind'] === 'string'
|
|
889
|
+
? update['kind']
|
|
890
|
+
: existing?.type === 'tool'
|
|
891
|
+
? existing.state.kind
|
|
892
|
+
: undefined,
|
|
893
|
+
time: {
|
|
894
|
+
start: existing?.type === 'tool' ? existing.state.time.start : Date.now(),
|
|
895
|
+
...(status === 'completed' || status === 'error' ? { end: Date.now() } : {}),
|
|
896
|
+
},
|
|
897
|
+
},
|
|
898
|
+
};
|
|
899
|
+
this.state.upsertPart(record, messageId, part);
|
|
900
|
+
this.emitPartUpdated(record, messageId, part);
|
|
901
|
+
// ---- opencode v2 tool events -------------------------------------------
|
|
902
|
+
// The TUI builds tool rows exclusively from these. `input.started` is the
|
|
903
|
+
// only one that creates the row, so it must be first and exactly once.
|
|
904
|
+
if (!existing) {
|
|
905
|
+
this.sink.emit({
|
|
906
|
+
type: EVENT.toolInputStarted,
|
|
907
|
+
data: { sessionID: record.session.id, assistantMessageID: messageId, id, name },
|
|
908
|
+
location: this.location,
|
|
909
|
+
});
|
|
910
|
+
this.sink.emit({
|
|
911
|
+
type: EVENT.toolInputEnded,
|
|
912
|
+
data: {
|
|
913
|
+
sessionID: record.session.id,
|
|
914
|
+
assistantMessageID: messageId,
|
|
915
|
+
id,
|
|
916
|
+
text: typeof normalized === 'string' ? normalized : JSON.stringify(normalized ?? {}),
|
|
917
|
+
},
|
|
918
|
+
location: this.location,
|
|
919
|
+
});
|
|
920
|
+
this.sink.emit({
|
|
921
|
+
type: EVENT.toolCalled,
|
|
922
|
+
data: {
|
|
923
|
+
sessionID: record.session.id,
|
|
924
|
+
assistantMessageID: messageId,
|
|
925
|
+
id,
|
|
926
|
+
// The client stores `running`/`completed` inputs as a record and runs
|
|
927
|
+
// `Object.entries` over it; `null`/`undefined` crashes the whole TUI
|
|
928
|
+
// ("Object.entries requires that input parameter not be null or undefined").
|
|
929
|
+
// A tool whose first frame carries no input still gets an empty record, and
|
|
930
|
+
// the real input arrives (and replaces it) with the next update.
|
|
931
|
+
input: normalized === undefined ? {} : normalized,
|
|
932
|
+
executed: true,
|
|
933
|
+
state: undefined,
|
|
934
|
+
},
|
|
935
|
+
location: this.location,
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
else if (JSON.stringify(normalized ?? null) !== JSON.stringify(lastInput)) {
|
|
939
|
+
// ★ The row was created with the input of its FIRST frame — and agents stream that
|
|
940
|
+
// input. `dsh --profile <profile>` announces a bash call with
|
|
941
|
+
// `rawInput: {arguments: '{"'}` and fills the command in over the following frames;
|
|
942
|
+
// because `tool.called` was only ever sent for a NEW part, the client kept the empty
|
|
943
|
+
// snapshot and showed "Writing command…" for a call that had long since finished
|
|
944
|
+
// (measured: one `tool.called` per call, carrying `{"arguments": "{\""`).
|
|
945
|
+
// Re-send it whenever the input actually changed: that is what the client re-reads.
|
|
946
|
+
this.sink.emit({
|
|
947
|
+
type: EVENT.toolCalled,
|
|
948
|
+
data: {
|
|
949
|
+
sessionID: record.session.id,
|
|
950
|
+
assistantMessageID: messageId,
|
|
951
|
+
id,
|
|
952
|
+
input: normalized === undefined ? {} : normalized,
|
|
953
|
+
executed: true,
|
|
954
|
+
state: undefined,
|
|
955
|
+
},
|
|
956
|
+
location: this.location,
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
// A finished call must end EVERY progress indicator, and the client's activity
|
|
960
|
+
// summary ("Sending", the per-turn spinner and its "Sending · Ns" counter) only
|
|
961
|
+
// goes quiet when `message.updated` says the message is completed. A failed tool is
|
|
962
|
+
// finished exactly like a successful one: dsh's `Write` answers
|
|
963
|
+
// `[tool error: FS_STALE_VERSION]`, and that turn then showed a spinner forever.
|
|
964
|
+
// This does not excuse the turn — `executionStarted` already marked the session
|
|
965
|
+
// busy, and `endTurn` sets the real end time and the outcome.
|
|
966
|
+
if (status === 'completed' || status === 'error') {
|
|
967
|
+
const message = this.state.getMessage(record, messageId);
|
|
968
|
+
if (message && message.time.completed === undefined) {
|
|
969
|
+
message.time = { ...message.time, completed: Date.now() };
|
|
970
|
+
this.sink.emit({
|
|
971
|
+
type: EVENT.messageUpdated,
|
|
972
|
+
data: { sessionID: record.session.id, messageID: messageId, completed: true },
|
|
973
|
+
location: this.location,
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
const toolResult = part.type === 'tool' ? part.state.output : undefined;
|
|
978
|
+
if (status === 'completed') {
|
|
979
|
+
this.sink.emit({
|
|
980
|
+
type: EVENT.toolSuccess,
|
|
981
|
+
data: {
|
|
982
|
+
sessionID: record.session.id,
|
|
983
|
+
assistantMessageID: messageId,
|
|
984
|
+
id,
|
|
985
|
+
executed: true,
|
|
986
|
+
metadata: { ...toolMetadata(update), ...(this.childMeta.get(String(update['toolCallId'] ?? '')) ?? {}) },
|
|
987
|
+
content: toolResult === undefined ? [] : [{ type: 'text', text: String(toolResult) }],
|
|
988
|
+
resultState: undefined,
|
|
989
|
+
},
|
|
990
|
+
location: this.location,
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
else if (status === 'error') {
|
|
994
|
+
this.sink.emit({
|
|
995
|
+
type: EVENT.toolFailed,
|
|
996
|
+
data: {
|
|
997
|
+
sessionID: record.session.id,
|
|
998
|
+
assistantMessageID: messageId,
|
|
999
|
+
id,
|
|
1000
|
+
executed: true,
|
|
1001
|
+
// A STRUCTURED error, not a string: opencode v2's tool part declares
|
|
1002
|
+
// `state.error: SessionError.Error` = `{type, message}`, and its `InlineTool`
|
|
1003
|
+
// renders `stripAnsi(props.part.state.error.message)`. A bare string there made
|
|
1004
|
+
// that read `undefined` and the whole TUI died with
|
|
1005
|
+
// "Expected a `string`, got `undefined`" the moment any tool failed.
|
|
1006
|
+
error: { type: 'tool', message: toolError(update) ?? String(toolResult ?? 'tool failed') },
|
|
1007
|
+
metadata: toolMetadata(update),
|
|
1008
|
+
content: part.type === 'tool' && part.state.error !== undefined
|
|
1009
|
+
? [{ type: 'text', text: part.state.error }]
|
|
1010
|
+
: [],
|
|
1011
|
+
},
|
|
1012
|
+
location: this.location,
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* ACP `plan` updates have nowhere to go. opencode v2 removed todo entirely
|
|
1018
|
+
* (PR #35989: tool, sidebar panel, events and the persisted table, with no
|
|
1019
|
+
* stated replacement), so there is no event to emit and no route to serve. The
|
|
1020
|
+
* entries are logged rather than dropped silently.
|
|
1021
|
+
*/
|
|
1022
|
+
applyPlan(record, update) {
|
|
1023
|
+
const entries = update['entries'];
|
|
1024
|
+
if (!Array.isArray(entries))
|
|
1025
|
+
return;
|
|
1026
|
+
const todos = entries.map((entry) => {
|
|
1027
|
+
const e = entry;
|
|
1028
|
+
return `${String(e.status ?? 'pending')}:${String(e.content ?? '')}`;
|
|
1029
|
+
});
|
|
1030
|
+
this.log(`[bridge] ACP plan update (${todos.length} entries) has no opencode v2 surface: ${todos.join(' | ')}`);
|
|
1031
|
+
}
|
|
1032
|
+
emitPartUpdated(record, messageId, part) {
|
|
1033
|
+
const time = Date.now();
|
|
1034
|
+
this.sink.emit({
|
|
1035
|
+
type: EVENT.messagePartUpdated,
|
|
1036
|
+
data: { sessionID: record.session.id, messageID: messageId, part, time },
|
|
1037
|
+
location: this.location,
|
|
1038
|
+
});
|
|
1039
|
+
// Frames stamped `time.now()` are what fill the client's "Sending · Ns" counter.
|
|
1040
|
+
// Every part update is a frame, so an unstamped one leaves that counter spinning
|
|
1041
|
+
// at whatever it last read; the stale-tool case below depends on it stopping.
|
|
1042
|
+
this.sink.emit({ type: EVENT.sessionTimeUpdated, data: { sessionID: record.session.id, time }, location: this.location });
|
|
1043
|
+
this.state.touch(record.session.id);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* ACP statuses are free-form strings in practice. Map conservatively: an
|
|
1048
|
+
* unknown status becomes `running`, never `completed`, so the UI keeps showing
|
|
1049
|
+
* activity instead of claiming a tool finished when it did not.
|
|
1050
|
+
*/
|
|
1051
|
+
/**
|
|
1052
|
+
* Is this input obviously a placeholder? opencode's pending frame carries `{}` (or
|
|
1053
|
+
* only `{cwd}`) and the command/query arrives with `in_progress`; publishing the
|
|
1054
|
+
* placeholder is what pinned every shell card to "Writing command…".
|
|
1055
|
+
*
|
|
1056
|
+
* `undefined` is NOT partial: a tool that never sends an input has nothing to wait
|
|
1057
|
+
* for.
|
|
1058
|
+
*/
|
|
1059
|
+
export function isPartialToolInput(input) {
|
|
1060
|
+
if (input === undefined || input === null)
|
|
1061
|
+
return false;
|
|
1062
|
+
if (typeof input === 'string')
|
|
1063
|
+
return input.trim() === '';
|
|
1064
|
+
if (Array.isArray(input))
|
|
1065
|
+
return false;
|
|
1066
|
+
if (typeof input === 'object') {
|
|
1067
|
+
const keys = Object.keys(input);
|
|
1068
|
+
if (keys.length === 0)
|
|
1069
|
+
return true;
|
|
1070
|
+
return keys.every((key) => key === 'cwd' || key === 'workdir');
|
|
1071
|
+
}
|
|
1072
|
+
return false;
|
|
1073
|
+
}
|
|
1074
|
+
/** `rawOutput.metadata` is where the agent puts `{exit, truncated, status}`. */
|
|
1075
|
+
export function toolMetadata(update) {
|
|
1076
|
+
const raw = update['rawOutput'];
|
|
1077
|
+
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
1078
|
+
const meta = raw.metadata;
|
|
1079
|
+
if (meta && typeof meta === 'object' && !Array.isArray(meta))
|
|
1080
|
+
return meta;
|
|
1081
|
+
}
|
|
1082
|
+
return {};
|
|
1083
|
+
}
|
|
1084
|
+
/** `rawOutput.error` is the agent's own reason a tool failed. */
|
|
1085
|
+
/** The text a completed call produced, if this frame carries it. */
|
|
1086
|
+
function pickOutput(update) {
|
|
1087
|
+
const output = toolOutput(update);
|
|
1088
|
+
return output === undefined ? {} : { output };
|
|
1089
|
+
}
|
|
1090
|
+
export function toolError(update) {
|
|
1091
|
+
const raw = update['rawOutput'];
|
|
1092
|
+
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
1093
|
+
const error = raw.error;
|
|
1094
|
+
if (typeof error === 'string' && error.length > 0)
|
|
1095
|
+
return error;
|
|
1096
|
+
}
|
|
1097
|
+
return undefined;
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Add the input key the opencode TUI reads, using ACP's `kind` to decide which one.
|
|
1101
|
+
*
|
|
1102
|
+
* ACP declares `rawInput` as "any JSON value" and gives `kind` as the display category, so
|
|
1103
|
+
* an agent may name its file argument anything. The TUI, meanwhile, renders `read`/`edit`
|
|
1104
|
+
* rows from `input.path` and a shell row from `input.command`. Without this bridge an agent
|
|
1105
|
+
* that follows the spec shows up as an empty "Reading file…" / "Preparing edit…" row, which
|
|
1106
|
+
* is exactly what a `{file_path}`-shaped agent produced (measured on v2.2.0).
|
|
1107
|
+
*
|
|
1108
|
+
* Only ADDS keys; never overwrites what the agent sent, and never guesses without a `kind`.
|
|
1109
|
+
*/
|
|
1110
|
+
export function withClientInputKey(input, kind, title) {
|
|
1111
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
1112
|
+
return input;
|
|
1113
|
+
const record = input;
|
|
1114
|
+
const k = typeof kind === 'string' ? kind.toLowerCase() : '';
|
|
1115
|
+
const t = typeof title === 'string' ? title.toLowerCase() : '';
|
|
1116
|
+
const wantsPath = ['read', 'edit', 'delete', 'move', 'write'].includes(k) || ['read', 'edit'].includes(t);
|
|
1117
|
+
if (wantsPath && typeof record['path'] !== 'string') {
|
|
1118
|
+
const path = firstPathLike(record);
|
|
1119
|
+
if (path)
|
|
1120
|
+
return { ...record, path };
|
|
1121
|
+
}
|
|
1122
|
+
if ((k === 'execute' || t === 'bash' || t === 'shell') && typeof record['command'] !== 'string') {
|
|
1123
|
+
const command = firstCommand(record);
|
|
1124
|
+
if (command)
|
|
1125
|
+
return { ...record, command };
|
|
1126
|
+
}
|
|
1127
|
+
return input;
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* The value that can stand in for `input.command`, or undefined while it is still streaming.
|
|
1131
|
+
*
|
|
1132
|
+
* An agent may announce a tool with its arguments half-arrived — measured with
|
|
1133
|
+
* `dsh --profile <profile>`, whose first `tool_call` for a bash tool carried
|
|
1134
|
+
* `rawInput: {arguments: '{"'}` and filled the rest in on the following update. Taking the
|
|
1135
|
+
* first string there put `{"` on screen as the command, which is the `$ {` the owner saw.
|
|
1136
|
+
* So a value that is an unfinished JSON fragment (`{`, `[`, or a string that will not parse
|
|
1137
|
+
* as an object of arguments) is skipped rather than displayed.
|
|
1138
|
+
*/
|
|
1139
|
+
function firstCommand(record) {
|
|
1140
|
+
for (const value of Object.values(record)) {
|
|
1141
|
+
if (typeof value !== 'string' || value.trim().length === 0)
|
|
1142
|
+
continue;
|
|
1143
|
+
if (looksLikeJsonFragment(value))
|
|
1144
|
+
continue;
|
|
1145
|
+
return value;
|
|
1146
|
+
}
|
|
1147
|
+
return undefined;
|
|
1148
|
+
}
|
|
1149
|
+
/** A string that is (or may still become) a serialized argument object, not a command. */
|
|
1150
|
+
function looksLikeJsonFragment(value) {
|
|
1151
|
+
const head = value.trimStart();
|
|
1152
|
+
if (head.startsWith('{') || head.startsWith('['))
|
|
1153
|
+
return true;
|
|
1154
|
+
return false;
|
|
1155
|
+
}
|
|
1156
|
+
/** The first value that looks like a filesystem path, whatever key the agent used. */
|
|
1157
|
+
function firstPathLike(record) {
|
|
1158
|
+
for (const value of Object.values(record)) {
|
|
1159
|
+
if (typeof value === 'string' && /^(?:\/|~\/|\.{1,2}\/)/.test(value) && value.length > 1)
|
|
1160
|
+
return value;
|
|
1161
|
+
}
|
|
1162
|
+
return undefined;
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* ACP: a `tool_call`'s status "defaults to `pending`", while on a `tool_call_update` an
|
|
1166
|
+
* omitted field means "unchanged" (the caller keeps the previous state and never asks here).
|
|
1167
|
+
*/
|
|
1168
|
+
export function mapToolStatus(status) {
|
|
1169
|
+
switch (String(status ?? '').toLowerCase()) {
|
|
1170
|
+
case 'pending':
|
|
1171
|
+
return 'pending';
|
|
1172
|
+
case 'completed':
|
|
1173
|
+
case 'success':
|
|
1174
|
+
return 'completed';
|
|
1175
|
+
case 'failed':
|
|
1176
|
+
case 'error':
|
|
1177
|
+
return 'error';
|
|
1178
|
+
case 'in_progress':
|
|
1179
|
+
case 'running':
|
|
1180
|
+
return 'running';
|
|
1181
|
+
// Not a status ACP defines on the wire (tool calls are pending / in_progress /
|
|
1182
|
+
// completed / failed), but agents do send it, and the old default made it
|
|
1183
|
+
// 'running' — a spinner that never stops.
|
|
1184
|
+
case 'cancelled':
|
|
1185
|
+
case 'canceled':
|
|
1186
|
+
return 'error';
|
|
1187
|
+
// ACP's stated default for a `tool_call` that names no status.
|
|
1188
|
+
default:
|
|
1189
|
+
return 'pending';
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
/** Best-effort extraction of a tool's textual result from an ACP update. */
|
|
1193
|
+
/** The tool names agents use for a delegated agent, as measured (see `applyToolCall`). */
|
|
1194
|
+
const SUBAGENT_NAME = /^(subagents?|task|agent)$/i;
|
|
1195
|
+
/** `codex-acp` verb-prefixes its subagent activity instead of naming the tool. */
|
|
1196
|
+
const SUBAGENT_VERB_TITLE = /^(start|interact with|interrupt|complete) subagent\b/i;
|
|
1197
|
+
export function toolOutput(update) {
|
|
1198
|
+
// ★ Order and shape follow Zed, which is what the ecosystem is actually debugged
|
|
1199
|
+
// against (`crates/acp_thread/src/acp_thread.rs`):
|
|
1200
|
+
//
|
|
1201
|
+
// 1. the negotiated `_meta.terminal_output` dialect — the only place a *finished*
|
|
1202
|
+
// command's text arrives from agents that use it (`CLIENT_CAPABILITIES` announces
|
|
1203
|
+
// the key; the agent switches dialect on it), and
|
|
1204
|
+
// 2. `content`, because ACP defines it as the blocks shown to the user — Zed stops
|
|
1205
|
+
// looking at `rawOutput` entirely once any `content` exists, and
|
|
1206
|
+
// 3. `rawOutput` last, pretty-printed when it is a record. Zed's `raw_output_text`
|
|
1207
|
+
// does exactly that (`to_string_pretty`) instead of guessing at field names, so an
|
|
1208
|
+
// agent that only sends `{output, isError}` still renders something legible
|
|
1209
|
+
// without this bridge having to know any agent's private shape.
|
|
1210
|
+
const meta = update['_meta'];
|
|
1211
|
+
const negotiated = meta?.terminal_output?.data ?? meta?.terminal_output_delta?.data;
|
|
1212
|
+
if (typeof negotiated === 'string' && negotiated.length > 0)
|
|
1213
|
+
return negotiated;
|
|
1214
|
+
const content = update['content'];
|
|
1215
|
+
if (Array.isArray(content)) {
|
|
1216
|
+
const text = content
|
|
1217
|
+
.map((block) => {
|
|
1218
|
+
const b = block;
|
|
1219
|
+
if (typeof b.text === 'string')
|
|
1220
|
+
return b.text;
|
|
1221
|
+
if (b.content && typeof b.content.text === 'string')
|
|
1222
|
+
return b.content.text;
|
|
1223
|
+
return '';
|
|
1224
|
+
})
|
|
1225
|
+
.join('');
|
|
1226
|
+
if (text)
|
|
1227
|
+
return text;
|
|
1228
|
+
}
|
|
1229
|
+
const raw = update['rawOutput'];
|
|
1230
|
+
if (typeof raw === 'string')
|
|
1231
|
+
return raw;
|
|
1232
|
+
if (raw && typeof raw === 'object') {
|
|
1233
|
+
// Indented, not one line: the TUI collapses a card's output to a handful of rows, so
|
|
1234
|
+
// structure costs nothing on screen and a single 300-character line is unreadable.
|
|
1235
|
+
try {
|
|
1236
|
+
return JSON.stringify(raw, null, 2);
|
|
1237
|
+
}
|
|
1238
|
+
catch {
|
|
1239
|
+
return undefined;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
return undefined;
|
|
1243
|
+
}
|
|
1244
|
+
//# sourceMappingURL=events.js.map
|