@sema-agent/core
Version:
Stateless, task-oriented AI agent core
414 lines (413 loc) • 25.2 kB
JavaScript
import { InMemorySessionStorage, SessionError, StoredSession } from "../internal/harness.js";
import { legBudgetSnapshot, resourceTotalOf } from "./leg-budget.js";
import { createModelFileReader } from "../tools/fs/fs-read.js";
import { compileReadDeny, inheritSessionReadFileState, readDenyBuiltinConfigOf, resolveContainmentFace, seedReadFileStateFromTranscript } from "../tools/fs/index.js";
import { whereItLeads, whereItsAnsweredPrefixLeads } from "../tools/fs/read-deny-home.js";
import { resolveKey } from "../tools/fs/safety.js";
import { unionAddOnly } from "./child-clamp-seats.js";
import { enterConfigDoor } from "./config-refusal-input.js";
import { legCallTargetStamp, validatePath } from "./effective-path-target.js";
import { SeenFileRegistry } from "./existing-target.js";
import { legTaskIdOf, ruleSessionOf } from "./leg-identity.js";
import { readPrincipal } from "./principal-name.js";
import { bindPathRules, createHeadLeads } from "./path-rule-binding.js";
import { assertStringArraySeat, screenReadDenySeat } from "./read-face-seats.js";
import { judgeReadFloorKept, readFloorSeat } from "../tools/fs/read-floor.js";
import { ENV_PURPOSE_UNSUPPORTED, hasDestroy } from "./remote-env.js";
import { dataRootSpellings } from "./sensitive-path-policy.js";
import { sessionRootOf } from "./session-checkout.js";
import { createSyntheticServedReadJudge } from "./synthetic-read-verdict.js";
import { readEntrySpec } from "./task-start-judge.js";
import { readMember, thrownText } from "./thrown-value.js";
import { TOOL_CATALOG_ENTRIES, toolFace } from "./tool-catalog-entries.js";
import { toolPolicyPathRules } from "./tool-policy.js";
import { chainPolicyOnLeg } from "./runner/child-tree.js";
import { createToolOccurrenceTable } from "./runner/tool-occurrence.js";
import { delegatedTreeOwner, judgedLegOf, judgedOwnerSeat, judgeRowForTree, legRowRefusal, readRootOccupant, readStandsAsJudged, rowNotTheOneJudged } from "./runner/delegation-owner.js";
import { legCallerPlaces } from "./runner/leg-caller-places.js";
import { readLegInternals } from "./runner/leg-frame.js";
import { receiveLeg } from "./runner/leg-receipt.js";
import { instructionFamilyOf, primeInstructionReading, } from "./runner/nested-memory-lane.js";
import { seatInstructionLane } from "./runner/prepare-turn-wiring.js";
import { createPermissionRuleLanes } from "./runner/permission-rule-lanes.js";
import { pathTablesCompile, personPathRowsOfTask, readRootsOver } from "./runner/person-path-rows.js";
import { prepareExecutionEnv } from "./runner/prepare-execution-env.js";
import { readBlockLeg, readBlockOf } from "./runner/read-block-judge.js";
import { createRollbackStack } from "./runner/rollback-stack.js";
import { readStateFromTranscript } from "./runner/session-file-state-replay.js";
import { legReadCarrier, readSeatLeaf } from "./runner/session-read-file-states.js";
import { createLiveSessionRules, createSessionRulePolicy } from "./runner/session-rule-policy.js";
import { taskStartDoors } from "./runner/task-start-doors.js";
import { resolveTaskRootCanonical } from "./runner/task-root-canonical.js";
import { settleTeardownLeg } from "./runner/teardown-bounded.js";
import { thrownFailureOf } from "./runner/terminal-account.js";
import { valveLeaves } from "../agents/tool-filter.js";
export const EXTERNAL_INCLUDE_POST_APPROVAL_BLOCKS = Object.freeze(["outside_roots", "rule_denied", "approval_required", "admission_unknown"]);
const NOOP = () => undefined;
export async function previewInstructionsOf(seats, spec, internals) {
try {
const bag = internals !== undefined ? enterConfigDoor("deps", () => readLegInternals(internals, "runTaskStream")) : undefined;
const request = readEntrySpec(spec, () => seats.deps.models).spec;
const silentDeps = { ...seats.deps, onNotice: NOOP, onError: NOOP, tracer: undefined };
const legInternals = {
...(enterConfigDoor("deps", () => readRootOccupant(bag, undefined, request.sessionId)) ?? {}),
receivedPeers: receiveLeg(request, silentDeps),
};
const start = taskStartDoors({ request, deps: silentDeps, sessions: seats.sessions, internals: legInternals });
const projectMemory = instructionFamilyOf(start.spec) === undefined ? "absent" : start.spec.projectMemory === "disabled" ? "disabled" : "on";
const nestedDecl = start.doors.nestedMemory;
const rows = rowReader(seats.sessions);
const existingSession = start.spec.sessionId !== undefined ? await previewSession(seats.sessions, rows, { ...start.spec, sessionId: start.spec.sessionId }, legInternals) : undefined;
const previewSessionId = start.spec.sessionId ?? "preview-instructions";
const previewPrincipal = readPrincipal(start.spec.principal);
const previewRuleSession = ruleSessionOf(legInternals, previewSessionId, previewPrincipal.kind === "name" ? previewPrincipal.name : undefined);
const previewRuleSessionId = previewRuleSession.sessionId;
const previewRunId = "preview-instructions";
const previewTaskId = legTaskIdOf(start.spec, legInternals, previewSessionId);
const abortController = new AbortController();
if (start.spec.signal?.aborted)
abortController.abort();
const owned = [];
const rollback = createRollbackStack(NOOP);
let envPhase;
try {
envPhase = await prepareExecutionEnv({
deps: silentDeps,
spec: start.spec,
internals: legInternals,
resume: undefined,
placementRootResolved: previewSessionId,
sessionId: previewSessionId,
forgetOnThrow: async () => undefined,
rollback,
startsEnv: true,
purpose: "read_changes",
});
rollback.commit();
if (envPhase.ownedEnvSeat.current !== undefined)
owned.push(envPhase.ownedEnvSeat.current);
}
catch (err) {
await rollback.unwindAll();
if (readMember(err, "code") !== ENV_PURPOSE_UNSUPPORTED)
throw err;
envPhase = undefined;
}
try {
const emptyContext = new StoredSession(new InMemorySessionStorage());
const previewLeg = {
harness: { getModel: () => start.doors.model },
session: { buildContext: () => (existingSession ?? emptyContext).buildContext() },
sessionId: previewSessionId,
runId: previewRunId,
announcedListingsRef: {},
frameReceipts: { listingSnapshotOwed: false },
hookIdentity: { taskId: previewTaskId, isDelegatedChild: start.delegation.isDelegatedChild },
};
const handsEnabled = envPhase !== undefined && envPhase.handsEnabled;
assertStringArraySeat(silentDeps.readDenyPatterns, "RunnerDeps.readDenyPatterns", "compiler-owned");
const readBlock = readBlockOf({ spec: start.spec, resume: undefined });
const liveReadFace = resolveContainmentFace({
kind: "read",
specFace: start.spec.readFace,
depsFace: silentDeps.readFace,
readOnlyMount: start.spec.handsReadOnly === true,
readBlock,
orgGoverned: silentDeps.permissionRuleStore?.partitions.org === true,
fullShellReachable: false,
});
const readDenyAdditions = unionAddOnly("readDenyPatterns", silentDeps.readDenyPatterns, start.spec.readDenyPatterns);
const readDenyBuiltinCfg = readDenyBuiltinConfigOf({ tiers: silentDeps.readDenyBuiltinTiers, exclude: silentDeps.readDenyBuiltinExclude });
if (!handsEnabled) {
if (readDenyAdditions.length > 0)
compileReadDeny(readDenyAdditions, "readDenyPatterns", { tiers: [] });
if (projectMemory !== "on" || nestedDecl === undefined)
return { ok: true, projectMemory };
const lane = seatInstructionLane({
declaration: nestedDecl,
signal: abortController.signal,
mark: undefined,
counts: undefined,
deps: silentDeps,
leg: () => previewLeg,
});
const instructions = await primeInstructionReading(lane, NOOP);
return { ok: true, projectMemory, ...(instructions !== undefined ? { instructions } : {}) };
}
const executionEnv = envPhase.executionEnv;
const taskRootFinal = existingSession !== undefined && start.spec.sessionId !== undefined
? await sessionRootOf({ env: executionEnv, session: existingSession, sessionId: start.spec.sessionId, baseRoot: envPhase.taskRootInitial, sessions: rows }, `Runner.previewInstructions: session "${start.spec.sessionId}" checkout cannot be resolved`)
: envPhase.taskRootInitial;
const { canonical: taskRootCanonical } = await resolveTaskRootCanonical({
env: executionEnv,
given: taskRootFinal,
onNotice: silentDeps.onNotice,
sessionId: previewSessionId,
runId: previewRunId,
});
assertStringArraySeat(start.spec.additionalDirectories, "TaskSpec.additionalDirectories", "strings");
assertStringArraySeat(start.spec.additionalReadDirectories, "TaskSpec.additionalReadDirectories", "strings");
const additionalRootsCanonical = [];
const additionalReadRootsCanonical = [];
const declaredAdditionalRoots = [];
const canonicalizeDirs = async (dirs, sink, declared) => {
for (const dir of dirs ?? []) {
if (!dir || !dir.trim())
continue;
const c = await executionEnv.canonicalPath(dir);
if (c.ok) {
sink.push(c.value);
declared?.push(Object.freeze({ directory: dir, canonical: c.value }));
}
}
};
await canonicalizeDirs(start.spec.additionalDirectories, additionalRootsCanonical, declaredAdditionalRoots);
await canonicalizeDirs(start.spec.additionalReadDirectories, additionalReadRootsCanonical);
for (const a of [additionalRootsCanonical, additionalReadRootsCanonical])
a.splice(0, a.length, ...new Set(a));
const legHome = validatePath(executionEnv.homeDir, { intent: "validate-coordinate" });
const legAnchors = { root: taskRootCanonical, ...(legHome !== undefined ? { home: legHome } : {}) };
const callerPlaces = legCallerPlaces({ deps: silentDeps, spec: start.spec, recorded: undefined });
const onLeg = enterConfigDoor("deps", () => chainPolicyOnLeg({
leg: legAnchors,
chainTop: legAnchors,
placement: undefined,
chain: (legInternals.inheritedGate?.parentConstraints ?? []).map((c) => c.policy),
installations: { live: legInternals.inheritedGate?.pathRuleInstallations, seed: undefined },
rebase: (p) => p,
}));
const installedToolPolicy = onLeg.own(start.doors.lockedPreflight.toolPolicy);
const inheritedPolicies = (legInternals.inheritedGate?.parentConstraints ?? []).flatMap((c, i) => c.policy !== undefined ? [onLeg.chained(c.policy, i)] : []);
const headLeads = createHeadLeads((part) => whereItsAnsweredPrefixLeads(executionEnv, part));
let sessionRulePolicy;
let ownSessionRow;
if (silentDeps.sessionPolicyStore !== undefined && start.spec.sessionId !== undefined) {
const key = { sessionId: start.spec.sessionId, ...(start.spec.principal ? { principal: start.spec.principal } : {}) };
const seed = (await silentDeps.sessionPolicyStore.getRules(key.sessionId, key.principal)) ?? { rev: 0 };
ownSessionRow = seed;
sessionRulePolicy = createSessionRulePolicy({ seed, read: createLiveSessionRules(silentDeps.sessionPolicyStore, { ...key, seed }, { onUnreadable: NOOP, onEnforced: (r) => void (ownSessionRow = r) }) }, { env: executionEnv, rootPath: taskRootFinal, toolEffects: new Map(), anchors: legAnchors, onEarlierGrammar: NOOP });
}
const personRows = personPathRowsOfTask({
deps: silentDeps,
notices: { onUnread: NOOP, onRowsDropped: NOOP },
principal: start.spec.principal,
ruleSessionId: previewRuleSessionId,
ids: { sessionId: previewSessionId, runId: previewRunId, taskId: previewTaskId },
root: taskRootFinal,
rootCanonical: taskRootCanonical,
leads: headLeads,
chainTop: legAnchors,
occurrences: createToolOccurrenceTable(),
signals: [abortController.signal, ...(start.spec.signal !== undefined ? [start.spec.signal] : [])],
seatsBeyond: {
session_rules: () => (ownSessionRow !== undefined ? { rules: ownSessionRow, unread: false } : undefined),
ancestor_session_rules: () => [],
skill_grants: () => [],
},
});
await personRows.prime();
const policyPathRows = toolPolicyPathRules([installedToolPolicy, ...inheritedPolicies], legAnchors);
const effectivePathDenyRules = policyPathRows.filter((r) => r.faces.length > 0 && r.behavior === "deny" && r.unanchored === undefined);
const canonicalizePersonDirs = async (dirs) => {
const out = [];
for (const d of dirs)
await canonicalizeDirs([d], out).catch(NOOP);
return out;
};
const compileTables = pathTablesCompile({
env: executionEnv,
additions: readDenyAdditions,
builtin: readDenyBuiltinCfg,
legRows: effectivePathDenyRules,
legReadAskRows: [],
leads: headLeads,
writeAskLeads: createHeadLeads((part) => whereItLeads(executionEnv, part), { unansweredRejects: true }),
configRoots: callerPlaces.configRoots.dirs,
callerHomes: callerPlaces.homes.dirs,
workspaceRoot: taskRootCanonical,
canonicalize: canonicalizePersonDirs,
});
const floorRequired = screenReadDenySeat("readDenyFloorRequired", silentDeps.readDenyFloorRequired) === true;
const tables = await personRows.attachTables(async (person) => {
const compiled = await compileTables(person);
judgeReadFloorKept({ env: executionEnv, table: compiled.readDeny, floor: readFloorSeat(compiled.readDeny)?.(undefined), required: floorRequired, deployment: [], onNotice: NOOP });
return compiled;
});
if (projectMemory !== "on" || nestedDecl === undefined)
return { ok: true, projectMemory };
const { personDirectories } = readBlockLeg(readBlock);
const readRoots = readRootsOver({
own: () => [...additionalRootsCanonical, ...additionalReadRootsCanonical],
tables,
ready: personRows.tablesReady,
store: () => undefined,
onHeld: NOOP,
personDirectories,
});
const readFileState = new Map();
const seenFiles = new SeenFileRegistry();
if (existingSession !== undefined && start.spec.sessionId !== undefined) {
const judgeKey = async (path) => {
const rk = await readRoots.ready().then(() => resolveKey(executionEnv, taskRootCanonical, path, undefined, undefined, readRoots(), undefined, undefined, liveReadFace));
return rk.ok ? rk.key : undefined;
};
const carrier = await legReadCarrier({
resuming: false,
spec: start.spec,
sessionId: start.spec.sessionId,
seats: seats.readStates,
leaf: () => readSeatLeaf(existingSession),
getEntry: (id) => existingSession.getEntry(id),
});
if (carrier.from === "seat") {
await inheritSessionReadFileState(readFileState, carrier.state, judgeKey, seenFiles);
}
else if (carrier.from === "transcript") {
const prior = await existingSession.buildContext().catch(() => undefined);
const rebuilt = readStateFromTranscript(prior?.messages ?? []);
for (const rec of rebuilt.records) {
const rk = await judgeKey(rec.path);
if (rk === undefined)
continue;
if ("content" in rec)
seedReadFileStateFromTranscript(readFileState, rk, rec.content, rec.at, rec.transmittedByToolCallId);
else
readFileState.set(rk, { ...rec.observation, lastReadAt: rec.at });
}
}
}
const reader = createModelFileReader({
env: executionEnv,
state: readFileState,
rootCanonical: taskRootCanonical,
additionalRoots: readRoots,
readDeny: tables.readDeny,
readFace: liveReadFace,
});
const ruleLanes = createPermissionRuleLanes({
provider: silentDeps.permissionRuleStore,
localOwnerDeclared: silentDeps.localOwnerRules === true,
principal: start.spec.principal,
sessionId: previewRuleSessionId,
root: taskRootFinal,
rootCanonical: taskRootCanonical,
chainTop: legAnchors,
leads: headLeads,
liveCwd: () => taskRootCanonical,
home: executionEnv.homeDir,
questionToolMounted: false,
questionToolName: "AskUserQuestion",
onRevisionDefect: NOOP,
onDisclosure: NOOP,
rows: { pin: (id, judged) => personRows.pin(id, judged), forRequest: () => personRows.forRequest() },
});
const stampCallTarget = legCallTargetStamp({
env: executionEnv,
root: taskRootCanonical,
cwd: () => undefined,
judgesPaths: () => installedToolPolicy?.pathRules !== undefined || ruleLanes.personal !== undefined,
leads: () => headLeads.resolve([...toolPolicyPathRules([installedToolPolicy, ...inheritedPolicies], legAnchors), ...bindPathRules([], legAnchors)]),
});
const exemptRoots = Object.freeze(dataRootSpellings(silentDeps.memoryEngineDir));
const budget = legBudgetSnapshot(resourceTotalOf(start.spec), undefined);
const servedReadVerdict = createSyntheticServedReadJudge({
...(sessionRulePolicy !== undefined ? { denyNarrowingPolicy: sessionRulePolicy } : {}),
...(installedToolPolicy !== undefined ? { callerPolicy: installedToolPolicy } : {}),
inheritedPolicies, ...(previewRuleSession.inTree ? { inTreeRuleSession: true } : {}),
...(ruleLanes.personal !== undefined ? { persistedRuleLane: ruleLanes.personal } : {}),
...(ruleLanes.org !== undefined ? { orgRuleLane: ruleLanes.org } : {}),
stampCallTarget,
signal: abortController.signal,
}, () => ({ cwd: taskRootCanonical, root: taskRootCanonical, exemptRoots, budget }));
const readName = TOOL_CATALOG_ENTRIES.find((e) => e.id === "read")?.name;
const readDecl = readName !== undefined && valveLeaves(start.toolFaceSnapshot.selector)({ name: readName }) ? toolFace("read") : undefined;
const readContract = readDecl?.contract;
const readToolFace = readName === undefined || readDecl === undefined || readContract === undefined
? undefined
: {
names: [readName],
family: readDecl.family,
...(readDecl.pathTarget !== undefined
? {
pathTarget: {
param: readDecl.pathTarget.param,
aliases: [...(readDecl.pathTarget.aliases ?? [])],
access: readDecl.pathTarget.access,
skillScopeEligible: readDecl.pathTarget.skillScopeEligible === true,
...(readDecl.pathTarget.base !== undefined ? { base: readDecl.pathTarget.base } : {}),
...(readDecl.pathTarget.absent !== undefined ? { absent: readDecl.pathTarget.absent } : {}),
},
}
: {}),
capabilityId: readContract.contractId,
contractId: readContract.contractId,
shapeDigest: "",
implementationRevision: readContract.implementationRevision,
engineMounted: true,
};
const lane = seatInstructionLane({
declaration: nestedDecl,
signal: abortController.signal,
mark: undefined,
counts: undefined,
deps: silentDeps,
leg: () => previewLeg,
env: executionEnv,
reader,
judge: servedReadVerdict,
readFace: () => readToolFace,
state: readFileState,
root: taskRootCanonical,
additionalRoots: declaredAdditionalRoots,
});
const instructions = await primeInstructionReading(lane, NOOP);
return { ok: true, projectMemory, ...(instructions !== undefined ? { instructions } : {}) };
}
finally {
for (const env of owned)
if (hasDestroy(env))
await settleTeardownLeg(() => env.destroy(), "ownedEnv.destroy (previewInstructions)", NOOP);
}
}
catch (err) {
const { code, message, detail } = thrownFailureOf(err, thrownText(err));
return { ok: false, ...(code !== undefined ? { code } : {}), message, ...(detail !== undefined ? { detail } : {}) };
}
}
function rowReader(sessions) {
const row = async (sessionId) => {
const readRow = sessions.readRow;
if (typeof readRow !== "function") {
throw Object.assign(new Error("Runner.previewInstructions: the session store has no row read (readRow) — a preview reads a named session without running on it, and never opens it through acquire, which sweeps and records activity"), { code: "config.invalid_session_store" });
}
return readRow.call(sessions, sessionId);
};
return {
row,
async acquire(sessionId) {
const read = sessionId === undefined ? undefined : await row(sessionId);
if (sessionId === undefined || read === undefined)
throw new SessionError("not_found", `Session not found: ${sessionId ?? "(none named)"}`);
return { session: detachedSession(read), sessionId };
},
};
}
const detachedSession = (row) => new StoredSession(new InMemorySessionStorage({ metadata: structuredClone(row.metadata), entries: structuredClone(row.entries) }));
async function previewSession(sessions, rows, spec, internals) {
const ownerSeat = judgedOwnerSeat(internals);
const leg = judgedLegOf(spec, internals, ownerSeat === undefined ? undefined : await delegatedTreeOwner(ownerSeat, spec.signal));
let judged;
if (leg !== undefined) {
const verdict = await judgeRowForTree(sessions, { sessionId: spec.sessionId, minted: leg.minted, runsOn: true, writes: false }, { bound: true, owner: leg.owner }, leg.signal);
if (!verdict.open)
throw legRowRefusal(spec.sessionId, verdict);
judged = verdict.head;
}
const row = await rows.row(spec.sessionId);
if (judged !== undefined && !(judged === null && row === undefined) && !readStandsAsJudged(judged, row?.head))
throw legRowRefusal(spec.sessionId, rowNotTheOneJudged());
if (row === undefined && spec.requireExistingSession === true) {
throw Object.assign(new Error(`Runner.previewInstructions: session "${spec.sessionId}" does not exist`), { code: "resume.session_not_found" });
}
return row === undefined ? undefined : detachedSession(row);
}