opencode-ahp 0.1.5 → 0.1.6

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,386 @@
1
+ /**
2
+ * Event pump section (design §8): the opencode event → AHP action translation (streaming, tool-call lifecycle, permissions, usage, terminals, client-tool handoff) and pump control.
3
+ */
4
+
5
+ import { HostDispatch } from "./host-dispatch.js";
6
+ import { ActionType, ResponsePartKind, SessionInputRequestKind, ToolCallContributorKind, ToolCallStatus, ErrorResponsePart, SessionToolClientExecutionRequest, SessionToolConfirmationRequest } from "@microsoft/agent-host-protocol";
7
+ import { displayNameFor, pastTenseMessageFor, userMessage, FacadeEvent } from "./bridge.js";
8
+ import { EXTERNAL_REGISTER_GRACE_MS, errorMessage, mapToolResultContent } from "./host-util.js";
9
+
10
+ export class HostEvents extends HostDispatch {
11
+ /**
12
+ * Start the opencode event → AHP action pump. Idempotent. The pump is a
13
+ * single sequential async loop, so event handling and client-dispatch
14
+ * handling (same event loop) interleave without races on the per-turn
15
+ * join state.
16
+ */
17
+ // ── event pump ─────────────────────────────────────────────────────────
18
+ startEventPump(): void {
19
+ if (this.pumpController !== null) return;
20
+ const controller = new AbortController();
21
+ this.pumpController = controller;
22
+ void (async () => {
23
+ try {
24
+ for await (const event of this.opts.facade.events(controller.signal)) {
25
+ if (controller.signal.aborted) break;
26
+ await this.handleEvent(event);
27
+ }
28
+ } catch (err) {
29
+ this.log(`event pump failed: ${err instanceof Error ? err.stack ?? err.message : String(err)}`);
30
+ } finally {
31
+ if (this.pumpController === controller) this.pumpController = null;
32
+ }
33
+ })();
34
+ }
35
+
36
+ /** Stop the event pump (teardown). Idempotent. */
37
+ stopEventPump(): void {
38
+ this.pumpController?.abort();
39
+ this.pumpController = null;
40
+ }
41
+
42
+ // ── opencode event pump handlers ───────────────────────────────────────
43
+ private async handleEvent(ev: FacadeEvent): Promise<void> {
44
+ if (ev.type === "session.created") {
45
+ // Every live chat has its own opencode session, so a
46
+ // created event for an already-bound id is ours (a createChat
47
+ // backend) and never an external session.
48
+ if (this.sessions.has(ev.sessionID) || this.byOpencode.has(ev.sessionID)) return;
49
+ // Deferred registration: a concurrent `createSession` may still be
50
+ // resolving for this opencode session under a client-chosen channel;
51
+ // the grace + existence check avoids the double registration, and
52
+ // the delete+recreate remap in `handleCreateSession` heals the slow
53
+ // path.
54
+ const sessionID = ev.sessionID;
55
+ setTimeout(() => {
56
+ void this.registerExternalDeferred(sessionID).catch((err) =>
57
+ this.log(`external session registration failed: ${errorMessage(err)}`),
58
+ );
59
+ }, EXTERNAL_REGISTER_GRACE_MS);
60
+ return;
61
+ }
62
+
63
+ // The opencode session id joins to (record, chat) — every chat has
64
+ // its own backend session, and per-turn state lives on the chat.
65
+ // Only session.created registers sessions.
66
+ const binding = this.byOpencode.get(ev.sessionID);
67
+ if (binding === undefined) return;
68
+ const { rec, chat } = binding;
69
+ const chatURI = chat.uri;
70
+ switch (ev.type) {
71
+ case "session.deleted":
72
+ if (chat.uri === rec.defaultChatURI) {
73
+ this.removeRecord(rec);
74
+ } else {
75
+ // Peer-chat backend gone (deleted in the TUI or by another
76
+ // surface): drop the AHP chat only — the record and its other
77
+ // chats stay.
78
+ this.removeChat(rec, chat);
79
+ this.publish({ channel: rec.channel, action: { type: ActionType.SessionChatRemoved, chat: chat.uri } });
80
+ }
81
+ return;
82
+ case "session.renamed":
83
+ if (chat.uri === rec.defaultChatURI) {
84
+ this.publish({ channel: rec.channel, action: { type: ActionType.SessionTitleChanged, title: ev.title } });
85
+ } else {
86
+ // No chat-title session action exists; the chat summary carries
87
+ // the title (the chat store's own title stays original — same
88
+ // pre-existing behavior as the default chat's titleChanged).
89
+ this.publish({
90
+ channel: rec.channel,
91
+ action: { type: ActionType.SessionChatUpdated, chat: chat.uri, changes: { title: ev.title } },
92
+ });
93
+ }
94
+ return;
95
+ case "inbox.enqueued":
96
+ chat.lastInbox = { text: ev.text, delivery: ev.delivery };
97
+ return;
98
+ case "inbox.delivered":
99
+ // Steering consumption is handled at turn end (finishTurn).
100
+ return;
101
+ case "execution.started":
102
+ if (chat.currentTurnId !== null) return; // write-ahead already claimed the turn
103
+ // Orphan turn (an external TUI prompt, or a handoff this host did
104
+ // not initiate): start it with the last-seen inbox message.
105
+ this.startTurn(chat, chat.lastInbox !== null ? userMessage(chat.lastInbox.text) : userMessage(""));
106
+ return;
107
+ case "execution.succeeded":
108
+ if (chat.currentTurnId === null) return;
109
+ this.publish({
110
+ channel: chatURI,
111
+ action: { type: ActionType.ChatTurnComplete, turnId: chat.currentTurnId, duration: this.turnDuration(chat) },
112
+ });
113
+ await this.finishTurn(chat);
114
+ return;
115
+ case "execution.failed":
116
+ if (chat.currentTurnId === null) return;
117
+ const part: ErrorResponsePart = {
118
+ kind: ResponsePartKind.Error,
119
+ error: { errorType: ev.error.type, message: ev.error.message },
120
+ };
121
+ this.publish({
122
+ channel: chatURI,
123
+ action: { type: ActionType.ChatError, turnId: chat.currentTurnId, duration: this.turnDuration(chat), part },
124
+ });
125
+ await this.finishTurn(chat);
126
+ return;
127
+ case "execution.interrupted":
128
+ // Skipped when the client's own `chat/turnCancelled` echo already
129
+ // finalized the turn (currentTurnId is null).
130
+ if (chat.currentTurnId === null) return;
131
+ this.publish({
132
+ channel: chatURI,
133
+ action: { type: ActionType.ChatTurnCancelled, turnId: chat.currentTurnId, duration: this.turnDuration(chat) },
134
+ });
135
+ await this.finishTurn(chat);
136
+ return;
137
+ case "step.started":
138
+ chat.turnModelRef = `${ev.model.providerID}/${ev.model.modelID}`;
139
+ return;
140
+ case "text.delta":
141
+ case "reasoning.delta": {
142
+ if (chat.currentTurnId === null) return;
143
+ const kind = ev.type === "text.delta" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
144
+ const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
145
+ const first = !chat.parts.has(key);
146
+ chat.parts.add(key);
147
+ const partId = `part-${key}`;
148
+ if (first) {
149
+ // Lazily emit the part on the first delta; it carries the
150
+ // initial content.
151
+ this.publish({
152
+ channel: chatURI,
153
+ action: {
154
+ type: ActionType.ChatResponsePart,
155
+ turnId: chat.currentTurnId,
156
+ part: { kind, id: partId, content: ev.delta },
157
+ },
158
+ });
159
+ } else {
160
+ this.publish({
161
+ channel: chatURI,
162
+ action:
163
+ kind === ResponsePartKind.Markdown
164
+ ? { type: ActionType.ChatDelta, turnId: chat.currentTurnId, partId, content: ev.delta }
165
+ : { type: ActionType.ChatReasoning, turnId: chat.currentTurnId, partId, content: ev.delta },
166
+ });
167
+ }
168
+ return;
169
+ }
170
+ case "text.ended":
171
+ case "reasoning.ended": {
172
+ if (chat.currentTurnId === null) return;
173
+ // Fallback for non-streaming providers that emit only the final
174
+ // text: if no delta opened the part, emit it now with the full text.
175
+ const kind = ev.type === "text.ended" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
176
+ const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
177
+ if (!chat.parts.has(key)) {
178
+ chat.parts.add(key);
179
+ this.publish({
180
+ channel: chatURI,
181
+ action: {
182
+ type: ActionType.ChatResponsePart,
183
+ turnId: chat.currentTurnId,
184
+ part: { kind, id: `part-${key}`, content: ev.text },
185
+ },
186
+ });
187
+ }
188
+ return;
189
+ }
190
+ case "tool.input.started": {
191
+ if (chat.currentTurnId === null) {
192
+ this.log(`tool.input.started outside a turn (session ${chat.sessionID}, tool ${ev.name}); ignored`);
193
+ return;
194
+ }
195
+ chat.toolName.set(ev.id, ev.name);
196
+ // When the session's active clients provide
197
+ // this tool, the call is client-executed — the client
198
+ // `contributor` must be established at start (the official
199
+ // reducer ignores a late one), and the call is tracked for the
200
+ // `execute` bridge + the client's dispatchable actions.
201
+ // (Active clients are session-level; the chat tracks the call.)
202
+ const clientTool = this.clientToolContributor(rec, ev.name);
203
+ if (clientTool !== null) {
204
+ chat.clientToolCalls.set(ev.id, { clientId: clientTool, turnId: chat.currentTurnId });
205
+ }
206
+ this.publish({
207
+ channel: chatURI,
208
+ action: {
209
+ type: ActionType.ChatToolCallStart,
210
+ turnId: chat.currentTurnId,
211
+ toolCallId: ev.id,
212
+ toolName: ev.name,
213
+ displayName: displayNameFor(ev.name),
214
+ ...(clientTool !== null
215
+ ? { contributor: { kind: ToolCallContributorKind.Client, clientId: clientTool } }
216
+ : {}),
217
+ },
218
+ });
219
+ return;
220
+ }
221
+ case "tool.input.ended": {
222
+ chat.toolInput.set(ev.id, ev.text);
223
+ // For file-mutating tools, capture the pre-edit file
224
+ // content now (the event fires before execution — the last safe
225
+ // point). Awaited in the sequential pump so the capture is
226
+ // complete before `execution.*` can end the turn.
227
+ if (this.opts.changesets) await this.captureTurnBefore(chat, ev.id, ev.text);
228
+ // A foreground `shell`-tool call opens its
229
+ // synthetic terminal channel here — the command line is only
230
+ // known at input.ended.
231
+ this.openTerminalForToolCall(rec, chat, ev.id, ev.text);
232
+ // A client-executed call clears its
233
+ // confirmation gate here (no opencode permission can fire for
234
+ // it) — ready straight to running, then surface the execution
235
+ // request so the owning client picks up the work.
236
+ if (chat.clientToolCalls.has(ev.id)) {
237
+ this.ensureToolReady(chat, ev.id, false);
238
+ const invocation = chat.clientToolCalls.get(ev.id);
239
+ const running = this.toolCallState(chat, ev.id);
240
+ if (invocation !== undefined && running !== null && running.status === ToolCallStatus.Running && chat.currentTurnId !== null) {
241
+ const request: SessionToolClientExecutionRequest = {
242
+ id: ev.id,
243
+ chat: chatURI,
244
+ kind: SessionInputRequestKind.ToolClientExecution,
245
+ turnId: chat.currentTurnId,
246
+ clientId: invocation.clientId,
247
+ toolCall: running,
248
+ };
249
+ this.publish({
250
+ channel: rec.channel,
251
+ action: { type: ActionType.SessionInputNeededSet, request },
252
+ });
253
+ }
254
+ }
255
+ return;
256
+ }
257
+ case "tool.progress":
258
+ // First sign the tool is actually running (opencode auto-approved):
259
+ // finalize the tool call as running.
260
+ this.ensureToolReady(chat, ev.id, false);
261
+ return;
262
+ case "tool.success": {
263
+ // The synthetic terminal completes on the
264
+ // tool's terminal event (before the turn guard — a command that
265
+ // finishes after its turn was torn down still exits its
266
+ // terminal; no-op when the call never opened one).
267
+ this.finishTerminal(chat, ev.id, { ok: true, content: ev.content });
268
+ if (chat.currentTurnId === null) return;
269
+ this.ensureToolReady(chat, ev.id, false);
270
+ if (this.toolCallTerminal(chat, ev.id)) {
271
+ // e.g. denied → already cancelled, or a client-executed call
272
+ // the client already completed: no echo, but the tracking
273
+ // (including the client-tool record) must still be cleared.
274
+ this.clearToolTracking(chat, ev.id);
275
+ return;
276
+ }
277
+ const name = chat.toolName.get(ev.id) ?? "tool";
278
+ const input = chat.toolInput.get(ev.id);
279
+ this.publish({
280
+ channel: chatURI,
281
+ action: {
282
+ type: ActionType.ChatToolCallComplete,
283
+ turnId: chat.currentTurnId,
284
+ toolCallId: ev.id,
285
+ result: {
286
+ success: true,
287
+ pastTenseMessage: pastTenseMessageFor(name, input),
288
+ content: mapToolResultContent(ev.content),
289
+ },
290
+ },
291
+ });
292
+ this.clearToolTracking(chat, ev.id);
293
+ return;
294
+ }
295
+ case "tool.failed": {
296
+ this.finishTerminal(chat, ev.id, { ok: false, message: ev.error.message });
297
+ if (chat.currentTurnId === null) return;
298
+ this.ensureToolReady(chat, ev.id, false);
299
+ if (this.toolCallTerminal(chat, ev.id)) {
300
+ // Already terminal (client-executed call completed by the
301
+ // client, or a call cancelled upstream) — clear the tracking.
302
+ this.clearToolTracking(chat, ev.id);
303
+ return;
304
+ }
305
+ const name = chat.toolName.get(ev.id) ?? "tool";
306
+ const input = chat.toolInput.get(ev.id);
307
+ this.publish({
308
+ channel: chatURI,
309
+ action: {
310
+ type: ActionType.ChatToolCallComplete,
311
+ turnId: chat.currentTurnId,
312
+ toolCallId: ev.id,
313
+ result: {
314
+ success: false,
315
+ pastTenseMessage: pastTenseMessageFor(name, input),
316
+ error: { message: ev.error.message },
317
+ },
318
+ },
319
+ });
320
+ this.clearToolTracking(chat, ev.id);
321
+ return;
322
+ }
323
+ case "usage.updated":
324
+ // Session-cumulative tokens; the chat reducer replaces the turn's
325
+ // usage, so the latest cumulative values are the turn's view.
326
+ if (chat.currentTurnId === null) return;
327
+ this.publish({
328
+ channel: chatURI,
329
+ action: {
330
+ type: ActionType.ChatUsage,
331
+ turnId: chat.currentTurnId,
332
+ usage: {
333
+ inputTokens: ev.tokens.input,
334
+ outputTokens: ev.tokens.output,
335
+ cacheReadTokens: ev.tokens.cache.read,
336
+ ...(chat.turnModelRef !== null ? { model: chat.turnModelRef } : {}),
337
+ },
338
+ },
339
+ });
340
+ return;
341
+ case "permission.asked":
342
+ // Only tool-sourced permissions map to a tool confirmation;
343
+ // anything else has no AHP counterpart (gap).
344
+ if (ev.source === undefined) {
345
+ this.log(`ignoring non-tool permission.asked ${ev.id} (action: ${ev.action})`);
346
+ return;
347
+ }
348
+ const toolCallId = ev.source.id;
349
+ chat.permissionForTool.set(toolCallId, ev.id);
350
+ chat.toolForPermission.set(ev.id, toolCallId);
351
+ this.ensureToolReady(chat, toolCallId, true);
352
+ const pending = this.pendingToolCall(chat, toolCallId);
353
+ if (pending !== null && chat.currentTurnId !== null) {
354
+ const request: SessionToolConfirmationRequest = {
355
+ id: toolCallId,
356
+ chat: chatURI,
357
+ kind: SessionInputRequestKind.ToolConfirmation,
358
+ turnId: chat.currentTurnId,
359
+ toolCall: pending,
360
+ };
361
+ this.publish({
362
+ channel: rec.channel,
363
+ action: { type: ActionType.SessionInputNeededSet, request },
364
+ });
365
+ }
366
+ return;
367
+ case "permission.replied": {
368
+ const toolCallId = chat.toolForPermission.get(ev.requestID);
369
+ chat.toolForPermission.delete(ev.requestID);
370
+ if (toolCallId !== undefined) {
371
+ chat.permissionForTool.delete(toolCallId);
372
+ // Safety net: the client's `chat/toolCallConfirmed` normally
373
+ // removes the input request first; this covers the reply
374
+ // arriving without (or before) the echo.
375
+ this.publish({
376
+ channel: rec.channel,
377
+ action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
378
+ });
379
+ }
380
+ return;
381
+ }
382
+ default:
383
+ return;
384
+ }
385
+ }
386
+ }