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,558 @@
1
+ /**
2
+ * Session section (design §7): `createSession`/`listSessions`/`resolveSessionConfig`, external session registration (TUI/restart resurfacing, AHP markers, peer-chat re-attach), and record removal.
3
+ */
4
+
5
+ import { HostChats } from "./host-chats.js";
6
+ import { ActionType, SessionStatus, ResolveSessionConfigResult, SessionActiveClient, SessionSummary } from "@microsoft/agent-host-protocol";
7
+ import { agentDirectoryCustomization, chatChangesetCatalog, chatSummaryOf, directoryUri, initialSessionState, mapAgentCustomizations, sessionChangesetCatalog, FacadeSession } from "./bridge.js";
8
+ import { ROOT_CHANNEL, channelKind, chatChannelURI, sessionChannelURI, sessionIDOf } from "./channels.js";
9
+ import { ERROR_INVALID_PARAMS } from "./handshake.js";
10
+ import { isRecord } from "./options.js";
11
+ import { createSessionStateStore } from "./state.js";
12
+ import { ERROR_NO_PROVIDER, ERROR_SESSION_EXISTS } from "./host-errors.js";
13
+ import { RpcMessage, SessionRecord } from "./host-types.js";
14
+ import { EXTERNAL_REGISTER_GRACE_MS, AHP_METADATA_KEY, parseAhpMarker, errorMessage, firstEnabledModelRef, normalizeActiveClient } from "./host-util.js";
15
+
16
+ /** Default page size for `listSessions` (AHP `PaginatedParams.limit`). */
17
+ const LIST_SESSIONS_DEFAULT_LIMIT = 100;
18
+
19
+ export class HostSessions extends HostChats {
20
+ /**
21
+ * `createSession` (AHP 1.0.0 session-channel command). Creates a real
22
+ * opencode session, seeds its session/chat stores, publishes the
23
+ * session-channel lifecycle actions, announces the session on the root
24
+ * channel, and responds `null` (per the command contract).
25
+ *
26
+ * Error codes: -32002 (no agent for the requested provider),
27
+ * -32003 (the session URI already exists).
28
+ */
29
+ protected async handleCreateSession(socketId: number, msg: RpcMessage): Promise<void> {
30
+ const params = isRecord(msg.params) ? msg.params : {};
31
+ const channel = params["channel"];
32
+ if (typeof channel !== "string" || channelKind(channel) !== "session") {
33
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createSession requires an ahp-session:/… channel");
34
+ return;
35
+ }
36
+ const suffix = sessionIDOf(channel) as string;
37
+ // A suffix containing the changeset marker would make this session
38
+ // channel string-identical to the changeset URI of the session before
39
+ // the marker — the changeset kind would win (channelKind), making the
40
+ // session channel un-subscribable. Reject it instead.
41
+ if (suffix.includes("/changeset/")) {
42
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "channel suffix must not contain \"/changeset/\"");
43
+ return;
44
+ }
45
+ for (const rec of this.sessions.values()) {
46
+ if (rec.channel === channel) {
47
+ this.sendError(socketId, msg.id, ERROR_SESSION_EXISTS, "Session already exists");
48
+ return;
49
+ }
50
+ }
51
+
52
+ // Resolve the provider/model for the new session.
53
+ const providers = await this.opts.facade.listCatalog();
54
+ const providerParam = params["provider"];
55
+ let provider;
56
+ if (typeof providerParam === "string" && providerParam.length > 0) {
57
+ provider = providers.find((p) => p.providerID === providerParam && p.activation !== "disabled");
58
+ if (provider === undefined) {
59
+ this.sendError(socketId, msg.id, ERROR_NO_PROVIDER, `No agent for provider ${providerParam}`);
60
+ return;
61
+ }
62
+ } else {
63
+ provider = providers.find((p) => p.activation !== "disabled");
64
+ }
65
+ const model = provider !== undefined ? firstEnabledModelRef(provider.models) : undefined;
66
+
67
+ // `activeClient` eagerly claims an active-client role; the spec requires
68
+ // the clientId to match the creating client.
69
+ let activeClients: SessionActiveClient[] = [];
70
+ const activeClientParam = params["activeClient"];
71
+ if (activeClientParam !== undefined) {
72
+ const socket = this.sockets.get(socketId);
73
+ const ac = activeClientParam as Record<string, unknown>;
74
+ if (
75
+ !isRecord(ac) ||
76
+ typeof ac["clientId"] !== "string" ||
77
+ ac["clientId"] !== socket?.clientId
78
+ ) {
79
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "activeClient.clientId must match the initializing clientId");
80
+ return;
81
+ }
82
+ activeClients = [normalizeActiveClient(ac)];
83
+ }
84
+
85
+ // opencode SessionIDs must start with "ses": pass the suffix through
86
+ // only when it already is one; otherwise let opencode mint an id and
87
+ // record the suffix→id mapping (the record key is the opencode id).
88
+ const passID = suffix.startsWith("ses") ? suffix : undefined;
89
+ const created = await this.opts.facade.createSession({
90
+ id: passID,
91
+ model,
92
+ // Durability: a minted-id default backend carries
93
+ // the client-chosen session channel in its opencode metadata —
94
+ // after a restart the session resurfaces under the ORIGINAL channel
95
+ // instead of its opencode id (a "ses" suffix IS the opencode id and
96
+ // needs no marker).
97
+ ...(passID === undefined ? { metadata: { [AHP_METADATA_KEY]: { channel } } } : {}),
98
+ });
99
+
100
+ // Slow-create race: the pump may have registered this opencode session
101
+ // under its own id as an external session while `createSession` was in
102
+ // flight. Remap: drop the interim record (root/sessionRemoved) and
103
+ // re-register under the client-chosen channel below.
104
+ //
105
+ // Marker interaction: with the channel marker, the
106
+ // interim external registration lands under the MARKED channel (the
107
+ // client's own), so `interim.channel !== channel` is false and the
108
+ // remap is skipped — the re-registration below then re-announces the
109
+ // session (a duplicate root/sessionAdded in this rare race; cosmetic,
110
+ // the client converges on the snapshot, and the race requires
111
+ // createSession to exceed the 250 ms external-register grace).
112
+ const interim = this.sessions.get(created.sessionID);
113
+ if (interim !== undefined && interim.channel !== channel) {
114
+ this.removeRecord(interim);
115
+ }
116
+
117
+ const agents = await this.opts.facade.listAgents();
118
+ const customizations =
119
+ mapAgentCustomizations(agents).length > 0 && this.opts.defaultDirectory !== undefined
120
+ ? [agentDirectoryCustomization(this.opts.defaultDirectory, agents)]
121
+ : undefined;
122
+ const now = new Date().toISOString();
123
+ const sessionStore = createSessionStateStore(
124
+ initialSessionState({
125
+ sessionID: created.sessionID,
126
+ provider: created.model?.providerID ?? provider?.providerID ?? "opencode",
127
+ title: created.title ?? "New Session",
128
+ activeClients,
129
+ customizations,
130
+ workingDirectories: this.workingDirectories(),
131
+ }),
132
+ );
133
+ const rec: SessionRecord = {
134
+ sessionID: created.sessionID,
135
+ channel,
136
+ provider: sessionStore.state.provider,
137
+ createdAt: new Date(created.time.created).toISOString(),
138
+ modifiedAt: new Date(created.time.updated).toISOString() > now
139
+ ? new Date(created.time.updated).toISOString()
140
+ : now,
141
+ sessionStore,
142
+ chats: new Map(),
143
+ defaultChatURI: chatChannelURI(created.sessionID),
144
+ sessionChangesets: new Map(),
145
+ };
146
+ this.sessions.set(created.sessionID, rec);
147
+ this.byChannel.set(channel, rec);
148
+ // The session channel carries the client-chosen suffix; the chat
149
+ // channel and the event pump carry the opencode id — both must
150
+ // resolve in the registry.
151
+ this.channels.addSession(suffix);
152
+ this.channels.addSession(created.sessionID);
153
+ const defaultChat = this.newChatRuntime(rec.defaultChatURI, created.sessionID, "Chat 1", now);
154
+ this.bindChat(rec, defaultChat);
155
+
156
+ // A createSession `activeClient` seeds the
157
+ // session's tools — register them with opencode now.
158
+ if (activeClients.length > 0) void this.syncClientToolsToOpencode();
159
+
160
+ // Session-channel lifecycle (server-side, no origin).
161
+ this.publish({ channel, action: { type: ActionType.SessionReady } });
162
+ this.publish({
163
+ channel,
164
+ action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(defaultChat.chatStore.state) },
165
+ });
166
+ this.publish({
167
+ channel,
168
+ action: { type: ActionType.SessionDefaultChatChanged, defaultChat: rec.defaultChatURI },
169
+ });
170
+ // Advertise the changeset catalogues (session channel: the
171
+ // session-wide changeset; chat channel: uncommitted + session + the
172
+ // per-turn template).
173
+ if (this.opts.changesets) {
174
+ this.publish({
175
+ channel,
176
+ action: { type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(channel) },
177
+ });
178
+ this.publish({
179
+ channel: rec.defaultChatURI,
180
+ action: {
181
+ type: ActionType.ChatChangesetsChanged,
182
+ changesets: chatChangesetCatalog(rec.defaultChatURI, channel),
183
+ },
184
+ });
185
+ }
186
+ // Root: active-session count (action, replayed) + sessionAdded (notification).
187
+ this.publish({
188
+ channel: ROOT_CHANNEL,
189
+ action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
190
+ });
191
+ this.notifyRoot("root/sessionAdded", {
192
+ channel: ROOT_CHANNEL,
193
+ summary: this.sessionSummary(rec),
194
+ });
195
+
196
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
197
+ }
198
+
199
+ /**
200
+ * `listSessions` (AHP 1.0.0 root command): all opencode sessions,
201
+ * most-recently-modified first, with in-memory cursor pagination.
202
+ * Unknown sessions are lazily registered (so their channels become
203
+ * subscribable); registration is idempotent per opencode session id.
204
+ */
205
+ protected async handleListSessions(socketId: number, msg: RpcMessage): Promise<void> {
206
+ const params = isRecord(msg.params) ? msg.params : {};
207
+ const limit =
208
+ typeof params["limit"] === "number" && Number.isInteger(params["limit"]) && (params["limit"] as number) > 0
209
+ ? (params["limit"] as number)
210
+ : LIST_SESSIONS_DEFAULT_LIMIT;
211
+ let offset = 0;
212
+ if (typeof params["cursor"] === "string" && params["cursor"].length > 0) {
213
+ const parsed = Number.parseInt(params["cursor"], 10);
214
+ if (Number.isInteger(parsed) && parsed > 0) offset = parsed;
215
+ }
216
+ const listed = await this.opts.facade.listSessions();
217
+ const records: (SessionRecord | undefined)[] = [];
218
+ for (const fs of listed) {
219
+ records.push(this.registerExternal(fs) ?? this.sessions.get(fs.sessionID));
220
+ }
221
+ const sorted = records
222
+ .filter((r): r is SessionRecord => r !== undefined)
223
+ .sort((a, b) => {
224
+ const ta = this.sessions.get(a.sessionID)?.modifiedAt ?? a.modifiedAt;
225
+ const tb = this.sessions.get(b.sessionID)?.modifiedAt ?? b.modifiedAt;
226
+ return ta < tb ? 1 : ta > tb ? -1 : 0;
227
+ });
228
+ const page = sorted.slice(offset, offset + limit);
229
+ const nextOffset = offset + limit;
230
+ const result: { items: SessionSummary[]; nextCursor?: string } = {
231
+ items: page.map((rec) => this.sessionSummary(rec)),
232
+ };
233
+ if (nextOffset < sorted.length) result.nextCursor = String(nextOffset);
234
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
235
+ }
236
+
237
+ /**
238
+ * AHP 1.0.0 root command — the client resolves the session-creation
239
+ * config schema. VS Code calls it every time the new-session composer
240
+ * opens and STRICTLY again before the first send of a new session
241
+ * (`_sendNewSessionRequest`), so an unimplemented host makes every
242
+ * fresh session unstartable ("unknown method: resolveSessionConfig").
243
+ * opencode collects no session-creation configuration —
244
+ * agent/model choice rides session-state customizations and the
245
+ * per-turn message — so the honest answer is an empty schema with
246
+ * empty values. `provider` / `workingDirectory` / `config` are
247
+ * accepted and deliberately unused: sessions run in the location
248
+ * directory and the host advertises no config properties (which also
249
+ * keeps `sessionConfigCompletions` unreachable — it only serves
250
+ * `enumDynamic` properties this schema does not carry).
251
+ */
252
+ protected handleResolveSessionConfig(socketId: number, msg: RpcMessage): void {
253
+ const params = isRecord(msg.params) ? msg.params : {};
254
+ if (params["channel"] !== ROOT_CHANNEL) {
255
+ this.sendError(
256
+ socketId,
257
+ msg.id,
258
+ ERROR_INVALID_PARAMS,
259
+ "resolveSessionConfig requires the ahp-root:// channel",
260
+ );
261
+ return;
262
+ }
263
+ const result: ResolveSessionConfigResult = {
264
+ schema: { type: "object", properties: {} },
265
+ values: {},
266
+ };
267
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
268
+ }
269
+
270
+ /**
271
+ * Verify a `session.created` event via the session API and register the
272
+ * session under its own id as the channel suffix (the suffix starts
273
+ * with "ses" — opencode ids are valid suffixes). No-op when the session
274
+ * is gone, already registered, or a createSession remap is pending.
275
+ */
276
+ // ── session registration / removal ─────────────────────────────────────
277
+ protected async registerExternalDeferred(sessionID: string): Promise<void> {
278
+ if (this.sessions.has(sessionID) || this.byOpencode.has(sessionID)) return;
279
+ let fs: FacadeSession | null;
280
+ try {
281
+ fs = await this.opts.facade.getSession(sessionID);
282
+ } catch {
283
+ return;
284
+ }
285
+ if (fs === null || this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) return;
286
+ this.registerExternal(fs);
287
+ }
288
+
289
+ /**
290
+ * Register an opencode session the host did not create (TUI, another
291
+ * client, or a session resurfacing after a restart).
292
+ * Outcomes:
293
+ *
294
+ * - the opencode id already backs a chat of a live record → skip
295
+ * (undefined); `listSessions` must not surface peer-chat backends
296
+ * as their own AHP sessions;
297
+ * - the session carries a peer marker and the owner record is
298
+ * registered (and the marker's chat URI is free) → re-attach it to
299
+ * the owner's chat catalog (undefined — no standalone session);
300
+ * - the peer marker's owner is not registered yet → queue the
301
+ * binding (undefined) — the owner may be listed later in the same
302
+ * `listSessions` pass (there is no boot-time event replay);
303
+ * - the session carries a channel marker (minted-id default backend)
304
+ * and the marked channel is free → a standalone session registered
305
+ * under the ORIGINAL client-chosen channel;
306
+ * - otherwise → a standalone session whose channel reuses the
307
+ * opencode id (the record).
308
+ */
309
+ private registerExternal(fs: FacadeSession): SessionRecord | undefined {
310
+ const existing = this.sessions.get(fs.sessionID);
311
+ if (existing !== undefined) return existing;
312
+ if (this.byOpencode.has(fs.sessionID)) return undefined;
313
+ const marker = parseAhpMarker(fs.metadata);
314
+ if (marker !== null) {
315
+ if (marker.chat !== undefined && marker.owner !== undefined) {
316
+ const owner = this.sessions.get(marker.owner);
317
+ if (owner !== undefined) {
318
+ if (this.byChannel.has(marker.chat)) {
319
+ // The marker's chat is already bound — e.g. a fork inherited
320
+ // the parent's metadata (core documents the inheritance).
321
+ // Standalone fallback: the data stays reachable in AHP.
322
+ this.log(
323
+ `ignoring the AHP marker on ${fs.sessionID}: chat ${marker.chat} is already bound (registering standalone)`,
324
+ );
325
+ } else {
326
+ return this.reattachPeerChat(owner, fs, marker.chat);
327
+ }
328
+ } else {
329
+ this.enqueueChatBinding(marker.owner, fs, marker.chat);
330
+ return undefined;
331
+ }
332
+ } else if (marker.channel !== undefined) {
333
+ // The default backend of a minted-id session carries the
334
+ // client-chosen session channel — resurface under it.
335
+ if (this.byChannel.has(marker.channel)) {
336
+ this.log(
337
+ `ignoring the AHP channel marker on ${fs.sessionID}: ${marker.channel} is already bound (registering under the opencode id)`,
338
+ );
339
+ } else {
340
+ return this.registerExternalStandalone(fs, marker.channel);
341
+ }
342
+ }
343
+ }
344
+ return this.registerExternalStandalone(fs);
345
+ }
346
+
347
+ /**
348
+ * Re-attach a marked peer backend to its owner session's chat catalog
349
+ * after a restart. The owner store is LIVE (unlike a
350
+ * fresh standalone registration), so the catalog change goes through
351
+ * `publish` (store + any existing subscribers + the root diff), not a
352
+ * direct apply. The chat title is re-derived (`Chat <n>`) — a
353
+ * documented divergence from the pre-restart title. Returns undefined:
354
+ * the backend gets no standalone AHP session (its session channel is
355
+ * not registered — `sessions.get(peerID)` misses).
356
+ */
357
+ private reattachPeerChat(rec: SessionRecord, fs: FacadeSession, chatURI: string): undefined {
358
+ const modifiedAt = new Date(fs.time.updated).toISOString();
359
+ const chat = this.newChatRuntime(chatURI, fs.sessionID, `Chat ${rec.chats.size + 1}`, modifiedAt);
360
+ this.bindChat(rec, chat);
361
+ this.publish({
362
+ channel: rec.channel,
363
+ action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chat.chatStore.state) },
364
+ });
365
+ if (this.opts.changesets) {
366
+ this.publish({
367
+ channel: chatURI,
368
+ action: { type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(chatURI, rec.channel) },
369
+ });
370
+ }
371
+ this.log(`reattached peer chat ${chatURI} (backend ${fs.sessionID}) to session ${rec.channel} from its AHP marker`);
372
+ return undefined;
373
+ }
374
+
375
+ /**
376
+ * Queue a peer-chat binding whose owner is not registered yet (the
377
+ * peer was listed before the owner, or the owner has not been listed
378
+ * at all). `drainPendingChatBindings` resolves it when the owner
379
+ * registers. The orphan fallback fires after the grace window: if the
380
+ * owner is still unregistered and gone from opencode, the peer is
381
+ * surfaced as its own AHP session instead (the data stays reachable).
382
+ */
383
+ private enqueueChatBinding(ownerID: string, fs: FacadeSession, chatURI: string): void {
384
+ const queue = this.pendingChatBindings.get(ownerID) ?? [];
385
+ queue.push({ fs, chatURI });
386
+ this.pendingChatBindings.set(ownerID, queue);
387
+ setTimeout(() => {
388
+ void this.checkOrphanChatBindings(ownerID).catch((err) =>
389
+ this.log(`orphan chat-binding check failed: ${errorMessage(err)}`),
390
+ );
391
+ }, EXTERNAL_REGISTER_GRACE_MS);
392
+ }
393
+
394
+ /**
395
+ * Orphan fallback for queued peer-chat bindings: the
396
+ * owner never registered and is gone from opencode (e.g. deleted in
397
+ * the TUI while the plugin was down). Drop the queue and register each
398
+ * peer as a standalone AHP session. A failed owner lookup keeps the
399
+ * queue — the next registration or timer re-checks.
400
+ */
401
+ private async checkOrphanChatBindings(ownerID: string): Promise<void> {
402
+ const queue = this.pendingChatBindings.get(ownerID);
403
+ if (queue === undefined || queue.length === 0) return; // the owner registered — drained
404
+ let owner: FacadeSession | null;
405
+ try {
406
+ owner = await this.opts.facade.getSession(ownerID);
407
+ } catch {
408
+ return;
409
+ }
410
+ if (owner !== null) return; // the owner still exists in opencode — it registers when listed
411
+ this.pendingChatBindings.delete(ownerID);
412
+ for (const { fs, chatURI } of queue) {
413
+ if (this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) continue;
414
+ this.log(
415
+ `AHP marker owner ${ownerID} is gone from opencode — registering the orphaned peer ${fs.sessionID} (chat ${chatURI}) as a standalone session`,
416
+ );
417
+ this.registerExternalStandalone(fs);
418
+ }
419
+ }
420
+
421
+ /**
422
+ * Resolve queued peer-chat bindings once their owner registers (called
423
+ * from the standalone registration's success path). A chat URI that is
424
+ * already bound by then (e.g. the client created it again across the
425
+ * restart) falls back to standalone registration.
426
+ */
427
+ private drainPendingChatBindings(ownerID: string): void {
428
+ const queue = this.pendingChatBindings.get(ownerID);
429
+ const owner = this.sessions.get(ownerID);
430
+ if (queue === undefined || queue.length === 0 || owner === undefined) return;
431
+ this.pendingChatBindings.delete(ownerID);
432
+ for (const { fs, chatURI } of queue) {
433
+ if (this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) continue;
434
+ if (this.byChannel.has(chatURI)) {
435
+ this.log(
436
+ `ignoring the AHP marker on ${fs.sessionID}: chat ${chatURI} is already bound (registering standalone)`,
437
+ );
438
+ this.registerExternalStandalone(fs);
439
+ } else {
440
+ this.reattachPeerChat(owner, fs, chatURI);
441
+ }
442
+ }
443
+ }
444
+
445
+ /**
446
+ * Register an opencode session as a single-chat AHP session (its
447
+ * default chat reuses the opencode id). The session channel defaults
448
+ * to the opencode id; the channel-marker path passes
449
+ * the ORIGINAL client-chosen channel instead — the registry then
450
+ * resolves both suffixes (mirroring `handleCreateSession`). Applied
451
+ * directly to the fresh stores (no seq, no actions) — the
452
+ * registration is server-side bookkeeping, not a client-visible state
453
+ * transition; the root announcement carries the lifecycle.
454
+ */
455
+ private registerExternalStandalone(fs: FacadeSession, channel?: string): SessionRecord {
456
+ const recChannel = channel ?? sessionChannelURI(fs.sessionID);
457
+ const modifiedAt = new Date(fs.time.updated).toISOString();
458
+ const sessionStore = createSessionStateStore(
459
+ initialSessionState({
460
+ sessionID: fs.sessionID,
461
+ provider: fs.model?.providerID ?? "opencode",
462
+ title: fs.title ?? "New Session",
463
+ status: fs.archived
464
+ ? ((SessionStatus.Idle | SessionStatus.IsRead | SessionStatus.IsArchived) as SessionStatus)
465
+ : undefined, // Idle | IsRead | IsArchived
466
+ workingDirectories: this.workingDirectories(),
467
+ }),
468
+ );
469
+ const rec: SessionRecord = {
470
+ sessionID: fs.sessionID,
471
+ channel: recChannel,
472
+ provider: sessionStore.state.provider,
473
+ createdAt: new Date(fs.time.created).toISOString(),
474
+ modifiedAt,
475
+ sessionStore,
476
+ chats: new Map(),
477
+ defaultChatURI: chatChannelURI(fs.sessionID),
478
+ sessionChangesets: new Map(),
479
+ };
480
+ this.sessions.set(fs.sessionID, rec);
481
+ this.byChannel.set(recChannel, rec);
482
+ // The registry resolves the opencode id (event pump, chat channels)
483
+ // and — for a channel-marker registration — the client-chosen
484
+ // suffix too (mirroring `handleCreateSession`).
485
+ const suffix = sessionIDOf(recChannel) as string;
486
+ if (suffix !== fs.sessionID) this.channels.addSession(suffix);
487
+ const defaultChat = this.newChatRuntime(rec.defaultChatURI, fs.sessionID, "Chat 1", modifiedAt);
488
+ this.bindChat(rec, defaultChat);
489
+ sessionStore.apply({ type: ActionType.SessionReady });
490
+ sessionStore.apply({ type: ActionType.SessionChatAdded, summary: chatSummaryOf(defaultChat.chatStore.state) });
491
+ sessionStore.apply({ type: ActionType.SessionDefaultChatChanged, defaultChat: rec.defaultChatURI });
492
+ // Advertise the changeset catalogues directly on the fresh
493
+ // stores (registration is server-side bookkeeping — no seq, no actions).
494
+ if (this.opts.changesets) {
495
+ sessionStore.apply({ type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(recChannel) });
496
+ defaultChat.chatStore.apply({
497
+ type: ActionType.ChatChangesetsChanged,
498
+ changesets: chatChangesetCatalog(rec.defaultChatURI, recChannel),
499
+ });
500
+ }
501
+ // Durability: peers whose marker points at this
502
+ // session may have been listed earlier in the same `listSessions`
503
+ // pass — re-attach them before the root announcement so the
504
+ // sessionAdded summary carries the full chat catalog.
505
+ this.drainPendingChatBindings(fs.sessionID);
506
+ this.publish({
507
+ channel: ROOT_CHANNEL,
508
+ action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
509
+ });
510
+ this.notifyRoot("root/sessionAdded", { channel: ROOT_CHANNEL, summary: this.sessionSummary(rec) });
511
+ return rec;
512
+ }
513
+
514
+ /** Drop a session record and announce the removal on the root channel. */
515
+ protected removeRecord(rec: SessionRecord): void {
516
+ const hadClients = rec.sessionStore.state.activeClients.length > 0;
517
+ // Peer-chat backends are removed while their bindings are still live:
518
+ // an unbound lingering backend would be re-registered by the next
519
+ // listSessions scan as its own AHP session. R2: failures log — the
520
+ // AHP side tears down either way (the ghost then shows in the TUI).
521
+ for (const chat of rec.chats.values()) {
522
+ if (chat.uri === rec.defaultChatURI) continue;
523
+ void this.opts.facade
524
+ .removeSession(chat.sessionID)
525
+ .catch((err) => this.log(`failed to remove the peer chat's opencode session ${chat.sessionID}: ${errorMessage(err)}`));
526
+ }
527
+ // Every live changeset URI is about to become un-subscribable
528
+ // — dispatch `changeset/cleared` (protocol case 2) before the teardown
529
+ // so subscribers release their references.
530
+ for (const uri of rec.sessionChangesets.keys()) {
531
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetCleared } });
532
+ }
533
+ rec.sessionChangesets.clear();
534
+ // Per-chat teardown: live chat changesets
535
+ // (`changeset/cleared`), in-flight client-tool executions failed
536
+ // (the waiters must not leak), and every binding dropped.
537
+ let failedTools = false;
538
+ for (const chat of [...rec.chats.values()]) {
539
+ failedTools = failedTools || [...chat.clientToolCalls.values()].some((inv) => inv.result === undefined);
540
+ this.removeChat(rec, chat, "session removed before the client completed the tool call");
541
+ }
542
+ this.sessions.delete(rec.sessionID);
543
+ this.byChannel.delete(rec.channel);
544
+ const id = sessionIDOf(rec.channel);
545
+ if (id !== null) this.channels.removeSession(id);
546
+ this.channels.removeSession(rec.sessionID);
547
+ this.publish({
548
+ channel: ROOT_CHANNEL,
549
+ action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
550
+ });
551
+ this.notifyRoot("root/sessionRemoved", { channel: ROOT_CHANNEL, session: rec.channel });
552
+ // Re-sync the opencode tool union when this
553
+ // session's clients' tools leave the cross-session set (or any
554
+ // in-flight call was failed — the facade union is unchanged, but the
555
+ // session's execute gate must not linger).
556
+ if (hadClients || failedTools) void this.syncClientToolsToOpencode();
557
+ }
558
+ }