opencode-ahp 0.1.4 → 0.1.5

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 CHANGED
@@ -2,15 +2,7 @@
2
2
 
3
3
  OpenCode v2 plugin that hosts the **Agent Host Protocol (AHP) 1.0.0**
4
4
  in-process so opencode is a native agent in the **VS Code Agents window** —
5
- on this machine and (MVP scope) on other machines over the local LAN.
6
-
7
- > **Status: Phase 3 — wss:// transport complete.** Sessions, model +
8
- > agent pickers, streaming, tool calls, permission prompts,
9
- > steering/queue, usage, **changesets (uncommitted / session / per-turn
10
- > diffs with `discard-changes`)**, and reconnect replay are
11
- > live-verified over the LAN with VS Code 1.145.2 (real Agents window ↔
12
- > host), over plain `ws://` **and native `wss://`** (TLS-terminated).
13
- > The full plan and wire findings live in [`plan.md`](plan.md).
5
+ on this machine and on other machines over the local LAN.
14
6
 
15
7
  ## What you get
16
8
 
@@ -29,6 +21,27 @@ In the Agents window, an `opencode` host with:
29
21
  (started → ready → confirmed → complete), and usage totals.
30
22
  - **Permissions** — opencode's `permission.asked` becomes an in-window
31
23
  approval prompt; approve runs the tool, deny blocks it.
24
+ - **Client tools** — a client can register its own tools per session
25
+ (`createSession` or `session/activeClientSet`): the model calls them
26
+ directly, the host delegates execution to the owning client
27
+ (`toolClientExecution` request — the session stays in progress while the
28
+ client runs), and the client's result flows back into the turn, including
29
+ `requiresResultConfirmation` approval. Client tools bypass opencode's
30
+ permission prompt; only the client that provided the tool may execute it
31
+ or confirm its result.
32
+ - **Multi-chat** — a session can host additional chats (AHP `createChat`,
33
+ gated on the advertised `multipleChats` capability): each chat runs
34
+ against its own opencode backend session with fully isolated turns, and
35
+ `disposeChat` removes a chat without touching the session. The chats
36
+ appear in the session's catalog (default chat first); each chat carries
37
+ its own changesets. Fork/side-chat creation is not supported (opencode
38
+ exposes no fork to plugins). Peer-chat backends appear in opencode's own
39
+ UI as ordinary sessions — they are real opencode sessions underneath.
40
+ **Survives restarts:** the host stamps small binding markers into the
41
+ opencode sessions' metadata at create, so after a location reload each
42
+ chat re-attaches at its original URI (and a client-chosen session
43
+ channel resurfaces under its original name); re-attached chat titles are
44
+ re-derived (`Chat 2`, …) while session titles and messages persist.
32
45
  - **Steering + queue** — a message sent mid-turn steers the active turn or
33
46
  queues for the next one (AHP `pendingMessageSet`).
