@sema-agent/core
Version:
Stateless, task-oriented AI agent core
602 lines (601 loc) • 39 kB
JavaScript
import { emitTrace } from "../trace.js";
import { defaultTaskRegistry } from "../task-registry.js";
import { bashReversibilityProbeIn, activeReadDenyBuiltinTiers, readDenyBuiltinConfigOf, compileReadDeny, createHandsToolkit, deploymentFaceClampNotice, servingModelPdfCapabilities, inheritSessionReadFileState, entriesCarriedAcrossLegs, backgroundOutputReadExemption, resolveContainmentFace, seedReadFileStateFromContext, seedReadFileStateFromTranscript, } from "../../tools/fs/index.js";
import { resolveKey, rootAdmittingArtifactStore, sha256 } from "../../tools/fs/safety.js";
import { dropReadsReadRefuses, requestReleasedRows, structuredReadBuiltinOf } from "../../tools/fs/read-deny.js";
import { thrownText } from "../thrown-value.js";
import { carryReadFace, whereItLeads } from "../../tools/fs/read-deny-home.js";
import { EMPTY_READ_ROOTS, afterCallTables, boundaryRowsOver, denySeatsOf, onNewestRead, onPinnedRead, pathTablesCompile, readRootsOver } from "./person-path-rows.js";
import { inlineUntrusted } from "../untrusted-text.js";
import { createHeadLeads } from "../path-rule-binding.js";
import { bindRetiredReads, createShellOverflowSpoolFence } from "../../tools/fs/fs-shared.js";
import { createShellReadStation } from "../../tools/fs/shell-read-check.js";
import { deploymentReadDenyEntries, judgeReadFloorKept, latchReadFloor, readFloorSeat } from "../../tools/fs/read-floor.js";
import { createFileReadStation, outsideReadDisposition, unjudgedReadsMember } from "../../tools/fs/file-read-check.js";
import { createFileWriteStation } from "../../tools/fs/file-write-check.js";
import { readBlockLeg, readBlockOf } from "./read-block-judge.js";
import { isShellFaceToolName, readTargetToolNames, writeTargetToolNames } from "../tool-registry.js";
import { normalizeFileText } from "../../tools/fs/encoding.js";
import { readStateFromTranscript } from "./session-file-state-replay.js";
import { SeenFileRegistry } from "../existing-target.js";
import { deliverEngineNotice } from "../types.js";
import { toolNameIndex } from "../../internal/llm.js";
import { mountedModelShellOf } from "../model-shell.js";
import { readRootGrantOver } from "./read-root-grant.js";
import { redeemSessionReadRoot } from "../permission-rule-consent.js";
import { legReadCarrier, readSeatLeaf, sessionLogWhole } from "./session-read-file-states.js";
import { rebaseWorkspacePath } from "./workspace-path.js";
import { RosterBuilder, survivorsByName } from "../tool-roster.js";
import { handsReadOnlyCarried, unionAddOnly } from "../child-clamp-seats.js";
import { assertStringArraySeat, screenReadDenySeat } from "../read-face-seats.js";
import { modePolicyOf } from "../mode-policy.js";
import { valveLeaves } from "../../agents/tool-filter.js";
import { writeAskRowsCountNow } from "../ask-origin.js";
const faceClampAnnouncedSinks = { read_only_mount: { read: new WeakSet(), write: new WeakSet() }, read_block: { read: new WeakSet(), write: new WeakSet() } };
const faceClampConsoleAnnounced = { read_only_mount: { read: false, write: false }, read_block: { read: false, write: false } };
function announceDeploymentFaceClamp(kind, cause, sink) {
if (typeof sink === "function") {
if (faceClampAnnouncedSinks[cause][kind].has(sink))
return;
faceClampAnnouncedSinks[cause][kind].add(sink);
}
else {
if (faceClampConsoleAnnounced[cause][kind])
return;
faceClampConsoleAnnounced[cause][kind] = true;
}
deliverEngineNotice(sink, deploymentFaceClampNotice(kind, cause));
}
export function __resetReadFaceClampAnnouncement() {
faceClampConsoleAnnounced.read_only_mount = { read: false, write: false };
faceClampConsoleAnnounced.read_block = { read: false, write: false };
}
function writeFaceReader(input, onDeploymentClamp) {
const { spec, deps, resume, fullShellReachable, permissionMode } = input;
const seats = { kind: "write", readOnlyMount: spec.handsReadOnly === true, orgGoverned: deps.permissionRuleStore?.partitions.org === true, fullShellReachable };
resolveContainmentFace({ ...seats, specFace: spec.writeFace, depsFace: deps.writeFace, ...(onDeploymentClamp !== undefined ? { onDeploymentClamp } : {}) });
const recorded = resume === undefined ? "live" : resume.seed.writeFace?.face;
const folded = (word) => (recorded === "roots" ? "roots" : word === "open" && recorded !== "open" && recorded !== "live" ? undefined : word);
const faceUnder = (modeFace) => resolveContainmentFace({ ...seats, specFace: folded(spec.writeFace), depsFace: folded(deps.writeFace), ...(modeFace !== undefined ? { modeFace } : {}) });
const under = (mode) => faceUnder(modePolicyOf(mode).writeFace);
return { inForce: () => under(permissionMode.current), under, fenced: faceUnder("open") === "roots" };
}
function carriedFacesOf(input, readBlock) {
const { spec, deps, resume, fullShellReachable } = input;
if (spec.ownHandsReadOnly !== true)
return undefined;
const handed = { ...spec, handsReadOnly: handsReadOnlyCarried(spec) };
const live = resolveContainmentFace({ kind: "read", specFace: spec.readFace, depsFace: deps.readFace, readOnlyMount: handed.handsReadOnly === true, readBlock, orgGoverned: deps.permissionRuleStore?.partitions.org === true, fullShellReachable });
const writeSeatOpen = resolveContainmentFace({ kind: "write", specFace: spec.writeFace, depsFace: deps.writeFace, readOnlyMount: false, orgGoverned: deps.permissionRuleStore?.partitions.org === true, fullShellReachable }) === "open";
return { read: resume !== undefined && (resume.seed.readFace === undefined || resume.seed.readFace.face === "roots") ? "roots" : live, write: resume?.seed.writeFace?.face === "open" && !writeSeatOpen ? writeFaceReader(input) : writeFaceReader({ ...input, spec: handed }), writeSeatOpen };
}
const FLOOR_NEVER_UNKEPT = Object.freeze({ current: false, judged: false });
export function resolveHandsLessReadFace(input) {
const { resume, fullShellReachable, spec, deps } = input;
assertStringArraySeat(deps.readDenyPatterns, "RunnerDeps.readDenyPatterns", "compiler-owned");
const readBlock = readBlockOf(input);
let handsLessResolvedFace;
let handsLessResolvedWriteFace;
let readDenyAdditionsNormalized = [];
let readDenyBuiltinTiersActive = [];
{
const liveFace = resolveContainmentFace({
kind: "read",
specFace: spec.readFace,
depsFace: deps.readFace,
readOnlyMount: spec.handsReadOnly === true,
readBlock,
orgGoverned: deps.permissionRuleStore?.partitions.org === true,
fullShellReachable,
});
const seed = resume?.seed.readFace;
handsLessResolvedFace = resume !== undefined && (seed === undefined || seed.face === "roots") ? "roots" : liveFace;
handsLessResolvedWriteFace = writeFaceReader(input);
const denyAdditions = unionAddOnly("readDenyPatterns", deps.readDenyPatterns, spec.readDenyPatterns, seed?.denyEntries);
readDenyBuiltinTiersActive = activeReadDenyBuiltinTiers(readDenyBuiltinConfigOf({ tiers: deps.readDenyBuiltinTiers, exclude: deps.readDenyBuiltinExclude }));
if (denyAdditions.length > 0) {
readDenyAdditionsNormalized = compileReadDeny(denyAdditions, "readDenyPatterns", { tiers: [] }).entries;
}
}
return {
readFileStateForCheckpoint: undefined,
seedContextFiles: undefined,
seededCopies: new Map(),
seenFiles: new Set(),
handsCwdRef: undefined,
workspaceStateSettle: undefined,
wsSnapshot: undefined,
rebaseWsPath: (p) => p,
backgroundTaskToolsActive: false,
shellReadCheck: unjudgedReadsMember((name) => input.judgedReadsSeat?.ported?.has(name) === true).check,
judgedReadsOf: undefined,
shellReadStationArmed: false,
shellReadAdmission: undefined,
runReadFloor: undefined,
shellReadLandings: undefined,
readAdmission: undefined,
readBlock,
readBlockJudge: undefined,
outsideReadRemedy: undefined,
resolvedReadFace: undefined,
resolvedWriteFace: undefined,
readDenyAdditionsNormalized,
readDenyBuiltinTiersActive,
readFloorUnkept: FLOOR_NEVER_UNKEPT,
handsLessResolvedFace,
handsLessResolvedWriteFace,
carriedFaces: carriedFacesOf(input, readBlock),
additionalRootsCanonical: [],
commandWriteRootsCanonical: [],
declaredAdditionalRoots: [],
additionalReadRootsCanonical: [],
grantReadRoot: undefined,
artifactStoreRef: undefined,
attachmentRootCanonical: undefined,
readDenyMatcher: undefined,
readRoots: EMPTY_READ_ROOTS,
pathTables: undefined,
envHandToolNames: input.roster.mounts.envHands,
shellGatedTools: new Set(),
sealReadStateSeat: undefined,
};
}
export async function prepareHandsMount(input) {
const { handsEnabled, executionEnv, taskRootCanonical, rebaseRestoredPath, resume, session, sessionId, ruleSessionId, hostTaskId, taskScope, fullShellReachable, effectiveShellGate, toolFaceSnapshot, model, spec, deps, internals, memoryWriteGate, advertisedWritableDirs, firstPartyOffload, roster, egressTools, irreversibilityTier, irreversibleTools, reversibilityProbes } = input;
assertStringArraySeat(spec.additionalDirectories, "TaskSpec.additionalDirectories", "strings");
assertStringArraySeat(spec.additionalReadDirectories, "TaskSpec.additionalReadDirectories", "strings");
const readBlock = readBlockOf(input);
const { outsideReadRemedy, grantsReadRootMidRun, personDirectories } = readBlockLeg(readBlock);
assertStringArraySeat(deps.readDenyPatterns, "RunnerDeps.readDenyPatterns", "compiler-owned");
let readFileStateForCheckpoint;
let sealReadStateSeat;
let seedContextFiles;
const seededCopies = new Map();
const seenFiles = new SeenFileRegistry();
let handsCwdRef;
let workspaceStateSettle;
let wsSnapshot;
let rebaseWsPath = (p) => p;
let backgroundTaskToolsActive = false;
let shellReadStation;
let runReadFloor;
let shellReadTools = new Set();
let fileReadStation;
let fileToolAdmission;
let readBlockJudge;
let fileWriteStation;
let resolvedReadFace;
let resolvedWriteFace;
let readDenyAdditionsNormalized = [];
let readDenyBuiltinTiersActive = [];
const readFloorUnkept = { current: false, judged: false };
let handsLessResolvedFace;
const handsLessResolvedWriteFace = undefined;
const shellGatedTools = new Set();
const additionalRootsCanonical = [];
const commandWriteRootsCanonical = [];
const declaredAdditionalRoots = [];
const additionalReadRootsCanonical = [];
let grantReadRoot;
const artifactStoreRef = { current: undefined };
let attachmentRootCanonical;
let readDenyMatcher;
let pathTables;
let readRoots = EMPTY_READ_ROOTS;
if (handsEnabled) {
const rootCanonical = taskRootCanonical;
attachmentRootCanonical = rootCanonical;
const canonicalizeExtraDirs = async (dirs, field, sink, declared) => {
for (const dir of dirs ?? []) {
if (!dir || !dir.trim())
continue;
const c = await (advertisedWritableDirs?.canonicalizeDeclaredRoot(dir) ?? executionEnv.canonicalPath(dir));
if (c.ok) {
sink.push(c.value);
declared?.push(Object.freeze({ directory: dir, canonical: c.value }));
}
else {
deps.onError?.(new Error(`${field} entry skipped (cannot canonicalize): ${dir}`), {
phase: "config",
sessionId,
});
emitTrace(deps.tracer, () => ({
kind: "config.additional_directory_skipped",
version: 1,
taskId: hostTaskId,
entry: dir,
...(field !== "additionalDirectories" ? { field } : {}),
reason: `${c.error.code}: ${c.error.message}`,
ts: Date.now(),
}));
}
}
};
await canonicalizeExtraDirs(spec.additionalDirectories, "additionalDirectories", additionalRootsCanonical, declaredAdditionalRoots);
await canonicalizeExtraDirs(spec.additionalReadDirectories, "additionalReadDirectories", additionalReadRootsCanonical);
if (advertisedWritableDirs !== undefined) {
if (spec.envFacts?.scratchpadDir)
await advertisedWritableDirs.admit({ path: spec.envFacts.scratchpadDir, advertiser: "scratchpad", materializeMarker: ".sema-scratchpad" });
if (spec.planFile !== undefined)
await advertisedWritableDirs.admitPlanFile(spec.planFile);
additionalRootsCanonical.push(...advertisedWritableDirs.roots);
}
commandWriteRootsCanonical.push(...declaredAdditionalRoots.map((d) => d.canonical), ...(advertisedWritableDirs?.commandRoots ?? []));
for (const a of [additionalRootsCanonical, additionalReadRootsCanonical, commandWriteRootsCanonical])
a.splice(0, a.length, ...new Set(a));
const ruleStore = deps.permissionRuleStore;
const personRows = input.personRows;
const sessionGrant = ruleStore !== undefined
? {
kept: () => personRows.sessionRowOwner() !== undefined,
write: (dir, card, signal) => redeemSessionReadRoot({
signal,
sessionRowOwner: () => personRows.sessionRowOwner(),
sessionId: ruleSessionId,
dir,
toolCallId: card.toolCallId,
...(card.boundInputHash !== undefined ? { boundInputHash: card.boundInputHash } : {}),
deniesDirectoryRead: (d) => readDenyMatcher === undefined || readDenyMatcher.matchPath(d) !== null,
deps: { provider: ruleStore },
}),
}
: undefined;
grantReadRoot = !grantsReadRootMidRun ? undefined : readRootGrantOver({ env: executionEnv, writeRoots: additionalRootsCanonical, readRoots: additionalReadRootsCanonical, artifactStore: artifactStoreRef, ...(sessionGrant !== undefined ? { session: sessionGrant } : {}) });
const readFileState = new Map(entriesCarriedAcrossLegs(resume?.seed.readFileState ?? []).map(([k, v]) => [rebaseRestoredPath(k), v]));
readFileStateForCheckpoint = readFileState;
bindRetiredReads(readFileState, seenFiles);
seedContextFiles = async (files) => {
for (const f of files) {
const rk = await readRoots.ready().then(() => resolveKey(executionEnv, rootCanonical, f.path, undefined, undefined, readRoots(), undefined, undefined, resolvedReadFace));
if (rk.ok)
seenFiles.add(rk.key);
if (rk.ok && f.content !== undefined)
seededCopies.set(rk.key, seedReadFileStateFromContext(readFileState, rk.key, f.content));
}
};
const handsIncludeShell = roster.mounts.holds("bash") || roster.mounts.holds("bash-readonly");
const handsReadOnly = !roster.mounts.holds("edit");
backgroundTaskToolsActive = roster.mounts.holds("monitor");
const shellFaceHere = roster.mounts.holding((e) => isShellFaceToolName(e.name));
const checkpointTracked = resume?.seed.handsCwd !== undefined;
const tracksCwd = (handsIncludeShell && !handsReadOnly) || roster.mounts.holds("enter-worktree");
wsSnapshot = checkpointTracked || !tracksCwd ? undefined : await session.getWorkspaceState().catch(() => undefined);
rebaseWsPath = (p) => (wsSnapshot === undefined || wsSnapshot.taskRoot === rootCanonical ? p : rebaseWorkspacePath(p, wsSnapshot.taskRoot, rootCanonical));
if (tracksCwd) {
handsCwdRef = { current: rootCanonical };
if (resume?.seed.handsCwd !== undefined)
handsCwdRef.current = rebaseRestoredPath(resume.seed.handsCwd);
else if (wsSnapshot?.handsCwd !== undefined)
handsCwdRef.current = rebaseWsPath(wsSnapshot.handsCwd);
workspaceStateSettle = {
rootCanonical,
restoredHandsCwd: handsCwdRef.current !== rootCanonical ? handsCwdRef.current : undefined,
...(resume !== undefined && wsSnapshot === undefined ? { baselineUnknown: true } : {}),
};
}
const seedReadFaceSection = resume?.seed.readFace;
const readDenyAdditions = unionAddOnly("readDenyPatterns", deps.readDenyPatterns, spec.readDenyPatterns, seedReadFaceSection?.denyEntries);
const readDenyBuiltinCfg = readDenyBuiltinConfigOf({ tiers: deps.readDenyBuiltinTiers, exclude: deps.readDenyBuiltinExclude });
const canonicalize = async (dirs) => { const out = []; for (const d of dirs)
await canonicalizeExtraDirs([d], "persistedReadRule", out).catch((err) => deps.onError?.(new Error(`persistedReadRule entry skipped (its lookup threw): ${d}: ${thrownText(err)}`), { phase: "config", sessionId })); return out; };
const floorRequired = screenReadDenySeat("readDenyFloorRequired", deps.readDenyFloorRequired) === true;
const builtinStructuredRead = structuredReadBuiltinOf(readDenyBuiltinCfg, requestReleasedRows(deps.readDenyBuiltinRequestExcludable, spec.readDenyBuiltinExclude));
const compileRunTables = pathTablesCompile({ env: executionEnv, additions: readDenyAdditions, builtin: readDenyBuiltinCfg, builtinStructuredRead, legRows: input.denyRuleRows, legReadAskRows: input.readAskRuleRows, legWriteAskRows: input.writeAskRuleRows, leads: input.headLeads, writeAskLeads: createHeadLeads((part) => whereItLeads(executionEnv, part), { unansweredRejects: true }), configRoots: input.callerPlaces.configRoots.dirs, callerHomes: input.callerPlaces.homes.dirs, workspaceRoot: rootCanonical, canonicalize });
let lastCompiled, deploymentRows;
const judgedRunTables = async (person) => {
const compiled = await compileRunTables(person);
readFloorUnkept.current = latchReadFloor(readFloorUnkept.current, judgeReadFloorKept({ env: executionEnv, table: compiled.readDeny, floor: readFloorSeat(compiled.readDeny)?.(undefined), required: floorRequired, deployment: (deploymentRows ??= deploymentReadDenyEntries(deps.readDenyPatterns, readDenyBuiltinCfg)), onNotice: deps.onNotice, attribution: { sessionId, runId: input.runId }, told: input.told }));
readFloorUnkept.judged = true;
return (lastCompiled = compiled);
};
const tables = (pathTables = await input.personRows.attachTables(judgedRunTables));
readDenyMatcher = tables.readDeny;
runReadFloor = readFloorSeat(tables.readDeny);
readRoots = readRootsOver({ own: () => [...(input.writeLocation() === rootCanonical ? [] : [input.writeLocation()]), ...additionalRootsCanonical, ...additionalReadRootsCanonical], tables, ready: input.personRows.tablesReady, store: () => artifactStoreRef.current, personDirectories,
onHeld: (entry, store) => emitTrace(deps.tracer, () => ({ kind: "config.additional_directory_skipped", version: 1, taskId: hostTaskId, entry, field: "persistedReadRule", reason: `admits_artifact_store: the local artifact store ${store} lies inside it or it inside the store — the Artifact tool's ledger and stored files stay outside every root the file tools reach`, ts: Date.now() })) });
readDenyBuiltinTiersActive = activeReadDenyBuiltinTiers(readDenyBuiltinCfg);
readDenyAdditionsNormalized = compileReadDeny(readDenyAdditions, "readDenyPatterns", { tiers: [] }).entries;
let liveReadFace = resolveContainmentFace({
kind: "read",
specFace: spec.readFace,
depsFace: deps.readFace,
readOnlyMount: handsReadOnly,
readBlock,
orgGoverned: deps.permissionRuleStore?.partitions.org === true,
fullShellReachable,
onDeploymentClamp: (cause) => announceDeploymentFaceClamp("read", cause, deps.onNotice),
});
if (resume !== undefined && (seedReadFaceSection === undefined || seedReadFaceSection.face === "roots"))
liveReadFace = "roots";
resolvedReadFace = liveReadFace;
resolvedWriteFace = writeFaceReader(input, (cause) => announceDeploymentFaceClamp("write", cause, deps.onNotice));
const sessionSeats = input.internals?.sessionReadStates;
const seatLeafId = await readSeatLeaf(session);
const judgeKey = async (path) => {
const rk = await readRoots.ready().then(() => resolveKey(executionEnv, rootCanonical, path, undefined, undefined, readRoots(), undefined, undefined, liveReadFace));
return rk.ok ? rk.key : undefined;
};
for (const [k, v] of resume?.seed.readFileState ?? [])
if (v.seededFromContext === true)
seenFiles.add((await judgeKey(rebaseRestoredPath(k))) ?? rebaseRestoredPath(k));
const carrier = await legReadCarrier({ resuming: resume !== undefined, spec, sessionId, seats: sessionSeats, leaf: async () => seatLeafId, getEntry: (id) => session.getEntry(id) });
if (carrier.from === "seat") {
await inheritSessionReadFileState(readFileState, carrier.state, judgeKey, seenFiles);
if (carrier.seen !== undefined)
seenFiles.inherit(carrier.seen);
}
else if (carrier.from === "transcript" || carrier.from === "checkpoint") {
const prior = await session.buildContext().catch(() => undefined);
const rebuilt = readStateFromTranscript(prior?.messages ?? []);
if (prior === undefined || rebuilt.unentered.unplaced || !sessionLogWhole(session))
seenFiles.markAll();
for (const path of [...rebuilt.unentered.paths, ...(carrier.from === "checkpoint" ? rebuilt.records.map((r) => r.path) : [])]) {
const rk = await judgeKey(rebaseRestoredPath(path));
if (rk === undefined)
seenFiles.markAll();
else
seenFiles.add(rk);
}
for (const rec of carrier.from === "transcript" ? rebuilt.records : []) {
const rk = await judgeKey(rec.path);
if (rk === undefined) {
seenFiles.markAll();
continue;
}
if ("content" in rec)
seedReadFileStateFromTranscript(readFileState, rk, rec.content, rec.at, rec.transmittedByToolCallId);
else
readFileState.set(rk, { ...rec.observation, lastReadAt: rec.at });
}
}
const restoredOwed = sessionSeats?.pendingRestored(sessionId) ?? [];
for (const abs of restoredOwed) {
const k = await judgeKey(abs);
if (k === undefined)
continue;
const entry = readFileState.get(k);
if (entry === undefined)
continue;
const cur = await executionEnv.readTextFile(k);
if (cur.ok && entry.hash === sha256(normalizeFileText(cur.value)))
continue;
readFileState.delete(k);
seenFiles.add(k);
}
if (lastCompiled !== undefined)
dropReadsReadRefuses(readFileState, seenFiles, lastCompiled.structuredReadDeny ?? lastCompiled.readDeny);
if (seatLeafId !== undefined) {
sessionSeats?.adopt(sessionId, readFileState, seatLeafId, seenFiles);
sessionSeats?.settleRestored(sessionId, restoredOwed);
}
sealReadStateSeat =
sessionSeats !== undefined && seatLeafId !== undefined
? (ownCommittedTailEntryId) => {
if (ownCommittedTailEntryId !== undefined)
sessionSeats.reanchor(sessionId, readFileState, ownCommittedTailEntryId);
}
: undefined;
const boundaryRows = boundaryRowsOver(input.personRows, personDirectories);
const unanchoredWriteAskSaid = new Set();
const writeAskUncounted = new Set();
const writeAskSeatOf = (t, mode, toolCallId) => {
if (toolCallId !== undefined)
writeAskUncounted.delete(toolCallId);
if (t.writeAskRows === undefined && t.writeAskUnanchored === undefined)
return {};
if (!writeAskRowsCountNow(mode)) {
if (toolCallId !== undefined && t.writeAskRows !== undefined)
writeAskUncounted.add(toolCallId);
return {};
}
for (const u of t.writeAskUnanchored ?? []) {
if (unanchoredWriteAskSaid.has(u.rule))
continue;
unanchoredWriteAskSaid.add(u.rule);
emitTrace(deps.tracer, () => ({ kind: "permission.rule_store_unreadable", version: 1, taskId: hostTaskId, message: `the ask rule ${inlineUntrusted(u.rule, 200)} needs a ${u.needs.join(" / ")} base this task does not declare — under bypassPermissions the shell's file commands do not ask it on this leg (the Edit tool's own check still does)`, ts: Date.now() }));
}
return t.writeAskRows !== undefined && t.writeAskRowsLed !== undefined ? { writeAskRows: t.writeAskRows, writeAskRowsLed: t.writeAskRowsLed } : {};
};
const shellReadBoundary = (toolCallId) => {
const callTables = tables.forCall(toolCallId);
const { read: denySeat, write: writeDenySeat } = denySeatsOf(callTables);
const mode = resolvedWriteFace !== undefined ? input.permissionMode.current : undefined;
return {
...((rows) => (rows !== undefined ? { readRuleRows: rows } : {}))(boundaryRows(callTables, toolCallId)),
...writeAskSeatOf(callTables, mode, toolCallId),
roots: [rootCanonical, ...readRoots.forCall(toolCallId)()],
...(handsCwdRef?.current !== undefined ? { cwd: handsCwdRef.current } : {}),
...(executionEnv.homeDir !== undefined ? { homeDir: executionEnv.homeDir } : {}),
...denySeat,
...writeDenySeat,
...(input.personRows.unreadFor(toolCallId) ? { unreadPartitions: true } : {}),
writeRoots: [input.writeLocation(), ...commandWriteRootsCanonical],
...(resolvedWriteFace !== undefined && mode !== undefined ? { writeFace: resolvedWriteFace.under(mode) } : {}),
...((judge) => (judge !== undefined ? { writeTargetJudge: judge } : {}))(input.writeTargetJudge?.()),
...(resolvedReadFace !== undefined ? { face: resolvedReadFace } : {}),
};
};
if (handsIncludeShell) {
const spoolFence = handsReadOnly ? createShellOverflowSpoolFence(executionEnv) : undefined;
const readonlyBoundary = (toolCallId) => {
if (spoolFence === undefined)
return undefined;
const callTables = tables.forCall(toolCallId);
const { read: denySeat, write: writeDenySeat } = denySeatsOf(callTables);
const readRuleRows = boundaryRows(callTables, toolCallId);
return { roots: [rootCanonical, ...readRoots.forCall(toolCallId)()], cwd: rootCanonical, ...denySeat, ...writeDenySeat, ...(readRuleRows !== undefined ? { readRuleRows } : {}), ...(input.personRows.unreadFor(toolCallId) ? { unreadPartitions: true } : {}), alsoInside: spoolFence };
};
shellReadTools = new Set(shellFaceHere);
shellReadStation = createShellReadStation({
env: executionEnv,
tools: shellReadTools,
seatOf: () => (handsReadOnly ? "readonly" : "full_shell"),
boundaryOf: (_tool, _cwd, toolCallId) => readonlyBoundary(toolCallId) ?? shellReadBoundary(toolCallId), rootsCanonical: true,
homeViews: tables.readDeny.homeViews,
onAdmissionRefused: (toolCallId, echoed) => void input.toolOccurrences.refuse(toolCallId, "read_boundary", echoed !== undefined ? { echoed } : undefined),
...(!grantsReadRootMidRun ? { offersReadRootGrant: false } : {}),
writeAskRowsUncounted: (toolCallId) => writeAskUncounted.has(toolCallId),
});
}
const outsideReads = outsideReadDisposition({ readOnlyMount: handsReadOnly, readBlock });
const bgOutputExempt = backgroundOutputReadExemption(defaultTaskRegistry, { taskOwner: hostTaskId, taskScope, ...(sessionId !== undefined ? { sessionId } : {}), occupant: input.legOccupant }, executionEnv);
fileReadStation = createFileReadStation({
outsideReads,
env: executionEnv,
rootCanonical,
roots: readRoots,
readDeny: tables.readDeny,
...(liveReadFace !== undefined ? { readFace: liveReadFace } : {}),
...("homeDir" in executionEnv && executionEnv.homeDir !== undefined ? { homeDir: executionEnv.homeDir } : {}),
tools: outsideReads === "tool_fence" ? new Set() : readTargetToolNames(),
excluded: (key) => artifactStoreRef.current !== undefined && rootAdmittingArtifactStore(artifactStoreRef.current, [key]) !== undefined,
exempt: (key) => bgOutputExempt?.(key) === true,
});
if (outsideReads === "refusal")
readBlockJudge = onNewestRead(input.personRows, fileReadStation);
if (outsideReads !== "tool_fence")
fileToolAdmission = fileReadStation.admitted;
const writeContainmentSeat = {};
const valveLeft = valveLeaves(toolFaceSnapshot.selector);
const band = createHandsToolkit(executionEnv, readFileState, rootCanonical, {
...(additionalRootsCanonical.length > 0 ? { additionalRoots: additionalRootsCanonical } : {}),
writeRoot: input.writeLocation,
readDenyHomes: carryReadFace([], { readDeny: tables.readDeny, ...(builtinStructuredRead !== undefined ? { structuredReadDeny: tables.structuredReadDeny } : {}), writeDeny: tables.writeDeny, readRoots, ...(outsideReadRemedy !== undefined ? { outsideReadRemedy } : {}) }),
readFace: liveReadFace,
writeFaceLive: resolvedWriteFace.inForce,
reminderMark: input.reminderMark,
reminderDisclosureCounts: input.reminderDisclosureCounts,
...(input.modelFileReaderSeat !== undefined ? { modelFileReaderSeat: input.modelFileReaderSeat } : {}),
...(input.readFirstWaiver !== undefined ? { readFirstWaiver: input.readFirstWaiver } : {}),
writeContainmentSeat,
...(input.contextRoom !== undefined ? { contextRoom: input.contextRoom } : {}),
...(input.trackFileEdit !== undefined ? { trackFileEdit: input.trackFileEdit } : {}),
...(input.onFileEdited !== undefined ? { onFileEdited: input.onFileEdited } : {}),
...(input.offloadStore !== undefined ? { toolResultBytes: input.offloadStore } : {}),
modelShell: handsIncludeShell ? mountedModelShellOf(input.modelShell, handsReadOnly ? "createBashReadonlyTool" : "createBashTool") : undefined,
readOnly: handsReadOnly,
...(shellReadStation !== undefined ? { shellReadAdmission: shellReadStation.admit } : {}),
...(input.commandSandbox !== undefined ? { commandSandbox: input.commandSandbox } : {}),
...(fileToolAdmission !== undefined ? { readAdmission: fileToolAdmission } : {}),
...(handsCwdRef ? { cwdRef: handsCwdRef } : {}),
taskRegistry: defaultTaskRegistry,
taskOwner: hostTaskId,
taskScope,
oneShot: spec.oneShot,
...(sessionId !== undefined ? { sessionId } : {}),
occupant: input.legOccupant,
retainBackgroundProcesses: spec.retainBackgroundProcesses === true,
...(internals?.onTaskNotification !== undefined ? { taskNotification: internals.onTaskNotification } : {}),
...(internals?.detachHub !== undefined ? { detachHub: internals.detachHub } : {}),
onToolProgress: (body) => input.toolProgressRef.current?.emit(body), onEnvRefusal: (failure) => input.envRefusal.note(failure),
queuedHumanInput: () => input.harnessRef.current?.hasPendingUserInput() === true,
...(input.delegation.isDelegatedChild ? {} : { turnCutMovesCommandAside: (signal) => input.harnessRef.current?.cutMovesArmedCommandAside(signal) === true }),
...(deps.onNotice !== undefined ? { onNotice: deps.onNotice } : {}),
pdfModelCapabilities: servingModelPdfCapabilities(() => input.harnessRef.current?.getModel() ?? model),
...(deps.hands?.bashReadonlyAllow !== undefined ? { bashReadonlyAllow: deps.hands.bashReadonlyAllow } : {}),
...(deps.hands?.commitCoAuthor !== undefined ? { commitCoAuthor: deps.hands.commitCoAuthor } : {}),
...(deps.imageProcessor !== undefined ? { imageProcessor: deps.imageProcessor } : {}),
...(deps.hands?.autoBackgroundOnTimeout !== undefined ? { autoBackgroundOnTimeout: deps.hands.autoBackgroundOnTimeout } : {}),
beforeWrite: async (w) => {
const deploymentGate = deps.hands?.beforeWrite;
if (deploymentGate) {
const verdict = await deploymentGate(w);
if (verdict !== undefined && verdict.ok === false)
return verdict;
}
return memoryWriteGate?.(w);
},
mountBackgroundTaskTools: false,
monitorToolActive: backgroundTaskToolsActive && valveLeft({ name: "Monitor" }),
});
if (writeContainmentSeat.current !== undefined)
fileWriteStation = createFileWriteStation({ tools: writeTargetToolNames(), contain: writeContainmentSeat.current });
{
const callerLeft = (spec.tools ?? []).filter((t) => valveLeft(t));
const bandLeft = band.filter((t) => valveLeft(t));
const bandTools = new Set(bandLeft);
const serves = toolNameIndex([...survivorsByName([...callerLeft, ...bandLeft]).values()]);
const lostTo = (name, tool) => {
const holder = serves(name);
return holder !== undefined && holder !== tool && bandTools.has(holder) ? holder : undefined;
};
const collisions = [];
for (const t of callerLeft) {
const replacedBy = lostTo(t.name, t);
if (replacedBy !== undefined) {
collisions.push(`"${t.name}" is replaced by the built-in "${replacedBy.name}", which serves that name (the caller tool never dispatches)`);
continue;
}
const aliases = (t.aliases ?? []).flatMap((a) => {
const holder = lostTo(a, t);
return holder === undefined ? [] : [`"${a}" serves the built-in "${holder.name}"`];
});
if (aliases.length > 0)
collisions.push(`"${t.name}" stays mounted under its own name, but its ${aliases.length > 1 ? "aliases" : "alias"} ${aliases.join(" and ")}`);
}
if (collisions.length > 0) {
deps.onError?.(new Error(`spec.tools ${collisions.length > 1 ? "entries collide" : "entry collides"} with the built-in hands tool band — the built-in wins each contested name: ${collisions.join("; ")}. Rename the colliding name, or don't inject executionEnv if you intend to replace the band.`), { phase: "config", sessionId });
}
}
roster.mounts.know({ "seat.offloadBytes": input.offloadStore?.bytesOf !== undefined });
roster.mountAll(band.filter((t) => roster.mounts.judgeTool(t)).map((t) => firstPartyOffload(afterCallTables(input.personRows, t))), { source: "builtin", mountedBy: "hands" });
const shellFloor = effectiveShellGate;
if (handsIncludeShell && spec.handsReadOnly !== true) {
const installShellSeat = (name) => {
const tierBefore = irreversibilityTier.get(name);
const seatOwned = !egressTools.has(name) && tierBefore !== "always" && tierBefore !== "maybe";
const tier = shellFloor === "always" || tierBefore === "always" ? "always" : "maybe";
irreversibilityTier.set(name, tier);
irreversibleTools.add(name);
if (seatOwned && tier === "maybe")
reversibilityProbes.set(name, bashReversibilityProbeIn(mountedModelShellOf(input.modelShell, "bashReversibilityProbe").shell, undefined, shellReadBoundary));
if (seatOwned)
shellGatedTools.add(name);
};
for (const name of shellFaceHere)
installShellSeat(name);
}
}
return {
readFileStateForCheckpoint,
seedContextFiles,
seededCopies,
seenFiles,
handsCwdRef,
workspaceStateSettle,
wsSnapshot,
rebaseWsPath,
backgroundTaskToolsActive,
shellReadCheck: onPinnedRead(input.personRows, [...(shellReadStation !== undefined ? [{ check: shellReadStation.check, tools: shellReadTools }] : []), ...(fileReadStation !== undefined ? [fileReadStation] : []), ...(fileWriteStation !== undefined ? [fileWriteStation] : [])]),
judgedReadsOf: fileReadStation?.judgedReadsOf,
shellReadStationArmed: shellReadStation !== undefined,
shellReadAdmission: shellReadStation?.admit,
runReadFloor,
shellReadLandings: shellReadStation?.landings,
readAdmission: fileToolAdmission,
readBlock,
readBlockJudge,
outsideReadRemedy,
resolvedReadFace,
resolvedWriteFace,
handsLessResolvedWriteFace,
carriedFaces: carriedFacesOf(input, readBlock),
readDenyAdditionsNormalized,
readDenyBuiltinTiersActive,
readFloorUnkept,
handsLessResolvedFace,
additionalRootsCanonical,
commandWriteRootsCanonical,
declaredAdditionalRoots,
additionalReadRootsCanonical,
grantReadRoot,
artifactStoreRef,
attachmentRootCanonical,
readDenyMatcher,
readRoots,
pathTables,
envHandToolNames: roster.mounts.envHands,
shellGatedTools,
sealReadStateSeat,
};
}