opencode-ahp 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,342 @@
1
+ /**
2
+ * The host core — first link of the section-class chain (host.ts composes the rest): the shared state (socket/client/session/chat/terminal maps, sequencer, root store, channel registry), the constructor, and the publish/notify plumbing every section builds on. Section classes may only call members declared at or below them in the chain.
3
+ */
4
+
5
+ import { ActionType, ChangesetStatus, ActionEnvelope, ActionOrigin, ChatAction, ChatSummary, ChangesetAction, RootAction, SessionAction, SessionSummary, StateAction, TerminalAction } from "@microsoft/agent-host-protocol";
6
+ import { buildSessionSummary, chatSummaryOf, directoryUri, sessionSummaryStatus, type FacadeSession } from "./bridge.js";
7
+ import { ChannelRegistry, ChannelKind, ROOT_CHANNEL, channelKind, parseChangesetChannel, sessionIDOf } from "./channels.js";
8
+ import { Sequencer } from "./seq.js";
9
+ import { createChangesetStateStore, createRootStateStore, ChangesetStateStore, RootStateStore } from "./state.js";
10
+ import { SocketState, ClientRecord, ChatRuntime, SessionRecord, TerminalRecord, HostOptions } from "./host-types.js";
11
+
12
+ export class HostBase {
13
+ protected readonly seq: Sequencer;
14
+
15
+ protected readonly channels = new ChannelRegistry();
16
+
17
+ protected readonly state: RootStateStore;
18
+
19
+ protected readonly sockets = new Map<number, SocketState>();
20
+
21
+ protected readonly clients = new Map<string, ClientRecord>();
22
+
23
+ /**
24
+ * Live sessions, keyed by opencode session id (the event-pump join key).
25
+ * `byChannel` maps a session/chat channel URI to the same record for the
26
+ * client-facing lookups — the channel suffix is not always the opencode id
27
+ * (client-chosen suffixes), so the two keyings differ.
28
+ */
29
+ protected readonly sessions = new Map<string, SessionRecord>();
30
+
31
+ protected readonly byChannel = new Map<string, SessionRecord>();
32
+
33
+ /**
34
+ * opencode session id → the (record, chat) the id backs. The event
35
+ * pump's join key — every chat has its own opencode session, and the
36
+ * pump must land on the owning chat, not just the record.
37
+ */
38
+ protected readonly byOpencode = new Map<string, { rec: SessionRecord; chat: ChatRuntime }>();
39
+
40
+ /**
41
+ * Durability: marked peer backends whose owner
42
+ * AHP session is not registered yet, keyed by the marker's `owner`
43
+ * (opencode session id). A peer can be listed before its owner in the
44
+ * same synchronous `listSessions` pass, and after a restart the owner
45
+ * record does not exist until it is listed (there is no boot-time
46
+ * event replay). Drained when the owner registers; an entry whose
47
+ * owner is gone from opencode falls back to standalone registration
48
+ * after the grace window.
49
+ */
50
+ protected readonly pendingChatBindings = new Map<string, { fs: FacadeSession; chatURI: string }[]>();
51
+
52
+ /**
53
+ * Terminal channels keyed by URI: synthetic `ahp-terminal:/<toolCallId>`
54
+ * records (created at the `shell`-tool call's `tool.input.ended`,
55
+ * retained until the owning chat/record is removed) and pty terminal
56
+ * records (client-chosen URIs from `createTerminal`, retained until the
57
+ * client disposes them or the location tears down).
58
+ */
59
+ protected readonly terminals = new Map<string, TerminalRecord>();
60
+
61
+ protected readonly opts: HostOptions;
62
+
63
+ protected readonly log: (message: string) => void;
64
+
65
+ protected turnCounter = 0;
66
+
67
+ protected pumpController: AbortController | null = null;
68
+
69
+ constructor(opts: HostOptions) {
70
+ this.opts = opts;
71
+ this.log = opts.log ?? (() => {});
72
+ this.seq = new Sequencer(opts.replayWindow);
73
+ this.state = createRootStateStore({ agents: [] });
74
+ }
75
+
76
+ protected sendFrame(socketId: number, message: unknown): void {
77
+ this.opts.send(socketId, message);
78
+ }
79
+
80
+ protected sendError(socketId: number, id: unknown, code: number, message: string): void {
81
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: id ?? null, error: { code, message } });
82
+ }
83
+
84
+ /**
85
+ * Channel kind with live-terminal awareness: client-chosen pty terminal
86
+ * URIs (from `createTerminal`) classify "unknown" by prefix alone —
87
+ * they classify "terminal" while their record is live.
88
+ */
89
+ protected kindOf(uri: string): ChannelKind {
90
+ const kind = channelKind(uri);
91
+ if (kind !== "unknown") return kind;
92
+ return this.terminals.has(uri) ? "terminal" : kind;
93
+ }
94
+
95
+ /**
96
+ * Assign a global seq, update state for accepted actions, retain for
97
+ * replay. Session/chat actions apply to the per-session stores through
98
+ * the official reducers; a changed chat summary is propagated to the
99
+ * session store via `session/chatUpdated`, and any summary-level change
100
+ * is announced on the root channel (notification).
101
+ */
102
+ protected publish(draft: {
103
+ channel: string;
104
+ action: StateAction;
105
+ origin?: ActionOrigin;
106
+ rejectionReason?: string;
107
+ }): ActionEnvelope {
108
+ const envelope = this.seq.publish(draft);
109
+ if (draft.rejectionReason === undefined) {
110
+ const kind = this.kindOf(draft.channel);
111
+ if (kind === "root") {
112
+ this.state.apply(draft.action as RootAction);
113
+ } else if (kind === "changeset") {
114
+ // Changeset stores are owner-keyed (session-kind on the record,
115
+ // chat-kind on the chat). Non-creating: a publish
116
+ // targets a store someone created (subscribe/refresh); a missing
117
+ // owner means the changeset is already torn down.
118
+ const parsed = parseChangesetChannel(draft.channel);
119
+ const rec = parsed !== null ? this.byChannel.get(parsed.ownerUri) : undefined;
120
+ const store = rec !== undefined ? this.changesetStoreOf(rec, draft.channel) : undefined;
121
+ if (store !== undefined) store.apply(draft.action as ChangesetAction);
122
+ } else if (kind === "terminal") {
123
+ // Synthetic shell-command terminals.
124
+ // Non-creating: a publish targets a record that exists (opened at
125
+ // `tool.input.ended`); a missing record means the channel was
126
+ // already torn down — the notification still goes out.
127
+ const t = this.terminals.get(draft.channel);
128
+ if (t !== undefined) t.store.apply(draft.action as TerminalAction);
129
+ } else {
130
+ // byChannel, not sessions.get(sessionIDOf(…)): the channel suffix
131
+ // is not always the opencode session id (client-chosen suffixes).
132
+ const rec = this.byChannel.get(draft.channel);
133
+ if (rec !== undefined) {
134
+ const before = this.sessionSummary(rec);
135
+ if (kind === "session") {
136
+ rec.sessionStore.apply(draft.action as SessionAction);
137
+ } else {
138
+ const chat = rec.chats.get(draft.channel);
139
+ if (chat !== undefined) chat.chatStore.apply(draft.action as ChatAction);
140
+ }
141
+ if (kind === "chat") this.syncChatSummary(rec, draft.channel);
142
+ const after = this.sessionSummary(rec);
143
+ this.maybeNotifySummaryChanged(rec, before, after);
144
+ }
145
+ }
146
+ }
147
+ // Every published action — accepted and rejected alike — is an
148
+ // `action` notification on its channel to the subscribers.
149
+ this.notifyAction(envelope);
150
+ return envelope;
151
+ }
152
+
153
+ /**
154
+ * Propagate a changed chat summary into the session store's chat catalog
155
+ * (`session/chatUpdated`) — the session status itself is only
156
+ * reducer-reachable for read/archive/input-needed bits, so the chat
157
+ * summary is the activity source of truth (the summary-level
158
+ * `SessionSummary.status` is aggregated from the chats by
159
+ * `sessionSummaryStatus`, never read back from the session store).
160
+ */
161
+ private syncChatSummary(rec: SessionRecord, chatURI: string): void {
162
+ const chat = rec.chats.get(chatURI)?.chatStore.state;
163
+ if (chat === undefined) return;
164
+ const entry = rec.sessionStore.state.chats.find((c) => c.resource === chat.resource);
165
+ if (entry === undefined) return;
166
+ const next = chatSummaryOf(chat);
167
+ const changes: Record<string, unknown> = {};
168
+ let changed = false;
169
+ for (const key of ["title", "status", "activity", "modifiedAt"] as const) {
170
+ if (entry[key] !== next[key]) {
171
+ changes[key] = next[key];
172
+ changed = true;
173
+ }
174
+ }
175
+ if (changed) {
176
+ this.publish({
177
+ channel: rec.channel,
178
+ action: { type: ActionType.SessionChatUpdated, chat: chat.resource, changes: changes as Partial<ChatSummary> },
179
+ });
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Announce summary-level changes on the root channel (`root/
185
+ * sessionSummaryChanged` notification — ephemeral, not replayed).
186
+ * Identity fields (resource/provider/createdAt) never change.
187
+ */
188
+ private maybeNotifySummaryChanged(rec: SessionRecord, before: SessionSummary, after: SessionSummary): void {
189
+ const changes: Record<string, unknown> = {};
190
+ for (const key of ["title", "status", "activity", "modifiedAt", "chats", "defaultChat"] as const) {
191
+ if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) {
192
+ changes[key] = after[key];
193
+ }
194
+ }
195
+ if (Object.keys(changes).length === 0) return;
196
+ if (after.modifiedAt > rec.modifiedAt) rec.modifiedAt = after.modifiedAt;
197
+ this.notifyRoot("root/sessionSummaryChanged", {
198
+ channel: ROOT_CHANNEL,
199
+ session: rec.channel,
200
+ changes,
201
+ });
202
+ }
203
+
204
+ /**
205
+ * The AHP `workingDirectories` every session of this host carries
206
+ * (`SessionMetadata.workingDirectories`): the single location directory —
207
+ * the session's agent has tool access exactly there. VS Code groups its
208
+ * session list by this workspace (the folder name, host-suffixed for
209
+ * remote hosts); sessions without it fall into the "Unknown" bucket.
210
+ * `undefined` when the location directory is unknown.
211
+ */
212
+ protected workingDirectories(): string[] | undefined {
213
+ return this.opts.defaultDirectory !== undefined ? [directoryUri(this.opts.defaultDirectory)] : undefined;
214
+ }
215
+
216
+ /** The denormalized `SessionSummary` view of a record. */
217
+ protected sessionSummary(rec: SessionRecord): SessionSummary {
218
+ const s = rec.sessionStore.state;
219
+ // Authoritative chat order: default first, then insertion order
220
+ // (the default chat is bound first).
221
+ const chats = [...rec.chats.values()].map((c) => chatSummaryOf(c.chatStore.state));
222
+ let modifiedAt = rec.modifiedAt;
223
+ for (const c of rec.chats.values()) {
224
+ if (c.chatStore.state.modifiedAt > modifiedAt) modifiedAt = c.chatStore.state.modifiedAt;
225
+ }
226
+ return buildSessionSummary({
227
+ channel: rec.channel,
228
+ provider: rec.provider,
229
+ title: s.title,
230
+ // Activity bits aggregated from the chat summaries (AHP rule): the
231
+ // session store's own status cannot source them — its reducer only
232
+ // reaches them through the input-queue path, which leaves
233
+ // `InProgress` set after an input-needed round trip when the turn
234
+ // ends. The `IsRead`/`IsArchived` flags stay session-scoped.
235
+ status: sessionSummaryStatus(s.status, chats, rec.defaultChatURI),
236
+ activity: s.activity,
237
+ createdAt: rec.createdAt,
238
+ modifiedAt,
239
+ chats,
240
+ defaultChat: rec.defaultChatURI,
241
+ workingDirectories: this.workingDirectories(),
242
+ });
243
+ }
244
+
245
+ /** Send a root-channel notification frame to every root subscriber. */
246
+ protected notifyRoot(method: string, params: unknown): void {
247
+ const frame = { jsonrpc: "2.0", method, params };
248
+ for (const socketId of this.channels.socketsSubscribedTo(ROOT_CHANNEL)) {
249
+ this.opts.send(socketId, frame);
250
+ }
251
+ }
252
+
253
+ /** Send an `action` notification to every socket subscribed to the channel. */
254
+ private notifyAction(envelope: ActionEnvelope): void {
255
+ const frame = { jsonrpc: "2.0", method: "action", params: envelope };
256
+ for (const socketId of this.channels.socketsSubscribedTo(envelope.channel)) {
257
+ this.opts.send(socketId, frame);
258
+ }
259
+ }
260
+
261
+ /** The socket currently bound to a clientId (rejection delivery target). */
262
+ protected socketIdForClient(clientId: string): number | undefined {
263
+ for (const [socketId, socket] of this.sockets) {
264
+ if (socket.clientId === clientId) return socketId;
265
+ }
266
+ return undefined;
267
+ }
268
+
269
+ /**
270
+ * Publish an accepted echo (or a rejection) on the action stream. A
271
+ * rejection must reach the dispatching socket even when it is not
272
+ * subscribed to the channel (write-ahead dispatch: the client applied
273
+ * the action optimistically and needs the rejection to roll it back).
274
+ */
275
+ protected echo(
276
+ channel: string,
277
+ action: StateAction,
278
+ origin: ActionOrigin | undefined,
279
+ rejectionReason?: string,
280
+ ): void {
281
+ const envelope = this.publish({
282
+ channel,
283
+ action,
284
+ origin,
285
+ ...(rejectionReason !== undefined ? { rejectionReason } : {}),
286
+ });
287
+ if (rejectionReason !== undefined && origin !== undefined) {
288
+ const socketId = this.socketIdForClient(origin.clientId);
289
+ if (socketId !== undefined && !this.channels.socketsSubscribedTo(channel).includes(socketId)) {
290
+ this.opts.send(socketId, { jsonrpc: "2.0", method: "action", params: envelope });
291
+ }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * The changeset store's owner: session-kind changesets
297
+ * live on the record (the session channel owns them); uncommitted/turn
298
+ * changesets live on the owning chat. Null when the owner is gone
299
+ * (a disposed chat's changesets are un-subscribable).
300
+ */
301
+ private changesetOwner(rec: SessionRecord, uri: string): { kind: "session" } | { kind: "chat"; chat: ChatRuntime } | null {
302
+ const parsed = parseChangesetChannel(uri);
303
+ if (parsed === null) return null;
304
+ if (parsed.kind === "session") return { kind: "session" };
305
+ const chat = rec.chats.get(parsed.ownerUri);
306
+ return chat === undefined ? null : { kind: "chat", chat };
307
+ }
308
+
309
+ /**
310
+ * Get-or-create the changeset store for a URI (fresh stores start
311
+ * computing). Owner-aware — see `changesetOwner`; null when the owner
312
+ * is gone.
313
+ */
314
+ protected changesetStore(rec: SessionRecord, uri: string): ChangesetStateStore | null {
315
+ const owner = this.changesetOwner(rec, uri);
316
+ if (owner === null) return null;
317
+ const map = owner.kind === "chat" ? owner.chat.changesets : rec.sessionChangesets;
318
+ let store = map.get(uri);
319
+ if (store === undefined) {
320
+ store = createChangesetStateStore({ status: ChangesetStatus.Computing, files: [] });
321
+ map.set(uri, store);
322
+ }
323
+ return store;
324
+ }
325
+
326
+ /** The live store for a URI, or undefined when it has never been created. */
327
+ protected changesetStoreOf(rec: SessionRecord, uri: string): ChangesetStateStore | undefined {
328
+ const owner = this.changesetOwner(rec, uri);
329
+ if (owner === null) return undefined;
330
+ const map = owner.kind === "chat" ? owner.chat.changesets : rec.sessionChangesets;
331
+ return map.get(uri);
332
+ }
333
+
334
+ /** The store's current per-file review flags, keyed by file id. */
335
+ protected reviewedById(store: ChangesetStateStore): Map<string, boolean> {
336
+ const out = new Map<string, boolean>();
337
+ for (const f of store.state.files) {
338
+ if (typeof f.reviewed === "boolean") out.set(f.id, f.reviewed);
339
+ }
340
+ return out;
341
+ }
342
+ }