opencode-ahp 0.1.7 → 0.1.9

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/host.ts CHANGED
@@ -38,9 +38,9 @@
38
38
  * `root/activeSessionsChanged` is a sequencer action.
39
39
  *
40
40
  * Module layout: this file only composes the host — the section classes
41
- * (host-base.ts → host-changesets.ts → host-terminals.ts → host-turns.ts →
42
- * host-client-tools.ts → host-chats.ts → host-sessions.ts → host-dispatch.ts →
43
- * host-events.ts → host-rpc.ts) form a linear chain, each extending the
41
+ * (host-base.ts → host-changesets.ts → host-resources.ts → host-terminals.ts
42
+ * → host-turns.ts → host-client-tools.ts → host-chats.ts → host-sessions.ts
43
+ * → host-dispatch.ts → host-events.ts → host-rpc.ts) form a linear chain, each extending the
44
44
  * previous one; shared state lives in HostBase, and a section may only
45
45
  * call members declared at or below it in the chain (that is what keeps
46
46
  * the split type-safe).
package/src/index.ts CHANGED
@@ -14,21 +14,29 @@
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: get-or-create the anchor session and start
18
- * touching it periodically so the location survives the idle timeout
19
- * without any user config
20
- * 4. wire the Host (JSON-RPC router) to the transport (Bun.serve)
21
- * 5. start the opencode event pump (maps `ctx.event.subscribe` into
17
+ * 2b. directory allowlist (optional): a misconfigured
18
+ * `allowedWorkingDirectories` fails closed (AHP off, R2)
19
+ * 3. wire the Host (JSON-RPC router) to the transport (Bun.serve)
20
+ * 4. start the opencode event pump (maps `ctx.event.subscribe` into
22
21
  * the host's AHP action stream)
23
- * 6. return cleanup that stops the keep-alive, the pump, and the listener
22
+ * 5. return cleanup that stops the pump and the listener
24
23
  *
25
24
  * Every failure path logs and stays up: a bad client connection or a
26
25
  * bridge error must never take down the opencode server (R2).
27
26
  */
28
27
  import { execFile } from "node:child_process";
29
- import { mkdir, readFile as fsReadFile, rm, writeFile as fsWriteFile } from "node:fs/promises";
28
+ import {
29
+ lstat,
30
+ mkdir,
31
+ readFile as fsReadFile,
32
+ readdir,
33
+ realpath,
34
+ rm,
35
+ stat,
36
+ writeFile as fsWriteFile,
37
+ } from "node:fs/promises";
30
38
  import { dirname, isAbsolute, join, relative } from "node:path";
31
- import { readFileSync } from "node:fs";
39
+ import { createReadStream, readFileSync } from "node:fs";
32
40
  import { fileURLToPath } from "node:url";
33
41
  import { promisify } from "node:util";
34
42
  import { Plugin } from "@opencode/plugin";
@@ -51,10 +59,10 @@ type SessionInfo = Awaited<ReturnType<SessionDomain["get"]>>;
51
59
  */
52
60
  type SessionCreateMetadata = NonNullable<Parameters<SessionDomain["create"]>[0]>["metadata"];
53
61
  import { isRecord, resolveOptions, type Options } from "./options.js";
62
+ import { normalizeDirPrefix, PathPolicy } from "./path-policy.js";
54
63
  import { createListener, type Listener } from "./transport.js";
55
64
  import { Host } from "./host.js";
56
65
  import type { SpawnPty } from "./host-types.js";
57
- import { KeepAlive, KEEPALIVE_SESSION_ID } from "./keep-alive.js";
58
66
  import { errorMessage } from "./error.js";
59
67
  import {
60
68
  eventLogLine,
@@ -62,9 +70,15 @@ import {
62
70
  timeStamp,
63
71
  type FacadeAgent,
64
72
  type FacadeClientTool,
73
+ type FacadeDirectoryEntry,
74
+ type FacadeDiffFile,
75
+ type FacadeMcpServer,
65
76
  type FacadeModel,
66
77
  type FacadeModelRef,
78
+ type FacadeResourceInfo,
67
79
  type FacadeSession,
80
+ type FacadeSkill,
81
+ type FacadeTool,
68
82
  type OpencodeFacade,
69
83
  } from "./bridge.js";
70
84
  import { normalizedName } from "./client-tools.js";
@@ -244,17 +258,16 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
244
258
  // Durable, core-opaque metadata: the host reads its
245
259
  // `opencode-ahp` chat-binding marker from it on external registration.
246
260
  ...(isRecord(info.metadata) ? { metadata: info.metadata as Record<string, unknown> } : {}),
261
+ // The location the session lives in — its directory is where the
262
+ // session's agent has tool access (≠ the plugin's own location when
263
+ // the session was created with `workingDirectories` or elsewhere).
264
+ ...(info.location !== undefined && info.location !== null
265
+ ? { location: { directory: String(info.location.directory) } }
266
+ : {}),
247
267
  time: { created: info.time.created, updated: info.time.updated },
248
268
  };
249
269
  }
250
270
 
251
- /** True when a raw V2 event envelope (`{id, type, data}`) belongs to a session. */
252
- function isHiddenSessionEvent(event: unknown, hiddenSessionID: string): boolean {
253
- if (!isRecord(event)) return false;
254
- const data = event["data"];
255
- return isRecord(data) && data["sessionID"] === hiddenSessionID;
256
- }
257
-
258
271
  // ── changeset git helpers ──────────────────────────
259
272
  //
260
273
  // The plugin `ctx` has no "file content at HEAD" or "discard one file"
@@ -293,6 +306,207 @@ function isEnoent(err: unknown): boolean {
293
306
  return (err as NodeJS.ErrnoException | null)?.code === "ENOENT";
294
307
  }
295
308
 
309
+ /**
310
+ * The allowlist's `PathPolicyEnv` (design §3.3): canonicalize the
311
+ * symlinks of the EXISTING prefix portion of `p` — walk up to the deepest
312
+ * existing ancestor, realpath it, re-append the missing tail (the result
313
+ * may not yet exist; the tail is never created). This is what keeps a
314
+ * symlink planted under an allowed prefix from escaping the allowlist
315
+ * (`/tmp/link → /home` resolves to `/home/…` and is denied). Throws when
316
+ * an existing ancestor cannot be canonicalized (e.g. EACCES) — the policy
317
+ * check then defers to the underlying operation's own errno error.
318
+ */
319
+ async function resolveExistingPrefix(p: string): Promise<string> {
320
+ let base = p;
321
+ let tail: string | null = null;
322
+ for (;;) {
323
+ try {
324
+ const real = await realpath(base);
325
+ return tail === null ? real : join(real, tail);
326
+ } catch (err) {
327
+ if (!isEnoent(err)) throw err;
328
+ const parent = dirname(base);
329
+ if (parent === base) return p; // no existing ancestor (malformed) — lexical
330
+ const name = base.slice(parent.length + 1);
331
+ tail = tail === null ? name : join(name, tail);
332
+ base = parent;
333
+ }
334
+ }
335
+ }
336
+
337
+ /**
338
+ * The allowlist prefixes (the `allowedWorkingDirectories` option): each
339
+ * entry lexically normalized, and symlink-canonicalized when it exists —
340
+ * a prefix that IS a symlink covers its target. Entries that do not exist
341
+ * yet stay lexical (a `resourceMkdir` may create one later). Throws on a
342
+ * non-absolute entry or an existing-but-undecidable prefix — the caller
343
+ * fails closed (R2: AHP off, opencode keeps serving) rather than run
344
+ * unrestricted.
345
+ */
346
+ async function resolveAllowedDirPrefixes(entries: string[]): Promise<string[]> {
347
+ const out = new Set<string>();
348
+ for (const entry of entries) {
349
+ let prefix = normalizeDirPrefix(entry); // throws when not absolute
350
+ try {
351
+ prefix = await realpath(prefix);
352
+ } catch (err) {
353
+ if (!isEnoent(err)) throw err;
354
+ }
355
+ out.add(prefix);
356
+ }
357
+ return [...out];
358
+ }
359
+
360
+ /**
361
+ * Cross-location working diff. `ctx.vcs.diff` is pinned to the plugin's
362
+ * own location (core's `Vcs` service is a location node), but sessions
363
+ * can now live in other directories — so for any other directory the
364
+ * facade shells out to `git` directly, mirroring core's git-adapter
365
+ * semantics: tracked-vs-HEAD `name-status` plus the `??` entries of a
366
+ * full `status` (untracked files), `numstat` line counts, and — for
367
+ * added files, which numstat does not cover — an in-process line count.
368
+ * Commands run with `cwd` = the directory and pathspec `-- .`, so the
369
+ * listing is scoped to that subtree; git emits repo-root-relative
370
+ * paths, which are joined onto the repo root. Any failure → `[]` (R2).
371
+ */
372
+ async function gitWorkingDiff(dir: string): Promise<FacadeDiffFile[]> {
373
+ const root = await gitRepoRoot(dir);
374
+ if (root === null) return []; // not a git repo → no working diff
375
+ try {
376
+ // Run with `cwd` = the directory and pathspec `-- .`: the listing is
377
+ // scoped to that subtree, and git emits repo-root-relative paths
378
+ // (verified against git 2.47 — independent of cwd / relativePaths).
379
+ const hasHead = await gitHasHead(dir);
380
+ const items: { file: string; code: string }[] = [];
381
+ if (hasHead) {
382
+ // Tracked changes vs HEAD: `name-status -z` is null-delimited
383
+ // code, file, code, file, … pairs (core `diffNames`).
384
+ const pairs = (
385
+ await git(dir, ["diff", "--no-ext-diff", "--no-renames", "--name-status", "-z", "HEAD", "--", "."])
386
+ )
387
+ .split("\0")
388
+ .filter(Boolean);
389
+ for (let i = 0; i + 1 < pairs.length; i += 2) {
390
+ const code = pairs[i];
391
+ const file = pairs[i + 1];
392
+ if (code && file) items.push({ file, code });
393
+ }
394
+ // Untracked files (`??`) — the tracked diff never sees them.
395
+ for (const item of (
396
+ await git(dir, ["status", "--porcelain=v1", "--untracked-files=all", "--no-renames", "-z", "--", "."])
397
+ ).split("\0")) {
398
+ if (item.length < 4) continue;
399
+ const code = item.slice(0, 2);
400
+ const file = item.slice(3);
401
+ if (code === "??" && file) items.push({ file, code });
402
+ }
403
+ // Line counts for tracked changes (untracked files are counted below).
404
+ const stats = new Map<string, { additions: number; deletions: number }>();
405
+ for (const item of (
406
+ await git(dir, ["diff", "--no-ext-diff", "--no-renames", "--numstat", "-z", "HEAD", "--", "."])
407
+ ).split("\0")) {
408
+ const a = item.indexOf("\t");
409
+ const b = item.indexOf("\t", a + 1);
410
+ if (a === -1 || b === -1) continue;
411
+ const file = item.slice(b + 1);
412
+ if (!file) continue;
413
+ stats.set(file, {
414
+ additions: gitNumstatCount(item.slice(0, a)),
415
+ deletions: gitNumstatCount(item.slice(a + 1, b)),
416
+ });
417
+ }
418
+ const out: FacadeDiffFile[] = [];
419
+ for (const item of items) {
420
+ const status = gitKind(item.code);
421
+ const stat = stats.get(item.file);
422
+ if (status === "added" && stat === undefined) {
423
+ // Untracked (or newly added): numstat has no entry for it —
424
+ // count the file's lines in-process (0 when unreadable).
425
+ out.push({
426
+ path: join(root, item.file),
427
+ additions: await countLines(join(root, item.file)),
428
+ deletions: 0,
429
+ status,
430
+ });
431
+ } else {
432
+ out.push({
433
+ path: join(root, item.file),
434
+ additions: stat?.additions ?? 0,
435
+ deletions: stat?.deletions ?? 0,
436
+ status,
437
+ });
438
+ }
439
+ }
440
+ return out;
441
+ }
442
+ // No HEAD commit (fresh repo): the full status list IS the working
443
+ // diff; added files get an in-process line count, everything else 0/0.
444
+ const out: FacadeDiffFile[] = [];
445
+ for (const item of (
446
+ await git(dir, ["status", "--porcelain=v1", "--untracked-files=all", "--no-renames", "-z", "--", "."])
447
+ ).split("\0")) {
448
+ if (item.length < 4) continue;
449
+ const code = item.slice(0, 2);
450
+ const file = item.slice(3);
451
+ if (!file) continue;
452
+ const status = gitKind(code);
453
+ out.push({
454
+ path: join(root, file),
455
+ additions: status === "added" ? await countLines(join(root, file)) : 0,
456
+ deletions: 0,
457
+ status,
458
+ });
459
+ }
460
+ return out;
461
+ } catch {
462
+ return []; // R2: degrade to empty, never throw
463
+ }
464
+ }
465
+
466
+ /** The change kind of a git status/name-status code (core `kind()`). */
467
+ function gitKind(code: string): FacadeDiffFile["status"] {
468
+ if (code === "??") return "added";
469
+ if (code.includes("U")) return "modified";
470
+ if (code.includes("A") && !code.includes("D")) return "added";
471
+ if (code.includes("D") && !code.includes("A")) return "deleted";
472
+ return "modified";
473
+ }
474
+
475
+ /** A `numstat` count field: `-` (binary) reads as 0 (core `count()`). */
476
+ function gitNumstatCount(value: string): number {
477
+ const parsed = value === "-" ? 0 : Number.parseInt(value || "0", 10);
478
+ return Number.isFinite(parsed) ? parsed : 0;
479
+ }
480
+
481
+ /** Whether the repo at `dir` has a HEAD commit (core `hasHead()`). */
482
+ async function gitHasHead(dir: string): Promise<boolean> {
483
+ try {
484
+ await git(dir, ["rev-parse", "--verify", "HEAD"]);
485
+ return true;
486
+ } catch {
487
+ return false;
488
+ }
489
+ }
490
+
491
+ /**
492
+ * The number of lines in a text file (newline count), streamed — used
493
+ * for the line counts of added files, which `git diff --numstat` does
494
+ * not report. 0 on any read failure (R2).
495
+ */
496
+ async function countLines(absPath: string): Promise<number> {
497
+ try {
498
+ let lines = 0;
499
+ for await (const chunk of createReadStream(absPath)) {
500
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf-8");
501
+ const matches = text.match(/\n/g);
502
+ if (matches !== null) lines += matches.length;
503
+ }
504
+ return lines;
505
+ } catch {
506
+ return 0;
507
+ }
508
+ }
509
+
296
510
  /**
297
511
  * The narrow opencode surface the bridge needs.
298
512
  *
@@ -309,12 +523,6 @@ function isEnoent(err: unknown): boolean {
309
523
  * (steer|queue), switchModel/switchAgent, interrupt, update (rename),
310
524
  * permission reply, and the mapped event stream.
311
525
  *
312
- * `hiddenSessionID` (the keep-alive anchor) is filtered from all
313
- * three session surfaces so the AHP client never sees it: `list`/snapshots
314
- * (by ID), `get` (null = not found), and the event stream (by
315
- * `data.sessionID` — covers `session.created` and anything a future bridge
316
- * version may map).
317
- *
318
526
  * `hostRef`: the client-tool
319
527
  * `execute` bridge needs the host, but the facade is constructed as part
320
528
  * of the host's own options — a mutable holder assigned right after
@@ -328,7 +536,6 @@ type HostRef = { current: Host | null };
328
536
 
329
537
  function implementFacade(
330
538
  ctx: Context,
331
- hiddenSessionID: string | null,
332
539
  hostRef: HostRef,
333
540
  logEvent: ((line: string) => void) | null,
334
541
  ): OpencodeFacade {
@@ -342,6 +549,14 @@ function implementFacade(
342
549
  let clientTools: FacadeClientTool[] = [];
343
550
  let clientToolsTransformRegistered = false;
344
551
 
552
+ // The MCP toggle decisions (server name → desired `disabled`), layered
553
+ // over the config-file servers by a single `ctx.mcp.transform`
554
+ // registration (same rebuild-then-reload pattern as the client tools).
555
+ // Runtime-only: the config file is untouched and the map is empty on
556
+ // a fresh location, so a restart drops the decisions.
557
+ const mcpDisabled = new Map<string, boolean>();
558
+ let mcpDisabledTransformRegistered = false;
559
+
345
560
  const readTextFile = async (absPath: string): Promise<string | null> => {
346
561
  try {
347
562
  return await fsReadFile(absPath, "utf-8");
@@ -402,6 +617,60 @@ function implementFacade(
402
617
  hidden: a.hidden,
403
618
  }));
404
619
  },
620
+ // ── session customization catalog ───────────────────────────
621
+ async listMcpServers(): Promise<readonly FacadeMcpServer[]> {
622
+ const { data: servers } = await ctx.mcp.list();
623
+ return servers.map((s) => ({
624
+ name: String(s.name),
625
+ ...(s.title !== undefined ? { title: String(s.title) } : {}),
626
+ status: s.status.status,
627
+ ...("error" in s.status ? { error: s.status.error } : {}),
628
+ }));
629
+ },
630
+ async listSkills(): Promise<readonly FacadeSkill[]> {
631
+ const { data: skills } = await ctx.skill.list();
632
+ return skills.map((s) => ({
633
+ id: String(s.id),
634
+ name: String(s.name),
635
+ ...(s.description !== undefined ? { description: s.description } : {}),
636
+ ...(s.autoinvoke !== undefined ? { autoinvoke: s.autoinvoke } : {}),
637
+ path: String(s.path),
638
+ }));
639
+ },
640
+ async listTools(): Promise<readonly FacadeTool[]> {
641
+ const tools = await ctx.tool.list();
642
+ return tools.map((t) => ({
643
+ name: t.name,
644
+ // `description` is required by the type; guard anyway (the
645
+ // mapper omits empty ones).
646
+ ...(typeof t.description === "string" ? { description: t.description } : {}),
647
+ input: t.input,
648
+ }));
649
+ },
650
+ async setMcpDisabled(name: string, disabled: boolean): Promise<void> {
651
+ mcpDisabled.set(name, disabled);
652
+ if (!mcpDisabledTransformRegistered) {
653
+ mcpDisabledTransformRegistered = true;
654
+ // Registered once for the location lifetime (scoped: disposed on
655
+ // location teardown). The callback is synchronous and reads the
656
+ // closure map at rebuild time; each rebuild is a fresh config
657
+ // set, so (re-)applying the current decisions is the whole sync.
658
+ // It runs after the config plugin's own transform (registration
659
+ // order), so the override lands on the file's server config.
660
+ await ctx.mcp.transform((editor) => {
661
+ for (const [server, want] of mcpDisabled) {
662
+ editor.update(server, (config) => {
663
+ config.disabled = want;
664
+ });
665
+ }
666
+ });
667
+ }
668
+ // The reload awaits the full MCP re-reconcile: a disable detaches
669
+ // the connection and settles status `disabled`; a re-enable starts
670
+ // the connection and resolves only once it has settled
671
+ // (connected / needs_auth / failed).
672
+ await ctx.mcp.reload();
673
+ },
405
674
  // ── sessions ────────────────────────────────────────────────
406
675
  async createSession(input?: {
407
676
  id?: string;
@@ -409,6 +678,7 @@ function implementFacade(
409
678
  agent?: string;
410
679
  model?: FacadeModelRef;
411
680
  metadata?: Record<string, unknown>;
681
+ location?: { directory: string };
412
682
  }) {
413
683
  const info = await ctx.session.create({
414
684
  ...(input?.id !== undefined ? { id: input.id } : {}),
@@ -429,17 +699,20 @@ function implementFacade(
429
699
  // metadata is JSON by the Session.Metadata schema; the facade keeps
430
700
  // it unknown-typed, so the single cast lives here.
431
701
  ...(input?.metadata !== undefined ? { metadata: input.metadata as SessionCreateMetadata } : {}),
702
+ // Target location (opencode v2: boots the target location on
703
+ // first use). Absent → the plugin's own location (the plugin
704
+ // host fills in its own `location.directory`).
705
+ ...(input?.location !== undefined
706
+ ? { location: { directory: input.location.directory } }
707
+ : {}),
432
708
  });
433
709
  return mapSessionInfo(info);
434
710
  },
435
711
  async listSessions() {
436
712
  const { data } = await ctx.session.list();
437
- return data
438
- .filter((s) => String(s.id) !== hiddenSessionID)
439
- .map(mapSessionInfo);
713
+ return data.map(mapSessionInfo);
440
714
  },
441
715
  async getSession(sessionID: string) {
442
- if (sessionID === hiddenSessionID) return null;
443
716
  try {
444
717
  return mapSessionInfo(await ctx.session.get({ sessionID }));
445
718
  } catch {
@@ -493,14 +766,19 @@ function implementFacade(
493
766
  */
494
767
  async *events(signal: AbortSignal) {
495
768
  for await (const event of ctx.event.subscribe({ signal })) {
496
- if (hiddenSessionID !== null && isHiddenSessionEvent(event, hiddenSessionID)) continue;
497
769
  const outcome = mapV2EventRaw(event);
498
770
  if (logEvent !== null) logEvent(eventLogLine(outcome, event, timeStamp(new Date())));
499
771
  if (outcome.status === "ok") yield outcome.event;
500
772
  }
501
773
  },
502
774
  // ── changesets ────────────────────────────────
503
- async vcsDiffWorking() {
775
+ async vcsDiffWorking(directory?: string) {
776
+ // The plugin's own location keeps using `ctx.vcs.diff` (core's
777
+ // location-pinned Vcs service); any other directory uses the
778
+ // direct git fallback (cross-location sessions).
779
+ if (directory !== undefined && directory !== locationDir) {
780
+ return gitWorkingDiff(directory);
781
+ }
504
782
  const root = await gitRepoRoot(locationDir);
505
783
  if (root === null) return []; // not a git repo → no working diff
506
784
  try {
@@ -518,8 +796,9 @@ function implementFacade(
518
796
  return []; // R2: degrade to empty, never throw
519
797
  }
520
798
  },
521
- async gitHeadFile(absPath: string) {
522
- const root = await gitRepoRoot(locationDir);
799
+ async gitHeadFile(absPath: string, directory?: string) {
800
+ const dir = directory ?? locationDir;
801
+ const root = await gitRepoRoot(dir);
523
802
  if (root === null) return null;
524
803
  const rel = repoRelative(root, absPath);
525
804
  if (rel === null) return null;
@@ -539,8 +818,9 @@ function implementFacade(
539
818
  async deleteFile(absPath: string) {
540
819
  await removeFile(absPath);
541
820
  },
542
- async discardFile(absPath: string) {
543
- const root = await gitRepoRoot(locationDir);
821
+ async discardFile(absPath: string, directory?: string) {
822
+ const dir = directory ?? locationDir;
823
+ const root = await gitRepoRoot(dir);
544
824
  const rel = root !== null ? repoRelative(root, absPath) : null;
545
825
  if (root === null || rel === null) {
546
826
  await removeFile(absPath); // not in a repo → just delete
@@ -558,6 +838,64 @@ function implementFacade(
558
838
  await removeFile(absPath); // in the index but not in HEAD → delete
559
839
  }
560
840
  },
841
+ // ── resources ─────────────────────────────────
842
+ // Direct filesystem access for the `resource*` commands (the folder
843
+ // picker's existence check + listing, `resourceMkdir`). Errors are the
844
+ // underlying Node `ErrnoException` — the host maps the `code` to the
845
+ // AHP error codes. No location confinement: the AHP surface is
846
+ // token-authenticated and the client may reference any path it can
847
+ // name (matching the VS Code reference agent host).
848
+ async resolveResource(absPath: string, followSymlinks?: boolean): Promise<FacadeResourceInfo> {
849
+ if (followSymlinks === false) {
850
+ // `lstat` semantics: stat the path itself — a symlink reports as
851
+ // a `symlink`, otherwise its own kind.
852
+ const s = await lstat(absPath);
853
+ return {
854
+ path: absPath,
855
+ type: s.isSymbolicLink() ? "symlink" : s.isDirectory() ? "directory" : "file",
856
+ size: s.size,
857
+ mtime: s.mtimeMs,
858
+ ctime: s.ctimeMs,
859
+ };
860
+ }
861
+ const real = await realpath(absPath); // throws ENOENT/EACCES/… on failure
862
+ const s = await stat(real);
863
+ return {
864
+ path: real,
865
+ type: s.isDirectory() ? "directory" : "file",
866
+ size: s.size,
867
+ mtime: s.mtimeMs,
868
+ ctime: s.ctimeMs,
869
+ };
870
+ },
871
+ async listDirectory(absPath: string): Promise<readonly FacadeDirectoryEntry[]> {
872
+ // `readdir` throws ENOENT (missing), ENOTDIR (not a directory), or
873
+ // EACCES (inaccessible) — the host maps each to the right AHP code.
874
+ const names = await readdir(absPath);
875
+ const entries: FacadeDirectoryEntry[] = [];
876
+ for (const name of names) {
877
+ let type: "file" | "directory" = "file";
878
+ try {
879
+ // `stat` follows symlinks: a symlink-to-directory lists as a
880
+ // directory, a dangling symlink as a file.
881
+ type = (await stat(join(absPath, name))).isDirectory() ? "directory" : "file";
882
+ } catch {
883
+ type = "file"; // unstat'able → file (the name still lists)
884
+ }
885
+ entries.push({ name, type });
886
+ }
887
+ // Directories first, then by name (plain code-unit compare).
888
+ entries.sort((a, b) => {
889
+ if (a.type !== b.type) return a.type === "directory" ? -1 : 1;
890
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
891
+ });
892
+ return entries;
893
+ },
894
+ async mkdirResource(absPath: string): Promise<void> {
895
+ // `mkdir -p`: an existing directory is a no-op success. A path
896
+ // occupied by a non-directory throws EEXIST (→ AlreadyExists).
897
+ await mkdir(absPath, { recursive: true });
898
+ },
561
899
  // ── client-provided tools ───────
562
900
  async syncClientTools(tools: readonly FacadeClientTool[]) {
563
901
  clientTools = [...tools];
@@ -586,7 +924,7 @@ function implementFacade(
586
924
  // (only the outer `execute` call does), so the host could
587
925
  // never see the call to track + relay to the client.
588
926
  // `codemode: false` keeps it out of the catalog and in
589
- // the direct list (live finding 2026-11-08).
927
+ // the direct list.
590
928
  options: { codemode: false },
591
929
  execute: async (_input: unknown, context: ToolContext) => {
592
930
  const host = hostRef.current;
@@ -647,47 +985,24 @@ export default Plugin.define({
647
985
  return; // R2: the opencode server stays up without AHP
648
986
  }
649
987
 
650
- // 3. Keep-alive. Before the host exists, so the anchor
651
- // session's `session.created` fires before the event pump subscribes
652
- // and never reaches AHP clients (the facade filters it from the
653
- // snapshot/list surfaces regardless). A deterministic session ID means
654
- // reloads reuse the same session — no accumulation in the DB.
655
- // start() never throws: on failure the keep-alive stays off and
656
- // opencode's idle timeout applies as before (R2).
657
- const hiddenSessionID = opts.keepAlive ? KEEPALIVE_SESSION_ID : null;
658
- let keepAlive: KeepAlive | null = null;
659
- if (opts.keepAlive) {
660
- keepAlive = new KeepAlive({
661
- // Get-or-create. (Upstream gap: `SessionUpdateInput`
662
- // advertises `archived`, but the plugin host's `session.update`
663
- // drops it — `packages/core/src/plugin/host.ts` forwards only
664
- // title/metadata/permissions, in v2.2.6 and current dev. So the
665
- // anchor cannot be archived from a plugin; it is visible in the
666
- // opencode TUI session list as "opencode-ahp (keep-alive)" and is
667
- // filtered out of every AHP surface by ID instead.)
668
- ensureSession: async () => {
669
- try {
670
- await ctx.session.get({ sessionID: KEEPALIVE_SESSION_ID });
671
- } catch {
672
- await ctx.session.create({
673
- id: KEEPALIVE_SESSION_ID,
674
- title: "opencode-ahp (keep-alive)",
675
- metadata: { "opencode-ahp": "keep-alive" },
676
- });
677
- }
678
- },
679
- touch: () =>
680
- ctx.session.update({
681
- sessionID: KEEPALIVE_SESSION_ID,
682
- metadata: { "opencode-ahp": "keep-alive", keepAliveAt: Date.now() },
683
- }),
684
- intervalMs: opts.keepAliveIntervalMinutes * 60_000,
685
- log: (msg) => console.warn(`${TAG} ${msg}`),
686
- });
687
- await keepAlive.start();
988
+ // 2b. Directory allowlist (the `allowedWorkingDirectories` option,
989
+ // design §3.3): resolve the prefixes (lexically normalized, and
990
+ // symlink-canonicalized when they exist). A non-absolute entry or an
991
+ // existing-but-undecidable prefix is a configuration error: fail
992
+ // closed (AHP off) rather than run unrestricted.
993
+ let pathPolicy: PathPolicy | undefined;
994
+ try {
995
+ const prefixes = await resolveAllowedDirPrefixes(opts.allowedWorkingDirectories);
996
+ pathPolicy =
997
+ prefixes.length > 0
998
+ ? PathPolicy.restricted(prefixes, { resolveExisting: resolveExistingPrefix })
999
+ : undefined;
1000
+ } catch (e) {
1001
+ console.error(`${TAG} invalid allowedWorkingDirectories (${errorMessage(e)}); not starting the AHP host`);
1002
+ return; // R2: the opencode server stays up without AHP
688
1003
  }
689
1004
 
690
- // 4. Host + transport. The host's send/close callbacks close over the
1005
+ // 3. Host + transport. The host's send/close callbacks close over the
691
1006
  // listener variable, which is assigned immediately after the host is
692
1007
  // constructed (the listener's socket ids are the host's socket ids).
693
1008
  let listener: Listener | null = null;
@@ -701,7 +1016,6 @@ export default Plugin.define({
701
1016
  serverInfo: { name: "opencode-ahp", version: pluginVersion(), title: "OpenCode" },
702
1017
  facade: implementFacade(
703
1018
  ctx,
704
- hiddenSessionID,
705
1019
  hostRef,
706
1020
  opts.logEvents ? (line) => console.log(line) : null,
707
1021
  ),
@@ -710,6 +1024,7 @@ export default Plugin.define({
710
1024
  changesets: opts.capabilities.changesets,
711
1025
  terminals: opts.capabilities.terminals,
712
1026
  spawnPty: createBunSpawnPty(),
1027
+ pathPolicy,
713
1028
  send: (socketId, message) => {
714
1029
  listener?.sendTo({ id: socketId }, JSON.stringify(message));
715
1030
  },
@@ -745,7 +1060,7 @@ export default Plugin.define({
745
1060
  onClose: (info) => host.onClose(info.id),
746
1061
  },
747
1062
  );
748
- // 5. Event pump: opencode V2 events → AHP actions (the streaming
1063
+ // 4. Event pump: opencode V2 events → AHP actions (the streaming
749
1064
  // text/reasoning, tool lifecycle, permissions, usage, turn
750
1065
  // terminals, steering/queue handoff).
751
1066
  host.startEventPump();
@@ -761,19 +1076,16 @@ export default Plugin.define({
761
1076
  );
762
1077
  } catch (e) {
763
1078
  console.error(`${TAG} failed to start the AHP listener: ${errorMessage(e)}`);
764
- keepAlive?.stop(); // don't hold the location for a dead AHP host
765
1079
  listener?.stop();
766
1080
  listener = null;
767
1081
  return; // R2: the opencode server stays up without AHP
768
1082
  }
769
1083
 
770
- // 6. Cleanup: stop the keep-alive timer, stop the pump (aborts the
771
- // event subscription), and stop the listener, dropping every client
772
- // connection. Logged because a torn-down listener with no log line
773
- // is otherwise undiagnosable.
1084
+ // 5. Cleanup: stop the pump (aborts the event subscription) and stop
1085
+ // the listener, dropping every client connection. Logged because a
1086
+ // torn-down listener with no log line is otherwise undiagnosable.
774
1087
  return () => {
775
1088
  console.log(`${TAG} location teardown — stopping the AHP host (location unloaded by opencode)`);
776
- keepAlive?.stop();
777
1089
  cleanupHost?.();
778
1090
  listener?.stop();
779
1091
  };