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,435 @@
1
+ /**
2
+ * RPC section (design §4, §13): JSON-RPC frame handling, routing, the initialize/reconnect/subscribe handshake, and snapshot serving.
3
+ */
4
+
5
+ import { HostEvents } from "./host-events.js";
6
+ import { ActionType, ChangesetStatus, ReconnectResultType, ReconnectResult, Snapshot } from "@microsoft/agent-host-protocol";
7
+ import { mapCatalog } from "./bridge.js";
8
+ import { ROOT_CHANNEL, parseChangesetChannel } from "./channels.js";
9
+ import { ERROR_INVALID_PARAMS, handleInitialize } from "./handshake.js";
10
+ import { isRecord } from "./options.js";
11
+ import { ERROR_PARSE, ERROR_INVALID_REQUEST, ERROR_METHOD_NOT_FOUND, ERROR_INTERNAL, ERROR_SESSION_NOT_FOUND, ERROR_NOT_FOUND } from "./host-errors.js";
12
+ import { RpcMessage } from "./host-types.js";
13
+ import { sameAgents, describeParams } from "./host-util.js";
14
+
15
+ /** Version assumed for a reconnecting client the host has never seen (host restart). */
16
+ const RECONNECT_DEFAULT_VERSION = "1.0.0";
17
+
18
+ export class HostRpc extends HostEvents {
19
+ // ── transport callbacks ────────────────────────────────────────────────
20
+ onOpen(socketId: number): void {
21
+ this.sockets.set(socketId, { initialized: false, version: null, clientId: null });
22
+ }
23
+
24
+ onMessage(socketId: number, text: string): void {
25
+ let raw: unknown;
26
+ try {
27
+ raw = JSON.parse(text);
28
+ } catch {
29
+ this.sendFrame(socketId, {
30
+ jsonrpc: "2.0",
31
+ id: null,
32
+ error: { code: ERROR_PARSE, message: "parse error" },
33
+ });
34
+ return;
35
+ }
36
+ if (!isRecord(raw) || raw.jsonrpc !== "2.0" || typeof raw.method !== "string") {
37
+ this.sendFrame(socketId, {
38
+ jsonrpc: "2.0",
39
+ id: isRecord(raw) ? raw.id ?? null : null,
40
+ error: { code: ERROR_INVALID_REQUEST, message: "invalid request" },
41
+ });
42
+ return;
43
+ }
44
+ // The routing is async (catalog reads await the opencode registry);
45
+ // each message is handled independently.
46
+ void this.route(socketId, raw).catch((err) => {
47
+ // R2: a bad frame or a bridge error must never take down the host.
48
+ this.log(
49
+ `error handling ${String(raw.method)}: ${err instanceof Error ? err.stack ?? err.message : String(err)}`,
50
+ );
51
+ if (raw.id !== undefined) {
52
+ this.sendFrame(socketId, {
53
+ jsonrpc: "2.0",
54
+ id: raw.id,
55
+ error: { code: ERROR_INTERNAL, message: "internal error" },
56
+ });
57
+ }
58
+ });
59
+ }
60
+
61
+ onClose(socketId: number): void {
62
+ const socket = this.sockets.get(socketId);
63
+ if (socket?.clientId) {
64
+ const record = this.clients.get(socket.clientId);
65
+ if (record && record.socketId === socketId) record.socketId = null;
66
+ // The spec says the server SHOULD remove an
67
+ // active client when it disconnects. Safe: the
68
+ // official client re-dispatches `activeClientSet` on re-subscribe.
69
+ this.evictActiveClient(socket.clientId);
70
+ }
71
+ this.channels.removeSocket(socketId);
72
+ this.sockets.delete(socketId);
73
+ }
74
+
75
+ /**
76
+ * Evict a disconnected client's active-client
77
+ * role from every session it holds (server-side
78
+ * `session/activeClientRemoved`), fail its in-flight client-tool
79
+ * executions (the opencode tool then fails → the pump's normal
80
+ * `tool.failed` path completes the AHP tool call — the state is still
81
+ * `running`, so the terminal suppression does not apply), clear the
82
+ * session input request each execution raised (the
83
+ * `toolClientExecution` request, or the `toolConfirmation` that
84
+ * replaced it under the same id when the result was held for
85
+ * approval — without this the session keeps a stale request and, for
86
+ * a held result, sits in InputNeeded forever), and re-sync the
87
+ * opencode tool union (it shrank).
88
+ */
89
+ private evictActiveClient(clientId: string): void {
90
+ let evicted = false;
91
+ for (const rec of this.sessions.values()) {
92
+ if (!rec.sessionStore.state.activeClients.some((c) => c.clientId === clientId)) continue;
93
+ evicted = true;
94
+ this.publish({
95
+ channel: rec.channel,
96
+ action: { type: ActionType.SessionActiveClientRemoved, clientId },
97
+ });
98
+ // In-flight client-tool calls are per-chat.
99
+ for (const chat of rec.chats.values()) {
100
+ for (const [toolCallId, inv] of chat.clientToolCalls) {
101
+ if (inv.clientId !== clientId || inv.result !== undefined) continue;
102
+ inv.result = { ok: false, error: `client ${clientId} disconnected before completing the tool call` };
103
+ this.settleClientTool(inv);
104
+ // The reducer's inputNeededRemoved is a no-op when the id is
105
+ // absent, so this is safe for an invocation whose request was
106
+ // already cleared on the normal completion path.
107
+ this.publish({
108
+ channel: rec.channel,
109
+ action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
110
+ });
111
+ }
112
+ }
113
+ }
114
+ if (evicted) void this.syncClientToolsToOpencode();
115
+ }
116
+
117
+ // ── routing ────────────────────────────────────────────────────────────
118
+ private async route(socketId: number, msg: RpcMessage): Promise<void> {
119
+ const socket = this.sockets.get(socketId);
120
+ if (!socket) return;
121
+ const method = msg.method as string;
122
+
123
+ if (!socket.initialized) {
124
+ if (method === "ping") {
125
+ // ping is answered even before initialize (AHP transport spec).
126
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
127
+ return;
128
+ }
129
+ if (method === "initialize") {
130
+ await this.handleInitialize(socketId, msg);
131
+ return;
132
+ }
133
+ if (method === "reconnect") {
134
+ await this.handleReconnect(socketId, msg);
135
+ return;
136
+ }
137
+ if (msg.id !== undefined) {
138
+ this.sendFrame(socketId, {
139
+ jsonrpc: "2.0",
140
+ id: msg.id,
141
+ error: {
142
+ code: ERROR_INVALID_REQUEST,
143
+ message: `not initialized: ${method} must follow initialize or reconnect`,
144
+ },
145
+ });
146
+ return;
147
+ }
148
+ this.log(`ignoring pre-initialize notification ${method} on socket ${socketId}`);
149
+ return;
150
+ }
151
+
152
+ switch (method) {
153
+ case "ping":
154
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
155
+ break;
156
+ case "subscribe":
157
+ await this.handleSubscribe(socketId, msg);
158
+ break;
159
+ case "unsubscribe":
160
+ this.handleUnsubscribe(socketId, msg); // notification (no id)
161
+ break;
162
+ case "dispatchAction":
163
+ await this.handleDispatchAction(socketId, msg); // notification (no id)
164
+ break;
165
+ case "listSessions":
166
+ await this.handleListSessions(socketId, msg);
167
+ break;
168
+ case "resolveSessionConfig":
169
+ this.handleResolveSessionConfig(socketId, msg);
170
+ break;
171
+ case "createSession":
172
+ await this.handleCreateSession(socketId, msg);
173
+ break;
174
+ case "createChat":
175
+ await this.handleCreateChat(socketId, msg);
176
+ break;
177
+ case "disposeChat":
178
+ await this.handleDisposeChat(socketId, msg);
179
+ break;
180
+ case "resourceRead":
181
+ await this.handleResourceRead(socketId, msg);
182
+ break;
183
+ case "invokeChangesetOperation":
184
+ await this.handleInvokeChangesetOperation(socketId, msg);
185
+ break;
186
+ case "createTerminal":
187
+ await this.handleCreateTerminal(socketId, msg);
188
+ break;
189
+ case "disposeTerminal":
190
+ await this.handleDisposeTerminal(socketId, msg);
191
+ break;
192
+ case "setClientManagedSettingsPermissions":
193
+ // VS Code-specific post-init notification: the
194
+ // permissions VS Code manages in its own settings UI. AHP 1.0.0
195
+ // has no counterpart — accept deliberately (parse + log), never
196
+ // error; the connection stays up.
197
+ this.log(
198
+ `setClientManagedSettingsPermissions received (${describeParams(msg.params)}); accepted (no-op)`,
199
+ );
200
+ break;
201
+ case "initialize":
202
+ case "reconnect":
203
+ this.sendFrame(socketId, {
204
+ jsonrpc: "2.0",
205
+ id: msg.id ?? null,
206
+ error: {
207
+ code: ERROR_INVALID_REQUEST,
208
+ message: `${method} is only valid before the handshake`,
209
+ },
210
+ });
211
+ break;
212
+ default:
213
+ if (msg.id !== undefined) {
214
+ this.sendFrame(socketId, {
215
+ jsonrpc: "2.0",
216
+ id: msg.id,
217
+ error: { code: ERROR_METHOD_NOT_FOUND, message: `unknown method: ${method}` },
218
+ });
219
+ } else {
220
+ this.log(`ignoring unknown notification ${method} on socket ${socketId}`);
221
+ }
222
+ }
223
+ }
224
+
225
+ // ── commands ───────────────────────────────────────────────────────────
226
+ private async handleInitialize(socketId: number, msg: RpcMessage): Promise<void> {
227
+ const socket = this.sockets.get(socketId)!;
228
+ const outcome = await handleInitialize({
229
+ params: msg.params,
230
+ serverInfo: this.opts.serverInfo,
231
+ serverSeq: this.seq.seq,
232
+ defaultDirectory: this.opts.defaultDirectory,
233
+ snapshotFor: (uri) => this.snapshotFor(uri),
234
+ });
235
+ if (!outcome.ok) {
236
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, error: outcome.error });
237
+ return;
238
+ }
239
+
240
+ const clientId = (msg.params as { clientId: string }).clientId;
241
+ const existing = this.clients.get(clientId);
242
+ if (existing && existing.socketId !== null && existing.socketId !== socketId) {
243
+ // A newer connection with the same clientId supersedes the old one.
244
+ this.log(`client ${clientId} re-initialized on socket ${socketId}; closing socket ${existing.socketId}`);
245
+ this.opts.close?.(existing.socketId, 4000, "superseded by a newer connection");
246
+ }
247
+
248
+ socket.initialized = true;
249
+ socket.version = outcome.result.protocolVersion;
250
+ socket.clientId = clientId;
251
+ this.clients.set(clientId, { version: outcome.result.protocolVersion, socketId });
252
+
253
+ // Register the initial subscriptions right after the snapshot
254
+ // computation above; no action can slip in between.
255
+ const params = isRecord(msg.params) ? msg.params : {};
256
+ const initial = Array.isArray(params["initialSubscriptions"])
257
+ ? params["initialSubscriptions"]
258
+ : [];
259
+ for (const uri of initial) {
260
+ if (typeof uri === "string" && uri.length > 0) {
261
+ this.channels.subscribe(socketId, uri);
262
+ }
263
+ }
264
+
265
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: outcome.result });
266
+ }
267
+
268
+ private async handleReconnect(socketId: number, msg: RpcMessage): Promise<void> {
269
+ const params = msg.params;
270
+ if (!isRecord(params) || params["channel"] !== ROOT_CHANNEL) {
271
+ this.sendFrame(socketId, {
272
+ jsonrpc: "2.0",
273
+ id: msg.id ?? null,
274
+ error: { code: ERROR_INVALID_PARAMS, message: `reconnect must target ${ROOT_CHANNEL}` },
275
+ });
276
+ return;
277
+ }
278
+ const clientId = params["clientId"];
279
+ const lastSeen = params["lastSeenServerSeq"];
280
+ const subscriptions = params["subscriptions"];
281
+ if (typeof clientId !== "string" || clientId.length === 0 ||
282
+ !Number.isInteger(lastSeen) || (lastSeen as number) < 0 ||
283
+ !Array.isArray(subscriptions) || !subscriptions.every((u) => typeof u === "string")) {
284
+ this.sendFrame(socketId, {
285
+ jsonrpc: "2.0",
286
+ id: msg.id ?? null,
287
+ error: { code: ERROR_INVALID_PARAMS, message: "invalid reconnect params" },
288
+ });
289
+ return;
290
+ }
291
+ const clientSubs = subscriptions as string[];
292
+
293
+ const record = this.clients.get(clientId);
294
+ const known = record !== undefined;
295
+ const version = record?.version ?? RECONNECT_DEFAULT_VERSION;
296
+
297
+ const socket = this.sockets.get(socketId)!;
298
+ socket.initialized = true;
299
+ socket.version = version;
300
+ socket.clientId = clientId;
301
+ this.clients.set(clientId, { version, socketId });
302
+
303
+ // Resolve every requested subscription; unresolvable ones are reported
304
+ // in `missing` (the client drops them — AHP lifecycle spec).
305
+ const snapshots: Snapshot[] = [];
306
+ const missing: string[] = [];
307
+ for (const uri of clientSubs) {
308
+ const snap = await this.snapshotFor(uri);
309
+ if (snap) snapshots.push(snap);
310
+ else missing.push(uri);
311
+ }
312
+ for (const uri of clientSubs) {
313
+ this.channels.subscribe(socketId, uri);
314
+ }
315
+
316
+ // Replay when the client is known and its gap is still in the window;
317
+ // otherwise fresh snapshots.
318
+ let result: ReconnectResult;
319
+ const replay = this.seq.since(lastSeen as number);
320
+ if (known && replay !== null) {
321
+ const set = new Set(clientSubs);
322
+ result = {
323
+ type: ReconnectResultType.Replay,
324
+ actions: replay.filter((a) => set.has(a.channel)),
325
+ missing,
326
+ };
327
+ } else {
328
+ result = { type: ReconnectResultType.Snapshot, snapshots };
329
+ }
330
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
331
+ }
332
+
333
+ private async handleSubscribe(socketId: number, msg: RpcMessage): Promise<void> {
334
+ const params = isRecord(msg.params) ? msg.params : {};
335
+ const uri = params["channel"];
336
+ if (typeof uri !== "string" || uri.length === 0) {
337
+ this.sendFrame(socketId, {
338
+ jsonrpc: "2.0",
339
+ id: msg.id ?? null,
340
+ error: { code: ERROR_INVALID_PARAMS, message: "subscribe requires a channel URI" },
341
+ });
342
+ return;
343
+ }
344
+ const outcome = this.channels.subscribe(socketId, uri);
345
+ if (!outcome.ok) {
346
+ this.sendFrame(socketId, {
347
+ jsonrpc: "2.0",
348
+ id: msg.id ?? null,
349
+ error: {
350
+ code:
351
+ outcome.reason === "no-such-session"
352
+ ? ERROR_SESSION_NOT_FOUND
353
+ : outcome.reason === "no-such-terminal"
354
+ ? ERROR_NOT_FOUND
355
+ : ERROR_INVALID_PARAMS,
356
+ message: `cannot subscribe to ${uri}`,
357
+ },
358
+ });
359
+ return;
360
+ }
361
+ const snap = await this.snapshotFor(uri);
362
+ this.sendFrame(socketId, {
363
+ jsonrpc: "2.0",
364
+ id: msg.id ?? null,
365
+ result: snap ? { snapshot: snap } : {},
366
+ });
367
+ }
368
+
369
+ private handleUnsubscribe(socketId: number, msg: RpcMessage): void {
370
+ const params = isRecord(msg.params) ? msg.params : {};
371
+ const uri = params["channel"];
372
+ if (typeof uri !== "string" || uri.length === 0) return;
373
+ this.channels.unsubscribe(socketId, uri);
374
+ }
375
+
376
+ /**
377
+ * Snapshot for a channel URI, or null when the channel is not
378
+ * subscribable right now.
379
+ *
380
+ * Root snapshots re-derive the catalog from the facade on every call
381
+ * (registry reads reflect every registration so far; in-process reads
382
+ * are cheap). Session/chat snapshots read the official-reducer stores.
383
+ */
384
+ // ── state / publishing ─────────────────────────────────────────────────
385
+ private async snapshotFor(uri: string): Promise<Snapshot | null> {
386
+ // kindOf, not channelKind: client-chosen pty terminal URIs classify
387
+ // "unknown" by prefix and resolve only while their record is live.
388
+ const kind = this.kindOf(uri);
389
+ if (kind === "unknown") return null;
390
+ if (kind === "changeset") {
391
+ if (!this.opts.changesets) return null;
392
+ const parsed = parseChangesetChannel(uri);
393
+ if (parsed === null) return null;
394
+ // The owner is the session/chat channel (owner-aware).
395
+ const rec = this.byChannel.get(parsed.ownerUri);
396
+ if (rec === undefined) return null;
397
+ const store = this.changesetStore(rec, uri);
398
+ if (store === null) return null; // owner gone (disposed chat)
399
+ // First subscribe (or a failed computation) triggers the computation;
400
+ // subsequent subscribes return the last completed state.
401
+ if (store.state.status === ChangesetStatus.Computing || store.state.status === ChangesetStatus.Error) {
402
+ await this.refreshChangeset(rec, uri);
403
+ }
404
+ return { resource: uri, state: store.state, fromSeq: this.seq.seq };
405
+ }
406
+ if (kind === "terminal") {
407
+ // The synthetic terminal's official-reducer
408
+ // state; null once the record is torn down (the chat is gone).
409
+ const t = this.terminals.get(uri);
410
+ if (t === undefined) return null;
411
+ return { resource: uri, state: t.store.state, fromSeq: this.seq.seq };
412
+ }
413
+ if (kind !== "root") {
414
+ const rec = this.byChannel.get(uri);
415
+ if (rec === undefined) return null;
416
+ if (uri === rec.channel) {
417
+ return { resource: uri, state: rec.sessionStore.state, fromSeq: this.seq.seq };
418
+ }
419
+ const chat = rec.chats.get(uri);
420
+ if (chat !== undefined) {
421
+ return { resource: uri, state: chat.chatStore.state, fromSeq: this.seq.seq };
422
+ }
423
+ return null;
424
+ }
425
+ const [providers, agents] = await Promise.all([
426
+ this.opts.facade.listCatalog(),
427
+ this.opts.facade.listAgents(),
428
+ ]);
429
+ const catalog = mapCatalog(providers, agents, this.opts.defaultDirectory);
430
+ if (!sameAgents(this.state.state.agents, catalog)) {
431
+ this.state.apply({ type: ActionType.RootAgentsChanged, agents: catalog });
432
+ }
433
+ return { resource: ROOT_CHANNEL, state: this.state.state, fromSeq: this.seq.seq };
434
+ }
435
+ }