opencode-ahp 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,2313 +17,38 @@
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.
39
+ *
40
+ * Module layout: this file only composes the host — the section classes
41
+ * (host-base.ts → host-changesets.ts → host-terminals.ts → host-turns.ts →
42
+ * host-client-tools.ts → host-chats.ts → host-sessions.ts → host-dispatch.ts →
43
+ * host-events.ts → host-rpc.ts) form a linear chain, each extending the
44
+ * previous one; shared state lives in HostBase, and a section may only
45
+ * call members declared at or below it in the chain (that is what keeps
46
+ * the split type-safe).
37
47
  */
38
- import { resolve as resolvePath } from "node:path";
39
- import { fileURLToPath } from "node:url";
40
- import {
41
- ActionType,
42
- ChangesetOperationScope,
43
- ChangesetOperationStatus,
44
- ChangesetStatus,
45
- PendingMessageKind,
46
- ReconnectResultType,
47
- ResponsePartKind,
48
- SessionInputRequestKind,
49
- SessionStatus,
50
- ToolCallConfirmationReason,
51
- ToolCallStatus,
52
- ToolResultContentType,
53
- isClientDispatchable,
54
- type ActionEnvelope,
55
- type ActionOrigin,
56
- type ChatAction,
57
- type ChatSummary,
58
- type ChatState,
59
- type ChatToolCallConfirmedAction,
60
- type ChatTurnCancelledAction,
61
- type ChatTurnStartedAction,
62
- type ChangesetAction,
63
- type ChangesetFilesReviewChangedAction,
64
- type ErrorResponsePart,
65
- type Implementation,
66
- type Message,
67
- type ReconnectResult,
68
- type RootAction,
69
- type SessionAction,
70
- type SessionActiveClient,
71
- type SessionState,
72
- type SessionSummary,
73
- type SessionToolConfirmationRequest,
74
- type Snapshot,
75
- type StateAction,
76
- type ToolCallConfirmationState,
77
- type ToolCallState,
78
- type ToolDefinition,
79
- type ToolResultContent,
80
- } from "@microsoft/agent-host-protocol";
81
- import {
82
- agentDirectoryCustomization,
83
- agentIDFromUri,
84
- buildSessionSummary,
85
- buildTurnChangesetFiles,
86
- buildWorkingChangesetFiles,
87
- chatChangesetCatalog,
88
- chatSummaryOf,
89
- displayNameFor,
90
- discardOperation,
91
- fileUri,
92
- initialChatState,
93
- initialSessionState,
94
- invocationMessageFor,
95
- mapCatalog,
96
- mapAgentCustomizations,
97
- parseContentRef,
98
- pastTenseMessageFor,
99
- sessionChangesetCatalog,
100
- userMessage,
101
- type FacadeDelivery,
102
- type FacadeEvent,
103
- type FacadeModelRef,
104
- type FacadeSession,
105
- type OpencodeFacade,
106
- } from "./bridge.js";
107
- import {
108
- ChannelRegistry,
109
- ROOT_CHANNEL,
110
- channelKind,
111
- chatChannelURI,
112
- parseChangesetChannel,
113
- sessionChannelURI,
114
- sessionChangesetURI,
115
- sessionIDOf,
116
- turnChangesetURI,
117
- uncommittedChangesetURI,
118
- } from "./channels.js";
119
- import { ERROR_INVALID_PARAMS, handleInitialize } from "./handshake.js";
120
- import { isRecord } from "./options.js";
121
- import { Sequencer } from "./seq.js";
122
- import {
123
- createChatStateStore,
124
- createChangesetStateStore,
125
- createRootStateStore,
126
- createSessionStateStore,
127
- type ChatStateStore,
128
- type ChangesetStateStore,
129
- type RootStateStore,
130
- type SessionStateStore,
131
- } from "./state.js";
132
-
133
- export const ERROR_PARSE = -32700;
134
- export const ERROR_INVALID_REQUEST = -32600;
135
- export const ERROR_METHOD_NOT_FOUND = -32601;
136
- export const ERROR_INTERNAL = -32603;
137
- export const ERROR_SESSION_NOT_FOUND = -32001;
138
- export const ERROR_NO_PROVIDER = -32002;
139
- export const ERROR_SESSION_EXISTS = -32003;
140
- export const ERROR_NOT_FOUND = -32008;
141
- export const ERROR_PERMISSION_DENIED = -32009;
142
-
143
- // ActionType / ReconnectResultType are `declare const enum` in the package
144
- // but are also real runtime objects (verified against the published dist),
145
- // so the value imports are safe under both tsc (inlined) and Bun.
146
-
147
- interface RpcMessage {
148
- jsonrpc?: unknown;
149
- id?: unknown;
150
- method?: unknown;
151
- params?: unknown;
152
- }
153
-
154
- interface SocketState {
155
- initialized: boolean;
156
- /** Negotiated version (set by initialize, inherited on reconnect). */
157
- version: string | null;
158
- clientId: string | null;
159
- }
160
-
161
- /**
162
- * Per-clientId registry record — survives socket closes so `reconnect`
163
- * can replay for the same client (AHP lifecycle spec).
164
- */
165
- interface ClientRecord {
166
- version: string;
167
- socketId: number | null;
168
- }
169
-
170
- /**
171
- * Everything the host knows about one live opencode session: the two
172
- * official-reducer stores (session + its single chat), the denormalized
173
- * summary fields for root notifications, and the per-turn tracking the
174
- * event pump needs to join opencode events to AHP turns.
175
- */
176
- interface SessionRecord {
177
- /** The opencode session id (`ses_…`). */
178
- sessionID: string;
179
- /** The AHP session channel URI (`ahp-session:/<suffix>`). */
180
- channel: string;
181
- /** Identity `SessionSummary.provider` (fixed at registration). */
182
- provider: string;
183
- createdAt: string;
184
- /** Denormalized `SessionSummary.modifiedAt` (ISO; lexicographic = chronological). */
185
- modifiedAt: string;
186
- sessionStore: SessionStateStore;
187
- chatStore: ChatStateStore;
188
- // ── turn tracking (event-pump join state) ────────────────────────────
189
- /** The AHP turnId the pump joins opencode events to, or null. */
190
- currentTurnId: string | null;
191
- turnStartedAt: number | null;
192
- /** `<providerID>/<modelID>` captured from `session.step.started` (usage model ref). */
193
- turnModelRef: string | null;
194
- // ── part / tool tracking ─────────────────────────────────────────────
195
- /** Emitted part keys (`<assistantMessageID>:<kind>:<ordinal>`). */
196
- parts: Set<string>;
197
- /** toolCallId → raw JSON input text (`session.tool.input.ended.text`). */
198
- toolInput: Map<string, string>;
199
- /** toolCallId → opencode tool name (`session.tool.input.started.name`). */
200
- toolName: Map<string, string>;
201
- /** toolCallIds that already received `chat/toolCallReady`. */
202
- toolReady: Set<string>;
203
- /** toolCallId → opencode permission request id. */
204
- permissionForTool: Map<string, string>;
205
- /** opencode permission request id → toolCallId. */
206
- toolForPermission: Map<string, string>;
207
- /** The most recent `session.inbox.enqueued` (external/TUI prompt tracking). */
208
- lastInbox: { text: string; delivery: string } | null;
209
- // ── Phase 2: changesets ────────────────────────────────────────────────
210
- /** Live changeset stores, keyed by changeset URI (created on subscribe). */
211
- changesets: Map<string, ChangesetStateStore>;
212
- /**
213
- * Per-turn file snapshots for the turn changesets: turnId → absPath →
214
- * captured {before (pre-edit disk read), after (disk at turn end)}.
215
- * `null` = the file was absent on that side. Kept until the session is
216
- * removed (content refs + discard-restore read them, plan §14.10).
217
- */
218
- turnSnapshots: Map<string, Map<string, { before: string | null; after: string | null }>>;
219
- }
220
-
221
- export interface HostOptions {
222
- serverInfo: Implementation;
223
- facade: OpencodeFacade;
224
- replayWindow: number;
225
- /** The opencode instance's working directory (InitializeResult.defaultDirectory). */
226
- defaultDirectory?: string;
227
- /** Advertise + serve the changeset channels (catalogues, snapshots, discard). */
228
- changesets: boolean;
229
- /** Deliver a JSON-serializable frame to a connection. */
230
- send: (socketId: number, message: unknown) => void;
231
- /** Close one connection (a superseded duplicate clientId). */
232
- close?: (socketId: number, code?: number, reason?: string) => void;
233
- log?: (message: string) => void;
234
- }
235
-
236
- /** Version assumed for a reconnecting client the host has never seen (host restart). */
237
- const RECONNECT_DEFAULT_VERSION = "1.0.0";
238
- /**
239
- * Grace before the pump registers an externally created session
240
- * (`session.created`): a concurrent `createSession` may still be resolving
241
- * for the same opencode session under a client-chosen channel; the slower
242
- * path is healed by the delete+recreate remap in `handleCreateSession`.
243
- */
244
- const EXTERNAL_REGISTER_GRACE_MS = 250;
245
- /** Default page size for `listSessions` (AHP `PaginatedParams.limit`). */
246
- const LIST_SESSIONS_DEFAULT_LIMIT = 100;
247
- /**
248
- * The file-mutating opencode tools whose inputs carry a target path — the
249
- * turn-changeset before-capture watches only these (`tool.input.ended`
250
- * fires before execution, so the pre-edit content is still on disk).
251
- */
252
- const SNAPSHOT_TOOLS = new Set(["write", "edit", "apply", "patch"]);
253
- /** The tool-input keys that carry a file path (checked in order). */
254
- const SNAPSHOT_PATH_KEYS = ["path", "file_path", "filePath", "file"] as const;
255
-
256
- export class Host {
257
- private readonly seq: Sequencer;
258
- private readonly channels = new ChannelRegistry();
259
- private readonly state: RootStateStore;
260
- private readonly sockets = new Map<number, SocketState>();
261
- private readonly clients = new Map<string, ClientRecord>();
262
- /**
263
- * Live sessions, keyed by opencode session id (the event-pump join key).
264
- * `byChannel` maps a session/chat channel URI to the same record for the
265
- * client-facing lookups — the channel suffix is not always the opencode id
266
- * (client-chosen suffixes), so the two keyings differ.
267
- */
268
- private readonly sessions = new Map<string, SessionRecord>();
269
- private readonly byChannel = new Map<string, SessionRecord>();
270
- private readonly opts: HostOptions;
271
- private readonly log: (message: string) => void;
272
- private turnCounter = 0;
273
- private pumpController: AbortController | null = null;
274
-
275
- constructor(opts: HostOptions) {
276
- this.opts = opts;
277
- this.log = opts.log ?? (() => {});
278
- this.seq = new Sequencer(opts.replayWindow);
279
- this.state = createRootStateStore({ agents: [] });
280
- }
281
-
282
- // ── transport callbacks ────────────────────────────────────────────────
283
-
284
- onOpen(socketId: number): void {
285
- this.sockets.set(socketId, { initialized: false, version: null, clientId: null });
286
- }
287
-
288
- onMessage(socketId: number, text: string): void {
289
- let raw: unknown;
290
- try {
291
- raw = JSON.parse(text);
292
- } catch {
293
- this.sendFrame(socketId, {
294
- jsonrpc: "2.0",
295
- id: null,
296
- error: { code: ERROR_PARSE, message: "parse error" },
297
- });
298
- return;
299
- }
300
- if (!isRecord(raw) || raw.jsonrpc !== "2.0" || typeof raw.method !== "string") {
301
- this.sendFrame(socketId, {
302
- jsonrpc: "2.0",
303
- id: isRecord(raw) ? raw.id ?? null : null,
304
- error: { code: ERROR_INVALID_REQUEST, message: "invalid request" },
305
- });
306
- return;
307
- }
308
- // The routing is async (catalog reads await the opencode registry);
309
- // each message is handled independently.
310
- void this.route(socketId, raw).catch((err) => {
311
- // R2: a bad frame or a bridge error must never take down the host.
312
- this.log(
313
- `error handling ${String(raw.method)}: ${err instanceof Error ? err.stack ?? err.message : String(err)}`,
314
- );
315
- if (raw.id !== undefined) {
316
- this.sendFrame(socketId, {
317
- jsonrpc: "2.0",
318
- id: raw.id,
319
- error: { code: ERROR_INTERNAL, message: "internal error" },
320
- });
321
- }
322
- });
323
- }
324
-
325
- onClose(socketId: number): void {
326
- const socket = this.sockets.get(socketId);
327
- if (socket?.clientId) {
328
- const record = this.clients.get(socket.clientId);
329
- if (record && record.socketId === socketId) record.socketId = null;
330
- }
331
- this.channels.removeSocket(socketId);
332
- this.sockets.delete(socketId);
333
- // MVP gap: active clients are not evicted on disconnect (the spec
334
- // expects eviction without a timely reconnect); they refresh via
335
- // `session/activeClientSet` on the next turn/dispatch.
336
- }
337
-
338
- // ── event pump ─────────────────────────────────────────────────────────
339
-
340
- /**
341
- * Start the opencode event → AHP action pump. Idempotent. The pump is a
342
- * single sequential async loop, so event handling and client-dispatch
343
- * handling (same event loop) interleave without races on the per-turn
344
- * join state.
345
- */
346
- startEventPump(): void {
347
- if (this.pumpController !== null) return;
348
- const controller = new AbortController();
349
- this.pumpController = controller;
350
- void (async () => {
351
- try {
352
- for await (const event of this.opts.facade.events(controller.signal)) {
353
- if (controller.signal.aborted) break;
354
- await this.handleEvent(event);
355
- }
356
- } catch (err) {
357
- this.log(`event pump failed: ${err instanceof Error ? err.stack ?? err.message : String(err)}`);
358
- } finally {
359
- if (this.pumpController === controller) this.pumpController = null;
360
- }
361
- })();
362
- }
363
-
364
- /** Stop the event pump (teardown). Idempotent. */
365
- stopEventPump(): void {
366
- this.pumpController?.abort();
367
- this.pumpController = null;
368
- }
369
-
370
- // ── routing ────────────────────────────────────────────────────────────
371
-
372
- private async route(socketId: number, msg: RpcMessage): Promise<void> {
373
- const socket = this.sockets.get(socketId);
374
- if (!socket) return;
375
- const method = msg.method as string;
376
-
377
- if (!socket.initialized) {
378
- if (method === "ping") {
379
- // ping is answered even before initialize (AHP transport spec).
380
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
381
- return;
382
- }
383
- if (method === "initialize") {
384
- await this.handleInitialize(socketId, msg);
385
- return;
386
- }
387
- if (method === "reconnect") {
388
- await this.handleReconnect(socketId, msg);
389
- return;
390
- }
391
- if (msg.id !== undefined) {
392
- this.sendFrame(socketId, {
393
- jsonrpc: "2.0",
394
- id: msg.id,
395
- error: {
396
- code: ERROR_INVALID_REQUEST,
397
- message: `not initialized: ${method} must follow initialize or reconnect`,
398
- },
399
- });
400
- return;
401
- }
402
- this.log(`ignoring pre-initialize notification ${method} on socket ${socketId}`);
403
- return;
404
- }
405
-
406
- switch (method) {
407
- case "ping":
408
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
409
- break;
410
- case "subscribe":
411
- await this.handleSubscribe(socketId, msg);
412
- break;
413
- case "unsubscribe":
414
- this.handleUnsubscribe(socketId, msg); // notification (no id)
415
- break;
416
- case "dispatchAction":
417
- await this.handleDispatchAction(socketId, msg); // notification (no id)
418
- break;
419
- case "listSessions":
420
- await this.handleListSessions(socketId, msg);
421
- break;
422
- case "createSession":
423
- await this.handleCreateSession(socketId, msg);
424
- break;
425
- case "resourceRead":
426
- await this.handleResourceRead(socketId, msg);
427
- break;
428
- case "invokeChangesetOperation":
429
- await this.handleInvokeChangesetOperation(socketId, msg);
430
- break;
431
- case "setClientManagedSettingsPermissions":
432
- // VS Code-specific post-init notification (plan §14.7): the
433
- // permissions VS Code manages in its own settings UI. AHP 1.0.0
434
- // has no counterpart — accept deliberately (parse + log), never
435
- // error; the connection stays up.
436
- this.log(
437
- `setClientManagedSettingsPermissions received (${describeParams(msg.params)}); accepted (no-op)`,
438
- );
439
- break;
440
- case "initialize":
441
- case "reconnect":
442
- this.sendFrame(socketId, {
443
- jsonrpc: "2.0",
444
- id: msg.id ?? null,
445
- error: {
446
- code: ERROR_INVALID_REQUEST,
447
- message: `${method} is only valid before the handshake`,
448
- },
449
- });
450
- break;
451
- default:
452
- if (msg.id !== undefined) {
453
- this.sendFrame(socketId, {
454
- jsonrpc: "2.0",
455
- id: msg.id,
456
- error: { code: ERROR_METHOD_NOT_FOUND, message: `unknown method: ${method}` },
457
- });
458
- } else {
459
- this.log(`ignoring unknown notification ${method} on socket ${socketId}`);
460
- }
461
- }
462
- }
463
-
464
- private sendFrame(socketId: number, message: unknown): void {
465
- this.opts.send(socketId, message);
466
- }
467
-
468
- // ── commands ───────────────────────────────────────────────────────────
469
-
470
- private async handleInitialize(socketId: number, msg: RpcMessage): Promise<void> {
471
- const socket = this.sockets.get(socketId)!;
472
- const outcome = await handleInitialize({
473
- params: msg.params,
474
- serverInfo: this.opts.serverInfo,
475
- serverSeq: this.seq.seq,
476
- defaultDirectory: this.opts.defaultDirectory,
477
- snapshotFor: (uri) => this.snapshotFor(uri),
478
- });
479
- if (!outcome.ok) {
480
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, error: outcome.error });
481
- return;
482
- }
483
-
484
- const clientId = (msg.params as { clientId: string }).clientId;
485
- const existing = this.clients.get(clientId);
486
- if (existing && existing.socketId !== null && existing.socketId !== socketId) {
487
- // A newer connection with the same clientId supersedes the old one.
488
- this.log(`client ${clientId} re-initialized on socket ${socketId}; closing socket ${existing.socketId}`);
489
- this.opts.close?.(existing.socketId, 4000, "superseded by a newer connection");
490
- }
491
-
492
- socket.initialized = true;
493
- socket.version = outcome.result.protocolVersion;
494
- socket.clientId = clientId;
495
- this.clients.set(clientId, { version: outcome.result.protocolVersion, socketId });
496
-
497
- // Register the initial subscriptions right after the snapshot
498
- // computation above; no action can slip in between.
499
- const params = isRecord(msg.params) ? msg.params : {};
500
- const initial = Array.isArray(params["initialSubscriptions"])
501
- ? params["initialSubscriptions"]
502
- : [];
503
- for (const uri of initial) {
504
- if (typeof uri === "string" && uri.length > 0) {
505
- this.channels.subscribe(socketId, uri);
506
- }
507
- }
508
-
509
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: outcome.result });
510
- }
511
-
512
- private async handleReconnect(socketId: number, msg: RpcMessage): Promise<void> {
513
- const params = msg.params;
514
- if (!isRecord(params) || params["channel"] !== ROOT_CHANNEL) {
515
- this.sendFrame(socketId, {
516
- jsonrpc: "2.0",
517
- id: msg.id ?? null,
518
- error: { code: ERROR_INVALID_PARAMS, message: `reconnect must target ${ROOT_CHANNEL}` },
519
- });
520
- return;
521
- }
522
- const clientId = params["clientId"];
523
- const lastSeen = params["lastSeenServerSeq"];
524
- const subscriptions = params["subscriptions"];
525
- if (typeof clientId !== "string" || clientId.length === 0 ||
526
- !Number.isInteger(lastSeen) || (lastSeen as number) < 0 ||
527
- !Array.isArray(subscriptions) || !subscriptions.every((u) => typeof u === "string")) {
528
- this.sendFrame(socketId, {
529
- jsonrpc: "2.0",
530
- id: msg.id ?? null,
531
- error: { code: ERROR_INVALID_PARAMS, message: "invalid reconnect params" },
532
- });
533
- return;
534
- }
535
- const clientSubs = subscriptions as string[];
536
-
537
- const record = this.clients.get(clientId);
538
- const known = record !== undefined;
539
- const version = record?.version ?? RECONNECT_DEFAULT_VERSION;
540
-
541
- const socket = this.sockets.get(socketId)!;
542
- socket.initialized = true;
543
- socket.version = version;
544
- socket.clientId = clientId;
545
- this.clients.set(clientId, { version, socketId });
546
-
547
- // Resolve every requested subscription; unresolvable ones are reported
548
- // in `missing` (the client drops them — AHP lifecycle spec).
549
- const snapshots: Snapshot[] = [];
550
- const missing: string[] = [];
551
- for (const uri of clientSubs) {
552
- const snap = await this.snapshotFor(uri);
553
- if (snap) snapshots.push(snap);
554
- else missing.push(uri);
555
- }
556
- for (const uri of clientSubs) {
557
- this.channels.subscribe(socketId, uri);
558
- }
559
-
560
- // Replay when the client is known and its gap is still in the window;
561
- // otherwise fresh snapshots.
562
- let result: ReconnectResult;
563
- const replay = this.seq.since(lastSeen as number);
564
- if (known && replay !== null) {
565
- const set = new Set(clientSubs);
566
- result = {
567
- type: ReconnectResultType.Replay,
568
- actions: replay.filter((a) => set.has(a.channel)),
569
- missing,
570
- };
571
- } else {
572
- result = { type: ReconnectResultType.Snapshot, snapshots };
573
- }
574
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
575
- }
576
-
577
- private async handleSubscribe(socketId: number, msg: RpcMessage): Promise<void> {
578
- const params = isRecord(msg.params) ? msg.params : {};
579
- const uri = params["channel"];
580
- if (typeof uri !== "string" || uri.length === 0) {
581
- this.sendFrame(socketId, {
582
- jsonrpc: "2.0",
583
- id: msg.id ?? null,
584
- error: { code: ERROR_INVALID_PARAMS, message: "subscribe requires a channel URI" },
585
- });
586
- return;
587
- }
588
- const outcome = this.channels.subscribe(socketId, uri);
589
- if (!outcome.ok) {
590
- this.sendFrame(socketId, {
591
- jsonrpc: "2.0",
592
- id: msg.id ?? null,
593
- error: {
594
- code:
595
- outcome.reason === "no-such-session"
596
- ? ERROR_SESSION_NOT_FOUND
597
- : ERROR_INVALID_PARAMS,
598
- message: `cannot subscribe to ${uri}`,
599
- },
600
- });
601
- return;
602
- }
603
- const snap = await this.snapshotFor(uri);
604
- this.sendFrame(socketId, {
605
- jsonrpc: "2.0",
606
- id: msg.id ?? null,
607
- result: snap ? { snapshot: snap } : {},
608
- });
609
- }
610
-
611
- private handleUnsubscribe(socketId: number, msg: RpcMessage): void {
612
- const params = isRecord(msg.params) ? msg.params : {};
613
- const uri = params["channel"];
614
- if (typeof uri !== "string" || uri.length === 0) return;
615
- this.channels.unsubscribe(socketId, uri);
616
- }
617
-
618
- /**
619
- * `createSession` (AHP 1.0.0 session-channel command). Creates a real
620
- * opencode session, seeds its session/chat stores, publishes the
621
- * session-channel lifecycle actions, announces the session on the root
622
- * channel, and responds `null` (per the command contract).
623
- *
624
- * Error codes: -32002 (no agent for the requested provider),
625
- * -32003 (the session URI already exists).
626
- */
627
- private async handleCreateSession(socketId: number, msg: RpcMessage): Promise<void> {
628
- const params = isRecord(msg.params) ? msg.params : {};
629
- const channel = params["channel"];
630
- if (typeof channel !== "string" || channelKind(channel) !== "session") {
631
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createSession requires an ahp-session:/… channel");
632
- return;
633
- }
634
- const suffix = sessionIDOf(channel) as string;
635
- // A suffix containing the changeset marker would make this session
636
- // channel string-identical to the changeset URI of the session before
637
- // the marker — the changeset kind would win (channelKind), making the
638
- // session channel un-subscribable. Reject it instead.
639
- if (suffix.includes("/changeset/")) {
640
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "channel suffix must not contain \"/changeset/\"");
641
- return;
642
- }
643
- for (const rec of this.sessions.values()) {
644
- if (rec.channel === channel) {
645
- this.sendError(socketId, msg.id, ERROR_SESSION_EXISTS, "Session already exists");
646
- return;
647
- }
648
- }
649
-
650
- // Resolve the provider/model for the new session.
651
- const providers = await this.opts.facade.listCatalog();
652
- const providerParam = params["provider"];
653
- let provider;
654
- if (typeof providerParam === "string" && providerParam.length > 0) {
655
- provider = providers.find((p) => p.providerID === providerParam && p.activation !== "disabled");
656
- if (provider === undefined) {
657
- this.sendError(socketId, msg.id, ERROR_NO_PROVIDER, `No agent for provider ${providerParam}`);
658
- return;
659
- }
660
- } else {
661
- provider = providers.find((p) => p.activation !== "disabled");
662
- }
663
- const model = provider !== undefined ? firstEnabledModelRef(provider.models) : undefined;
664
-
665
- // `activeClient` eagerly claims an active-client role; the spec requires
666
- // the clientId to match the creating client.
667
- let activeClients: SessionActiveClient[] = [];
668
- const activeClientParam = params["activeClient"];
669
- if (activeClientParam !== undefined) {
670
- const socket = this.sockets.get(socketId);
671
- const ac = activeClientParam as Record<string, unknown>;
672
- if (
673
- !isRecord(ac) ||
674
- typeof ac["clientId"] !== "string" ||
675
- ac["clientId"] !== socket?.clientId
676
- ) {
677
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "activeClient.clientId must match the initializing clientId");
678
- return;
679
- }
680
- activeClients = [normalizeActiveClient(ac)];
681
- }
682
-
683
- // opencode SessionIDs must start with "ses": pass the suffix through
684
- // only when it already is one; otherwise let opencode mint an id and
685
- // record the suffix→id mapping (the record key is the opencode id).
686
- const passID = suffix.startsWith("ses") ? suffix : undefined;
687
- const created = await this.opts.facade.createSession({ id: passID, model });
688
-
689
- // Slow-create race: the pump may have registered this opencode session
690
- // under its own id as an external session while `createSession` was in
691
- // flight. Remap: drop the interim record (root/sessionRemoved) and
692
- // re-register under the client-chosen channel below.
693
- const interim = this.sessions.get(created.sessionID);
694
- if (interim !== undefined && interim.channel !== channel) {
695
- this.removeRecord(interim);
696
- }
697
-
698
- const agents = await this.opts.facade.listAgents();
699
- const customizations =
700
- mapAgentCustomizations(agents).length > 0 && this.opts.defaultDirectory !== undefined
701
- ? [agentDirectoryCustomization(this.opts.defaultDirectory, agents)]
702
- : undefined;
703
- const now = new Date().toISOString();
704
- const sessionStore = createSessionStateStore(
705
- initialSessionState({
706
- sessionID: created.sessionID,
707
- provider: created.model?.providerID ?? provider?.providerID ?? "opencode",
708
- title: created.title ?? "New Session",
709
- activeClients,
710
- customizations,
711
- }),
712
- );
713
- const chatStore = createChatStateStore(
714
- initialChatState({ resource: chatChannelURI(created.sessionID), title: "Chat 1", modifiedAt: now }),
715
- );
716
- const rec: SessionRecord = {
717
- sessionID: created.sessionID,
718
- channel,
719
- provider: sessionStore.state.provider,
720
- createdAt: new Date(created.time.created).toISOString(),
721
- modifiedAt: new Date(created.time.updated).toISOString() > now
722
- ? new Date(created.time.updated).toISOString()
723
- : now,
724
- sessionStore,
725
- chatStore,
726
- currentTurnId: null,
727
- turnStartedAt: null,
728
- turnModelRef: null,
729
- parts: new Set(),
730
- toolInput: new Map(),
731
- toolName: new Map(),
732
- toolReady: new Set(),
733
- permissionForTool: new Map(),
734
- toolForPermission: new Map(),
735
- lastInbox: null,
736
- changesets: new Map(),
737
- turnSnapshots: new Map(),
738
- };
739
- this.sessions.set(created.sessionID, rec);
740
- this.byChannel.set(channel, rec);
741
- this.byChannel.set(chatChannelURI(created.sessionID), rec);
742
- // The session channel carries the client-chosen suffix; the chat
743
- // channel and the event pump carry the opencode id — both must
744
- // resolve in the registry.
745
- this.channels.addSession(suffix);
746
- this.channels.addSession(created.sessionID);
747
-
748
- // Session-channel lifecycle (server-side, no origin).
749
- this.publish({ channel, action: { type: ActionType.SessionReady } });
750
- this.publish({
751
- channel,
752
- action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chatStore.state) },
753
- });
754
- this.publish({
755
- channel,
756
- action: { type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(created.sessionID) },
757
- });
758
- // Phase 2: advertise the changeset catalogues (session channel: the
759
- // session-wide changeset; chat channel: uncommitted + session + the
760
- // per-turn template).
761
- if (this.opts.changesets) {
762
- this.publish({
763
- channel,
764
- action: { type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(created.sessionID) },
765
- });
766
- this.publish({
767
- channel: chatChannelURI(created.sessionID),
768
- action: { type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(created.sessionID) },
769
- });
770
- }
771
- // Root: active-session count (action, replayed) + sessionAdded (notification).
772
- this.publish({
773
- channel: ROOT_CHANNEL,
774
- action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
775
- });
776
- this.notifyRoot("root/sessionAdded", {
777
- channel: ROOT_CHANNEL,
778
- summary: this.sessionSummary(rec),
779
- });
780
-
781
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
782
- }
783
-
784
- /**
785
- * `listSessions` (AHP 1.0.0 root command): all opencode sessions,
786
- * most-recently-modified first, with in-memory cursor pagination.
787
- * Unknown sessions are lazily registered (so their channels become
788
- * subscribable); registration is idempotent per opencode session id.
789
- */
790
- private async handleListSessions(socketId: number, msg: RpcMessage): Promise<void> {
791
- const params = isRecord(msg.params) ? msg.params : {};
792
- const limit =
793
- typeof params["limit"] === "number" && Number.isInteger(params["limit"]) && (params["limit"] as number) > 0
794
- ? (params["limit"] as number)
795
- : LIST_SESSIONS_DEFAULT_LIMIT;
796
- let offset = 0;
797
- if (typeof params["cursor"] === "string" && params["cursor"].length > 0) {
798
- const parsed = Number.parseInt(params["cursor"], 10);
799
- if (Number.isInteger(parsed) && parsed > 0) offset = parsed;
800
- }
801
- const listed = await this.opts.facade.listSessions();
802
- const records: (SessionRecord | undefined)[] = [];
803
- for (const fs of listed) {
804
- records.push(this.registerExternal(fs) ?? this.sessions.get(fs.sessionID));
805
- }
806
- const sorted = records
807
- .filter((r): r is SessionRecord => r !== undefined)
808
- .sort((a, b) => {
809
- const ta = this.sessions.get(a.sessionID)?.modifiedAt ?? a.modifiedAt;
810
- const tb = this.sessions.get(b.sessionID)?.modifiedAt ?? b.modifiedAt;
811
- return ta < tb ? 1 : ta > tb ? -1 : 0;
812
- });
813
- const page = sorted.slice(offset, offset + limit);
814
- const nextOffset = offset + limit;
815
- const result: { items: SessionSummary[]; nextCursor?: string } = {
816
- items: page.map((rec) => this.sessionSummary(rec)),
817
- };
818
- if (nextOffset < sorted.length) result.nextCursor = String(nextOffset);
819
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
820
- }
821
-
822
- // ── client-dispatchable actions (Phase 1) ──────────────────────────────
823
-
824
- /**
825
- * `dispatchAction` is a notification — the response is the `action`
826
- * notification stream itself. Phase 1 routes the client-dispatchable
827
- * actions VS Code sends; everything else is acknowledged with a
828
- * rejection on that stream.
829
- */
830
- private async handleDispatchAction(socketId: number, msg: RpcMessage): Promise<void> {
831
- const params = isRecord(msg.params) ? msg.params : {};
832
- const channel = params["channel"];
833
- const clientSeq = params["clientSeq"];
834
- const action = params["action"];
835
- if (
836
- typeof channel !== "string" ||
837
- channel.length === 0 ||
838
- !Number.isInteger(clientSeq) ||
839
- !isRecord(action) ||
840
- typeof action["type"] !== "string"
841
- ) {
842
- this.log(`malformed dispatchAction on socket ${socketId} (dropped)`);
843
- return;
844
- }
845
-
846
- const socket = this.sockets.get(socketId);
847
- const clientId = socket?.clientId ?? null;
848
- const origin: ActionOrigin | undefined =
849
- clientId !== null ? { clientId, clientSeq: clientSeq as number } : undefined;
850
-
851
- const stateAction = action as unknown as StateAction;
852
- const rejectionReason = this.dispatchRejectionReason(channel, stateAction, clientId);
853
- if (rejectionReason !== null) {
854
- this.echo(channel, stateAction, origin, rejectionReason);
855
- return;
856
- }
857
-
858
- const kind = channelKind(channel);
859
- if (kind === "changeset") {
860
- // The only client-dispatchable changeset action is the per-file
861
- // review toggle — echo it through the official reducer.
862
- if (stateAction.type === ActionType.ChangesetFilesReviewChanged) {
863
- this.dispatchChangesetFilesReviewChanged(channel, stateAction, origin);
864
- } else {
865
- this.echo(channel, stateAction, origin, `unsupported action on changeset channel: ${String(action.type)}`);
866
- }
867
- return;
868
- }
869
- if (kind !== "session" && kind !== "chat") {
870
- this.echo(channel, stateAction, origin, `unsupported action on ${channelKind(channel)} channel: ${String(action.type)}`);
871
- return;
872
- }
873
- const rec = this.byChannel.get(channel);
874
- if (rec === undefined) {
875
- this.echo(channel, stateAction, origin, `no such session: ${channel}`);
876
- return;
877
- }
878
-
879
- // From here on every branch either echoes (accepted or rejected).
880
- switch (stateAction.type) {
881
- case ActionType.ChatTurnStarted:
882
- await this.dispatchTurnStarted(rec, stateAction, origin);
883
- return;
884
- case ActionType.ChatPendingMessageSet:
885
- await this.dispatchPendingMessageSet(rec, stateAction, origin);
886
- return;
887
- case ActionType.ChatToolCallConfirmed:
888
- await this.dispatchToolCallConfirmed(rec, stateAction, origin);
889
- return;
890
- case ActionType.ChatTurnCancelled:
891
- await this.dispatchTurnCancelled(rec, stateAction, origin);
892
- return;
893
- case ActionType.SessionTitleChanged:
894
- await this.dispatchTitleChanged(rec, stateAction, origin);
895
- return;
896
- case ActionType.SessionActiveClientSet:
897
- this.dispatchActiveClientSet(rec, stateAction, origin, clientId);
898
- return;
899
- case ActionType.SessionActiveClientRemoved:
900
- this.dispatchActiveClientRemoved(rec, stateAction, origin, clientId);
901
- return;
902
- case ActionType.ChatPendingMessageRemoved:
903
- // Honest gap: the opencode plugin surface has no inbox cancel —
904
- // a pending (steer/queue) message cannot be withdrawn once sent.
905
- this.echo(channel, stateAction, origin, "cannot remove a pending message: opencode has no inbox cancel");
906
- return;
907
- case ActionType.ChatDraftChanged:
908
- case ActionType.ChatIsReadChanged:
909
- case ActionType.ChatIsArchivedChanged:
910
- case ActionType.SessionIsReadChanged:
911
- case ActionType.SessionIsArchivedChanged:
912
- this.echo(channel, stateAction, origin);
913
- return;
914
- default:
915
- this.echo(channel, stateAction, origin, `unsupported action (Phase 1): ${String(stateAction.type)}`);
916
- }
917
- }
918
48
 
