opencode-ahp 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/channels.ts CHANGED
@@ -1,20 +1,19 @@
1
1
  /**
2
- * AHP channel registry (plan §6.1 channels.ts): URI parsing/formatting,
3
- * per-socket subscription bookkeeping, and the set of live opencode
4
- * sessions. Pure in-memory — no runtime dependencies.
2
+ * AHP channel registry: URI parsing/formatting, per-socket subscription
3
+ * bookkeeping, and the sets of live opencode sessions and live terminal
4
+ * channels. Pure in-memory — no runtime dependencies.
5
5
  *
6
- * Phase 0 only the root channel is live; session/chat URI handling and
7
- * the session registry land with Phase 1 (session support). Phase 2 adds
8
- * the changeset channel kind (`<owner>/changeset/{uncommitted|session|
9
- * turn/<turnId>}` — plan §11).
6
+ * Channel kinds: root, session, chat, changeset
7
+ * (`<owner>/changeset/{uncommitted|session|turn/<turnId>}`), and terminal.
10
8
  */
11
9
 
12
10
  export const ROOT_CHANNEL = "ahp-root://";
13
11
  const SESSION_PREFIX = "ahp-session:/";
14
12
  const CHAT_PREFIX = "ahp-chat:/";
15
13
  const CHANGASET_MARKER = "/changeset/";
14
+ const TERMINAL_PREFIX = "ahp-terminal:/";
16
15
 
17
- export type ChannelKind = "root" | "session" | "chat" | "changeset" | "unknown";
16
+ export type ChannelKind = "root" | "session" | "chat" | "changeset" | "terminal" | "unknown";
18
17
 
