opencode-ahp 0.1.3 → 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,31 +17,42 @@
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
35
37
  * *notifications* in AHP 1.0.0 (ephemeral, not replayed) — only
36
38
  * `root/activeSessionsChanged` is a sequencer action.
37
39
  */
40
+ import { resolve as resolvePath } from "node:path";
41
+ import { fileURLToPath } from "node:url";
38
42
  import {
39
43
  ActionType,
44
+ ChangesetOperationScope,
45
+ ChangesetOperationStatus,
46
+ ChangesetStatus,
40
47
  PendingMessageKind,
41
48
  ReconnectResultType,
42
49
  ResponsePartKind,
43
50
  SessionInputRequestKind,
44
51
  SessionStatus,
52
+ TerminalClaimKind,
53
+ TerminalLifecycleStatus,
45
54
  ToolCallConfirmationReason,
55
+ ToolCallContributorKind,
46
56
  ToolCallStatus,
47
57
  ToolResultContentType,
48
58
  isClientDispatchable,
@@ -50,57 +60,101 @@ import {
50
60
  type ActionOrigin,
51
61
  type ChatAction,
52
62
  type ChatSummary,
53
- type ChatState,
63
+ type ChatToolCallCompleteAction,
54
64
  type ChatToolCallConfirmedAction,
65
+ type ChatToolCallContentChangedAction,
66
+ type ChatToolCallResultConfirmedAction,
55
67
  type ChatTurnCancelledAction,
56
68
  type ChatTurnStartedAction,
69
+ type ChangesetAction,
70
+ type ChangesetFilesReviewChangedAction,
57
71
  type ErrorResponsePart,
58
72
  type Implementation,
59
73
  type Message,
60
74
  type ReconnectResult,
75
+ type ResolveSessionConfigResult,
61
76
  type RootAction,
62
77
  type SessionAction,
63
78
  type SessionActiveClient,
64
- type SessionState,
65
79
  type SessionSummary,
80
+ type SessionToolClientExecutionRequest,
66
81
  type SessionToolConfirmationRequest,
67
82
  type Snapshot,
68
83
  type StateAction,
84
+ type StringOrMarkdown,
85
+ type TerminalAction,
86
+ type TerminalInfo,
87
+ type TerminalState,
69
88
  type ToolCallConfirmationState,
89
+ type ToolCallResult,
70
90
  type ToolCallState,
71
- type ToolDefinition,
72
91
  type ToolResultContent,
73
92
  } from "@microsoft/agent-host-protocol";
74
93
  import {
75
94
  agentDirectoryCustomization,
76
95
  agentIDFromUri,
77
96
  buildSessionSummary,
97
+ buildTurnChangesetFiles,
98
+ buildWorkingChangesetFiles,
99
+ chatChangesetCatalog,
78
100
  chatSummaryOf,
79
101
  displayNameFor,
102
+ discardOperation,
103
+ directoryUri,
104
+ fileUri,
80
105
  initialChatState,
81
106
  initialSessionState,
82
107
  invocationMessageFor,
83
108
  mapCatalog,
84
109
  mapAgentCustomizations,
110
+ parseContentRef,
85
111
  pastTenseMessageFor,
112
+ sessionChangesetCatalog,
86
113
  userMessage,
114
+ type FacadeClientTool,
115
+ type FacadeClientToolResult,
87
116
  type FacadeDelivery,
88
117
  type FacadeEvent,
89
118
  type FacadeModelRef,
90
119
  type FacadeSession,
120
+ type FacadeToolContent,
91
121
  type OpencodeFacade,
92
122
  } from "./bridge.js";
93
- import { ChannelRegistry, ROOT_CHANNEL, channelKind, chatChannelURI, sessionChannelURI, sessionIDOf } from "./channels.js";
123
+ import {
124
+ descriptionFor,
125
+ findProvider,
126
+ inputSchemaFor,
127
+ normalizeToolDefinitions,
128
+ toolUnion,
129
+ type ClientToolInvocation,
130
+ } from "./client-tools.js";
131
+ import {
132
+ ChannelRegistry,
133
+ ROOT_CHANNEL,
134
+ channelKind,
135
+ chatChannelURI,
136
+ parseChangesetChannel,
137
+ sessionChannelURI,
138
+ sessionChangesetURI,
139
+ sessionIDOf,
140
+ terminalChannelURI,
141
+ turnChangesetURI,
142
+ uncommittedChangesetURI,
143
+ } from "./channels.js";
94
144
  import { ERROR_INVALID_PARAMS, handleInitialize } from "./handshake.js";
95
145
  import { isRecord } from "./options.js";
96
146
  import { Sequencer } from "./seq.js";
97
147
  import {
98
148
  createChatStateStore,
149
+ createChangesetStateStore,
99
150
  createRootStateStore,
100
151
  createSessionStateStore,
152
+ createTerminalStateStore,
101
153
  type ChatStateStore,
154
+ type ChangesetStateStore,
102
155
  type RootStateStore,
103
156
  type SessionStateStore,
157
+ type TerminalStateStore,
104
158
  } from "./state.js";
105
159
 
106
160
  export const ERROR_PARSE = -32700;
@@ -110,6 +164,9 @@ export const ERROR_INTERNAL = -32603;
110
164
  export const ERROR_SESSION_NOT_FOUND = -32001;
111
165
  export const ERROR_NO_PROVIDER = -32002;
112
166
  export const ERROR_SESSION_EXISTS = -32003;
167
+ export const ERROR_NOT_FOUND = -32008;
168
+ export const ERROR_PERMISSION_DENIED = -32009;
169
+ export const ERROR_NOT_SUPPORTED = -32010;
113
170
 
114
171
  // ActionType / ReconnectResultType are `declare const enum` in the package
115
172
  // but are also real runtime objects (verified against the published dist),
@@ -139,22 +196,16 @@ interface ClientRecord {
139
196
  }
140
197
 
141
198
  /**
142
- * Everything the host knows about one live opencode session: the two
143
- * official-reducer stores (session + its single chat), the denormalized
144
- * summary fields for root notifications, and the per-turn tracking the
145
- * event pump needs to join opencode events to AHP turns.
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.
146
203
  */
147
- interface SessionRecord {
148
- /** 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_…`). */
149
208
  sessionID: string;
150
- /** The AHP session channel URI (`ahp-session:/<suffix>`). */
151
- channel: string;
152
- /** Identity `SessionSummary.provider` (fixed at registration). */
153
- provider: string;
154
- createdAt: string;
155
- /** Denormalized `SessionSummary.modifiedAt` (ISO; lexicographic = chronological). */
156
- modifiedAt: string;
157
- sessionStore: SessionStateStore;
158
209
  chatStore: ChatStateStore;
159
210
  // ── turn tracking (event-pump join state) ────────────────────────────
160
211
  /** The AHP turnId the pump joins opencode events to, or null. */
@@ -175,8 +226,80 @@ interface SessionRecord {
175
226
  permissionForTool: Map<string, string>;
176
227
  /** opencode permission request id → toolCallId. */
177
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>;
178
234
  /** The most recent `session.inbox.enqueued` (external/TUI prompt tracking). */
179
235
  lastInbox: { text: string; delivery: string } | null;
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
+ */
242
+ changesets: Map<string, ChangesetStateStore>;
243
+ /**
244
+ * Per-turn file snapshots for the turn changesets: turnId → absPath →
245
+ * captured {before (pre-edit disk read), after (disk at turn end)}.
246
+ * `null` = the file was absent on that side. Kept until the chat is
247
+ * removed (content refs + discard-restore read them).
248
+ */
249
+ turnSnapshots: Map<string, Map<string, { before: string | null; after: string | null }>>;
250
+ }
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;
180
303
  }
181
304
 
182
305
  export interface HostOptions {
@@ -185,6 +308,15 @@ export interface HostOptions {
185
308
  replayWindow: number;
186
309
  /** The opencode instance's working directory (InitializeResult.defaultDirectory). */
187
310
  defaultDirectory?: string;
311
+ /** Advertise + serve the changeset channels (catalogues, snapshots, discard). */
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;
188
320
  /** Deliver a JSON-serializable frame to a connection. */
189
321
  send: (socketId: number, message: unknown) => void;
190
322
  /** Close one connection (a superseded duplicate clientId). */
@@ -203,6 +335,84 @@ const RECONNECT_DEFAULT_VERSION = "1.0.0";
203
335
  const EXTERNAL_REGISTER_GRACE_MS = 250;
204
336
  /** Default page size for `listSessions` (AHP `PaginatedParams.limit`). */
205
337
  const LIST_SESSIONS_DEFAULT_LIMIT = 100;
338
+ /**
339
+ * The file-mutating opencode tools whose inputs carry a target path — the
340
+ * turn-changeset before-capture watches only these (`tool.input.ended`
341
+ * fires before execution, so the pre-edit content is still on disk).
342
+ */
343
+ const SNAPSHOT_TOOLS = new Set(["write", "edit", "apply", "patch"]);
344
+ /** The tool-input keys that carry a file path (checked in order). */
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
+ }
206
416
 
207
417
  export class Host {
208
418
  private readonly seq: Sequencer;
@@ -218,6 +428,30 @@ export class Host {
218
428
  */
219
429
  private readonly sessions = new Map<string, SessionRecord>();
220
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>();
221
455
  private readonly opts: HostOptions;
222
456
  private readonly log: (message: string) => void;
223
457
  private turnCounter = 0;
@@ -278,12 +512,55 @@ export class Host {
278
512
  if (socket?.clientId) {
279
513
  const record = this.clients.get(socket.clientId);
280
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);
281
519
  }
282
520
  this.channels.removeSocket(socketId);
283
521
  this.sockets.delete(socketId);
284
- // MVP gap: active clients are not evicted on disconnect (the spec
285
- // expects eviction without a timely reconnect); they refresh via
286
- // `session/activeClientSet` on the next turn/dispatch.
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();
287
564
  }
288
565
 
289
566
  // ── event pump ─────────────────────────────────────────────────────────
@@ -370,11 +647,40 @@ export class Host {
370
647
  case "listSessions":
371
648
  await this.handleListSessions(socketId, msg);
372
649
  break;
650
+ case "resolveSessionConfig":
651
+ this.handleResolveSessionConfig(socketId, msg);
652
+ break;
373
653
  case "createSession":
374
654
  await this.handleCreateSession(socketId, msg);
375
655
  break;
656
+ case "createChat":
657
+ await this.handleCreateChat(socketId, msg);
658
+ break;
659
+ case "disposeChat":
660
+ await this.handleDisposeChat(socketId, msg);
661
+ break;
662
+ case "resourceRead":
663
+ await this.handleResourceRead(socketId, msg);
664
+ break;
665
+ case "invokeChangesetOperation":
666
+ await this.handleInvokeChangesetOperation(socketId, msg);
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;
376
682
  case "setClientManagedSettingsPermissions":
377
- // VS Code-specific post-init notification (plan §14.7): the
683
+ // VS Code-specific post-init notification: the
378
684
  // permissions VS Code manages in its own settings UI. AHP 1.0.0
379
685
  // has no counterpart — accept deliberately (parse + log), never
380
686
  // error; the connection stays up.
@@ -539,7 +845,9 @@ export class Host {
539
845
  code:
540
846
  outcome.reason === "no-such-session"
541
847
  ? ERROR_SESSION_NOT_FOUND
542
- : ERROR_INVALID_PARAMS,
848
+ : outcome.reason === "no-such-terminal"
849
+ ? ERROR_NOT_FOUND
850
+ : ERROR_INVALID_PARAMS,
543
851
  message: `cannot subscribe to ${uri}`,
544
852
  },
545
853
  });
@@ -577,6 +885,14 @@ export class Host {
577
885
  return;
578
886
  }
579
887
  const suffix = sessionIDOf(channel) as string;
888
+ // A suffix containing the changeset marker would make this session
889
+ // channel string-identical to the changeset URI of the session before
890
+ // the marker — the changeset kind would win (channelKind), making the
891
+ // session channel un-subscribable. Reject it instead.
892
+ if (suffix.includes("/changeset/")) {
893
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "channel suffix must not contain \"/changeset/\"");
894
+ return;
895
+ }
580
896
  for (const rec of this.sessions.values()) {
581
897
  if (rec.channel === channel) {
582
898
  this.sendError(socketId, msg.id, ERROR_SESSION_EXISTS, "Session already exists");
@@ -621,12 +937,29 @@ export class Host {
621
937
  // only when it already is one; otherwise let opencode mint an id and
622
938
  // record the suffix→id mapping (the record key is the opencode id).
623
939
  const passID = suffix.startsWith("ses") ? suffix : undefined;
624
- 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
+ });
625
950
 
626
951
  // Slow-create race: the pump may have registered this opencode session
627
952
  // under its own id as an external session while `createSession` was in
628
953
  // flight. Remap: drop the interim record (root/sessionRemoved) and
629
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).
630
963
  const interim = this.sessions.get(created.sessionID);
631
964
  if (interim !== undefined && interim.channel !== channel) {
632
965
  this.removeRecord(interim);
@@ -647,9 +980,6 @@ export class Host {
647
980
  customizations,
648
981
  }),
649
982
  );
