opencode-ahp 0.1.4 → 0.1.5

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 CHANGED
@@ -1,11 +1,10 @@
1
1
  /**
2
2
  * The AHP host: the JSON-RPC 2.0 router over transport connections that
3
3
  * ties the sequencer, channel registry, root state store, and bridge
4
- * together (plan §6.1).
4
+ * together.
5
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
6
+ * The router that wires the pure modules to sockets is extracted here
7
+ * (a `Host` class) so the whole protocol layer is unit-testable and
9
8
  * exercisable by the spike client without a WebSocket runtime.
10
9
  *
11
10
  * Connection model (AHP 1.0.0 lifecycle spec):
@@ -18,17 +17,20 @@
18
17
  * dispatched action comes back on the `action` notification stream
19
18
  * (write-ahead reconciliation; rejections carry `rejectionReason`).
20
19
  *
21
- * Phase 1 (plan §11): `createSession` + `listSessions`, session/chat
20
+ * Session surface: `createSession` + `listSessions`, session/chat
22
21
  * snapshots, the opencode event pump (streaming text/reasoning, tool-call
23
22
  * lifecycle, permission prompts, usage, turn terminals + steering/queue
24
23
  * handoff), and the client-dispatchable actions VS Code sends
25
24
  * (`chat/turnStarted`, `chat/pendingMessageSet`, `chat/toolCallConfirmed`,
26
25
  * `chat/turnCancelled`, drafts/read/title/activeClient echoes, …).
27
26
  *
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.
27
+ * Session model: one AHP session = one opencode location session record
28
+ * holding a chat catalog; one AHP chat = one opencode session. The
29
+ * default chat reuses the record's opencode session, so
30
+ * single-chat clients see zero wire change; peer chats created via
31
+ * `createChat` bind fresh opencode sessions to client-chosen chat URIs.
32
+ * Channel suffixes are opaque; opencode session ids start with "ses"
33
+ * and double as suffixes for externally created sessions.
32
34
  *
33
35
  * Root session lifecycle events (`root/sessionAdded`,
34
36
  * `root/sessionRemoved`, `root/sessionSummaryChanged`) are JSON-RPC
@@ -47,7 +49,10 @@ import {
47
49
  ResponsePartKind,
48
50
  SessionInputRequestKind,
49
51
  SessionStatus,
52
+ TerminalClaimKind,
53
+ TerminalLifecycleStatus,
50
54
  ToolCallConfirmationReason,
55
+ ToolCallContributorKind,
51
56
  ToolCallStatus,
52
57
  ToolResultContentType,
53
58
  isClientDispatchable,
@@ -55,8 +60,10 @@ import {
55
60
  type ActionOrigin,
56
61
  type ChatAction,
57
62
  type ChatSummary,
58
- type ChatState,
63
+ type ChatToolCallCompleteAction,
59
64
  type ChatToolCallConfirmedAction,
65
+ type ChatToolCallContentChangedAction,
66
+ type ChatToolCallResultConfirmedAction,
60
67
  type ChatTurnCancelledAction,
61
68
  type ChatTurnStartedAction,
62
69
  type ChangesetAction,
@@ -65,17 +72,22 @@ import {
65
72
  type Implementation,
66
73
  type Message,
67
74
  type ReconnectResult,
75
+ type ResolveSessionConfigResult,
68
76
  type RootAction,
69
77
  type SessionAction,
70
78
  type SessionActiveClient,
71
- type SessionState,
72
79
  type SessionSummary,
80
+ type SessionToolClientExecutionRequest,
73
81
  type SessionToolConfirmationRequest,
74
82
  type Snapshot,
75
83
  type StateAction,
84
+ type StringOrMarkdown,
85
+ type TerminalAction,
86
+ type TerminalInfo,
87
+ type TerminalState,
76
88
  type ToolCallConfirmationState,
89
+ type ToolCallResult,
77
90
  type ToolCallState,
78
- type ToolDefinition,
79
91
  type ToolResultContent,
80
92
  } from "@microsoft/agent-host-protocol";
81
93
  import {
@@ -88,6 +100,7 @@ import {
88
100
  chatSummaryOf,
89
101
  displayNameFor,
90
102
  discardOperation,
103
+ directoryUri,
91
104
  fileUri,
92
105
  initialChatState,
93
106
  initialSessionState,
@@ -98,12 +111,23 @@ import {
98
111
  pastTenseMessageFor,
99
112
  sessionChangesetCatalog,
100
113
  userMessage,
114
+ type FacadeClientTool,
115
+ type FacadeClientToolResult,
101
116
  type FacadeDelivery,
102
117
  type FacadeEvent,
103
118
  type FacadeModelRef,
104
119
  type FacadeSession,
120
+ type FacadeToolContent,
105
121
  type OpencodeFacade,
106
122
  } from "./bridge.js";
123
+ import {
124
+ descriptionFor,
125
+ findProvider,
126
+ inputSchemaFor,
127
+ normalizeToolDefinitions,
128
+ toolUnion,
129
+ type ClientToolInvocation,
130
+ } from "./client-tools.js";
107
131
  import {
108
132
  ChannelRegistry,
109
133
  ROOT_CHANNEL,
@@ -113,6 +137,7 @@ import {
113
137
  sessionChannelURI,
114
138
  sessionChangesetURI,
115
139
  sessionIDOf,
140
+ terminalChannelURI,
116
141
  turnChangesetURI,
117
142
  uncommittedChangesetURI,
118
143
  } from "./channels.js";
@@ -124,10 +149,12 @@ import {
124
149
  createChangesetStateStore,
125
150
  createRootStateStore,
126
151
  createSessionStateStore,
152
+ createTerminalStateStore,
127
153
  type ChatStateStore,
128
154
  type ChangesetStateStore,
129
155
  type RootStateStore,
130
156
  type SessionStateStore,
157
+ type TerminalStateStore,
131
158
  } from "./state.js";
132
159
 
133
160
  export const ERROR_PARSE = -32700;
@@ -139,6 +166,7 @@ export const ERROR_NO_PROVIDER = -32002;
139
166
  export const ERROR_SESSION_EXISTS = -32003;
140
167
  export const ERROR_NOT_FOUND = -32008;
141
168
  export const ERROR_PERMISSION_DENIED = -32009;
169
+ export const ERROR_NOT_SUPPORTED = -32010;
142
170
 
143
171
  // ActionType / ReconnectResultType are `declare const enum` in the package
144
172
  // but are also real runtime objects (verified against the published dist),
@@ -168,22 +196,16 @@ interface ClientRecord {
168
196
  }
169
197
 
170
198
  /**
171
- * Everything the host knows about one live opencode session: the two
172
- * official-reducer stores (session + its single chat), the denormalized
173
- * summary fields for root notifications, and the per-turn tracking the
174
- * event pump needs to join opencode events to AHP turns.
199
+ * Everything the host tracks for one AHP chat — the backing opencode
200
+ * session, its chat-state store, and the per-turn tracking the event
201
+ * pump needs to join opencode events to AHP turns. One AHP chat ↔ one
202
+ * opencode session.
175
203
  */