34
47
  - **Changesets** — per-session diff channels (uncommitted, session, and
@@ -37,10 +50,16 @@ In the Agents window, an `opencode` host with:
37
50
  `discard-changes` operation restores a file. Requires the location
38
51
  directory to be a git repository (otherwise the changesets are empty);
39
52
  opt out with `capabilities.changesets: false`.
40
-
41
- Not yet: cancelling a queued message and the `always` permission reply
42
- (Phase 4 extensions); official conformance-suite coverage (Phase 5,
43
- last — after the extensions land).
53
+ - **Terminals** — read-only `ahp-terminal:` channels rendered from
54
+ `shell`-tool executions (`isPty: false`, completed-command output with
55
+ exit codes): while a turn runs a foreground shell command, the terminal
56
+ appears in the root catalog, streams
57
+ `data` → `commandFinished` → `exited` to subscribers, and leaves the
58
+ catalog at turn end (the channel state stays subscribable until the
59
+ chat/session is removed). The terminals are renderings, not pty —
60
+ `createTerminal`/`disposeTerminal` and client `terminal/*` actions get
61
+ clean read-only errors. Opt out with
62
+ `capabilities.terminals: false`.
44
63
 
45
64
  ## Requirements
46
65
 
@@ -98,13 +117,13 @@ sibling of `src/index.ts` (checkouts only — copy
98
117
  | `keepAlive` | `true` | Keep the opencode location loaded against its idle timeout (`experimental.location_idle_timeout`, default 60 min) by periodically touching an internal anchor session — with this on, **no `location_idle_timeout` config entry is needed**. The anchor (`opencode-ahp (keep-alive)`) is a real opencode session: it shows in the TUI session list but is hidden from AHP clients (opencode's plugin surface cannot archive it) |
99
118
  | `keepAliveIntervalMinutes` | `10` | Minutes between keep-alive touches; keep well below the effective idle timeout |
100
119
  | `replayWindow` | `1000` | Per-channel actions kept for reconnect replay; older gaps → fresh snapshot |
101
- | `capabilities` | `{ changesets: true, terminals: false, automations: false }` | Advertised in `initialize` — never advertise what we don't implement. Set `changesets` to `false` to disable the diff channels (the session/chat snapshots then carry no changeset catalogues and changeset URIs resolve to nothing) |
120
+ | `capabilities` | `{ changesets: true, terminals: true, automations: false }` | Host-side switches — never advertise what we don't implement (in AHP 1.0.0 none of these is a wire field; discovery is the state's optionality). Set `changesets` to `false` to disable the diff channels (the session/chat snapshots then carry no changeset catalogues and changeset URIs resolve to nothing); set `terminals` to `false` to disable the synthetic shell-command terminal channels (no `root/terminals` list, `shell` calls open no `ahp-terminal:` channels) |
102
121
 
103
- ## Remote access (local LAN — MVP)
122
+ ## Remote access (local LAN)
104
123
 
105
- MVP transport is plain `ws://` + token on the LAN (the token in the URL is
124
+ The LAN transport is plain `ws://` + token (the token in the URL is
106
125
  cleartext — LAN only, by design). Off-LAN options (Tailscale, a dev-tunnel
107
- port forward, any `wss://` proxy) are post-MVP; the host accepts any
126
+ port forward, any `wss://` proxy) are operational; the host accepts any
108
127
  `ws(s)://` URL whose path and token match.
109
128
 
110
129
  ### Host side
@@ -151,8 +170,9 @@ port forward, any `wss://` proxy) are post-MVP; the host accepts any
151
170
  needs an upstream auto-boot option.)
152
171
  4. Verify: `curl -s http://<host-lan-ip>:<port>/healthz` → `ok`.
153
172
 
154
- Full two-machine walkthrough:
155
- [`docs/lan-test-runbook.md`](docs/lan-test-runbook.md).
173
+ Full two-machine walkthrough (and the complete testing strategy: unit,
174
+ static, live verification, two-machine, conformance):
175
+ [`docs/testing.md`](docs/testing.md).
156
176
 
157
177
  ### Client side (each PC)
158
178
 
@@ -174,7 +194,7 @@ Note: the Agents window's built-in **SSH** and **Dev tunnels** flows run
174
194
  For a third-party host, only raw network reachability of the `ws(s)://`
175
195
  URL matters.
176
196
 
177
- ### Off-LAN: native `wss://` (Phase 3)
197
+ ### Off-LAN: native `wss://`
178
198
 
179
199
  When plain LAN `ws://` doesn't fit (host on another network, or
180
200
  token-in-URL on a shared network you don't want), set `tls` and the same
@@ -214,12 +234,20 @@ Dependency-free live probes (Node ≥ 20 global WebSocket):
214
234
 
