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/src/index.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * opencode-ahp — OpenCode V2 plugin: hosts the **Agent Host Protocol
3
3
  * (AHP) 1.0.0** in-process so opencode appears as a native agent in the
4
- * VS Code Agents window (plan §8.1).
4
+ * VS Code Agents window.
5
5
  *
6
- * This is the only module that touches the plugin `ctx` (plan §7
7
- * pure-module principle). Everything else — options, transport,
8
- * handshake, channels, seq, state, bridge, host — is pure or
9
- * dependency-injected and unit-tested without an OpenCode runtime.
6
+ * This is the only module that touches the plugin `ctx` — everything
7
+ * else (options, transport, handshake, channels, seq, state, bridge,
8
+ * host) is pure or dependency-injected and unit-tested without an
9
+ * OpenCode runtime.
10
10
  *
11
11
  * Lifecycle:
12
12
  * 1. resolve options (ctx.options ▸ options.jsonc sibling ▸ built-ins;
@@ -14,12 +14,12 @@
14
14
  * `enabled: false` → the plugin is fully inert (no listener)
15
15
  * 2. token: explicit option, else persisted in ctx.storage (generated
16
16
  * once, printed once to the server log)
17
- * 3. keep-alive (plan §15): get-or-create the anchor session and start
17
+ * 3. keep-alive: get-or-create the anchor session and start
18
18
  * touching it periodically so the location survives the idle timeout
19
19
  * without any user config
20
20
  * 4. wire the Host (JSON-RPC router) to the transport (Bun.serve)
21
21
  * 5. start the opencode event pump (maps `ctx.event.subscribe` into
22
- * the host's AHP action stream — plan §6.1/§11)
22
+ * the host's AHP action stream)
23
23
  * 6. return cleanup that stops the keep-alive, the pump, and the listener
24
24
  *
25
25
  * Every failure path logs and stays up: a bad client connection or a
@@ -45,6 +45,11 @@ import type { SessionDomain } from "@opencode/plugin/promise/session";
45
45
  * is derived through the plugin package's declared subpaths.
46
46
  */
47
47
  type SessionInfo = Awaited<ReturnType<SessionDomain["get"]>>;
48
+ /**
49
+ * The `SessionCreateInput["metadata"]` type — a JSON record per the
50
+ * `Session.Metadata` schema (derived the same way as `SessionInfo`).
51
+ */
52
+ type SessionCreateMetadata = NonNullable<Parameters<SessionDomain["create"]>[0]>["metadata"];
48
53
  import { isRecord, resolveOptions, type Options } from "./options.js";
49
54
  import { createListener, type Listener } from "./transport.js";
50
55
  import { Host } from "./host.js";
@@ -53,11 +58,25 @@ import { errorMessage } from "./error.js";
53
58
  import {
54
59
  mapV2Event,
55
60
  type FacadeAgent,
61
+ type FacadeClientTool,
56
62
  type FacadeModel,
57
63
  type FacadeModelRef,
58
64
  type FacadeSession,
59
65
  type OpencodeFacade,
60
66
  } from "./bridge.js";
67
+ import { normalizedName } from "./client-tools.js";
68
+ /**
69
+ * The opencode tool surface for client-provided tools. `ToolError` is
70
+ * the schema `Error` class (thrown from the `execute` bridge); `ToolInfo`
71
+ * is the promise-flavored
72
+ * tool registration; `ToolContext` carries the tool-call context
73
+ * (sessionID, the tool-call `id`, the abort `signal`).
74
+ */
75
+ import {
76
+ Error as ToolError,
77
+ type Info as ToolInfo,
78
+ type ToolContext,
79
+ } from "@opencode/plugin/promise/tool";
61
80
 
62
81
  const TAG = "[opencode-ahp]";
63
82
 
@@ -100,7 +119,7 @@ function generateToken(): string {
100
119
  * Token from options when set; otherwise the persisted one from plugin
101
120
  * storage, generated (and printed once) on first start. Persisting in
102
121
  * `ctx.storage` means restarts reuse the same token — a printed token
103
- * must not go stale on `opencode service restart` (plan §8.1).
122
+ * must not go stale on `opencode service restart`.
104
123
  */
105
124
  async function ensureToken(ctx: Context): Promise<string> {
106
125
  const existing = await ctx.storage.get(TOKEN_STORAGE_KEY);
@@ -133,6 +152,9 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
133
152
  ...(info.model !== undefined ? { model: modelRefOf(info) } : {}),
134
153
  // SessionInfo.time carries `archived` only while archived.
135
154
  ...(info.time.archived !== undefined ? { archived: true } : {}),
155
+ // Durable, core-opaque metadata: the host reads its
156
+ // `opencode-ahp` chat-binding marker from it on external registration.
157
+ ...(isRecord(info.metadata) ? { metadata: info.metadata as Record<string, unknown> } : {}),
136
158
  time: { created: info.time.created, updated: info.time.updated },
137
159
  };
138
160
  }
@@ -144,7 +166,7 @@ function isHiddenSessionEvent(event: unknown, hiddenSessionID: string): boolean
144
166
  return isRecord(data) && data["sessionID"] === hiddenSessionID;
145
167
  }
146
168
 
147
- // ── Phase 2: changeset git helpers (plan §14.10) ──────────────────────────
169
+ // ── changeset git helpers ──────────────────────────
148
170
  //
149
171
  // The plugin `ctx` has no "file content at HEAD" or "discard one file"
150
172
  // surface (`ctx.vcs` only diffs), so the facade shells out to `git` in the
@@ -183,7 +205,7 @@ function isEnoent(err: unknown): boolean {
183
205
  }
184
206
 
185
207
  /**
186
- * The narrow opencode surface the bridge needs (plan §3.2, §14.7, §11).
208
+ * The narrow opencode surface the bridge needs.
187
209
  *
188
210
  * The catalog and agents are re-read on every call (the host snapshots
189
211
  * lazily on initialize/subscribe/reconnect, not at setup) from the
@@ -194,19 +216,34 @@ function isEnoent(err: unknown): boolean {
194
216
  * registry reads reflect every registration so far — including during
195
217
  * plugin setup — so no setup-time race.
196
218
  *
197
- * Phase 1 adds the session surface: create/list/get, prompt with
198
- * `delivery` (steer|queue), switchModel/switchAgent, interrupt, update
199
- * (rename), permission reply, and the mapped event stream.
219
+ * The session surface covers create/list/get, prompt with `delivery`
220
+ * (steer|queue), switchModel/switchAgent, interrupt, update (rename),
221
+ * permission reply, and the mapped event stream.
200
222
  *
201
- * `hiddenSessionID` (the keep-alive anchor, plan §15) is filtered from all
223
+ * `hiddenSessionID` (the keep-alive anchor) is filtered from all
202
224
  * three session surfaces so the AHP client never sees it: `list`/snapshots
203
225
  * (by ID), `get` (null = not found), and the event stream (by
204
226
  * `data.sessionID` — covers `session.created` and anything a future bridge
205
227
  * version may map).
228
+ *
229
+ * `hostRef`: the client-tool
230
+ * `execute` bridge needs the host, but the facade is constructed as part
231
+ * of the host's own options — a mutable holder assigned right after
232
+ * `new Host(...)` returns (the `listener` closure pattern).
206
233
  */
207
- function implementFacade(ctx: Context, hiddenSessionID: string | null): OpencodeFacade {
234
+ type HostRef = { current: Host | null };
235
+
236
+ function implementFacade(ctx: Context, hiddenSessionID: string | null, hostRef: HostRef): OpencodeFacade {
208
237
  const locationDir = ctx.location.directory;
209
238
 
239
+ // The cross-session client-tool set (client-provided tools).
240
+ // The single `ctx.tool.transform` registration is applied on every
241
+ // registry rebuild (opencode rebuilds from scratch, re-running all
242
+ // transforms over a fresh base — verified in core `State.create`), so
243
+ // the sync is: replace the set, (register the transform once), reload.
244
+ let clientTools: FacadeClientTool[] = [];
245
+ let clientToolsTransformRegistered = false;
246
+
210
247
  const readTextFile = async (absPath: string): Promise<string | null> => {
211
248
  try {
212
249
  return await fsReadFile(absPath, "utf-8");
@@ -267,8 +304,14 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
267
304
  hidden: a.hidden,
268
305
  }));
269
306
  },
270
- // ── Phase 1: sessions ────────────────────────────────────────────────
271
- async createSession(input?: { id?: string; title?: string; agent?: string; model?: FacadeModelRef }) {
307
+ // ── sessions ────────────────────────────────────────────────
308
+ async createSession(input?: {
309
+ id?: string;
310
+ title?: string;
311
+ agent?: string;
312
+ model?: FacadeModelRef;
313
+ metadata?: Record<string, unknown>;
314
+ }) {
272
315
  const info = await ctx.session.create({
273
316
  ...(input?.id !== undefined ? { id: input.id } : {}),
274
317
  ...(input?.title !== undefined ? { title: input.title } : {}),
@@ -282,6 +325,12 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
282
325
  },
283
326
  }
284
327
  : {}),
328
+ // The chat-binding marker is written atomically at
329
+ // create (no read-merge — core projects MetadataUpdated as a full
330
+ // column replacement, so a later update would clobber it). Session
331
+ // metadata is JSON by the Session.Metadata schema; the facade keeps
332
+ // it unknown-typed, so the single cast lives here.
333
+ ...(input?.metadata !== undefined ? { metadata: input.metadata as SessionCreateMetadata } : {}),
285
334
  });