176
- interface SessionRecord {
177
- /** The opencode session id (`ses_…`). */
204
+ interface ChatRuntime {
205
+ /** The AHP chat channel URI (`ahp-chat:/…`). */
206
+ uri: string;
207
+ /** The opencode session id backing this chat (`ses_…`). */
178
208
  sessionID: string;
179
- /** The AHP session channel URI (`ahp-session:/<suffix>`). */
180
- channel: string;
181
- /** Identity `SessionSummary.provider` (fixed at registration). */
182
- provider: string;
183
- createdAt: string;
184
- /** Denormalized `SessionSummary.modifiedAt` (ISO; lexicographic = chronological). */
185
- modifiedAt: string;
186
- sessionStore: SessionStateStore;
187
209
  chatStore: ChatStateStore;
188
210
  // ── turn tracking (event-pump join state) ────────────────────────────
189
211
  /** The AHP turnId the pump joins opencode events to, or null. */
@@ -204,20 +226,82 @@ interface SessionRecord {
204
226
  permissionForTool: Map<string, string>;
205
227
  /** opencode permission request id → toolCallId. */
206
228
  toolForPermission: Map<string, string>;
229
+ /**
230
+ * toolCallId → client-executed tool call tracking (created at
231
+ * `tool.input.started`, removed at the opencode-side terminal).
232
+ */
233
+ clientToolCalls: Map<string, ClientToolInvocation>;
207
234
  /** The most recent `session.inbox.enqueued` (external/TUI prompt tracking). */
208
235
  lastInbox: { text: string; delivery: string } | null;
209
- // ── Phase 2: changesets ────────────────────────────────────────────────
210
- /** Live changeset stores, keyed by changeset URI (created on subscribe). */
236
+ // ── changesets ────────────────────────────────────────────────
237
+ /**
238
+ * Live chat-owned changeset stores (uncommitted + turn), keyed by
239
+ * changeset URI (created on subscribe). The session-kind changeset
240
+ * store lives on the record instead (the session channel owns it).
241
+ */
211
242
  changesets: Map<string, ChangesetStateStore>;
212
243
  /**
213
244
  * Per-turn file snapshots for the turn changesets: turnId → absPath →
214
245
  * captured {before (pre-edit disk read), after (disk at turn end)}.
215
- * `null` = the file was absent on that side. Kept until the session is
216
- * removed (content refs + discard-restore read them, plan §14.10).
246
+ * `null` = the file was absent on that side. Kept until the chat is
247
+ * removed (content refs + discard-restore read them).
217
248
  */
218
249
  turnSnapshots: Map<string, Map<string, { before: string | null; after: string | null }>>;
219
250
  }
220
251
 
252
+ /**
253
+ * Everything the host knows about one AHP session: the session store,
254
+ * its chat catalog (default chat first, then insertion order), and the
255
+ * denormalized summary fields for root notifications. `sessionID` is the
256
+ * default chat's opencode id — the key of the `sessions` map and the
257
+ * event-pump join key for the default chat.
258
+ */
259
+ interface SessionRecord {
260
+ /** The default chat's opencode session id (`ses_…`). */
261
+ sessionID: string;
262
+ /** The AHP session channel URI (`ahp-session:/<suffix>`). */
263
+ channel: string;
264
+ /** Identity `SessionSummary.provider` (fixed at registration). */
265
+ provider: string;
266
+ createdAt: string;
267
+ /** Denormalized `SessionSummary.modifiedAt` (ISO; lexicographic = chronological). */
268
+ modifiedAt: string;
269
+ sessionStore: SessionStateStore;
270
+ /** Chat runtimes keyed by chat channel URI (default first, insertion order). */
271
+ chats: Map<string, ChatRuntime>;
272
+ /** The chat channel URI that receives input when none is selected. */
273
+ defaultChatURI: string;
274
+ /** The session-kind changeset store (owned by the session channel). */
275
+ sessionChangesets: Map<string, ChangesetStateStore>;
276
+ }
277
+
278
+ /**
279
+ * Everything the host tracks for one synthetic terminal channel — a
280
+ * read-only rendering of a
281
+ * `shell`-tool command execution (`isPty: false`, command parts only).
282
+ * Opened at the tool call's `tool.input.ended` (the command line is only
283
+ * known there); the record outlives its turn — the root catalog drops it
284
+ * at turn end (retention), and the channel state stays subscribable until
285
+ * the owning chat/record is removed.
286
+ */
287
+ interface TerminalRecord {
288
+ /** The terminal channel URI (`ahp-terminal:/<toolCallId>`). */
289
+ uri: string;
290
+ /** The AHP session record that owns the channel (claim `session`). */
291
+ rec: SessionRecord;
292
+ /** The chat whose turn ran the command (claim `chat`). */
293
+ chat: ChatRuntime;
294
+ /** The opencode tool call id (also the `commandId`, scoped to the URI). */
295
+ toolCallId: string;
296
+ /** The AHP turnId the command executed in — the catalog membership key. */
297
+ turnId: string;
298
+ /** The official-reducer store (the snapshot payload). */
299
+ store: TerminalStateStore;
300
+ commandLine: string;
301
+ /** Date.now() at `terminal/commandExecuted` (the `durationMs` baseline). */
302
+ startedAt: number;
303
+ }
304
+
221
305
  export interface HostOptions {
222
306
  serverInfo: Implementation;
223
307
  facade: OpencodeFacade;
@@ -226,6 +310,13 @@ export interface HostOptions {
226
310
  defaultDirectory?: string;
227
311
  /** Advertise + serve the changeset channels (catalogues, snapshots, discard). */
228
312
  changesets: boolean;
313
+ /**
314
+ * Open + serve the synthetic shell-command terminal channels: one
315
+ * read-only `ahp-terminal:`
316
+ * channel per foreground `shell`-tool call. Off the wire in 1.0.0
317
+ * (no capability field) — the switch gates the host-side behavior.
318
+ */
319
+ terminals: boolean;
229
320
  /** Deliver a JSON-serializable frame to a connection. */
230
321
  send: (socketId: number, message: unknown) => void;
231
322
  /** Close one connection (a superseded duplicate clientId). */
@@ -252,6 +343,76 @@ const LIST_SESSIONS_DEFAULT_LIMIT = 100;
252
343
  const SNAPSHOT_TOOLS = new Set(["write", "edit", "apply", "patch"]);
253
344
  /** The tool-input keys that carry a file path (checked in order). */
254
345
  const SNAPSHOT_PATH_KEYS = ["path", "file_path", "filePath", "file"] as const;
346
+ /**
347
+ * The opencode tool names whose executions render as synthetic
348
+ * `ahp-terminal:` channels. `shell`
349
+ * is the v2 core tool name; `bash` is its pre-rename alias (kept so an
350
+ * older provider-side tool name still maps).
351
+ */
352
+ const SHELL_TOOL_NAMES = new Set(["shell", "bash"]);
353
+ /**
354
+ * Max characters of the command line kept in the terminal title (the
355
+ * catalog row and the state title share it — long pipelines stay
356
+ * one-line in the Agents-window list).
357
+ */
358
+ const TERMINAL_TITLE_MAX = 64;
359
+
360
+ /**
361
+ * The exit code of a successful `shell`-tool result, read from its LAST
362
+ * text content part. opencode's shell tool
363
+ * appends a trailing `Exit code: N` notice part only for non-zero exits
364
+ * and signals (`Exit code: 137 (SIGKILL)` — the 128+signum convention
365
+ * parses as the numeric status); a zero exit carries no notice.
366
+ * Spawn failures arrive as `tool.failed` instead (no code available
367
+ * there). `null` when the last part carries an `Exit code:` line with a
368
+ * non-numeric value (e.g. `Exit code: unknown`) — the actions then
369
+ * omit the field.
370
+ */
371
+ function shellExitCodeOf(content: FacadeToolContent[]): number | null {
372
+ const last = content
373
+ .map((c) => (c.type === "text" && typeof c.text === "string" ? c.text : null))
374
+ .filter((t): t is string => t !== null)
375
+ .pop();
376
+ if (last === undefined) return 0; // no output, no notice — clean zero exit
377
+ const numeric = /Exit code: (-?\d+)\b/.exec(last);
378
+ if (numeric !== null) return Number.parseInt(numeric[1]!, 10);
379
+ return /Exit code:/.test(last) ? null : 0;
380
+ }
381
+ /**
382
+ * Durability: the opencode session-metadata key carrying the AHP
383
+ * markers. Two shapes, same key:
384
+ * - on a peer-chat backend:
385
+ * `{ chat: <chat channel URI>, owner: <the opencode session id of
386
+ * the owning AHP session> }` — `owner` is the opencode id, not the
387
+ * channel suffix (a client-chosen suffix differs from the minted
388
+ * opencode id);
389
+ * - on the default backend of a minted-id session:
390
+ * `{ channel: <session channel URI> }` — the client-chosen session
391
+ * channel (a "ses" suffix is its own opencode id and needs none).
392
+ * (The keep-alive anchor uses the same key with a STRING value —
393
+ * `parseAhpMarker` ignores non-record markers.)
394
+ */
395
+ const AHP_METADATA_KEY = "opencode-ahp";
396
+
397
+ /**
398
+ * Parse the AHP markers from an opencode session's durable metadata.
399
+ * Defensive: a malformed shape (missing key, non-record marker — e.g.
400
+ * the keep-alive anchor — or wrong-kind fields) means "no marker" —
401
+ * standalone registration under the opencode id.
402
+ */
403
+ function parseAhpMarker(metadata: unknown): { chat?: string; owner?: string; channel?: string } | null {
404
+ if (!isRecord(metadata)) return null;
405
+ const marker = metadata[AHP_METADATA_KEY];
406
+ if (!isRecord(marker)) return null;
407
+ const out: { chat?: string; owner?: string; channel?: string } = {};
408
+ const chat = marker["chat"];
409
+ if (typeof chat === "string" && channelKind(chat) === "chat") out.chat = chat;
410
+ const owner = marker["owner"];
411
+ if (typeof owner === "string" && owner.startsWith("ses")) out.owner = owner;
412
+ const channel = marker["channel"];
413
+ if (typeof channel === "string" && channelKind(channel) === "session") out.channel = channel;
414
+ return Object.keys(out).length > 0 ? out : null;
415
+ }
255
416
 
256
417
  export class Host {
257
418
  private readonly seq: Sequencer;
@@ -267,6 +428,30 @@ export class Host {
267
428
  */
268
429
  private readonly sessions = new Map<string, SessionRecord>();
269
430
  private readonly byChannel = new Map<string, SessionRecord>();
431
+ /**
432
+ * opencode session id → the (record, chat) the id backs. The event
433
+ * pump's join key — every chat has its own opencode session, and the
434
+ * pump must land on the owning chat, not just the record.
435
+ */
436
+ private readonly byOpencode = new Map<string, { rec: SessionRecord; chat: ChatRuntime }>();
437
+ /**
438
+ * Durability: marked peer backends whose owner
439
+ * AHP session is not registered yet, keyed by the marker's `owner`
440
+ * (opencode session id). A peer can be listed before its owner in the
441
+ * same synchronous `listSessions` pass, and after a restart the owner
442
+ * record does not exist until it is listed (there is no boot-time
443
+ * event replay). Drained when the owner registers; an entry whose
444
+ * owner is gone from opencode falls back to standalone registration
445
+ * after the grace window.
446
+ */
447
+ private readonly pendingChatBindings = new Map<string, { fs: FacadeSession; chatURI: string }[]>();
448
+ /**
449
+ * Synthetic terminal channels keyed by URI
450
+ * (`ahp-terminal:/<toolCallId>`), created at the `shell`-tool call's
451
+ * `tool.input.ended` and retained until the owning chat/record is
452
+ * removed.
453
+ */
454
+ private readonly terminals = new Map<string, TerminalRecord>();
270
455
  private readonly opts: HostOptions;
271
456
  private readonly log: (message: string) => void;
272
457
  private turnCounter = 0;
@@ -327,12 +512,55 @@ export class Host {
327
512
  if (socket?.clientId) {
328
513
  const record = this.clients.get(socket.clientId);
329
514
  if (record && record.socketId === socketId) record.socketId = null;
515
+ // The spec says the server SHOULD remove an
516
+ // active client when it disconnects. Safe: the
517
+ // official client re-dispatches `activeClientSet` on re-subscribe.
518
+ this.evictActiveClient(socket.clientId);
330
519
  }
331
520
  this.channels.removeSocket(socketId);
332
521
  this.sockets.delete(socketId);
333
- // MVP gap: active clients are not evicted on disconnect (the spec
334
- // expects eviction without a timely reconnect); they refresh via
335
- // `session/activeClientSet` on the next turn/dispatch.
522
+ }
523
+
524
+ /**
525
+ * Evict a disconnected client's active-client
526
+ * role from every session it holds (server-side
527
+ * `session/activeClientRemoved`), fail its in-flight client-tool
528
+ * executions (the opencode tool then fails → the pump's normal
529
+ * `tool.failed` path completes the AHP tool call — the state is still
530
+ * `running`, so the terminal suppression does not apply), clear the
531
+ * session input request each execution raised (the
532
+ * `toolClientExecution` request, or the `toolConfirmation` that
533
+ * replaced it under the same id when the result was held for
534
+ * approval — without this the session keeps a stale request and, for
535
+ * a held result, sits in InputNeeded forever), and re-sync the
536
+ * opencode tool union (it shrank).
537
+ */
538
+ private evictActiveClient(clientId: string): void {
539
+ let evicted = false;
540
+ for (const rec of this.sessions.values()) {
541
+ if (!rec.sessionStore.state.activeClients.some((c) => c.clientId === clientId)) continue;
542
+ evicted = true;
543
+ this.publish({
544
+ channel: rec.channel,
545
+ action: { type: ActionType.SessionActiveClientRemoved, clientId },
546
+ });
547
+ // In-flight client-tool calls are per-chat.
548
+ for (const chat of rec.chats.values()) {
549
+ for (const [toolCallId, inv] of chat.clientToolCalls) {
550
+ if (inv.clientId !== clientId || inv.result !== undefined) continue;
551
+ inv.result = { ok: false, error: `client ${clientId} disconnected before completing the tool call` };
552
+ this.settleClientTool(inv);
553
+ // The reducer's inputNeededRemoved is a no-op when the id is
554
+ // absent, so this is safe for an invocation whose request was
555
+ // already cleared on the normal completion path.
556
+ this.publish({
557
+ channel: rec.channel,
558
+ action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
559
+ });
560
+ }
561
+ }
562
+ }
563
+ if (evicted) void this.syncClientToolsToOpencode();
336
564
  }
337
565
 
338
566
  // ── event pump ─────────────────────────────────────────────────────────
@@ -419,17 +647,40 @@ export class Host {
419
647
  case "listSessions":
420
648
  await this.handleListSessions(socketId, msg);
421
649
  break;
650
+ case "resolveSessionConfig":
651
+ this.handleResolveSessionConfig(socketId, msg);
652
+ break;
422
653
  case "createSession":
423
654
  await this.handleCreateSession(socketId, msg);
424
655
  break;
656
+ case "createChat":
657
+ await this.handleCreateChat(socketId, msg);
658
+ break;
659
+ case "disposeChat":
660
+ await this.handleDisposeChat(socketId, msg);
661
+ break;
425
662
  case "resourceRead":
426
663
  await this.handleResourceRead(socketId, msg);
427
664
  break;
428
665
  case "invokeChangesetOperation":
429
666
  await this.handleInvokeChangesetOperation(socketId, msg);
430
667
  break;
668
+ case "createTerminal":
669
+ case "disposeTerminal":
670
+ // The host's terminals are read-only
671
+ // renderings of `shell`-tool executions — the plugin surface can
672
+ // neither create nor destroy pty-backed terminals, so both
673
+ // commands get a clean server error instead of -32601
674
+ // (proper error handling once terminals exist).
675
+ this.sendError(
676
+ socketId,
677
+ msg.id,
678
+ ERROR_NOT_SUPPORTED,
679
+ `${method} is not supported: this host's terminals are read-only renderings of shell tool calls`,
680
+ );
681
+ break;
431
682
  case "setClientManagedSettingsPermissions":
432
- // VS Code-specific post-init notification (plan §14.7): the
683
+ // VS Code-specific post-init notification: the
433
684
  // permissions VS Code manages in its own settings UI. AHP 1.0.0
434
685
  // has no counterpart — accept deliberately (parse + log), never
435
686
  // error; the connection stays up.
@@ -594,7 +845,9 @@ export class Host {
594
845
  code:
595
846
  outcome.reason === "no-such-session"
596
847
  ? ERROR_SESSION_NOT_FOUND
597
- : ERROR_INVALID_PARAMS,
848
+ : outcome.reason === "no-such-terminal"
849
+ ? ERROR_NOT_FOUND
850
+ : ERROR_INVALID_PARAMS,
598
851
  message: `cannot subscribe to ${uri}`,
599
852
  },
600
853
  });
@@ -684,12 +937,29 @@ export class Host {
684
937
  // only when it already is one; otherwise let opencode mint an id and
685
938
  // record the suffix→id mapping (the record key is the opencode id).
686
939
  const passID = suffix.startsWith("ses") ? suffix : undefined;
687
- const created = await this.opts.facade.createSession({ id: passID, model });
940
+ const created = await this.opts.facade.createSession({
941
+ id: passID,
942
+ model,
943
+ // Durability: a minted-id default backend carries
944
+ // the client-chosen session channel in its opencode metadata —
945
+ // after a restart the session resurfaces under the ORIGINAL channel
946
+ // instead of its opencode id (a "ses" suffix IS the opencode id and
947
+ // needs no marker).
948
+ ...(passID === undefined ? { metadata: { [AHP_METADATA_KEY]: { channel } } } : {}),
949
+ });
688
950
 
689
951
  // Slow-create race: the pump may have registered this opencode session
690
952
  // under its own id as an external session while `createSession` was in
691
953
  // flight. Remap: drop the interim record (root/sessionRemoved) and
692
954
  // re-register under the client-chosen channel below.
955
+ //
956
+ // Marker interaction: with the channel marker, the
957
+ // interim external registration lands under the MARKED channel (the
958
+ // client's own), so `interim.channel !== channel` is false and the
959
+ // remap is skipped — the re-registration below then re-announces the
960
+ // session (a duplicate root/sessionAdded in this rare race; cosmetic,
961
+ // the client converges on the snapshot, and the race requires
962
+ // createSession to exceed the 250 ms external-register grace).
693
963
  const interim = this.sessions.get(created.sessionID);
694
964
  if (interim !== undefined && interim.channel !== channel) {
695
965
  this.removeRecord(interim);
@@ -710,9 +980,6 @@ export class Host {
710
980
  customizations,
711
981
  }),
712
982
  );
713
- const chatStore = createChatStateStore(
714
- initialChatState({ resource: chatChannelURI(created.sessionID), title: "Chat 1", modifiedAt: now }),
715
- );
716
983
  const rec: SessionRecord = {
717
984
  sessionID: created.sessionID,
718
985
  channel,
@@ -722,50 +989,48 @@ export class Host {
722
989
  ? new Date(created.time.updated).toISOString()
723
990
  : now,
724
991
  sessionStore,
725
- chatStore,
726
- currentTurnId: null,
727
- turnStartedAt: null,
728
- turnModelRef: null,
729
- parts: new Set(),
730
- toolInput: new Map(),
731
- toolName: new Map(),
732
- toolReady: new Set(),
733
- permissionForTool: new Map(),
734
- toolForPermission: new Map(),
735
- lastInbox: null,
736
- changesets: new Map(),
737
- turnSnapshots: new Map(),
992
+ chats: new Map(),
993
+ defaultChatURI: chatChannelURI(created.sessionID),
994
+ sessionChangesets: new Map(),
738
995
  };
739
996
  this.sessions.set(created.sessionID, rec);
740
997
  this.byChannel.set(channel, rec);
741
- this.byChannel.set(chatChannelURI(created.sessionID), rec);
742
998
  // The session channel carries the client-chosen suffix; the chat
743
999
  // channel and the event pump carry the opencode id — both must
744
1000
  // resolve in the registry.
745
1001
  this.channels.addSession(suffix);
746
1002
  this.channels.addSession(created.sessionID);
1003
+ const defaultChat = this.newChatRuntime(rec.defaultChatURI, created.sessionID, "Chat 1", now);
1004
+ this.bindChat(rec, defaultChat);
1005
+
1006
+ // A createSession `activeClient` seeds the
1007
+ // session's tools — register them with opencode now.
1008
+ if (activeClients.length > 0) void this.syncClientToolsToOpencode();
747
1009
 
748
1010
  // Session-channel lifecycle (server-side, no origin).
749
1011
  this.publish({ channel, action: { type: ActionType.SessionReady } });
750
1012
  this.publish({
751
1013
  channel,
752
- action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chatStore.state) },
1014
+ action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(defaultChat.chatStore.state) },
753
1015
  });
754
1016
  this.publish({
755
1017
  channel,
756
- action: { type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(created.sessionID) },
1018
+ action: { type: ActionType.SessionDefaultChatChanged, defaultChat: rec.defaultChatURI },
757
1019
  });
758
- // Phase 2: advertise the changeset catalogues (session channel: the
1020
+ // Advertise the changeset catalogues (session channel: the
759
1021
  // session-wide changeset; chat channel: uncommitted + session + the
760
1022
  // per-turn template).
761
1023
  if (this.opts.changesets) {
762
1024
  this.publish({
763
1025
  channel,
764
- action: { type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(created.sessionID) },
1026
+ action: { type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(channel) },
765
1027
  });
766
1028
  this.publish({
767
- channel: chatChannelURI(created.sessionID),
768
- action: { type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(created.sessionID) },
1029
+ channel: rec.defaultChatURI,
1030
+ action: {
1031
+ type: ActionType.ChatChangesetsChanged,
1032
+ changesets: chatChangesetCatalog(rec.defaultChatURI, channel),
1033
+ },
769
1034
  });
770
1035
  }
771
1036
  // Root: active-session count (action, replayed) + sessionAdded (notification).
@@ -781,6 +1046,291 @@ export class Host {
781
1046
  this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
782
1047
  }
783
1048
 
1049
+ // ── multi-chat ────────────────────────────────────
1050
+
1051
+ /**
1052
+ * Fresh per-chat runtime: one AHP chat = one opencode
1053
+ * session, with its own chat-state store and all the per-turn tracking
1054
+ * the event pump joins opencode events to.
1055
+ */
1056
+ private newChatRuntime(uri: string, sessionID: string, title: string, modifiedAt: string): ChatRuntime {
1057
+ return {
1058
+ uri,
1059
+ sessionID,
1060
+ chatStore: createChatStateStore(initialChatState({ resource: uri, title, modifiedAt })),
1061
+ currentTurnId: null,
1062
+ turnStartedAt: null,
1063
+ turnModelRef: null,
1064
+ parts: new Set(),
1065
+ toolInput: new Map(),
1066
+ toolName: new Map(),
1067
+ toolReady: new Set(),
1068
+ permissionForTool: new Map(),
1069
+ toolForPermission: new Map(),
1070
+ clientToolCalls: new Map(),
1071
+ lastInbox: null,
1072
+ changesets: new Map(),
1073
+ turnSnapshots: new Map(),
1074
+ };
1075
+ }
1076
+
1077
+ /**
1078
+ * Bind a chat runtime to its record: the record's catalog, the
1079
+ * channel→record lookup, and the opencode-id→(record, chat) reverse
1080
+ * binding (the event pump's join key). The channel registry gets the
1081
+ * chat URI's suffix — that is what makes the chat channel and its
1082
+ * changesets (whose owner is the chat channel) subscribable. The
1083
+ * default chat's suffix IS its opencode id, added by the
1084
+ * registration paths; a peer chat's opencode id gets no registry
1085
+ * entry (it has no subscribable session channel of its own).
1086
+ */
1087
+ private bindChat(rec: SessionRecord, chat: ChatRuntime): void {
1088
+ rec.chats.set(chat.uri, chat);
1089
+ this.byChannel.set(chat.uri, rec);
1090
+ this.byOpencode.set(chat.sessionID, { rec, chat });
1091
+ const suffix = sessionIDOf(chat.uri);
1092
+ if (suffix !== null) this.channels.addSession(suffix);
1093
+ }
1094
+
1095
+ /**
1096
+ * Unbind a chat runtime (dispose or record removal): clear its live
1097
+ * changesets (`changeset/cleared` — protocol case 2), fail its
1098
+ * in-flight client-tool executions (the waiters must not leak), and
1099
+ * drop every binding.
1100
+ */
1101
+ private removeChat(rec: SessionRecord, chat: ChatRuntime, toolError = "chat removed before the client completed the tool call"): void {
1102
+ // The chat's terminal channels go with it
1103
+ // (running commands get a final `terminal/exited` first).
1104
+ this.teardownTerminalsForChat(chat);
1105
+ for (const uri of chat.changesets.keys()) {
1106
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetCleared } });
1107
+ }
1108
+ chat.changesets.clear();
1109
+ chat.turnSnapshots.clear();
1110
+ for (const inv of chat.clientToolCalls.values()) {
1111
+ if (inv.result !== undefined) continue;
1112
+ inv.result = { ok: false, error: toolError };
1113
+ this.settleClientTool(inv);
1114
+ }
1115
+ chat.clientToolCalls.clear();
1116
+ rec.chats.delete(chat.uri);
1117
+ this.byChannel.delete(chat.uri);
1118
+ this.byOpencode.delete(chat.sessionID);
1119
+ const suffix = sessionIDOf(chat.uri);
1120
+ if (suffix !== null) this.channels.removeSession(suffix);
1121
+ this.channels.removeSession(chat.sessionID);
1122
+ }
1123
+
1124
+ /**
1125
+ * `createChat` (AHP 1.0.0 chat command): create a new chat in an
1126
+ * existing session. The 1:1 mapping: mint a fresh
1127
+ * opencode session (same provider/model resolution as `createSession`)
1128
+ * and bind it to the client-chosen chat URI. Result: `null` (the
1129
+ * client waits for `session/chatAdded` on the session channel, and
1130
+ * rolls back with `disposeChat` when the chat never surfaces — so
1131
+ * everything below is published before the response). `source` and
1132
+ * `workingDirectories` are rejected with INVALID_PARAMS: the
1133
+ * capability is advertised without fork/sideChat/
1134
+ * multipleWorkingDirectories, so conformant clients never send them.
1135
+ *
1136
+ * Error codes: -32602 (invalid params, including `source`/
1137
+ * `workingDirectories`), -32001 (no such session), -32003 (chat URI
1138
+ * already exists), -32603 (backend session creation or initial
1139
+ * message failure — the chat is rolled back in that case).
1140
+ */
1141
+ private async handleCreateChat(socketId: number, msg: RpcMessage): Promise<void> {
1142
+ const params = isRecord(msg.params) ? msg.params : {};
1143
+ const channel = params["channel"];
1144
+ const chatURI = params["chat"];
1145
+ if (typeof channel !== "string" || channelKind(channel) !== "session") {
1146
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat requires an ahp-session:/… channel");
1147
+ return;
1148
+ }
1149
+ const rec = this.byChannel.get(channel);
1150
+ if (rec === undefined) {
1151
+ this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such session: ${channel}`);
1152
+ return;
1153
+ }
1154
+ if (typeof chatURI !== "string" || channelKind(chatURI) !== "chat") {
1155
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat requires an ahp-chat:/… chat URI");
1156
+ return;
1157
+ }
1158
+ // A marker in the chat suffix would make the chat channel
1159
+ // string-identical to a changeset URI of the chat before the marker
1160
+ // (the same trap createSession rejects for session suffixes).
1161
+ if (chatURI.includes("/changeset/")) {
1162
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "chat URI must not contain \"/changeset/\"");
1163
+ return;
1164
+ }
1165
+ if (chatURI === rec.defaultChatURI || rec.chats.has(chatURI)) {
1166
+ this.sendError(socketId, msg.id, ERROR_SESSION_EXISTS, `chat already exists: ${chatURI}`);
1167
+ return;
1168
+ }
1169
+ if (params["source"] !== undefined) {
1170
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat `source` is not supported (no fork/sideChat capability)");
1171
+ return;
1172
+ }
1173
+ if (params["workingDirectories"] !== undefined) {
1174
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat `workingDirectories` is not supported (no multipleWorkingDirectories capability)");
1175
+ return;
1176
+ }
1177
+
1178
+ // Same provider/model resolution as createSession's default path:
1179
+ // the first non-disabled provider's first enabled model.
1180
+ const providers = await this.opts.facade.listCatalog();
1181
+ const provider = providers.find((p) => p.activation !== "disabled");
1182
+ const model = provider !== undefined ? firstEnabledModelRef(provider.models) : undefined;
1183
+ const now = new Date().toISOString();
1184
+ let created;
1185
+ try {
1186
+ // Write the chat-binding marker atomically at
1187
+ // create — it is what re-attaches this backend to this session's
1188
+ // chat catalog after an opencode/plugin restart (opencode session
1189
+ // metadata is the only durable surface a plugin has).
1190
+ created = await this.opts.facade.createSession({
1191
+ model,
1192
+ metadata: { [AHP_METADATA_KEY]: { chat: chatURI, owner: rec.sessionID } },
1193
+ });
1194
+ } catch (err) {
1195
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to create the chat's backend session: ${errorMessage(err)}`);
1196
+ return;
1197
+ }
1198
+ const chat = this.newChatRuntime(chatURI, created.sessionID, `Chat ${rec.chats.size + 1}`, now);
1199
+ this.bindChat(rec, chat);
1200
+ // Session-channel lifecycle (server-side, no origin): the catalog
1201
+ // mutation the client is waiting for, plus the changeset catalogue
1202
+ // on the new chat channel.
1203
+ this.publish({
1204
+ channel,
1205
+ action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chat.chatStore.state) },
1206
+ });
1207
+ if (this.opts.changesets) {
1208
+ this.publish({
1209
+ channel: chatURI,
1210
+ action: { type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(chatURI, rec.channel) },
1211
+ });
1212
+ }
1213
+
1214
+ // initialMessage → the chat's first turn (write-ahead, same
1215
+ // claim-then-prompt semantics as dispatchTurnStarted). A failure
1216
+ // rolls the whole chat back — the client never sees a chat whose
1217
+ // promised first turn never happened.
1218
+ const initialParam = params["initialMessage"];
1219
+ if (initialParam !== undefined) {
1220
+ if (!isRecord(initialParam) || typeof initialParam["text"] !== "string" || (initialParam["text"] as string).length === 0) {
1221
+ await this.disposeChatBackend(rec, chat);
1222
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat `initialMessage` requires a message with non-empty text");
1223
+ return;
1224
+ }
1225
+ const message = initialParam as unknown as Message;
1226
+ const selectionError = await this.applyMessageSelection(chat, message);
1227
+ if (selectionError !== null) {
1228
+ await this.disposeChatBackend(rec, chat);
1229
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to apply initial message model/agent selection: ${selectionError}`);
1230
+ return;
1231
+ }
1232
+ const turnId = this.mintTurnId();
1233
+ chat.currentTurnId = turnId;
1234
+ chat.turnStartedAt = Date.now();
1235
+ try {
1236
+ await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text });
1237
+ } catch (err) {
1238
+ chat.currentTurnId = null;
1239
+ chat.turnStartedAt = null;
1240
+ await this.disposeChatBackend(rec, chat);
1241
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, `initial message failed: ${errorMessage(err)}`);
1242
+ return;
1243
+ }
1244
+ this.publish({
1245
+ channel: chatURI,
1246
+ action: {
1247
+ type: ActionType.ChatTurnStarted,
1248
+ turnId,
1249
+ startedAt: new Date().toISOString(),
1250
+ message,
1251
+ },
1252
+ });
1253
+ }
1254
+
1255
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
1256
+ }
1257
+
1258
+ /**
1259
+ * `disposeChat` (AHP 1.0.0 chat command): remove a chat and its
1260
+ * opencode session from the session catalog. Result: `null`. The
1261
+ * default chat cannot be disposed — a session keeps its default chat
1262
+ * (there is no re-home mechanism; disposing it would leave the
1263
+ * `defaultChat` hint dangling). VS Code's createChat-rollback path
1264
+ * relies on `disposeChat` being answerable for any chat it created.
1265
+ */
1266
+ private async handleDisposeChat(socketId: number, msg: RpcMessage): Promise<void> {
1267
+ const params = isRecord(msg.params) ? msg.params : {};
1268
+ const channel = params["channel"];
1269
+ if (typeof channel !== "string" || channelKind(channel) !== "chat") {
1270
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "disposeChat requires an ahp-chat:/… channel");
1271
+ return;
1272
+ }
1273
+ const rec = this.byChannel.get(channel);
1274
+ const chat = rec !== undefined ? rec.chats.get(channel) : undefined;
1275
+ if (rec === undefined || chat === undefined) {
1276
+ this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such chat: ${channel}`);
1277
+ return;
1278
+ }
1279
+ if (channel === rec.defaultChatURI) {
1280
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "the default chat cannot be disposed");
1281
+ return;
1282
+ }
1283
+ await this.disposeChatBackend(rec, chat);
1284
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
1285
+ }
1286
+
1287
+ /**
1288
+ * Remove a chat from the AHP surface, then its opencode session. The
1289
+ * AHP-side unbind goes FIRST: opencode's `session.deleted` event for
1290
+ * the backend races this call through the event pump, and the pump
1291
+ * must see the chat already unbound (its `byOpencode` guard) or it
1292
+ * would publish a duplicate `session/chatRemoved`. R2: a failed
1293
+ * removal still drops the AHP chat — the lingering opencode session
1294
+ * shows up in the TUI (and lazily in `listSessions`) until deleted
1295
+ * there.
1296
+ */
1297
+ private async disposeChatBackend(rec: SessionRecord, chat: ChatRuntime): Promise<void> {
1298
+ this.removeChat(rec, chat);
1299
+ try {
1300
+ await this.opts.facade.removeSession(chat.sessionID);
1301
+ } catch (err) {
1302
+ this.log(`failed to remove the chat's opencode session ${chat.sessionID}: ${errorMessage(err)}`);
1303
+ }
1304
+ this.publish({ channel: rec.channel, action: { type: ActionType.SessionChatRemoved, chat: chat.uri } });
1305
+ }
1306
+
1307
+ /**
1308
+ * Apply a message's model/agent selection to a chat's opencode session
1309
+ * before its prompt (`SessionPromptInput` carries no model/agent
1310
+ * fields). Null on success, the error message on failure.
1311
+ */
1312
+ private async applyMessageSelection(chat: ChatRuntime, message: Message): Promise<string | null> {
1313
+ try {
1314
+ if (message.model?.id !== undefined && message.model.id.includes("/")) {
1315
+ const sep = message.model.id.indexOf("/");
1316
+ const providerID = message.model.id.slice(0, sep);
1317
+ const modelID = message.model.id.slice(sep + 1);
1318
+ if (providerID.length > 0 && modelID.length > 0) {
1319
+ await this.opts.facade.switchModel({ sessionID: chat.sessionID, model: { providerID, modelID } });
1320
+ }
1321
+ }
1322
+ if (message.agent?.uri !== undefined) {
1323
+ const agentID = agentIDFromUri(message.agent.uri);
1324
+ if (agentID !== null) {
1325
+ await this.opts.facade.switchAgent({ sessionID: chat.sessionID, agent: agentID });
1326
+ }
1327
+ }
1328
+ } catch (err) {
1329
+ return errorMessage(err);
1330
+ }
1331
+ return null;
1332
+ }
1333
+
784
1334
  /**
785
1335
  * `listSessions` (AHP 1.0.0 root command): all opencode sessions,
786
1336
  * most-recently-modified first, with in-memory cursor pagination.
@@ -819,11 +1369,44 @@ export class Host {
819
1369
  this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
820
1370
  }
821
1371
 
822
- // ── client-dispatchable actions (Phase 1) ──────────────────────────────
1372
+ /**
1373
+ * AHP 1.0.0 root command — the client resolves the session-creation
1374
+ * config schema. VS Code calls it every time the new-session composer
1375
+ * opens and STRICTLY again before the first send of a new session
1376
+ * (`_sendNewSessionRequest`), so an unimplemented host makes every
1377
+ * fresh session unstartable ("unknown method: resolveSessionConfig").
1378
+ * opencode collects no session-creation configuration —
1379
+ * agent/model choice rides session-state customizations and the
1380
+ * per-turn message — so the honest answer is an empty schema with
1381
+ * empty values. `provider` / `workingDirectory` / `config` are
1382
+ * accepted and deliberately unused: sessions run in the location
1383
+ * directory and the host advertises no config properties (which also
1384
+ * keeps `sessionConfigCompletions` unreachable — it only serves
1385
+ * `enumDynamic` properties this schema does not carry).
1386
+ */
1387
+ private handleResolveSessionConfig(socketId: number, msg: RpcMessage): void {
1388
+ const params = isRecord(msg.params) ? msg.params : {};
1389
+ if (params["channel"] !== ROOT_CHANNEL) {
1390
+ this.sendError(
1391
+ socketId,
1392
+ msg.id,
1393
+ ERROR_INVALID_PARAMS,
1394
+ "resolveSessionConfig requires the ahp-root:// channel",
1395
+ );
1396
+ return;
1397
+ }
1398
+ const result: ResolveSessionConfigResult = {
1399
+ schema: { type: "object", properties: {} },
1400
+ values: {},
1401
+ };
1402
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
1403
+ }
1404
+
1405
+ // ── client-dispatchable actions ──────────────────────────────
823
1406
 
