Multiplayer agent harness for work.
Share the tool-descriptor parser between core and the CLI (#1997)
Regan Bellf4685550567f
diff --git a/cli/src/commands/conformance.ts b/cli/src/commands/conformance.tsindex 12ee1221b..aa53797d5 100644--- a/cli/src/commands/conformance.ts+++ b/cli/src/commands/conformance.ts@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";import { type Target, type QmConfig } from "../config.ts";import { deploymentLayerBundle, deploymentLayerRequest, type DeploymentLayerBundle } from "../deployment-layer.ts";import { CliError, errMessage, header, ok, step } from "../log.ts";-import { parseToolDescriptor, type ToolDescriptor } from "../sandbox-layer.ts";+import { parseToolDescriptor, type ToolDescriptor } from "../tool-descriptor.ts";import { canonicalJson } from "../util.ts";import { runChecks } from "./check.ts";import { hostingProvider } from "../backends/registry.ts";diff --git a/cli/src/contract.d.ts b/cli/src/contract.d.tsindex 115612696..ea5be6ee0 100644--- a/cli/src/contract.d.ts+++ b/cli/src/contract.d.ts@@ -1,6 +1,7 @@export { loadConfigAt, sandboxCoreEnv, securityScreenEnv, CONTRACT_VERSION as contractVersion } from "./config.ts";export { orgEnv } from "./services.ts";-export { compileApproval, parseSkillFrontmatter, validateSandboxLayer } from "./sandbox-layer.ts";+export { compileApproval } from "./tool-descriptor.ts";+export { parseSkillFrontmatter, validateSandboxLayer } from "./sandbox-layer.ts";export { renderTaskDefinition } from "./backends/aws.ts";export { HOSTING_PROVIDER_IDS, hostingProviderChoices, isTarget } from "./providers.ts";export type {@@ -12,12 +13,11 @@ export type {Target,QmConfig,} from "./config.ts";+export type { SandboxValidation, SkillFrontmatter } from "./sandbox-layer.ts";export type {ApprovalDecision,- SandboxValidation,- SkillFrontmatter,ToolApproval,ToolAuthDescriptor,ToolCredentialPath,ToolDescriptor,-} from "./sandbox-layer.ts";+} from "./tool-descriptor.ts";diff --git a/cli/src/contract.ts b/cli/src/contract.tsindex 115612696..ea5be6ee0 100644--- a/cli/src/contract.ts+++ b/cli/src/contract.ts@@ -1,6 +1,7 @@export { loadConfigAt, sandboxCoreEnv, securityScreenEnv, CONTRACT_VERSION as contractVersion } from "./config.ts";export { orgEnv } from "./services.ts";-export { compileApproval, parseSkillFrontmatter, validateSandboxLayer } from "./sandbox-layer.ts";+export { compileApproval } from "./tool-descriptor.ts";+export { parseSkillFrontmatter, validateSandboxLayer } from "./sandbox-layer.ts";export { renderTaskDefinition } from "./backends/aws.ts";export { HOSTING_PROVIDER_IDS, hostingProviderChoices, isTarget } from "./providers.ts";export type {@@ -12,12 +13,11 @@ export type {Target,QmConfig,} from "./config.ts";+export type { SandboxValidation, SkillFrontmatter } from "./sandbox-layer.ts";export type {ApprovalDecision,- SandboxValidation,- SkillFrontmatter,ToolApproval,ToolAuthDescriptor,ToolCredentialPath,ToolDescriptor,-} from "./sandbox-layer.ts";+} from "./tool-descriptor.ts";diff --git a/cli/src/credential-paths.ts b/cli/src/credential-paths.tsnew file mode 100644index 000000000..8b68142e9--- /dev/null+++ b/cli/src/credential-paths.ts@@ -0,0 +1,30 @@+export const BASE_EPHEMERAL_CRED_LINKS: ReadonlyArray<{ rel: string; kind: "dir" | "file" }> = [+ { rel: ".aws", kind: "dir" },+ { rel: ".netrc", kind: "file" },+ { rel: ".config/gh", kind: "dir" },+ { rel: ".config/glab", kind: "dir" },+ { rel: ".config/glab-cli", kind: "dir" },+ { rel: ".config/gcloud", kind: "dir" },+];++export const DURABLE_CREDENTIAL_PATHS = [".ssh", ".git-credentials"] as const;++export const DISPLACED_DIR_REL = ".agent-displaced";++export interface CredentialPathSpec {+ path: string;+ kind: "file" | "directory";+}++export const CREDENTIAL_PATH_RE = /^[A-Za-z0-9._/@+-]+$/;++export function builtInCredentialPaths(): CredentialPathSpec[] {+ return [+ ...BASE_EPHEMERAL_CRED_LINKS.map(({ rel, kind }) => ({+ path: rel,+ kind: kind === "dir" ? ("directory" as const) : ("file" as const),+ })),+ { path: ".ssh", kind: "directory" },+ { path: ".git-credentials", kind: "file" },+ ];+}diff --git a/cli/src/deployment-layer.ts b/cli/src/deployment-layer.tsindex be9431de0..c74eac50f 100644--- a/cli/src/deployment-layer.ts+++ b/cli/src/deployment-layer.ts@@ -4,7 +4,7 @@ import { join, relative, sep } from "node:path";import type { QmConfig } from "./config.ts";import { CliError, errMessage, step, warn } from "./log.ts";import { deploymentSecretValue, readEnvFile, sleep } from "./util.ts";-import { parseToolDescriptor } from "./sandbox-layer.ts";+import { parseToolDescriptor } from "./tool-descriptor.ts";interface DeploymentLayerFile {path: string;diff --git a/cli/src/sandbox-layer.ts b/cli/src/sandbox-layer.tsindex 2371bcf69..905b60eae 100644--- a/cli/src/sandbox-layer.ts+++ b/cli/src/sandbox-layer.ts@@ -2,690 +2,10 @@ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";import { join } from "node:path";import { JUNK_FILE, deploymentLayerBundle } from "./deployment-layer.ts";import { errMessage } from "./log.ts";--export type ApprovalDecision = "require_approval" | "deny";--const isPlainObject = (v: unknown): v is Record<string, unknown> =>- typeof v === "object" && v !== null && !Array.isArray(v);--const isStringArray = (v: unknown): v is string[] => Array.isArray(v) && v.every((x) => typeof x === "string");--const BUILT_IN_CREDENTIAL_PATHS: readonly ToolCredentialPath[] = [- { path: ".aws", kind: "directory" },- { path: ".config/gh", kind: "directory" },- { path: ".config/glab", kind: "directory" },- { path: ".config/glab-cli", kind: "directory" },- { path: ".config/gcloud", kind: "directory" },- { path: ".ssh", kind: "directory" },- { path: ".netrc", kind: "file" },- { path: ".git-credentials", kind: "file" },-] as const;+import { parseToolDescriptor, type ToolDescriptor } from "./tool-descriptor.ts";const nested = (a: string, b: string): boolean => a.startsWith(`${b}/`);-export interface ToolApproval {- command?: string;- pattern?: string;- decision?: ApprovalDecision;- reason?: string;-}--export interface ToolAuthDescriptor {- check: string;- reauth: string;- credentialPaths?: ToolCredentialPath[];- splitEnv?: Record<string, string>;- broker?: ToolCredentialBroker;-}--interface ToolCredentialBroker {- kind: "aws-role";- roleArnEnv: string;- regionEnv?: string;- region?: string;- sessionActions: string[];-}--export interface ToolCredentialPath {- path: string;- kind: "file" | "directory";-}--export interface ToolDescriptor {- id: string;- label?: string;- advertise?: string;- hints?: string[];- egress?: string[];- auth?: ToolAuthDescriptor;- approvals?: ToolApproval[];- install?: ToolInstall;-}--interface ToolInstallFile {- from: string;- to: string;- mode: string;-}--interface ToolInstall {- binary?: string;- files?: ToolInstallFile[];-}--const INSTALL_FROM_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;-const INSTALL_TO_RE = /^\/usr\/local\/(?:bin|lib)\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;-const INSTALL_MODE_RE = /^0[0-7]{3}$/;--function installFileError(- file: unknown,- sourcePath: string,- index: number,- owner: { id: string; binary: string },-): string | undefined {- const at = `${sourcePath}: "install.files[${index}]"`;- if (!isPlainObject(file)) return `${at} must be an object`;- const { from, to, mode } = file;- if (typeof from !== "string" || !INSTALL_FROM_RE.test(from) || from === "tool.json")- return `${at}.from must name a file beside tool.json (letters, digits, . _ -), not tool.json itself`;- if (typeof to !== "string" || !INSTALL_TO_RE.test(to) || to.split("/").some((seg) => seg === ".." || seg === "."))- return `${at}.to must be an absolute path under /usr/local/bin/ or /usr/local/lib/ with no dot segments`;- if (to !== `/usr/local/bin/${owner.binary}` && !to.startsWith(`/usr/local/lib/${owner.id}/`))- return `${at}.to must be /usr/local/bin/${owner.binary} or a path under /usr/local/lib/${owner.id}/ — a tool may only install its own binary and its own library directory`;- if (mode !== undefined && (typeof mode !== "string" || !INSTALL_MODE_RE.test(mode)))- return `${at}.mode must be a four-digit octal string like "0755"`;- return undefined;-}--function parseInstallFiles(raw: unknown, sourcePath: string, owner: { id: string; binary: string }): ToolInstallFile[] {- if (!Array.isArray(raw)) throw new Error(`${sourcePath}: "install.files" must be an array`);- const out: ToolInstallFile[] = [];- for (const [index, file] of raw.entries()) {- const err = installFileError(file, sourcePath, index, owner);- if (err) throw new Error(err);- const { from, to, mode } = file as { from: string; to: string; mode?: string };- if (out.some((other) => other.to === to))- throw new Error(`${sourcePath}: "install.files" declares ${JSON.stringify(to)} twice`);- out.push({ from, to, mode: mode ?? (to.startsWith("/usr/local/bin/") ? "0755" : "0644") });- }- return out;-}--export function parseToolDescriptor(raw: string, sourcePath: string): ToolDescriptor {- let parsed: unknown;- try {- parsed = JSON.parse(raw);- } catch (err) {- throw new Error(`${sourcePath} is not valid JSON: ${errMessage(err)}`, { cause: err });- }- if (!isPlainObject(parsed)) {- throw new Error(`${sourcePath} must be a JSON object`);- }- const d = parsed;- if (typeof d["id"] !== "string" || !d["id"].trim()) {- throw new Error(`${sourcePath}: "id" is required and must be a non-empty string`);- }- if (!TOOL_ID_RE.test(d["id"])) {- throw new Error(- `${sourcePath}: "id" must match ${TOOL_ID_RE.source} (lowercase alphanumerics and hyphens) — it is interpolated into shell probes`,- );- }- const id = d["id"];- const out: ToolDescriptor = { id };-- for (const key of ["label", "advertise"] as const) {- if (d[key] !== undefined) {- if (typeof d[key] !== "string") throw new Error(`${sourcePath}: "${key}" must be a string`);- out[key] = d[key] as string;- }- }-- if (d["hints"] !== undefined) {- if (!isStringArray(d["hints"])) throw new Error(`${sourcePath}: "hints" must be an array of strings`);- out.hints = d["hints"];- }-- if (d["egress"] !== undefined) {- if (!isStringArray(d["egress"])) {- throw new Error(`${sourcePath}: "egress" must be an array of host strings`);- }- out.egress = d["egress"];- }-- if (d["auth"] !== undefined) out.auth = parseAuth(d["auth"], sourcePath);- if (d["approvals"] !== undefined) out.approvals = parseApprovals(d["approvals"], sourcePath);-- if (d["install"] !== undefined) {- const inst = d["install"];- if (!isPlainObject(inst)) {- throw new Error(`${sourcePath}: "install" must be an object`);- }- const binary = inst["binary"];- if (binary !== undefined && typeof binary !== "string") {- throw new Error(`${sourcePath}: "install.binary" must be a string`);- }- if (binary !== undefined && !TOOL_ID_RE.test(binary)) {- throw new Error(- `${sourcePath}: "install.binary" must match ${TOOL_ID_RE.source} (lowercase alphanumerics and hyphens) — it is interpolated into generated Dockerfile lines`,- );- }- const files = inst["files"];- out.install = {- ...(binary !== undefined ? { binary } : {}),- ...(files !== undefined ? { files: parseInstallFiles(files, sourcePath, { id, binary: binary ?? id }) } : {}),- };- }-- const credentialPaths = out.auth?.credentialPaths ?? [];- for (const [index, credentialPath] of credentialPaths.entries()) {- const { path, kind } = credentialPath;- const segments = path.split("/");- if (- !path ||- path.startsWith("/") ||- path.startsWith("~") ||- path.includes("\\") ||- /\s/.test(path) ||- segments.includes("..") ||- segments.includes(".") ||- segments.includes("")- ) {- throw new Error(- `${sourcePath}: credential path ${JSON.stringify(path)} must be a $HOME-relative path with no traversal`,- );- }- if (!segments[0]!.startsWith(".")) {- throw new Error(- `${sourcePath}: credential path ${JSON.stringify(path)} must start with a dotfile or dot-directory segment — non-hidden $HOME paths are durable agent data, not credentials`,- );- }- if (!/^[A-Za-z0-9._/@+-]+$/.test(path)) {- throw new Error(- `${sourcePath}: credential path ${JSON.stringify(path)} may only use letters, digits, and ._/@+- — other characters cannot ride the capture sweep`,- );- }- const builtIn = BUILT_IN_CREDENTIAL_PATHS.find(- (base) => path === base.path || nested(path, base.path) || nested(base.path, path),- );- if (builtIn && (path !== builtIn.path || kind !== builtIn.kind)) {- throw new Error(- `${sourcePath}: credential path ${JSON.stringify(path)} (${kind}) overlaps the built-in credential path ${JSON.stringify(builtIn.path)} (${builtIn.kind}) — declare the exact built-in path with its correct kind or a disjoint one`,- );- }- const other = credentialPaths.find(- (entry, otherIndex) =>- otherIndex !== index && (path === entry.path || nested(path, entry.path) || nested(entry.path, path)),- );- if (other) {- throw new Error(- `${sourcePath}: credential paths ${JSON.stringify(path)} and ${JSON.stringify(other.path)} overlap — declare disjoint paths`,- );- }- }- const binary = out.install?.binary ?? out.id;- if (out.auth?.broker && !POSIX_FUNCTION_NAME_RE.test(binary)) {- throw new Error(- `${sourcePath}: a brokered tool's binary ${JSON.stringify(binary)} must match ${POSIX_FUNCTION_NAME_RE.source} — vended credentials wrap it in a shell function, and not every sandbox shell accepts hyphenated function names`,- );- }- for (const [i, approval] of (out.approvals ?? []).entries()) {- const compiled = compileApproval(binary, approval);- try {- new RegExp(compiled.pattern, "i");- } catch (e) {- throw new Error(`${sourcePath}: approvals[${i}] is not a valid regex: ${errMessage(e)}`, { cause: e });- }- if (compiled.pattern.length > MAX_APPROVAL_PATTERN_LEN) {- throw new Error(`${sourcePath}: approvals[${i}] pattern is too long (max ${MAX_APPROVAL_PATTERN_LEN} chars)`);- }- if (approvalPatternTooSlow(compiled.pattern)) {- throw new Error(- `${sourcePath}: approvals[${i}] pattern is too slow to evaluate — it may cause catastrophic backtracking`,- );- }- if (approval.pattern !== undefined && !rawApprovalTargetsTool(binary, approval.pattern)) {- throw new Error(- `${sourcePath}: approvals[${i}].pattern must refer to its own tool binary by starting with \\b${binary}\\b and may not use a top-level alternative`,- );- }- }-- return out;-}--function parseAuth(raw: unknown, sourcePath: string): ToolAuthDescriptor {- if (!isPlainObject(raw)) {- throw new Error(`${sourcePath}: "auth" must be an object`);- }- const a = raw;- for (const key of ["check", "reauth"] as const) {- if (typeof a[key] !== "string" || !(a[key] as string).trim()) {- throw new Error(`${sourcePath}: "auth.${key}" is required and must be a non-empty string`);- }- }- const out: ToolAuthDescriptor = { check: a["check"] as string, reauth: a["reauth"] as string };- if (a["credentialPaths"] !== undefined) {- if (!Array.isArray(a["credentialPaths"])) {- throw new Error(`${sourcePath}: "auth.credentialPaths" must be an array of { path, kind } objects`);- }- out.credentialPaths = a["credentialPaths"].map((entry, index) => {- if (!isPlainObject(entry)) {- throw new Error(`${sourcePath}: "auth.credentialPaths[${index}]" must be an object`);- }- if (typeof entry.path !== "string" || (entry.kind !== "file" && entry.kind !== "directory")) {- throw new Error(- `${sourcePath}: "auth.credentialPaths[${index}]" requires string path and kind file or directory`,- );- }- return { path: entry.path, kind: entry.kind };- });- }- if (a["splitEnv"] !== undefined) {- const se = a["splitEnv"];- if (!isPlainObject(se)) {- throw new Error(`${sourcePath}: "auth.splitEnv" must be an object of string values`);- }- const map: Record<string, string> = {};- for (const [k, v] of Object.entries(se)) {- if (!SPLIT_ENV_KEY_RE.test(k)) {- throw new Error(- `${sourcePath}: "auth.splitEnv" key ${JSON.stringify(k)} must match ${SPLIT_ENV_KEY_RE.source}`,- );- }- if (typeof v !== "string") throw new Error(`${sourcePath}: "auth.splitEnv.${k}" must be a string`);- if (/[{}]/.test(v.replaceAll("{actingSlackUserId}", ""))) {- throw new Error(`${sourcePath}: "auth.splitEnv.${k}" may only use the {actingSlackUserId} placeholder`);- }- map[k] = v;- }- out.splitEnv = map;- }- if (a["broker"] !== undefined) out.broker = parseBroker(a["broker"], sourcePath);- return out;-}--function parseBroker(raw: unknown, sourcePath: string): ToolCredentialBroker {- if (!isPlainObject(raw)) {- throw new Error(`${sourcePath}: "auth.broker" must be an object`);- }- const b = raw;- if (b["kind"] !== "aws-role") throw new Error(`${sourcePath}: "auth.broker.kind" must be "aws-role"`);- if (typeof b["roleArnEnv"] !== "string" || !SPLIT_ENV_KEY_RE.test(b["roleArnEnv"])) {- throw new Error(`${sourcePath}: "auth.broker.roleArnEnv" is required and must match ${SPLIT_ENV_KEY_RE.source}`);- }- const out: ToolCredentialBroker = { kind: "aws-role", roleArnEnv: b["roleArnEnv"], sessionActions: [] };- if (b["regionEnv"] !== undefined) {- if (typeof b["regionEnv"] !== "string" || !SPLIT_ENV_KEY_RE.test(b["regionEnv"])) {- throw new Error(`${sourcePath}: "auth.broker.regionEnv" must match ${SPLIT_ENV_KEY_RE.source}`);- }- out.regionEnv = b["regionEnv"];- }- if (b["region"] !== undefined) {- if (typeof b["region"] !== "string" || !b["region"].trim()) {- throw new Error(`${sourcePath}: "auth.broker.region" must be a non-empty string`);- }- out.region = b["region"];- }- if (out.region === undefined && out.regionEnv === undefined) {- throw new Error(- `${sourcePath}: "auth.broker" needs "region" or "regionEnv" — the vended credentials carry a region`,- );- }- const actions = b["sessionActions"];- if (- !Array.isArray(actions) ||- actions.length === 0 ||- actions.some((entry) => typeof entry !== "string" || !entry.trim())- ) {- throw new Error(`${sourcePath}: "auth.broker.sessionActions" must be a non-empty array of IAM action strings`);- }- out.sessionActions = actions as string[];- return out;-}--function parseApprovals(raw: unknown, sourcePath: string): ToolApproval[] {- if (!Array.isArray(raw)) throw new Error(`${sourcePath}: "approvals" must be an array`);- return raw.map((entry, i) => {- if (!isPlainObject(entry)) {- throw new Error(`${sourcePath}: approvals[${i}] must be an object`);- }- const e = entry;- const hasCommand = typeof e["command"] === "string" && (e["command"] as string).trim() !== "";- const hasPattern = typeof e["pattern"] === "string" && (e["pattern"] as string).trim() !== "";- if (!hasCommand && !hasPattern) {- throw new Error(`${sourcePath}: approvals[${i}] needs a "command" or a "pattern"`);- }- if (hasCommand && hasPattern) {- throw new Error(`${sourcePath}: approvals[${i}] has both "command" and "pattern" — use one`);- }- const out: ToolApproval = {};- if (hasCommand) out.command = e["command"] as string;- if (hasPattern) out.pattern = e["pattern"] as string;- if (e["decision"] !== undefined) {- const dec = e["decision"];- if (dec !== "require_approval" && dec !== "deny") {- throw new Error(`${sourcePath}: approvals[${i}].decision must be require_approval or deny`);- }- out.decision = dec;- }- if (e["reason"] !== undefined) {- if (typeof e["reason"] !== "string") throw new Error(`${sourcePath}: approvals[${i}].reason must be a string`);- out.reason = e["reason"];- }- return out;- });-}--const TOOL_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;-const SPLIT_ENV_KEY_RE = /^[A-Z][A-Z0-9_]*$/;-const POSIX_FUNCTION_NAME_RE = /^[a-z_][a-z0-9_]*$/;--const MAX_APPROVAL_PATTERN_LEN = 256;-function approvalPatternTooSlow(pattern: string): boolean {- if (/\\[1-9]|\\k<[^>]+>/.test(pattern)) return true;- type AtomChars = { ascii: Set<number>; asciiOnly: boolean };- const unknownChars = (): AtomChars => ({- ascii: new Set(Array.from({ length: 128 }, (_, i) => i)),- asciiOnly: false,- });- const atomChars = (source: string): AtomChars => {- let atom: RegExp;- try {- atom = new RegExp(`^(?:${source})$`, "i");- } catch {- return unknownChars();- }- const ascii = new Set<number>();- for (let code = 0; code < 128; code++) if (atom.test(String.fromCharCode(code))) ascii.add(code);- const asciiOnly =- (source.length === 1 && source.charCodeAt(0) < 128 && source !== ".") ||- /^\\(?:[dw]|x[0-7][0-9a-f]|u00[0-7][0-9a-f])$/i.test(source) ||- /^\[(?!\^)(?:[^\\\]]|\\(?:[dw]|x[0-7][0-9a-f]|u00[0-7][0-9a-f]))+\]$/i.test(source);- return { ascii, asciiOnly };- };- const overlaps = (left: AtomChars | undefined, right: AtomChars | undefined): boolean => {- if (!left || !right) return false;- for (const code of left.ascii) if (right.ascii.has(code)) return true;- return !left.asciiOnly && !right.asciiOnly;- };- const splitAlternatives = (source: string): string[] => {- const branches: string[] = [];- let start = 0;- let depth = 0;- let inClass = false;- for (let i = 0; i < source.length; i++) {- const char = source[i]!;- if (char === "\\") {- i++;- continue;- }- if (char === "[") inClass = true;- else if (char === "]" && inClass) inClass = false;- else if (!inClass && char === "(") depth++;- else if (!inClass && char === ")") depth--;- else if (!inClass && depth === 0 && char === "|") {- branches.push(source.slice(start, i));- start = i + 1;- }- }- branches.push(source.slice(start));- return branches;- };- const branchShape = (branch: string): { domains: AtomChars[]; nullable: boolean } => {- const domains: AtomChars[] = [];- let nullable = true;- for (let i = 0; i < branch.length; i++) {- const char = branch[i]!;- if (char === "^" || char === "$") continue;- let end = i + 1;- let domain: AtomChars;- if (char === "\\") {- if (branch[i + 1] === "b" || branch[i + 1] === "B") {- i++;- continue;- }- end = i + 2;- if (branch[i + 1] === "x" && /^[0-9a-f]{2}$/i.test(branch.slice(i + 2, i + 4))) end = i + 4;- else if (branch[i + 1] === "u" && /^[0-9a-f]{4}$/i.test(branch.slice(i + 2, i + 6))) end = i + 6;- domain = atomChars(branch.slice(i, end));- } else if (char === "[") {- end = i + 1;- for (; end < branch.length; end++) {- if (branch[end] === "\\") end++;- else if (branch[end] === "]") {- end++;- break;- }- }- domain = atomChars(branch.slice(i, end));- } else if (char === "(" || char === "*" || char === "+" || char === "?" || char === "{") {- return { domains: domains.length ? domains : [unknownChars()], nullable: true };- } else {- domain = atomChars(char);- }- domains.push(domain);- const quantifier = /^(?:[*+?]|\{\d+(?:,\d*)?\})\??/.exec(branch.slice(end))?.[0];- if (quantifier) {- if (quantifier === "+" || /^\{[1-9]/.test(quantifier)) nullable = false;- end += quantifier.length;- } else nullable = false;- i = end - 1;- }- return domains.length ? { domains, nullable } : { domains: [unknownChars()], nullable: true };- };- const prefixAmbiguous = (left: ReturnType<typeof branchShape>, right: ReturnType<typeof branchShape>): boolean => {- if (left.nullable || right.nullable) return true;- const length = Math.min(left.domains.length, right.domains.length);- for (let i = 0; i < length; i++) if (!overlaps(left.domains[i], right.domains[i])) return false;- return true;- };- const alternativeFactor = (source: string): number => {- const branches = splitAlternatives(source).map(branchShape);- let overlapsCount = 0;- for (let i = 0; i < branches.length; i++) {- for (let j = i + 1; j < branches.length; j++) if (prefixAmbiguous(branches[i]!, branches[j]!)) overlapsCount++;- }- return 1 + overlapsCount;- };- let ambiguityBudget = 1;- const stack: Array<{- start: number;- bodyStart: number;- hasQuantifier: boolean;- hasAlternative: boolean;- directAlternative: boolean;- assertion: boolean;- branchStart: boolean;- startsQuantified?: AtomChars;- endsQuantified?: AtomChars;- lastQuantified?: AtomChars;- firstChars?: AtomChars;- lastChars?: AtomChars;- hasAtom: boolean;- }> = [- {- start: -1,- bodyStart: 0,- hasQuantifier: false,- hasAlternative: false,- directAlternative: false,- assertion: false,- branchStart: true,- hasAtom: false,- },- ];- const quantifierEnd = (at: number): number | undefined => {- if (pattern[at] === "*" || pattern[at] === "+" || pattern[at] === "?")- return at + 1 + (pattern[at + 1] === "?" ? 1 : 0);- if (pattern[at] !== "{") return undefined;- const match = /^\{\d+(?:,\d*)?\}/.exec(pattern.slice(at));- if (!match) return undefined;- const end = at + match[0].length;- return end + (pattern[end] === "?" ? 1 : 0);- };- const markAtom = (quantified: boolean, firstChars: AtomChars, lastChars = firstChars): boolean => {- const frame = stack.at(-1)!;- if (quantified && overlaps(frame.lastQuantified, firstChars)) return true;- if (frame.branchStart) {- frame.firstChars ??= firstChars;- if (quantified) frame.startsQuantified ??= firstChars;- }- frame.branchStart = false;- frame.hasAtom = true;- frame.lastChars = lastChars;- frame.lastQuantified = quantified ? lastChars : undefined;- if (quantified) for (const open of stack) open.hasQuantifier = true;- return false;- };- for (let i = 0; i < pattern.length; i++) {- const char = pattern[i]!;- if (char === "\\") {- let end = i + 2;- if (pattern[i + 1] === "x" && /^[0-9a-f]{2}$/i.test(pattern.slice(i + 2, i + 4))) end = i + 4;- else if (pattern[i + 1] === "u" && /^[0-9a-f]{4}$/i.test(pattern.slice(i + 2, i + 6))) end = i + 6;- if (pattern[i + 1] === "b" || pattern[i + 1] === "B") {- i = end - 1;- continue;- }- const quantifiedEnd = quantifierEnd(end);- if (markAtom(quantifiedEnd !== undefined, atomChars(pattern.slice(i, end)))) return true;- i = (quantifiedEnd ?? end) - 1;- continue;- }- if (char === "[") {- let end = i + 1;- for (; end < pattern.length; end++) {- if (pattern[end] === "\\") end++;- else if (pattern[end] === "]") {- end++;- break;- }- }- const quantifiedEnd = quantifierEnd(end);- if (markAtom(quantifiedEnd !== undefined, atomChars(pattern.slice(i, end)))) return true;- i = (quantifiedEnd ?? end) - 1;- continue;- }- if (char === "(") {- let prefixEnd = i + 1;- let assertion = false;- if (pattern[prefixEnd] === "?") {- const kind = pattern[prefixEnd + 1];- if (kind === ":") prefixEnd += 2;- else if (kind === "=" || kind === "!") {- assertion = true;- prefixEnd += 2;- } else if (kind === "<" && (pattern[prefixEnd + 2] === "=" || pattern[prefixEnd + 2] === "!")) {- assertion = true;- prefixEnd += 3;- } else if (kind === "<") {- const close = pattern.indexOf(">", prefixEnd + 2);- if (close !== -1) prefixEnd = close + 1;- }- }- stack.push({- start: i,- bodyStart: prefixEnd,- hasQuantifier: false,- hasAlternative: false,- directAlternative: false,- assertion,- branchStart: true,- hasAtom: false,- });- i = prefixEnd - 1;- continue;- }- if (char === "|") {- for (const group of stack) group.hasAlternative = true;- const frame = stack.at(-1)!;- frame.directAlternative = true;- frame.endsQuantified ??= frame.lastQuantified;- frame.lastQuantified = undefined;- frame.branchStart = true;- continue;- }- if (char === ")" && stack.length > 1) {- const group = stack.pop()!;- if (group.directAlternative) {- ambiguityBudget *= alternativeFactor(pattern.slice(group.bodyStart, i));- if (ambiguityBudget > 1_024) return true;- }- group.endsQuantified ??= group.lastQuantified;- const quantifiedEnd = quantifierEnd(i + 1);- const quantified = quantifiedEnd !== undefined;- if (quantified && (group.hasQuantifier || group.hasAlternative)) return true;- if (!group.assertion) {- const parent = stack.at(-1)!;- const firstChars = group.hasAlternative ? unknownChars() : (group.firstChars ?? unknownChars());- const lastChars = group.hasAlternative ? unknownChars() : (group.lastChars ?? unknownChars());- if (quantified) {- if (markAtom(true, firstChars, lastChars)) return true;- } else if (group.hasAtom) {- if (overlaps(parent.lastQuantified, group.startsQuantified)) return true;- if (parent.branchStart) {- parent.firstChars ??= firstChars;- parent.startsQuantified ??= group.startsQuantified;- }- parent.branchStart = false;- parent.hasAtom = true;- parent.lastChars = lastChars;- parent.lastQuantified = group.endsQuantified;- parent.hasQuantifier ||= group.hasQuantifier;- parent.hasAlternative ||= group.hasAlternative;- }- }- i = (quantifiedEnd ?? i + 1) - 1;- continue;- }- if (char === "^" || char === "$" || char === ")") continue;- const quantifiedEnd = quantifierEnd(i + 1);- if (markAtom(quantifiedEnd !== undefined, atomChars(char))) return true;- i = (quantifiedEnd ?? i + 1) - 1;- }- return false;-}--const escapeRegex = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");--function rawApprovalTargetsTool(binary: string, pattern: string): boolean {- if (!pattern.startsWith(`\\b${escapeRegex(binary)}\\b`)) return false;- let depth = 0;- let inClass = false;- let escaped = false;- for (const char of pattern) {- if (escaped) {- escaped = false;- continue;- }- if (char === "\\") {- escaped = true;- continue;- }- if (char === "[" && !inClass) {- inClass = true;- continue;- }- if (char === "]" && inClass) {- inClass = false;- continue;- }- if (inClass) continue;- if (char === "(") depth++;- else if (char === ")") depth = Math.max(0, depth - 1);- else if (char === "|" && depth === 0) return false;- }- return true;-}--export function compileApproval(binary: string, a: ToolApproval): { pattern: string; decision: ApprovalDecision } {- const decision: ApprovalDecision = a.decision ?? "require_approval";- if (a.pattern !== undefined) return { pattern: a.pattern, decision };- const words = (a.command ?? "").trim().split(/\s+/).filter(Boolean).map(escapeRegex);- const pattern = `\\b${[escapeRegex(binary), ...words].join("\\s+")}(?:\\b|\\s|$)`;- return { pattern, decision };-}-export interface SkillFrontmatter {name: string;description: string;diff --git a/cli/src/tool-descriptor.ts b/cli/src/tool-descriptor.tsnew file mode 100644index 000000000..596d0ec5c--- /dev/null+++ b/cli/src/tool-descriptor.ts@@ -0,0 +1,672 @@+import { CREDENTIAL_PATH_RE, DISPLACED_DIR_REL, builtInCredentialPaths } from "./credential-paths.ts";++export type ApprovalDecision = "require_approval" | "deny";++export interface ToolApproval {+ command?: string;+ pattern?: string;+ decision?: ApprovalDecision;+ reason?: string;+}++export interface ToolAuthDescriptor {+ check: string;+ reauth: string;+ credentialPaths?: ToolCredentialPath[];+ splitEnv?: Record<string, string>;+ broker?: ToolCredentialBroker;+}++export interface ToolCredentialBroker {+ kind: "aws-role";+ roleArnEnv: string;+ regionEnv?: string;+ region?: string;+ sessionActions: string[];+}++export interface ToolCredentialPath {+ path: string;+ kind: "file" | "directory";+}++export interface ToolDescriptor {+ id: string;+ label?: string;+ advertise?: string;+ hints?: string[];+ egress?: string[];+ auth?: ToolAuthDescriptor;+ approvals?: ToolApproval[];+ install?: ToolInstall;+}++export interface ToolInstallFile {+ from: string;+ to: string;+ mode: string;+}++interface ToolInstall {+ binary?: string;+ files?: ToolInstallFile[];+}++const INSTALL_FROM_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;+const INSTALL_TO_RE = /^\/usr\/local\/(?:bin|lib)\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;+const INSTALL_MODE_RE = /^0[0-7]{3}$/;++function installFileError(+ file: unknown,+ sourcePath: string,+ index: number,+ owner: { id: string; binary: string },+): string | undefined {+ const at = `${sourcePath}: "install.files[${index}]"`;+ if (typeof file !== "object" || file === null || Array.isArray(file)) return `${at} must be an object`;+ const { from, to, mode } = file as Record<string, unknown>;+ if (typeof from !== "string" || !INSTALL_FROM_RE.test(from) || from === "tool.json")+ return `${at}.from must name a file beside tool.json (letters, digits, . _ -), not tool.json itself`;+ if (typeof to !== "string" || !INSTALL_TO_RE.test(to) || to.split("/").some((seg) => seg === ".." || seg === "."))+ return `${at}.to must be an absolute path under /usr/local/bin/ or /usr/local/lib/ with no dot segments`;+ if (to !== `/usr/local/bin/${owner.binary}` && !to.startsWith(`/usr/local/lib/${owner.id}/`))+ return `${at}.to must be /usr/local/bin/${owner.binary} or a path under /usr/local/lib/${owner.id}/ — a tool may only install its own binary and its own library directory`;+ if (mode !== undefined && (typeof mode !== "string" || !INSTALL_MODE_RE.test(mode)))+ return `${at}.mode must be a four-digit octal string like "0755"`;+ return undefined;+}++function parseInstallFiles(raw: unknown, sourcePath: string, owner: { id: string; binary: string }): ToolInstallFile[] {+ if (!Array.isArray(raw)) throw new Error(`${sourcePath}: "install.files" must be an array`);+ const out: ToolInstallFile[] = [];+ for (const [index, file] of raw.entries()) {+ const err = installFileError(file, sourcePath, index, owner);+ if (err) throw new Error(err);+ const { from, to, mode } = file as { from: string; to: string; mode?: string };+ if (out.some((other) => other.to === to))+ throw new Error(`${sourcePath}: "install.files" declares ${JSON.stringify(to)} twice`);+ out.push({ from, to, mode: mode ?? (to.startsWith("/usr/local/bin/") ? "0755" : "0644") });+ }+ return out;+}++const BUILT_IN_CREDENTIAL_PATHS: readonly ToolCredentialPath[] = builtInCredentialPaths();++const nested = (a: string, b: string): boolean => a.startsWith(`${b}/`);++export function credentialPathError(path: string, kind: "file" | "directory"): string | undefined {+ const segments = path.split("/");+ if (+ !path ||+ path.startsWith("/") ||+ path.startsWith("~") ||+ path.includes("\\") ||+ /\s/.test(path) ||+ segments.includes("..") ||+ segments.includes(".") ||+ segments.includes("")+ ) {+ return `credential path ${JSON.stringify(path)} must be a $HOME-relative path with no traversal`;+ }+ if (segments[0] === DISPLACED_DIR_REL)+ return `credential path ${JSON.stringify(path)} is reserved — ${DISPLACED_DIR_REL} is where provision quarantines displaced $HOME state, and linking it would make it its own displacement target`;+ if (!segments[0]!.startsWith("."))+ return `credential path ${JSON.stringify(path)} must start with a dotfile or dot-directory segment — non-hidden $HOME paths are durable agent data, not credentials`;+ if (!CREDENTIAL_PATH_RE.test(path))+ return `credential path ${JSON.stringify(path)} may only use letters, digits, and ._/@+- — other characters cannot ride the capture sweep`;+ const builtIn = BUILT_IN_CREDENTIAL_PATHS.find(+ (base) => path === base.path || nested(path, base.path) || nested(base.path, path),+ );+ if (builtIn && (path !== builtIn.path || kind !== builtIn.kind))+ return `credential path ${JSON.stringify(path)} (${kind}) overlaps the built-in credential path ${JSON.stringify(builtIn.path)} (${builtIn.kind}) — declare the exact built-in path with its correct kind or a disjoint one`;+ return undefined;+}++export function parseToolDescriptor(raw: string, sourcePath: string): ToolDescriptor {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (err) {+ throw new Error(`${sourcePath} is not valid JSON: ${(err as Error).message}`, { cause: err });+ }+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new Error(`${sourcePath} must be a JSON object`);+ }+ const d = parsed as Record<string, unknown>;+ if (typeof d["id"] !== "string" || !d["id"].trim()) {+ throw new Error(`${sourcePath}: "id" is required and must be a non-empty string`);+ }+ if (!TOOL_ID_RE.test(d["id"])) {+ throw new Error(+ `${sourcePath}: "id" must match ${TOOL_ID_RE.source} (lowercase alphanumerics and hyphens) — it is interpolated into shell probes`,+ );+ }+ const out: ToolDescriptor = { id: d["id"] };++ for (const key of ["label", "advertise"] as const) {+ if (d[key] !== undefined) {+ if (typeof d[key] !== "string") throw new Error(`${sourcePath}: "${key}" must be a string`);+ out[key] = d[key] as string;+ }+ }++ if (d["hints"] !== undefined) {+ if (!Array.isArray(d["hints"]) || d["hints"].some((h) => typeof h !== "string")) {+ throw new Error(`${sourcePath}: "hints" must be an array of strings`);+ }+ out.hints = d["hints"] as string[];+ }++ if (d["egress"] !== undefined) {+ if (!Array.isArray(d["egress"]) || d["egress"].some((h) => typeof h !== "string")) {+ throw new Error(`${sourcePath}: "egress" must be an array of host strings`);+ }+ out.egress = d["egress"] as string[];+ }++ if (d["auth"] !== undefined) out.auth = parseAuth(d["auth"], sourcePath);+ if (d["approvals"] !== undefined) out.approvals = parseApprovals(d["approvals"], sourcePath);++ if (d["install"] !== undefined) {+ const inst = d["install"];+ if (typeof inst !== "object" || inst === null || Array.isArray(inst)) {+ throw new Error(`${sourcePath}: "install" must be an object`);+ }+ const binary = (inst as Record<string, unknown>)["binary"];+ if (binary !== undefined && typeof binary !== "string") {+ throw new Error(`${sourcePath}: "install.binary" must be a string`);+ }+ if (binary !== undefined && !TOOL_ID_RE.test(binary as string)) {+ throw new Error(+ `${sourcePath}: "install.binary" must match ${TOOL_ID_RE.source} (lowercase alphanumerics and hyphens) — it is interpolated into generated Dockerfile lines`,+ );+ }+ const files = (inst as Record<string, unknown>)["files"];+ out.install = {+ ...(binary !== undefined ? { binary: binary as string } : {}),+ ...(files !== undefined+ ? {+ files: parseInstallFiles(files, sourcePath, {+ id: out.id,+ binary: (binary as string | undefined) ?? out.id,+ }),+ }+ : {}),+ };+ }++ const credentialPaths = out.auth?.credentialPaths ?? [];+ for (const [index, credentialPath] of credentialPaths.entries()) {+ const { path } = credentialPath;+ const err = credentialPathError(path, credentialPath.kind);+ if (err) throw new Error(`${sourcePath}: ${err}`);+ const other = credentialPaths.find(+ (entry, otherIndex) =>+ otherIndex !== index && (path === entry.path || nested(path, entry.path) || nested(entry.path, path)),+ );+ if (other) {+ throw new Error(+ `${sourcePath}: credential paths ${JSON.stringify(path)} and ${JSON.stringify(other.path)} overlap — declare disjoint paths`,+ );+ }+ }+ const binary = out.install?.binary ?? out.id;+ if (out.auth?.broker && !POSIX_FUNCTION_NAME_RE.test(binary)) {+ throw new Error(+ `${sourcePath}: a brokered tool's binary ${JSON.stringify(binary)} must match ${POSIX_FUNCTION_NAME_RE.source} — vended credentials wrap it in a shell function, and not every sandbox shell accepts hyphenated function names`,+ );+ }+ for (const [i, approval] of (out.approvals ?? []).entries()) {+ const compiled = compileApproval(binary, approval);+ try {+ new RegExp(compiled.pattern, "i");+ } catch (e) {+ throw new Error(`${sourcePath}: approvals[${i}] is not a valid regex: ${(e as Error).message}`, { cause: e });+ }+ if (compiled.pattern.length > MAX_APPROVAL_PATTERN_LEN) {+ throw new Error(`${sourcePath}: approvals[${i}] pattern is too long (max ${MAX_APPROVAL_PATTERN_LEN} chars)`);+ }+ if (approvalPatternTooSlow(compiled.pattern)) {+ throw new Error(+ `${sourcePath}: approvals[${i}] pattern is too slow to evaluate — it may cause catastrophic backtracking`,+ );+ }+ if (approval.pattern !== undefined && !rawApprovalTargetsTool(binary, approval.pattern)) {+ throw new Error(+ `${sourcePath}: approvals[${i}].pattern must refer to its own tool binary by starting with \\b${binary}\\b and may not use a top-level alternative`,+ );+ }+ }++ return out;+}++function parseAuth(raw: unknown, sourcePath: string): ToolAuthDescriptor {+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {+ throw new Error(`${sourcePath}: "auth" must be an object`);+ }+ const a = raw as Record<string, unknown>;+ for (const key of ["check", "reauth"] as const) {+ if (typeof a[key] !== "string" || !(a[key] as string).trim()) {+ throw new Error(`${sourcePath}: "auth.${key}" is required and must be a non-empty string`);+ }+ }+ const out: ToolAuthDescriptor = { check: a["check"] as string, reauth: a["reauth"] as string };+ if (a["credentialPaths"] !== undefined) {+ if (!Array.isArray(a["credentialPaths"])) {+ throw new Error(`${sourcePath}: "auth.credentialPaths" must be an array of { path, kind } objects`);+ }+ out.credentialPaths = a["credentialPaths"].map((entry, index) => {+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {+ throw new Error(`${sourcePath}: "auth.credentialPaths[${index}]" must be an object`);+ }+ const value = entry as Record<string, unknown>;+ if (typeof value.path !== "string" || (value.kind !== "file" && value.kind !== "directory")) {+ throw new Error(+ `${sourcePath}: "auth.credentialPaths[${index}]" requires string path and kind file or directory`,+ );+ }+ return { path: value.path, kind: value.kind };+ });+ }+ if (a["splitEnv"] !== undefined) {+ const se = a["splitEnv"];+ if (typeof se !== "object" || se === null || Array.isArray(se)) {+ throw new Error(`${sourcePath}: "auth.splitEnv" must be an object of string values`);+ }+ const map: Record<string, string> = {};+ for (const [k, v] of Object.entries(se)) {+ if (!SPLIT_ENV_KEY_RE.test(k)) {+ throw new Error(+ `${sourcePath}: "auth.splitEnv" key ${JSON.stringify(k)} must match ${SPLIT_ENV_KEY_RE.source}`,+ );+ }+ if (typeof v !== "string") throw new Error(`${sourcePath}: "auth.splitEnv.${k}" must be a string`);+ if (/[{}]/.test(v.replaceAll("{actingSlackUserId}", ""))) {+ throw new Error(`${sourcePath}: "auth.splitEnv.${k}" may only use the {actingSlackUserId} placeholder`);+ }+ map[k] = v;+ }+ out.splitEnv = map;+ }+ if (a["broker"] !== undefined) out.broker = parseBroker(a["broker"], sourcePath);+ return out;+}++function parseBroker(raw: unknown, sourcePath: string): ToolCredentialBroker {+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {+ throw new Error(`${sourcePath}: "auth.broker" must be an object`);+ }+ const b = raw as Record<string, unknown>;+ if (b["kind"] !== "aws-role") throw new Error(`${sourcePath}: "auth.broker.kind" must be "aws-role"`);+ if (typeof b["roleArnEnv"] !== "string" || !SPLIT_ENV_KEY_RE.test(b["roleArnEnv"])) {+ throw new Error(`${sourcePath}: "auth.broker.roleArnEnv" is required and must match ${SPLIT_ENV_KEY_RE.source}`);+ }+ const out: ToolCredentialBroker = { kind: "aws-role", roleArnEnv: b["roleArnEnv"], sessionActions: [] };+ if (b["regionEnv"] !== undefined) {+ if (typeof b["regionEnv"] !== "string" || !SPLIT_ENV_KEY_RE.test(b["regionEnv"])) {+ throw new Error(`${sourcePath}: "auth.broker.regionEnv" must match ${SPLIT_ENV_KEY_RE.source}`);+ }+ out.regionEnv = b["regionEnv"];+ }+ if (b["region"] !== undefined) {+ if (typeof b["region"] !== "string" || !b["region"].trim()) {+ throw new Error(`${sourcePath}: "auth.broker.region" must be a non-empty string`);+ }+ out.region = b["region"];+ }+ if (out.region === undefined && out.regionEnv === undefined) {+ throw new Error(+ `${sourcePath}: "auth.broker" needs "region" or "regionEnv" — the vended credentials carry a region`,+ );+ }+ const actions = b["sessionActions"];+ if (+ !Array.isArray(actions) ||+ actions.length === 0 ||+ actions.some((entry) => typeof entry !== "string" || !entry.trim())+ ) {+ throw new Error(`${sourcePath}: "auth.broker.sessionActions" must be a non-empty array of IAM action strings`);+ }+ out.sessionActions = actions as string[];+ return out;+}++function parseApprovals(raw: unknown, sourcePath: string): ToolApproval[] {+ if (!Array.isArray(raw)) throw new Error(`${sourcePath}: "approvals" must be an array`);+ return raw.map((entry, i) => {+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {+ throw new Error(`${sourcePath}: approvals[${i}] must be an object`);+ }+ const e = entry as Record<string, unknown>;+ const hasCommand = typeof e["command"] === "string" && (e["command"] as string).trim() !== "";+ const hasPattern = typeof e["pattern"] === "string" && (e["pattern"] as string).trim() !== "";+ if (!hasCommand && !hasPattern) throw new Error(`${sourcePath}: approvals[${i}] needs a "command" or a "pattern"`);+ if (hasCommand && hasPattern)+ throw new Error(`${sourcePath}: approvals[${i}] has both "command" and "pattern" — use one`);+ const out: ToolApproval = {};+ if (hasCommand) out.command = e["command"] as string;+ if (hasPattern) out.pattern = e["pattern"] as string;+ if (e["decision"] !== undefined) {+ const dec = e["decision"];+ if (dec !== "require_approval" && dec !== "deny") {+ throw new Error(`${sourcePath}: approvals[${i}].decision must be require_approval or deny`);+ }+ out.decision = dec;+ }+ if (e["reason"] !== undefined) {+ if (typeof e["reason"] !== "string") throw new Error(`${sourcePath}: approvals[${i}].reason must be a string`);+ out.reason = e["reason"];+ }+ return out;+ });+}++const TOOL_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;+const SPLIT_ENV_KEY_RE = /^[A-Z][A-Z0-9_]*$/;+const POSIX_FUNCTION_NAME_RE = /^[a-z_][a-z0-9_]*$/;++const MAX_APPROVAL_PATTERN_LEN = 256;+function approvalPatternTooSlow(pattern: string): boolean {+ if (/\\[1-9]|\\k<[^>]+>/.test(pattern)) return true;+ type AtomChars = { ascii: Set<number>; asciiOnly: boolean };+ const unknownChars = (): AtomChars => ({+ ascii: new Set(Array.from({ length: 128 }, (_, i) => i)),+ asciiOnly: false,+ });+ const atomChars = (source: string): AtomChars => {+ let atom: RegExp;+ try {+ atom = new RegExp(`^(?:${source})$`, "i");+ } catch {+ return unknownChars();+ }+ const ascii = new Set<number>();+ for (let code = 0; code < 128; code++) if (atom.test(String.fromCharCode(code))) ascii.add(code);+ const asciiOnly =+ (source.length === 1 && source.charCodeAt(0) < 128 && source !== ".") ||+ /^\\(?:[dw]|x[0-7][0-9a-f]|u00[0-7][0-9a-f])$/i.test(source) ||+ /^\[(?!\^)(?:[^\\\]]|\\(?:[dw]|x[0-7][0-9a-f]|u00[0-7][0-9a-f]))+\]$/i.test(source);+ return { ascii, asciiOnly };+ };+ const overlaps = (left: AtomChars | undefined, right: AtomChars | undefined): boolean => {+ if (!left || !right) return false;+ for (const code of left.ascii) if (right.ascii.has(code)) return true;+ return !left.asciiOnly && !right.asciiOnly;+ };+ const splitAlternatives = (source: string): string[] => {+ const branches: string[] = [];+ let start = 0;+ let depth = 0;+ let inClass = false;+ for (let i = 0; i < source.length; i++) {+ const char = source[i]!;+ if (char === "\\") {+ i++;+ continue;+ }+ if (char === "[") inClass = true;+ else if (char === "]" && inClass) inClass = false;+ else if (!inClass && char === "(") depth++;+ else if (!inClass && char === ")") depth--;+ else if (!inClass && depth === 0 && char === "|") {+ branches.push(source.slice(start, i));+ start = i + 1;+ }+ }+ branches.push(source.slice(start));+ return branches;+ };+ const branchShape = (branch: string): { domains: AtomChars[]; nullable: boolean } => {+ const domains: AtomChars[] = [];+ let nullable = true;+ for (let i = 0; i < branch.length; i++) {+ const char = branch[i]!;+ if (char === "^" || char === "$") continue;+ let end = i + 1;+ let domain: AtomChars;+ if (char === "\\") {+ if (branch[i + 1] === "b" || branch[i + 1] === "B") {+ i++;+ continue;+ }+ end = i + 2;+ if (branch[i + 1] === "x" && /^[0-9a-f]{2}$/i.test(branch.slice(i + 2, i + 4))) end = i + 4;+ else if (branch[i + 1] === "u" && /^[0-9a-f]{4}$/i.test(branch.slice(i + 2, i + 6))) end = i + 6;+ domain = atomChars(branch.slice(i, end));+ } else if (char === "[") {+ end = i + 1;+ for (; end < branch.length; end++) {+ if (branch[end] === "\\") end++;+ else if (branch[end] === "]") {+ end++;+ break;+ }+ }+ domain = atomChars(branch.slice(i, end));+ } else if (char === "(" || char === "*" || char === "+" || char === "?" || char === "{") {+ return { domains: domains.length ? domains : [unknownChars()], nullable: true };+ } else {+ domain = atomChars(char);+ }+ domains.push(domain);+ const quantifier = /^(?:[*+?]|\{\d+(?:,\d*)?\})\??/.exec(branch.slice(end))?.[0];+ if (quantifier) {+ if (quantifier === "+" || /^\{[1-9]/.test(quantifier)) nullable = false;+ end += quantifier.length;+ } else nullable = false;+ i = end - 1;+ }+ return domains.length ? { domains, nullable } : { domains: [unknownChars()], nullable: true };+ };+ const prefixAmbiguous = (left: ReturnType<typeof branchShape>, right: ReturnType<typeof branchShape>): boolean => {+ if (left.nullable || right.nullable) return true;+ const length = Math.min(left.domains.length, right.domains.length);+ for (let i = 0; i < length; i++) if (!overlaps(left.domains[i], right.domains[i])) return false;+ return true;+ };+ const alternativeFactor = (source: string): number => {+ const branches = splitAlternatives(source).map(branchShape);+ let overlapsCount = 0;+ for (let i = 0; i < branches.length; i++) {+ for (let j = i + 1; j < branches.length; j++) if (prefixAmbiguous(branches[i]!, branches[j]!)) overlapsCount++;+ }+ return 1 + overlapsCount;+ };+ let ambiguityBudget = 1;+ const stack: Array<{+ start: number;+ bodyStart: number;+ hasQuantifier: boolean;+ hasAlternative: boolean;+ directAlternative: boolean;+ assertion: boolean;+ branchStart: boolean;+ startsQuantified?: AtomChars;+ endsQuantified?: AtomChars;+ lastQuantified?: AtomChars;+ firstChars?: AtomChars;+ lastChars?: AtomChars;+ hasAtom: boolean;+ }> = [+ {+ start: -1,+ bodyStart: 0,+ hasQuantifier: false,+ hasAlternative: false,+ directAlternative: false,+ assertion: false,+ branchStart: true,+ hasAtom: false,+ },+ ];+ const quantifierEnd = (at: number): number | undefined => {+ if (pattern[at] === "*" || pattern[at] === "+" || pattern[at] === "?")+ return at + 1 + (pattern[at + 1] === "?" ? 1 : 0);+ if (pattern[at] !== "{") return undefined;+ const match = /^\{\d+(?:,\d*)?\}/.exec(pattern.slice(at));+ if (!match) return undefined;+ const end = at + match[0].length;+ return end + (pattern[end] === "?" ? 1 : 0);+ };+ const markAtom = (quantified: boolean, firstChars: AtomChars, lastChars = firstChars): boolean => {+ const frame = stack.at(-1)!;+ if (quantified && overlaps(frame.lastQuantified, firstChars)) return true;+ if (frame.branchStart) {+ frame.firstChars ??= firstChars;+ if (quantified) frame.startsQuantified ??= firstChars;+ }+ frame.branchStart = false;+ frame.hasAtom = true;+ frame.lastChars = lastChars;+ frame.lastQuantified = quantified ? lastChars : undefined;+ if (quantified) for (const open of stack) open.hasQuantifier = true;+ return false;+ };+ for (let i = 0; i < pattern.length; i++) {+ const char = pattern[i]!;+ if (char === "\\") {+ let end = i + 2;+ if (pattern[i + 1] === "x" && /^[0-9a-f]{2}$/i.test(pattern.slice(i + 2, i + 4))) end = i + 4;+ else if (pattern[i + 1] === "u" && /^[0-9a-f]{4}$/i.test(pattern.slice(i + 2, i + 6))) end = i + 6;+ if (pattern[i + 1] === "b" || pattern[i + 1] === "B") {+ i = end - 1;+ continue;+ }+ const quantifiedEnd = quantifierEnd(end);+ if (markAtom(quantifiedEnd !== undefined, atomChars(pattern.slice(i, end)))) return true;+ i = (quantifiedEnd ?? end) - 1;+ continue;+ }+ if (char === "[") {+ let end = i + 1;+ for (; end < pattern.length; end++) {+ if (pattern[end] === "\\") end++;+ else if (pattern[end] === "]") {+ end++;+ break;+ }+ }+ const quantifiedEnd = quantifierEnd(end);+ if (markAtom(quantifiedEnd !== undefined, atomChars(pattern.slice(i, end)))) return true;+ i = (quantifiedEnd ?? end) - 1;+ continue;+ }+ if (char === "(") {+ let prefixEnd = i + 1;+ let assertion = false;+ if (pattern[prefixEnd] === "?") {+ const kind = pattern[prefixEnd + 1];+ if (kind === ":") prefixEnd += 2;+ else if (kind === "=" || kind === "!") {+ assertion = true;+ prefixEnd += 2;+ } else if (kind === "<" && (pattern[prefixEnd + 2] === "=" || pattern[prefixEnd + 2] === "!")) {+ assertion = true;+ prefixEnd += 3;+ } else if (kind === "<") {+ const close = pattern.indexOf(">", prefixEnd + 2);+ if (close !== -1) prefixEnd = close + 1;+ }+ }+ stack.push({+ start: i,+ bodyStart: prefixEnd,+ hasQuantifier: false,+ hasAlternative: false,+ directAlternative: false,+ assertion,+ branchStart: true,+ hasAtom: false,+ });+ i = prefixEnd - 1;+ continue;+ }+ if (char === "|") {+ for (const group of stack) group.hasAlternative = true;+ const frame = stack.at(-1)!;+ frame.directAlternative = true;+ frame.endsQuantified ??= frame.lastQuantified;+ frame.lastQuantified = undefined;+ frame.branchStart = true;+ continue;+ }+ if (char === ")" && stack.length > 1) {+ const group = stack.pop()!;+ if (group.directAlternative) {+ ambiguityBudget *= alternativeFactor(pattern.slice(group.bodyStart, i));+ if (ambiguityBudget > 1_024) return true;+ }+ group.endsQuantified ??= group.lastQuantified;+ const quantifiedEnd = quantifierEnd(i + 1);+ const quantified = quantifiedEnd !== undefined;+ if (quantified && (group.hasQuantifier || group.hasAlternative)) return true;+ if (!group.assertion) {+ const parent = stack.at(-1)!;+ const firstChars = group.hasAlternative ? unknownChars() : (group.firstChars ?? unknownChars());+ const lastChars = group.hasAlternative ? unknownChars() : (group.lastChars ?? unknownChars());+ if (quantified) {+ if (markAtom(true, firstChars, lastChars)) return true;+ } else if (group.hasAtom) {+ if (overlaps(parent.lastQuantified, group.startsQuantified)) return true;+ if (parent.branchStart) {+ parent.firstChars ??= firstChars;+ parent.startsQuantified ??= group.startsQuantified;+ }+ parent.branchStart = false;+ parent.hasAtom = true;+ parent.lastChars = lastChars;+ parent.lastQuantified = group.endsQuantified;+ parent.hasQuantifier ||= group.hasQuantifier;+ parent.hasAlternative ||= group.hasAlternative;+ }+ }+ i = (quantifiedEnd ?? i + 1) - 1;+ continue;+ }+ if (char === "^" || char === "$" || char === ")") continue;+ const quantifiedEnd = quantifierEnd(i + 1);+ if (markAtom(quantifiedEnd !== undefined, atomChars(char))) return true;+ i = (quantifiedEnd ?? i + 1) - 1;+ }+ return false;+}++const escapeRegex = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++function rawApprovalTargetsTool(binary: string, pattern: string): boolean {+ if (!pattern.startsWith(`\\b${escapeRegex(binary)}\\b`)) return false;+ let depth = 0;+ let inClass = false;+ let escaped = false;+ for (const char of pattern) {+ if (escaped) {+ escaped = false;+ continue;+ }+ if (char === "\\") {+ escaped = true;+ continue;+ }+ if (char === "[" && !inClass) {+ inClass = true;+ continue;+ }+ if (char === "]" && inClass) {+ inClass = false;+ continue;+ }+ if (inClass) continue;+ if (char === "(") depth++;+ else if (char === ")") depth = Math.max(0, depth - 1);+ else if (char === "|" && depth === 0) return false;+ }+ return true;+}++export function compileApproval(binary: string, a: ToolApproval): { pattern: string; decision: ApprovalDecision } {+ const decision: ApprovalDecision = a.decision ?? "require_approval";+ if (a.pattern !== undefined) return { pattern: a.pattern, decision };+ const words = (a.command ?? "").trim().split(/\s+/).filter(Boolean).map(escapeRegex);+ return { pattern: `\\b${[escapeRegex(binary), ...words].join("\\s+")}(?:\\b|\\s|$)`, decision };+}diff --git a/cli/test/init.test.ts b/cli/test/init.test.tsindex 70639e754..f3646da99 100644--- a/cli/test/init.test.ts+++ b/cli/test/init.test.ts@@ -7,7 +7,8 @@ import { join } from "node:path";import { runInit } from "../src/commands/init.ts";import { CONFIG_FILENAME, loadConfigInDir } from "../src/config.ts";import { cliVersion } from "../src/manifest.ts";-import { parseToolDescriptor, validateSandboxLayer } from "../src/sandbox-layer.ts";+import { validateSandboxLayer } from "../src/sandbox-layer.ts";+import { parseToolDescriptor } from "../src/tool-descriptor.ts";import { SERVICE_NAMES, VIRTUAL_SERVICE_NAMES } from "../src/services.ts";import { renderEnvExample } from "../src/secrets.ts";import { runChecks } from "../src/commands/check.ts";diff --git a/cli/test/tool-descriptor.test.ts b/cli/test/tool-descriptor.test.tsindex e33218d04..6d91bd6af 100644--- a/cli/test/tool-descriptor.test.ts+++ b/cli/test/tool-descriptor.test.ts@@ -1,6 +1,8 @@import { test } from "node:test";import assert from "node:assert/strict";-import { compileApproval, parseSkillFrontmatter, parseToolDescriptor } from "../src/sandbox-layer.ts";+import { parseSkillFrontmatter } from "../src/sandbox-layer.ts";+import { builtInCredentialPaths } from "../src/credential-paths.ts";+import { compileApproval, parseToolDescriptor } from "../src/tool-descriptor.ts";import * as canonical from "../../src/deployment/deployment-layer.ts";import { parseSeedSkillFrontmatter } from "../../src/skills/frontmatter.ts";@@ -312,7 +314,29 @@ test("drift-lock: cli skill parser matches the core seed parser's output", () =>}});-test("drift-lock: cli sandbox-layer parser matches the canonical src/deployment schema", () => {+test("core and the CLI share one parser", () => {+ assert.equal(canonical.parseToolDescriptor, parseToolDescriptor);+ assert.equal(canonical.compileApproval, compileApproval);+});++test("the CLI rejects the reserved .agent-displaced directory and uses the derived built-in paths", () => {+ for (const path of [".agent-displaced", ".agent-displaced/x"]) {+ assert.throws(+ () => P({ id: "x", auth: { check: "a", reauth: "b", credentialPaths: [credentialDirectory(path)] } }),+ /is reserved/,+ );+ }+ for (const base of builtInCredentialPaths()) {+ assert.doesNotThrow(() => P({ id: "x", auth: { check: "a", reauth: "b", credentialPaths: [base] } }));+ const wrongKind = base.kind === "file" ? credentialDirectory(base.path) : credentialFile(base.path);+ assert.throws(+ () => P({ id: "x", auth: { check: "a", reauth: "b", credentialPaths: [wrongKind] } }),+ /overlaps the built-in credential path/,+ );+ }+});++test("parser accepts and rejects a fixed corpus", () => {const valid = [{ id: "ex" },{ id: "my-tool", label: "L", advertise: "a", egress: ["h"], install: { binary: "b" } },@@ -358,11 +382,7 @@ test("drift-lock: cli sandbox-layer parser matches the canonical src/deployment},];for (const v of valid) {- assert.deepEqual(- parseToolDescriptor(JSON.stringify(v), "t.json"),- canonical.parseToolDescriptor(JSON.stringify(v), "t.json"),- `valid descriptor parsed differently: ${JSON.stringify(v)}`,- );+ assert.doesNotThrow(() => parseToolDescriptor(JSON.stringify(v), "t.json"), JSON.stringify(v));}const invalid = ['{"id":"x","auth":{"check":"a","reauth":"b","broker":{}}}',@@ -396,29 +416,23 @@ test("drift-lock: cli sandbox-layer parser matches the canonical src/deploymentJSON.stringify({ id: "acmecli", approvals: [{ pattern: "\\bacmecli\\b" + "a".repeat(300) }] }),];for (const raw of invalid) {- const cliErr = (() => {- try {- parseToolDescriptor(raw, "t.json");- return null;- } catch (e) {- return (e as Error).message;- }- })();- const canErr = (() => {- try {- canonical.parseToolDescriptor(raw, "t.json");- return null;- } catch (e) {- return (e as Error).message;- }- })();- assert.ok(cliErr !== null && canErr !== null, `both should reject: ${raw}`);- assert.equal(cliErr, canErr, `error message drift on: ${raw}`);+ assert.throws(() => parseToolDescriptor(raw, "t.json"), Error, `should reject: ${raw}`);}- assert.deepEqual(compileApproval("t", { command: "a b" }), canonical.compileApproval("t", { command: "a b" }));+ const cred = (path: string, kind = "file") =>+ JSON.stringify({ id: "x", auth: { check: "a", reauth: "b", credentialPaths: [{ path, kind }] } });+ const pinned: Array<[string, RegExp]> = [+ [cred(".agent-displaced/x"), /is reserved/],+ [cred(".ssh/id_rsa"), /overlaps the built-in credential path ".ssh"/],+ [cred("a//b"), /must be a \$HOME-relative path with no traversal/],+ [cred("workspace", "directory"), /must start with a dotfile/],+ [JSON.stringify({ id: "x", approvals: [{ pattern: "(" }] }), /is not a valid regex/],+ ["not json", /is not valid JSON/],+ ['{"id":"x","approvals":[{}]}', /needs a "command" or a "pattern"/],+ ];+ for (const [raw, message] of pinned) assert.throws(() => parseToolDescriptor(raw, "t.json"), message, raw);});-test("install.files: shape-checked, mode defaulted by destination, and byte-identical to the canonical parser", () => {+test("install.files: shape-checked and mode defaulted by destination", () => {const raw = {id: "t",install: {@@ -437,7 +451,6 @@ test("install.files: shape-checked, mode defaulted by destination, and byte-iden{ from: "lib.mjs", to: "/usr/local/lib/t/lib.mjs", mode: "0600" },],});- assert.deepEqual(parsed, canonical.parseToolDescriptor(JSON.stringify(raw), "t.json"));for (const [files, message] of [[{}, /must be an array/],[["t"], /must be an object/],@@ -460,9 +473,5 @@ test("install.files: shape-checked, mode defaulted by destination, and byte-iden],] as const) {assert.throws(() => P({ id: "t", install: { files } }), message);- assert.throws(- () => canonical.parseToolDescriptor(JSON.stringify({ id: "t", install: { files } }), "t.json"),- message,- );}});diff --git a/deploy/core/Dockerfile b/deploy/core/Dockerfileindex 12975872a..4f879fc29 100644--- a/deploy/core/Dockerfile+++ b/deploy/core/Dockerfile@@ -24,6 +24,7 @@ RUN npm ci --omit=dev && npm audit --omit=dev --audit-level=moderate \COPY --from=connector-sdk-build /app/.generated/connector-sdk ./.generated/connector-sdkCOPY src ./src+COPY cli/src/credential-paths.ts cli/src/tool-descriptor.ts ./cli/src/COPY scripts/migrate-transcript-tape.ts ./scripts/migrate-transcript-tape.tsCOPY scripts/lib/transcript-tape-migration.ts ./scripts/lib/transcript-tape-migration.tsCOPY cli/templates/slack-manifest.json ./cli/templates/slack-manifest.jsondiff --git a/deploy/egress-proxy/Dockerfile b/deploy/egress-proxy/Dockerfileindex b88ba052f..47a55440f 100644--- a/deploy/egress-proxy/Dockerfile+++ b/deploy/egress-proxy/Dockerfile@@ -12,6 +12,7 @@ COPY .husky/install.mjs .husky/install.mjsRUN npm ci --omit=devCOPY src ./src+COPY cli/src/credential-paths.ts cli/src/tool-descriptor.ts ./cli/src/COPY plugins/chassis ./plugins/chassisCOPY tsconfig.json ./RUN node --input-type=module -e "await import('./src/egress-authz-main.ts')"diff --git a/src/credentials/resident-paths.ts b/src/credentials/resident-paths.tsindex db847c220..f4d75ed74 100644--- a/src/credentials/resident-paths.ts+++ b/src/credentials/resident-paths.ts@@ -2,6 +2,20 @@ import { posix } from "node:path";import { shq } from "../util/shell.ts";import { pathUnder } from "../util/paths.ts";import { homeRelativePath } from "./paths.ts";+import {+ BASE_EPHEMERAL_CRED_LINKS,+ DISPLACED_DIR_REL,+ DURABLE_CREDENTIAL_PATHS,+ type CredentialPathSpec,+} from "../../cli/src/credential-paths.ts";++export {+ BASE_EPHEMERAL_CRED_LINKS,+ CREDENTIAL_PATH_RE,+ DISPLACED_DIR_REL,+ builtInCredentialPaths,+ type CredentialPathSpec,+} from "../../cli/src/credential-paths.ts";export const BASE_RESIDENT_AUTH_PATHS = [".aws",@@ -12,27 +26,8 @@ export const BASE_RESIDENT_AUTH_PATHS = [".git-credentials",] as const;-export const BASE_EPHEMERAL_CRED_LINKS: ReadonlyArray<{ rel: string; kind: "dir" | "file" }> = [- { rel: ".aws", kind: "dir" },- { rel: ".netrc", kind: "file" },- { rel: ".config/gh", kind: "dir" },- { rel: ".config/glab", kind: "dir" },- { rel: ".config/glab-cli", kind: "dir" },- { rel: ".config/gcloud", kind: "dir" },-];--const DURABLE_CREDENTIAL_PATHS = [".ssh", ".git-credentials"] as const;export const EPHEMERAL_CRED_DIR = "/tmp/agent-creds";-//--export const DISPLACED_DIR_REL = ".agent-displaced";--export interface CredentialPathSpec {- path: string;- kind: "file" | "directory";-}-export function residentAuthPaths(extra: readonly CredentialPathSpec[] = []): string[] {return [...new Set([...BASE_RESIDENT_AUTH_PATHS, ...extra.map((entry) => entry.path)])];}@@ -62,19 +57,6 @@ export function configCredentialDirs(): string[] {return BASE_EPHEMERAL_CRED_LINKS.filter((l) => l.rel.startsWith(".config/")).map((l) => l.rel);}-export const CREDENTIAL_PATH_RE = /^[A-Za-z0-9._/@+-]+$/;--export function builtInCredentialPaths(): CredentialPathSpec[] {- return [- ...BASE_EPHEMERAL_CRED_LINKS.map(({ rel, kind }) => ({- path: rel,- kind: kind === "dir" ? ("directory" as const) : ("file" as const),- })),- { path: ".ssh", kind: "directory" },- { path: ".git-credentials", kind: "file" },- ];-}-const SERVICE_ALIASES: Readonly<Record<string, readonly string[]>> = { glab: ["glab-cli"] };export function expandServiceAliases(services: readonly string[]): string[] {diff --git a/src/deployment/deployment-layer.ts b/src/deployment/deployment-layer.tsindex 247a13828..18d681ff1 100644--- a/src/deployment/deployment-layer.ts+++ b/src/deployment/deployment-layer.ts@@ -1,675 +1,12 @@-import { CREDENTIAL_PATH_RE, DISPLACED_DIR_REL, builtInCredentialPaths } from "../credentials/resident-paths.ts";--export type ApprovalDecision = "require_approval" | "deny";--export interface ToolApproval {- command?: string;- pattern?: string;- decision?: ApprovalDecision;- reason?: string;-}--interface ToolAuthDescriptor {- check: string;- reauth: string;- credentialPaths?: ToolCredentialPath[];- splitEnv?: Record<string, string>;- broker?: ToolCredentialBroker;-}--export interface ToolCredentialBroker {- kind: "aws-role";- roleArnEnv: string;- regionEnv?: string;- region?: string;- sessionActions: string[];-}--export interface ToolCredentialPath {- path: string;- kind: "file" | "directory";-}--export interface ToolDescriptor {- id: string;- label?: string;- advertise?: string;- hints?: string[];- egress?: string[];- auth?: ToolAuthDescriptor;- approvals?: ToolApproval[];- install?: ToolInstall;-}--export interface ToolInstallFile {- from: string;- to: string;- mode: string;-}--interface ToolInstall {- binary?: string;- files?: ToolInstallFile[];-}--const INSTALL_FROM_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;-const INSTALL_TO_RE = /^\/usr\/local\/(?:bin|lib)\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;-const INSTALL_MODE_RE = /^0[0-7]{3}$/;--function installFileError(- file: unknown,- sourcePath: string,- index: number,- owner: { id: string; binary: string },-): string | undefined {- const at = `${sourcePath}: "install.files[${index}]"`;- if (typeof file !== "object" || file === null || Array.isArray(file)) return `${at} must be an object`;- const { from, to, mode } = file as Record<string, unknown>;- if (typeof from !== "string" || !INSTALL_FROM_RE.test(from) || from === "tool.json")- return `${at}.from must name a file beside tool.json (letters, digits, . _ -), not tool.json itself`;- if (typeof to !== "string" || !INSTALL_TO_RE.test(to) || to.split("/").some((seg) => seg === ".." || seg === "."))- return `${at}.to must be an absolute path under /usr/local/bin/ or /usr/local/lib/ with no dot segments`;- if (to !== `/usr/local/bin/${owner.binary}` && !to.startsWith(`/usr/local/lib/${owner.id}/`))- return `${at}.to must be /usr/local/bin/${owner.binary} or a path under /usr/local/lib/${owner.id}/ — a tool may only install its own binary and its own library directory`;- if (mode !== undefined && (typeof mode !== "string" || !INSTALL_MODE_RE.test(mode)))- return `${at}.mode must be a four-digit octal string like "0755"`;- return undefined;-}--function parseInstallFiles(raw: unknown, sourcePath: string, owner: { id: string; binary: string }): ToolInstallFile[] {- if (!Array.isArray(raw)) throw new Error(`${sourcePath}: "install.files" must be an array`);- const out: ToolInstallFile[] = [];- for (const [index, file] of raw.entries()) {- const err = installFileError(file, sourcePath, index, owner);- if (err) throw new Error(err);- const { from, to, mode } = file as { from: string; to: string; mode?: string };- if (out.some((other) => other.to === to))- throw new Error(`${sourcePath}: "install.files" declares ${JSON.stringify(to)} twice`);- out.push({ from, to, mode: mode ?? (to.startsWith("/usr/local/bin/") ? "0755" : "0644") });- }- return out;-}--const BUILT_IN_CREDENTIAL_PATHS: readonly ToolCredentialPath[] = builtInCredentialPaths();--const nested = (a: string, b: string): boolean => a.startsWith(`${b}/`);--export function credentialPathError(path: string, kind: "file" | "directory"): string | undefined {- const segments = path.split("/");- if (- !path ||- path.startsWith("/") ||- path.startsWith("~") ||- path.includes("\\") ||- /\s/.test(path) ||- segments.includes("..") ||- segments.includes(".") ||- segments.includes("")- ) {- return `credential path ${JSON.stringify(path)} must be a $HOME-relative path with no traversal`;- }- if (segments[0] === DISPLACED_DIR_REL)- return `credential path ${JSON.stringify(path)} is reserved — ${DISPLACED_DIR_REL} is where provision quarantines displaced $HOME state, and linking it would make it its own displacement target`;- if (!segments[0]!.startsWith("."))- return `credential path ${JSON.stringify(path)} must start with a dotfile or dot-directory segment — non-hidden $HOME paths are durable agent data, not credentials`;- if (!CREDENTIAL_PATH_RE.test(path))- return `credential path ${JSON.stringify(path)} may only use letters, digits, and ._/@+- — other characters cannot ride the capture sweep`;- const builtIn = BUILT_IN_CREDENTIAL_PATHS.find(- (base) => path === base.path || nested(path, base.path) || nested(base.path, path),- );- if (builtIn && (path !== builtIn.path || kind !== builtIn.kind))- return `credential path ${JSON.stringify(path)} (${kind}) overlaps the built-in credential path ${JSON.stringify(builtIn.path)} (${builtIn.kind}) — declare the exact built-in path with its correct kind or a disjoint one`;- return undefined;-}--export function parseToolDescriptor(raw: string, sourcePath: string): ToolDescriptor {- let parsed: unknown;- try {- parsed = JSON.parse(raw);- } catch (err) {- throw new Error(`${sourcePath} is not valid JSON: ${(err as Error).message}`, { cause: err });- }- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {- throw new Error(`${sourcePath} must be a JSON object`);- }- const d = parsed as Record<string, unknown>;- if (typeof d["id"] !== "string" || !d["id"].trim()) {- throw new Error(`${sourcePath}: "id" is required and must be a non-empty string`);- }- if (!TOOL_ID_RE.test(d["id"])) {- throw new Error(- `${sourcePath}: "id" must match ${TOOL_ID_RE.source} (lowercase alphanumerics and hyphens) — it is interpolated into shell probes`,- );- }- const out: ToolDescriptor = { id: d["id"] };-- for (const key of ["label", "advertise"] as const) {- if (d[key] !== undefined) {- if (typeof d[key] !== "string") throw new Error(`${sourcePath}: "${key}" must be a string`);- out[key] = d[key] as string;- }- }-- if (d["hints"] !== undefined) {- if (!Array.isArray(d["hints"]) || d["hints"].some((h) => typeof h !== "string")) {- throw new Error(`${sourcePath}: "hints" must be an array of strings`);- }- out.hints = d["hints"] as string[];- }-- if (d["egress"] !== undefined) {- if (!Array.isArray(d["egress"]) || d["egress"].some((h) => typeof h !== "string")) {- throw new Error(`${sourcePath}: "egress" must be an array of host strings`);- }- out.egress = d["egress"] as string[];- }-- if (d["auth"] !== undefined) out.auth = parseAuth(d["auth"], sourcePath);- if (d["approvals"] !== undefined) out.approvals = parseApprovals(d["approvals"], sourcePath);-- if (d["install"] !== undefined) {- const inst = d["install"];- if (typeof inst !== "object" || inst === null || Array.isArray(inst)) {- throw new Error(`${sourcePath}: "install" must be an object`);- }- const binary = (inst as Record<string, unknown>)["binary"];- if (binary !== undefined && typeof binary !== "string") {- throw new Error(`${sourcePath}: "install.binary" must be a string`);- }- if (binary !== undefined && !TOOL_ID_RE.test(binary as string)) {- throw new Error(- `${sourcePath}: "install.binary" must match ${TOOL_ID_RE.source} (lowercase alphanumerics and hyphens) — it is interpolated into generated Dockerfile lines`,- );- }- const files = (inst as Record<string, unknown>)["files"];- out.install = {- ...(binary !== undefined ? { binary: binary as string } : {}),- ...(files !== undefined- ? {- files: parseInstallFiles(files, sourcePath, {- id: out.id,- binary: (binary as string | undefined) ?? out.id,- }),- }- : {}),- };- }-- const credentialPaths = out.auth?.credentialPaths ?? [];- for (const [index, credentialPath] of credentialPaths.entries()) {- const { path } = credentialPath;- const err = credentialPathError(path, credentialPath.kind);- if (err) throw new Error(`${sourcePath}: ${err}`);- const other = credentialPaths.find(- (entry, otherIndex) =>- otherIndex !== index && (path === entry.path || nested(path, entry.path) || nested(entry.path, path)),- );- if (other) {- throw new Error(- `${sourcePath}: credential paths ${JSON.stringify(path)} and ${JSON.stringify(other.path)} overlap — declare disjoint paths`,- );- }- }- const binary = out.install?.binary ?? out.id;- if (out.auth?.broker && !POSIX_FUNCTION_NAME_RE.test(binary)) {- throw new Error(- `${sourcePath}: a brokered tool's binary ${JSON.stringify(binary)} must match ${POSIX_FUNCTION_NAME_RE.source} — vended credentials wrap it in a shell function, and not every sandbox shell accepts hyphenated function names`,- );- }- for (const [i, approval] of (out.approvals ?? []).entries()) {- const compiled = compileApproval(binary, approval);- try {- new RegExp(compiled.pattern, "i");- } catch (e) {- throw new Error(`${sourcePath}: approvals[${i}] is not a valid regex: ${(e as Error).message}`, { cause: e });- }- if (compiled.pattern.length > MAX_APPROVAL_PATTERN_LEN) {- throw new Error(`${sourcePath}: approvals[${i}] pattern is too long (max ${MAX_APPROVAL_PATTERN_LEN} chars)`);- }- if (approvalPatternTooSlow(compiled.pattern)) {- throw new Error(- `${sourcePath}: approvals[${i}] pattern is too slow to evaluate — it may cause catastrophic backtracking`,- );- }- if (approval.pattern !== undefined && !rawApprovalTargetsTool(binary, approval.pattern)) {- throw new Error(- `${sourcePath}: approvals[${i}].pattern must refer to its own tool binary by starting with \\b${binary}\\b and may not use a top-level alternative`,- );- }- }-- return out;-}--function parseAuth(raw: unknown, sourcePath: string): ToolAuthDescriptor {- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {- throw new Error(`${sourcePath}: "auth" must be an object`);- }- const a = raw as Record<string, unknown>;- for (const key of ["check", "reauth"] as const) {- if (typeof a[key] !== "string" || !(a[key] as string).trim()) {- throw new Error(`${sourcePath}: "auth.${key}" is required and must be a non-empty string`);- }- }- const out: ToolAuthDescriptor = { check: a["check"] as string, reauth: a["reauth"] as string };- if (a["credentialPaths"] !== undefined) {- if (!Array.isArray(a["credentialPaths"])) {- throw new Error(`${sourcePath}: "auth.credentialPaths" must be an array of { path, kind } objects`);- }- out.credentialPaths = a["credentialPaths"].map((entry, index) => {- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {- throw new Error(`${sourcePath}: "auth.credentialPaths[${index}]" must be an object`);- }- const value = entry as Record<string, unknown>;- if (typeof value.path !== "string" || (value.kind !== "file" && value.kind !== "directory")) {- throw new Error(- `${sourcePath}: "auth.credentialPaths[${index}]" requires string path and kind file or directory`,- );- }- return { path: value.path, kind: value.kind };- });- }- if (a["splitEnv"] !== undefined) {- const se = a["splitEnv"];- if (typeof se !== "object" || se === null || Array.isArray(se)) {- throw new Error(`${sourcePath}: "auth.splitEnv" must be an object of string values`);- }- const map: Record<string, string> = {};- for (const [k, v] of Object.entries(se)) {- if (!SPLIT_ENV_KEY_RE.test(k)) {- throw new Error(- `${sourcePath}: "auth.splitEnv" key ${JSON.stringify(k)} must match ${SPLIT_ENV_KEY_RE.source}`,- );- }- if (typeof v !== "string") throw new Error(`${sourcePath}: "auth.splitEnv.${k}" must be a string`);- if (/[{}]/.test(v.replaceAll("{actingSlackUserId}", ""))) {- throw new Error(`${sourcePath}: "auth.splitEnv.${k}" may only use the {actingSlackUserId} placeholder`);- }- map[k] = v;- }- out.splitEnv = map;- }- if (a["broker"] !== undefined) out.broker = parseBroker(a["broker"], sourcePath);- return out;-}--function parseBroker(raw: unknown, sourcePath: string): ToolCredentialBroker {- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {- throw new Error(`${sourcePath}: "auth.broker" must be an object`);- }- const b = raw as Record<string, unknown>;- if (b["kind"] !== "aws-role") throw new Error(`${sourcePath}: "auth.broker.kind" must be "aws-role"`);- if (typeof b["roleArnEnv"] !== "string" || !SPLIT_ENV_KEY_RE.test(b["roleArnEnv"])) {- throw new Error(`${sourcePath}: "auth.broker.roleArnEnv" is required and must match ${SPLIT_ENV_KEY_RE.source}`);- }- const out: ToolCredentialBroker = { kind: "aws-role", roleArnEnv: b["roleArnEnv"], sessionActions: [] };- if (b["regionEnv"] !== undefined) {- if (typeof b["regionEnv"] !== "string" || !SPLIT_ENV_KEY_RE.test(b["regionEnv"])) {- throw new Error(`${sourcePath}: "auth.broker.regionEnv" must match ${SPLIT_ENV_KEY_RE.source}`);- }- out.regionEnv = b["regionEnv"];- }- if (b["region"] !== undefined) {- if (typeof b["region"] !== "string" || !b["region"].trim()) {- throw new Error(`${sourcePath}: "auth.broker.region" must be a non-empty string`);- }- out.region = b["region"];- }- if (out.region === undefined && out.regionEnv === undefined) {- throw new Error(- `${sourcePath}: "auth.broker" needs "region" or "regionEnv" — the vended credentials carry a region`,- );- }- const actions = b["sessionActions"];- if (- !Array.isArray(actions) ||- actions.length === 0 ||- actions.some((entry) => typeof entry !== "string" || !entry.trim())- ) {- throw new Error(`${sourcePath}: "auth.broker.sessionActions" must be a non-empty array of IAM action strings`);- }- out.sessionActions = actions as string[];- return out;-}--function parseApprovals(raw: unknown, sourcePath: string): ToolApproval[] {- if (!Array.isArray(raw)) throw new Error(`${sourcePath}: "approvals" must be an array`);- return raw.map((entry, i) => {- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {- throw new Error(`${sourcePath}: approvals[${i}] must be an object`);- }- const e = entry as Record<string, unknown>;- const hasCommand = typeof e["command"] === "string" && (e["command"] as string).trim() !== "";- const hasPattern = typeof e["pattern"] === "string" && (e["pattern"] as string).trim() !== "";- if (!hasCommand && !hasPattern) throw new Error(`${sourcePath}: approvals[${i}] needs a "command" or a "pattern"`);- if (hasCommand && hasPattern)- throw new Error(`${sourcePath}: approvals[${i}] has both "command" and "pattern" — use one`);- const out: ToolApproval = {};- if (hasCommand) out.command = e["command"] as string;- if (hasPattern) out.pattern = e["pattern"] as string;- if (e["decision"] !== undefined) {- const dec = e["decision"];- if (dec !== "require_approval" && dec !== "deny") {- throw new Error(`${sourcePath}: approvals[${i}].decision must be require_approval or deny`);- }- out.decision = dec;- }- if (e["reason"] !== undefined) {- if (typeof e["reason"] !== "string") throw new Error(`${sourcePath}: approvals[${i}].reason must be a string`);- out.reason = e["reason"];- }- return out;- });-}--const TOOL_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;-const SPLIT_ENV_KEY_RE = /^[A-Z][A-Z0-9_]*$/;-const POSIX_FUNCTION_NAME_RE = /^[a-z_][a-z0-9_]*$/;--const MAX_APPROVAL_PATTERN_LEN = 256;-function approvalPatternTooSlow(pattern: string): boolean {- if (/\\[1-9]|\\k<[^>]+>/.test(pattern)) return true;- type AtomChars = { ascii: Set<number>; asciiOnly: boolean };- const unknownChars = (): AtomChars => ({- ascii: new Set(Array.from({ length: 128 }, (_, i) => i)),- asciiOnly: false,- });- const atomChars = (source: string): AtomChars => {- let atom: RegExp;- try {- atom = new RegExp(`^(?:${source})$`, "i");- } catch {- return unknownChars();- }- const ascii = new Set<number>();- for (let code = 0; code < 128; code++) if (atom.test(String.fromCharCode(code))) ascii.add(code);- const asciiOnly =- (source.length === 1 && source.charCodeAt(0) < 128 && source !== ".") ||- /^\\(?:[dw]|x[0-7][0-9a-f]|u00[0-7][0-9a-f])$/i.test(source) ||- /^\[(?!\^)(?:[^\\\]]|\\(?:[dw]|x[0-7][0-9a-f]|u00[0-7][0-9a-f]))+\]$/i.test(source);- return { ascii, asciiOnly };- };- const overlaps = (left: AtomChars | undefined, right: AtomChars | undefined): boolean => {- if (!left || !right) return false;- for (const code of left.ascii) if (right.ascii.has(code)) return true;- return !left.asciiOnly && !right.asciiOnly;- };- const splitAlternatives = (source: string): string[] => {- const branches: string[] = [];- let start = 0;- let depth = 0;- let inClass = false;- for (let i = 0; i < source.length; i++) {- const char = source[i]!;- if (char === "\\") {- i++;- continue;- }- if (char === "[") inClass = true;- else if (char === "]" && inClass) inClass = false;- else if (!inClass && char === "(") depth++;- else if (!inClass && char === ")") depth--;- else if (!inClass && depth === 0 && char === "|") {- branches.push(source.slice(start, i));- start = i + 1;- }- }- branches.push(source.slice(start));- return branches;- };- const branchShape = (branch: string): { domains: AtomChars[]; nullable: boolean } => {- const domains: AtomChars[] = [];- let nullable = true;- for (let i = 0; i < branch.length; i++) {- const char = branch[i]!;- if (char === "^" || char === "$") continue;- let end = i + 1;- let domain: AtomChars;- if (char === "\\") {- if (branch[i + 1] === "b" || branch[i + 1] === "B") {- i++;- continue;- }- end = i + 2;- if (branch[i + 1] === "x" && /^[0-9a-f]{2}$/i.test(branch.slice(i + 2, i + 4))) end = i + 4;- else if (branch[i + 1] === "u" && /^[0-9a-f]{4}$/i.test(branch.slice(i + 2, i + 6))) end = i + 6;- domain = atomChars(branch.slice(i, end));- } else if (char === "[") {- end = i + 1;- for (; end < branch.length; end++) {- if (branch[end] === "\\") end++;- else if (branch[end] === "]") {- end++;- break;- }- }- domain = atomChars(branch.slice(i, end));- } else if (char === "(" || char === "*" || char === "+" || char === "?" || char === "{") {- return { domains: domains.length ? domains : [unknownChars()], nullable: true };- } else {- domain = atomChars(char);- }- domains.push(domain);- const quantifier = /^(?:[*+?]|\{\d+(?:,\d*)?\})\??/.exec(branch.slice(end))?.[0];- if (quantifier) {- if (quantifier === "+" || /^\{[1-9]/.test(quantifier)) nullable = false;- end += quantifier.length;- } else nullable = false;- i = end - 1;- }- return domains.length ? { domains, nullable } : { domains: [unknownChars()], nullable: true };- };- const prefixAmbiguous = (left: ReturnType<typeof branchShape>, right: ReturnType<typeof branchShape>): boolean => {- if (left.nullable || right.nullable) return true;- const length = Math.min(left.domains.length, right.domains.length);- for (let i = 0; i < length; i++) if (!overlaps(left.domains[i], right.domains[i])) return false;- return true;- };- const alternativeFactor = (source: string): number => {- const branches = splitAlternatives(source).map(branchShape);- let overlapsCount = 0;- for (let i = 0; i < branches.length; i++) {- for (let j = i + 1; j < branches.length; j++) if (prefixAmbiguous(branches[i]!, branches[j]!)) overlapsCount++;- }- return 1 + overlapsCount;- };- let ambiguityBudget = 1;- const stack: Array<{- start: number;- bodyStart: number;- hasQuantifier: boolean;- hasAlternative: boolean;- directAlternative: boolean;- assertion: boolean;- branchStart: boolean;- startsQuantified?: AtomChars;- endsQuantified?: AtomChars;- lastQuantified?: AtomChars;- firstChars?: AtomChars;- lastChars?: AtomChars;- hasAtom: boolean;- }> = [- {- start: -1,- bodyStart: 0,- hasQuantifier: false,- hasAlternative: false,- directAlternative: false,- assertion: false,- branchStart: true,- hasAtom: false,- },- ];- const quantifierEnd = (at: number): number | undefined => {- if (pattern[at] === "*" || pattern[at] === "+" || pattern[at] === "?")- return at + 1 + (pattern[at + 1] === "?" ? 1 : 0);- if (pattern[at] !== "{") return undefined;- const match = /^\{\d+(?:,\d*)?\}/.exec(pattern.slice(at));- if (!match) return undefined;- const end = at + match[0].length;- return end + (pattern[end] === "?" ? 1 : 0);- };- const markAtom = (quantified: boolean, firstChars: AtomChars, lastChars = firstChars): boolean => {- const frame = stack.at(-1)!;- if (quantified && overlaps(frame.lastQuantified, firstChars)) return true;- if (frame.branchStart) {- frame.firstChars ??= firstChars;- if (quantified) frame.startsQuantified ??= firstChars;- }- frame.branchStart = false;- frame.hasAtom = true;- frame.lastChars = lastChars;- frame.lastQuantified = quantified ? lastChars : undefined;- if (quantified) for (const open of stack) open.hasQuantifier = true;- return false;- };- for (let i = 0; i < pattern.length; i++) {- const char = pattern[i]!;- if (char === "\\") {- let end = i + 2;- if (pattern[i + 1] === "x" && /^[0-9a-f]{2}$/i.test(pattern.slice(i + 2, i + 4))) end = i + 4;- else if (pattern[i + 1] === "u" && /^[0-9a-f]{4}$/i.test(pattern.slice(i + 2, i + 6))) end = i + 6;- if (pattern[i + 1] === "b" || pattern[i + 1] === "B") {- i = end - 1;- continue;- }- const quantifiedEnd = quantifierEnd(end);- if (markAtom(quantifiedEnd !== undefined, atomChars(pattern.slice(i, end)))) return true;- i = (quantifiedEnd ?? end) - 1;- continue;- }- if (char === "[") {- let end = i + 1;- for (; end < pattern.length; end++) {- if (pattern[end] === "\\") end++;- else if (pattern[end] === "]") {- end++;- break;- }- }- const quantifiedEnd = quantifierEnd(end);- if (markAtom(quantifiedEnd !== undefined, atomChars(pattern.slice(i, end)))) return true;- i = (quantifiedEnd ?? end) - 1;- continue;- }- if (char === "(") {- let prefixEnd = i + 1;- let assertion = false;- if (pattern[prefixEnd] === "?") {- const kind = pattern[prefixEnd + 1];- if (kind === ":") prefixEnd += 2;- else if (kind === "=" || kind === "!") {- assertion = true;- prefixEnd += 2;- } else if (kind === "<" && (pattern[prefixEnd + 2] === "=" || pattern[prefixEnd + 2] === "!")) {- assertion = true;- prefixEnd += 3;- } else if (kind === "<") {- const close = pattern.indexOf(">", prefixEnd + 2);- if (close !== -1) prefixEnd = close + 1;- }- }- stack.push({- start: i,- bodyStart: prefixEnd,- hasQuantifier: false,- hasAlternative: false,- directAlternative: false,- assertion,- branchStart: true,- hasAtom: false,- });- i = prefixEnd - 1;- continue;- }- if (char === "|") {- for (const group of stack) group.hasAlternative = true;- const frame = stack.at(-1)!;- frame.directAlternative = true;- frame.endsQuantified ??= frame.lastQuantified;- frame.lastQuantified = undefined;- frame.branchStart = true;- continue;- }- if (char === ")" && stack.length > 1) {- const group = stack.pop()!;- if (group.directAlternative) {- ambiguityBudget *= alternativeFactor(pattern.slice(group.bodyStart, i));- if (ambiguityBudget > 1_024) return true;- }- group.endsQuantified ??= group.lastQuantified;- const quantifiedEnd = quantifierEnd(i + 1);- const quantified = quantifiedEnd !== undefined;- if (quantified && (group.hasQuantifier || group.hasAlternative)) return true;- if (!group.assertion) {- const parent = stack.at(-1)!;- const firstChars = group.hasAlternative ? unknownChars() : (group.firstChars ?? unknownChars());- const lastChars = group.hasAlternative ? unknownChars() : (group.lastChars ?? unknownChars());- if (quantified) {- if (markAtom(true, firstChars, lastChars)) return true;- } else if (group.hasAtom) {- if (overlaps(parent.lastQuantified, group.startsQuantified)) return true;- if (parent.branchStart) {- parent.firstChars ??= firstChars;- parent.startsQuantified ??= group.startsQuantified;- }- parent.branchStart = false;- parent.hasAtom = true;- parent.lastChars = lastChars;- parent.lastQuantified = group.endsQuantified;- parent.hasQuantifier ||= group.hasQuantifier;- parent.hasAlternative ||= group.hasAlternative;- }- }- i = (quantifiedEnd ?? i + 1) - 1;- continue;- }- if (char === "^" || char === "$" || char === ")") continue;- const quantifiedEnd = quantifierEnd(i + 1);- if (markAtom(quantifiedEnd !== undefined, atomChars(char))) return true;- i = (quantifiedEnd ?? i + 1) - 1;- }- return false;-}--const escapeRegex = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");--function rawApprovalTargetsTool(binary: string, pattern: string): boolean {- if (!pattern.startsWith(`\\b${escapeRegex(binary)}\\b`)) return false;- let depth = 0;- let inClass = false;- let escaped = false;- for (const char of pattern) {- if (escaped) {- escaped = false;- continue;- }- if (char === "\\") {- escaped = true;- continue;- }- if (char === "[" && !inClass) {- inClass = true;- continue;- }- if (char === "]" && inClass) {- inClass = false;- continue;- }- if (inClass) continue;- if (char === "(") depth++;- else if (char === ")") depth = Math.max(0, depth - 1);- else if (char === "|" && depth === 0) return false;- }- return true;-}--export function compileApproval(binary: string, a: ToolApproval): { pattern: string; decision: ApprovalDecision } {- const decision: ApprovalDecision = a.decision ?? "require_approval";- if (a.pattern !== undefined) return { pattern: a.pattern, decision };- const words = (a.command ?? "").trim().split(/\s+/).filter(Boolean).map(escapeRegex);- return { pattern: `\\b${[escapeRegex(binary), ...words].join("\\s+")}(?:\\b|\\s|$)`, decision };-}+export {+ compileApproval,+ credentialPathError,+ parseToolDescriptor,+ type ToolCredentialBroker,+ type ToolCredentialPath,+ type ToolDescriptor,+ type ToolInstallFile,+} from "../../cli/src/tool-descriptor.ts";export function interpolateSplitEnv(template: Record<string, string>,diff --git a/test/core-cli-import-closure.test.ts b/test/core-cli-import-closure.test.tsnew file mode 100644index 000000000..2754e1d9c--- /dev/null+++ b/test/core-cli-import-closure.test.ts@@ -0,0 +1,43 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { readFileSync, readdirSync } from "node:fs";+import { dirname, join, relative, resolve } from "node:path";++// Core images copy only the cli/src files named in deploy/core/Dockerfile. If core reaches any other+// cli/src file at runtime, the image fails at startup, so pin the import closure here.+const root = resolve(import.meta.dirname, "..");++const runtimeImports = (file: string): string[] =>+ [+ /^(?:import|export)\s+(?!type\b)[^;]*?\sfrom\s+["']([^"']+)["']/gm,+ /\bimport\s*\(\s*["']([^"']+)["']/g,+ /^\s*import\s+["']([^"']+)["']/gm,+ ]+ .flatMap((re) => [...readFileSync(file, "utf8").matchAll(re)].map((m) => m[1]!))+ .filter((spec) => spec.startsWith("."))+ .map((spec) => relative(root, resolve(dirname(file), spec)));++const tsFiles = (dir: string): string[] =>+ readdirSync(join(root, dir), { recursive: true, encoding: "utf8" })+ .filter((f) => f.endsWith(".ts"))+ .map((f) => join(root, dir, f));++test("core reaches only the cli/src files the core image copies, and those import nothing else", () => {+ const copyLine = /^COPY ((?:cli\/src\/\S+\s+)+)\.\/cli\/src\/$/m.exec(+ readFileSync(join(root, "deploy/core/Dockerfile"), "utf8"),+ );+ assert.ok(copyLine, "deploy/core/Dockerfile should COPY the shared cli/src files");+ const copied = new Set(copyLine[1]!.trim().split(/\s+/));++ const reached = tsFiles("src")+ .flatMap(runtimeImports)+ .filter((p) => p.startsWith("cli/"));+ assert.ok(reached.length > 0);+ for (const target of reached) assert.ok(copied.has(target), `core imports ${target}, which the image does not copy`);++ for (const file of copied) {+ for (const target of runtimeImports(join(root, file))) {+ assert.ok(copied.has(target), `${file} imports ${target}, which the image does not copy`);+ }+ }+});diff --git a/test/deploy-directory-doc.test.ts b/test/deploy-directory-doc.test.tsindex c1906d684..dcc6b8046 100644--- a/test/deploy-directory-doc.test.ts+++ b/test/deploy-directory-doc.test.ts@@ -23,7 +23,7 @@ test("every ENFORCED deployment-contract clause names a verifier and its impleme["../src/api/routes/deployment-layer.ts", /PUT.*\/v1\/deployment-layer/],],"sandbox.approvals-tighten": [- ["../src/deployment/deployment-layer.ts", /ApprovalDecision\s*=\s*"require_approval"\s*\|\s*"deny"/],+ ["../cli/src/tool-descriptor.ts", /ApprovalDecision\s*=\s*"require_approval"\s*\|\s*"deny"/],["../src/policy/command-policy.ts", /function evaluateCommand/],],"runtime.layer-resolved": [