opencode-ahp 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,381 @@
1
+ /**
2
+ * Changesets section (design §11): turn before/after file capture, changeset recomputation, `resourceRead`, and the `discard-changes` operation.
3
+ */
4
+
5
+ import { HostBase } from "./host-base.js";
6
+ import { resolve as resolvePath } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { ActionType, ChangesetOperationScope, ChangesetOperationStatus, ChangesetStatus } from "@microsoft/agent-host-protocol";
9
+ import { buildTurnChangesetFiles, buildWorkingChangesetFiles, discardOperation, fileUri, parseContentRef } from "./bridge.js";
10
+ import { parseChangesetChannel, sessionChangesetURI, turnChangesetURI, uncommittedChangesetURI } from "./channels.js";
11
+ import { ERROR_INVALID_PARAMS } from "./handshake.js";
12
+ import { isRecord } from "./options.js";
13
+ import { ERROR_METHOD_NOT_FOUND, ERROR_INTERNAL, ERROR_SESSION_NOT_FOUND, ERROR_NOT_FOUND, ERROR_PERMISSION_DENIED } from "./host-errors.js";
14
+ import { RpcMessage, ChatRuntime, SessionRecord } from "./host-types.js";
15
+ import { errorMessage, isPathInside } from "./host-util.js";
16
+
17
+ /**
18
+ * The file-mutating opencode tools whose inputs carry a target path — the
19
+ * turn-changeset before-capture watches only these (`tool.input.ended`
20
+ * fires before execution, so the pre-edit content is still on disk).
21
+ */
22
+ const SNAPSHOT_TOOLS = new Set(["write", "edit", "apply", "patch"]);
23
+
24
+ /** The tool-input keys that carry a file path (checked in order). */
25
+ const SNAPSHOT_PATH_KEYS = ["path", "file_path", "filePath", "file"] as const;
26
+
27
+ export class HostChangesets extends HostBase {
28
+ /**
29
+ * Capture the pre-edit content of a file-mutating tool's target file for
30
+ * the current turn's changeset (first capture per file wins — the
31
+ * pre-turn content survives later edits in the same turn). No-op when
32
+ * the tool is not file-mutating, the input carries no parseable path,
33
+ * or the path resolves outside the location directory.
34
+ */
35
+ // ── changesets ────────────────────────────────────────────────
36
+ protected async captureTurnBefore(chat: ChatRuntime, toolCallId: string, inputJson: string): Promise<void> {
37
+ const turnId = chat.currentTurnId;
38
+ const toolName = chat.toolName.get(toolCallId);
39
+ if (turnId === null || toolName === undefined || !SNAPSHOT_TOOLS.has(toolName)) return;
40
+ let parsed: unknown;
41
+ try {
42
+ parsed = JSON.parse(inputJson);
43
+ } catch {
44
+ return;
45
+ }
46
+ if (!isRecord(parsed)) return;
47
+ const rawPath = SNAPSHOT_PATH_KEYS.map((k) => parsed[k]).find((v) => typeof v === "string" && (v as string).length > 0);
48
+ if (typeof rawPath !== "string") return;
49
+ const absPath = this.resolveSnapshotPath(rawPath);
50
+ if (absPath === null) {
51
+ this.log(`turn snapshot: ${toolName} target ${rawPath} is outside the location directory; not captured`);
52
+ return;
53
+ }
54
+ let before: string | null;
55
+ try {
56
+ before = await this.opts.facade.readFile(absPath);
57
+ } catch (err) {
58
+ this.log(`turn snapshot: read of ${absPath} failed: ${errorMessage(err)}`);
59
+ return;
60
+ }
61
+ // The pump is sequential, so the turn cannot have ended between the
62
+ // call and the await — but the chat may be gone (session deleted or
63
+ // chat disposed).
64
+ if (chat.currentTurnId !== turnId || !this.byOpencode.has(chat.sessionID)) return;
65
+ const turnFiles = chat.turnSnapshots.get(turnId) ?? new Map();
66
+ if (!turnFiles.has(absPath)) turnFiles.set(absPath, { before, after: null });
67
+ chat.turnSnapshots.set(turnId, turnFiles);
68
+ }
69
+
70
+ /** Resolve a tool-input path against the location directory (must stay inside it). */
71
+ private resolveSnapshotPath(rawPath: string): string | null {
72
+ const dir = this.opts.defaultDirectory;
73
+ if (dir === undefined) return null;
74
+ const absPath = resolvePath(dir, rawPath);
75
+ return isPathInside(absPath, dir) ? absPath : null;
76
+ }
77
+
78
+ /**
79
+ * Recompute one changeset and publish the delta (gateway's
80
+ * `updateChangesetChannel` pattern): `changeset/contentChanged` when the
81
+ * file list changed (the discard operation is (re)attached while files
82
+ * exist, and cleared when they vanish), then `changeset/statusChanged`
83
+ * to ready when the status was not ready. A failed computation publishes
84
+ * `changeset/statusChanged` with an error.
85
+ */
86
+ protected async refreshChangeset(rec: SessionRecord, uri: string): Promise<void> {
87
+ const parsed = parseChangesetChannel(uri);
88
+ if (parsed === null) return;
89
+ const store = this.changesetStore(rec, uri);
90
+ if (store === null) return; // owner gone (disposed chat)
91
+ let files;
92
+ try {
93
+ if (parsed.kind === "turn") {
94
+ // The turn's snapshots live on the owning chat; the content refs
95
+ // carry its opencode session id (the byOpencode join key).
96
+ const chat = rec.chats.get(parsed.ownerUri);
97
+ if (chat === undefined) return;
98
+ files = buildTurnChangesetFiles({
99
+ sessionID: chat.sessionID,
100
+ turnId: parsed.turnId ?? "",
101
+ files: chat.turnSnapshots.get(parsed.turnId ?? "") ?? new Map(),
102
+ reviewedById: this.reviewedById(store),
103
+ });
104
+ } else {
105
+ const diffs = await this.opts.facade.vcsDiffWorking();
106
+ files = buildWorkingChangesetFiles({ diffs, reviewedById: this.reviewedById(store) });
107
+ }
108
+ } catch (err) {
109
+ this.publish({
110
+ channel: uri,
111
+ action: {
112
+ type: ActionType.ChangesetStatusChanged,
113
+ status: ChangesetStatus.Error,
114
+ error: { errorType: "changeset-computation", message: errorMessage(err) },
115
+ },
116
+ });
117
+ return;
118
+ }
119
+ const state = store.state;
120
+ const hadFiles = state.files.length > 0;
121
+ const hasFiles = files.length > 0;
122
+ if (JSON.stringify(state.files) !== JSON.stringify(files)) {
123
+ this.publish({
124
+ channel: uri,
125
+ action: {
126
+ type: ActionType.ChangesetContentChanged,
127
+ files,
128
+ ...(hasFiles ? { operations: [discardOperation()] } : {}),
129
+ },
130
+ });
131
+ // operations persist across contentChanged — clear them explicitly
132
+ // when the changeset empties out.
133
+ if (!hasFiles && state.operations !== undefined && state.operations.length > 0) {
134
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: undefined } });
135
+ }
136
+ }
137
+ if (!hadFiles && hasFiles && state.operations === undefined) {
138
+ // contentChanged above already attached the operation; this branch
139
+ // is unreachable unless the reducer drops it — kept as a guard.
140
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: [discardOperation()] } });
141
+ }
142
+ if (state.status !== ChangesetStatus.Ready) {
143
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetStatusChanged, status: ChangesetStatus.Ready } });
144
+ }
145
+ }
146
+
147
+ /**
148
+ * At a turn terminal: read the disk into each captured file's `after`
149
+ * (a file deleted during the turn stays null → "deleted"), then refresh
150
+ * the uncommitted, session, and ended-turn changesets — only the ones a
151
+ * client has subscribed (unsubscribed changesets cost no seq).
152
+ */
153
+ protected async refreshTurnChangesets(rec: SessionRecord, chat: ChatRuntime, turnId: string): Promise<void> {
154
+ const turnFiles = chat.turnSnapshots.get(turnId);
155
+ if (turnFiles !== undefined) {
156
+ for (const [absPath, snap] of turnFiles) {
157
+ if (snap.after === null) {
158
+ try {
159
+ snap.after = await this.opts.facade.readFile(absPath);
160
+ } catch {
161
+ snap.after = null;
162
+ }
163
+ }
164
+ }
165
+ }
166
+ // The chat's own uncommitted + turn changesets, plus the session-wide
167
+ // one (shared by all chats). Only the ones a client has subscribed.
168
+ for (const uri of [
169
+ uncommittedChangesetURI(chat.uri),
170
+ sessionChangesetURI(rec.channel),
171
+ turnChangesetURI(chat.uri, turnId),
172
+ ]) {
173
+ if (this.changesetStoreOf(rec, uri) !== undefined) await this.refreshChangeset(rec, uri);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * `resourceRead` (AHP root command): serve file content for the URIs
179
+ * this host advertises in changesets —
180
+ * - `file://` → live disk, confined to the location directory;
181
+ * - `ahp-content://head/…` → the file's HEAD content;
182
+ * - `ahp-content://snap/…` → a turn's captured before/after content.
183
+ * Errors: -32008 (not found), -32009 (path outside the location).
184
+ */
185
+ protected async handleResourceRead(socketId: number, msg: RpcMessage): Promise<void> {
186
+ const params = isRecord(msg.params) ? msg.params : {};
187
+ const uri = params["uri"];
188
+ if (typeof uri !== "string" || uri.length === 0) {
189
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resourceRead requires a content URI");
190
+ return;
191
+ }
192
+ const encoding: "base64" | "utf-8" = params["encoding"] === "utf-8" ? "utf-8" : "base64";
193
+ if (uri.startsWith("file://")) {
194
+ let absPath: string;
195
+ try {
196
+ absPath = fileURLToPath(uri);
197
+ } catch {
198
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
199
+ return;
200
+ }
201
+ if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
202
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
203
+ return;
204
+ }
205
+ let content: string | null;
206
+ try {
207
+ content = await this.opts.facade.readFile(absPath);
208
+ } catch (err) {
209
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, `read failed: ${errorMessage(err)}`);
210
+ return;
211
+ }
212
+ if (content === null) {
213
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
214
+ return;
215
+ }
216
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
217
+ return;
218
+ }
219
+ // Opaque content refs require the changesets capability.
220
+ if (!this.opts.changesets) {
221
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
222
+ return;
223
+ }
224
+ const ref = parseContentRef(uri);
225
+ if (ref === null) {
226
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
227
+ return;
228
+ }
229
+ if (ref.kind === "head") {
230
+ if (this.opts.defaultDirectory !== undefined && !isPathInside(ref.path, this.opts.defaultDirectory)) {
231
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
232
+ return;
233
+ }
234
+ let content: string | null;
235
+ try {
236
+ content = await this.opts.facade.gitHeadFile(ref.path);
237
+ } catch (err) {
238
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, `HEAD read failed: ${errorMessage(err)}`);
239
+ return;
240
+ }
241
+ if (content === null) {
242
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not in HEAD: ${ref.path}`);
243
+ return;
244
+ }
245
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
246
+ return;
247
+ }
248
+ // snap — in-memory turn snapshot of a live chat's opencode session.
249
+ const binding = this.byOpencode.get(ref.sessionID);
250
+ if (binding === undefined) {
251
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, "no such session");
252
+ return;
253
+ }
254
+ const snap = binding.chat.turnSnapshots.get(ref.turnId)?.get(ref.path);
255
+ const content = snap === undefined ? null : ref.part === "before" ? snap.before : snap.after;
256
+ if (content === null) {
257
+ this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
258
+ return;
259
+ }
260
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
261
+ }
262
+
263
+ /** Encode content for a `resourceRead` result (utf-8 or base64). */
264
+ private encodeContent(content: string, encoding: "base64" | "utf-8") {
265
+ return {
266
+ data: encoding === "utf-8" ? content : Buffer.from(content, "utf-8").toString("base64"),
267
+ encoding,
268
+ };
269
+ }
270
+
271
+ /**
272
+ * `invokeChangesetOperation`: the host's only operation is
273
+ * `discard-changes` (resource-scoped) — restore one file from the
274
+ * changeset's "before" content. Status flows through the
275
+ * `changeset/operationStatusChanged` stream; the JSON-RPC result carries
276
+ * a human-readable message.
277
+ */
278
+ protected async handleInvokeChangesetOperation(socketId: number, msg: RpcMessage): Promise<void> {
279
+ const params = isRecord(msg.params) ? msg.params : {};
280
+ const channel = params["channel"];
281
+ const operationId = params["operationId"];
282
+ if (typeof channel !== "string" || channel.length === 0 || typeof operationId !== "string" || operationId.length === 0) {
283
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "invokeChangesetOperation requires channel + operationId");
284
+ return;
285
+ }
286
+ const parsed = parseChangesetChannel(channel);
287
+ if (parsed === null) {
288
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `not a changeset channel: ${channel}`);
289
+ return;
290
+ }
291
+ const rec = this.byChannel.get(parsed.ownerUri);
292
+ if (rec === undefined) {
293
+ this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, "no such session");
294
+ return;
295
+ }
296
+ const store = this.changesetStoreOf(rec, channel);
297
+ if (store === undefined) {
298
+ this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such changeset: ${channel}`);
299
+ return;
300
+ }
301
+ const op = store.state.operations?.find((o) => o.id === operationId);
302
+ if (op === undefined) {
303
+ this.sendError(socketId, msg.id, ERROR_METHOD_NOT_FOUND, `unknown operation: ${operationId}`);
304
+ return;
305
+ }
306
+ if (!op.scopes.includes(ChangesetOperationScope.Resource)) {
307
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `operation ${operationId} is not resource-scoped`);
308
+ return;
309
+ }
310
+ const target = params["target"];
311
+ if (!isRecord(target) || target["kind"] !== "resource" || typeof target["resource"] !== "string") {
312
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resource-scoped operation requires a resource target");
313
+ return;
314
+ }
315
+ let absPath: string;
316
+ try {
317
+ absPath = fileURLToPath(target["resource"] as string);
318
+ } catch {
319
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "target.resource must be a file URI");
320
+ return;
321
+ }
322
+ if (!store.state.files.some((f) => f.id === fileUri(absPath))) {
323
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `no such file in changeset: ${target["resource"]}`);
324
+ return;
325
+ }
326
+ if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
327
+ this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
328
+ return;
329
+ }
330
+ this.publish({
331
+ channel,
332
+ action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Running },
333
+ });
334
+ try {
335
+ if (parsed.kind === "turn" && parsed.turnId !== undefined) {
336
+ // A live turn-changeset store implies a live owning chat
337
+ // (changesetStoreOf resolved it above).
338
+ await this.restoreTurnFile(rec.chats.get(parsed.ownerUri)!, parsed.turnId, absPath);
339
+ } else {
340
+ await this.opts.facade.discardFile(absPath);
341
+ }
342
+ } catch (err) {
343
+ this.publish({
344
+ channel,
345
+ action: {
346
+ type: ActionType.ChangesetOperationStatusChanged,
347
+ operationId,
348
+ status: ChangesetOperationStatus.Error,
349
+ error: { errorType: "operation-failed", message: errorMessage(err) },
350
+ },
351
+ });
352
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, errorMessage(err));
353
+ return;
354
+ }
355
+ await this.refreshChangeset(rec, channel);
356
+ this.publish({
357
+ channel,
358
+ action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Idle },
359
+ });
360
+ this.sendFrame(socketId, {
361
+ jsonrpc: "2.0",
362
+ id: msg.id ?? null,
363
+ result: { message: `Discarded changes to ${absPath}` },
364
+ });
365
+ }
366
+
367
+ /**
368
+ * Restore one file from a turn's before-snapshot: the file was added by
369
+ * the turn (before === null) → delete it; otherwise write the pre-edit
370
+ * content back.
371
+ */
372
+ private async restoreTurnFile(chat: ChatRuntime, turnId: string, absPath: string): Promise<void> {
373
+ const snap = chat.turnSnapshots.get(turnId)?.get(absPath);
374
+ const before = snap?.before ?? null;
375
+ if (before === null) {
376
+ await this.opts.facade.deleteFile(absPath);
377
+ } else {
378
+ await this.opts.facade.writeFile(absPath, before);
379
+ }
380
+ }
381
+ }
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Chat section (design §7): per-chat runtimes (one AHP chat = one opencode session), `createChat`/`disposeChat`, and the message model/agent selection.
3
+ */
4
+
5
+ import { HostClientTools } from "./host-client-tools.js";
6
+ import { ActionType, Message } from "@microsoft/agent-host-protocol";
7
+ import { agentIDFromUri, chatChangesetCatalog, chatSummaryOf, initialChatState } from "./bridge.js";
8
+ import { channelKind, sessionIDOf } from "./channels.js";
9
+ import { ERROR_INVALID_PARAMS } from "./handshake.js";
10
+ import { isRecord } from "./options.js";
11
+ import { createChatStateStore } from "./state.js";
12
+ import { ERROR_INTERNAL, ERROR_SESSION_NOT_FOUND, ERROR_SESSION_EXISTS } from "./host-errors.js";
13
+ import { RpcMessage, ChatRuntime, SessionRecord } from "./host-types.js";
14
+ import { AHP_METADATA_KEY, errorMessage, firstEnabledModelRef } from "./host-util.js";
15
+
16
+ export class HostChats extends HostClientTools {
17
+ /**
18
+ * Fresh per-chat runtime: one AHP chat = one opencode
19
+ * session, with its own chat-state store and all the per-turn tracking
20
+ * the event pump joins opencode events to.
21
+ */
22
+ // ── multi-chat ────────────────────────────────────
23
+ protected newChatRuntime(uri: string, sessionID: string, title: string, modifiedAt: string): ChatRuntime {
24
+ return {
25
+ uri,
26
+ sessionID,
27
+ chatStore: createChatStateStore(initialChatState({ resource: uri, title, modifiedAt })),
28
+ currentTurnId: null,
29
+ turnStartedAt: null,
30
+ turnModelRef: null,
31
+ parts: new Set(),
32
+ toolInput: new Map(),
33
+ toolName: new Map(),
34
+ toolReady: new Set(),
35
+ permissionForTool: new Map(),
36
+ toolForPermission: new Map(),
37
+ clientToolCalls: new Map(),
38
+ lastInbox: null,
39
+ changesets: new Map(),
40
+ turnSnapshots: new Map(),
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Bind a chat runtime to its record: the record's catalog, the
46
+ * channel→record lookup, and the opencode-id→(record, chat) reverse
47
+ * binding (the event pump's join key). The channel registry gets the
48
+ * chat URI's suffix — that is what makes the chat channel and its
49
+ * changesets (whose owner is the chat channel) subscribable. The
50
+ * default chat's suffix IS its opencode id, added by the
51
+ * registration paths; a peer chat's opencode id gets no registry
52
+ * entry (it has no subscribable session channel of its own).
53
+ */
54
+ protected bindChat(rec: SessionRecord, chat: ChatRuntime): void {
55
+ rec.chats.set(chat.uri, chat);
56
+ this.byChannel.set(chat.uri, rec);
57
+ this.byOpencode.set(chat.sessionID, { rec, chat });
58
+ const suffix = sessionIDOf(chat.uri);
59
+ if (suffix !== null) this.channels.addSession(suffix);
60
+ }
61
+
62
+ /**
63
+ * Unbind a chat runtime (dispose or record removal): clear its live
64
+ * changesets (`changeset/cleared` — protocol case 2), fail its
65
+ * in-flight client-tool executions (the waiters must not leak), and
66
+ * drop every binding.
67
+ */
68
+ protected removeChat(rec: SessionRecord, chat: ChatRuntime, toolError = "chat removed before the client completed the tool call"): void {
69
+ // The chat's terminal channels go with it
70
+ // (running commands get a final `terminal/exited` first).
71
+ this.teardownTerminalsForChat(chat);
72
+ for (const uri of chat.changesets.keys()) {
73
+ this.publish({ channel: uri, action: { type: ActionType.ChangesetCleared } });
74
+ }
75
+ chat.changesets.clear();
76
+ chat.turnSnapshots.clear();
77
+ for (const inv of chat.clientToolCalls.values()) {
78
+ if (inv.result !== undefined) continue;
79
+ inv.result = { ok: false, error: toolError };
80
+ this.settleClientTool(inv);
81
+ }
82
+ chat.clientToolCalls.clear();
83
+ rec.chats.delete(chat.uri);
84
+ this.byChannel.delete(chat.uri);
85
+ this.byOpencode.delete(chat.sessionID);
86
+ const suffix = sessionIDOf(chat.uri);
87
+ if (suffix !== null) this.channels.removeSession(suffix);
88
+ this.channels.removeSession(chat.sessionID);
89
+ }
90
+
91
+ /**
92
+ * `createChat` (AHP 1.0.0 chat command): create a new chat in an
93
+ * existing session. The 1:1 mapping: mint a fresh
94
+ * opencode session (same provider/model resolution as `createSession`)
95
+ * and bind it to the client-chosen chat URI. Result: `null` (the
96
+ * client waits for `session/chatAdded` on the session channel, and
97
+ * rolls back with `disposeChat` when the chat never surfaces — so
98
+ * everything below is published before the response). `source` and
99
+ * `workingDirectories` are rejected with INVALID_PARAMS: the
100
+ * capability is advertised without fork/sideChat/
101
+ * multipleWorkingDirectories, so conformant clients never send them.
102
+ *
103
+ * Error codes: -32602 (invalid params, including `source`/
104
+ * `workingDirectories`), -32001 (no such session), -32003 (chat URI
105
+ * already exists), -32603 (backend session creation or initial
106
+ * message failure — the chat is rolled back in that case).
107
+ */
108
+ protected async handleCreateChat(socketId: number, msg: RpcMessage): Promise<void> {
109
+ const params = isRecord(msg.params) ? msg.params : {};
110
+ const channel = params["channel"];
111
+ const chatURI = params["chat"];
112
+ if (typeof channel !== "string" || channelKind(channel) !== "session") {
113
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat requires an ahp-session:/… channel");
114
+ return;
115
+ }
116
+ const rec = this.byChannel.get(channel);
117
+ if (rec === undefined) {
118
+ this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such session: ${channel}`);
119
+ return;
120
+ }
121
+ if (typeof chatURI !== "string" || channelKind(chatURI) !== "chat") {
122
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat requires an ahp-chat:/… chat URI");
123
+ return;
124
+ }
125
+ // A marker in the chat suffix would make the chat channel
126
+ // string-identical to a changeset URI of the chat before the marker
127
+ // (the same trap createSession rejects for session suffixes).
128
+ if (chatURI.includes("/changeset/")) {
129
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "chat URI must not contain \"/changeset/\"");
130
+ return;
131
+ }
132
+ if (chatURI === rec.defaultChatURI || rec.chats.has(chatURI)) {
133
+ this.sendError(socketId, msg.id, ERROR_SESSION_EXISTS, `chat already exists: ${chatURI}`);
134
+ return;
135
+ }
136
+ if (params["source"] !== undefined) {
137
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat `source` is not supported (no fork/sideChat capability)");
138
+ return;
139
+ }
140
+ if (params["workingDirectories"] !== undefined) {
141
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat `workingDirectories` is not supported (no multipleWorkingDirectories capability)");
142
+ return;
143
+ }
144
+
145
+ // Same provider/model resolution as createSession's default path:
146
+ // the first non-disabled provider's first enabled model.
147
+ const providers = await this.opts.facade.listCatalog();
148
+ const provider = providers.find((p) => p.activation !== "disabled");
149
+ const model = provider !== undefined ? firstEnabledModelRef(provider.models) : undefined;
150
+ const now = new Date().toISOString();
151
+ let created;
152
+ try {
153
+ // Write the chat-binding marker atomically at
154
+ // create — it is what re-attaches this backend to this session's
155
+ // chat catalog after an opencode/plugin restart (opencode session
156
+ // metadata is the only durable surface a plugin has).
157
+ created = await this.opts.facade.createSession({
158
+ model,
159
+ metadata: { [AHP_METADATA_KEY]: { chat: chatURI, owner: rec.sessionID } },
160
+ });
161
+ } catch (err) {
162
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to create the chat's backend session: ${errorMessage(err)}`);
163
+ return;
164
+ }
165
+ const chat = this.newChatRuntime(chatURI, created.sessionID, `Chat ${rec.chats.size + 1}`, now);
166
+ this.bindChat(rec, chat);
167
+ // Session-channel lifecycle (server-side, no origin): the catalog
168
+ // mutation the client is waiting for, plus the changeset catalogue
169
+ // on the new chat channel.
170
+ this.publish({
171
+ channel,
172
+ action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chat.chatStore.state) },
173
+ });
174
+ if (this.opts.changesets) {
175
+ this.publish({
176
+ channel: chatURI,
177
+ action: { type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(chatURI, rec.channel) },
178
+ });
179
+ }
180
+
181
+ // initialMessage → the chat's first turn (write-ahead, same
182
+ // claim-then-prompt semantics as dispatchTurnStarted). A failure
183
+ // rolls the whole chat back — the client never sees a chat whose
184
+ // promised first turn never happened.
185
+ const initialParam = params["initialMessage"];
186
+ if (initialParam !== undefined) {
187
+ if (!isRecord(initialParam) || typeof initialParam["text"] !== "string" || (initialParam["text"] as string).length === 0) {
188
+ await this.disposeChatBackend(rec, chat);
189
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat `initialMessage` requires a message with non-empty text");
190
+ return;
191
+ }
192
+ const message = initialParam as unknown as Message;
193
+ const selectionError = await this.applyMessageSelection(chat, message);
194
+ if (selectionError !== null) {
195
+ await this.disposeChatBackend(rec, chat);
196
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to apply initial message model/agent selection: ${selectionError}`);
197
+ return;
198
+ }
199
+ const turnId = this.mintTurnId();
200
+ chat.currentTurnId = turnId;
201
+ chat.turnStartedAt = Date.now();
202
+ try {
203
+ await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text });
204
+ } catch (err) {
205
+ chat.currentTurnId = null;
206
+ chat.turnStartedAt = null;
207
+ await this.disposeChatBackend(rec, chat);
208
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, `initial message failed: ${errorMessage(err)}`);
209
+ return;
210
+ }
211
+ this.publish({
212
+ channel: chatURI,
213
+ action: {
214
+ type: ActionType.ChatTurnStarted,
215
+ turnId,
216
+ startedAt: new Date().toISOString(),
217
+ message,
218
+ },
219
+ });
220
+ }
221
+
222
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
223
+ }
224
+
225
+ /**
226
+ * `disposeChat` (AHP 1.0.0 chat command): remove a chat and its
227
+ * opencode session from the session catalog. Result: `null`. The
228
+ * default chat cannot be disposed — a session keeps its default chat
229
+ * (there is no re-home mechanism; disposing it would leave the
230
+ * `defaultChat` hint dangling). VS Code's createChat-rollback path
231
+ * relies on `disposeChat` being answerable for any chat it created.
232
+ */
233
+ protected async handleDisposeChat(socketId: number, msg: RpcMessage): Promise<void> {
234
+ const params = isRecord(msg.params) ? msg.params : {};
235
+ const channel = params["channel"];
236
+ if (typeof channel !== "string" || channelKind(channel) !== "chat") {
237
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "disposeChat requires an ahp-chat:/… channel");
238
+ return;
239
+ }
240
+ const rec = this.byChannel.get(channel);
241
+ const chat = rec !== undefined ? rec.chats.get(channel) : undefined;
242
+ if (rec === undefined || chat === undefined) {
243
+ this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such chat: ${channel}`);
244
+ return;
245
+ }
246
+ if (channel === rec.defaultChatURI) {
247
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "the default chat cannot be disposed");
248
+ return;
249
+ }
250
+ await this.disposeChatBackend(rec, chat);
251
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
252
+ }
253
+
254
+ /**
255
+ * Remove a chat from the AHP surface, then its opencode session. The
256
+ * AHP-side unbind goes FIRST: opencode's `session.deleted` event for
257
+ * the backend races this call through the event pump, and the pump
258
+ * must see the chat already unbound (its `byOpencode` guard) or it
259
+ * would publish a duplicate `session/chatRemoved`. R2: a failed
260
+ * removal still drops the AHP chat — the lingering opencode session
261
+ * shows up in the TUI (and lazily in `listSessions`) until deleted
262
+ * there.
263
+ */
264
+ private async disposeChatBackend(rec: SessionRecord, chat: ChatRuntime): Promise<void> {
265
+ this.removeChat(rec, chat);
266
+ try {
267
+ await this.opts.facade.removeSession(chat.sessionID);
268
+ } catch (err) {
269
+ this.log(`failed to remove the chat's opencode session ${chat.sessionID}: ${errorMessage(err)}`);
270
+ }
271
+ this.publish({ channel: rec.channel, action: { type: ActionType.SessionChatRemoved, chat: chat.uri } });
272
+ }
273
+
274
+ /**
275
+ * Apply a message's model/agent selection to a chat's opencode session
276
+ * before its prompt (`SessionPromptInput` carries no model/agent
277
+ * fields). Null on success, the error message on failure.
278
+ */
279
+ protected async applyMessageSelection(chat: ChatRuntime, message: Message): Promise<string | null> {
280
+ try {
281
+ if (message.model?.id !== undefined && message.model.id.includes("/")) {
282
+ const sep = message.model.id.indexOf("/");
283
+ const providerID = message.model.id.slice(0, sep);
284
+ const modelID = message.model.id.slice(sep + 1);
285
+ if (providerID.length > 0 && modelID.length > 0) {
286
+ await this.opts.facade.switchModel({ sessionID: chat.sessionID, model: { providerID, modelID } });
287
+ }
288
+ }
289
+ if (message.agent?.uri !== undefined) {
290
+ const agentID = agentIDFromUri(message.agent.uri);
291
+ if (agentID !== null) {
292
+ await this.opts.facade.switchAgent({ sessionID: chat.sessionID, agent: agentID });
293
+ }
294
+ }
295
+ } catch (err) {
296
+ return errorMessage(err);
297
+ }
298
+ return null;
299
+ }
300
+ }