215
235
  ```sh
216
236
  node scripts/ahp-client.mjs --token <token> [--base http://127.0.0.1:8765]
217
- # Phase 1 end-to-end: createSession → agent-picker snapshot → full turn lifecycle
218
- node scripts/ahp-phase1.mjs --token <token> --base http://127.0.0.1:8765 --provider opencode
219
- # Phase 2 end-to-end: changesets (edit → diffs → discard) + mid-turn reconnect/replay
220
- node scripts/ahp-phase2.mjs --token <token> --base http://127.0.0.1:8765
237
+ # end-to-end: createSession → agent-picker snapshot → full turn lifecycle
238
+ node scripts/ahp-turn-lifecycle.mjs --token <token> --base http://127.0.0.1:8765 --provider opencode
239
+ # changesets end-to-end: edit → diffs → discard, plus mid-turn reconnect/replay
240
+ node scripts/ahp-changesets.mjs --token <token> --base http://127.0.0.1:8765
241
+ # client-provided tools (ping tool, failed result, confirmation cycle)
242
+ node scripts/ahp-client-tools.mjs --token <token> --base http://127.0.0.1:8765
243
+ # multi-chat (createChat/disposeChat, per-chat backends, no ghost sessions)
244
+ node scripts/ahp-multi-chat.mjs --token <token> --base http://127.0.0.1:8765
245
+ # multi-chat durability: leave the peer chat + backend alive, reload the
246
+ # location, then recheck the re-attachment (chat at its original URI)
247
+ node scripts/ahp-multi-chat.mjs --token <token> --base http://127.0.0.1:8765 --leave-peer
248
+ node scripts/ahp-multi-chat.mjs --token <token> --base http://127.0.0.1:8765 --recheck <sessionChannel> <peerChatURI>
221
249
  # the same probes over native wss:// (self-signed test cert):
222
- NODE_TLS_REJECT_UNAUTHORIZED=0 node scripts/ahp-phase2.mjs --token <token> --base https://127.0.0.1:8765
250
+ NODE_TLS_REJECT_UNAUTHORIZED=0 node scripts/ahp-changesets.mjs --token <token> --base https://127.0.0.1:8765
223
251
  ```
224
252
 
225
253
  ## Publishing
@@ -233,6 +261,13 @@ settings* → *Trusted publishers* → this workflow).
233
261
  Installed copies don't auto-update: `opencode plugin update opencode-ahp`
234
262
  - `opencode service restart`.
235
263
 
264
+ ## Documentation
265
+
266
+ - [`docs/design.md`](docs/design.md) — architecture and wire-contract findings.
267
+ - [`docs/futures.md`](docs/futures.md) — candidate future work
268
+ - [`docs/testing.md`](docs/testing.md) — the testing strategy: unit, live
269
+ verification, two-machine, and conformance.
270
+
236
271
  ## License
237
272
 
238
273
  MIT — see [LICENSE](LICENSE).