824
1407
  /**
825
1408
  * `dispatchAction` is a notification — the response is the `action`
826
- * notification stream itself. Phase 1 routes the client-dispatchable
1409
+ * notification stream itself. The host routes the client-dispatchable
827
1410
  * actions VS Code sends; everything else is acknowledged with a
828
1411
  * rejection on that stream.
829
1412
  */
@@ -866,29 +1449,76 @@ export class Host {
866
1449
  }
867
1450
  return;
868
1451
  }
1452
+ if (kind === "terminal") {
1453
+ // The synthetic terminals are read-only
1454
+ // renderings of shell-tool calls — every client-dispatchable
1455
+ // action (`input`, `resized`, `claimed`, `titleChanged`,
1456
+ // `cleared`) has no pty to act on, so each gets an explicit
1457
+ // rejection (write-ahead clients roll back on the reason); the
1458
+ // `no such terminal` check covers a channel whose chat was removed.
1459
+ this.echo(
1460
+ channel,
1461
+ stateAction,
1462
+ origin,
1463
+ this.terminals.has(channel)
1464
+ ? "read-only terminal: this host's terminals render shell tool calls and accept no input, resize, claim, title, or clear"
1465
+ : `no such terminal: ${channel}`,
1466
+ );
1467
+ return;
1468
+ }
869
1469
  if (kind !== "session" && kind !== "chat") {
870
1470
  this.echo(channel, stateAction, origin, `unsupported action on ${channelKind(channel)} channel: ${String(action.type)}`);
871
1471
  return;
872
1472
  }
873
1473
  const rec = this.byChannel.get(channel);
874
1474
  if (rec === undefined) {
875
- this.echo(channel, stateAction, origin, `no such session: ${channel}`);
1475
+ this.echo(
1476
+ channel,
1477
+ stateAction,
1478
+ origin,
1479
+ kind === "chat" ? `no such chat: ${channel}` : `no such session: ${channel}`,
1480
+ );
1481
+ return;
1482
+ }
1483
+ if (kind === "chat" && !rec.chats.has(channel)) {
1484
+ this.echo(channel, stateAction, origin, `no such chat: ${channel}`);
876
1485
  return;
877
1486
  }
1487
+ // Chat actions run against the owning chat runtime;
1488
+ // a chat action on a session channel is rejected (a session no
1489
+ // longer identifies a single chat once multi-chat is on).
1490
+ const chat = rec.chats.get(channel);
1491
+ const noChat = () => this.echo(channel, stateAction, origin, `chat actions require a chat channel: ${channel}`);
878
1492
 
879
1493
  // From here on every branch either echoes (accepted or rejected).
880
1494
  switch (stateAction.type) {
881
1495
  case ActionType.ChatTurnStarted:
882
- await this.dispatchTurnStarted(rec, stateAction, origin);
1496
+ if (chat === undefined) { noChat(); return; }
1497
+ await this.dispatchTurnStarted(chat, stateAction, origin);
883
1498
  return;
884
1499
  case ActionType.ChatPendingMessageSet:
885
- await this.dispatchPendingMessageSet(rec, stateAction, origin);
1500
+ if (chat === undefined) { noChat(); return; }
1501
+ await this.dispatchPendingMessageSet(chat, stateAction, origin);
886
1502
  return;
887
1503
  case ActionType.ChatToolCallConfirmed:
888
- await this.dispatchToolCallConfirmed(rec, stateAction, origin);
1504
+ if (chat === undefined) { noChat(); return; }
1505
+ await this.dispatchToolCallConfirmed(chat, stateAction, origin);
1506
+ return;
1507
+ case ActionType.ChatToolCallComplete:
1508
+ if (chat === undefined) { noChat(); return; }
1509
+ await this.dispatchToolCallComplete(chat, stateAction, origin);
1510
+ return;
1511
+ case ActionType.ChatToolCallContentChanged:
1512
+ if (chat === undefined) { noChat(); return; }
1513
+ this.dispatchToolCallContentChanged(chat, stateAction, origin);
1514
+ return;
1515
+ case ActionType.ChatToolCallResultConfirmed:
1516
+ if (chat === undefined) { noChat(); return; }
1517
+ this.dispatchToolCallResultConfirmed(chat, stateAction, origin);
889
1518
  return;
890
1519
  case ActionType.ChatTurnCancelled:
891
- await this.dispatchTurnCancelled(rec, stateAction, origin);
1520
+ if (chat === undefined) { noChat(); return; }
1521
+ await this.dispatchTurnCancelled(chat, stateAction, origin);
892
1522
  return;
893
1523
  case ActionType.SessionTitleChanged:
894
1524
  await this.dispatchTitleChanged(rec, stateAction, origin);
@@ -912,7 +1542,7 @@ export class Host {
912
1542
  this.echo(channel, stateAction, origin);
913
1543
  return;
914
1544
  default:
915
- this.echo(channel, stateAction, origin, `unsupported action (Phase 1): ${String(stateAction.type)}`);
1545
+ this.echo(channel, stateAction, origin, `unsupported action: ${String(stateAction.type)}`);
916
1546
  }
917
1547
  }
918
1548
 
@@ -965,8 +1595,8 @@ export class Host {
965
1595
  return undefined;
966
1596
  }
967
1597
 