286
335
  return mapSessionInfo(info);
287
336
  },
@@ -299,6 +348,9 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
299
348
  return null; // gone (removed) — the pump treats null as "skip"
300
349
  }
301
350
  },
351
+ async removeSession(sessionID: string) {
352
+ await ctx.session.remove({ sessionID });
353
+ },
302
354
  async prompt(input: { sessionID: string; text: string; delivery?: "steer" | "queue" }) {
303
355
  const res = await ctx.session.prompt({
304
356
  sessionID: input.sessionID,
@@ -345,7 +397,7 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
345
397
  if (mapped !== null) yield mapped;
346
398
  }
347
399
  },
348
- // ── Phase 2: changesets (plan §14.10) ────────────────────────────────
400
+ // ── changesets ────────────────────────────────
349
401
  async vcsDiffWorking() {
350
402
  const root = await gitRepoRoot(locationDir);
351
403
  if (root === null) return []; // not a git repo → no working diff
@@ -404,13 +456,74 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
404
456
  await removeFile(absPath); // in the index but not in HEAD → delete
405
457
  }
406
458
  },
459
+ // ── client-provided tools ───────
460
+ async syncClientTools(tools: readonly FacadeClientTool[]) {
461
+ clientTools = [...tools];
462
+ if (!clientToolsTransformRegistered) {
463
+ clientToolsTransformRegistered = true;
464
+ // Registered once for the location lifetime (scoped: disposed on
465
+ // location teardown). The callback is synchronous and reads the
466
+ // closure `clientTools` at rebuild time; each rebuild is a fresh
467
+ // registry, so only (re-)adding the current set is needed.
468
+ await ctx.tool.transform((editor) => {
469
+ const added = new Set<string>();
470
+ for (const tool of clientTools) {
471
+ const id = normalizedName(tool.name);
472
+ if (added.has(id)) continue; // normalized-name collision → first wins
473
+ added.add(id);
474
+ editor.add({
475
+ name: tool.name,
476
+ // The AHP `inputSchema` is a raw object JSON Schema —
477
+ // opencode's `inputJsonSchema` passes it through verbatim
478
+ // and validates model inputs against it.
479
+ input: tool.inputSchema,
480
+ description: tool.description,
481
+ // A client tool must be a DIRECT tool: under Code Mode a
482
+ // tool in the `execute` catalog is invoked as nested JS
483
+ // (`tools.ping(...)`) that emits no tool events of its own
484
+ // (only the outer `execute` call does), so the host could
485
+ // never see the call to track + relay to the client.
486
+ // `codemode: false` keeps it out of the catalog and in
487
+ // the direct list (live finding 2026-11-08).
488
+ options: { codemode: false },
489
+ execute: async (_input: unknown, context: ToolContext) => {
490
+ const host = hostRef.current;
491
+ if (host === null) {
492
+ throw new ToolError({ message: "the AHP host is not running" });
493
+ }
494
+ const result = await host.executeClientTool({
495
+ sessionID: String(context.sessionID),
496
+ toolCallId: String(context.id),
497
+ name: tool.name,
498
+ signal: context.signal,
499
+ });
500
+ if (!result.ok) throw new ToolError({ message: result.error });
501
+ const text = [result.pastTenseMessage, result.content]
502
+ .filter((part): part is string => typeof part === "string" && part.length > 0)
503
+ .join("\n\n");
504
+ return {
505
+ ...(text.length > 0 ? { content: text } : {}),
506
+ // No `output` (no output schema is declared — the
507
+ // runtime rejects one); structured content rides in
508
+ // the tool part's metadata.
509
+ ...(result.structuredContent !== undefined
510
+ ? { metadata: { structured: result.structuredContent } }
511
+ : {}),
512
+ };
513
+ },
514
+ } as unknown as ToolInfo);
515
+ }
516
+ });
517
+ }
518
+ await ctx.tool.reload();
519
+ },
407
520
  };