650
- const chatStore = createChatStateStore(
651
- initialChatState({ resource: chatChannelURI(created.sessionID), title: "Chat 1", modifiedAt: now }),
652
- );
653
983
  const rec: SessionRecord = {
654
984
  sessionID: created.sessionID,
655
985
  channel,
@@ -659,37 +989,50 @@ export class Host {
659
989
  ? new Date(created.time.updated).toISOString()
660
990
  : now,
661
991
  sessionStore,
662
- chatStore,
663
- currentTurnId: null,
664
- turnStartedAt: null,
665
- turnModelRef: null,
666
- parts: new Set(),
667
- toolInput: new Map(),
668
- toolName: new Map(),
669
- toolReady: new Set(),
670
- permissionForTool: new Map(),
671
- toolForPermission: new Map(),
672
- lastInbox: null,
992
+ chats: new Map(),
993
+ defaultChatURI: chatChannelURI(created.sessionID),
994
+ sessionChangesets: new Map(),
673
995
  };
674
996
  this.sessions.set(created.sessionID, rec);
675
997
  this.byChannel.set(channel, rec);
676
- this.byChannel.set(chatChannelURI(created.sessionID), rec);
677
998
  // The session channel carries the client-chosen suffix; the chat
678
999
  // channel and the event pump carry the opencode id — both must
679
1000
  // resolve in the registry.
680
1001
  this.channels.addSession(suffix);
681
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();
682
1009
 
683
1010
  // Session-channel lifecycle (server-side, no origin).
684
1011
  this.publish({ channel, action: { type: ActionType.SessionReady } });
685
1012
  this.publish({
686
1013
  channel,
687
- action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chatStore.state) },
1014
+ action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(defaultChat.chatStore.state) },
688
1015
  });
689
1016
  this.publish({
690
1017
  channel,
691
- action: { type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(created.sessionID) },
1018
+ action: { type: ActionType.SessionDefaultChatChanged, defaultChat: rec.defaultChatURI },
692
1019
  });
1020
+ // Advertise the changeset catalogues (session channel: the
1021
+ // session-wide changeset; chat channel: uncommitted + session + the
1022
+ // per-turn template).
1023
+ if (this.opts.changesets) {
1024
+ this.publish({
1025
+ channel,
1026
+ action: { type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(channel) },
1027
+ });
1028
+ this.publish({
1029
+ channel: rec.defaultChatURI,
1030
+ action: {
1031
+ type: ActionType.ChatChangesetsChanged,
1032
+ changesets: chatChangesetCatalog(rec.defaultChatURI, channel),
1033
+ },
1034
+ });
1035
+ }
693
1036
  // Root: active-session count (action, replayed) + sessionAdded (notification).
694
1037
  this.publish({
695
1038
  channel: ROOT_CHANNEL,
@@ -703,6 +1046,291 @@ export class Host {
703
1046
  this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
704
1047
  }
705
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
+
706
1334
  /**
707
1335
  * `listSessions` (AHP 1.0.0 root command): all opencode sessions,
708
1336
  * most-recently-modified first, with in-memory cursor pagination.
@@ -741,11 +1369,44 @@ export class Host {
741
1369
  this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
742
1370
  }
743
1371
 
744
- // ── 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 ──────────────────────────────
745
1406
 
746
1407
  /**
747
1408
  * `dispatchAction` is a notification — the response is the `action`
748
- * notification stream itself. Phase 1 routes the client-dispatchable
1409
+ * notification stream itself. The host routes the client-dispatchable
749
1410
  * actions VS Code sends; everything else is acknowledged with a
750
1411
  * rejection on that stream.
751
1412
  */
@@ -778,29 +1439,86 @@ export class Host {
778
1439
  }
779
1440
 
780
1441
  const kind = channelKind(channel);
1442
+ if (kind === "changeset") {
1443
+ // The only client-dispatchable changeset action is the per-file
1444
+ // review toggle — echo it through the official reducer.
1445
+ if (stateAction.type === ActionType.ChangesetFilesReviewChanged) {
1446
+ this.dispatchChangesetFilesReviewChanged(channel, stateAction, origin);
1447
+ } else {
1448
+ this.echo(channel, stateAction, origin, `unsupported action on changeset channel: ${String(action.type)}`);
1449
+ }
1450
+ return;
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
+ }
781
1469
  if (kind !== "session" && kind !== "chat") {
782
1470
  this.echo(channel, stateAction, origin, `unsupported action on ${channelKind(channel)} channel: ${String(action.type)}`);
783
1471
  return;
784
1472
  }
785
1473
  const rec = this.byChannel.get(channel);
786
1474
  if (rec === undefined) {
787
- 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}`);
788
1485
  return;
789
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}`);
790
1492
 
791
1493
  // From here on every branch either echoes (accepted or rejected).
792
1494
  switch (stateAction.type) {
793
1495
  case ActionType.ChatTurnStarted:
794
- await this.dispatchTurnStarted(rec, stateAction, origin);
1496
+ if (chat === undefined) { noChat(); return; }
1497
+ await this.dispatchTurnStarted(chat, stateAction, origin);
795
1498
  return;
796
1499
  case ActionType.ChatPendingMessageSet:
797
- await this.dispatchPendingMessageSet(rec, stateAction, origin);
1500
+ if (chat === undefined) { noChat(); return; }
1501
+ await this.dispatchPendingMessageSet(chat, stateAction, origin);
798
1502
  return;
799
1503
  case ActionType.ChatToolCallConfirmed:
800
- 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);
801
1518
  return;
802
1519
  case ActionType.ChatTurnCancelled:
803
- await this.dispatchTurnCancelled(rec, stateAction, origin);
1520
+ if (chat === undefined) { noChat(); return; }
1521
+ await this.dispatchTurnCancelled(chat, stateAction, origin);
804
1522
  return;
805
1523
  case ActionType.SessionTitleChanged:
806
1524
  await this.dispatchTitleChanged(rec, stateAction, origin);
@@ -824,7 +1542,7 @@ export class Host {
824
1542
  this.echo(channel, stateAction, origin);
825
1543
  return;
826
1544
  default:
827
- this.echo(channel, stateAction, origin, `unsupported action (Phase 1): ${String(stateAction.type)}`);
1545
+ this.echo(channel, stateAction, origin, `unsupported action: ${String(stateAction.type)}`);
828
1546
  }
829
1547
  }
