opencode-ahp 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -24
- package/options.example.jsonc +15 -3
- package/package.json +1 -1
- package/src/bridge.ts +221 -76
- package/src/channels.ts +10 -4
- package/src/host-base.ts +335 -0
- package/src/host-changesets.ts +381 -0
- package/src/host-chats.ts +300 -0
- package/src/host-client-tools.ts +205 -0
- package/src/host-dispatch.ts +593 -0
- package/src/host-errors.ts +29 -0
- package/src/host-events.ts +386 -0
- package/src/host-rpc.ts +435 -0
- package/src/host-sessions.ts +558 -0
- package/src/host-terminals.ts +654 -0
- package/src/host-turns.ts +82 -0
- package/src/host-types.ts +225 -0
- package/src/host-util.ts +194 -0
- package/src/host.ts +12 -3741
- package/src/index.ts +122 -9
- package/src/options.ts +11 -0
- package/src/state.ts +11 -0
package/src/host.ts
CHANGED
|
@@ -36,3748 +36,19 @@
|
|
|
36
36
|
* `root/sessionRemoved`, `root/sessionSummaryChanged`) are JSON-RPC
|
|
37
37
|
* *notifications* in AHP 1.0.0 (ephemeral, not replayed) — only
|
|
38
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).
|
|
39
47
|
*/
|
|
40
|
-
import { resolve as resolvePath } from "node:path";
|
|
41
|
-
import { fileURLToPath } from "node:url";
|
|
42
|
-
import {
|
|
43
|
-
ActionType,
|
|
44
|
-
ChangesetOperationScope,
|
|
45
|
-
ChangesetOperationStatus,
|
|
46
|
-
ChangesetStatus,
|
|
47
|
-
PendingMessageKind,
|
|
48
|
-
ReconnectResultType,
|
|
49
|
-
ResponsePartKind,
|
|
50
|
-
SessionInputRequestKind,
|
|
51
|
-
SessionStatus,
|
|
52
|
-
TerminalClaimKind,
|
|
53
|
-
TerminalLifecycleStatus,
|
|
54
|
-
ToolCallConfirmationReason,
|
|
55
|
-
ToolCallContributorKind,
|
|
56
|
-
ToolCallStatus,
|
|
57
|
-
ToolResultContentType,
|
|
58
|
-
isClientDispatchable,
|
|
59
|
-
type ActionEnvelope,
|
|
60
|
-
type ActionOrigin,
|
|
61
|
-
type ChatAction,
|
|
62
|
-
type ChatSummary,
|
|
63
|
-
type ChatToolCallCompleteAction,
|
|
64
|
-
type ChatToolCallConfirmedAction,
|
|
65
|
-
type ChatToolCallContentChangedAction,
|
|
66
|
-
type ChatToolCallResultConfirmedAction,
|
|
67
|
-
type ChatTurnCancelledAction,
|
|
68
|
-
type ChatTurnStartedAction,
|
|
69
|
-
type ChangesetAction,
|
|
70
|
-
type ChangesetFilesReviewChangedAction,
|
|
71
|
-
type ErrorResponsePart,
|
|
72
|
-
type Implementation,
|
|
73
|
-
type Message,
|
|
74
|
-
type ReconnectResult,
|
|
75
|
-
type ResolveSessionConfigResult,
|
|
76
|
-
type RootAction,
|
|
77
|
-
type SessionAction,
|
|
78
|
-
type SessionActiveClient,
|
|
79
|
-
type SessionSummary,
|
|
80
|
-
type SessionToolClientExecutionRequest,
|
|
81
|
-
type SessionToolConfirmationRequest,
|
|
82
|
-
type Snapshot,
|
|
83
|
-
type StateAction,
|
|
84
|
-
type StringOrMarkdown,
|
|
85
|
-
type TerminalAction,
|
|
86
|
-
type TerminalInfo,
|
|
87
|
-
type TerminalState,
|
|
88
|
-
type ToolCallConfirmationState,
|
|
89
|
-
type ToolCallResult,
|
|
90
|
-
type ToolCallState,
|
|
91
|
-
type ToolResultContent,
|
|
92
|
-
} from "@microsoft/agent-host-protocol";
|
|
93
|
-
import {
|
|
94
|
-
agentDirectoryCustomization,
|
|
95
|
-
agentIDFromUri,
|
|
96
|
-
buildSessionSummary,
|
|
97
|
-
buildTurnChangesetFiles,
|
|
98
|
-
buildWorkingChangesetFiles,
|
|
99
|
-
chatChangesetCatalog,
|
|
100
|
-
chatSummaryOf,
|
|
101
|
-
displayNameFor,
|
|
102
|
-
discardOperation,
|
|
103
|
-
directoryUri,
|
|
104
|
-
fileUri,
|
|
105
|
-
initialChatState,
|
|
106
|
-
initialSessionState,
|
|
107
|
-
invocationMessageFor,
|
|
108
|
-
mapCatalog,
|
|
109
|
-
mapAgentCustomizations,
|
|
110
|
-
parseContentRef,
|
|
111
|
-
pastTenseMessageFor,
|
|
112
|
-
sessionChangesetCatalog,
|
|
113
|
-
userMessage,
|
|
114
|
-
type FacadeClientTool,
|
|
115
|
-
type FacadeClientToolResult,
|
|
116
|
-
type FacadeDelivery,
|
|
117
|
-
type FacadeEvent,
|
|
118
|
-
type FacadeModelRef,
|
|
119
|
-
type FacadeSession,
|
|
120
|
-
type FacadeToolContent,
|
|
121
|
-
type OpencodeFacade,
|
|
122
|
-
} from "./bridge.js";
|
|
123
|
-
import {
|
|
124
|
-
descriptionFor,
|
|
125
|
-
findProvider,
|
|
126
|
-
inputSchemaFor,
|
|
127
|
-
normalizeToolDefinitions,
|
|
128
|
-
toolUnion,
|
|
129
|
-
type ClientToolInvocation,
|
|
130
|
-
} from "./client-tools.js";
|
|
131
|
-
import {
|
|
132
|
-
ChannelRegistry,
|
|
133
|
-
ROOT_CHANNEL,
|
|
134
|
-
channelKind,
|
|
135
|
-
chatChannelURI,
|
|
136
|
-
parseChangesetChannel,
|
|
137
|
-
sessionChannelURI,
|
|
138
|
-
sessionChangesetURI,
|
|
139
|
-
sessionIDOf,
|
|
140
|
-
terminalChannelURI,
|
|
141
|
-
turnChangesetURI,
|
|
142
|
-
uncommittedChangesetURI,
|
|
143
|
-
} from "./channels.js";
|
|
144
|
-
import { ERROR_INVALID_PARAMS, handleInitialize } from "./handshake.js";
|
|
145
|
-
import { isRecord } from "./options.js";
|
|
146
|
-
import { Sequencer } from "./seq.js";
|
|
147
|
-
import {
|
|
148
|
-
createChatStateStore,
|
|
149
|
-
createChangesetStateStore,
|
|
150
|
-
createRootStateStore,
|
|
151
|
-
createSessionStateStore,
|
|
152
|
-
createTerminalStateStore,
|
|
153
|
-
type ChatStateStore,
|
|
154
|
-
type ChangesetStateStore,
|
|
155
|
-
type RootStateStore,
|
|
156
|
-
type SessionStateStore,
|
|
157
|
-
type TerminalStateStore,
|
|
158
|
-
} from "./state.js";
|
|
159
|
-
|
|
160
|
-
export const ERROR_PARSE = -32700;
|
|
161
|
-
export const ERROR_INVALID_REQUEST = -32600;
|
|
162
|
-
export const ERROR_METHOD_NOT_FOUND = -32601;
|
|
163
|
-
export const ERROR_INTERNAL = -32603;
|
|
164
|
-
export const ERROR_SESSION_NOT_FOUND = -32001;
|
|
165
|
-
export const ERROR_NO_PROVIDER = -32002;
|
|
166
|
-
export const ERROR_SESSION_EXISTS = -32003;
|
|
167
|
-
export const ERROR_NOT_FOUND = -32008;
|
|
168
|
-
export const ERROR_PERMISSION_DENIED = -32009;
|
|
169
|
-
export const ERROR_NOT_SUPPORTED = -32010;
|
|
170
|
-
|
|
171
|
-
// ActionType / ReconnectResultType are `declare const enum` in the package
|
|
172
|
-
// but are also real runtime objects (verified against the published dist),
|
|
173
|
-
// so the value imports are safe under both tsc (inlined) and Bun.
|
|
174
|
-
|
|
175
|
-
interface RpcMessage {
|
|
176
|
-
jsonrpc?: unknown;
|
|
177
|
-
id?: unknown;
|
|
178
|
-
method?: unknown;
|
|
179
|
-
params?: unknown;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
interface SocketState {
|
|
183
|
-
initialized: boolean;
|
|
184
|
-
/** Negotiated version (set by initialize, inherited on reconnect). */
|
|
185
|
-
version: string | null;
|
|
186
|
-
clientId: string | null;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/**
|
|
190
|
-
* Per-clientId registry record — survives socket closes so `reconnect`
|
|
191
|
-
* can replay for the same client (AHP lifecycle spec).
|
|
192
|
-
*/
|
|
193
|
-
interface ClientRecord {
|
|
194
|
-
version: string;
|
|
195
|
-
socketId: number | null;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* Everything the host tracks for one AHP chat — the backing opencode
|
|
200
|
-
* session, its chat-state store, and the per-turn tracking the event
|
|
201
|
-
* pump needs to join opencode events to AHP turns. One AHP chat ↔ one
|
|
202
|
-
* opencode session.
|
|
203
|
-
*/
|
|
204
|
-
interface ChatRuntime {
|
|
205
|
-
/** The AHP chat channel URI (`ahp-chat:/…`). */
|
|
206
|
-
uri: string;
|
|
207
|
-
/** The opencode session id backing this chat (`ses_…`). */
|
|
208
|
-
sessionID: string;
|
|
209
|
-
chatStore: ChatStateStore;
|
|
210
|
-
// ── turn tracking (event-pump join state) ────────────────────────────
|
|
211
|
-
/** The AHP turnId the pump joins opencode events to, or null. */
|
|
212
|
-
currentTurnId: string | null;
|
|
213
|
-
turnStartedAt: number | null;
|
|
214
|
-
/** `<providerID>/<modelID>` captured from `session.step.started` (usage model ref). */
|
|
215
|
-
turnModelRef: string | null;
|
|
216
|
-
// ── part / tool tracking ─────────────────────────────────────────────
|
|
217
|
-
/** Emitted part keys (`<assistantMessageID>:<kind>:<ordinal>`). */
|
|
218
|
-
parts: Set<string>;
|
|
219
|
-
/** toolCallId → raw JSON input text (`session.tool.input.ended.text`). */
|
|
220
|
-
toolInput: Map<string, string>;
|
|
221
|
-
/** toolCallId → opencode tool name (`session.tool.input.started.name`). */
|
|
222
|
-
toolName: Map<string, string>;
|
|
223
|
-
/** toolCallIds that already received `chat/toolCallReady`. */
|
|
224
|
-
toolReady: Set<string>;
|
|
225
|
-
/** toolCallId → opencode permission request id. */
|
|
226
|
-
permissionForTool: Map<string, string>;
|
|
227
|
-
/** opencode permission request id → toolCallId. */
|
|
228
|
-
toolForPermission: Map<string, string>;
|
|
229
|
-
/**
|
|
230
|
-
* toolCallId → client-executed tool call tracking (created at
|
|
231
|
-
* `tool.input.started`, removed at the opencode-side terminal).
|
|
232
|
-
*/
|
|
233
|
-
clientToolCalls: Map<string, ClientToolInvocation>;
|
|
234
|
-
/** The most recent `session.inbox.enqueued` (external/TUI prompt tracking). */
|
|
235
|
-
lastInbox: { text: string; delivery: string } | null;
|
|
236
|
-
// ── changesets ────────────────────────────────────────────────
|
|
237
|
-
/**
|
|
238
|
-
* Live chat-owned changeset stores (uncommitted + turn), keyed by
|
|
239
|
-
* changeset URI (created on subscribe). The session-kind changeset
|
|
240
|
-
* store lives on the record instead (the session channel owns it).
|
|
241
|
-
*/
|
|
242
|
-
changesets: Map<string, ChangesetStateStore>;
|
|
243
|
-
/**
|
|
244
|
-
* Per-turn file snapshots for the turn changesets: turnId → absPath →
|
|
245
|
-
* captured {before (pre-edit disk read), after (disk at turn end)}.
|
|
246
|
-
* `null` = the file was absent on that side. Kept until the chat is
|
|
247
|
-
* removed (content refs + discard-restore read them).
|
|
248
|
-
*/
|
|
249
|
-
turnSnapshots: Map<string, Map<string, { before: string | null; after: string | null }>>;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* Everything the host knows about one AHP session: the session store,
|
|
254
|
-
* its chat catalog (default chat first, then insertion order), and the
|
|
255
|
-
* denormalized summary fields for root notifications. `sessionID` is the
|
|
256
|
-
* default chat's opencode id — the key of the `sessions` map and the
|
|
257
|
-
* event-pump join key for the default chat.
|
|
258
|
-
*/
|
|
259
|
-
interface SessionRecord {
|
|
260
|
-
/** The default chat's opencode session id (`ses_…`). */
|
|
261
|
-
sessionID: string;
|
|
262
|
-
/** The AHP session channel URI (`ahp-session:/<suffix>`). */
|
|
263
|
-
channel: string;
|
|
264
|
-
/** Identity `SessionSummary.provider` (fixed at registration). */
|
|
265
|
-
provider: string;
|
|
266
|
-
createdAt: string;
|
|
267
|
-
/** Denormalized `SessionSummary.modifiedAt` (ISO; lexicographic = chronological). */
|
|
268
|
-
modifiedAt: string;
|
|
269
|
-
sessionStore: SessionStateStore;
|
|
270
|
-
/** Chat runtimes keyed by chat channel URI (default first, insertion order). */
|
|
271
|
-
chats: Map<string, ChatRuntime>;
|
|
272
|
-
/** The chat channel URI that receives input when none is selected. */
|
|
273
|
-
defaultChatURI: string;
|
|
274
|
-
/** The session-kind changeset store (owned by the session channel). */
|
|
275
|
-
sessionChangesets: Map<string, ChangesetStateStore>;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* Everything the host tracks for one synthetic terminal channel — a
|
|
280
|
-
* read-only rendering of a
|
|
281
|
-
* `shell`-tool command execution (`isPty: false`, command parts only).
|
|
282
|
-
* Opened at the tool call's `tool.input.ended` (the command line is only
|
|
283
|
-
* known there); the record outlives its turn — the root catalog drops it
|
|
284
|
-
* at turn end (retention), and the channel state stays subscribable until
|
|
285
|
-
* the owning chat/record is removed.
|
|
286
|
-
*/
|
|
287
|
-
interface TerminalRecord {
|
|
288
|
-
/** The terminal channel URI (`ahp-terminal:/<toolCallId>`). */
|
|
289
|
-
uri: string;
|
|
290
|
-
/** The AHP session record that owns the channel (claim `session`). */
|
|
291
|
-
rec: SessionRecord;
|
|
292
|
-
/** The chat whose turn ran the command (claim `chat`). */
|
|
293
|
-
chat: ChatRuntime;
|
|
294
|
-
/** The opencode tool call id (also the `commandId`, scoped to the URI). */
|
|
295
|
-
toolCallId: string;
|
|
296
|
-
/** The AHP turnId the command executed in — the catalog membership key. */
|
|
297
|
-
turnId: string;
|
|
298
|
-
/** The official-reducer store (the snapshot payload). */
|
|
299
|
-
store: TerminalStateStore;
|
|
300
|
-
commandLine: string;
|
|
301
|
-
/** Date.now() at `terminal/commandExecuted` (the `durationMs` baseline). */
|
|
302
|
-
startedAt: number;
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
export interface HostOptions {
|
|
306
|
-
serverInfo: Implementation;
|
|
307
|
-
facade: OpencodeFacade;
|
|
308
|
-
replayWindow: number;
|
|
309
|
-
/** The opencode instance's working directory (InitializeResult.defaultDirectory). */
|
|
310
|
-
defaultDirectory?: string;
|
|
311
|
-
/** Advertise + serve the changeset channels (catalogues, snapshots, discard). */
|
|
312
|
-
changesets: boolean;
|
|
313
|
-
/**
|
|
314
|
-
* Open + serve the synthetic shell-command terminal channels: one
|
|
315
|
-
* read-only `ahp-terminal:`
|
|
316
|
-
* channel per foreground `shell`-tool call. Off the wire in 1.0.0
|
|
317
|
-
* (no capability field) — the switch gates the host-side behavior.
|
|
318
|
-
*/
|
|
319
|
-
terminals: boolean;
|
|
320
|
-
/** Deliver a JSON-serializable frame to a connection. */
|
|
321
|
-
send: (socketId: number, message: unknown) => void;
|
|
322
|
-
/** Close one connection (a superseded duplicate clientId). */
|
|
323
|
-
close?: (socketId: number, code?: number, reason?: string) => void;
|
|
324
|
-
log?: (message: string) => void;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
/** Version assumed for a reconnecting client the host has never seen (host restart). */
|
|
328
|
-
const RECONNECT_DEFAULT_VERSION = "1.0.0";
|
|
329
|
-
/**
|
|
330
|
-
* Grace before the pump registers an externally created session
|
|
331
|
-
* (`session.created`): a concurrent `createSession` may still be resolving
|
|
332
|
-
* for the same opencode session under a client-chosen channel; the slower
|
|
333
|
-
* path is healed by the delete+recreate remap in `handleCreateSession`.
|
|
334
|
-
*/
|
|
335
|
-
const EXTERNAL_REGISTER_GRACE_MS = 250;
|
|
336
|
-
/** Default page size for `listSessions` (AHP `PaginatedParams.limit`). */
|
|
337
|
-
const LIST_SESSIONS_DEFAULT_LIMIT = 100;
|
|
338
|
-
/**
|
|
339
|
-
* The file-mutating opencode tools whose inputs carry a target path — the
|
|
340
|
-
* turn-changeset before-capture watches only these (`tool.input.ended`
|
|
341
|
-
* fires before execution, so the pre-edit content is still on disk).
|
|
342
|
-
*/
|
|
343
|
-
const SNAPSHOT_TOOLS = new Set(["write", "edit", "apply", "patch"]);
|
|
344
|
-
/** The tool-input keys that carry a file path (checked in order). */
|
|
345
|
-
const SNAPSHOT_PATH_KEYS = ["path", "file_path", "filePath", "file"] as const;
|
|
346
|
-
/**
|
|
347
|
-
* The opencode tool names whose executions render as synthetic
|
|
348
|
-
* `ahp-terminal:` channels. `shell`
|
|
349
|
-
* is the v2 core tool name; `bash` is its pre-rename alias (kept so an
|
|
350
|
-
* older provider-side tool name still maps).
|
|
351
|
-
*/
|
|
352
|
-
const SHELL_TOOL_NAMES = new Set(["shell", "bash"]);
|
|
353
|
-
/**
|
|
354
|
-
* Max characters of the command line kept in the terminal title (the
|
|
355
|
-
* catalog row and the state title share it — long pipelines stay
|
|
356
|
-
* one-line in the Agents-window list).
|
|
357
|
-
*/
|
|
358
|
-
const TERMINAL_TITLE_MAX = 64;
|
|
359
|
-
|
|
360
|
-
/**
|
|
361
|
-
* The exit code of a successful `shell`-tool result, read from its LAST
|
|
362
|
-
* text content part. opencode's shell tool
|
|
363
|
-
* appends a trailing `Exit code: N` notice part only for non-zero exits
|
|
364
|
-
* and signals (`Exit code: 137 (SIGKILL)` — the 128+signum convention
|
|
365
|
-
* parses as the numeric status); a zero exit carries no notice.
|
|
366
|
-
* Spawn failures arrive as `tool.failed` instead (no code available
|
|
367
|
-
* there). `null` when the last part carries an `Exit code:` line with a
|
|
368
|
-
* non-numeric value (e.g. `Exit code: unknown`) — the actions then
|
|
369
|
-
* omit the field.
|
|
370
|
-
*/
|
|
371
|
-
function shellExitCodeOf(content: FacadeToolContent[]): number | null {
|
|
372
|
-
const last = content
|
|
373
|
-
.map((c) => (c.type === "text" && typeof c.text === "string" ? c.text : null))
|
|
374
|
-
.filter((t): t is string => t !== null)
|
|
375
|
-
.pop();
|
|
376
|
-
if (last === undefined) return 0; // no output, no notice — clean zero exit
|
|
377
|
-
const numeric = /Exit code: (-?\d+)\b/.exec(last);
|
|
378
|
-
if (numeric !== null) return Number.parseInt(numeric[1]!, 10);
|
|
379
|
-
return /Exit code:/.test(last) ? null : 0;
|
|
380
|
-
}
|
|
381
|
-
/**
|
|
382
|
-
* Durability: the opencode session-metadata key carrying the AHP
|
|
383
|
-
* markers. Two shapes, same key:
|
|
384
|
-
* - on a peer-chat backend:
|
|
385
|
-
* `{ chat: <chat channel URI>, owner: <the opencode session id of
|
|
386
|
-
* the owning AHP session> }` — `owner` is the opencode id, not the
|
|
387
|
-
* channel suffix (a client-chosen suffix differs from the minted
|
|
388
|
-
* opencode id);
|
|
389
|
-
* - on the default backend of a minted-id session:
|
|
390
|
-
* `{ channel: <session channel URI> }` — the client-chosen session
|
|
391
|
-
* channel (a "ses" suffix is its own opencode id and needs none).
|
|
392
|
-
* (The keep-alive anchor uses the same key with a STRING value —
|
|
393
|
-
* `parseAhpMarker` ignores non-record markers.)
|
|
394
|
-
*/
|
|
395
|
-
const AHP_METADATA_KEY = "opencode-ahp";
|
|
396
|
-
|
|
397
|
-
/**
|
|
398
|
-
* Parse the AHP markers from an opencode session's durable metadata.
|
|
399
|
-
* Defensive: a malformed shape (missing key, non-record marker — e.g.
|
|
400
|
-
* the keep-alive anchor — or wrong-kind fields) means "no marker" —
|
|
401
|
-
* standalone registration under the opencode id.
|
|
402
|
-
*/
|
|
403
|
-
function parseAhpMarker(metadata: unknown): { chat?: string; owner?: string; channel?: string } | null {
|
|
404
|
-
if (!isRecord(metadata)) return null;
|
|
405
|
-
const marker = metadata[AHP_METADATA_KEY];
|
|
406
|
-
if (!isRecord(marker)) return null;
|
|
407
|
-
const out: { chat?: string; owner?: string; channel?: string } = {};
|
|
408
|
-
const chat = marker["chat"];
|
|
409
|
-
if (typeof chat === "string" && channelKind(chat) === "chat") out.chat = chat;
|
|
410
|
-
const owner = marker["owner"];
|
|
411
|
-
if (typeof owner === "string" && owner.startsWith("ses")) out.owner = owner;
|
|
412
|
-
const channel = marker["channel"];
|
|
413
|
-
if (typeof channel === "string" && channelKind(channel) === "session") out.channel = channel;
|
|
414
|
-
return Object.keys(out).length > 0 ? out : null;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
export class Host {
|
|
418
|
-
private readonly seq: Sequencer;
|
|
419
|
-
private readonly channels = new ChannelRegistry();
|
|
420
|
-
private readonly state: RootStateStore;
|
|
421
|
-
private readonly sockets = new Map<number, SocketState>();
|
|
422
|
-
private readonly clients = new Map<string, ClientRecord>();
|
|
423
|
-
/**
|
|
424
|
-
* Live sessions, keyed by opencode session id (the event-pump join key).
|
|
425
|
-
* `byChannel` maps a session/chat channel URI to the same record for the
|
|
426
|
-
* client-facing lookups — the channel suffix is not always the opencode id
|
|
427
|
-
* (client-chosen suffixes), so the two keyings differ.
|
|
428
|
-
*/
|
|
429
|
-
private readonly sessions = new Map<string, SessionRecord>();
|
|
430
|
-
private readonly byChannel = new Map<string, SessionRecord>();
|
|
431
|
-
/**
|
|
432
|
-
* opencode session id → the (record, chat) the id backs. The event
|
|
433
|
-
* pump's join key — every chat has its own opencode session, and the
|
|
434
|
-
* pump must land on the owning chat, not just the record.
|
|
435
|
-
*/
|
|
436
|
-
private readonly byOpencode = new Map<string, { rec: SessionRecord; chat: ChatRuntime }>();
|
|
437
|
-
/**
|
|
438
|
-
* Durability: marked peer backends whose owner
|
|
439
|
-
* AHP session is not registered yet, keyed by the marker's `owner`
|
|
440
|
-
* (opencode session id). A peer can be listed before its owner in the
|
|
441
|
-
* same synchronous `listSessions` pass, and after a restart the owner
|
|
442
|
-
* record does not exist until it is listed (there is no boot-time
|
|
443
|
-
* event replay). Drained when the owner registers; an entry whose
|
|
444
|
-
* owner is gone from opencode falls back to standalone registration
|
|
445
|
-
* after the grace window.
|
|
446
|
-
*/
|
|
447
|
-
private readonly pendingChatBindings = new Map<string, { fs: FacadeSession; chatURI: string }[]>();
|
|
448
|
-
/**
|
|
449
|
-
* Synthetic terminal channels keyed by URI
|
|
450
|
-
* (`ahp-terminal:/<toolCallId>`), created at the `shell`-tool call's
|
|
451
|
-
* `tool.input.ended` and retained until the owning chat/record is
|
|
452
|
-
* removed.
|
|
453
|
-
*/
|
|
454
|
-
private readonly terminals = new Map<string, TerminalRecord>();
|
|
455
|
-
private readonly opts: HostOptions;
|
|
456
|
-
private readonly log: (message: string) => void;
|
|
457
|
-
private turnCounter = 0;
|
|
458
|
-
private pumpController: AbortController | null = null;
|
|
459
|
-
|
|
460
|
-
constructor(opts: HostOptions) {
|
|
461
|
-
this.opts = opts;
|
|
462
|
-
this.log = opts.log ?? (() => {});
|
|
463
|
-
this.seq = new Sequencer(opts.replayWindow);
|
|
464
|
-
this.state = createRootStateStore({ agents: [] });
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
// ── transport callbacks ────────────────────────────────────────────────
|
|
468
|
-
|
|
469
|
-
onOpen(socketId: number): void {
|
|
470
|
-
this.sockets.set(socketId, { initialized: false, version: null, clientId: null });
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
onMessage(socketId: number, text: string): void {
|
|
474
|
-
let raw: unknown;
|
|
475
|
-
try {
|
|
476
|
-
raw = JSON.parse(text);
|
|
477
|
-
} catch {
|
|
478
|
-
this.sendFrame(socketId, {
|
|
479
|
-
jsonrpc: "2.0",
|
|
480
|
-
id: null,
|
|
481
|
-
error: { code: ERROR_PARSE, message: "parse error" },
|
|
482
|
-
});
|
|
483
|
-
return;
|
|
484
|
-
}
|
|
485
|
-
if (!isRecord(raw) || raw.jsonrpc !== "2.0" || typeof raw.method !== "string") {
|
|
486
|
-
this.sendFrame(socketId, {
|
|
487
|
-
jsonrpc: "2.0",
|
|
488
|
-
id: isRecord(raw) ? raw.id ?? null : null,
|
|
489
|
-
error: { code: ERROR_INVALID_REQUEST, message: "invalid request" },
|
|
490
|
-
});
|
|
491
|
-
return;
|
|
492
|
-
}
|
|
493
|
-
// The routing is async (catalog reads await the opencode registry);
|
|
494
|
-
// each message is handled independently.
|
|
495
|
-
void this.route(socketId, raw).catch((err) => {
|
|
496
|
-
// R2: a bad frame or a bridge error must never take down the host.
|
|
497
|
-
this.log(
|
|
498
|
-
`error handling ${String(raw.method)}: ${err instanceof Error ? err.stack ?? err.message : String(err)}`,
|
|
499
|
-
);
|
|
500
|
-
if (raw.id !== undefined) {
|
|
501
|
-
this.sendFrame(socketId, {
|
|
502
|
-
jsonrpc: "2.0",
|
|
503
|
-
id: raw.id,
|
|
504
|
-
error: { code: ERROR_INTERNAL, message: "internal error" },
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
});
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
onClose(socketId: number): void {
|
|
511
|
-
const socket = this.sockets.get(socketId);
|
|
512
|
-
if (socket?.clientId) {
|
|
513
|
-
const record = this.clients.get(socket.clientId);
|
|
514
|
-
if (record && record.socketId === socketId) record.socketId = null;
|
|
515
|
-
// The spec says the server SHOULD remove an
|
|
516
|
-
// active client when it disconnects. Safe: the
|
|
517
|
-
// official client re-dispatches `activeClientSet` on re-subscribe.
|
|
518
|
-
this.evictActiveClient(socket.clientId);
|
|
519
|
-
}
|
|
520
|
-
this.channels.removeSocket(socketId);
|
|
521
|
-
this.sockets.delete(socketId);
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* Evict a disconnected client's active-client
|
|
526
|
-
* role from every session it holds (server-side
|
|
527
|
-
* `session/activeClientRemoved`), fail its in-flight client-tool
|
|
528
|
-
* executions (the opencode tool then fails → the pump's normal
|
|
529
|
-
* `tool.failed` path completes the AHP tool call — the state is still
|
|
530
|
-
* `running`, so the terminal suppression does not apply), clear the
|
|
531
|
-
* session input request each execution raised (the
|
|
532
|
-
* `toolClientExecution` request, or the `toolConfirmation` that
|
|
533
|
-
* replaced it under the same id when the result was held for
|
|
534
|
-
* approval — without this the session keeps a stale request and, for
|
|
535
|
-
* a held result, sits in InputNeeded forever), and re-sync the
|
|
536
|
-
* opencode tool union (it shrank).
|
|
537
|
-
*/
|
|
538
|
-
private evictActiveClient(clientId: string): void {
|
|
539
|
-
let evicted = false;
|
|
540
|
-
for (const rec of this.sessions.values()) {
|
|
541
|
-
if (!rec.sessionStore.state.activeClients.some((c) => c.clientId === clientId)) continue;
|
|
542
|
-
evicted = true;
|
|
543
|
-
this.publish({
|
|
544
|
-
channel: rec.channel,
|
|
545
|
-
action: { type: ActionType.SessionActiveClientRemoved, clientId },
|
|
546
|
-
});
|
|
547
|
-
// In-flight client-tool calls are per-chat.
|
|
548
|
-
for (const chat of rec.chats.values()) {
|
|
549
|
-
for (const [toolCallId, inv] of chat.clientToolCalls) {
|
|
550
|
-
if (inv.clientId !== clientId || inv.result !== undefined) continue;
|
|
551
|
-
inv.result = { ok: false, error: `client ${clientId} disconnected before completing the tool call` };
|
|
552
|
-
this.settleClientTool(inv);
|
|
553
|
-
// The reducer's inputNeededRemoved is a no-op when the id is
|
|
554
|
-
// absent, so this is safe for an invocation whose request was
|
|
555
|
-
// already cleared on the normal completion path.
|
|
556
|
-
this.publish({
|
|
557
|
-
channel: rec.channel,
|
|
558
|
-
action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
|
|
559
|
-
});
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
if (evicted) void this.syncClientToolsToOpencode();
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// ── event pump ─────────────────────────────────────────────────────────
|
|
567
|
-
|
|
568
|
-
/**
|
|
569
|
-
* Start the opencode event → AHP action pump. Idempotent. The pump is a
|
|
570
|
-
* single sequential async loop, so event handling and client-dispatch
|
|
571
|
-
* handling (same event loop) interleave without races on the per-turn
|
|
572
|
-
* join state.
|
|
573
|
-
*/
|
|
574
|
-
startEventPump(): void {
|
|
575
|
-
if (this.pumpController !== null) return;
|
|
576
|
-
const controller = new AbortController();
|
|
577
|
-
this.pumpController = controller;
|
|
578
|
-
void (async () => {
|
|
579
|
-
try {
|
|
580
|
-
for await (const event of this.opts.facade.events(controller.signal)) {
|
|
581
|
-
if (controller.signal.aborted) break;
|
|
582
|
-
await this.handleEvent(event);
|
|
583
|
-
}
|
|
584
|
-
} catch (err) {
|
|
585
|
-
this.log(`event pump failed: ${err instanceof Error ? err.stack ?? err.message : String(err)}`);
|
|
586
|
-
} finally {
|
|
587
|
-
if (this.pumpController === controller) this.pumpController = null;
|
|
588
|
-
}
|
|
589
|
-
})();
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
/** Stop the event pump (teardown). Idempotent. */
|
|
593
|
-
stopEventPump(): void {
|
|
594
|
-
this.pumpController?.abort();
|
|
595
|
-
this.pumpController = null;
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
// ── routing ────────────────────────────────────────────────────────────
|
|
599
|
-
|
|
600
|
-
private async route(socketId: number, msg: RpcMessage): Promise<void> {
|
|
601
|
-
const socket = this.sockets.get(socketId);
|
|
602
|
-
if (!socket) return;
|
|
603
|
-
const method = msg.method as string;
|
|
604
|
-
|
|
605
|
-
if (!socket.initialized) {
|
|
606
|
-
if (method === "ping") {
|
|
607
|
-
// ping is answered even before initialize (AHP transport spec).
|
|
608
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
|
|
609
|
-
return;
|
|
610
|
-
}
|
|
611
|
-
if (method === "initialize") {
|
|
612
|
-
await this.handleInitialize(socketId, msg);
|
|
613
|
-
return;
|
|
614
|
-
}
|
|
615
|
-
if (method === "reconnect") {
|
|
616
|
-
await this.handleReconnect(socketId, msg);
|
|
617
|
-
return;
|
|
618
|
-
}
|
|
619
|
-
if (msg.id !== undefined) {
|
|
620
|
-
this.sendFrame(socketId, {
|
|
621
|
-
jsonrpc: "2.0",
|
|
622
|
-
id: msg.id,
|
|
623
|
-
error: {
|
|
624
|
-
code: ERROR_INVALID_REQUEST,
|
|
625
|
-
message: `not initialized: ${method} must follow initialize or reconnect`,
|
|
626
|
-
},
|
|
627
|
-
});
|
|
628
|
-
return;
|
|
629
|
-
}
|
|
630
|
-
this.log(`ignoring pre-initialize notification ${method} on socket ${socketId}`);
|
|
631
|
-
return;
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
switch (method) {
|
|
635
|
-
case "ping":
|
|
636
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
|
|
637
|
-
break;
|
|
638
|
-
case "subscribe":
|
|
639
|
-
await this.handleSubscribe(socketId, msg);
|
|
640
|
-
break;
|
|
641
|
-
case "unsubscribe":
|
|
642
|
-
this.handleUnsubscribe(socketId, msg); // notification (no id)
|
|
643
|
-
break;
|
|
644
|
-
case "dispatchAction":
|
|
645
|
-
await this.handleDispatchAction(socketId, msg); // notification (no id)
|
|
646
|
-
break;
|
|
647
|
-
case "listSessions":
|
|
648
|
-
await this.handleListSessions(socketId, msg);
|
|
649
|
-
break;
|
|
650
|
-
case "resolveSessionConfig":
|
|
651
|
-
this.handleResolveSessionConfig(socketId, msg);
|
|
652
|
-
break;
|
|
653
|
-
case "createSession":
|
|
654
|
-
await this.handleCreateSession(socketId, msg);
|
|
655
|
-
break;
|
|
656
|
-
case "createChat":
|
|
657
|
-
await this.handleCreateChat(socketId, msg);
|
|
658
|
-
break;
|
|
659
|
-
case "disposeChat":
|
|
660
|
-
await this.handleDisposeChat(socketId, msg);
|
|
661
|
-
break;
|
|
662
|
-
case "resourceRead":
|
|
663
|
-
await this.handleResourceRead(socketId, msg);
|
|
664
|
-
break;
|
|
665
|
-
case "invokeChangesetOperation":
|
|
666
|
-
await this.handleInvokeChangesetOperation(socketId, msg);
|
|
667
|
-
break;
|
|
668
|
-
case "createTerminal":
|
|
669
|
-
case "disposeTerminal":
|
|
670
|
-
// The host's terminals are read-only
|
|
671
|
-
// renderings of `shell`-tool executions — the plugin surface can
|
|
672
|
-
// neither create nor destroy pty-backed terminals, so both
|
|
673
|
-
// commands get a clean server error instead of -32601
|
|
674
|
-
// (proper error handling once terminals exist).
|
|
675
|
-
this.sendError(
|
|
676
|
-
socketId,
|
|
677
|
-
msg.id,
|
|
678
|
-
ERROR_NOT_SUPPORTED,
|
|
679
|
-
`${method} is not supported: this host's terminals are read-only renderings of shell tool calls`,
|
|
680
|
-
);
|
|
681
|
-
break;
|
|
682
|
-
case "setClientManagedSettingsPermissions":
|
|
683
|
-
// VS Code-specific post-init notification: the
|
|
684
|
-
// permissions VS Code manages in its own settings UI. AHP 1.0.0
|
|
685
|
-
// has no counterpart — accept deliberately (parse + log), never
|
|
686
|
-
// error; the connection stays up.
|
|
687
|
-
this.log(
|
|
688
|
-
`setClientManagedSettingsPermissions received (${describeParams(msg.params)}); accepted (no-op)`,
|
|
689
|
-
);
|
|
690
|
-
break;
|
|
691
|
-
case "initialize":
|
|
692
|
-
case "reconnect":
|
|
693
|
-
this.sendFrame(socketId, {
|
|
694
|
-
jsonrpc: "2.0",
|
|
695
|
-
id: msg.id ?? null,
|
|
696
|
-
error: {
|
|
697
|
-
code: ERROR_INVALID_REQUEST,
|
|
698
|
-
message: `${method} is only valid before the handshake`,
|
|
699
|
-
},
|
|
700
|
-
});
|
|
701
|
-
break;
|
|
702
|
-
default:
|
|
703
|
-
if (msg.id !== undefined) {
|
|
704
|
-
this.sendFrame(socketId, {
|
|
705
|
-
jsonrpc: "2.0",
|
|
706
|
-
id: msg.id,
|
|
707
|
-
error: { code: ERROR_METHOD_NOT_FOUND, message: `unknown method: ${method}` },
|
|
708
|
-
});
|
|
709
|
-
} else {
|
|
710
|
-
this.log(`ignoring unknown notification ${method} on socket ${socketId}`);
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
private sendFrame(socketId: number, message: unknown): void {
|
|
716
|
-
this.opts.send(socketId, message);
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
// ── commands ───────────────────────────────────────────────────────────
|
|
720
|
-
|
|
721
|
-
private async handleInitialize(socketId: number, msg: RpcMessage): Promise<void> {
|
|
722
|
-
const socket = this.sockets.get(socketId)!;
|
|
723
|
-
const outcome = await handleInitialize({
|
|
724
|
-
params: msg.params,
|
|
725
|
-
serverInfo: this.opts.serverInfo,
|
|
726
|
-
serverSeq: this.seq.seq,
|
|
727
|
-
defaultDirectory: this.opts.defaultDirectory,
|
|
728
|
-
snapshotFor: (uri) => this.snapshotFor(uri),
|
|
729
|
-
});
|
|
730
|
-
if (!outcome.ok) {
|
|
731
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, error: outcome.error });
|
|
732
|
-
return;
|
|
733
|
-
}
|
|
734
|
-
|
|
735
|
-
const clientId = (msg.params as { clientId: string }).clientId;
|
|
736
|
-
const existing = this.clients.get(clientId);
|
|
737
|
-
if (existing && existing.socketId !== null && existing.socketId !== socketId) {
|
|
738
|
-
// A newer connection with the same clientId supersedes the old one.
|
|
739
|
-
this.log(`client ${clientId} re-initialized on socket ${socketId}; closing socket ${existing.socketId}`);
|
|
740
|
-
this.opts.close?.(existing.socketId, 4000, "superseded by a newer connection");
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
socket.initialized = true;
|
|
744
|
-
socket.version = outcome.result.protocolVersion;
|
|
745
|
-
socket.clientId = clientId;
|
|
746
|
-
this.clients.set(clientId, { version: outcome.result.protocolVersion, socketId });
|
|
747
|
-
|
|
748
|
-
// Register the initial subscriptions right after the snapshot
|
|
749
|
-
// computation above; no action can slip in between.
|
|
750
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
751
|
-
const initial = Array.isArray(params["initialSubscriptions"])
|
|
752
|
-
? params["initialSubscriptions"]
|
|
753
|
-
: [];
|
|
754
|
-
for (const uri of initial) {
|
|
755
|
-
if (typeof uri === "string" && uri.length > 0) {
|
|
756
|
-
this.channels.subscribe(socketId, uri);
|
|
757
|
-
}
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: outcome.result });
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
private async handleReconnect(socketId: number, msg: RpcMessage): Promise<void> {
|
|
764
|
-
const params = msg.params;
|
|
765
|
-
if (!isRecord(params) || params["channel"] !== ROOT_CHANNEL) {
|
|
766
|
-
this.sendFrame(socketId, {
|
|
767
|
-
jsonrpc: "2.0",
|
|
768
|
-
id: msg.id ?? null,
|
|
769
|
-
error: { code: ERROR_INVALID_PARAMS, message: `reconnect must target ${ROOT_CHANNEL}` },
|
|
770
|
-
});
|
|
771
|
-
return;
|
|
772
|
-
}
|
|
773
|
-
const clientId = params["clientId"];
|
|
774
|
-
const lastSeen = params["lastSeenServerSeq"];
|
|
775
|
-
const subscriptions = params["subscriptions"];
|
|
776
|
-
if (typeof clientId !== "string" || clientId.length === 0 ||
|
|
777
|
-
!Number.isInteger(lastSeen) || (lastSeen as number) < 0 ||
|
|
778
|
-
!Array.isArray(subscriptions) || !subscriptions.every((u) => typeof u === "string")) {
|
|
779
|
-
this.sendFrame(socketId, {
|
|
780
|
-
jsonrpc: "2.0",
|
|
781
|
-
id: msg.id ?? null,
|
|
782
|
-
error: { code: ERROR_INVALID_PARAMS, message: "invalid reconnect params" },
|
|
783
|
-
});
|
|
784
|
-
return;
|
|
785
|
-
}
|
|
786
|
-
const clientSubs = subscriptions as string[];
|
|
787
|
-
|
|
788
|
-
const record = this.clients.get(clientId);
|
|
789
|
-
const known = record !== undefined;
|
|
790
|
-
const version = record?.version ?? RECONNECT_DEFAULT_VERSION;
|
|
791
|
-
|
|
792
|
-
const socket = this.sockets.get(socketId)!;
|
|
793
|
-
socket.initialized = true;
|
|
794
|
-
socket.version = version;
|
|
795
|
-
socket.clientId = clientId;
|
|
796
|
-
this.clients.set(clientId, { version, socketId });
|
|
797
|
-
|
|
798
|
-
// Resolve every requested subscription; unresolvable ones are reported
|
|
799
|
-
// in `missing` (the client drops them — AHP lifecycle spec).
|
|
800
|
-
const snapshots: Snapshot[] = [];
|
|
801
|
-
const missing: string[] = [];
|
|
802
|
-
for (const uri of clientSubs) {
|
|
803
|
-
const snap = await this.snapshotFor(uri);
|
|
804
|
-
if (snap) snapshots.push(snap);
|
|
805
|
-
else missing.push(uri);
|
|
806
|
-
}
|
|
807
|
-
for (const uri of clientSubs) {
|
|
808
|
-
this.channels.subscribe(socketId, uri);
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
// Replay when the client is known and its gap is still in the window;
|
|
812
|
-
// otherwise fresh snapshots.
|
|
813
|
-
let result: ReconnectResult;
|
|
814
|
-
const replay = this.seq.since(lastSeen as number);
|
|
815
|
-
if (known && replay !== null) {
|
|
816
|
-
const set = new Set(clientSubs);
|
|
817
|
-
result = {
|
|
818
|
-
type: ReconnectResultType.Replay,
|
|
819
|
-
actions: replay.filter((a) => set.has(a.channel)),
|
|
820
|
-
missing,
|
|
821
|
-
};
|
|
822
|
-
} else {
|
|
823
|
-
result = { type: ReconnectResultType.Snapshot, snapshots };
|
|
824
|
-
}
|
|
825
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
private async handleSubscribe(socketId: number, msg: RpcMessage): Promise<void> {
|
|
829
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
830
|
-
const uri = params["channel"];
|
|
831
|
-
if (typeof uri !== "string" || uri.length === 0) {
|
|
832
|
-
this.sendFrame(socketId, {
|
|
833
|
-
jsonrpc: "2.0",
|
|
834
|
-
id: msg.id ?? null,
|
|
835
|
-
error: { code: ERROR_INVALID_PARAMS, message: "subscribe requires a channel URI" },
|
|
836
|
-
});
|
|
837
|
-
return;
|
|
838
|
-
}
|
|
839
|
-
const outcome = this.channels.subscribe(socketId, uri);
|
|
840
|
-
if (!outcome.ok) {
|
|
841
|
-
this.sendFrame(socketId, {
|
|
842
|
-
jsonrpc: "2.0",
|
|
843
|
-
id: msg.id ?? null,
|
|
844
|
-
error: {
|
|
845
|
-
code:
|
|
846
|
-
outcome.reason === "no-such-session"
|
|
847
|
-
? ERROR_SESSION_NOT_FOUND
|
|
848
|
-
: outcome.reason === "no-such-terminal"
|
|
849
|
-
? ERROR_NOT_FOUND
|
|
850
|
-
: ERROR_INVALID_PARAMS,
|
|
851
|
-
message: `cannot subscribe to ${uri}`,
|
|
852
|
-
},
|
|
853
|
-
});
|
|
854
|
-
return;
|
|
855
|
-
}
|
|
856
|
-
const snap = await this.snapshotFor(uri);
|
|
857
|
-
this.sendFrame(socketId, {
|
|
858
|
-
jsonrpc: "2.0",
|
|
859
|
-
id: msg.id ?? null,
|
|
860
|
-
result: snap ? { snapshot: snap } : {},
|
|
861
|
-
});
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
private handleUnsubscribe(socketId: number, msg: RpcMessage): void {
|
|
865
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
866
|
-
const uri = params["channel"];
|
|
867
|
-
if (typeof uri !== "string" || uri.length === 0) return;
|
|
868
|
-
this.channels.unsubscribe(socketId, uri);
|
|
869
|
-
}
|
|
870
|
-
|
|
871
|
-
/**
|
|
872
|
-
* `createSession` (AHP 1.0.0 session-channel command). Creates a real
|
|
873
|
-
* opencode session, seeds its session/chat stores, publishes the
|
|
874
|
-
* session-channel lifecycle actions, announces the session on the root
|
|
875
|
-
* channel, and responds `null` (per the command contract).
|
|
876
|
-
*
|
|
877
|
-
* Error codes: -32002 (no agent for the requested provider),
|
|
878
|
-
* -32003 (the session URI already exists).
|
|
879
|
-
*/
|
|
880
|
-
private async handleCreateSession(socketId: number, msg: RpcMessage): Promise<void> {
|
|
881
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
882
|
-
const channel = params["channel"];
|
|
883
|
-
if (typeof channel !== "string" || channelKind(channel) !== "session") {
|
|
884
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createSession requires an ahp-session:/… channel");
|
|
885
|
-
return;
|
|
886
|
-
}
|
|
887
|
-
const suffix = sessionIDOf(channel) as string;
|
|
888
|
-
// A suffix containing the changeset marker would make this session
|
|
889
|
-
// channel string-identical to the changeset URI of the session before
|
|
890
|
-
// the marker — the changeset kind would win (channelKind), making the
|
|
891
|
-
// session channel un-subscribable. Reject it instead.
|
|
892
|
-
if (suffix.includes("/changeset/")) {
|
|
893
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "channel suffix must not contain \"/changeset/\"");
|
|
894
|
-
return;
|
|
895
|
-
}
|
|
896
|
-
for (const rec of this.sessions.values()) {
|
|
897
|
-
if (rec.channel === channel) {
|
|
898
|
-
this.sendError(socketId, msg.id, ERROR_SESSION_EXISTS, "Session already exists");
|
|
899
|
-
return;
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
|
|
903
|
-
// Resolve the provider/model for the new session.
|
|
904
|
-
const providers = await this.opts.facade.listCatalog();
|
|
905
|
-
const providerParam = params["provider"];
|
|
906
|
-
let provider;
|
|
907
|
-
if (typeof providerParam === "string" && providerParam.length > 0) {
|
|
908
|
-
provider = providers.find((p) => p.providerID === providerParam && p.activation !== "disabled");
|
|
909
|
-
if (provider === undefined) {
|
|
910
|
-
this.sendError(socketId, msg.id, ERROR_NO_PROVIDER, `No agent for provider ${providerParam}`);
|
|
911
|
-
return;
|
|
912
|
-
}
|
|
913
|
-
} else {
|
|
914
|
-
provider = providers.find((p) => p.activation !== "disabled");
|
|
915
|
-
}
|
|
916
|
-
const model = provider !== undefined ? firstEnabledModelRef(provider.models) : undefined;
|
|
917
|
-
|
|
918
|
-
// `activeClient` eagerly claims an active-client role; the spec requires
|
|
919
|
-
// the clientId to match the creating client.
|
|
920
|
-
let activeClients: SessionActiveClient[] = [];
|
|
921
|
-
const activeClientParam = params["activeClient"];
|
|
922
|
-
if (activeClientParam !== undefined) {
|
|
923
|
-
const socket = this.sockets.get(socketId);
|
|
924
|
-
const ac = activeClientParam as Record<string, unknown>;
|
|
925
|
-
if (
|
|
926
|
-
!isRecord(ac) ||
|
|
927
|
-
typeof ac["clientId"] !== "string" ||
|
|
928
|
-
ac["clientId"] !== socket?.clientId
|
|
929
|
-
) {
|
|
930
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "activeClient.clientId must match the initializing clientId");
|
|
931
|
-
return;
|
|
932
|
-
}
|
|
933
|
-
activeClients = [normalizeActiveClient(ac)];
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
// opencode SessionIDs must start with "ses": pass the suffix through
|
|
937
|
-
// only when it already is one; otherwise let opencode mint an id and
|
|
938
|
-
// record the suffix→id mapping (the record key is the opencode id).
|
|
939
|
-
const passID = suffix.startsWith("ses") ? suffix : undefined;
|
|
940
|
-
const created = await this.opts.facade.createSession({
|
|
941
|
-
id: passID,
|
|
942
|
-
model,
|
|
943
|
-
// Durability: a minted-id default backend carries
|
|
944
|
-
// the client-chosen session channel in its opencode metadata —
|
|
945
|
-
// after a restart the session resurfaces under the ORIGINAL channel
|
|
946
|
-
// instead of its opencode id (a "ses" suffix IS the opencode id and
|
|
947
|
-
// needs no marker).
|
|
948
|
-
...(passID === undefined ? { metadata: { [AHP_METADATA_KEY]: { channel } } } : {}),
|
|
949
|
-
});
|
|
950
|
-
|
|
951
|
-
// Slow-create race: the pump may have registered this opencode session
|
|
952
|
-
// under its own id as an external session while `createSession` was in
|
|
953
|
-
// flight. Remap: drop the interim record (root/sessionRemoved) and
|
|
954
|
-
// re-register under the client-chosen channel below.
|
|
955
|
-
//
|
|
956
|
-
// Marker interaction: with the channel marker, the
|
|
957
|
-
// interim external registration lands under the MARKED channel (the
|
|
958
|
-
// client's own), so `interim.channel !== channel` is false and the
|
|
959
|
-
// remap is skipped — the re-registration below then re-announces the
|
|
960
|
-
// session (a duplicate root/sessionAdded in this rare race; cosmetic,
|
|
961
|
-
// the client converges on the snapshot, and the race requires
|
|
962
|
-
// createSession to exceed the 250 ms external-register grace).
|
|
963
|
-
const interim = this.sessions.get(created.sessionID);
|
|
964
|
-
if (interim !== undefined && interim.channel !== channel) {
|
|
965
|
-
this.removeRecord(interim);
|
|
966
|
-
}
|
|
967
|
-
|
|
968
|
-
const agents = await this.opts.facade.listAgents();
|
|
969
|
-
const customizations =
|
|
970
|
-
mapAgentCustomizations(agents).length > 0 && this.opts.defaultDirectory !== undefined
|
|
971
|
-
? [agentDirectoryCustomization(this.opts.defaultDirectory, agents)]
|
|
972
|
-
: undefined;
|
|
973
|
-
const now = new Date().toISOString();
|
|
974
|
-
const sessionStore = createSessionStateStore(
|
|
975
|
-
initialSessionState({
|
|
976
|
-
sessionID: created.sessionID,
|
|
977
|
-
provider: created.model?.providerID ?? provider?.providerID ?? "opencode",
|
|
978
|
-
title: created.title ?? "New Session",
|
|
979
|
-
activeClients,
|
|
980
|
-
customizations,
|
|
981
|
-
}),
|
|
982
|
-
);
|
|
983
|
-
const rec: SessionRecord = {
|
|
984
|
-
sessionID: created.sessionID,
|
|
985
|
-
channel,
|
|
986
|
-
provider: sessionStore.state.provider,
|
|
987
|
-
createdAt: new Date(created.time.created).toISOString(),
|
|
988
|
-
modifiedAt: new Date(created.time.updated).toISOString() > now
|
|
989
|
-
? new Date(created.time.updated).toISOString()
|
|
990
|
-
: now,
|
|
991
|
-
sessionStore,
|
|
992
|
-
chats: new Map(),
|
|
993
|
-
defaultChatURI: chatChannelURI(created.sessionID),
|
|
994
|
-
sessionChangesets: new Map(),
|
|
995
|
-
};
|
|
996
|
-
this.sessions.set(created.sessionID, rec);
|
|
997
|
-
this.byChannel.set(channel, rec);
|
|
998
|
-
// The session channel carries the client-chosen suffix; the chat
|
|
999
|
-
// channel and the event pump carry the opencode id — both must
|
|
1000
|
-
// resolve in the registry.
|
|
1001
|
-
this.channels.addSession(suffix);
|
|
1002
|
-
this.channels.addSession(created.sessionID);
|
|
1003
|
-
const defaultChat = this.newChatRuntime(rec.defaultChatURI, created.sessionID, "Chat 1", now);
|
|
1004
|
-
this.bindChat(rec, defaultChat);
|
|
1005
|
-
|
|
1006
|
-
// A createSession `activeClient` seeds the
|
|
1007
|
-
// session's tools — register them with opencode now.
|
|
1008
|
-
if (activeClients.length > 0) void this.syncClientToolsToOpencode();
|
|
1009
|
-
|
|
1010
|
-
// Session-channel lifecycle (server-side, no origin).
|
|
1011
|
-
this.publish({ channel, action: { type: ActionType.SessionReady } });
|
|
1012
|
-
this.publish({
|
|
1013
|
-
channel,
|
|
1014
|
-
action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(defaultChat.chatStore.state) },
|
|
1015
|
-
});
|
|
1016
|
-
this.publish({
|
|
1017
|
-
channel,
|
|
1018
|
-
action: { type: ActionType.SessionDefaultChatChanged, defaultChat: rec.defaultChatURI },
|
|
1019
|
-
});
|
|
1020
|
-
// Advertise the changeset catalogues (session channel: the
|
|
1021
|
-
// session-wide changeset; chat channel: uncommitted + session + the
|
|
1022
|
-
// per-turn template).
|
|
1023
|
-
if (this.opts.changesets) {
|
|
1024
|
-
this.publish({
|
|
1025
|
-
channel,
|
|
1026
|
-
action: { type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(channel) },
|
|
1027
|
-
});
|
|
1028
|
-
this.publish({
|
|
1029
|
-
channel: rec.defaultChatURI,
|
|
1030
|
-
action: {
|
|
1031
|
-
type: ActionType.ChatChangesetsChanged,
|
|
1032
|
-
changesets: chatChangesetCatalog(rec.defaultChatURI, channel),
|
|
1033
|
-
},
|
|
1034
|
-
});
|
|
1035
|
-
}
|
|
1036
|
-
// Root: active-session count (action, replayed) + sessionAdded (notification).
|
|
1037
|
-
this.publish({
|
|
1038
|
-
channel: ROOT_CHANNEL,
|
|
1039
|
-
action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
|
|
1040
|
-
});
|
|
1041
|
-
this.notifyRoot("root/sessionAdded", {
|
|
1042
|
-
channel: ROOT_CHANNEL,
|
|
1043
|
-
summary: this.sessionSummary(rec),
|
|
1044
|
-
});
|
|
1045
|
-
|
|
1046
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
|
|
1047
|
-
}
|
|
1048
|
-
|
|
1049
|
-
// ── multi-chat ────────────────────────────────────
|
|
1050
|
-
|
|
1051
|
-
/**
|
|
1052
|
-
* Fresh per-chat runtime: one AHP chat = one opencode
|
|
1053
|
-
* session, with its own chat-state store and all the per-turn tracking
|
|
1054
|
-
* the event pump joins opencode events to.
|
|
1055
|
-
*/
|
|
1056
|
-
private newChatRuntime(uri: string, sessionID: string, title: string, modifiedAt: string): ChatRuntime {
|
|
1057
|
-
return {
|
|
1058
|
-
uri,
|
|
1059
|
-
sessionID,
|
|
1060
|
-
chatStore: createChatStateStore(initialChatState({ resource: uri, title, modifiedAt })),
|
|
1061
|
-
currentTurnId: null,
|
|
1062
|
-
turnStartedAt: null,
|
|
1063
|
-
turnModelRef: null,
|
|
1064
|
-
parts: new Set(),
|
|
1065
|
-
toolInput: new Map(),
|
|
1066
|
-
toolName: new Map(),
|
|
1067
|
-
toolReady: new Set(),
|
|
1068
|
-
permissionForTool: new Map(),
|
|
1069
|
-
toolForPermission: new Map(),
|
|
1070
|
-
clientToolCalls: new Map(),
|
|
1071
|
-
lastInbox: null,
|
|
1072
|
-
changesets: new Map(),
|
|
1073
|
-
turnSnapshots: new Map(),
|
|
1074
|
-
};
|
|
1075
|
-
}
|
|
1076
|
-
|
|
1077
|
-
/**
|
|
1078
|
-
* Bind a chat runtime to its record: the record's catalog, the
|
|
1079
|
-
* channel→record lookup, and the opencode-id→(record, chat) reverse
|
|
1080
|
-
* binding (the event pump's join key). The channel registry gets the
|
|
1081
|
-
* chat URI's suffix — that is what makes the chat channel and its
|
|
1082
|
-
* changesets (whose owner is the chat channel) subscribable. The
|
|
1083
|
-
* default chat's suffix IS its opencode id, added by the
|
|
1084
|
-
* registration paths; a peer chat's opencode id gets no registry
|
|
1085
|
-
* entry (it has no subscribable session channel of its own).
|
|
1086
|
-
*/
|
|
1087
|
-
private bindChat(rec: SessionRecord, chat: ChatRuntime): void {
|
|
1088
|
-
rec.chats.set(chat.uri, chat);
|
|
1089
|
-
this.byChannel.set(chat.uri, rec);
|
|
1090
|
-
this.byOpencode.set(chat.sessionID, { rec, chat });
|
|
1091
|
-
const suffix = sessionIDOf(chat.uri);
|
|
1092
|
-
if (suffix !== null) this.channels.addSession(suffix);
|
|
1093
|
-
}
|
|
1094
|
-
|
|
1095
|
-
/**
|
|
1096
|
-
* Unbind a chat runtime (dispose or record removal): clear its live
|
|
1097
|
-
* changesets (`changeset/cleared` — protocol case 2), fail its
|
|
1098
|
-
* in-flight client-tool executions (the waiters must not leak), and
|
|
1099
|
-
* drop every binding.
|
|
1100
|
-
*/
|
|
1101
|
-
private removeChat(rec: SessionRecord, chat: ChatRuntime, toolError = "chat removed before the client completed the tool call"): void {
|
|
1102
|
-
// The chat's terminal channels go with it
|
|
1103
|
-
// (running commands get a final `terminal/exited` first).
|
|
1104
|
-
this.teardownTerminalsForChat(chat);
|
|
1105
|
-
for (const uri of chat.changesets.keys()) {
|
|
1106
|
-
this.publish({ channel: uri, action: { type: ActionType.ChangesetCleared } });
|
|
1107
|
-
}
|
|
1108
|
-
chat.changesets.clear();
|
|
1109
|
-
chat.turnSnapshots.clear();
|
|
1110
|
-
for (const inv of chat.clientToolCalls.values()) {
|
|
1111
|
-
if (inv.result !== undefined) continue;
|
|
1112
|
-
inv.result = { ok: false, error: toolError };
|
|
1113
|
-
this.settleClientTool(inv);
|
|
1114
|
-
}
|
|
1115
|
-
chat.clientToolCalls.clear();
|
|
1116
|
-
rec.chats.delete(chat.uri);
|
|
1117
|
-
this.byChannel.delete(chat.uri);
|
|
1118
|
-
this.byOpencode.delete(chat.sessionID);
|
|
1119
|
-
const suffix = sessionIDOf(chat.uri);
|
|
1120
|
-
if (suffix !== null) this.channels.removeSession(suffix);
|
|
1121
|
-
this.channels.removeSession(chat.sessionID);
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
/**
|
|
1125
|
-
* `createChat` (AHP 1.0.0 chat command): create a new chat in an
|
|
1126
|
-
* existing session. The 1:1 mapping: mint a fresh
|
|
1127
|
-
* opencode session (same provider/model resolution as `createSession`)
|
|
1128
|
-
* and bind it to the client-chosen chat URI. Result: `null` (the
|
|
1129
|
-
* client waits for `session/chatAdded` on the session channel, and
|
|
1130
|
-
* rolls back with `disposeChat` when the chat never surfaces — so
|
|
1131
|
-
* everything below is published before the response). `source` and
|
|
1132
|
-
* `workingDirectories` are rejected with INVALID_PARAMS: the
|
|
1133
|
-
* capability is advertised without fork/sideChat/
|
|
1134
|
-
* multipleWorkingDirectories, so conformant clients never send them.
|
|
1135
|
-
*
|
|
1136
|
-
* Error codes: -32602 (invalid params, including `source`/
|
|
1137
|
-
* `workingDirectories`), -32001 (no such session), -32003 (chat URI
|
|
1138
|
-
* already exists), -32603 (backend session creation or initial
|
|
1139
|
-
* message failure — the chat is rolled back in that case).
|
|
1140
|
-
*/
|
|
1141
|
-
private async handleCreateChat(socketId: number, msg: RpcMessage): Promise<void> {
|
|
1142
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
1143
|
-
const channel = params["channel"];
|
|
1144
|
-
const chatURI = params["chat"];
|
|
1145
|
-
if (typeof channel !== "string" || channelKind(channel) !== "session") {
|
|
1146
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat requires an ahp-session:/… channel");
|
|
1147
|
-
return;
|
|
1148
|
-
}
|
|
1149
|
-
const rec = this.byChannel.get(channel);
|
|
1150
|
-
if (rec === undefined) {
|
|
1151
|
-
this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such session: ${channel}`);
|
|
1152
|
-
return;
|
|
1153
|
-
}
|
|
1154
|
-
if (typeof chatURI !== "string" || channelKind(chatURI) !== "chat") {
|
|
1155
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat requires an ahp-chat:/… chat URI");
|
|
1156
|
-
return;
|
|
1157
|
-
}
|
|
1158
|
-
// A marker in the chat suffix would make the chat channel
|
|
1159
|
-
// string-identical to a changeset URI of the chat before the marker
|
|
1160
|
-
// (the same trap createSession rejects for session suffixes).
|
|
1161
|
-
if (chatURI.includes("/changeset/")) {
|
|
1162
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "chat URI must not contain \"/changeset/\"");
|
|
1163
|
-
return;
|
|
1164
|
-
}
|
|
1165
|
-
if (chatURI === rec.defaultChatURI || rec.chats.has(chatURI)) {
|
|
1166
|
-
this.sendError(socketId, msg.id, ERROR_SESSION_EXISTS, `chat already exists: ${chatURI}`);
|
|
1167
|
-
return;
|
|
1168
|
-
}
|
|
1169
|
-
if (params["source"] !== undefined) {
|
|
1170
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat `source` is not supported (no fork/sideChat capability)");
|
|
1171
|
-
return;
|
|
1172
|
-
}
|
|
1173
|
-
if (params["workingDirectories"] !== undefined) {
|
|
1174
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat `workingDirectories` is not supported (no multipleWorkingDirectories capability)");
|
|
1175
|
-
return;
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
// Same provider/model resolution as createSession's default path:
|
|
1179
|
-
// the first non-disabled provider's first enabled model.
|
|
1180
|
-
const providers = await this.opts.facade.listCatalog();
|
|
1181
|
-
const provider = providers.find((p) => p.activation !== "disabled");
|
|
1182
|
-
const model = provider !== undefined ? firstEnabledModelRef(provider.models) : undefined;
|
|
1183
|
-
const now = new Date().toISOString();
|
|
1184
|
-
let created;
|
|
1185
|
-
try {
|
|
1186
|
-
// Write the chat-binding marker atomically at
|
|
1187
|
-
// create — it is what re-attaches this backend to this session's
|
|
1188
|
-
// chat catalog after an opencode/plugin restart (opencode session
|
|
1189
|
-
// metadata is the only durable surface a plugin has).
|
|
1190
|
-
created = await this.opts.facade.createSession({
|
|
1191
|
-
model,
|
|
1192
|
-
metadata: { [AHP_METADATA_KEY]: { chat: chatURI, owner: rec.sessionID } },
|
|
1193
|
-
});
|
|
1194
|
-
} catch (err) {
|
|
1195
|
-
this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to create the chat's backend session: ${errorMessage(err)}`);
|
|
1196
|
-
return;
|
|
1197
|
-
}
|
|
1198
|
-
const chat = this.newChatRuntime(chatURI, created.sessionID, `Chat ${rec.chats.size + 1}`, now);
|
|
1199
|
-
this.bindChat(rec, chat);
|
|
1200
|
-
// Session-channel lifecycle (server-side, no origin): the catalog
|
|
1201
|
-
// mutation the client is waiting for, plus the changeset catalogue
|
|
1202
|
-
// on the new chat channel.
|
|
1203
|
-
this.publish({
|
|
1204
|
-
channel,
|
|
1205
|
-
action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chat.chatStore.state) },
|
|
1206
|
-
});
|
|
1207
|
-
if (this.opts.changesets) {
|
|
1208
|
-
this.publish({
|
|
1209
|
-
channel: chatURI,
|
|
1210
|
-
action: { type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(chatURI, rec.channel) },
|
|
1211
|
-
});
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
// initialMessage → the chat's first turn (write-ahead, same
|
|
1215
|
-
// claim-then-prompt semantics as dispatchTurnStarted). A failure
|
|
1216
|
-
// rolls the whole chat back — the client never sees a chat whose
|
|
1217
|
-
// promised first turn never happened.
|
|
1218
|
-
const initialParam = params["initialMessage"];
|
|
1219
|
-
if (initialParam !== undefined) {
|
|
1220
|
-
if (!isRecord(initialParam) || typeof initialParam["text"] !== "string" || (initialParam["text"] as string).length === 0) {
|
|
1221
|
-
await this.disposeChatBackend(rec, chat);
|
|
1222
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createChat `initialMessage` requires a message with non-empty text");
|
|
1223
|
-
return;
|
|
1224
|
-
}
|
|
1225
|
-
const message = initialParam as unknown as Message;
|
|
1226
|
-
const selectionError = await this.applyMessageSelection(chat, message);
|
|
1227
|
-
if (selectionError !== null) {
|
|
1228
|
-
await this.disposeChatBackend(rec, chat);
|
|
1229
|
-
this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to apply initial message model/agent selection: ${selectionError}`);
|
|
1230
|
-
return;
|
|
1231
|
-
}
|
|
1232
|
-
const turnId = this.mintTurnId();
|
|
1233
|
-
chat.currentTurnId = turnId;
|
|
1234
|
-
chat.turnStartedAt = Date.now();
|
|
1235
|
-
try {
|
|
1236
|
-
await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text });
|
|
1237
|
-
} catch (err) {
|
|
1238
|
-
chat.currentTurnId = null;
|
|
1239
|
-
chat.turnStartedAt = null;
|
|
1240
|
-
await this.disposeChatBackend(rec, chat);
|
|
1241
|
-
this.sendError(socketId, msg.id, ERROR_INTERNAL, `initial message failed: ${errorMessage(err)}`);
|
|
1242
|
-
return;
|
|
1243
|
-
}
|
|
1244
|
-
this.publish({
|
|
1245
|
-
channel: chatURI,
|
|
1246
|
-
action: {
|
|
1247
|
-
type: ActionType.ChatTurnStarted,
|
|
1248
|
-
turnId,
|
|
1249
|
-
startedAt: new Date().toISOString(),
|
|
1250
|
-
message,
|
|
1251
|
-
},
|
|
1252
|
-
});
|
|
1253
|
-
}
|
|
1254
|
-
|
|
1255
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
|
|
1256
|
-
}
|
|
1257
|
-
|
|
1258
|
-
/**
|
|
1259
|
-
* `disposeChat` (AHP 1.0.0 chat command): remove a chat and its
|
|
1260
|
-
* opencode session from the session catalog. Result: `null`. The
|
|
1261
|
-
* default chat cannot be disposed — a session keeps its default chat
|
|
1262
|
-
* (there is no re-home mechanism; disposing it would leave the
|
|
1263
|
-
* `defaultChat` hint dangling). VS Code's createChat-rollback path
|
|
1264
|
-
* relies on `disposeChat` being answerable for any chat it created.
|
|
1265
|
-
*/
|
|
1266
|
-
private async handleDisposeChat(socketId: number, msg: RpcMessage): Promise<void> {
|
|
1267
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
1268
|
-
const channel = params["channel"];
|
|
1269
|
-
if (typeof channel !== "string" || channelKind(channel) !== "chat") {
|
|
1270
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "disposeChat requires an ahp-chat:/… channel");
|
|
1271
|
-
return;
|
|
1272
|
-
}
|
|
1273
|
-
const rec = this.byChannel.get(channel);
|
|
1274
|
-
const chat = rec !== undefined ? rec.chats.get(channel) : undefined;
|
|
1275
|
-
if (rec === undefined || chat === undefined) {
|
|
1276
|
-
this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such chat: ${channel}`);
|
|
1277
|
-
return;
|
|
1278
|
-
}
|
|
1279
|
-
if (channel === rec.defaultChatURI) {
|
|
1280
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "the default chat cannot be disposed");
|
|
1281
|
-
return;
|
|
1282
|
-
}
|
|
1283
|
-
await this.disposeChatBackend(rec, chat);
|
|
1284
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
|
|
1285
|
-
}
|
|
1286
|
-
|
|
1287
|
-
/**
|
|
1288
|
-
* Remove a chat from the AHP surface, then its opencode session. The
|
|
1289
|
-
* AHP-side unbind goes FIRST: opencode's `session.deleted` event for
|
|
1290
|
-
* the backend races this call through the event pump, and the pump
|
|
1291
|
-
* must see the chat already unbound (its `byOpencode` guard) or it
|
|
1292
|
-
* would publish a duplicate `session/chatRemoved`. R2: a failed
|
|
1293
|
-
* removal still drops the AHP chat — the lingering opencode session
|
|
1294
|
-
* shows up in the TUI (and lazily in `listSessions`) until deleted
|
|
1295
|
-
* there.
|
|
1296
|
-
*/
|
|
1297
|
-
private async disposeChatBackend(rec: SessionRecord, chat: ChatRuntime): Promise<void> {
|
|
1298
|
-
this.removeChat(rec, chat);
|
|
1299
|
-
try {
|
|
1300
|
-
await this.opts.facade.removeSession(chat.sessionID);
|
|
1301
|
-
} catch (err) {
|
|
1302
|
-
this.log(`failed to remove the chat's opencode session ${chat.sessionID}: ${errorMessage(err)}`);
|
|
1303
|
-
}
|
|
1304
|
-
this.publish({ channel: rec.channel, action: { type: ActionType.SessionChatRemoved, chat: chat.uri } });
|
|
1305
|
-
}
|
|
1306
|
-
|
|
1307
|
-
/**
|
|
1308
|
-
* Apply a message's model/agent selection to a chat's opencode session
|
|
1309
|
-
* before its prompt (`SessionPromptInput` carries no model/agent
|
|
1310
|
-
* fields). Null on success, the error message on failure.
|
|
1311
|
-
*/
|
|
1312
|
-
private async applyMessageSelection(chat: ChatRuntime, message: Message): Promise<string | null> {
|
|
1313
|
-
try {
|
|
1314
|
-
if (message.model?.id !== undefined && message.model.id.includes("/")) {
|
|
1315
|
-
const sep = message.model.id.indexOf("/");
|
|
1316
|
-
const providerID = message.model.id.slice(0, sep);
|
|
1317
|
-
const modelID = message.model.id.slice(sep + 1);
|
|
1318
|
-
if (providerID.length > 0 && modelID.length > 0) {
|
|
1319
|
-
await this.opts.facade.switchModel({ sessionID: chat.sessionID, model: { providerID, modelID } });
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
if (message.agent?.uri !== undefined) {
|
|
1323
|
-
const agentID = agentIDFromUri(message.agent.uri);
|
|
1324
|
-
if (agentID !== null) {
|
|
1325
|
-
await this.opts.facade.switchAgent({ sessionID: chat.sessionID, agent: agentID });
|
|
1326
|
-
}
|
|
1327
|
-
}
|
|
1328
|
-
} catch (err) {
|
|
1329
|
-
return errorMessage(err);
|
|
1330
|
-
}
|
|
1331
|
-
return null;
|
|
1332
|
-
}
|
|
1333
|
-
|
|
1334
|
-
/**
|
|
1335
|
-
* `listSessions` (AHP 1.0.0 root command): all opencode sessions,
|
|
1336
|
-
* most-recently-modified first, with in-memory cursor pagination.
|
|
1337
|
-
* Unknown sessions are lazily registered (so their channels become
|
|
1338
|
-
* subscribable); registration is idempotent per opencode session id.
|
|
1339
|
-
*/
|
|
1340
|
-
private async handleListSessions(socketId: number, msg: RpcMessage): Promise<void> {
|
|
1341
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
1342
|
-
const limit =
|
|
1343
|
-
typeof params["limit"] === "number" && Number.isInteger(params["limit"]) && (params["limit"] as number) > 0
|
|
1344
|
-
? (params["limit"] as number)
|
|
1345
|
-
: LIST_SESSIONS_DEFAULT_LIMIT;
|
|
1346
|
-
let offset = 0;
|
|
1347
|
-
if (typeof params["cursor"] === "string" && params["cursor"].length > 0) {
|
|
1348
|
-
const parsed = Number.parseInt(params["cursor"], 10);
|
|
1349
|
-
if (Number.isInteger(parsed) && parsed > 0) offset = parsed;
|
|
1350
|
-
}
|
|
1351
|
-
const listed = await this.opts.facade.listSessions();
|
|
1352
|
-
const records: (SessionRecord | undefined)[] = [];
|
|
1353
|
-
for (const fs of listed) {
|
|
1354
|
-
records.push(this.registerExternal(fs) ?? this.sessions.get(fs.sessionID));
|
|
1355
|
-
}
|
|
1356
|
-
const sorted = records
|
|
1357
|
-
.filter((r): r is SessionRecord => r !== undefined)
|
|
1358
|
-
.sort((a, b) => {
|
|
1359
|
-
const ta = this.sessions.get(a.sessionID)?.modifiedAt ?? a.modifiedAt;
|
|
1360
|
-
const tb = this.sessions.get(b.sessionID)?.modifiedAt ?? b.modifiedAt;
|
|
1361
|
-
return ta < tb ? 1 : ta > tb ? -1 : 0;
|
|
1362
|
-
});
|
|
1363
|
-
const page = sorted.slice(offset, offset + limit);
|
|
1364
|
-
const nextOffset = offset + limit;
|
|
1365
|
-
const result: { items: SessionSummary[]; nextCursor?: string } = {
|
|
1366
|
-
items: page.map((rec) => this.sessionSummary(rec)),
|
|
1367
|
-
};
|
|
1368
|
-
if (nextOffset < sorted.length) result.nextCursor = String(nextOffset);
|
|
1369
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
|
|
1370
|
-
}
|
|
1371
|
-
|
|
1372
|
-
/**
|
|
1373
|
-
* AHP 1.0.0 root command — the client resolves the session-creation
|
|
1374
|
-
* config schema. VS Code calls it every time the new-session composer
|
|
1375
|
-
* opens and STRICTLY again before the first send of a new session
|
|
1376
|
-
* (`_sendNewSessionRequest`), so an unimplemented host makes every
|
|
1377
|
-
* fresh session unstartable ("unknown method: resolveSessionConfig").
|
|
1378
|
-
* opencode collects no session-creation configuration —
|
|
1379
|
-
* agent/model choice rides session-state customizations and the
|
|
1380
|
-
* per-turn message — so the honest answer is an empty schema with
|
|
1381
|
-
* empty values. `provider` / `workingDirectory` / `config` are
|
|
1382
|
-
* accepted and deliberately unused: sessions run in the location
|
|
1383
|
-
* directory and the host advertises no config properties (which also
|
|
1384
|
-
* keeps `sessionConfigCompletions` unreachable — it only serves
|
|
1385
|
-
* `enumDynamic` properties this schema does not carry).
|
|
1386
|
-
*/
|
|
1387
|
-
private handleResolveSessionConfig(socketId: number, msg: RpcMessage): void {
|
|
1388
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
1389
|
-
if (params["channel"] !== ROOT_CHANNEL) {
|
|
1390
|
-
this.sendError(
|
|
1391
|
-
socketId,
|
|
1392
|
-
msg.id,
|
|
1393
|
-
ERROR_INVALID_PARAMS,
|
|
1394
|
-
"resolveSessionConfig requires the ahp-root:// channel",
|
|
1395
|
-
);
|
|
1396
|
-
return;
|
|
1397
|
-
}
|
|
1398
|
-
const result: ResolveSessionConfigResult = {
|
|
1399
|
-
schema: { type: "object", properties: {} },
|
|
1400
|
-
values: {},
|
|
1401
|
-
};
|
|
1402
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result });
|
|
1403
|
-
}
|
|
1404
|
-
|
|
1405
|
-
// ── client-dispatchable actions ──────────────────────────────
|
|
1406
|
-
|
|
1407
|
-
/**
|
|
1408
|
-
* `dispatchAction` is a notification — the response is the `action`
|
|
1409
|
-
* notification stream itself. The host routes the client-dispatchable
|
|
1410
|
-
* actions VS Code sends; everything else is acknowledged with a
|
|
1411
|
-
* rejection on that stream.
|
|
1412
|
-
*/
|
|
1413
|
-
private async handleDispatchAction(socketId: number, msg: RpcMessage): Promise<void> {
|
|
1414
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
1415
|
-
const channel = params["channel"];
|
|
1416
|
-
const clientSeq = params["clientSeq"];
|
|
1417
|
-
const action = params["action"];
|
|
1418
|
-
if (
|
|
1419
|
-
typeof channel !== "string" ||
|
|
1420
|
-
channel.length === 0 ||
|
|
1421
|
-
!Number.isInteger(clientSeq) ||
|
|
1422
|
-
!isRecord(action) ||
|
|
1423
|
-
typeof action["type"] !== "string"
|
|
1424
|
-
) {
|
|
1425
|
-
this.log(`malformed dispatchAction on socket ${socketId} (dropped)`);
|
|
1426
|
-
return;
|
|
1427
|
-
}
|
|
1428
|
-
|
|
1429
|
-
const socket = this.sockets.get(socketId);
|
|
1430
|
-
const clientId = socket?.clientId ?? null;
|
|
1431
|
-
const origin: ActionOrigin | undefined =
|
|
1432
|
-
clientId !== null ? { clientId, clientSeq: clientSeq as number } : undefined;
|
|
1433
|
-
|
|
1434
|
-
const stateAction = action as unknown as StateAction;
|
|
1435
|
-
const rejectionReason = this.dispatchRejectionReason(channel, stateAction, clientId);
|
|
1436
|
-
if (rejectionReason !== null) {
|
|
1437
|
-
this.echo(channel, stateAction, origin, rejectionReason);
|
|
1438
|
-
return;
|
|
1439
|
-
}
|
|
1440
|
-
|
|
1441
|
-
const kind = channelKind(channel);
|
|
1442
|
-
if (kind === "changeset") {
|
|
1443
|
-
// The only client-dispatchable changeset action is the per-file
|
|
1444
|
-
// review toggle — echo it through the official reducer.
|
|
1445
|
-
if (stateAction.type === ActionType.ChangesetFilesReviewChanged) {
|
|
1446
|
-
this.dispatchChangesetFilesReviewChanged(channel, stateAction, origin);
|
|
1447
|
-
} else {
|
|
1448
|
-
this.echo(channel, stateAction, origin, `unsupported action on changeset channel: ${String(action.type)}`);
|
|
1449
|
-
}
|
|
1450
|
-
return;
|
|
1451
|
-
}
|
|
1452
|
-
if (kind === "terminal") {
|
|
1453
|
-
// The synthetic terminals are read-only
|
|
1454
|
-
// renderings of shell-tool calls — every client-dispatchable
|
|
1455
|
-
// action (`input`, `resized`, `claimed`, `titleChanged`,
|
|
1456
|
-
// `cleared`) has no pty to act on, so each gets an explicit
|
|
1457
|
-
// rejection (write-ahead clients roll back on the reason); the
|
|
1458
|
-
// `no such terminal` check covers a channel whose chat was removed.
|
|
1459
|
-
this.echo(
|
|
1460
|
-
channel,
|
|
1461
|
-
stateAction,
|
|
1462
|
-
origin,
|
|
1463
|
-
this.terminals.has(channel)
|
|
1464
|
-
? "read-only terminal: this host's terminals render shell tool calls and accept no input, resize, claim, title, or clear"
|
|
1465
|
-
: `no such terminal: ${channel}`,
|
|
1466
|
-
);
|
|
1467
|
-
return;
|
|
1468
|
-
}
|
|
1469
|
-
if (kind !== "session" && kind !== "chat") {
|
|
1470
|
-
this.echo(channel, stateAction, origin, `unsupported action on ${channelKind(channel)} channel: ${String(action.type)}`);
|
|
1471
|
-
return;
|
|
1472
|
-
}
|
|
1473
|
-
const rec = this.byChannel.get(channel);
|
|
1474
|
-
if (rec === undefined) {
|
|
1475
|
-
this.echo(
|
|
1476
|
-
channel,
|
|
1477
|
-
stateAction,
|
|
1478
|
-
origin,
|
|
1479
|
-
kind === "chat" ? `no such chat: ${channel}` : `no such session: ${channel}`,
|
|
1480
|
-
);
|
|
1481
|
-
return;
|
|
1482
|
-
}
|
|
1483
|
-
if (kind === "chat" && !rec.chats.has(channel)) {
|
|
1484
|
-
this.echo(channel, stateAction, origin, `no such chat: ${channel}`);
|
|
1485
|
-
return;
|
|
1486
|
-
}
|
|
1487
|
-
// Chat actions run against the owning chat runtime;
|
|
1488
|
-
// a chat action on a session channel is rejected (a session no
|
|
1489
|
-
// longer identifies a single chat once multi-chat is on).
|
|
1490
|
-
const chat = rec.chats.get(channel);
|
|
1491
|
-
const noChat = () => this.echo(channel, stateAction, origin, `chat actions require a chat channel: ${channel}`);
|
|
1492
|
-
|
|
1493
|
-
// From here on every branch either echoes (accepted or rejected).
|
|
1494
|
-
switch (stateAction.type) {
|
|
1495
|
-
case ActionType.ChatTurnStarted:
|
|
1496
|
-
if (chat === undefined) { noChat(); return; }
|
|
1497
|
-
await this.dispatchTurnStarted(chat, stateAction, origin);
|
|
1498
|
-
return;
|
|
1499
|
-
case ActionType.ChatPendingMessageSet:
|
|
1500
|
-
if (chat === undefined) { noChat(); return; }
|
|
1501
|
-
await this.dispatchPendingMessageSet(chat, stateAction, origin);
|
|
1502
|
-
return;
|
|
1503
|
-
case ActionType.ChatToolCallConfirmed:
|
|
1504
|
-
if (chat === undefined) { noChat(); return; }
|
|
1505
|
-
await this.dispatchToolCallConfirmed(chat, stateAction, origin);
|
|
1506
|
-
return;
|
|
1507
|
-
case ActionType.ChatToolCallComplete:
|
|
1508
|
-
if (chat === undefined) { noChat(); return; }
|
|
1509
|
-
await this.dispatchToolCallComplete(chat, stateAction, origin);
|
|
1510
|
-
return;
|
|
1511
|
-
case ActionType.ChatToolCallContentChanged:
|
|
1512
|
-
if (chat === undefined) { noChat(); return; }
|
|
1513
|
-
this.dispatchToolCallContentChanged(chat, stateAction, origin);
|
|
1514
|
-
return;
|
|
1515
|
-
case ActionType.ChatToolCallResultConfirmed:
|
|
1516
|
-
if (chat === undefined) { noChat(); return; }
|
|
1517
|
-
this.dispatchToolCallResultConfirmed(chat, stateAction, origin);
|
|
1518
|
-
return;
|
|
1519
|
-
case ActionType.ChatTurnCancelled:
|
|
1520
|
-
if (chat === undefined) { noChat(); return; }
|
|
1521
|
-
await this.dispatchTurnCancelled(chat, stateAction, origin);
|
|
1522
|
-
return;
|
|
1523
|
-
case ActionType.SessionTitleChanged:
|
|
1524
|
-
await this.dispatchTitleChanged(rec, stateAction, origin);
|
|
1525
|
-
return;
|
|
1526
|
-
case ActionType.SessionActiveClientSet:
|
|
1527
|
-
this.dispatchActiveClientSet(rec, stateAction, origin, clientId);
|
|
1528
|
-
return;
|
|
1529
|
-
case ActionType.SessionActiveClientRemoved:
|
|
1530
|
-
this.dispatchActiveClientRemoved(rec, stateAction, origin, clientId);
|
|
1531
|
-
return;
|
|
1532
|
-
case ActionType.ChatPendingMessageRemoved:
|
|
1533
|
-
// Honest gap: the opencode plugin surface has no inbox cancel —
|
|
1534
|
-
// a pending (steer/queue) message cannot be withdrawn once sent.
|
|
1535
|
-
this.echo(channel, stateAction, origin, "cannot remove a pending message: opencode has no inbox cancel");
|
|
1536
|
-
return;
|
|
1537
|
-
case ActionType.ChatDraftChanged:
|
|
1538
|
-
case ActionType.ChatIsReadChanged:
|
|
1539
|
-
case ActionType.ChatIsArchivedChanged:
|
|
1540
|
-
case ActionType.SessionIsReadChanged:
|
|
1541
|
-
case ActionType.SessionIsArchivedChanged:
|
|
1542
|
-
this.echo(channel, stateAction, origin);
|
|
1543
|
-
return;
|
|
1544
|
-
default:
|
|
1545
|
-
this.echo(channel, stateAction, origin, `unsupported action: ${String(stateAction.type)}`);
|
|
1546
|
-
}
|
|
1547
|
-
}
|
|
1548
|
-
|
|
1549
|
-
/**
|
|
1550
|
-
* Shared pre-checks for a dispatched action; null when the action may
|
|
1551
|
-
* proceed to per-type handling.
|
|
1552
|
-
*/
|
|
1553
|
-
private dispatchRejectionReason(channel: string, action: StateAction, clientId: string | null): string | null {
|
|
1554
|
-
if (channelKind(channel) === "unknown") return `unknown channel: ${channel}`;
|
|
1555
|
-
let dispatchable: boolean;
|
|
1556
|
-
try {
|
|
1557
|
-
dispatchable = isClientDispatchable(action as Parameters<typeof isClientDispatchable>[0]);
|
|
1558
|
-
} catch {
|
|
1559
|
-
dispatchable = false;
|
|
1560
|
-
}
|
|
1561
|
-
if (!dispatchable) return `action ${String(action.type)} is not client-dispatchable`;
|
|
1562
|
-
if (clientId === null) return "client is not initialized";
|
|
1563
|
-
return null;
|
|
1564
|
-
}
|
|
1565
|
-
|
|
1566
|
-
/** Publish an accepted echo (or a rejection) on the action stream. */
|
|
1567
|
-
private echo(
|
|
1568
|
-
channel: string,
|
|
1569
|
-
action: StateAction,
|
|
1570
|
-
origin: ActionOrigin | undefined,
|
|
1571
|
-
rejectionReason?: string,
|
|
1572
|
-
): void {
|
|
1573
|
-
const envelope = this.publish({
|
|
1574
|
-
channel,
|
|
1575
|
-
action,
|
|
1576
|
-
origin,
|
|
1577
|
-
...(rejectionReason !== undefined ? { rejectionReason } : {}),
|
|
1578
|
-
});
|
|
1579
|
-
if (rejectionReason !== undefined && origin !== undefined) {
|
|
1580
|
-
// A rejection must reach the dispatching socket even when it is not
|
|
1581
|
-
// subscribed to the channel (write-ahead dispatch: the client applied
|
|
1582
|
-
// the action optimistically and needs the rejection to roll it back).
|
|
1583
|
-
const socketId = this.socketIdForClient(origin.clientId);
|
|
1584
|
-
if (socketId !== undefined && !this.channels.socketsSubscribedTo(channel).includes(socketId)) {
|
|
1585
|
-
this.opts.send(socketId, { jsonrpc: "2.0", method: "action", params: envelope });
|
|
1586
|
-
}
|
|
1587
|
-
}
|
|
1588
|
-
}
|
|
1589
|
-
|
|
1590
|
-
/** The socket currently bound to a clientId (rejection delivery target). */
|
|
1591
|
-
private socketIdForClient(clientId: string): number | undefined {
|
|
1592
|
-
for (const [socketId, socket] of this.sockets) {
|
|
1593
|
-
if (socket.clientId === clientId) return socketId;
|
|
1594
|
-
}
|
|
1595
|
-
return undefined;
|
|
1596
|
-
}
|
|
1597
|
-
|
|
1598
|
-
private async dispatchTurnStarted(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
1599
|
-
const chatURI = chat.uri;
|
|
1600
|
-
const a = action as ChatTurnStartedAction;
|
|
1601
|
-
const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
|
|
1602
|
-
const message =
|
|
1603
|
-
isRecord(a.message) && typeof a.message["text"] === "string"
|
|
1604
|
-
? (a.message as unknown as Message)
|
|
1605
|
-
: null;
|
|
1606
|
-
if (turnId === null || message === null) {
|
|
1607
|
-
this.echo(chatURI, action, origin, "invalid chat/turnStarted params");
|
|
1608
|
-
return;
|
|
1609
|
-
}
|
|
1610
|
-
// `startedAt` is required on the wire (the reducer uses it for the
|
|
1611
|
-
// chat's `modifiedAt`); fall back to the host clock when the client
|
|
1612
|
-
// did not supply a parseable one.
|
|
1613
|
-
const normalized: ChatTurnStartedAction =
|
|
1614
|
-
typeof a.startedAt === "string" && !Number.isNaN(Date.parse(a.startedAt))
|
|
1615
|
-
? a
|
|
1616
|
-
: { ...a, startedAt: new Date().toISOString() };
|
|
1617
|
-
if (chat.chatStore.state.activeTurn !== undefined) {
|
|
1618
|
-
this.echo(
|
|
1619
|
-
chatURI,
|
|
1620
|
-
action,
|
|
1621
|
-
origin,
|
|
1622
|
-
"a turn is already active; follow-up messages go via chat/pendingMessageSet",
|
|
1623
|
-
);
|
|
1624
|
-
return;
|
|
1625
|
-
}
|
|
1626
|
-
|
|
1627
|
-
// Apply the message's model/agent selection to THIS chat's opencode
|
|
1628
|
-
// session before the prompt (per-chat isolation).
|
|
1629
|
-
const selectionError = await this.applyMessageSelection(chat, message);
|
|
1630
|
-
if (selectionError !== null) {
|
|
1631
|
-
this.echo(chatURI, action, origin, `failed to apply model/agent selection: ${selectionError}`);
|
|
1632
|
-
return;
|
|
1633
|
-
}
|
|
1634
|
-
|
|
1635
|
-
// Write-ahead: claim the turn BEFORE the prompt so the
|
|
1636
|
-
// `session.execution.started` event joins it even when it races the
|
|
1637
|
-
// prompt's resolve; revert on failure.
|
|
1638
|
-
chat.currentTurnId = turnId;
|
|
1639
|
-
chat.turnStartedAt = Date.now();
|
|
1640
|
-
try {
|
|
1641
|
-
await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text });
|
|
1642
|
-
} catch (err) {
|
|
1643
|
-
chat.currentTurnId = null;
|
|
1644
|
-
chat.turnStartedAt = null;
|
|
1645
|
-
this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
|
|
1646
|
-
return;
|
|
1647
|
-
}
|
|
1648
|
-
this.echo(chatURI, normalized, origin);
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
|
-
private async dispatchPendingMessageSet(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
1652
|
-
const chatURI = chat.uri;
|
|
1653
|
-
const a = action as { kind?: unknown; id?: unknown; message?: unknown };
|
|
1654
|
-
const kind = a.kind === "steering" || a.kind === "queued" ? a.kind : null;
|
|
1655
|
-
const id = typeof a.id === "string" && a.id.length > 0 ? a.id : null;
|
|
1656
|
-
const message =
|
|
1657
|
-
isRecord(a.message) && typeof a.message["text"] === "string"
|
|
1658
|
-
? (a.message as unknown as Message)
|
|
1659
|
-
: null;
|
|
1660
|
-
if (kind === null || id === null || message === null) {
|
|
1661
|
-
this.echo(chatURI, action, origin, "invalid chat/pendingMessageSet params");
|
|
1662
|
-
return;
|
|
1663
|
-
}
|
|
1664
|
-
const hasActiveTurn = chat.chatStore.state.activeTurn !== undefined;
|
|
1665
|
-
// steer → delivery "steer" (only while a turn is active); queued →
|
|
1666
|
-
// delivery "queue"; a steering message with no active turn falls back
|
|
1667
|
-
// to a plain prompt (it becomes the next turn).
|
|
1668
|
-
const delivery: FacadeDelivery | undefined = hasActiveTurn
|
|
1669
|
-
? kind === "steering"
|
|
1670
|
-
? "steer"
|
|
1671
|
-
: "queue"
|
|
1672
|
-
: undefined;
|
|
1673
|
-
try {
|
|
1674
|
-
await this.opts.facade.prompt({ sessionID: chat.sessionID, text: message.text, delivery });
|
|
1675
|
-
} catch (err) {
|
|
1676
|
-
this.echo(chatURI, action, origin, `prompt failed: ${errorMessage(err)}`);
|
|
1677
|
-
return;
|
|
1678
|
-
}
|
|
1679
|
-
if (hasActiveTurn) {
|
|
1680
|
-
this.echo(chatURI, action, origin);
|
|
1681
|
-
return;
|
|
1682
|
-
}
|
|
1683
|
-
// No active turn: the message starts a turn right now. Echo the
|
|
1684
|
-
// pending-message first, then a host-minted turnStarted carrying
|
|
1685
|
-
// `queuedMessageId` — the reducer dequeues it.
|
|
1686
|
-
this.echo(chatURI, action, origin);
|
|
1687
|
-
const turnId = this.mintTurnId();
|
|
1688
|
-
chat.currentTurnId = turnId;
|
|
1689
|
-
chat.turnStartedAt = Date.now();
|
|
1690
|
-
this.publish({
|
|
1691
|
-
channel: chatURI,
|
|
1692
|
-
action: {
|
|
1693
|
-
type: ActionType.ChatTurnStarted,
|
|
1694
|
-
turnId,
|
|
1695
|
-
startedAt: new Date().toISOString(),
|
|
1696
|
-
message,
|
|
1697
|
-
queuedMessageId: id,
|
|
1698
|
-
},
|
|
1699
|
-
});
|
|
1700
|
-
}
|
|
1701
|
-
|
|
1702
|
-
private async dispatchToolCallConfirmed(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
1703
|
-
const chatURI = chat.uri;
|
|
1704
|
-
const rec = this.byChannel.get(chatURI)!;
|
|
1705
|
-
const a = action as ChatToolCallConfirmedAction;
|
|
1706
|
-
const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
|
|
1707
|
-
if (toolCallId === null) {
|
|
1708
|
-
this.echo(chatURI, action, origin, "invalid chat/toolCallConfirmed params");
|
|
1709
|
-
return;
|
|
1710
|
-
}
|
|
1711
|
-
const permissionID = chat.permissionForTool.get(toolCallId);
|
|
1712
|
-
if (permissionID === undefined) {
|
|
1713
|
-
this.echo(chatURI, action, origin, `no pending permission for tool call ${toolCallId}`);
|
|
1714
|
-
return;
|
|
1715
|
-
}
|
|
1716
|
-
try {
|
|
1717
|
-
await this.opts.facade.replyPermission({
|
|
1718
|
-
sessionID: chat.sessionID,
|
|
1719
|
-
requestID: permissionID,
|
|
1720
|
-
decision: a.approved === true ? "once" : "reject",
|
|
1721
|
-
});
|
|
1722
|
-
} catch (err) {
|
|
1723
|
-
this.echo(chatURI, action, origin, `permission reply failed: ${errorMessage(err)}`);
|
|
1724
|
-
return;
|
|
1725
|
-
}
|
|
1726
|
-
// Echo the confirmation (reducer → running/cancelled), then clear the
|
|
1727
|
-
// session-level input request. The `permission.replied` event is a
|
|
1728
|
-
// safety net (its tracking is already gone → no-op).
|
|
1729
|
-
this.echo(chatURI, action, origin);
|
|
1730
|
-
this.publish({
|
|
1731
|
-
channel: rec.channel,
|
|
1732
|
-
action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
|
|
1733
|
-
});
|
|
1734
|
-
chat.permissionForTool.delete(toolCallId);
|
|
1735
|
-
chat.toolForPermission.delete(permissionID);
|
|
1736
|
-
}
|
|
1737
|
-
|
|
1738
|
-
// ── client-executed tool calls ───────────────────
|
|
1739
|
-
|
|
1740
|
-
/**
|
|
1741
|
-
* `chat/toolCallComplete` (client-dispatchable): the owning client
|
|
1742
|
-
* finished executing a delegated tool call. Only valid for
|
|
1743
|
-
* client-executed calls (the host emits its own complete for
|
|
1744
|
-
* server-executed ones); the dispatching client must be the
|
|
1745
|
-
* contributor. Echoes the action (reducer: running → completed, or
|
|
1746
|
-
* → pending-result-confirmation when `requiresResultConfirmation`),
|
|
1747
|
-
* clears the execution input request, and settles the opencode-side
|
|
1748
|
-
* waiter with the client's result.
|
|
1749
|
-
*/
|
|
1750
|
-
private async dispatchToolCallComplete(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
1751
|
-
const chatURI = chat.uri;
|
|
1752
|
-
const rec = this.byChannel.get(chatURI)!;
|
|
1753
|
-
const a = action as ChatToolCallCompleteAction;
|
|
1754
|
-
const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
|
|
1755
|
-
const invocation = toolCallId !== null ? chat.clientToolCalls.get(toolCallId) : undefined;
|
|
1756
|
-
if (toolCallId === null || invocation === undefined) {
|
|
1757
|
-
this.echo(chatURI, action, origin, `tool call ${toolCallId ?? "?"} is not a client-executed call`);
|
|
1758
|
-
return;
|
|
1759
|
-
}
|
|
1760
|
-
if (origin !== undefined && invocation.clientId !== origin.clientId) {
|
|
1761
|
-
this.echo(chatURI, action, origin, `only the contributing client (${invocation.clientId}) may complete this call`);
|
|
1762
|
-
return;
|
|
1763
|
-
}
|
|
1764
|
-
const result = normalizeToolCallResult(a.result);
|
|
1765
|
-
if (result === null) {
|
|
1766
|
-
this.echo(chatURI, action, origin, "invalid chat/toolCallComplete params (result.success must be a boolean)");
|
|
1767
|
-
return;
|
|
1768
|
-
}
|
|
1769
|
-
const status = this.toolCallState(chat, toolCallId)?.status;
|
|
1770
|
-
if (status !== ToolCallStatus.Running && status !== ToolCallStatus.PendingConfirmation) {
|
|
1771
|
-
this.echo(chatURI, action, origin, `tool call ${toolCallId} is not ready to complete (status ${status ?? "absent"})`);
|
|
1772
|
-
return;
|
|
1773
|
-
}
|
|
1774
|
-
const requiresConfirmation = a.requiresResultConfirmation === true;
|
|
1775
|
-
// Echo first: the reducer moves running → completed (or
|
|
1776
|
-
// pending-result-confirmation); the settle below must observe the
|
|
1777
|
-
// new state for the confirmation input request.
|
|
1778
|
-
this.echo(chatURI, action, origin);
|
|
1779
|
-
if (requiresConfirmation) {
|
|
1780
|
-
// Hold the client's result until the approval reply; surface the
|
|
1781
|
-
// user-facing confirmation on the session channel (this variant,
|
|
1782
|
-
// unlike the execution request, raises SessionStatus.InputNeeded).
|
|
1783
|
-
invocation.pendingResult = result;
|
|
1784
|
-
const pending = this.pendingToolCall(chat, toolCallId);
|
|
1785
|
-
if (pending !== null && chat.currentTurnId !== null) {
|
|
1786
|
-
this.publish({
|
|
1787
|
-
channel: rec.channel,
|
|
1788
|
-
action: {
|
|
1789
|
-
type: ActionType.SessionInputNeededSet,
|
|
1790
|
-
request: {
|
|
1791
|
-
id: toolCallId,
|
|
1792
|
-
chat: chatURI,
|
|
1793
|
-
kind: SessionInputRequestKind.ToolConfirmation,
|
|
1794
|
-
turnId: chat.currentTurnId,
|
|
1795
|
-
toolCall: pending,
|
|
1796
|
-
} satisfies SessionToolConfirmationRequest,
|
|
1797
|
-
},
|
|
1798
|
-
});
|
|
1799
|
-
}
|
|
1800
|
-
} else {
|
|
1801
|
-
this.publish({
|
|
1802
|
-
channel: rec.channel,
|
|
1803
|
-
action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
|
|
1804
|
-
});
|
|
1805
|
-
this.settleClientTool(invocation, clientResultToFacade(result));
|
|
1806
|
-
}
|
|
1807
|
-
}
|
|
1808
|
-
|
|
1809
|
-
/**
|
|
1810
|
-
* `chat/toolCallContentChanged` (client-dispatchable): the owning
|
|
1811
|
-
* client streams partial content while executing (the reducer
|
|
1812
|
-
* replaces the running call's `content`). Echo-only — opencode needs
|
|
1813
|
-
* no counterpart; the spec says the server SHOULD reject dispatches
|
|
1814
|
-
* from a client that is not the contributor.
|
|
1815
|
-
*/
|
|
1816
|
-
private dispatchToolCallContentChanged(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): void {
|
|
1817
|
-
const chatURI = chat.uri;
|
|
1818
|
-
const a = action as ChatToolCallContentChangedAction;
|
|
1819
|
-
const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
|
|
1820
|
-
const invocation = toolCallId !== null ? chat.clientToolCalls.get(toolCallId) : undefined;
|
|
1821
|
-
if (toolCallId === null || invocation === undefined) {
|
|
1822
|
-
this.echo(chatURI, action, origin, `tool call ${toolCallId ?? "?"} is not a client-executed call`);
|
|
1823
|
-
return;
|
|
1824
|
-
}
|
|
1825
|
-
if (origin !== undefined && invocation.clientId !== origin.clientId) {
|
|
1826
|
-
this.echo(chatURI, action, origin, `only the contributing client (${invocation.clientId}) may stream content for this call`);
|
|
1827
|
-
return;
|
|
1828
|
-
}
|
|
1829
|
-
if (!Array.isArray(a.content)) {
|
|
1830
|
-
this.echo(chatURI, action, origin, "invalid chat/toolCallContentChanged params (content must be an array)");
|
|
1831
|
-
return;
|
|
1832
|
-
}
|
|
1833
|
-
if (this.toolCallState(chat, toolCallId)?.status !== ToolCallStatus.Running) {
|
|
1834
|
-
this.echo(chatURI, action, origin, `tool call ${toolCallId} is not running`);
|
|
1835
|
-
return;
|
|
1836
|
-
}
|
|
1837
|
-
this.echo(chatURI, action, origin);
|
|
1838
|
-
}
|
|
1839
|
-
|
|
1840
|
-
/**
|
|
1841
|
-
* `chat/toolCallResultConfirmed` (client-dispatchable): the user
|
|
1842
|
-
* approved or denied a client tool's result after a
|
|
1843
|
-
* `requiresResultConfirmation` completion. Echoes (reducer:
|
|
1844
|
-
* pending-result-confirmation → completed / cancelled with reason
|
|
1845
|
-
* `result-denied`), clears the confirmation input request, and
|
|
1846
|
-
* settles the opencode-side waiter (approved → the held client
|
|
1847
|
-
* result; denied → a Tool.Error the model sees).
|
|
1848
|
-
*/
|
|
1849
|
-
private dispatchToolCallResultConfirmed(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): void {
|
|
1850
|
-
const chatURI = chat.uri;
|
|
1851
|
-
const rec = this.byChannel.get(chatURI)!;
|
|
1852
|
-
const a = action as ChatToolCallResultConfirmedAction;
|
|
1853
|
-
const toolCallId = typeof a.toolCallId === "string" ? a.toolCallId : null;
|
|
1854
|
-
if (toolCallId === null || typeof a.approved !== "boolean") {
|
|
1855
|
-
this.echo(chatURI, action, origin, "invalid chat/toolCallResultConfirmed params");
|
|
1856
|
-
return;
|
|
1857
|
-
}
|
|
1858
|
-
const invocation = chat.clientToolCalls.get(toolCallId);
|
|
1859
|
-
if (invocation === undefined) {
|
|
1860
|
-
this.echo(chatURI, action, origin, `no pending result confirmation for tool call ${toolCallId}`);
|
|
1861
|
-
return;
|
|
1862
|
-
}
|
|
1863
|
-
if (origin !== undefined && invocation.clientId !== origin.clientId) {
|
|
1864
|
-
this.echo(chatURI, action, origin, `only the contributing client (${invocation.clientId}) may confirm this result`);
|
|
1865
|
-
return;
|
|
1866
|
-
}
|
|
1867
|
-
if (this.toolCallState(chat, toolCallId)?.status !== ToolCallStatus.PendingResultConfirmation) {
|
|
1868
|
-
this.echo(chatURI, action, origin, `tool call ${toolCallId} is not awaiting result confirmation`);
|
|
1869
|
-
return;
|
|
1870
|
-
}
|
|
1871
|
-
this.echo(chatURI, action, origin);
|
|
1872
|
-
this.publish({
|
|
1873
|
-
channel: rec.channel,
|
|
1874
|
-
action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
|
|
1875
|
-
});
|
|
1876
|
-
const held = invocation.pendingResult;
|
|
1877
|
-
if (held === undefined) {
|
|
1878
|
-
// Unreachable in practice (the state only reaches
|
|
1879
|
-
// pending-result-confirmation through our complete path); fail
|
|
1880
|
-
// closed so the opencode tool cannot hang.
|
|
1881
|
-
this.settleClientTool(invocation, { ok: false, error: "no recorded result to confirm" });
|
|
1882
|
-
return;
|
|
1883
|
-
}
|
|
1884
|
-
if (a.approved) {
|
|
1885
|
-
this.settleClientTool(invocation, clientResultToFacade(held as ToolCallResult));
|
|
1886
|
-
} else {
|
|
1887
|
-
this.settleClientTool(invocation, { ok: false, error: "the client denied the tool result" });
|
|
1888
|
-
}
|
|
1889
|
-
}
|
|
1890
|
-
|
|
1891
|
-
private async dispatchTurnCancelled(chat: ChatRuntime, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
1892
|
-
const chatURI = chat.uri;
|
|
1893
|
-
const a = action as ChatTurnCancelledAction;
|
|
1894
|
-
const turnId = typeof a.turnId === "string" && a.turnId.length > 0 ? a.turnId : null;
|
|
1895
|
-
const active = chat.chatStore.state.activeTurn;
|
|
1896
|
-
if (turnId === null || active === undefined || active.id !== turnId) {
|
|
1897
|
-
this.echo(chatURI, action, origin, "no active turn to cancel");
|
|
1898
|
-
return;
|
|
1899
|
-
}
|
|
1900
|
-
try {
|
|
1901
|
-
await this.opts.facade.interrupt({ sessionID: chat.sessionID });
|
|
1902
|
-
} catch (err) {
|
|
1903
|
-
this.echo(chatURI, action, origin, `interrupt failed: ${errorMessage(err)}`);
|
|
1904
|
-
return;
|
|
1905
|
-
}
|
|
1906
|
-
// `duration` is required on the wire (the reducer derives the final
|
|
1907
|
-
// `modifiedAt` from it); the host clock is authoritative when the
|
|
1908
|
-
// client did not supply one.
|
|
1909
|
-
const duration =
|
|
1910
|
-
typeof a.duration === "number" && Number.isFinite(a.duration) ? a.duration : this.turnDuration(chat);
|
|
1911
|
-
this.echo(chatURI, { ...a, duration }, origin);
|
|
1912
|
-
// The opencode `session.execution.interrupted` event finds no active
|
|
1913
|
-
// turn after the echo finalized it (skipped); run the queued/steering
|
|
1914
|
-
// handoff now, on the host side.
|
|
1915
|
-
await this.finishTurn(chat);
|
|
1916
|
-
}
|
|
1917
|
-
|
|
1918
|
-
/**
|
|
1919
|
-
* `changeset/filesReviewChanged` (the only client-dispatchable changeset
|
|
1920
|
-
* action): validate the channel resolves to a live store, then echo —
|
|
1921
|
-
* the official reducer toggles `reviewed` per matched file id.
|
|
1922
|
-
*/
|
|
1923
|
-
private dispatchChangesetFilesReviewChanged(channel: string, action: StateAction, origin: ActionOrigin | undefined): void {
|
|
1924
|
-
const a = action as ChangesetFilesReviewChangedAction;
|
|
1925
|
-
if (!Array.isArray(a.files) || !a.files.every((f) => typeof f === "string") || typeof a.reviewed !== "boolean") {
|
|
1926
|
-
this.echo(channel, action, origin, "invalid changeset/filesReviewChanged params");
|
|
1927
|
-
return;
|
|
1928
|
-
}
|
|
1929
|
-
const parsed = parseChangesetChannel(channel);
|
|
1930
|
-
const rec = parsed !== null ? this.byChannel.get(parsed.ownerUri) : undefined;
|
|
1931
|
-
const store = rec !== undefined ? this.changesetStoreOf(rec, channel) : undefined;
|
|
1932
|
-
if (rec === undefined || store === undefined) {
|
|
1933
|
-
this.echo(channel, action, origin, "no such changeset");
|
|
1934
|
-
return;
|
|
1935
|
-
}
|
|
1936
|
-
this.echo(channel, action, origin);
|
|
1937
|
-
}
|
|
1938
|
-
|
|
1939
|
-
private async dispatchTitleChanged(rec: SessionRecord, action: StateAction, origin: ActionOrigin | undefined): Promise<void> {
|
|
1940
|
-
const a = action as { title?: unknown };
|
|
1941
|
-
const title = typeof a.title === "string" && a.title.length > 0 ? a.title : null;
|
|
1942
|
-
if (title === null) {
|
|
1943
|
-
this.echo(rec.channel, action, origin, "invalid session/titleChanged params");
|
|
1944
|
-
return;
|
|
1945
|
-
}
|
|
1946
|
-
try {
|
|
1947
|
-
await this.opts.facade.rename({ sessionID: rec.sessionID, title });
|
|
1948
|
-
} catch (err) {
|
|
1949
|
-
this.echo(rec.channel, action, origin, `rename failed: ${errorMessage(err)}`);
|
|
1950
|
-
return;
|
|
1951
|
-
}
|
|
1952
|
-
this.echo(rec.channel, action, origin);
|
|
1953
|
-
}
|
|
1954
|
-
|
|
1955
|
-
private dispatchActiveClientSet(
|
|
1956
|
-
rec: SessionRecord,
|
|
1957
|
-
action: StateAction,
|
|
1958
|
-
origin: ActionOrigin | undefined,
|
|
1959
|
-
clientId: string | null,
|
|
1960
|
-
): void {
|
|
1961
|
-
const a = action as { activeClient?: unknown };
|
|
1962
|
-
const ac = a.activeClient;
|
|
1963
|
-
if (!isRecord(ac) || typeof ac["clientId"] !== "string" || (clientId !== null && ac["clientId"] !== clientId)) {
|
|
1964
|
-
this.echo(rec.channel, action, origin, "activeClient.clientId must match the dispatching client");
|
|
1965
|
-
return;
|
|
1966
|
-
}
|
|
1967
|
-
const tools = normalizeToolDefinitions(ac["tools"]);
|
|
1968
|
-
const normalized: SessionActiveClient = {
|
|
1969
|
-
clientId: ac["clientId"] as string,
|
|
1970
|
-
tools,
|
|
1971
|
-
...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
|
|
1972
|
-
};
|
|
1973
|
-
this.publish({
|
|
1974
|
-
channel: rec.channel,
|
|
1975
|
-
action: { type: ActionType.SessionActiveClientSet, activeClient: normalized },
|
|
1976
|
-
origin,
|
|
1977
|
-
});
|
|
1978
|
-
// The session's tool contribution changed —
|
|
1979
|
-
// re-sync the location-global opencode tool union.
|
|
1980
|
-
void this.syncClientToolsToOpencode();
|
|
1981
|
-
}
|
|
1982
|
-
|
|
1983
|
-
private dispatchActiveClientRemoved(
|
|
1984
|
-
rec: SessionRecord,
|
|
1985
|
-
action: StateAction,
|
|
1986
|
-
origin: ActionOrigin | undefined,
|
|
1987
|
-
clientId: string | null,
|
|
1988
|
-
): void {
|
|
1989
|
-
const a = action as { clientId?: unknown };
|
|
1990
|
-
if (typeof a.clientId !== "string" || (clientId !== null && a.clientId !== clientId)) {
|
|
1991
|
-
this.echo(rec.channel, action, origin, "clientId must match the dispatching client");
|
|
1992
|
-
return;
|
|
1993
|
-
}
|
|
1994
|
-
this.echo(rec.channel, action, origin);
|
|
1995
|
-
// The session's tool contribution shrank —
|
|
1996
|
-
// re-sync the location-global opencode tool union.
|
|
1997
|
-
void this.syncClientToolsToOpencode();
|
|
1998
|
-
}
|
|
1999
|
-
|
|
2000
|
-
// ── opencode event pump handlers ───────────────────────────────────────
|
|
2001
|
-
|
|
2002
|
-
private async handleEvent(ev: FacadeEvent): Promise<void> {
|
|
2003
|
-
if (ev.type === "session.created") {
|
|
2004
|
-
// Every live chat has its own opencode session, so a
|
|
2005
|
-
// created event for an already-bound id is ours (a createChat
|
|
2006
|
-
// backend) and never an external session.
|
|
2007
|
-
if (this.sessions.has(ev.sessionID) || this.byOpencode.has(ev.sessionID)) return;
|
|
2008
|
-
// Deferred registration: a concurrent `createSession` may still be
|
|
2009
|
-
// resolving for this opencode session under a client-chosen channel;
|
|
2010
|
-
// the grace + existence check avoids the double registration, and
|
|
2011
|
-
// the delete+recreate remap in `handleCreateSession` heals the slow
|
|
2012
|
-
// path.
|
|
2013
|
-
const sessionID = ev.sessionID;
|
|
2014
|
-
setTimeout(() => {
|
|
2015
|
-
void this.registerExternalDeferred(sessionID).catch((err) =>
|
|
2016
|
-
this.log(`external session registration failed: ${errorMessage(err)}`),
|
|
2017
|
-
);
|
|
2018
|
-
}, EXTERNAL_REGISTER_GRACE_MS);
|
|
2019
|
-
return;
|
|
2020
|
-
}
|
|
2021
|
-
|
|
2022
|
-
// The opencode session id joins to (record, chat) — every chat has
|
|
2023
|
-
// its own backend session, and per-turn state lives on the chat.
|
|
2024
|
-
// Only session.created registers sessions.
|
|
2025
|
-
const binding = this.byOpencode.get(ev.sessionID);
|
|
2026
|
-
if (binding === undefined) return;
|
|
2027
|
-
const { rec, chat } = binding;
|
|
2028
|
-
const chatURI = chat.uri;
|
|
2029
|
-
switch (ev.type) {
|
|
2030
|
-
case "session.deleted":
|
|
2031
|
-
if (chat.uri === rec.defaultChatURI) {
|
|
2032
|
-
this.removeRecord(rec);
|
|
2033
|
-
} else {
|
|
2034
|
-
// Peer-chat backend gone (deleted in the TUI or by another
|
|
2035
|
-
// surface): drop the AHP chat only — the record and its other
|
|
2036
|
-
// chats stay.
|
|
2037
|
-
this.removeChat(rec, chat);
|
|
2038
|
-
this.publish({ channel: rec.channel, action: { type: ActionType.SessionChatRemoved, chat: chat.uri } });
|
|
2039
|
-
}
|
|
2040
|
-
return;
|
|
2041
|
-
case "session.renamed":
|
|
2042
|
-
if (chat.uri === rec.defaultChatURI) {
|
|
2043
|
-
this.publish({ channel: rec.channel, action: { type: ActionType.SessionTitleChanged, title: ev.title } });
|
|
2044
|
-
} else {
|
|
2045
|
-
// No chat-title session action exists; the chat summary carries
|
|
2046
|
-
// the title (the chat store's own title stays original — same
|
|
2047
|
-
// pre-existing behavior as the default chat's titleChanged).
|
|
2048
|
-
this.publish({
|
|
2049
|
-
channel: rec.channel,
|
|
2050
|
-
action: { type: ActionType.SessionChatUpdated, chat: chat.uri, changes: { title: ev.title } },
|
|
2051
|
-
});
|
|
2052
|
-
}
|
|
2053
|
-
return;
|
|
2054
|
-
case "inbox.enqueued":
|
|
2055
|
-
chat.lastInbox = { text: ev.text, delivery: ev.delivery };
|
|
2056
|
-
return;
|
|
2057
|
-
case "inbox.delivered":
|
|
2058
|
-
// Steering consumption is handled at turn end (finishTurn).
|
|
2059
|
-
return;
|
|
2060
|
-
case "execution.started":
|
|
2061
|
-
if (chat.currentTurnId !== null) return; // write-ahead already claimed the turn
|
|
2062
|
-
// Orphan turn (an external TUI prompt, or a handoff this host did
|
|
2063
|
-
// not initiate): start it with the last-seen inbox message.
|
|
2064
|
-
this.startTurn(chat, chat.lastInbox !== null ? userMessage(chat.lastInbox.text) : userMessage(""));
|
|
2065
|
-
return;
|
|
2066
|
-
case "execution.succeeded":
|
|
2067
|
-
if (chat.currentTurnId === null) return;
|
|
2068
|
-
this.publish({
|
|
2069
|
-
channel: chatURI,
|
|
2070
|
-
action: { type: ActionType.ChatTurnComplete, turnId: chat.currentTurnId, duration: this.turnDuration(chat) },
|
|
2071
|
-
});
|
|
2072
|
-
await this.finishTurn(chat);
|
|
2073
|
-
return;
|
|
2074
|
-
case "execution.failed":
|
|
2075
|
-
if (chat.currentTurnId === null) return;
|
|
2076
|
-
const part: ErrorResponsePart = {
|
|
2077
|
-
kind: ResponsePartKind.Error,
|
|
2078
|
-
error: { errorType: ev.error.type, message: ev.error.message },
|
|
2079
|
-
};
|
|
2080
|
-
this.publish({
|
|
2081
|
-
channel: chatURI,
|
|
2082
|
-
action: { type: ActionType.ChatError, turnId: chat.currentTurnId, duration: this.turnDuration(chat), part },
|
|
2083
|
-
});
|
|
2084
|
-
await this.finishTurn(chat);
|
|
2085
|
-
return;
|
|
2086
|
-
case "execution.interrupted":
|
|
2087
|
-
// Skipped when the client's own `chat/turnCancelled` echo already
|
|
2088
|
-
// finalized the turn (currentTurnId is null).
|
|
2089
|
-
if (chat.currentTurnId === null) return;
|
|
2090
|
-
this.publish({
|
|
2091
|
-
channel: chatURI,
|
|
2092
|
-
action: { type: ActionType.ChatTurnCancelled, turnId: chat.currentTurnId, duration: this.turnDuration(chat) },
|
|
2093
|
-
});
|
|
2094
|
-
await this.finishTurn(chat);
|
|
2095
|
-
return;
|
|
2096
|
-
case "step.started":
|
|
2097
|
-
chat.turnModelRef = `${ev.model.providerID}/${ev.model.modelID}`;
|
|
2098
|
-
return;
|
|
2099
|
-
case "text.delta":
|
|
2100
|
-
case "reasoning.delta": {
|
|
2101
|
-
if (chat.currentTurnId === null) return;
|
|
2102
|
-
const kind = ev.type === "text.delta" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
|
|
2103
|
-
const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
|
|
2104
|
-
const first = !chat.parts.has(key);
|
|
2105
|
-
chat.parts.add(key);
|
|
2106
|
-
const partId = `part-${key}`;
|
|
2107
|
-
if (first) {
|
|
2108
|
-
// Lazily emit the part on the first delta; it carries the
|
|
2109
|
-
// initial content.
|
|
2110
|
-
this.publish({
|
|
2111
|
-
channel: chatURI,
|
|
2112
|
-
action: {
|
|
2113
|
-
type: ActionType.ChatResponsePart,
|
|
2114
|
-
turnId: chat.currentTurnId,
|
|
2115
|
-
part: { kind, id: partId, content: ev.delta },
|
|
2116
|
-
},
|
|
2117
|
-
});
|
|
2118
|
-
} else {
|
|
2119
|
-
this.publish({
|
|
2120
|
-
channel: chatURI,
|
|
2121
|
-
action:
|
|
2122
|
-
kind === ResponsePartKind.Markdown
|
|
2123
|
-
? { type: ActionType.ChatDelta, turnId: chat.currentTurnId, partId, content: ev.delta }
|
|
2124
|
-
: { type: ActionType.ChatReasoning, turnId: chat.currentTurnId, partId, content: ev.delta },
|
|
2125
|
-
});
|
|
2126
|
-
}
|
|
2127
|
-
return;
|
|
2128
|
-
}
|
|
2129
|
-
case "text.ended":
|
|
2130
|
-
case "reasoning.ended": {
|
|
2131
|
-
if (chat.currentTurnId === null) return;
|
|
2132
|
-
// Fallback for non-streaming providers that emit only the final
|
|
2133
|
-
// text: if no delta opened the part, emit it now with the full text.
|
|
2134
|
-
const kind = ev.type === "text.ended" ? ResponsePartKind.Markdown : ResponsePartKind.Reasoning;
|
|
2135
|
-
const key = `${ev.assistantMessageID}:${kind}:${ev.ordinal}`;
|
|
2136
|
-
if (!chat.parts.has(key)) {
|
|
2137
|
-
chat.parts.add(key);
|
|
2138
|
-
this.publish({
|
|
2139
|
-
channel: chatURI,
|
|
2140
|
-
action: {
|
|
2141
|
-
type: ActionType.ChatResponsePart,
|
|
2142
|
-
turnId: chat.currentTurnId,
|
|
2143
|
-
part: { kind, id: `part-${key}`, content: ev.text },
|
|
2144
|
-
},
|
|
2145
|
-
});
|
|
2146
|
-
}
|
|
2147
|
-
return;
|
|
2148
|
-
}
|
|
2149
|
-
case "tool.input.started": {
|
|
2150
|
-
if (chat.currentTurnId === null) {
|
|
2151
|
-
this.log(`tool.input.started outside a turn (session ${chat.sessionID}, tool ${ev.name}); ignored`);
|
|
2152
|
-
return;
|
|
2153
|
-
}
|
|
2154
|
-
chat.toolName.set(ev.id, ev.name);
|
|
2155
|
-
// When the session's active clients provide
|
|
2156
|
-
// this tool, the call is client-executed — the client
|
|
2157
|
-
// `contributor` must be established at start (the official
|
|
2158
|
-
// reducer ignores a late one), and the call is tracked for the
|
|
2159
|
-
// `execute` bridge + the client's dispatchable actions.
|
|
2160
|
-
// (Active clients are session-level; the chat tracks the call.)
|
|
2161
|
-
const clientTool = this.clientToolContributor(rec, ev.name);
|
|
2162
|
-
if (clientTool !== null) {
|
|
2163
|
-
chat.clientToolCalls.set(ev.id, { clientId: clientTool, turnId: chat.currentTurnId });
|
|
2164
|
-
}
|
|
2165
|
-
this.publish({
|
|
2166
|
-
channel: chatURI,
|
|
2167
|
-
action: {
|
|
2168
|
-
type: ActionType.ChatToolCallStart,
|
|
2169
|
-
turnId: chat.currentTurnId,
|
|
2170
|
-
toolCallId: ev.id,
|
|
2171
|
-
toolName: ev.name,
|
|
2172
|
-
displayName: displayNameFor(ev.name),
|
|
2173
|
-
...(clientTool !== null
|
|
2174
|
-
? { contributor: { kind: ToolCallContributorKind.Client, clientId: clientTool } }
|
|
2175
|
-
: {}),
|
|
2176
|
-
},
|
|
2177
|
-
});
|
|
2178
|
-
return;
|
|
2179
|
-
}
|
|
2180
|
-
case "tool.input.ended": {
|
|
2181
|
-
chat.toolInput.set(ev.id, ev.text);
|
|
2182
|
-
// For file-mutating tools, capture the pre-edit file
|
|
2183
|
-
// content now (the event fires before execution — the last safe
|
|
2184
|
-
// point). Awaited in the sequential pump so the capture is
|
|
2185
|
-
// complete before `execution.*` can end the turn.
|
|
2186
|
-
if (this.opts.changesets) await this.captureTurnBefore(chat, ev.id, ev.text);
|
|
2187
|
-
// A foreground `shell`-tool call opens its
|
|
2188
|
-
// synthetic terminal channel here — the command line is only
|
|
2189
|
-
// known at input.ended.
|
|
2190
|
-
this.openTerminalForToolCall(rec, chat, ev.id, ev.text);
|
|
2191
|
-
// A client-executed call clears its
|
|
2192
|
-
// confirmation gate here (no opencode permission can fire for
|
|
2193
|
-
// it) — ready straight to running, then surface the execution
|
|
2194
|
-
// request so the owning client picks up the work.
|
|
2195
|
-
if (chat.clientToolCalls.has(ev.id)) {
|
|
2196
|
-
this.ensureToolReady(chat, ev.id, false);
|
|
2197
|
-
const invocation = chat.clientToolCalls.get(ev.id);
|
|
2198
|
-
const running = this.toolCallState(chat, ev.id);
|
|
2199
|
-
if (invocation !== undefined && running !== null && running.status === ToolCallStatus.Running && chat.currentTurnId !== null) {
|
|
2200
|
-
const request: SessionToolClientExecutionRequest = {
|
|
2201
|
-
id: ev.id,
|
|
2202
|
-
chat: chatURI,
|
|
2203
|
-
kind: SessionInputRequestKind.ToolClientExecution,
|
|
2204
|
-
turnId: chat.currentTurnId,
|
|
2205
|
-
clientId: invocation.clientId,
|
|
2206
|
-
toolCall: running,
|
|
2207
|
-
};
|
|
2208
|
-
this.publish({
|
|
2209
|
-
channel: rec.channel,
|
|
2210
|
-
action: { type: ActionType.SessionInputNeededSet, request },
|
|
2211
|
-
});
|
|
2212
|
-
}
|
|
2213
|
-
}
|
|
2214
|
-
return;
|
|
2215
|
-
}
|
|
2216
|
-
case "tool.progress":
|
|
2217
|
-
// First sign the tool is actually running (opencode auto-approved):
|
|
2218
|
-
// finalize the tool call as running.
|
|
2219
|
-
this.ensureToolReady(chat, ev.id, false);
|
|
2220
|
-
return;
|
|
2221
|
-
case "tool.success": {
|
|
2222
|
-
// The synthetic terminal completes on the
|
|
2223
|
-
// tool's terminal event (before the turn guard — a command that
|
|
2224
|
-
// finishes after its turn was torn down still exits its
|
|
2225
|
-
// terminal; no-op when the call never opened one).
|
|
2226
|
-
this.finishTerminal(chat, ev.id, { ok: true, content: ev.content });
|
|
2227
|
-
if (chat.currentTurnId === null) return;
|
|
2228
|
-
this.ensureToolReady(chat, ev.id, false);
|
|
2229
|
-
if (this.toolCallTerminal(chat, ev.id)) {
|
|
2230
|
-
// e.g. denied → already cancelled, or a client-executed call
|
|
2231
|
-
// the client already completed: no echo, but the tracking
|
|
2232
|
-
// (including the client-tool record) must still be cleared.
|
|
2233
|
-
this.clearToolTracking(chat, ev.id);
|
|
2234
|
-
return;
|
|
2235
|
-
}
|
|
2236
|
-
const name = chat.toolName.get(ev.id) ?? "tool";
|
|
2237
|
-
const input = chat.toolInput.get(ev.id);
|
|
2238
|
-
this.publish({
|
|
2239
|
-
channel: chatURI,
|
|
2240
|
-
action: {
|
|
2241
|
-
type: ActionType.ChatToolCallComplete,
|
|
2242
|
-
turnId: chat.currentTurnId,
|
|
2243
|
-
toolCallId: ev.id,
|
|
2244
|
-
result: {
|
|
2245
|
-
success: true,
|
|
2246
|
-
pastTenseMessage: pastTenseMessageFor(name, input),
|
|
2247
|
-
content: mapToolResultContent(ev.content),
|
|
2248
|
-
},
|
|
2249
|
-
},
|
|
2250
|
-
});
|
|
2251
|
-
this.clearToolTracking(chat, ev.id);
|
|
2252
|
-
return;
|
|
2253
|
-
}
|
|
2254
|
-
case "tool.failed": {
|
|
2255
|
-
this.finishTerminal(chat, ev.id, { ok: false, message: ev.error.message });
|
|
2256
|
-
if (chat.currentTurnId === null) return;
|
|
2257
|
-
this.ensureToolReady(chat, ev.id, false);
|
|
2258
|
-
if (this.toolCallTerminal(chat, ev.id)) {
|
|
2259
|
-
// Already terminal (client-executed call completed by the
|
|
2260
|
-
// client, or a call cancelled upstream) — clear the tracking.
|
|
2261
|
-
this.clearToolTracking(chat, ev.id);
|
|
2262
|
-
return;
|
|
2263
|
-
}
|
|
2264
|
-
const name = chat.toolName.get(ev.id) ?? "tool";
|
|
2265
|
-
const input = chat.toolInput.get(ev.id);
|
|
2266
|
-
this.publish({
|
|
2267
|
-
channel: chatURI,
|
|
2268
|
-
action: {
|
|
2269
|
-
type: ActionType.ChatToolCallComplete,
|
|
2270
|
-
turnId: chat.currentTurnId,
|
|
2271
|
-
toolCallId: ev.id,
|
|
2272
|
-
result: {
|
|
2273
|
-
success: false,
|
|
2274
|
-
pastTenseMessage: pastTenseMessageFor(name, input),
|
|
2275
|
-
error: { message: ev.error.message },
|
|
2276
|
-
},
|
|
2277
|
-
},
|
|
2278
|
-
});
|
|
2279
|
-
this.clearToolTracking(chat, ev.id);
|
|
2280
|
-
return;
|
|
2281
|
-
}
|
|
2282
|
-
case "usage.updated":
|
|
2283
|
-
// Session-cumulative tokens; the chat reducer replaces the turn's
|
|
2284
|
-
// usage, so the latest cumulative values are the turn's view.
|
|
2285
|
-
if (chat.currentTurnId === null) return;
|
|
2286
|
-
this.publish({
|
|
2287
|
-
channel: chatURI,
|
|
2288
|
-
action: {
|
|
2289
|
-
type: ActionType.ChatUsage,
|
|
2290
|
-
turnId: chat.currentTurnId,
|
|
2291
|
-
usage: {
|
|
2292
|
-
inputTokens: ev.tokens.input,
|
|
2293
|
-
outputTokens: ev.tokens.output,
|
|
2294
|
-
cacheReadTokens: ev.tokens.cache.read,
|
|
2295
|
-
...(chat.turnModelRef !== null ? { model: chat.turnModelRef } : {}),
|
|
2296
|
-
},
|
|
2297
|
-
},
|
|
2298
|
-
});
|
|
2299
|
-
return;
|
|
2300
|
-
case "permission.asked":
|
|
2301
|
-
// Only tool-sourced permissions map to a tool confirmation;
|
|
2302
|
-
// anything else has no AHP counterpart (gap).
|
|
2303
|
-
if (ev.source === undefined) {
|
|
2304
|
-
this.log(`ignoring non-tool permission.asked ${ev.id} (action: ${ev.action})`);
|
|
2305
|
-
return;
|
|
2306
|
-
}
|
|
2307
|
-
const toolCallId = ev.source.id;
|
|
2308
|
-
chat.permissionForTool.set(toolCallId, ev.id);
|
|
2309
|
-
chat.toolForPermission.set(ev.id, toolCallId);
|
|
2310
|
-
this.ensureToolReady(chat, toolCallId, true);
|
|
2311
|
-
const pending = this.pendingToolCall(chat, toolCallId);
|
|
2312
|
-
if (pending !== null && chat.currentTurnId !== null) {
|
|
2313
|
-
const request: SessionToolConfirmationRequest = {
|
|
2314
|
-
id: toolCallId,
|
|
2315
|
-
chat: chatURI,
|
|
2316
|
-
kind: SessionInputRequestKind.ToolConfirmation,
|
|
2317
|
-
turnId: chat.currentTurnId,
|
|
2318
|
-
toolCall: pending,
|
|
2319
|
-
};
|
|
2320
|
-
this.publish({
|
|
2321
|
-
channel: rec.channel,
|
|
2322
|
-
action: { type: ActionType.SessionInputNeededSet, request },
|
|
2323
|
-
});
|
|
2324
|
-
}
|
|
2325
|
-
return;
|
|
2326
|
-
case "permission.replied": {
|
|
2327
|
-
const toolCallId = chat.toolForPermission.get(ev.requestID);
|
|
2328
|
-
chat.toolForPermission.delete(ev.requestID);
|
|
2329
|
-
if (toolCallId !== undefined) {
|
|
2330
|
-
chat.permissionForTool.delete(toolCallId);
|
|
2331
|
-
// Safety net: the client's `chat/toolCallConfirmed` normally
|
|
2332
|
-
// removes the input request first; this covers the reply
|
|
2333
|
-
// arriving without (or before) the echo.
|
|
2334
|
-
this.publish({
|
|
2335
|
-
channel: rec.channel,
|
|
2336
|
-
action: { type: ActionType.SessionInputNeededRemoved, id: toolCallId },
|
|
2337
|
-
});
|
|
2338
|
-
}
|
|
2339
|
-
return;
|
|
2340
|
-
}
|
|
2341
|
-
default:
|
|
2342
|
-
return;
|
|
2343
|
-
}
|
|
2344
|
-
}
|
|
2345
|
-
|
|
2346
|
-
// ── turn helpers ───────────────────────────────────────────────────────
|
|
2347
|
-
|
|
2348
|
-
private mintTurnId(): string {
|
|
2349
|
-
this.turnCounter += 1;
|
|
2350
|
-
return `turn_${Date.now().toString(36)}_${this.turnCounter.toString(36)}`;
|
|
2351
|
-
}
|
|
2352
|
-
|
|
2353
|
-
private turnDuration(chat: ChatRuntime): number {
|
|
2354
|
-
return Math.max(0, Date.now() - (chat.turnStartedAt ?? Date.now()));
|
|
2355
|
-
}
|
|
2356
|
-
|
|
2357
|
-
/** Claim a turn (write-ahead) and publish `chat/turnStarted`. */
|
|
2358
|
-
private startTurn(chat: ChatRuntime, message: Message, queuedMessageId?: string): void {
|
|
2359
|
-
const turnId = this.mintTurnId();
|
|
2360
|
-
chat.currentTurnId = turnId;
|
|
2361
|
-
chat.turnStartedAt = Date.now();
|
|
2362
|
-
this.publish({
|
|
2363
|
-
channel: chat.uri,
|
|
2364
|
-
action: {
|
|
2365
|
-
type: ActionType.ChatTurnStarted,
|
|
2366
|
-
turnId,
|
|
2367
|
-
startedAt: new Date().toISOString(),
|
|
2368
|
-
message,
|
|
2369
|
-
...(queuedMessageId !== undefined ? { queuedMessageId } : {}),
|
|
2370
|
-
},
|
|
2371
|
-
});
|
|
2372
|
-
}
|
|
2373
|
-
|
|
2374
|
-
/**
|
|
2375
|
-
* After a turn terminal: clear the steering message opencode consumed
|
|
2376
|
-
* during the turn, and auto-start the next turn from the queue (the
|
|
2377
|
-
* queued prompt was already sent with `delivery: "queue"` — opencode
|
|
2378
|
-
* starts it automatically; this only updates the AHP state).
|
|
2379
|
-
*
|
|
2380
|
-
* Then refresh the session's changesets — the turn's captured
|
|
2381
|
-
* "after" content is read from disk here, and the uncommitted/session/
|
|
2382
|
-
* turn changesets recompute (async: awaits the facade).
|
|
2383
|
-
*/
|
|
2384
|
-
private async finishTurn(chat: ChatRuntime): Promise<void> {
|
|
2385
|
-
const endedTurnId = chat.currentTurnId;
|
|
2386
|
-
chat.currentTurnId = null;
|
|
2387
|
-
chat.turnStartedAt = null;
|
|
2388
|
-
const state = chat.chatStore.state;
|
|
2389
|
-
if (state.steeringMessage !== undefined) {
|
|
2390
|
-
this.publish({
|
|
2391
|
-
channel: chat.uri,
|
|
2392
|
-
action: {
|
|
2393
|
-
type: ActionType.ChatPendingMessageRemoved,
|
|
2394
|
-
kind: PendingMessageKind.Steering,
|
|
2395
|
-
id: state.steeringMessage.id,
|
|
2396
|
-
},
|
|
2397
|
-
});
|
|
2398
|
-
}
|
|
2399
|
-
const queued = state.queuedMessages;
|
|
2400
|
-
if (queued !== undefined && queued.length > 0) {
|
|
2401
|
-
const next = queued[0]!;
|
|
2402
|
-
this.startTurn(chat, next.message, next.id);
|
|
2403
|
-
} else if (chat.lastInbox !== null && chat.lastInbox.delivery === "queue") {
|
|
2404
|
-
// A queued prompt from outside AHP (e.g. the TUI).
|
|
2405
|
-
this.startTurn(chat, userMessage(chat.lastInbox.text));
|
|
2406
|
-
}
|
|
2407
|
-
// The ended turn's command terminals leave the
|
|
2408
|
-
// root catalog now (retention — their state stays subscribable until
|
|
2409
|
-
// the chat/record is removed). Runs after the possible
|
|
2410
|
-
// chained startTurn so the published list is the post-handoff one.
|
|
2411
|
-
if (this.opts.terminals && endedTurnId !== null && this.terminals.size > 0) {
|
|
2412
|
-
this.refreshTerminals();
|
|
2413
|
-
}
|
|
2414
|
-
if (this.opts.changesets && endedTurnId !== null) {
|
|
2415
|
-
await this.refreshTurnChangesets(this.byChannel.get(chat.uri)!, chat, endedTurnId);
|
|
2416
|
-
}
|
|
2417
|
-
}
|
|
2418
|
-
|
|
2419
|
-
// ── synthetic shell-command terminals ───────────────────────────────────
|
|
2420
|
-
|
|
2421
|
-
/**
|
|
2422
|
-
* Open the synthetic `ahp-terminal:` channel for a foreground
|
|
2423
|
-
* `shell`-tool call (read-only rendering of the command execution):
|
|
2424
|
-
* seed the state (`isPty: false`, session claim scoped to
|
|
2425
|
-
* chat/turn/toolCall, `supportsCommandDetection: true`), publish
|
|
2426
|
-
* `terminal/commandExecuted` (commandId = toolCallId), register the
|
|
2427
|
-
* channel, and refresh the root catalog. No-op for the excluded shapes
|
|
2428
|
-
* (capability off, no active turn, non-shell tool, malformed input,
|
|
2429
|
-
* background calls — the background result carries no turn-scoped
|
|
2430
|
-
* completion).
|
|
2431
|
-
*/
|
|
2432
|
-
private openTerminalForToolCall(rec: SessionRecord, chat: ChatRuntime, toolCallId: string, inputJson: string): void {
|
|
2433
|
-
if (!this.opts.terminals) return;
|
|
2434
|
-
const turnId = chat.currentTurnId;
|
|
2435
|
-
if (turnId === null) return;
|
|
2436
|
-
const name = chat.toolName.get(toolCallId);
|
|
2437
|
-
if (name === undefined || !SHELL_TOOL_NAMES.has(name)) return;
|
|
2438
|
-
let input: unknown;
|
|
2439
|
-
try {
|
|
2440
|
-
input = JSON.parse(inputJson);
|
|
2441
|
-
} catch {
|
|
2442
|
-
return; // malformed input text — nothing to render
|
|
2443
|
-
}
|
|
2444
|
-
if (!isRecord(input)) return;
|
|
2445
|
-
const command = input["command"];
|
|
2446
|
-
if (typeof command !== "string" || command.length === 0) return;
|
|
2447
|
-
if (input["background"] === true) return; // excluded: no synchronous completion
|
|
2448
|
-
const uri = terminalChannelURI(toolCallId);
|
|
2449
|
-
if (this.terminals.has(uri)) {
|
|
2450
|
-
this.log(`terminal ${uri} already exists (duplicate toolCallId ${toolCallId}); not reopening`);
|
|
2451
|
-
return;
|
|
2452
|
-
}
|
|
2453
|
-
const now = Date.now();
|
|
2454
|
-
const initial: TerminalState = {
|
|
2455
|
-
title:
|
|
2456
|
-
command.length > TERMINAL_TITLE_MAX ? `${command.slice(0, TERMINAL_TITLE_MAX - 1)}…` : command,
|
|
2457
|
-
content: [],
|
|
2458
|
-
lifecycle: { status: TerminalLifecycleStatus.Running },
|
|
2459
|
-
claim: { kind: TerminalClaimKind.Session, session: rec.channel, chat: chat.uri, turnId, toolCallId },
|
|
2460
|
-
supportsCommandDetection: true,
|
|
2461
|
-
isPty: false,
|
|
2462
|
-
// A directory URI (trailing slash — RFC 8089).
|
|
2463
|
-
...(this.opts.defaultDirectory !== undefined ? { cwd: directoryUri(this.opts.defaultDirectory) } : {}),
|
|
2464
|
-
};
|
|
2465
|
-
this.terminals.set(uri, {
|
|
2466
|
-
uri,
|
|
2467
|
-
rec,
|
|
2468
|
-
chat,
|
|
2469
|
-
toolCallId,
|
|
2470
|
-
turnId,
|
|
2471
|
-
store: createTerminalStateStore(initial),
|
|
2472
|
-
commandLine: command,
|
|
2473
|
-
startedAt: now,
|
|
2474
|
-
});
|
|
2475
|
-
this.channels.addTerminal(uri);
|
|
2476
|
-
this.publish({
|
|
2477
|
-
channel: uri,
|
|
2478
|
-
action: { type: ActionType.TerminalCommandExecuted, commandId: toolCallId, commandLine: command, timestamp: now },
|
|
2479
|
-
});
|
|
2480
|
-
this.refreshTerminals();
|
|
2481
|
-
}
|
|
2482
|
-
|
|
2483
|
-
/**
|
|
2484
|
-
* Complete the synthetic terminal of a `shell`-tool call: publish
|
|
2485
|
-
* `terminal/data` (the output — the tool's text content on success,
|
|
2486
|
-
* the error message on failure), `terminal/commandFinished` (exitCode
|
|
2487
|
-
* + duration), and `terminal/exited`, then refresh the root catalog
|
|
2488
|
-
* (the listed lifecycle flips to exited while the turn still runs).
|
|
2489
|
-
* Idempotent — a terminal that already exited is left alone. The
|
|
2490
|
-
* record itself is retained (retention); only the state moves on.
|
|
2491
|
-
*/
|
|
2492
|
-
private finishTerminal(
|
|
2493
|
-
chat: ChatRuntime,
|
|
2494
|
-
toolCallId: string,
|
|
2495
|
-
result: { ok: true; content: FacadeToolContent[] } | { ok: false; message: string },
|
|
2496
|
-
): void {
|
|
2497
|
-
if (!this.opts.terminals) return;
|
|
2498
|
-
const uri = terminalChannelURI(toolCallId);
|
|
2499
|
-
const t = this.terminals.get(uri);
|
|
2500
|
-
if (t === undefined) return;
|
|
2501
|
-
if (t.store.state.lifecycle.status === TerminalLifecycleStatus.Exited) return;
|
|
2502
|
-
const output = result.ok
|
|
2503
|
-
? result.content
|
|
2504
|
-
.filter((c) => c.type === "text" && typeof c.text === "string")
|
|
2505
|
-
.map((c) => c.text as string)
|
|
2506
|
-
.join("\n")
|
|
2507
|
-
: result.message;
|
|
2508
|
-
if (output.length > 0) {
|
|
2509
|
-
this.publish({ channel: uri, action: { type: ActionType.TerminalData, data: output } });
|
|
2510
|
-
}
|
|
2511
|
-
const exitCode = result.ok ? (shellExitCodeOf(result.content) ?? undefined) : undefined;
|
|
2512
|
-
const durationMs = Math.max(0, Date.now() - t.startedAt);
|
|
2513
|
-
this.publish({
|
|
2514
|
-
channel: uri,
|
|
2515
|
-
action: {
|
|
2516
|
-
type: ActionType.TerminalCommandFinished,
|
|
2517
|
-
commandId: toolCallId,
|
|
2518
|
-
...(exitCode !== undefined ? { exitCode } : {}),
|
|
2519
|
-
...(durationMs > 0 ? { durationMs } : {}),
|
|
2520
|
-
},
|
|
2521
|
-
});
|
|
2522
|
-
this.publish({
|
|
2523
|
-
channel: uri,
|
|
2524
|
-
action: { type: ActionType.TerminalExited, ...(exitCode !== undefined ? { exitCode } : {}) },
|
|
2525
|
-
});
|
|
2526
|
-
this.refreshTerminals();
|
|
2527
|
-
}
|
|
2528
|
-
|
|
2529
|
-
/**
|
|
2530
|
-
* Republish the root terminal catalog (`root/terminalsChanged`, full
|
|
2531
|
-
* replacement). Catalog membership is turn-scoped: a terminal is
|
|
2532
|
-
* listed while its turn is still the owning chat's active turn —
|
|
2533
|
-
* finished commands keep their (final) lifecycle row until the turn
|
|
2534
|
-
* ends, then the row drops (host-controlled retention).
|
|
2535
|
-
* No-op when the serialized list is unchanged.
|
|
2536
|
-
*/
|
|
2537
|
-
private refreshTerminals(): void {
|
|
2538
|
-
if (!this.opts.terminals) return;
|
|
2539
|
-
const terminals: TerminalInfo[] = [];
|
|
2540
|
-
for (const t of this.terminals.values()) {
|
|
2541
|
-
if (t.chat.currentTurnId !== t.turnId) continue;
|
|
2542
|
-
const s = t.store.state;
|
|
2543
|
-
terminals.push({ resource: t.uri, title: s.title, claim: s.claim, lifecycle: s.lifecycle });
|
|
2544
|
-
}
|
|
2545
|
-
if (JSON.stringify(this.state.state.terminals) === JSON.stringify(terminals)) return;
|
|
2546
|
-
this.publish({ channel: ROOT_CHANNEL, action: { type: ActionType.RootTerminalsChanged, terminals } });
|
|
2547
|
-
}
|
|
2548
|
-
|
|
2549
|
-
/**
|
|
2550
|
-
* Drop a chat's terminal channels (removeChat — covers both chat
|
|
2551
|
-
* disposal and record removal): a still-running command gets a final
|
|
2552
|
-
* `terminal/exited` (it dies with the chat), then the records and
|
|
2553
|
-
* registry entries go and the root catalog refreshes. Existing socket
|
|
2554
|
-
* subscriptions linger (the session-removal precedent) — no further
|
|
2555
|
-
* actions will reach them.
|
|
2556
|
-
*/
|
|
2557
|
-
private teardownTerminalsForChat(chat: ChatRuntime): void {
|
|
2558
|
-
let changed = false;
|
|
2559
|
-
for (const t of [...this.terminals.values()]) {
|
|
2560
|
-
if (t.chat !== chat) continue;
|
|
2561
|
-
if (t.store.state.lifecycle.status === TerminalLifecycleStatus.Running) {
|
|
2562
|
-
this.publish({ channel: t.uri, action: { type: ActionType.TerminalExited } });
|
|
2563
|
-
}
|
|
2564
|
-
this.terminals.delete(t.uri);
|
|
2565
|
-
this.channels.removeTerminal(t.uri);
|
|
2566
|
-
changed = true;
|
|
2567
|
-
}
|
|
2568
|
-
if (changed) this.refreshTerminals();
|
|
2569
|
-
}
|
|
2570
|
-
|
|
2571
|
-
// ── changesets ────────────────────────────────────────────────
|
|
2572
|
-
|
|
2573
|
-
/**
|
|
2574
|
-
* Capture the pre-edit content of a file-mutating tool's target file for
|
|
2575
|
-
* the current turn's changeset (first capture per file wins — the
|
|
2576
|
-
* pre-turn content survives later edits in the same turn). No-op when
|
|
2577
|
-
* the tool is not file-mutating, the input carries no parseable path,
|
|
2578
|
-
* or the path resolves outside the location directory.
|
|
2579
|
-
*/
|
|
2580
|
-
private async captureTurnBefore(chat: ChatRuntime, toolCallId: string, inputJson: string): Promise<void> {
|
|
2581
|
-
const turnId = chat.currentTurnId;
|
|
2582
|
-
const toolName = chat.toolName.get(toolCallId);
|
|
2583
|
-
if (turnId === null || toolName === undefined || !SNAPSHOT_TOOLS.has(toolName)) return;
|
|
2584
|
-
let parsed: unknown;
|
|
2585
|
-
try {
|
|
2586
|
-
parsed = JSON.parse(inputJson);
|
|
2587
|
-
} catch {
|
|
2588
|
-
return;
|
|
2589
|
-
}
|
|
2590
|
-
if (!isRecord(parsed)) return;
|
|
2591
|
-
const rawPath = SNAPSHOT_PATH_KEYS.map((k) => parsed[k]).find((v) => typeof v === "string" && (v as string).length > 0);
|
|
2592
|
-
if (typeof rawPath !== "string") return;
|
|
2593
|
-
const absPath = this.resolveSnapshotPath(rawPath);
|
|
2594
|
-
if (absPath === null) {
|
|
2595
|
-
this.log(`turn snapshot: ${toolName} target ${rawPath} is outside the location directory; not captured`);
|
|
2596
|
-
return;
|
|
2597
|
-
}
|
|
2598
|
-
let before: string | null;
|
|
2599
|
-
try {
|
|
2600
|
-
before = await this.opts.facade.readFile(absPath);
|
|
2601
|
-
} catch (err) {
|
|
2602
|
-
this.log(`turn snapshot: read of ${absPath} failed: ${errorMessage(err)}`);
|
|
2603
|
-
return;
|
|
2604
|
-
}
|
|
2605
|
-
// The pump is sequential, so the turn cannot have ended between the
|
|
2606
|
-
// call and the await — but the chat may be gone (session deleted or
|
|
2607
|
-
// chat disposed).
|
|
2608
|
-
if (chat.currentTurnId !== turnId || !this.byOpencode.has(chat.sessionID)) return;
|
|
2609
|
-
const turnFiles = chat.turnSnapshots.get(turnId) ?? new Map();
|
|
2610
|
-
if (!turnFiles.has(absPath)) turnFiles.set(absPath, { before, after: null });
|
|
2611
|
-
chat.turnSnapshots.set(turnId, turnFiles);
|
|
2612
|
-
}
|
|
2613
|
-
|
|
2614
|
-
/** Resolve a tool-input path against the location directory (must stay inside it). */
|
|
2615
|
-
private resolveSnapshotPath(rawPath: string): string | null {
|
|
2616
|
-
const dir = this.opts.defaultDirectory;
|
|
2617
|
-
if (dir === undefined) return null;
|
|
2618
|
-
const absPath = resolvePath(dir, rawPath);
|
|
2619
|
-
return isPathInside(absPath, dir) ? absPath : null;
|
|
2620
|
-
}
|
|
2621
|
-
|
|
2622
|
-
/**
|
|
2623
|
-
* The changeset store's owner: session-kind changesets
|
|
2624
|
-
* live on the record (the session channel owns them); uncommitted/turn
|
|
2625
|
-
* changesets live on the owning chat. Null when the owner is gone
|
|
2626
|
-
* (a disposed chat's changesets are un-subscribable).
|
|
2627
|
-
*/
|
|
2628
|
-
private changesetOwner(rec: SessionRecord, uri: string): { kind: "session" } | { kind: "chat"; chat: ChatRuntime } | null {
|
|
2629
|
-
const parsed = parseChangesetChannel(uri);
|
|
2630
|
-
if (parsed === null) return null;
|
|
2631
|
-
if (parsed.kind === "session") return { kind: "session" };
|
|
2632
|
-
const chat = rec.chats.get(parsed.ownerUri);
|
|
2633
|
-
return chat === undefined ? null : { kind: "chat", chat };
|
|
2634
|
-
}
|
|
2635
|
-
|
|
2636
|
-
/**
|
|
2637
|
-
* Get-or-create the changeset store for a URI (fresh stores start
|
|
2638
|
-
* computing). Owner-aware — see `changesetOwner`; null when the owner
|
|
2639
|
-
* is gone.
|
|
2640
|
-
*/
|
|
2641
|
-
private changesetStore(rec: SessionRecord, uri: string): ChangesetStateStore | null {
|
|
2642
|
-
const owner = this.changesetOwner(rec, uri);
|
|
2643
|
-
if (owner === null) return null;
|
|
2644
|
-
const map = owner.kind === "chat" ? owner.chat.changesets : rec.sessionChangesets;
|
|
2645
|
-
let store = map.get(uri);
|
|
2646
|
-
if (store === undefined) {
|
|
2647
|
-
store = createChangesetStateStore({ status: ChangesetStatus.Computing, files: [] });
|
|
2648
|
-
map.set(uri, store);
|
|
2649
|
-
}
|
|
2650
|
-
return store;
|
|
2651
|
-
}
|
|
2652
|
-
|
|
2653
|
-
/** The live store for a URI, or undefined when it has never been created. */
|
|
2654
|
-
private changesetStoreOf(rec: SessionRecord, uri: string): ChangesetStateStore | undefined {
|
|
2655
|
-
const owner = this.changesetOwner(rec, uri);
|
|
2656
|
-
if (owner === null) return undefined;
|
|
2657
|
-
const map = owner.kind === "chat" ? owner.chat.changesets : rec.sessionChangesets;
|
|
2658
|
-
return map.get(uri);
|
|
2659
|
-
}
|
|
2660
|
-
|
|
2661
|
-
/** The store's current per-file review flags, keyed by file id. */
|
|
2662
|
-
private reviewedById(store: ChangesetStateStore): Map<string, boolean> {
|
|
2663
|
-
const out = new Map<string, boolean>();
|
|
2664
|
-
for (const f of store.state.files) {
|
|
2665
|
-
if (typeof f.reviewed === "boolean") out.set(f.id, f.reviewed);
|
|
2666
|
-
}
|
|
2667
|
-
return out;
|
|
2668
|
-
}
|
|
2669
|
-
|
|
2670
|
-
/**
|
|
2671
|
-
* Recompute one changeset and publish the delta (gateway's
|
|
2672
|
-
* `updateChangesetChannel` pattern): `changeset/contentChanged` when the
|
|
2673
|
-
* file list changed (the discard operation is (re)attached while files
|
|
2674
|
-
* exist, and cleared when they vanish), then `changeset/statusChanged`
|
|
2675
|
-
* to ready when the status was not ready. A failed computation publishes
|
|
2676
|
-
* `changeset/statusChanged` with an error.
|
|
2677
|
-
*/
|
|
2678
|
-
private async refreshChangeset(rec: SessionRecord, uri: string): Promise<void> {
|
|
2679
|
-
const parsed = parseChangesetChannel(uri);
|
|
2680
|
-
if (parsed === null) return;
|
|
2681
|
-
const store = this.changesetStore(rec, uri);
|
|
2682
|
-
if (store === null) return; // owner gone (disposed chat)
|
|
2683
|
-
let files;
|
|
2684
|
-
try {
|
|
2685
|
-
if (parsed.kind === "turn") {
|
|
2686
|
-
// The turn's snapshots live on the owning chat; the content refs
|
|
2687
|
-
// carry its opencode session id (the byOpencode join key).
|
|
2688
|
-
const chat = rec.chats.get(parsed.ownerUri);
|
|
2689
|
-
if (chat === undefined) return;
|
|
2690
|
-
files = buildTurnChangesetFiles({
|
|
2691
|
-
sessionID: chat.sessionID,
|
|
2692
|
-
turnId: parsed.turnId ?? "",
|
|
2693
|
-
files: chat.turnSnapshots.get(parsed.turnId ?? "") ?? new Map(),
|
|
2694
|
-
reviewedById: this.reviewedById(store),
|
|
2695
|
-
});
|
|
2696
|
-
} else {
|
|
2697
|
-
const diffs = await this.opts.facade.vcsDiffWorking();
|
|
2698
|
-
files = buildWorkingChangesetFiles({ diffs, reviewedById: this.reviewedById(store) });
|
|
2699
|
-
}
|
|
2700
|
-
} catch (err) {
|
|
2701
|
-
this.publish({
|
|
2702
|
-
channel: uri,
|
|
2703
|
-
action: {
|
|
2704
|
-
type: ActionType.ChangesetStatusChanged,
|
|
2705
|
-
status: ChangesetStatus.Error,
|
|
2706
|
-
error: { errorType: "changeset-computation", message: errorMessage(err) },
|
|
2707
|
-
},
|
|
2708
|
-
});
|
|
2709
|
-
return;
|
|
2710
|
-
}
|
|
2711
|
-
const state = store.state;
|
|
2712
|
-
const hadFiles = state.files.length > 0;
|
|
2713
|
-
const hasFiles = files.length > 0;
|
|
2714
|
-
if (JSON.stringify(state.files) !== JSON.stringify(files)) {
|
|
2715
|
-
this.publish({
|
|
2716
|
-
channel: uri,
|
|
2717
|
-
action: {
|
|
2718
|
-
type: ActionType.ChangesetContentChanged,
|
|
2719
|
-
files,
|
|
2720
|
-
...(hasFiles ? { operations: [discardOperation()] } : {}),
|
|
2721
|
-
},
|
|
2722
|
-
});
|
|
2723
|
-
// operations persist across contentChanged — clear them explicitly
|
|
2724
|
-
// when the changeset empties out.
|
|
2725
|
-
if (!hasFiles && state.operations !== undefined && state.operations.length > 0) {
|
|
2726
|
-
this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: undefined } });
|
|
2727
|
-
}
|
|
2728
|
-
}
|
|
2729
|
-
if (!hadFiles && hasFiles && state.operations === undefined) {
|
|
2730
|
-
// contentChanged above already attached the operation; this branch
|
|
2731
|
-
// is unreachable unless the reducer drops it — kept as a guard.
|
|
2732
|
-
this.publish({ channel: uri, action: { type: ActionType.ChangesetOperationsChanged, operations: [discardOperation()] } });
|
|
2733
|
-
}
|
|
2734
|
-
if (state.status !== ChangesetStatus.Ready) {
|
|
2735
|
-
this.publish({ channel: uri, action: { type: ActionType.ChangesetStatusChanged, status: ChangesetStatus.Ready } });
|
|
2736
|
-
}
|
|
2737
|
-
}
|
|
2738
|
-
|
|
2739
|
-
/**
|
|
2740
|
-
* At a turn terminal: read the disk into each captured file's `after`
|
|
2741
|
-
* (a file deleted during the turn stays null → "deleted"), then refresh
|
|
2742
|
-
* the uncommitted, session, and ended-turn changesets — only the ones a
|
|
2743
|
-
* client has subscribed (unsubscribed changesets cost no seq).
|
|
2744
|
-
*/
|
|
2745
|
-
private async refreshTurnChangesets(rec: SessionRecord, chat: ChatRuntime, turnId: string): Promise<void> {
|
|
2746
|
-
const turnFiles = chat.turnSnapshots.get(turnId);
|
|
2747
|
-
if (turnFiles !== undefined) {
|
|
2748
|
-
for (const [absPath, snap] of turnFiles) {
|
|
2749
|
-
if (snap.after === null) {
|
|
2750
|
-
try {
|
|
2751
|
-
snap.after = await this.opts.facade.readFile(absPath);
|
|
2752
|
-
} catch {
|
|
2753
|
-
snap.after = null;
|
|
2754
|
-
}
|
|
2755
|
-
}
|
|
2756
|
-
}
|
|
2757
|
-
}
|
|
2758
|
-
// The chat's own uncommitted + turn changesets, plus the session-wide
|
|
2759
|
-
// one (shared by all chats). Only the ones a client has subscribed.
|
|
2760
|
-
for (const uri of [
|
|
2761
|
-
uncommittedChangesetURI(chat.uri),
|
|
2762
|
-
sessionChangesetURI(rec.channel),
|
|
2763
|
-
turnChangesetURI(chat.uri, turnId),
|
|
2764
|
-
]) {
|
|
2765
|
-
if (this.changesetStoreOf(rec, uri) !== undefined) await this.refreshChangeset(rec, uri);
|
|
2766
|
-
}
|
|
2767
|
-
}
|
|
2768
|
-
|
|
2769
|
-
/**
|
|
2770
|
-
* `resourceRead` (AHP root command): serve file content for the URIs
|
|
2771
|
-
* this host advertises in changesets —
|
|
2772
|
-
* - `file://` → live disk, confined to the location directory;
|
|
2773
|
-
* - `ahp-content://head/…` → the file's HEAD content;
|
|
2774
|
-
* - `ahp-content://snap/…` → a turn's captured before/after content.
|
|
2775
|
-
* Errors: -32008 (not found), -32009 (path outside the location).
|
|
2776
|
-
*/
|
|
2777
|
-
private async handleResourceRead(socketId: number, msg: RpcMessage): Promise<void> {
|
|
2778
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
2779
|
-
const uri = params["uri"];
|
|
2780
|
-
if (typeof uri !== "string" || uri.length === 0) {
|
|
2781
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resourceRead requires a content URI");
|
|
2782
|
-
return;
|
|
2783
|
-
}
|
|
2784
|
-
const encoding: "base64" | "utf-8" = params["encoding"] === "utf-8" ? "utf-8" : "base64";
|
|
2785
|
-
if (uri.startsWith("file://")) {
|
|
2786
|
-
let absPath: string;
|
|
2787
|
-
try {
|
|
2788
|
-
absPath = fileURLToPath(uri);
|
|
2789
|
-
} catch {
|
|
2790
|
-
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
2791
|
-
return;
|
|
2792
|
-
}
|
|
2793
|
-
if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
|
|
2794
|
-
this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
|
|
2795
|
-
return;
|
|
2796
|
-
}
|
|
2797
|
-
let content: string | null;
|
|
2798
|
-
try {
|
|
2799
|
-
content = await this.opts.facade.readFile(absPath);
|
|
2800
|
-
} catch (err) {
|
|
2801
|
-
this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, `read failed: ${errorMessage(err)}`);
|
|
2802
|
-
return;
|
|
2803
|
-
}
|
|
2804
|
-
if (content === null) {
|
|
2805
|
-
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
2806
|
-
return;
|
|
2807
|
-
}
|
|
2808
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
|
|
2809
|
-
return;
|
|
2810
|
-
}
|
|
2811
|
-
// Opaque content refs require the changesets capability.
|
|
2812
|
-
if (!this.opts.changesets) {
|
|
2813
|
-
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
2814
|
-
return;
|
|
2815
|
-
}
|
|
2816
|
-
const ref = parseContentRef(uri);
|
|
2817
|
-
if (ref === null) {
|
|
2818
|
-
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
2819
|
-
return;
|
|
2820
|
-
}
|
|
2821
|
-
if (ref.kind === "head") {
|
|
2822
|
-
if (this.opts.defaultDirectory !== undefined && !isPathInside(ref.path, this.opts.defaultDirectory)) {
|
|
2823
|
-
this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
|
|
2824
|
-
return;
|
|
2825
|
-
}
|
|
2826
|
-
let content: string | null;
|
|
2827
|
-
try {
|
|
2828
|
-
content = await this.opts.facade.gitHeadFile(ref.path);
|
|
2829
|
-
} catch (err) {
|
|
2830
|
-
this.sendError(socketId, msg.id, ERROR_INTERNAL, `HEAD read failed: ${errorMessage(err)}`);
|
|
2831
|
-
return;
|
|
2832
|
-
}
|
|
2833
|
-
if (content === null) {
|
|
2834
|
-
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not in HEAD: ${ref.path}`);
|
|
2835
|
-
return;
|
|
2836
|
-
}
|
|
2837
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
|
|
2838
|
-
return;
|
|
2839
|
-
}
|
|
2840
|
-
// snap — in-memory turn snapshot of a live chat's opencode session.
|
|
2841
|
-
const binding = this.byOpencode.get(ref.sessionID);
|
|
2842
|
-
if (binding === undefined) {
|
|
2843
|
-
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, "no such session");
|
|
2844
|
-
return;
|
|
2845
|
-
}
|
|
2846
|
-
const snap = binding.chat.turnSnapshots.get(ref.turnId)?.get(ref.path);
|
|
2847
|
-
const content = snap === undefined ? null : ref.part === "before" ? snap.before : snap.after;
|
|
2848
|
-
if (content === null) {
|
|
2849
|
-
this.sendError(socketId, msg.id, ERROR_NOT_FOUND, `not found: ${uri}`);
|
|
2850
|
-
return;
|
|
2851
|
-
}
|
|
2852
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: this.encodeContent(content, encoding) });
|
|
2853
|
-
}
|
|
2854
|
-
|
|
2855
|
-
/** Encode content for a `resourceRead` result (utf-8 or base64). */
|
|
2856
|
-
private encodeContent(content: string, encoding: "base64" | "utf-8") {
|
|
2857
|
-
return {
|
|
2858
|
-
data: encoding === "utf-8" ? content : Buffer.from(content, "utf-8").toString("base64"),
|
|
2859
|
-
encoding,
|
|
2860
|
-
};
|
|
2861
|
-
}
|
|
2862
|
-
|
|
2863
|
-
/**
|
|
2864
|
-
* `invokeChangesetOperation`: the host's only operation is
|
|
2865
|
-
* `discard-changes` (resource-scoped) — restore one file from the
|
|
2866
|
-
* changeset's "before" content. Status flows through the
|
|
2867
|
-
* `changeset/operationStatusChanged` stream; the JSON-RPC result carries
|
|
2868
|
-
* a human-readable message.
|
|
2869
|
-
*/
|
|
2870
|
-
private async handleInvokeChangesetOperation(socketId: number, msg: RpcMessage): Promise<void> {
|
|
2871
|
-
const params = isRecord(msg.params) ? msg.params : {};
|
|
2872
|
-
const channel = params["channel"];
|
|
2873
|
-
const operationId = params["operationId"];
|
|
2874
|
-
if (typeof channel !== "string" || channel.length === 0 || typeof operationId !== "string" || operationId.length === 0) {
|
|
2875
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "invokeChangesetOperation requires channel + operationId");
|
|
2876
|
-
return;
|
|
2877
|
-
}
|
|
2878
|
-
const parsed = parseChangesetChannel(channel);
|
|
2879
|
-
if (parsed === null) {
|
|
2880
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `not a changeset channel: ${channel}`);
|
|
2881
|
-
return;
|
|
2882
|
-
}
|
|
2883
|
-
const rec = this.byChannel.get(parsed.ownerUri);
|
|
2884
|
-
if (rec === undefined) {
|
|
2885
|
-
this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, "no such session");
|
|
2886
|
-
return;
|
|
2887
|
-
}
|
|
2888
|
-
const store = this.changesetStoreOf(rec, channel);
|
|
2889
|
-
if (store === undefined) {
|
|
2890
|
-
this.sendError(socketId, msg.id, ERROR_SESSION_NOT_FOUND, `no such changeset: ${channel}`);
|
|
2891
|
-
return;
|
|
2892
|
-
}
|
|
2893
|
-
const op = store.state.operations?.find((o) => o.id === operationId);
|
|
2894
|
-
if (op === undefined) {
|
|
2895
|
-
this.sendError(socketId, msg.id, ERROR_METHOD_NOT_FOUND, `unknown operation: ${operationId}`);
|
|
2896
|
-
return;
|
|
2897
|
-
}
|
|
2898
|
-
if (!op.scopes.includes(ChangesetOperationScope.Resource)) {
|
|
2899
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `operation ${operationId} is not resource-scoped`);
|
|
2900
|
-
return;
|
|
2901
|
-
}
|
|
2902
|
-
const target = params["target"];
|
|
2903
|
-
if (!isRecord(target) || target["kind"] !== "resource" || typeof target["resource"] !== "string") {
|
|
2904
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "resource-scoped operation requires a resource target");
|
|
2905
|
-
return;
|
|
2906
|
-
}
|
|
2907
|
-
let absPath: string;
|
|
2908
|
-
try {
|
|
2909
|
-
absPath = fileURLToPath(target["resource"] as string);
|
|
2910
|
-
} catch {
|
|
2911
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "target.resource must be a file URI");
|
|
2912
|
-
return;
|
|
2913
|
-
}
|
|
2914
|
-
if (!store.state.files.some((f) => f.id === fileUri(absPath))) {
|
|
2915
|
-
this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, `no such file in changeset: ${target["resource"]}`);
|
|
2916
|
-
return;
|
|
2917
|
-
}
|
|
2918
|
-
if (this.opts.defaultDirectory !== undefined && !isPathInside(absPath, this.opts.defaultDirectory)) {
|
|
2919
|
-
this.sendError(socketId, msg.id, ERROR_PERMISSION_DENIED, "path is outside the location directory");
|
|
2920
|
-
return;
|
|
2921
|
-
}
|
|
2922
|
-
this.publish({
|
|
2923
|
-
channel,
|
|
2924
|
-
action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Running },
|
|
2925
|
-
});
|
|
2926
|
-
try {
|
|
2927
|
-
if (parsed.kind === "turn" && parsed.turnId !== undefined) {
|
|
2928
|
-
// A live turn-changeset store implies a live owning chat
|
|
2929
|
-
// (changesetStoreOf resolved it above).
|
|
2930
|
-
await this.restoreTurnFile(rec.chats.get(parsed.ownerUri)!, parsed.turnId, absPath);
|
|
2931
|
-
} else {
|
|
2932
|
-
await this.opts.facade.discardFile(absPath);
|
|
2933
|
-
}
|
|
2934
|
-
} catch (err) {
|
|
2935
|
-
this.publish({
|
|
2936
|
-
channel,
|
|
2937
|
-
action: {
|
|
2938
|
-
type: ActionType.ChangesetOperationStatusChanged,
|
|
2939
|
-
operationId,
|
|
2940
|
-
status: ChangesetOperationStatus.Error,
|
|
2941
|
-
error: { errorType: "operation-failed", message: errorMessage(err) },
|
|
2942
|
-
},
|
|
2943
|
-
});
|
|
2944
|
-
this.sendError(socketId, msg.id, ERROR_INTERNAL, errorMessage(err));
|
|
2945
|
-
return;
|
|
2946
|
-
}
|
|
2947
|
-
await this.refreshChangeset(rec, channel);
|
|
2948
|
-
this.publish({
|
|
2949
|
-
channel,
|
|
2950
|
-
action: { type: ActionType.ChangesetOperationStatusChanged, operationId, status: ChangesetOperationStatus.Idle },
|
|
2951
|
-
});
|
|
2952
|
-
this.sendFrame(socketId, {
|
|
2953
|
-
jsonrpc: "2.0",
|
|
2954
|
-
id: msg.id ?? null,
|
|
2955
|
-
result: { message: `Discarded changes to ${absPath}` },
|
|
2956
|
-
});
|
|
2957
|
-
}
|
|
2958
|
-
|
|
2959
|
-
/**
|
|
2960
|
-
* Restore one file from a turn's before-snapshot: the file was added by
|
|
2961
|
-
* the turn (before === null) → delete it; otherwise write the pre-edit
|
|
2962
|
-
* content back.
|
|
2963
|
-
*/
|
|
2964
|
-
private async restoreTurnFile(chat: ChatRuntime, turnId: string, absPath: string): Promise<void> {
|
|
2965
|
-
const snap = chat.turnSnapshots.get(turnId)?.get(absPath);
|
|
2966
|
-
const before = snap?.before ?? null;
|
|
2967
|
-
if (before === null) {
|
|
2968
|
-
await this.opts.facade.deleteFile(absPath);
|
|
2969
|
-
} else {
|
|
2970
|
-
await this.opts.facade.writeFile(absPath, before);
|
|
2971
|
-
}
|
|
2972
|
-
}
|
|
2973
|
-
|
|
2974
|
-
/**
|
|
2975
|
-
* Lazily publish `chat/toolCallReady` for a tool call (first of
|
|
2976
|
-
* progress/success/failed/permission.asked):
|
|
2977
|
-
* - permission trigger → no `confirmed` → the reducer parks it in
|
|
2978
|
-
* `pending-confirmation` (the caller then raises `inputNeededSet`);
|
|
2979
|
-
* - otherwise → `confirmed: "not-needed"` → straight to `running`
|
|
2980
|
-
* (opencode auto-approved).
|
|
2981
|
-
*/
|
|
2982
|
-
private ensureToolReady(chat: ChatRuntime, toolCallId: string, permission: boolean): void {
|
|
2983
|
-
if (chat.toolReady.has(toolCallId) || chat.currentTurnId === null) return;
|
|
2984
|
-
chat.toolReady.add(toolCallId);
|
|
2985
|
-
const name = chat.toolName.get(toolCallId) ?? "tool";
|
|
2986
|
-
const input = chat.toolInput.get(toolCallId);
|
|
2987
|
-
this.publish({
|
|
2988
|
-
channel: chat.uri,
|
|
2989
|
-
action: {
|
|
2990
|
-
type: ActionType.ChatToolCallReady,
|
|
2991
|
-
turnId: chat.currentTurnId,
|
|
2992
|
-
toolCallId,
|
|
2993
|
-
invocationMessage: invocationMessageFor(name, input),
|
|
2994
|
-
toolInput: input,
|
|
2995
|
-
...(permission ? {} : { confirmed: ToolCallConfirmationReason.NotNeeded }),
|
|
2996
|
-
},
|
|
2997
|
-
});
|
|
2998
|
-
}
|
|
2999
|
-
|
|
3000
|
-
/** The live tool-call state in the chat's current turn, or null when absent. */
|
|
3001
|
-
private toolCallState(chat: ChatRuntime, toolCallId: string): ToolCallState | null {
|
|
3002
|
-
const turn = chat.chatStore.state.activeTurn;
|
|
3003
|
-
if (turn === undefined) return null;
|
|
3004
|
-
for (const part of turn.responseParts) {
|
|
3005
|
-
if (part.kind === ResponsePartKind.ToolCall && part.toolCall.toolCallId === toolCallId) {
|
|
3006
|
-
return part.toolCall;
|
|
3007
|
-
}
|
|
3008
|
-
}
|
|
3009
|
-
return null;
|
|
3010
|
-
}
|
|
3011
|
-
|
|
3012
|
-
/**
|
|
3013
|
-
* The tool call's state when it is awaiting confirmation (the
|
|
3014
|
-
* `SessionToolConfirmationRequest.toolCall` shape), or null otherwise.
|
|
3015
|
-
*/
|
|
3016
|
-
private pendingToolCall(chat: ChatRuntime, toolCallId: string): ToolCallConfirmationState | null {
|
|
3017
|
-
const tc = this.toolCallState(chat, toolCallId);
|
|
3018
|
-
if (tc === null) return null;
|
|
3019
|
-
if (tc.status === ToolCallStatus.PendingConfirmation || tc.status === ToolCallStatus.PendingResultConfirmation) {
|
|
3020
|
-
return tc;
|
|
3021
|
-
}
|
|
3022
|
-
return null;
|
|
3023
|
-
}
|
|
3024
|
-
|
|
3025
|
-
/** True when the tool call already left the ready states (completed/cancelled). */
|
|
3026
|
-
private toolCallTerminal(chat: ChatRuntime, toolCallId: string): boolean {
|
|
3027
|
-
const tc = this.toolCallState(chat, toolCallId);
|
|
3028
|
-
return tc !== null && (tc.status === ToolCallStatus.Completed || tc.status === ToolCallStatus.Cancelled);
|
|
3029
|
-
}
|
|
3030
|
-
|
|
3031
|
-
private clearToolTracking(chat: ChatRuntime, toolCallId: string): void {
|
|
3032
|
-
chat.toolInput.delete(toolCallId);
|
|
3033
|
-
chat.toolName.delete(toolCallId);
|
|
3034
|
-
chat.toolReady.delete(toolCallId);
|
|
3035
|
-
chat.clientToolCalls.delete(toolCallId);
|
|
3036
|
-
}
|
|
3037
|
-
|
|
3038
|
-
// ── client-tool helpers ─────────────────────────────────────────────────
|
|
3039
|
-
|
|
3040
|
-
/**
|
|
3041
|
-
* The session's active client providing `toolName` (the tool-call
|
|
3042
|
-
* contributor), or null when no active client provides it (a
|
|
3043
|
-
* server-executed call — the normal path).
|
|
3044
|
-
*/
|
|
3045
|
-
private clientToolContributor(rec: SessionRecord, toolName: string): string | null {
|
|
3046
|
-
return findProvider(rec.sessionStore.state.activeClients, toolName);
|
|
3047
|
-
}
|
|
3048
|
-
|
|
3049
|
-
/**
|
|
3050
|
-
* Re-sync the location-global opencode tool registry with the
|
|
3051
|
-
* cross-session union of every live session's active-client tools
|
|
3052
|
-
* (first-registered wins per name). Location-global by design —
|
|
3053
|
-
* opencode's tool state is per-location, not per-session: the
|
|
3054
|
-
* `execute` bridge re-checks per-session ownership at
|
|
3055
|
-
* runtime.
|
|
3056
|
-
*/
|
|
3057
|
-
private async syncClientToolsToOpencode(): Promise<void> {
|
|
3058
|
-
const clients: SessionActiveClient[] = [];
|
|
3059
|
-
for (const rec of this.sessions.values()) {
|
|
3060
|
-
for (const client of rec.sessionStore.state.activeClients) clients.push(client);
|
|
3061
|
-
}
|
|
3062
|
-
const tools = toolUnion(clients).map(
|
|
3063
|
-
(t): FacadeClientTool => ({
|
|
3064
|
-
name: t.name,
|
|
3065
|
-
description: descriptionFor(t),
|
|
3066
|
-
inputSchema: inputSchemaFor(t),
|
|
3067
|
-
}),
|
|
3068
|
-
);
|
|
3069
|
-
try {
|
|
3070
|
-
await this.opts.facade.syncClientTools(tools);
|
|
3071
|
-
} catch (err) {
|
|
3072
|
-
// R2: a tool-registry failure must not break the AHP surface —
|
|
3073
|
-
// the active-client state stays authoritative on the AHP side.
|
|
3074
|
-
this.log(`client tool sync failed: ${errorMessage(err)}`);
|
|
3075
|
-
}
|
|
3076
|
-
}
|
|
3077
|
-
|
|
3078
|
-
/**
|
|
3079
|
-
* Settle a client-tool invocation with its final result: the
|
|
3080
|
-
* opencode-side `execute` (blocked on the waiter) unblocks and
|
|
3081
|
-
* returns/throws, which drives the pump's `tool.success`/
|
|
3082
|
-
* `tool.failed` terminal (the AHP state is already terminal — the
|
|
3083
|
-
* pump's `toolCallTerminal` check suppresses a duplicate echo and
|
|
3084
|
-
* clears the tracking). Settling twice is a no-op.
|
|
3085
|
-
*
|
|
3086
|
-
* `result` may be omitted when the invocation's `result` was already
|
|
3087
|
-
* set by the caller (the eviction / session-removal paths set it
|
|
3088
|
-
* first and then settle to deliver it).
|
|
3089
|
-
*/
|
|
3090
|
-
private settleClientTool(invocation: ClientToolInvocation, result?: FacadeClientToolResult): void {
|
|
3091
|
-
if (invocation.result === undefined) {
|
|
3092
|
-
if (result === undefined) return; // nothing to settle
|
|
3093
|
-
invocation.result = result;
|
|
3094
|
-
}
|
|
3095
|
-
if (invocation.waiter !== undefined && invocation.waiter !== null) {
|
|
3096
|
-
invocation.waiter(invocation.result);
|
|
3097
|
-
invocation.waiter = null;
|
|
3098
|
-
}
|
|
3099
|
-
}
|
|
3100
|
-
|
|
3101
|
-
/**
|
|
3102
|
-
* The opencode tool `execute` bridge (called from the
|
|
3103
|
-
* `ctx.tool.transform` registration in src/index.ts): route one
|
|
3104
|
-
* client-tool invocation to the owning AHP client and wait for its
|
|
3105
|
-
* result.
|
|
3106
|
-
*
|
|
3107
|
-
* Per-session scoping: the tool is visible location-
|
|
3108
|
-
* globally, but execution only resolves when *this* session is an
|
|
3109
|
-
* AHP session with an active client providing the tool — otherwise
|
|
3110
|
-
* the opencode tool fails (a `Tool.Error` the model sees), so e.g. a
|
|
3111
|
-
* TUI session can see the tool but not execute it.
|
|
3112
|
-
*/
|
|
3113
|
-
executeClientTool(input: {
|
|
3114
|
-
sessionID: string;
|
|
3115
|
-
toolCallId: string;
|
|
3116
|
-
name: string;
|
|
3117
|
-
signal: AbortSignal;
|
|
3118
|
-
}): Promise<FacadeClientToolResult> {
|
|
3119
|
-
// The opencode session id joins to the (record, chat) that owns it —
|
|
3120
|
-
// every chat has its own backend session.
|
|
3121
|
-
const binding = this.byOpencode.get(input.sessionID);
|
|
3122
|
-
if (binding === undefined) {
|
|
3123
|
-
return Promise.resolve({
|
|
3124
|
-
ok: false,
|
|
3125
|
-
error: `no AHP session for tool "${input.name}" (session ${input.sessionID} is not an AHP session)`,
|
|
3126
|
-
});
|
|
3127
|
-
}
|
|
3128
|
-
const { rec, chat } = binding;
|
|
3129
|
-
const invocation = chat.clientToolCalls.get(input.toolCallId);
|
|
3130
|
-
if (invocation === undefined) {
|
|
3131
|
-
return Promise.resolve({
|
|
3132
|
-
ok: false,
|
|
3133
|
-
error: `no client-executed call in flight for tool "${input.name}" (it was not registered by this session's active client)`,
|
|
3134
|
-
});
|
|
3135
|
-
}
|
|
3136
|
-
if (findProvider(rec.sessionStore.state.activeClients, input.name) !== invocation.clientId) {
|
|
3137
|
-
return Promise.resolve({
|
|
3138
|
-
ok: false,
|
|
3139
|
-
error: `session ${rec.sessionID} has no active client providing tool "${input.name}"`,
|
|
3140
|
-
});
|
|
3141
|
-
}
|
|
3142
|
-
if (input.signal.aborted) {
|
|
3143
|
-
const result: FacadeClientToolResult = { ok: false, error: `execution of "${input.name}" was cancelled` };
|
|
3144
|
-
this.settleClientTool(invocation, result);
|
|
3145
|
-
return Promise.resolve(result);
|
|
3146
|
-
}
|
|
3147
|
-
// The invocation may already be settled (the client completed before
|
|
3148
|
-
// opencode started the execute — possible: the client only needs the
|
|
3149
|
-
// pump's ready/inputNeeded actions, not our execute). Deliver the
|
|
3150
|
-
// settled result; otherwise register the waiter.
|
|
3151
|
-
const settled = invocation.result;
|
|
3152
|
-
if (settled !== undefined) return Promise.resolve(settled);
|
|
3153
|
-
return new Promise<FacadeClientToolResult>((resolve) => {
|
|
3154
|
-
invocation.waiter = resolve;
|
|
3155
|
-
const onAbort = () => {
|
|
3156
|
-
if (invocation.result === undefined) {
|
|
3157
|
-
this.settleClientTool(invocation, {
|
|
3158
|
-
ok: false,
|
|
3159
|
-
error: `execution of "${input.name}" was cancelled (turn interrupted)`,
|
|
3160
|
-
});
|
|
3161
|
-
}
|
|
3162
|
-
// If already settled, the waiter is gone — the abort is a no-op.
|
|
3163
|
-
};
|
|
3164
|
-
input.signal.addEventListener("abort", onAbort, { once: true });
|
|
3165
|
-
});
|
|
3166
|
-
}
|
|
3167
|
-
|
|
3168
|
-
// ── session registration / removal ─────────────────────────────────────
|
|
3169
|
-
|
|
3170
|
-
/**
|
|
3171
|
-
* Verify a `session.created` event via the session API and register the
|
|
3172
|
-
* session under its own id as the channel suffix (the suffix starts
|
|
3173
|
-
* with "ses" — opencode ids are valid suffixes). No-op when the session
|
|
3174
|
-
* is gone, already registered, or a createSession remap is pending.
|
|
3175
|
-
*/
|
|
3176
|
-
private async registerExternalDeferred(sessionID: string): Promise<void> {
|
|
3177
|
-
if (this.sessions.has(sessionID) || this.byOpencode.has(sessionID)) return;
|
|
3178
|
-
let fs: FacadeSession | null;
|
|
3179
|
-
try {
|
|
3180
|
-
fs = await this.opts.facade.getSession(sessionID);
|
|
3181
|
-
} catch {
|
|
3182
|
-
return;
|
|
3183
|
-
}
|
|
3184
|
-
if (fs === null || this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) return;
|
|
3185
|
-
this.registerExternal(fs);
|
|
3186
|
-
}
|
|
3187
|
-
|
|
3188
|
-
/**
|
|
3189
|
-
* Register an opencode session the host did not create (TUI, another
|
|
3190
|
-
* client, or a session resurfacing after a restart).
|
|
3191
|
-
* Outcomes:
|
|
3192
|
-
*
|
|
3193
|
-
* - the opencode id already backs a chat of a live record → skip
|
|
3194
|
-
* (undefined); `listSessions` must not surface peer-chat backends
|
|
3195
|
-
* as their own AHP sessions;
|
|
3196
|
-
* - the session carries a peer marker and the owner record is
|
|
3197
|
-
* registered (and the marker's chat URI is free) → re-attach it to
|
|
3198
|
-
* the owner's chat catalog (undefined — no standalone session);
|
|
3199
|
-
* - the peer marker's owner is not registered yet → queue the
|
|
3200
|
-
* binding (undefined) — the owner may be listed later in the same
|
|
3201
|
-
* `listSessions` pass (there is no boot-time event replay);
|
|
3202
|
-
* - the session carries a channel marker (minted-id default backend)
|
|
3203
|
-
* and the marked channel is free → a standalone session registered
|
|
3204
|
-
* under the ORIGINAL client-chosen channel;
|
|
3205
|
-
* - otherwise → a standalone session whose channel reuses the
|
|
3206
|
-
* opencode id (the record).
|
|
3207
|
-
*/
|
|
3208
|
-
private registerExternal(fs: FacadeSession): SessionRecord | undefined {
|
|
3209
|
-
const existing = this.sessions.get(fs.sessionID);
|
|
3210
|
-
if (existing !== undefined) return existing;
|
|
3211
|
-
if (this.byOpencode.has(fs.sessionID)) return undefined;
|
|
3212
|
-
const marker = parseAhpMarker(fs.metadata);
|
|
3213
|
-
if (marker !== null) {
|
|
3214
|
-
if (marker.chat !== undefined && marker.owner !== undefined) {
|
|
3215
|
-
const owner = this.sessions.get(marker.owner);
|
|
3216
|
-
if (owner !== undefined) {
|
|
3217
|
-
if (this.byChannel.has(marker.chat)) {
|
|
3218
|
-
// The marker's chat is already bound — e.g. a fork inherited
|
|
3219
|
-
// the parent's metadata (core documents the inheritance).
|
|
3220
|
-
// Standalone fallback: the data stays reachable in AHP.
|
|
3221
|
-
this.log(
|
|
3222
|
-
`ignoring the AHP marker on ${fs.sessionID}: chat ${marker.chat} is already bound (registering standalone)`,
|
|
3223
|
-
);
|
|
3224
|
-
} else {
|
|
3225
|
-
return this.reattachPeerChat(owner, fs, marker.chat);
|
|
3226
|
-
}
|
|
3227
|
-
} else {
|
|
3228
|
-
this.enqueueChatBinding(marker.owner, fs, marker.chat);
|
|
3229
|
-
return undefined;
|
|
3230
|
-
}
|
|
3231
|
-
} else if (marker.channel !== undefined) {
|
|
3232
|
-
// The default backend of a minted-id session carries the
|
|
3233
|
-
// client-chosen session channel — resurface under it.
|
|
3234
|
-
if (this.byChannel.has(marker.channel)) {
|
|
3235
|
-
this.log(
|
|
3236
|
-
`ignoring the AHP channel marker on ${fs.sessionID}: ${marker.channel} is already bound (registering under the opencode id)`,
|
|
3237
|
-
);
|
|
3238
|
-
} else {
|
|
3239
|
-
return this.registerExternalStandalone(fs, marker.channel);
|
|
3240
|
-
}
|
|
3241
|
-
}
|
|
3242
|
-
}
|
|
3243
|
-
return this.registerExternalStandalone(fs);
|
|
3244
|
-
}
|
|
3245
|
-
|
|
3246
|
-
/**
|
|
3247
|
-
* Re-attach a marked peer backend to its owner session's chat catalog
|
|
3248
|
-
* after a restart. The owner store is LIVE (unlike a
|
|
3249
|
-
* fresh standalone registration), so the catalog change goes through
|
|
3250
|
-
* `publish` (store + any existing subscribers + the root diff), not a
|
|
3251
|
-
* direct apply. The chat title is re-derived (`Chat <n>`) — a
|
|
3252
|
-
* documented divergence from the pre-restart title. Returns undefined:
|
|
3253
|
-
* the backend gets no standalone AHP session (its session channel is
|
|
3254
|
-
* not registered — `sessions.get(peerID)` misses).
|
|
3255
|
-
*/
|
|
3256
|
-
private reattachPeerChat(rec: SessionRecord, fs: FacadeSession, chatURI: string): undefined {
|
|
3257
|
-
const modifiedAt = new Date(fs.time.updated).toISOString();
|
|
3258
|
-
const chat = this.newChatRuntime(chatURI, fs.sessionID, `Chat ${rec.chats.size + 1}`, modifiedAt);
|
|
3259
|
-
this.bindChat(rec, chat);
|
|
3260
|
-
this.publish({
|
|
3261
|
-
channel: rec.channel,
|
|
3262
|
-
action: { type: ActionType.SessionChatAdded, summary: chatSummaryOf(chat.chatStore.state) },
|
|
3263
|
-
});
|
|
3264
|
-
if (this.opts.changesets) {
|
|
3265
|
-
this.publish({
|
|
3266
|
-
channel: chatURI,
|
|
3267
|
-
action: { type: ActionType.ChatChangesetsChanged, changesets: chatChangesetCatalog(chatURI, rec.channel) },
|
|
3268
|
-
});
|
|
3269
|
-
}
|
|
3270
|
-
this.log(`reattached peer chat ${chatURI} (backend ${fs.sessionID}) to session ${rec.channel} from its AHP marker`);
|
|
3271
|
-
return undefined;
|
|
3272
|
-
}
|
|
3273
|
-
|
|
3274
|
-
/**
|
|
3275
|
-
* Queue a peer-chat binding whose owner is not registered yet (the
|
|
3276
|
-
* peer was listed before the owner, or the owner has not been listed
|
|
3277
|
-
* at all). `drainPendingChatBindings` resolves it when the owner
|
|
3278
|
-
* registers. The orphan fallback fires after the grace window: if the
|
|
3279
|
-
* owner is still unregistered and gone from opencode, the peer is
|
|
3280
|
-
* surfaced as its own AHP session instead (the data stays reachable).
|
|
3281
|
-
*/
|
|
3282
|
-
private enqueueChatBinding(ownerID: string, fs: FacadeSession, chatURI: string): void {
|
|
3283
|
-
const queue = this.pendingChatBindings.get(ownerID) ?? [];
|
|
3284
|
-
queue.push({ fs, chatURI });
|
|
3285
|
-
this.pendingChatBindings.set(ownerID, queue);
|
|
3286
|
-
setTimeout(() => {
|
|
3287
|
-
void this.checkOrphanChatBindings(ownerID).catch((err) =>
|
|
3288
|
-
this.log(`orphan chat-binding check failed: ${errorMessage(err)}`),
|
|
3289
|
-
);
|
|
3290
|
-
}, EXTERNAL_REGISTER_GRACE_MS);
|
|
3291
|
-
}
|
|
3292
|
-
|
|
3293
|
-
/**
|
|
3294
|
-
* Orphan fallback for queued peer-chat bindings: the
|
|
3295
|
-
* owner never registered and is gone from opencode (e.g. deleted in
|
|
3296
|
-
* the TUI while the plugin was down). Drop the queue and register each
|
|
3297
|
-
* peer as a standalone AHP session. A failed owner lookup keeps the
|
|
3298
|
-
* queue — the next registration or timer re-checks.
|
|
3299
|
-
*/
|
|
3300
|
-
private async checkOrphanChatBindings(ownerID: string): Promise<void> {
|
|
3301
|
-
const queue = this.pendingChatBindings.get(ownerID);
|
|
3302
|
-
if (queue === undefined || queue.length === 0) return; // the owner registered — drained
|
|
3303
|
-
let owner: FacadeSession | null;
|
|
3304
|
-
try {
|
|
3305
|
-
owner = await this.opts.facade.getSession(ownerID);
|
|
3306
|
-
} catch {
|
|
3307
|
-
return;
|
|
3308
|
-
}
|
|
3309
|
-
if (owner !== null) return; // the owner still exists in opencode — it registers when listed
|
|
3310
|
-
this.pendingChatBindings.delete(ownerID);
|
|
3311
|
-
for (const { fs, chatURI } of queue) {
|
|
3312
|
-
if (this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) continue;
|
|
3313
|
-
this.log(
|
|
3314
|
-
`AHP marker owner ${ownerID} is gone from opencode — registering the orphaned peer ${fs.sessionID} (chat ${chatURI}) as a standalone session`,
|
|
3315
|
-
);
|
|
3316
|
-
this.registerExternalStandalone(fs);
|
|
3317
|
-
}
|
|
3318
|
-
}
|
|
3319
|
-
|
|
3320
|
-
/**
|
|
3321
|
-
* Resolve queued peer-chat bindings once their owner registers (called
|
|
3322
|
-
* from the standalone registration's success path). A chat URI that is
|
|
3323
|
-
* already bound by then (e.g. the client created it again across the
|
|
3324
|
-
* restart) falls back to standalone registration.
|
|
3325
|
-
*/
|
|
3326
|
-
private drainPendingChatBindings(ownerID: string): void {
|
|
3327
|
-
const queue = this.pendingChatBindings.get(ownerID);
|
|
3328
|
-
const owner = this.sessions.get(ownerID);
|
|
3329
|
-
if (queue === undefined || queue.length === 0 || owner === undefined) return;
|
|
3330
|
-
this.pendingChatBindings.delete(ownerID);
|
|
3331
|
-
for (const { fs, chatURI } of queue) {
|
|
3332
|
-
if (this.sessions.has(fs.sessionID) || this.byOpencode.has(fs.sessionID)) continue;
|
|
3333
|
-
if (this.byChannel.has(chatURI)) {
|
|
3334
|
-
this.log(
|
|
3335
|
-
`ignoring the AHP marker on ${fs.sessionID}: chat ${chatURI} is already bound (registering standalone)`,
|
|
3336
|
-
);
|
|
3337
|
-
this.registerExternalStandalone(fs);
|
|
3338
|
-
} else {
|
|
3339
|
-
this.reattachPeerChat(owner, fs, chatURI);
|
|
3340
|
-
}
|
|
3341
|
-
}
|
|
3342
|
-
}
|
|
3343
|
-
|
|
3344
|
-
/**
|
|
3345
|
-
* Register an opencode session as a single-chat AHP session (its
|
|
3346
|
-
* default chat reuses the opencode id). The session channel defaults
|
|
3347
|
-
* to the opencode id; the channel-marker path passes
|
|
3348
|
-
* the ORIGINAL client-chosen channel instead — the registry then
|
|
3349
|
-
* resolves both suffixes (mirroring `handleCreateSession`). Applied
|
|
3350
|
-
* directly to the fresh stores (no seq, no actions) — the
|
|
3351
|
-
* registration is server-side bookkeeping, not a client-visible state
|
|
3352
|
-
* transition; the root announcement carries the lifecycle.
|
|
3353
|
-
*/
|
|
3354
|
-
private registerExternalStandalone(fs: FacadeSession, channel?: string): SessionRecord {
|
|
3355
|
-
const recChannel = channel ?? sessionChannelURI(fs.sessionID);
|
|
3356
|
-
const modifiedAt = new Date(fs.time.updated).toISOString();
|
|
3357
|
-
const sessionStore = createSessionStateStore(
|
|
3358
|
-
initialSessionState({
|
|
3359
|
-
sessionID: fs.sessionID,
|
|
3360
|
-
provider: fs.model?.providerID ?? "opencode",
|
|
3361
|
-
title: fs.title ?? "New Session",
|
|
3362
|
-
status: fs.archived
|
|
3363
|
-
? ((SessionStatus.Idle | SessionStatus.IsRead | SessionStatus.IsArchived) as SessionStatus)
|
|
3364
|
-
: undefined, // Idle | IsRead | IsArchived
|
|
3365
|
-
}),
|
|
3366
|
-
);
|
|
3367
|
-
const rec: SessionRecord = {
|
|
3368
|
-
sessionID: fs.sessionID,
|
|
3369
|
-
channel: recChannel,
|
|
3370
|
-
provider: sessionStore.state.provider,
|
|
3371
|
-
createdAt: new Date(fs.time.created).toISOString(),
|
|
3372
|
-
modifiedAt,
|
|
3373
|
-
sessionStore,
|
|
3374
|
-
chats: new Map(),
|
|
3375
|
-
defaultChatURI: chatChannelURI(fs.sessionID),
|
|
3376
|
-
sessionChangesets: new Map(),
|
|
3377
|
-
};
|
|
3378
|
-
this.sessions.set(fs.sessionID, rec);
|
|
3379
|
-
this.byChannel.set(recChannel, rec);
|
|
3380
|
-
// The registry resolves the opencode id (event pump, chat channels)
|
|
3381
|
-
// and — for a channel-marker registration — the client-chosen
|
|
3382
|
-
// suffix too (mirroring `handleCreateSession`).
|
|
3383
|
-
const suffix = sessionIDOf(recChannel) as string;
|
|
3384
|
-
if (suffix !== fs.sessionID) this.channels.addSession(suffix);
|
|
3385
|
-
const defaultChat = this.newChatRuntime(rec.defaultChatURI, fs.sessionID, "Chat 1", modifiedAt);
|
|
3386
|
-
this.bindChat(rec, defaultChat);
|
|
3387
|
-
sessionStore.apply({ type: ActionType.SessionReady });
|
|
3388
|
-
sessionStore.apply({ type: ActionType.SessionChatAdded, summary: chatSummaryOf(defaultChat.chatStore.state) });
|
|
3389
|
-
sessionStore.apply({ type: ActionType.SessionDefaultChatChanged, defaultChat: rec.defaultChatURI });
|
|
3390
|
-
// Advertise the changeset catalogues directly on the fresh
|
|
3391
|
-
// stores (registration is server-side bookkeeping — no seq, no actions).
|
|
3392
|
-
if (this.opts.changesets) {
|
|
3393
|
-
sessionStore.apply({ type: ActionType.SessionChangesetsChanged, changesets: sessionChangesetCatalog(recChannel) });
|
|
3394
|
-
defaultChat.chatStore.apply({
|
|
3395
|
-
type: ActionType.ChatChangesetsChanged,
|
|
3396
|
-
changesets: chatChangesetCatalog(rec.defaultChatURI, recChannel),
|
|
3397
|
-
});
|
|
3398
|
-
}
|
|
3399
|
-
// Durability: peers whose marker points at this
|
|
3400
|
-
// session may have been listed earlier in the same `listSessions`
|
|
3401
|
-
// pass — re-attach them before the root announcement so the
|
|
3402
|
-
// sessionAdded summary carries the full chat catalog.
|
|
3403
|
-
this.drainPendingChatBindings(fs.sessionID);
|
|
3404
|
-
this.publish({
|
|
3405
|
-
channel: ROOT_CHANNEL,
|
|
3406
|
-
action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
|
|
3407
|
-
});
|
|
3408
|
-
this.notifyRoot("root/sessionAdded", { channel: ROOT_CHANNEL, summary: this.sessionSummary(rec) });
|
|
3409
|
-
return rec;
|
|
3410
|
-
}
|
|
3411
|
-
|
|
3412
|
-
/** Drop a session record and announce the removal on the root channel. */
|
|
3413
|
-
private removeRecord(rec: SessionRecord): void {
|
|
3414
|
-
const hadClients = rec.sessionStore.state.activeClients.length > 0;
|
|
3415
|
-
// Peer-chat backends are removed while their bindings are still live:
|
|
3416
|
-
// an unbound lingering backend would be re-registered by the next
|
|
3417
|
-
// listSessions scan as its own AHP session. R2: failures log — the
|
|
3418
|
-
// AHP side tears down either way (the ghost then shows in the TUI).
|
|
3419
|
-
for (const chat of rec.chats.values()) {
|
|
3420
|
-
if (chat.uri === rec.defaultChatURI) continue;
|
|
3421
|
-
void this.opts.facade
|
|
3422
|
-
.removeSession(chat.sessionID)
|
|
3423
|
-
.catch((err) => this.log(`failed to remove the peer chat's opencode session ${chat.sessionID}: ${errorMessage(err)}`));
|
|
3424
|
-
}
|
|
3425
|
-
// Every live changeset URI is about to become un-subscribable
|
|
3426
|
-
// — dispatch `changeset/cleared` (protocol case 2) before the teardown
|
|
3427
|
-
// so subscribers release their references.
|
|
3428
|
-
for (const uri of rec.sessionChangesets.keys()) {
|
|
3429
|
-
this.publish({ channel: uri, action: { type: ActionType.ChangesetCleared } });
|
|
3430
|
-
}
|
|
3431
|
-
rec.sessionChangesets.clear();
|
|
3432
|
-
// Per-chat teardown: live chat changesets
|
|
3433
|
-
// (`changeset/cleared`), in-flight client-tool executions failed
|
|
3434
|
-
// (the waiters must not leak), and every binding dropped.
|
|
3435
|
-
let failedTools = false;
|
|
3436
|
-
for (const chat of [...rec.chats.values()]) {
|
|
3437
|
-
failedTools = failedTools || [...chat.clientToolCalls.values()].some((inv) => inv.result === undefined);
|
|
3438
|
-
this.removeChat(rec, chat, "session removed before the client completed the tool call");
|
|
3439
|
-
}
|
|
3440
|
-
this.sessions.delete(rec.sessionID);
|
|
3441
|
-
this.byChannel.delete(rec.channel);
|
|
3442
|
-
const id = sessionIDOf(rec.channel);
|
|
3443
|
-
if (id !== null) this.channels.removeSession(id);
|
|
3444
|
-
this.channels.removeSession(rec.sessionID);
|
|
3445
|
-
this.publish({
|
|
3446
|
-
channel: ROOT_CHANNEL,
|
|
3447
|
-
action: { type: ActionType.RootActiveSessionsChanged, activeSessions: this.sessions.size },
|
|
3448
|
-
});
|
|
3449
|
-
this.notifyRoot("root/sessionRemoved", { channel: ROOT_CHANNEL, session: rec.channel });
|
|
3450
|
-
// Re-sync the opencode tool union when this
|
|
3451
|
-
// session's clients' tools leave the cross-session set (or any
|
|
3452
|
-
// in-flight call was failed — the facade union is unchanged, but the
|
|
3453
|
-
// session's execute gate must not linger).
|
|
3454
|
-
if (hadClients || failedTools) void this.syncClientToolsToOpencode();
|
|
3455
|
-
}
|
|
3456
|
-
|
|
3457
|
-
// ── state / publishing ─────────────────────────────────────────────────
|
|
3458
|
-
|
|
3459
|
-
/**
|
|
3460
|
-
* Snapshot for a channel URI, or null when the channel is not
|
|
3461
|
-
* subscribable right now.
|
|
3462
|
-
*
|
|
3463
|
-
* Root snapshots re-derive the catalog from the facade on every call
|
|
3464
|
-
* (registry reads reflect every registration so far; in-process reads
|
|
3465
|
-
* are cheap). Session/chat snapshots read the official-reducer stores.
|
|
3466
|
-
*/
|
|
3467
|
-
private async snapshotFor(uri: string): Promise<Snapshot | null> {
|
|
3468
|
-
const kind = channelKind(uri);
|
|
3469
|
-
if (kind === "unknown") return null;
|
|
3470
|
-
if (kind === "changeset") {
|
|
3471
|
-
if (!this.opts.changesets) return null;
|
|
3472
|
-
const parsed = parseChangesetChannel(uri);
|
|
3473
|
-
if (parsed === null) return null;
|
|
3474
|
-
// The owner is the session/chat channel (owner-aware).
|
|
3475
|
-
const rec = this.byChannel.get(parsed.ownerUri);
|
|
3476
|
-
if (rec === undefined) return null;
|
|
3477
|
-
const store = this.changesetStore(rec, uri);
|
|
3478
|
-
if (store === null) return null; // owner gone (disposed chat)
|
|
3479
|
-
// First subscribe (or a failed computation) triggers the computation;
|
|
3480
|
-
// subsequent subscribes return the last completed state.
|
|
3481
|
-
if (store.state.status === ChangesetStatus.Computing || store.state.status === ChangesetStatus.Error) {
|
|
3482
|
-
await this.refreshChangeset(rec, uri);
|
|
3483
|
-
}
|
|
3484
|
-
return { resource: uri, state: store.state, fromSeq: this.seq.seq };
|
|
3485
|
-
}
|
|
3486
|
-
if (kind === "terminal") {
|
|
3487
|
-
// The synthetic terminal's official-reducer
|
|
3488
|
-
// state; null once the record is torn down (the chat is gone).
|
|
3489
|
-
const t = this.terminals.get(uri);
|
|
3490
|
-
if (t === undefined) return null;
|
|
3491
|
-
return { resource: uri, state: t.store.state, fromSeq: this.seq.seq };
|
|
3492
|
-
}
|
|
3493
|
-
if (kind !== "root") {
|
|
3494
|
-
const rec = this.byChannel.get(uri);
|
|
3495
|
-
if (rec === undefined) return null;
|
|
3496
|
-
if (uri === rec.channel) {
|
|
3497
|
-
return { resource: uri, state: rec.sessionStore.state, fromSeq: this.seq.seq };
|
|
3498
|
-
}
|
|
3499
|
-
const chat = rec.chats.get(uri);
|
|
3500
|
-
if (chat !== undefined) {
|
|
3501
|
-
return { resource: uri, state: chat.chatStore.state, fromSeq: this.seq.seq };
|
|
3502
|
-
}
|
|
3503
|
-
return null;
|
|
3504
|
-
}
|
|
3505
|
-
const [providers, agents] = await Promise.all([
|
|
3506
|
-
this.opts.facade.listCatalog(),
|
|
3507
|
-
this.opts.facade.listAgents(),
|
|
3508
|
-
]);
|
|
3509
|
-
const catalog = mapCatalog(providers, agents, this.opts.defaultDirectory);
|
|
3510
|
-
if (!sameAgents(this.state.state.agents, catalog)) {
|
|
3511
|
-
this.state.apply({ type: ActionType.RootAgentsChanged, agents: catalog });
|
|
3512
|
-
}
|
|
3513
|
-
return { resource: ROOT_CHANNEL, state: this.state.state, fromSeq: this.seq.seq };
|
|
3514
|
-
}
|
|
3515
|
-
|
|
3516
|
-
/** The denormalized `SessionSummary` view of a record. */
|
|
3517
|
-
private sessionSummary(rec: SessionRecord): SessionSummary {
|
|
3518
|
-
const s = rec.sessionStore.state;
|
|
3519
|
-
// Authoritative chat order: default first, then insertion order
|
|
3520
|
-
// (the default chat is bound first).
|
|
3521
|
-
const chats = [...rec.chats.values()].map((c) => chatSummaryOf(c.chatStore.state));
|
|
3522
|
-
let modifiedAt = rec.modifiedAt;
|
|
3523
|
-
for (const c of rec.chats.values()) {
|
|
3524
|
-
if (c.chatStore.state.modifiedAt > modifiedAt) modifiedAt = c.chatStore.state.modifiedAt;
|
|
3525
|
-
}
|
|
3526
|
-
return buildSessionSummary({
|
|
3527
|
-
channel: rec.channel,
|
|
3528
|
-
provider: rec.provider,
|
|
3529
|
-
title: s.title,
|
|
3530
|
-
status: s.status,
|
|
3531
|
-
activity: s.activity,
|
|
3532
|
-
createdAt: rec.createdAt,
|
|
3533
|
-
modifiedAt,
|
|
3534
|
-
chats,
|
|
3535
|
-
defaultChat: rec.defaultChatURI,
|
|
3536
|
-
});
|
|
3537
|
-
}
|
|
3538
|
-
|
|
3539
|
-
/**
|
|
3540
|
-
* Assign a global seq, update state for accepted actions, retain for
|
|
3541
|
-
* replay. Session/chat actions apply to the per-session stores through
|
|
3542
|
-
* the official reducers; a changed chat summary is propagated to the
|
|
3543
|
-
* session store via `session/chatUpdated`, and any summary-level change
|
|
3544
|
-
* is announced on the root channel (notification).
|
|
3545
|
-
*/
|
|
3546
|
-
private publish(draft: {
|
|
3547
|
-
channel: string;
|
|
3548
|
-
action: StateAction;
|
|
3549
|
-
origin?: ActionOrigin;
|
|
3550
|
-
rejectionReason?: string;
|
|
3551
|
-
}): ActionEnvelope {
|
|
3552
|
-
const envelope = this.seq.publish(draft);
|
|
3553
|
-
if (draft.rejectionReason === undefined) {
|
|
3554
|
-
const kind = channelKind(draft.channel);
|
|
3555
|
-
if (kind === "root") {
|
|
3556
|
-
this.state.apply(draft.action as RootAction);
|
|
3557
|
-
} else if (kind === "changeset") {
|
|
3558
|
-
// Changeset stores are owner-keyed (session-kind on the record,
|
|
3559
|
-
// chat-kind on the chat). Non-creating: a publish
|
|
3560
|
-
// targets a store someone created (subscribe/refresh); a missing
|
|
3561
|
-
// owner means the changeset is already torn down.
|
|
3562
|
-
const parsed = parseChangesetChannel(draft.channel);
|
|
3563
|
-
const rec = parsed !== null ? this.byChannel.get(parsed.ownerUri) : undefined;
|
|
3564
|
-
const store = rec !== undefined ? this.changesetStoreOf(rec, draft.channel) : undefined;
|
|
3565
|
-
if (store !== undefined) store.apply(draft.action as ChangesetAction);
|
|
3566
|
-
} else if (kind === "terminal") {
|
|
3567
|
-
// Synthetic shell-command terminals.
|
|
3568
|
-
// Non-creating: a publish targets a record that exists (opened at
|
|
3569
|
-
// `tool.input.ended`); a missing record means the channel was
|
|
3570
|
-
// already torn down — the notification still goes out.
|
|
3571
|
-
const t = this.terminals.get(draft.channel);
|
|
3572
|
-
if (t !== undefined) t.store.apply(draft.action as TerminalAction);
|
|
3573
|
-
} else {
|
|
3574
|
-
// byChannel, not sessions.get(sessionIDOf(…)): the channel suffix
|
|
3575
|
-
// is not always the opencode session id (client-chosen suffixes).
|
|
3576
|
-
const rec = this.byChannel.get(draft.channel);
|
|
3577
|
-
if (rec !== undefined) {
|
|
3578
|
-
const before = this.sessionSummary(rec);
|
|
3579
|
-
if (kind === "session") {
|
|
3580
|
-
rec.sessionStore.apply(draft.action as SessionAction);
|
|
3581
|
-
} else {
|
|
3582
|
-
const chat = rec.chats.get(draft.channel);
|
|
3583
|
-
if (chat !== undefined) chat.chatStore.apply(draft.action as ChatAction);
|
|
3584
|
-
}
|
|
3585
|
-
if (kind === "chat") this.syncChatSummary(rec, draft.channel);
|
|
3586
|
-
const after = this.sessionSummary(rec);
|
|
3587
|
-
this.maybeNotifySummaryChanged(rec, before, after);
|
|
3588
|
-
}
|
|
3589
|
-
}
|
|
3590
|
-
}
|
|
3591
|
-
// Every published action — accepted and rejected alike — is an
|
|
3592
|
-
// `action` notification on its channel to the subscribers.
|
|
3593
|
-
this.notifyAction(envelope);
|
|
3594
|
-
return envelope;
|
|
3595
|
-
}
|
|
3596
|
-
|
|
3597
|
-
/**
|
|
3598
|
-
* Propagate a changed chat summary into the session store's chat catalog
|
|
3599
|
-
* (`session/chatUpdated`) — the session status itself is only
|
|
3600
|
-
* reducer-reachable for read/archive/input-needed bits, so the chat
|
|
3601
|
-
* summary is the activity source of truth.
|
|
3602
|
-
*/
|
|
3603
|
-
private syncChatSummary(rec: SessionRecord, chatURI: string): void {
|
|
3604
|
-
const chat = rec.chats.get(chatURI)?.chatStore.state;
|
|
3605
|
-
if (chat === undefined) return;
|
|
3606
|
-
const entry = rec.sessionStore.state.chats.find((c) => c.resource === chat.resource);
|
|
3607
|
-
if (entry === undefined) return;
|
|
3608
|
-
const next = chatSummaryOf(chat);
|
|
3609
|
-
const changes: Record<string, unknown> = {};
|
|
3610
|
-
let changed = false;
|
|
3611
|
-
for (const key of ["title", "status", "activity", "modifiedAt"] as const) {
|
|
3612
|
-
if (entry[key] !== next[key]) {
|
|
3613
|
-
changes[key] = next[key];
|
|
3614
|
-
changed = true;
|
|
3615
|
-
}
|
|
3616
|
-
}
|
|
3617
|
-
if (changed) {
|
|
3618
|
-
this.publish({
|
|
3619
|
-
channel: rec.channel,
|
|
3620
|
-
action: { type: ActionType.SessionChatUpdated, chat: chat.resource, changes: changes as Partial<ChatSummary> },
|
|
3621
|
-
});
|
|
3622
|
-
}
|
|
3623
|
-
}
|
|
3624
|
-
|
|
3625
|
-
/**
|
|
3626
|
-
* Announce summary-level changes on the root channel (`root/
|
|
3627
|
-
* sessionSummaryChanged` notification — ephemeral, not replayed).
|
|
3628
|
-
* Identity fields (resource/provider/createdAt) never change.
|
|
3629
|
-
*/
|
|
3630
|
-
private maybeNotifySummaryChanged(rec: SessionRecord, before: SessionSummary, after: SessionSummary): void {
|
|
3631
|
-
const changes: Record<string, unknown> = {};
|
|
3632
|
-
for (const key of ["title", "status", "activity", "modifiedAt", "chats", "defaultChat"] as const) {
|
|
3633
|
-
if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) {
|
|
3634
|
-
changes[key] = after[key];
|
|
3635
|
-
}
|
|
3636
|
-
}
|
|
3637
|
-
if (Object.keys(changes).length === 0) return;
|
|
3638
|
-
if (after.modifiedAt > rec.modifiedAt) rec.modifiedAt = after.modifiedAt;
|
|
3639
|
-
this.notifyRoot("root/sessionSummaryChanged", {
|
|
3640
|
-
channel: ROOT_CHANNEL,
|
|
3641
|
-
session: rec.channel,
|
|
3642
|
-
changes,
|
|
3643
|
-
});
|
|
3644
|
-
}
|
|
3645
|
-
|
|
3646
|
-
/** Send a root-channel notification frame to every root subscriber. */
|
|
3647
|
-
private notifyRoot(method: string, params: unknown): void {
|
|
3648
|
-
const frame = { jsonrpc: "2.0", method, params };
|
|
3649
|
-
for (const socketId of this.channels.socketsSubscribedTo(ROOT_CHANNEL)) {
|
|
3650
|
-
this.opts.send(socketId, frame);
|
|
3651
|
-
}
|
|
3652
|
-
}
|
|
3653
|
-
|
|
3654
|
-
/** Send an `action` notification to every socket subscribed to the channel. */
|
|
3655
|
-
private notifyAction(envelope: ActionEnvelope): void {
|
|
3656
|
-
const frame = { jsonrpc: "2.0", method: "action", params: envelope };
|
|
3657
|
-
for (const socketId of this.channels.socketsSubscribedTo(envelope.channel)) {
|
|
3658
|
-
this.opts.send(socketId, frame);
|
|
3659
|
-
}
|
|
3660
|
-
}
|
|
3661
|
-
|
|
3662
|
-
private sendError(socketId: number, id: unknown, code: number, message: string): void {
|
|
3663
|
-
this.sendFrame(socketId, { jsonrpc: "2.0", id: id ?? null, error: { code, message } });
|
|
3664
|
-
}
|
|
3665
|
-
}
|
|
3666
|
-
|
|
3667
|
-
function sameAgents(a: unknown, b: unknown): boolean {
|
|
3668
|
-
return JSON.stringify(a) === JSON.stringify(b);
|
|
3669
|
-
}
|
|
3670
|
-
|
|
3671
|
-
function errorMessage(e: unknown): string {
|
|
3672
|
-
return e instanceof Error ? e.message : String(e);
|
|
3673
|
-
}
|
|
3674
|
-
|
|
3675
|
-
/** Short, stable description of untrusted params for log lines. */
|
|
3676
|
-
function describeParams(params: unknown): string {
|
|
3677
|
-
if (!isRecord(params)) return String(typeof params);
|
|
3678
|
-
try {
|
|
3679
|
-
const raw = JSON.stringify(Object.keys(params));
|
|
3680
|
-
return raw.length > 120 ? raw.slice(0, 120) + "…" : raw;
|
|
3681
|
-
} catch {
|
|
3682
|
-
return "unserializable";
|
|
3683
|
-
}
|
|
3684
|
-
}
|
|
3685
|
-
|
|
3686
|
-
/** The first enabled model of a provider, as a FacadeModelRef. */
|
|
3687
|
-
function firstEnabledModelRef(models: readonly { providerID: string; modelID: string; enabled: boolean }[]): FacadeModelRef | undefined {
|
|
3688
|
-
const m = models.find((x) => x.enabled);
|
|
3689
|
-
return m !== undefined ? { providerID: m.providerID, modelID: m.modelID } : undefined;
|
|
3690
|
-
}
|
|
3691
|
-
|
|
3692
|
-
/** Normalize an untrusted `activeClient` payload (untrusted JSON-RPC). */
|
|
3693
|
-
function normalizeActiveClient(ac: Record<string, unknown>): SessionActiveClient {
|
|
3694
|
-
return {
|
|
3695
|
-
clientId: ac["clientId"] as string,
|
|
3696
|
-
tools: normalizeToolDefinitions(ac["tools"]),
|
|
3697
|
-
...(typeof ac["displayName"] === "string" ? { displayName: ac["displayName"] as string } : {}),
|
|
3698
|
-
};
|
|
3699
|
-
}
|
|
3700
|
-
|
|
3701
|
-
/**
|
|
3702
|
-
* Wire-validate a client-dispatched `toolCallComplete` result:
|
|
3703
|
-
* `success` is the one field the host depends on (it decides
|
|
3704
|
-
* the facade result + the Tool.Error path); the rest is stored
|
|
3705
|
-
* verbatim for the AHP state mirror.
|
|
3706
|
-
*/
|
|
3707
|
-
function normalizeToolCallResult(raw: unknown): ToolCallResult | null {
|
|
3708
|
-
if (typeof raw !== "object" || raw === null) return null;
|
|
3709
|
-
const r = raw as Record<string, unknown>;
|
|
3710
|
-
if (typeof r["success"] !== "boolean") return null;
|
|
3711
|
-
const pastTense = r["pastTenseMessage"];
|
|
3712
|
-
return {
|
|
3713
|
-
success: r["success"],
|
|
3714
|
-
pastTenseMessage:
|
|
3715
|
-
typeof pastTense === "string"
|
|
3716
|
-
? pastTense
|
|
3717
|
-
: (isRecord(pastTense) && typeof pastTense["markdown"] === "string"
|
|
3718
|
-
? (pastTense["markdown"] as string)
|
|
3719
|
-
: ""),
|
|
3720
|
-
...(Array.isArray(r["content"]) ? { content: r["content"] as ToolResultContent[] } : {}),
|
|
3721
|
-
...(isRecord(r["structuredContent"]) ? { structuredContent: r["structuredContent"] as Record<string, unknown> } : {}),
|
|
3722
|
-
...(isRecord(r["error"]) ? { error: r["error"] as { message: string; code?: string } } : {}),
|
|
3723
|
-
};
|
|
3724
|
-
}
|
|
3725
48
|
|
|
3726
|
-
|
|
3727
|
-
function stringOrMarkdownToText(v: StringOrMarkdown | undefined): string {
|
|
3728
|
-
if (v === undefined) return "";
|
|
3729
|
-
if (typeof v === "string") return v;
|
|
3730
|
-
return typeof v.markdown === "string" ? v.markdown : "";
|
|
3731
|
-
}
|
|
49
|
+
import { HostRpc } from "./host-rpc.js";
|
|
3732
50
|
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
* success:false → the `Tool.Error` message (the model sees the
|
|
3736
|
-
* failure); success → the text content blocks joined (non-text blocks
|
|
3737
|
-
* stay in the AHP state for the client's UI; the model gets the text +
|
|
3738
|
-
* the past-tense message).
|
|
3739
|
-
*/
|
|
3740
|
-
function clientResultToFacade(result: ToolCallResult): FacadeClientToolResult {
|
|
3741
|
-
if (!result.success) {
|
|
3742
|
-
return { ok: false, error: result.error?.message ?? "the client reported a tool failure" };
|
|
3743
|
-
}
|
|
3744
|
-
const texts: string[] = [];
|
|
3745
|
-
for (const c of result.content ?? []) {
|
|
3746
|
-
// The content came from the wire (untrusted) — guard the shape.
|
|
3747
|
-
if (c.type === ToolResultContentType.Text && typeof c.text === "string") texts.push(c.text);
|
|
3748
|
-
}
|
|
3749
|
-
const content = texts.join("\n\n");
|
|
3750
|
-
return {
|
|
3751
|
-
ok: true,
|
|
3752
|
-
pastTenseMessage: stringOrMarkdownToText(result.pastTenseMessage),
|
|
3753
|
-
...(content.length > 0 ? { content } : {}),
|
|
3754
|
-
...(result.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}),
|
|
3755
|
-
};
|
|
3756
|
-
}
|
|
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";
|
|
3757
53
|
|
|
3758
|
-
|
|
3759
|
-
* Map opencode tool result content blocks to AHP `ToolResultContent`
|
|
3760
|
-
* (only text blocks are representable; file/patch text is
|
|
3761
|
-
* carried as text).
|
|
3762
|
-
*/
|
|
3763
|
-
function mapToolResultContent(content: readonly { type: string; text?: string }[]): ToolResultContent[] {
|
|
3764
|
-
const out: ToolResultContent[] = [];
|
|
3765
|
-
for (const c of content) {
|
|
3766
|
-
if (c.type === "text" || c.type === "file" || c.type === "patch") {
|
|
3767
|
-
out.push({ type: ToolResultContentType.Text, text: c.text ?? "" });
|
|
3768
|
-
}
|
|
3769
|
-
}
|
|
3770
|
-
return out;
|
|
3771
|
-
}
|
|
3772
|
-
|
|
3773
|
-
/**
|
|
3774
|
-
* True when `child` is `parent` itself or strictly inside it (both resolved
|
|
3775
|
-
* first, so relative segments and `..` cannot escape the comparison). Used
|
|
3776
|
-
* to confine turn-snapshot paths and `resourceRead`/`invokeChangesetOperation`
|
|
3777
|
-
* targets to the location directory.
|
|
3778
|
-
*/
|
|
3779
|
-
function isPathInside(child: string, parent: string): boolean {
|
|
3780
|
-
const a = resolvePath(child);
|
|
3781
|
-
const b = resolvePath(parent);
|
|
3782
|
-
return a === b || a.startsWith(b + "/");
|
|
3783
|
-
}
|
|
54
|
+
export class Host extends HostRpc {}
|