@sema-agent/core
Version:
Stateless, task-oriented AI agent core
583 lines (582 loc) • 42.8 kB
JavaScript
import { types } from "node:util";
import { resolveBrainCallGuardrailMs } from "../../brain/timeout.js";
import { assertContainmentFaceValue, requestReleasedRows, screenRequestReleasableSeat } from "../../tools/fs/index.js";
import { MICRO_COMPACT_MACHINES } from "../context-edit.js";
import { assertAddOnlySeats } from "../child-clamp-seats.js";
import { CROSS_BOUNDARY_POSTURES } from "../cross-boundary-taint.js";
import { compileHostFloor } from "../host-floor.js";
import { receiveHostInstance } from "../host-instance.js";
import { assertNoRetiredRunnerDeps } from "./retired-runner-deps.js";
import { resolveCheckpointStore } from "../checkpoint-store.js";
import { refuseUncountedOwnModel } from "./own-model-money-door.js";
import { runOriginOfLeg, screenRecordedRunOrigin } from "../run-origin.js";
import { assertHolderValue, assertSessionSeatJudgesHolder, assertStoreJudgesHolder } from "../checkpoint-generation.js";
import { claimHolderOf, engineLaneLegOf, writeHolderOf } from "../park-resumability.js";
import { asResumeConfigRefusal, refusePermissionModeDoors } from "../mode-policy.js";
import { screenOutputStyle } from "../output-style.js";
import { screenLanguageSeat } from "./language-frame.js";
import { screenUserAttachments } from "../user-attachment.js";
import { screenUserInvokedSkills } from "../skill-grant.js";
import { readSkillsSeat } from "./skills-seat.js";
import { screenHandsBandOptions } from "../hands-band-screen.js";
import { assertAutoConsolidationWirable } from "./memory-consolidation-driver.js";
import { malformedPricingField, priceTableOf } from "../pricing.js";
import { ownMoneyCeiling, priceTableInput, unpricedModelRefusal } from "./side-call-account.js";
import { fastTierNoticeTo } from "../fast-tier-door.js";
import { receiveRoleMapPriced, resolveRunModel } from "./seat-model-doors.js";
import { keepDeploymentOf } from "./model-lane-seat.js";
import { preflightLockedConfig, received } from "../locked-config.js";
import { enterConfigDoor, refusalAbout, resolveSeatValue } from "../config-refusal-input.js";
import { assertRetentionWords } from "../retention.js";
import { screenModelRole } from "../roles.js";
import { resolveSkillListingBudget } from "../skill-listing-budget.js";
import { describeRejectedValue } from "../tool-search-setting.js";
import { compactionSeatsDefect } from "../context-settings.js";
import { assertAdvisorModelShape } from "../advisor-verdict.js";
import { applyToolModelGate } from "../tool-model-gate.js";
import { readToolFaceLists } from "../tool-face-lists.js";
import { TASK_WAKE_SOURCES } from "../task-spec.js";
import { assertPrincipalIsNotUsageKey, resolveUsageWindows } from "../usage-window-store.js";
import { deriveAskEffective, resolveAskSeat, resolveQuestionSeam, screenApprovalReach, screenInteractionPostureWord } from "../wiring-manifest.js";
import { effectiveTraitsOf, readModelPromptTraits, resolveHost, resolvePromptLean, resolvePromptLocale } from "../../prompt-assembly/select.js";
import { assertNoRetiredKeys, RETIRED_MODEL_KEYS } from "../retired-keys.js";
import { resolvePromptBinding } from "../../prompt-assembly/overlay.js";
import { assertPeerPresenceValue } from "../../agents/peer-directory.js";
import { attachmentSwitchOn, mcpUnavailableOn, TOTAL_TOKENS_REMINDER_MODES } from "./turn-attachments.js";
import { rosterFaceOf } from "./caller-roster.js";
import { assertToolBoundaryLegs, entryDelegates, rosterMountsDelegation } from "../tool-roster.js";
import { copyBackDeclarations } from "../tool-spec-members.js";
import { assertToolCardDeclarations } from "../../prompt-assembly/tool-catalog.js";
import { refuseRenamedDelegationMounts } from "./sub-agent-deny-lists.js";
import { readDeclaredCheckpointScope } from "./checkpoint-scope.js";
import { screenNestedMemory } from "./nested-memory-lane.js";
import { holdsUnpairedSurrogate, readPrincipal, unpairedSurrogateRefusal } from "../principal-name.js";
import { callerKey } from "../caller-text.js";
import { optionKeys, strayMembersOf } from "../own-property-receipt.js";
import { assertManagerApprovesDeclaration } from "../run-ledger.js";
const TASK_LIMIT_KEYS = optionKeys()({
maxTokens: 0,
maxCostUsd: 0,
maxTurns: 0,
maxWalltimeMs: 0,
oneShotWaitCeilingMs: 0,
maxOutputTokens: 0,
approachNotice: 0,
budgetStreamCancel: 0,
degrade: 0,
brainCallGuardrailMs: 0,
});
const NUMERIC_TASK_LIMIT_KEYS = ["maxTokens", "maxCostUsd", "maxTurns", "maxWalltimeMs", "oneShotWaitCeilingMs", "maxOutputTokens"];
const TIMER_MAX_MS = 2_147_483_647;
const RETIRED_TASK_LIMIT_KEYS = {
timeoutSec: "maxWalltimeMs (milliseconds, not seconds)",
deadlineNudge: "approachNotice",
callCapByDeadline: "(retired — no replacement)",
gracefulFinalize: "(retired — the approach notice is the only end-of-budget prompt)",
};
export function limitConfigError(code, message) {
const e = new Error(message);
e.code = code;
return e;
}
export function assertFiniteNonNegativeWhenPresent(value, member, code, because) {
if (value === undefined || (typeof value === "number" && Number.isFinite(value) && value >= 0))
return;
const e = limitConfigError(code, `TaskSpec.${member} must be a finite, non-negative number (got ${describeRejectedValue(value)}) — ${because}`);
e.detail = { field: member };
throw e;
}
export function assertPrincipalValue(raw, member = "principal") {
const reading = readPrincipal(raw);
if (reading.kind === "invalid") {
const [absence, readAs] = member === "principal" ? ["a task with no principal", "no principal"] : ["a task whose isolation scope is its principal", "no isolation scope"];
throw limitConfigError("config.invalid_argument", `TaskSpec.${member} must be a principal name when present (got ${reading.fault}) — omit the key for ${absence}; a provided value that names nobody is refused, never read as "${readAs}".`);
}
}
export function assertCheckpointScopesFollowIsolationScope(spec) {
const own = spec.isolationScope || undefined;
if (own === undefined)
return;
const declared = [
["durableApproval.scope", spec.durableApproval === false ? undefined : spec.durableApproval?.scope],
["resourceSuspend.scope", spec.resourceSuspend?.scope],
];
for (const [field, value] of declared) {
if (value === undefined || value === own)
continue;
const e = limitConfigError("config.invalid_argument", `TaskSpec.${field} (${describeRejectedValue(value)}) differs from TaskSpec.isolationScope (${JSON.stringify(own)}) — a checkpoint scope beside an isolation scope must be that scope, or one scope's parked rows land in another's bucket. Set it to the isolation scope.`);
e.detail = { field };
throw e;
}
}
export function assertDurableApprovalDeclaresScope(declared) {
const reading = readDeclaredCheckpointScope(declared);
if (reading.kind === "scope")
return;
const message = reading.at === "ttlMs"
? `TaskSpec.durableApproval.ttlMs must be a finite number >= 0 when present (got ${reading.fault}) — the opt-in is read as plain data, and its \`ttlMs\` is the lifetime of every approval parked under it; omit \`ttlMs\` for an approval no operator bounds.`
: reading.at === "undeclared"
? `TaskSpec.durableApproval must be plain data (got ${reading.fault} in a member the opt-in does not declare) — an opt-in carries \`scope\` and, optionally, \`ttlMs\`; remove the other member.`
: `TaskSpec.durableApproval must be an object carrying a non-empty string \`scope\` (got ${typeof declared === "object" && declared !== null ? "an object" : describeRejectedValue(declared)}: ${reading.fault}) — the object is plain data (no accessor, no Proxy) and the scope is a name (visible content; no control, separator or format character), the rule \`isolationScope\` is judged by; it is the isolation key every durable approval is filed under, and the one a parked child's revival reads the opt-in back by; an opt-in that names none is refused, never read as the isolation scope on one path and as no opt-in on another. Set \`scope\`, or omit \`durableApproval\`.`;
throw Object.assign(limitConfigError("config.invalid_argument", message), { detail: { field: reading.at === "ttlMs" ? "durableApproval.ttlMs" : reading.at === "undeclared" || (reading.at === undefined && reading.fault.startsWith("not plain data — ")) ? "durableApproval" : "durableApproval.scope" } });
}
export function assertDurableApprovalDeclaration(declared) {
assertDurableApprovalDeclaresScope(declared);
assertFiniteNonNegativeWhenPresent(declared.ttlMs, "durableApproval.ttlMs", "config.invalid_argument", "it is the lifetime of every approval parked under this opt-in: a NaN mints a deadline no reaper cutoff ever passes and a negative one a deadline already behind it; omit `ttlMs` for an approval no operator bounds.");
}
export function resolveTaskLimits(limits) {
if (limits === undefined)
return undefined;
if (typeof limits !== "object" || limits === null || Array.isArray(limits)) {
throw limitConfigError("config.limit_invalid", `TaskSpec.limits must be an object (got ${limits === null ? "null" : Array.isArray(limits) ? "an array" : typeof limits})`);
}
const raw = limits;
const stray = strayMembersOf(raw, { subject: "TaskSpec.limits", unit: "limit", moment: "when the task is prepared" }, TASK_LIMIT_KEYS)?.names[0];
if (stray !== undefined) {
const key = String(stray);
const replacement = Object.hasOwn(RETIRED_TASK_LIMIT_KEYS, key) ? RETIRED_TASK_LIMIT_KEYS[key] : undefined;
throw limitConfigError("config.limit_unknown_key", `TaskSpec.limits[${callerKey(stray)}] is not a limit this engine reads` +
(replacement !== undefined ? ` — it was replaced by \`${replacement}\`` : "") +
`. Legal keys: ${TASK_LIMIT_KEYS.join(", ")}. Refused rather than ignored: a limit that is silently dropped reads to the caller as an armed ceiling.`);
}
for (const key of NUMERIC_TASK_LIMIT_KEYS) {
assertFiniteNonNegativeWhenPresent(raw[key], `limits.${key}`, "config.limit_invalid", "an unevaluable ceiling is not a ceiling, and folding it to a default would run the task under a limit nobody chose.");
}
const ceiling = raw.oneShotWaitCeilingMs;
if (ceiling !== undefined && ceiling > TIMER_MAX_MS) {
throw limitConfigError("config.limit_invalid", `TaskSpec.limits.oneShotWaitCeilingMs must be at most ${TIMER_MAX_MS} ms (got ${ceiling}) — a timer cannot hold a longer wait; write 0 to wait as long as the run's walltime allows.`);
}
const notice = raw.approachNotice;
if (notice !== undefined && notice !== false) {
if (typeof notice !== "object" || notice === null || Array.isArray(notice)) {
throw limitConfigError("config.limit_invalid", `TaskSpec.limits.approachNotice must be \`false\` or { at?: [first, second] } (got ${describeRejectedValue(notice)})`);
}
const at = notice.at;
if (at !== undefined) {
const ok = Array.isArray(at) &&
at.length === 2 &&
at.every((n) => typeof n === "number" && Number.isFinite(n) && n > 0 && n <= 1) &&
at[0] <= at[1];
if (!ok) {
throw limitConfigError("config.limit_invalid", `TaskSpec.limits.approachNotice.at must be two fractions in (0, 1] with first <= second (got ${describeRejectedValue(at)})`);
}
}
}
return limits;
}
export function resolveAttachmentsConfig(attachments) {
if (attachments === null || (typeof attachments !== "object" && typeof attachments !== "function"))
return attachments;
mcpUnavailableOn(attachments);
attachmentSwitchOn(attachments, "silentTurnReminder", "silent_turn_reminder");
attachmentSwitchOn(attachments, "elapsedTimeReminder", "elapsed_time_reminder");
const mode = attachments.totalTokensReminderMode;
if (mode !== undefined) {
const legal = TOTAL_TOKENS_REMINDER_MODES;
if (typeof mode !== "string" || !legal.includes(mode)) {
throw limitConfigError("config.attachment_invalid", `TaskSpec.attachments.totalTokensReminderMode must be one of ${TOTAL_TOKENS_REMINDER_MODES.map((m) => `"${m}"`).join(", ")} ` +
`(got ${describeRejectedValue(mode)}) — refused rather than folded to the default, which would publish a different readout than the one the deployment asked for.`);
}
}
return attachments;
}
export function resolvePromptTraits(model, promptLean) {
assertNoRetiredKeys(model, RETIRED_MODEL_KEYS, "Model");
return effectiveTraitsOf(readModelPromptTraits(model), promptLean);
}
function microCompactConfigError(field, value, legal) {
const shown = describeRejectedValue(value);
const seat = field === undefined ? "microCompact" : `microCompact.${field}`;
const e = new Error(`${seat} ${shown} is not ${legal} — an unevaluable declaration is refused loudly, ` +
`never folded to the default: a silently-ignored declaration would run the DEFAULT machine ` +
`while the deployment believes its opt-in or opt-out took effect.`);
e.code = "config.microcompact_invalid";
return e;
}
export function resolveMicroCompactKnob(bag) {
if (bag !== undefined && (typeof bag !== "object" || bag === null || Array.isArray(bag))) {
throw microCompactConfigError(undefined, bag, "an object carrying optional machine/clearOnRejection keys");
}
const declaredMachine = bag?.machine;
if (declaredMachine !== undefined && !MICRO_COMPACT_MACHINES.includes(declaredMachine)) {
throw microCompactConfigError("machine", declaredMachine, MICRO_COMPACT_MACHINES.map((m) => `"${m}"`).join(" | "));
}
return { machine: declaredMachine ?? "off", clearOnRejection: resolveClearOnRejection(bag) };
}
function resolveClearOnRejection(bag) {
const declared = bag?.clearOnRejection;
if (declared !== undefined && typeof declared !== "boolean") {
throw microCompactConfigError("clearOnRejection", declared, "a boolean");
}
return declared ?? true;
}
function closedWord(raw, seat, words, absent, code, why) {
if (raw === undefined)
return absent;
const word = words.find((w) => w === raw);
if (word !== undefined)
return word;
const spelled = words.map((w) => `"${w}"`);
throw limitConfigError(code, `${seat} must be ${spelled.length > 1 ? `${spelled.slice(0, -1).join(", ")} or ` : ""}${spelled.at(-1)} when present (got ${describeRejectedValue(raw)}) — ${why}`);
}
export const checkpointStoreSeat = (spec) => (spec.checkpointStore !== undefined ? "taskConfig" : "deps");
export function assertResumeConfigRecord(config) {
if (config === null || typeof config !== "object" || Array.isArray(config)) {
throw limitConfigError("config.invalid_argument", `the resume's taskConfig must be an object — the TaskSpec the run suspended with (got ${config === null ? "null" : Array.isArray(config) ? "an array" : typeof config})`);
}
}
function interactionPostureDoor(spec, inherited, deps, disclose) {
const disclosed = (door) => {
try {
return door();
}
catch (e) {
if (e instanceof Error)
disclose?.(e);
throw e;
}
};
const declared = resolveSeatValue(spec.interactionPosture, () => inherited ?? deps.interactionPosture);
const posture = enterConfigDoor(declared.input, () => disclosed(() => screenInteractionPostureWord(declared.value)));
if (posture === "interactive" && spec.interactiveTools === false) {
enterConfigDoor("taskConfig", () => disclosed(() => {
const e = new Error(`interaction posture "interactive" declared together with interactiveTools: false — the hard-headless ` +
`clamp removes the AskUserQuestion mount, so no content question can ever reach the human this posture ` +
`promises. Drop one of the two declarations.`);
e.code = "config.interaction_posture";
throw e;
}));
}
return { posture, input: declared.input };
}
function agentsWithoutDelegationMount() {
const e = new Error(`TaskSpec.agents was provided but no delegation tool (createSubagentTool) is mounted in spec.tools — the per-task agents could never be offered. Mount the delegation tool, or drop spec.agents.`);
e.code = "config.agents.no_delegation_tool";
return e;
}
export function configValueDoors(input) {
const { spec, resumeLeg, sessions } = input;
const holder = input.leg?.holder;
const startedBy = holderSeatStarterOf(input.leg);
let deps = input.deps;
enterConfigDoor("deps", () => assertNoRetiredRunnerDeps(deps));
const hostInstance = enterConfigDoor("deps", () => receiveHostInstance(deps.host, "RunnerDeps.host"));
enterConfigDoor("taskConfig", () => assertPrincipalValue(spec.principal));
enterConfigDoor("taskConfig", () => assertPrincipalIsNotUsageKey(spec.principal));
enterConfigDoor("taskConfig", () => assertPrincipalValue(spec.isolationScope, "isolationScope"));
if (!resumeLeg && typeof spec.sessionId === "string" && holdsUnpairedSurrogate(spec.sessionId))
enterConfigDoor("taskConfig", () => { throw limitConfigError("config.invalid_argument", unpairedSurrogateRefusal("TaskSpec.sessionId")); });
const runOrigin = enterConfigDoor("taskConfig", () => runOriginOfLeg(spec.runOrigin, input.resumedRow));
enterConfigDoor("taskConfig", () => assertPeerPresenceValue(spec.peerPresence));
const toolFaceLists = enterConfigDoor("taskConfig", () => readToolFaceLists(spec));
const microCompactKnob = enterConfigDoor("deps", () => resolveMicroCompactKnob(deps.microCompact));
const promptHost = enterConfigDoor("taskConfig", () => resolveHost(spec));
const deploymentRoles = enterConfigDoor("deps", () => receiveRoleMapPriced(deps.roles, "RunnerDeps.roles", deps.pricing, input.tellFastTier));
if (deploymentRoles !== undefined)
deps = keepDeploymentOf(deps, { ...deps, roles: deploymentRoles });
const taskRoles = enterConfigDoor("taskConfig", () => receiveRoleMapPriced(spec.roles, "TaskSpec.roles", deps.pricing, input.tellFastTier));
const promptBinding = enterConfigDoor("taskConfig", () => resolvePromptBinding(spec));
const promptLocale = enterConfigDoor("taskConfig", () => resolvePromptLocale(spec));
const promptLean = enterConfigDoor("taskConfig", () => resolvePromptLean(spec));
if (spec.resumeAt !== undefined)
enterConfigDoor("taskConfig", () => {
if (resumeLeg) {
const e = new Error("resumeAt cannot be combined with a durable resume");
e.code = "resume_at.conflicts_resume";
throw e;
}
if (!spec.sessionId) {
const e = new Error("resumeAt requires a sessionId (the session to branch)");
e.code = "resume_at.no_session";
throw e;
}
});
enterConfigDoor("taskConfig", () => assertContainmentFaceValue(spec.readFace, "read", "spec"));
enterConfigDoor("deps", () => assertContainmentFaceValue(deps.readFace, "read", "deps"));
enterConfigDoor("taskConfig", () => assertContainmentFaceValue(spec.writeFace, "write", "spec"));
enterConfigDoor("deps", () => assertContainmentFaceValue(deps.writeFace, "write", "deps"));
enterConfigDoor("taskConfig", () => assertAddOnlySeats(spec));
enterConfigDoor("taskConfig", () => requestReleasedRows(screenRequestReleasableSeat(deps.readDenyBuiltinRequestExcludable), spec.readDenyBuiltinExclude));
const memoryDelegationEvidence = enterConfigDoor("deps", () => closedWord(deps.memoryDelegationEvidence, "RunnerDeps.memoryDelegationEvidence", ["static-face", "attested-only"], "static-face", "config.memory_delegation_evidence", "an unevaluable evidence standard is refused loudly, never folded to either standard."));
const memoryProvenance = enterConfigDoor("deps", () => closedWord(deps.memoryProvenance, "RunnerDeps.memoryProvenance", ["off", "carry"], "carry", "config.memory_provenance", "an unevaluable provenance mode is refused loudly, never folded to either mode."));
const memoryCapturePolicy = enterConfigDoor("deps", () => closedWord(deps.memoryCapturePolicy, "RunnerDeps.memoryCapturePolicy", ["open", "governed", "capture-required"], "open", "config.memory_capture_policy", "an unevaluable capture posture is refused loudly, never folded to any posture (the fault arms differ per posture, so a guess would pick a polarity nobody configured)."));
const crossBoundaryPosture = enterConfigDoor("deps", () => closedWord(deps.crossBoundaryPosture, "RunnerDeps.crossBoundaryPosture", CROSS_BOUNDARY_POSTURES, undefined, "config.cross_boundary_posture", "an unevaluable posture is refused loudly, never folded to either word (an absent seat is undeclared, which is its own fact)."));
const hostFloor = enterConfigDoor("deps", () => compileHostFloor(deps.hostFloor));
const advisorTool = enterConfigDoor("deps", () => closedWord(deps.advisorTool, "RunnerDeps.advisorTool", ["disabled"], undefined, "config.advisor_tool_invalid", "the switch has one word; anything else is refused, never read as either state."));
if (advisorTool === undefined)
enterConfigDoor("taskConfig", () => assertAdvisorModelShape(spec.advisorModel));
const projectMemory = enterConfigDoor("taskConfig", () => closedWord(spec.projectMemory, "TaskSpec.projectMemory", ["disabled"], undefined, "config.invalid_argument", "the switch has one word; omit the key to leave the deployment's project context in force."));
enterConfigDoor("deps", () => assertAutoConsolidationWirable(deps));
if (spec.resumeAtMode !== undefined)
enterConfigDoor("taskConfig", () => {
if (spec.resumeAt === undefined) {
const e = new Error(`resumeAtMode ${describeRejectedValue(spec.resumeAtMode)} requires resumeAt (there is no branch target to position against)`);
e.code = "resume_at.mode_without_target";
throw e;
}
if (spec.resumeAtMode !== "at" && spec.resumeAtMode !== "before") {
const e = new Error(`resumeAtMode ${describeRejectedValue(spec.resumeAtMode)} is invalid — expected "at" (inclusive branch, the default) or "before" (exclusive branch)`);
e.code = "resume_at.invalid_mode";
throw e;
}
});
if (spec.toolMaterializeStrategy !== undefined && spec.toolMaterializeStrategy !== "swap" && spec.toolMaterializeStrategy !== "static")
enterConfigDoor("taskConfig", () => {
const e = new Error(`toolMaterializeStrategy must be "swap" or "static" (got ${describeRejectedValue(spec.toolMaterializeStrategy)}).`);
e.code = "config.tool_materialize_invalid";
throw e;
});
if (spec.memoryPersistenceCapable !== undefined && typeof spec.memoryPersistenceCapable !== "boolean")
enterConfigDoor("taskConfig", () => {
const e = new Error(`memoryPersistenceCapable must be a boolean when present (got ${describeRejectedValue(spec.memoryPersistenceCapable)}) — a non-boolean would silently read as capable.`);
e.code = "config.memory_persistence_invalid";
throw e;
});
if (spec.classifyAllShell !== undefined && typeof spec.classifyAllShell !== "boolean")
enterConfigDoor("taskConfig", () => { throw limitConfigError("config.invalid_argument", `TaskSpec.classifyAllShell must be a boolean when present (got ${describeRejectedValue(spec.classifyAllShell)}) — true lets no shell allow entry clear a call in auto mode; omit the key for the default.`); });
if (spec.blockReadsOutsideRoots !== undefined && typeof spec.blockReadsOutsideRoots !== "boolean")
enterConfigDoor("taskConfig", () => { throw limitConfigError("config.invalid_argument", `TaskSpec.blockReadsOutsideRoots must be a boolean when present (got ${describeRejectedValue(spec.blockReadsOutsideRoots)}) — true refuses reads outside this task's directories without asking; omit the key for the default.`); });
if (spec.fastMode !== undefined && typeof spec.fastMode !== "boolean")
enterConfigDoor("taskConfig", () => { throw limitConfigError("config.invalid_argument", `TaskSpec.fastMode must be a boolean when present (got ${describeRejectedValue(spec.fastMode)}) — true asks for fast speed on the models whose catalog entry declares it; omit the key for standard speed.`); });
const compactionSeats = typeof spec.compaction === "object" && spec.compaction !== null ? compactionSeatsDefect(spec.compaction, "TaskSpec.compaction") : undefined;
if (compactionSeats !== undefined)
enterConfigDoor("taskConfig", () => { throw limitConfigError(compactionSeats.kind === "retired" ? "config.spec_retired_key" : "config.invalid_argument", compactionSeats.sentence); });
if (spec.toolMaterializeStrategy === "static" && spec.deferSelfResolve === false)
enterConfigDoor("taskConfig", () => {
const e = new Error(`toolMaterializeStrategy "static" cannot be combined with deferSelfResolve: false — with the direct-call ` +
`lane disabled a placeholder is never swapped and never self-resolves, so no deferred tool could ever be ` +
`called. Use "swap", or leave deferSelfResolve on.`);
e.code = "config.tool_materialize_unreachable";
throw e;
});
if (spec.wake !== undefined)
enterConfigDoor("taskConfig", () => {
closedWord(spec.wake, "TaskSpec.wake", TASK_WAKE_SOURCES, undefined, "config.invalid_argument", "omit the key for a leg that opens on its objective.");
const second = resumeLeg ? "a resumed row" : (spec.objective ?? "").trim().length > 0 ? "an objective" : (spec.images?.length ?? 0) > 0 ? "images" : (spec.userAttachments?.length ?? 0) > 0 ? "attachments" : undefined;
if (second !== undefined)
throw limitConfigError("config.invalid_argument", `TaskSpec.wake opens the leg on its parked notifications, and the leg also carries ${second} — a leg opens on exactly one input; omit wake, or drop the other.`);
});
if (!resumeLeg && spec.wake === undefined && (spec.objective ?? "").trim().length === 0)
enterConfigDoor("taskConfig", () => {
const e = new Error("TaskSpec.objective is empty — a task needs an instruction (an empty user message is rejected by strict model endpoints and would fail every later request of the session).");
e.code = "config.empty_objective";
throw e;
});
const lockedPreflight = preflightLockedConfig(spec, deps, input.receivedPeers);
const declaredSkills = spec.skills;
const skills = declaredSkills === undefined ? undefined : enterConfigDoor("taskConfig", () => readSkillsSeat(declaredSkills));
enterConfigDoor("deps", () => screenHandsBandOptions(deps.hands));
const skillListingSeats = { fraction: spec.skillListingBudgetFraction, maxDescChars: spec.skillListingMaxDescChars };
enterConfigDoor("taskConfig", () => resolveSkillListingBudget(skillListingSeats));
enterConfigDoor("taskConfig", () => resolveTaskLimits(spec.limits));
enterConfigDoor("taskConfig", () => resolveAttachmentsConfig(spec.attachments));
const nestedMemory = enterConfigDoor("taskConfig", () => screenNestedMemory(spec, projectMemory));
if (spec.resourceSuspend !== undefined)
enterConfigDoor("taskConfig", () => {
const declared = spec.resourceSuspend;
if (typeof declared !== "object" || declared === null || Array.isArray(declared)) {
throw limitConfigError("config.limit_invalid", `TaskSpec.resourceSuspend must be an object carrying a non-empty \`scope\` (got ${declared === null ? "null" : Array.isArray(declared) ? "an array" : typeof declared}) — it is the allocation every resource checkpoint is filed under.`);
}
const rsus = declared;
if (typeof rsus.scope !== "string" || rsus.scope === "") {
throw limitConfigError("config.limit_invalid", `TaskSpec.resourceSuspend.scope must be a non-empty string (got ${describeRejectedValue(rsus.scope)}) — it is the multi-tenant isolation key every resource checkpoint is filed under.`);
}
for (const key of ["totalBudgetUsd", "totalTokens", "maxSlices", "ttlMs"]) {
assertFiniteNonNegativeWhenPresent(rsus[key], `resourceSuspend.${key}`, "config.limit_invalid", "an unevaluable allocation is not an allocation, and a NaN here blinds even the validated per-slice window.");
}
});
if (spec.durableApproval !== undefined && spec.durableApproval !== false)
enterConfigDoor("taskConfig", () => assertDurableApprovalDeclaration(spec.durableApproval));
enterConfigDoor("taskConfig", () => assertCheckpointScopesFollowIsolationScope(spec));
const usageWindows = enterConfigDoor("deps", () => resolveUsageWindows(deps.usageWindows));
const taskGuardrail = spec.limits?.brainCallGuardrailMs;
const guardrail = resolveSeatValue(taskGuardrail, () => deps.brainCallGuardrailMs);
const brainCallGuardrailMs = enterConfigDoor(guardrail.input, () => resolveBrainCallGuardrailMs(guardrail.value));
const checkpointStore = enterConfigDoor(checkpointStoreSeat(spec), () => resolveCheckpointStore(spec, deps));
enterConfigDoor("deps", () => (assertHolderValue(holder), assertHolderValue(input.leg?.treeHolder, "RunInternals.treeHolder")));
enterConfigDoor(checkpointStoreSeat(spec), () => assertStoreJudgesHolder("checkpoint", checkpointStoreSeat(spec) === "taskConfig" ? "TaskSpec.checkpointStore" : "RunnerDeps.checkpointStore", checkpointStore, claimHolderOf(input.leg), startedBy));
enterConfigDoor("deps", () => assertSessionSeatJudgesHolder(sessions, writeHolderOf(input.leg), startedBy));
const taskStore = checkpointStoreSeat(spec) === "taskConfig" ? checkpointStore : undefined;
const retention = { policy: deps.retentionPolicy, locked: lockedPreflight.lockedKeys.has("retentionPolicy") };
enterConfigDoor("deps", () => assertRetentionWords({
...retention,
stores: [
{ name: "sessionStore", store: sessions },
{ name: "checkpointStore", store: taskStore === undefined ? checkpointStore : undefined },
{ name: "toolResultStore", store: deps.toolResultStore },
],
}));
if (taskStore !== undefined)
enterConfigDoor("taskConfig", () => assertRetentionWords({ ...retention, stores: [{ name: "checkpointStore", store: taskStore }] }));
const { posture: resolvedInteractionPosture, input: interactionPostureInput } = interactionPostureDoor(spec, input.parentInteractionPosture, deps, input.discloseInteractionPosture);
enterConfigDoor("taskConfig", () => screenModelRole(spec.modelRole));
return { toolFaceLists, promptHost, promptBinding, promptLocale, promptLean, lockedPreflight, skillListingSeats, skills, projectMemory, microCompactKnob, memoryDelegationEvidence, memoryProvenance, memoryCapturePolicy, usageWindows, brainCallGuardrailMs, crossBoundaryPosture, advisorTool, hostFloor, runOrigin, nestedMemory, deploymentRoles, hostInstance, taskRoles, resolvedInteractionPosture, interactionPostureInput };
}
function holderSeatStarterOf(internals) {
return engineLaneLegOf(internals) ? "engine" : "host";
}
export function refuseResumeDoors(config, deps, sessions, internals, priorLedger) {
asResumeConfigRefusal("taskConfig", () => {
refusePermissionModeDoors(config);
assertManagerApprovesDeclaration(config);
screenOutputStyle(config.outputStyle);
screenLanguageSeat(config.language);
screenApprovalReach(config.approvalReach);
screenUserInvokedSkills(config);
screenUserAttachments(config.userAttachments, { resumeLeg: true });
assertToolBoundaryLegs(config.tools);
assertToolCardDeclarations(config.tools);
const agents = config.agents;
if (Array.isArray(agents) && !types.isProxy(agents) && agents.length > 0 && rosterMountsDelegation(config.tools) === false)
throw agentsWithoutDelegationMount();
});
const { lockedPreflight, skills, deploymentRoles, taskRoles } = asResumeConfigRefusal("taskConfig", () => configValueDoors({ spec: config, deps, resumeLeg: true, sessions, leg: internals, parentInteractionPosture: internals?.parentInteractionPosture, resumedRow: { recorded: undefined } }));
asResumeConfigRefusal("taskConfig", () => refuseUncountedOwnModel(config, deploymentRoles !== undefined ? { ...deps, roles: deploymentRoles } : deps, taskRoles, priorLedger));
return { ...config, ...(config.mcp !== undefined ? { mcp: lockedPreflight.mcp ?? [] } : {}), ...(config.a2a !== undefined ? { a2a: lockedPreflight.a2a ?? [] } : {}), skills };
}
export function prepareConfigDoors(input) {
const { sessions, resume, internals } = input;
enterConfigDoor("taskConfig", () => {
assertToolBoundaryLegs(input.spec.tools);
assertToolCardDeclarations(input.spec.tools);
});
const callerSpec = input.spec;
const discloseInteractionPostureRefusal = (err) => {
try {
input.refusalSink?.(err, { phase: "config", sessionId: callerSpec.sessionId ?? "(pre-session)", classification: "interaction-posture-refused" });
}
catch {
}
};
const tellFastTier = input.refusalSink !== undefined ? fastTierNoticeTo(input.refusalSink, callerSpec.sessionId ?? "(pre-session)") : undefined;
const { toolFaceLists, promptHost, promptBinding, promptLocale, promptLean, lockedPreflight, skillListingSeats, skills, projectMemory, microCompactKnob, memoryDelegationEvidence, memoryProvenance, memoryCapturePolicy, usageWindows, brainCallGuardrailMs, crossBoundaryPosture, advisorTool, hostFloor, runOrigin, nestedMemory, deploymentRoles, hostInstance, taskRoles, resolvedInteractionPosture, interactionPostureInput } = configValueDoors({ spec: callerSpec, deps: input.deps, resumeLeg: resume !== undefined, sessions, leg: internals, parentInteractionPosture: internals?.parentInteractionPosture, discloseInteractionPosture: discloseInteractionPostureRefusal, ...(tellFastTier !== undefined ? { tellFastTier } : {}), receivedPeers: input.receipt, ...(resume !== undefined ? { resumedRow: { recorded: screenRecordedRunOrigin(resume.seed.runOrigin), ...(resume.opening !== undefined ? { opening: resume.opening } : {}) } } : {}) });
const doorRead = (value) => ({ value, enumerable: value !== undefined, writable: false, configurable: false });
const deps = deploymentRoles !== undefined || hostInstance !== undefined ? keepDeploymentOf(input.deps, { ...input.deps, ...(deploymentRoles !== undefined ? { roles: deploymentRoles } : {}), ...(hostInstance !== undefined ? { host: hostInstance } : {}) }) : input.deps;
const declaredDurableApproval = callerSpec.durableApproval;
const hostApprovalParksNotResumable = declaredDurableApproval === false;
let spec = Object.create(Object.getPrototypeOf(callerSpec), { ...Object.getOwnPropertyDescriptors(callerSpec), skills: doorRead(skills), projectMemory: doorRead(projectMemory), runOrigin: doorRead(runOrigin), durableApproval: doorRead(hostApprovalParksNotResumable ? undefined : declaredDurableApproval), ...(taskRoles !== undefined ? { roles: doorRead(taskRoles) } : {}) });
const askSeat = enterConfigDoor("taskConfig", () => resolveAskSeat(spec, deps));
{
if (resolvedInteractionPosture === "interactive") {
const humanReachable = deriveAskEffective(askSeat.form, "unresolved") === "human_reachable";
const questionDoor = resolveQuestionSeam(spec, deps);
const strippedByEngine = internals?.questionFaceStripped === true;
if (!humanReachable || !(questionDoor.wired || strippedByEngine)) {
const missing = [];
if (!humanReachable) {
missing.push(askSeat.form === "declared_none" ? 'this run declares approvalReach: "none" — nobody on it can be asked to approve' : askSeat.form === "absent"
? "no onAsk approver is wired (spec.onAsk ?? deps.onAsk is absent — asks would auto-deny or park)"
: `the resolved onAsk seat is a policy — ${askSeat.form === "policy_callback" ? "an approver the deployment declared a policy (asPolicyApprover)" : `the blanket policy "${askSeat.form}"`} (${askSeat.provenance ?? "?"}) — a policy is not a reachable human`);
}
if (!questionDoor.wired && !strippedByEngine) {
missing.push("no content-question channel (spec.onQuestion ?? deps.onQuestion is absent, and this leg is not an engine-stripped background lane)");
}
const e = new Error(`interaction posture "interactive" declared, but this assembly cannot reach a human: ${missing.join("; ")}. ` +
`Wire the missing seam(s), or drop the posture declaration (absent = no check).`);
e.code = "config.interaction_posture";
discloseInteractionPostureRefusal(e);
const requestSetsAside = (!humanReachable && (askSeat.form === "declared_none" || askSeat.provenance === "spec")) || (!questionDoor.wired && !strippedByEngine && spec.onQuestion !== undefined);
throw refusalAbout(interactionPostureInput === "taskConfig" || requestSetsAside ? "taskConfig" : "deps", e);
}
}
}
const brainCallGuardrailRef = {};
const mountedRoster = spec.tools;
const receivedAgents = input.receipt.agents;
if (receivedAgents !== undefined && ("refused" in receivedAgents || receivedAgents.read.length > 0)) {
const rebound = spec;
spec = enterConfigDoor("taskConfig", () => {
const pool = rebound.tools ?? [];
if (!pool.some((t) => entryDelegates(t)))
throw agentsWithoutDelegationMount();
const perTask = received(receivedAgents).map(received);
return {
...rebound,
agents: perTask,
tools: pool.map((t, index) => {
if (!entryDelegates(t))
return t;
const rebuilt = t.withAgents(perTask);
return rosterFaceOf(copyBackDeclarations(t, rebuilt, `spec.tools[${index}]`), index);
}),
};
});
}
else if (receivedAgents !== undefined)
spec = { ...spec, agents: [] };
enterConfigDoor("taskConfig", () => refuseRenamedDelegationMounts(mountedRoster, spec.tools));
const { modelInput, ...resolvedRoleRaw } = resolveRunModel(spec, deps, "TaskSpec.model", tellFastTier);
const resolvedRole = internals?.inheritedModelRef !== undefined ? { ...resolvedRoleRaw, modelRef: internals.inheritedModelRef } : resolvedRoleRaw;
const model = resolvedRole.model;
const priceTableOfModel = () => priceTableOf(model, deps.pricing);
const tableInput = (table) => priceTableInput(table, modelInput);
if (usageWindows !== undefined && deps.usageWindowStore !== undefined) {
const costed = usageWindows.find((w) => w.maxCostUsd !== undefined);
const priceTable = costed !== undefined ? priceTableOfModel() : undefined;
const why = costed === undefined
? undefined
: !priceTable.exists
? `model ${JSON.stringify(model.id)} is unpriced — it has neither a RunnerDeps.pricing entry nor a Model.cost declaration, so this run produces NO cost figure to charge the window with (an unpriced run has no cost, which is not the same as a cost of 0). Price the model, or drop maxCostUsd from the window.`
: (() => {
const bad = malformedPricingField(priceTable.table);
return bad === undefined
? undefined
: `the price table for model ${JSON.stringify(model.id)} declares an unevaluable ${bad} — every rate must be a finite, non-negative number of USD per 1M tokens. A table like this prices every turn at zero (or below), so the ceiling would never fill: refused rather than enforced in name only.`;
})();
if (costed !== undefined && why !== undefined) {
const e = new Error(`RunnerDeps.usageWindows declares a cost ceiling (maxCostUsd ${String(costed.maxCostUsd)} over ${String(costed.windowMs)}ms, ${costed.anchor}) but ${why}`);
e.code = "config.usage_window_unpriced";
throw refusalAbout(tableInput(priceTable), e);
}
}
const ownUncounted = unpricedModelRefusal(ownMoneyCeiling(spec, resume?.priorLedger), model, deps.pricing, modelInput);
if (ownUncounted !== undefined)
throw ownUncounted;
const promptTraits = enterConfigDoor(modelInput, () => resolvePromptTraits(model, promptLean));
const gatedRoster = spec.tools;
const gateDecision = enterConfigDoor("deps", () => applyToolModelGate({
tools: gatedRoster,
modelId: model.id,
depsSeat: deps.toolModelGate,
restoreGated: toolFaceLists.restoreGated,
envRaw: process.env.SEMA_TOOL_MODEL_GATE,
}));
if (gateDecision.survivors !== undefined) {
spec = { ...spec, tools: gateDecision.survivors };
}
const skillListingBudget = resolveSkillListingBudget({ ...skillListingSeats, model });
const modelGate = Object.freeze({
removedByClass: gateDecision.removedByClass,
unknownClasses: gateDecision.unknownClasses,
discardedEnvRaw: gateDecision.discardedEnvRaw,
});
const thinking = resolvedRole.thinking;
return {
spec,
deps,
toolFaceLists,
promptLean,
promptTraits,
traitsOf: (m) => resolvePromptTraits(m, promptLean),
promptHost,
promptBinding,
promptLocale,
lockedPreflight,
resolvedInteractionPosture,
askSeat,
microCompactKnob,
resolvedRole,
model,
modelInput,
thinking,
modelGate,
memoryDelegationEvidence,
skillListingBudget,
memoryProvenance,
memoryCapturePolicy, crossBoundaryPosture, advisorTool, hostFloor, runOrigin, nestedMemory,
usageWindows,
brainCallGuardrailRef,
brainCallGuardrailMs,
hostApprovalParksNotResumable,
};
}