830
1548
 
@@ -877,8 +1595,8 @@ export class Host {
877
1595
  return undefined;
878
1596
  }
879
1597
 
880
- private async dispatchTurnStarted(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
881
- const chatURI = chatChannelURI(rec.sessionID);
1598
+ private async dispatchTurnStarted(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1599
+ const chatURI = chat.uri;
882
1600
  const a = action as ChatTurnStartedAction;
883
1601
  const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
884
1602
  const message =
@@ -896,7 +1614,7 @@ export class Host {
896
1614
  typeof a.startedAt === "string" && !Number.isNaN(Date.parse(a.startedAt))
897
1615
  ? a
898
1616
  : { ...a, startedAt: new Date().toISOString() };
899
- if (rec.chatStore.state.activeTurn !== undefined) {
1617
+ if (chat.chatStore.state.activeTurn !== undefined) {
900
1618
  this.echo(
901
1619
  chatURI,
902
1620
  action,
@@ -906,46 +1624,32 @@ export class Host {
906
1624
  return;
907
1625
  }
908
1626
 
909
- // Apply the message's model/agent selection before the prompt
910
- // (`SessionPromptInput` carries no model/agent fields).
911
- try {
912
- if (message.model?.id !== undefined && message.model.id.includes("/")) {
913
- const sep = message.model.id.indexOf("/");
914
- const providerID = message.model.id.slice(0, sep);
915
- const modelID = message.model.id.slice(sep + 1);
916
- if (providerID.length > 0 && modelID.length > 0) {
917
- await this.opts.facade.switchModel({ sessionID: rec.sessionID, model: { providerID, modelID } });
918
- }
919
- }
920
- if (message.agent?.uri !== undefined) {
921
- const agentID = agentIDFromUri(message.agent.uri);
922
- if (agentID !== null) {
923
- await this.opts.facade.switchAgent({ sessionID: rec.sessionID, agent: agentID });
924
- }
925
- }
926
- } catch (err) {
927
- this.echo(chatURI, action, origin, `failed to apply model/agent selection: ${errorMessage(err)}`);
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}`);
928
1632
  return;
929
1633
  }
930
1634
 
931
1635
  // Write-ahead: claim the turn BEFORE the prompt so the
932
1636
  // `session.execution.started` event joins it even when it races the
933
1637
  // prompt's resolve; revert on failure.
934
- rec.currentTurnId = turnId;
935
- rec.turnStartedAt = Date.now();
1638
+ chat.currentTurnId = turnId;
1639
+ chat.turnStartedAt = Date.now();
936
1640
  try {
937
- await this.opts.facade.prompt({ sessionID: rec.sessionID, text: message.text });
1641
+ await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text });
938
1642
  } catch (err) {
939
- rec.currentTurnId = null;
940
- rec.turnStartedAt = null;
1643
+ chat.currentTurnId = null;
1644
+ chat.turnStartedAt = null;
941
1645
  this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
942
1646
  return;
943
1647
  }
944
1648
  this.echo(chatURI, normalized, origin);
945
1649
  }
946
1650
 
947
- private async dispatchPendingMessageSet(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
948
- const chatURI = chatChannelURI(rec.sessionID);
1651
+ private async dispatchPendingMessageSet(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1652
+ const chatURI = chat.uri;
949
1653
  const a = action as { kind?: unknown; id?: unknown; message?: unknown };
950
1654
  const kind = a.kind === "steering" || a.kind === "queued" ? a.kind : null;
951
1655
  const id = typeof a.id === "string" && a.id.length > 0 ? a.id : null;
@@ -957,7 +1661,7 @@ export class Host {
957
1661
  this.echo(chatURI, action, origin, "invalid chat/pendingMessageSet params");
958
1662
  return;
959
1663
  }
960
- const hasActiveTurn = rec.chatStore.state.activeTurn !== undefined;
1664
+ const hasActiveTurn = chat.chatStore.state.activeTurn !== undefined;
961
1665
  // steer → delivery "steer" (only while a turn is active); queued →
962
1666
  // delivery "queue"; a steering message with no active turn falls back
963
1667
  // to a plain prompt (it becomes the next turn).
@@ -967,7 +1671,7 @@ export class Host {
967
1671
  : "queue"
968
1672
  : undefined;
969
1673
  try {
970
- 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 });
971
1675
  } catch (err) {
972
1676
  this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
973
1677
  return;
@@ -981,8 +1685,8 @@ export class Host {
981
1685
  // `queuedMessageId` — the reducer dequeues it.
982
1686
  this.echo(chatURI, action, origin);
983
1687
  const turnId = this.mintTurnId();
984
- rec.currentTurnId = turnId;
985
- rec.turnStartedAt = Date.now();
1688
+ chat.currentTurnId = turnId;
1689
+ chat.turnStartedAt = Date.now();
986
1690
  this.publish({
987
1691
  channel: chatURI,
988
1692
  action: {
@@ -995,22 +1699,23 @@ export class Host {
995
1699
  });
996
1700
  }
997
1701
 
998
- private async dispatchToolCallConfirmed(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
999
- 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)!;
1000
1705
  const a = action as ChatToolCallConfirmedAction;
1001
1706
  const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
1002
1707
  if (toolCallId === null) {
1003
1708
  this.echo(chatURI, action, origin, "invalid chat/toolCallConfirmed params");
1004
1709
  return;
1005
1710
  }
1006
- const permissionID = rec.permissionForTool.get(toolCallId);
1711
+ const permissionID = chat.permissionForTool.get(toolCallId);
1007
1712
  if (permissionID === undefined) {
1008
1713
  this.echo(chatURI, action, origin, `no pending permission for tool call ${toolCallId}`);
1009
1714
  return;
1010
1715
  }
1011
1716
  try {
1012
1717
  await this.opts.facade.replyPermission({
1013
- sessionID: rec.sessionID,
1718
+ sessionID: chat.sessionID,
1014
1719
  requestID: permissionID,
1015
1720
  decision: a.approved === true ? "once" : "reject",
1016
1721
  });
@@ -1026,21 +1731,174 @@ export class Host {
1026
1731
  channel: rec.channel,
1027
1732
  action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
1028
1733
  });
1029
- rec.permissionForTool.delete(toolCallId);
1030
- rec.toolForPermission.delete(permissionID);
1734
+ chat.permissionForTool.delete(toolCallId);
1735
+ chat.toolForPermission.delete(permissionID);
1736
+ }
1737
+
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
+ }
1031
1807
  }
1032
1808
 
1033
- private async dispatchTurnCancelled(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1034
- const chatURI = chatChannelURI(rec.sessionID);
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;
1035
1893
  const a = action as ChatTurnCancelledAction;
1036
1894
  const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
1037
- const active = rec.chatStore.state.activeTurn;
1895
+ const active = chat.chatStore.state.activeTurn;
1038
1896
  if (turnId === null || active === undefined || active.id !== turnId) {
1039
1897
  this.echo(chatURI, action, origin, "no active turn to cancel");
1040
1898
  return;
1041
1899
  }
1042
1900
  try {
1043
- await this.opts.facade.interrupt({ sessionID: rec.sessionID });
1901
+ await this.opts.facade.interrupt({ sessionID: chat.sessionID });
1044
1902
  } catch (err) {
1045
1903
  this.echo(chatURI, action, origin, `interrupt failed: ${errorMessage(err)}`);
1046
1904
  return;
@@ -1049,12 +1907,33 @@ export class Host {
1049
1907
  // `modifiedAt` from it); the host clock is authoritative when the
1050
1908
  // client did not supply one.
1051
1909
  const duration =
1052
- 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);
1053
1911
  this.echo(chatURI, { ...a, duration }, origin);
1054
1912
  // The opencode `session.execution.interrupted` event finds no active
1055
1913
  // turn after the echo finalized it (skipped); run the queued/steering
1056
1914
  // handoff now, on the host side.
1057
- this.finishTurn(rec);
1915
+ await this.finishTurn(chat);
1916
+ }
1917
+
1918
+ /**
1919
+ * `changeset/filesReviewChanged` (the only client-dispatchable changeset
1920
+ * action): validate the channel resolves to a live store, then echo —
1921
+ * the official reducer toggles `reviewed` per matched file id.
1922
+ */
1923
+ private dispatchChangesetFilesReviewChanged(channel: string, action: StateAction, origin: ActionOrigin | undefined): void {
1924
+ const a = action as ChangesetFilesReviewChangedAction;
1925
+ if (!Array.isArray(a.files) || !a.files.every((f) => typeof f === "string") || typeof a.reviewed !== "boolean") {
1926
+ this.echo(channel, action, origin, "invalid changeset/filesReviewChanged params");
1927
+ return;
1928
+ }
1929
+ const parsed = parseChangesetChannel(channel);
1930
+ const rec = parsed !== null ? this.byChannel.get(parsed.ownerUri) : undefined;
1931
+ const store = rec !== undefined ? this.changesetStoreOf(rec, channel) : undefined;
1932
+ if (rec === undefined || store === undefined) {
1933
+ this.echo(channel, action, origin, "no such changeset");
1934
+ return;
1935
+ }
1936
+ this.echo(channel, action, origin);
1058
1937
  }
1059
1938
 
1060
1939
  private async dispatchTitleChanged(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
@@ -1085,7 +1964,7 @@ export class Host {
1085
1964
  this.echo(rec.channel, action, origin, "activeClient.clientId must match the dispatching client");
1086
1965
  return;
1087
1966
  }
1088
- const tools = Array.isArray(ac["tools"]) ? (ac["tools"] as ToolDefinition[]) : [];
1967
+ const tools = normalizeToolDefinitions(ac["tools"]);
1089
1968
  const normalized: SessionActiveClient = {
1090
1969
  clientId: ac["clientId"] as string,
1091
1970
  tools,
@@ -1096,6 +1975,9 @@ export class Host {
1096
1975
  action: { type: ActionType.SessionActiveClientSet, activeClient: normalized },
1097
1976
  origin,
1098
1977
  });
1978
+ // The session's tool contribution changed —
1979
+ // re-sync the location-global opencode tool union.
1980
+ void this.syncClientToolsToOpencode();
1099
1981
  }
1100
1982
 
1101
1983
  private dispatchActiveClientRemoved(
@@ -1110,13 +1992,19 @@ export class Host {
1110
1992
  return;
1111
1993
  }
1112
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();
1113
1998
  }
1114
1999
 
1115
2000
  // ── opencode event pump handlers ───────────────────────────────────────
1116
2001
 
1117
2002
  private async handleEvent(ev: FacadeEvent): Promise<void> {
1118
2003
  if (ev.type === "session.created") {
1119
- 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;
1120
2008
  // Deferred registration: a concurrent `createSession` may still be
1121
2009
  // resolving for this opencode session under a client-chosen channel;
1122
2010
  // the grace + existence check avoids the double registration, and
@@ -1131,69 +2019,90 @@ export class Host {
1131
2019
  return;
1132
2020
  }
1133
2021
 
1134
- const rec = this.sessions.get(ev.sessionID);
1135
- if (rec === undefined) return; // only session.created registers sessions
1136
-
1137
- const chatURI = chatChannelURI(rec.sessionID);
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;
1138
2029
  switch (ev.type) {
1139
2030
  case "session.deleted":
1140
- 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
+ }
1141
2040
  return;
1142
2041
  case "session.renamed":
1143
- 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
+ }
1144
2053
  return;
1145
2054
  case "inbox.enqueued":
1146
- rec.lastInbox = { text: ev.text, delivery: ev.delivery };
2055
+ chat.lastInbox = { text: ev.text, delivery: ev.delivery };
1147
2056
  return;
1148
2057
  case "inbox.delivered":
1149
2058
  // Steering consumption is handled at turn end (finishTurn).
1150
2059
  return;
1151
2060
  case "execution.started":
1152
- if (rec.currentTurnId !== null) return; // write-ahead already claimed the turn
2061
+ if (chat.currentTurnId !== null) return; // write-ahead already claimed the turn
1153
2062
  // Orphan turn (an external TUI prompt, or a handoff this host did
1154
2063
  // not initiate): start it with the last-seen inbox message.
1155
- this.startTurn(rec, rec.lastInbox !== null ? userMessage(rec.lastInbox.text) : userMessage(""));
2064
+ this.startTurn(chat, chat.lastInbox !== null ? userMessage(chat.lastInbox.text) : userMessage(""));
1156
2065
  return;
1157
2066
  case "execution.succeeded":
1158
- if (rec.currentTurnId === null) return;
2067
+ if (chat.currentTurnId === null) return;
1159
2068
  this.publish({
1160
2069
  channel: chatURI,
1161
- action: { type: ActionType.ChatTurnComplete, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
2070
+ action: { type: ActionType.ChatTurnComplete, turnId: chat.currentTurnId, duration: this.turnDuration(chat) },
1162
2071
  });
1163
- this.finishTurn(rec);
2072
+ await this.finishTurn(chat);
1164
2073
  return;
1165
2074
  case "execution.failed":
1166
- if (rec.currentTurnId === null) return;
2075
+ if (chat.currentTurnId === null) return;
1167
2076
  const part: ErrorResponsePart = {
1168
2077
  kind: ResponsePartKind.Error,
1169
2078
  error: { errorType: ev.error.type, message: ev.error.message },
1170
2079
  };
1171
2080
  this.publish({
1172
2081
  channel: chatURI,
1173
- 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 },
1174
2083
  });
1175
- this.finishTurn(rec);
2084
+ await this.finishTurn(chat);
1176
2085
  return;
1177
2086
  case "execution.interrupted":
1178
2087
  // Skipped when the client's own `chat/turnCancelled` echo already
1179
2088
  // finalized the turn (currentTurnId is null).
1180
- if (rec.currentTurnId === null) return;
2089
+ if (chat.currentTurnId === null) return;
1181
2090
  this.publish({
1182
2091
  channel: chatURI,
1183
- action: { type: ActionType.ChatTurnCancelled, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
2092
+ action: { type: ActionType.ChatTurnCancelled, turnId: chat.currentTurnId, duration: this.turnDuration(chat) },
1184
2093
  });
1185
- this.finishTurn(rec);
2094
+ await this.finishTurn(chat);
1186
2095
  return;
1187
2096
  case "step.started":
1188
- rec.turnModelRef = `${ev.model.providerID}/${ev.model.modelID}`;
2097
+ chat.turnModelRef = `${ev.model.providerID}/${ev.model.modelID}`;
1189
2098
  return;
1190
2099
  case "text.delta":
1191
2100
  case "reasoning.delta": {
1192
- if (rec.currentTurnId === null) return;
2101
+ if (chat.currentTurnId === null) return;
1193
2102
  const kind = ev.type === "text.delta" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
1194
2103
  const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
1195
- const first = !rec.parts.has(key);
1196
- rec.parts.add(key);
2104
+ const first = !chat.parts.has(key);
2105
+ chat.parts.add(key);
1197
2106
  const partId = `part-${key}`;
1198
2107
  if (first) {
1199
2108
  // Lazily emit the part on the first delta; it carries the
@@ -1202,7 +2111,7 @@ export class Host {
1202
2111
  channel: chatURI,
1203
2112
  action: {
1204
2113
  type: ActionType.ChatResponsePart,
1205
- turnId: rec.currentTurnId,
2114
+ turnId: chat.currentTurnId,
1206
2115
  part: { kind, id: partId, content: ev.delta },
1207
2116
  },
1208
2117
  });
@@ -1211,68 +2120,126 @@ export class Host {
1211
2120
  channel: chatURI,
1212
2121
  action:
1213
2122
  kind === ResponsePartKind.Markdown
1214
- ? { type: ActionType.ChatDelta, turnId: rec.currentTurnId, partId, content: ev.delta }
1215
- : { type: ActionType.ChatReasoning, turnId: rec.currentTurnId, partId, content: ev.delta },
2123
+ ? { type: ActionType.ChatDelta, turnId: chat.currentTurnId, partId, content: ev.delta }
2124
+ : { type: ActionType.ChatReasoning, turnId: chat.currentTurnId, partId, content: ev.delta },
1216
2125
  });
1217
2126
  }
1218
2127
  return;
1219
2128
  }
1220
2129
  case "text.ended":
1221
2130
  case "reasoning.ended": {
1222
- if (rec.currentTurnId === null) return;
2131
+ if (chat.currentTurnId === null) return;
1223
2132
  // Fallback for non-streaming providers that emit only the final
1224
2133
  // text: if no delta opened the part, emit it now with the full text.
1225
2134
  const kind = ev.type === "text.ended" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
1226
2135
  const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
1227
- if (!rec.parts.has(key)) {
1228
- rec.parts.add(key);
2136
+ if (!chat.parts.has(key)) {
2137
+ chat.parts.add(key);
1229
2138
  this.publish({
1230
2139
  channel: chatURI,
1231
2140
  action: {
1232
2141
  type: ActionType.ChatResponsePart,
1233
- turnId: rec.currentTurnId,
2142
+ turnId: chat.currentTurnId,
1234
2143
  part: { kind, id: `part-${key}`, content: ev.text },
1235
2144
  },
1236
2145
  });
1237
2146
  }
1238
2147
  return;
1239
2148
  }
1240
- case "tool.input.started":
1241
- if (rec.currentTurnId === null) {
1242
- this.log(`tool.input.started outside a turn (session ${rec.sessionID}, tool ${ev.name}); ignored`);
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`);
1243
2152
  return;
1244
2153
  }
1245
- 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
+ }
1246
2165
  this.publish({
1247
2166
  channel: chatURI,
1248
2167
  action: {
1249
2168
  type: ActionType.ChatToolCallStart,
1250
- turnId: rec.currentTurnId,
2169
+ turnId: chat.currentTurnId,
1251
2170
  toolCallId: ev.id,
1252
2171
  toolName: ev.name,
1253
2172
  displayName: displayNameFor(ev.name),
2173
+ ...(clientTool !== null
2174
+ ? { contributor: { kind: ToolCallContributorKind.Client, clientId: clientTool } }
2175
+ : {}),
1254
2176
  },
1255
2177
  });
1256
2178
  return;
1257
- case "tool.input.ended":
1258
- rec.toolInput.set(ev.id, ev.text);
2179
+ }
2180
+ case "tool.input.ended": {
2181
+ chat.toolInput.set(ev.id, ev.text);
2182
+ // For file-mutating tools, capture the pre-edit file
2183
+ // content now (the event fires before execution — the last safe
2184
+ // point). Awaited in the sequential pump so the capture is
2185
+ // complete before `execution.*` can end the turn.
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
+ }
1259
2214
  return;
2215
+ }
1260
2216
  case "tool.progress":
1261
2217
  // First sign the tool is actually running (opencode auto-approved):
1262
2218
  // finalize the tool call as running.
1263
- this.ensureToolReady(rec, ev.id, false);
2219
+ this.ensureToolReady(chat, ev.id, false);
1264
2220
  return;
1265
2221
  case "tool.success": {
1266
- if (rec.currentTurnId === null) return;
1267
- this.ensureToolReady(rec, ev.id, false);
1268
- if (this.toolCallTerminal(rec, ev.id)) return; // e.g. denied → already cancelled
1269
- const name = rec.toolName.get(ev.id) ?? "tool";
1270
- const input = rec.toolInput.get(ev.id);
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);
1271
2238
  this.publish({
1272
2239
  channel: chatURI,
1273
2240
  action: {
1274
2241
  type: ActionType.ChatToolCallComplete,
1275
- turnId: rec.currentTurnId,
2242
+ turnId: chat.currentTurnId,
1276
2243
  toolCallId: ev.id,
1277
2244
  result: {
1278
2245
  success: true,
@@ -1281,20 +2248,26 @@ export class Host {
1281
2248
  },
1282
2249
  },
1283
2250
  });
1284
- this.clearToolTracking(rec, ev.id);
2251
+ this.clearToolTracking(chat, ev.id);
1285
2252
  return;
1286
2253
  }
1287
2254
  case "tool.failed": {
1288
- if (rec.currentTurnId === null) return;
1289
- this.ensureToolReady(rec, ev.id, false);
1290
- if (this.toolCallTerminal(rec, ev.id)) return;
1291
- const name = rec.toolName.get(ev.id) ?? "tool";
1292
- const input = rec.toolInput.get(ev.id);
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);
1293
2266
  this.publish({
1294
2267
  channel: chatURI,
1295
2268
  action: {
1296
2269
  type: ActionType.ChatToolCallComplete,
1297
- turnId: rec.currentTurnId,
2270
+ turnId: chat.currentTurnId,
1298
2271
  toolCallId: ev.id,
1299
2272
  result: {
1300
2273
  success: false,
@@ -1303,45 +2276,45 @@ export class Host {
1303
2276
  },
1304
2277
  },
1305
2278
  });
1306
- this.clearToolTracking(rec, ev.id);
2279
+ this.clearToolTracking(chat, ev.id);
1307
2280
  return;
1308
2281
  }
1309
2282
  case "usage.updated":
1310
2283
  // Session-cumulative tokens; the chat reducer replaces the turn's
1311
2284
  // usage, so the latest cumulative values are the turn's view.
1312
- if (rec.currentTurnId === null) return;
2285
+ if (chat.currentTurnId === null) return;
1313
2286
  this.publish({
1314
2287
  channel: chatURI,
1315
2288
  action: {
1316
2289
  type: ActionType.ChatUsage,
1317
- turnId: rec.currentTurnId,
2290
+ turnId: chat.currentTurnId,
1318
2291
  usage: {
1319
2292
  inputTokens: ev.tokens.input,
1320
2293
  outputTokens: ev.tokens.output,
1321
2294
  cacheReadTokens: ev.tokens.cache.read,
1322
- ...(rec.turnModelRef !== null ? { model: rec.turnModelRef } : {}),
2295
+ ...(chat.turnModelRef !== null ? { model: chat.turnModelRef } : {}),
1323
2296
  },
1324
2297
  },
1325
2298
  });
1326
2299
  return;
1327
2300
  case "permission.asked":
1328
2301
  // Only tool-sourced permissions map to a tool confirmation;
1329
- // anything else has no AHP counterpart in this MVP (gap).
2302
+ // anything else has no AHP counterpart (gap).
1330
2303
  if (ev.source === undefined) {
1331
2304
  this.log(`ignoring non-tool permission.asked ${ev.id} (action: ${ev.action})`);
1332
2305
  return;
1333
2306
  }
1334
2307
  const toolCallId = ev.source.id;
1335
- rec.permissionForTool.set(toolCallId, ev.id);
1336
- rec.toolForPermission.set(ev.id, toolCallId);
1337
- this.ensureToolReady(rec, toolCallId, true);
1338
- const pending = this.pendingToolCall(rec, toolCallId);
1339
- if (pending !== null && rec.currentTurnId !== null) {
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) {
1340
2313
  const request: SessionToolConfirmationRequest = {
1341
2314
  id: toolCallId,
1342
2315
  chat: chatURI,
1343
2316
  kind: SessionInputRequestKind.ToolConfirmation,
1344
- turnId: rec.currentTurnId,
2317
+ turnId: chat.currentTurnId,
1345
2318
  toolCall: pending,
1346
2319
  };
1347
2320
  this.publish({
@@ -1351,10 +2324,10 @@ export class Host {
1351
2324
  }
1352
2325
  return;
1353
2326
  case "permission.replied": {
1354
- const toolCallId = rec.toolForPermission.get(ev.requestID);
1355
- rec.toolForPermission.delete(ev.requestID);
2327
+ const toolCallId = chat.toolForPermission.get(ev.requestID);
2328
+ chat.toolForPermission.delete(ev.requestID);
1356
2329
  if (toolCallId !== undefined) {
1357
- rec.permissionForTool.delete(toolCallId);
2330
+ chat.permissionForTool.delete(toolCallId);
1358
2331
  // Safety net: the client's `chat/toolCallConfirmed` normally
1359
2332
  // removes the input request first; this covers the reply
1360
2333
  // arriving without (or before) the echo.
@@ -1377,17 +2350,17 @@ export class Host {
1377
2350
  return `turn_${Date.now().toString(36)}_${this.turnCounter.toString(36)}`;
1378
2351
  }
1379
2352
 
1380
- private turnDuration(rec: SessionRecord): number {
1381
- 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()));
1382
2355
  }
1383
2356
 
1384
2357
  /** Claim a turn (write-ahead) and publish `chat/turnStarted`. */
1385
- private startTurn(rec: SessionRecord, message: Message, queuedMessageId?: string): void {
2358
+ private startTurn(chat: ChatRuntime, message: Message, queuedMessageId?: string): void {
1386
2359
  const turnId = this.mintTurnId();
1387
- rec.currentTurnId = turnId;
1388
- rec.turnStartedAt = Date.now();
2360
+ chat.currentTurnId = turnId;
2361
+ chat.turnStartedAt = Date.now();
1389
2362
  this.publish({
1390
- channel: chatChannelURI(rec.sessionID),
2363
+ channel: chat.uri,
1391
2364
  action: {
1392
2365
  type: ActionType.ChatTurnStarted,
1393
2366
  turnId,
@@ -1403,14 +2376,19 @@ export class Host {
1403
2376
  * during the turn, and auto-start the next turn from the queue (the
1404
2377
  * queued prompt was already sent with `delivery: "queue"` — opencode
1405
2378
  * starts it automatically; this only updates the AHP state).
2379
+ *
2380
+ * Then refresh the session's changesets — the turn's captured
2381
+ * "after" content is read from disk here, and the uncommitted/session/
2382
+ * turn changesets recompute (async: awaits the facade).
1406
2383
  */
1407
- private finishTurn(rec: SessionRecord): void {
1408
- rec.currentTurnId = null;
1409
- rec.turnStartedAt = null;
1410
- 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;
1411
2389
  if (state.steeringMessage !== undefined) {
1412
2390
  this.publish({
1413
- channel: chatChannelURI(rec.sessionID),
2391
+ channel: chat.uri,
1414
2392
  action: {
1415
2393
  type: ActionType.ChatPendingMessageRemoved,
1416
2394
  kind: PendingMessageKind.Steering,
@@ -1421,10 +2399,575 @@ export class Host {
1421
2399
  const queued = state.queuedMessages;
1422
2400
  if (queued !== undefined && queued.length > 0) {
1423
2401
  const next = queued[0]!;
1424
- this.startTurn(rec, next.message, next.id);
1425
- } 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") {
1426
2404
  // A queued prompt from outside AHP (e.g. the TUI).
1427
- 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();
2413
+ }
2414
+ if (this.opts.changesets && endedTurnId !== null) {
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;
2567
+ }
2568
+ if (changed) this.refreshTerminals();
2569
+ }
2570
+
2571
+ // ── changesets ────────────────────────────────────────────────
2572
+
2573
+ /**
2574
+ * Capture the pre-edit content of a file-mutating tool's target file for
2575
+ * the current turn's changeset (first capture per file wins — the
2576
+ * pre-turn content survives later edits in the same turn). No-op when
2577
+ * the tool is not file-mutating, the input carries no parseable path,
2578
+ * or the path resolves outside the location directory.
2579
+ */
2580
+ private async captureTurnBefore(chat: ChatRuntime, toolCallId: string, inputJson: string): Promise<void> {
2581
+ const turnId = chat.currentTurnId;
2582
+ const toolName = chat.toolName.get(toolCallId);
2583
+ if (turnId === null || toolName === undefined || !SNAPSHOT_TOOLS.has(toolName)) return;
2584
+ let parsed: unknown;
2585
+ try {
2586
+ parsed = JSON.parse(inputJson);
2587
+ } catch {
2588
+ return;
2589
+ }
2590
+ if (!isRecord(parsed)) return;
2591
+ const rawPath = SNAPSHOT_PATH_KEYS.map((k) => parsed[k]).find((v) => typeof v === "string" && (v as string).length > 0);
2592
+ if (typeof rawPath !== "string") return;
2593
+ const absPath = this.resolveSnapshotPath(rawPath);
2594
+ if (absPath === null) {
2595
+ this.log(`turn snapshot: ${toolName} target ${rawPath} is outside the location directory; not captured`);
2596
+ return;
2597
+ }
2598
+ let before: string | null;
2599
+ try {
2600
+ before = await this.opts.facade.readFile(absPath);
2601
+ } catch (err) {
2602
+ this.log(`turn snapshot: read of ${absPath} failed: ${errorMessage(err)}`);
2603
+ return;
2604
+ }
2605
+ // The pump is sequential, so the turn cannot have ended between the
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();
2610
+ if (!turnFiles.has(absPath)) turnFiles.set(absPath, { before, after: null });
2611
+ chat.turnSnapshots.set(turnId, turnFiles);
2612
+ }
2613
+
2614
+ /** Resolve a tool-input path against the location directory (must stay inside it). */
2615
+ private resolveSnapshotPath(rawPath: string): string | null {
2616
+ const dir = this.opts.defaultDirectory;
2617
+ if (dir === undefined) return null;
2618
+ const absPath = resolvePath(dir, rawPath);
2619
+ return isPathInside(absPath, dir) ? absPath : null;
2620
+ }
2621
+
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);
2646
+ if (store === undefined) {
2647
+ store = createChangesetStateStore({ status: ChangesetStatus.Computing, files: [] });
2648
+ map.set(uri, store);
2649
+ }
2650
+ return store;
2651
+ }
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
+
2661
+ /** The store's current per-file review flags, keyed by file id. */
2662
+ private reviewedById(store: ChangesetStateStore): Map<string, boolean> {
2663
+ const out = new Map<string, boolean>();
2664
+ for (const f of store.state.files) {
2665
+ if (typeof f.reviewed === "boolean") out.set(f.id, f.reviewed);
2666
+ }
2667
+ return out;
2668
+ }
2669
+
2670
+ /**
2671
+ * Recompute one changeset and publish the delta (gateway's
2672
+ * `updateChangesetChannel` pattern): `changeset/contentChanged` when the
2673
+ * file list changed (the discard operation is (re)attached while files
2674
+ * exist, and cleared when they vanish), then `changeset/statusChanged`
2675
+ * to ready when the status was not ready. A failed computation publishes
2676
+ * `changeset/statusChanged` with an error.
2677
+ */
2678
+ private async refreshChangeset(rec: SessionRecord, uri: string): Promise<void> {
2679
+ const parsed = parseChangesetChannel(uri);
2680
+ if (parsed === null) return;
2681
+ const store = this.changesetStore(rec, uri);
2682
+ if (store === null) return; // owner gone (disposed chat)
2683
+ let files;
2684
+ try {
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;
2690
+ files = buildTurnChangesetFiles({
2691
+ sessionID: chat.sessionID,
2692
+ turnId: parsed.turnId ?? "",
2693
+ files: chat.turnSnapshots.get(parsed.turnId ?? "") ?? new Map(),
2694
+ reviewedById: this.reviewedById(store),
2695
+ });
2696
+ } else {
2697
+ const diffs = await this.opts.facade.vcsDiffWorking();
2698
+ files = buildWorkingChangesetFiles({ diffs, reviewedById: this.reviewedById(store) });
2699
+ }
2700
+ } catch (err) {
2701
+ this.publish({
2702
+ channel: uri,
2703
+ action: {
2704
+ type: ActionType.ChangesetStatusChanged,
2705
+ status: ChangesetStatus.Error,
2706
+ error: { errorType: "changeset-computation", message: errorMessage(err) },
2707
+ },
2708
+ });
2709
+ return;
2710
+ }
2711
+ const state = store.state;
2712
+ const hadFiles = state.files.length > 0;
2713
+ const hasFiles = files.length > 0;
2714
+ if (JSON.stringify(state.files) !== JSON.stringify(files)) {
2715
+ this.publish({
2716
+ channel: uri,
2717
+ action: {
2718
+ type: ActionType.ChangesetContentChanged,
2719
+ files,
2720
+ ...(hasFiles ? { operations: [discardOperation()] } : {}),
2721
+ },
2722
+ });
2723
+ // operations persist across contentChanged — clear them explicitly
2724
+ // when the changeset empties out.
2725
+ if (!hasFiles && state.operations !== undefined && state.operations.length > 0) {
2726
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: undefined } });
2727
+ }
2728
+ }
2729
+ if (!hadFiles && hasFiles && state.operations === undefined) {
2730
+ // contentChanged above already attached the operation; this branch
2731
+ // is unreachable unless the reducer drops it — kept as a guard.
2732
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: [discardOperation()] } });
2733
+ }
2734
+ if (state.status !== ChangesetStatus.Ready) {
2735
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetStatusChanged, status: ChangesetStatus.Ready } });
2736
+ }
2737
+ }
2738
+
2739
+ /**
2740
+ * At a turn terminal: read the disk into each captured file's `after`
2741
+ * (a file deleted during the turn stays null → "deleted"), then refresh
2742
+ * the uncommitted, session, and ended-turn changesets — only the ones a
2743
+ * client has subscribed (unsubscribed changesets cost no seq).
2744
+ */
2745
+ private async refreshTurnChangesets(rec: SessionRecord, chat: ChatRuntime, turnId: string): Promise<void> {
2746
+ const turnFiles = chat.turnSnapshots.get(turnId);
2747
+ if (turnFiles !== undefined) {
2748
+ for (const [absPath, snap] of turnFiles) {
2749
+ if (snap.after === null) {
2750
+ try {
2751
+ snap.after = await this.opts.facade.readFile(absPath);
2752
+ } catch {
2753
+ snap.after = null;
2754
+ }
2755
+ }
2756
+ }
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.
2760
+ for (const uri of [
2761
+ uncommittedChangesetURI(chat.uri),
2762
+ sessionChangesetURI(rec.channel),
2763
+ turnChangesetURI(chat.uri, turnId),
2764
+ ]) {
2765
+ if (this.changesetStoreOf(rec, uri) !== undefined) await this.refreshChangeset(rec, uri);
2766
+ }
2767
+ }
2768
+
2769
+ /**
2770
+ * `resourceRead` (AHP root command): serve file content for the URIs
2771
+ * this host advertises in changesets —
2772
+ * - `file://` → live disk, confined to the location directory;
2773
+ * - `ahp-content://head/…` → the file's HEAD content;
2774
+ * - `ahp-content://snap/…` → a turn's captured before/after content.
2775
+ * Errors: -32008 (not found), -32009 (path outside the location).
2776
+ */
2777
+ private async handleResourceRead(socketId: number, msg: RpcMessage): Promise<void> {
2778
+ const params = isRecord(msg.params) ? msg.params : {};
2779
+ const uri = params["uri"];
2780
+ if (typeof uri !== "string" || uri.length === 0) {
2781
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resourceRead requires a content URI");
2782
+ return;
2783
+ }
2784
+ const encoding: "base64" | "utf-8" = params["encoding"] === "utf-8" ? "utf-8" : "base64";
2785
+ if (uri.startsWith("file://")) {
2786
+ let absPath: string;
2787
+ try {
2788
+ absPath = fileURLToPath(uri);
2789
+ } catch {
2790
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
2791
+ return;
2792
+ }
2793
+ if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
2794
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
2795
+ return;
2796
+ }
2797
+ let content: string | null;
2798
+ try {
2799
+ content = await this.opts.facade.readFile(absPath);
2800
+ } catch (err) {
2801
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, `read failed: ${errorMessage(err)}`);
2802
+ return;
2803
+ }
2804
+ if (content === null) {
2805
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
2806
+ return;
2807
+ }
2808
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
2809
+ return;
2810
+ }
2811
+ // Opaque content refs require the changesets capability.
2812
+ if (!this.opts.changesets) {
2813
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
2814
+ return;
2815
+ }
2816
+ const ref = parseContentRef(uri);
2817
+ if (ref === null) {
2818
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
2819
+ return;
2820
+ }
2821
+ if (ref.kind === "head") {
2822
+ if (this.opts.defaultDirectory !== undefined && !isPathInside(ref.path, this.opts.defaultDirectory)) {
2823
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
2824
+ return;
2825
+ }
2826
+ let content: string | null;
2827
+ try {
2828
+ content = await this.opts.facade.gitHeadFile(ref.path);
2829
+ } catch (err) {
2830
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, `HEAD read failed: ${errorMessage(err)}`);
2831
+ return;
2832
+ }
2833
+ if (content === null) {
2834
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not in HEAD: ${ref.path}`);
2835
+ return;
2836
+ }
2837
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
2838
+ return;
2839
+ }
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) {
2843
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, "no such session");
2844
+ return;
2845
+ }
2846
+ const snap = binding.chat.turnSnapshots.get(ref.turnId)?.get(ref.path);
2847
+ const content = snap === undefined ? null : ref.part === "before" ? snap.before : snap.after;
2848
+ if (content === null) {
2849
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
2850
+ return;
2851
+ }
2852
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
2853
+ }
2854
+
2855
+ /** Encode content for a `resourceRead` result (utf-8 or base64). */
2856
+ private encodeContent(content: string, encoding: "base64" | "utf-8") {
2857
+ return {
2858
+ data: encoding === "utf-8" ? content : Buffer.from(content, "utf-8").toString("base64"),
2859
+ encoding,
2860
+ };
2861
+ }
2862
+
2863
+ /**
2864
+ * `invokeChangesetOperation`: the host's only operation is
2865
+ * `discard-changes` (resource-scoped) — restore one file from the
2866
+ * changeset's "before" content. Status flows through the
2867
+ * `changeset/operationStatusChanged` stream; the JSON-RPC result carries
2868
+ * a human-readable message.
2869
+ */
2870
+ private async handleInvokeChangesetOperation(socketId: number, msg: RpcMessage): Promise<void> {
2871
+ const params = isRecord(msg.params) ? msg.params : {};
2872
+ const channel = params["channel"];
2873
+ const operationId = params["operationId"];
2874
+ if (typeof channel !== "string" || channel.length === 0 || typeof operationId !== "string" || operationId.length === 0) {
2875
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "invokeChangesetOperation requires channel + operationId");
2876
+ return;
2877
+ }
2878
+ const parsed = parseChangesetChannel(channel);
2879
+ if (parsed === null) {
2880
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `not a changeset channel: ${channel}`);
2881
+ return;
2882
+ }
2883
+ const rec = this.byChannel.get(parsed.ownerUri);
2884
+ if (rec === undefined) {
2885
+ this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, "no such session");
2886
+ return;
2887
+ }
2888
+ const store = this.changesetStoreOf(rec, channel);
2889
+ if (store === undefined) {
2890
+ this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such changeset: ${channel}`);
2891
+ return;
2892
+ }
2893
+ const op = store.state.operations?.find((o) => o.id === operationId);
2894
+ if (op === undefined) {
2895
+ this.sendError(socketId, msg.id, ERROR_METHOD_NOT_FOUND, `unknown operation: ${operationId}`);
2896
+ return;
2897
+ }
2898
+ if (!op.scopes.includes(ChangesetOperationScope.Resource)) {
2899
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `operation ${operationId} is not resource-scoped`);
2900
+ return;
2901
+ }
2902
+ const target = params["target"];
2903
+ if (!isRecord(target) || target["kind"] !== "resource" || typeof target["resource"] !== "string") {
2904
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resource-scoped operation requires a resource target");
2905
+ return;
2906
+ }
2907
+ let absPath: string;
2908
+ try {
2909
+ absPath = fileURLToPath(target["resource"] as string);
2910
+ } catch {
2911
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "target.resource must be a file URI");
2912
+ return;
2913
+ }
2914
+ if (!store.state.files.some((f) => f.id === fileUri(absPath))) {
2915
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `no such file in changeset: ${target["resource"]}`);
2916
+ return;
2917
+ }
2918
+ if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
2919
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
2920
+ return;
2921
+ }
2922
+ this.publish({
2923
+ channel,
2924
+ action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Running },
2925
+ });
2926
+ try {
2927
+ if (parsed.kind === "turn" && parsed.turnId !== undefined) {
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);
2931
+ } else {
2932
+ await this.opts.facade.discardFile(absPath);
2933
+ }
2934
+ } catch (err) {
2935
+ this.publish({
2936
+ channel,
2937
+ action: {
2938
+ type: ActionType.ChangesetOperationStatusChanged,
2939
+ operationId,
2940
+ status: ChangesetOperationStatus.Error,
2941
+ error: { errorType: "operation-failed", message: errorMessage(err) },
2942
+ },
2943
+ });
2944
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, errorMessage(err));
2945
+ return;
2946
+ }
2947
+ await this.refreshChangeset(rec, channel);
2948
+ this.publish({
2949
+ channel,
2950
+ action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Idle },
2951
+ });
2952
+ this.sendFrame(socketId, {
2953
+ jsonrpc: "2.0",
2954
+ id: msg.id ?? null,
2955
+ result: { message: `Discarded changes to ${absPath}` },
2956
+ });
2957
+ }
2958
+
2959
+ /**
2960
+ * Restore one file from a turn's before-snapshot: the file was added by
2961
+ * the turn (before === null) → delete it; otherwise write the pre-edit
2962
+ * content back.
2963
+ */
2964
+ private async restoreTurnFile(chat: ChatRuntime, turnId: string, absPath: string): Promise<void> {
2965
+ const snap = chat.turnSnapshots.get(turnId)?.get(absPath);
2966
+ const before = snap?.before ?? null;
2967
+ if (before === null) {
2968
+ await this.opts.facade.deleteFile(absPath);
2969
+ } else {
2970
+ await this.opts.facade.writeFile(absPath, before);
1428
2971
  }
1429
2972
  }