919
- /**
920
- * Shared pre-checks for a dispatched action; null when the action may
921
- * proceed to per-type handling.
922
- */
923
- private dispatchRejectionReason(channel: string, action: StateAction, clientId: string | null): string | null {
924
- if (channelKind(channel) === "unknown") return `unknown channel: ${channel}`;
925
- let dispatchable: boolean;
926
- try {
927
- dispatchable = isClientDispatchable(action as Parameters<typeof isClientDispatchable>[0]);
928
- } catch {
929
- dispatchable = false;
930
- }
931
- if (!dispatchable) return `action ${String(action.type)} is not client-dispatchable`;
932
- if (clientId === null) return "client is not initialized";
933
- return null;
934
- }
49
+ import { HostRpc } from "./host-rpc.js";
935
50
 
936
- /** Publish an accepted echo (or a rejection) on the action stream. */
937
- private echo(
938
- channel: string,
939
- action: StateAction,
940
- origin: ActionOrigin | undefined,
941
- rejectionReason?: string,
942
- ): void {
943
- const envelope = this.publish({
944
- channel,
945
- action,
946
- origin,
947
- ...(rejectionReason !== undefined ? { rejectionReason } : {}),
948
- });
949
- if (rejectionReason !== undefined && origin !== undefined) {
950
- // A rejection must reach the dispatching socket even when it is not
951
- // subscribed to the channel (write-ahead dispatch: the client applied
952
- // the action optimistically and needs the rejection to roll it back).
953
- const socketId = this.socketIdForClient(origin.clientId);
954
- if (socketId !== undefined && !this.channels.socketsSubscribedTo(channel).includes(socketId)) {
955
- this.opts.send(socketId, { jsonrpc: "2.0", method: "action", params: envelope });
956
- }
957
- }
958
- }
51
+ export { ERROR_PARSE, ERROR_INVALID_REQUEST, ERROR_METHOD_NOT_FOUND, ERROR_INTERNAL, ERROR_SESSION_NOT_FOUND, ERROR_NO_PROVIDER, ERROR_SESSION_EXISTS, ERROR_NOT_FOUND, ERROR_PERMISSION_DENIED, ERROR_ALREADY_EXISTS } from "./host-errors.js";
52
+ export type { HostOptions } from "./host-types.js";
959
53
 
