opencode-ahp 0.1.3 → 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,19 +14,23 @@
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
26
26
  * bridge error must never take down the opencode server (R2).
27
27
  */
28
+ import { execFile } from "node:child_process";
29
+ import { mkdir, readFile as fsReadFile, rm, writeFile as fsWriteFile } from "node:fs/promises";
30
+ import { dirname, isAbsolute, join, relative } from "node:path";
28
31
  import { readFileSync } from "node:fs";
29
32
  import { fileURLToPath } from "node:url";
33
+ import { promisify } from "node:util";
30
34
  import { Plugin } from "@opencode/plugin";
31
35
  // Type-only import of the plugin context. The package's root entry
32
36
  // intentionally re-exports no `Context` (it is only ever observed as the
@@ -41,6 +45,11 @@ import type { SessionDomain } from "@opencode/plugin/promise/session";
41
45
  * is derived through the plugin package's declared subpaths.
42
46
  */
43
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"];
44
53
  import { isRecord, resolveOptions, type Options } from "./options.js";
45
54
  import { createListener, type Listener } from "./transport.js";
46
55
  import { Host } from "./host.js";
@@ -49,11 +58,25 @@ import { errorMessage } from "./error.js";
49
58
  import {
50
59
  mapV2Event,
51
60
  type FacadeAgent,
61
+ type FacadeClientTool,
52
62
  type FacadeModel,
53
63
  type FacadeModelRef,
54
64
  type FacadeSession,
55
65
  type OpencodeFacade,
56
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";
57
80
 
58
81
  const TAG = "[opencode-ahp]";
59
82
 
@@ -96,7 +119,7 @@ function generateToken(): string {
96
119
  * Token from options when set; otherwise the persisted one from plugin
97
120
  * storage, generated (and printed once) on first start. Persisting in
98
121
  * `ctx.storage` means restarts reuse the same token — a printed token
99
- * must not go stale on `opencode service restart` (plan §8.1).
122
+ * must not go stale on `opencode service restart`.
100
123
  */
101
124
  async function ensureToken(ctx: Context): Promise<string> {
102
125
  const existing = await ctx.storage.get(TOKEN_STORAGE_KEY);
@@ -129,6 +152,9 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
129
152
  ...(info.model !== undefined ? { model: modelRefOf(info) } : {}),
130
153
  // SessionInfo.time carries `archived` only while archived.
131
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> } : {}),
132
158
  time: { created: info.time.created, updated: info.time.updated },
133
159
  };
134
160
  }
@@ -140,8 +166,46 @@ function isHiddenSessionEvent(event: unknown, hiddenSessionID: string): boolean
140
166
  return isRecord(data) && data["sessionID"] === hiddenSessionID;
141
167
  }
142
168
 
169
+ // ── changeset git helpers ──────────────────────────
170
+ //
171
+ // The plugin `ctx` has no "file content at HEAD" or "discard one file"
172
+ // surface (`ctx.vcs` only diffs), so the facade shells out to `git` in the
173
+ // location directory. Every helper degrades to null/[] on any failure — a
174
+ // VCS hiccup must never throw into the host (R2).
175
+
176
+ const execFileAsync = promisify(execFile);
177
+
178
+ /** Run `git <args…>` in `cwd` and return stdout. Throws on non-zero exit. */
179
+ async function git(cwd: string, args: string[]): Promise<string> {
180
+ // 64 MiB buffer: file contents can be large; a buffer overflow must read
181
+ // as "failed" (→ null/[]), not hang the host.
182
+ const { stdout } = await execFileAsync("git", args, { cwd, maxBuffer: 64 * 1024 * 1024 });
183
+ return stdout;
184
+ }
185
+
186
+ /** The git repo root containing `cwd`, or null when it is not inside one. */
187
+ async function gitRepoRoot(cwd: string): Promise<string | null> {
188
+ try {
189
+ const out = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim();
190
+ return out.length > 0 ? out : null;
191
+ } catch {
192
+ return null;
193
+ }
194
+ }
195
+
196
+ /** The repo-root-relative path of `absPath`, or null when outside the repo. */
197
+ function repoRelative(root: string, absPath: string): string | null {
198
+ const rel = relative(root, absPath);
199
+ if (rel.length === 0 || rel.startsWith("..") || isAbsolute(rel)) return null;
200
+ return rel;
201
+ }
202
+
203
+ function isEnoent(err: unknown): boolean {
204
+ return (err as NodeJS.ErrnoException | null)?.code === "ENOENT";
205
+ }
206
+
143
207
  /**
144
- * The narrow opencode surface the bridge needs (plan §3.2, §14.7, §11).
208
+ * The narrow opencode surface the bridge needs.
145
209
  *
146
210
  * The catalog and agents are re-read on every call (the host snapshots
147
211
  * lazily on initialize/subscribe/reconnect, not at setup) from the
@@ -152,17 +216,50 @@ function isHiddenSessionEvent(event: unknown, hiddenSessionID: string): boolean
152
216
  * registry reads reflect every registration so far — including during
153
217
  * plugin setup — so no setup-time race.
154
218
  *
155
- * Phase 1 adds the session surface: create/list/get, prompt with
156
- * `delivery` (steer|queue), switchModel/switchAgent, interrupt, update
157
- * (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.
158
222
  *
159
- * `hiddenSessionID` (the keep-alive anchor, plan §15) is filtered from all
223
+ * `hiddenSessionID` (the keep-alive anchor) is filtered from all
160
224
  * three session surfaces so the AHP client never sees it: `list`/snapshots
161
225
  * (by ID), `get` (null = not found), and the event stream (by
162
226
  * `data.sessionID` — covers `session.created` and anything a future bridge
163
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).
164
233
  */