1430
2973
 
@@ -1436,16 +2979,16 @@ export class Host {
1436
2979
  * - otherwise → `confirmed: "not-needed"` → straight to `running`
1437
2980
  * (opencode auto-approved).
1438
2981
  */
1439
- private ensureToolReady(rec: SessionRecord, toolCallId: string, permission: boolean): void {
1440
- if (rec.toolReady.has(toolCallId) || rec.currentTurnId === null) return;
1441
- rec.toolReady.add(toolCallId);
1442
- const name = rec.toolName.get(toolCallId) ?? "tool";
1443
- const input = rec.toolInput.get(toolCallId);
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);
1444
2987
  this.publish({
1445
- channel: chatChannelURI(rec.sessionID),
2988
+ channel: chat.uri,
1446
2989
  action: {
1447
2990
  type: ActionType.ChatToolCallReady,
1448
- turnId: rec.currentTurnId,
2991
+ turnId: chat.currentTurnId,
1449
2992
  toolCallId,
1450
2993
  invocationMessage: invocationMessageFor(name, input),
1451
2994
  toolInput: input,
@@ -1454,9 +2997,9 @@ export class Host {
1454
2997
  });
1455
2998
  }
1456
2999
 
1457
- /** The live tool-call state in the current turn, or null when absent. */
1458
- private toolCallState(rec: SessionRecord, toolCallId: string): ToolCallState | null {
1459
- const turn = rec.chatStore.state.activeTurn;
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;
1460
3003
  if (turn === undefined) return null;
1461
3004
  for (const part of turn.responseParts) {
1462
3005
  if (part.kind === ResponsePartKind.ToolCall && part.toolCall.toolCallId === toolCallId) {
@@ -1470,8 +3013,8 @@ export class Host {
1470
3013
  * The tool call's state when it is awaiting confirmation (the
1471
3014
  * `SessionToolConfirmationRequest.toolCall` shape), or null otherwise.
1472
3015
  */
1473
- private pendingToolCall(rec: SessionRecord, toolCallId: string): ToolCallConfirmationState | null {
1474
- const tc = this.toolCallState(rec, toolCallId);
3016
+ private pendingToolCall(chat: ChatRuntime, toolCallId: string): ToolCallConfirmationState | null {
3017
+ const tc = this.toolCallState(chat, toolCallId);
1475
3018
  if (tc === null) return null;
1476
3019
  if (tc.status === ToolCallStatus.PendingConfirmation || tc.status === ToolCallStatus.PendingResultConfirmation) {
1477
3020
  return tc;
@@ -1480,15 +3023,146 @@ export class Host {
1480
3023
  }
1481
3024
 
1482
3025
  /** True when the tool call already left the ready states (completed/cancelled). */
1483
- private toolCallTerminal(rec: SessionRecord, toolCallId: string): boolean {
1484
- const tc = this.toolCallState(rec, toolCallId);
3026
+ private toolCallTerminal(chat: ChatRuntime, toolCallId: string): boolean {
3027
+ const tc = this.toolCallState(chat, toolCallId);
1485
3028
  return tc !== null && (tc.status === ToolCallStatus.Completed || tc.status === ToolCallStatus.Cancelled);
1486
3029
  }
1487
3030
 
1488
- private clearToolTracking(rec: SessionRecord, toolCallId: string): void {
1489
- rec.toolInput.delete(toolCallId);
1490
- rec.toolName.delete(toolCallId);
1491
- 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
+ });
1492
3166
  }
1493
3167
 
1494
3168
  // ── session registration / removal ─────────────────────────────────────
@@ -1500,27 +3174,185 @@ export class Host {
1500
3174
  * is gone, already registered, or a createSession remap is pending.
1501
3175
  */
1502
3176
  private async registerExternalDeferred(sessionID: string): Promise<void> {
1503
- if (this.sessions.has(sessionID)) return;
3177
+ if (this.sessions.has(sessionID) || this.byOpencode.has(sessionID)) return;
1504
3178
  let fs: FacadeSession | null;
1505
3179
  try {
1506
3180
  fs = await this.opts.facade.getSession(sessionID);
1507
3181
  } catch {
1508
3182
  return;
1509
3183
  }
1510
- if (fs === null || this.sessions.has(fs.sessionID)) return;
3184
+ if (fs === null || this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) return;
1511
3185
  this.registerExternal(fs);
1512
3186
  }
1513
3187
 
1514
3188
  /**
1515
3189
  * Register an opencode session the host did not create (TUI, another
1516
- * client). Applied directly to the fresh stores (no seq, no actions) —
1517
- * the registration is server-side bookkeeping, not a client-visible
1518
- * state transition; the root announcement carries the lifecycle.
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).
1519
3207
  */
1520
3208
  private registerExternal(fs: FacadeSession): SessionRecord | undefined {
1521
3209
  const existing = this.sessions.get(fs.sessionID);
1522
3210
  if (existing !== undefined) return existing;
1523
- 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);
1524
3356
  const modifiedAt = new Date(fs.time.updated).toISOString();
1525
3357
  const sessionStore = createSessionStateStore(
1526
3358
  initialSessionState({
@@ -1532,35 +3364,43 @@ export class Host {
1532
3364
  : undefined, // Idle | IsRead | IsArchived
1533
3365
  }),
1534
3366
  );
1535
- const chatStore = createChatStateStore(
1536
- initialChatState({ resource: chatChannelURI(fs.sessionID), title: "Chat 1", modifiedAt }),
1537
- );
1538
- sessionStore.apply({ type: ActionType.SessionReady });
1539
- sessionStore.apply({ type: ActionType.SessionChatAdded, summary: chatSummaryOf(chatStore.state) });
1540
- sessionStore.apply({ type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(fs.sessionID) });
1541
3367
  const rec: SessionRecord = {
1542
3368
  sessionID: fs.sessionID,
1543
- channel,
3369
+ channel: recChannel,
1544
3370
  provider: sessionStore.state.provider,
1545
3371
  createdAt: new Date(fs.time.created).toISOString(),
1546
3372
  modifiedAt,
1547
3373
  sessionStore,
1548
- chatStore,
1549
- currentTurnId: null,
1550
- turnStartedAt: null,
1551
- turnModelRef: null,
1552
- parts: new Set(),
1553
- toolInput: new Map(),
1554
- toolName: new Map(),
1555
- toolReady: new Set(),
1556
- permissionForTool: new Map(),
1557
- toolForPermission: new Map(),
1558
- lastInbox: null,
3374
+ chats: new Map(),
3375
+ defaultChatURI: chatChannelURI(fs.sessionID),
3376
+ sessionChangesets: new Map(),
1559
3377
  };
1560
3378
  this.sessions.set(fs.sessionID, rec);
1561
- this.byChannel.set(channel, rec);
1562
- this.byChannel.set(chatChannelURI(fs.sessionID), rec);
1563
- this.channels.addSession(fs.sessionID);
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);
1564
3404
  this.publish({
1565
3405
  channel: ROOT_CHANNEL,
1566
3406
  action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
@@ -1571,9 +3411,34 @@ export class Host {
1571
3411
 
1572
3412
  /** Drop a session record and announce the removal on the root channel. */
1573
3413
  private removeRecord(rec: SessionRecord): void {
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()) {
3429
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetCleared } });
3430
+ }
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
+ }
1574
3440
  this.sessions.delete(rec.sessionID);
1575
3441
  this.byChannel.delete(rec.channel);
1576
- this.byChannel.delete(chatChannelURI(rec.sessionID));
1577
3442
  const id = sessionIDOf(rec.channel);
1578
3443
  if (id !== null) this.channels.removeSession(id);
1579
3444
  this.channels.removeSession(rec.sessionID);
@@ -1582,6 +3447,11 @@ export class Host {
1582
3447
  action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
1583
3448
  });
1584
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();
1585
3455
  }
1586
3456
 
1587
3457
  // ── state / publishing ─────────────────────────────────────────────────
@@ -1597,14 +3467,38 @@ export class Host {
1597
3467
  private async snapshotFor(uri: string): Promise<Snapshot | null> {
1598
3468
  const kind = channelKind(uri);
1599
3469
  if (kind === "unknown") return null;
3470
+ if (kind === "changeset") {
3471
+ if (!this.opts.changesets) return null;
3472
+ const parsed = parseChangesetChannel(uri);
3473
+ if (parsed === null) return null;
3474
+ // The owner is the session/chat channel (owner-aware).
3475
+ const rec = this.byChannel.get(parsed.ownerUri);
3476
+ if (rec === undefined) return null;
3477
+ const store = this.changesetStore(rec, uri);
3478
+ if (store === null) return null; // owner gone (disposed chat)
3479
+ // First subscribe (or a failed computation) triggers the computation;
3480
+ // subsequent subscribes return the last completed state.
3481
+ if (store.state.status === ChangesetStatus.Computing || store.state.status === ChangesetStatus.Error) {
3482
+ await this.refreshChangeset(rec, uri);
3483
+ }
3484
+ return { resource: uri, state: store.state, fromSeq: this.seq.seq };
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
+ }
1600
3493
  if (kind !== "root") {
1601
3494
  const rec = this.byChannel.get(uri);
1602
3495
  if (rec === undefined) return null;
1603
3496
  if (uri === rec.channel) {
1604
3497
  return { resource: uri, state: rec.sessionStore.state, fromSeq: this.seq.seq };
1605
3498
  }
1606
- if (uri === chatChannelURI(rec.sessionID)) {
1607
- 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 };
1608
3502
  }
1609
3503
  return null;
1610
3504
  }
@@ -1622,8 +3516,13 @@ export class Host {
1622
3516
  /** The denormalized `SessionSummary` view of a record. */
1623
3517
  private sessionSummary(rec: SessionRecord): SessionSummary {
1624
3518
  const s = rec.sessionStore.state;
1625
- const c = rec.chatStore.state;
1626
- 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
+ }
1627
3526
  return buildSessionSummary({
1628
3527
  channel: rec.channel,
1629
3528
  provider: rec.provider,
@@ -1632,8 +3531,8 @@ export class Host {
1632
3531
  activity: s.activity,
1633
3532
  createdAt: rec.createdAt,
1634
3533
  modifiedAt,
1635
- chat: chatSummaryOf(c),
1636
- defaultChat: chatChannelURI(rec.sessionID),
3534
+ chats,
3535
+ defaultChat: rec.defaultChatURI,
1637
3536
  });
1638
3537
  }
1639
3538
 
@@ -1655,15 +3554,35 @@ export class Host {
1655
3554
  const kind = channelKind(draft.channel);
1656
3555
  if (kind === "root") {
1657
3556
  this.state.apply(draft.action as RootAction);
3557
+ } else if (kind === "changeset") {
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.
3562
+ const parsed = parseChangesetChannel(draft.channel);
3563
+ const rec = parsed !== null ? this.byChannel.get(parsed.ownerUri) : undefined;
3564
+ const store = rec !== undefined ? this.changesetStoreOf(rec, draft.channel) : undefined;
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);
1658
3573
  } else {
1659
3574
  // byChannel, not sessions.get(sessionIDOf(…)): the channel suffix
1660
3575
  // is not always the opencode session id (client-chosen suffixes).
1661
3576
  const rec = this.byChannel.get(draft.channel);
1662
3577
  if (rec !== undefined) {
1663
3578
  const before = this.sessionSummary(rec);
1664
- if (kind === "session") rec.sessionStore.apply(draft.action as SessionAction);
1665
- else rec.chatStore.apply(draft.action as ChatAction);
1666
- if (kind === "chat") this.syncChatSummary(rec);
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);
1667
3586
  const after = this.sessionSummary(rec);
1668
3587
  this.maybeNotifySummaryChanged(rec, before, after);
1669
3588
  }
@@ -1681,8 +3600,9 @@ export class Host {
1681
3600
  * reducer-reachable for read/archive/input-needed bits, so the chat
1682
3601
  * summary is the activity source of truth.
1683
3602
  */
1684
- private syncChatSummary(rec: SessionRecord): void {
1685
- 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;
1686
3606
  const entry = rec.sessionStore.state.chats.find((c) => c.resource === chat.resource);
1687
3607
  if (entry === undefined) return;
1688
3608
  const next = chatSummaryOf(chat);
@@ -1771,17 +3691,73 @@ function firstEnabledModelRef(models: readonly { providerID: string; modelID: st
1771
3691
 
1772
3692
  /** Normalize an untrusted `activeClient` payload (untrusted JSON-RPC). */
1773
3693
  function normalizeActiveClient(ac: Record<string, unknown>): SessionActiveClient {
1774
- const tools = Array.isArray(ac["tools"]) ? (ac["tools"] as ToolDefinition[]) : [];
1775
3694
  return {
1776
3695
  clientId: ac["clientId"] as string,
1777
- tools,
3696
+ tools: normalizeToolDefinitions(ac["tools"]),
1778
3697
  ...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
1779
3698
  };
1780
3699
  }
1781
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
+
1782
3758
  /**
1783
3759
  * Map opencode tool result content blocks to AHP `ToolResultContent`
1784
- * (only text blocks are representable in this MVP; file/patch text is
3760
+ * (only text blocks are representable; file/patch text is
1785
3761
  * carried as text).
1786
3762
  */
1787
3763
  function mapToolResultContent(content: readonly { type: string; text?: string }[]): ToolResultContent[] {
@@ -1793,3 +3769,15 @@ function mapToolResultContent(content: readonly { type: string; text?: string }[
1793
3769
  }
1794
3770
  return out;
1795
3771
  }
3772
+
3773
+ /**
3774
+ * True when `child` is `parent` itself or strictly inside it (both resolved
3775
+ * first, so relative segments and `..` cannot escape the comparison). Used
3776
+ * to confine turn-snapshot paths and `resourceRead`/`invokeChangesetOperation`
3777
+ * targets to the location directory.
3778
+ */
3779
+ function isPathInside(child: string, parent: string): boolean {
3780
+ const a = resolvePath(child);
3781
+ const b = resolvePath(parent);
3782
+ return a === b || a.startsWith(b + "/");
3783
+ }