@sema-agent/core
Version:
Stateless, task-oriented AI agent core
265 lines (264 loc) • 13.1 kB
JavaScript
import { types } from "node:util";
import { receive } from "./mods/kernel/receive.js";
const WORKSPACE_HANDLE_MEMBER_TABLE = { sandboxId: 1, provider: 1, mountPath: 1, snapshotId: 1, sessionToken: 1, restoreMode: 1, deviceId: 1 };
export const WORKSPACE_HANDLE_MEMBERS = Object.keys(WORKSPACE_HANDLE_MEMBER_TABLE);
const FROZEN_COPY_OF = new WeakMap();
export function frozenHandleCopy(handle) {
const known = FROZEN_COPY_OF.get(handle);
if (known !== undefined)
return known;
const copy = {};
for (const member of WORKSPACE_HANDLE_MEMBERS) {
const value = handle[member];
if (typeof value === "string")
copy[member] = value;
}
const frozen = Object.freeze(copy);
if (typeof handle === "object" && handle !== null)
FROZEN_COPY_OF.set(handle, frozen);
return frozen;
}
export function placementTargetOf(handle) {
const provider = handle.provider;
const deviceId = handle.deviceId;
if (typeof provider !== "string" || provider === "")
return undefined;
return Object.freeze(typeof deviceId === "string" ? { provider, deviceId } : { provider });
}
export function reportedPlacementTarget(env) {
if (env === undefined || env === null || !isRemoteExecutionEnv(env))
return undefined;
try {
return placementTargetOf(env.workspaceHandle());
}
catch {
return undefined;
}
}
export function placementHonored(fence, report) {
return fence?.deviceId === undefined || report?.deviceId === fence.deviceId;
}
export const WORKSPACE_SYNC_REASONS = Object.freeze(["turn_end", "destroy"]);
export const REMOTE_EXECUTION_ERROR_CODES = Object.freeze(Object.keys({
suspended: 1, command_in_flight: 1, connect_failed: 1, post_resume_failed: 1, aborted: 1, timeout: 1, liveness_no_output: 1, unsupported: 1, auth_transient: 1, auth_failed: 1,
transport_lost: 1, outcome_unknown: 1, spawn_error: 1, shell_unavailable: 1, target_unavailable: 1, refused: 1, unknown: 1,
}));
const ENV_CODE_SPELLING = /^env\.[a-z][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)*$/;
export function isDeploymentEnvCode(code) {
return typeof code === "string" && ENV_CODE_SPELLING.test(code);
}
export function isStreamFailureWord(code) {
return (typeof code === "string" && REMOTE_EXECUTION_ERROR_CODES.some((w) => w === code)) || isDeploymentEnvCode(code);
}
export const RETRYABLE_REMOTE_ERROR_CODES = [
"auth_transient",
"connect_failed",
"timeout",
"liveness_no_output",
"transport_lost",
];
export function isRetryableRemoteErrorCode(code) {
return RETRYABLE_REMOTE_ERROR_CODES.some((retryable) => retryable === code);
}
export class RemoteExecutionError extends Error {
code;
constructor(code, message, cause) {
super(message, cause === undefined ? undefined : { cause });
this.name = "RemoteExecutionError";
this.code = code;
}
}
export const EXECUTION_ENV_PURPOSES = Object.freeze(["run", "rewind_files", "read_changes"]);
export const ENV_PURPOSE_UNSUPPORTED = "env.purpose_unsupported";
export function hasDestroy(env) {
return typeof env.destroy === "function";
}
export function hasWorkspaceSync(env) {
try {
return typeof env.syncWorkspace === "function";
}
catch {
return false;
}
}
export function hasReleaseToRow(env) {
try {
return typeof env.releaseToRow === "function";
}
catch {
return false;
}
}
export function isRemoteExecutionEnv(env) {
const e = env;
return (typeof e.workspaceHandle === "function" &&
typeof e.execStream === "function" &&
typeof e.suspendVM === "function" &&
typeof e.destroy === "function" &&
capabilityReceiptOf(env).blockIsObject);
}
export function missingRestoreSurface(env) {
const e = env;
const missing = [];
if (typeof e.resumeVM !== "function")
missing.push("resumeVM");
if (typeof e.postResumeInit !== "function")
missing.push("postResumeInit");
return missing;
}
export const UNDECLARED_CAPABILITY_READING = {
isolation: {
reads: false,
so: "no reader treats the environment as a sandbox: autonomy, the policy tiers and the read boundary's containment legs stay on their checking side",
},
suspendable: {
reads: "undeclared",
so: "the snapshot reader takes only a declared `true` and the park-only lane only a declared `false`, so the environment is neither snapshot nor parked, and a run on it cannot suspend durably",
},
sharesProcessTable: {
reads: "undeclared",
so: "whether the commands it runs are processes on this engine's own process table has no default, so the Bash tool refuses every pattern kill that needs the question (`pkill`, `killall`, a `kill` fed by `pgrep`; `pkill -P $$`, the shell's own children, runs) on this environment — declare `true` when its commands run on a table that holds the engine (a host lane, or a PID namespace that contains the engine's), `false` only when they run where the engine is not (another machine, a PID namespace that does not contain it)",
},
canonicalPathAuthoritative: {
reads: true,
so: "its resolver's silence is read as a failure, so a command chain it cannot answer at all is refused at the read boundary's execute-time recheck instead of passing on its written spelling",
},
hostLocalPaths: {
reads: "undeclared",
so: "the engine does not treat a path this environment names as the host's own file, and a worktree child on it is refused (its tree can be neither compared nor exempted)",
},
externalContentTarget: {
reads: "undeclared",
so: "what it produces is treated as content from outside the deployment's trust boundary (the memory session mark), and a call that reaches it owes what reaching the target and what leaving it both owe (the cross-boundary taint)",
},
io: {
reads: "undeclared",
so: "no shell face mounts on it, and what it names is still read through it (the project marker), never past its own read limits",
},
keepsReadFloor: {
reads: false,
so: "it is read as not keeping the byte floor, so a run whose read-deny table is non-empty is refused at prepare when the deployment sets `readDenyFloorRequired`, and otherwise announced as such (`config.read_deny_floor_unkept`) when the caller brought rows of its own",
},
commandSandbox: {
reads: false,
so: "it is read as keeping no command sandbox, so a run that requires one (`TaskSpec.sandbox.enabled`) is refused at prepare, or — under `failIfUnavailable: false` — announced (`config.command_sandbox_unavailable`) and run unsandboxed",
},
};
export const CAPABILITY_KEYS = Object.keys(UNDECLARED_CAPABILITY_READING);
const CAPABILITY_RECEIPT_MODE = Object.freeze({ accessors: "call-once", depth: 2, others: "copy", contain: true, freeze: true, isProxy: (v) => types.isProxy(v) });
const CAPABILITY_KEY_SET = new Set(CAPABILITY_KEYS);
const RECEIVED_CAPABILITIES = new WeakMap();
const typeWord = (v) => (v === null ? "null" : typeof v);
const blockRefused = (valueType, blockIsObject) => Object.freeze({ declared: Object.freeze({}), blockIsObject, findings: Object.freeze([Object.freeze({ key: "capabilities", valueType, expected: "object" })]) });
function receiveCapabilities(env) {
let block;
try {
block = Reflect.get(env, "capabilities");
}
catch {
return blockRefused("unreadable", false);
}
if (block === undefined) {
return Object.freeze({ declared: Object.freeze({}), blockIsObject: false, findings: Object.freeze(CAPABILITY_KEYS.map((key) => Object.freeze({ key, valueType: "undefined", expected: "boolean" }))) });
}
if (typeof block !== "object" || block === null)
return blockRefused(typeWord(block), false);
const received = receive(block, CAPABILITY_RECEIPT_MODE);
if (!received.ok)
return blockRefused("unreadable", true);
const members = received.value;
const unreadable = new Set((received.faults ?? []).map((f) => f.path[0]).filter((k) => k !== undefined));
const declared = {};
const findings = [];
for (const key of CAPABILITY_KEYS) {
const value = members[key];
if (typeof value === "boolean")
declared[key] = value;
else
findings.push(Object.freeze({ key, valueType: unreadable.has(key) ? "unreadable" : typeWord(value), expected: "boolean" }));
}
for (const key of [...Object.keys(members), ...unreadable]) {
if (!CAPABILITY_KEY_SET.has(key) && !findings.some((f) => f.key === key))
findings.push(Object.freeze({ key, valueType: unreadable.has(key) ? "unreadable" : typeWord(members[key]), expected: "absent" }));
}
return Object.freeze({ declared: Object.freeze(declared), blockIsObject: true, findings: Object.freeze(findings) });
}
export function capabilityReceiptOf(env) {
const holder = env;
if ((typeof holder !== "object" && typeof holder !== "function") || holder === null)
return blockRefused(typeWord(holder), false);
const prior = RECEIVED_CAPABILITIES.get(holder);
if (prior !== undefined)
return prior;
const receipt = receiveCapabilities(holder);
RECEIVED_CAPABILITIES.set(holder, receipt);
return receipt;
}
function declaredCapability(env, key) {
return capabilityReceiptOf(env).declared[key];
}
export function declaredSuspend(env) {
return declaredCapability(env, "suspendable") ?? UNDECLARED_CAPABILITY_READING.suspendable.reads;
}
export function isSuspendable(env) {
return declaredSuspend(env) === true && isRemoteExecutionEnv(env) && missingRestoreSurface(env).length === 0;
}
function undeclaredSuspendWord(env) {
const finding = capabilityReceiptOf(env).findings.find((f) => f.key === "suspendable");
if (finding === undefined || finding.valueType === "undefined")
return "it is absent";
if (finding.valueType === "unreadable")
return "it could not be read";
return `its value is of type ${finding.valueType}, not a boolean`;
}
export function suspendTargetGapRowOf(ownedEnv) {
if (ownedEnv === undefined)
return undefined;
if (!isRemoteExecutionEnv(ownedEnv))
return { code: "env_not_remote", clause: "is not a RemoteExecutionEnv (it would be destroyed on suspend, so a resumed file or shell tool would act on a fresh, empty env)" };
const declared = declaredSuspend(ownedEnv);
if (declared === "undeclared")
return { code: "env_suspend_undeclared", clause: `does not declare capabilities.suspendable (${undeclaredSuspendWord(ownedEnv)}), so it is neither snapshot nor parked` };
const restoreGap = declared === true ? missingRestoreSurface(ownedEnv) : [];
return restoreGap.length > 0 ? { code: "env_restore_incomplete", clause: `declares capabilities.suspendable but its adapter does not implement ${restoreGap.join(" or ")}` } : undefined;
}
export function suspendTargetGapOf(ownedEnv) {
return suspendTargetGapRowOf(ownedEnv)?.clause;
}
export function perTaskEnvParkRefusal(gap) {
return `durable suspend is not supported with this per-task executionEnvFactory env: it ${gap}, so no resumable checkpoint can be taken. Use a RemoteExecutionEnv factory that declares capabilities.suspendable — true with the full restore surface, or false if the workspace is externally durable (the park-only lane) — or a static, caller-owned RunnerDeps.executionEnv.`;
}
export function isIsolated(env) {
return declaredCapability(env, "isolation") ?? UNDECLARED_CAPABILITY_READING.isolation.reads;
}
export function boundaryIsTheSandbox(env) {
return isIsolated(env);
}
export function canonicalPathIsAuthoritative(env) {
return declaredCapability(env, "canonicalPathAuthoritative") ?? UNDECLARED_CAPABILITY_READING.canonicalPathAuthoritative.reads;
}
export function processTableOf(env) {
const declared = declaredCapability(env, "sharesProcessTable");
return declared === true ? "this" : declared === false ? "other" : UNDECLARED_CAPABILITY_READING.sharesProcessTable.reads;
}
export function declaredHostLocalPaths(env) {
return declaredCapability(env, "hostLocalPaths") ?? UNDECLARED_CAPABILITY_READING.hostLocalPaths.reads;
}
export function pathsAreHostLocal(env) {
return declaredHostLocalPaths(env) === true;
}
export function isDeclaredSandboxOffHost(env) {
return declaredHostLocalPaths(env) === false && isIsolated(env);
}
export function targetIsExternal(env) {
return declaredCapability(env, "externalContentTarget") ?? UNDECLARED_CAPABILITY_READING.externalContentTarget.reads;
}
export function performsIo(env) {
return declaredCapability(env, "io") ?? UNDECLARED_CAPABILITY_READING.io.reads;
}
export function keepsReadFloor(env) {
return declaredCapability(env, "keepsReadFloor") ?? UNDECLARED_CAPABILITY_READING.keepsReadFloor.reads;
}
export function providesCommandSandbox(env) {
return declaredCapability(env, "commandSandbox") ?? UNDECLARED_CAPABILITY_READING.commandSandbox.reads;
}