165
- 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 {
237
+ const locationDir = ctx.location.directory;
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
+
247
+ const readTextFile = async (absPath: string): Promise<string | null> => {
248
+ try {
249
+ return await fsReadFile(absPath, "utf-8");
250
+ } catch (err) {
251
+ if (isEnoent(err)) return null; // absent → null (caller decides)
252
+ throw err; // other errors propagate (host maps them)
253
+ }
254
+ };
255
+ const removeFile = async (absPath: string): Promise<void> => {
256
+ try {
257
+ await rm(absPath);
258
+ } catch (err) {
259
+ if (!isEnoent(err)) throw err; // already gone → no-op
260
+ }
261
+ };
262
+
166
263
  return {
167
264
  async listCatalog() {
168
265
  const [providers, models] = await Promise.all([ctx.provider.list(), ctx.model.list()]);
@@ -207,8 +304,14 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
207
304
  hidden: a.hidden,
208
305
  }));
209
306
  },
210
- // ── Phase 1: sessions ────────────────────────────────────────────────
211
- 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
+ }) {
212
315
  const info = await ctx.session.create({
213
316
  ...(input?.id !== undefined ? { id: input.id } : {}),
214
317
  ...(input?.title !== undefined ? { title: input.title } : {}),
@@ -222,6 +325,12 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
222
325
  },
223
326
  }
224
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 } : {}),
225
334
  });
226
335
  return mapSessionInfo(info);
227
336
  },
@@ -239,6 +348,9 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
239
348
  return null; // gone (removed) — the pump treats null as "skip"
240
349
  }
241
350
  },
