opencode-ahp 0.1.8 → 0.1.10
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 +171 -112
- package/options.example.jsonc +16 -1
- package/package.json +1 -1
- package/src/bridge.ts +355 -13
- package/src/channels.ts +61 -8
- package/src/host-base.ts +42 -5
- package/src/host-changesets.ts +30 -14
- package/src/host-chats.ts +12 -3
- package/src/host-client-tools.ts +20 -1
- package/src/host-dispatch.ts +67 -2
- package/src/host-events.ts +2 -2
- package/src/host-resources.ts +177 -0
- package/src/host-rpc.ts +12 -0
- package/src/host-sessions.ts +367 -32
- package/src/host-terminals.ts +47 -15
- package/src/host-types.ts +18 -1
- package/src/host-util.ts +8 -2
- package/src/host.ts +3 -3
- package/src/index.ts +386 -8
- package/src/options.ts +22 -0
- package/src/path-policy.ts +85 -0
- package/src/transport.ts +11 -2
package/src/host-types.ts
CHANGED
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* Record types shared by the host section classes: the per-socket, per-client, per-session, per-chat and per-terminal state shapes, and the HostOptions the Host is constructed with.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { Implementation } from "@microsoft/agent-host-protocol";
|
|
6
6
|
import { OpencodeFacade } from "./bridge.js";
|
|
7
7
|
import { ClientToolInvocation } from "./client-tools.js";
|
|
8
8
|
import { ChatStateStore, ChangesetStateStore, SessionStateStore, TerminalStateStore } from "./state.js";
|
|
9
|
+
import type { PathPolicy } from "./path-policy.js";
|
|
9
10
|
|
|
10
11
|
// ActionType / ReconnectResultType are `declare const enum` in the package
|
|
11
12
|
// but are also real runtime objects (verified against the published dist),
|
|
@@ -111,6 +112,14 @@ export interface SessionRecord {
|
|
|
111
112
|
defaultChatURI: string;
|
|
112
113
|
/** The session-kind changeset store (owned by the session channel). */
|
|
113
114
|
sessionChangesets: Map<string, ChangesetStateStore>;
|
|
115
|
+
/**
|
|
116
|
+
* The directory the session's agent has tool access to (its
|
|
117
|
+
* `workingDirectories` first entry, or the location directory the
|
|
118
|
+
* session was created in). `undefined` for legacy sessions created
|
|
119
|
+
* before working-directory support — they behave as if they live in
|
|
120
|
+
* the location directory.
|
|
121
|
+
*/
|
|
122
|
+
directory?: string;
|
|
114
123
|
}
|
|
115
124
|
|
|
116
125
|
/**
|
|
@@ -217,6 +226,14 @@ export interface HostOptions {
|
|
|
217
226
|
* entry provides the Bun-backed factory; tests inject a fake.
|
|
218
227
|
*/
|
|
219
228
|
spawnPty?: SpawnPty;
|
|
229
|
+
/**
|
|
230
|
+
* The directory allowlist (the `allowedWorkingDirectories` option,
|
|
231
|
+
* design §3.3): undefined → unrestricted. When restricted, a
|
|
232
|
+
* client-named path must resolve under one of the prefixes (after
|
|
233
|
+
* symlink resolution) — the `createSession.workingDirectories` target
|
|
234
|
+
* and the unconfined `resource*` commands; a denial is a flat -32009.
|
|
235
|
+
*/
|
|
236
|
+
pathPolicy?: PathPolicy;
|
|
220
237
|
/** Deliver a JSON-serializable frame to a connection. */
|
|
221
238
|
send: (socketId: number, message: unknown) => void;
|
|
222
239
|
/** Close one connection (a superseded duplicate clientId). */
|
package/src/host-util.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { resolve as resolvePath } from "node:path";
|
|
|
6
6
|
import { ToolResultContentType, SessionActiveClient, StringOrMarkdown, ToolCallResult, ToolResultContent } from "@microsoft/agent-host-protocol";
|
|
7
7
|
import { FacadeClientToolResult, FacadeModelRef, FacadeToolContent } from "./bridge.js";
|
|
8
8
|
import { normalizeToolDefinitions } from "./client-tools.js";
|
|
9
|
-
import { channelKind } from "./channels.js";
|
|
9
|
+
import { channelKind, isSessionChannel } from "./channels.js";
|
|
10
10
|
import { isRecord } from "./options.js";
|
|
11
11
|
|
|
12
12
|
/**
|
|
@@ -69,7 +69,10 @@ export function parseAhpMarker(metadata: unknown): { chat?: string; owner?: stri
|
|
|
69
69
|
const owner = marker["owner"];
|
|
70
70
|
if (typeof owner === "string" && owner.startsWith("ses")) out.owner = owner;
|
|
71
71
|
const channel = marker["channel"];
|
|
72
|
-
|
|
72
|
+
// isSessionChannel, not channelKind === "session": a session created
|
|
73
|
+
// on a non-standard (legacy) channel must resurface under the ORIGINAL
|
|
74
|
+
// channel after a restart, not fall back to the opencode id.
|
|
75
|
+
if (typeof channel === "string" && isSessionChannel(channel)) out.channel = channel;
|
|
73
76
|
return Object.keys(out).length > 0 ? out : null;
|
|
74
77
|
}
|
|
75
78
|
|
|
@@ -188,5 +191,8 @@ export function mapToolResultContent(content: readonly { type: string; text?: st
|
|
|
188
191
|
export function isPathInside(child: string, parent: string): boolean {
|
|
189
192
|
const a = resolvePath(child);
|
|
190
193
|
const b = resolvePath(parent);
|
|
194
|
+
// The root contains every absolute path (the `b + "/"` join would
|
|
195
|
+
// otherwise compare against `"//"`).
|
|
196
|
+
if (b === "/") return a === "/" || a.startsWith("/");
|
|
191
197
|
return a === b || a.startsWith(b + "/");
|
|
192
198
|
}
|
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-
|
|
42
|
-
* host-
|
|
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,6 +14,8 @@
|
|
|
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
|
+
* 2b. directory allowlist (optional): a misconfigured
|
|
18
|
+
* `allowedWorkingDirectories` fails closed (AHP off, R2)
|
|
17
19
|
* 3. wire the Host (JSON-RPC router) to the transport (Bun.serve)
|
|
18
20
|
* 4. start the opencode event pump (maps `ctx.event.subscribe` into
|
|
19
21
|
* the host's AHP action stream)
|
|
@@ -23,9 +25,18 @@
|
|
|
23
25
|
* bridge error must never take down the opencode server (R2).
|
|
24
26
|
*/
|
|
25
27
|
import { execFile } from "node:child_process";
|
|
26
|
-
import {
|
|
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";
|
|
27
38
|
import { dirname, isAbsolute, join, relative } from "node:path";
|
|
28
|
-
import { readFileSync } from "node:fs";
|
|
39
|
+
import { createReadStream, readFileSync } from "node:fs";
|
|
29
40
|
import { fileURLToPath } from "node:url";
|
|
30
41
|
import { promisify } from "node:util";
|
|
31
42
|
import { Plugin } from "@opencode/plugin";
|
|
@@ -48,6 +59,7 @@ type SessionInfo = Awaited<ReturnType<SessionDomain["get"]>>;
|
|
|
48
59
|
*/
|
|
49
60
|
type SessionCreateMetadata = NonNullable<Parameters<SessionDomain["create"]>[0]>["metadata"];
|
|
50
61
|
import { isRecord, resolveOptions, type Options } from "./options.js";
|
|
62
|
+
import { normalizeDirPrefix, PathPolicy } from "./path-policy.js";
|
|
51
63
|
import { createListener, type Listener } from "./transport.js";
|
|
52
64
|
import { Host } from "./host.js";
|
|
53
65
|
import type { SpawnPty } from "./host-types.js";
|
|
@@ -58,9 +70,15 @@ import {
|
|
|
58
70
|
timeStamp,
|
|
59
71
|
type FacadeAgent,
|
|
60
72
|
type FacadeClientTool,
|
|
73
|
+
type FacadeDirectoryEntry,
|
|
74
|
+
type FacadeDiffFile,
|
|
75
|
+
type FacadeMcpServer,
|
|
61
76
|
type FacadeModel,
|
|
62
77
|
type FacadeModelRef,
|
|
78
|
+
type FacadeResourceInfo,
|
|
63
79
|
type FacadeSession,
|
|
80
|
+
type FacadeSkill,
|
|
81
|
+
type FacadeTool,
|
|
64
82
|
type OpencodeFacade,
|
|
65
83
|
} from "./bridge.js";
|
|
66
84
|
import { normalizedName } from "./client-tools.js";
|
|
@@ -240,6 +258,12 @@ function mapSessionInfo(info: SessionInfo): FacadeSession {
|
|
|
240
258
|
// Durable, core-opaque metadata: the host reads its
|
|
241
259
|
// `opencode-ahp` chat-binding marker from it on external registration.
|
|
242
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
|
+
: {}),
|
|
243
267
|
time: { created: info.time.created, updated: info.time.updated },
|
|
244
268
|
};
|
|
245
269
|
}
|
|
@@ -282,6 +306,207 @@ function isEnoent(err: unknown): boolean {
|
|
|
282
306
|
return (err as NodeJS.ErrnoException | null)?.code === "ENOENT";
|
|
283
307
|
}
|
|
284
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
|
+
|
|
285
510
|
/**
|
|
286
511
|
* The narrow opencode surface the bridge needs.
|
|
287
512
|
*
|
|
@@ -324,6 +549,14 @@ function implementFacade(
|
|
|
324
549
|
let clientTools: FacadeClientTool[] = [];
|
|
325
550
|
let clientToolsTransformRegistered = false;
|
|
326
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
|
+
|
|
327
560
|
const readTextFile = async (absPath: string): Promise<string | null> => {
|
|
328
561
|
try {
|
|
329
562
|
return await fsReadFile(absPath, "utf-8");
|
|
@@ -384,6 +617,60 @@ function implementFacade(
|
|
|
384
617
|
hidden: a.hidden,
|
|
385
618
|
}));
|
|
386
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
|
+
},
|
|
387
674
|
// ── sessions ────────────────────────────────────────────────
|
|
388
675
|
async createSession(input?: {
|
|
389
676
|
id?: string;
|
|
@@ -391,6 +678,7 @@ function implementFacade(
|
|
|
391
678
|
agent?: string;
|
|
392
679
|
model?: FacadeModelRef;
|
|
393
680
|
metadata?: Record<string, unknown>;
|
|
681
|
+
location?: { directory: string };
|
|
394
682
|
}) {
|
|
395
683
|
const info = await ctx.session.create({
|
|
396
684
|
...(input?.id !== undefined ? { id: input.id } : {}),
|
|
@@ -411,6 +699,12 @@ function implementFacade(
|
|
|
411
699
|
// metadata is JSON by the Session.Metadata schema; the facade keeps
|
|
412
700
|
// it unknown-typed, so the single cast lives here.
|
|
413
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
|
+
: {}),
|
|
414
708
|
});
|
|
415
709
|
return mapSessionInfo(info);
|
|
416
710
|
},
|
|
@@ -478,7 +772,13 @@ function implementFacade(
|
|
|
478
772
|
}
|
|
479
773
|
},
|
|
480
774
|
// ── changesets ────────────────────────────────
|
|
481
|
-
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
|
+
}
|
|
482
782
|
const root = await gitRepoRoot(locationDir);
|
|
483
783
|
if (root === null) return []; // not a git repo → no working diff
|
|
484
784
|
try {
|
|
@@ -496,8 +796,9 @@ function implementFacade(
|
|
|
496
796
|
return []; // R2: degrade to empty, never throw
|
|
497
797
|
}
|
|
498
798
|
},
|
|
499
|
-
async gitHeadFile(absPath: string) {
|
|
500
|
-
const
|
|
799
|
+
async gitHeadFile(absPath: string, directory?: string) {
|
|
800
|
+
const dir = directory ?? locationDir;
|
|
801
|
+
const root = await gitRepoRoot(dir);
|
|
501
802
|
if (root === null) return null;
|
|
502
803
|
const rel = repoRelative(root, absPath);
|
|
503
804
|
if (rel === null) return null;
|
|
@@ -517,8 +818,9 @@ function implementFacade(
|
|
|
517
818
|
async deleteFile(absPath: string) {
|
|
518
819
|
await removeFile(absPath);
|
|
519
820
|
},
|
|
520
|
-
async discardFile(absPath: string) {
|
|
521
|
-
const
|
|
821
|
+
async discardFile(absPath: string, directory?: string) {
|
|
822
|
+
const dir = directory ?? locationDir;
|
|
823
|
+
const root = await gitRepoRoot(dir);
|
|
522
824
|
const rel = root !== null ? repoRelative(root, absPath) : null;
|
|
523
825
|
if (root === null || rel === null) {
|
|
524
826
|
await removeFile(absPath); // not in a repo → just delete
|
|
@@ -536,6 +838,64 @@ function implementFacade(
|
|
|
536
838
|
await removeFile(absPath); // in the index but not in HEAD → delete
|
|
537
839
|
}
|
|
538
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
|
+
},
|
|
539
899
|
// ── client-provided tools ───────
|
|
540
900
|
async syncClientTools(tools: readonly FacadeClientTool[]) {
|
|
541
901
|
clientTools = [...tools];
|
|
@@ -564,7 +924,7 @@ function implementFacade(
|
|
|
564
924
|
// (only the outer `execute` call does), so the host could
|
|
565
925
|
// never see the call to track + relay to the client.
|
|
566
926
|
// `codemode: false` keeps it out of the catalog and in
|
|
567
|
-
// the direct list
|
|
927
|
+
// the direct list.
|
|
568
928
|
options: { codemode: false },
|
|
569
929
|
execute: async (_input: unknown, context: ToolContext) => {
|
|
570
930
|
const host = hostRef.current;
|
|
@@ -625,6 +985,23 @@ export default Plugin.define({
|
|
|
625
985
|
return; // R2: the opencode server stays up without AHP
|
|
626
986
|
}
|
|
627
987
|
|
|
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
|
|
1003
|
+
}
|
|
1004
|
+
|
|
628
1005
|
// 3. Host + transport. The host's send/close callbacks close over the
|
|
629
1006
|
// listener variable, which is assigned immediately after the host is
|
|
630
1007
|
// constructed (the listener's socket ids are the host's socket ids).
|
|
@@ -647,6 +1024,7 @@ export default Plugin.define({
|
|
|
647
1024
|
changesets: opts.capabilities.changesets,
|
|
648
1025
|
terminals: opts.capabilities.terminals,
|
|
649
1026
|
spawnPty: createBunSpawnPty(),
|
|
1027
|
+
pathPolicy,
|
|
650
1028
|
send: (socketId, message) => {
|
|
651
1029
|
listener?.sendTo({ id: socketId }, JSON.stringify(message));
|
|
652
1030
|
},
|
package/src/options.ts
CHANGED
|
@@ -35,6 +35,15 @@ export interface Options {
|
|
|
35
35
|
token: string | null;
|
|
36
36
|
/** Origin allowlist; the token is always required regardless. */
|
|
37
37
|
allowedOrigins: string[] | "*";
|
|
38
|
+
/**
|
|
39
|
+
* Directory allowlist — absolute path prefixes (design §3.3). Empty
|
|
40
|
+
* (default) → unrestricted. Non-empty: a client-named path must resolve
|
|
41
|
+
* under one of the prefixes (after symlink resolution) — the
|
|
42
|
+
* `createSession.workingDirectories` target and the unconfined
|
|
43
|
+
* `resource*` commands. A non-absolute entry is a configuration error:
|
|
44
|
+
* the host fails closed (AHP off).
|
|
45
|
+
*/
|
|
46
|
+
allowedWorkingDirectories: string[];
|
|
38
47
|
/** Native TLS via Bun.serve on the same listener (off-LAN). */
|
|
39
48
|
tls: TlsOptions | null;
|
|
40
49
|
/** Plain-HTTP health endpoint (no auth). */
|
|
@@ -59,6 +68,9 @@ export const BUILTIN_OPTIONS: Options = {
|
|
|
59
68
|
path: "/ahp",
|
|
60
69
|
token: null,
|
|
61
70
|
allowedOrigins: "*",
|
|
71
|
+
// No restriction by default (an opt-in hardening); a non-absolute entry
|
|
72
|
+
// is a configuration error the plugin entry fails closed on.
|
|
73
|
+
allowedWorkingDirectories: [],
|
|
62
74
|
tls: null,
|
|
63
75
|
healthPath: "/healthz",
|
|
64
76
|
replayWindow: 1000,
|
|
@@ -95,6 +107,13 @@ function validateAllowedOrigins(v: unknown): string[] | "*" | null {
|
|
|
95
107
|
return null;
|
|
96
108
|
}
|
|
97
109
|
|
|
110
|
+
/** A directory-allowlist value: an array of non-empty strings. */
|
|
111
|
+
function validateAllowedDirs(v: unknown): string[] | null {
|
|
112
|
+
if (!Array.isArray(v)) return null;
|
|
113
|
+
if (!v.every((x) => typeof x === "string" && x.length > 0)) return null;
|
|
114
|
+
return [...v];
|
|
115
|
+
}
|
|
116
|
+
|
|
98
117
|
function validateTls(v: unknown): TlsOptions | null {
|
|
99
118
|
if (!isRecord(v) || !isString(v["keyPath"]) || !isString(v["certPath"])) return null;
|
|
100
119
|
return { keyPath: v["keyPath"], certPath: v["certPath"] };
|
|
@@ -236,6 +255,9 @@ export function resolveOptions(
|
|
|
236
255
|
allowedOrigins:
|
|
237
256
|
pickNullable("allowedOrigins", validateAllowedOrigins, BUILTIN_OPTIONS.allowedOrigins) ??
|
|
238
257
|
BUILTIN_OPTIONS.allowedOrigins,
|
|
258
|
+
allowedWorkingDirectories:
|
|
259
|
+
pickNullable("allowedWorkingDirectories", validateAllowedDirs, BUILTIN_OPTIONS.allowedWorkingDirectories) ??
|
|
260
|
+
BUILTIN_OPTIONS.allowedWorkingDirectories,
|
|
239
261
|
tls: pickNullable("tls", validateTls, BUILTIN_OPTIONS.tls),
|
|
240
262
|
healthPath: pick("healthPath", isUrlPath, BUILTIN_OPTIONS.healthPath),
|
|
241
263
|
replayWindow: pick("replayWindow", isPosInt, BUILTIN_OPTIONS.replayWindow),
|