@sema-agent/core
Version:
Stateless, task-oriented AI agent core
146 lines (145 loc) • 9.27 kB
JavaScript
import { isDeclaredSandboxOffHost, pathsAreHostLocal } from "../remote-env.js";
import { managedTreeAt } from "../git-worktree-env.js";
import { validatePath } from "../effective-path-target.js";
import { installPolicyAnchors, installationAnchorsOf, installedFrom } from "../path-rule-binding.js";
import { CheckpointError } from "../checkpoint-store.js";
export function deploymentCanRerootChild(deps) {
return deps.executionEnvFactory !== undefined;
}
export async function childPlacementOf(env, childRoot, asked, callerRoot, callerCheckout) {
const root = await canonicalOrSelf(env, childRoot);
if (asked !== undefined && (await canonicalOrSelf(env, asked)) === root)
return "honored";
return (await atOrBelow(env, root, callerRoot)) || (callerCheckout !== undefined && (await atOrBelow(env, root, callerCheckout))) ? "caller_tree" : "elsewhere";
}
export async function canonicalOrSelf(env, p) {
try {
const r = await env.canonicalPath(p);
return r.ok ? r.value : p;
}
catch {
return p;
}
}
async function atOrBelow(env, root, dir) {
const tree = await canonicalOrSelf(env, dir);
const sep = tree.includes("\\") && !tree.includes("/") ? "\\" : "/";
return root === tree || root.startsWith(tree.endsWith(sep) ? tree : tree + sep);
}
export async function callerTreeMissed(env, placement, callerRoot, childRoot) {
if (placement === "honored")
return undefined;
const tree = managedTreeAt(await canonicalOrSelf(env, callerRoot))?.root;
if (tree === undefined || isDeclaredSandboxOffHost(env))
return undefined;
return (await atOrBelow(env, await canonicalOrSelf(env, childRoot), tree)) ? undefined : tree;
}
export function factoryIgnoredHint(childRoot, envCwd, tree) {
const where = envCwd === childRoot ? childRoot : `${childRoot} (its environment stands at ${envCwd})`;
return Object.assign(new Error(`The sub-agent was not started (factory_ignored_hint): the execution environment factory placed the child at ${where} while the session's tree is ${tree}, where its caller works — a child outside that tree would read and write the checkout it isolates. The factory must root the child at the parentCwd it is handed; the child is never started outside the tree instead.`), { code: "workspace.isolation_unavailable" });
}
export function callerPlacementSeats(parentCwd, callerRoot) {
const root = callerRoot ?? parentCwd;
return {
...(root !== undefined ? { callerRoot: root } : {}),
...(parentCwd !== undefined && callerRoot !== undefined && parentCwd !== callerRoot ? { callerCheckout: parentCwd } : {}),
};
}
export function childPlacementOnLeg(env, internals, root) {
const asked = internals.isolation === "worktree" ? (pathsAreHostLocal(env) ? root : undefined) : internals.parentCwd;
return childPlacementOf(env, root, asked, internals.callerRoot, internals.callerCheckout);
}
export function worktreeNotHonored(cwd) {
return Object.assign(new Error(`isolation "worktree" was requested but cannot be honored: the execution environment factory placed the sub-agent at "${cwd}", inside the caller's own tree, instead of the worktree it was offered. The sub-agent was not started (fail-closed — no silent fallback to the shared working tree).`), { code: "isolation.unavailable" });
}
const AS_RECORDED = (p) => p;
function recordedAnchors(r, rebase) {
if (r === null || r === undefined)
return undefined;
const read = (v) => {
if (typeof v !== "string")
return undefined;
const p = rebase(v);
return validatePath(p, { intent: "validate-coordinate" });
};
const [root, home] = [read(r.root), read(r.home)];
return { ...(root !== undefined ? { root } : {}), ...(home !== undefined ? { home } : {}) };
}
export function chainTopAnchors(cfg) {
if (cfg.placement === "elsewhere")
return cfg.leg;
return (cfg.live !== undefined ? recordedAnchors(cfg.live, AS_RECORDED) : recordedAnchors(cfg.seed, cfg.rebase)) ?? cfg.leg;
}
const GAP_REASON = { absent: "installation_record_absent", misaligned: "installation_record_misaligned", invalid: "installation_record_invalid" };
function dependsOnInstallation(policy) {
if (installedFrom(policy) !== undefined)
return false;
return typeof policy.pathRules === "function" && policy.pathRules({}).some((row) => row.unanchored !== undefined);
}
function recordedInstallation(installations, chainLength, position, rebase) {
const [record, read] = installations.live !== undefined ? [installations.live, AS_RECORDED] : [installations.seed, rebase];
if (record === undefined)
return "absent";
if (record.length !== chainLength)
return "misaligned";
if (record[position] === null)
return "absent";
const a = recordedAnchors(record[position], read);
return a?.root === undefined ? "invalid" : a;
}
export function chainInstallationGaps(chain, installations, rebase) {
const record = installations.live !== undefined ? "chain" : "checkpoint";
return chain.flatMap((policy, position) => {
if (policy === undefined || !dependsOnInstallation(policy))
return [];
const r = recordedInstallation(installations, chain.length, position, rebase);
return typeof r === "string" ? [{ position, gap: r, record }] : [];
});
}
const GAP_CAUSE = {
absent: {
checkpoint: "the checkpoint records no installation for it — the engine that parked it recorded one only for an entry whose path rules depended on where it was installed at the time (releases before 7.70.0; none before 7.46.0), and the policy now given for it has such a rule",
chain: "the chain was handed without a record of where it was installed",
},
misaligned: { checkpoint: "the checkpoint's installation record does not cover the chain entry for entry", chain: "the handed installation record does not cover the chain entry for entry" },
invalid: { checkpoint: "the checkpoint's installation record names no absolute root for it", chain: "the handed installation record names no absolute root for it" },
};
export function chainInstallationRefusal(gaps, pending) {
const first = gaps[0];
const one = gaps.length === 1;
return new CheckpointError("resume.parent_constraint_mismatch", `the parent-constraint chain carries ${gaps.length} polic${one ? "y" : "ies"} (entry ${gaps.map((g) => g.position).join(", ")}) whose path rules resolve against the leg that installed ${one ? "it" : "them"}, and ${GAP_CAUSE[first.gap][first.record]} — installing ${one ? "it" : "them"} anywhere else could move what ${one ? "it protects" : "they protect"}, so the chain is refused` +
(pending ? " before the claim (the checkpoint stays pending). Expire it and run the work again; a parked delegated agent can be denied instead (it is stopped, nothing runs)." : "."), { reason: GAP_REASON[first.gap] });
}
export function chainPolicyOnLeg(cfg) {
if (cfg.placement !== "elsewhere") {
const gaps = chainInstallationGaps(cfg.chain, cfg.installations, cfg.rebase);
if (gaps.length > 0)
throw chainInstallationRefusal(gaps, false);
}
const recorded = (position) => {
const r = recordedInstallation(cfg.installations, cfg.chain.length, position, cfg.rebase);
return typeof r === "string" ? undefined : r;
};
const site = (position) => (cfg.placement === "elsewhere" || position < 0 ? cfg.leg : (recorded(position) ?? cfg.chainTop));
const chained = (policy, position) => (installedFrom(policy) !== undefined && cfg.placement !== "elsewhere" ? policy : installPolicyAnchors(policy, site(position))) ?? policy;
const ownPosition = (policy) => (cfg.placement === "elsewhere" ? -1 : cfg.chain.findIndex((c) => c !== undefined && (installedFrom(c) ?? c) === (installedFrom(policy) ?? policy)));
const own = (policy) => {
if (policy === undefined)
return undefined;
const position = ownPosition(policy);
return position >= 0 ? chained(cfg.chain[position], position) : installPolicyAnchors(policy, cfg.leg);
};
return { own, chained, siteOf: (policy, position) => (installedFrom(policy) !== undefined && cfg.placement !== "elsewhere" ? undefined : site(position < cfg.chain.length ? position : ownPosition(policy))) };
}
export function installationRecordOf(policy) {
const a = policy !== undefined ? installationAnchorsOf(policy) : undefined;
return a?.root === undefined ? null : { root: a.root, ...(a.home !== undefined ? { home: a.home } : {}) };
}
export function chainAnchorRecords(chainTop, chain, siteOf) {
const records = chain.map((pc, position) => (pc.policy === undefined ? null : (installationRecordOf(pc.policy) ?? anchorsRecord(siteOf(pc.policy, position)))));
return {
...(chainTop.root !== undefined ? { pathRuleAnchors: { root: chainTop.root, ...(chainTop.home !== undefined ? { home: chainTop.home } : {}) } } : {}),
...(records.some((r) => r !== null) ? { pathRuleInstallations: records } : {}),
};
}
const anchorsRecord = (a) => (a?.root === undefined ? null : { root: a.root, ...(a.home !== undefined ? { home: a.home } : {}) });