351
+ async removeSession(sessionID: string) {
352
+ await ctx.session.remove({ sessionID });
353
+ },
242
354
  async prompt(input: { sessionID: string; text: string; delivery?: "steer" | "queue" }) {
243
355
  const res = await ctx.session.prompt({
244
356
  sessionID: input.sessionID,
@@ -285,13 +397,133 @@ function implementFacade(ctx: Context, hiddenSessionID: string | null): Opencode
285
397
  if (mapped !== null) yield mapped;
286
398
  }
287
399
  },
400
+ // ── changesets ────────────────────────────────
401
+ async vcsDiffWorking() {
402
+ const root = await gitRepoRoot(locationDir);
403
+ if (root === null) return []; // not a git repo → no working diff
404
+ try {
405
+ // `ctx.vcs.diff` returns `{ location, data: FileDiff.Info[] }` with
406
+ // repo-root-relative `file` paths — join to the repo root for the
407
+ // facade's absolute-path contract.
408
+ const res = await ctx.vcs.diff({ mode: "working", untracked: "files" });
409
+ return res.data.map((d) => ({
410
+ path: join(root, d.file),
411
+ additions: d.additions,
412
+ deletions: d.deletions,
413
+ status: d.status,
414
+ }));
415
+ } catch {
416
+ return []; // R2: degrade to empty, never throw
417
+ }
418
+ },
419
+ async gitHeadFile(absPath: string) {
420
+ const root = await gitRepoRoot(locationDir);
421
+ if (root === null) return null;
422
+ const rel = repoRelative(root, absPath);
423
+ if (rel === null) return null;
424
+ try {
425
+ return await git(root, ["show", `HEAD:${rel}`]);
426
+ } catch {
427
+ return null; // no HEAD / not tracked / failed → absent
428
+ }
429
+ },
430
+ async readFile(absPath: string) {
431
+ return readTextFile(absPath);
432
+ },
433
+ async writeFile(absPath: string, content: string) {
434
+ await mkdir(dirname(absPath), { recursive: true });
435
+ await fsWriteFile(absPath, content, "utf-8");
436
+ },
437
+ async deleteFile(absPath: string) {
438
+ await removeFile(absPath);
439
+ },
440
+ async discardFile(absPath: string) {
441
+ const root = await gitRepoRoot(locationDir);
442
+ const rel = root !== null ? repoRelative(root, absPath) : null;
443
+ if (root === null || rel === null) {
444
+ await removeFile(absPath); // not in a repo → just delete
445
+ return;
446
+ }
447
+ try {
448
+ await git(root, ["ls-files", "--error-unmatch", "--", rel]);
449
+ } catch {
450
+ await removeFile(absPath); // untracked (or staged-new) → delete
451
+ return;
452
+ }
453
+ try {
454
+ await git(root, ["checkout", "HEAD", "--", rel]);
455
+ } catch {
456
+ await removeFile(absPath); // in the index but not in HEAD → delete
457
+ }
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
+ },
288
520
  };
289
521
  }
290
522
 