960
- /** The socket currently bound to a clientId (rejection delivery target). */
961
- private socketIdForClient(clientId: string): number | undefined {
962
- for (const [socketId, socket] of this.sockets) {
963
- if (socket.clientId === clientId) return socketId;
964
- }
965
- return undefined;
966
- }
967
-
968
- private async dispatchTurnStarted(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
969
- const chatURI = chatChannelURI(rec.sessionID);
970
- const a = action as ChatTurnStartedAction;
971
- const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
972
- const message =
973
- isRecord(a.message) && typeof a.message["text"] === "string"
974
- ? (a.message as unknown as Message)
975
- : null;
976
- if (turnId === null || message === null) {
977
- this.echo(chatURI, action, origin, "invalid chat/turnStarted params");
978
- return;
979
- }
980
- // `startedAt` is required on the wire (the reducer uses it for the
981
- // chat's `modifiedAt`); fall back to the host clock when the client
982
- // did not supply a parseable one.
983
- const normalized: ChatTurnStartedAction =
984
- typeof a.startedAt === "string" && !Number.isNaN(Date.parse(a.startedAt))
985
- ? a
986
- : { ...a, startedAt: new Date().toISOString() };
987
- if (rec.chatStore.state.activeTurn !== undefined) {
988
- this.echo(
989
- chatURI,
990
- action,
991
- origin,
992
- "a turn is already active; follow-up messages go via chat/pendingMessageSet",
993
- );
994
- return;
995
- }
996
-
997
- // Apply the message's model/agent selection before the prompt
998
- // (`SessionPromptInput` carries no model/agent fields).
999
- try {
1000
- if (message.model?.id !== undefined && message.model.id.includes("/")) {
1001
- const sep = message.model.id.indexOf("/");
1002
- const providerID = message.model.id.slice(0, sep);
1003
- const modelID = message.model.id.slice(sep + 1);
1004
- if (providerID.length > 0 && modelID.length > 0) {
1005
- await this.opts.facade.switchModel({ sessionID: rec.sessionID, model: { providerID, modelID } });
1006
- }
1007
- }
1008
- if (message.agent?.uri !== undefined) {
1009
- const agentID = agentIDFromUri(message.agent.uri);
1010
- if (agentID !== null) {
1011
- await this.opts.facade.switchAgent({ sessionID: rec.sessionID, agent: agentID });
1012
- }
1013
- }
1014
- } catch (err) {
1015
- this.echo(chatURI, action, origin, `failed to apply model/agent selection: ${errorMessage(err)}`);
1016
- return;
1017
- }
1018
-
1019
- // Write-ahead: claim the turn BEFORE the prompt so the
1020
- // `session.execution.started` event joins it even when it races the
1021
- // prompt's resolve; revert on failure.
1022
- rec.currentTurnId = turnId;
1023
- rec.turnStartedAt = Date.now();
1024
- try {
1025
- await this.opts.facade.prompt({ sessionID: rec.sessionID, text: message.text });
1026
- } catch (err) {
1027
- rec.currentTurnId = null;
1028
- rec.turnStartedAt = null;
1029
- this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
1030
- return;
1031
- }
1032
- this.echo(chatURI, normalized, origin);
1033
- }
1034
-
1035
- private async dispatchPendingMessageSet(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1036
- const chatURI = chatChannelURI(rec.sessionID);
1037
- const a = action as { kind?: unknown; id?: unknown; message?: unknown };
1038
- const kind = a.kind === "steering" || a.kind === "queued" ? a.kind : null;
1039
- const id = typeof a.id === "string" && a.id.length > 0 ? a.id : null;
1040
- const message =
1041
- isRecord(a.message) && typeof a.message["text"] === "string"
1042
- ? (a.message as unknown as Message)
1043
- : null;
1044
- if (kind === null || id === null || message === null) {
1045
- this.echo(chatURI, action, origin, "invalid chat/pendingMessageSet params");
1046
- return;
1047
- }
1048
- const hasActiveTurn = rec.chatStore.state.activeTurn !== undefined;
1049
- // steer → delivery "steer" (only while a turn is active); queued →
1050
- // delivery "queue"; a steering message with no active turn falls back
1051
- // to a plain prompt (it becomes the next turn).
1052
- const delivery: FacadeDelivery | undefined = hasActiveTurn
1053
- ? kind === "steering"
1054
- ? "steer"
1055
- : "queue"
1056
- : undefined;
1057
- try {
1058
- await this.opts.facade.prompt({ sessionID: rec.sessionID, text: message.text, delivery });
1059
- } catch (err) {
1060
- this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
1061
- return;
1062
- }
1063
- if (hasActiveTurn) {
1064
- this.echo(chatURI, action, origin);
1065
- return;
1066
- }
1067
- // No active turn: the message starts a turn right now. Echo the
1068
- // pending-message first, then a host-minted turnStarted carrying
1069
- // `queuedMessageId` — the reducer dequeues it.
1070
- this.echo(chatURI, action, origin);
1071
- const turnId = this.mintTurnId();
1072
- rec.currentTurnId = turnId;
1073
- rec.turnStartedAt = Date.now();
1074
- this.publish({
1075
- channel: chatURI,
1076
- action: {
1077
- type: ActionType.ChatTurnStarted,
1078
- turnId,
1079
- startedAt: new Date().toISOString(),
1080
- message,
1081
- queuedMessageId: id,
1082
- },
1083
- });
1084
- }
1085
-
1086
- private async dispatchToolCallConfirmed(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1087
- const chatURI = chatChannelURI(rec.sessionID);
1088
- const a = action as ChatToolCallConfirmedAction;
1089
- const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
1090
- if (toolCallId === null) {
1091
- this.echo(chatURI, action, origin, "invalid chat/toolCallConfirmed params");
1092
- return;
1093
- }
1094
- const permissionID = rec.permissionForTool.get(toolCallId);
1095
- if (permissionID === undefined) {
1096
- this.echo(chatURI, action, origin, `no pending permission for tool call ${toolCallId}`);
1097
- return;
1098
- }
1099
- try {
1100
- await this.opts.facade.replyPermission({
1101
- sessionID: rec.sessionID,
1102
- requestID: permissionID,
1103
- decision: a.approved === true ? "once" : "reject",
1104
- });
1105
- } catch (err) {
1106
- this.echo(chatURI, action, origin, `permission reply failed: ${errorMessage(err)}`);
1107
- return;
1108
- }
1109
- // Echo the confirmation (reducer → running/cancelled), then clear the
1110
- // session-level input request. The `permission.replied` event is a
1111
- // safety net (its tracking is already gone → no-op).
1112
- this.echo(chatURI, action, origin);
1113
- this.publish({
1114
- channel: rec.channel,
1115
- action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
1116
- });
1117
- rec.permissionForTool.delete(toolCallId);
1118
- rec.toolForPermission.delete(permissionID);
1119
- }
1120
-
1121
- private async dispatchTurnCancelled(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1122
- const chatURI = chatChannelURI(rec.sessionID);
1123
- const a = action as ChatTurnCancelledAction;
1124
- const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
1125
- const active = rec.chatStore.state.activeTurn;
1126
- if (turnId === null || active === undefined || active.id !== turnId) {
1127
- this.echo(chatURI, action, origin, "no active turn to cancel");
1128
- return;
1129
- }
1130
- try {
1131
- await this.opts.facade.interrupt({ sessionID: rec.sessionID });
1132
- } catch (err) {
1133
- this.echo(chatURI, action, origin, `interrupt failed: ${errorMessage(err)}`);
1134
- return;
1135
- }
1136
- // `duration` is required on the wire (the reducer derives the final
1137
- // `modifiedAt` from it); the host clock is authoritative when the
1138
- // client did not supply one.
1139
- const duration =
1140
- typeof a.duration === "number" && Number.isFinite(a.duration) ? a.duration : this.turnDuration(rec);
1141
- this.echo(chatURI, { ...a, duration }, origin);
1142
- // The opencode `session.execution.interrupted` event finds no active
1143
- // turn after the echo finalized it (skipped); run the queued/steering
1144
- // handoff now, on the host side.
1145
- await this.finishTurn(rec);
1146
- }
1147
-
1148
- /**
1149
- * `changeset/filesReviewChanged` (the only client-dispatchable changeset
1150
- * action): validate the channel resolves to a live store, then echo —
1151
- * the official reducer toggles `reviewed` per matched file id.
1152
- */
1153
- private dispatchChangesetFilesReviewChanged(channel: string, action: StateAction, origin: ActionOrigin | undefined): void {
1154
- const a = action as ChangesetFilesReviewChangedAction;
1155
- if (!Array.isArray(a.files) || !a.files.every((f) => typeof f === "string") || typeof a.reviewed !== "boolean") {
1156
- this.echo(channel, action, origin, "invalid changeset/filesReviewChanged params");
1157
- return;
1158
- }
1159
- const parsed = parseChangesetChannel(channel);
1160
- const rec = parsed !== null ? this.sessions.get(parsed.sessionID) : undefined;
1161
- const store = rec !== undefined ? rec.changesets.get(channel) : undefined;
1162
- if (rec === undefined || store === undefined) {
1163
- this.echo(channel, action, origin, "no such changeset");
1164
- return;
1165
- }
1166
- this.echo(channel, action, origin);
1167
- }
1168
-
1169
- private async dispatchTitleChanged(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
1170
- const a = action as { title?: unknown };
1171
- const title = typeof a.title === "string" && a.title.length > 0 ? a.title : null;
1172
- if (title === null) {
1173
- this.echo(rec.channel, action, origin, "invalid session/titleChanged params");
1174
- return;
1175
- }
1176
- try {
1177
- await this.opts.facade.rename({ sessionID: rec.sessionID, title });
1178
- } catch (err) {
1179
- this.echo(rec.channel, action, origin, `rename failed: ${errorMessage(err)}`);
1180
- return;
1181
- }
1182
- this.echo(rec.channel, action, origin);
1183
- }
1184
-
1185
- private dispatchActiveClientSet(
1186
- rec: SessionRecord,
1187
- action: StateAction,
1188
- origin: ActionOrigin | undefined,
1189
- clientId: string | null,
1190
- ): void {
1191
- const a = action as { activeClient?: unknown };
1192
- const ac = a.activeClient;
1193
- if (!isRecord(ac) || typeof ac["clientId"] !== "string" || (clientId !== null && ac["clientId"] !== clientId)) {
1194
- this.echo(rec.channel, action, origin, "activeClient.clientId must match the dispatching client");
1195
- return;
1196
- }
1197
- const tools = Array.isArray(ac["tools"]) ? (ac["tools"] as ToolDefinition[]) : [];
1198
- const normalized: SessionActiveClient = {
1199
- clientId: ac["clientId"] as string,
1200
- tools,
1201
- ...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
1202
- };
1203
- this.publish({
1204
- channel: rec.channel,
1205
- action: { type: ActionType.SessionActiveClientSet, activeClient: normalized },
1206
- origin,
1207
- });
1208
- }
1209
-
1210
- private dispatchActiveClientRemoved(
1211
- rec: SessionRecord,
1212
- action: StateAction,
1213
- origin: ActionOrigin | undefined,
1214
- clientId: string | null,
1215
- ): void {
1216
- const a = action as { clientId?: unknown };
1217
- if (typeof a.clientId !== "string" || (clientId !== null && a.clientId !== clientId)) {
1218
- this.echo(rec.channel, action, origin, "clientId must match the dispatching client");
1219
- return;
1220
- }
1221
- this.echo(rec.channel, action, origin);
1222
- }
1223
-
1224
- // ── opencode event pump handlers ───────────────────────────────────────
1225
-
1226
- private async handleEvent(ev: FacadeEvent): Promise<void> {
1227
- if (ev.type === "session.created") {
1228
- if (this.sessions.has(ev.sessionID)) return;
1229
- // Deferred registration: a concurrent `createSession` may still be
1230
- // resolving for this opencode session under a client-chosen channel;
1231
- // the grace + existence check avoids the double registration, and
1232
- // the delete+recreate remap in `handleCreateSession` heals the slow
1233
- // path.
1234
- const sessionID = ev.sessionID;
1235
- setTimeout(() => {
1236
- void this.registerExternalDeferred(sessionID).catch((err) =>
1237
- this.log(`external session registration failed: ${errorMessage(err)}`),
1238
- );
1239
- }, EXTERNAL_REGISTER_GRACE_MS);
1240
- return;
1241
- }
1242
-
1243
- const rec = this.sessions.get(ev.sessionID);
1244
- if (rec === undefined) return; // only session.created registers sessions
1245
-
1246
- const chatURI = chatChannelURI(rec.sessionID);
1247
- switch (ev.type) {
1248
- case "session.deleted":
1249
- this.removeRecord(rec);
1250
- return;
1251
- case "session.renamed":
1252
- this.publish({ channel: rec.channel, action: { type: ActionType.SessionTitleChanged, title: ev.title } });
1253
- return;
1254
- case "inbox.enqueued":
1255
- rec.lastInbox = { text: ev.text, delivery: ev.delivery };
1256
- return;
1257
- case "inbox.delivered":
1258
- // Steering consumption is handled at turn end (finishTurn).
1259
- return;
1260
- case "execution.started":
1261
- if (rec.currentTurnId !== null) return; // write-ahead already claimed the turn
1262
- // Orphan turn (an external TUI prompt, or a handoff this host did
1263
- // not initiate): start it with the last-seen inbox message.
1264
- this.startTurn(rec, rec.lastInbox !== null ? userMessage(rec.lastInbox.text) : userMessage(""));
1265
- return;
1266
- case "execution.succeeded":
1267
- if (rec.currentTurnId === null) return;
1268
- this.publish({
1269
- channel: chatURI,
1270
- action: { type: ActionType.ChatTurnComplete, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
1271
- });
1272
- await this.finishTurn(rec);
1273
- return;
1274
- case "execution.failed":
1275
- if (rec.currentTurnId === null) return;
1276
- const part: ErrorResponsePart = {
1277
- kind: ResponsePartKind.Error,
1278
- error: { errorType: ev.error.type, message: ev.error.message },
1279
- };
1280
- this.publish({
1281
- channel: chatURI,
1282
- action: { type: ActionType.ChatError, turnId: rec.currentTurnId, duration: this.turnDuration(rec), part },
1283
- });
1284
- await this.finishTurn(rec);
1285
- return;
1286
- case "execution.interrupted":
1287
- // Skipped when the client's own `chat/turnCancelled` echo already
1288
- // finalized the turn (currentTurnId is null).
1289
- if (rec.currentTurnId === null) return;
1290
- this.publish({
1291
- channel: chatURI,
1292
- action: { type: ActionType.ChatTurnCancelled, turnId: rec.currentTurnId, duration: this.turnDuration(rec) },
1293
- });
1294
- await this.finishTurn(rec);
1295
- return;
1296
- case "step.started":
1297
- rec.turnModelRef = `${ev.model.providerID}/${ev.model.modelID}`;
1298
- return;
1299
- case "text.delta":
1300
- case "reasoning.delta": {
1301
- if (rec.currentTurnId === null) return;
1302
- const kind = ev.type === "text.delta" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
1303
- const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
1304
- const first = !rec.parts.has(key);
1305
- rec.parts.add(key);
1306
- const partId = `part-${key}`;
1307
- if (first) {
1308
- // Lazily emit the part on the first delta; it carries the
1309
- // initial content.
1310
- this.publish({
1311
- channel: chatURI,
1312
- action: {
1313
- type: ActionType.ChatResponsePart,
1314
- turnId: rec.currentTurnId,
1315
- part: { kind, id: partId, content: ev.delta },
1316
- },
1317
- });
1318
- } else {
1319
- this.publish({
1320
- channel: chatURI,
1321
- action:
1322
- kind === ResponsePartKind.Markdown
1323
- ? { type: ActionType.ChatDelta, turnId: rec.currentTurnId, partId, content: ev.delta }
1324
- : { type: ActionType.ChatReasoning, turnId: rec.currentTurnId, partId, content: ev.delta },
1325
- });
1326
- }
1327
- return;
1328
- }
1329
- case "text.ended":
1330
- case "reasoning.ended": {
1331
- if (rec.currentTurnId === null) return;
1332
- // Fallback for non-streaming providers that emit only the final
1333
- // text: if no delta opened the part, emit it now with the full text.
1334
- const kind = ev.type === "text.ended" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
1335
- const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
1336
- if (!rec.parts.has(key)) {
1337
- rec.parts.add(key);
1338
- this.publish({
1339
- channel: chatURI,
1340
- action: {
1341
- type: ActionType.ChatResponsePart,
1342
- turnId: rec.currentTurnId,
1343
- part: { kind, id: `part-${key}`, content: ev.text },
1344
- },
1345
- });
1346
- }
1347
- return;
1348
- }
1349
- case "tool.input.started":
1350
- if (rec.currentTurnId === null) {
1351
- this.log(`tool.input.started outside a turn (session ${rec.sessionID}, tool ${ev.name}); ignored`);
1352
- return;
1353
- }
1354
- rec.toolName.set(ev.id, ev.name);
1355
- this.publish({
1356
- channel: chatURI,
1357
- action: {
1358
- type: ActionType.ChatToolCallStart,
1359
- turnId: rec.currentTurnId,
1360
- toolCallId: ev.id,
1361
- toolName: ev.name,
1362
- displayName: displayNameFor(ev.name),
1363
- },
1364
- });
1365
- return;
1366
- case "tool.input.ended":
1367
- rec.toolInput.set(ev.id, ev.text);
1368
- // Phase 2: for file-mutating tools, capture the pre-edit file
1369
- // content now (the event fires before execution — the last safe
1370
- // point). Awaited in the sequential pump so the capture is
1371
- // complete before `execution.*` can end the turn.
1372
- if (this.opts.changesets) await this.captureTurnBefore(rec, ev.id, ev.text);
1373
- return;
1374
- case "tool.progress":
1375
- // First sign the tool is actually running (opencode auto-approved):
1376
- // finalize the tool call as running.
1377
- this.ensureToolReady(rec, ev.id, false);
1378
- return;
1379
- case "tool.success": {
1380
- if (rec.currentTurnId === null) return;
1381
- this.ensureToolReady(rec, ev.id, false);
1382
- if (this.toolCallTerminal(rec, ev.id)) return; // e.g. denied → already cancelled
1383
- const name = rec.toolName.get(ev.id) ?? "tool";
1384
- const input = rec.toolInput.get(ev.id);
1385
- this.publish({
1386
- channel: chatURI,
1387
- action: {
1388
- type: ActionType.ChatToolCallComplete,
1389
- turnId: rec.currentTurnId,
1390
- toolCallId: ev.id,
1391
- result: {
1392
- success: true,
1393
- pastTenseMessage: pastTenseMessageFor(name, input),
1394
- content: mapToolResultContent(ev.content),
1395
- },
1396
- },
1397
- });
1398
- this.clearToolTracking(rec, ev.id);
1399
- return;
1400
- }
1401
- case "tool.failed": {
1402
- if (rec.currentTurnId === null) return;
1403
- this.ensureToolReady(rec, ev.id, false);
1404
- if (this.toolCallTerminal(rec, ev.id)) return;
1405
- const name = rec.toolName.get(ev.id) ?? "tool";
1406
- const input = rec.toolInput.get(ev.id);
1407
- this.publish({
1408
- channel: chatURI,
1409
- action: {
1410
- type: ActionType.ChatToolCallComplete,
1411
- turnId: rec.currentTurnId,
1412
- toolCallId: ev.id,
1413
- result: {
1414
- success: false,
1415
- pastTenseMessage: pastTenseMessageFor(name, input),
1416
- error: { message: ev.error.message },
1417
- },
1418
- },
1419
- });
1420
- this.clearToolTracking(rec, ev.id);
1421
- return;
1422
- }
1423
- case "usage.updated":
1424
- // Session-cumulative tokens; the chat reducer replaces the turn's
1425
- // usage, so the latest cumulative values are the turn's view.
1426
- if (rec.currentTurnId === null) return;
1427
- this.publish({
1428
- channel: chatURI,
1429
- action: {
1430
- type: ActionType.ChatUsage,
1431
- turnId: rec.currentTurnId,
1432
- usage: {
1433
- inputTokens: ev.tokens.input,
1434
- outputTokens: ev.tokens.output,
1435
- cacheReadTokens: ev.tokens.cache.read,
1436
- ...(rec.turnModelRef !== null ? { model: rec.turnModelRef } : {}),
1437
- },
1438
- },
1439
- });
1440
- return;
1441
- case "permission.asked":
1442
- // Only tool-sourced permissions map to a tool confirmation;
1443
- // anything else has no AHP counterpart in this MVP (gap).
1444
- if (ev.source === undefined) {
1445
- this.log(`ignoring non-tool permission.asked ${ev.id} (action: ${ev.action})`);
1446
- return;
1447
- }
1448
- const toolCallId = ev.source.id;
1449
- rec.permissionForTool.set(toolCallId, ev.id);
1450
- rec.toolForPermission.set(ev.id, toolCallId);
1451
- this.ensureToolReady(rec, toolCallId, true);
1452
- const pending = this.pendingToolCall(rec, toolCallId);
1453
- if (pending !== null && rec.currentTurnId !== null) {
1454
- const request: SessionToolConfirmationRequest = {
1455
- id: toolCallId,
1456
- chat: chatURI,
1457
- kind: SessionInputRequestKind.ToolConfirmation,
1458
- turnId: rec.currentTurnId,
1459
- toolCall: pending,
1460
- };
1461
- this.publish({
1462
- channel: rec.channel,
1463
- action: { type: ActionType.SessionInputNeededSet, request },
1464
- });
1465
- }
1466
- return;
1467
- case "permission.replied": {
1468
- const toolCallId = rec.toolForPermission.get(ev.requestID);
1469
- rec.toolForPermission.delete(ev.requestID);
1470
- if (toolCallId !== undefined) {
1471
- rec.permissionForTool.delete(toolCallId);
1472
- // Safety net: the client's `chat/toolCallConfirmed` normally
1473
- // removes the input request first; this covers the reply
1474
- // arriving without (or before) the echo.
1475
- this.publish({
1476
- channel: rec.channel,
1477
- action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
1478
- });
1479
- }
1480
- return;
1481
- }
1482
- default:
1483
- return;
1484
- }
1485
- }
1486
-
1487
- // ── turn helpers ───────────────────────────────────────────────────────
1488
-
1489
- private mintTurnId(): string {
1490
- this.turnCounter += 1;
1491
- return `turn_${Date.now().toString(36)}_${this.turnCounter.toString(36)}`;
1492
- }
1493
-
1494
- private turnDuration(rec: SessionRecord): number {
1495
- return Math.max(0, Date.now() - (rec.turnStartedAt ?? Date.now()));
1496
- }
1497
-
1498
- /** Claim a turn (write-ahead) and publish `chat/turnStarted`. */
1499
- private startTurn(rec: SessionRecord, message: Message, queuedMessageId?: string): void {
1500
- const turnId = this.mintTurnId();
1501
- rec.currentTurnId = turnId;
1502
- rec.turnStartedAt = Date.now();
1503
- this.publish({
1504
- channel: chatChannelURI(rec.sessionID),
1505
- action: {
1506
- type: ActionType.ChatTurnStarted,
1507
- turnId,
1508
- startedAt: new Date().toISOString(),
1509
- message,
1510
- ...(queuedMessageId !== undefined ? { queuedMessageId } : {}),
1511
- },
1512
- });
1513
- }
1514
-
1515
- /**
1516
- * After a turn terminal: clear the steering message opencode consumed
1517
- * during the turn, and auto-start the next turn from the queue (the
1518
- * queued prompt was already sent with `delivery: "queue"` — opencode
1519
- * starts it automatically; this only updates the AHP state).
1520
- *
1521
- * Phase 2: then refresh the session's changesets — the turn's captured
1522
- * "after" content is read from disk here, and the uncommitted/session/
1523
- * turn changesets recompute (async: awaits the facade).
1524
- */
1525
- private async finishTurn(rec: SessionRecord): Promise<void> {
1526
- const endedTurnId = rec.currentTurnId;
1527
- rec.currentTurnId = null;
1528
- rec.turnStartedAt = null;
1529
- const state = rec.chatStore.state;
1530
- if (state.steeringMessage !== undefined) {
1531
- this.publish({
1532
- channel: chatChannelURI(rec.sessionID),
1533
- action: {
1534
- type: ActionType.ChatPendingMessageRemoved,
1535
- kind: PendingMessageKind.Steering,
1536
- id: state.steeringMessage.id,
1537
- },
1538
- });
1539
- }
1540
- const queued = state.queuedMessages;
1541
- if (queued !== undefined && queued.length > 0) {
1542
- const next = queued[0]!;
1543
- this.startTurn(rec, next.message, next.id);
1544
- } else if (rec.lastInbox !== null && rec.lastInbox.delivery === "queue") {
1545
- // A queued prompt from outside AHP (e.g. the TUI).
1546
- this.startTurn(rec, userMessage(rec.lastInbox.text));
1547
- }
1548
- if (this.opts.changesets && endedTurnId !== null) {
1549
- await this.refreshTurnChangesets(rec, endedTurnId);
1550
- }
1551
- }
1552
-
1553
- // ── Phase 2: changesets ────────────────────────────────────────────────
1554
-
1555
- /**
1556
- * Capture the pre-edit content of a file-mutating tool's target file for
1557
- * the current turn's changeset (first capture per file wins — the
1558
- * pre-turn content survives later edits in the same turn). No-op when
1559
- * the tool is not file-mutating, the input carries no parseable path,
1560
- * or the path resolves outside the location directory.
1561
- */
1562
- private async captureTurnBefore(rec: SessionRecord, toolCallId: string, inputJson: string): Promise<void> {
1563
- const turnId = rec.currentTurnId;
1564
- const toolName = rec.toolName.get(toolCallId);
1565
- if (turnId === null || toolName === undefined || !SNAPSHOT_TOOLS.has(toolName)) return;
1566
- let parsed: unknown;
1567
- try {
1568
- parsed = JSON.parse(inputJson);
1569
- } catch {
1570
- return;
1571
- }
1572
- if (!isRecord(parsed)) return;
1573
- const rawPath = SNAPSHOT_PATH_KEYS.map((k) => parsed[k]).find((v) => typeof v === "string" && (v as string).length > 0);
1574
- if (typeof rawPath !== "string") return;
1575
- const absPath = this.resolveSnapshotPath(rawPath);
1576
- if (absPath === null) {
1577
- this.log(`turn snapshot: ${toolName} target ${rawPath} is outside the location directory; not captured`);
1578
- return;
1579
- }
1580
- let before: string | null;
1581
- try {
1582
- before = await this.opts.facade.readFile(absPath);
1583
- } catch (err) {
1584
- this.log(`turn snapshot: read of ${absPath} failed: ${errorMessage(err)}`);
1585
- return;
1586
- }
1587
- // The pump is sequential, so the turn cannot have ended between the
1588
- // call and the await — but the record may be gone (session deleted).
1589
- if (rec.currentTurnId !== turnId || !this.sessions.has(rec.sessionID)) return;
1590
- const turnFiles = rec.turnSnapshots.get(turnId) ?? new Map();
1591
- if (!turnFiles.has(absPath)) turnFiles.set(absPath, { before, after: null });
1592
- rec.turnSnapshots.set(turnId, turnFiles);
1593
- }
1594
-
1595
- /** Resolve a tool-input path against the location directory (must stay inside it). */
1596
- private resolveSnapshotPath(rawPath: string): string | null {
1597
- const dir = this.opts.defaultDirectory;
1598
- if (dir === undefined) return null;
1599
- const absPath = resolvePath(dir, rawPath);
1600
- return isPathInside(absPath, dir) ? absPath : null;
1601
- }
1602
-
1603
- /** Get-or-create the changeset store for a URI (fresh stores start computing). */
1604
- private changesetStore(rec: SessionRecord, uri: string): ChangesetStateStore {
1605
- let store = rec.changesets.get(uri);
1606
- if (store === undefined) {
1607
- store = createChangesetStateStore({ status: ChangesetStatus.Computing, files: [] });
1608
- rec.changesets.set(uri, store);
1609
- }
1610
- return store;
1611
- }
1612
-
1613
- /** The store's current per-file review flags, keyed by file id. */
1614
- private reviewedById(store: ChangesetStateStore): Map<string, boolean> {
1615
- const out = new Map<string, boolean>();
1616
- for (const f of store.state.files) {
1617
- if (typeof f.reviewed === "boolean") out.set(f.id, f.reviewed);
1618
- }
1619
- return out;
1620
- }
1621
-
1622
- /**
1623
- * Recompute one changeset and publish the delta (gateway's
1624
- * `updateChangesetChannel` pattern): `changeset/contentChanged` when the
1625
- * file list changed (the discard operation is (re)attached while files
1626
- * exist, and cleared when they vanish), then `changeset/statusChanged`
1627
- * to ready when the status was not ready. A failed computation publishes
1628
- * `changeset/statusChanged` with an error.
1629
- */
1630
- private async refreshChangeset(rec: SessionRecord, uri: string): Promise<void> {
1631
- const parsed = parseChangesetChannel(uri);
1632
- if (parsed === null) return;
1633
- const store = this.changesetStore(rec, uri);
1634
- let files;
1635
- try {
1636
- if (parsed.kind === "turn") {
1637
- files = buildTurnChangesetFiles({
1638
- sessionID: parsed.sessionID,
1639
- turnId: parsed.turnId ?? "",
1640
- files: rec.turnSnapshots.get(parsed.turnId ?? "") ?? new Map(),
1641
- reviewedById: this.reviewedById(store),
1642
- });
1643
- } else {
1644
- const diffs = await this.opts.facade.vcsDiffWorking();
1645
- files = buildWorkingChangesetFiles({ diffs, reviewedById: this.reviewedById(store) });
1646
- }
1647
- } catch (err) {
1648
- this.publish({
1649
- channel: uri,
1650
- action: {
1651
- type: ActionType.ChangesetStatusChanged,
1652
- status: ChangesetStatus.Error,
1653
- error: { errorType: "changeset-computation", message: errorMessage(err) },
1654
- },
1655
- });
1656
- return;
1657
- }
1658
- const state = store.state;
1659
- const hadFiles = state.files.length > 0;
1660
- const hasFiles = files.length > 0;
1661
- if (JSON.stringify(state.files) !== JSON.stringify(files)) {
1662
- this.publish({
1663
- channel: uri,
1664
- action: {
1665
- type: ActionType.ChangesetContentChanged,
1666
- files,
1667
- ...(hasFiles ? { operations: [discardOperation()] } : {}),
1668
- },
1669
- });
1670
- // operations persist across contentChanged — clear them explicitly
1671
- // when the changeset empties out.
1672
- if (!hasFiles && state.operations !== undefined && state.operations.length > 0) {
1673
- this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: undefined } });
1674
- }
1675
- }
1676
- if (!hadFiles && hasFiles && state.operations === undefined) {
1677
- // contentChanged above already attached the operation; this branch
1678
- // is unreachable unless the reducer drops it — kept as a guard.
1679
- this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: [discardOperation()] } });
1680
- }
1681
- if (state.status !== ChangesetStatus.Ready) {
1682
- this.publish({ channel: uri, action: { type: ActionType.ChangesetStatusChanged, status: ChangesetStatus.Ready } });
1683
- }
1684
- }
1685
-
1686
- /**
1687
- * At a turn terminal: read the disk into each captured file's `after`
1688
- * (a file deleted during the turn stays null → "deleted"), then refresh
1689
- * the uncommitted, session, and ended-turn changesets — only the ones a
1690
- * client has subscribed (unsubscribed changesets cost no seq).
1691
- */
1692
- private async refreshTurnChangesets(rec: SessionRecord, turnId: string): Promise<void> {
1693
- const turnFiles = rec.turnSnapshots.get(turnId);
1694
- if (turnFiles !== undefined) {
1695
- for (const [absPath, snap] of turnFiles) {
1696
- if (snap.after === null) {
1697
- try {
1698
- snap.after = await this.opts.facade.readFile(absPath);
1699
- } catch {
1700
- snap.after = null;
1701
- }
1702
- }
1703
- }
1704
- }
1705
- for (const uri of [
1706
- uncommittedChangesetURI(rec.sessionID),
1707
- sessionChangesetURI(rec.sessionID),
1708
- turnChangesetURI(rec.sessionID, turnId),
1709
- ]) {
1710
- if (rec.changesets.has(uri)) await this.refreshChangeset(rec, uri);
1711
- }
1712
- }
1713
-
1714
- /**
1715
- * `resourceRead` (AHP root command): serve file content for the URIs
1716
- * this host advertises in changesets —
1717
- * - `file://` → live disk, confined to the location directory;
1718
- * - `ahp-content://head/…` → the file's HEAD content;
1719
- * - `ahp-content://snap/…` → a turn's captured before/after content.
1720
- * Errors: -32008 (not found), -32009 (path outside the location).
1721
- */
1722
- private async handleResourceRead(socketId: number, msg: RpcMessage): Promise<void> {
1723
- const params = isRecord(msg.params) ? msg.params : {};
1724
- const uri = params["uri"];
1725
- if (typeof uri !== "string" || uri.length === 0) {
1726
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resourceRead requires a content URI");
1727
- return;
1728
- }
1729
- const encoding: "base64" | "utf-8" = params["encoding"] === "utf-8" ? "utf-8" : "base64";
1730
- if (uri.startsWith("file://")) {
1731
- let absPath: string;
1732
- try {
1733
- absPath = fileURLToPath(uri);
1734
- } catch {
1735
- this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
1736
- return;
1737
- }
1738
- if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
1739
- this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
1740
- return;
1741
- }
1742
- let content: string | null;
1743
- try {
1744
- content = await this.opts.facade.readFile(absPath);
1745
- } catch (err) {
1746
- this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, `read failed: ${errorMessage(err)}`);
1747
- return;
1748
- }
1749
- if (content === null) {
1750
- this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
1751
- return;
1752
- }
1753
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
1754
- return;
1755
- }
1756
- // Opaque content refs require the changesets capability.
1757
- if (!this.opts.changesets) {
1758
- this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
1759
- return;
1760
- }
1761
- const ref = parseContentRef(uri);
1762
- if (ref === null) {
1763
- this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
1764
- return;
1765
- }
1766
- if (ref.kind === "head") {
1767
- if (this.opts.defaultDirectory !== undefined && !isPathInside(ref.path, this.opts.defaultDirectory)) {
1768
- this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
1769
- return;
1770
- }
1771
- let content: string | null;
1772
- try {
1773
- content = await this.opts.facade.gitHeadFile(ref.path);
1774
- } catch (err) {
1775
- this.sendError(socketId, msg.id, ERROR_INTERNAL, `HEAD read failed: ${errorMessage(err)}`);
1776
- return;
1777
- }
1778
- if (content === null) {
1779
- this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not in HEAD: ${ref.path}`);
1780
- return;
1781
- }
1782
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
1783
- return;
1784
- }
1785
- // snap — in-memory turn snapshot of a live session.
1786
- const rec = this.sessions.get(ref.sessionID);
1787
- if (rec === undefined) {
1788
- this.sendError(socketId, msg.id, ERROR_NOT_FOUND, "no such session");
1789
- return;
1790
- }
1791
- const snap = rec.turnSnapshots.get(ref.turnId)?.get(ref.path);
1792
- const content = snap === undefined ? null : ref.part === "before" ? snap.before : snap.after;
1793
- if (content === null) {
1794
- this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
1795
- return;
1796
- }
1797
- this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
1798
- }
1799
-
1800
- /** Encode content for a `resourceRead` result (utf-8 or base64). */
1801
- private encodeContent(content: string, encoding: "base64" | "utf-8") {
1802
- return {
1803
- data: encoding === "utf-8" ? content : Buffer.from(content, "utf-8").toString("base64"),
1804
- encoding,
1805
- };
1806
- }
1807
-
1808
- /**
1809
- * `invokeChangesetOperation`: the host's only operation is
1810
- * `discard-changes` (resource-scoped) — restore one file from the
1811
- * changeset's "before" content. Status flows through the
1812
- * `changeset/operationStatusChanged` stream; the JSON-RPC result carries
1813
- * a human-readable message.
1814
- */
1815
- private async handleInvokeChangesetOperation(socketId: number, msg: RpcMessage): Promise<void> {
1816
- const params = isRecord(msg.params) ? msg.params : {};
1817
- const channel = params["channel"];
1818
- const operationId = params["operationId"];
1819
- if (typeof channel !== "string" || channel.length === 0 || typeof operationId !== "string" || operationId.length === 0) {
1820
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "invokeChangesetOperation requires channel + operationId");
1821
- return;
1822
- }
1823
- const parsed = parseChangesetChannel(channel);
1824
- if (parsed === null) {
1825
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `not a changeset channel: ${channel}`);
1826
- return;
1827
- }
1828
- const rec = this.sessions.get(parsed.sessionID);
1829
- if (rec === undefined) {
1830
- this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, "no such session");
1831
- return;
1832
- }
1833
- const store = rec.changesets.get(channel);
1834
- if (store === undefined) {
1835
- this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such changeset: ${channel}`);
1836
- return;
1837
- }
1838
- const op = store.state.operations?.find((o) => o.id === operationId);
1839
- if (op === undefined) {
1840
- this.sendError(socketId, msg.id, ERROR_METHOD_NOT_FOUND, `unknown operation: ${operationId}`);
1841
- return;
1842
- }
1843
- if (!op.scopes.includes(ChangesetOperationScope.Resource)) {
1844
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `operation ${operationId} is not resource-scoped`);
1845
- return;
1846
- }
1847
- const target = params["target"];
1848
- if (!isRecord(target) || target["kind"] !== "resource" || typeof target["resource"] !== "string") {
1849
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resource-scoped operation requires a resource target");
1850
- return;
1851
- }
1852
- let absPath: string;
1853
- try {
1854
- absPath = fileURLToPath(target["resource"] as string);
1855
- } catch {
1856
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "target.resource must be a file URI");
1857
- return;
1858
- }
1859
- if (!store.state.files.some((f) => f.id === fileUri(absPath))) {
1860
- this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `no such file in changeset: ${target["resource"]}`);
1861
- return;
1862
- }
1863
- if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
1864
- this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
1865
- return;
1866
- }
1867
- this.publish({
1868
- channel,
1869
- action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Running },
1870
- });
1871
- try {
1872
- if (parsed.kind === "turn" && parsed.turnId !== undefined) {
1873
- await this.restoreTurnFile(rec, parsed.turnId, absPath);
1874
- } else {
1875
- await this.opts.facade.discardFile(absPath);
1876
- }
1877
- } catch (err) {
1878
- this.publish({
1879
- channel,
1880
- action: {
1881
- type: ActionType.ChangesetOperationStatusChanged,
1882
- operationId,
1883
- status: ChangesetOperationStatus.Error,
1884
- error: { errorType: "operation-failed", message: errorMessage(err) },
1885
- },
1886
- });
1887
- this.sendError(socketId, msg.id, ERROR_INTERNAL, errorMessage(err));
1888
- return;
1889
- }
1890
- await this.refreshChangeset(rec, channel);
1891
- this.publish({
1892
- channel,
1893
- action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Idle },
1894
- });
1895
- this.sendFrame(socketId, {
1896
- jsonrpc: "2.0",
1897
- id: msg.id ?? null,
1898
- result: { message: `Discarded changes to ${absPath}` },
1899
- });
1900
- }
1901
-
1902
- /**
1903
- * Restore one file from a turn's before-snapshot: the file was added by
1904
- * the turn (before === null) → delete it; otherwise write the pre-edit
1905
- * content back.
1906
- */
1907
- private async restoreTurnFile(rec: SessionRecord, turnId: string, absPath: string): Promise<void> {
1908
- const snap = rec.turnSnapshots.get(turnId)?.get(absPath);
1909
- const before = snap?.before ?? null;
1910
- if (before === null) {
1911
- await this.opts.facade.deleteFile(absPath);
1912
- } else {
1913
- await this.opts.facade.writeFile(absPath, before);
1914
- }
1915
- }
1916
-
1917
- /**
1918
- * Lazily publish `chat/toolCallReady` for a tool call (first of
1919
- * progress/success/failed/permission.asked):
1920
- * - permission trigger → no `confirmed` → the reducer parks it in
1921
- * `pending-confirmation` (the caller then raises `inputNeededSet`);
1922
- * - otherwise → `confirmed: "not-needed"` → straight to `running`
1923
- * (opencode auto-approved).
1924
- */
1925
- private ensureToolReady(rec: SessionRecord, toolCallId: string, permission: boolean): void {
1926
- if (rec.toolReady.has(toolCallId) || rec.currentTurnId === null) return;
1927
- rec.toolReady.add(toolCallId);
1928
- const name = rec.toolName.get(toolCallId) ?? "tool";
1929
- const input = rec.toolInput.get(toolCallId);
1930
- this.publish({
1931
- channel: chatChannelURI(rec.sessionID),
1932
- action: {
1933
- type: ActionType.ChatToolCallReady,
1934
- turnId: rec.currentTurnId,
1935
- toolCallId,
1936
- invocationMessage: invocationMessageFor(name, input),
1937
- toolInput: input,
1938
- ...(permission ? {} : { confirmed: ToolCallConfirmationReason.NotNeeded }),
1939
- },
1940
- });
1941
- }
1942
-
1943
- /** The live tool-call state in the current turn, or null when absent. */
1944
- private toolCallState(rec: SessionRecord, toolCallId: string): ToolCallState | null {
1945
- const turn = rec.chatStore.state.activeTurn;
1946
- if (turn === undefined) return null;
1947
- for (const part of turn.responseParts) {
1948
- if (part.kind === ResponsePartKind.ToolCall && part.toolCall.toolCallId === toolCallId) {
1949
- return part.toolCall;
1950
- }
1951
- }
1952
- return null;
1953
- }
1954
-
1955
- /**
1956
- * The tool call's state when it is awaiting confirmation (the
1957
- * `SessionToolConfirmationRequest.toolCall` shape), or null otherwise.
1958
- */
1959
- private pendingToolCall(rec: SessionRecord, toolCallId: string): ToolCallConfirmationState | null {
1960
- const tc = this.toolCallState(rec, toolCallId);
1961
- if (tc === null) return null;
1962
- if (tc.status === ToolCallStatus.PendingConfirmation || tc.status === ToolCallStatus.PendingResultConfirmation) {
1963
- return tc;
1964
- }
1965
- return null;
1966
- }
1967
-
1968
- /** True when the tool call already left the ready states (completed/cancelled). */
1969
- private toolCallTerminal(rec: SessionRecord, toolCallId: string): boolean {
1970
- const tc = this.toolCallState(rec, toolCallId);
1971
- return tc !== null && (tc.status === ToolCallStatus.Completed || tc.status === ToolCallStatus.Cancelled);
1972
- }
1973
-
1974
- private clearToolTracking(rec: SessionRecord, toolCallId: string): void {
1975
- rec.toolInput.delete(toolCallId);
1976
- rec.toolName.delete(toolCallId);
1977
- rec.toolReady.delete(toolCallId);
1978
- }
1979
-
1980
- // ── session registration / removal ─────────────────────────────────────
1981
-
1982
- /**
1983
- * Verify a `session.created` event via the session API and register the
1984
- * session under its own id as the channel suffix (the suffix starts
1985
- * with "ses" — opencode ids are valid suffixes). No-op when the session
1986
- * is gone, already registered, or a createSession remap is pending.
1987
- */
1988
- private async registerExternalDeferred(sessionID: string): Promise<void> {
1989
- if (this.sessions.has(sessionID)) return;
1990
- let fs: FacadeSession | null;
1991
- try {
1992
- fs = await this.opts.facade.getSession(sessionID);
1993
- } catch {
1994
- return;
1995
- }
1996
- if (fs === null || this.sessions.has(fs.sessionID)) return;
1997
- this.registerExternal(fs);
1998
- }
1999
-
2000
- /**
2001
- * Register an opencode session the host did not create (TUI, another
2002
- * client). Applied directly to the fresh stores (no seq, no actions) —
2003
- * the registration is server-side bookkeeping, not a client-visible
2004
- * state transition; the root announcement carries the lifecycle.
2005
- */
2006
- private registerExternal(fs: FacadeSession): SessionRecord | undefined {
2007
- const existing = this.sessions.get(fs.sessionID);
2008
- if (existing !== undefined) return existing;
2009
- const channel = sessionChannelURI(fs.sessionID);
2010
- const modifiedAt = new Date(fs.time.updated).toISOString();
2011
- const sessionStore = createSessionStateStore(
2012
- initialSessionState({
2013
- sessionID: fs.sessionID,
2014
- provider: fs.model?.providerID ?? "opencode",
2015
- title: fs.title ?? "New Session",
2016
- status: fs.archived
2017
- ? ((SessionStatus.Idle | SessionStatus.IsRead | SessionStatus.IsArchived) as SessionStatus)
2018
- : undefined, // Idle | IsRead | IsArchived
2019
- }),
2020
- );
2021
- const chatStore = createChatStateStore(
2022
- initialChatState({ resource: chatChannelURI(fs.sessionID), title: "Chat 1", modifiedAt }),
2023
- );
2024
- sessionStore.apply({ type: ActionType.SessionReady });
2025
- sessionStore.apply({ type: ActionType.SessionChatAdded, summary: chatSummaryOf(chatStore.state) });
2026
- sessionStore.apply({ type: ActionType.SessionDefaultChatChanged, defaultChat: chatChannelURI(fs.sessionID) });
2027
- // Phase 2: advertise the changeset catalogues directly on the fresh
2028
- // stores (registration is server-side bookkeeping — no seq, no actions).
2029
- if (this.opts.changesets) {
2030
- sessionStore.apply({ type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(fs.sessionID) });
2031
- chatStore.apply({ type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(fs.sessionID) });
2032
- }
2033
- const rec: SessionRecord = {
2034
- sessionID: fs.sessionID,
2035
- channel,
2036
- provider: sessionStore.state.provider,
2037
- createdAt: new Date(fs.time.created).toISOString(),
2038
- modifiedAt,
2039
- sessionStore,
2040
- chatStore,
2041
- currentTurnId: null,
2042
- turnStartedAt: null,
2043
- turnModelRef: null,
2044
- parts: new Set(),
2045
- toolInput: new Map(),
2046
- toolName: new Map(),
2047
- toolReady: new Set(),
2048
- permissionForTool: new Map(),
2049
- toolForPermission: new Map(),
2050
- lastInbox: null,
2051
- changesets: new Map(),
2052
- turnSnapshots: new Map(),
2053
- };
2054
- this.sessions.set(fs.sessionID, rec);
2055
- this.byChannel.set(channel, rec);
2056
- this.byChannel.set(chatChannelURI(fs.sessionID), rec);
2057
- this.channels.addSession(fs.sessionID);
2058
- this.publish({
2059
- channel: ROOT_CHANNEL,
2060
- action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
2061
- });
2062
- this.notifyRoot("root/sessionAdded", { channel: ROOT_CHANNEL, summary: this.sessionSummary(rec) });
2063
- return rec;
2064
- }
2065
-
2066
- /** Drop a session record and announce the removal on the root channel. */
2067
- private removeRecord(rec: SessionRecord): void {
2068
- // Phase 2: every live changeset URI is about to become un-subscribable —
2069
- // dispatch `changeset/cleared` (protocol case 2) before the teardown so
2070
- // subscribers release their references.
2071
- for (const uri of rec.changesets.keys()) {
2072
- this.publish({ channel: uri, action: { type: ActionType.ChangesetCleared } });
2073
- }
2074
- rec.changesets.clear();
2075
- rec.turnSnapshots.clear();
2076
- this.sessions.delete(rec.sessionID);
2077
- this.byChannel.delete(rec.channel);
2078
- this.byChannel.delete(chatChannelURI(rec.sessionID));
2079
- const id = sessionIDOf(rec.channel);
2080
- if (id !== null) this.channels.removeSession(id);
2081
- this.channels.removeSession(rec.sessionID);
2082
- this.publish({
2083
- channel: ROOT_CHANNEL,
2084
- action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
2085
- });
2086
- this.notifyRoot("root/sessionRemoved", { channel: ROOT_CHANNEL, session: rec.channel });
2087
- }
2088
-
2089
- // ── state / publishing ─────────────────────────────────────────────────
2090
-
2091
- /**
2092
- * Snapshot for a channel URI, or null when the channel is not
2093
- * subscribable right now.
2094
- *
2095
- * Root snapshots re-derive the catalog from the facade on every call
2096
- * (registry reads reflect every registration so far; in-process reads
2097
- * are cheap). Session/chat snapshots read the official-reducer stores.
2098
- */
2099
- private async snapshotFor(uri: string): Promise<Snapshot | null> {
2100
- const kind = channelKind(uri);
2101
- if (kind === "unknown") return null;
2102
- if (kind === "changeset") {
2103
- if (!this.opts.changesets) return null;
2104
- const parsed = parseChangesetChannel(uri);
2105
- if (parsed === null) return null;
2106
- const rec = this.sessions.get(parsed.sessionID);
2107
- if (rec === undefined) return null;
2108
- const store = this.changesetStore(rec, uri);
2109
- // First subscribe (or a failed computation) triggers the computation;
2110
- // subsequent subscribes return the last completed state.
2111
- if (store.state.status === ChangesetStatus.Computing || store.state.status === ChangesetStatus.Error) {
2112
- await this.refreshChangeset(rec, uri);
2113
- }
2114
- return { resource: uri, state: store.state, fromSeq: this.seq.seq };
2115
- }
2116
- if (kind !== "root") {
2117
- const rec = this.byChannel.get(uri);
2118
- if (rec === undefined) return null;
2119
- if (uri === rec.channel) {
2120
- return { resource: uri, state: rec.sessionStore.state, fromSeq: this.seq.seq };
2121
- }
2122
- if (uri === chatChannelURI(rec.sessionID)) {
2123
- return { resource: uri, state: rec.chatStore.state, fromSeq: this.seq.seq };
2124
- }
2125
- return null;
2126
- }
2127
- const [providers, agents] = await Promise.all([
2128
- this.opts.facade.listCatalog(),
2129
- this.opts.facade.listAgents(),
2130
- ]);
2131
- const catalog = mapCatalog(providers, agents, this.opts.defaultDirectory);
2132
- if (!sameAgents(this.state.state.agents, catalog)) {
2133
- this.state.apply({ type: ActionType.RootAgentsChanged, agents: catalog });
2134
- }
2135
- return { resource: ROOT_CHANNEL, state: this.state.state, fromSeq: this.seq.seq };
2136
- }
2137
-
2138
- /** The denormalized `SessionSummary` view of a record. */
2139
- private sessionSummary(rec: SessionRecord): SessionSummary {
2140
- const s = rec.sessionStore.state;
2141
- const c = rec.chatStore.state;
2142
- const modifiedAt = c.modifiedAt > rec.modifiedAt ? c.modifiedAt : rec.modifiedAt;
2143
- return buildSessionSummary({
2144
- channel: rec.channel,
2145
- provider: rec.provider,
2146
- title: s.title,
2147
- status: s.status,
2148
- activity: s.activity,
2149
- createdAt: rec.createdAt,
2150
- modifiedAt,
2151
- chat: chatSummaryOf(c),
2152
- defaultChat: chatChannelURI(rec.sessionID),
2153
- });
2154
- }
2155
-
2156
- /**
2157
- * Assign a global seq, update state for accepted actions, retain for
2158
- * replay. Session/chat actions apply to the per-session stores through
2159
- * the official reducers; a changed chat summary is propagated to the
2160
- * session store via `session/chatUpdated`, and any summary-level change
2161
- * is announced on the root channel (notification).
2162
- */
2163
- private publish(draft: {
2164
- channel: string;
2165
- action: StateAction;
2166
- origin?: ActionOrigin;
2167
- rejectionReason?: string;
2168
- }): ActionEnvelope {
2169
- const envelope = this.seq.publish(draft);
2170
- if (draft.rejectionReason === undefined) {
2171
- const kind = channelKind(draft.channel);
2172
- if (kind === "root") {
2173
- this.state.apply(draft.action as RootAction);
2174
- } else if (kind === "changeset") {
2175
- // Changeset stores live on the record (keyed by URI), resolved
2176
- // through the parsed owner session.
2177
- const parsed = parseChangesetChannel(draft.channel);
2178
- const rec = parsed !== null ? this.sessions.get(parsed.sessionID) : undefined;
2179
- const store = rec !== undefined ? rec.changesets.get(draft.channel) : undefined;
2180
- if (store !== undefined) store.apply(draft.action as ChangesetAction);
2181
- } else {
2182
- // byChannel, not sessions.get(sessionIDOf(…)): the channel suffix
2183
- // is not always the opencode session id (client-chosen suffixes).
2184
- const rec = this.byChannel.get(draft.channel);
2185
- if (rec !== undefined) {
2186
- const before = this.sessionSummary(rec);
2187
- if (kind === "session") rec.sessionStore.apply(draft.action as SessionAction);
2188
- else rec.chatStore.apply(draft.action as ChatAction);
2189
- if (kind === "chat") this.syncChatSummary(rec);
2190
- const after = this.sessionSummary(rec);
2191
- this.maybeNotifySummaryChanged(rec, before, after);
2192
- }
2193
- }
2194
- }
2195
- // Every published action — accepted and rejected alike — is an
2196
- // `action` notification on its channel to the subscribers.
2197
- this.notifyAction(envelope);
2198
- return envelope;
2199
- }
2200
-
2201
- /**
2202
- * Propagate a changed chat summary into the session store's chat catalog
2203
- * (`session/chatUpdated`) — the session status itself is only
2204
- * reducer-reachable for read/archive/input-needed bits, so the chat
2205
- * summary is the activity source of truth.
2206
- */
2207
- private syncChatSummary(rec: SessionRecord): void {
2208
- const chat = rec.chatStore.state;
2209
- const entry = rec.sessionStore.state.chats.find((c) => c.resource === chat.resource);
2210
- if (entry === undefined) return;
2211
- const next = chatSummaryOf(chat);
2212
- const changes: Record<string, unknown> = {};
2213
- let changed = false;
2214
- for (const key of ["title", "status", "activity", "modifiedAt"] as const) {
2215
- if (entry[key] !== next[key]) {
2216
- changes[key] = next[key];
2217
- changed = true;
2218
- }
2219
- }
2220
- if (changed) {
2221
- this.publish({
2222
- channel: rec.channel,
2223
- action: { type: ActionType.SessionChatUpdated, chat: chat.resource, changes: changes as Partial<ChatSummary> },
2224
- });
2225
- }
2226
- }
2227
-
2228
- /**
2229
- * Announce summary-level changes on the root channel (`root/
2230
- * sessionSummaryChanged` notification — ephemeral, not replayed).
2231
- * Identity fields (resource/provider/createdAt) never change.
2232
- */
2233
- private maybeNotifySummaryChanged(rec: SessionRecord, before: SessionSummary, after: SessionSummary): void {
2234
- const changes: Record<string, unknown> = {};
2235
- for (const key of ["title", "status", "activity", "modifiedAt", "chats", "defaultChat"] as const) {
2236
- if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) {
2237
- changes[key] = after[key];
2238
- }
2239
- }
2240
- if (Object.keys(changes).length === 0) return;
2241
- if (after.modifiedAt > rec.modifiedAt) rec.modifiedAt = after.modifiedAt;
2242
- this.notifyRoot("root/sessionSummaryChanged", {
2243
- channel: ROOT_CHANNEL,
2244
- session: rec.channel,
2245
- changes,
2246
- });
2247
- }
2248
-
2249
- /** Send a root-channel notification frame to every root subscriber. */
2250
- private notifyRoot(method: string, params: unknown): void {
2251
- const frame = { jsonrpc: "2.0", method, params };
2252
- for (const socketId of this.channels.socketsSubscribedTo(ROOT_CHANNEL)) {
2253
- this.opts.send(socketId, frame);
2254
- }
2255
- }
2256
-
2257
- /** Send an `action` notification to every socket subscribed to the channel. */
2258
- private notifyAction(envelope: ActionEnvelope): void {
2259
- const frame = { jsonrpc: "2.0", method: "action", params: envelope };
2260
- for (const socketId of this.channels.socketsSubscribedTo(envelope.channel)) {
2261
- this.opts.send(socketId, frame);
2262
- }
2263
- }
2264
-
2265
- private sendError(socketId: number, id: unknown, code: number, message: string): void {
2266
- this.sendFrame(socketId, { jsonrpc: "2.0", id: id ?? null, error: { code, message } });
2267
- }
2268
- }
2269
-
2270
- function sameAgents(a: unknown, b: unknown): boolean {
2271
- return JSON.stringify(a) === JSON.stringify(b);
2272
- }
2273
-
2274
- function errorMessage(e: unknown): string {
2275
- return e instanceof Error ? e.message : String(e);
2276
- }
2277
-
2278
- /** Short, stable description of untrusted params for log lines. */
2279
- function describeParams(params: unknown): string {
2280
- if (!isRecord(params)) return String(typeof params);
2281
- try {
2282
- const raw = JSON.stringify(Object.keys(params));
2283
- return raw.length > 120 ? raw.slice(0, 120) + "…" : raw;
2284
- } catch {
2285
- return "unserializable";
2286
- }
2287
- }
2288
-
2289
- /** The first enabled model of a provider, as a FacadeModelRef. */
2290
- function firstEnabledModelRef(models: readonly { providerID: string; modelID: string; enabled: boolean }[]): FacadeModelRef | undefined {
2291
- const m = models.find((x) => x.enabled);
2292
- return m !== undefined ? { providerID: m.providerID, modelID: m.modelID } : undefined;
2293
- }
2294
-
2295
- /** Normalize an untrusted `activeClient` payload (untrusted JSON-RPC). */
2296
- function normalizeActiveClient(ac: Record<string, unknown>): SessionActiveClient {
2297
- const tools = Array.isArray(ac["tools"]) ? (ac["tools"] as ToolDefinition[]) : [];
2298
- return {
2299
- clientId: ac["clientId"] as string,
2300
- tools,
2301
- ...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
2302
- };
2303
- }
2304
-
2305
- /**
2306
- * Map opencode tool result content blocks to AHP `ToolResultContent`
2307
- * (only text blocks are representable in this MVP; file/patch text is
2308
- * carried as text).
2309
- */
2310
- function mapToolResultContent(content: readonly { type: string; text?: string }[]): ToolResultContent[] {
2311
- const out: ToolResultContent[] = [];
2312
- for (const c of content) {
2313
- if (c.type === "text" || c.type === "file" || c.type === "patch") {
2314
- out.push({ type: ToolResultContentType.Text, text: c.text ?? "" });
2315
- }
2316
- }
2317
- return out;
2318
- }
2319
-
2320
- /**
2321
- * True when `child` is `parent` itself or strictly inside it (both resolved
2322
- * first, so relative segments and `..` cannot escape the comparison). Used
2323
- * to confine turn-snapshot paths and `resourceRead`/`invokeChangesetOperation`
2324
- * targets to the location directory.
2325
- */
2326
- function isPathInside(child: string, parent: string): boolean {
2327
- const a = resolvePath(child);
2328
- const b = resolvePath(parent);
2329
- return a === b || a.startsWith(b + "/");
2330
- }
54
+ export class Host extends HostRpc {}