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.
- package/README.md +43 -24
- package/options.example.jsonc +15 -3
- package/package.json +1 -1
- package/src/bridge.ts +221 -76
- package/src/channels.ts +10 -4
- package/src/host-base.ts +335 -0
- package/src/host-changesets.ts +381 -0
- package/src/host-chats.ts +300 -0
- package/src/host-client-tools.ts +205 -0
- package/src/host-dispatch.ts +593 -0
- package/src/host-errors.ts +29 -0
- package/src/host-events.ts +386 -0
- package/src/host-rpc.ts +435 -0
- package/src/host-sessions.ts +558 -0
- package/src/host-terminals.ts +654 -0
- package/src/host-turns.ts +82 -0
- package/src/host-types.ts +225 -0
- package/src/host-util.ts +194 -0
- package/src/host.ts +12 -3741
- package/src/index.ts +122 -9
- package/src/options.ts +11 -0
- package/src/state.ts +11 -0
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dispatch section (design §9): `dispatchAction` routing for the client-dispatchable actions (turns, steering/queue, tool confirmations, renames, active-client echoes) with write-ahead rejections.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { HostSessions } from "./host-sessions.js";
|
|
6
|
+
import { ActionType, SessionInputRequestKind, SessionStatus, ToolCallStatus, isClientDispatchable, ActionOrigin, ChatToolCallCompleteAction, ChatToolCallConfirmedAction, ChatToolCallContentChangedAction, ChatToolCallResultConfirmedAction, ChatTurnCancelledAction, ChatTurnStartedAction, ChangesetFilesReviewChangedAction, Message, SessionActiveClient, SessionToolConfirmationRequest, StateAction, ToolCallResult } from "@microsoft/agent-host-protocol";
|
|
7
|
+
import { FacadeDelivery } from "./bridge.js";
|
|
8
|
+
import { normalizeToolDefinitions } from "./client-tools.js";
|
|
9
|
+
import { channelKind, parseChangesetChannel } from "./channels.js";
|
|
10
|
+
import { isRecord } from "./options.js";
|
|
11
|
+
import { RpcMessage, ChatRuntime, SessionRecord } from "./host-types.js";
|
|
12
|
+
import { errorMessage, normalizeToolCallResult, clientResultToFacade } from "./host-util.js";
|
|
13
|
+
|
|
14
|
+
export class HostDispatch extends HostSessions {
|
|
15
|
+
/**
|
|
16
|
+
* `dispatchAction` is a notification — the response is the `action`
|
|
17
|
+
* notification stream itself. The host routes the client-dispatchable
|
|
18
|
+
* actions VS Code sends; everything else is acknowledged with a
|
|
19
|
+
* rejection on that stream.
|
|
20
|
+
*/
|
|
21
|
+
// ── client-dispatchable actions ──────────────────────────────
|
|
22
|
+
protected async handleDispatchAction(socketId: number, msg: RpcMessage): Promise<void> {
|
|
23
|
+
const params = isRecord(msg.params) ? msg.params : {};
|
|
24
|
+
const channel = params["channel"];
|
|
25
|
+
const clientSeq = params["clientSeq"];
|
|
26
|
+
const action = params["action"];
|
|
27
|
+
if (
|
|
28
|
+
typeof channel !== "string" ||
|
|
29
|
+
channel.length === 0 ||
|
|
30
|
+
!Number.isInteger(clientSeq) ||
|
|
31
|
+
!isRecord(action) ||
|
|
32
|
+
typeof action["type"] !== "string"
|
|
33
|
+
) {
|
|
34
|
+
this.log(`malformed dispatchAction on socket ${socketId} (dropped)`);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const socket = this.sockets.get(socketId);
|
|
39
|
+
const clientId = socket?.clientId ?? null;
|
|
40
|
+
const origin: ActionOrigin | undefined =
|
|
41
|
+
clientId !== null ? { clientId, clientSeq: clientSeq as number } : undefined;
|
|
42
|
+
|
|
43
|
+
const stateAction = action as unknown as StateAction;
|
|
44
|
+
const rejectionReason = this.dispatchRejectionReason(channel, stateAction, clientId);
|
|
45
|
+
if (rejectionReason !== null) {
|
|
46
|
+
this.echo(channel, stateAction, origin, rejectionReason);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// kindOf, not channelKind: a live pty terminal's client-chosen URI
|
|
51
|
+
// classifies "unknown" by prefix alone.
|
|
52
|
+
const kind = this.kindOf(channel);
|
|
53
|
+
if (kind === "changeset") {
|
|
54
|
+
// The only client-dispatchable changeset action is the per-file
|
|
55
|
+
// review toggle — echo it through the official reducer.
|
|
56
|
+
if (stateAction.type === ActionType.ChangesetFilesReviewChanged) {
|
|
57
|
+
this.dispatchChangesetFilesReviewChanged(channel, stateAction, origin);
|
|
58
|
+
} else {
|
|
59
|
+
this.echo(channel, stateAction, origin, `unsupported action on changeset channel: ${String(action.type)}`);
|
|
60
|
+
}
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (kind === "terminal") {
|
|
64
|
+
const t = this.terminals.get(channel);
|
|
65
|
+
if (t === undefined) {
|
|
66
|
+
// A synthetic channel whose record is gone (the chat was
|
|
67
|
+
// removed). A disposed pty terminal's client-chosen URI never
|
|
68
|
+
// reaches here — without its record it classifies "unknown" in
|
|
69
|
+
// the pre-check above.
|
|
70
|
+
this.echo(channel, stateAction, origin, `no such terminal: ${channel}`);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (t.kind === "synthetic") {
|
|
74
|
+
// The synthetic terminals are read-only
|
|
75
|
+
// renderings of shell-tool calls — every client-dispatchable
|
|
76
|
+
// action (`input`, `resized`, `claimed`, `titleChanged`,
|
|
77
|
+
// `cleared`) has no pty to act on, so each gets an explicit
|
|
78
|
+
// rejection (write-ahead clients roll back on the reason).
|
|
79
|
+
this.echo(
|
|
80
|
+
channel,
|
|
81
|
+
stateAction,
|
|
82
|
+
origin,
|
|
83
|
+
"read-only terminal: this host's shell-tool terminals render tool calls and accept no input, resize, claim, title, or clear",
|
|
84
|
+
);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
// A live pty terminal: input/resize drive the process, claim/
|
|
88
|
+
// title/clear apply through the official reducer.
|
|
89
|
+
this.dispatchPtyTerminal(t, stateAction, origin);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (kind !== "session" && kind !== "chat") {
|
|
93
|
+
this.echo(channel, stateAction, origin, `unsupported action on ${channelKind(channel)} channel: ${String(action.type)}`);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const rec = this.byChannel.get(channel);
|
|
97
|
+
if (rec === undefined) {
|
|
98
|
+
this.echo(
|
|
99
|
+
channel,
|
|
100
|
+
stateAction,
|
|
101
|
+
origin,
|
|
102
|
+
kind === "chat" ? `no such chat: ${channel}` : `no such session: ${channel}`,
|
|
103
|
+
);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (kind === "chat" && !rec.chats.has(channel)) {
|
|
107
|
+
this.echo(channel, stateAction, origin, `no such chat: ${channel}`);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
// Chat actions run against the owning chat runtime;
|
|
111
|
+
// a chat action on a session channel is rejected (a session no
|
|
112
|
+
// longer identifies a single chat once multi-chat is on).
|
|
113
|
+
const chat = rec.chats.get(channel);
|
|
114
|
+
const noChat = () => this.echo(channel, stateAction, origin, `chat actions require a chat channel: ${channel}`);
|
|
115
|
+
|
|
116
|
+
// From here on every branch either echoes (accepted or rejected).
|
|
117
|
+
switch (stateAction.type) {
|
|
118
|
+
case ActionType.ChatTurnStarted:
|
|
119
|
+
if (chat === undefined) { noChat(); return; }
|
|
120
|
+
await this.dispatchTurnStarted(chat, stateAction, origin);
|
|
121
|
+
return;
|
|
122
|
+
case ActionType.ChatPendingMessageSet:
|
|
123
|
+
if (chat === undefined) { noChat(); return; }
|
|
124
|
+
await this.dispatchPendingMessageSet(chat, stateAction, origin);
|
|
125
|
+
return;
|
|
126
|
+
case ActionType.ChatToolCallConfirmed:
|
|
127
|
+
if (chat === undefined) { noChat(); return; }
|
|
128
|
+
await this.dispatchToolCallConfirmed(chat, stateAction, origin);
|
|
129
|
+
return;
|
|
130
|
+
case ActionType.ChatToolCallComplete:
|
|
131
|
+
if (chat === undefined) { noChat(); return; }
|
|
132
|
+
await this.dispatchToolCallComplete(chat, stateAction, origin);
|
|
133
|
+
return;
|
|
134
|
+
case ActionType.ChatToolCallContentChanged:
|
|
135
|
+
if (chat === undefined) { noChat(); return; }
|
|
136
|
+
this.dispatchToolCallContentChanged(chat, stateAction, origin);
|
|
137
|
+
return;
|
|
138
|
+
case ActionType.ChatToolCallResultConfirmed:
|
|
139
|
+
if (chat === undefined) { noChat(); return; }
|
|
140
|
+
this.dispatchToolCallResultConfirmed(chat, stateAction, origin);
|
|
141
|
+
return;
|
|
142
|
+
case ActionType.ChatTurnCancelled:
|
|
143
|
+
if (chat === undefined) { noChat(); return; }
|
|
144
|
+
await this.dispatchTurnCancelled(chat, stateAction, origin);
|
|
145
|
+
return;
|
|
146
|
+
case ActionType.SessionTitleChanged:
|
|
147
|
+
await this.dispatchTitleChanged(rec, stateAction, origin);
|
|
148
|
+
return;
|
|
149
|
+
case ActionType.SessionActiveClientSet:
|
|
150
|
+
this.dispatchActiveClientSet(rec, stateAction, origin, clientId);
|
|
151
|
+
return;
|
|
152
|
+
case ActionType.SessionActiveClientRemoved:
|
|
153
|
+
this.dispatchActiveClientRemoved(rec, stateAction, origin, clientId);
|
|
154
|
+
return;
|
|
155
|
+
case ActionType.ChatPendingMessageRemoved:
|
|
156
|
+
// Honest gap: the opencode plugin surface has no inbox cancel —
|
|
157
|
+
// a pending (steer/queue) message cannot be withdrawn once sent.
|
|
158
|
+
this.echo(channel, stateAction, origin, "cannot remove a pending message: opencode has no inbox cancel");
|
|
159
|
+
return;
|
|
160
|
+
case ActionType.ChatDraftChanged:
|
|
161
|
+
case ActionType.ChatIsReadChanged:
|
|
162
|
+
case ActionType.ChatIsArchivedChanged:
|
|
163
|
+
case ActionType.SessionIsReadChanged:
|
|
164
|
+
case ActionType.SessionIsArchivedChanged:
|
|
165
|
+
this.echo(channel, stateAction, origin);
|
|
166
|
+
return;
|
|
167
|
+
default:
|
|
168
|
+
this.echo(channel, stateAction, origin, `unsupported action: ${String(stateAction.type)}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Shared pre-checks for a dispatched action; null when the action may
|
|
174
|
+
* proceed to per-type handling.
|
|
175
|
+
*/
|
|
176
|
+
private dispatchRejectionReason(channel: string, action: StateAction, clientId: string | null): string | null {
|
|
177
|
+
// kindOf: a live pty terminal's client-chosen URI is a known channel.
|
|
178
|
+
if (this.kindOf(channel) === "unknown") return `unknown channel: ${channel}`;
|
|
179
|
+
let dispatchable: boolean;
|
|
180
|
+
try {
|
|
181
|
+
dispatchable = isClientDispatchable(action as Parameters<typeof isClientDispatchable>[0]);
|
|
182
|
+
} catch {
|
|
183
|
+
dispatchable = false;
|
|
184
|
+
}
|
|
185
|
+
if (!dispatchable) return `action ${String(action.type)} is not client-dispatchable`;
|
|
186
|
+
if (clientId === null) return "client is not initialized";
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// `echo` (accepted echoes + write-ahead rejections) lives on HostBase
|
|
191
|
+
// so the terminal section below this one can reuse it.
|
|
192
|
+
|
|
193
|
+
private async dispatchTurnStarted(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
194
|
+
const chatURI = chat.uri;
|
|
195
|
+
const a = action as ChatTurnStartedAction;
|
|
196
|
+
const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
|
|
197
|
+
const message =
|
|
198
|
+
isRecord(a.message) && typeof a.message["text"] === "string"
|
|
199
|
+
? (a.message as unknown as Message)
|
|
200
|
+
: null;
|
|
201
|
+
if (turnId === null || message === null) {
|
|
202
|
+
this.echo(chatURI, action, origin, "invalid chat/turnStarted params");
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
// `startedAt` is required on the wire (the reducer uses it for the
|
|
206
|
+
// chat's `modifiedAt`); fall back to the host clock when the client
|
|
207
|
+
// did not supply a parseable one.
|
|
208
|
+
const normalized: ChatTurnStartedAction =
|
|
209
|
+
typeof a.startedAt === "string" && !Number.isNaN(Date.parse(a.startedAt))
|
|
210
|
+
? a
|
|
211
|
+
: { ...a, startedAt: new Date().toISOString() };
|
|
212
|
+
if (chat.chatStore.state.activeTurn !== undefined) {
|
|
213
|
+
this.echo(
|
|
214
|
+
chatURI,
|
|
215
|
+
action,
|
|
216
|
+
origin,
|
|
217
|
+
"a turn is already active; follow-up messages go via chat/pendingMessageSet",
|
|
218
|
+
);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Apply the message's model/agent selection to THIS chat's opencode
|
|
223
|
+
// session before the prompt (per-chat isolation).
|
|
224
|
+
const selectionError = await this.applyMessageSelection(chat, message);
|
|
225
|
+
if (selectionError !== null) {
|
|
226
|
+
this.echo(chatURI, action, origin, `failed to apply model/agent selection: ${selectionError}`);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Write-ahead: claim the turn BEFORE the prompt so the
|
|
231
|
+
// `session.execution.started` event joins it even when it races the
|
|
232
|
+
// prompt's resolve; revert on failure.
|
|
233
|
+
chat.currentTurnId = turnId;
|
|
234
|
+
chat.turnStartedAt = Date.now();
|
|
235
|
+
try {
|
|
236
|
+
await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text });
|
|
237
|
+
} catch (err) {
|
|
238
|
+
chat.currentTurnId = null;
|
|
239
|
+
chat.turnStartedAt = null;
|
|
240
|
+
this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
this.echo(chatURI, normalized, origin);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
private async dispatchPendingMessageSet(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
247
|
+
const chatURI = chat.uri;
|
|
248
|
+
const a = action as { kind?: unknown; id?: unknown; message?: unknown };
|
|
249
|
+
const kind = a.kind === "steering" || a.kind === "queued" ? a.kind : null;
|
|
250
|
+
const id = typeof a.id === "string" && a.id.length > 0 ? a.id : null;
|
|
251
|
+
const message =
|
|
252
|
+
isRecord(a.message) && typeof a.message["text"] === "string"
|
|
253
|
+
? (a.message as unknown as Message)
|
|
254
|
+
: null;
|
|
255
|
+
if (kind === null || id === null || message === null) {
|
|
256
|
+
this.echo(chatURI, action, origin, "invalid chat/pendingMessageSet params");
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const hasActiveTurn = chat.chatStore.state.activeTurn !== undefined;
|
|
260
|
+
// steer → delivery "steer" (only while a turn is active); queued →
|
|
261
|
+
// delivery "queue"; a steering message with no active turn falls back
|
|
262
|
+
// to a plain prompt (it becomes the next turn).
|
|
263
|
+
const delivery: FacadeDelivery | undefined = hasActiveTurn
|
|
264
|
+
? kind === "steering"
|
|
265
|
+
? "steer"
|
|
266
|
+
: "queue"
|
|
267
|
+
: undefined;
|
|
268
|
+
try {
|
|
269
|
+
await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text, delivery });
|
|
270
|
+
} catch (err) {
|
|
271
|
+
this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (hasActiveTurn) {
|
|
275
|
+
this.echo(chatURI, action, origin);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
// No active turn: the message starts a turn right now. Echo the
|
|
279
|
+
// pending-message first, then a host-minted turnStarted carrying
|
|
280
|
+
// `queuedMessageId` — the reducer dequeues it.
|
|
281
|
+
this.echo(chatURI, action, origin);
|
|
282
|
+
const turnId = this.mintTurnId();
|
|
283
|
+
chat.currentTurnId = turnId;
|
|
284
|
+
chat.turnStartedAt = Date.now();
|
|
285
|
+
this.publish({
|
|
286
|
+
channel: chatURI,
|
|
287
|
+
action: {
|
|
288
|
+
type: ActionType.ChatTurnStarted,
|
|
289
|
+
turnId,
|
|
290
|
+
startedAt: new Date().toISOString(),
|
|
291
|
+
message,
|
|
292
|
+
queuedMessageId: id,
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
private async dispatchToolCallConfirmed(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
298
|
+
const chatURI = chat.uri;
|
|
299
|
+
const rec = this.byChannel.get(chatURI)!;
|
|
300
|
+
const a = action as ChatToolCallConfirmedAction;
|
|
301
|
+
const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
|
|
302
|
+
if (toolCallId === null) {
|
|
303
|
+
this.echo(chatURI, action, origin, "invalid chat/toolCallConfirmed params");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
const permissionID = chat.permissionForTool.get(toolCallId);
|
|
307
|
+
if (permissionID === undefined) {
|
|
308
|
+
this.echo(chatURI, action, origin, `no pending permission for tool call ${toolCallId}`);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
try {
|
|
312
|
+
await this.opts.facade.replyPermission({
|
|
313
|
+
sessionID: chat.sessionID,
|
|
314
|
+
requestID: permissionID,
|
|
315
|
+
decision: a.approved === true ? "once" : "reject",
|
|
316
|
+
});
|
|
317
|
+
} catch (err) {
|
|
318
|
+
this.echo(chatURI, action, origin, `permission reply failed: ${errorMessage(err)}`);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
// Echo the confirmation (reducer → running/cancelled), then clear the
|
|
322
|
+
// session-level input request. The `permission.replied` event is a
|
|
323
|
+
// safety net (its tracking is already gone → no-op).
|
|
324
|
+
this.echo(chatURI, action, origin);
|
|
325
|
+
this.publish({
|
|
326
|
+
channel: rec.channel,
|
|
327
|
+
action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
|
|
328
|
+
});
|
|
329
|
+
chat.permissionForTool.delete(toolCallId);
|
|
330
|
+
chat.toolForPermission.delete(permissionID);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* `chat/toolCallComplete` (client-dispatchable): the owning client
|
|
335
|
+
* finished executing a delegated tool call. Only valid for
|
|
336
|
+
* client-executed calls (the host emits its own complete for
|
|
337
|
+
* server-executed ones); the dispatching client must be the
|
|
338
|
+
* contributor. Echoes the action (reducer: running → completed, or
|
|
339
|
+
* → pending-result-confirmation when `requiresResultConfirmation`),
|
|
340
|
+
* clears the execution input request, and settles the opencode-side
|
|
341
|
+
* waiter with the client's result.
|
|
342
|
+
*/
|
|
343
|
+
// ── client-executed tool calls ───────────────────
|
|
344
|
+
private async dispatchToolCallComplete(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
345
|
+
const chatURI = chat.uri;
|
|
346
|
+
const rec = this.byChannel.get(chatURI)!;
|
|
347
|
+
const a = action as ChatToolCallCompleteAction;
|
|
348
|
+
const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
|
|
349
|
+
const invocation = toolCallId !== null ? chat.clientToolCalls.get(toolCallId) : undefined;
|
|
350
|
+
if (toolCallId === null || invocation === undefined) {
|
|
351
|
+
this.echo(chatURI, action, origin, `tool call ${toolCallId ?? "?"} is not a client-executed call`);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
if (origin !== undefined && invocation.clientId !== origin.clientId) {
|
|
355
|
+
this.echo(chatURI, action, origin, `only the contributing client (${invocation.clientId}) may complete this call`);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
const result = normalizeToolCallResult(a.result);
|
|
359
|
+
if (result === null) {
|
|
360
|
+
this.echo(chatURI, action, origin, "invalid chat/toolCallComplete params (result.success must be a boolean)");
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const status = this.toolCallState(chat, toolCallId)?.status;
|
|
364
|
+
if (status !== ToolCallStatus.Running && status !== ToolCallStatus.PendingConfirmation) {
|
|
365
|
+
this.echo(chatURI, action, origin, `tool call ${toolCallId} is not ready to complete (status ${status ?? "absent"})`);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const requiresConfirmation = a.requiresResultConfirmation === true;
|
|
369
|
+
// Echo first: the reducer moves running → completed (or
|
|
370
|
+
// pending-result-confirmation); the settle below must observe the
|
|
371
|
+
// new state for the confirmation input request.
|
|
372
|
+
this.echo(chatURI, action, origin);
|
|
373
|
+
if (requiresConfirmation) {
|
|
374
|
+
// Hold the client's result until the approval reply; surface the
|
|
375
|
+
// user-facing confirmation on the session channel (this variant,
|
|
376
|
+
// unlike the execution request, raises SessionStatus.InputNeeded).
|
|
377
|
+
invocation.pendingResult = result;
|
|
378
|
+
const pending = this.pendingToolCall(chat, toolCallId);
|
|
379
|
+
if (pending !== null && chat.currentTurnId !== null) {
|
|
380
|
+
this.publish({
|
|
381
|
+
channel: rec.channel,
|
|
382
|
+
action: {
|
|
383
|
+
type: ActionType.SessionInputNeededSet,
|
|
384
|
+
request: {
|
|
385
|
+
id: toolCallId,
|
|
386
|
+
chat: chatURI,
|
|
387
|
+
kind: SessionInputRequestKind.ToolConfirmation,
|
|
388
|
+
turnId: chat.currentTurnId,
|
|
389
|
+
toolCall: pending,
|
|
390
|
+
} satisfies SessionToolConfirmationRequest,
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
} else {
|
|
395
|
+
this.publish({
|
|
396
|
+
channel: rec.channel,
|
|
397
|
+
action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
|
|
398
|
+
});
|
|
399
|
+
this.settleClientTool(invocation, clientResultToFacade(result));
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* `chat/toolCallContentChanged` (client-dispatchable): the owning
|
|
405
|
+
* client streams partial content while executing (the reducer
|
|
406
|
+
* replaces the running call's `content`). Echo-only — opencode needs
|
|
407
|
+
* no counterpart; the spec says the server SHOULD reject dispatches
|
|
408
|
+
* from a client that is not the contributor.
|
|
409
|
+
*/
|
|
410
|
+
private dispatchToolCallContentChanged(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): void {
|
|
411
|
+
const chatURI = chat.uri;
|
|
412
|
+
const a = action as ChatToolCallContentChangedAction;
|
|
413
|
+
const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
|
|
414
|
+
const invocation = toolCallId !== null ? chat.clientToolCalls.get(toolCallId) : undefined;
|
|
415
|
+
if (toolCallId === null || invocation === undefined) {
|
|
416
|
+
this.echo(chatURI, action, origin, `tool call ${toolCallId ?? "?"} is not a client-executed call`);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
if (origin !== undefined && invocation.clientId !== origin.clientId) {
|
|
420
|
+
this.echo(chatURI, action, origin, `only the contributing client (${invocation.clientId}) may stream content for this call`);
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
if (!Array.isArray(a.content)) {
|
|
424
|
+
this.echo(chatURI, action, origin, "invalid chat/toolCallContentChanged params (content must be an array)");
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
if (this.toolCallState(chat, toolCallId)?.status !== ToolCallStatus.Running) {
|
|
428
|
+
this.echo(chatURI, action, origin, `tool call ${toolCallId} is not running`);
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
this.echo(chatURI, action, origin);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* `chat/toolCallResultConfirmed` (client-dispatchable): the user
|
|
436
|
+
* approved or denied a client tool's result after a
|
|
437
|
+
* `requiresResultConfirmation` completion. Echoes (reducer:
|
|
438
|
+
* pending-result-confirmation → completed / cancelled with reason
|
|
439
|
+
* `result-denied`), clears the confirmation input request, and
|
|
440
|
+
* settles the opencode-side waiter (approved → the held client
|
|
441
|
+
* result; denied → a Tool.Error the model sees).
|
|
442
|
+
*/
|
|
443
|
+
private dispatchToolCallResultConfirmed(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): void {
|
|
444
|
+
const chatURI = chat.uri;
|
|
445
|
+
const rec = this.byChannel.get(chatURI)!;
|
|
446
|
+
const a = action as ChatToolCallResultConfirmedAction;
|
|
447
|
+
const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
|
|
448
|
+
if (toolCallId === null || typeof a.approved !== "boolean") {
|
|
449
|
+
this.echo(chatURI, action, origin, "invalid chat/toolCallResultConfirmed params");
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
const invocation = chat.clientToolCalls.get(toolCallId);
|
|
453
|
+
if (invocation === undefined) {
|
|
454
|
+
this.echo(chatURI, action, origin, `no pending result confirmation for tool call ${toolCallId}`);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
if (origin !== undefined && invocation.clientId !== origin.clientId) {
|
|
458
|
+
this.echo(chatURI, action, origin, `only the contributing client (${invocation.clientId}) may confirm this result`);
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
if (this.toolCallState(chat, toolCallId)?.status !== ToolCallStatus.PendingResultConfirmation) {
|
|
462
|
+
this.echo(chatURI, action, origin, `tool call ${toolCallId} is not awaiting result confirmation`);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
this.echo(chatURI, action, origin);
|
|
466
|
+
this.publish({
|
|
467
|
+
channel: rec.channel,
|
|
468
|
+
action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
|
|
469
|
+
});
|
|
470
|
+
const held = invocation.pendingResult;
|
|
471
|
+
if (held === undefined) {
|
|
472
|
+
// Unreachable in practice (the state only reaches
|
|
473
|
+
// pending-result-confirmation through our complete path); fail
|
|
474
|
+
// closed so the opencode tool cannot hang.
|
|
475
|
+
this.settleClientTool(invocation, { ok: false, error: "no recorded result to confirm" });
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
if (a.approved) {
|
|
479
|
+
this.settleClientTool(invocation, clientResultToFacade(held as ToolCallResult));
|
|
480
|
+
} else {
|
|
481
|
+
this.settleClientTool(invocation, { ok: false, error: "the client denied the tool result" });
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private async dispatchTurnCancelled(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
486
|
+
const chatURI = chat.uri;
|
|
487
|
+
const a = action as ChatTurnCancelledAction;
|
|
488
|
+
const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
|
|
489
|
+
const active = chat.chatStore.state.activeTurn;
|
|
490
|
+
if (turnId === null || active === undefined || active.id !== turnId) {
|
|
491
|
+
this.echo(chatURI, action, origin, "no active turn to cancel");
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
try {
|
|
495
|
+
await this.opts.facade.interrupt({ sessionID: chat.sessionID });
|
|
496
|
+
} catch (err) {
|
|
497
|
+
this.echo(chatURI, action, origin, `interrupt failed: ${errorMessage(err)}`);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
// `duration` is required on the wire (the reducer derives the final
|
|
501
|
+
// `modifiedAt` from it); the host clock is authoritative when the
|
|
502
|
+
// client did not supply one.
|
|
503
|
+
const duration =
|
|
504
|
+
typeof a.duration === "number" && Number.isFinite(a.duration) ? a.duration : this.turnDuration(chat);
|
|
505
|
+
this.echo(chatURI, { ...a, duration }, origin);
|
|
506
|
+
// The opencode `session.execution.interrupted` event finds no active
|
|
507
|
+
// turn after the echo finalized it (skipped); run the queued/steering
|
|
508
|
+
// handoff now, on the host side.
|
|
509
|
+
await this.finishTurn(chat);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* `changeset/filesReviewChanged` (the only client-dispatchable changeset
|
|
514
|
+
* action): validate the channel resolves to a live store, then echo —
|
|
515
|
+
* the official reducer toggles `reviewed` per matched file id.
|
|
516
|
+
*/
|
|
517
|
+
private dispatchChangesetFilesReviewChanged(channel: string, action: StateAction, origin: ActionOrigin | undefined): void {
|
|
518
|
+
const a = action as ChangesetFilesReviewChangedAction;
|
|
519
|
+
if (!Array.isArray(a.files) || !a.files.every((f) => typeof f === "string") || typeof a.reviewed !== "boolean") {
|
|
520
|
+
this.echo(channel, action, origin, "invalid changeset/filesReviewChanged params");
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
const parsed = parseChangesetChannel(channel);
|
|
524
|
+
const rec = parsed !== null ? this.byChannel.get(parsed.ownerUri) : undefined;
|
|
525
|
+
const store = rec !== undefined ? this.changesetStoreOf(rec, channel) : undefined;
|
|
526
|
+
if (rec === undefined || store === undefined) {
|
|
527
|
+
this.echo(channel, action, origin, "no such changeset");
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
this.echo(channel, action, origin);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
private async dispatchTitleChanged(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
534
|
+
const a = action as { title?: unknown };
|
|
535
|
+
const title = typeof a.title === "string" && a.title.length > 0 ? a.title : null;
|
|
536
|
+
if (title === null) {
|
|
537
|
+
this.echo(rec.channel, action, origin, "invalid session/titleChanged params");
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
try {
|
|
541
|
+
await this.opts.facade.rename({ sessionID: rec.sessionID, title });
|
|
542
|
+
} catch (err) {
|
|
543
|
+
this.echo(rec.channel, action, origin, `rename failed: ${errorMessage(err)}`);
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
this.echo(rec.channel, action, origin);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
private dispatchActiveClientSet(
|
|
550
|
+
rec: SessionRecord,
|
|
551
|
+
action: StateAction,
|
|
552
|
+
origin: ActionOrigin | undefined,
|
|
553
|
+
clientId: string | null,
|
|
554
|
+
): void {
|
|
555
|
+
const a = action as { activeClient?: unknown };
|
|
556
|
+
const ac = a.activeClient;
|
|
557
|
+
if (!isRecord(ac) || typeof ac["clientId"] !== "string" || (clientId !== null && ac["clientId"] !== clientId)) {
|
|
558
|
+
this.echo(rec.channel, action, origin, "activeClient.clientId must match the dispatching client");
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
const tools = normalizeToolDefinitions(ac["tools"]);
|
|
562
|
+
const normalized: SessionActiveClient = {
|
|
563
|
+
clientId: ac["clientId"] as string,
|
|
564
|
+
tools,
|
|
565
|
+
...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
|
|
566
|
+
};
|
|
567
|
+
this.publish({
|
|
568
|
+
channel: rec.channel,
|
|
569
|
+
action: { type: ActionType.SessionActiveClientSet, activeClient: normalized },
|
|
570
|
+
origin,
|
|
571
|
+
});
|
|
572
|
+
// The session's tool contribution changed —
|
|
573
|
+
// re-sync the location-global opencode tool union.
|
|
574
|
+
void this.syncClientToolsToOpencode();
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
private dispatchActiveClientRemoved(
|
|
578
|
+
rec: SessionRecord,
|
|
579
|
+
action: StateAction,
|
|
580
|
+
origin: ActionOrigin | undefined,
|
|
581
|
+
clientId: string | null,
|
|
582
|
+
): void {
|
|
583
|
+
const a = action as { clientId?: unknown };
|
|
584
|
+
if (typeof a.clientId !== "string" || (clientId !== null && a.clientId !== clientId)) {
|
|
585
|
+
this.echo(rec.channel, action, origin, "clientId must match the dispatching client");
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
this.echo(rec.channel, action, origin);
|
|
589
|
+
// The session's tool contribution shrank —
|
|
590
|
+
// re-sync the location-global opencode tool union.
|
|
591
|
+
void this.syncClientToolsToOpencode();
|
|
592
|
+
}
|
|
593
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON-RPC error codes emitted by the host: the standard -327xx range plus the AHP-specific -320xx codes.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export const ERROR_PARSE = -32700;
|
|
6
|
+
|
|
7
|
+
export const ERROR_INVALID_REQUEST = -32600;
|
|
8
|
+
|
|
9
|
+
export const ERROR_METHOD_NOT_FOUND = -32601;
|
|
10
|
+
|
|
11
|
+
export const ERROR_INTERNAL = -32603;
|
|
12
|
+
|
|
13
|
+
export const ERROR_SESSION_NOT_FOUND = -32001;
|
|
14
|
+
|
|
15
|
+
export const ERROR_NO_PROVIDER = -32002;
|
|
16
|
+
|
|
17
|
+
export const ERROR_SESSION_EXISTS = -32003;
|
|
18
|
+
|
|
19
|
+
export const ERROR_NOT_FOUND = -32008;
|
|
20
|
+
|
|
21
|
+
export const ERROR_PERMISSION_DENIED = -32009;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* AHP `AlreadyExists` (-32010): the target resource already exists. This
|
|
25
|
+
* host's use: a `createTerminal` for a channel that is already open.
|
|
26
|
+
* (AHP 1.0.0 defines no "not supported" code — the -32600…-32603
|
|
27
|
+
* standard range covers those shapes.)
|
|
28
|
+
*/
|
|
29
|
+
export const ERROR_ALREADY_EXISTS = -32010;
|