291
523
  export default Plugin.define({
292
524
  id: "opencode-ahp",
293
525
  async setup(ctx: Context) {
294
- // 1. Options — resolved before anything else (plan §8.1).
526
+ // 1. Options — resolved before anything else.
295
527
  let opts: Options;
296
528
  try {
297
529
  opts = resolveOptions(ctx.options, readOptionsFile());
@@ -313,8 +545,8 @@ export default Plugin.define({
313
545
  return; // R2: the opencode server stays up without AHP
314
546
  }
315
547
 
316
- // 3. Keep-alive (plan §15). Before the host exists, so the anchor
317
- // 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
318
550
  // and never reaches AHP clients (the facade filters it from the
319
551
  // snapshot/list surfaces regardless). A deterministic session ID means
320
552
  // reloads reuse the same session — no accumulation in the DB.
@@ -324,7 +556,7 @@ export default Plugin.define({
324
556
  let keepAlive: KeepAlive | null = null;
325
557
  if (opts.keepAlive) {
326
558
  keepAlive = new KeepAlive({
327
- // Get-or-create. (Upstream gap, plan §15: `SessionUpdateInput`
559
+ // Get-or-create. (Upstream gap: `SessionUpdateInput`
328
560
  // advertises `archived`, but the plugin host's `session.update`
329
561
  // drops it — `packages/core/src/plugin/host.ts` forwards only
330
562
  // title/metadata/permissions, in v2.2.6 and current dev. So the
@@ -358,12 +590,18 @@ export default Plugin.define({
358
590
  // constructed (the listener's socket ids are the host's socket ids).
359
591
  let listener: Listener | null = null;
360
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 };
361
597
  try {
362
598
  const host = new Host({
363
599
  serverInfo: { name: "opencode-ahp", version: pluginVersion(), title: "OpenCode" },
364
- facade: implementFacade(ctx, hiddenSessionID),
600
+ facade: implementFacade(ctx, hiddenSessionID, hostRef),
365
601
  replayWindow: opts.replayWindow,
366
602
  defaultDirectory: ctx.location.directory,
603
+ changesets: opts.capabilities.changesets,
604
+ terminals: opts.capabilities.terminals,
367
605
  send: (socketId, message) => {
368
606
  listener?.sendTo({ id: socketId }, JSON.stringify(message));
369
607
  },
@@ -372,6 +610,17 @@ export default Plugin.define({
372
610
  },
373
611
  log: (msg) => console.warn(`${TAG} ${msg}`),
374
612
  });
613
+ hostRef.current = host; // the client-tool execute bridge can route now
614
+ // TLS material: read the key/cert files here so a
615
+ // missing/unreadable file fails before binding and takes the R2
616
+ // degrade path below — the transport itself stays
617
+ // filesystem-free (it receives the PEM contents).
618
+ const tls = opts.tls
619
+ ? {
620
+ key: await fsReadFile(opts.tls.keyPath, "utf8"),
621
+ cert: await fsReadFile(opts.tls.certPath, "utf8"),
622
+ }
623
+ : null;
375
624
  listener = createListener(
376
625
  {
377
626
  host: opts.host,
@@ -380,7 +629,7 @@ export default Plugin.define({
380
629
  healthPath: opts.healthPath,
381
630
  token,
382
631
  allowedOrigins: opts.allowedOrigins,
383
- tls: opts.tls,
632
+ tls,
384
633
  },
385
634
  {
386
635
  onOpen: (info) => host.onOpen(info.id),
@@ -390,7 +639,7 @@ export default Plugin.define({
390
639
  );
391
640
  // 5. Event pump: opencode V2 events → AHP actions (the streaming
392
641
  // text/reasoning, tool lifecycle, permissions, usage, turn
393
- // terminals, steering/queue handoff — plan §11).
642
+ // terminals, steering/queue handoff).
394
643
  host.startEventPump();
395
644
  cleanupHost = () => host.stopEventPump();
396
645
  console.log(
@@ -408,7 +657,7 @@ export default Plugin.define({
408
657
  // 6. Cleanup: stop the keep-alive timer, stop the pump (aborts the
409
658
  // event subscription), and stop the listener, dropping every client
410
659
  // connection. Logged because a torn-down listener with no log line
411
- // is otherwise undiagnosable (plan §14.8).
660
+ // is otherwise undiagnosable.
412
661
  return () => {
413
662
  console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
414
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,7 +71,12 @@ export const BUILTIN_OPTIONS: Options = {
71
71
  keepAlive: true,
72
72
  keepAliveIntervalMinutes: 10,
73
73
  replayWindow: 1000,
74
- capabilities: { changesets: false, 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 },
75
80
  };
76
81
 
77
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,23 +1,30 @@
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).
6
+ * - root channel: `rootReducer`;
7
+ * - session channels: `sessionReducer`;
8
+ * - chat channels: `chatReducer`;
9
+ * - changeset channels: `changesetReducer`;
10
+ * - terminal channels: `terminalReducer`.
10
11
  */
11
12
  import {
12
13
  chatReducer,
14
+ changesetReducer,
13
15
  rootReducer,
14
16
  sessionReducer,
17
+ terminalReducer,
15
18
  type ChatAction,
16
19
  type ChatState,
20
+ type ChangesetAction,
21
+ type ChangesetState,
17
22
  type RootAction,
18
23
  type RootState,
19
24
  type SessionAction,
20
25
  type SessionState,
26
+ type TerminalAction,
27
+ type TerminalState,
21
28
  } from "@microsoft/agent-host-protocol";
22
29
 
23
30
  export interface RootStateStore {
@@ -41,6 +48,20 @@ export interface ChatStateStore {
41
48
  apply(action: ChatAction): ChatState;
42
49
  }
43
50
 
51
+ export interface ChangesetStateStore {
52
+ /** Current changeset state (the `…/changeset/…` snapshot payload). */
53
+ readonly state: ChangesetState;
54
+ /** Apply a changeset-channel action through the official reducer. */
55
+ apply(action: ChangesetAction): ChangesetState;
56
+ }
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
+
44
65
  export function createRootStateStore(initial: RootState): RootStateStore {
45
66
  let state: RootState = initial;
46
67
  return {
@@ -79,3 +100,29 @@ export function createChatStateStore(initial: ChatState): ChatStateStore {
79
100
  },
80
101
  };
81
102
  }
103
+
104
+ export function createChangesetStateStore(initial: ChangesetState): ChangesetStateStore {
105
+ let state: ChangesetState = initial;
106
+ return {
107
+ get state(): ChangesetState {
108
+ return state;
109
+ },
110
+ apply(action: ChangesetAction): ChangesetState {
111
+ state = changesetReducer(state, action);
112
+ return state;
113
+ },
114
+ };
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
+ }