968
- private async dispatchTurnStarted(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
969
- const chatURI = chatChannelURI(rec.sessionID);
1598
+ private async dispatchTurnStarted(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1599
+ const chatURI = chat.uri;
970
1600
  const a = action as ChatTurnStartedAction;
971
1601
  const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
972
1602
  const message =
@@ -984,7 +1614,7 @@ export class Host {
984
1614
  typeof a.startedAt === "string" && !Number.isNaN(Date.parse(a.startedAt))
985
1615
  ? a
986
1616
  : { ...a, startedAt: new Date().toISOString() };
987
- if (rec.chatStore.state.activeTurn !== undefined) {
1617
+ if (chat.chatStore.state.activeTurn !== undefined) {
988
1618
  this.echo(
989
1619
  chatURI,
990
1620
  action,
@@ -994,46 +1624,32 @@ export class Host {
994
1624
  return;
995
1625
  }
996
1626
 
997
- // Apply the message's model/agent selection before the prompt
998
- // (`SessionPromptInput` carries no model/agent fields).
999
- try {
1000
- if (message.model?.id !== undefined && message.model.id.includes("/")) {
1001
- const sep = message.model.id.indexOf("/");
1002
- const providerID = message.model.id.slice(0, sep);
1003
- const modelID = message.model.id.slice(sep + 1);
1004
- if (providerID.length > 0 && modelID.length > 0) {
1005
- await this.opts.facade.switchModel({ sessionID: rec.sessionID, model: { providerID, modelID } });
1006
- }
1007
- }
1008
- if (message.agent?.uri !== undefined) {
1009
- const agentID = agentIDFromUri(message.agent.uri);
1010
- if (agentID !== null) {
1011
- await this.opts.facade.switchAgent({ sessionID: rec.sessionID, agent: agentID });
1012
- }
1013
- }
1014
- } catch (err) {
1015
- this.echo(chatURI, action, origin, `failed to apply model/agent selection: ${errorMessage(err)}`);
1627
+ // Apply the message's model/agent selection to THIS chat's opencode
1628
+ // session before the prompt (per-chat isolation).
1629
+ const selectionError = await this.applyMessageSelection(chat, message);
1630
+ if (selectionError !== null) {
1631
+ this.echo(chatURI, action, origin, `failed to apply model/agent selection: ${selectionError}`);
1016
1632
  return;
1017
1633
  }
1018
1634
 
1019
1635
  // Write-ahead: claim the turn BEFORE the prompt so the
1020
1636
  // `session.execution.started` event joins it even when it races the
1021
1637
  // prompt's resolve; revert on failure.
1022
- rec.currentTurnId = turnId;
1023
- rec.turnStartedAt = Date.now();
1638
+ chat.currentTurnId = turnId;
1639
+ chat.turnStartedAt = Date.now();
1024
1640
  try {
1025
- await this.opts.facade.prompt({ sessionID: rec.sessionID, text: message.text });
1641
+ await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text });
1026
1642
  } catch (err) {
1027
- rec.currentTurnId = null;
1028
- rec.turnStartedAt = null;
1643
+ chat.currentTurnId = null;
1644
+ chat.turnStartedAt = null;
1029
1645
  this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
1030
1646
  return;
1031
1647
  }
1032
1648
  this.echo(chatURI, normalized, origin);
1033
1649
  }
1034
1650
 
1035
- private async dispatchPendingMessageSet(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1036
- const chatURI = chatChannelURI(rec.sessionID);
1651
+ private async dispatchPendingMessageSet(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1652
+ const chatURI = chat.uri;
1037
1653
  const a = action as { kind?: unknown; id?: unknown; message?: unknown };
1038
1654
  const kind = a.kind === "steering" || a.kind === "queued" ? a.kind : null;
1039
1655
  const id = typeof a.id === "string" && a.id.length > 0 ? a.id : null;
@@ -1045,7 +1661,7 @@ export class Host {
1045
1661
  this.echo(chatURI, action, origin, "invalid chat/pendingMessageSet params");
1046
1662
  return;
1047
1663
  }
1048
- const hasActiveTurn = rec.chatStore.state.activeTurn !== undefined;
1664
+ const hasActiveTurn = chat.chatStore.state.activeTurn !== undefined;
1049
1665
  // steer → delivery "steer" (only while a turn is active); queued →
1050
1666
  // delivery "queue"; a steering message with no active turn falls back
1051
1667
  // to a plain prompt (it becomes the next turn).
@@ -1055,7 +1671,7 @@ export class Host {
1055
1671
  : "queue"
1056
1672
  : undefined;
1057
1673
  try {
1058
- await this.opts.facade.prompt({ sessionID: rec.sessionID, text: message.text, delivery });
1674
+ await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text, delivery });
1059
1675
  } catch (err) {
1060
1676
  this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
1061
1677
  return;
@@ -1069,8 +1685,8 @@ export class Host {
1069
1685
  // `queuedMessageId` — the reducer dequeues it.
1070
1686
  this.echo(chatURI, action, origin);
1071
1687
  const turnId = this.mintTurnId();
1072
- rec.currentTurnId = turnId;
1073
- rec.turnStartedAt = Date.now();
1688
+ chat.currentTurnId = turnId;
1689
+ chat.turnStartedAt = Date.now();
1074
1690
  this.publish({
1075
1691
  channel: chatURI,
1076
1692
  action: {
@@ -1083,22 +1699,23 @@ export class Host {
1083
1699
  });
1084
1700
  }
1085
1701
 
1086
- private async dispatchToolCallConfirmed(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1087
- const chatURI = chatChannelURI(rec.sessionID);
1702
+ private async dispatchToolCallConfirmed(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1703
+ const chatURI = chat.uri;
1704
+ const rec = this.byChannel.get(chatURI)!;
1088
1705
  const a = action as ChatToolCallConfirmedAction;
1089
1706
  const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
1090
1707
  if (toolCallId === null) {
1091
1708
  this.echo(chatURI, action, origin, "invalid chat/toolCallConfirmed params");
1092
1709
  return;
1093
1710
  }
1094
- const permissionID = rec.permissionForTool.get(toolCallId);
1711
+ const permissionID = chat.permissionForTool.get(toolCallId);
1095
1712
  if (permissionID === undefined) {
1096
1713
  this.echo(chatURI, action, origin, `no pending permission for tool call ${toolCallId}`);
1097
1714
  return;
1098
1715
  }
1099
1716
  try {
1100
1717
  await this.opts.facade.replyPermission({
1101
- sessionID: rec.sessionID,
1718
+ sessionID: chat.sessionID,
1102
1719
  requestID: permissionID,
1103
1720
  decision: a.approved === true ? "once" : "reject",
1104
1721
  });
@@ -1114,21 +1731,174 @@ export class Host {
1114
1731
  channel: rec.channel,
1115
1732
  action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
1116
1733
  });
1117
- rec.permissionForTool.delete(toolCallId);
1118
- rec.toolForPermission.delete(permissionID);
1734
+ chat.permissionForTool.delete(toolCallId);
1735
+ chat.toolForPermission.delete(permissionID);
1119
1736
  }
1120
1737
 
1121
- private async dispatchTurnCancelled(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1122
- const chatURI = chatChannelURI(rec.sessionID);
1738
+ // ── client-executed tool calls ───────────────────
1739
+
1740
+ /**
1741
+ * `chat/toolCallComplete` (client-dispatchable): the owning client
1742
+ * finished executing a delegated tool call. Only valid for
1743
+ * client-executed calls (the host emits its own complete for
1744
+ * server-executed ones); the dispatching client must be the
1745
+ * contributor. Echoes the action (reducer: running → completed, or
1746
+ * → pending-result-confirmation when `requiresResultConfirmation`),
1747
+ * clears the execution input request, and settles the opencode-side
1748
+ * waiter with the client's result.
1749
+ */
1750
+ private async dispatchToolCallComplete(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1751
+ const chatURI = chat.uri;
1752
+ const rec = this.byChannel.get(chatURI)!;
1753
+ const a = action as ChatToolCallCompleteAction;
1754
+ const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
1755
+ const invocation = toolCallId !== null ? chat.clientToolCalls.get(toolCallId) : undefined;
1756
+ if (toolCallId === null || invocation === undefined) {
1757
+ this.echo(chatURI, action, origin, `tool call ${toolCallId ?? "?"} is not a client-executed call`);
1758
+ return;
1759
+ }
1760
+ if (origin !== undefined && invocation.clientId !== origin.clientId) {
1761
+ this.echo(chatURI, action, origin, `only the contributing client (${invocation.clientId}) may complete this call`);
1762
+ return;
1763
+ }
1764
+ const result = normalizeToolCallResult(a.result);
1765
+ if (result === null) {
1766
+ this.echo(chatURI, action, origin, "invalid chat/toolCallComplete params (result.success must be a boolean)");
1767
+ return;
1768
+ }
1769
+ const status = this.toolCallState(chat, toolCallId)?.status;
1770
+ if (status !== ToolCallStatus.Running && status !== ToolCallStatus.PendingConfirmation) {
1771
+ this.echo(chatURI, action, origin, `tool call ${toolCallId} is not ready to complete (status ${status ?? "absent"})`);
1772
+ return;
1773
+ }
1774
+ const requiresConfirmation = a.requiresResultConfirmation === true;
1775
+ // Echo first: the reducer moves running → completed (or
1776
+ // pending-result-confirmation); the settle below must observe the
1777
+ // new state for the confirmation input request.
1778
+ this.echo(chatURI, action, origin);
1779
+ if (requiresConfirmation) {
1780
+ // Hold the client's result until the approval reply; surface the
1781
+ // user-facing confirmation on the session channel (this variant,
1782
+ // unlike the execution request, raises SessionStatus.InputNeeded).
1783
+ invocation.pendingResult = result;
1784
+ const pending = this.pendingToolCall(chat, toolCallId);
1785
+ if (pending !== null && chat.currentTurnId !== null) {
1786
+ this.publish({
1787
+ channel: rec.channel,
1788
+ action: {
1789
+ type: ActionType.SessionInputNeededSet,
1790
+ request: {
1791
+ id: toolCallId,
1792
+ chat: chatURI,
1793
+ kind: SessionInputRequestKind.ToolConfirmation,
1794
+ turnId: chat.currentTurnId,
1795
+ toolCall: pending,
1796
+ } satisfies SessionToolConfirmationRequest,
1797
+ },
1798
+ });
1799
+ }
1800
+ } else {
1801
+ this.publish({
1802
+ channel: rec.channel,
1803
+ action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
1804
+ });
1805
+ this.settleClientTool(invocation, clientResultToFacade(result));
1806
+ }
1807
+ }
1808
+
1809
+ /**
1810
+ * `chat/toolCallContentChanged` (client-dispatchable): the owning
1811
+ * client streams partial content while executing (the reducer
1812
+ * replaces the running call's `content`). Echo-only — opencode needs
1813
+ * no counterpart; the spec says the server SHOULD reject dispatches
1814
+ * from a client that is not the contributor.
1815
+ */
1816
+ private dispatchToolCallContentChanged(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): void {
1817
+ const chatURI = chat.uri;
1818
+ const a = action as ChatToolCallContentChangedAction;
1819
+ const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
1820
+ const invocation = toolCallId !== null ? chat.clientToolCalls.get(toolCallId) : undefined;
1821
+ if (toolCallId === null || invocation === undefined) {
1822
+ this.echo(chatURI, action, origin, `tool call ${toolCallId ?? "?"} is not a client-executed call`);
1823
+ return;
1824
+ }
1825
+ if (origin !== undefined && invocation.clientId !== origin.clientId) {
1826
+ this.echo(chatURI, action, origin, `only the contributing client (${invocation.clientId}) may stream content for this call`);
1827
+ return;
1828
+ }
1829
+ if (!Array.isArray(a.content)) {
1830
+ this.echo(chatURI, action, origin, "invalid chat/toolCallContentChanged params (content must be an array)");
1831
+ return;
1832
+ }
1833
+ if (this.toolCallState(chat, toolCallId)?.status !== ToolCallStatus.Running) {
1834
+ this.echo(chatURI, action, origin, `tool call ${toolCallId} is not running`);
1835
+ return;
1836
+ }
1837
+ this.echo(chatURI, action, origin);
1838
+ }
1839
+
1840
+ /**
1841
+ * `chat/toolCallResultConfirmed` (client-dispatchable): the user
1842
+ * approved or denied a client tool's result after a
1843
+ * `requiresResultConfirmation` completion. Echoes (reducer:
1844
+ * pending-result-confirmation → completed / cancelled with reason
1845
+ * `result-denied`), clears the confirmation input request, and
1846
+ * settles the opencode-side waiter (approved → the held client
1847
+ * result; denied → a Tool.Error the model sees).
1848
+ */
1849
+ private dispatchToolCallResultConfirmed(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): void {
1850
+ const chatURI = chat.uri;
1851
+ const rec = this.byChannel.get(chatURI)!;
1852
+ const a = action as ChatToolCallResultConfirmedAction;
1853
+ const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
1854
+ if (toolCallId === null || typeof a.approved !== "boolean") {
1855
+ this.echo(chatURI, action, origin, "invalid chat/toolCallResultConfirmed params");
1856
+ return;
1857
+ }
1858
+ const invocation = chat.clientToolCalls.get(toolCallId);
1859
+ if (invocation === undefined) {
1860
+ this.echo(chatURI, action, origin, `no pending result confirmation for tool call ${toolCallId}`);
1861
+ return;
1862
+ }
1863
+ if (origin !== undefined && invocation.clientId !== origin.clientId) {
1864
+ this.echo(chatURI, action, origin, `only the contributing client (${invocation.clientId}) may confirm this result`);
1865
+ return;
1866
+ }
1867
+ if (this.toolCallState(chat, toolCallId)?.status !== ToolCallStatus.PendingResultConfirmation) {
1868
+ this.echo(chatURI, action, origin, `tool call ${toolCallId} is not awaiting result confirmation`);
1869
+ return;
1870
+ }
1871
+ this.echo(chatURI, action, origin);
1872
+ this.publish({
1873
+ channel: rec.channel,
1874
+ action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
1875
+ });
1876
+ const held = invocation.pendingResult;
1877
+ if (held === undefined) {
1878
+ // Unreachable in practice (the state only reaches
1879
+ // pending-result-confirmation through our complete path); fail
1880
+ // closed so the opencode tool cannot hang.
1881
+ this.settleClientTool(invocation, { ok: false, error: "no recorded result to confirm" });
1882
+ return;
1883
+ }
1884
+ if (a.approved) {
1885
+ this.settleClientTool(invocation, clientResultToFacade(held as ToolCallResult));
1886
+ } else {
1887
+ this.settleClientTool(invocation, { ok: false, error: "the client denied the tool result" });
1888
+ }
1889
+ }
1890
+
1891
+ private async dispatchTurnCancelled(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1892
+ const chatURI = chat.uri;
1123
1893
  const a = action as ChatTurnCancelledAction;
1124
1894
  const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
1125
- const active = rec.chatStore.state.activeTurn;
1895
+ const active = chat.chatStore.state.activeTurn;
1126
1896
  if (turnId === null || active === undefined || active.id !== turnId) {
1127
1897
  this.echo(chatURI, action, origin, "no active turn to cancel");
1128
1898
  return;
1129
1899
  }
1130
1900
  try {
1131
- await this.opts.facade.interrupt({ sessionID: rec.sessionID });
1901
+ await this.opts.facade.interrupt({ sessionID: chat.sessionID });
1132
1902
  } catch (err) {
1133
1903
  this.echo(chatURI, action, origin, `interrupt failed: ${errorMessage(err)}`);
1134
1904
  return;
@@ -1137,12 +1907,12 @@ export class Host {
1137
1907
  // `modifiedAt` from it); the host clock is authoritative when the
1138
1908
  // client did not supply one.
1139
1909
  const duration =
1140
- typeof a.duration === "number" && Number.isFinite(a.duration) ? a.duration : this.turnDuration(rec);
1910
+ typeof a.duration === "number" && Number.isFinite(a.duration) ? a.duration : this.turnDuration(chat);
1141
1911
  this.echo(chatURI, { ...a, duration }, origin);
1142
1912
  // The opencode `session.execution.interrupted` event finds no active
1143
1913
  // turn after the echo finalized it (skipped); run the queued/steering
1144
1914
  // handoff now, on the host side.
1145
- await this.finishTurn(rec);
1915
+ await this.finishTurn(chat);
1146
1916
  }
1147
1917
 
1148
1918
  /**
@@ -1157,8 +1927,8 @@ export class Host {
1157
1927
  return;
1158
1928
  }
1159
1929
  const parsed = parseChangesetChannel(channel);
1160
- const rec = parsed !== null ? this.sessions.get(parsed.sessionID) : undefined;
1161
- const store = rec !== undefined ? rec.changesets.get(channel) : undefined;
1930
+ const rec = parsed !== null ? this.byChannel.get(parsed.ownerUri) : undefined;
1931
+ const store = rec !== undefined ? this.changesetStoreOf(rec, channel) : undefined;
1162
1932
  if (rec === undefined || store === undefined) {
1163
1933
  this.echo(channel, action, origin, "no such changeset");
1164
1934
  return;
@@ -1194,7 +1964,7 @@ export class Host {
1194
1964
  this.echo(rec.channel, action, origin, "activeClient.clientId must match the dispatching client");
1195
1965
  return;
1196
1966
  }
1197
- const tools = Array.isArray(ac["tools"]) ? (ac["tools"] as ToolDefinition[]) : [];
1967
+ const tools = normalizeToolDefinitions(ac["tools"]);
1198
1968
  const normalized: SessionActiveClient = {
1199
1969
  clientId: ac["clientId"] as string,
1200
1970
  tools,
@@ -1205,6 +1975,9 @@ export class Host {
1205
1975
  action: { type: ActionType.SessionActiveClientSet, activeClient: normalized },
1206
1976
  origin,
1207
1977
  });
1978
+ // The session's tool contribution changed —
1979
+ // re-sync the location-global opencode tool union.
1980
+ void this.syncClientToolsToOpencode();
1208
1981
  }
1209
1982
 
1210
1983
  private dispatchActiveClientRemoved(
@@ -1219,13 +1992,19 @@ export class Host {
1219
1992
  return;
1220
1993
  }
1221
1994
  this.echo(rec.channel, action, origin);
1995
+ // The session's tool contribution shrank —
1996
+ // re-sync the location-global opencode tool union.
1997
+ void this.syncClientToolsToOpencode();
1222
1998
  }
1223
1999
 
1224
2000
  // ── opencode event pump handlers ───────────────────────────────────────
1225
2001
 
1226
2002
  private async handleEvent(ev: FacadeEvent): Promise<void> {
1227
2003
  if (ev.type === "session.created") {
1228
- if (this.sessions.has(ev.sessionID)) return;
2004
+ // Every live chat has its own opencode session, so a
2005
+ // created event for an already-bound id is ours (a createChat
2006
+ // backend) and never an external session.
2007
+ if (this.sessions.has(ev.sessionID) || this.byOpencode.has(ev.sessionID)) return;
1229
2008
  // Deferred registration: a concurrent `createSession` may still be
1230
2009
  // resolving for this opencode session under a client-chosen channel;
1231
2010
  // the grace + existence check avoids the double registration, and
@@ -1240,69 +2019,90 @@ export class Host {
1240
2019
  return;
1241
2020
  }
1242
2021
 
1243
- const rec = this.sessions.get(ev.sessionID);
1244
- if (rec === undefined) return; // only session.created registers sessions
1245
-
1246
- const chatURI = chatChannelURI(rec.sessionID);
2022
+ // The opencode session id joins to (record, chat) — every chat has
2023
+ // its own backend session, and per-turn state lives on the chat.
2024
+ // Only session.created registers sessions.
2025
+ const binding = this.byOpencode.get(ev.sessionID);
2026
+ if (binding === undefined) return;
2027
+ const { rec, chat } = binding;
2028
+ const chatURI = chat.uri;
1247
2029
  switch (ev.type) {
1248
2030
  case "session.deleted":
1249
- this.removeRecord(rec);
2031
+ if (chat.uri === rec.defaultChatURI) {
2032
+ this.removeRecord(rec);
2033
+ } else {
2034
+ // Peer-chat backend gone (deleted in the TUI or by another
2035
+ // surface): drop the AHP chat only — the record and its other
2036
+ // chats stay.
2037
+ this.removeChat(rec, chat);
2038
+ this.publish({ channel: rec.channel, action: { type: ActionType.SessionChatRemoved, chat: chat.uri } });
2039
+ }
1250
2040
  return;
1251
2041
  case "session.renamed":
1252
- this.publish({ channel: rec.channel, action: { type: ActionType.SessionTitleChanged, title: ev.title } });
2042
+ if (chat.uri === rec.defaultChatURI) {
2043
+ this.publish({ channel: rec.channel, action: { type: ActionType.SessionTitleChanged, title: ev.title } });
2044
+ } else {
2045
+ // No chat-title session action exists; the chat summary carries
2046
+ // the title (the chat store's own title stays original — same
2047
+ // pre-existing behavior as the default chat's titleChanged).
2048
+ this.publish({
2049
+ channel: rec.channel,
2050
+ action: { type: ActionType.SessionChatUpdated, chat: chat.uri, changes: { title: ev.title } },
2051
+ });
2052
+ }
1253
2053
  return;
1254
2054
  case "inbox.enqueued":
1255
- rec.lastInbox = { text: ev.text, delivery: ev.delivery };
2055
+ chat.lastInbox = { text: ev.text, delivery: ev.delivery };
1256
2056
  return;
1257
2057
  case "inbox.delivered":
1258
2058
  // Steering consumption is handled at turn end (finishTurn).
1259
2059
  return;
1260
2060
  case "execution.started":
1261
- if (rec.currentTurnId !== null) return; // write-ahead already claimed the turn
2061
+ if (chat.currentTurnId !== null) return; // write-ahead already claimed the turn
1262
2062
  // Orphan turn (an external TUI prompt, or a handoff this host did
1263
2063
  // not initiate): start it with the last-seen inbox message.
1264
- this.startTurn(rec, rec.lastInbox !== null ? userMessage(rec.lastInbox.text) : userMessage(""));
2064
+ this.startTurn(chat, chat.lastInbox !== null ? userMessage(chat.lastInbox.text) : userMessage(""));
1265
2065
  return;
1266
2066
  case "execution.succeeded":
1267
- if (rec.currentTurnId === null) return;
2067
+ if (chat.currentTurnId === null) return;
1268
2068
  this.publish({
1269
2069
  channel: chatURI,
1270
- action: { type: ActionType.ChatTurnComplete, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
2070
+ action: { type: ActionType.ChatTurnComplete, turnId: chat.currentTurnId, duration: this.turnDuration(chat) },
1271
2071
  });
1272
- await this.finishTurn(rec);
2072
+ await this.finishTurn(chat);
1273
2073
  return;
1274
2074
  case "execution.failed":
1275
- if (rec.currentTurnId === null) return;
2075
+ if (chat.currentTurnId === null) return;
1276
2076
  const part: ErrorResponsePart = {
1277
2077
  kind: ResponsePartKind.Error,
1278
2078
  error: { errorType: ev.error.type, message: ev.error.message },
1279
2079
  };
1280
2080
  this.publish({
1281
2081
  channel: chatURI,
1282
- action: { type: ActionType.ChatError, turnId: rec.currentTurnId, duration: this.turnDuration(rec), part },
2082
+ action: { type: ActionType.ChatError, turnId: chat.currentTurnId, duration: this.turnDuration(chat), part },
1283
2083
  });
1284
- await this.finishTurn(rec);
2084
+ await this.finishTurn(chat);
1285
2085
  return;
1286
2086
  case "execution.interrupted":
1287
2087
  // Skipped when the client's own `chat/turnCancelled` echo already
1288
2088
  // finalized the turn (currentTurnId is null).
1289
- if (rec.currentTurnId === null) return;
2089
+ if (chat.currentTurnId === null) return;
1290
2090
  this.publish({
1291
2091
  channel: chatURI,
1292
- action: { type: ActionType.ChatTurnCancelled, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
2092
+ action: { type: ActionType.ChatTurnCancelled, turnId: chat.currentTurnId, duration: this.turnDuration(chat) },
1293
2093
  });
1294
- await this.finishTurn(rec);
2094
+ await this.finishTurn(chat);
1295
2095
  return;
1296
2096
  case "step.started":
1297
- rec.turnModelRef = `${ev.model.providerID}/${ev.model.modelID}`;
2097
+ chat.turnModelRef = `${ev.model.providerID}/${ev.model.modelID}`;
1298
2098
  return;
1299
2099
  case "text.delta":
1300
2100
  case "reasoning.delta": {
1301
- if (rec.currentTurnId === null) return;
2101
+ if (chat.currentTurnId === null) return;
1302
2102
  const kind = ev.type === "text.delta" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
1303
2103
  const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
1304
- const first = !rec.parts.has(key);
1305
- rec.parts.add(key);
2104
+ const first = !chat.parts.has(key);
2105
+ chat.parts.add(key);
1306
2106
  const partId = `part-${key}`;
1307
2107
  if (first) {
1308
2108
  // Lazily emit the part on the first delta; it carries the
@@ -1311,7 +2111,7 @@ export class Host {
1311
2111
  channel: chatURI,
1312
2112
  action: {
1313
2113
  type: ActionType.ChatResponsePart,
1314
- turnId: rec.currentTurnId,
2114
+ turnId: chat.currentTurnId,
1315
2115
  part: { kind, id: partId, content: ev.delta },
1316
2116
  },
1317
2117
  });
@@ -1320,73 +2120,126 @@ export class Host {
1320
2120
  channel: chatURI,
1321
2121
  action:
1322
2122
  kind === ResponsePartKind.Markdown
1323
- ? { type: ActionType.ChatDelta, turnId: rec.currentTurnId, partId, content: ev.delta }
1324
- : { type: ActionType.ChatReasoning, turnId: rec.currentTurnId, partId, content: ev.delta },
2123
+ ? { type: ActionType.ChatDelta, turnId: chat.currentTurnId, partId, content: ev.delta }
2124
+ : { type: ActionType.ChatReasoning, turnId: chat.currentTurnId, partId, content: ev.delta },
1325
2125
  });
1326
2126
  }
1327
2127
  return;
1328
2128
  }
1329
2129
  case "text.ended":
1330
2130
  case "reasoning.ended": {
1331
- if (rec.currentTurnId === null) return;
2131
+ if (chat.currentTurnId === null) return;
1332
2132
  // Fallback for non-streaming providers that emit only the final
1333
2133
  // text: if no delta opened the part, emit it now with the full text.
1334
2134
  const kind = ev.type === "text.ended" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
1335
2135
  const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
1336
- if (!rec.parts.has(key)) {
1337
- rec.parts.add(key);
2136
+ if (!chat.parts.has(key)) {
2137
+ chat.parts.add(key);
1338
2138
  this.publish({
1339
2139
  channel: chatURI,
1340
2140
  action: {
1341
2141
  type: ActionType.ChatResponsePart,
1342
- turnId: rec.currentTurnId,
2142
+ turnId: chat.currentTurnId,
1343
2143
  part: { kind, id: `part-${key}`, content: ev.text },
1344
2144
  },
1345
2145
  });
1346
2146
  }
1347
2147
  return;
1348
2148
  }
1349
- case "tool.input.started":
1350
- if (rec.currentTurnId === null) {
1351
- this.log(`tool.input.started outside a turn (session ${rec.sessionID}, tool ${ev.name}); ignored`);
2149
+ case "tool.input.started": {
2150
+ if (chat.currentTurnId === null) {
2151
+ this.log(`tool.input.started outside a turn (session ${chat.sessionID}, tool ${ev.name}); ignored`);
1352
2152
  return;
1353
2153
  }
1354
- rec.toolName.set(ev.id, ev.name);
2154
+ chat.toolName.set(ev.id, ev.name);
2155
+ // When the session's active clients provide
2156
+ // this tool, the call is client-executed — the client
2157
+ // `contributor` must be established at start (the official
2158
+ // reducer ignores a late one), and the call is tracked for the
2159
+ // `execute` bridge + the client's dispatchable actions.
2160
+ // (Active clients are session-level; the chat tracks the call.)
2161
+ const clientTool = this.clientToolContributor(rec, ev.name);
2162
+ if (clientTool !== null) {
2163
+ chat.clientToolCalls.set(ev.id, { clientId: clientTool, turnId: chat.currentTurnId });
2164
+ }
1355
2165
  this.publish({
1356
2166
  channel: chatURI,
1357
2167
  action: {
1358
2168
  type: ActionType.ChatToolCallStart,
1359
- turnId: rec.currentTurnId,
2169
+ turnId: chat.currentTurnId,
1360
2170
  toolCallId: ev.id,
1361
2171
  toolName: ev.name,
1362
2172
  displayName: displayNameFor(ev.name),
2173
+ ...(clientTool !== null
2174
+ ? { contributor: { kind: ToolCallContributorKind.Client, clientId: clientTool } }
2175
+ : {}),
1363
2176
  },
1364
2177
  });
1365
2178
  return;
1366
- case "tool.input.ended":
1367
- rec.toolInput.set(ev.id, ev.text);
1368
- // Phase 2: for file-mutating tools, capture the pre-edit file
2179
+ }
2180
+ case "tool.input.ended": {
2181
+ chat.toolInput.set(ev.id, ev.text);
2182
+ // For file-mutating tools, capture the pre-edit file
1369
2183
  // content now (the event fires before execution — the last safe
1370
2184
  // point). Awaited in the sequential pump so the capture is
1371
2185
  // complete before `execution.*` can end the turn.
1372
- if (this.opts.changesets) await this.captureTurnBefore(rec, ev.id, ev.text);
2186
+ if (this.opts.changesets) await this.captureTurnBefore(chat, ev.id, ev.text);
2187
+ // A foreground `shell`-tool call opens its
2188
+ // synthetic terminal channel here — the command line is only
2189
+ // known at input.ended.
2190
+ this.openTerminalForToolCall(rec, chat, ev.id, ev.text);
2191
+ // A client-executed call clears its
2192
+ // confirmation gate here (no opencode permission can fire for
2193
+ // it) — ready straight to running, then surface the execution
2194
+ // request so the owning client picks up the work.
2195
+ if (chat.clientToolCalls.has(ev.id)) {
2196
+ this.ensureToolReady(chat, ev.id, false);
2197
+ const invocation = chat.clientToolCalls.get(ev.id);
2198
+ const running = this.toolCallState(chat, ev.id);
2199
+ if (invocation !== undefined && running !== null && running.status === ToolCallStatus.Running && chat.currentTurnId !== null) {
2200
+ const request: SessionToolClientExecutionRequest = {
2201
+ id: ev.id,
2202
+ chat: chatURI,
2203
+ kind: SessionInputRequestKind.ToolClientExecution,
2204
+ turnId: chat.currentTurnId,
2205
+ clientId: invocation.clientId,
2206
+ toolCall: running,
2207
+ };
2208
+ this.publish({
2209
+ channel: rec.channel,
2210
+ action: { type: ActionType.SessionInputNeededSet, request },
2211
+ });
2212
+ }
2213
+ }
1373
2214
  return;
2215
+ }
1374
2216
  case "tool.progress":
1375
2217
  // First sign the tool is actually running (opencode auto-approved):
1376
2218
  // finalize the tool call as running.
1377
- this.ensureToolReady(rec, ev.id, false);
2219
+ this.ensureToolReady(chat, ev.id, false);
1378
2220
  return;
1379
2221
  case "tool.success": {
1380
- if (rec.currentTurnId === null) return;
1381
- this.ensureToolReady(rec, ev.id, false);
1382
- if (this.toolCallTerminal(rec, ev.id)) return; // e.g. denied → already cancelled
1383
- const name = rec.toolName.get(ev.id) ?? "tool";
1384
- const input = rec.toolInput.get(ev.id);
2222
+ // The synthetic terminal completes on the
2223
+ // tool's terminal event (before the turn guard — a command that
2224
+ // finishes after its turn was torn down still exits its
2225
+ // terminal; no-op when the call never opened one).
2226
+ this.finishTerminal(chat, ev.id, { ok: true, content: ev.content });
2227
+ if (chat.currentTurnId === null) return;
2228
+ this.ensureToolReady(chat, ev.id, false);
2229
+ if (this.toolCallTerminal(chat, ev.id)) {
2230
+ // e.g. denied → already cancelled, or a client-executed call
2231
+ // the client already completed: no echo, but the tracking
2232
+ // (including the client-tool record) must still be cleared.
2233
+ this.clearToolTracking(chat, ev.id);
2234
+ return;
2235
+ }
2236
+ const name = chat.toolName.get(ev.id) ?? "tool";
2237
+ const input = chat.toolInput.get(ev.id);
1385
2238
  this.publish({
1386
2239
  channel: chatURI,
1387
2240
  action: {
1388
2241
  type: ActionType.ChatToolCallComplete,
1389
- turnId: rec.currentTurnId,
2242
+ turnId: chat.currentTurnId,
1390
2243
  toolCallId: ev.id,
1391
2244
  result: {
1392
2245
  success: true,
@@ -1395,20 +2248,26 @@ export class Host {
1395
2248
  },
1396
2249
  },
1397
2250
  });
1398
- this.clearToolTracking(rec, ev.id);
2251
+ this.clearToolTracking(chat, ev.id);
1399
2252
  return;
1400
2253
  }
1401
2254
  case "tool.failed": {
1402
- if (rec.currentTurnId === null) return;
1403
- this.ensureToolReady(rec, ev.id, false);
1404
- if (this.toolCallTerminal(rec, ev.id)) return;
1405
- const name = rec.toolName.get(ev.id) ?? "tool";
1406
- const input = rec.toolInput.get(ev.id);
2255
+ this.finishTerminal(chat, ev.id, { ok: false, message: ev.error.message });
2256
+ if (chat.currentTurnId === null) return;
2257
+ this.ensureToolReady(chat, ev.id, false);
2258
+ if (this.toolCallTerminal(chat, ev.id)) {
2259
+ // Already terminal (client-executed call completed by the
2260
+ // client, or a call cancelled upstream) — clear the tracking.
2261
+ this.clearToolTracking(chat, ev.id);
2262
+ return;
2263
+ }
2264
+ const name = chat.toolName.get(ev.id) ?? "tool";
2265
+ const input = chat.toolInput.get(ev.id);
1407
2266
  this.publish({
1408
2267
  channel: chatURI,
1409
2268
  action: {
1410
2269
  type: ActionType.ChatToolCallComplete,
1411
- turnId: rec.currentTurnId,
2270
+ turnId: chat.currentTurnId,
1412
2271
  toolCallId: ev.id,
1413
2272
  result: {
1414
2273
  success: false,
@@ -1417,45 +2276,45 @@ export class Host {
1417
2276
  },
1418
2277
  },
1419
2278
  });
1420
- this.clearToolTracking(rec, ev.id);
2279
+ this.clearToolTracking(chat, ev.id);
1421
2280
  return;
1422
2281
  }
1423
2282
  case "usage.updated":
1424
2283
  // Session-cumulative tokens; the chat reducer replaces the turn's
1425
2284
  // usage, so the latest cumulative values are the turn's view.
1426
- if (rec.currentTurnId === null) return;
2285
+ if (chat.currentTurnId === null) return;
1427
2286
  this.publish({
1428
2287
  channel: chatURI,
1429
2288
  action: {
1430
2289
  type: ActionType.ChatUsage,
1431
- turnId: rec.currentTurnId,
2290
+ turnId: chat.currentTurnId,
1432
2291
  usage: {
1433
2292
  inputTokens: ev.tokens.input,
1434
2293
  outputTokens: ev.tokens.output,
1435
2294
  cacheReadTokens: ev.tokens.cache.read,
1436
- ...(rec.turnModelRef !== null ? { model: rec.turnModelRef } : {}),
2295
+ ...(chat.turnModelRef !== null ? { model: chat.turnModelRef } : {}),
1437
2296
  },
1438
2297
  },
1439
2298
  });
1440
2299
  return;
1441
2300
  case "permission.asked":
1442
2301
  // Only tool-sourced permissions map to a tool confirmation;
1443
- // anything else has no AHP counterpart in this MVP (gap).
2302
+ // anything else has no AHP counterpart (gap).
1444
2303
  if (ev.source === undefined) {
1445
2304
  this.log(`ignoring non-tool permission.asked ${ev.id} (action: ${ev.action})`);
1446
2305
  return;
1447
2306
  }
1448
2307
  const toolCallId = ev.source.id;
1449
- rec.permissionForTool.set(toolCallId, ev.id);
1450
- rec.toolForPermission.set(ev.id, toolCallId);
1451
- this.ensureToolReady(rec, toolCallId, true);
1452
- const pending = this.pendingToolCall(rec, toolCallId);
1453
- if (pending !== null && rec.currentTurnId !== null) {
2308
+ chat.permissionForTool.set(toolCallId, ev.id);
2309
+ chat.toolForPermission.set(ev.id, toolCallId);
2310
+ this.ensureToolReady(chat, toolCallId, true);
2311
+ const pending = this.pendingToolCall(chat, toolCallId);
2312
+ if (pending !== null && chat.currentTurnId !== null) {
1454
2313
  const request: SessionToolConfirmationRequest = {
1455
2314
  id: toolCallId,
1456
2315
  chat: chatURI,
1457
2316
  kind: SessionInputRequestKind.ToolConfirmation,
1458
- turnId: rec.currentTurnId,
2317
+ turnId: chat.currentTurnId,
1459
2318
  toolCall: pending,
1460
2319
  };
1461
2320
  this.publish({
@@ -1465,10 +2324,10 @@ export class Host {
1465
2324
  }
1466
2325
  return;
1467
2326
  case "permission.replied": {
1468
- const toolCallId = rec.toolForPermission.get(ev.requestID);
1469
- rec.toolForPermission.delete(ev.requestID);
2327
+ const toolCallId = chat.toolForPermission.get(ev.requestID);
2328
+ chat.toolForPermission.delete(ev.requestID);
1470
2329
  if (toolCallId !== undefined) {
1471
- rec.permissionForTool.delete(toolCallId);
2330
+ chat.permissionForTool.delete(toolCallId);
1472
2331
  // Safety net: the client's `chat/toolCallConfirmed` normally
1473
2332
  // removes the input request first; this covers the reply
1474
2333
  // arriving without (or before) the echo.
@@ -1491,17 +2350,17 @@ export class Host {
1491
2350
  return `turn_${Date.now().toString(36)}_${this.turnCounter.toString(36)}`;
1492
2351
  }
1493
2352
 
1494
- private turnDuration(rec: SessionRecord): number {
1495
- return Math.max(0, Date.now() - (rec.turnStartedAt ?? Date.now()));
2353
+ private turnDuration(chat: ChatRuntime): number {
2354
+ return Math.max(0, Date.now() - (chat.turnStartedAt ?? Date.now()));
1496
2355
  }
1497
2356
 
1498
2357
  /** Claim a turn (write-ahead) and publish `chat/turnStarted`. */
1499
- private startTurn(rec: SessionRecord, message: Message, queuedMessageId?: string): void {
2358
+ private startTurn(chat: ChatRuntime, message: Message, queuedMessageId?: string): void {
1500
2359
  const turnId = this.mintTurnId();
1501
- rec.currentTurnId = turnId;
1502
- rec.turnStartedAt = Date.now();
2360
+ chat.currentTurnId = turnId;
2361
+ chat.turnStartedAt = Date.now();
1503
2362
  this.publish({
1504
- channel: chatChannelURI(rec.sessionID),
2363
+ channel: chat.uri,
1505
2364
  action: {
1506
2365
  type: ActionType.ChatTurnStarted,
1507
2366
  turnId,
@@ -1518,18 +2377,18 @@ export class Host {
1518
2377
  * queued prompt was already sent with `delivery: "queue"` — opencode
1519
2378
  * starts it automatically; this only updates the AHP state).
1520
2379
  *
1521
- * Phase 2: then refresh the session's changesets — the turn's captured
2380
+ * Then refresh the session's changesets — the turn's captured
1522
2381
  * "after" content is read from disk here, and the uncommitted/session/
1523
2382
  * turn changesets recompute (async: awaits the facade).
1524
2383
  */
1525
- private async finishTurn(rec: SessionRecord): Promise<void> {
1526
- const endedTurnId = rec.currentTurnId;
1527
- rec.currentTurnId = null;
1528
- rec.turnStartedAt = null;
1529
- const state = rec.chatStore.state;
2384
+ private async finishTurn(chat: ChatRuntime): Promise<void> {
2385
+ const endedTurnId = chat.currentTurnId;
2386
+ chat.currentTurnId = null;
2387
+ chat.turnStartedAt = null;
2388
+ const state = chat.chatStore.state;
1530
2389
  if (state.steeringMessage !== undefined) {
1531
2390
  this.publish({
1532
- channel: chatChannelURI(rec.sessionID),
2391
+ channel: chat.uri,
1533
2392
  action: {
1534
2393
  type: ActionType.ChatPendingMessageRemoved,
1535
2394
  kind: PendingMessageKind.Steering,
@@ -1540,17 +2399,176 @@ export class Host {
1540
2399
  const queued = state.queuedMessages;
1541
2400
  if (queued !== undefined && queued.length > 0) {
1542
2401
  const next = queued[0]!;
1543
- this.startTurn(rec, next.message, next.id);
1544
- } else if (rec.lastInbox !== null && rec.lastInbox.delivery === "queue") {
2402
+ this.startTurn(chat, next.message, next.id);
2403
+ } else if (chat.lastInbox !== null && chat.lastInbox.delivery === "queue") {
1545
2404
  // A queued prompt from outside AHP (e.g. the TUI).
1546
- this.startTurn(rec, userMessage(rec.lastInbox.text));
2405
+ this.startTurn(chat, userMessage(chat.lastInbox.text));
2406
+ }
2407
+ // The ended turn's command terminals leave the
2408
+ // root catalog now (retention — their state stays subscribable until
2409
+ // the chat/record is removed). Runs after the possible
2410
+ // chained startTurn so the published list is the post-handoff one.
2411
+ if (this.opts.terminals && endedTurnId !== null && this.terminals.size > 0) {
2412
+ this.refreshTerminals();
1547
2413
  }
1548
2414
  if (this.opts.changesets && endedTurnId !== null) {
1549
- await this.refreshTurnChangesets(rec, endedTurnId);
2415
+ await this.refreshTurnChangesets(this.byChannel.get(chat.uri)!, chat, endedTurnId);
2416
+ }
2417
+ }
2418
+
2419
+ // ── synthetic shell-command terminals ───────────────────────────────────
2420
+
2421
+ /**
2422
+ * Open the synthetic `ahp-terminal:` channel for a foreground
2423
+ * `shell`-tool call (read-only rendering of the command execution):
2424
+ * seed the state (`isPty: false`, session claim scoped to
2425
+ * chat/turn/toolCall, `supportsCommandDetection: true`), publish
2426
+ * `terminal/commandExecuted` (commandId = toolCallId), register the
2427
+ * channel, and refresh the root catalog. No-op for the excluded shapes
2428
+ * (capability off, no active turn, non-shell tool, malformed input,
2429
+ * background calls — the background result carries no turn-scoped
2430
+ * completion).
2431
+ */
2432
+ private openTerminalForToolCall(rec: SessionRecord, chat: ChatRuntime, toolCallId: string, inputJson: string): void {
2433
+ if (!this.opts.terminals) return;
2434
+ const turnId = chat.currentTurnId;
2435
+ if (turnId === null) return;
2436
+ const name = chat.toolName.get(toolCallId);
2437
+ if (name === undefined || !SHELL_TOOL_NAMES.has(name)) return;
2438
+ let input: unknown;
2439
+ try {
2440
+ input = JSON.parse(inputJson);
2441
+ } catch {
2442
+ return; // malformed input text — nothing to render
2443
+ }
2444
+ if (!isRecord(input)) return;
2445
+ const command = input["command"];
2446
+ if (typeof command !== "string" || command.length === 0) return;
2447
+ if (input["background"] === true) return; // excluded: no synchronous completion
2448
+ const uri = terminalChannelURI(toolCallId);
2449
+ if (this.terminals.has(uri)) {
2450
+ this.log(`terminal ${uri} already exists (duplicate toolCallId ${toolCallId}); not reopening`);
2451
+ return;
2452
+ }
2453
+ const now = Date.now();
2454
+ const initial: TerminalState = {
2455
+ title:
2456
+ command.length > TERMINAL_TITLE_MAX ? `${command.slice(0, TERMINAL_TITLE_MAX - 1)}…` : command,
2457
+ content: [],
2458
+ lifecycle: { status: TerminalLifecycleStatus.Running },
2459
+ claim: { kind: TerminalClaimKind.Session, session: rec.channel, chat: chat.uri, turnId, toolCallId },
2460
+ supportsCommandDetection: true,
2461
+ isPty: false,
2462
+ // A directory URI (trailing slash — RFC 8089).
2463
+ ...(this.opts.defaultDirectory !== undefined ? { cwd: directoryUri(this.opts.defaultDirectory) } : {}),
2464
+ };
2465
+ this.terminals.set(uri, {
2466
+ uri,
2467
+ rec,
2468
+ chat,
2469
+ toolCallId,
2470
+ turnId,
2471
+ store: createTerminalStateStore(initial),
2472
+ commandLine: command,
2473
+ startedAt: now,
2474
+ });
2475
+ this.channels.addTerminal(uri);
2476
+ this.publish({
2477
+ channel: uri,
2478
+ action: { type: ActionType.TerminalCommandExecuted, commandId: toolCallId, commandLine: command, timestamp: now },
2479
+ });
2480
+ this.refreshTerminals();
2481
+ }
2482
+
2483
+ /**
2484
+ * Complete the synthetic terminal of a `shell`-tool call: publish
2485
+ * `terminal/data` (the output — the tool's text content on success,
2486
+ * the error message on failure), `terminal/commandFinished` (exitCode
2487
+ * + duration), and `terminal/exited`, then refresh the root catalog
2488
+ * (the listed lifecycle flips to exited while the turn still runs).
2489
+ * Idempotent — a terminal that already exited is left alone. The
2490
+ * record itself is retained (retention); only the state moves on.
2491
+ */
2492
+ private finishTerminal(
2493
+ chat: ChatRuntime,
2494
+ toolCallId: string,
2495
+ result: { ok: true; content: FacadeToolContent[] } | { ok: false; message: string },
2496
+ ): void {
2497
+ if (!this.opts.terminals) return;
2498
+ const uri = terminalChannelURI(toolCallId);
2499
+ const t = this.terminals.get(uri);
2500
+ if (t === undefined) return;
2501
+ if (t.store.state.lifecycle.status === TerminalLifecycleStatus.Exited) return;
2502
+ const output = result.ok
2503
+ ? result.content
2504
+ .filter((c) => c.type === "text" && typeof c.text === "string")
2505
+ .map((c) => c.text as string)
2506
+ .join("\n")
2507
+ : result.message;
2508
+ if (output.length > 0) {
2509
+ this.publish({ channel: uri, action: { type: ActionType.TerminalData, data: output } });
2510
+ }
2511
+ const exitCode = result.ok ? (shellExitCodeOf(result.content) ?? undefined) : undefined;
2512
+ const durationMs = Math.max(0, Date.now() - t.startedAt);
2513
+ this.publish({
2514
+ channel: uri,
2515
+ action: {
2516
+ type: ActionType.TerminalCommandFinished,
2517
+ commandId: toolCallId,
2518
+ ...(exitCode !== undefined ? { exitCode } : {}),
2519
+ ...(durationMs > 0 ? { durationMs } : {}),
2520
+ },
2521
+ });
2522
+ this.publish({
2523
+ channel: uri,
2524
+ action: { type: ActionType.TerminalExited, ...(exitCode !== undefined ? { exitCode } : {}) },
2525
+ });
2526
+ this.refreshTerminals();
2527
+ }
2528
+
2529
+ /**
2530
+ * Republish the root terminal catalog (`root/terminalsChanged`, full
2531
+ * replacement). Catalog membership is turn-scoped: a terminal is
2532
+ * listed while its turn is still the owning chat's active turn —
2533
+ * finished commands keep their (final) lifecycle row until the turn
2534
+ * ends, then the row drops (host-controlled retention).
2535
+ * No-op when the serialized list is unchanged.
2536
+ */
2537
+ private refreshTerminals(): void {
2538
+ if (!this.opts.terminals) return;
2539
+ const terminals: TerminalInfo[] = [];
2540
+ for (const t of this.terminals.values()) {
2541
+ if (t.chat.currentTurnId !== t.turnId) continue;
2542
+ const s = t.store.state;
2543
+ terminals.push({ resource: t.uri, title: s.title, claim: s.claim, lifecycle: s.lifecycle });
2544
+ }
2545
+ if (JSON.stringify(this.state.state.terminals) === JSON.stringify(terminals)) return;
2546
+ this.publish({ channel: ROOT_CHANNEL, action: { type: ActionType.RootTerminalsChanged, terminals } });
2547
+ }
2548
+
2549
+ /**
2550
+ * Drop a chat's terminal channels (removeChat — covers both chat
2551
+ * disposal and record removal): a still-running command gets a final
2552
+ * `terminal/exited` (it dies with the chat), then the records and
2553
+ * registry entries go and the root catalog refreshes. Existing socket
2554
+ * subscriptions linger (the session-removal precedent) — no further
2555
+ * actions will reach them.
2556
+ */
2557
+ private teardownTerminalsForChat(chat: ChatRuntime): void {
2558
+ let changed = false;
2559
+ for (const t of [...this.terminals.values()]) {
2560
+ if (t.chat !== chat) continue;
2561
+ if (t.store.state.lifecycle.status === TerminalLifecycleStatus.Running) {
2562
+ this.publish({ channel: t.uri, action: { type: ActionType.TerminalExited } });
2563
+ }
2564
+ this.terminals.delete(t.uri);
2565
+ this.channels.removeTerminal(t.uri);
2566
+ changed = true;
1550
2567
  }
2568
+ if (changed) this.refreshTerminals();
1551
2569
  }
1552
2570
 
1553
- // ── Phase 2: changesets ────────────────────────────────────────────────
2571
+ // ── changesets ────────────────────────────────────────────────
1554
2572
 
1555
2573
  /**
1556
2574
  * Capture the pre-edit content of a file-mutating tool's target file for
@@ -1559,9 +2577,9 @@ export class Host {
1559
2577
  * the tool is not file-mutating, the input carries no parseable path,
1560
2578
  * or the path resolves outside the location directory.
1561
2579
  */
1562
- private async captureTurnBefore(rec: SessionRecord, toolCallId: string, inputJson: string): Promise<void> {
1563
- const turnId = rec.currentTurnId;
1564
- const toolName = rec.toolName.get(toolCallId);
2580
+ private async captureTurnBefore(chat: ChatRuntime, toolCallId: string, inputJson: string): Promise<void> {
2581
+ const turnId = chat.currentTurnId;
2582
+ const toolName = chat.toolName.get(toolCallId);
1565
2583
  if (turnId === null || toolName === undefined || !SNAPSHOT_TOOLS.has(toolName)) return;
1566
2584
  let parsed: unknown;
1567
2585
  try {
@@ -1585,11 +2603,12 @@ export class Host {
1585
2603
  return;
1586
2604
  }
1587
2605
  // The pump is sequential, so the turn cannot have ended between the
1588
- // call and the await — but the record may be gone (session deleted).
1589
- if (rec.currentTurnId !== turnId || !this.sessions.has(rec.sessionID)) return;
1590
- const turnFiles = rec.turnSnapshots.get(turnId) ?? new Map();
2606
+ // call and the await — but the chat may be gone (session deleted or
2607
+ // chat disposed).
2608
+ if (chat.currentTurnId !== turnId || !this.byOpencode.has(chat.sessionID)) return;
2609
+ const turnFiles = chat.turnSnapshots.get(turnId) ?? new Map();
1591
2610
  if (!turnFiles.has(absPath)) turnFiles.set(absPath, { before, after: null });
1592
- rec.turnSnapshots.set(turnId, turnFiles);
2611
+ chat.turnSnapshots.set(turnId, turnFiles);
1593
2612
  }
1594
2613
 
1595
2614
  /** Resolve a tool-input path against the location directory (must stay inside it). */
@@ -1600,16 +2619,45 @@ export class Host {
1600
2619
  return isPathInside(absPath, dir) ? absPath : null;
1601
2620
  }
1602
2621
 
1603
- /** Get-or-create the changeset store for a URI (fresh stores start computing). */
1604
- private changesetStore(rec: SessionRecord, uri: string): ChangesetStateStore {
1605
- let store = rec.changesets.get(uri);
2622
+ /**
2623
+ * The changeset store's owner: session-kind changesets
2624
+ * live on the record (the session channel owns them); uncommitted/turn
2625
+ * changesets live on the owning chat. Null when the owner is gone
2626
+ * (a disposed chat's changesets are un-subscribable).
2627
+ */
2628
+ private changesetOwner(rec: SessionRecord, uri: string): { kind: "session" } | { kind: "chat"; chat: ChatRuntime } | null {
2629
+ const parsed = parseChangesetChannel(uri);
2630
+ if (parsed === null) return null;
2631
+ if (parsed.kind === "session") return { kind: "session" };
2632
+ const chat = rec.chats.get(parsed.ownerUri);
2633
+ return chat === undefined ? null : { kind: "chat", chat };
2634
+ }
2635
+
2636
+ /**
2637
+ * Get-or-create the changeset store for a URI (fresh stores start
2638
+ * computing). Owner-aware — see `changesetOwner`; null when the owner
2639
+ * is gone.
2640
+ */
2641
+ private changesetStore(rec: SessionRecord, uri: string): ChangesetStateStore | null {
2642
+ const owner = this.changesetOwner(rec, uri);
2643
+ if (owner === null) return null;
2644
+ const map = owner.kind === "chat" ? owner.chat.changesets : rec.sessionChangesets;
2645
+ let store = map.get(uri);
1606
2646
  if (store === undefined) {
1607
2647
  store = createChangesetStateStore({ status: ChangesetStatus.Computing, files: [] });
1608
- rec.changesets.set(uri, store);
2648
+ map.set(uri, store);
1609
2649
  }
1610
2650
  return store;
1611
2651
  }
1612
2652
 
2653
+ /** The live store for a URI, or undefined when it has never been created. */
2654
+ private changesetStoreOf(rec: SessionRecord, uri: string): ChangesetStateStore | undefined {
2655
+ const owner = this.changesetOwner(rec, uri);
2656
+ if (owner === null) return undefined;
2657
+ const map = owner.kind === "chat" ? owner.chat.changesets : rec.sessionChangesets;
2658
+ return map.get(uri);
2659
+ }
2660
+
1613
2661
  /** The store's current per-file review flags, keyed by file id. */
1614
2662
  private reviewedById(store: ChangesetStateStore): Map<string, boolean> {
1615
2663
  const out = new Map<string, boolean>();
@@ -1631,13 +2679,18 @@ export class Host {
1631
2679
  const parsed = parseChangesetChannel(uri);
1632
2680
  if (parsed === null) return;
1633
2681
  const store = this.changesetStore(rec, uri);
2682
+ if (store === null) return; // owner gone (disposed chat)
1634
2683
  let files;
1635
2684
  try {
1636
2685
  if (parsed.kind === "turn") {
2686
+ // The turn's snapshots live on the owning chat; the content refs
2687
+ // carry its opencode session id (the byOpencode join key).
2688
+ const chat = rec.chats.get(parsed.ownerUri);
2689
+ if (chat === undefined) return;
1637
2690
  files = buildTurnChangesetFiles({
1638
- sessionID: parsed.sessionID,
2691
+ sessionID: chat.sessionID,
1639
2692
  turnId: parsed.turnId ?? "",
1640
- files: rec.turnSnapshots.get(parsed.turnId ?? "") ?? new Map(),
2693
+ files: chat.turnSnapshots.get(parsed.turnId ?? "") ?? new Map(),
1641
2694
  reviewedById: this.reviewedById(store),
1642
2695
  });
1643
2696
  } else {
@@ -1689,8 +2742,8 @@ export class Host {
1689
2742
  * the uncommitted, session, and ended-turn changesets — only the ones a
1690
2743
  * client has subscribed (unsubscribed changesets cost no seq).
1691
2744
  */
1692
- private async refreshTurnChangesets(rec: SessionRecord, turnId: string): Promise<void> {
1693
- const turnFiles = rec.turnSnapshots.get(turnId);
2745
+ private async refreshTurnChangesets(rec: SessionRecord, chat: ChatRuntime, turnId: string): Promise<void> {
2746
+ const turnFiles = chat.turnSnapshots.get(turnId);
1694
2747
  if (turnFiles !== undefined) {
1695
2748
  for (const [absPath, snap] of turnFiles) {
1696
2749
  if (snap.after === null) {
@@ -1702,12 +2755,14 @@ export class Host {
1702
2755
  }
1703
2756
  }
1704
2757
  }
2758
+ // The chat's own uncommitted + turn changesets, plus the session-wide
2759
+ // one (shared by all chats). Only the ones a client has subscribed.
1705
2760
  for (const uri of [
1706
- uncommittedChangesetURI(rec.sessionID),
1707
- sessionChangesetURI(rec.sessionID),
1708
- turnChangesetURI(rec.sessionID, turnId),
2761
+ uncommittedChangesetURI(chat.uri),
2762
+ sessionChangesetURI(rec.channel),
2763
+ turnChangesetURI(chat.uri, turnId),
1709
2764
  ]) {
1710
- if (rec.changesets.has(uri)) await this.refreshChangeset(rec, uri);
2765
+ if (this.changesetStoreOf(rec, uri) !== undefined) await this.refreshChangeset(rec, uri);
1711
2766
  }
1712
2767
  }
1713
2768
 
@@ -1782,13 +2837,13 @@ export class Host {
1782
2837
  this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
1783
2838
  return;
1784
2839
  }
1785
- // snap — in-memory turn snapshot of a live session.
1786
- const rec = this.sessions.get(ref.sessionID);
1787
- if (rec === undefined) {
2840
+ // snap — in-memory turn snapshot of a live chat's opencode session.
2841
+ const binding = this.byOpencode.get(ref.sessionID);
2842
+ if (binding === undefined) {
1788
2843
  this.sendError(socketId, msg.id, ERROR_NOT_FOUND, "no such session");
1789
2844
  return;
1790
2845
  }
1791
- const snap = rec.turnSnapshots.get(ref.turnId)?.get(ref.path);
2846
+ const snap = binding.chat.turnSnapshots.get(ref.turnId)?.get(ref.path);
1792
2847
  const content = snap === undefined ? null : ref.part === "before" ? snap.before : snap.after;
1793
2848
  if (content === null) {
1794
2849
  this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
@@ -1825,12 +2880,12 @@ export class Host {
1825
2880
  this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `not a changeset channel: ${channel}`);
1826
2881
  return;
1827
2882
  }
1828
- const rec = this.sessions.get(parsed.sessionID);
2883
+ const rec = this.byChannel.get(parsed.ownerUri);
1829
2884
  if (rec === undefined) {
1830
2885
  this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, "no such session");
1831
2886
  return;
1832
2887
  }
1833
- const store = rec.changesets.get(channel);
2888
+ const store = this.changesetStoreOf(rec, channel);
1834
2889
  if (store === undefined) {
1835
2890
  this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such changeset: ${channel}`);
1836
2891
  return;
@@ -1870,7 +2925,9 @@ export class Host {
1870
2925
  });
1871
2926
  try {
1872
2927
  if (parsed.kind === "turn" && parsed.turnId !== undefined) {
1873
- await this.restoreTurnFile(rec, parsed.turnId, absPath);
2928
+ // A live turn-changeset store implies a live owning chat
2929
+ // (changesetStoreOf resolved it above).
2930
+ await this.restoreTurnFile(rec.chats.get(parsed.ownerUri)!, parsed.turnId, absPath);
1874
2931
  } else {
1875
2932
  await this.opts.facade.discardFile(absPath);
1876
2933
  }
@@ -1904,8 +2961,8 @@ export class Host {
1904
2961
  * the turn (before === null) → delete it; otherwise write the pre-edit
1905
2962
  * content back.
1906
2963
  */
1907
- private async restoreTurnFile(rec: SessionRecord, turnId: string, absPath: string): Promise<void> {
1908
- const snap = rec.turnSnapshots.get(turnId)?.get(absPath);
2964
+ private async restoreTurnFile(chat: ChatRuntime, turnId: string, absPath: string): Promise<void> {
2965
+ const snap = chat.turnSnapshots.get(turnId)?.get(absPath);
1909
2966
  const before = snap?.before ?? null;
1910
2967
  if (before === null) {
1911
2968
  await this.opts.facade.deleteFile(absPath);
@@ -1922,16 +2979,16 @@ export class Host {
1922
2979
  * - otherwise → `confirmed: "not-needed"` → straight to `running`
1923
2980
  * (opencode auto-approved).
1924
2981
  */
1925
- private ensureToolReady(rec: SessionRecord, toolCallId: string, permission: boolean): void {
1926
- if (rec.toolReady.has(toolCallId) || rec.currentTurnId === null) return;
1927
- rec.toolReady.add(toolCallId);
1928
- const name = rec.toolName.get(toolCallId) ?? "tool";
1929
- const input = rec.toolInput.get(toolCallId);
2982
+ private ensureToolReady(chat: ChatRuntime, toolCallId: string, permission: boolean): void {
2983
+ if (chat.toolReady.has(toolCallId) || chat.currentTurnId === null) return;
2984
+ chat.toolReady.add(toolCallId);
2985
+ const name = chat.toolName.get(toolCallId) ?? "tool";
2986
+ const input = chat.toolInput.get(toolCallId);
1930
2987
  this.publish({
1931
- channel: chatChannelURI(rec.sessionID),
2988
+ channel: chat.uri,
1932
2989
  action: {
1933
2990
  type: ActionType.ChatToolCallReady,
1934
- turnId: rec.currentTurnId,
2991
+ turnId: chat.currentTurnId,
1935
2992
  toolCallId,
1936
2993
  invocationMessage: invocationMessageFor(name, input),
1937
2994
  toolInput: input,
@@ -1940,9 +2997,9 @@ export class Host {
1940
2997
  });
1941
2998
  }
1942
2999
 
1943
- /** The live tool-call state in the current turn, or null when absent. */
1944
- private toolCallState(rec: SessionRecord, toolCallId: string): ToolCallState | null {
1945
- const turn = rec.chatStore.state.activeTurn;
3000
+ /** The live tool-call state in the chat's current turn, or null when absent. */
3001
+ private toolCallState(chat: ChatRuntime, toolCallId: string): ToolCallState | null {
3002
+ const turn = chat.chatStore.state.activeTurn;
1946
3003
  if (turn === undefined) return null;
1947
3004
  for (const part of turn.responseParts) {
1948
3005
  if (part.kind === ResponsePartKind.ToolCall && part.toolCall.toolCallId === toolCallId) {
@@ -1956,8 +3013,8 @@ export class Host {
1956
3013
  * The tool call's state when it is awaiting confirmation (the
1957
3014
  * `SessionToolConfirmationRequest.toolCall` shape), or null otherwise.
1958
3015
  */
1959
- private pendingToolCall(rec: SessionRecord, toolCallId: string): ToolCallConfirmationState | null {
1960
- const tc = this.toolCallState(rec, toolCallId);
3016
+ private pendingToolCall(chat: ChatRuntime, toolCallId: string): ToolCallConfirmationState | null {
3017
+ const tc = this.toolCallState(chat, toolCallId);
1961
3018
  if (tc === null) return null;
1962
3019
  if (tc.status === ToolCallStatus.PendingConfirmation || tc.status === ToolCallStatus.PendingResultConfirmation) {
1963
3020
  return tc;
@@ -1966,15 +3023,146 @@ export class Host {
1966
3023
  }
1967
3024
 
1968
3025
  /** True when the tool call already left the ready states (completed/cancelled). */
1969
- private toolCallTerminal(rec: SessionRecord, toolCallId: string): boolean {
1970
- const tc = this.toolCallState(rec, toolCallId);
3026
+ private toolCallTerminal(chat: ChatRuntime, toolCallId: string): boolean {
3027
+ const tc = this.toolCallState(chat, toolCallId);
1971
3028
  return tc !== null && (tc.status === ToolCallStatus.Completed || tc.status === ToolCallStatus.Cancelled);
1972
3029
  }
1973
3030
 
1974
- private clearToolTracking(rec: SessionRecord, toolCallId: string): void {
1975
- rec.toolInput.delete(toolCallId);
1976
- rec.toolName.delete(toolCallId);
1977
- rec.toolReady.delete(toolCallId);
3031
+ private clearToolTracking(chat: ChatRuntime, toolCallId: string): void {
3032
+ chat.toolInput.delete(toolCallId);
3033
+ chat.toolName.delete(toolCallId);
3034
+ chat.toolReady.delete(toolCallId);
3035
+ chat.clientToolCalls.delete(toolCallId);
3036
+ }
3037
+
3038
+ // ── client-tool helpers ─────────────────────────────────────────────────
3039
+
3040
+ /**
3041
+ * The session's active client providing `toolName` (the tool-call
3042
+ * contributor), or null when no active client provides it (a
3043
+ * server-executed call — the normal path).
3044
+ */
3045
+ private clientToolContributor(rec: SessionRecord, toolName: string): string | null {
3046
+ return findProvider(rec.sessionStore.state.activeClients, toolName);
3047
+ }
3048
+
3049
+ /**
3050
+ * Re-sync the location-global opencode tool registry with the
3051
+ * cross-session union of every live session's active-client tools
3052
+ * (first-registered wins per name). Location-global by design —
3053
+ * opencode's tool state is per-location, not per-session: the
3054
+ * `execute` bridge re-checks per-session ownership at
3055
+ * runtime.
3056
+ */
3057
+ private async syncClientToolsToOpencode(): Promise<void> {
3058
+ const clients: SessionActiveClient[] = [];
3059
+ for (const rec of this.sessions.values()) {
3060
+ for (const client of rec.sessionStore.state.activeClients) clients.push(client);
3061
+ }
3062
+ const tools = toolUnion(clients).map(
3063
+ (t): FacadeClientTool => ({
3064
+ name: t.name,
3065
+ description: descriptionFor(t),
3066
+ inputSchema: inputSchemaFor(t),
3067
+ }),
3068
+ );
3069
+ try {
3070
+ await this.opts.facade.syncClientTools(tools);
3071
+ } catch (err) {
3072
+ // R2: a tool-registry failure must not break the AHP surface —
3073
+ // the active-client state stays authoritative on the AHP side.
3074
+ this.log(`client tool sync failed: ${errorMessage(err)}`);
3075
+ }
3076
+ }
3077
+
3078
+ /**
3079
+ * Settle a client-tool invocation with its final result: the
3080
+ * opencode-side `execute` (blocked on the waiter) unblocks and
3081
+ * returns/throws, which drives the pump's `tool.success`/
3082
+ * `tool.failed` terminal (the AHP state is already terminal — the
3083
+ * pump's `toolCallTerminal` check suppresses a duplicate echo and
3084
+ * clears the tracking). Settling twice is a no-op.
3085
+ *
3086
+ * `result` may be omitted when the invocation's `result` was already
3087
+ * set by the caller (the eviction / session-removal paths set it
3088
+ * first and then settle to deliver it).
3089
+ */
3090
+ private settleClientTool(invocation: ClientToolInvocation, result?: FacadeClientToolResult): void {
3091
+ if (invocation.result === undefined) {
3092
+ if (result === undefined) return; // nothing to settle
3093
+ invocation.result = result;
3094
+ }
3095
+ if (invocation.waiter !== undefined && invocation.waiter !== null) {
3096
+ invocation.waiter(invocation.result);
3097
+ invocation.waiter = null;
3098
+ }
3099
+ }
3100
+
3101
+ /**
3102
+ * The opencode tool `execute` bridge (called from the
3103
+ * `ctx.tool.transform` registration in src/index.ts): route one
3104
+ * client-tool invocation to the owning AHP client and wait for its
3105
+ * result.
3106
+ *
3107
+ * Per-session scoping: the tool is visible location-
3108
+ * globally, but execution only resolves when *this* session is an
3109
+ * AHP session with an active client providing the tool — otherwise
3110
+ * the opencode tool fails (a `Tool.Error` the model sees), so e.g. a
3111
+ * TUI session can see the tool but not execute it.
3112
+ */
3113
+ executeClientTool(input: {
3114
+ sessionID: string;
3115
+ toolCallId: string;
3116
+ name: string;
3117
+ signal: AbortSignal;
3118
+ }): Promise<FacadeClientToolResult> {
3119
+ // The opencode session id joins to the (record, chat) that owns it —
3120
+ // every chat has its own backend session.
3121
+ const binding = this.byOpencode.get(input.sessionID);
3122
+ if (binding === undefined) {
3123
+ return Promise.resolve({
3124
+ ok: false,
3125
+ error: `no AHP session for tool "${input.name}" (session ${input.sessionID} is not an AHP session)`,
3126
+ });
3127
+ }
3128
+ const { rec, chat } = binding;
3129
+ const invocation = chat.clientToolCalls.get(input.toolCallId);
3130
+ if (invocation === undefined) {
3131
+ return Promise.resolve({
3132
+ ok: false,
3133
+ error: `no client-executed call in flight for tool "${input.name}" (it was not registered by this session's active client)`,
3134
+ });
3135
+ }
3136
+ if (findProvider(rec.sessionStore.state.activeClients, input.name) !== invocation.clientId) {
3137
+ return Promise.resolve({
3138
+ ok: false,
3139
+ error: `session ${rec.sessionID} has no active client providing tool "${input.name}"`,
3140
+ });
3141
+ }
3142
+ if (input.signal.aborted) {
3143
+ const result: FacadeClientToolResult = { ok: false, error: `execution of "${input.name}" was cancelled` };
3144
+ this.settleClientTool(invocation, result);
3145
+ return Promise.resolve(result);
3146
+ }
3147
+ // The invocation may already be settled (the client completed before
3148
+ // opencode started the execute — possible: the client only needs the
3149
+ // pump's ready/inputNeeded actions, not our execute). Deliver the
3150
+ // settled result; otherwise register the waiter.
3151
+ const settled = invocation.result;
3152
+ if (settled !== undefined) return Promise.resolve(settled);
3153
+ return new Promise<FacadeClientToolResult>((resolve) => {
3154
+ invocation.waiter = resolve;
3155
+ const onAbort = () => {
3156
+ if (invocation.result === undefined) {
3157
+ this.settleClientTool(invocation, {
3158
+ ok: false,
3159
+ error: `execution of "${input.name}" was cancelled (turn interrupted)`,
3160
+ });
3161
+ }
3162
+ // If already settled, the waiter is gone — the abort is a no-op.
3163
+ };
3164
+ input.signal.addEventListener("abort", onAbort, { once: true });
3165
+ });
1978
3166
  }
1979
3167
 
1980
3168
  // ── session registration / removal ─────────────────────────────────────
@@ -1986,27 +3174,185 @@ export class Host {
1986
3174
  * is gone, already registered, or a createSession remap is pending.
1987
3175
  */
1988
3176
  private async registerExternalDeferred(sessionID: string): Promise<void> {
1989
- if (this.sessions.has(sessionID)) return;
3177
+ if (this.sessions.has(sessionID) || this.byOpencode.has(sessionID)) return;
1990
3178
  let fs: FacadeSession | null;
1991
3179
  try {
1992
3180
  fs = await this.opts.facade.getSession(sessionID);
1993
3181
  } catch {
1994
3182
  return;
1995
3183
  }
1996
- if (fs === null || this.sessions.has(fs.sessionID)) return;
3184
+ if (fs === null || this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) return;
1997
3185
  this.registerExternal(fs);
1998
3186
  }
1999
3187
 
2000
3188
  /**
2001
3189
  * Register an opencode session the host did not create (TUI, another
2002
- * client). Applied directly to the fresh stores (no seq, no actions) —
2003
- * the registration is server-side bookkeeping, not a client-visible
2004
- * state transition; the root announcement carries the lifecycle.
3190
+ * client, or a session resurfacing after a restart).
3191
+ * Outcomes:
3192
+ *
3193
+ * - the opencode id already backs a chat of a live record → skip
3194
+ * (undefined); `listSessions` must not surface peer-chat backends
3195
+ * as their own AHP sessions;
3196
+ * - the session carries a peer marker and the owner record is
3197
+ * registered (and the marker's chat URI is free) → re-attach it to
3198
+ * the owner's chat catalog (undefined — no standalone session);
3199
+ * - the peer marker's owner is not registered yet → queue the
3200
+ * binding (undefined) — the owner may be listed later in the same
3201
+ * `listSessions` pass (there is no boot-time event replay);
3202
+ * - the session carries a channel marker (minted-id default backend)
3203
+ * and the marked channel is free → a standalone session registered
3204
+ * under the ORIGINAL client-chosen channel;
3205
+ * - otherwise → a standalone session whose channel reuses the
3206
+ * opencode id (the record).
2005
3207
  */
2006
3208
  private registerExternal(fs: FacadeSession): SessionRecord | undefined {
2007
3209
  const existing = this.sessions.get(fs.sessionID);
2008
3210
  if (existing !== undefined) return existing;
2009
- const channel = sessionChannelURI(fs.sessionID);
3211
+ if (this.byOpencode.has(fs.sessionID)) return undefined;
3212
+ const marker = parseAhpMarker(fs.metadata);
3213
+ if (marker !== null) {
3214
+ if (marker.chat !== undefined && marker.owner !== undefined) {
3215
+ const owner = this.sessions.get(marker.owner);
3216
+ if (owner !== undefined) {
3217
+ if (this.byChannel.has(marker.chat)) {
3218
+ // The marker's chat is already bound — e.g. a fork inherited
3219
+ // the parent's metadata (core documents the inheritance).
3220
+ // Standalone fallback: the data stays reachable in AHP.
3221
+ this.log(
3222
+ `ignoring the AHP marker on ${fs.sessionID}: chat ${marker.chat} is already bound (registering standalone)`,
3223
+ );
3224
+ } else {
3225
+ return this.reattachPeerChat(owner, fs, marker.chat);
3226
+ }
3227
+ } else {
3228
+ this.enqueueChatBinding(marker.owner, fs, marker.chat);
3229
+ return undefined;
3230
+ }
3231
+ } else if (marker.channel !== undefined) {
3232
+ // The default backend of a minted-id session carries the
3233
+ // client-chosen session channel — resurface under it.
3234
+ if (this.byChannel.has(marker.channel)) {
3235
+ this.log(
3236
+ `ignoring the AHP channel marker on ${fs.sessionID}: ${marker.channel} is already bound (registering under the opencode id)`,
3237
+ );
3238
+ } else {
3239
+ return this.registerExternalStandalone(fs, marker.channel);
3240
+ }
3241
+ }
3242
+ }
3243
+ return this.registerExternalStandalone(fs);
3244
+ }
3245
+
3246
+ /**
3247
+ * Re-attach a marked peer backend to its owner session's chat catalog
3248
+ * after a restart. The owner store is LIVE (unlike a
3249
+ * fresh standalone registration), so the catalog change goes through
3250
+ * `publish` (store + any existing subscribers + the root diff), not a
3251
+ * direct apply. The chat title is re-derived (`Chat <n>`) — a
3252
+ * documented divergence from the pre-restart title. Returns undefined:
3253
+ * the backend gets no standalone AHP session (its session channel is
3254
+ * not registered — `sessions.get(peerID)` misses).
3255
+ */
3256
+ private reattachPeerChat(rec: SessionRecord, fs: FacadeSession, chatURI: string): undefined {
3257
+ const modifiedAt = new Date(fs.time.updated).toISOString();
3258
+ const chat = this.newChatRuntime(chatURI, fs.sessionID, `Chat ${rec.chats.size + 1}`, modifiedAt);
3259
+ this.bindChat(rec, chat);
3260
+ this.publish({
3261
+ channel: rec.channel,
3262
+ action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chat.chatStore.state) },
3263
+ });
3264
+ if (this.opts.changesets) {
3265
+ this.publish({
3266
+ channel: chatURI,
3267
+ action: { type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(chatURI, rec.channel) },
3268
+ });
3269
+ }
3270
+ this.log(`reattached peer chat ${chatURI} (backend ${fs.sessionID}) to session ${rec.channel} from its AHP marker`);
3271
+ return undefined;
3272
+ }
3273
+
3274
+ /**
3275
+ * Queue a peer-chat binding whose owner is not registered yet (the
3276
+ * peer was listed before the owner, or the owner has not been listed
3277
+ * at all). `drainPendingChatBindings` resolves it when the owner
3278
+ * registers. The orphan fallback fires after the grace window: if the
3279
+ * owner is still unregistered and gone from opencode, the peer is
3280
+ * surfaced as its own AHP session instead (the data stays reachable).
3281
+ */
3282
+ private enqueueChatBinding(ownerID: string, fs: FacadeSession, chatURI: string): void {
3283
+ const queue = this.pendingChatBindings.get(ownerID) ?? [];
3284
+ queue.push({ fs, chatURI });
3285
+ this.pendingChatBindings.set(ownerID, queue);
3286
+ setTimeout(() => {
3287
+ void this.checkOrphanChatBindings(ownerID).catch((err) =>
3288
+ this.log(`orphan chat-binding check failed: ${errorMessage(err)}`),
3289
+ );
3290
+ }, EXTERNAL_REGISTER_GRACE_MS);
3291
+ }
3292
+
3293
+ /**
3294
+ * Orphan fallback for queued peer-chat bindings: the
3295
+ * owner never registered and is gone from opencode (e.g. deleted in
3296
+ * the TUI while the plugin was down). Drop the queue and register each
3297
+ * peer as a standalone AHP session. A failed owner lookup keeps the
3298
+ * queue — the next registration or timer re-checks.
3299
+ */
3300
+ private async checkOrphanChatBindings(ownerID: string): Promise<void> {
3301
+ const queue = this.pendingChatBindings.get(ownerID);
3302
+ if (queue === undefined || queue.length === 0) return; // the owner registered — drained
3303
+ let owner: FacadeSession | null;
3304
+ try {
3305
+ owner = await this.opts.facade.getSession(ownerID);
3306
+ } catch {
3307
+ return;
3308
+ }
3309
+ if (owner !== null) return; // the owner still exists in opencode — it registers when listed
3310
+ this.pendingChatBindings.delete(ownerID);
3311
+ for (const { fs, chatURI } of queue) {
3312
+ if (this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) continue;
3313
+ this.log(
3314
+ `AHP marker owner ${ownerID} is gone from opencode — registering the orphaned peer ${fs.sessionID} (chat ${chatURI}) as a standalone session`,
3315
+ );
3316
+ this.registerExternalStandalone(fs);
3317
+ }
3318
+ }
3319
+
3320
+ /**
3321
+ * Resolve queued peer-chat bindings once their owner registers (called
3322
+ * from the standalone registration's success path). A chat URI that is
3323
+ * already bound by then (e.g. the client created it again across the
3324
+ * restart) falls back to standalone registration.
3325
+ */
3326
+ private drainPendingChatBindings(ownerID: string): void {
3327
+ const queue = this.pendingChatBindings.get(ownerID);
3328
+ const owner = this.sessions.get(ownerID);
3329
+ if (queue === undefined || queue.length === 0 || owner === undefined) return;
3330
+ this.pendingChatBindings.delete(ownerID);
3331
+ for (const { fs, chatURI } of queue) {
3332
+ if (this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) continue;
3333
+ if (this.byChannel.has(chatURI)) {
3334
+ this.log(
3335
+ `ignoring the AHP marker on ${fs.sessionID}: chat ${chatURI} is already bound (registering standalone)`,
3336
+ );
3337
+ this.registerExternalStandalone(fs);
3338
+ } else {
3339
+ this.reattachPeerChat(owner, fs, chatURI);
3340
+ }
3341
+ }
3342
+ }
3343
+
3344
+ /**
3345
+ * Register an opencode session as a single-chat AHP session (its
3346
+ * default chat reuses the opencode id). The session channel defaults
3347
+ * to the opencode id; the channel-marker path passes
3348
+ * the ORIGINAL client-chosen channel instead — the registry then
3349
+ * resolves both suffixes (mirroring `handleCreateSession`). Applied
3350
+ * directly to the fresh stores (no seq, no actions) — the
3351
+ * registration is server-side bookkeeping, not a client-visible state
3352
+ * transition; the root announcement carries the lifecycle.
3353
+ */
3354
+ private registerExternalStandalone(fs: FacadeSession, channel?: string): SessionRecord {
3355
+ const recChannel = channel ?? sessionChannelURI(fs.sessionID);
2010
3356
  const modifiedAt = new Date(fs.time.updated).toISOString();
2011
3357
  const sessionStore = createSessionStateStore(
2012
3358
  initialSessionState({
@@ -2018,43 +3364,43 @@ export class Host {
2018
3364
  : undefined, // Idle | IsRead | IsArchived
2019
3365
  }),
2020
3366
  );
2021
- const chatStore = createChatStateStore(
2022
- initialChatState({ resource: chatChannelURI(fs.sessionID), title: "Chat 1", modifiedAt }),
2023
- );
2024
- sessionStore.apply({ type: ActionType.SessionReady });
2025
- sessionStore.apply({ type: ActionType.SessionChatAdded, summary: chatSummaryOf(chatStore.state) });
2026
- sessionStore.apply({ type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(fs.sessionID) });
2027
- // Phase 2: advertise the changeset catalogues directly on the fresh
2028
- // stores (registration is server-side bookkeeping — no seq, no actions).
2029
- if (this.opts.changesets) {
2030
- sessionStore.apply({ type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(fs.sessionID) });
2031
- chatStore.apply({ type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(fs.sessionID) });
2032
- }
2033
3367
  const rec: SessionRecord = {
2034
3368
  sessionID: fs.sessionID,
2035
- channel,
3369
+ channel: recChannel,
2036
3370
  provider: sessionStore.state.provider,
2037
3371
  createdAt: new Date(fs.time.created).toISOString(),
2038
3372
  modifiedAt,
2039
3373
  sessionStore,
2040
- chatStore,
2041
- currentTurnId: null,
2042
- turnStartedAt: null,
2043
- turnModelRef: null,
2044
- parts: new Set(),
2045
- toolInput: new Map(),
2046
- toolName: new Map(),
2047
- toolReady: new Set(),
2048
- permissionForTool: new Map(),
2049
- toolForPermission: new Map(),
2050
- lastInbox: null,
2051
- changesets: new Map(),
2052
- turnSnapshots: new Map(),
3374
+ chats: new Map(),
3375
+ defaultChatURI: chatChannelURI(fs.sessionID),
3376
+ sessionChangesets: new Map(),
2053
3377
  };
2054
3378
  this.sessions.set(fs.sessionID, rec);
2055
- this.byChannel.set(channel, rec);
2056
- this.byChannel.set(chatChannelURI(fs.sessionID), rec);
2057
- this.channels.addSession(fs.sessionID);
3379
+ this.byChannel.set(recChannel, rec);
3380
+ // The registry resolves the opencode id (event pump, chat channels)
3381
+ // and — for a channel-marker registration — the client-chosen
3382
+ // suffix too (mirroring `handleCreateSession`).
3383
+ const suffix = sessionIDOf(recChannel) as string;
3384
+ if (suffix !== fs.sessionID) this.channels.addSession(suffix);
3385
+ const defaultChat = this.newChatRuntime(rec.defaultChatURI, fs.sessionID, "Chat 1", modifiedAt);
3386
+ this.bindChat(rec, defaultChat);
3387
+ sessionStore.apply({ type: ActionType.SessionReady });
3388
+ sessionStore.apply({ type: ActionType.SessionChatAdded, summary: chatSummaryOf(defaultChat.chatStore.state) });
3389
+ sessionStore.apply({ type: ActionType.SessionDefaultChatChanged, defaultChat: rec.defaultChatURI });
3390
+ // Advertise the changeset catalogues directly on the fresh
3391
+ // stores (registration is server-side bookkeeping — no seq, no actions).
3392
+ if (this.opts.changesets) {
3393
+ sessionStore.apply({ type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(recChannel) });
3394
+ defaultChat.chatStore.apply({
3395
+ type: ActionType.ChatChangesetsChanged,
3396
+ changesets: chatChangesetCatalog(rec.defaultChatURI, recChannel),
3397
+ });
3398
+ }
3399
+ // Durability: peers whose marker points at this
3400
+ // session may have been listed earlier in the same `listSessions`
3401
+ // pass — re-attach them before the root announcement so the
3402
+ // sessionAdded summary carries the full chat catalog.
3403
+ this.drainPendingChatBindings(fs.sessionID);
2058
3404
  this.publish({
2059
3405
  channel: ROOT_CHANNEL,
2060
3406
  action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
@@ -2065,17 +3411,34 @@ export class Host {
2065
3411
 
2066
3412
  /** Drop a session record and announce the removal on the root channel. */
2067
3413
  private removeRecord(rec: SessionRecord): void {
2068
- // Phase 2: every live changeset URI is about to become un-subscribable —
2069
- // dispatch `changeset/cleared` (protocol case 2) before the teardown so
2070
- // subscribers release their references.
2071
- for (const uri of rec.changesets.keys()) {
3414
+ const hadClients = rec.sessionStore.state.activeClients.length > 0;
3415
+ // Peer-chat backends are removed while their bindings are still live:
3416
+ // an unbound lingering backend would be re-registered by the next
3417
+ // listSessions scan as its own AHP session. R2: failures log — the
3418
+ // AHP side tears down either way (the ghost then shows in the TUI).
3419
+ for (const chat of rec.chats.values()) {
3420
+ if (chat.uri === rec.defaultChatURI) continue;
3421
+ void this.opts.facade
3422
+ .removeSession(chat.sessionID)
3423
+ .catch((err) => this.log(`failed to remove the peer chat's opencode session ${chat.sessionID}: ${errorMessage(err)}`));
3424
+ }
3425
+ // Every live changeset URI is about to become un-subscribable
3426
+ // — dispatch `changeset/cleared` (protocol case 2) before the teardown
3427
+ // so subscribers release their references.
3428
+ for (const uri of rec.sessionChangesets.keys()) {
2072
3429
  this.publish({ channel: uri, action: { type: ActionType.ChangesetCleared } });
2073
3430
  }
2074
- rec.changesets.clear();
2075
- rec.turnSnapshots.clear();
3431
+ rec.sessionChangesets.clear();
3432
+ // Per-chat teardown: live chat changesets
3433
+ // (`changeset/cleared`), in-flight client-tool executions failed
3434
+ // (the waiters must not leak), and every binding dropped.
3435
+ let failedTools = false;
3436
+ for (const chat of [...rec.chats.values()]) {
3437
+ failedTools = failedTools || [...chat.clientToolCalls.values()].some((inv) => inv.result === undefined);
3438
+ this.removeChat(rec, chat, "session removed before the client completed the tool call");
3439
+ }
2076
3440
  this.sessions.delete(rec.sessionID);
2077
3441
  this.byChannel.delete(rec.channel);
2078
- this.byChannel.delete(chatChannelURI(rec.sessionID));
2079
3442
  const id = sessionIDOf(rec.channel);
2080
3443
  if (id !== null) this.channels.removeSession(id);
2081
3444
  this.channels.removeSession(rec.sessionID);
@@ -2084,6 +3447,11 @@ export class Host {
2084
3447
  action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
2085
3448
  });
2086
3449
  this.notifyRoot("root/sessionRemoved", { channel: ROOT_CHANNEL, session: rec.channel });
3450
+ // Re-sync the opencode tool union when this
3451
+ // session's clients' tools leave the cross-session set (or any
3452
+ // in-flight call was failed — the facade union is unchanged, but the
3453
+ // session's execute gate must not linger).
3454
+ if (hadClients || failedTools) void this.syncClientToolsToOpencode();
2087
3455
  }
2088
3456
 
2089
3457
  // ── state / publishing ─────────────────────────────────────────────────
@@ -2103,9 +3471,11 @@ export class Host {
2103
3471
  if (!this.opts.changesets) return null;
2104
3472
  const parsed = parseChangesetChannel(uri);
2105
3473
  if (parsed === null) return null;
2106
- const rec = this.sessions.get(parsed.sessionID);
3474
+ // The owner is the session/chat channel (owner-aware).
3475
+ const rec = this.byChannel.get(parsed.ownerUri);
2107
3476
  if (rec === undefined) return null;
2108
3477
  const store = this.changesetStore(rec, uri);
3478
+ if (store === null) return null; // owner gone (disposed chat)
2109
3479
  // First subscribe (or a failed computation) triggers the computation;
2110
3480
  // subsequent subscribes return the last completed state.
2111
3481
  if (store.state.status === ChangesetStatus.Computing || store.state.status === ChangesetStatus.Error) {
@@ -2113,14 +3483,22 @@ export class Host {
2113
3483
  }
2114
3484
  return { resource: uri, state: store.state, fromSeq: this.seq.seq };
2115
3485
  }
3486
+ if (kind === "terminal") {
3487
+ // The synthetic terminal's official-reducer
3488
+ // state; null once the record is torn down (the chat is gone).
3489
+ const t = this.terminals.get(uri);
3490
+ if (t === undefined) return null;
3491
+ return { resource: uri, state: t.store.state, fromSeq: this.seq.seq };
3492
+ }
2116
3493
  if (kind !== "root") {
2117
3494
  const rec = this.byChannel.get(uri);
2118
3495
  if (rec === undefined) return null;
2119
3496
  if (uri === rec.channel) {
2120
3497
  return { resource: uri, state: rec.sessionStore.state, fromSeq: this.seq.seq };
2121
3498
  }
2122
- if (uri === chatChannelURI(rec.sessionID)) {
2123
- return { resource: uri, state: rec.chatStore.state, fromSeq: this.seq.seq };
3499
+ const chat = rec.chats.get(uri);
3500
+ if (chat !== undefined) {
3501
+ return { resource: uri, state: chat.chatStore.state, fromSeq: this.seq.seq };
2124
3502
  }
2125
3503
  return null;
2126
3504
  }
@@ -2138,8 +3516,13 @@ export class Host {
2138
3516
  /** The denormalized `SessionSummary` view of a record. */
2139
3517
  private sessionSummary(rec: SessionRecord): SessionSummary {
2140
3518
  const s = rec.sessionStore.state;
2141
- const c = rec.chatStore.state;
2142
- const modifiedAt = c.modifiedAt > rec.modifiedAt ? c.modifiedAt : rec.modifiedAt;
3519
+ // Authoritative chat order: default first, then insertion order
3520
+ // (the default chat is bound first).
3521
+ const chats = [...rec.chats.values()].map((c) => chatSummaryOf(c.chatStore.state));
3522
+ let modifiedAt = rec.modifiedAt;
3523
+ for (const c of rec.chats.values()) {
3524
+ if (c.chatStore.state.modifiedAt > modifiedAt) modifiedAt = c.chatStore.state.modifiedAt;
3525
+ }
2143
3526
  return buildSessionSummary({
2144
3527
  channel: rec.channel,
2145
3528
  provider: rec.provider,
@@ -2148,8 +3531,8 @@ export class Host {
2148
3531
  activity: s.activity,
2149
3532
  createdAt: rec.createdAt,
2150
3533
  modifiedAt,
2151
- chat: chatSummaryOf(c),
2152
- defaultChat: chatChannelURI(rec.sessionID),
3534
+ chats,
3535
+ defaultChat: rec.defaultChatURI,
2153
3536
  });
2154
3537
  }
2155
3538
 
@@ -2172,21 +3555,34 @@ export class Host {
2172
3555
  if (kind === "root") {
2173
3556
  this.state.apply(draft.action as RootAction);
2174
3557
  } else if (kind === "changeset") {
2175
- // Changeset stores live on the record (keyed by URI), resolved
2176
- // through the parsed owner session.
3558
+ // Changeset stores are owner-keyed (session-kind on the record,
3559
+ // chat-kind on the chat). Non-creating: a publish
3560
+ // targets a store someone created (subscribe/refresh); a missing
3561
+ // owner means the changeset is already torn down.
2177
3562
  const parsed = parseChangesetChannel(draft.channel);
2178
- const rec = parsed !== null ? this.sessions.get(parsed.sessionID) : undefined;
2179
- const store = rec !== undefined ? rec.changesets.get(draft.channel) : undefined;
3563
+ const rec = parsed !== null ? this.byChannel.get(parsed.ownerUri) : undefined;
3564
+ const store = rec !== undefined ? this.changesetStoreOf(rec, draft.channel) : undefined;
2180
3565
  if (store !== undefined) store.apply(draft.action as ChangesetAction);
3566
+ } else if (kind === "terminal") {
3567
+ // Synthetic shell-command terminals.
3568
+ // Non-creating: a publish targets a record that exists (opened at
3569
+ // `tool.input.ended`); a missing record means the channel was
3570
+ // already torn down — the notification still goes out.
3571
+ const t = this.terminals.get(draft.channel);
3572
+ if (t !== undefined) t.store.apply(draft.action as TerminalAction);
2181
3573
  } else {
2182
3574
  // byChannel, not sessions.get(sessionIDOf(…)): the channel suffix
2183
3575
  // is not always the opencode session id (client-chosen suffixes).
2184
3576
  const rec = this.byChannel.get(draft.channel);
2185
3577
  if (rec !== undefined) {
2186
3578
  const before = this.sessionSummary(rec);
2187
- if (kind === "session") rec.sessionStore.apply(draft.action as SessionAction);
2188
- else rec.chatStore.apply(draft.action as ChatAction);
2189
- if (kind === "chat") this.syncChatSummary(rec);
3579
+ if (kind === "session") {
3580
+ rec.sessionStore.apply(draft.action as SessionAction);
3581
+ } else {
3582
+ const chat = rec.chats.get(draft.channel);
3583
+ if (chat !== undefined) chat.chatStore.apply(draft.action as ChatAction);
3584
+ }
3585
+ if (kind === "chat") this.syncChatSummary(rec, draft.channel);
2190
3586
  const after = this.sessionSummary(rec);
2191
3587
  this.maybeNotifySummaryChanged(rec, before, after);
2192
3588
  }
@@ -2204,8 +3600,9 @@ export class Host {
2204
3600
  * reducer-reachable for read/archive/input-needed bits, so the chat
2205
3601
  * summary is the activity source of truth.
2206
3602
  */
2207
- private syncChatSummary(rec: SessionRecord): void {
2208
- const chat = rec.chatStore.state;
3603
+ private syncChatSummary(rec: SessionRecord, chatURI: string): void {
3604
+ const chat = rec.chats.get(chatURI)?.chatStore.state;
3605
+ if (chat === undefined) return;
2209
3606
  const entry = rec.sessionStore.state.chats.find((c) => c.resource === chat.resource);
2210
3607
  if (entry === undefined) return;
2211
3608
  const next = chatSummaryOf(chat);
@@ -2294,17 +3691,73 @@ function firstEnabledModelRef(models: readonly { providerID: string; modelID: st
2294
3691
 
2295
3692
  /** Normalize an untrusted `activeClient` payload (untrusted JSON-RPC). */
2296
3693
  function normalizeActiveClient(ac: Record<string, unknown>): SessionActiveClient {
2297
- const tools = Array.isArray(ac["tools"]) ? (ac["tools"] as ToolDefinition[]) : [];
2298
3694
  return {
2299
3695
  clientId: ac["clientId"] as string,
2300
- tools,
3696
+ tools: normalizeToolDefinitions(ac["tools"]),
2301
3697
  ...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
2302
3698
  };
2303
3699
  }
2304
3700
 
3701
+ /**
3702
+ * Wire-validate a client-dispatched `toolCallComplete` result:
3703
+ * `success` is the one field the host depends on (it decides
3704
+ * the facade result + the Tool.Error path); the rest is stored
3705
+ * verbatim for the AHP state mirror.
3706
+ */
3707
+ function normalizeToolCallResult(raw: unknown): ToolCallResult | null {
3708
+ if (typeof raw !== "object" || raw === null) return null;
3709
+ const r = raw as Record<string, unknown>;
3710
+ if (typeof r["success"] !== "boolean") return null;
3711
+ const pastTense = r["pastTenseMessage"];
3712
+ return {
3713
+ success: r["success"],
3714
+ pastTenseMessage:
3715
+ typeof pastTense === "string"
3716
+ ? pastTense
3717
+ : (isRecord(pastTense) && typeof pastTense["markdown"] === "string"
3718
+ ? (pastTense["markdown"] as string)
3719
+ : ""),
3720
+ ...(Array.isArray(r["content"]) ? { content: r["content"] as ToolResultContent[] } : {}),
3721
+ ...(isRecord(r["structuredContent"]) ? { structuredContent: r["structuredContent"] as Record<string, unknown> } : {}),
3722
+ ...(isRecord(r["error"]) ? { error: r["error"] as { message: string; code?: string } } : {}),
3723
+ };
3724
+ }
3725
+
3726
+ /** StringOrMarkdown → plain string (the facade result carries text). */
3727
+ function stringOrMarkdownToText(v: StringOrMarkdown | undefined): string {
3728
+ if (v === undefined) return "";
3729
+ if (typeof v === "string") return v;
3730
+ return typeof v.markdown === "string" ? v.markdown : "";
3731
+ }
3732
+
3733
+ /**
3734
+ * A validated client `ToolCallResult` → the opencode-side result:
3735
+ * success:false → the `Tool.Error` message (the model sees the
3736
+ * failure); success → the text content blocks joined (non-text blocks
3737
+ * stay in the AHP state for the client's UI; the model gets the text +
3738
+ * the past-tense message).
3739
+ */
3740
+ function clientResultToFacade(result: ToolCallResult): FacadeClientToolResult {
3741
+ if (!result.success) {
3742
+ return { ok: false, error: result.error?.message ?? "the client reported a tool failure" };
3743
+ }
3744
+ const texts: string[] = [];
3745
+ for (const c of result.content ?? []) {
3746
+ // The content came from the wire (untrusted) — guard the shape.
3747
+ if (c.type === ToolResultContentType.Text && typeof c.text === "string") texts.push(c.text);
3748
+ }
3749
+ const content = texts.join("\n\n");
3750
+ return {
3751
+ ok: true,
3752
+ pastTenseMessage: stringOrMarkdownToText(result.pastTenseMessage),
3753
+ ...(content.length > 0 ? { content } : {}),
3754
+ ...(result.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}),
3755
+ };
3756
+ }
3757
+
2305
3758
  /**
2306
3759
  * Map opencode tool result content blocks to AHP `ToolResultContent`
2307
- * (only text blocks are representable in this MVP; file/patch text is
3760
+ * (only text blocks are representable; file/patch text is
2308
3761
  * carried as text).
2309
3762
  */
2310
3763
  function mapToolResultContent(content: readonly { type: string; text?: string }[]): ToolResultContent[] {