@@ -1,5 +1,5 @@
1
1
  {
2
- // Documented option set for opencode-ahp (plan §8.2).
2
+ // Documented option set for opencode-ahp.
3
3
  //
4
4
  // How to use: copy this file to `options.jsonc` next to src/index.ts when
5
5
  // running from a checkout, or — the usual case — put the values you want
@@ -12,8 +12,8 @@
12
12
  // WS listen port.
13
13
  // "port": 8765,
14
14
 
15
- // Bind address. Binding a non-loopback address REQUIRES a token (the
16
- // listener refuses to start without one — plan R4).
15
+ // Bind address. Binding a non-loopback address REQUIRES a token (R4:
16
+ // the listener refuses to start without one).
17
17
  // "host": "127.0.0.1",
18
18
 
19
19
  // WS path — VS Code's remoteAgentHosts URL carries it verbatim.
@@ -25,7 +25,7 @@
25
25
  // "token": "…",
26
26
 
27
27
  // Origin allowlist: "*" (default) or an exact list, e.g.
28
- // ["vscode://vscode"]. The token is always required regardless (R5).
28
+ // ["vscode://vscode"]. The token is always required regardless.
29
29
  // "allowedOrigins": "*",
30
30
 
31
31
  // Native TLS termination via Bun.serve → wss:// (off-LAN transports,
@@ -39,7 +39,7 @@
39
39
 
40
40
  // Keep the opencode location loaded against the idle timeout
41
41
  // (experimental.location_idle_timeout, default 60 min) by touching an
42
- // internal anchor session periodically (plan §15). On, the
42
+ // internal anchor session periodically. On, the
43
43
  // location_idle_timeout config entry is not needed. The anchor shows in
44
44
  // the TUI session list as "opencode-ahp (keep-alive)"; AHP clients never
45
45
  // see it.
@@ -52,11 +52,16 @@
52
52
  // Global actions kept for reconnect replay; older gaps → fresh snapshot.
53
53
  // "replayWindow": 1000,
54
54
 
55
- // What initialize advertises — never advertise what we don't implement.
56
- // Default: { "changesets": true, "terminals": false, "automations": false }.
57
- // Set "changesets": false to disable the diff channels (no changeset
55
+ // Host-side capability switches — never advertise what we don't
56
+ // implement (in AHP 1.0.0 none of these is a wire field; discovery is
57
+ // the state's optionality).
58
+ // Default: { "changesets": true, "terminals": true, "automations": false }.
59
+ // "changesets": false disables the diff channels (no changeset
58
60
  // catalogues in the session/chat snapshots; changeset URIs resolve to
59
61
  // nothing). Changesets require the location directory to be a git
60
62
  // repository.
63
+ // "terminals": false disables the synthetic shell-command terminal
64
+ // channels (shell-tool calls open no ahp-terminal: channels and the
65
+ // root state carries no terminals list).
61
66
  // "capabilities": { "changesets": false, "terminals": false, "automations": false }
62
67
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-ahp",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "OpenCode V2 plugin: hosts Agent Host Protocol (AHP) 1.0.0 in-process so opencode is a native agent in the VS Code Agents window",
5
5
  "type": "module",
6
6
  "exports": {
package/src/bridge.ts CHANGED
@@ -1,16 +1,13 @@
1
1
  /**
2
- * The opencode ⇄ AHP bridge (plan §6.1 bridge.ts) — the only opencode-
3
- * aware module, kept pure: it receives the narrow `OpencodeFacade` that
4
- * src/index.ts implements against the plugin `ctx`, and unit tests inject
5
- * a fake.
2
+ * The opencode ⇄ AHP bridge — the only opencode-aware module, kept pure:
3
+ * it receives the narrow `OpencodeFacade` that src/index.ts implements
4
+ * against the plugin `ctx`, and unit tests inject a fake.
6
5
  *
7
- * Phase 0: the `ahp-root://` catalog (providers as AgentInfo, opencode
8
- * agents as AHP customizations — plan §14.7).
9
- *
10
- * Phase 1: the opencode session surface (create/list/get, prompt with
11
- * delivery, switchAgent/switchModel, interrupt, permission replies, the
12
- * mapped event stream) plus the initial-state builders and summary mappers
13
- * the host uses to seed session/chat stores.
6
+ * Surfaces: the `ahp-root://` catalog (providers as AgentInfo, opencode
7
+ * agents as AHP customizations); the opencode session surface (create/
8
+ * list/get, prompt with delivery, switchAgent/switchModel, interrupt,
9
+ * permission replies, the mapped event stream); and the initial-state
10
+ * builders and summary mappers the host uses to seed session/chat stores.
14
11
  */
15
12
  import { pathToFileURL } from "node:url";
16
13
  import { sessionChangesetURI, turnChangesetURI, uncommittedChangesetURI } from "./channels.js";
@@ -63,8 +60,7 @@ export interface FacadeProvider {
63
60
  export type FacadeAgentMode = "primary" | "subagent" | "all";
64
61
 
65
62
  /**
66
- * Narrow opencode agent (plan §14.7 mapping table), from
67
- * `ctx.agent.list()` → `Agent.Info[]`.
63
+ * Narrow opencode agent, from `ctx.agent.list()` → `Agent.Info[]`.
68
64
  */
69
65
  export interface FacadeAgent {
70
66
  id: string;
@@ -91,12 +87,18 @@ export interface FacadeSession {
91
87
  model?: FacadeModelRef;
92
88
  archived?: boolean;
93
89
  time: { created: number; updated: number };
90
+ /**
91
+ * Durable, core-opaque session metadata. The host uses
92
+ * one key — `opencode-ahp` — to make the peer-chat binding survive a
93
+ * restart; everything else is passed through opaquely.
94
+ */
95
+ metadata?: Record<string, unknown>;
94
96
  }
95
97
 
96
98
  /** `SessionPromptInput.delivery` (steer | queue; absent = default). */
97
99
  export type FacadeDelivery = "steer" | "queue";
98
100
 
99
- /** The decision values the host uses (`always` is out of MVP scope). */
101
+ /** The decision values the host uses (`always` is not implemented). */
100
102
  export type FacadePermissionDecision = "once" | "reject";
101
103
 
102
104
  /**
@@ -152,19 +154,19 @@ export interface FacadeTokens {
152
154
 
153
155
  /**
154
156
  * The narrow opencode surface the bridge needs. Implemented in
155
- * src/index.ts against the plugin `ctx` (the only ctx call sites, plan
156
- * §7 pure-module principle); a fake in unit tests.
157
+ * src/index.ts against the plugin `ctx` (the only ctx call sites — this
158
+ * module stays pure); a fake in unit tests.
157
159
  *
158
160
  * All methods are async: the catalog, agents, and sessions come from the
159
161
  * registry/session read APIs, which the docs guarantee reflect every
160
162
  * registration so far, including during plugin setup.
161
163
  */
162
164
  export interface OpencodeFacade {
163
- /** Live provider/model catalog (plan §3.2: `ctx.provider` + `ctx.model`). */
165
+ /** Live provider/model catalog (`ctx.provider` + `ctx.model`). */
164
166
  listCatalog(): Promise<readonly FacadeProvider[]>;
165
- /** Live opencode agents (plan §14.7: `ctx.agent.list()`). */
167
+ /** Live opencode agents (`ctx.agent.list()`). */
166
168
  listAgents(): Promise<readonly FacadeAgent[]>;
167
- // ── Phase 1: sessions ─────────────────────────────────────────────────
169
+ // ── sessions ─────────────────────────────────────────────────
168
170
  /**
169
171
  * Create an opencode session. `id` is only passed through when it is a
170
172
  * valid opencode SessionID (must start with "ses"); the host decides.
@@ -174,11 +176,19 @@ export interface OpencodeFacade {
174
176
  title?: string;
175
177
  agent?: string;
176
178
  model?: FacadeModelRef;
179
+ /** Durable session metadata — the host's chat-binding marker rides here. */
180
+ metadata?: Record<string, unknown>;
177
181
  }): Promise<FacadeSession>;
178
182
  /** All opencode sessions for this location. */
179
183
  listSessions(): Promise<readonly FacadeSession[]>;
180
184
  /** One opencode session, or null when it does not exist. */
181
185
  getSession(sessionID: string): Promise<FacadeSession | null>;
186
+ /**
187
+ * Remove an opencode session (`ctx.session.remove`). `disposeChat`
188
+ * removes a chat's backend session, and record removal disposes the
189
+ * peer-chat backends (multi-chat: one AHP chat per opencode session).
190
+ */
191
+ removeSession(sessionID: string): Promise<void>;
182
192
  /**
183
193
  * Send a prompt. `delivery` maps to `SessionPromptInput.delivery`
184
194
  * ("steer" | "queue"); absent = the default (start or continue a turn).
@@ -199,7 +209,7 @@ export interface OpencodeFacade {
199
209
  * iterator ends (without error) when the signal aborts.
200
210
  */
201
211
  events(signal: AbortSignal): AsyncIterable<FacadeEvent>;
202
- // ── Phase 2: changesets ───────────────────────────────────────────────
212
+ // ── changesets ───────────────────────────────────────────────
203
213
  /**
204
214
  * Working-tree diff vs HEAD (uncommitted changes, untracked files
205
215
  * included), with **absolute** file paths. `[]` when the location is
@@ -223,8 +233,47 @@ export interface OpencodeFacade {
223
233
  * (fallback delete), untracked → delete.
224
234
  */
225
235
  discardFile(absPath: string): Promise<void>;
236
+ // ── client-provided tools ─────────────────────────
237
+ /**
238
+ * Replace the location's registered client tools with `tools` (the
239
+ * cross-session union of every AHP session's active-client tools;
240
+ * `[]` when none). The implementation applies them to the opencode
241
+ * tool registry (`ctx.tool.transform` + `ctx.tool.reload`) — the
242
+ * registered tools' `execute` routes back to the host.
243
+ */
244
+ syncClientTools(tools: readonly FacadeClientTool[]): Promise<void>;
226
245
  }
227
246
 
247
+ /**
248
+ * A client-provided tool in its opencode-registration form (the host
249
+ * derives it from the AHP `ToolDefinition`s — `inputSchema` already
250
+ * normalized to an object JSON Schema, `description` already defaulted).
251
+ */
252
+ export interface FacadeClientTool {
253
+ name: string;
254
+ description: string;
255
+ /** Object JSON Schema for the tool input (raw — opencode passes it through). */
256
+ inputSchema: Record<string, unknown>;
257
+ }
258
+
259
+ /**
260
+ * The settled result of a client-executed tool call, as the opencode
261
+ * `execute` bridge consumes it: `ok` → a `Tool.Result` (the client's
262
+ * `toolCallComplete` content, text blocks joined), not-ok → a thrown
263
+ * `Tool.Error`.
264
+ */
265
+ export type FacadeClientToolResult =
266
+ | {
267
+ ok: true;
268
+ /** The client's past-tense message (`ToolCallResult.pastTenseMessage`). */
269
+ pastTenseMessage: string;
270
+ /** The client's text content blocks, joined (absent when none). */
271
+ content?: string;
272
+ /** The client's structured content, verbatim. */
273
+ structuredContent?: Record<string, unknown>;
274
+ }
275
+ | { ok: false; error: string };
276
+
228
277
  /**
229
278
  * One entry of a VCS working-tree diff (the facade's shape — absolute
230
279
  * paths, unlike opencode's repo-root-relative `FileDiff.Info`).
@@ -236,12 +285,12 @@ export interface FacadeDiffFile {
236
285
  status: "added" | "deleted" | "modified";
237
286
  }
238
287
 
239
- // ── Phase 0: catalog mappers ─────────────────────────────────────────────
288
+ // ── catalog mappers ─────────────────────────────────────────────
240
289
 
241
290
  /**
242
- * Stable synthetic AHP URI for an opencode agent (plan §14.7: file URIs
243
- * are not available for config/built-in agents, and the URI only has to
244
- * match between the customization tree and `Message.agent`).
291
+ * Stable synthetic AHP URI for an opencode agent (file URIs are not
292
+ * available for config/built-in agents, and the URI only has to match
293
+ * between the customization tree and `Message.agent`).
245
294
  */
246
295
  export function agentUri(id: string): string {
247
296
  return `opencode:agent/${id}`;
@@ -253,8 +302,7 @@ export function agentIDFromUri(uri: string): string | null {
253
302
  }
254
303
 
255
304
  /**
256
- * Map opencode agents to AHP `AgentCustomization` children
257
- * (plan §14.7 mapping table):
305
+ * Map opencode agents to AHP `AgentCustomization` children:
258
306
  * - `id` → `uri` (synthetic `opencode:agent/<id>`, stable per agent) and
259
307
  * `id` (same value — the host is the minting publisher);
260
308
  * - `hidden: true` agents are omitted (internal: summary/title/…);
@@ -312,7 +360,7 @@ export function agentDirectoryCustomization(
312
360
 
313
361
  /**
314
362
  * Map the opencode catalog to the AHP root state's `agents` list.
315
- * Mapping locked 2026-11-07 (plan §14):
363
+ * Mapping locked 2026-11-07:
316
364
  * - one AgentInfo per opencode provider;
317
365
  * - providers with activation "disabled" are excluded;
318
366
  * - models with enabled: false are excluded;
@@ -321,7 +369,7 @@ export function agentDirectoryCustomization(
321
369
  * · maxPromptTokens ← limit.input;
322
370
  * - supportsVision ← capabilities.input contains "image".
323
371
  *
324
- * With opencode agents + a workspace directory (plan §14.7), every
372
+ * With opencode agents + a workspace directory, every
325
373
  * AgentInfo also carries the same workspace directory container with the
326
374
  * agent children as `customizations` — omitted when there is no visible
327
375
  * (non-hidden) agent, so the picker shows the generic provider default
@@ -358,13 +406,19 @@ export function mapCatalog(
358
406
  displayName: provider.name,
359
407
  description: provider.description ?? provider.name,
360
408
  models,
409
+ // Multi-chat: advertise plain multipleChats.
410
+ // No `fork`/`sideChat` sub-caps — the opencode plugin surface has
411
+ // no fork API in 2.2.6, so conformant clients (VS Code gates its
412
+ // UI on these) will never attempt the unsupported source forms.
413
+ // No `multipleWorkingDirectories` either (a location is one dir).
414
+ capabilities: { multipleChats: {} },
361
415
  ...(customizations !== undefined ? { customizations } : {}),
362
416
  });
363
417
  }
364
418
  return out;
365
419
  }
366
420
 
367
- // ── Phase 1: event mapping ───────────────────────────────────────────────
421
+ // ── event mapping ───────────────────────────────────────────────
368
422
 
369
423
  const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
370
424
 
@@ -581,7 +635,7 @@ function mapToolContent(c: Record<string, unknown>): FacadeToolContent | undefin
581
635
  return undefined;
582
636
  }
583
637
 
584
- // ── Phase 1: state builders & summary mappers ────────────────────────────
638
+ // ── state builders & summary mappers ────────────────────────────
585
639
 
586
640
  const STATUS_IDLE_READ = (SessionStatus.Idle | SessionStatus.IsRead) as SessionStatus;
587
641
 
@@ -597,7 +651,7 @@ export function modelRefString(model?: FacadeModelRef): string | null {
597
651
  * Initial `SessionState` for a new or lazily-registered opencode session.
598
652
  * `status` starts at `Idle | IsRead` (33) — the session reducer can only
599
653
  * move the read/archive/input-needed bits, so the *activity* source of
600
- * truth is the chat status (synced via `session/chatUpdated`, plan §14.9).
654
+ * truth is the chat status (synced via `session/chatUpdated`).
601
655
  * `customizations` carries the workspace agent directory container — the
602
656
  * same one the root catalog builds — because VS Code's agent dropdown reads
603
657
  * `SessionState.customizations` (root-state customizations are NOT read).
@@ -665,7 +719,8 @@ export function userMessage(text: string, model?: string, agentUri?: string): Me
665
719
 
666
720
  /**
667
721
  * Build the `SessionSummary` for root notifications / `listSessions` from
668
- * a live record's denormalized fields.
722
+ * a live record's denormalized fields. `chats` is the full catalog in
723
+ * authoritative order (default first, then insertion order).
669
724
  */
670
725
  export function buildSessionSummary(input: {
671
726
  channel: string;
@@ -675,7 +730,7 @@ export function buildSessionSummary(input: {
675
730
  activity?: string;
676
731
  createdAt: string;
677
732
  modifiedAt: string;
678
- chat: ChatSummary;
733
+ chats: ChatSummary[];
679
734
  defaultChat: string;
680
735
  }): SessionSummary {
681
736
  return {
@@ -686,7 +741,7 @@ export function buildSessionSummary(input: {
686
741
  ...(input.activity !== undefined ? { activity: input.activity } : {}),
687
742
  createdAt: input.createdAt,
688
743
  modifiedAt: input.modifiedAt,
689
- chats: [input.chat],
744
+ chats: input.chats,
690
745
  defaultChat: input.defaultChat,
691
746
  };
692
747
  }
@@ -767,10 +822,10 @@ export function pastTenseMessageFor(toolName: string, inputText: string | undefi
767
822
  return msg;
768
823
  }
769
824
 
770
- // ── Phase 2: changesets ───────────────────────────────────────────────────
825
+ // ── changesets ───────────────────────────────────────────────────
771
826
 
772
827
  /**
773
- * Content-ref URIs the host serves through `resourceRead` (plan §14.10):
828
+ * Content-ref URIs the host serves through `resourceRead`:
774
829
  * - `ahp-content://head/<b64url(absPath)>` — the file's content in HEAD
775
830
  * (`git show HEAD:<rel>`), for the "before" side of uncommitted/session
776
831
  * changes;
@@ -792,6 +847,11 @@ export function fileUri(absPath: string): string {
792
847
  return pathToFileURL(absPath).href;
793
848
  }
794
849
 
850
+ /** File URI of a directory — directory paths end with `/` (RFC 8089). */
851
+ export function directoryUri(absPath: string): string {
852
+ return fileUri(absPath.endsWith("/") ? absPath : absPath + "/");
853
+ }
854
+
795
855
  /** Content ref for a file's HEAD content (the "before" of a live diff). */
796
856
  export function headContentRef(absPath: string): string {
797
857
  return CONTENT_HEAD_MARKER + b64url(absPath);
@@ -840,8 +900,8 @@ function b64urlDecode(value: string): string | null {
840
900
  }
841
901
 
842
902
  /**
843
- * Line diff stats for two file contents (port of the ahp-acp-gateway
844
- * implementation, plan §14.10): CRLF-normalized, trailing newline ignored,
903
+ * Line diff stats for two file contents (ported from the ahp-acp-gateway
904
+ * implementation): CRLF-normalized, trailing newline ignored,
845
905
  * common prefix/suffix stripped, then an LCS DP over the middle with a
846
906
  * 40 000-cell cap (falls back to counting the whole middle when exceeded).
847
907
  */
@@ -905,7 +965,7 @@ export function computeLineDiffStats(
905
965
  };
906
966
  }
907
967
 
908
- /** The single operation this host advertises (plan §11 Phase 2). */
968
+ /** The single changeset operation this host advertises. */
909
969
  export const DISCARD_OPERATION_ID = "discard-changes";
910
970
 
911
971
  /**
@@ -927,13 +987,14 @@ export function discardOperation(): ChangesetOperation {
927
987
  /**
928
988
  * The session channel's changeset catalogue: the session-wide changeset
929
989
  * only (the protocol's "session" changeKind — all changes the agent has
930
- * produced; approximated by the working tree vs HEAD, plan §14.10).
990
+ * produced; approximated by the working tree vs HEAD). Takes the session
991
+ * channel URI as the changeset owner.
931
992
  */
932
- export function sessionChangesetCatalog(sessionID: string): Changeset[] {
993
+ export function sessionChangesetCatalog(sessionChannel: string): Changeset[] {
933
994
  return [
934
995
  {
935
996
  label: "Session Changes",
936
- uriTemplate: sessionChangesetURI(sessionID),
997
+ uriTemplate: sessionChangesetURI(sessionChannel),
937
998
  changeKind: "session",
938
999
  capabilities: { review: {} },
939
1000
  },
@@ -941,27 +1002,29 @@ export function sessionChangesetCatalog(sessionID: string): Changeset[] {
941
1002
  }
942
1003
 
943
1004
  /**
944
- * The chat channel's changeset catalogue: uncommitted changes, the
945
- * session-wide changeset, and the per-turn template (`{turnId}` expands
946
- * against the chat's turns — the protocol's standard template shapes).
1005
+ * The chat channel's changeset catalogue: the chat's own uncommitted
1006
+ * changes, the session-wide changeset, and the per-turn template
1007
+ * (`{turnId}` expands against the chat's turns — the protocol's standard
1008
+ * template shapes). Multi-chat: every chat has its own catalogue keyed
1009
+ * off its own channel URI.
947
1010
  */
948
- export function chatChangesetCatalog(sessionID: string): Changeset[] {
1011
+ export function chatChangesetCatalog(chatChannel: string, sessionChannel: string): Changeset[] {
949
1012
  return [
950
1013
  {
951
1014
  label: "Uncommitted Changes",
952
- uriTemplate: uncommittedChangesetURI(sessionID),
1015
+ uriTemplate: uncommittedChangesetURI(chatChannel),
953
1016
  changeKind: "uncommitted",
954
1017
  capabilities: { review: {} },
955
1018
  },
956
1019
  {
957
1020
  label: "Session Changes",
958
- uriTemplate: sessionChangesetURI(sessionID),
1021
+ uriTemplate: sessionChangesetURI(sessionChannel),
959
1022
  changeKind: "session",
960
1023
  capabilities: { review: {} },
961
1024
  },
962
1025
  {
963
1026
  label: "Turn Changes",
964
- uriTemplate: turnChangesetURI(sessionID, "{turnId}"),
1027
+ uriTemplate: turnChangesetURI(chatChannel, "{turnId}"),
965
1028
  changeKind: "turn",
966
1029
  capabilities: { review: {} },
967
1030
  },
@@ -974,8 +1037,8 @@ function withReviewed(file: ChangesetFile, reviewed: boolean | undefined): Chang
974
1037
  }
975
1038
 
976
1039
  /**
977
- * `ChangesetFile` entries for the working-tree diff (the `uncommitted` and
978
- * `session` changesets share this approximation, plan §14.10):
1040
+ * `ChangesetFile` entries for the working-tree diff (the `uncommitted`
1041
+ * and `session` changesets share this approximation):
979
1042
  * - added → `after` only, live `file://` content ref;
980
1043
  * - deleted → `before` only, HEAD content ref;
981
1044
  * - modified → live `file://` after + HEAD before.