@theokit/sdk 4.55.0 → 4.56.0
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/CHANGELOG.md +63 -0
- package/dist/a2a/index.cjs +13 -4
- package/dist/a2a/index.cjs.map +1 -1
- package/dist/a2a/index.d.cts +1 -1
- package/dist/a2a/index.d.ts +1 -1
- package/dist/a2a/index.js +13 -5
- package/dist/a2a/index.js.map +1 -1
- package/dist/a2a/message-bus.d.cts +33 -4
- package/dist/a2a/message-bus.d.ts +33 -4
- package/dist/{agent-HDEVVUBS.js → agent-K3PQBS7D.js} +6 -5
- package/dist/{agent-HDEVVUBS.js.map → agent-K3PQBS7D.js.map} +1 -1
- package/dist/{agent-R2HOJFZJ.cjs → agent-PJMBK7HQ.cjs} +7 -6
- package/dist/{agent-R2HOJFZJ.cjs.map → agent-PJMBK7HQ.cjs.map} +1 -1
- package/dist/{chunk-5UOVYM3P.cjs → chunk-6VLKVX7O.cjs} +131 -54
- package/dist/chunk-6VLKVX7O.cjs.map +1 -0
- package/dist/{chunk-5PHVENFV.js → chunk-7FHZ4VQX.js} +3 -55
- package/dist/chunk-7FHZ4VQX.js.map +1 -0
- package/dist/{chunk-Q47R5E2X.cjs → chunk-E3WZ6Y4H.cjs} +7 -59
- package/dist/chunk-E3WZ6Y4H.cjs.map +1 -0
- package/dist/{chunk-ITSSOVOB.cjs → chunk-H5GOSXSC.cjs} +4 -4
- package/dist/{chunk-ITSSOVOB.cjs.map → chunk-H5GOSXSC.cjs.map} +1 -1
- package/dist/{chunk-I5BE5M5L.js → chunk-KBXWEWKS.js} +4 -4
- package/dist/{chunk-I5BE5M5L.js.map → chunk-KBXWEWKS.js.map} +1 -1
- package/dist/chunk-KRD3GQAA.cjs +71 -0
- package/dist/chunk-KRD3GQAA.cjs.map +1 -0
- package/dist/chunk-KVNWIAO4.js +68 -0
- package/dist/chunk-KVNWIAO4.js.map +1 -0
- package/dist/{chunk-F5WMX4EA.cjs → chunk-LQYQHXIW.cjs} +19 -19
- package/dist/{chunk-F5WMX4EA.cjs.map → chunk-LQYQHXIW.cjs.map} +1 -1
- package/dist/{chunk-IVNNSANC.js → chunk-M7UHYBEY.js} +3 -3
- package/dist/{chunk-IVNNSANC.js.map → chunk-M7UHYBEY.js.map} +1 -1
- package/dist/{chunk-DAPSQZT4.js → chunk-ODTZ7HX3.js} +131 -54
- package/dist/chunk-ODTZ7HX3.js.map +1 -0
- package/dist/context/index.cjs +6 -5
- package/dist/context/index.cjs.map +1 -1
- package/dist/context/index.js +3 -2
- package/dist/context/index.js.map +1 -1
- package/dist/cron.cjs +6 -5
- package/dist/cron.js +5 -4
- package/dist/eval.cjs +5 -4
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +4 -3
- package/dist/eval.js.map +1 -1
- package/dist/{index-manager-ZMRJ6ZII.js → index-manager-WBIMDVQT.js} +4 -3
- package/dist/{index-manager-ZMRJ6ZII.js.map → index-manager-WBIMDVQT.js.map} +1 -1
- package/dist/{index-manager-NG5YENWO.cjs → index-manager-WC5ZVJWO.cjs} +5 -4
- package/dist/{index-manager-NG5YENWO.cjs.map → index-manager-WC5ZVJWO.cjs.map} +1 -1
- package/dist/index.cjs +28 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +8 -7
- package/dist/index.js.map +1 -1
- package/dist/internal/memory/storage/markdown-store.d.ts +14 -2
- package/dist/internal/memory/storage/memory-file.d.ts +54 -0
- package/dist/internal/memory/types.d.ts +28 -0
- package/dist/sandbox/index.cjs +1 -1
- package/dist/sandbox/index.cjs.map +1 -1
- package/dist/sandbox/index.js +1 -1
- package/dist/sandbox/index.js.map +1 -1
- package/docs/error-codes.md +3 -1
- package/docs/harness-capability-map.md +2 -1
- package/package.json +1 -1
- package/dist/chunk-5PHVENFV.js.map +0 -1
- package/dist/chunk-5UOVYM3P.cjs.map +0 -1
- package/dist/chunk-DAPSQZT4.js.map +0 -1
- package/dist/chunk-Q47R5E2X.cjs.map +0 -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,CAAE,CAAA;AAAA,EACjF;AAEA,EAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,OAAA;AAAA,IACxB,CAAA,OAAA,EAAU,gBAAA,CAAiB,UAAU,CAAC,CAAA,0BAAA;AAAA,GACxC;AACA,EAAA,IAAI,GAAA,CAAI,aAAa,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,mBAAmB,UAAA,EAAY,CAAA,wBAAA,EAA2B,IAAI,MAAA,CAAO,IAAA,EAAM,CAAA,CAAE,CAAA;AAAA,EACzF;AACA,EAAA,MAAM,OAAA,GAAU,GAAA,CAAI,MAAA,CAAO,IAAA,EAAK;AAGhC,EAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,OAAA;AAAA,IAC7B,UAAU,gBAAA,CAAiB,OAAO,CAAC,CAAA,kBAAA,EAAqB,gBAAA,CAAiB,GAAG,CAAC,CAAA;AAAA,GAC/E;AACA,EAAA,IAAI,QAAA,CAAS,aAAa,CAAA,EAAG;AAC3B,IAAA,MAAM,IAAI,kBAAA,CAAmB,UAAA,EAAY,CAAA,SAAA,EAAY,GAAG,YAAY,QAAA,CAAS,MAAA,CAAO,IAAA,EAAM,CAAA,CAAE,CAAA;AAAA,EAC9F;AAEA,EAAA,OAAO,EAAE,OAAA,EAAQ;AACnB","file":"index.js","sourcesContent":["// Promoted out of the agent-builder in M75 (plan m75-sandbox-kernel-no-framework, D1): kernel\n// confinement is framework infrastructure, not the consumer's. Measured cost of the promotion: ZERO\n// dependencies — only node:child_process, node:fs and node:path. The cBPF filter is a pure-JS Buffer.\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/*\n * M53 — bubblewrap argv + honest detection.\n *\n * HONEST SCOPE: filesystem confinement + network isolation via bwrap, PLUS the second stage —\n * a cBPF seccomp syscall filter (`agents/sandbox/seccomp.ts`), wired in `agents/sandbox/backend.ts`\n * via `restrictedSeccompPath()`. Ported in M63; this block claimed the opposite until M67 and\n * UNDER-DECLARED the real security posture. The honest limit that remains: the filter is **x86_64**\n * (an architecture guard refuses to install it on any other arch, with a WARN, and bwrap's FS/network\n * confinement still applies) **and** it is only installed when the network is restricted\n * (`backend.ts:87`, faithful to `landlock.rs:96-117`): with the network on there is no syscall\n * filter, only bwrap's FS confinement. `danger-full-access` skips bwrap entirely, mirroring\n * `bwrap.rs:245-252`. Deltas versus Codex remain documented in docs/CODEX-PARITY.md.\n */\n\n/**\n * Codex's three canonical modes. Defined HERE because they are sandbox vocabulary, not consumer\n * configuration: `danger-full-access` means \"do not wrap\", and that is a decision belonging to the\n * confinement subsystem.\n */\nexport type SandboxMode = \"read-only\" | \"workspace-write\" | \"danger-full-access\";\n\n/**\n * The RW binds `workspace-write` installs (protocol.rs:1189-1214), plus the metadata protection that\n * must sit ON TOP of them — order matters (permissions.rs:22-31; bwrap.rs:571-597).\n */\nfunction pushWorkspaceBinds(argv: string[], cwd: string, hasGit: boolean, gitDir: string): void {\n for (const root of workspaceWriteRoots(cwd)) argv.push(\"--bind\", root, root);\n if (hasGit) argv.push(\"--ro-bind\", gitDir, gitDir);\n}\n\n/** The RW binds `workspace-write` installs (protocol.rs:1189-1214): the workspace itself, and /tmp. */\nfunction workspaceWriteRoots(cwd: string): readonly string[] {\n return [cwd, \"/tmp\"];\n}\n\n/**\n * U-6 — the roots a mode may write to, answerable WITHOUT spawning anything.\n *\n * `[]` means nothing is writable; `null` means unrestricted — which is not the same as `[\"/\"]`,\n * because unrestricted is the absence of a root rather than a root that happens to be `/`.\n *\n * The SDK already knew this: `buildBwrapArgv` binds these exact paths. It only knew it while\n * BUILDING an argv, and a consumer needs the answer earlier — tools are scoped at agent\n * construction, before any process exists, and a file-write tool has to be told its root then. With\n * nothing to ask, consumers keep a second encoding of this three-mode vocabulary and it drifts from\n * the argv builder with nothing to catch it. This reads from the same helper the builder uses, so\n * the two cannot disagree.\n */\nexport function writableRootsFor(mode: SandboxMode, cwd: string): readonly string[] | null {\n switch (mode) {\n case \"read-only\":\n return [];\n case \"workspace-write\":\n return workspaceWriteRoots(cwd);\n case \"danger-full-access\":\n return null;\n }\n}\n\n/**\n * Everything {@link buildBwrapArgv} needs besides the {@link SandboxMode}.\n *\n * Only `cwd` is required, and it is resolved to an absolute path before any bind\n * is emitted. The defaults are the restrictive ones in one direction and the\n * permissive one in the other: omitting `network` emits `--unshare-net` (no\n * network), while omitting `env` means the child INHERITS the parent\n * environment — bwrap only clears it when an allowlist is supplied.\n */\nexport interface BwrapArgvOptions {\n /** Workspace root — the single RW bind under `workspace-write` (protocol.rs:1189-1200). */\n cwd: string;\n /** `true` removes `--unshare-net` (policy `network_access`, default false). */\n network?: boolean;\n /** Injectable for tests; defaults to a real `existsSync` check on `<cwd>/.git`. */\n gitDirExists?: boolean;\n /**\n * When present, emit `--clearenv` and re-inject ONLY these vars (Codex env_clear model,\n * `exec_env.rs:25-31`). Closes the denylist gap: a secret in an oddly-named var never reaches the\n * sandboxed child. Omitted ⇒ inherit the parent env (backward-compatible; SDK scrub still applies).\n */\n env?: Record<string, string>;\n}\n\n/**\n * Pure argv builder. Returns the bwrap flags ending in `--` (caller appends `/bin/sh -c <cmd>`),\n * or `null` when the policy skips the sandbox entirely (`danger-full-access`).\n */\nexport function buildBwrapArgv(mode: SandboxMode, opts: BwrapArgvOptions): string[] | null {\n if (mode === \"danger-full-access\") return null; // bwrap skipped entirely (bwrap.rs:245-252)\n\n const cwd = path.resolve(opts.cwd);\n const gitDir = path.join(cwd, \".git\");\n const hasGit = opts.gitDirExists ?? existsSync(gitDir);\n\n const argv: string[] = [\n // core, always (bwrap.rs:318-332; user+pid namespaces explicit so it works as root in containers)\n \"--new-session\",\n \"--die-with-parent\",\n \"--unshare-user\",\n \"--unshare-pid\",\n // full-read filesystem base (bwrap.rs:446-452)\n \"--ro-bind\",\n \"/\",\n \"/\",\n \"--dev\",\n \"/dev\",\n \"--proc\",\n \"/proc\",\n ];\n\n if (!opts.network) argv.push(\"--unshare-net\"); // network off by default (bwrap.rs:325-327)\n\n // env confinement — `--clearenv` MUST precede every `--setenv` or the clear wipes them\n // (exec_env.rs:25-31 clears then rebuilds). Only when an explicit allowlist is provided.\n if (opts.env) argv.push(\"--clearenv\");\n const setenv: Record<string, string> = {\n ...(opts.env ?? {}),\n // the flag signals the child that network is unshared (spawn.rs:20,79)\n ...(opts.network ? {} : { CODEX_SANDBOX_NETWORK_DISABLED: \"1\" }),\n };\n for (const [k, v] of Object.entries(setenv)) argv.push(\"--setenv\", k, v);\n\n if (mode === \"workspace-write\") pushWorkspaceBinds(argv, cwd, hasGit, gitDir);\n // read-only: zero writable roots (protocol.rs:1176) — nothing to add\n\n argv.push(\"--chdir\", cwd, \"--\");\n return argv;\n}\n\n/** Injectable probes — each mirrors one Codex availability check. */\nexport interface BwrapProbes {\n /** `which bwrap` outside the cwd (anti-hijack, sandboxing/src/bwrap.rs:168-191). */\n which: () => string | null;\n /** `bwrap --help` text — must advertise `--perms` (launcher.rs:108-124). */\n helpText: (bin: string) => string | null;\n /** Active user-namespace probe with timeout (sandboxing/src/bwrap.rs:74-136). */\n userns: (bin: string) => boolean;\n}\n\n/**\n * Result of {@link detectBwrap} / {@link detectBwrapMemoized}, discriminated on\n * `ok`: `{ ok: true, bin }` carries the absolute path of the validated `bwrap`,\n * `{ ok: false, reason }` a human-readable cause — \"bwrap not found in PATH\",\n * \"bwrap at <bin> lacks --perms support (too old)\",\n * \"user namespaces unavailable (container/kernel restriction)\",\n * \"bwrap probe failed: <err>\", or (memoized only)\n * \"bwrap disappeared from <bin> after detection\".\n *\n * `reason` is prose for a warning line. It is not a stable code — do not branch\n * on it.\n *\n * `ok: false` is an ordinary outcome rather than an error: bubblewrap is\n * Linux-only, so failing detection on macOS, on Windows, or inside a container\n * without user namespaces is expected. Detection NEVER throws, so wrapping it in\n * `try`/`catch` catches nothing; callers warn and fall back to an unconfined\n * `LocalSandbox`.\n */\nexport type BwrapDetection = { ok: true; bin: string } | { ok: false; reason: string };\n\n/** Honest detection — fail-closed on every probe; NEVER throws (callers WARN + fall back). */\nexport function detectBwrap(probes: BwrapProbes = realProbes): BwrapDetection {\n try {\n const bin = probes.which();\n if (!bin) return { ok: false, reason: \"bwrap not found in PATH\" };\n const help = probes.helpText(bin);\n if (!help?.includes(\"--perms\")) {\n return { ok: false, reason: `bwrap at ${bin} lacks --perms support (too old)` };\n }\n if (!probes.userns(bin)) {\n return { ok: false, reason: \"user namespaces unavailable (container/kernel restriction)\" };\n }\n return { ok: true, bin };\n } catch (err) {\n return {\n ok: false,\n reason: `bwrap probe failed: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n}\n\n/**\n * How many times the REAL probe ran in this process.\n *\n * Instrumented here rather than in a wrapper, because this is where the cost is: every `which`\n * spawns a subprocess (`which bwrap`), and the full probe cost 22.2 ms. A gate counting INJECTED\n * probes does not see the real one — that was the M71 gate's first mistake, and a mutant exposed it.\n */\nlet realProbeRuns = 0;\n\n/** How many real probes ran. TEST seam — the performance gate counts this. */\nexport function realProbeCount(): number {\n return realProbeRuns;\n}\n\n/** Real probes used in production. */\nexport const realProbes: BwrapProbes = {\n which: () => {\n realProbeRuns++;\n try {\n const out = execFileSync(\"which\", [\"bwrap\"], { encoding: \"utf8\", timeout: 2_000 }).trim();\n // anti-hijack: never accept a bwrap that lives inside the workspace (bwrap.rs:168-191)\n if (!out || out.startsWith(process.cwd() + path.sep)) return null;\n return out;\n } catch {\n return null;\n }\n },\n helpText: (bin) => {\n try {\n // bwrap --help exits 0/1 depending on version; capture output either way\n return execFileSync(bin, [\"--help\"], { encoding: \"utf8\", timeout: 2_000 });\n } catch (err) {\n const e = err as { stdout?: string; stderr?: string };\n return [e.stdout, e.stderr].filter(Boolean).join(\"\\n\") || null;\n }\n },\n userns: (bin) => {\n try {\n // active probe, 500ms budget like Codex (sandboxing/src/bwrap.rs:74-136)\n execFileSync(bin, [\"--unshare-user\", \"--unshare-net\", \"--ro-bind\", \"/\", \"/\", \"/bin/true\"], {\n timeout: 500,\n stdio: \"ignore\",\n });\n return true;\n } catch {\n return false;\n }\n },\n};\n\n/**\n * The probe result, memoized for the lifetime of the PROCESS.\n *\n * Measured before M71: `detectBwrap()` costs **22.2 ms** and was not memoized — the second call\n * cost 19.4 ms. `buildChatAgent` on the headless path fired **two** (one from\n * `createSandboxBackend`, another from `resolveSandboxPosture`, which M70 added), totalling 46.4 ms\n * per construction — and construction happens per turn. Under `strace`, ~90% of the 182 syscalls of\n * an already-warm construction came from here: `which` sweeping the PATH, `/proc/filesystems`,\n * `/newroot`, and the `.so` files the two probe subprocesses load.\n *\n * ## Why there is no invalidation\n *\n * The milestone called for invalidating on `SessionStart`. That does not work:\n * `agents/lib/hooks/hooks.ts:28-30` documents — as a **measured** correction of an earlier\n * assumption — that the event fires **once per TURN**, not per session. Invalidating there would\n * re-probe every turn, exactly the behavior memoization exists to eliminate.\n *\n * A write-once cache is sufficient here: the expensive probe runs once per process,\n * only to print a UI warning.\n *\n * **The price, stated plainly — in BOTH directions.** The original m71-cost-per-turn#ADR-1 declared\n * only one of them; the M71 review (F-perf-9) showed the omitted one was precisely the one with a\n * security consequence:\n *\n * - **Stale negative** (`bwrap` installed AFTERWARDS): not detected until restart. The system fails\n * CLOSED — the posture reports `enforced: false` and M70's veto **refuses**. Cost: annoyance (the\n * message tells you to install the bwrap you just installed). Accepted.\n * - **Stale positive** (`bwrap` removed/renamed AFTERWARDS): the posture would keep asserting\n * `enforced: true / \"kernel (bwrap)\"` and the veto would **approve**, citing a confinement that no\n * longer exists. That is the literal reintroduction of the defect M70 fixed — *\"telling the\n * operator they are protected when they are not is worse than saying nothing\"*. Before M71 the\n * per-turn re-probe closed that window on the next turn; memoization would leave it open for the\n * whole process. **That is why the positive is revalidated** below, at 1 syscall — 3 orders of\n * magnitude below the 22.2 ms of the full probe, which is the cost memoization exists to remove.\n */\nlet memo: BwrapDetection | undefined;\n\n/**\n * `detectBwrap` with memoization — what production should call.\n *\n * Note that `detectBwrap` itself does **not** memoize, on purpose: it accepts injected probes, and\n * memoizing there would let a test with fake probes poison the process cache for everyone else.\n *\n * Revalidating the positive is NOT a re-probe: `detectBwrap` spends three probes (a `which`\n * subprocess + `--help` + a user namespace). Here we only confirm the validated binary is still in\n * place. If it vanished, the memo is downgraded to a negative with the reason stated — never\n * promoted to a positive, which would require the expensive probe back.\n */\nexport function detectBwrapMemoized(probes: BwrapProbes = realProbes): BwrapDetection {\n memo ??= detectBwrap(probes);\n if (memo.ok && !existsSync(memo.bin)) {\n memo = { ok: false, reason: `bwrap disappeared from ${memo.bin} after detection` };\n }\n return memo;\n}\n\n/** TEST seam — clears the memo. Production never calls it (see m71-cost-per-turn#ADR-1). */\nexport function resetBwrapMemo(): void {\n memo = undefined;\n}\n","// Promoted from agent-builder in M75 (plan m75-sandbox-kernel-no-framework, D1): confinement with\n// kernel confinement is framework infrastructure, not the consumer's. Measured cost of the promotion: ZERO\n// no dependencies — only node:child_process, node:fs and node:path. The cBPF filter is a Buffer in pure JS.\n\n/**\n * M63 — cBPF seccomp filter generator. Produces a raw `sock_filter[]` program (the exact\n * shape `bwrap --seccomp <fd>` consumes) so syscall confinement needs no\n * native helper — bwrap applies `PR_SET_NO_NEW_PRIVS` + the filter before `execve`.\n *\n * Semantics (landlock.rs:252-253): default action = ALLOW; per-syscall match = ERRNO(EPERM). KILL is\n * used ONLY by the architecture/x32 guard. x86_64 only in v1 (aarch64 is a documented delta).\n */\n\n// BPF opcodes (linux/bpf_common.h)\nconst BPF_LD = 0x00;\nconst BPF_W = 0x00;\nconst BPF_ABS = 0x20;\nconst BPF_JMP = 0x05;\nconst BPF_JEQ = 0x10;\nconst BPF_JGE = 0x30;\nconst BPF_K = 0x00;\nconst BPF_RET = 0x06;\n\nconst LD_ABS_W = BPF_LD | BPF_W | BPF_ABS; // 0x20\nconst JEQ_K = BPF_JMP | BPF_JEQ | BPF_K; // 0x15\nconst JGE_K = BPF_JMP | BPF_JGE | BPF_K; // 0x35\nconst RET_K = BPF_RET | BPF_K; // 0x06\n\n// seccomp_data offsets (little-endian): nr@0, arch@4, args[0] low dword @16\nconst OFF_NR = 0;\nconst OFF_ARCH = 4;\nconst OFF_ARG0 = 16;\n\nconst AUDIT_ARCH_X86_64 = 0xc000003e;\nconst X32_BIT = 0x40000000; // nr >= this ⇒ x32 ABI ⇒ reject\n\n// seccomp return actions (linux/seccomp.h)\nconst SECCOMP_RET_ALLOW = 0x7fff0000;\nconst SECCOMP_RET_ERRNO = 0x00050000;\nconst EPERM = 1;\nconst RET_EPERM = SECCOMP_RET_ERRNO | (EPERM & 0xffff); // 0x00050001\nconst SECCOMP_RET_KILL_PROCESS = 0x80000000;\n\nconst AF_UNIX = 1;\n\n/** Always-denied, network-independent (landlock.rs:179-184). */\nconst ALWAYS_DENIED = [101, 310, 311, 425, 426, 427]; // ptrace, process_vm_readv/writev, io_uring_setup/enter/register\n/** Denied only when the network is restricted (landlock.rs:188-204). recvfrom(45)/sendmsg(46) are NOT here. */\nconst NETWORK_DENIED = [42, 43, 288, 49, 50, 52, 51, 48, 44, 307, 299, 55, 54];\n/** socket(2) / socketpair(2) — conditional on domain != AF_UNIX (landlock.rs:206-216). */\nconst SOCKET_SYSCALLS = [41, 53];\n\n/** One `sock_filter` instruction: `{u16 code, u8 jt, u8 jf, u32 k}`. */\ninterface Insn {\n code: number;\n jt: number;\n jf: number;\n k: number;\n}\nconst stmt = (code: number, k: number): Insn => ({ code, jt: 0, jf: 0, k });\nconst jmp = (code: number, k: number, jt: number, jf: number): Insn => ({ code, jt, jf, k });\n\n/**\n * Input to {@link buildSeccompFilter} — the one axis the generated cBPF program varies on.\n *\n * `networkRestricted: true` adds the socket-family denials on top of the always-denied syscall set;\n * `false` emits the base program, which is NOT \"no filter\". The always-denied set applies either way.\n */\nexport interface SeccompOptions {\n /** When true (network off), also deny the socket set + non-AF_UNIX socket(). */\n networkRestricted: boolean;\n}\n\n/**\n * Build the cBPF seccomp program as a `Buffer` (each `sock_filter` = 8 bytes). Jump targets are\n * expressed against labels and back-patched to relative offsets, so the layout is deterministic and\n * unit-testable against the authoritative syscall list.\n */\nexport function buildSeccompFilter(opts: SeccompOptions): Buffer {\n // We assemble with symbolic targets, then resolve to relative jumps. To keep the classic\n // \"deny → jump to a single DENY return; else fall through\" shape, DENY and ALLOW live at the END and\n // every JEQ jumps FORWARD to them. jt/jf carry the DISTANCE (in instructions) to the target.\n const insns: Insn[] = [];\n\n // Placeholder labels resolved after we know total length.\n // Layout: [arch guard][x32 guard][LD nr][deny checks...][socket checks...][ALLOW][DENY][KILL]\n // We build the body first with jumps to ALLOW/DENY/KILL as sentinel indices, then patch.\n const ALLOW = Symbol(\"ALLOW\");\n const DENY = Symbol(\"DENY\");\n const KILL = Symbol(\"KILL\");\n type Target = typeof ALLOW | typeof DENY | typeof KILL | number;\n interface SInsn {\n code: number;\n k: number;\n jt: Target;\n jf: Target;\n }\n const body: SInsn[] = [];\n const push = (code: number, k: number, jt: Target = 0, jf: Target = 0): void => {\n body.push({ code, k, jt, jf });\n };\n\n // --- arch guard: arch == x86_64 ? continue : KILL ---\n push(LD_ABS_W, OFF_ARCH);\n push(JEQ_K, AUDIT_ARCH_X86_64, 0, KILL); // if != → KILL\n // --- x32 guard: nr >= 0x40000000 ? KILL : continue ---\n push(LD_ABS_W, OFF_NR);\n push(JGE_K, X32_BIT, KILL, 0); // if >= → KILL\n // nr already loaded; keep it loaded for the deny checks.\n\n // --- unconditional denials → DENY ---\n const denied = opts.networkRestricted\n ? [...ALWAYS_DENIED, ...NETWORK_DENIED]\n : [...ALWAYS_DENIED];\n for (const nr of denied) push(JEQ_K, nr, DENY, 0); // if nr == syscall → DENY\n\n // --- socket-family: socket(41)/socketpair(53) → allow only AF_UNIX (only when restricted) ---\n if (opts.networkRestricted) {\n for (const sysno of SOCKET_SYSCALLS) {\n // if nr == socket → check domain; else skip the 2 domain-check instructions\n push(JEQ_K, sysno, 0, 2); // match: fall through to the LD/JEQ; no-match: jump +2 (past them)\n push(LD_ABS_W, OFF_ARG0); // load domain (args[0] low dword)\n push(JEQ_K, AF_UNIX, ALLOW, DENY); // AF_UNIX → ALLOW, else DENY\n // NOTE: after these, nr is NO LONGER in the accumulator — but every remaining syscall check\n // reloads via a fresh LD? No: the remaining path is only ALLOW. socket checks are LAST before\n // the tail, so a fall-through (non-socket syscall that reached here) goes straight to ALLOW.\n }\n }\n\n // --- tail ---\n push(RET_K, SECCOMP_RET_ALLOW); // ALLOW label target\n const allowIdx = body.length - 1;\n push(RET_K, RET_EPERM); // DENY\n const denyIdx = body.length - 1;\n push(RET_K, SECCOMP_RET_KILL_PROCESS); // KILL\n const killIdx = body.length - 1;\n\n // --- resolve symbolic targets to relative offsets ---\n // The branching IS the cBPF program: ALLOW/DENY/KILL are symbolic targets resolved to an\n // offset RELATIVE to the next instruction. Breaking it into helpers does not reduce real complexity —\n // it moves the jump arithmetic to another file and makes auditing against landlock.rs harder, the\n // the authoritative source.\n //\n // Not refactoring NOW is an M75 process decision: this function is being MIGRATED without behavior\n // change (plan m75, D4) and there is still no byte-for-byte equivalence oracle against the\n // original version. Refactoring security without that oracle is changing the lock in the dark.\n // Revisit when the parity gate (T4.2) is green — the oracle exists then.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\n const resolve = (i: number, t: Target): number => {\n const abs = t === ALLOW ? allowIdx : t === DENY ? denyIdx : t === KILL ? killIdx : i + 1 + t;\n // BPF jump offset is relative to the NEXT instruction: target - (i + 1)\n const off = abs - (i + 1);\n if (off < 0 || off > 255) throw new RangeError(`seccomp jump out of range at ${i}: ${off}`);\n return off;\n };\n // `for...of` over entries instead of a raw index: the SDK compiles with `noUncheckedIndexedAccess`, which\n // (correctly) types `body[i]` as possibly undefined. Iterating gives the guarantee in the type instead\n // requiring a `!` — the code already could not leave the range, and now the compiler knows it.\n for (const [i, b] of body.entries()) {\n if (b.code === JEQ_K || b.code === JGE_K) {\n insns.push(jmp(b.code, b.k, resolve(i, b.jt), resolve(i, b.jf)));\n } else {\n insns.push(stmt(b.code, b.k));\n }\n }\n\n const buf = Buffer.alloc(insns.length * 8);\n insns.forEach((ins, i) => {\n buf.writeUInt16LE(ins.code, i * 8);\n buf.writeUInt8(ins.jt, i * 8 + 2);\n buf.writeUInt8(ins.jf, i * 8 + 3);\n buf.writeUInt32LE(ins.k >>> 0, i * 8 + 4);\n });\n return buf;\n}\n","// Promoted from agent-builder in M75 (plan m75-sandbox-kernel-no-framework, D1). Renamed from\n// `BwrapSandbox` to `LinuxSandbox`: bwrap is the IMPLEMENTATION, Linux is the contract — swapping the\n// mechanism (landlock, for example) should not change the name the consumer imports.\n\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { redactSecrets } from \"../internal/security/redact.js\";\nimport type { BwrapDetection, SandboxMode } from \"./bwrap.js\";\nimport { buildBwrapArgv, detectBwrapMemoized } from \"./bwrap.js\";\nimport { LocalSandbox } from \"./local-sandbox.js\";\nimport { buildSeccompFilter } from \"./seccomp.js\";\nimport type { SandboxBackend, SandboxConfig } from \"./types.js\";\n\n/*\n * M53 — kernel-enforced sandbox backend, injected into `createShellTool({ sandbox })`.\n *\n * `LinuxSandbox extends LocalSandbox` and only REWRITES the command: `<bwrap-bin> <policy flags> --\n * /bin/sh -c '<original>'`. Everything else (spawn, output caps, timeout, ExecuteResult shape, file\n * ops) is inherited — the SDK backend stays the single execution engine. Mirrors Codex's\n * `SandboxManager::transform` (argv prefixing before spawn, never in-process).\n */\n\n/** POSIX single-quote escaping — the inner command crosses ONE extra `/bin/sh -c` boundary. */\nfunction shellQuote(s: string): string {\n return `'${s.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/**\n * M57 — the single source of truth for the sandbox command wrap. Turns `command` into\n * `<bin> <bwrap flags> [--seccomp 3] -- /bin/sh -c '<command>' [3< <bpf>]`, or `null` when the policy\n * skips the sandbox (`danger-full-access`). Extracted from `LinuxSandbox.wrapCommand` so the interactive\n * PTY backend (M57) can reuse the EXACT wrap the one-shot `run_shell` already uses (DRY) — faithful to\n * Codex, where the sandbox transforms the argv before the PTY spawns it (`sandboxing/src/manager.rs:321`).\n */\nexport function wrapCommandForSandbox(\n mode: SandboxMode,\n opts: {\n cwd: string;\n network?: boolean;\n env?: Record<string, string>;\n bin?: string;\n seccompPath?: string;\n },\n command: string,\n): string | null {\n const argv = buildBwrapArgv(mode, { cwd: opts.cwd, network: opts.network, env: opts.env });\n if (argv === null) return null; // danger-full-access: bwrap skipped\n const bin = opts.bin ?? \"bwrap\";\n const seccompArgv = opts.seccompPath !== undefined ? [\"--seccomp\", \"3\"] : [];\n const base = `${shellQuote(bin)} ${[...argv.slice(0, -1), ...seccompArgv, \"--\"].map(shellQuote).join(\" \")} /bin/sh -c ${shellQuote(command)}`;\n return opts.seccompPath !== undefined ? `${base} 3< ${shellQuote(opts.seccompPath)}` : base;\n}\n\n/**\n * Env allowlist re-injected inside the sandbox after `--clearenv`. Codex env_clear model: the child\n * gets exactly what it needs to run a shell, never the parent's full env (which may hold oddly-named\n * secrets the SDK name-pattern scrub misses). `CODEX_SANDBOX_NETWORK_DISABLED` is added by the argv\n * builder when network is unshared.\n */\nconst ENV_ALLOWLIST = [\n \"PATH\",\n \"HOME\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TERM\",\n \"USER\",\n \"TMPDIR\",\n \"SHELL\",\n];\n\n/**\n * Build the environment a confined command runs with after `--clearenv`: `PATH`, `HOME`, `LANG`,\n * `LC_ALL`, `LC_CTYPE`, `TERM`, `USER`, `TMPDIR` and `SHELL`, copied from `source` (default\n * `process.env`) and omitted where unset.\n *\n * The allowlist shape is the point, and it is what separates this from the other env control in the\n * package. `SandboxConfig.env: \"inherit-scrubbed\"` is a denylist: it drops variables whose NAME looks\n * secret-ish, so an oddly named secret survives. Here the child gets these nine names and nothing\n * else, and a secret's name stops mattering.\n *\n * Call it when you compose the wrap yourself and need an `env` for `wrapCommandForSandbox`;\n * {@link LinuxSandbox} already applies it when its `env` option is omitted. Passing a different\n * `source` changes the VALUES, never the set of names — to give a confined command an extra variable,\n * extend the returned object, which is a fresh one on every call.\n */\nexport function allowlistedEnv(source: NodeJS.ProcessEnv = process.env): Record<string, string> {\n const out: Record<string, string> = {};\n for (const k of ENV_ALLOWLIST) {\n const v = source[k];\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/**\n * Kernel-confined backend for Linux hosts: a `LocalSandbox` whose commands are rewritten as\n * `bwrap <policy flags> -- /bin/sh -c '<command>'` before they are spawned. Spawning, output caps,\n * timeouts and the `ExecuteResult` shape are all inherited, so confinement is a change to the argv\n * and never an in-process one.\n *\n * Prefer `createSandboxBackend` over constructing this directly. The class assumes bubblewrap is\n * present and never probes for it, so on a host without it every command comes back failed rather\n * than confined; the factory probes first and degrades to a plain `LocalSandbox` with a warning.\n *\n * What the confinement actually covers: the filesystem is bound read-only in full, and\n * `mode: \"workspace-write\"` adds the workspace root plus `/tmp` as the only writable paths, while\n * `\"read-only\"` adds none. The network is unshared unless `network: true`. The environment is cleared\n * and repopulated from {@link allowlistedEnv} unless an explicit `env` is passed. The seccomp syscall\n * filter is a second stage with two conditions on it — x86_64 only, and only when the network is\n * restricted — so `network: true` gives you bwrap's filesystem confinement and no syscall filter.\n * `mode: \"danger-full-access\"` skips the wrap entirely and this class behaves as plain\n * `LocalSandbox`.\n *\n * `uploadFile` is overridden so that writes go through the confined `execute` (base64 over stdin,\n * keeping arbitrary content out of the shell command line). A write the policy forbids therefore\n * fails, throwing a plain `Error` naming the target path and the stderr, instead of quietly landing\n * on the host as the inherited implementation would.\n */\nexport class LinuxSandbox extends LocalSandbox {\n private readonly mode: SandboxMode;\n private readonly network: boolean;\n private readonly cwd: string;\n private readonly bin: string;\n private readonly env: Record<string, string>;\n /** M63 — path to the cBPF seccomp program written host-side; passed to `bwrap --seccomp 3` via a\n * shell redirect. `undefined` when the network is unrestricted OR generation failed (honest fallback). */\n private readonly seccompPath: string | undefined;\n\n constructor(\n config: SandboxConfig,\n opts: { mode: SandboxMode; network?: boolean; bin?: string; env?: Record<string, string> },\n ) {\n super(config);\n this.mode = opts.mode;\n this.network = opts.network ?? false;\n this.cwd = config.workDir ?? process.cwd();\n // MEDIUM-1: run the VALIDATED absolute binary from detection (anti-hijack), never bare `bwrap`\n // which the outer shell would re-resolve via $PATH at spawn time (TOCTOU / hijack window).\n this.bin = opts.bin ?? \"bwrap\";\n this.env = opts.env ?? allowlistedEnv();\n this.seccompPath = seccompPathForNetwork(this.network);\n }\n\n /** Extracted for test visibility — delegates to the pure `wrapCommandForSandbox` (M57, single wrap SoT). */\n wrapCommand(command: string): string | null {\n return wrapCommandForSandbox(\n this.mode,\n {\n cwd: this.cwd,\n network: this.network,\n env: this.env,\n bin: this.bin,\n seccompPath: this.seccompPath,\n },\n command,\n );\n }\n\n /**\n * M75 review (architecture, HIGH) — without this override the class LIED.\n *\n * `LinuxSandbox` documents itself as a \"kernel-enforced sandbox backend\", but it overrode only\n * `execute`. `uploadFile` stayed the one inherited from `LocalSandbox`, which writes straight to\n * the host via `fs/promises` and accepts an ABSOLUTE path — no bwrap, no seccomp, no path\n * restriction. And `SandboxBackend.writeFile` delegates to it. The result was an incoherent class:\n * reading, searching and listing went through the confinement; writing did not.\n *\n * Routing through the wrapped `execute` fixes it at the root: writes come to live under the SAME\n * policy as everything else — if bwrap denies the path, the write fails, as it should. The content\n * goes over stdin (not argv) because argv has a size limit and file content does not.\n */\n override async uploadFile(path: string, content: string | Buffer): Promise<void> {\n if (this.mode === \"danger-full-access\") return super.uploadFile(path, content);\n\n const target = path.startsWith(\"/\") ? path : `${this.cwd}/${path}`;\n const b64 = Buffer.from(content).toString(\"base64\");\n // base64 on a single line: avoids any shell quoting over arbitrary content, which is exactly\n // where a \"confined\" write would turn into command injection.\n const r = await this.execute(\n `mkdir -p ${shellQuote(dirname(target))} && printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(target)}`,\n );\n if (r.exitCode !== 0) {\n throw new Error(\n `uploadFile blocked or failed under confinement (${target}): ${r.stderr.trim() || `exit ${r.exitCode}`}`,\n );\n }\n }\n\n override execute(command: string, opts?: { timeoutMs?: number }) {\n const wrapped = this.wrapCommand(command);\n if (wrapped === null) return super.execute(command, opts); // danger-full-access: plain local\n return super.execute(wrapped, opts);\n }\n}\n\nlet warnedNonX64 = false;\n\n/**\n * M63 — the restricted-network seccomp program is DETERMINISTIC, so write it ONCE per process and\n * reuse the path across every LinuxSandbox (no per-instance temp accumulation).\n *\n * ARCH GUARD (review HIGH): `buildSeccompFilter` emits an x86_64 program whose arch guard KILLs every\n * syscall whose `seccomp_data.arch != AUDIT_ARCH_X86_64`. On a non-x86_64 host that would brick EVERY\n * sandboxed command (the first execve is killed) — and silently, because generation succeeds and bwrap\n * accepts it. So we REFUSE to install on non-x64 and WARN through the honest-downgrade channel (bwrap\n * FS/network confinement still applies), exactly like the bwrap-missing fallback. `arch` is injectable\n * for tests. Cleaned on exit AND on SIGINT/SIGTERM (TUI Ctrl+C would otherwise leak the temp dir).\n */\nexport function seccompPathForArch(arch: string, warn: (m: string) => void): string | undefined {\n if (arch !== \"x64\") {\n if (!warnedNonX64) {\n warnedNonX64 = true;\n warn(\n `[sandbox] seccomp syscall filter unsupported on ${arch} (x86_64 only in v1) — running without ` +\n \"the filter; bwrap FS/network confinement still applies.\",\n );\n }\n return undefined;\n }\n try {\n const dir = mkdtempSync(join(tmpdir(), \"ab-seccomp-\"));\n const path = join(dir, \"filter.bpf\");\n writeFileSync(path, buildSeccompFilter({ networkRestricted: true }));\n const cleanup = (): void => rmSync(dir, { recursive: true, force: true });\n process.once(\"exit\", cleanup);\n process.once(\"SIGINT\", cleanup);\n process.once(\"SIGTERM\", cleanup);\n return path;\n } catch (err) {\n warn(\n `[sandbox] seccomp filter unavailable (${err instanceof Error ? err.message : String(err)}) — ` +\n \"running without syscall filter (bwrap FS/network confinement still applies).\",\n );\n return undefined;\n }\n}\n\nlet seccompFilterPath: string | undefined | null; // undefined = not tried; null = resolved absent\n/** M57 — exported so the interactive PTY backend reuses the SAME memoized x64-gated seccomp program. */\nexport function restrictedSeccompPath(): string | undefined {\n if (seccompFilterPath !== undefined) return seccompFilterPath ?? undefined;\n const path = seccompPathForArch(process.arch, (m) => console.warn(redactSecrets(m)));\n seccompFilterPath = path ?? null;\n return path;\n}\n\nlet warnedUnavailable = false;\n\n/** Test seam: reset the WARN-once latch. */\nexport function resetSandboxWarnLatch(): void {\n warnedUnavailable = false;\n}\n\n/** Durable sandbox posture for the UI — the honest answer to \"am I kernel-enforced right now?\". */\nexport interface SandboxPosture {\n mode: SandboxMode;\n enforced: boolean;\n detail: string;\n}\n\n/**\n * MEDIUM-2: compute the posture so a surface (TUI footer) can show enforcement DURABLY instead of a\n * one-shot warn. `danger-full-access` is honestly reported as unenforced; an unavailable bwrap reports\n * the downgrade reason so the user never believes they are confined when they are not.\n */\nexport function resolveSandboxPosture(opts: {\n mode: SandboxMode;\n detect?: () => BwrapDetection;\n}): SandboxPosture {\n if (opts.mode === \"danger-full-access\") {\n return { mode: opts.mode, enforced: false, detail: \"no confinement (danger-full-access)\" };\n }\n const detection = (opts.detect ?? detectBwrapMemoized)();\n if (!detection.ok) {\n return { mode: opts.mode, enforced: false, detail: `tool-gating only — ${detection.reason}` };\n }\n return { mode: opts.mode, enforced: true, detail: \"kernel (bwrap)\" };\n}\n\n/**\n * Options for `createSandboxBackend`, which probes for bubblewrap and returns a {@link LinuxSandbox}\n * when confinement is genuinely available or a `LocalSandbox` when it is not — warning once when the\n * absence is a failure, and silently when `mode` is `\"danger-full-access\"`, since that is an explicit\n * opt-out rather than a degradation.\n *\n * The declared return type is `SandboxBackend` either way, so it does not tell you which one you got.\n * Call `resolveSandboxPosture({ mode })` for that, and surface it durably — the warning fires once\n * per process and a user who missed it has no way to tell they are unconfined.\n *\n * `workDir` and `timeoutMs` are forwarded into the backend's `SandboxConfig`; `maxOutputBytes` and\n * the env policy are not, and keep their defaults. `network` only reaches the confined path, being\n * meaningless on a fallback where the network was never restricted. `detect` and `warn` exist so\n * tests can drive both branches without a real bubblewrap.\n */\nexport interface CreateSandboxBackendOptions {\n mode: SandboxMode;\n workDir?: string;\n network?: boolean;\n timeoutMs?: number;\n /** Injectable for tests; defaults to the real 3-probe detection. */\n detect?: () => BwrapDetection;\n /** Injectable for tests; defaults to console.warn. */\n warn?: (message: string) => void;\n}\n\n/**\n * Honest factory: bwrap available + mode wants confinement → `LinuxSandbox` (kernel enforcement,\n * running the VALIDATED absolute bin); `danger-full-access` → plain `LocalSandbox` silently (explicit\n * opt-out, `bwrap.rs:245-252`); bwrap unavailable → WARN once + `LocalSandbox` (the declarative M23\n * gating remains the guard). NEVER pretends to sandbox — the fallback is loud, mirroring Codex's\n * MISSING_BWRAP_WARNING. The durable posture lives in `resolveSandboxPosture` for the UI.\n */\nexport function createSandboxBackend(opts: CreateSandboxBackendOptions): SandboxBackend {\n const config: SandboxConfig = { workDir: opts.workDir, timeoutMs: opts.timeoutMs };\n if (opts.mode === \"danger-full-access\") return new LocalSandbox(config);\n\n const detection = (opts.detect ?? detectBwrapMemoized)();\n if (!detection.ok) {\n if (!warnedUnavailable) {\n warnedUnavailable = true;\n const warn = opts.warn ?? ((m: string) => console.warn(redactSecrets(m)));\n warn(\n `[sandbox] OS-level enforcement unavailable (${detection.reason}) — ` +\n `falling back to tool-level gating only (sandbox_mode=${opts.mode}).`,\n );\n }\n return new LocalSandbox(config);\n }\n return new LinuxSandbox(config, { mode: opts.mode, network: opts.network, bin: detection.bin });\n}\n\n/**\n * M75 T3.2 — warning latch for the INTERACTIVE path.\n *\n * Kept separate from `createSandboxBackend`'s latch on purpose: they are two distinct decisions\n * taken at distinct moments, and a user who only ever runs an interactive shell needs to see the\n * warning even if the non-interactive path already emitted it — otherwise the session where they\n * actually type commands would be the one without the alert.\n */\nlet interactiveWarned = false;\n\n/** Reset for tests — the latch is module state and tests need isolation. */\nexport function resetInteractiveWarnLatch(): void {\n interactiveWarned = false;\n}\n\n/**\n * The rule \"seccomp ONLY with restricted network\" — in ONE place.\n *\n * Codex installs the filter only when the network is closed (`landlock.rs:96-117`), and that is not\n * a detail: the cBPF program **denies the network syscalls** (`NETWORK_DENIED`). Applying it with\n * the network open produces the worst possible combination — bwrap **allows** the network (no\n * `--unshare-net`) and seccomp **denies** it with EPERM. The user asked for network, got the bind,\n * and the calls die.\n *\n * It existed duplicated: the constructor decided conditionally, `interactiveWrapCommand` installed\n * unconditionally. They had already diverged in the first version (M75 architecture review, proven\n * at runtime: `network:true` gave `--seccomp` interactively and not one-shot). Two copies of a\n * security rule is not duplicated form — it is duplicated KNOWLEDGE, and it had already diverged.\n */\nfunction seccompPathForNetwork(networkOpen: boolean): string | undefined {\n return networkOpen ? undefined : restrictedSeccompPath();\n}\n\n/**\n * Options for `interactiveWrapCommand`, the PTY counterpart of `createSandboxBackend`.\n *\n * They differ in what they hand back, and that is how you choose. A PTY owns its own spawn and\n * accepts no backend object, so this path returns a `(command, cwd) => string | null` transform: the\n * wrapped command line, or `null` meaning run it as-is. Use it when something else does the spawning;\n * use `createSandboxBackend` when you want an object that executes.\n *\n * Detection is consulted on every wrap instead of being frozen at construction, because an\n * interactive session outlives the probe — a bubblewrap binary that disappears mid-session stops\n * being asserted as present.\n *\n * `network` defaults to `false`, matching the non-interactive path, and carries the same consequence:\n * the seccomp filter is installed only when the network is restricted. The warn-once latch is\n * deliberately separate from the one `createSandboxBackend` keeps, so a user who only ever opens an\n * interactive shell still sees the \"runs WITHOUT kernel confinement\" warning in the session where\n * they type commands.\n */\nexport interface InteractiveWrapOptions {\n mode: SandboxMode;\n /** `true` keeps the network. Default `false`, same as non-interactive `run_shell`. */\n network?: boolean;\n /** Injectable for tests; defaults to the real memoized detection. */\n detect?: () => BwrapDetection;\n /** Injectable for tests; defaults to `console.warn` with redaction. */\n warn?: (message: string) => void;\n}\n\n/**\n * The decision to confine or degrade, separated from the wrap itself.\n *\n * Extracted because they are two responsibilities and the SDK's complexity gate separated them for\n * us: DECIDING (is confinement available? did the user opt out?) and APPLYING (assembling the argv).\n * Keeping them together pushed the closure past 10 cognitive complexity — and the linter was right:\n * the deciding part is the one with security consequences and deserves to be read on its own.\n *\n * Returns the validated binary when confinement exists, or `null` when it does not — warning ONCE,\n * and only when the absence is a failure (not when it is an opt-out).\n */\nfunction decideConfinement(opts: InteractiveWrapOptions): string | null {\n if (opts.mode === \"danger-full-access\") return null;\n\n const detection = (opts.detect ?? detectBwrapMemoized)();\n if (detection.ok) return detection.bin;\n\n if (!interactiveWarned) {\n interactiveWarned = true;\n const warn = opts.warn ?? ((m: string) => console.warn(redactSecrets(m)));\n warn(\n `[sandbox] OS-level enforcement unavailable (${detection.reason}) — interactive session ` +\n `runs WITHOUT kernel confinement (sandbox_mode=${opts.mode}).`,\n );\n }\n return null;\n}\n\n/**\n * The composition the interactive path needs — the counterpart of `createSandboxBackend`.\n *\n * `createSandboxBackend` solves this for the non-interactive path by returning a ready BACKEND. The\n * PTY accepts no backend: it owns the spawn and only allows transforming the command. This function\n * delivers the SAME decision in the shape the PTY accepts — `(command, cwd) => string | null` —\n * ready for `new PtyInteractiveBackend({ wrapCommand: interactiveWrapCommand({ mode }) })`.\n *\n * Detection is consulted on **every wrap**, not frozen at construction: an interactive session lives\n * for hours, and a stale positive detection would keep asserting confinement after the binary\n * disappeared (the `existsSync` revalidation lives inside `detectBwrapMemoized`).\n *\n * The two routes returning `null` are semantically different and the code does not merge them:\n * `danger-full-access` is an explicit opt-out and does NOT warn; bwrap being unavailable is a\n * failure and warns once.\n */\nexport function interactiveWrapCommand(\n opts: InteractiveWrapOptions,\n): (command: string, cwd: string) => string | null {\n return (command: string, cwd: string): string | null => {\n const bin = decideConfinement(opts);\n if (bin === null) return null;\n\n return wrapCommandForSandbox(\n opts.mode,\n {\n cwd,\n network: opts.network ?? false,\n env: allowlistedEnv(),\n bin,\n seccompPath: seccompPathForNetwork(opts.network ?? false),\n },\n command,\n );\n };\n}\n","/**\n * M6-3 — portable repo provisioner for the eval harness.\n *\n * Clones a repository and checks out a ref into an isolated working dir, issuing\n * every git command through {@link SandboxBackend.execute} (ADR D2 — same code\n * runs on Local/Docker/E2B; never a direct `child_process` import). Promotes\n * theocode's `prepareRepo` (`swebench-provision.ts:37`) onto the SDK's sandbox\n * abstraction.\n *\n * reference: knowledge-base/references/theocode-eval/lib/swebench-provision.ts:37\n * (clone+checkout), :13 (ProvisionError with instanceId).\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"../errors.js\";\nimport { LocalSandbox } from \"./local-sandbox.js\";\nimport { shellEscapePosix } from \"./shell-escape.js\";\nimport type { SandboxBackend } from \"./types.js\";\n\n/**\n * Raised when cloning or checking out a repo fails. Carries the `instanceId`\n * so a batch run can attribute the failure to the offending dataset row.\n */\nexport class RepoProvisionError extends TheokitAgentError {\n override readonly name = \"RepoProvisionError\";\n\n constructor(\n readonly instanceId: string,\n message: string,\n options: { cause?: unknown } = {},\n ) {\n super(`[${instanceId}] ${message}`, {\n code: \"repo_provision_failed\",\n isRetryable: false,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n });\n }\n}\n\n/** Options for {@link provisionRepo}. */\nexport interface ProvisionRepoOptions {\n /**\n * Clonable repo URL or local path. SECURITY: when this comes from an\n * untrusted dataset, the value is passed to `git clone` after a `--`\n * end-of-options terminator (no flag injection) and with the `ext::`\n * transport disabled (no arbitrary-command transport).\n */\n readonly repoUrl: string;\n /** Branch, tag, or commit SHA to check out. Rejected if it begins with `-`. */\n readonly ref: string;\n /**\n * Unique id for this row — names the target dir and any error. Validated to\n * `[A-Za-z0-9._-]` (no path traversal) since it becomes a directory name.\n */\n readonly instanceId: string;\n}\n\n/**\n * Reject ids that would escape the workdir or be parsed as a git flag. Must\n * start with an alphanumeric (blocks `.`, `..`, `-foo`, leading-dot names) and\n * thereafter allow only `[A-Za-z0-9._-]`.\n */\nconst SAFE_INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * Clone `repoUrl` into `<sandbox workdir>/<instanceId>` and check out `ref`.\n * Returns the absolute `repoDir` (resolved via `git rev-parse --show-toplevel`,\n * which is portable across backends). Throws {@link RepoProvisionError} naming\n * the `instanceId` when clone or checkout exits non-zero.\n *\n * The `sandbox` is optional (V3-5): when omitted, a default {@link LocalSandbox}\n * is used (clones into the process cwd's `<instanceId>`) — pass an explicit\n * sandbox (e.g. `LocalSandbox({ workDir })` / Docker / E2B) to control the workdir.\n */\nexport function provisionRepo(opts: ProvisionRepoOptions): Promise<{ repoDir: string }>;\nexport function provisionRepo(\n sandbox: SandboxBackend,\n opts: ProvisionRepoOptions,\n): Promise<{ repoDir: string }>;\nexport async function provisionRepo(\n sandboxOrOpts: SandboxBackend | ProvisionRepoOptions,\n maybeOpts?: ProvisionRepoOptions,\n): Promise<{ repoDir: string }> {\n const sandbox = maybeOpts !== undefined ? (sandboxOrOpts as SandboxBackend) : new LocalSandbox();\n const opts = maybeOpts ?? (sandboxOrOpts as ProvisionRepoOptions);\n const { repoUrl, ref, instanceId } = opts;\n\n // Validate untrusted-derivable inputs before they reach git/the shell.\n if (!SAFE_INSTANCE_ID.test(instanceId)) {\n throw new RepoProvisionError(\n instanceId,\n \"invalid instanceId: must match [A-Za-z0-9._-] (no path traversal)\",\n );\n }\n if (ref.startsWith(\"-\")) {\n throw new RepoProvisionError(instanceId, `invalid ref: must not begin with '-' (got ${ref})`);\n }\n\n // `--` terminates options (no `--upload-pack=` flag injection); `protocol.ext.allow=never`\n // blocks the `ext::` arbitrary-command transport. `file`/`https` stay allowed.\n const clone = await sandbox.execute(\n `git -c protocol.ext.allow=never clone --quiet -- ${shellEscapePosix(repoUrl)} ${shellEscapePosix(instanceId)}`,\n );\n if (clone.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `clone failed: ${clone.stderr.trim()}`);\n }\n\n const top = await sandbox.execute(\n `git -C ${shellEscapePosix(instanceId)} rev-parse --show-toplevel`,\n );\n if (top.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `resolve repoDir failed: ${top.stderr.trim()}`);\n }\n const repoDir = top.stdout.trim();\n\n // `ref` is validated above not to begin with `-`, so it cannot be parsed as a flag.\n const checkout = await sandbox.execute(\n `git -C ${shellEscapePosix(repoDir)} checkout --quiet ${shellEscapePosix(ref)}`,\n );\n if (checkout.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `checkout ${ref} failed: ${checkout.stderr.trim()}`);\n }\n\n return { repoDir };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sandbox/bwrap.ts","../../src/sandbox/seccomp.ts","../../src/sandbox/linux-sandbox.ts","../../src/sandbox/provision.ts"],"names":["path"],"mappings":";;;;;;;;;;;AAiCA,SAAS,kBAAA,CAAmB,IAAA,EAAgB,GAAA,EAAa,MAAA,EAAiB,MAAA,EAAsB;AAC9F,EAAA,KAAA,MAAW,IAAA,IAAQ,oBAAoB,GAAG,CAAA,OAAQ,IAAA,CAAK,QAAA,EAAU,MAAM,IAAI,CAAA;AAC3E,EAAA,IAAI,MAAA,EAAQ,IAAA,CAAK,IAAA,CAAK,WAAA,EAAa,QAAQ,MAAM,CAAA;AACnD;AAGA,SAAS,oBAAoB,GAAA,EAAgC;AAC3D,EAAA,OAAO,CAAC,KAAK,MAAM,CAAA;AACrB;AAeO,SAAS,gBAAA,CAAiB,MAAmB,GAAA,EAAuC;AACzF,EAAA,QAAQ,IAAA;AAAM,IACZ,KAAK,WAAA;AACH,MAAA,OAAO,EAAC;AAAA,IACV,KAAK,iBAAA;AACH,MAAA,OAAO,oBAAoB,GAAG,CAAA;AAAA,IAChC,KAAK,oBAAA;AACH,MAAA,OAAO,IAAA;AAAA;AAEb;AA8BO,SAAS,cAAA,CAAe,MAAmB,IAAA,EAAyC;AACzF,EAAA,IAAI,IAAA,KAAS,sBAAsB,OAAO,IAAA;AAE1C,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA;AACjC,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,IAAA,CAAK,GA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I,gBAAA,CAAiB,UAAU,CAAC,CAAA;AAAA,GAC/G;AACA,EAAA,IAAI,KAAA,CAAM,aAAa,CAAA,EAAG;AACxB,IAAA,MAAM,IAAI,mBAAmB,UAAA,EAAY,CAAA,cAAA,EAAiB,MAAM,MAAA,CAAO,IAAA,EAAM,CAAA,CAAE,CAAA;AAAA,EACjF;AAEA,EAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,OAAA;AAAA,IACxB,CAAA,OAAA,EAAU,gBAAA,CAAiB,UAAU,CAAC,CAAA,0BAAA;AAAA,GACxC;AACA,EAAA,IAAI,GAAA,CAAI,aAAa,CAAA,EAAG;AACtB,IAAA,MAAM,IAAI,mBAAmB,UAAA,EAAY,CAAA,wBAAA,EAA2B,IAAI,MAAA,CAAO,IAAA,EAAM,CAAA,CAAE,CAAA;AAAA,EACzF;AACA,EAAA,MAAM,OAAA,GAAU,GAAA,CAAI,MAAA,CAAO,IAAA,EAAK;AAGhC,EAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,OAAA;AAAA,IAC7B,UAAU,gBAAA,CAAiB,OAAO,CAAC,CAAA,kBAAA,EAAqB,gBAAA,CAAiB,GAAG,CAAC,CAAA;AAAA,GAC/E;AACA,EAAA,IAAI,QAAA,CAAS,aAAa,CAAA,EAAG;AAC3B,IAAA,MAAM,IAAI,kBAAA,CAAmB,UAAA,EAAY,CAAA,SAAA,EAAY,GAAG,YAAY,QAAA,CAAS,MAAA,CAAO,IAAA,EAAM,CAAA,CAAE,CAAA;AAAA,EAC9F;AAEA,EAAA,OAAO,EAAE,OAAA,EAAQ;AACnB","file":"index.js","sourcesContent":["// Promoted out of the agent-builder in M75 (plan m75-sandbox-kernel-no-framework, D1): kernel\n// confinement is framework infrastructure, not the consumer's. Measured cost of the promotion: ZERO\n// dependencies — only node:child_process, node:fs and node:path. The cBPF filter is a pure-JS Buffer.\n\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/*\n * M53 — bubblewrap argv + honest detection.\n *\n * HONEST SCOPE: filesystem confinement + network isolation via bwrap, PLUS the second stage —\n * a cBPF seccomp syscall filter (`agents/sandbox/seccomp.ts`), wired in `agents/sandbox/backend.ts`\n * via `restrictedSeccompPath()`. Ported in M63; this block claimed the opposite until M67 and\n * UNDER-DECLARED the real security posture. The honest limit that remains: the filter is **x86_64**\n * (an architecture guard refuses to install it on any other arch, with a WARN, and bwrap's FS/network\n * confinement still applies) **and** it is only installed when the network is restricted\n * (`backend.ts:87`, faithful to `landlock.rs:96-117`): with the network on there is no syscall\n * filter, only bwrap's FS confinement. `danger-full-access` skips bwrap entirely, mirroring\n * `bwrap.rs:245-252`. Deltas versus Codex remain documented in docs/CODEX-PARITY.md.\n */\n\n/**\n * Codex's three canonical modes. Defined HERE because they are sandbox vocabulary, not consumer\n * configuration: `danger-full-access` means \"do not wrap\", and that is a decision belonging to the\n * confinement subsystem.\n */\nexport type SandboxMode = \"read-only\" | \"workspace-write\" | \"danger-full-access\";\n\n/**\n * The RW binds `workspace-write` installs (protocol.rs:1189-1214), plus the metadata protection that\n * must sit ON TOP of them — order matters (permissions.rs:22-31; bwrap.rs:571-597).\n */\nfunction pushWorkspaceBinds(argv: string[], cwd: string, hasGit: boolean, gitDir: string): void {\n for (const root of workspaceWriteRoots(cwd)) argv.push(\"--bind\", root, root);\n if (hasGit) argv.push(\"--ro-bind\", gitDir, gitDir);\n}\n\n/** The RW binds `workspace-write` installs (protocol.rs:1189-1214): the workspace itself, and /tmp. */\nfunction workspaceWriteRoots(cwd: string): readonly string[] {\n return [cwd, \"/tmp\"];\n}\n\n/**\n * U-6 — the roots a mode may write to, answerable WITHOUT spawning anything.\n *\n * `[]` means nothing is writable; `null` means unrestricted — which is not the same as `[\"/\"]`,\n * because unrestricted is the absence of a root rather than a root that happens to be `/`.\n *\n * The SDK already knew this: `buildBwrapArgv` binds these exact paths. It only knew it while\n * BUILDING an argv, and a consumer needs the answer earlier — tools are scoped at agent\n * construction, before any process exists, and a file-write tool has to be told its root then. With\n * nothing to ask, consumers keep a second encoding of this three-mode vocabulary and it drifts from\n * the argv builder with nothing to catch it. This reads from the same helper the builder uses, so\n * the two cannot disagree.\n */\nexport function writableRootsFor(mode: SandboxMode, cwd: string): readonly string[] | null {\n switch (mode) {\n case \"read-only\":\n return [];\n case \"workspace-write\":\n return workspaceWriteRoots(cwd);\n case \"danger-full-access\":\n return null;\n }\n}\n\n/**\n * Everything {@link buildBwrapArgv} needs besides the {@link SandboxMode}.\n *\n * Only `cwd` is required, and it is resolved to an absolute path before any bind\n * is emitted. The defaults are the restrictive ones in one direction and the\n * permissive one in the other: omitting `network` emits `--unshare-net` (no\n * network), while omitting `env` means the child INHERITS the parent\n * environment — bwrap only clears it when an allowlist is supplied.\n */\nexport interface BwrapArgvOptions {\n /** Workspace root — the single RW bind under `workspace-write` (protocol.rs:1189-1200). */\n cwd: string;\n /** `true` removes `--unshare-net` (policy `network_access`, default false). */\n network?: boolean;\n /** Injectable for tests; defaults to a real `existsSync` check on `<cwd>/.git`. */\n gitDirExists?: boolean;\n /**\n * When present, emit `--clearenv` and re-inject ONLY these vars (Codex env_clear model,\n * `exec_env.rs:25-31`). Closes the denylist gap: a secret in an oddly-named var never reaches the\n * sandboxed child. Omitted ⇒ inherit the parent env (backward-compatible; SDK scrub still applies).\n */\n env?: Record<string, string>;\n}\n\n/**\n * Pure argv builder. Returns the bwrap flags ending in `--` (caller appends `/bin/sh -c <cmd>`),\n * or `null` when the policy skips the sandbox entirely (`danger-full-access`).\n */\nexport function buildBwrapArgv(mode: SandboxMode, opts: BwrapArgvOptions): string[] | null {\n if (mode === \"danger-full-access\") return null; // bwrap skipped entirely (bwrap.rs:245-252)\n\n const cwd = path.resolve(opts.cwd);\n const gitDir = path.join(cwd, \".git\");\n const hasGit = opts.gitDirExists ?? existsSync(gitDir);\n\n const argv: string[] = [\n // core, always (bwrap.rs:318-332; user+pid namespaces explicit so it works as root in containers)\n \"--new-session\",\n \"--die-with-parent\",\n \"--unshare-user\",\n \"--unshare-pid\",\n // full-read filesystem base (bwrap.rs:446-452)\n \"--ro-bind\",\n \"/\",\n \"/\",\n \"--dev\",\n \"/dev\",\n \"--proc\",\n \"/proc\",\n ];\n\n if (!opts.network) argv.push(\"--unshare-net\"); // network off by default (bwrap.rs:325-327)\n\n // env confinement — `--clearenv` MUST precede every `--setenv` or the clear wipes them\n // (exec_env.rs:25-31 clears then rebuilds). Only when an explicit allowlist is provided.\n if (opts.env) argv.push(\"--clearenv\");\n const setenv: Record<string, string> = {\n ...(opts.env ?? {}),\n // the flag signals the child that network is unshared (spawn.rs:20,79)\n ...(opts.network ? {} : { CODEX_SANDBOX_NETWORK_DISABLED: \"1\" }),\n };\n for (const [k, v] of Object.entries(setenv)) argv.push(\"--setenv\", k, v);\n\n if (mode === \"workspace-write\") pushWorkspaceBinds(argv, cwd, hasGit, gitDir);\n // read-only: zero writable roots (protocol.rs:1176) — nothing to add\n\n argv.push(\"--chdir\", cwd, \"--\");\n return argv;\n}\n\n/** Injectable probes — each mirrors one Codex availability check. */\nexport interface BwrapProbes {\n /** `which bwrap` outside the cwd (anti-hijack, sandboxing/src/bwrap.rs:168-191). */\n which: () => string | null;\n /** `bwrap --help` text — must advertise `--perms` (launcher.rs:108-124). */\n helpText: (bin: string) => string | null;\n /** Active user-namespace probe with timeout (sandboxing/src/bwrap.rs:74-136). */\n userns: (bin: string) => boolean;\n}\n\n/**\n * Result of {@link detectBwrap} / {@link detectBwrapMemoized}, discriminated on\n * `ok`: `{ ok: true, bin }` carries the absolute path of the validated `bwrap`,\n * `{ ok: false, reason }` a human-readable cause — \"bwrap not found in PATH\",\n * \"bwrap at <bin> lacks --perms support (too old)\",\n * \"user namespaces unavailable (container/kernel restriction)\",\n * \"bwrap probe failed: <err>\", or (memoized only)\n * \"bwrap disappeared from <bin> after detection\".\n *\n * `reason` is prose for a warning line. It is not a stable code — do not branch\n * on it.\n *\n * `ok: false` is an ordinary outcome rather than an error: bubblewrap is\n * Linux-only, so failing detection on macOS, on Windows, or inside a container\n * without user namespaces is expected. Detection NEVER throws, so wrapping it in\n * `try`/`catch` catches nothing; callers warn and fall back to an unconfined\n * `LocalSandbox`.\n */\nexport type BwrapDetection = { ok: true; bin: string } | { ok: false; reason: string };\n\n/** Honest detection — fail-closed on every probe; NEVER throws (callers WARN + fall back). */\nexport function detectBwrap(probes: BwrapProbes = realProbes): BwrapDetection {\n try {\n const bin = probes.which();\n if (!bin) return { ok: false, reason: \"bwrap not found in PATH\" };\n const help = probes.helpText(bin);\n if (!help?.includes(\"--perms\")) {\n return { ok: false, reason: `bwrap at ${bin} lacks --perms support (too old)` };\n }\n if (!probes.userns(bin)) {\n return { ok: false, reason: \"user namespaces unavailable (container/kernel restriction)\" };\n }\n return { ok: true, bin };\n } catch (err) {\n return {\n ok: false,\n reason: `bwrap probe failed: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n}\n\n/**\n * How many times the REAL probe ran in this process.\n *\n * Instrumented here rather than in a wrapper, because this is where the cost is: every `which`\n * spawns a subprocess (`which bwrap`), and the full probe cost 22.2 ms. A gate counting INJECTED\n * probes does not see the real one — that was the M71 gate's first mistake, and a mutant exposed it.\n */\nlet realProbeRuns = 0;\n\n/** How many real probes ran. TEST seam — the performance gate counts this. */\nexport function realProbeCount(): number {\n return realProbeRuns;\n}\n\n/** Real probes used in production. */\nexport const realProbes: BwrapProbes = {\n which: () => {\n realProbeRuns++;\n try {\n const out = execFileSync(\"which\", [\"bwrap\"], { encoding: \"utf8\", timeout: 2_000 }).trim();\n // anti-hijack: never accept a bwrap that lives inside the workspace (bwrap.rs:168-191)\n if (!out || out.startsWith(process.cwd() + path.sep)) return null;\n return out;\n } catch {\n return null;\n }\n },\n helpText: (bin) => {\n try {\n // bwrap --help exits 0/1 depending on version; capture output either way\n return execFileSync(bin, [\"--help\"], { encoding: \"utf8\", timeout: 2_000 });\n } catch (err) {\n const e = err as { stdout?: string; stderr?: string };\n return [e.stdout, e.stderr].filter(Boolean).join(\"\\n\") || null;\n }\n },\n userns: (bin) => {\n try {\n // active probe, 500ms budget like Codex (sandboxing/src/bwrap.rs:74-136)\n execFileSync(bin, [\"--unshare-user\", \"--unshare-net\", \"--ro-bind\", \"/\", \"/\", \"/bin/true\"], {\n timeout: 500,\n stdio: \"ignore\",\n });\n return true;\n } catch {\n return false;\n }\n },\n};\n\n/**\n * The probe result, memoized for the lifetime of the PROCESS.\n *\n * Measured before M71: `detectBwrap()` costs **22.2 ms** and was not memoized — the second call\n * cost 19.4 ms. `buildChatAgent` on the headless path fired **two** (one from\n * `createSandboxBackend`, another from `resolveSandboxPosture`, which M70 added), totalling 46.4 ms\n * per construction — and construction happens per turn. Under `strace`, ~90% of the 182 syscalls of\n * an already-warm construction came from here: `which` sweeping the PATH, `/proc/filesystems`,\n * `/newroot`, and the `.so` files the two probe subprocesses load.\n *\n * ## Why there is no invalidation\n *\n * The milestone called for invalidating on `SessionStart`. That does not work:\n * `agents/lib/hooks/hooks.ts:28-30` documents — as a **measured** correction of an earlier\n * assumption — that the event fires **once per TURN**, not per session. Invalidating there would\n * re-probe every turn, exactly the behavior memoization exists to eliminate.\n *\n * A write-once cache is sufficient here: the expensive probe runs once per process,\n * only to print a UI warning.\n *\n * **The price, stated plainly — in BOTH directions.** The original m71-cost-per-turn#ADR-1 declared\n * only one of them; the M71 review (F-perf-9) showed the omitted one was precisely the one with a\n * security consequence:\n *\n * - **Stale negative** (`bwrap` installed AFTERWARDS): not detected until restart. The system fails\n * CLOSED — the posture reports `enforced: false` and M70's veto **refuses**. Cost: annoyance (the\n * message tells you to install the bwrap you just installed). Accepted.\n * - **Stale positive** (`bwrap` removed/renamed AFTERWARDS): the posture would keep asserting\n * `enforced: true / \"kernel (bwrap)\"` and the veto would **approve**, citing a confinement that no\n * longer exists. That is the literal reintroduction of the defect M70 fixed — *\"telling the\n * operator they are protected when they are not is worse than saying nothing\"*. Before M71 the\n * per-turn re-probe closed that window on the next turn; memoization would leave it open for the\n * whole process. **That is why the positive is revalidated** below, at 1 syscall — 3 orders of\n * magnitude below the 22.2 ms of the full probe, which is the cost memoization exists to remove.\n */\nlet memo: BwrapDetection | undefined;\n\n/**\n * `detectBwrap` with memoization — what production should call.\n *\n * Note that `detectBwrap` itself does **not** memoize, on purpose: it accepts injected probes, and\n * memoizing there would let a test with fake probes poison the process cache for everyone else.\n *\n * Revalidating the positive is NOT a re-probe: `detectBwrap` spends three probes (a `which`\n * subprocess + `--help` + a user namespace). Here we only confirm the validated binary is still in\n * place. If it vanished, the memo is downgraded to a negative with the reason stated — never\n * promoted to a positive, which would require the expensive probe back.\n */\nexport function detectBwrapMemoized(probes: BwrapProbes = realProbes): BwrapDetection {\n memo ??= detectBwrap(probes);\n if (memo.ok && !existsSync(memo.bin)) {\n memo = { ok: false, reason: `bwrap disappeared from ${memo.bin} after detection` };\n }\n return memo;\n}\n\n/** TEST seam — clears the memo. Production never calls it (see m71-cost-per-turn#ADR-1). */\nexport function resetBwrapMemo(): void {\n memo = undefined;\n}\n","// Promoted from agent-builder in M75 (plan m75-sandbox-kernel-no-framework, D1): confinement with\n// kernel confinement is framework infrastructure, not the consumer's. Measured cost of the promotion: ZERO\n// no dependencies — only node:child_process, node:fs and node:path. The cBPF filter is a Buffer in pure JS.\n\n/**\n * M63 — cBPF seccomp filter generator. Produces a raw `sock_filter[]` program (the exact\n * shape `bwrap --seccomp <fd>` consumes) so syscall confinement needs no\n * native helper — bwrap applies `PR_SET_NO_NEW_PRIVS` + the filter before `execve`.\n *\n * Semantics (landlock.rs:252-253): default action = ALLOW; per-syscall match = ERRNO(EPERM). KILL is\n * used ONLY by the architecture/x32 guard. x86_64 only in v1 (aarch64 is a documented delta).\n */\n\n// BPF opcodes (linux/bpf_common.h)\nconst BPF_LD = 0x00;\nconst BPF_W = 0x00;\nconst BPF_ABS = 0x20;\nconst BPF_JMP = 0x05;\nconst BPF_JEQ = 0x10;\nconst BPF_JGE = 0x30;\nconst BPF_K = 0x00;\nconst BPF_RET = 0x06;\n\nconst LD_ABS_W = BPF_LD | BPF_W | BPF_ABS; // 0x20\nconst JEQ_K = BPF_JMP | BPF_JEQ | BPF_K; // 0x15\nconst JGE_K = BPF_JMP | BPF_JGE | BPF_K; // 0x35\nconst RET_K = BPF_RET | BPF_K; // 0x06\n\n// seccomp_data offsets (little-endian): nr@0, arch@4, args[0] low dword @16\nconst OFF_NR = 0;\nconst OFF_ARCH = 4;\nconst OFF_ARG0 = 16;\n\nconst AUDIT_ARCH_X86_64 = 0xc000003e;\nconst X32_BIT = 0x40000000; // nr >= this ⇒ x32 ABI ⇒ reject\n\n// seccomp return actions (linux/seccomp.h)\nconst SECCOMP_RET_ALLOW = 0x7fff0000;\nconst SECCOMP_RET_ERRNO = 0x00050000;\nconst EPERM = 1;\nconst RET_EPERM = SECCOMP_RET_ERRNO | (EPERM & 0xffff); // 0x00050001\nconst SECCOMP_RET_KILL_PROCESS = 0x80000000;\n\nconst AF_UNIX = 1;\n\n/** Always-denied, network-independent (landlock.rs:179-184). */\nconst ALWAYS_DENIED = [101, 310, 311, 425, 426, 427]; // ptrace, process_vm_readv/writev, io_uring_setup/enter/register\n/**\n * Denied only when the network is restricted (landlock.rs:188-204). recvfrom(45)/sendmsg(46) are\n * NOT here — and, since #385, neither are `getsockname`(51), `getpeername`(52), `setsockopt`(54)\n * and `getsockopt`(55).\n *\n * Those four take an ALREADY-OPEN fd rather than an address, and cBPF cannot dereference an fd to\n * learn the family behind it. Denying them therefore denied them on AF_UNIX as well — which is\n * exactly what libuv calls on a child's IPC channel, so any command that spawned a child died.\n * Measured: `node --test` returned 0 lines under the filter and 38 without it, and the parent's\n * own stdout vanished with it (killed mid-flight, its buffered pipe write never flushed, while the\n * child's already-written bytes survived). The AF_UNIX exemption on `socket`/`socketpair` below\n * shows breaking local IPC was never the intent.\n *\n * They cannot reach a network on their own. Everything that takes an address or changes an fd's\n * role — `connect`, `bind`, `listen`, `accept`, `accept4`, `sendto`, `sendmmsg`, `recvmmsg`,\n * `shutdown` — stays denied, and `socket()` still refuses every family but AF_UNIX. Measured\n * unchanged across the fix: an AF_INET socket is `EPERM` before and after, an AF_UNIX socketpair\n * works before and after.\n *\n * The blunt alternative — dropping the whole set, on the grounds that `--unshare-net` already\n * removes the network — would restore the output AND let a confined command open a connection the\n * moment a future mode runs the filter with the network on. This keeps the belt.\n */\nconst NETWORK_DENIED = [42, 43, 288, 49, 50, 48, 44, 307, 299];\n/** socket(2) / socketpair(2) — conditional on domain != AF_UNIX (landlock.rs:206-216). */\nconst SOCKET_SYSCALLS = [41, 53];\n\n/** One `sock_filter` instruction: `{u16 code, u8 jt, u8 jf, u32 k}`. */\ninterface Insn {\n code: number;\n jt: number;\n jf: number;\n k: number;\n}\nconst stmt = (code: number, k: number): Insn => ({ code, jt: 0, jf: 0, k });\nconst jmp = (code: number, k: number, jt: number, jf: number): Insn => ({ code, jt, jf, k });\n\n/**\n * Input to {@link buildSeccompFilter} — the one axis the generated cBPF program varies on.\n *\n * `networkRestricted: true` adds the socket-family denials on top of the always-denied syscall set;\n * `false` emits the base program, which is NOT \"no filter\". The always-denied set applies either way.\n */\nexport interface SeccompOptions {\n /** When true (network off), also deny the socket set + non-AF_UNIX socket(). */\n networkRestricted: boolean;\n}\n\n/**\n * Build the cBPF seccomp program as a `Buffer` (each `sock_filter` = 8 bytes). Jump targets are\n * expressed against labels and back-patched to relative offsets, so the layout is deterministic and\n * unit-testable against the authoritative syscall list.\n */\nexport function buildSeccompFilter(opts: SeccompOptions): Buffer {\n // We assemble with symbolic targets, then resolve to relative jumps. To keep the classic\n // \"deny → jump to a single DENY return; else fall through\" shape, DENY and ALLOW live at the END and\n // every JEQ jumps FORWARD to them. jt/jf carry the DISTANCE (in instructions) to the target.\n const insns: Insn[] = [];\n\n // Placeholder labels resolved after we know total length.\n // Layout: [arch guard][x32 guard][LD nr][deny checks...][socket checks...][ALLOW][DENY][KILL]\n // We build the body first with jumps to ALLOW/DENY/KILL as sentinel indices, then patch.\n const ALLOW = Symbol(\"ALLOW\");\n const DENY = Symbol(\"DENY\");\n const KILL = Symbol(\"KILL\");\n type Target = typeof ALLOW | typeof DENY | typeof KILL | number;\n interface SInsn {\n code: number;\n k: number;\n jt: Target;\n jf: Target;\n }\n const body: SInsn[] = [];\n const push = (code: number, k: number, jt: Target = 0, jf: Target = 0): void => {\n body.push({ code, k, jt, jf });\n };\n\n // --- arch guard: arch == x86_64 ? continue : KILL ---\n push(LD_ABS_W, OFF_ARCH);\n push(JEQ_K, AUDIT_ARCH_X86_64, 0, KILL); // if != → KILL\n // --- x32 guard: nr >= 0x40000000 ? KILL : continue ---\n push(LD_ABS_W, OFF_NR);\n push(JGE_K, X32_BIT, KILL, 0); // if >= → KILL\n // nr already loaded; keep it loaded for the deny checks.\n\n // --- unconditional denials → DENY ---\n const denied = opts.networkRestricted\n ? [...ALWAYS_DENIED, ...NETWORK_DENIED]\n : [...ALWAYS_DENIED];\n for (const nr of denied) push(JEQ_K, nr, DENY, 0); // if nr == syscall → DENY\n\n // --- socket-family: socket(41)/socketpair(53) → allow only AF_UNIX (only when restricted) ---\n if (opts.networkRestricted) {\n for (const sysno of SOCKET_SYSCALLS) {\n // if nr == socket → check domain; else skip the 2 domain-check instructions\n push(JEQ_K, sysno, 0, 2); // match: fall through to the LD/JEQ; no-match: jump +2 (past them)\n push(LD_ABS_W, OFF_ARG0); // load domain (args[0] low dword)\n push(JEQ_K, AF_UNIX, ALLOW, DENY); // AF_UNIX → ALLOW, else DENY\n // NOTE: after these, nr is NO LONGER in the accumulator — but every remaining syscall check\n // reloads via a fresh LD? No: the remaining path is only ALLOW. socket checks are LAST before\n // the tail, so a fall-through (non-socket syscall that reached here) goes straight to ALLOW.\n }\n }\n\n // --- tail ---\n push(RET_K, SECCOMP_RET_ALLOW); // ALLOW label target\n const allowIdx = body.length - 1;\n push(RET_K, RET_EPERM); // DENY\n const denyIdx = body.length - 1;\n push(RET_K, SECCOMP_RET_KILL_PROCESS); // KILL\n const killIdx = body.length - 1;\n\n // --- resolve symbolic targets to relative offsets ---\n // The branching IS the cBPF program: ALLOW/DENY/KILL are symbolic targets resolved to an\n // offset RELATIVE to the next instruction. Breaking it into helpers does not reduce real complexity —\n // it moves the jump arithmetic to another file and makes auditing against landlock.rs harder, the\n // the authoritative source.\n //\n // Not refactoring NOW is an M75 process decision: this function is being MIGRATED without behavior\n // change (plan m75, D4) and there is still no byte-for-byte equivalence oracle against the\n // original version. Refactoring security without that oracle is changing the lock in the dark.\n // Revisit when the parity gate (T4.2) is green — the oracle exists then.\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\n const resolve = (i: number, t: Target): number => {\n const abs = t === ALLOW ? allowIdx : t === DENY ? denyIdx : t === KILL ? killIdx : i + 1 + t;\n // BPF jump offset is relative to the NEXT instruction: target - (i + 1)\n const off = abs - (i + 1);\n if (off < 0 || off > 255) throw new RangeError(`seccomp jump out of range at ${i}: ${off}`);\n return off;\n };\n // `for...of` over entries instead of a raw index: the SDK compiles with `noUncheckedIndexedAccess`, which\n // (correctly) types `body[i]` as possibly undefined. Iterating gives the guarantee in the type instead\n // requiring a `!` — the code already could not leave the range, and now the compiler knows it.\n for (const [i, b] of body.entries()) {\n if (b.code === JEQ_K || b.code === JGE_K) {\n insns.push(jmp(b.code, b.k, resolve(i, b.jt), resolve(i, b.jf)));\n } else {\n insns.push(stmt(b.code, b.k));\n }\n }\n\n const buf = Buffer.alloc(insns.length * 8);\n insns.forEach((ins, i) => {\n buf.writeUInt16LE(ins.code, i * 8);\n buf.writeUInt8(ins.jt, i * 8 + 2);\n buf.writeUInt8(ins.jf, i * 8 + 3);\n buf.writeUInt32LE(ins.k >>> 0, i * 8 + 4);\n });\n return buf;\n}\n","// Promoted from agent-builder in M75 (plan m75-sandbox-kernel-no-framework, D1). Renamed from\n// `BwrapSandbox` to `LinuxSandbox`: bwrap is the IMPLEMENTATION, Linux is the contract — swapping the\n// mechanism (landlock, for example) should not change the name the consumer imports.\n\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { redactSecrets } from \"../internal/security/redact.js\";\nimport type { BwrapDetection, SandboxMode } from \"./bwrap.js\";\nimport { buildBwrapArgv, detectBwrapMemoized } from \"./bwrap.js\";\nimport { LocalSandbox } from \"./local-sandbox.js\";\nimport { buildSeccompFilter } from \"./seccomp.js\";\nimport type { SandboxBackend, SandboxConfig } from \"./types.js\";\n\n/*\n * M53 — kernel-enforced sandbox backend, injected into `createShellTool({ sandbox })`.\n *\n * `LinuxSandbox extends LocalSandbox` and only REWRITES the command: `<bwrap-bin> <policy flags> --\n * /bin/sh -c '<original>'`. Everything else (spawn, output caps, timeout, ExecuteResult shape, file\n * ops) is inherited — the SDK backend stays the single execution engine. Mirrors Codex's\n * `SandboxManager::transform` (argv prefixing before spawn, never in-process).\n */\n\n/** POSIX single-quote escaping — the inner command crosses ONE extra `/bin/sh -c` boundary. */\nfunction shellQuote(s: string): string {\n return `'${s.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/**\n * M57 — the single source of truth for the sandbox command wrap. Turns `command` into\n * `<bin> <bwrap flags> [--seccomp 3] -- /bin/sh -c '<command>' [3< <bpf>]`, or `null` when the policy\n * skips the sandbox (`danger-full-access`). Extracted from `LinuxSandbox.wrapCommand` so the interactive\n * PTY backend (M57) can reuse the EXACT wrap the one-shot `run_shell` already uses (DRY) — faithful to\n * Codex, where the sandbox transforms the argv before the PTY spawns it (`sandboxing/src/manager.rs:321`).\n */\nexport function wrapCommandForSandbox(\n mode: SandboxMode,\n opts: {\n cwd: string;\n network?: boolean;\n env?: Record<string, string>;\n bin?: string;\n seccompPath?: string;\n },\n command: string,\n): string | null {\n const argv = buildBwrapArgv(mode, { cwd: opts.cwd, network: opts.network, env: opts.env });\n if (argv === null) return null; // danger-full-access: bwrap skipped\n const bin = opts.bin ?? \"bwrap\";\n const seccompArgv = opts.seccompPath !== undefined ? [\"--seccomp\", \"3\"] : [];\n const base = `${shellQuote(bin)} ${[...argv.slice(0, -1), ...seccompArgv, \"--\"].map(shellQuote).join(\" \")} /bin/sh -c ${shellQuote(command)}`;\n return opts.seccompPath !== undefined ? `${base} 3< ${shellQuote(opts.seccompPath)}` : base;\n}\n\n/**\n * Env allowlist re-injected inside the sandbox after `--clearenv`. Codex env_clear model: the child\n * gets exactly what it needs to run a shell, never the parent's full env (which may hold oddly-named\n * secrets the SDK name-pattern scrub misses). `CODEX_SANDBOX_NETWORK_DISABLED` is added by the argv\n * builder when network is unshared.\n */\nconst ENV_ALLOWLIST = [\n \"PATH\",\n \"HOME\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TERM\",\n \"USER\",\n \"TMPDIR\",\n \"SHELL\",\n];\n\n/**\n * Build the environment a confined command runs with after `--clearenv`: `PATH`, `HOME`, `LANG`,\n * `LC_ALL`, `LC_CTYPE`, `TERM`, `USER`, `TMPDIR` and `SHELL`, copied from `source` (default\n * `process.env`) and omitted where unset.\n *\n * The allowlist shape is the point, and it is what separates this from the other env control in the\n * package. `SandboxConfig.env: \"inherit-scrubbed\"` is a denylist: it drops variables whose NAME looks\n * secret-ish, so an oddly named secret survives. Here the child gets these nine names and nothing\n * else, and a secret's name stops mattering.\n *\n * Call it when you compose the wrap yourself and need an `env` for `wrapCommandForSandbox`;\n * {@link LinuxSandbox} already applies it when its `env` option is omitted. Passing a different\n * `source` changes the VALUES, never the set of names — to give a confined command an extra variable,\n * extend the returned object, which is a fresh one on every call.\n */\nexport function allowlistedEnv(source: NodeJS.ProcessEnv = process.env): Record<string, string> {\n const out: Record<string, string> = {};\n for (const k of ENV_ALLOWLIST) {\n const v = source[k];\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/**\n * Kernel-confined backend for Linux hosts: a `LocalSandbox` whose commands are rewritten as\n * `bwrap <policy flags> -- /bin/sh -c '<command>'` before they are spawned. Spawning, output caps,\n * timeouts and the `ExecuteResult` shape are all inherited, so confinement is a change to the argv\n * and never an in-process one.\n *\n * Prefer `createSandboxBackend` over constructing this directly. The class assumes bubblewrap is\n * present and never probes for it, so on a host without it every command comes back failed rather\n * than confined; the factory probes first and degrades to a plain `LocalSandbox` with a warning.\n *\n * What the confinement actually covers: the filesystem is bound read-only in full, and\n * `mode: \"workspace-write\"` adds the workspace root plus `/tmp` as the only writable paths, while\n * `\"read-only\"` adds none. The network is unshared unless `network: true`. The environment is cleared\n * and repopulated from {@link allowlistedEnv} unless an explicit `env` is passed. The seccomp syscall\n * filter is a second stage with two conditions on it — x86_64 only, and only when the network is\n * restricted — so `network: true` gives you bwrap's filesystem confinement and no syscall filter.\n * `mode: \"danger-full-access\"` skips the wrap entirely and this class behaves as plain\n * `LocalSandbox`.\n *\n * `uploadFile` is overridden so that writes go through the confined `execute` (base64 over stdin,\n * keeping arbitrary content out of the shell command line). A write the policy forbids therefore\n * fails, throwing a plain `Error` naming the target path and the stderr, instead of quietly landing\n * on the host as the inherited implementation would.\n */\nexport class LinuxSandbox extends LocalSandbox {\n private readonly mode: SandboxMode;\n private readonly network: boolean;\n private readonly cwd: string;\n private readonly bin: string;\n private readonly env: Record<string, string>;\n /** M63 — path to the cBPF seccomp program written host-side; passed to `bwrap --seccomp 3` via a\n * shell redirect. `undefined` when the network is unrestricted OR generation failed (honest fallback). */\n private readonly seccompPath: string | undefined;\n\n constructor(\n config: SandboxConfig,\n opts: { mode: SandboxMode; network?: boolean; bin?: string; env?: Record<string, string> },\n ) {\n super(config);\n this.mode = opts.mode;\n this.network = opts.network ?? false;\n this.cwd = config.workDir ?? process.cwd();\n // MEDIUM-1: run the VALIDATED absolute binary from detection (anti-hijack), never bare `bwrap`\n // which the outer shell would re-resolve via $PATH at spawn time (TOCTOU / hijack window).\n this.bin = opts.bin ?? \"bwrap\";\n this.env = opts.env ?? allowlistedEnv();\n this.seccompPath = seccompPathForNetwork(this.network);\n }\n\n /** Extracted for test visibility — delegates to the pure `wrapCommandForSandbox` (M57, single wrap SoT). */\n wrapCommand(command: string): string | null {\n return wrapCommandForSandbox(\n this.mode,\n {\n cwd: this.cwd,\n network: this.network,\n env: this.env,\n bin: this.bin,\n seccompPath: this.seccompPath,\n },\n command,\n );\n }\n\n /**\n * M75 review (architecture, HIGH) — without this override the class LIED.\n *\n * `LinuxSandbox` documents itself as a \"kernel-enforced sandbox backend\", but it overrode only\n * `execute`. `uploadFile` stayed the one inherited from `LocalSandbox`, which writes straight to\n * the host via `fs/promises` and accepts an ABSOLUTE path — no bwrap, no seccomp, no path\n * restriction. And `SandboxBackend.writeFile` delegates to it. The result was an incoherent class:\n * reading, searching and listing went through the confinement; writing did not.\n *\n * Routing through the wrapped `execute` fixes it at the root: writes come to live under the SAME\n * policy as everything else — if bwrap denies the path, the write fails, as it should. The content\n * goes over stdin (not argv) because argv has a size limit and file content does not.\n */\n override async uploadFile(path: string, content: string | Buffer): Promise<void> {\n if (this.mode === \"danger-full-access\") return super.uploadFile(path, content);\n\n const target = path.startsWith(\"/\") ? path : `${this.cwd}/${path}`;\n const b64 = Buffer.from(content).toString(\"base64\");\n // base64 on a single line: avoids any shell quoting over arbitrary content, which is exactly\n // where a \"confined\" write would turn into command injection.\n const r = await this.execute(\n `mkdir -p ${shellQuote(dirname(target))} && printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(target)}`,\n );\n if (r.exitCode !== 0) {\n throw new Error(\n `uploadFile blocked or failed under confinement (${target}): ${r.stderr.trim() || `exit ${r.exitCode}`}`,\n );\n }\n }\n\n override execute(command: string, opts?: { timeoutMs?: number }) {\n const wrapped = this.wrapCommand(command);\n if (wrapped === null) return super.execute(command, opts); // danger-full-access: plain local\n return super.execute(wrapped, opts);\n }\n}\n\nlet warnedNonX64 = false;\n\n/**\n * M63 — the restricted-network seccomp program is DETERMINISTIC, so write it ONCE per process and\n * reuse the path across every LinuxSandbox (no per-instance temp accumulation).\n *\n * ARCH GUARD (review HIGH): `buildSeccompFilter` emits an x86_64 program whose arch guard KILLs every\n * syscall whose `seccomp_data.arch != AUDIT_ARCH_X86_64`. On a non-x86_64 host that would brick EVERY\n * sandboxed command (the first execve is killed) — and silently, because generation succeeds and bwrap\n * accepts it. So we REFUSE to install on non-x64 and WARN through the honest-downgrade channel (bwrap\n * FS/network confinement still applies), exactly like the bwrap-missing fallback. `arch` is injectable\n * for tests. Cleaned on exit AND on SIGINT/SIGTERM (TUI Ctrl+C would otherwise leak the temp dir).\n */\nexport function seccompPathForArch(arch: string, warn: (m: string) => void): string | undefined {\n if (arch !== \"x64\") {\n if (!warnedNonX64) {\n warnedNonX64 = true;\n warn(\n `[sandbox] seccomp syscall filter unsupported on ${arch} (x86_64 only in v1) — running without ` +\n \"the filter; bwrap FS/network confinement still applies.\",\n );\n }\n return undefined;\n }\n try {\n const dir = mkdtempSync(join(tmpdir(), \"ab-seccomp-\"));\n const path = join(dir, \"filter.bpf\");\n writeFileSync(path, buildSeccompFilter({ networkRestricted: true }));\n const cleanup = (): void => rmSync(dir, { recursive: true, force: true });\n process.once(\"exit\", cleanup);\n process.once(\"SIGINT\", cleanup);\n process.once(\"SIGTERM\", cleanup);\n return path;\n } catch (err) {\n warn(\n `[sandbox] seccomp filter unavailable (${err instanceof Error ? err.message : String(err)}) — ` +\n \"running without syscall filter (bwrap FS/network confinement still applies).\",\n );\n return undefined;\n }\n}\n\nlet seccompFilterPath: string | undefined | null; // undefined = not tried; null = resolved absent\n/** M57 — exported so the interactive PTY backend reuses the SAME memoized x64-gated seccomp program. */\nexport function restrictedSeccompPath(): string | undefined {\n if (seccompFilterPath !== undefined) return seccompFilterPath ?? undefined;\n const path = seccompPathForArch(process.arch, (m) => console.warn(redactSecrets(m)));\n seccompFilterPath = path ?? null;\n return path;\n}\n\nlet warnedUnavailable = false;\n\n/** Test seam: reset the WARN-once latch. */\nexport function resetSandboxWarnLatch(): void {\n warnedUnavailable = false;\n}\n\n/** Durable sandbox posture for the UI — the honest answer to \"am I kernel-enforced right now?\". */\nexport interface SandboxPosture {\n mode: SandboxMode;\n enforced: boolean;\n detail: string;\n}\n\n/**\n * MEDIUM-2: compute the posture so a surface (TUI footer) can show enforcement DURABLY instead of a\n * one-shot warn. `danger-full-access` is honestly reported as unenforced; an unavailable bwrap reports\n * the downgrade reason so the user never believes they are confined when they are not.\n */\nexport function resolveSandboxPosture(opts: {\n mode: SandboxMode;\n detect?: () => BwrapDetection;\n}): SandboxPosture {\n if (opts.mode === \"danger-full-access\") {\n return { mode: opts.mode, enforced: false, detail: \"no confinement (danger-full-access)\" };\n }\n const detection = (opts.detect ?? detectBwrapMemoized)();\n if (!detection.ok) {\n return { mode: opts.mode, enforced: false, detail: `tool-gating only — ${detection.reason}` };\n }\n return { mode: opts.mode, enforced: true, detail: \"kernel (bwrap)\" };\n}\n\n/**\n * Options for `createSandboxBackend`, which probes for bubblewrap and returns a {@link LinuxSandbox}\n * when confinement is genuinely available or a `LocalSandbox` when it is not — warning once when the\n * absence is a failure, and silently when `mode` is `\"danger-full-access\"`, since that is an explicit\n * opt-out rather than a degradation.\n *\n * The declared return type is `SandboxBackend` either way, so it does not tell you which one you got.\n * Call `resolveSandboxPosture({ mode })` for that, and surface it durably — the warning fires once\n * per process and a user who missed it has no way to tell they are unconfined.\n *\n * `workDir` and `timeoutMs` are forwarded into the backend's `SandboxConfig`; `maxOutputBytes` and\n * the env policy are not, and keep their defaults. `network` only reaches the confined path, being\n * meaningless on a fallback where the network was never restricted. `detect` and `warn` exist so\n * tests can drive both branches without a real bubblewrap.\n */\nexport interface CreateSandboxBackendOptions {\n mode: SandboxMode;\n workDir?: string;\n network?: boolean;\n timeoutMs?: number;\n /** Injectable for tests; defaults to the real 3-probe detection. */\n detect?: () => BwrapDetection;\n /** Injectable for tests; defaults to console.warn. */\n warn?: (message: string) => void;\n}\n\n/**\n * Honest factory: bwrap available + mode wants confinement → `LinuxSandbox` (kernel enforcement,\n * running the VALIDATED absolute bin); `danger-full-access` → plain `LocalSandbox` silently (explicit\n * opt-out, `bwrap.rs:245-252`); bwrap unavailable → WARN once + `LocalSandbox` (the declarative M23\n * gating remains the guard). NEVER pretends to sandbox — the fallback is loud, mirroring Codex's\n * MISSING_BWRAP_WARNING. The durable posture lives in `resolveSandboxPosture` for the UI.\n */\nexport function createSandboxBackend(opts: CreateSandboxBackendOptions): SandboxBackend {\n const config: SandboxConfig = { workDir: opts.workDir, timeoutMs: opts.timeoutMs };\n if (opts.mode === \"danger-full-access\") return new LocalSandbox(config);\n\n const detection = (opts.detect ?? detectBwrapMemoized)();\n if (!detection.ok) {\n if (!warnedUnavailable) {\n warnedUnavailable = true;\n const warn = opts.warn ?? ((m: string) => console.warn(redactSecrets(m)));\n warn(\n `[sandbox] OS-level enforcement unavailable (${detection.reason}) — ` +\n `falling back to tool-level gating only (sandbox_mode=${opts.mode}).`,\n );\n }\n return new LocalSandbox(config);\n }\n return new LinuxSandbox(config, { mode: opts.mode, network: opts.network, bin: detection.bin });\n}\n\n/**\n * M75 T3.2 — warning latch for the INTERACTIVE path.\n *\n * Kept separate from `createSandboxBackend`'s latch on purpose: they are two distinct decisions\n * taken at distinct moments, and a user who only ever runs an interactive shell needs to see the\n * warning even if the non-interactive path already emitted it — otherwise the session where they\n * actually type commands would be the one without the alert.\n */\nlet interactiveWarned = false;\n\n/** Reset for tests — the latch is module state and tests need isolation. */\nexport function resetInteractiveWarnLatch(): void {\n interactiveWarned = false;\n}\n\n/**\n * The rule \"seccomp ONLY with restricted network\" — in ONE place.\n *\n * Codex installs the filter only when the network is closed (`landlock.rs:96-117`), and that is not\n * a detail: the cBPF program **denies the network syscalls** (`NETWORK_DENIED`). Applying it with\n * the network open produces the worst possible combination — bwrap **allows** the network (no\n * `--unshare-net`) and seccomp **denies** it with EPERM. The user asked for network, got the bind,\n * and the calls die.\n *\n * It existed duplicated: the constructor decided conditionally, `interactiveWrapCommand` installed\n * unconditionally. They had already diverged in the first version (M75 architecture review, proven\n * at runtime: `network:true` gave `--seccomp` interactively and not one-shot). Two copies of a\n * security rule is not duplicated form — it is duplicated KNOWLEDGE, and it had already diverged.\n */\nfunction seccompPathForNetwork(networkOpen: boolean): string | undefined {\n return networkOpen ? undefined : restrictedSeccompPath();\n}\n\n/**\n * Options for `interactiveWrapCommand`, the PTY counterpart of `createSandboxBackend`.\n *\n * They differ in what they hand back, and that is how you choose. A PTY owns its own spawn and\n * accepts no backend object, so this path returns a `(command, cwd) => string | null` transform: the\n * wrapped command line, or `null` meaning run it as-is. Use it when something else does the spawning;\n * use `createSandboxBackend` when you want an object that executes.\n *\n * Detection is consulted on every wrap instead of being frozen at construction, because an\n * interactive session outlives the probe — a bubblewrap binary that disappears mid-session stops\n * being asserted as present.\n *\n * `network` defaults to `false`, matching the non-interactive path, and carries the same consequence:\n * the seccomp filter is installed only when the network is restricted. The warn-once latch is\n * deliberately separate from the one `createSandboxBackend` keeps, so a user who only ever opens an\n * interactive shell still sees the \"runs WITHOUT kernel confinement\" warning in the session where\n * they type commands.\n */\nexport interface InteractiveWrapOptions {\n mode: SandboxMode;\n /** `true` keeps the network. Default `false`, same as non-interactive `run_shell`. */\n network?: boolean;\n /** Injectable for tests; defaults to the real memoized detection. */\n detect?: () => BwrapDetection;\n /** Injectable for tests; defaults to `console.warn` with redaction. */\n warn?: (message: string) => void;\n}\n\n/**\n * The decision to confine or degrade, separated from the wrap itself.\n *\n * Extracted because they are two responsibilities and the SDK's complexity gate separated them for\n * us: DECIDING (is confinement available? did the user opt out?) and APPLYING (assembling the argv).\n * Keeping them together pushed the closure past 10 cognitive complexity — and the linter was right:\n * the deciding part is the one with security consequences and deserves to be read on its own.\n *\n * Returns the validated binary when confinement exists, or `null` when it does not — warning ONCE,\n * and only when the absence is a failure (not when it is an opt-out).\n */\nfunction decideConfinement(opts: InteractiveWrapOptions): string | null {\n if (opts.mode === \"danger-full-access\") return null;\n\n const detection = (opts.detect ?? detectBwrapMemoized)();\n if (detection.ok) return detection.bin;\n\n if (!interactiveWarned) {\n interactiveWarned = true;\n const warn = opts.warn ?? ((m: string) => console.warn(redactSecrets(m)));\n warn(\n `[sandbox] OS-level enforcement unavailable (${detection.reason}) — interactive session ` +\n `runs WITHOUT kernel confinement (sandbox_mode=${opts.mode}).`,\n );\n }\n return null;\n}\n\n/**\n * The composition the interactive path needs — the counterpart of `createSandboxBackend`.\n *\n * `createSandboxBackend` solves this for the non-interactive path by returning a ready BACKEND. The\n * PTY accepts no backend: it owns the spawn and only allows transforming the command. This function\n * delivers the SAME decision in the shape the PTY accepts — `(command, cwd) => string | null` —\n * ready for `new PtyInteractiveBackend({ wrapCommand: interactiveWrapCommand({ mode }) })`.\n *\n * Detection is consulted on **every wrap**, not frozen at construction: an interactive session lives\n * for hours, and a stale positive detection would keep asserting confinement after the binary\n * disappeared (the `existsSync` revalidation lives inside `detectBwrapMemoized`).\n *\n * The two routes returning `null` are semantically different and the code does not merge them:\n * `danger-full-access` is an explicit opt-out and does NOT warn; bwrap being unavailable is a\n * failure and warns once.\n */\nexport function interactiveWrapCommand(\n opts: InteractiveWrapOptions,\n): (command: string, cwd: string) => string | null {\n return (command: string, cwd: string): string | null => {\n const bin = decideConfinement(opts);\n if (bin === null) return null;\n\n return wrapCommandForSandbox(\n opts.mode,\n {\n cwd,\n network: opts.network ?? false,\n env: allowlistedEnv(),\n bin,\n seccompPath: seccompPathForNetwork(opts.network ?? false),\n },\n command,\n );\n };\n}\n","/**\n * M6-3 — portable repo provisioner for the eval harness.\n *\n * Clones a repository and checks out a ref into an isolated working dir, issuing\n * every git command through {@link SandboxBackend.execute} (ADR D2 — same code\n * runs on Local/Docker/E2B; never a direct `child_process` import). Promotes\n * theocode's `prepareRepo` (`swebench-provision.ts:37`) onto the SDK's sandbox\n * abstraction.\n *\n * reference: knowledge-base/references/theocode-eval/lib/swebench-provision.ts:37\n * (clone+checkout), :13 (ProvisionError with instanceId).\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"../errors.js\";\nimport { LocalSandbox } from \"./local-sandbox.js\";\nimport { shellEscapePosix } from \"./shell-escape.js\";\nimport type { SandboxBackend } from \"./types.js\";\n\n/**\n * Raised when cloning or checking out a repo fails. Carries the `instanceId`\n * so a batch run can attribute the failure to the offending dataset row.\n */\nexport class RepoProvisionError extends TheokitAgentError {\n override readonly name = \"RepoProvisionError\";\n\n constructor(\n readonly instanceId: string,\n message: string,\n options: { cause?: unknown } = {},\n ) {\n super(`[${instanceId}] ${message}`, {\n code: \"repo_provision_failed\",\n isRetryable: false,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n });\n }\n}\n\n/** Options for {@link provisionRepo}. */\nexport interface ProvisionRepoOptions {\n /**\n * Clonable repo URL or local path. SECURITY: when this comes from an\n * untrusted dataset, the value is passed to `git clone` after a `--`\n * end-of-options terminator (no flag injection) and with the `ext::`\n * transport disabled (no arbitrary-command transport).\n */\n readonly repoUrl: string;\n /** Branch, tag, or commit SHA to check out. Rejected if it begins with `-`. */\n readonly ref: string;\n /**\n * Unique id for this row — names the target dir and any error. Validated to\n * `[A-Za-z0-9._-]` (no path traversal) since it becomes a directory name.\n */\n readonly instanceId: string;\n}\n\n/**\n * Reject ids that would escape the workdir or be parsed as a git flag. Must\n * start with an alphanumeric (blocks `.`, `..`, `-foo`, leading-dot names) and\n * thereafter allow only `[A-Za-z0-9._-]`.\n */\nconst SAFE_INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * Clone `repoUrl` into `<sandbox workdir>/<instanceId>` and check out `ref`.\n * Returns the absolute `repoDir` (resolved via `git rev-parse --show-toplevel`,\n * which is portable across backends). Throws {@link RepoProvisionError} naming\n * the `instanceId` when clone or checkout exits non-zero.\n *\n * The `sandbox` is optional (V3-5): when omitted, a default {@link LocalSandbox}\n * is used (clones into the process cwd's `<instanceId>`) — pass an explicit\n * sandbox (e.g. `LocalSandbox({ workDir })` / Docker / E2B) to control the workdir.\n */\nexport function provisionRepo(opts: ProvisionRepoOptions): Promise<{ repoDir: string }>;\nexport function provisionRepo(\n sandbox: SandboxBackend,\n opts: ProvisionRepoOptions,\n): Promise<{ repoDir: string }>;\nexport async function provisionRepo(\n sandboxOrOpts: SandboxBackend | ProvisionRepoOptions,\n maybeOpts?: ProvisionRepoOptions,\n): Promise<{ repoDir: string }> {\n const sandbox = maybeOpts !== undefined ? (sandboxOrOpts as SandboxBackend) : new LocalSandbox();\n const opts = maybeOpts ?? (sandboxOrOpts as ProvisionRepoOptions);\n const { repoUrl, ref, instanceId } = opts;\n\n // Validate untrusted-derivable inputs before they reach git/the shell.\n if (!SAFE_INSTANCE_ID.test(instanceId)) {\n throw new RepoProvisionError(\n instanceId,\n \"invalid instanceId: must match [A-Za-z0-9._-] (no path traversal)\",\n );\n }\n if (ref.startsWith(\"-\")) {\n throw new RepoProvisionError(instanceId, `invalid ref: must not begin with '-' (got ${ref})`);\n }\n\n // `--` terminates options (no `--upload-pack=` flag injection); `protocol.ext.allow=never`\n // blocks the `ext::` arbitrary-command transport. `file`/`https` stay allowed.\n const clone = await sandbox.execute(\n `git -c protocol.ext.allow=never clone --quiet -- ${shellEscapePosix(repoUrl)} ${shellEscapePosix(instanceId)}`,\n );\n if (clone.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `clone failed: ${clone.stderr.trim()}`);\n }\n\n const top = await sandbox.execute(\n `git -C ${shellEscapePosix(instanceId)} rev-parse --show-toplevel`,\n );\n if (top.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `resolve repoDir failed: ${top.stderr.trim()}`);\n }\n const repoDir = top.stdout.trim();\n\n // `ref` is validated above not to begin with `-`, so it cannot be parsed as a flag.\n const checkout = await sandbox.execute(\n `git -C ${shellEscapePosix(repoDir)} checkout --quiet ${shellEscapePosix(ref)}`,\n );\n if (checkout.exitCode !== 0) {\n throw new RepoProvisionError(instanceId, `checkout ${ref} failed: ${checkout.stderr.trim()}`);\n }\n\n return { repoDir };\n}\n"]}
|
package/docs/error-codes.md
CHANGED
|
@@ -6,10 +6,11 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
|
|
|
6
6
|
|
|
7
7
|
**Transport codes vs the rest.** `ErrorCode` in `errors.ts` is the small canonical union a provider failure maps onto — the codes marked *transport* below. Everything else is raised by a specific subsystem at a specific place, and a `catch` that only handles the union will meet them anyway.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
204 distinct code(s).
|
|
10
10
|
|
|
11
11
|
| Code | Kind | Raised by | Sites |
|
|
12
12
|
|---|---|---|---|
|
|
13
|
+
| `a2a_request_timeout` | domain | A2ARequestTimeoutError | `packages/sdk/src/a2a/message-bus.ts:31` |
|
|
13
14
|
| `aborted` | domain | TheokitAgentError | `packages/sdk/src/batch.ts:280` +1 |
|
|
14
15
|
| `agent_disposed` | domain | — | `packages/sdk/src/errors.ts:668` |
|
|
15
16
|
| `agent_id_already_exists` | domain | ConfigurationError | `packages/sdk/src/agent-helpers.ts:54` |
|
|
@@ -87,6 +88,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
|
|
|
87
88
|
| `invalid_input` | domain | MemoryAdapterError | `packages/memory-honcho/src/adapter.ts:98` +9 |
|
|
88
89
|
| `invalid_max_iterations` | domain | ConfigurationError | `packages/sdk/src/internal/local-agent/real-local-run.ts:215` |
|
|
89
90
|
| `invalid_memory_backend` | domain | ConfigurationError | `packages/sdk/src/internal/memory/index-manager-dispatch.ts:24` +1 |
|
|
91
|
+
| `invalid_memory_kind` | domain | ConfigurationError | `packages/sdk/src/internal/memory/storage/markdown-store.ts:118` |
|
|
90
92
|
| `invalid_model_selection` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/model-selection.ts:21` |
|
|
91
93
|
| `invalid_request` | transport | — | `packages/sdk/src/internal/error-mappers/vertex.ts:52` +1 |
|
|
92
94
|
| `invalid_retry_config` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/retry/with-retry.ts:67` |
|
|
@@ -4,7 +4,7 @@ Every public symbol the TheoKit workspace publishes, and the exact specifier to
|
|
|
4
4
|
|
|
5
5
|
A symbol listed under two specifiers is reachable from both, but that does NOT make the two interchangeable: a class emitted separately into a subpath entry is a distinct nominal type from the one in the root bundle, so passing one where the other is expected fails on a private field. When a symbol appears twice, import it and everything it is passed to from the SAME specifier.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
1126 export(s) across 45 entry point(s).
|
|
8
8
|
|
|
9
9
|
## `@theokit/acp`
|
|
10
10
|
|
|
@@ -787,6 +787,7 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
|
|
|
787
787
|
| Symbol | Kind | Summary |
|
|
788
788
|
|---|---|---|
|
|
789
789
|
| `A2AMessage` | interface | One message as a handler receives it. |
|
|
790
|
+
| `A2ARequestTimeoutError` | class | A peer did not answer a {@link MessageBus.request } within its timeout. |
|
|
790
791
|
| `AgentMailbox` | class | One agent's endpoint on a {@link MessageBus } : registers `agentId` on construction and forwards inbound messages to the handler installed by `onMessage`. |
|
|
791
792
|
| `DelegationCompleteContext` | interface | Context passed to {@link SubAgentSpec.onDelegationComplete } after the child settles. |
|
|
792
793
|
| `DelegationCompleteDecision` | interface | Decision returned from {@link SubAgentSpec.onDelegationComplete } . |
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/runtime/context/context-loaders.ts","../src/internal/runtime/context/context-import-resolver.ts","../src/internal/runtime/context/context-glob.ts","../src/internal/runtime/context/context-yaml-lite.ts","../src/internal/runtime/context/context-rules-frontmatter.ts","../src/internal/runtime/context/context-mdc-parser.ts","../src/internal/runtime/context/context-discovery-runner.ts"],"names":["resolvePath","z","dirname","readFile"],"mappings":";;;;;;;AAaA,IAAM,UAAA,GAAa,GAAA;AACnB,IAAM,UAAA,GAAa,GAAA;AACnB,IAAM,MAAA,GAAS,sCAAA;AAGR,IAAM,0BAAA,GAA6B;AAiCnC,SAAS,kBAAA,CAAmB,SAAiB,GAAA,EAA6B;AAC/E,EAAA,IAAI,OAAA,CAAQ,UAAU,GAAA,EAAK;AACzB,IAAA,OAAO,EAAE,SAAA,EAAW,KAAA,EAAO,YAAA,EAAc,OAAA,EAAQ;AAAA,E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A,CAAkB,IAAA,EAAM,EAAE,eAAA,EAAiB,IAAA,CAAK,iBAAiB,CAAA;AACtF,EAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AACjC,EAAA,IAAI,UAAU,MAAA,CAAO,OAAA;AACrB,EAAA,IAAI,KAAK,aAAA,EAAe;AACtB,IAAA,OAAA,GAAU,MAAM,cAAA,CAAe,OAAA,EAAS,IAAA,EAAM;AAAA,MAC5C,OAAA,kBAAS,IAAI,GAAA,CAAI,CAAC,IAAI,CAAC,CAAA;AAAA,MACvB,KAAA,EAAO,CAAA;AAAA,MACP,iBAAiB,IAAA,CAAK,eAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAKtB,WAAA,EAAa,IAAA,CAAK,UAAA,IAAc,OAAA,IAAW,IAAA,CAAK;AAAA,KACjD,CAAA;AAAA,EACH;AACA,EAAA,OAAO;AAAA,IACL,EAAA;AAAA,IACA,MAAA,EAAQ,IAAA;AAAA,IACR,OAAA;AAAA,IACA,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,WAAW,MAAA,CAAO;AAAA,GACpB;AACF","file":"chunk-5PHVENFV.js","sourcesContent":["/**\n * Context file loaders + truncation (T1.2, ADRs D154 / D155 / D159).\n *\n * Reads context source files from disk, applies the per-file size cap\n * with 70%/20% head/tail truncation, and emits the\n * `context_files_truncated` telemetry counter when the cap fires.\n * Pure (no I/O) for `truncateWithMarker` — testable in isolation.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\n\nconst HEAD_RATIO = 0.7;\nconst TAIL_RATIO = 0.2;\nconst MARKER = \"\\n\\n…[truncated by theokit]\\n\\n\";\n\n/** Default per-file cap (40k chars ≈ 10k tokens). D155. */\nexport const DEFAULT_MAX_BYTES_PER_FILE = 40_000;\n\nexport interface LoadedSource {\n /** Absolute path the content came from. */\n readonly source: string;\n readonly content: string;\n readonly originalBytes: number;\n readonly truncated: boolean;\n}\n\nexport interface TruncateResult {\n readonly truncated: boolean;\n readonly finalContent: string;\n}\n\n/**\n * Cap `content` at `max` characters with 70%/20% head/tail truncation\n * and an explicit marker. Pure — no I/O, no telemetry.\n *\n * EC-C: when `max <= MARKER.length`, skip the marker entirely and\n * return a head-only slice. Without this guard, `budget = max -\n * MARKER.length` would go negative and `content.slice(-tailBytes)`\n * would slice from the END of the string rather than truncating.\n *\n * EC-H: codepoint integrity — `String.slice()` operates on UTF-16\n * code units, which can split surrogate pairs. We accept that\n * trailing/leading replacement chars (U+FFFD) may appear at boundaries.\n * Modern LLMs tolerate them; byte-exact safety would require Buffer\n * slicing + TextDecoder with `fatal: true` retry, which adds complexity\n * without value.\n *\n * @public\n */\nexport function truncateWithMarker(content: string, max: number): TruncateResult {\n if (content.length <= max) {\n return { truncated: false, finalContent: content };\n }\n // EC-C: max too small to fit even the marker — return head-only slice.\n if (max <= MARKER.length) {\n return { truncated: true, finalContent: content.slice(0, max) };\n }\n const budget = max - MARKER.length;\n const headBytes = Math.floor(budget * (HEAD_RATIO / (HEAD_RATIO + TAIL_RATIO)));\n const tailBytes = budget - headBytes;\n return {\n truncated: true,\n finalContent: content.slice(0, headBytes) + MARKER + content.slice(-tailBytes),\n };\n}\n\n/**\n * Read a file from disk and apply the per-file cap. Emits telemetry\n * counter when truncation fires.\n *\n * EC-G: file deleted between discovery and read (FS race) → returns\n * `undefined`, never throws.\n *\n * @internal\n */\nexport async function loadPlainMarkdown(\n absPath: string,\n opts: { maxBytesPerFile?: number } = {},\n): Promise<LoadedSource | undefined> {\n const max = opts.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;\n let content: string;\n try {\n content = await readFile(absPath, \"utf8\");\n } catch {\n // EC-G: ENOENT / EACCES / etc → caller treats as missing.\n return undefined;\n }\n const { truncated, finalContent } = truncateWithMarker(content, max);\n if (truncated) {\n emitTruncationCounter(absPath);\n }\n return {\n source: absPath,\n content: finalContent,\n originalBytes: content.length,\n truncated,\n };\n}\n\n/**\n * EC-L: telemetry no-op when OTel is not imported. We import the tracer\n * lazily and use `safeCall` so the lookup never throws and never pulls\n * OTel into the import graph for users without `@opentelemetry/api`\n * installed.\n *\n * @internal\n */\nfunction emitTruncationCounter(source: string): void {\n // Lazy resolution via globalThis avoids static import of telemetry/tracer.\n // Tests can spy via the same path; production users without OTel see no-op.\n const tracer = (\n globalThis as { __theokit_tracer?: { inc?: (k: string, attrs: unknown) => void } }\n ).__theokit_tracer;\n if (tracer?.inc === undefined) return;\n try {\n tracer.inc(\"context_files_truncated\", { file: source });\n } catch {\n // Telemetry must never break the loader.\n }\n}\n","/**\n * `@path/to/file` import resolver (T2.1, ADR D156).\n *\n * Anthropic/Gemini convention: lines that are EXACTLY `@path` get\n * replaced with the imported file's content, recursively (5-hop cap),\n * with cycle detection. Inline `see @x.md, also @y.md` references are\n * NOT resolved (EC-Q — own-line only, mirrors Anthropic's actual\n * behavior).\n *\n * EC-D fix: every imported file is itself capped at `maxBytesPerFile`\n * via `loadPlainMarkdown` BEFORE concatenation. Prevents a CLAUDE.md\n * with 5 imports of 30k each from ballooning to 150k of imported\n * content before the outer cap fires.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, resolve as resolvePath } from \"node:path\";\n\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { insideRoot } from \"./path-containment.js\";\n\n/** EC-Q: line-anchored. `@path` must be alone on its line. */\nconst IMPORT_RE = /^@(\\S+)\\s*$/gm;\nconst MAX_HOPS = 5;\n\nexport interface ResolveImportsOptions {\n /** Absolute paths already resolved (cycle detection). */\n readonly visited: Set<string>;\n /** Current recursion depth — caps at MAX_HOPS. */\n readonly depth: number;\n /** Per-import file cap (EC-D). Forwarded to loadPlainMarkdown. */\n readonly maxBytesPerFile: number;\n /**\n * The directory an import may not escape. When set, a target resolving outside it is\n * refused and replaced with a placeholder.\n *\n * The file carrying the import is REPOSITORY-CONTROLLED — `CLAUDE.md` and `GEMINI.md`\n * are the two default specs with `followImports: true`, and both are found by\n * `git-root-walk` inside the tree the agent was pointed at. Without a root, a cloned\n * repository could name `@~/.ssh/id_rsa` or any absolute path and have its contents\n * inlined into the system prompt, and from there sent to the model provider. The\n * traversal guard that already existed (`isSafePattern`) guards the discovery PATTERN,\n * not the import TARGET, so it never saw this.\n *\n * OPTIONAL, so a caller outside the discovery path keeps the previous behaviour rather\n * than breaking on an upgrade. `runDiscovery` always supplies `gitRoot ?? cwd` — the\n * same value it already uses to keep absolute paths out of `<source name=\"\">`.\n */\n readonly projectRoot?: string;\n}\n\n/**\n * Resolve `@path` directives in `content`. Each match is replaced with\n * the imported file content (already cap-truncated per EC-D), and\n * recursion continues on the resolved content until MAX_HOPS or cycle.\n *\n * Failure modes (placeholders, never throws):\n * - file not found → `[@import not found: <path>]`\n * - cycle detected → `[@import cycle detected: <path>]`\n * - depth exceeded → trailing `\\n\\n…[@import depth limit 5 reached]\\n\\n`\n *\n * @internal\n */\nexport async function resolveImports(\n content: string,\n basePath: string,\n opts: ResolveImportsOptions,\n): Promise<string> {\n if (opts.depth >= MAX_HOPS) {\n return `${content}\\n\\n…[@import depth limit ${MAX_HOPS} reached]\\n\\n`;\n }\n const baseDir = dirname(basePath);\n return replaceAsync(content, IMPORT_RE, async (raw) => {\n const absolute = resolveImportPath(raw, baseDir);\n // Containment BEFORE the read. Reporting the refusal after loading the file would\n // already have put the bytes in memory, and the placeholder names the path the author\n // wrote rather than the resolved one — echoing `/home/<user>/.ssh/id_rsa` back into the\n // prompt would leak the layout of the machine to the same untrusted document.\n if (opts.projectRoot !== undefined && !insideRoot(absolute, opts.projectRoot)) {\n return `[@import outside the project root, refused: ${raw}]`;\n }\n if (opts.visited.has(absolute)) {\n return `[@import cycle detected: ${raw}]`;\n }\n opts.visited.add(absolute);\n const loaded = await loadPlainMarkdown(absolute, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) {\n return `[@import not found: ${raw}]`;\n }\n // Recurse with same visited set + incremented depth. `projectRoot` is FORWARDED: an\n // imported file is repository-controlled too, so a root that applied only at depth 0\n // would be escapable in one extra hop.\n return resolveImports(loaded.content, absolute, {\n visited: opts.visited,\n depth: opts.depth + 1,\n maxBytesPerFile: opts.maxBytesPerFile,\n ...(opts.projectRoot === undefined ? {} : { projectRoot: opts.projectRoot }),\n });\n });\n}\n\nfunction resolveImportPath(raw: string, baseDir: string): string {\n if (raw.startsWith(\"~/\")) {\n return resolvePath(join(homedir(), raw.slice(2)));\n }\n if (isAbsolute(raw)) {\n return resolvePath(raw);\n }\n return resolvePath(join(baseDir, raw));\n}\n\n/**\n * Async equivalent of `String.prototype.replace` — sequential. Returns\n * `content` with every `re` match replaced by `await replacer(match)`.\n *\n * @internal\n */\nasync function replaceAsync(\n content: string,\n re: RegExp,\n replacer: (raw: string) => Promise<string>,\n): Promise<string> {\n const matches: Array<{ match: string; raw: string; index: number }> = [];\n // Reset lastIndex; clone the regex to avoid stateful traps.\n const localRe = new RegExp(re.source, re.flags);\n let m: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex loop\n while ((m = localRe.exec(content)) !== null) {\n matches.push({ match: m[0], raw: m[1] ?? \"\", index: m.index });\n if (m.index === localRe.lastIndex) localRe.lastIndex += 1;\n }\n if (matches.length === 0) return content;\n let result = \"\";\n let cursor = 0;\n for (const entry of matches) {\n result += content.slice(cursor, entry.index);\n result += await replacer(entry.raw);\n cursor = entry.index + entry.match.length;\n }\n result += content.slice(cursor);\n return result;\n}\n","/**\n * Shared glob → RegExp compiler for context discovery (extracted from the\n * MDC parser so the `.cursor/rules/*.mdc` and `.theokit/rules/*.md` parsers\n * share ONE implementation — DRY, no new dependency).\n *\n * Supports `**` (any depth), `*` (single path segment, no `/`), `?` (single\n * non-separator char). Sufficient for the patterns Cursor and Claude Code\n * themselves recommend.\n *\n * @internal\n */\nexport function globToRegex(glob: string): RegExp {\n // Support **/ (zero-or-more path segments), ** (any depth), * (single\n // segment), ? (single non-separator char). `**/` collapses so `src/**/*.ts`\n // matches `src/foo.ts` AND `src/a/b/foo.ts` — the semantics Cursor and Claude\n // Code document (\"src/**/* → all files under src/\"). `*` and `?` never cross a\n // `/` (strict glob segment semantics). Escape other regex metas.\n const compiled = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*\\//g, \"::GLOBSTAR_SLASH::\")\n .replace(/\\*\\*/g, \"::GLOBSTAR::\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/::GLOBSTAR_SLASH::/g, \"(?:.*/)?\")\n .replace(/::GLOBSTAR::/g, \".*\");\n return new RegExp(`^${compiled}$`);\n}\n\n/**\n * True when any of `patterns` glob-matches any of `paths`. Central helper so\n * both rule parsers agree on activation semantics.\n *\n * @internal\n */\nexport function anyGlobMatches(\n patterns: ReadonlyArray<string>,\n paths: ReadonlyArray<string>,\n): boolean {\n if (patterns.length === 0 || paths.length === 0) return false;\n const res = patterns.map(globToRegex);\n return paths.some((p) => res.some((re) => re.test(p)));\n}\n","/**\n * Minimal YAML-subset frontmatter parsing shared by the `.cursor/rules/*.mdc`\n * and `.theokit/rules/*.md` parsers (extracted for DRY — one parser, one set\n * of edge-case behaviours, no new dependency).\n *\n * Handles `key: value` lines (string scalars, booleans, integers) and `key:`\n * followed by indented `- item` arrays or inline `[a, b]` arrays. Sufficient\n * for the small, fixed frontmatter field sets these rule files use. Throws on\n * a truly malformed line (no colon).\n *\n * NOTE — distinct from the sibling `yaml-frontmatter.ts` `parseSimpleYaml` on\n * purpose: that one parses INLINE arrays only (`key: [a, b]`), whereas rule\n * files (`.cursor/rules/*.mdc`, `.theokit/rules/*.md`) use MULTI-LINE `- item`\n * lists (`paths:` / `globs:`), which this parser adds. Unifying onto the inline\n * parser would drop multi-line list support; unifying the other way would touch\n * the skills/subagents/persistence loaders that depend on the inline one. The\n * two intentionally coexist until a shared parser handles both shapes.\n *\n * @internal\n */\n\nconst FRONTMATTER_RE = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/;\n\nexport interface FrontmatterSplit {\n /** Raw YAML block between the `---` fences, or undefined when absent. */\n readonly yaml: string | undefined;\n /** The markdown body after the frontmatter (or the whole content). */\n readonly body: string;\n}\n\n/**\n * Split `---`-fenced frontmatter from the body. When no frontmatter fence is\n * present, `yaml` is undefined and `body` is the whole content.\n *\n * @internal\n */\nexport function splitFrontmatter(content: string): FrontmatterSplit {\n const m = FRONTMATTER_RE.exec(content);\n if (m === null) return { yaml: undefined, body: content };\n return { yaml: m[1] ?? \"\", body: m[2] ?? \"\" };\n}\n\n/**\n * Parse the minimal YAML subset. Throws on a line without a colon (malformed).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: YAML-subset parser handles scalars + multi-line arrays + inline arrays in a single pass; extracting helpers fragments the line-state machine.\nexport function parseSimpleYaml(yaml: string): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const lines = yaml.split(/\\r?\\n/);\n let i = 0;\n while (i < lines.length) {\n const line = lines[i];\n i += 1;\n if (line === undefined) continue;\n const trimmed = line.trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n const colon = trimmed.indexOf(\":\");\n if (colon === -1) throw new Error(`Invalid YAML line: ${trimmed}`);\n const key = trimmed.slice(0, colon).trim();\n const rest = trimmed.slice(colon + 1).trim();\n if (rest === \"\") {\n // Possible array; collect indented `- item` lines.\n const items: string[] = [];\n while (i < lines.length) {\n const next = lines[i];\n if (next === undefined) break;\n const nextTrim = next.trim();\n if (nextTrim.startsWith(\"- \")) {\n items.push(parseScalar(nextTrim.slice(2).trim()) as string);\n i += 1;\n } else if (nextTrim === \"\") {\n i += 1;\n } else {\n break;\n }\n }\n out[key] = items;\n } else if (rest.startsWith(\"[\") && rest.endsWith(\"]\")) {\n // Inline array `globs: [\"**/*.ts\", \"**/*.tsx\"]`\n const inner = rest.slice(1, -1).trim();\n out[key] =\n inner === \"\"\n ? []\n : inner.split(\",\").map((s) => parseScalar(s.trim().replace(/^[\"']|[\"']$/g, \"\")));\n } else {\n out[key] = parseScalar(rest);\n }\n }\n return out;\n}\n\nfunction parseScalar(s: string): string | boolean | number {\n if (s === \"true\") return true;\n if (s === \"false\") return false;\n if (/^-?\\d+$/.test(s)) return parseInt(s, 10);\n // Strip surrounding quotes if present.\n return s.replace(/^[\"']|[\"']$/g, \"\");\n}\n","/**\n * Parser for `.theokit/rules/*.md` — theokit-native path-scoped rules,\n * mirroring Claude Code's `.claude/rules/`.\n *\n * Frontmatter fields:\n * - `paths` — glob-pattern array (Claude Code parity: `.claude/rules` uses `paths:`).\n * - `globs` — glob-pattern array (Cursor-compatible alias; unioned with `paths`).\n * - `alwaysApply` — activate unconditionally (no scope needed).\n * - `enabled` — set `false` to disable the rule entirely (wins over everything).\n * - `description` — human note; not used for activation in v1.\n *\n * Activation (`shouldActivateRule`):\n * - `enabled: false` → never activates.\n * - `alwaysApply: true` → always activates.\n * - otherwise → activates iff a `paths`/`globs` pattern matches an in-scope\n * file (the caller's `agent.send(..., { contextPaths })`). With no in-scope\n * files, a scoped rule stays dormant (parity with Cursor `.mdc`).\n *\n * A file with no `---` frontmatter is treated as an unconditional rule\n * (`alwaysApply: true`). Malformed YAML → `undefined` (caller drops + counts).\n *\n * Glob + YAML subset are shared with the MDC parser (DRY, no new dependency).\n *\n * NOTE — no internal-visibility tag in this block. `tsconfig.base.json` sets `stripInternal: true`,\n * and TypeScript scans EVERY leading comment range of the declaration that follows, including the\n * import right below this one. The tag that used to sit here deleted that import from the emitted\n * `.d.ts`, leaving the types it binds unresolvable for any consumer running type-aware lint\n * (usetheodev/theokit-sdk#283 records the same trap on a declaration).\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/**\n * YAML frontmatter schema for `.theokit/rules/*.md` files.\n *\n * Every field is optional, and unknown keys are dropped rather than rejected — `safeParse` failing\n * therefore means a declared key had the wrong TYPE (`paths` as a bare string, `enabled` as the\n * string `\"false\"`), never that an unexpected key was present.\n *\n * Exported because {@link RulesFrontmatter} is inferred from it and appears in the signature of\n * {@link shouldActivateRule}, which `@theokit/sdk/context` publishes: the constant has to reach the\n * emitted declarations for that inferred type to resolve in a consumer's project.\n */\nexport const RulesFrontmatterSchema = z.object({\n description: z.string().optional(),\n paths: z.array(z.string()).optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n enabled: z.boolean().optional(),\n});\n\nexport type RulesFrontmatter = z.infer<typeof RulesFrontmatterSchema>;\n\nexport interface RulesParseResult {\n readonly frontmatter: RulesFrontmatter;\n readonly body: string;\n}\n\n/**\n * Split a `.theokit/rules/*.md` document into its frontmatter and its body.\n *\n * A file with no `---` fence is not an error: the whole text becomes the body and the frontmatter\n * is synthesised as `{ alwaysApply: true }`, so a plain markdown rule with no metadata applies\n * unconditionally. That default is the one thing to know before adding a fence — adding one and\n * omitting both `alwaysApply` and a path pattern turns an always-on rule into a dormant one.\n *\n * `undefined` means the fence was there and its contents did not survive: YAML the lite parser\n * could not read, or a shape the schema rejected (`paths` as a bare string rather than a list,\n * `enabled` as `\"false\"` rather than `false`). It never throws, and it does not say WHICH of the\n * two happened — the caller drops the file and counts it.\n *\n * Unknown frontmatter keys are dropped rather than rejected, so a misspelled `alwaysAply` parses\n * fine and simply has no effect.\n *\n * Nothing here decides whether the rule applies; that is `shouldActivateRule`.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport function parseRules(content: string): RulesParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = RulesFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether a parsed rule applies to this turn, given the files in scope.\n *\n * Checked in strict order, first match wins:\n *\n * 1. `enabled: false` — never applies, whatever else the frontmatter says. This overrides\n * `alwaysApply: true`, which is the point of having it.\n * 2. `alwaysApply: true` — applies, and `inScopePaths` is not consulted.\n * 3. otherwise — applies only if some pattern from `paths` or `globs` matches some path in\n * `inScopePaths`. The two lists are a union, not alternatives; `globs` exists for\n * Cursor compatibility and behaves identically.\n *\n * A scoped rule with an EMPTY `inScopePaths` never applies. That is the case worth planning for:\n * `contextPaths` is empty on a plain `agent.send()`, so a rule scoped by path stays dormant until\n * the caller declares which files the turn is about. It is quiet — a dormant rule looks exactly\n * like a rule that was never written.\n *\n * A rule with a fence but no patterns and no `alwaysApply` also never applies, since step 3 has\n * nothing to match.\n *\n * `description` is not consulted. It is a note for humans, not an activation condition.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport function shouldActivateRule(\n fm: RulesFrontmatter,\n inScopePaths: ReadonlyArray<string>,\n): boolean {\n if (fm.enabled === false) return false;\n if (fm.alwaysApply === true) return true;\n const patterns = [...(fm.paths ?? []), ...(fm.globs ?? [])];\n if (patterns.length === 0) return false;\n return anyGlobMatches(patterns, inScopePaths);\n}\n","/**\n * MDC (Markdown Cursor) parser for `.cursor/rules/*.mdc` (T3.1, ADR D154).\n *\n * Parses YAML frontmatter with `description` / `globs` / `alwaysApply`\n * fields. Honors activation per Cursor's docs:\n * - `alwaysApply: true` → activates unconditionally.\n * - `alwaysApply: false` + matching glob in `touchedFiles` → activates.\n * - `alwaysApply: false` + no glob match → skipped.\n *\n * **EC-I (v1 semantic):** at `agent.send()` time, `touchedFiles` is empty\n * UNLESS the caller passes `contextPaths` (the in-scope file set). When\n * `contextPaths` is provided, per-glob activation fires; otherwise only\n * `alwaysApply: true` rules activate. Description-based \"agent requested\"\n * classification is out of scope.\n *\n * Glob matching + the YAML subset are shared with the `.theokit/rules/*.md`\n * parser via `context-glob.ts` / `context-yaml-lite.ts` (DRY, no new dep).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for MDC files. @internal */\nexport const McdFrontmatterSchema = z.object({\n description: z.string().optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n});\n\nexport type McdFrontmatter = z.infer<typeof McdFrontmatterSchema>;\n\nexport interface McdParseResult {\n readonly frontmatter: McdFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.mdc` content. Returns frontmatter + body. EC-18: when the\n * file has no `---` frontmatter, returns `frontmatter: {alwaysApply:\n * true}` so the body is treated as an unconditional rule.\n *\n * On YAML parse error, returns `undefined` and the caller emits a\n * telemetry counter (EC-21).\n *\n * @internal\n */\nexport function parseMdc(content: string): McdParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n // EC-18: no frontmatter — treat as alwaysApply\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = McdFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether an MDC rule activates given the currently-touched\n * files. EC-I: empty `touchedFiles` → only `alwaysApply: true`\n * activates.\n *\n * @internal\n */\nexport function shouldActivate(fm: McdFrontmatter, touchedFiles: ReadonlyArray<string>): boolean {\n if (fm.alwaysApply === true) return true;\n if (fm.globs === undefined || fm.globs.length === 0) return false;\n return anyGlobMatches(fm.globs, touchedFiles);\n}\n","/**\n * Multi-format context discovery runner (T5.1, ADRs D150-D156).\n *\n * Walks `DEFAULT_DISCOVERY_SPECS` (or caller override), loads each\n * spec via the appropriate parser, applies `@import` resolution where\n * declared, and returns a flat list of `AggregatorSource[]` ready for\n * the aggregate cap.\n *\n * **EC-E privacy fix:** source disambiguation uses\n * `relative(gitRoot ?? cwd, ...)` — NEVER absolute paths in\n * `<source name=\"\">`.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, relative } from \"node:path\";\n\nimport type { AggregatorSource } from \"./context-aggregator.js\";\nimport {\n DEFAULT_DISCOVERY_SPECS,\n type DiscoverySpec,\n findGitRoot,\n walkUpForFile,\n walkUpForGlob,\n} from \"./context-discovery.js\";\nimport { resolveImports } from \"./context-import-resolver.js\";\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { parseMdc, shouldActivate } from \"./context-mdc-parser.js\";\nimport { parseRules, shouldActivateRule } from \"./context-rules-frontmatter.js\";\n\n/**\n * Input to the context-discovery run: where to walk, how much of each file to keep, and which\n * trust boundary an `@import` may not cross.\n *\n * `cwd` and `maxBytesPerFile` are required because neither has a safe default — an unset root walks\n * the wrong tree, and an unset cap lets one large file consume the context window.\n *\n * `importRoot` is the field to reach for when the caller's trust boundary is narrower than the\n * repository. Left unset, the repository IS the boundary (`gitRoot ?? cwd`), which is the honest\n * default for a document found by walking the repository — but it does mean an `@import` can pull\n * in any file the repo contains.\n *\n * @public — re-exported from '@theokit/sdk/context', and therefore under semver.\n */\nexport interface DiscoveryRunnerOptions {\n /** Workspace root passed to all discovery scopes. */\n readonly cwd: string;\n /** Per-file truncation cap (D155). */\n readonly maxBytesPerFile: number;\n /** Optional override of the default registry. */\n readonly specs?: ReadonlyArray<DiscoverySpec>;\n /** Cursor MDC: file paths the LLM has touched this turn (EC-I: empty at send-time). */\n readonly touchedFiles?: ReadonlyArray<string>;\n /** When true, skip `theokit-context` spec — caller already handles the legacy path. */\n readonly skipLegacyTheokitContext?: boolean;\n /**\n * The root an `@import` may not escape. Defaults to `gitRoot ?? cwd` — the same value\n * this runner already uses to keep absolute paths out of `<source name=\"\">`.\n *\n * Present so an embedder with a trust boundary narrower than the repository can declare\n * it. Absent, the repository IS the boundary, which is the honest default for a document\n * discovered by walking the repository.\n */\n readonly importRoot?: string;\n}\n\n/**\n * Find, read and parse every context file the specs describe, and return them ready for the\n * aggregator.\n *\n * Specs are processed in the order given — `opts.specs` when supplied, otherwise\n * `DEFAULT_DISCOVERY_SPECS` — and within a spec, in the order its scope resolves paths. The\n * returned array carries `priority` on each source; it is NOT sorted here, so the aggregator is\n * what applies the ordering.\n *\n * A path already emitted is skipped, across specs as well as within one. Paths arrive resolved\n * through `realpath`, so two specs pointing at the same physical file through a symlink produce\n * one source rather than two.\n *\n * Missing and unreadable files are not errors: a file that does not exist is simply not matched,\n * and one that fails to read or parse is dropped and the run continues. A frontmatter file whose\n * activation conditions do not hold — `enabled: false`, or a scope that no touched file matches —\n * is dropped the same way. So a shorter result than expected means \"nothing qualified\", and this\n * function will not tell you which of those it was.\n *\n * Reads the filesystem and nothing else. No network, no writes, and no mutation of `opts`.\n *\n * Privacy: `<source name=\"\">` is built from the path RELATIVE to the git root (or `cwd` when\n * there is no git root), never an absolute path, so a home directory never reaches the prompt.\n * `@import` resolution is bounded by `opts.importRoot`, defaulting to that same root — a document\n * cannot pull in a file from outside the repository.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: per-spec dispatch ladder + cross-spec dedup is a flat orchestrator; splitting would obscure the priority-merge invariant.\nexport async function runDiscovery(opts: DiscoveryRunnerOptions): Promise<AggregatorSource[]> {\n const gitRoot = findGitRoot(opts.cwd);\n const specs = opts.specs ?? DEFAULT_DISCOVERY_SPECS;\n const out: AggregatorSource[] = [];\n const seenReal = new Set<string>();\n\n for (const spec of specs) {\n if (opts.skipLegacyTheokitContext && spec.id === \"theokit-context\") continue;\n const paths = await resolvePathsForSpec(spec, opts.cwd, gitRoot);\n for (const path of paths) {\n if (seenReal.has(path)) continue;\n seenReal.add(path);\n const source = await loadOneSource(spec, path, opts, gitRoot);\n if (source !== undefined) out.push(source);\n }\n }\n return out;\n}\n\nasync function resolvePathsForSpec(\n spec: DiscoverySpec,\n cwd: string,\n gitRoot: string | undefined,\n): Promise<string[]> {\n if (spec.scope === \"cwd-only\") {\n return walkUpForFile(cwd, spec.pattern, cwd);\n }\n if (spec.scope === \"git-root-walk\") {\n return walkUpForFile(cwd, spec.pattern, gitRoot ?? cwd);\n }\n // globbed\n return walkUpForGlob(cwd, spec.pattern);\n}\n\nasync function loadOneSource(\n spec: DiscoverySpec,\n path: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n // EC-E privacy: name uses relative-to-git-root for disambiguation;\n // NEVER absolute paths in the public `<source name=\"\">` attribute.\n // For cwd-only specs (THEO.md), no disambiguation is needed because\n // the scope can only ever match a single file.\n const relPath = relative(gitRoot ?? opts.cwd, dirname(path));\n const needsSuffix = spec.scope !== \"cwd-only\" && relPath !== \"\" && relPath !== \".\";\n const id = needsSuffix ? `${spec.id}@${relPath}` : spec.id;\n\n if (spec.parser === \"mdc\") {\n return loadMdcSource(spec, path, id, opts);\n }\n if (spec.parser === \"rules-frontmatter\") {\n return loadRulesSource(spec, path, id, opts);\n }\n if (spec.parser === \"frontmatter-zod\") {\n // Legacy `.theokit/context/*.md` — handled by `loadContextConfig` in\n // `context-manager.ts` for backward compat. We skip here unless caller\n // explicitly wants us to load it (currently always skipped).\n return undefined;\n }\n // plain-markdown\n return loadPlainMarkdownSource(spec, path, id, opts, gitRoot);\n}\n\n/**\n * Shared read → parse → activation-gate → source pipeline for the frontmatter\n * discovery parsers (mdc, rules). Binds the parser + the activation predicate so\n * the mdc and rules loaders differ only in those two, not in the surrounding\n * read/guard/shape boilerplate (DRY).\n */\nasync function loadParsedSource<F>(\n spec: DiscoverySpec,\n path: string,\n id: string,\n parse: (raw: string) => { frontmatter: F; body: string } | undefined,\n isActive: (frontmatter: F) => boolean,\n): Promise<AggregatorSource | undefined> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n return undefined;\n }\n const parsed = parse(raw);\n if (parsed === undefined || !isActive(parsed.frontmatter)) return undefined;\n return { id, source: path, content: parsed.body, priority: spec.priority, truncated: false };\n}\n\nfunction loadMdcSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseMdc, (fm) =>\n shouldActivate(fm, opts.touchedFiles ?? []),\n );\n}\n\nfunction loadRulesSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseRules, (fm) =>\n shouldActivateRule(fm, opts.touchedFiles ?? []),\n );\n}\n\nasync function loadPlainMarkdownSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n const loaded = await loadPlainMarkdown(path, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) return undefined;\n let content = loaded.content;\n if (spec.followImports) {\n content = await resolveImports(content, path, {\n visited: new Set([path]),\n depth: 0,\n maxBytesPerFile: opts.maxBytesPerFile,\n // The document carrying the import is repository-controlled, so the repository is the\n // boundary it may not cross. Without this, `CLAUDE.md` / `GEMINI.md` — the two specs\n // with `followImports: true` — could name any absolute or `~/` path and have it\n // inlined into the system prompt.\n projectRoot: opts.importRoot ?? gitRoot ?? opts.cwd,\n });\n }\n return {\n id,\n source: path,\n content,\n priority: spec.priority,\n truncated: loaded.truncated,\n };\n}\n"]}
|