opencode-ahp 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/src/host.ts ADDED
@@ -0,0 +1,1795 @@
1
+ /**
2
+ * The AHP host: the JSON-RPC 2.0 router over transport connections that
3
+ * ties the sequencer, channel registry, root state store, and bridge
4
+ * together (plan §6.1).
5
+ *
6
+ * Deviation (plan §14): the plan's §7 module list stopped at bridge.ts;
7
+ * the router that wires the pure modules to sockets is extracted here (a
8
+ * `Host` class) so the whole protocol layer is unit-testable and
9
+ * exercisable by the spike client without a WebSocket runtime.
10
+ *
11
+ * Connection model (AHP 1.0.0 lifecycle spec):
12
+ * - the first request on a socket is `initialize` (new client) or
13
+ * `reconnect` (known clientId — the host keeps a per-clientId registry
14
+ * across sockets);
15
+ * - `ping` is answered even before initialize;
16
+ * - `serverSeq` is a single host-wide sequence (seq.ts);
17
+ * - `dispatchAction` and `unsubscribe` are notifications (no id); a
18
+ * dispatched action comes back on the `action` notification stream
19
+ * (write-ahead reconciliation; rejections carry `rejectionReason`).
20
+ *
21
+ * Phase 1 (plan §11): `createSession` + `listSessions`, session/chat
22
+ * snapshots, the opencode event pump (streaming text/reasoning, tool-call
23
+ * lifecycle, permission prompts, usage, turn terminals + steering/queue
24
+ * handoff), and the client-dispatchable actions VS Code sends
25
+ * (`chat/turnStarted`, `chat/pendingMessageSet`, `chat/toolCallConfirmed`,
26
+ * `chat/turnCancelled`, drafts/read/title/activeClient echoes, …).
27
+ *
28
+ * Session model: one opencode session = one AHP session channel = one
29
+ * default chat channel (plan §3.2 gap, same as pi-ahp). Channel suffixes
30
+ * are opaque; opencode session ids start with "ses" and double as
31
+ * suffixes for externally created sessions.
32
+ *
33
+ * Root session lifecycle events (`root/sessionAdded`,
34
+ * `root/sessionRemoved`, `root/sessionSummaryChanged`) are JSON-RPC
35
+ * *notifications* in AHP 1.0.0 (ephemeral, not replayed) — only
36
+ * `root/activeSessionsChanged` is a sequencer action.
37
+ */
38
+ import {
39
+ ActionType,
40
+ PendingMessageKind,
41
+ ReconnectResultType,
42
+ ResponsePartKind,
43
+ SessionInputRequestKind,
44
+ SessionStatus,
45
+ ToolCallConfirmationReason,
46
+ ToolCallStatus,
47
+ ToolResultContentType,
48
+ isClientDispatchable,
49
+ type ActionEnvelope,
50
+ type ActionOrigin,
51
+ type ChatAction,
52
+ type ChatSummary,
53
+ type ChatState,
54
+ type ChatToolCallConfirmedAction,
55
+ type ChatTurnCancelledAction,
56
+ type ChatTurnStartedAction,
57
+ type ErrorResponsePart,
58
+ type Implementation,
59
+ type Message,
60
+ type ReconnectResult,
61
+ type RootAction,
62
+ type SessionAction,
63
+ type SessionActiveClient,
64
+ type SessionState,
65
+ type SessionSummary,
66
+ type SessionToolConfirmationRequest,
67
+ type Snapshot,
68
+ type StateAction,
69
+ type ToolCallConfirmationState,
70
+ type ToolCallState,
71
+ type ToolDefinition,
72
+ type ToolResultContent,
73
+ } from "@microsoft/agent-host-protocol";
74
+ import {
75
+ agentDirectoryCustomization,
76
+ agentIDFromUri,
77
+ buildSessionSummary,
78
+ chatSummaryOf,
79
+ displayNameFor,
80
+ initialChatState,
81
+ initialSessionState,
82
+ invocationMessageFor,
83
+ mapCatalog,
84
+ mapAgentCustomizations,
85
+ pastTenseMessageFor,
86
+ userMessage,
87
+ type FacadeDelivery,
88
+ type FacadeEvent,
89
+ type FacadeModelRef,
90
+ type FacadeSession,
91
+ type OpencodeFacade,
92
+ } from "./bridge.js";
93
+ import { ChannelRegistry, ROOT_CHANNEL, channelKind, chatChannelURI, sessionChannelURI, sessionIDOf } from "./channels.js";
94
+ import { ERROR_INVALID_PARAMS, handleInitialize } from "./handshake.js";
95
+ import { isRecord } from "./options.js";
96
+ import { Sequencer } from "./seq.js";
97
+ import {
98
+ createChatStateStore,
99
+ createRootStateStore,
100
+ createSessionStateStore,
101
+ type ChatStateStore,
102
+ type RootStateStore,
103
+ type SessionStateStore,
104
+ } from "./state.js";
105
+
106
+ export const ERROR_PARSE = -32700;
107
+ export const ERROR_INVALID_REQUEST = -32600;
108
+ export const ERROR_METHOD_NOT_FOUND = -32601;
109
+ export const ERROR_INTERNAL = -32603;
110
+ export const ERROR_SESSION_NOT_FOUND = -32001;
111
+ export const ERROR_NO_PROVIDER = -32002;
112
+ export const ERROR_SESSION_EXISTS = -32003;
113
+
114
+ // ActionType / ReconnectResultType are `declare const enum` in the package
115
+ // but are also real runtime objects (verified against the published dist),
116
+ // so the value imports are safe under both tsc (inlined) and Bun.
117
+
118
+ interface RpcMessage {
119
+ jsonrpc?: unknown;
120
+ id?: unknown;
121
+ method?: unknown;
122
+ params?: unknown;
123
+ }
124
+
125
+ interface SocketState {
126
+ initialized: boolean;
127
+ /** Negotiated version (set by initialize, inherited on reconnect). */
128
+ version: string | null;
129
+ clientId: string | null;
130
+ }
131
+
132
+ /**
133
+ * Per-clientId registry record — survives socket closes so `reconnect`
134
+ * can replay for the same client (AHP lifecycle spec).
135
+ */
136
+ interface ClientRecord {
137
+ version: string;
138
+ socketId: number | null;
139
+ }
140
+
141
+ /**
142
+ * Everything the host knows about one live opencode session: the two
143
+ * official-reducer stores (session + its single chat), the denormalized
144
+ * summary fields for root notifications, and the per-turn tracking the
145
+ * event pump needs to join opencode events to AHP turns.
146
+ */
147
+ interface SessionRecord {
148
+ /** The opencode session id (`ses_…`). */
149
+ sessionID: string;
150
+ /** The AHP session channel URI (`ahp-session:/<suffix>`). */
151
+ channel: string;
152
+ /** Identity `SessionSummary.provider` (fixed at registration). */
153
+ provider: string;
154
+ createdAt: string;
155
+ /** Denormalized `SessionSummary.modifiedAt` (ISO; lexicographic = chronological). */
156
+ modifiedAt: string;
157
+ sessionStore: SessionStateStore;
158
+ chatStore: ChatStateStore;
159
+ // ── turn tracking (event-pump join state) ────────────────────────────
160
+ /** The AHP turnId the pump joins opencode events to, or null. */
161
+ currentTurnId: string | null;
162
+ turnStartedAt: number | null;
163
+ /** `<providerID>/<modelID>` captured from `session.step.started` (usage model ref). */
164
+ turnModelRef: string | null;
165
+ // ── part / tool tracking ─────────────────────────────────────────────
166
+ /** Emitted part keys (`<assistantMessageID>:<kind>:<ordinal>`). */
167
+ parts: Set<string>;
168
+ /** toolCallId → raw JSON input text (`session.tool.input.ended.text`). */
169
+ toolInput: Map<string, string>;
170
+ /** toolCallId → opencode tool name (`session.tool.input.started.name`). */
171
+ toolName: Map<string, string>;
172
+ /** toolCallIds that already received `chat/toolCallReady`. */
173
+ toolReady: Set<string>;
174
+ /** toolCallId → opencode permission request id. */
175
+ permissionForTool: Map<string, string>;
176
+ /** opencode permission request id → toolCallId. */
177
+ toolForPermission: Map<string, string>;
178
+ /** The most recent `session.inbox.enqueued` (external/TUI prompt tracking). */
179
+ lastInbox: { text: string; delivery: string } | null;
180
+ }
181
+
182
+ export interface HostOptions {
183
+ serverInfo: Implementation;
184
+ facade: OpencodeFacade;
185
+ replayWindow: number;
186
+ /** The opencode instance's working directory (InitializeResult.defaultDirectory). */
187
+ defaultDirectory?: string;
188
+ /** Deliver a JSON-serializable frame to a connection. */
189
+ send: (socketId: number, message: unknown) => void;
190
+ /** Close one connection (a superseded duplicate clientId). */
191
+ close?: (socketId: number, code?: number, reason?: string) => void;
192
+ log?: (message: string) => void;
193
+ }
194
+
195
+ /** Version assumed for a reconnecting client the host has never seen (host restart). */
196
+ const RECONNECT_DEFAULT_VERSION = "1.0.0";
197
+ /**
198
+ * Grace before the pump registers an externally created session
199
+ * (`session.created`): a concurrent `createSession` may still be resolving
200
+ * for the same opencode session under a client-chosen channel; the slower
201
+ * path is healed by the delete+recreate remap in `handleCreateSession`.
202
+ */
203
+ const EXTERNAL_REGISTER_GRACE_MS = 250;
204
+ /** Default page size for `listSessions` (AHP `PaginatedParams.limit`). */
205
+ const LIST_SESSIONS_DEFAULT_LIMIT = 100;
206
+
207
+ export class Host {
208
+ private readonly seq: Sequencer;
209
+ private readonly channels = new ChannelRegistry();
210
+ private readonly state: RootStateStore;
211
+ private readonly sockets = new Map<number, SocketState>();
212
+ private readonly clients = new Map<string, ClientRecord>();
213
+ /**
214
+ * Live sessions, keyed by opencode session id (the event-pump join key).
215
+ * `byChannel` maps a session/chat channel URI to the same record for the
216
+ * client-facing lookups — the channel suffix is not always the opencode id
217
+ * (client-chosen suffixes), so the two keyings differ.
218
+ */
219
+ private readonly sessions = new Map<string, SessionRecord>();
220
+ private readonly byChannel = new Map<string, SessionRecord>();
221
+ private readonly opts: HostOptions;
222
+ private readonly log: (message: string) => void;
223
+ private turnCounter = 0;
224
+ private pumpController: AbortController | null = null;
225
+
226
+ constructor(opts: HostOptions) {
227
+ this.opts = opts;
228
+ this.log = opts.log ?? (() => {});
229
+ this.seq = new Sequencer(opts.replayWindow);
230
+ this.state = createRootStateStore({ agents: [] });
231
+ }
232
+
233
+ // ── transport callbacks ────────────────────────────────────────────────
234
+
235
+ onOpen(socketId: number): void {
236
+ this.sockets.set(socketId, { initialized: false, version: null, clientId: null });
237
+ }
238
+
239
+ onMessage(socketId: number, text: string): void {
240
+ let raw: unknown;
241
+ try {
242
+ raw = JSON.parse(text);
243
+ } catch {
244
+ this.sendFrame(socketId, {
245
+ jsonrpc: "2.0",
246
+ id: null,
247
+ error: { code: ERROR_PARSE, message: "parse error" },
248
+ });
249
+ return;
250
+ }
251
+ if (!isRecord(raw) || raw.jsonrpc !== "2.0" || typeof raw.method !== "string") {
252
+ this.sendFrame(socketId, {
253
+ jsonrpc: "2.0",
254
+ id: isRecord(raw) ? raw.id ?? null : null,
255
+ error: { code: ERROR_INVALID_REQUEST, message: "invalid request" },
256
+ });
257
+ return;
258
+ }
259
+ // The routing is async (catalog reads await the opencode registry);
260
+ // each message is handled independently.
261
+ void this.route(socketId, raw).catch((err) => {
262
+ // R2: a bad frame or a bridge error must never take down the host.
263
+ this.log(
264
+ `error handling ${String(raw.method)}: ${err instanceof Error ? err.stack ?? err.message : String(err)}`,
265
+ );
266
+ if (raw.id !== undefined) {
267
+ this.sendFrame(socketId, {
268
+ jsonrpc: "2.0",
269
+ id: raw.id,
270
+ error: { code: ERROR_INTERNAL, message: "internal error" },
271
+ });
272
+ }
273
+ });
274
+ }
275
+
276
+ onClose(socketId: number): void {
277
+ const socket = this.sockets.get(socketId);
278
+ if (socket?.clientId) {
279
+ const record = this.clients.get(socket.clientId);
280
+ if (record && record.socketId === socketId) record.socketId = null;
281
+ }
282
+ this.channels.removeSocket(socketId);
283
+ this.sockets.delete(socketId);
284
+ // MVP gap: active clients are not evicted on disconnect (the spec
285
+ // expects eviction without a timely reconnect); they refresh via
286
+ // `session/activeClientSet` on the next turn/dispatch.
287
+ }
288
+
289
+ // ── event pump ─────────────────────────────────────────────────────────
290
+
291
+ /**
292
+ * Start the opencode event → AHP action pump. Idempotent. The pump is a
293
+ * single sequential async loop, so event handling and client-dispatch
294
+ * handling (same event loop) interleave without races on the per-turn
295
+ * join state.
296
+ */
297
+ startEventPump(): void {
298
+ if (this.pumpController !== null) return;
299
+ const controller = new AbortController();
300
+ this.pumpController = controller;
301
+ void (async () => {
302
+ try {
303
+ for await (const event of this.opts.facade.events(controller.signal)) {
304
+ if (controller.signal.aborted) break;
305
+ await this.handleEvent(event);
306
+ }
307
+ } catch (err) {
308
+ this.log(`event pump failed: ${err instanceof Error ? err.stack ?? err.message : String(err)}`);
309
+ } finally {
310
+ if (this.pumpController === controller) this.pumpController = null;
311
+ }
312
+ })();
313
+ }
314
+
315
+ /** Stop the event pump (teardown). Idempotent. */
316
+ stopEventPump(): void {
317
+ this.pumpController?.abort();
318
+ this.pumpController = null;
319
+ }
320
+
321
+ // ── routing ────────────────────────────────────────────────────────────
322
+
323
+ private async route(socketId: number, msg: RpcMessage): Promise<void> {
324
+ const socket = this.sockets.get(socketId);
325
+ if (!socket) return;
326
+ const method = msg.method as string;
327
+
328
+ if (!socket.initialized) {
329
+ if (method === "ping") {
330
+ // ping is answered even before initialize (AHP transport spec).
331
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
332
+ return;
333
+ }
334
+ if (method === "initialize") {
335
+ await this.handleInitialize(socketId, msg);
336
+ return;
337
+ }
338
+ if (method === "reconnect") {
339
+ await this.handleReconnect(socketId, msg);
340
+ return;
341
+ }
342
+ if (msg.id !== undefined) {
343
+ this.sendFrame(socketId, {
344
+ jsonrpc: "2.0",
345
+ id: msg.id,
346
+ error: {
347
+ code: ERROR_INVALID_REQUEST,
348
+ message: `not initialized: ${method} must follow initialize or reconnect`,
349
+ },
350
+ });
351
+ return;
352
+ }
353
+ this.log(`ignoring pre-initialize notification ${method} on socket ${socketId}`);
354
+ return;
355
+ }
356
+
357
+ switch (method) {
358
+ case "ping":
359
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
360
+ break;
361
+ case "subscribe":
362
+ await this.handleSubscribe(socketId, msg);
363
+ break;
364
+ case "unsubscribe":
365
+ this.handleUnsubscribe(socketId, msg); // notification (no id)
366
+ break;
367
+ case "dispatchAction":
368
+ await this.handleDispatchAction(socketId, msg); // notification (no id)
369
+ break;
370
+ case "listSessions":
371
+ await this.handleListSessions(socketId, msg);
372
+ break;
373
+ case "createSession":
374
+ await this.handleCreateSession(socketId, msg);
375
+ break;
376
+ case "setClientManagedSettingsPermissions":
377
+ // VS Code-specific post-init notification (plan §14.7): the
378
+ // permissions VS Code manages in its own settings UI. AHP 1.0.0
379
+ // has no counterpart — accept deliberately (parse + log), never
380
+ // error; the connection stays up.
381
+ this.log(
382
+ `setClientManagedSettingsPermissions received (${describeParams(msg.params)}); accepted (no-op)`,
383
+ );
384
+ break;
385
+ case "initialize":
386
+ case "reconnect":
387
+ this.sendFrame(socketId, {
388
+ jsonrpc: "2.0",
389
+ id: msg.id ?? null,
390
+ error: {
391
+ code: ERROR_INVALID_REQUEST,
392
+ message: `${method} is only valid before the handshake`,
393
+ },
394
+ });
395
+ break;
396
+ default:
397
+ if (msg.id !== undefined) {
398
+ this.sendFrame(socketId, {
399
+ jsonrpc: "2.0",
400
+ id: msg.id,
401
+ error: { code: ERROR_METHOD_NOT_FOUND, message: `unknown method: ${method}` },
402
+ });
403
+ } else {
404
+ this.log(`ignoring unknown notification ${method} on socket ${socketId}`);
405
+ }
406
+ }
407
+ }
408
+
409
+ private sendFrame(socketId: number, message: unknown): void {
410
+ this.opts.send(socketId, message);
411
+ }
412
+
413
+ // ── commands ───────────────────────────────────────────────────────────
414
+
415
+ private async handleInitialize(socketId: number, msg: RpcMessage): Promise<void> {
416
+ const socket = this.sockets.get(socketId)!;
417
+ const outcome = await handleInitialize({
418
+ params: msg.params,
419
+ serverInfo: this.opts.serverInfo,
420
+ serverSeq: this.seq.seq,
421
+ defaultDirectory: this.opts.defaultDirectory,
422
+ snapshotFor: (uri) => this.snapshotFor(uri),
423
+ });
424
+ if (!outcome.ok) {
425
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, error: outcome.error });
426
+ return;
427
+ }
428
+
429
+ const clientId = (msg.params as { clientId: string }).clientId;
430
+ const existing = this.clients.get(clientId);
431
+ if (existing && existing.socketId !== null && existing.socketId !== socketId) {
432
+ // A newer connection with the same clientId supersedes the old one.
433
+ this.log(`client ${clientId} re-initialized on socket ${socketId}; closing socket ${existing.socketId}`);
434
+ this.opts.close?.(existing.socketId, 4000, "superseded by a newer connection");
435
+ }
436
+
437
+ socket.initialized = true;
438
+ socket.version = outcome.result.protocolVersion;
439
+ socket.clientId = clientId;
440
+ this.clients.set(clientId, { version: outcome.result.protocolVersion, socketId });
441
+
442
+ // Register the initial subscriptions right after the snapshot
443
+ // computation above; no action can slip in between.
444
+ const params = isRecord(msg.params) ? msg.params : {};
445
+ const initial = Array.isArray(params["initialSubscriptions"])
446
+ ? params["initialSubscriptions"]
447
+ : [];
448
+ for (const uri of initial) {
449
+ if (typeof uri === "string" && uri.length > 0) {
450
+ this.channels.subscribe(socketId, uri);
451
+ }
452
+ }
453
+
454
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: outcome.result });
455
+ }
456
+
457
+ private async handleReconnect(socketId: number, msg: RpcMessage): Promise<void> {
458
+ const params = msg.params;
459
+ if (!isRecord(params) || params["channel"] !== ROOT_CHANNEL) {
460
+ this.sendFrame(socketId, {
461
+ jsonrpc: "2.0",
462
+ id: msg.id ?? null,
463
+ error: { code: ERROR_INVALID_PARAMS, message: `reconnect must target ${ROOT_CHANNEL}` },
464
+ });
465
+ return;
466
+ }
467
+ const clientId = params["clientId"];
468
+ const lastSeen = params["lastSeenServerSeq"];
469
+ const subscriptions = params["subscriptions"];
470
+ if (typeof clientId !== "string" || clientId.length === 0 ||
471
+ !Number.isInteger(lastSeen) || (lastSeen as number) < 0 ||
472
+ !Array.isArray(subscriptions) || !subscriptions.every((u) => typeof u === "string")) {
473
+ this.sendFrame(socketId, {
474
+ jsonrpc: "2.0",
475
+ id: msg.id ?? null,
476
+ error: { code: ERROR_INVALID_PARAMS, message: "invalid reconnect params" },
477
+ });
478
+ return;
479
+ }
480
+ const clientSubs = subscriptions as string[];
481
+
482
+ const record = this.clients.get(clientId);
483
+ const known = record !== undefined;
484
+ const version = record?.version ?? RECONNECT_DEFAULT_VERSION;
485
+
486
+ const socket = this.sockets.get(socketId)!;
487
+ socket.initialized = true;
488
+ socket.version = version;
489
+ socket.clientId = clientId;
490
+ this.clients.set(clientId, { version, socketId });
491
+
492
+ // Resolve every requested subscription; unresolvable ones are reported
493
+ // in `missing` (the client drops them — AHP lifecycle spec).
494
+ const snapshots: Snapshot[] = [];
495
+ const missing: string[] = [];
496
+ for (const uri of clientSubs) {
497
+ const snap = await this.snapshotFor(uri);
498
+ if (snap) snapshots.push(snap);
499
+ else missing.push(uri);
500
+ }
501
+ for (const uri of clientSubs) {
502
+ this.channels.subscribe(socketId, uri);
503
+ }
504
+
505
+ // Replay when the client is known and its gap is still in the window;
506
+ // otherwise fresh snapshots.
507
+ let result: ReconnectResult;
508
+ const replay = this.seq.since(lastSeen as number);
509
+ if (known && replay !== null) {
510
+ const set = new Set(clientSubs);
511
+ result = {
512
+ type: ReconnectResultType.Replay,
513
+ actions: replay.filter((a) => set.has(a.channel)),
514
+ missing,
515
+ };
516
+ } else {
517
+ result = { type: ReconnectResultType.Snapshot, snapshots };
518
+ }
519
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
520
+ }
521
+
522
+ private async handleSubscribe(socketId: number, msg: RpcMessage): Promise<void> {
523
+ const params = isRecord(msg.params) ? msg.params : {};
524
+ const uri = params["channel"];
525
+ if (typeof uri !== "string" || uri.length === 0) {
526
+ this.sendFrame(socketId, {
527
+ jsonrpc: "2.0",
528
+ id: msg.id ?? null,
529
+ error: { code: ERROR_INVALID_PARAMS, message: "subscribe requires a channel URI" },
530
+ });
531
+ return;
532
+ }
533
+ const outcome = this.channels.subscribe(socketId, uri);
534
+ if (!outcome.ok) {
535
+ this.sendFrame(socketId, {
536
+ jsonrpc: "2.0",
537
+ id: msg.id ?? null,
538
+ error: {
539
+ code:
540
+ outcome.reason === "no-such-session"
541
+ ? ERROR_SESSION_NOT_FOUND
542
+ : ERROR_INVALID_PARAMS,
543
+ message: `cannot subscribe to ${uri}`,
544
+ },
545
+ });
546
+ return;
547
+ }
548
+ const snap = await this.snapshotFor(uri);
549
+ this.sendFrame(socketId, {
550
+ jsonrpc: "2.0",
551
+ id: msg.id ?? null,
552
+ result: snap ? { snapshot: snap } : {},
553
+ });
554
+ }
555
+
556
+ private handleUnsubscribe(socketId: number, msg: RpcMessage): void {
557
+ const params = isRecord(msg.params) ? msg.params : {};
558
+ const uri = params["channel"];
559
+ if (typeof uri !== "string" || uri.length === 0) return;
560
+ this.channels.unsubscribe(socketId, uri);
561
+ }
562
+
563
+ /**
564
+ * `createSession` (AHP 1.0.0 session-channel command). Creates a real
565
+ * opencode session, seeds its session/chat stores, publishes the
566
+ * session-channel lifecycle actions, announces the session on the root
567
+ * channel, and responds `null` (per the command contract).
568
+ *
569
+ * Error codes: -32002 (no agent for the requested provider),
570
+ * -32003 (the session URI already exists).
571
+ */
572
+ private async handleCreateSession(socketId: number, msg: RpcMessage): Promise<void> {
573
+ const params = isRecord(msg.params) ? msg.params : {};
574
+ const channel = params["channel"];
575
+ if (typeof channel !== "string" || channelKind(channel) !== "session") {
576
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createSession requires an ahp-session:/… channel");
577
+ return;
578
+ }
579
+ const suffix = sessionIDOf(channel) as string;
580
+ for (const rec of this.sessions.values()) {
581
+ if (rec.channel === channel) {
582
+ this.sendError(socketId, msg.id, ERROR_SESSION_EXISTS, "Session already exists");
583
+ return;
584
+ }
585
+ }
586
+
587
+ // Resolve the provider/model for the new session.
588
+ const providers = await this.opts.facade.listCatalog();
589
+ const providerParam = params["provider"];
590
+ let provider;
591
+ if (typeof providerParam === "string" && providerParam.length > 0) {
592
+ provider = providers.find((p) => p.providerID === providerParam && p.activation !== "disabled");
593
+ if (provider === undefined) {
594
+ this.sendError(socketId, msg.id, ERROR_NO_PROVIDER, `No agent for provider ${providerParam}`);
595
+ return;
596
+ }
597
+ } else {
598
+ provider = providers.find((p) => p.activation !== "disabled");
599
+ }
600
+ const model = provider !== undefined ? firstEnabledModelRef(provider.models) : undefined;
601
+
602
+ // `activeClient` eagerly claims an active-client role; the spec requires
603
+ // the clientId to match the creating client.
604
+ let activeClients: SessionActiveClient[] = [];
605
+ const activeClientParam = params["activeClient"];
606
+ if (activeClientParam !== undefined) {
607
+ const socket = this.sockets.get(socketId);
608
+ const ac = activeClientParam as Record<string, unknown>;
609
+ if (
610
+ !isRecord(ac) ||
611
+ typeof ac["clientId"] !== "string" ||
612
+ ac["clientId"] !== socket?.clientId
613
+ ) {
614
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "activeClient.clientId must match the initializing clientId");
615
+ return;
616
+ }
617
+ activeClients = [normalizeActiveClient(ac)];
618
+ }
619
+
620
+ // opencode SessionIDs must start with "ses": pass the suffix through
621
+ // only when it already is one; otherwise let opencode mint an id and
622
+ // record the suffix→id mapping (the record key is the opencode id).
623
+ const passID = suffix.startsWith("ses") ? suffix : undefined;
624
+ const created = await this.opts.facade.createSession({ id: passID, model });
625
+
626
+ // Slow-create race: the pump may have registered this opencode session
627
+ // under its own id as an external session while `createSession` was in
628
+ // flight. Remap: drop the interim record (root/sessionRemoved) and
629
+ // re-register under the client-chosen channel below.
630
+ const interim = this.sessions.get(created.sessionID);
631
+ if (interim !== undefined && interim.channel !== channel) {
632
+ this.removeRecord(interim);
633
+ }
634
+
635
+ const agents = await this.opts.facade.listAgents();
636
+ const customizations =
637
+ mapAgentCustomizations(agents).length > 0 && this.opts.defaultDirectory !== undefined
638
+ ? [agentDirectoryCustomization(this.opts.defaultDirectory, agents)]
639
+ : undefined;
640
+ const now = new Date().toISOString();
641
+ const sessionStore = createSessionStateStore(
642
+ initialSessionState({
643
+ sessionID: created.sessionID,
644
+ provider: created.model?.providerID ?? provider?.providerID ?? "opencode",
645
+ title: created.title ?? "New Session",
646
+ activeClients,
647
+ customizations,
648
+ }),
649
+ );
650
+ const chatStore = createChatStateStore(
651
+ initialChatState({ resource: chatChannelURI(created.sessionID), title: "Chat 1", modifiedAt: now }),
652
+ );
653
+ const rec: SessionRecord = {
654
+ sessionID: created.sessionID,
655
+ channel,
656
+ provider: sessionStore.state.provider,
657
+ createdAt: new Date(created.time.created).toISOString(),
658
+ modifiedAt: new Date(created.time.updated).toISOString() > now
659
+ ? new Date(created.time.updated).toISOString()
660
+ : now,
661
+ sessionStore,
662
+ chatStore,
663
+ currentTurnId: null,
664
+ turnStartedAt: null,
665
+ turnModelRef: null,
666
+ parts: new Set(),
667
+ toolInput: new Map(),
668
+ toolName: new Map(),
669
+ toolReady: new Set(),
670
+ permissionForTool: new Map(),
671
+ toolForPermission: new Map(),
672
+ lastInbox: null,
673
+ };
674
+ this.sessions.set(created.sessionID, rec);
675
+ this.byChannel.set(channel, rec);
676
+ this.byChannel.set(chatChannelURI(created.sessionID), rec);
677
+ // The session channel carries the client-chosen suffix; the chat
678
+ // channel and the event pump carry the opencode id — both must
679
+ // resolve in the registry.
680
+ this.channels.addSession(suffix);
681
+ this.channels.addSession(created.sessionID);
682
+
683
+ // Session-channel lifecycle (server-side, no origin).
684
+ this.publish({ channel, action: { type: ActionType.SessionReady } });
685
+ this.publish({
686
+ channel,
687
+ action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chatStore.state) },
688
+ });
689
+ this.publish({
690
+ channel,
691
+ action: { type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(created.sessionID) },
692
+ });
693
+ // Root: active-session count (action, replayed) + sessionAdded (notification).
694
+ this.publish({
695
+ channel: ROOT_CHANNEL,
696
+ action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
697
+ });
698
+ this.notifyRoot("root/sessionAdded", {
699
+ channel: ROOT_CHANNEL,
700
+ summary: this.sessionSummary(rec),
701
+ });
702
+
703
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
704
+ }
705
+
706
+ /**
707
+ * `listSessions` (AHP 1.0.0 root command): all opencode sessions,
708
+ * most-recently-modified first, with in-memory cursor pagination.
709
+ * Unknown sessions are lazily registered (so their channels become
710
+ * subscribable); registration is idempotent per opencode session id.
711
+ */
712
+ private async handleListSessions(socketId: number, msg: RpcMessage): Promise<void> {
713
+ const params = isRecord(msg.params) ? msg.params : {};
714
+ const limit =
715
+ typeof params["limit"] === "number" && Number.isInteger(params["limit"]) && (params["limit"] as number) > 0
716
+ ? (params["limit"] as number)
717
+ : LIST_SESSIONS_DEFAULT_LIMIT;
718
+ let offset = 0;
719
+ if (typeof params["cursor"] === "string" && params["cursor"].length > 0) {
720
+ const parsed = Number.parseInt(params["cursor"], 10);
721
+ if (Number.isInteger(parsed) && parsed > 0) offset = parsed;
722
+ }
723
+ const listed = await this.opts.facade.listSessions();
724
+ const records: (SessionRecord | undefined)[] = [];
725
+ for (const fs of listed) {
726
+ records.push(this.registerExternal(fs) ?? this.sessions.get(fs.sessionID));
727
+ }
728
+ const sorted = records
729
+ .filter((r): r is SessionRecord => r !== undefined)
730
+ .sort((a, b) => {
731
+ const ta = this.sessions.get(a.sessionID)?.modifiedAt ?? a.modifiedAt;
732
+ const tb = this.sessions.get(b.sessionID)?.modifiedAt ?? b.modifiedAt;
733
+ return ta < tb ? 1 : ta > tb ? -1 : 0;
734
+ });
735
+ const page = sorted.slice(offset, offset + limit);
736
+ const nextOffset = offset + limit;
737
+ const result: { items: SessionSummary[]; nextCursor?: string } = {
738
+ items: page.map((rec) => this.sessionSummary(rec)),
739
+ };
740
+ if (nextOffset < sorted.length) result.nextCursor = String(nextOffset);
741
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
742
+ }
743
+
744
+ // ── client-dispatchable actions (Phase 1) ──────────────────────────────
745
+
746
+ /**
747
+ * `dispatchAction` is a notification — the response is the `action`
748
+ * notification stream itself. Phase 1 routes the client-dispatchable
749
+ * actions VS Code sends; everything else is acknowledged with a
750
+ * rejection on that stream.
751
+ */
752
+ private async handleDispatchAction(socketId: number, msg: RpcMessage): Promise<void> {
753
+ const params = isRecord(msg.params) ? msg.params : {};
754
+ const channel = params["channel"];
755
+ const clientSeq = params["clientSeq"];
756
+ const action = params["action"];
757
+ if (
758
+ typeof channel !== "string" ||
759
+ channel.length === 0 ||
760
+ !Number.isInteger(clientSeq) ||
761
+ !isRecord(action) ||
762
+ typeof action["type"] !== "string"
763
+ ) {
764
+ this.log(`malformed dispatchAction on socket ${socketId} (dropped)`);
765
+ return;
766
+ }
767
+
768
+ const socket = this.sockets.get(socketId);
769
+ const clientId = socket?.clientId ?? null;
770
+ const origin: ActionOrigin | undefined =
771
+ clientId !== null ? { clientId, clientSeq: clientSeq as number } : undefined;
772
+
773
+ const stateAction = action as unknown as StateAction;
774
+ const rejectionReason = this.dispatchRejectionReason(channel, stateAction, clientId);
775
+ if (rejectionReason !== null) {
776
+ this.echo(channel, stateAction, origin, rejectionReason);
777
+ return;
778
+ }
779
+
780
+ const kind = channelKind(channel);
781
+ if (kind !== "session" && kind !== "chat") {
782
+ this.echo(channel, stateAction, origin, `unsupported action on ${channelKind(channel)} channel: ${String(action.type)}`);
783
+ return;
784
+ }
785
+ const rec = this.byChannel.get(channel);
786
+ if (rec === undefined) {
787
+ this.echo(channel, stateAction, origin, `no such session: ${channel}`);
788
+ return;
789
+ }
790
+
791
+ // From here on every branch either echoes (accepted or rejected).
792
+ switch (stateAction.type) {
793
+ case ActionType.ChatTurnStarted:
794
+ await this.dispatchTurnStarted(rec, stateAction, origin);
795
+ return;
796
+ case ActionType.ChatPendingMessageSet:
797
+ await this.dispatchPendingMessageSet(rec, stateAction, origin);
798
+ return;
799
+ case ActionType.ChatToolCallConfirmed:
800
+ await this.dispatchToolCallConfirmed(rec, stateAction, origin);
801
+ return;
802
+ case ActionType.ChatTurnCancelled:
803
+ await this.dispatchTurnCancelled(rec, stateAction, origin);
804
+ return;
805
+ case ActionType.SessionTitleChanged:
806
+ await this.dispatchTitleChanged(rec, stateAction, origin);
807
+ return;
808
+ case ActionType.SessionActiveClientSet:
809
+ this.dispatchActiveClientSet(rec, stateAction, origin, clientId);
810
+ return;
811
+ case ActionType.SessionActiveClientRemoved:
812
+ this.dispatchActiveClientRemoved(rec, stateAction, origin, clientId);
813
+ return;
814
+ case ActionType.ChatPendingMessageRemoved:
815
+ // Honest gap: the opencode plugin surface has no inbox cancel —
816
+ // a pending (steer/queue) message cannot be withdrawn once sent.
817
+ this.echo(channel, stateAction, origin, "cannot remove a pending message: opencode has no inbox cancel");
818
+ return;
819
+ case ActionType.ChatDraftChanged:
820
+ case ActionType.ChatIsReadChanged:
821
+ case ActionType.ChatIsArchivedChanged:
822
+ case ActionType.SessionIsReadChanged:
823
+ case ActionType.SessionIsArchivedChanged:
824
+ this.echo(channel, stateAction, origin);
825
+ return;
826
+ default:
827
+ this.echo(channel, stateAction, origin, `unsupported action (Phase 1): ${String(stateAction.type)}`);
828
+ }
829
+ }
830
+
831
+ /**
832
+ * Shared pre-checks for a dispatched action; null when the action may
833
+ * proceed to per-type handling.
834
+ */
835
+ private dispatchRejectionReason(channel: string, action: StateAction, clientId: string | null): string | null {
836
+ if (channelKind(channel) === "unknown") return `unknown channel: ${channel}`;
837
+ let dispatchable: boolean;
838
+ try {
839
+ dispatchable = isClientDispatchable(action as Parameters<typeof isClientDispatchable>[0]);
840
+ } catch {
841
+ dispatchable = false;
842
+ }
843
+ if (!dispatchable) return `action ${String(action.type)} is not client-dispatchable`;
844
+ if (clientId === null) return "client is not initialized";
845
+ return null;
846
+ }
847
+
848
+ /** Publish an accepted echo (or a rejection) on the action stream. */
849
+ private echo(
850
+ channel: string,
851
+ action: StateAction,
852
+ origin: ActionOrigin | undefined,
853
+ rejectionReason?: string,
854
+ ): void {
855
+ const envelope = this.publish({
856
+ channel,
857
+ action,
858
+ origin,
859
+ ...(rejectionReason !== undefined ? { rejectionReason } : {}),
860
+ });
861
+ if (rejectionReason !== undefined && origin !== undefined) {
862
+ // A rejection must reach the dispatching socket even when it is not
863
+ // subscribed to the channel (write-ahead dispatch: the client applied
864
+ // the action optimistically and needs the rejection to roll it back).
865
+ const socketId = this.socketIdForClient(origin.clientId);
866
+ if (socketId !== undefined && !this.channels.socketsSubscribedTo(channel).includes(socketId)) {
867
+ this.opts.send(socketId, { jsonrpc: "2.0", method: "action", params: envelope });
868
+ }
869
+ }
870
+ }
871
+
872
+ /** The socket currently bound to a clientId (rejection delivery target). */
873
+ private socketIdForClient(clientId: string): number | undefined {
874
+ for (const [socketId, socket] of this.sockets) {
875
+ if (socket.clientId === clientId) return socketId;
876
+ }
877
+ return undefined;
878
+ }
879
+
880
+ private async dispatchTurnStarted(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
881
+ const chatURI = chatChannelURI(rec.sessionID);
882
+ const a = action as ChatTurnStartedAction;
883
+ const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
884
+ const message =
885
+ isRecord(a.message) && typeof a.message["text"] === "string"
886
+ ? (a.message as unknown as Message)
887
+ : null;
888
+ if (turnId === null || message === null) {
889
+ this.echo(chatURI, action, origin, "invalid chat/turnStarted params");
890
+ return;
891
+ }
892
+ // `startedAt` is required on the wire (the reducer uses it for the
893
+ // chat's `modifiedAt`); fall back to the host clock when the client
894
+ // did not supply a parseable one.
895
+ const normalized: ChatTurnStartedAction =
896
+ typeof a.startedAt === "string" && !Number.isNaN(Date.parse(a.startedAt))
897
+ ? a
898
+ : { ...a, startedAt: new Date().toISOString() };
899
+ if (rec.chatStore.state.activeTurn !== undefined) {
900
+ this.echo(
901
+ chatURI,
902
+ action,
903
+ origin,
904
+ "a turn is already active; follow-up messages go via chat/pendingMessageSet",
905
+ );
906
+ return;
907
+ }
908
+
909
+ // Apply the message's model/agent selection before the prompt
910
+ // (`SessionPromptInput` carries no model/agent fields).
911
+ try {
912
+ if (message.model?.id !== undefined && message.model.id.includes("/")) {
913
+ const sep = message.model.id.indexOf("/");
914
+ const providerID = message.model.id.slice(0, sep);
915
+ const modelID = message.model.id.slice(sep + 1);
916
+ if (providerID.length > 0 && modelID.length > 0) {
917
+ await this.opts.facade.switchModel({ sessionID: rec.sessionID, model: { providerID, modelID } });
918
+ }
919
+ }
920
+ if (message.agent?.uri !== undefined) {
921
+ const agentID = agentIDFromUri(message.agent.uri);
922
+ if (agentID !== null) {
923
+ await this.opts.facade.switchAgent({ sessionID: rec.sessionID, agent: agentID });
924
+ }
925
+ }
926
+ } catch (err) {
927
+ this.echo(chatURI, action, origin, `failed to apply model/agent selection: ${errorMessage(err)}`);
928
+ return;
929
+ }
930
+
931
+ // Write-ahead: claim the turn BEFORE the prompt so the
932
+ // `session.execution.started` event joins it even when it races the
933
+ // prompt's resolve; revert on failure.
934
+ rec.currentTurnId = turnId;
935
+ rec.turnStartedAt = Date.now();
936
+ try {
937
+ await this.opts.facade.prompt({ sessionID: rec.sessionID, text: message.text });
938
+ } catch (err) {
939
+ rec.currentTurnId = null;
940
+ rec.turnStartedAt = null;
941
+ this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
942
+ return;
943
+ }
944
+ this.echo(chatURI, normalized, origin);
945
+ }
946
+
947
+ private async dispatchPendingMessageSet(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
948
+ const chatURI = chatChannelURI(rec.sessionID);
949
+ const a = action as { kind?: unknown; id?: unknown; message?: unknown };
950
+ const kind = a.kind === "steering" || a.kind === "queued" ? a.kind : null;
951
+ const id = typeof a.id === "string" && a.id.length > 0 ? a.id : null;
952
+ const message =
953
+ isRecord(a.message) && typeof a.message["text"] === "string"
954
+ ? (a.message as unknown as Message)
955
+ : null;
956
+ if (kind === null || id === null || message === null) {
957
+ this.echo(chatURI, action, origin, "invalid chat/pendingMessageSet params");
958
+ return;
959
+ }
960
+ const hasActiveTurn = rec.chatStore.state.activeTurn !== undefined;
961
+ // steer → delivery "steer" (only while a turn is active); queued →
962
+ // delivery "queue"; a steering message with no active turn falls back
963
+ // to a plain prompt (it becomes the next turn).
964
+ const delivery: FacadeDelivery | undefined = hasActiveTurn
965
+ ? kind === "steering"
966
+ ? "steer"
967
+ : "queue"
968
+ : undefined;
969
+ try {
970
+ await this.opts.facade.prompt({ sessionID: rec.sessionID, text: message.text, delivery });
971
+ } catch (err) {
972
+ this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
973
+ return;
974
+ }
975
+ if (hasActiveTurn) {
976
+ this.echo(chatURI, action, origin);
977
+ return;
978
+ }
979
+ // No active turn: the message starts a turn right now. Echo the
980
+ // pending-message first, then a host-minted turnStarted carrying
981
+ // `queuedMessageId` — the reducer dequeues it.
982
+ this.echo(chatURI, action, origin);
983
+ const turnId = this.mintTurnId();
984
+ rec.currentTurnId = turnId;
985
+ rec.turnStartedAt = Date.now();
986
+ this.publish({
987
+ channel: chatURI,
988
+ action: {
989
+ type: ActionType.ChatTurnStarted,
990
+ turnId,
991
+ startedAt: new Date().toISOString(),
992
+ message,
993
+ queuedMessageId: id,
994
+ },
995
+ });
996
+ }
997
+
998
+ private async dispatchToolCallConfirmed(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
999
+ const chatURI = chatChannelURI(rec.sessionID);
1000
+ const a = action as ChatToolCallConfirmedAction;
1001
+ const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
1002
+ if (toolCallId === null) {
1003
+ this.echo(chatURI, action, origin, "invalid chat/toolCallConfirmed params");
1004
+ return;
1005
+ }
1006
+ const permissionID = rec.permissionForTool.get(toolCallId);
1007
+ if (permissionID === undefined) {
1008
+ this.echo(chatURI, action, origin, `no pending permission for tool call ${toolCallId}`);
1009
+ return;
1010
+ }
1011
+ try {
1012
+ await this.opts.facade.replyPermission({
1013
+ sessionID: rec.sessionID,
1014
+ requestID: permissionID,
1015
+ decision: a.approved === true ? "once" : "reject",
1016
+ });
1017
+ } catch (err) {
1018
+ this.echo(chatURI, action, origin, `permission reply failed: ${errorMessage(err)}`);
1019
+ return;
1020
+ }
1021
+ // Echo the confirmation (reducer → running/cancelled), then clear the
1022
+ // session-level input request. The `permission.replied` event is a
1023
+ // safety net (its tracking is already gone → no-op).
1024
+ this.echo(chatURI, action, origin);
1025
+ this.publish({
1026
+ channel: rec.channel,
1027
+ action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
1028
+ });
1029
+ rec.permissionForTool.delete(toolCallId);
1030
+ rec.toolForPermission.delete(permissionID);
1031
+ }
1032
+
1033
+ private async dispatchTurnCancelled(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1034
+ const chatURI = chatChannelURI(rec.sessionID);
1035
+ const a = action as ChatTurnCancelledAction;
1036
+ const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
1037
+ const active = rec.chatStore.state.activeTurn;
1038
+ if (turnId === null || active === undefined || active.id !== turnId) {
1039
+ this.echo(chatURI, action, origin, "no active turn to cancel");
1040
+ return;
1041
+ }
1042
+ try {
1043
+ await this.opts.facade.interrupt({ sessionID: rec.sessionID });
1044
+ } catch (err) {
1045
+ this.echo(chatURI, action, origin, `interrupt failed: ${errorMessage(err)}`);
1046
+ return;
1047
+ }
1048
+ // `duration` is required on the wire (the reducer derives the final
1049
+ // `modifiedAt` from it); the host clock is authoritative when the
1050
+ // client did not supply one.
1051
+ const duration =
1052
+ typeof a.duration === "number" && Number.isFinite(a.duration) ? a.duration : this.turnDuration(rec);
1053
+ this.echo(chatURI, { ...a, duration }, origin);
1054
+ // The opencode `session.execution.interrupted` event finds no active
1055
+ // turn after the echo finalized it (skipped); run the queued/steering
1056
+ // handoff now, on the host side.
1057
+ this.finishTurn(rec);
1058
+ }
1059
+
1060
+ private async dispatchTitleChanged(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1061
+ const a = action as { title?: unknown };
1062
+ const title = typeof a.title === "string" && a.title.length > 0 ? a.title : null;
1063
+ if (title === null) {
1064
+ this.echo(rec.channel, action, origin, "invalid session/titleChanged params");
1065
+ return;
1066
+ }
1067
+ try {
1068
+ await this.opts.facade.rename({ sessionID: rec.sessionID, title });
1069
+ } catch (err) {
1070
+ this.echo(rec.channel, action, origin, `rename failed: ${errorMessage(err)}`);
1071
+ return;
1072
+ }
1073
+ this.echo(rec.channel, action, origin);
1074
+ }
1075
+
1076
+ private dispatchActiveClientSet(
1077
+ rec: SessionRecord,
1078
+ action: StateAction,
1079
+ origin: ActionOrigin | undefined,
1080
+ clientId: string | null,
1081
+ ): void {
1082
+ const a = action as { activeClient?: unknown };
1083
+ const ac = a.activeClient;
1084
+ if (!isRecord(ac) || typeof ac["clientId"] !== "string" || (clientId !== null && ac["clientId"] !== clientId)) {
1085
+ this.echo(rec.channel, action, origin, "activeClient.clientId must match the dispatching client");
1086
+ return;
1087
+ }
1088
+ const tools = Array.isArray(ac["tools"]) ? (ac["tools"] as ToolDefinition[]) : [];
1089
+ const normalized: SessionActiveClient = {
1090
+ clientId: ac["clientId"] as string,
1091
+ tools,
1092
+ ...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
1093
+ };
1094
+ this.publish({
1095
+ channel: rec.channel,
1096
+ action: { type: ActionType.SessionActiveClientSet, activeClient: normalized },
1097
+ origin,
1098
+ });
1099
+ }
1100
+
1101
+ private dispatchActiveClientRemoved(
1102
+ rec: SessionRecord,
1103
+ action: StateAction,
1104
+ origin: ActionOrigin | undefined,
1105
+ clientId: string | null,
1106
+ ): void {
1107
+ const a = action as { clientId?: unknown };
1108
+ if (typeof a.clientId !== "string" || (clientId !== null && a.clientId !== clientId)) {
1109
+ this.echo(rec.channel, action, origin, "clientId must match the dispatching client");
1110
+ return;
1111
+ }
1112
+ this.echo(rec.channel, action, origin);
1113
+ }
1114
+
1115
+ // ── opencode event pump handlers ───────────────────────────────────────
1116
+
1117
+ private async handleEvent(ev: FacadeEvent): Promise<void> {
1118
+ if (ev.type === "session.created") {
1119
+ if (this.sessions.has(ev.sessionID)) return;
1120
+ // Deferred registration: a concurrent `createSession` may still be
1121
+ // resolving for this opencode session under a client-chosen channel;
1122
+ // the grace + existence check avoids the double registration, and
1123
+ // the delete+recreate remap in `handleCreateSession` heals the slow
1124
+ // path.
1125
+ const sessionID = ev.sessionID;
1126
+ setTimeout(() => {
1127
+ void this.registerExternalDeferred(sessionID).catch((err) =>
1128
+ this.log(`external session registration failed: ${errorMessage(err)}`),
1129
+ );
1130
+ }, EXTERNAL_REGISTER_GRACE_MS);
1131
+ return;
1132
+ }
1133
+
1134
+ const rec = this.sessions.get(ev.sessionID);
1135
+ if (rec === undefined) return; // only session.created registers sessions
1136
+
1137
+ const chatURI = chatChannelURI(rec.sessionID);
1138
+ switch (ev.type) {
1139
+ case "session.deleted":
1140
+ this.removeRecord(rec);
1141
+ return;
1142
+ case "session.renamed":
1143
+ this.publish({ channel: rec.channel, action: { type: ActionType.SessionTitleChanged, title: ev.title } });
1144
+ return;
1145
+ case "inbox.enqueued":
1146
+ rec.lastInbox = { text: ev.text, delivery: ev.delivery };
1147
+ return;
1148
+ case "inbox.delivered":
1149
+ // Steering consumption is handled at turn end (finishTurn).
1150
+ return;
1151
+ case "execution.started":
1152
+ if (rec.currentTurnId !== null) return; // write-ahead already claimed the turn
1153
+ // Orphan turn (an external TUI prompt, or a handoff this host did
1154
+ // not initiate): start it with the last-seen inbox message.
1155
+ this.startTurn(rec, rec.lastInbox !== null ? userMessage(rec.lastInbox.text) : userMessage(""));
1156
+ return;
1157
+ case "execution.succeeded":
1158
+ if (rec.currentTurnId === null) return;
1159
+ this.publish({
1160
+ channel: chatURI,
1161
+ action: { type: ActionType.ChatTurnComplete, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
1162
+ });
1163
+ this.finishTurn(rec);
1164
+ return;
1165
+ case "execution.failed":
1166
+ if (rec.currentTurnId === null) return;
1167
+ const part: ErrorResponsePart = {
1168
+ kind: ResponsePartKind.Error,
1169
+ error: { errorType: ev.error.type, message: ev.error.message },
1170
+ };
1171
+ this.publish({
1172
+ channel: chatURI,
1173
+ action: { type: ActionType.ChatError, turnId: rec.currentTurnId, duration: this.turnDuration(rec), part },
1174
+ });
1175
+ this.finishTurn(rec);
1176
+ return;
1177
+ case "execution.interrupted":
1178
+ // Skipped when the client's own `chat/turnCancelled` echo already
1179
+ // finalized the turn (currentTurnId is null).
1180
+ if (rec.currentTurnId === null) return;
1181
+ this.publish({
1182
+ channel: chatURI,
1183
+ action: { type: ActionType.ChatTurnCancelled, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
1184
+ });
1185
+ this.finishTurn(rec);
1186
+ return;
1187
+ case "step.started":
1188
+ rec.turnModelRef = `${ev.model.providerID}/${ev.model.modelID}`;
1189
+ return;
1190
+ case "text.delta":
1191
+ case "reasoning.delta": {
1192
+ if (rec.currentTurnId === null) return;
1193
+ const kind = ev.type === "text.delta" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
1194
+ const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
1195
+ const first = !rec.parts.has(key);
1196
+ rec.parts.add(key);
1197
+ const partId = `part-${key}`;
1198
+ if (first) {
1199
+ // Lazily emit the part on the first delta; it carries the
1200
+ // initial content.
1201
+ this.publish({
1202
+ channel: chatURI,
1203
+ action: {
1204
+ type: ActionType.ChatResponsePart,
1205
+ turnId: rec.currentTurnId,
1206
+ part: { kind, id: partId, content: ev.delta },
1207
+ },
1208
+ });
1209
+ } else {
1210
+ this.publish({
1211
+ channel: chatURI,
1212
+ action:
1213
+ kind === ResponsePartKind.Markdown
1214
+ ? { type: ActionType.ChatDelta, turnId: rec.currentTurnId, partId, content: ev.delta }
1215
+ : { type: ActionType.ChatReasoning, turnId: rec.currentTurnId, partId, content: ev.delta },
1216
+ });
1217
+ }
1218
+ return;
1219
+ }
1220
+ case "text.ended":
1221
+ case "reasoning.ended": {
1222
+ if (rec.currentTurnId === null) return;
1223
+ // Fallback for non-streaming providers that emit only the final
1224
+ // text: if no delta opened the part, emit it now with the full text.
1225
+ const kind = ev.type === "text.ended" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
1226
+ const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
1227
+ if (!rec.parts.has(key)) {
1228
+ rec.parts.add(key);
1229
+ this.publish({
1230
+ channel: chatURI,
1231
+ action: {
1232
+ type: ActionType.ChatResponsePart,
1233
+ turnId: rec.currentTurnId,
1234
+ part: { kind, id: `part-${key}`, content: ev.text },
1235
+ },
1236
+ });
1237
+ }
1238
+ return;
1239
+ }
1240
+ case "tool.input.started":
1241
+ if (rec.currentTurnId === null) {
1242
+ this.log(`tool.input.started outside a turn (session ${rec.sessionID}, tool ${ev.name}); ignored`);
1243
+ return;
1244
+ }
1245
+ rec.toolName.set(ev.id, ev.name);
1246
+ this.publish({
1247
+ channel: chatURI,
1248
+ action: {
1249
+ type: ActionType.ChatToolCallStart,
1250
+ turnId: rec.currentTurnId,
1251
+ toolCallId: ev.id,
1252
+ toolName: ev.name,
1253
+ displayName: displayNameFor(ev.name),
1254
+ },
1255
+ });
1256
+ return;
1257
+ case "tool.input.ended":
1258
+ rec.toolInput.set(ev.id, ev.text);
1259
+ return;
1260
+ case "tool.progress":
1261
+ // First sign the tool is actually running (opencode auto-approved):
1262
+ // finalize the tool call as running.
1263
+ this.ensureToolReady(rec, ev.id, false);
1264
+ return;
1265
+ case "tool.success": {
1266
+ if (rec.currentTurnId === null) return;
1267
+ this.ensureToolReady(rec, ev.id, false);
1268
+ if (this.toolCallTerminal(rec, ev.id)) return; // e.g. denied → already cancelled
1269
+ const name = rec.toolName.get(ev.id) ?? "tool";
1270
+ const input = rec.toolInput.get(ev.id);
1271
+ this.publish({
1272
+ channel: chatURI,
1273
+ action: {
1274
+ type: ActionType.ChatToolCallComplete,
1275
+ turnId: rec.currentTurnId,
1276
+ toolCallId: ev.id,
1277
+ result: {
1278
+ success: true,
1279
+ pastTenseMessage: pastTenseMessageFor(name, input),
1280
+ content: mapToolResultContent(ev.content),
1281
+ },
1282
+ },
1283
+ });
1284
+ this.clearToolTracking(rec, ev.id);
1285
+ return;
1286
+ }
1287
+ case "tool.failed": {
1288
+ if (rec.currentTurnId === null) return;
1289
+ this.ensureToolReady(rec, ev.id, false);
1290
+ if (this.toolCallTerminal(rec, ev.id)) return;
1291
+ const name = rec.toolName.get(ev.id) ?? "tool";
1292
+ const input = rec.toolInput.get(ev.id);
1293
+ this.publish({
1294
+ channel: chatURI,
1295
+ action: {
1296
+ type: ActionType.ChatToolCallComplete,
1297
+ turnId: rec.currentTurnId,
1298
+ toolCallId: ev.id,
1299
+ result: {
1300
+ success: false,
1301
+ pastTenseMessage: pastTenseMessageFor(name, input),
1302
+ error: { message: ev.error.message },
1303
+ },
1304
+ },
1305
+ });
1306
+ this.clearToolTracking(rec, ev.id);
1307
+ return;
1308
+ }
1309
+ case "usage.updated":
1310
+ // Session-cumulative tokens; the chat reducer replaces the turn's
1311
+ // usage, so the latest cumulative values are the turn's view.
1312
+ if (rec.currentTurnId === null) return;
1313
+ this.publish({
1314
+ channel: chatURI,
1315
+ action: {
1316
+ type: ActionType.ChatUsage,
1317
+ turnId: rec.currentTurnId,
1318
+ usage: {
1319
+ inputTokens: ev.tokens.input,
1320
+ outputTokens: ev.tokens.output,
1321
+ cacheReadTokens: ev.tokens.cache.read,
1322
+ ...(rec.turnModelRef !== null ? { model: rec.turnModelRef } : {}),
1323
+ },
1324
+ },
1325
+ });
1326
+ return;
1327
+ case "permission.asked":
1328
+ // Only tool-sourced permissions map to a tool confirmation;
1329
+ // anything else has no AHP counterpart in this MVP (gap).
1330
+ if (ev.source === undefined) {
1331
+ this.log(`ignoring non-tool permission.asked ${ev.id} (action: ${ev.action})`);
1332
+ return;
1333
+ }
1334
+ const toolCallId = ev.source.id;
1335
+ rec.permissionForTool.set(toolCallId, ev.id);
1336
+ rec.toolForPermission.set(ev.id, toolCallId);
1337
+ this.ensureToolReady(rec, toolCallId, true);
1338
+ const pending = this.pendingToolCall(rec, toolCallId);
1339
+ if (pending !== null && rec.currentTurnId !== null) {
1340
+ const request: SessionToolConfirmationRequest = {
1341
+ id: toolCallId,
1342
+ chat: chatURI,
1343
+ kind: SessionInputRequestKind.ToolConfirmation,
1344
+ turnId: rec.currentTurnId,
1345
+ toolCall: pending,
1346
+ };
1347
+ this.publish({
1348
+ channel: rec.channel,
1349
+ action: { type: ActionType.SessionInputNeededSet, request },
1350
+ });
1351
+ }
1352
+ return;
1353
+ case "permission.replied": {
1354
+ const toolCallId = rec.toolForPermission.get(ev.requestID);
1355
+ rec.toolForPermission.delete(ev.requestID);
1356
+ if (toolCallId !== undefined) {
1357
+ rec.permissionForTool.delete(toolCallId);
1358
+ // Safety net: the client's `chat/toolCallConfirmed` normally
1359
+ // removes the input request first; this covers the reply
1360
+ // arriving without (or before) the echo.
1361
+ this.publish({
1362
+ channel: rec.channel,
1363
+ action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
1364
+ });
1365
+ }
1366
+ return;
1367
+ }
1368
+ default:
1369
+ return;
1370
+ }
1371
+ }
1372
+
1373
+ // ── turn helpers ───────────────────────────────────────────────────────
1374
+
1375
+ private mintTurnId(): string {
1376
+ this.turnCounter += 1;
1377
+ return `turn_${Date.now().toString(36)}_${this.turnCounter.toString(36)}`;
1378
+ }
1379
+
1380
+ private turnDuration(rec: SessionRecord): number {
1381
+ return Math.max(0, Date.now() - (rec.turnStartedAt ?? Date.now()));
1382
+ }
1383
+
1384
+ /** Claim a turn (write-ahead) and publish `chat/turnStarted`. */
1385
+ private startTurn(rec: SessionRecord, message: Message, queuedMessageId?: string): void {
1386
+ const turnId = this.mintTurnId();
1387
+ rec.currentTurnId = turnId;
1388
+ rec.turnStartedAt = Date.now();
1389
+ this.publish({
1390
+ channel: chatChannelURI(rec.sessionID),
1391
+ action: {
1392
+ type: ActionType.ChatTurnStarted,
1393
+ turnId,
1394
+ startedAt: new Date().toISOString(),
1395
+ message,
1396
+ ...(queuedMessageId !== undefined ? { queuedMessageId } : {}),
1397
+ },
1398
+ });
1399
+ }
1400
+
1401
+ /**
1402
+ * After a turn terminal: clear the steering message opencode consumed
1403
+ * during the turn, and auto-start the next turn from the queue (the
1404
+ * queued prompt was already sent with `delivery: "queue"` — opencode
1405
+ * starts it automatically; this only updates the AHP state).
1406
+ */
1407
+ private finishTurn(rec: SessionRecord): void {
1408
+ rec.currentTurnId = null;
1409
+ rec.turnStartedAt = null;
1410
+ const state = rec.chatStore.state;
1411
+ if (state.steeringMessage !== undefined) {
1412
+ this.publish({
1413
+ channel: chatChannelURI(rec.sessionID),
1414
+ action: {
1415
+ type: ActionType.ChatPendingMessageRemoved,
1416
+ kind: PendingMessageKind.Steering,
1417
+ id: state.steeringMessage.id,
1418
+ },
1419
+ });
1420
+ }
1421
+ const queued = state.queuedMessages;
1422
+ if (queued !== undefined && queued.length > 0) {
1423
+ const next = queued[0]!;
1424
+ this.startTurn(rec, next.message, next.id);
1425
+ } else if (rec.lastInbox !== null && rec.lastInbox.delivery === "queue") {
1426
+ // A queued prompt from outside AHP (e.g. the TUI).
1427
+ this.startTurn(rec, userMessage(rec.lastInbox.text));
1428
+ }
1429
+ }
1430
+
1431
+ /**
1432
+ * Lazily publish `chat/toolCallReady` for a tool call (first of
1433
+ * progress/success/failed/permission.asked):
1434
+ * - permission trigger → no `confirmed` → the reducer parks it in
1435
+ * `pending-confirmation` (the caller then raises `inputNeededSet`);
1436
+ * - otherwise → `confirmed: "not-needed"` → straight to `running`
1437
+ * (opencode auto-approved).
1438
+ */
1439
+ private ensureToolReady(rec: SessionRecord, toolCallId: string, permission: boolean): void {
1440
+ if (rec.toolReady.has(toolCallId) || rec.currentTurnId === null) return;
1441
+ rec.toolReady.add(toolCallId);
1442
+ const name = rec.toolName.get(toolCallId) ?? "tool";
1443
+ const input = rec.toolInput.get(toolCallId);
1444
+ this.publish({
1445
+ channel: chatChannelURI(rec.sessionID),
1446
+ action: {
1447
+ type: ActionType.ChatToolCallReady,
1448
+ turnId: rec.currentTurnId,
1449
+ toolCallId,
1450
+ invocationMessage: invocationMessageFor(name, input),
1451
+ toolInput: input,
1452
+ ...(permission ? {} : { confirmed: ToolCallConfirmationReason.NotNeeded }),
1453
+ },
1454
+ });
1455
+ }
1456
+
1457
+ /** The live tool-call state in the current turn, or null when absent. */
1458
+ private toolCallState(rec: SessionRecord, toolCallId: string): ToolCallState | null {
1459
+ const turn = rec.chatStore.state.activeTurn;
1460
+ if (turn === undefined) return null;
1461
+ for (const part of turn.responseParts) {
1462
+ if (part.kind === ResponsePartKind.ToolCall && part.toolCall.toolCallId === toolCallId) {
1463
+ return part.toolCall;
1464
+ }
1465
+ }
1466
+ return null;
1467
+ }
1468
+
1469
+ /**
1470
+ * The tool call's state when it is awaiting confirmation (the
1471
+ * `SessionToolConfirmationRequest.toolCall` shape), or null otherwise.
1472
+ */
1473
+ private pendingToolCall(rec: SessionRecord, toolCallId: string): ToolCallConfirmationState | null {
1474
+ const tc = this.toolCallState(rec, toolCallId);
1475
+ if (tc === null) return null;
1476
+ if (tc.status === ToolCallStatus.PendingConfirmation || tc.status === ToolCallStatus.PendingResultConfirmation) {
1477
+ return tc;
1478
+ }
1479
+ return null;
1480
+ }
1481
+
1482
+ /** True when the tool call already left the ready states (completed/cancelled). */
1483
+ private toolCallTerminal(rec: SessionRecord, toolCallId: string): boolean {
1484
+ const tc = this.toolCallState(rec, toolCallId);
1485
+ return tc !== null && (tc.status === ToolCallStatus.Completed || tc.status === ToolCallStatus.Cancelled);
1486
+ }
1487
+
1488
+ private clearToolTracking(rec: SessionRecord, toolCallId: string): void {
1489
+ rec.toolInput.delete(toolCallId);
1490
+ rec.toolName.delete(toolCallId);
1491
+ rec.toolReady.delete(toolCallId);
1492
+ }
1493
+
1494
+ // ── session registration / removal ─────────────────────────────────────
1495
+
1496
+ /**
1497
+ * Verify a `session.created` event via the session API and register the
1498
+ * session under its own id as the channel suffix (the suffix starts
1499
+ * with "ses" — opencode ids are valid suffixes). No-op when the session
1500
+ * is gone, already registered, or a createSession remap is pending.
1501
+ */
1502
+ private async registerExternalDeferred(sessionID: string): Promise<void> {
1503
+ if (this.sessions.has(sessionID)) return;
1504
+ let fs: FacadeSession | null;
1505
+ try {
1506
+ fs = await this.opts.facade.getSession(sessionID);
1507
+ } catch {
1508
+ return;
1509
+ }
1510
+ if (fs === null || this.sessions.has(fs.sessionID)) return;
1511
+ this.registerExternal(fs);
1512
+ }
1513
+
1514
+ /**
1515
+ * Register an opencode session the host did not create (TUI, another
1516
+ * client). Applied directly to the fresh stores (no seq, no actions) —
1517
+ * the registration is server-side bookkeeping, not a client-visible
1518
+ * state transition; the root announcement carries the lifecycle.
1519
+ */
1520
+ private registerExternal(fs: FacadeSession): SessionRecord | undefined {
1521
+ const existing = this.sessions.get(fs.sessionID);
1522
+ if (existing !== undefined) return existing;
1523
+ const channel = sessionChannelURI(fs.sessionID);
1524
+ const modifiedAt = new Date(fs.time.updated).toISOString();
1525
+ const sessionStore = createSessionStateStore(
1526
+ initialSessionState({
1527
+ sessionID: fs.sessionID,
1528
+ provider: fs.model?.providerID ?? "opencode",
1529
+ title: fs.title ?? "New Session",
1530
+ status: fs.archived
1531
+ ? ((SessionStatus.Idle | SessionStatus.IsRead | SessionStatus.IsArchived) as SessionStatus)
1532
+ : undefined, // Idle | IsRead | IsArchived
1533
+ }),
1534
+ );
1535
+ const chatStore = createChatStateStore(
1536
+ initialChatState({ resource: chatChannelURI(fs.sessionID), title: "Chat 1", modifiedAt }),
1537
+ );
1538
+ sessionStore.apply({ type: ActionType.SessionReady });
1539
+ sessionStore.apply({ type: ActionType.SessionChatAdded, summary: chatSummaryOf(chatStore.state) });
1540
+ sessionStore.apply({ type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(fs.sessionID) });
1541
+ const rec: SessionRecord = {
1542
+ sessionID: fs.sessionID,
1543
+ channel,
1544
+ provider: sessionStore.state.provider,
1545
+ createdAt: new Date(fs.time.created).toISOString(),
1546
+ modifiedAt,
1547
+ sessionStore,
1548
+ chatStore,
1549
+ currentTurnId: null,
1550
+ turnStartedAt: null,
1551
+ turnModelRef: null,
1552
+ parts: new Set(),
1553
+ toolInput: new Map(),
1554
+ toolName: new Map(),
1555
+ toolReady: new Set(),
1556
+ permissionForTool: new Map(),
1557
+ toolForPermission: new Map(),
1558
+ lastInbox: null,
1559
+ };
1560
+ this.sessions.set(fs.sessionID, rec);
1561
+ this.byChannel.set(channel, rec);
1562
+ this.byChannel.set(chatChannelURI(fs.sessionID), rec);
1563
+ this.channels.addSession(fs.sessionID);
1564
+ this.publish({
1565
+ channel: ROOT_CHANNEL,
1566
+ action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
1567
+ });
1568
+ this.notifyRoot("root/sessionAdded", { channel: ROOT_CHANNEL, summary: this.sessionSummary(rec) });
1569
+ return rec;
1570
+ }
1571
+
1572
+ /** Drop a session record and announce the removal on the root channel. */
1573
+ private removeRecord(rec: SessionRecord): void {
1574
+ this.sessions.delete(rec.sessionID);
1575
+ this.byChannel.delete(rec.channel);
1576
+ this.byChannel.delete(chatChannelURI(rec.sessionID));
1577
+ const id = sessionIDOf(rec.channel);
1578
+ if (id !== null) this.channels.removeSession(id);
1579
+ this.channels.removeSession(rec.sessionID);
1580
+ this.publish({
1581
+ channel: ROOT_CHANNEL,
1582
+ action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
1583
+ });
1584
+ this.notifyRoot("root/sessionRemoved", { channel: ROOT_CHANNEL, session: rec.channel });
1585
+ }
1586
+
1587
+ // ── state / publishing ─────────────────────────────────────────────────
1588
+
1589
+ /**
1590
+ * Snapshot for a channel URI, or null when the channel is not
1591
+ * subscribable right now.
1592
+ *
1593
+ * Root snapshots re-derive the catalog from the facade on every call
1594
+ * (registry reads reflect every registration so far; in-process reads
1595
+ * are cheap). Session/chat snapshots read the official-reducer stores.
1596
+ */
1597
+ private async snapshotFor(uri: string): Promise<Snapshot | null> {
1598
+ const kind = channelKind(uri);
1599
+ if (kind === "unknown") return null;
1600
+ if (kind !== "root") {
1601
+ const rec = this.byChannel.get(uri);
1602
+ if (rec === undefined) return null;
1603
+ if (uri === rec.channel) {
1604
+ return { resource: uri, state: rec.sessionStore.state, fromSeq: this.seq.seq };
1605
+ }
1606
+ if (uri === chatChannelURI(rec.sessionID)) {
1607
+ return { resource: uri, state: rec.chatStore.state, fromSeq: this.seq.seq };
1608
+ }
1609
+ return null;
1610
+ }
1611
+ const [providers, agents] = await Promise.all([
1612
+ this.opts.facade.listCatalog(),
1613
+ this.opts.facade.listAgents(),
1614
+ ]);
1615
+ const catalog = mapCatalog(providers, agents, this.opts.defaultDirectory);
1616
+ if (!sameAgents(this.state.state.agents, catalog)) {
1617
+ this.state.apply({ type: ActionType.RootAgentsChanged, agents: catalog });
1618
+ }
1619
+ return { resource: ROOT_CHANNEL, state: this.state.state, fromSeq: this.seq.seq };
1620
+ }
1621
+
1622
+ /** The denormalized `SessionSummary` view of a record. */
1623
+ private sessionSummary(rec: SessionRecord): SessionSummary {
1624
+ const s = rec.sessionStore.state;
1625
+ const c = rec.chatStore.state;
1626
+ const modifiedAt = c.modifiedAt > rec.modifiedAt ? c.modifiedAt : rec.modifiedAt;
1627
+ return buildSessionSummary({
1628
+ channel: rec.channel,
1629
+ provider: rec.provider,
1630
+ title: s.title,
1631
+ status: s.status,
1632
+ activity: s.activity,
1633
+ createdAt: rec.createdAt,
1634
+ modifiedAt,
1635
+ chat: chatSummaryOf(c),
1636
+ defaultChat: chatChannelURI(rec.sessionID),
1637
+ });
1638
+ }
1639
+
1640
+ /**
1641
+ * Assign a global seq, update state for accepted actions, retain for
1642
+ * replay. Session/chat actions apply to the per-session stores through
1643
+ * the official reducers; a changed chat summary is propagated to the
1644
+ * session store via `session/chatUpdated`, and any summary-level change
1645
+ * is announced on the root channel (notification).
1646
+ */
1647
+ private publish(draft: {
1648
+ channel: string;
1649
+ action: StateAction;
1650
+ origin?: ActionOrigin;
1651
+ rejectionReason?: string;
1652
+ }): ActionEnvelope {
1653
+ const envelope = this.seq.publish(draft);
1654
+ if (draft.rejectionReason === undefined) {
1655
+ const kind = channelKind(draft.channel);
1656
+ if (kind === "root") {
1657
+ this.state.apply(draft.action as RootAction);
1658
+ } else {
1659
+ // byChannel, not sessions.get(sessionIDOf(…)): the channel suffix
1660
+ // is not always the opencode session id (client-chosen suffixes).
1661
+ const rec = this.byChannel.get(draft.channel);
1662
+ if (rec !== undefined) {
1663
+ const before = this.sessionSummary(rec);
1664
+ if (kind === "session") rec.sessionStore.apply(draft.action as SessionAction);
1665
+ else rec.chatStore.apply(draft.action as ChatAction);
1666
+ if (kind === "chat") this.syncChatSummary(rec);
1667
+ const after = this.sessionSummary(rec);
1668
+ this.maybeNotifySummaryChanged(rec, before, after);
1669
+ }
1670
+ }
1671
+ }
1672
+ // Every published action — accepted and rejected alike — is an
1673
+ // `action` notification on its channel to the subscribers.
1674
+ this.notifyAction(envelope);
1675
+ return envelope;
1676
+ }
1677
+
1678
+ /**
1679
+ * Propagate a changed chat summary into the session store's chat catalog
1680
+ * (`session/chatUpdated`) — the session status itself is only
1681
+ * reducer-reachable for read/archive/input-needed bits, so the chat
1682
+ * summary is the activity source of truth.
1683
+ */
1684
+ private syncChatSummary(rec: SessionRecord): void {
1685
+ const chat = rec.chatStore.state;
1686
+ const entry = rec.sessionStore.state.chats.find((c) => c.resource === chat.resource);
1687
+ if (entry === undefined) return;
1688
+ const next = chatSummaryOf(chat);
1689
+ const changes: Record<string, unknown> = {};
1690
+ let changed = false;
1691
+ for (const key of ["title", "status", "activity", "modifiedAt"] as const) {
1692
+ if (entry[key] !== next[key]) {
1693
+ changes[key] = next[key];
1694
+ changed = true;
1695
+ }
1696
+ }
1697
+ if (changed) {
1698
+ this.publish({
1699
+ channel: rec.channel,
1700
+ action: { type: ActionType.SessionChatUpdated, chat: chat.resource, changes: changes as Partial<ChatSummary> },
1701
+ });
1702
+ }
1703
+ }
1704
+
1705
+ /**
1706
+ * Announce summary-level changes on the root channel (`root/
1707
+ * sessionSummaryChanged` notification — ephemeral, not replayed).
1708
+ * Identity fields (resource/provider/createdAt) never change.
1709
+ */
1710
+ private maybeNotifySummaryChanged(rec: SessionRecord, before: SessionSummary, after: SessionSummary): void {
1711
+ const changes: Record<string, unknown> = {};
1712
+ for (const key of ["title", "status", "activity", "modifiedAt", "chats", "defaultChat"] as const) {
1713
+ if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) {
1714
+ changes[key] = after[key];
1715
+ }
1716
+ }
1717
+ if (Object.keys(changes).length === 0) return;
1718
+ if (after.modifiedAt > rec.modifiedAt) rec.modifiedAt = after.modifiedAt;
1719
+ this.notifyRoot("root/sessionSummaryChanged", {
1720
+ channel: ROOT_CHANNEL,
1721
+ session: rec.channel,
1722
+ changes,
1723
+ });
1724
+ }
1725
+
1726
+ /** Send a root-channel notification frame to every root subscriber. */
1727
+ private notifyRoot(method: string, params: unknown): void {
1728
+ const frame = { jsonrpc: "2.0", method, params };
1729
+ for (const socketId of this.channels.socketsSubscribedTo(ROOT_CHANNEL)) {
1730
+ this.opts.send(socketId, frame);
1731
+ }
1732
+ }
1733
+
1734
+ /** Send an `action` notification to every socket subscribed to the channel. */
1735
+ private notifyAction(envelope: ActionEnvelope): void {
1736
+ const frame = { jsonrpc: "2.0", method: "action", params: envelope };
1737
+ for (const socketId of this.channels.socketsSubscribedTo(envelope.channel)) {
1738
+ this.opts.send(socketId, frame);
1739
+ }
1740
+ }
1741
+
1742
+ private sendError(socketId: number, id: unknown, code: number, message: string): void {
1743
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: id ?? null, error: { code, message } });
1744
+ }
1745
+ }
1746
+
1747
+ function sameAgents(a: unknown, b: unknown): boolean {
1748
+ return JSON.stringify(a) === JSON.stringify(b);
1749
+ }
1750
+
1751
+ function errorMessage(e: unknown): string {
1752
+ return e instanceof Error ? e.message : String(e);
1753
+ }
1754
+
1755
+ /** Short, stable description of untrusted params for log lines. */
1756
+ function describeParams(params: unknown): string {
1757
+ if (!isRecord(params)) return String(typeof params);
1758
+ try {
1759
+ const raw = JSON.stringify(Object.keys(params));
1760
+ return raw.length > 120 ? raw.slice(0, 120) + "…" : raw;
1761
+ } catch {
1762
+ return "unserializable";
1763
+ }
1764
+ }
1765
+
1766
+ /** The first enabled model of a provider, as a FacadeModelRef. */
1767
+ function firstEnabledModelRef(models: readonly { providerID: string; modelID: string; enabled: boolean }[]): FacadeModelRef | undefined {
1768
+ const m = models.find((x) => x.enabled);
1769
+ return m !== undefined ? { providerID: m.providerID, modelID: m.modelID } : undefined;
1770
+ }
1771
+
1772
+ /** Normalize an untrusted `activeClient` payload (untrusted JSON-RPC). */
1773
+ function normalizeActiveClient(ac: Record<string, unknown>): SessionActiveClient {
1774
+ const tools = Array.isArray(ac["tools"]) ? (ac["tools"] as ToolDefinition[]) : [];
1775
+ return {
1776
+ clientId: ac["clientId"] as string,
1777
+ tools,
1778
+ ...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
1779
+ };
1780
+ }
1781
+
1782
+ /**
1783
+ * Map opencode tool result content blocks to AHP `ToolResultContent`
1784
+ * (only text blocks are representable in this MVP; file/patch text is
1785
+ * carried as text).
1786
+ */
1787
+ function mapToolResultContent(content: readonly { type: string; text?: string }[]): ToolResultContent[] {
1788
+ const out: ToolResultContent[] = [];
1789
+ for (const c of content) {
1790
+ if (c.type === "text" || c.type === "file" || c.type === "patch") {
1791
+ out.push({ type: ToolResultContentType.Text, text: c.text ?? "" });
1792
+ }
1793
+ }
1794
+ return out;
1795
+ }