19
18
  export function channelKind(uri: string): ChannelKind {
20
19
  if (uri === ROOT_CHANNEL) return "root";
@@ -22,27 +21,41 @@ export function channelKind(uri: string): ChannelKind {
22
21
  // Checked before the owner prefixes so `<sessionURI>/changeset/session`
23
22
  // is not misread as a session channel whose suffix contains the marker
24
23
  // (createSession rejects such suffixes, so no live session channel can
25
- // contain the marker — plan §14).
24
+ // contain the marker).
26
25
  if (uri.lastIndexOf(CHANGASET_MARKER) > 0) return "changeset";
27
26
  if (uri.startsWith(SESSION_PREFIX) && uri.length > SESSION_PREFIX.length) return "session";
28
27
  if (uri.startsWith(CHAT_PREFIX) && uri.length > CHAT_PREFIX.length) return "chat";
28
+ // Synthetic shell-command terminals.
29
+ if (uri.startsWith(TERMINAL_PREFIX) && uri.length > TERMINAL_PREFIX.length) return "terminal";
29
30
  return "unknown";
30
31
  }
31
32
 
32
- /**
33
- * Channel URI of a session. opencode has one chat per session (plan §3.2
34
- * gap, same as pi-ahp / ahp-acp-gateway), and the session's default chat
35
- * reuses the session id.
36
- */
33
+ /** Channel URI of a session. */
37
34
  export function sessionChannelURI(sessionID: string): string {
38
35
  return SESSION_PREFIX + sessionID;
39
36
  }
40
37
 
41
- /** Channel URI of a session's (single) default chat. */
38
+ /**
39
+ * Channel URI of a session's default chat. The default chat reuses the
40
+ * session's opencode id as its suffix (the single-chat zero-wire-change
41
+ * mapping); peer chats created via `createChat` carry client-chosen
42
+ * suffixes instead.
43
+ */
42
44
  export function chatChannelURI(sessionID: string): string {
43
45
  return CHAT_PREFIX + sessionID;
44
46
  }
45
47
 
48
+ /**
49
+ * Channel URI of a synthetic shell-command terminal. The suffix is the
50
+ * opencode tool call id —
51
+ * globally unique per tool invocation, so the URI is unambiguous and the
52
+ * terminal correlates 1:1 with the `chat/toolCall*` actions for the same
53
+ * call.
54
+ */
55
+ export function terminalChannelURI(toolCallId: string): string {
56
+ return TERMINAL_PREFIX + toolCallId;
57
+ }
58
+
46
59
  /** The session id behind a session/chat channel URI, or null. */
47
60
  export function sessionIDOf(uri: string): string | null {
48
61
  const kind = channelKind(uri);
@@ -52,7 +65,7 @@ export function sessionIDOf(uri: string): string | null {
52
65
  }
53
66
 
54
67
  /**
55
- * The three changeset kinds this host advertises (plan §11 Phase 2):
68
+ * The three changeset kinds this host advertises:
56
69
  * - `uncommitted`: working tree vs HEAD (owner: the chat channel);
57
70
  * - `session`: session-wide changes, same approximation (owner: the
58
71
  * session channel — the protocol's "session" changeKind);
@@ -97,48 +110,63 @@ export function parseChangesetChannel(uri: string): ParsedChangesetChannel | nul
97
110
  return null;
98
111
  }
99
112
 
100
- /** Changeset URI of a session's uncommitted (working-tree) changes. */
101
- export function uncommittedChangesetURI(sessionID: string): string {
102
- return `${chatChannelURI(sessionID)}/changeset/uncommitted`;
113
+ /**
114
+ * Changeset URI of one chat's uncommitted (working-tree) changes. The
115
+ * owner is the chat channel itself (multi-chat: every chat has its own
116
+ * uncommitted changeset).
117
+ */
118
+ export function uncommittedChangesetURI(chatChannel: string): string {
119
+ return `${chatChannel}/changeset/uncommitted`;
103
120
  }
104
121
 
105
- /** Changeset URI of a session's session-wide changes. */
106
- export function sessionChangesetURI(sessionID: string): string {
107
- return `${sessionChannelURI(sessionID)}/changeset/session`;
122
+ /** Changeset URI of a session's session-wide changes (owner: the session channel). */
123
+ export function sessionChangesetURI(sessionChannel: string): string {
124
+ return `${sessionChannel}/changeset/session`;
108
125
  }
109
126
 
110
- /** Changeset URI of one turn's captured file changes. */
111
- export function turnChangesetURI(sessionID: string, turnId: string): string {
112
- return `${chatChannelURI(sessionID)}/changeset/turn/${turnId}`;
127
+ /** Changeset URI of one turn's captured file changes (owner: the chat channel). */
128
+ export function turnChangesetURI(chatChannel: string, turnId: string): string {
129
+ return `${chatChannel}/changeset/turn/${turnId}`;
113
130
  }
114
131
 
115
132
  export interface SubscribeOutcome {
116
133
  ok: boolean;
117
- reason?: "unknown-uri" | "no-such-session";
134
+ reason?: "unknown-uri" | "no-such-session" | "no-such-terminal";
118
135
  }
119
136
 
120
137
  /**
121
138
  * Subscription bookkeeping keyed by transport socket id, plus the set of
122
- * live session ids (Phase 1).
139
+ * live session ids and the set of live terminal channel URIs (the host
140
+ * adds/removes them as terminals are opened and torn down — synthetic
141
+ * `ahp-terminal:` channels AND client-chosen pty terminal channels from
142
+ * `createTerminal`, whose URIs classify "unknown" by prefix alone).
123
143
  */
124
144
  export class ChannelRegistry {
125
145
  private readonly subs = new Map<number, Set<string>>();
126
146
  private readonly sessions = new Set<string>();
147
+ private readonly terminals = new Set<string>();
127
148
 
128
- /** Subscribe a socket to a channel; fails for unknown URIs or dead sessions. */
149
+ /** Subscribe a socket to a channel; fails for unknown URIs, dead sessions, or gone terminals. */
129
150
  subscribe(socketId: number, uri: string): SubscribeOutcome {
130
151
  const kind = channelKind(uri);
131
- if (kind === "unknown") return { ok: false, reason: "unknown-uri" };
132
- if (kind !== "root") {
152
+ if (kind === "unknown") {
153
+ // A client-chosen terminal URI (a live pty terminal) classifies
154
+ // "unknown" by prefix; it is subscribable while the host keeps it
155
+ // in the live-terminal set (in step with the record map).
156
+ if (!this.terminals.has(uri)) return { ok: false, reason: "unknown-uri" };
157
+ } else if (kind !== "root") {
133
158
  let id: string | null;
134
159
  if (kind === "changeset") {
135
160
  const parsed = parseChangesetChannel(uri);
136
161
  if (parsed === null) return { ok: false, reason: "unknown-uri" };
137
162
  id = parsed.sessionID;
163
+ } else if (kind === "terminal") {
164
+ if (!this.terminals.has(uri)) return { ok: false, reason: "no-such-terminal" };
165
+ id = null;
138
166
  } else {
139
167
  id = sessionIDOf(uri);
140
168
  }
141
- if (id === null || !this.sessions.has(id)) return { ok: false, reason: "no-such-session" };
169
+ if (id !== null && !this.sessions.has(id)) return { ok: false, reason: "no-such-session" };
142
170
  }
143
171
  let set = this.subs.get(socketId);
144
172
  if (!set) {
@@ -170,7 +198,7 @@ export class ChannelRegistry {
170
198
  this.subs.delete(socketId);
171
199
  }
172
200
 
173
- // ── live sessions (Phase 1: session/chat channels) ────────────────────
201
+ // ── live sessions (session/chat channels) ─────────────────────────────
174
202
 
175
203
  addSession(sessionID: string): void {
176
204
  this.sessions.add(sessionID);
@@ -183,4 +211,18 @@ export class ChannelRegistry {
183
211
  hasSession(sessionID: string): boolean {
184
212
  return this.sessions.has(sessionID);
185
213
  }
214
+
215
+ // ── live terminals (synthetic channels + client-chosen pty channels) ──
216
+
217
+ addTerminal(uri: string): void {
218
+ this.terminals.add(uri);
219
+ }
220
+
221
+ removeTerminal(uri: string): void {
222
+ this.terminals.delete(uri);
223
+ }
224
+
225
+ hasTerminal(uri: string): boolean {
226
+ return this.terminals.has(uri);
227
+ }
186
228
  }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Client-provided tools: the pure helpers the host uses for the
3
+ * client-tool surface — wire validation
4
+ * of AHP `ToolDefinition`s, the cross-session definition union the model
5
+ * sees (first-registered wins per name), and the per-session provider
6
+ * lookup used to attribute the tool-call contributor and route execution.
7
+ *
8
+ * Everything here is a pure function over wire-shaped data: no sockets, no
9
+ * opencode, no timers (house pattern — see the other pure modules).
10
+ */
11
+ import type { ToolDefinition } from "@microsoft/agent-host-protocol";
12
+
13
+ /**
14
+ * The per-invocation tracking record the host keeps for a client-executed
15
+ * tool call (keyed by the opencode tool-call id, which the client sees as
16
+ * `toolCallId` on the chat channel).
17
+ *
18
+ * Lifecycle: created at `tool.input.started` (the contributor is known —
19
+ * the session's active client providing the tool), the `result` is set
20
+ * when the execution settles (the client's `toolCallComplete`, the
21
+ * result-confirmation reply, or a disconnect eviction), and the record is
22
+ * removed at the opencode-side terminal (`tool.success`/`tool.failed`),
23
+ * which always follows the settlement (the settlement is what unblocks
24
+ * the opencode tool's `execute`).
25
+ */
26
+ export interface ClientToolInvocation {
27
+ /** The active client that provides the tool (the contributor's clientId). */
28
+ clientId: string;
29
+ /** The AHP turn the call belongs to. */
30
+ turnId: string;
31
+ /**
32
+ * The client's `toolCallComplete` result, held while a
33
+ * `requiresResultConfirmation` awaits `toolCallResultConfirmed`.
34
+ */
35
+ pendingResult?: unknown;
36
+ /** The settled execution result (undefined until settled). */
37
+ result?: { ok: true; pastTenseMessage: string; content?: string; structuredContent?: Record<string, unknown> } | { ok: false; error: string };
38
+ /** The opencode-side waiter, or null once it was settled. */
39
+ waiter?: ((result: NonNullable<ClientToolInvocation["result"]>) => void) | null;
40
+ }
41
+
42
+ /**
43
+ * Wire-validate an `activeClient.tools` array: keep the entries that are
44
+ * real `ToolDefinition`s (a non-empty `name` string), drop the rest. The
45
+ * AHP contract makes every other field optional, so no deeper validation
46
+ * is needed — the opencode side only reads `name`/`description`/
47
+ * `inputSchema`, and the AHP state mirror stores the rest verbatim.
48
+ */
49
+ export function normalizeToolDefinitions(raw: unknown): ToolDefinition[] {
50
+ if (!Array.isArray(raw)) return [];
51
+ const out: ToolDefinition[] = [];
52
+ for (const item of raw) {
53
+ if (typeof item !== "object" || item === null) continue;
54
+ const name = (item as Record<string, unknown>)["name"];
55
+ if (typeof name !== "string" || name.length === 0) continue;
56
+ out.push(item as ToolDefinition);
57
+ }
58
+ return out;
59
+ }
60
+
61
+ /**
62
+ * The cross-session tool union the model sees: first-registered wins per
63
+ * name (iteration order = the caller's session order, which the host
64
+ * fixes to the live-session insertion order — deterministic per host
65
+ * lifetime).
66
+ */
67
+ export function toolUnion(clients: ReadonlyArray<{ tools: readonly ToolDefinition[] }>): ToolDefinition[] {
68
+ const seen = new Map<string, ToolDefinition>();
69
+ for (const client of clients) {
70
+ for (const tool of client.tools ?? []) {
71
+ if (typeof tool.name !== "string" || tool.name.length === 0) continue;
72
+ if (!seen.has(tool.name)) seen.set(tool.name, tool);
73
+ }
74
+ }
75
+ return [...seen.values()];
76
+ }
77
+
78
+ /** opencode's `normalizedName` (core `tool/runtime.ts`) — the tool id. */
79
+ export function normalizedName(name: string): string {
80
+ return name.replace(/[^a-zA-Z0-9_-]/g, "_");
81
+ }
82
+
83
+ /**
84
+ * The active client providing `toolName` for a session (the contributor's
85
+ * clientId), or null. Matches on the raw name or on the opencode-
86
+ * normalized name (a tool named "my tool" registers under `my_tool`, so
87
+ * the pump's event name and the wire name can differ only by that
88
+ * sanitization).
89
+ */
90
+ export function findProvider(
91
+ clients: ReadonlyArray<{ clientId: string; tools: readonly ToolDefinition[] }>,
92
+ toolName: string,
93
+ ): string | null {
94
+ if (typeof toolName !== "string" || toolName.length === 0) return null;
95
+ const needle = normalizedName(toolName);
96
+ for (const client of clients) {
97
+ for (const tool of client.tools ?? []) {
98
+ if (tool.name === toolName || normalizedName(tool.name) === needle) return client.clientId;
99
+ }
100
+ }
101
+ return null;
102
+ }
103
+
104
+ /**
105
+ * The input JSON Schema for an opencode tool registration: the client's
106
+ * `inputSchema` verbatim when present (it is a JSON Schema — opencode's
107
+ * `inputJsonSchema` passes raw schemas through untouched), otherwise the
108
+ * lenient "any object" schema.
109
+ */
110
+ export function inputSchemaFor(tool: ToolDefinition): Record<string, unknown> {
111
+ const s = tool.inputSchema;
112
+ if (
113
+ typeof s === "object" &&
114
+ s !== null &&
115
+ (s as Record<string, unknown>)["type"] === "object"
116
+ ) {
117
+ return s as Record<string, unknown>;
118
+ }
119
+ return { type: "object" };
120
+ }
121
+
122
+ /** The description an opencode tool registration carries for a client tool. */
123
+ export function descriptionFor(tool: ToolDefinition): string {
124
+ if (typeof tool.description === "string" && tool.description.length > 0) return tool.description;
125
+ if (typeof tool.title === "string" && tool.title.length > 0) return tool.title;
126
+ return tool.name;
127
+ }
package/src/handshake.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  /**
2
- * AHP 1.0.0 handshake (plan §6.1 handshake.ts): the `initialize` command
3
- * — semver capability negotiation via the official package's
4
- * `negotiateProtocolVersion`.
2
+ * AHP 1.0.0 handshake: the `initialize` command — semver capability
3
+ * negotiation via the official package's `negotiateProtocolVersion`.
5
4
  *
6
5
  * Version semantics (AHP versioning spec): the server picks the highest
7
6
  * client-offered version inside its supported caret baselines and echoes
@@ -0,0 +1,335 @@
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, 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.
158
+ */
159
+ private syncChatSummary(rec: SessionRecord, chatURI: string): void {
160
+ const chat = rec.chats.get(chatURI)?.chatStore.state;
161
+ if (chat === undefined) return;
162
+ const entry = rec.sessionStore.state.chats.find((c) => c.resource === chat.resource);
163
+ if (entry === undefined) return;
164
+ const next = chatSummaryOf(chat);
165
+ const changes: Record<string, unknown> = {};
166
+ let changed = false;
167
+ for (const key of ["title", "status", "activity", "modifiedAt"] as const) {
168
+ if (entry[key] !== next[key]) {
169
+ changes[key] = next[key];
170
+ changed = true;
171
+ }
172
+ }
173
+ if (changed) {
174
+ this.publish({
175
+ channel: rec.channel,
176
+ action: { type: ActionType.SessionChatUpdated, chat: chat.resource, changes: changes as Partial<ChatSummary> },
177
+ });
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Announce summary-level changes on the root channel (`root/
183
+ * sessionSummaryChanged` notification — ephemeral, not replayed).
184
+ * Identity fields (resource/provider/createdAt) never change.
185
+ */
186
+ private maybeNotifySummaryChanged(rec: SessionRecord, before: SessionSummary, after: SessionSummary): void {
187
+ const changes: Record<string, unknown> = {};
188
+ for (const key of ["title", "status", "activity", "modifiedAt", "chats", "defaultChat"] as const) {
189
+ if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) {
190
+ changes[key] = after[key];
191
+ }
192
+ }
193
+ if (Object.keys(changes).length === 0) return;
194
+ if (after.modifiedAt > rec.modifiedAt) rec.modifiedAt = after.modifiedAt;
195
+ this.notifyRoot("root/sessionSummaryChanged", {
196
+ channel: ROOT_CHANNEL,
197
+ session: rec.channel,
198
+ changes,
199
+ });
200
+ }
201
+
202
+ /**
203
+ * The AHP `workingDirectories` every session of this host carries
204
+ * (`SessionMetadata.workingDirectories`): the single location directory —
205
+ * the session's agent has tool access exactly there. VS Code groups its
206
+ * session list by this workspace (the folder name, host-suffixed for
207
+ * remote hosts); sessions without it fall into the "Unknown" bucket.
208
+ * `undefined` when the location directory is unknown.
209
+ */
210
+ protected workingDirectories(): string[] | undefined {
211
+ return this.opts.defaultDirectory !== undefined ? [directoryUri(this.opts.defaultDirectory)] : undefined;
212
+ }
213
+
214
+ /** The denormalized `SessionSummary` view of a record. */
215
+ protected sessionSummary(rec: SessionRecord): SessionSummary {
216
+ const s = rec.sessionStore.state;
217
+ // Authoritative chat order: default first, then insertion order
218
+ // (the default chat is bound first).
219
+ const chats = [...rec.chats.values()].map((c) => chatSummaryOf(c.chatStore.state));
220
+ let modifiedAt = rec.modifiedAt;
221
+ for (const c of rec.chats.values()) {
222
+ if (c.chatStore.state.modifiedAt > modifiedAt) modifiedAt = c.chatStore.state.modifiedAt;
223
+ }
224
+ return buildSessionSummary({
225
+ channel: rec.channel,
226
+ provider: rec.provider,
227
+ title: s.title,
228
+ status: s.status,
229
+ activity: s.activity,
230
+ createdAt: rec.createdAt,
231
+ modifiedAt,
232
+ chats,
233
+ defaultChat: rec.defaultChatURI,
234
+ workingDirectories: this.workingDirectories(),
235
+ });
236
+ }
237
+
238
+ /** Send a root-channel notification frame to every root subscriber. */
239
+ protected notifyRoot(method: string, params: unknown): void {
240
+ const frame = { jsonrpc: "2.0", method, params };
241
+ for (const socketId of this.channels.socketsSubscribedTo(ROOT_CHANNEL)) {
242
+ this.opts.send(socketId, frame);
243
+ }
244
+ }
245
+
246
+ /** Send an `action` notification to every socket subscribed to the channel. */
247
+ private notifyAction(envelope: ActionEnvelope): void {
248
+ const frame = { jsonrpc: "2.0", method: "action", params: envelope };
249
+ for (const socketId of this.channels.socketsSubscribedTo(envelope.channel)) {
250
+ this.opts.send(socketId, frame);
251
+ }
252
+ }
253
+
254
+ /** The socket currently bound to a clientId (rejection delivery target). */
255
+ protected socketIdForClient(clientId: string): number | undefined {
256
+ for (const [socketId, socket] of this.sockets) {
257
+ if (socket.clientId === clientId) return socketId;
258
+ }
259
+ return undefined;
260
+ }
261
+
262
+ /**
263
+ * Publish an accepted echo (or a rejection) on the action stream. A
264
+ * rejection must reach the dispatching socket even when it is not
265
+ * subscribed to the channel (write-ahead dispatch: the client applied
266
+ * the action optimistically and needs the rejection to roll it back).
267
+ */
268
+ protected echo(
269
+ channel: string,
270
+ action: StateAction,
271
+ origin: ActionOrigin | undefined,
272
+ rejectionReason?: string,
273
+ ): void {
274
+ const envelope = this.publish({
275
+ channel,
276
+ action,
277
+ origin,
278
+ ...(rejectionReason !== undefined ? { rejectionReason } : {}),
279
+ });
280
+ if (rejectionReason !== undefined && origin !== undefined) {
281
+ const socketId = this.socketIdForClient(origin.clientId);
282
+ if (socketId !== undefined && !this.channels.socketsSubscribedTo(channel).includes(socketId)) {
283
+ this.opts.send(socketId, { jsonrpc: "2.0", method: "action", params: envelope });
284
+ }
285
+ }
286
+ }
287
+
288
+ /**
289
+ * The changeset store's owner: session-kind changesets
290
+ * live on the record (the session channel owns them); uncommitted/turn
291
+ * changesets live on the owning chat. Null when the owner is gone
292
+ * (a disposed chat's changesets are un-subscribable).
293
+ */
294
+ private changesetOwner(rec: SessionRecord, uri: string): { kind: "session" } | { kind: "chat"; chat: ChatRuntime } | null {
295
+ const parsed = parseChangesetChannel(uri);
296
+ if (parsed === null) return null;
297
+ if (parsed.kind === "session") return { kind: "session" };
298
+ const chat = rec.chats.get(parsed.ownerUri);
299
+ return chat === undefined ? null : { kind: "chat", chat };
300
+ }
301
+
302
+ /**
303
+ * Get-or-create the changeset store for a URI (fresh stores start
304
+ * computing). Owner-aware — see `changesetOwner`; null when the owner
305
+ * is gone.
306
+ */
307
+ protected changesetStore(rec: SessionRecord, uri: string): ChangesetStateStore | null {
308
+ const owner = this.changesetOwner(rec, uri);
309
+ if (owner === null) return null;
310
+ const map = owner.kind === "chat" ? owner.chat.changesets : rec.sessionChangesets;
311
+ let store = map.get(uri);
312
+ if (store === undefined) {
313
+ store = createChangesetStateStore({ status: ChangesetStatus.Computing, files: [] });
314
+ map.set(uri, store);
315
+ }
316
+ return store;
317
+ }
318
+
319
+ /** The live store for a URI, or undefined when it has never been created. */
320
+ protected changesetStoreOf(rec: SessionRecord, uri: string): ChangesetStateStore | undefined {
321
+ const owner = this.changesetOwner(rec, uri);
322
+ if (owner === null) return undefined;
323
+ const map = owner.kind === "chat" ? owner.chat.changesets : rec.sessionChangesets;
324
+ return map.get(uri);
325
+ }
326
+
327
+ /** The store's current per-file review flags, keyed by file id. */
328
+ protected reviewedById(store: ChangesetStateStore): Map<string, boolean> {
329
+ const out = new Map<string, boolean>();
330
+ for (const f of store.state.files) {
331
+ if (typeof f.reviewed === "boolean") out.set(f.id, f.reviewed);
332
+ }
333
+ return out;
334
+ }
335
+ }