@sema-agent/core
Version:
Stateless, task-oriented AI agent core
528 lines (527 loc) • 29.3 kB
JavaScript
import { types } from "node:util";
import { receive } from "./mods/kernel/receive.js";
import { commandSandboxPlanInForce } from "./command-sandbox-dispatch.js";
import { isShellFaceToolName } from "./tool-registry.js";
import { wireOf } from "./tool-name-readings.js";
import { providesCommandSandbox } from "./remote-env.js";
import { deliverEngineNotice } from "./engine-notice.js";
import { foreignLine } from "./protocol-http-auth.js";
import { arbitrateByMode, askClassMembersOf, classifyAsk } from "./ask-origin.js";
import { attest } from "./engine-attestation.js";
import { hostOfUrl } from "./host-target.js";
export const SANDBOX_SETTINGS_INVALID = "config.sandbox_settings_invalid";
export const COMMAND_SANDBOX_UNAVAILABLE = "config.command_sandbox_unavailable";
const BOOL = { t: "bool" };
const STR = { t: "str" };
const STRINGS = { t: "strings" };
const PATHS = { t: "strings", paths: true };
const NO_MATCH = { t: "enum", of: ["warn", "deny", "error"] };
const MODE = { t: "enum", of: ["deny", "mask"] };
const SIG = { t: "enum", of: ["deny", "passthrough"] };
const SETTINGS = {
t: "obj",
fields: {
enabled: BOOL,
failIfUnavailable: BOOL,
autoAllowBashIfSandboxed: BOOL,
allowUnsandboxedCommands: BOOL,
excludedCommands: STRINGS,
ignoreViolations: { t: "map", value: PATHS },
filesystem: { t: "obj", fields: { allowWrite: PATHS, denyWrite: PATHS, denyRead: PATHS, allowRead: PATHS, disabled: BOOL, allowManagedReadPathsOnly: { t: "merge" } } },
network: {
t: "obj",
fields: {
allowedDomains: STRINGS, deniedDomains: STRINGS, strictAllowlist: BOOL, allowManagedDomainsOnly: { t: "merge" }, allowUnixSockets: PATHS, allowAllUnixSockets: BOOL,
allowLocalBinding: BOOL, allowMachLookup: STRINGS, httpProxyPort: { t: "port" }, socksProxyPort: { t: "port" },
tlsTerminate: { t: "obj", fields: { caCertPath: { t: "abs" }, caKeyPath: { t: "abs" } } },
},
},
credentials: {
t: "obj",
fields: {
files: { t: "list", item: { t: "obj", required: ["path", "mode"], fields: { path: { t: "abs" }, mode: MODE, extract: STR, onExtractNoMatch: NO_MATCH, decode: { t: "enum", of: ["jwt"] }, maskClaims: STRINGS, maskDuplicates: BOOL, injectHosts: STRINGS } } },
envVars: { t: "list", item: { t: "obj", required: ["name", "mode"], fields: { name: STR, mode: MODE, extract: STR, onExtractNoMatch: NO_MATCH, decode: { t: "enum", of: ["jwt"] }, maskClaims: STRINGS, injectHosts: STRINGS } } },
allowPlaintextInject: BOOL,
awsPairs: { t: "list", item: { t: "obj", required: ["accessKeyIdVar", "secretAccessKeyVar"], fields: { accessKeyIdVar: STR, secretAccessKeyVar: STR, sessionTokenVar: STR } } },
sigv4: { t: "obj", fields: { streaming: SIG, presigned: SIG, sigv4a: SIG } },
},
},
enableWeakerNestedSandbox: BOOL,
allowNestedUserNamespaces: BOOL,
enableWeakerNetworkIsolation: BOOL,
allowAppleEvents: BOOL,
ripgrep: { t: "obj", required: ["command"], fields: { command: STR, args: STRINGS } },
bwrapPath: { t: "abs" },
socatPath: { t: "abs" },
},
};
function settingsInvalid(key, why) {
const e = new Error(`TaskSpec.sandbox${key === "" ? "" : `.${key}`} ${why} — a sandbox requirement that cannot be read is no requirement, so the run is refused rather than started without it.`);
e.code = SANDBOX_SETTINGS_INVALID;
e.detail = { key: key === "" ? "sandbox" : key, reason: why };
return e;
}
const shown = (v) => {
if (typeof v === "string")
return JSON.stringify(v.slice(0, 120));
if (v === null)
return "null";
if (Array.isArray(v))
return "an array";
return typeof v === "object" ? "an object" : `${typeof v} ${String(v).slice(0, 40)}`;
};
function pathProblem(p) {
if (p.includes("\0"))
return "holds a NUL character";
if (p.startsWith("/") || p.startsWith("~/"))
return undefined;
return "is not an absolute path or one under the home directory (`~/`): resolve it against the settings file it came from before sending it";
}
function judge(value, field, key) {
switch (field.t) {
case "merge":
throw settingsInvalid(key, "is applied by the host when it merges settings sources, and a task's requirement does not carry it");
case "bool":
if (typeof value !== "boolean")
throw settingsInvalid(key, `must be a boolean (got ${shown(value)})`);
return value;
case "str":
if (typeof value !== "string" || value.length === 0)
throw settingsInvalid(key, `must be a non-empty string (got ${shown(value)})`);
return value;
case "abs": {
if (typeof value !== "string" || value.length === 0)
throw settingsInvalid(key, `must be a non-empty path (got ${shown(value)})`);
const problem = pathProblem(value);
if (problem !== undefined)
throw settingsInvalid(key, `${shown(value)} ${problem}`);
return value;
}
case "port":
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 65535)
throw settingsInvalid(key, `must be a TCP port, a whole number from 1 to 65535 (got ${shown(value)})`);
return value;
case "enum":
if (typeof value !== "string" || !field.of.includes(value))
throw settingsInvalid(key, `must be one of ${field.of.map((w) => JSON.stringify(w)).join(", ")} (got ${shown(value)})`);
return value;
case "strings": {
if (!Array.isArray(value))
throw settingsInvalid(key, `must be an array of strings (got ${shown(value)})`);
return Array.from(value, (v, i) => judge(v, field.paths === true ? { t: "abs" } : STR, `${key}[${i}]`));
}
case "list": {
if (!Array.isArray(value))
throw settingsInvalid(key, `must be an array (got ${shown(value)})`);
return Array.from(value, (v, i) => judge(v, field.item, `${key}[${i}]`));
}
case "map": {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw settingsInvalid(key, `must be an object of lists (got ${shown(value)})`);
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, judge(v, field.value, `${key}[${JSON.stringify(k)}]`)]));
}
case "obj": {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw settingsInvalid(key, `must be an object (got ${shown(value)})`);
const out = {};
for (const [k, v] of Object.entries(value)) {
const member = Object.hasOwn(field.fields, k) ? field.fields[k] : undefined;
const at = key === "" ? k : `${key}.${k}`;
if (member === undefined)
throw settingsInvalid(at, "is not a member of the sandbox settings");
if (v === undefined)
continue;
out[k] = judge(v, member, at);
}
for (const k of field.required ?? [])
if (out[k] === undefined)
throw settingsInvalid(key === "" ? k : `${key}.${k}`, "is required");
return out;
}
}
}
function resolvePaths(value, field, key, home) {
switch (field.t) {
case "abs":
return resolvedPath(String(value), key, home);
case "strings":
return field.paths === true && Array.isArray(value) ? value.map((p, i) => resolvedPath(String(p), `${key}[${i}]`, home)) : value;
case "list":
return Array.isArray(value) ? value.map((v, i) => resolvePaths(v, field.item, `${key}[${i}]`, home)) : value;
case "map":
return typeof value === "object" && value !== null ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolvePaths(v, field.value, `${key}[${JSON.stringify(k)}]`, home)])) : value;
case "obj":
return typeof value === "object" && value !== null
? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, Object.hasOwn(field.fields, k) ? resolvePaths(v, field.fields[k], key === "" ? k : `${key}.${k}`, home) : v]))
: value;
default:
return value;
}
}
export function receiveTaskSandbox(value) {
if (value === undefined)
return undefined;
const prior = typeof value === "object" && value !== null ? RECEIVED_REQUIREMENTS.get(value) : undefined;
if (prior !== undefined)
return prior;
const received = receive(value, { accessors: "call-once", depth: 6, others: "refuse", past: "refuse", isProxy: (v) => types.isProxy(v) });
if (!received.ok)
throw settingsInvalid(received.fault.path.join("."), `cannot be received as data (${received.fault.kind})`);
const judged = deepFreeze(judge(received.value, SETTINGS, ""));
if (typeof value === "object" && value !== null)
RECEIVED_REQUIREMENTS.set(value, judged);
return judged;
}
const RECEIVED_REQUIREMENTS = new WeakMap();
function deepFreeze(v) {
if (typeof v === "object" && v !== null && !Object.isFrozen(v)) {
for (const m of Object.values(v))
deepFreeze(m);
Object.freeze(v);
}
return v;
}
const OFF = Object.freeze({ state: "off" });
const NOT_NEEDED = Object.freeze({ state: "not_needed" });
export function resumedSandbox(recorded, stated) {
return mergeChildSandbox(receiveTaskSandbox(recorded), stated);
}
export function judgeCommandSandbox(j) {
const settings = receiveTaskSandbox(j.requirement);
if (settings === undefined || settings.enabled !== true)
return OFF;
if (j.env === undefined)
return NOT_NEEDED;
const failIfUnavailable = failsIfUnavailable(settings);
if (!providesCommandSandbox(j.env)) {
const said = "the execution environment does not declare a command sandbox";
const reason = `${said} (capabilities.commandSandbox is not true)`;
if (failIfUnavailable) {
const e = new Error(`sandbox required but unavailable: ${reason} — sandbox.failIfUnavailable is set, so the run is refused rather than started without a working sandbox. Run it on an environment that keeps a command sandbox, or set sandbox.failIfUnavailable to false to run without one.`);
e.code = COMMAND_SANDBOX_UNAVAILABLE;
throw e;
}
deliverEngineNotice(j.onNotice, {
code: COMMAND_SANDBOX_UNAVAILABLE,
message: `Sandbox disabled: ${said}. Commands will run WITHOUT sandboxing: the network and filesystem restrictions of sandbox will NOT be enforced.`,
detail: { reason, ...(j.attribution?.sessionId !== undefined ? { sessionId: j.attribution.sessionId } : {}), ...(j.attribution?.runId !== undefined ? { runId: j.attribution.runId } : {}) },
});
return Object.freeze({ state: "unavailable", reason });
}
return Object.freeze({ state: "armed", requirement: settings, lapse: { reason: undefined } });
}
const failsIfUnavailable = (s) => s.failIfUnavailable ?? true;
class HomeUnstated extends Error {
}
function resolvedPath(p, key, home) {
if (!p.startsWith("~/"))
return p;
if (home === undefined || !home.startsWith("/"))
throw new HomeUnstated(`TaskSandbox.${key} ${shown(p)} is under the home directory, and this environment states no absolute home directory to read it against`);
return `${home.replace(/\/+$/, "")}/${p.slice(2)}`;
}
function instructionOf(judged, home) {
const s = resolvePaths(judged, SETTINGS, "", home);
const fsPaths = (k) => [...(s.filesystem?.[k] ?? [])];
const { allowedDomains: _a, deniedDomains: _d, strictAllowlist: _s, ...networkMechanism } = s.network ?? {};
const mechanism = {
...(s.filesystem?.disabled !== undefined ? { filesystem: { disabled: s.filesystem.disabled } } : {}),
...(Object.keys(networkMechanism).length > 0 ? { network: networkMechanism } : {}),
...(s.credentials !== undefined ? { credentials: s.credentials } : {}),
...(s.enableWeakerNestedSandbox !== undefined ? { enableWeakerNestedSandbox: s.enableWeakerNestedSandbox } : {}),
...(s.allowNestedUserNamespaces !== undefined ? { allowNestedUserNamespaces: s.allowNestedUserNamespaces } : {}),
...(s.enableWeakerNetworkIsolation !== undefined ? { enableWeakerNetworkIsolation: s.enableWeakerNetworkIsolation } : {}),
...(s.allowAppleEvents !== undefined ? { allowAppleEvents: s.allowAppleEvents } : {}),
...(s.ripgrep !== undefined ? { ripgrep: s.ripgrep } : {}),
...(s.bwrapPath !== undefined ? { bwrapPath: s.bwrapPath } : {}),
...(s.socatPath !== undefined ? { socatPath: s.socatPath } : {}),
};
const instruction = deepFreeze({
boundary: {
filesystem: { allowWrite: fsPaths("allowWrite"), denyWrite: fsPaths("denyWrite"), denyRead: fsPaths("denyRead"), allowRead: fsPaths("allowRead") },
network: { allowedDomains: [...(s.network?.allowedDomains ?? [])], deniedDomains: [...(s.network?.deniedDomains ?? [])] },
},
mechanism: structuredClone(mechanism),
});
return { instruction, ignoreViolations: s.ignoreViolations };
}
const NO_PLAN = Object.freeze({ kind: "none" });
const ESCAPED = Object.freeze({ kind: "unsandboxed", by: "escape" });
const LAPSED = Object.freeze({ kind: "unsandboxed", by: "lapsed" });
function asksToEscape(args) {
return typeof args === "object" && args !== null && Object.hasOwn(args, "dangerouslyDisableSandbox") && args.dangerouslyDisableSandbox === true;
}
export function declaresSandboxEscape(parameters) {
const properties = typeof parameters === "object" && parameters !== null ? parameters.properties : undefined;
return typeof properties === "object" && properties !== null && Object.hasOwn(properties, "dangerouslyDisableSandbox");
}
export function commandSandboxPlan(run, call, leg) {
if (run.state !== "armed" || !call.envHand || !isShellFaceToolName(call.toolName))
return NO_PLAN;
const { requirement, lapse } = run;
if (lapse.reason !== undefined)
return failsIfUnavailable(requirement) ? Object.freeze({ kind: "refused", reason: `its sandbox stopped working during this run (${lapse.reason.slice(0, 300)}) and sandbox.failIfUnavailable is set, so no command runs without it` }) : LAPSED;
if (call.escapeJudged && requirement.allowUnsandboxedCommands !== false && asksToEscape(call.args))
return ESCAPED;
let read;
try {
read = instructionOf(requirement, leg.home);
}
catch (e) {
if (e instanceof HomeUnstated)
return Object.freeze({ kind: "refused", reason: e.message });
throw e;
}
const { boundary, mechanism } = read.instruction;
const allowWrite = Object.freeze([...new Set([...leg.writeRoots(), ...boundary.filesystem.allowWrite])]);
const askHost = requirement.network?.strictAllowlist !== true ? call.askHost : undefined;
const instruction = Object.freeze({ boundary: Object.freeze({ filesystem: Object.freeze({ ...boundary.filesystem, allowWrite }), network: boundary.network }), mechanism, ...(askHost !== undefined ? { askHost } : {}) });
return Object.freeze({ kind: "command", instruction, ...(read.ignoreViolations !== undefined ? { ignoreViolations: deepFreeze(read.ignoreViolations) } : {}) });
}
export function commandSandboxSideOf(plan) {
return plan.kind === "none" ? undefined : plan.kind === "unsandboxed" ? "outside" : "inside";
}
export function commandSandboxPlans(run, leg, mounted, hosts) {
const planOf = (call) => {
const hand = wireOf("commandSandbox.plan.hand", call);
const escapeJudged = declaresSandboxEscape(mounted.tools.find((t) => t.name === hand)?.parameters) && (call.parkedClasses === undefined || call.parkedClasses.includes("sandbox_override"));
const questions = hosts.current;
return commandSandboxPlan(run, { toolName: call.toolName, envHand: mounted.envHandToolNames.has(hand), args: call.args, escapeJudged, ...(questions !== undefined ? { askHost: (host) => questions(call.toolCallId, host) } : {}) }, leg);
};
const sideOf = (call, args) => {
const side = commandSandboxSideOf(planOf({ toolName: call.toolName, toolCallId: call.toolCallId, args }));
return side !== undefined ? { commandSandbox: side } : {};
};
return { planOf, sideOf };
}
export const SANDBOX_NETWORK_TOOL_NAME = "SandboxNetworkAccess";
export function sandboxHostQuestions(seat) {
const allowed = new Set();
const open = new Map();
const decide = async (toolCallId, host) => {
const rules = await seat.rules(host);
if (rules.refused)
return "no";
if (allowed.has(host))
return "yes";
const call = { toolCallId, toolName: SANDBOX_NETWORK_TOOL_NAME };
const message = `Allow network connection to ${host}?`;
const governed = rules.realApproval ? { requiresRealApproval: true } : {};
const asked = attest({ action: "ask", message, ...governed }, call, { guards: ["sandbox_network"], ...(rules.asks.length > 0 ? { foldedClasses: rules.asks } : {}) });
const classification = classifyAsk(asked, { call, contentQuestion: false, markedUnresolvable: false, org: undefined, tightened: undefined, mandateMarks: {} });
if (classification.row.ruleMayClear && (await rules.allowed()))
return "yes";
const byMode = () => {
const verdict = arbitrateByMode(seat.mode(), classification);
return verdict.kind === "released" ? "yes" : verdict.kind === "ask" ? "ask" : "no";
};
const question = { ...call, args: { host }, message };
let standing = byMode();
if (standing === "ask" && seat.mode() === "auto" && classification.row.classifierEligible) {
const heard = await seat.classify(question);
if (heard === false)
return "no";
if (heard === true)
standing = seat.mode() === "auto" ? "yes" : byMode();
}
if (standing !== "ask")
return standing;
if (seat.signal.aborted)
return "no";
return (await seat.ask({ ...question, ...askClassMembersOf(classification), ...governed, approvalCard: "network", ...rules.offers })) ? "person" : "no";
};
const answerOf = async (toolCallId, host) => {
const reached = await decide(toolCallId, host);
if (reached === "no" || seat.signal.aborted || (await seat.rules(host)).refused || seat.signal.aborted)
return false;
if (reached === "person")
allowed.add(host);
return true;
};
return (toolCallId, host) => {
if (typeof host !== "string")
return Promise.resolve(false);
const reading = hostOfUrl(`https://${host}/`);
if (!("host" in reading) || reading.host !== host)
return Promise.resolve(false);
const pending = open.get(host);
if (pending !== undefined)
return pending;
const answer = answerOf(toolCallId, host)
.catch(() => false)
.finally(() => open.delete(host));
open.set(host, answer);
return answer;
};
}
export function leavesByEscape(plan) {
return plan.kind === "unsandboxed" && plan.by === "escape";
}
const NO_PLAN_START = Object.freeze({ ok: false, reason: "this call carries no sandbox plan (it was not let go by the run's gate)" });
const OUTSIDE_START = Object.freeze({ ok: true });
export const SANDBOX_LAPSED_SENTENCE = "The Bash command sandbox has been disabled. Commands now run without sandbox restrictions; the earlier sandbox instructions no longer apply.";
export const SANDBOX_LAPSED_REQUIRED_SENTENCE = "The sandbox stopped working and this run requires it (sandbox.failIfUnavailable), so shell commands are refused for the rest of this run.";
export function lapseSentenceOf(run) {
if (run.state !== "armed" || run.lapse.reason === undefined)
return undefined;
return failsIfUnavailable(run.requirement) ? SANDBOX_LAPSED_REQUIRED_SENTENCE : SANDBOX_LAPSED_SENTENCE;
}
export function commandSandboxSeat(run, announce = { onNotice: undefined }) {
if (run.state !== "armed")
return undefined;
return {
start: () => {
const plan = commandSandboxPlanInForce();
switch (plan?.kind) {
case "command":
return { ok: true, sandbox: plan.instruction, ...(plan.ignoreViolations !== undefined ? { ignoreViolations: plan.ignoreViolations } : {}) };
case "unsandboxed":
return OUTSIDE_START;
case "refused":
return { ok: false, reason: plan.reason };
default:
return NO_PLAN_START;
}
},
refused: (by, detail) => {
if (by === "this_call" || run.lapse.reason !== undefined)
return undefined;
run.lapse.reason = detail.slice(0, 300);
const required = failsIfUnavailable(run.requirement);
const sentence = lapseSentenceOf(run);
deliverEngineNotice(announce.onNotice, {
code: COMMAND_SANDBOX_UNAVAILABLE,
message: `Sandbox disabled: the execution environment's command sandbox stopped working (${run.lapse.reason}). ${required ? "Shell commands are refused for the rest of this run (sandbox.failIfUnavailable)." : "Commands now run WITHOUT sandboxing for the rest of this run: the network and filesystem restrictions of sandbox will NOT be enforced."}`,
detail: { reason: run.lapse.reason, ...(announce.attribution?.sessionId !== undefined ? { sessionId: announce.attribution.sessionId } : {}), ...(announce.attribution?.runId !== undefined ? { runId: announce.attribution.runId } : {}) },
});
return sentence;
},
};
}
export function lapsedBy(seat, by, detail) {
const sentence = seat?.refused(by, detail);
return sentence !== undefined ? { lapsed: sentence } : {};
}
export function sandboxRefusalText(toolName, refusal) {
const head = `Error (${toolName.slice(0, 64)}): the command was not run`;
if (refusal.by === "plan")
return `${head}: the run requires an OS sandbox for its commands, and ${refusal.reason.slice(0, 600)}.`;
const tail = refusal.refusedBy === "this_call"
? "The environment cannot keep an entry of this command's sandbox boundary; a command whose boundary it can keep still runs."
: "The environment's sandbox is not working, so no command can run sandboxed here; report it rather than retrying.";
return `${head}: the sandbox could not be enforced for it (${refusal.detail.slice(0, 600)}). ${tail}${refusal.lapsed !== undefined ? ` ${refusal.lapsed.slice(0, 300)}` : ""}`;
}
const VIOLATIONS_SHOWN = 50;
function ignoredViolation(line, command, ignore) {
if (ignore === undefined)
return false;
if ((ignore["*"] ?? []).some((p) => line.includes(p)))
return true;
return Object.entries(ignore).some(([pattern, paths]) => pattern !== "*" && command.includes(pattern) && paths.some((p) => line.includes(p)));
}
export function sandboxResultNote(start, command, record) {
if (!start.ok || start.sandbox === undefined)
return "";
if (record === undefined || record.launch !== "enforced")
return "\n[sandbox: the environment did not confirm it kept this command's sandbox (unverified)]";
const shown = (Array.isArray(record.violations) ? record.violations : []).filter((v) => typeof v?.line === "string" && !ignoredViolation(v.line, command, start.ignoreViolations));
if (shown.length === 0)
return "";
const lines = shown.slice(0, VIOLATIONS_SHOWN).map((v) => foreignLine(v.line, 300));
if (shown.length > VIOLATIONS_SHOWN)
lines.push(`(${shown.length - VIOLATIONS_SHOWN} more not shown)`);
return `\n<sandbox_violations>\n${lines.join("\n")}\n</sandbox_violations>`;
}
const listOf = (v) => (Array.isArray(v) ? v : undefined);
const literalIntersection = (a, b) => b.filter((x) => (a ?? []).includes(x));
const union = (a, b) => [...new Set([...(a ?? []), ...(b ?? [])])];
const NO_MATCH_ORDER = ["warn", "deny", "error"];
const TIGHTEN_BOOLS = { enabled: false, "network.strictAllowlist": false };
const LOOSEN_BOOLS = {
autoAllowBashIfSandboxed: true, allowUnsandboxedCommands: true, "filesystem.disabled": false, enableWeakerNestedSandbox: false, allowNestedUserNamespaces: false,
enableWeakerNetworkIsolation: false, allowAppleEvents: false, "network.allowAllUnixSockets": false, "network.allowLocalBinding": false, "credentials.allowPlaintextInject": false,
};
const DENY_LISTS = ["filesystem.denyWrite", "filesystem.denyRead", "network.deniedDomains"];
const ALLOW_LISTS = ["filesystem.allowWrite", "filesystem.allowRead", "network.allowedDomains", "network.allowUnixSockets", "network.allowMachLookup", "excludedCommands"];
const SIGV4_WORDS = ["credentials.sigv4.streaming", "credentials.sigv4.presigned", "credentials.sigv4.sigv4a"];
const at = (o, path) => path.split(".").reduce((v, k) => (typeof v === "object" && v !== null ? v[k] : undefined), o);
function put(o, path, value) {
const keys = path.split(".");
let cur = o;
for (const k of keys.slice(0, -1)) {
if (typeof cur[k] !== "object" || cur[k] === null)
cur[k] = {};
cur = cur[k];
}
if (value === undefined)
delete cur[keys[keys.length - 1]];
else
cur[keys[keys.length - 1]] = value;
}
export function mergeChildSandbox(parent, childValue) {
const child = receiveTaskSandbox(childValue);
if (parent === undefined)
return child;
if (child === undefined)
return parent;
const p = { ...parent };
const out = structuredClone({ ...parent });
const stated = (path) => at(child, path) !== undefined;
const parentBool = (path, absent) => {
if (path === "failIfUnavailable")
return typeof p["failIfUnavailable"] === "boolean" ? p["failIfUnavailable"] : p["enabled"] === true;
const v = at(p, path);
return typeof v === "boolean" ? v : absent;
};
for (const [path, absent] of Object.entries({ ...TIGHTEN_BOOLS, failIfUnavailable: false }))
if (stated(path))
put(out, path, parentBool(path, absent) || at(child, path) === true);
for (const [path, absent] of Object.entries(LOOSEN_BOOLS))
if (stated(path))
put(out, path, parentBool(path, absent) && at(child, path) === true);
for (const path of DENY_LISTS)
if (stated(path))
put(out, path, union(listOf(at(p, path)), listOf(at(child, path))));
for (const path of ALLOW_LISTS)
if (stated(path))
put(out, path, literalIntersection(listOf(at(p, path)), listOf(at(child, path)) ?? []));
if (stated("ignoreViolations")) {
const pv = (p["ignoreViolations"] ?? {});
const cv = at(child, "ignoreViolations");
const merged = {};
if (typeof cv === "object" && cv !== null)
for (const [pattern, paths] of Object.entries(cv))
if (pv[pattern] !== undefined)
merged[pattern] = literalIntersection(pv[pattern], listOf(paths) ?? []);
out["ignoreViolations"] = merged;
}
for (const path of SIGV4_WORDS)
if (at(child, path) === "deny")
put(out, path, "deny");
for (const [list, key] of [["credentials.files", "path"], ["credentials.envVars", "name"]]) {
if (!stated(list))
continue;
const fold = (members, a, b) => {
const [x, y] = [a["onExtractNoMatch"], b["onExtractNoMatch"]];
const noMatch = x === undefined ? y : y === undefined ? x : NO_MATCH_ORDER.indexOf(String(x)) >= NO_MATCH_ORDER.indexOf(String(y)) ? x : y;
return { ...members, mode: a["mode"] === "deny" || b["mode"] === "deny" ? "deny" : "mask", ...(noMatch !== undefined ? { onExtractNoMatch: noMatch } : {}) };
};
const entries = new Map();
for (const e of listOf(at(p, list)) ?? []) {
if (typeof e !== "object" || e === null)
continue;
const mine = e;
const prior = entries.get(mine[key]);
entries.set(mine[key], prior === undefined ? { ...mine } : fold(mine, prior, mine));
}
for (const e of listOf(at(child, list)) ?? []) {
if (typeof e !== "object" || e === null)
continue;
const mine = e;
const theirs = entries.get(mine[key]);
entries.set(mine[key], theirs === undefined ? { ...mine } : fold(theirs, theirs, mine));
}
put(out, list, [...entries.values()]);
}
return receiveTaskSandbox(out);
}