408
521
  }
409
522
 
410
523
  export default Plugin.define({
411
524
  id: "opencode-ahp",
412
525
  async setup(ctx: Context) {
413
- // 1. Options — resolved before anything else (plan §8.1).
526
+ // 1. Options — resolved before anything else.
414
527
  let opts: Options;
415
528
  try {
416
529
  opts = resolveOptions(ctx.options, readOptionsFile());
@@ -432,8 +545,8 @@ export default Plugin.define({
432
545
  return; // R2: the opencode server stays up without AHP
433
546
  }
434
547
 
435
- // 3. Keep-alive (plan §15). Before the host exists, so the anchor
436
- // session's `session.created` fires before the event pump subscribesbscribes
548
+ // 3. Keep-alive. Before the host exists, so the anchor
549
+ // session's `session.created` fires before the event pump subscribes
437
550
  // and never reaches AHP clients (the facade filters it from the
438
551
  // snapshot/list surfaces regardless). A deterministic session ID means
439
552
  // reloads reuse the same session — no accumulation in the DB.
@@ -443,7 +556,7 @@ export default Plugin.define({
443
556
  let keepAlive: KeepAlive | null = null;
444
557
  if (opts.keepAlive) {
445
558
  keepAlive = new KeepAlive({
446
- // Get-or-create. (Upstream gap, plan §15: `SessionUpdateInput`
559
+ // Get-or-create. (Upstream gap: `SessionUpdateInput`
447
560
  // advertises `archived`, but the plugin host's `session.update`
448
561
  // drops it — `packages/core/src/plugin/host.ts` forwards only
449
562
  // title/metadata/permissions, in v2.2.6 and current dev. So the
@@ -477,13 +590,18 @@ export default Plugin.define({
477
590
  // constructed (the listener's socket ids are the host's socket ids).
478
591
  let listener: Listener | null = null;
479
592
  let cleanupHost: (() => void) | null = null;
593
+ // The host back-reference for the client-tool `execute` bridge (the
594
+ // facade is built from the host's options, so the reference lands
595
+ // one statement later — the `listener` pattern).
596
+ const hostRef: HostRef = { current: null };
480
597
  try {
481
598
  const host = new Host({
482
599
  serverInfo: { name: "opencode-ahp", version: pluginVersion(), title: "OpenCode" },
483
- facade: implementFacade(ctx, hiddenSessionID),
600
+ facade: implementFacade(ctx, hiddenSessionID, hostRef),
484
601
  replayWindow: opts.replayWindow,
485
602
  defaultDirectory: ctx.location.directory,
486
603
  changesets: opts.capabilities.changesets,
604
+ terminals: opts.capabilities.terminals,
487
605
  send: (socketId, message) => {
488
606
  listener?.sendTo({ id: socketId }, JSON.stringify(message));
489
607
  },
@@ -492,7 +610,8 @@ export default Plugin.define({
492
610
  },
493
611
  log: (msg) => console.warn(`${TAG} ${msg}`),
494
612
  });
495
- // TLS material (Phase 3): read the key/cert files here so a
613
+ hostRef.current = host; // the client-tool execute bridge can route now
614
+ // TLS material: read the key/cert files here so a
496
615
  // missing/unreadable file fails before binding and takes the R2
497
616
  // degrade path below — the transport itself stays
498
617
  // filesystem-free (it receives the PEM contents).
@@ -520,7 +639,7 @@ export default Plugin.define({
520
639
  );
521
640
  // 5. Event pump: opencode V2 events → AHP actions (the streaming
522
641
  // text/reasoning, tool lifecycle, permissions, usage, turn
523
- // terminals, steering/queue handoff — plan §11).
642
+ // terminals, steering/queue handoff).
524
643
  host.startEventPump();
525
644
  cleanupHost = () => host.stopEventPump();
526
645
  console.log(
@@ -538,7 +657,7 @@ export default Plugin.define({
538
657
  // 6. Cleanup: stop the keep-alive timer, stop the pump (aborts the
539
658
  // event subscription), and stop the listener, dropping every client
540
659
  // connection. Logged because a torn-down listener with no log line
541
- // is otherwise undiagnosable (plan §14.8).
660
+ // is otherwise undiagnosable.
542
661
  return () => {
543
662
  console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
544
663
  keepAlive?.stop();
package/src/keep-alive.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Location keep-alive (plan §15).
2
+ * Location keep-alive.
3
3
  *
4
4
  * opencode v2 unloads idle locations after `experimental.location_idle_timeout`
5
5
  * (default 60 minutes). `LocationActivity` (packages/core/src/location-activity.ts)
@@ -11,14 +11,14 @@
11
11
  * any user config (`location_idle_timeout: false` is no longer required).
12
12
  *
13
13
  * The anchor session is visible in the opencode TUI session list (the plugin
14
- * surface cannot archive it — plan §15); the AHP host filters it out by its
14
+ * surface cannot archive it); the AHP host filters it out by its
15
15
  * deterministic ID from every client-facing surface.
16
16
  *
17
17
  * Cold boot is an architectural limit, not a keep-alive problem: plugins load
18
18
  * per location (`Node.makeLocationNode`) and cannot run before the location
19
19
  * boots, and no config boots a location at server start. The anchor session's
20
20
  * first touch therefore only helps once the location is up — the one-time boot
21
- * step stays (README "Remote access").
21
+ * step stays (open the project once, or a headless location-boot request).
22
22
  *
23
23
  * Pure module: session access and the timer are dependency-injected, so this
24
24
  * is unit-tested without an OpenCode runtime (house pattern).
package/src/options.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Plugin option resolution (plan §8.2): ctx.options ▸ options.jsonc
3
- * sibling file ▸ built-in defaults.
2
+ * Plugin option resolution: ctx.options ▸ options.jsonc sibling file ▸
3
+ * built-in defaults.
4
4
  *
5
5
  * Resolution is per top-level key (shallow): a key's value comes from
6
6
  * the highest-priority source that provides a valid value for it. Invalid
@@ -33,16 +33,16 @@ export interface Options {
33
33
  path: string;
34
34
  /** Auth token; null → auto-generate on first start and persist it. */
35
35
  token: string | null;
36
- /** Origin allowlist; the token is always required regardless (R5). */
36
+ /** Origin allowlist; the token is always required regardless. */
37
37
  allowedOrigins: string[] | "*";
38
- /** Native TLS via Bun.serve (post-MVP; off-LAN transports only, D3). */
38
+ /** Native TLS via Bun.serve on the same listener (off-LAN). */
39
39
  tls: TlsOptions | null;
40
40
  /** Plain-HTTP health endpoint (no auth). */
41
41
  healthPath: string;
42
42
  /**
43
43
  * Keep the opencode location loaded against the idle timeout (default
44
44
  * `experimental.location_idle_timeout`, 60 minutes) via a periodic durable
45
- * touch of an internal anchor session (plan §15). With this on, the
45
+ * touch of an internal anchor session. With this on, the
46
46
  * `location_idle_timeout: false` config entry is not needed. The anchor
47
47
  * shows in the TUI session list as "opencode-ahp (keep-alive)"; AHP
48
48
  * clients never see it.
@@ -55,7 +55,7 @@ export interface Options {
55
55
  keepAliveIntervalMinutes: number;
56
56
  /** Global actions kept for reconnect replay; older gaps → snapshot. */
57
57
  replayWindow: number;
58
- /** Advertised in `initialize` (plan §8.2). */
58
+ /** Advertised in `initialize`. */
59
59
  capabilities: CapabilityFlags;
60
60
  }
61
61
 
@@ -71,9 +71,12 @@ export const BUILTIN_OPTIONS: Options = {
71
71
  keepAlive: true,
72
72
  keepAliveIntervalMinutes: 10,
73
73
  replayWindow: 1000,
74
- // Phase 2: changesets are on by default (opt out with
75
- // `capabilities.changesets: false`).
76
- capabilities: { changesets: true, terminals: false, automations: false },
74
+ // Changesets and the synthetic shell-command terminals are both on by
75
+ // default; opt out with `capabilities.changesets: false` and
76
+ // `capabilities.terminals: false` respectively.
77
+ // Off the wire in 1.0.0 (no capability field) — the flag gates the
78
+ // host-side behavior only.
79
+ capabilities: { changesets: true, terminals: true, automations: false },
77
80
  };
78
81
 
79
82
  export function isRecord(v: unknown): v is Record<string, unknown> {
package/src/seq.ts CHANGED
@@ -1,10 +1,9 @@
1
1
  /**
2
- * Global action sequencer + replay window (plan §6.1 seq.ts).
2
+ * Global action sequencer + replay window.
3
3
  *
4
- * Deviation from the plan's "per-channel seq" wording (plan §14): AHP
5
- * 1.0.0's `serverSeq` is a single host-wide sequence across all channels
6
- * — the spec's lifecycle example numbers a chat action 43 while a root
7
- * snapshot is taken at 42. Consequences:
4
+ * AHP 1.0.0's `serverSeq` is a single host-wide sequence across all
5
+ * channels (not per-channel) — the spec's lifecycle example numbers a
6
+ * chat action 43 while a root snapshot is taken at 42. Consequences:
8
7
  * - snapshots carry `fromSeq` = the current global seq;
9
8
  * - reconnect replay is a *global* range (serverSeq > lastSeen) filtered
10
9
  * by the client's subscriptions;
package/src/state.ts CHANGED
@@ -1,19 +1,20 @@
1
1
  /**
2
2
  * Channel state stores, all maintained by the official reducers from
3
3
  * @microsoft/agent-host-protocol — the host never hand-rolls state
4
- * transitions (plan §6.1 state.ts: "state computed by the official
5
- * reducers").
4
+ * transitions (state is computed by the official reducers).
6
5
  *
7
- * - root channel: `rootReducer` (Phase 0);
8
- * - session channels: `sessionReducer` (Phase 1);
9
- * - chat channels: `chatReducer` (Phase 1);
10
- * - changeset channels: `changesetReducer` (Phase 2).
6
+ * - root channel: `rootReducer`;
7
+ * - session channels: `sessionReducer`;
8
+ * - chat channels: `chatReducer`;
9
+ * - changeset channels: `changesetReducer`;
10
+ * - terminal channels: `terminalReducer`.
11
11
  */
12
12
  import {
13
13
  chatReducer,
14
14
  changesetReducer,
15
15
  rootReducer,
16
16
  sessionReducer,
17
+ terminalReducer,
17
18
  type ChatAction,
18
19
  type ChatState,
19
20
  type ChangesetAction,
@@ -22,6 +23,8 @@ import {
22
23
  type RootState,
23
24
  type SessionAction,
24
25
  type SessionState,
26
+ type TerminalAction,
27
+ type TerminalState,
25
28
  } from "@microsoft/agent-host-protocol";
26
29
 
27
30
  export interface RootStateStore {
@@ -52,6 +55,13 @@ export interface ChangesetStateStore {
52
55
  apply(action: ChangesetAction): ChangesetState;
53
56
  }
54
57
 
58
+ export interface TerminalStateStore {
59
+ /** Current terminal state (the `ahp-terminal:/…` snapshot payload). */
60
+ readonly state: TerminalState;
61
+ /** Apply a terminal-channel action through the official reducer. */
62
+ apply(action: TerminalAction): TerminalState;
63
+ }
64
+
55
65
  export function createRootStateStore(initial: RootState): RootStateStore {
56
66
  let state: RootState = initial;
57
67
  return {
@@ -103,3 +113,16 @@ export function createChangesetStateStore(initial: ChangesetState): ChangesetSta
103
113
  },
104
114
  };
105
115
  }
116
+
117
+ export function createTerminalStateStore(initial: TerminalState): TerminalStateStore {
118
+ let state: TerminalState = initial;
119
+ return {
120
+ get state(): TerminalState {
121
+ return state;
122
+ },
123
+ apply(action: TerminalAction): TerminalState {
124
+ state = terminalReducer(state, action);
125
+ return state;
126
+ },
127
+ };
128
+ }
package/src/transport.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * AHP transport (plan §6.1 transport.ts).
2
+ * AHP transport.
3
3
  *
4
4
  * Two layers:
5
5
  *
@@ -7,8 +7,8 @@
7
7
  * policy, path routing, loopback check. Unit-tested without a runtime.
8
8
  * 2. **A thin listener** behind the `Listener` interface. The reference
9
9
  * implementation uses `Bun.serve` (opencode v2 is Bun-based, so the
10
- * in-process plugin runtime has it — verified by the Phase 0 spike,
11
- * R6). If the plugin context ever forbids raw listeners, a `ws`-
10
+ * in-process plugin runtime has it). If the plugin context ever
11
+ * forbids raw listeners, a `ws`-
12
12
  * package implementation drops in here with no changes to the
13
13
  * protocol layer.
14
14
  *
@@ -71,7 +71,7 @@ export function tokenValid(expected: string, presented: string | null): boolean
71
71
  }
72
72
 
73
73
  /**
74
- * Origin policy (plan R5). The token is the only credential; this only
74
+ * Origin policy. The token is the only credential; this only
75
75
  * filters *which* browser origins may attempt a connection. A null Origin
76
76
  * (non-browser clients: VS Code's own connection, CLI clients) always
77
77
  * passes — browser-origin filtering is the real attack surface.
@@ -183,7 +183,7 @@ const textDecoder = new TextDecoder();
183
183
  /**
184
184
  * Start the AHP listener. Throws before binding when a non-loopback
185
185
  * address is given without a token (R4) or when the runtime lacks
186
- * `Bun.serve` (R6 — the fallback implementation would be added here).
186
+ * `Bun.serve` (the fallback implementation would be added here).
187
187
  */
188
188
  export function createListener(opts: ListenerOptions, callbacks: TransportCallbacks): Listener {
189
189
  if (!isLoopback(opts.host) && !opts.token) {
@@ -194,7 +194,7 @@ export function createListener(opts: ListenerOptions, callbacks: TransportCallba
194
194
  const bun = bunOf();
195
195
  if (!bun) {
196
196
  throw new Error(
197
- "Bun.serve is not available in this runtime (R6); expected inside the " +
197
+ "Bun.serve is not available in this runtime; expected inside the " +
198
198
  "Bun-based opencode v2 server — a `ws`-package fallback would go here",
199
199
  );
200
200
  }