@sema-agent/core
Version:
Stateless, task-oriented AI agent core
808 lines • 56.6 kB
JavaScript
import { snapshotActorAssertion } from "../../internal/llm.js";
import { redactThenCut } from "../../agents/subagent-steps.js";
import { ASK_USER_QUESTION_TOOL_NAME } from "../ask-question.js";
import { CheckpointError, readPendingSteerQueue, realApprovalOrgFact, remainingBudgetMicroUsd } from "../checkpoint-store.js";
import { normalizePersistedRuleHit } from "../rule-lane-reads.js";
import { decidersNote, SETTLEMENT_NOBODY_JUDGED } from "../gate-outcome.js";
import { formatHookFeedback, hookSeatExpiredError, runHookSeat } from "../hooks.js";
import { buildAppliedHumanInputEvent, buildHumanInputEvent, projectHumanInput } from "../human-input-projection.js";
import { ORG_ADJUDICATION_TIMEOUT_MS, settleOrgVerdictWithin } from "../permission-rule-org.js";
import { applyPersistedTightening, disclosedRuleSet } from "../persisted-rule-arms.js";
import { parkedSkillApprovalRefusal, skillRowRefusal } from "../skill-grant.js";
import { SKILL_TOOL_NAME } from "./synthetic-tools.js";
import { computeCostMicroUsd } from "../pricing.js";
import { mintSystemReminder } from "../reminder-mint.js";
import { hasDestroy } from "../remote-env.js";
import { advertisedWritableRootsSeat, policyCannotAnswer, policyRefusalMessage, refuseOutOfContractDecision } from "../tool-policy.js";
import { callFaceSeat, judgeParkedToolIdentity, parkedRowLiveFace, rosterEntryNamed } from "../tool-roster.js";
import { deliverEngineNotice } from "../types.js";
import { delimitUntrusted, inlineUntrusted, REVIEWER_NOTE_MAX_BODY, sanitizeUntrustedText } from "../untrusted-text.js";
import { errorCodeOf } from "./assemble-result.js";
import { DEFAULT_PRECALL_OUTPUT_TOKENS, platformLimitTerminal } from "./clock-and-limits.js";
import { mintOutputStyleReminder, owedPostureText } from "./compaction-restate.js";
import { deepJsonEqual, resumeContinuation } from "./decide-continuation.js";
import { chainCannotJudge } from "./call-hook-stations.js";
import { settleExecutionRecord } from "./execution-record.js";
import { holdPrompt } from "./prompt-block.js";
import { mintGateOutcome } from "./gate-exit.js";
import { withGateTimeout } from "../gate-bounded-await.js";
import { resolveGitLegDelivery, wrapGitFrame } from "./git-leg-delivery.js";
import { GIT_STATUS_ECHO_PREVIEW } from "./git-status-frame.js";
import { toImageContent } from "./image.js";
import { maybeHumanRejectionHalt } from "./prepare-gate-stations.js";
import { nextHumanInputSeq } from "./steer-admission.js";
import { settleTeardownLeg } from "./teardown-bounded.js";
import { toolEndBodyFrom, toolResultMsg } from "./tool-end-body.js";
import { announceListingTruncation } from "../skill-listing-budget.js";
import { attachmentEnvelopeTags, collectDateChange, commitAgentListing, commitSkillsListing, reduceToolEnd, renderAgentListingFrame, renderOrphanedBackgroundTasks, renderSkillsListingFrame, stampWriteAnchor } from "./turn-attachments.js";
import { flushOwedAnnouncedSnapshot } from "./announce-once-ledger.js";
import { asThrownError, thrownMarksOf, thrownText } from "../thrown-value.js";
import { ruleSourcePhrase } from "../rule-denial-sentence.js";
import { wireOf } from "../tool-name-readings.js";
export async function runLeg(input) {
const { spec, queue, prepared, resume, rs, isDelegatedChild, entryActor, effectiveTimeoutMs, timeout, pushContent, ident, emitCommitted, writeFamilyOf, startedToolCallIds, announceWorkspaceMove, withBrainSinks, flushGitMirror, loopLatch, notificationLane, unsubscribeTaskNotifications, unsubGitRetry, unsubBoundary, unsub, runner, next } = input;
let final;
let threw;
let abortedLive = false;
let userInterruptedLive = false;
let strandedHumanAnswers = [];
try {
if (prepared.abortController.signal.aborted) {
const e = new Error("run aborted");
e.name = "AbortError";
throw e;
}
if (resume) {
const walltimeExhaustedResume = effectiveTimeoutMs !== undefined && effectiveTimeoutMs <= 0;
const resumeWindowRetryAfterMs = !walltimeExhaustedResume && prepared.usageGovernance !== undefined ? await prepared.usageGovernance.check(Date.now()) : undefined;
if (resumeWindowRetryAfterMs !== undefined) {
const owesNothing = resume.outcome.gate === "resource_limit" &&
readPendingSteerQueue(resume.cp.state).length === 0 &&
(resume.cp.state.runningBackgroundTasks?.length ?? 0) === 0;
const committed = owesNothing &&
prepared.suspendForPlatformLimit !== undefined &&
(await prepared.suspendForPlatformLimit("usage_window", { costMicroUsd: 0, tokens: 0, turns: 0, walltimeMs: Math.round(performance.now() - rs.telemetry.taskStartMonotonic) }, { resumeAfterMs: resumeWindowRetryAfterMs }));
if (committed) {
rs.limits.turnsExceeded = false;
rs.limits.budgetHit = undefined;
}
else {
const terminal = platformLimitTerminal("usage_window", resumeWindowRetryAfterMs, "resume");
rs.limits.platformTerminal = terminal;
try {
runner.deps.onError?.(terminal, { phase: "config", sessionId: prepared.sessionId });
}
catch {
}
}
}
if (resumeWindowRetryAfterMs === undefined && !walltimeExhaustedResume && resume.outcome.gate !== "wake") {
await applyResumeDecision(runner, prepared, resume, (e) => pushContent({ ...e, ...ident() }), emitCommitted, (toolName, details) => {
if (rs.attach.attachState === undefined)
return;
const family = writeFamilyOf(toolName);
if (family !== undefined)
stampWriteAnchor(rs.attach.attachState, family, rs.counters.cadenceTurns);
if (details !== undefined)
reduceToolEnd(rs.attach.attachState, details);
}, (toolCallId) => {
startedToolCallIds.add(toolCallId);
if (resume !== undefined && resume.cp.pendingAction.kind === "tool_approval" && toolCallId === resume.cp.pendingAction.toolCallId) {
resume.pendingActionStarted = true;
}
});
if (resume.outcome.gate === "policy_ask")
resume.decisionDelivered = true;
announceWorkspaceMove();
}
if (resumeWindowRetryAfterMs !== undefined) {
}
else if (walltimeExhaustedResume) {
timeout.fired = true;
timeout.clear();
void prepared.harness.abort();
prepared.abortController.abort();
}
else if (rs.budget.maxTokensWindow !== undefined && rs.budget.maxTokensWindow <= 0) {
rs.limits.budgetHit = "exceeded";
rs.limits.budgetAxis = "tokens";
}
else if (rs.budget.maxCostMicroUsd !== undefined && rs.budget.maxCostMicroUsd <= 0) {
rs.limits.budgetHit = "exceeded";
rs.limits.budgetAxis = "cost";
}
else {
let continuation = resumeContinuation(resume, prepared.reminderMark, prepared.fullShellReachable);
const bgSnapshot = resume.cp.state.runningBackgroundTasks;
let orphanTasks = [];
if (bgSnapshot !== undefined && bgSnapshot.length > 0) {
const alive = new Set(prepared.listBackgroundTasks().map((t) => t.id));
orphanTasks = bgSnapshot.filter((t) => !alive.has(t.id));
if (orphanTasks.length > 0) {
continuation += "\n\n" + formatHookFeedback(renderOrphanedBackgroundTasks(orphanTasks), prepared.reminderMark);
}
}
let gitResumeDelivered;
{
const gitBody = await resolveGitLegDelivery(prepared, resume.cp.state.gitAnnouncement, (err) => {
try {
runner.deps.onError?.(new Error(`git announcement ladder unreadable (conservative re-announce): ${err.message}`), { phase: "degraded", sessionId: prepared.sessionId });
}
catch {
}
});
const gitFrame = prepared.gitStatusRef.frame;
if (gitBody !== undefined && gitFrame !== undefined) {
const wrappedGit = wrapGitFrame(gitBody, prepared.reminderMark);
continuation += "\n\n" + wrappedGit;
gitResumeDelivered = { kind: gitFrame.kind, hash: gitFrame.hash, wrapped: wrappedGit };
if (gitFrame.kind === "full" && gitFrame.shrunk !== undefined) {
prepared.gitStatusRef.wrappedShrink = { find: wrappedGit, replace: wrapGitFrame(gitFrame.shrunk.body, prepared.reminderMark) };
}
}
}
const postureText = await owedPostureText(prepared, "always");
if (postureText !== undefined)
continuation += "\n\n" + postureText;
const outputStyleWrapped = mintOutputStyleReminder(prepared);
if (outputStyleWrapped !== undefined)
continuation += "\n\n" + outputStyleWrapped;
const engineSegments = continuation.length > 0 ? [{ start: 0, end: continuation.length }] : [];
const parkedSteers = readPendingSteerQueue(resume.cp.state);
const resumeFrames = [
...parkedSteers.map((entry) => ({ entry, source: "steer" })),
...(resume.wakeMessage !== undefined ? [{ entry: resume.wakeMessage, source: "wake" }] : []),
];
const appliedEvents = [];
const withheldSteerIds = new Set();
for (const { entry: steer, source } of resumeFrames) {
if (source === "wake" && resume.wakeMessageHookContext !== undefined) {
const hookStart = continuation.length;
continuation += "\n\n" + formatHookFeedback(resume.wakeMessageHookContext, prepared.reminderMark);
engineSegments.push({ start: hookStart, end: continuation.length });
}
if (source === "steer") {
const parkedScreen = (spec.hooks ?? runner.deps.hooks)?.userPromptSubmit;
if (parkedScreen !== undefined) {
let outcome;
try {
const seat = await runHookSeat("userPromptSubmit", { timeoutMs: prepared.hookTimeoutMs, signal: prepared.abortController.signal, abortEnds: true }, (sig) => parkedScreen(steer.text, {
identity: prepared.hookIdentity, permissionMode: prepared.permissionMode.observed,
signal: sig,
source: "parked_redelivery",
...(steer.inputId !== undefined ? { inputId: steer.inputId } : {}),
...(steer.actor !== undefined ? { actor: snapshotActorAssertion(steer.actor) } : {}),
}));
outcome = seat.expired
? { blocked: seat.cause === "timeout" ? `the screen did not answer within its ${prepared.hookTimeoutMs}ms bound (fail-closed)` : "the run was cancelled while the screen was still deciding (fail-closed)" }
: seat.value?.block !== undefined && seat.value.block !== ""
? { blocked: inlineUntrusted(seat.value.block) }
: { ...(seat.value?.additionalContext !== undefined && seat.value.additionalContext !== "" ? { context: seat.value.additionalContext } : {}) };
}
catch (hookErr) {
const err = asThrownError(hookErr);
try {
runner.deps.onError?.(err, { phase: "hook", sessionId: prepared.sessionId });
}
catch {
}
outcome = { blocked: `the screen crashed (${inlineUntrusted(err.message)}; fail-closed)` };
}
if ("blocked" in outcome) {
if (steer.inputId !== undefined)
withheldSteerIds.add(steer.inputId);
deliverEngineNotice(runner.deps.onNotice, {
code: "steering.parked_input_blocked",
message: "a parked steering input was withheld by the deployment's userPromptSubmit screen when this resume redelivered it: " +
`${outcome.blocked}. The parked row was consumed with the checkpoint; the instruction never reached the model — ` +
"re-issue it if it still applies.",
detail: {
...(steer.inputId !== undefined ? { inputId: steer.inputId } : {}),
sessionId: prepared.sessionId,
runId: prepared.runId,
...(spec.taskId !== undefined ? { taskId: spec.taskId } : {}),
},
});
queue.push({
...buildHumanInputEvent({
carrier: source,
source,
delivery: "blocked",
sessionSeq: nextHumanInputSeq(prepared.harness),
...(steer.inputId !== undefined ? { inputId: steer.inputId } : {}),
...(steer.actor !== undefined ? { actor: steer.actor } : {}),
...(steer.actor?.issuer !== undefined ? { issuer: steer.actor.issuer } : {}),
...(spec.principal !== undefined ? { principal: spec.principal } : {}),
}),
...ident(),
});
continue;
}
if ("context" in outcome && outcome.context !== undefined) {
const hookStart = continuation.length;
continuation += "\n\n" + formatHookFeedback(outcome.context, prepared.reminderMark);
engineSegments.push({ start: hookStart, end: continuation.length });
}
}
}
const start = continuation.length;
const projected = projectHumanInput({ text: steer.text, actor: steer.actor, source });
continuation +=
"\n\n" +
(steer.trusted ? formatHookFeedback(projected, prepared.reminderMark) : delimitUntrusted("supervisor steering message", projected));
if (steer.trusted)
engineSegments.push({ start, end: continuation.length });
appliedEvents.push({
...buildAppliedHumanInputEvent({ carrier: source, source, sessionSeq: nextHumanInputSeq(prepared.harness), inputId: steer.inputId, actor: steer.actor, principal: spec.principal }),
...ident(),
});
}
const pending = resume.cp.pendingAction;
const rejectionHalt = pending.kind === "tool_approval" && resume.outcome.gate === "policy_ask"
? maybeHumanRejectionHalt({ gate: resume.outcome.gateOutcome, isDelegatedChild, toolName: pending.toolName, toolCallId: pending.toolCallId })
: undefined;
if (rejectionHalt !== undefined && pending.kind === "tool_approval")
prepared.batchHaltRef.current = { rejectedToolCallId: pending.toolCallId };
prepared.undeliveredContinuationRef.current = { parkedSteers: resumeFrames.map(({ entry }) => entry).filter((e) => !withheldSteerIds.has(e.inputId)), orphanTasks };
if (!prepared.abortController.signal.aborted) {
if (resume !== undefined)
resume.decisionDelivered = true;
if (gitResumeDelivered !== undefined) {
const delivered = gitResumeDelivered;
prepared.gitStatusRef.protectedText = delivered.wrapped;
prepared.frameReceipts.pending.push({
source: "git_status",
text: continuation,
commit: (entryId) => {
prepared.gitStatusRef.announced = { kind: delivered.kind, hash: delivered.hash, entryId };
queue.push({ type: "steering_injected", source: "git_status", preview: GIT_STATUS_ECHO_PREVIEW[delivered.kind], ...ident() });
rs.attach.attachmentsInjected += 1;
prepared.gitStatusRef.mirrorOwed = { kind: delivered.kind, hash: delivered.hash, entryId };
},
});
}
if (outputStyleWrapped !== undefined) {
const preview = redactThenCut(prepared.outputStyleFrame, 220);
prepared.frameReceipts.pending.push({ source: "output_style", text: continuation, commit: () => void (queue.push({ type: "steering_injected", source: "output_style", preview, ...ident() }), (rs.attach.attachmentsInjected += 1)) });
}
final = await withBrainSinks(() => prepared.harness.prompt(continuation, {
engineSegments,
settleUnansweredToolCalls: rejectionHalt !== undefined ? { halt: rejectionHalt } : {},
onDelivered: () => {
prepared.undeliveredContinuationRef.current = { parkedSteers: [], orphanTasks: [] };
for (const e of appliedEvents)
queue.push(e);
},
}));
await flushGitMirror();
if (prepared.gitStatusRef.announced?.pending === true)
await prepared.gitStatusRef.reassert?.();
}
}
}
else {
const objectiveActor = entryActor;
const projectedObjective = projectHumanInput({ text: spec.objective, actor: objectiveActor, source: "objective" });
let effectiveObjective = projectedObjective;
let promptBlocked = false;
const userPromptSubmit = (spec.hooks ?? runner.deps.hooks)?.userPromptSubmit;
if (userPromptSubmit) {
try {
const promptSeat = await runHookSeat("userPromptSubmit", { timeoutMs: prepared.hookTimeoutMs, signal: prepared.abortController.signal, abortEnds: true }, (sig) => userPromptSubmit(spec.objective, { identity: prepared.hookIdentity, permissionMode: prepared.permissionMode.observed, signal: sig, source: "objective", ...(objectiveActor !== undefined ? { actor: snapshotActorAssertion(objectiveActor) } : {}) }));
if (promptSeat.expired) {
if (promptSeat.cause === "timeout") {
try {
runner.deps.onError?.(hookSeatExpiredError("userPromptSubmit", prepared.hookTimeoutMs, promptSeat.cause, "the prompt was NOT submitted (fail-closed) and the task ends blocked"), { phase: "hook", sessionId: prepared.sessionId });
}
catch {
}
}
const timedOut = promptSeat.cause === "timeout";
holdPrompt(prepared.blockedRef, prepared.reminderMark, timedOut ? "timeout" : "cancelled", timedOut
? `the deployment's userPromptSubmit hook did not answer within its ${prepared.hookTimeoutMs}ms bound while screening this prompt; ` +
`the prompt was NOT submitted (fail-closed)`
: `the task was cancelled while the deployment's userPromptSubmit hook was still screening this prompt; ` +
`the prompt was NOT submitted (fail-closed)`);
promptBlocked = true;
}
const decision = promptSeat.expired ? undefined : promptSeat.value;
const blockWords = decision?.block;
if (blockWords) {
holdPrompt(prepared.blockedRef, prepared.reminderMark, "block", blockWords);
promptBlocked = true;
}
else if (decision?.additionalContext) {
effectiveObjective = `${formatHookFeedback(decision.additionalContext, prepared.reminderMark)}\n\n${projectedObjective}`;
}
}
catch (hookErr) {
const err = asThrownError(hookErr);
try {
runner.deps.onError?.(err, { phase: "hook", sessionId: prepared.sessionId });
}
catch {
}
holdPrompt(prepared.blockedRef, prepared.reminderMark, "crashed", `the deployment's userPromptSubmit hook crashed while screening this prompt (${err.message}); ` + `the prompt was NOT submitted (fail-closed)`);
promptBlocked = true;
}
}
let gitLegDelivered;
if (!promptBlocked) {
const gitBody = await resolveGitLegDelivery(prepared, undefined, (err) => {
try {
runner.deps.onError?.(new Error(`git announcement ladder unreadable (conservative re-announce): ${err.message}`), { phase: "degraded", sessionId: prepared.sessionId });
}
catch {
}
});
const gitFrame = prepared.gitStatusRef.frame;
if (gitBody !== undefined && gitFrame !== undefined) {
const wrappedGit = wrapGitFrame(gitBody, prepared.reminderMark);
const standalone = spec.images !== undefined && spec.images.length > 0;
if (!standalone)
effectiveObjective = `${wrappedGit}\n${effectiveObjective}`;
gitLegDelivered = { kind: gitFrame.kind, hash: gitFrame.hash, standalone, wrapped: wrappedGit };
if (gitFrame.kind === "full" && gitFrame.shrunk !== undefined) {
prepared.gitStatusRef.wrappedShrink = { find: wrappedGit, replace: wrapGitFrame(gitFrame.shrunk.body, prepared.reminderMark) };
}
}
}
const firstFrames = [];
const legToday = rs.attach.dateState !== undefined ? prepared.dateChange.today() : undefined;
const dateFrame = legToday !== undefined ? collectDateChange(rs.attach.dateState, legToday) : undefined;
if (dateFrame !== undefined)
firstFrames.push({ source: "date_change", body: dateFrame.body, commit: () => void (rs.attach.dateState.announcedDate = legToday), disclose: () => undefined });
if (rs.attach.attachState !== undefined) {
const attach = rs.attach.attachState;
if (rs.attach.agentListingOn && prepared.agentListing !== undefined) {
const listing = prepared.agentListing;
const frame = renderAgentListingFrame(attach, listing.entries, listing.toolName, listing.models, listing.budget);
if (frame !== undefined) {
firstFrames.push({
source: "agent_listing",
body: frame.text,
commit: () => {
commitAgentListing(attach, listing.entries, listing.models);
prepared.frameReceipts.listingSnapshotOwed = true;
prepared.announcedListingsRef.agents = listing.entries.map((e) => e.name);
if (listing.models !== undefined)
prepared.announcedListingsRef.models = [...listing.models];
},
disclose: () => announceListingTruncation(runner.deps.onNotice, { listing: "agents", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId }),
});
}
}
if (rs.attach.skillsListingOn && prepared.skillsListing !== undefined) {
const listing = prepared.skillsListing;
const frame = renderSkillsListingFrame(attach, listing.entries, listing.budget);
if (frame !== undefined) {
firstFrames.push({
source: "skills_listing",
body: frame.text,
commit: () => {
commitSkillsListing(attach, listing.entries);
prepared.frameReceipts.listingSnapshotOwed = true;
prepared.announcedListingsRef.skills = listing.entries.map((e) => e.name);
},
disclose: () => announceListingTruncation(runner.deps.onNotice, { listing: "skills", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId }),
});
}
}
}
if (prepared.outputStyleFrame !== undefined)
firstFrames.push({ source: "output_style", body: prepared.outputStyleFrame, commit: () => undefined, disclose: () => undefined });
if (firstFrames.length > 0) {
effectiveObjective = `${firstFrames.map((f) => mintSystemReminder(sanitizeUntrustedText(f.body, attachmentEnvelopeTags(f.source)), prepared.reminderMark)).join("\n")}\n${effectiveObjective}`;
}
const postureText = await owedPostureText(prepared, "always");
if (postureText !== undefined)
effectiveObjective = `${postureText}\n${effectiveObjective}`;
const gitQueuedChars = gitLegDelivered !== undefined && gitLegDelivered.standalone ? gitLegDelivered.wrapped.length : 0;
const precallMicroUsd = rs.budget.maxCostMicroUsd === undefined
? 0
: computeCostMicroUsd({
totalInputTokens: Math.ceil((effectiveObjective.length + gitQueuedChars) / 4),
cacheReadTokens: 0,
cacheWriteTokens: 0,
cacheWriteTokensLong: 0,
outputTokens: prepared.model.maxTokens ?? DEFAULT_PRECALL_OUTPUT_TOKENS,
}, rs.telemetry.pricing);
const precallCeilingMicroUsd = prepared.suspendForResource !== undefined ? rs.budget.remainingMicroUsd : rs.budget.maxCostMicroUsd;
const precallTokens = Math.ceil((effectiveObjective.length + gitQueuedChars) / 4) + (prepared.model.maxTokens ?? DEFAULT_PRECALL_OUTPUT_TOKENS);
const precallCeilingTokens = prepared.suspendForResource !== undefined ? rs.budget.remainingTokens : rs.budget.maxTokensWindow;
const entryUsageRetryAfterMs = prepared.usageGovernance !== undefined ? await prepared.usageGovernance.check(Date.now()) : undefined;
if (promptBlocked) {
}
else if (entryUsageRetryAfterMs !== undefined) {
const terminal = platformLimitTerminal("usage_window", entryUsageRetryAfterMs, "entry");
rs.limits.platformTerminal = terminal;
try {
runner.deps.onError?.(terminal, { phase: "config", sessionId: prepared.sessionId });
}
catch {
}
}
else if (precallCeilingTokens !== undefined && precallTokens > precallCeilingTokens) {
rs.limits.budgetHit = "precall";
rs.limits.budgetAxis = "tokens";
}
else if (precallCeilingMicroUsd !== undefined && precallMicroUsd > precallCeilingMicroUsd) {
rs.limits.budgetHit = "precall";
rs.limits.budgetAxis = "cost";
}
else if (effectiveTimeoutMs !== undefined && effectiveTimeoutMs <= 0) {
timeout.fired = true;
timeout.clear();
void prepared.harness.abort();
prepared.abortController.abort();
}
else {
const images = spec.images
? await Promise.all(spec.images.map((img) => toImageContent(img, runner.deps.allowImageUrl)))
: undefined;
if (gitLegDelivered !== undefined) {
const delivered = gitLegDelivered;
if (delivered.standalone)
await prepared.harness.nextTurn(delivered.wrapped, { engineMinted: true });
prepared.gitStatusRef.protectedText = delivered.wrapped;
prepared.frameReceipts.pending.push({
source: "git_status",
text: delivered.standalone ? delivered.wrapped : effectiveObjective,
commit: (entryId) => {
prepared.gitStatusRef.announced = { kind: delivered.kind, hash: delivered.hash, entryId };
queue.push({ type: "steering_injected", source: "git_status", preview: GIT_STATUS_ECHO_PREVIEW[delivered.kind], ...ident() });
rs.attach.attachmentsInjected += 1;
prepared.gitStatusRef.mirrorOwed = { kind: delivered.kind, hash: delivered.hash, entryId };
},
});
}
for (const f of firstFrames) {
prepared.frameReceipts.pending.push({
source: f.source,
text: effectiveObjective,
commit: () => {
f.commit();
queue.push({ type: "steering_injected", source: f.source, preview: redactThenCut(f.body, 220), ...ident() });
rs.attach.attachmentsInjected += 1;
f.disclose();
},
});
}
const enginePrefixChars = effectiveObjective.length - projectedObjective.length;
if (!prepared.abortController.signal.aborted) {
queue.push({
...buildHumanInputEvent({
carrier: "objective",
source: "objective",
delivery: "applied",
sessionSeq: nextHumanInputSeq(prepared.harness),
...(objectiveActor !== undefined ? { actor: objectiveActor } : {}),
...(objectiveActor?.issuer !== undefined ? { issuer: objectiveActor.issuer } : {}),
...(spec.principal !== undefined ? { principal: spec.principal } : {}),
}),
...ident(),
});
final = await withBrainSinks(() => prepared.harness.prompt(effectiveObjective, {
...(images && images.length > 0 ? { images } : {}),
...(enginePrefixChars > 0 ? { enginePrefixChars } : {}),
...(objectiveActor !== undefined ? { actor: objectiveActor } : {}),
}));
await flushGitMirror();
if (prepared.gitStatusRef.announced?.pending === true)
await prepared.gitStatusRef.reassert?.();
}
}
}
loopLatch.ended = true;
abortedLive = prepared.abortController.signal.aborted;
userInterruptedLive = loopLatch.userInterrupted;
}
catch (err) {
loopLatch.ended = true;
if (errorCodeOf(err) === "resume.tool_unavailable" || errorCodeOf(err) === "resume.tool_contract_mismatch") {
await settleTeardownLeg(() => prepared.mcp.dispose(), "mcp.dispose (tool_unavailable leg)", (e) => runner.deps.onError?.(e, { phase: "config", sessionId: prepared.sessionId }));
await settleTeardownLeg(() => prepared.a2a?.dispose(), "a2a.dispose (tool_unavailable leg)", (e) => runner.deps.onError?.(e, { phase: "config", sessionId: prepared.sessionId }));
await settleTeardownLeg(() => (prepared.ownedEnv && hasDestroy(prepared.ownedEnv) ? prepared.ownedEnv.destroy() : undefined), "ownedEnv.destroy (tool_unavailable leg)", (e) => runner.deps.onError?.(e, { phase: "config", sessionId: prepared.sessionId }));
throw err;
}
threw = err;
abortedLive = prepared.abortController.signal.aborted;
userInterruptedLive = loopLatch.userInterrupted;
}
finally {
timeout.clear();
prepared.lspDiagnostics?.registry.releaseRun(prepared.lspDiagnostics.runIdent);
prepared.toolProgressRef.current?.clear();
if (prepared.frameReceipts.listingSnapshotOwed) {
await settleTeardownLeg(() => flushOwedAnnouncedSnapshot(prepared), "announced-listing snapshot (leg exit)", (e) => runner.deps.onError?.(e, { phase: "degraded", sessionId: prepared.sessionId }));
}
prepared.abortController.abort();
prepared.releaseSignal();
prepared.endModeCeiling();
strandedHumanAnswers = prepared.settleContentAskBindings();
try {
prepared.harness.recoverUndrainedEngineNotes();
}
catch {
}
notificationLane.live = false;
unsubscribeTaskNotifications();
prepared.toolRosterDeltas.unsubscribe();
prepared.toolDisclosure?.unsubscribe();
unsubGitRetry();
unsubBoundary();
unsub();
}
return await next({ final, threw, abortedLive, userInterruptedLive, strandedHumanAnswers });
}
const ORG_DISCLOSURE_MAX_CHARS = 600;
async function applyResumeDecision(runner, prepared, resume, emit, emitCommitted, onResolvedToolSuccess, onExecuteStart) {
const { pendingAction } = resume.cp;
if (resume.outcome.gate === "dry_run_review")
return;
if (resume.outcome.gate === "plan_review")
return;
if (pendingAction.kind !== "tool_approval")
return;
if (resume.outcome.gate === "policy_ask" &&
resume.outcome.decision === "allow" &&
!prepared.tools.some((t) => t.name === pendingAction.toolName)) {
const e = new Error(`the approved tool "${pendingAction.toolName}" is no longer available on resume — refusing to continue as if it ran; the checkpoint is reopened for a retry with the tool present`);
e.code = "resume.tool_unavailable";
throw e;
}
const liveRoster = prepared.toolRosterDeltas.current;
if (pendingAction.kind === "tool_approval" && liveRoster !== undefined && judgeParkedToolIdentity(pendingAction, rosterEntryNamed(liveRoster, pendingAction.toolName)) === "mismatch") {
const e = new Error(`the approved tool "${pendingAction.toolName}" on this leg is not the tool the approval was minted against (its contract / shape / revision differ) — refusing to execute a replacement wearing the name; the checkpoint is reopened for a retry with the original tool present`);
e.code = "resume.tool_contract_mismatch";
throw e;
}
await resolvePendingCall(runner, prepared, resume, emit, emitCommitted, onResolvedToolSuccess, onExecuteStart);
}
async function resolvePendingCall(runner, prepared, resume, emit, emitCommitted, onResolvedToolSuccess, onExecuteStart) {
const { pendingAction } = resume.cp;
const { outcome } = resume;
if (pendingAction.kind !== "tool_approval" || outcome.gate !== "policy_ask")
return;
const decidedGate = outcome.gateOutcome;
if (decidedGate === undefined) {
throw new CheckpointError("checkpoint.invalid_outcome", "pending action reached the resolver with no settlement record on its decision (gateOutcome) — refusing to execute or settle a decision that carries no record");
}
const humanRewrite = wireOf("resume.questionArgsShown", pendingAction) === ASK_USER_QUESTION_TOOL_NAME ? undefined : outcome.updatedInput;
const resolvedArgs = humanRewrite !== undefined ? humanRewrite : pendingAction.args;
const pendingLabel = (() => { const l = prepared.tools.find((t) => t.name === pendingAction.toolName)?.label; return l !== undefined && l !== pendingAction.toolName ? { label: l } : {}; })();
const spelledName = pendingAction.names?.[0] ?? pendingAction.toolName;
emit({ type: "tool_start", toolCallId: pendingAction.toolCallId, toolName: spelledName, ...pendingLabel, args: resolvedArgs });
const settleEnd = async (isError, result, gate = decidedGate) => {
prepared.toolProgressRef.current?.noteEnd(pendingAction.toolCallId);
emit({ type: "tool_end", toolCallId: pendingAction.toolCallId, toolName: spelledName, ...pendingLabel, isError, ...toolEndBodyFrom(result, isError, prepared.structuredProjector, gate) });
const word = await resume.recordExecutionOutcome(gate);
settleExecutionRecord(runner.deps.onNotice, word, { toolName: pendingAction.toolName, gate, sessionId: prepared.sessionId, runId: prepared.runId, scope: resume.cp.scope, ...(resume.cp.checkpointId !== undefined ? { checkpointId: resume.cp.checkpointId } : {}) });
};
const vetoed = (layer) => mintGateOutcome({
deniedBy: layer,
...(outcome.gateOutcome?.settlement !== undefined && outcome.gateOutcome.origin !== undefined ? { settled: { settlement: outcome.gateOutcome.settlement, origin: outcome.gateOutcome.origin } } : {}),
});
if (outcome.decision === "deny") {
const settlementKind = outcome.gateOutcome?.settlement?.kind;
const defaultDenial = settlementKind === "park_sla_expired"
? `No one answered the approval request for the pending tool call "${pendingAction.toolName}" — the approval window elapsed with no answer, so it was not executed.`
: `The pending tool call "${pendingAction.toolName}" was denied by an approver.`;
const reason = settlementKind === "policy_refused"
? policyRefusalMessage(pendingAction.toolName, undefined, decidersNote(outcome.reason))
: outcome.reason
? delimitUntrusted("reviewer note", outcome.reason, REVIEWER_NOTE_MAX_BODY)
: defaultDenial;
await settleEnd(true, { content: formatHookFeedback(reason, prepared.reminderMark) });
const eid = await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, formatHookFeedback(reason, prepared.reminderMark), true));
emitCommitted(eid, "toolResult", pendingAction.toolCallId);
const parkedFallback = pendingAction.denialLimitFallback;
if (parkedFallback !== undefined && settlementKind !== undefined && SETTLEMENT_NOBODY_JUDGED[settlementKind]) {
prepared.stopForDenialLimit({ toolName: pendingAction.toolName, toolCallId: pendingAction.toolCallId, fallback: parkedFallback, settlement: settlementKind });
}
return;
}
if (outcome.decision !== "allow") {
throw new CheckpointError("checkpoint.invalid_outcome", `pending action reached the resolver with decision "${String(outcome.decision)}" — only "allow" executes and only "deny" injects a denial; refusing to execute`);
}
const screened = await prepared.approvedCallScreen?.({ toolCallId: pendingAction.toolCallId, toolName: pendingAction.toolName, args: structuredClone(resolvedArgs), decidedBy: outcome.hostDecision.decidedBy });
if (screened !== undefined && "refused" in screened) {
const hookDenial = formatHookFeedback(screened.refused, prepared.reminderMark);
await settleEnd(true, { content: hookDenial }, vetoed("hook"));
emitCommitted(await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, hookDenial, true)), "toolResult", pendingAction.toolCallId);
return;
}
const executedArgs = humanRewrite !== undefined ? resolvedArgs : screened !== undefined ? screened.args : resolvedArgs;
const unseen = !deepJsonEqual(executedArgs, pendingAction.args);
const beltReq = () => ({ toolName: pendingAction.toolName, args: executedArgs, toolCallId: pendingAction.toolCallId, ...callFaceSeat(parkedRowLiveFace(prepared.toolRosterDeltas.current, pendingAction)), budget: beltBudget, ...(prepared.cwdRef !== undefined ? { cwd: prepared.cwdRef.current } : {}), ...advertisedWritableRootsSeat(prepared.advertisedWritableDirs) });
const unjudgeable = unseen ? chainCannotJudge(resume.cp.state.inheritedGate) : undefined;
if (unjudgeable !== undefined) {
const chainDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: its input changed after the approval and the inherited ancestor chain cannot judge the changed input (${unjudgeable}). This approval is spent — the call has to be re-issued.`, prepared.reminderMark);
await settleEnd(true, { content: chainDenial }, vetoed("policy"));
emitCommitted(await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, chainDenial, true)), "toolResult", pendingAction.toolCallId);
return;
}
const beltBudget = {
resourceRemainingMicroUsd: remainingBudgetMicroUsd(prepared.resourceLedger),
resourceSpentMicroUsd: prepared.resourceLedger?.spentMicroUsd ?? 0,
suspendCount: resume.cp.suspendCount ?? 0,
};
if (unseen && prepared.basePolicyForResumeEdit) {
const rechecked = refuseOutOfContractDecision(await prepared.basePolicyForResumeEdit.check(beltReq(), prepared.abortController.signal));
const personUnanswered = policyCannotAnswer(rechecked, outcome.hostDecision.decidedBy);
const beltUnsafe = rechecked.action === "deny" ||
(rechecked.updatedInput !== undefined && !deepJsonEqual(rechecked.updatedInput, executedArgs)) ||
personUnanswered;
if (beltUnsafe) {
const why = rechecked.action === "deny"
? (rechecked.message ? `: ${rechecked.message}` : "")
: personUnanswered
? " (the call as it would run requires a person's approval, and this decision was the deployment's policy)"
: " (the policy rewrote these bytes to a value that was not approved)";
const editedDenial = formatHookFeedback(`${outcome.updatedInput !== undefined ? "The approver EDITED this call's input; the edited call" : "A PreToolUse hook REWROTE this approved call's input; the rewritten call"} is refused by the deployment's tool policy and was not executed${why}.`, prepared.reminderMark);
await settleEnd(true, { content: editedDenial }, vetoed("policy"));
const eid = await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, editedDenial, true));
emitCommitted(eid, "toolResult", pendingAction.toolCallId);
return;
}
}
const gateRealApproval = resume.cp.gate.kind === "irreversible_ask" ? resume.cp.gate.realApproval : undefined;
const gateOrgGoverned = realApprovalOrgFact(gateRealApproval) !== undefined;
if (gateOrgGoverned && prepared.permissionRuleOrg === undefined) {
const unwiredDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: its approval was minted under organization governance (${gateRealApproval.origin}), and this worker has no org adjudication wiring — a governed approval may only be redeemed where governance can be enforced. This approval is spent; re-issue the call on an org-wired worker.`, prepared.reminderMark);
await settleEnd(true, { content: unwiredDenial }, vetoed("org"));
const eid = await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, unwiredDenial, true));
emitCommitted(eid, "toolResult", pendingAction.toolCallId);
return;
}
if (prepared.permissionRuleOrg !== undefined) {
const orgVerdict = prepared.permissionRuleOrg
.adjudicate({ toolName: pendingAction.toolName, args: executedArgs, toolCallId: pendingAction.toolCallId, ...callFaceSeat(parkedRowLiveFace(prepared.toolRosterDeltas.current, pendingAction)) })
.catch(() => ({ status: "unavailable", disclosures: ["the org adjudication face threw on resume"] }));
let orgWaitCancelled = false;
const org = await settleOrgVerdictWithin(orgVerdict, { status: "unavailable", disclosures: [`the org adjudication face did not answer within ${ORG_ADJUDICATION_TIMEOUT_MS}ms (or the task ended first)`] }, {
signal: prepared.abortController.signal,
timeoutMs: ORG_ADJUDICATION_TIMEOUT_MS,
onFallback: (cause) => {
orgWaitCancelled = cause === "aborted";
},
});
const unanswered = policyCannotAnswer(org, outcome.hostDecision.decidedBy);
const blocked = org.status === "unavailable"
? realApprovalOrgFact(gateRealApproval) === "unavailable"
? undefined
: orgWaitCancelled
? "this deployment is org-governed and the task was cancelled before the organization policy snapshot could be adjudicated"
: "this deployment is org-governed and cannot currently adjudicate against an organization policy snapshot"
: org.verdict?.behavior === "deny"
? `an organization policy rule (${org.verdict.rule}) denies it`
: unanswered
? `an organization policy rule (${org.verdict?.rule})${org.verdict?.unreadable !== undefined ? ` may reach this call, which could not be read against it (${org.verdict.unreadable}), so it` : ""} requires a person's approval for this call, and the decision recorded for it was the deployment's policy, not a person's`
: undefined;
if (blocked !== undefined) {
const orgDisclosures = org.status === "unavailable" && org.disclosures.length > 0
? ` Governance disclosures: ${inlineUntrusted(org.disclosures.join("; "), ORG_DISCLOSURE_MAX_CHARS)}.`
: "";
const orgDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: ${blocked}.${orgDisclosures} This approval is spent — the call has to be re-issued and ${unanswered ? "decided by a person" : "approved again once organization policy permits it"}.`, prepared.reminderMark);
await settleEnd(true, { content: orgDenial }, vetoed("org"));
const eid = await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, orgDenial, true));
emitCommitted(eid, "toolResult", pendingAction.toolCallId);
return;
}
}
if (prepared.denyNarrowingPolicy) {
const narrowed = refuseOutOfContractDecision(await prepared.denyNarrowingPolicy.check(beltReq(), prepared.abortController.signal));
if (narrowed.action === "deny") {
const narrowedDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" is now denied by ${ruleSourcePhrase("narrowing")} and was not executed${narrowed.message ? `: ${narrowed.message}` : ""}.`, prepared.reminderMark);
await settleEnd(true, { content: narrowedDenial }, vetoed("policy"));
const eid = await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, narrowedDenial, true));
emitCommitted(eid, "toolResult", pendingAction.toolCallId);
return;
}
}
const skillRefusal = skillRowRefusal(prepared.skillGrants, beltReq());
if (skillRefusal !== undefined) {
const skillDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: ${skillRefusal.message}. This approval is spent — the call has to be re-issued.`, prepared.reminderMark);
await settleEnd(true, { content: skillDenial }, vetoed("policy"));
emitCommitted(await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, skillDenial, true)), "toolResult", pendingAction.toolCallId);
return;
}
if (prepared.persistedRuleLane !== undefined) {
const unreadable = { unreadable: true };
let laneWaitCancelled = false;
let laneRead;
try {
laneRead = Promise.resolve(prepared.persistedRuleLane.adjudicate(beltReq())).then((answer) => normalizePersistedRuleHit(answer));
}
catch {
laneRead = Promise.resolve(unreadable);
}
const read = await settleOrgVerdictWithin(laneRead, unreadable, { signal: prepared.abortController.signal, timeoutMs: ORG_ADJUDICATION_TIMEOUT_MS, onFallback: (cause) => void (laneWaitCancelled = cause === "aborted") });
const tightened = applyPersistedTightening({ action: "allow" }, read);
if (laneWaitCancelled || tightened.tightened === "deny" || tightened.tightened === "unreadable") {
const why = laneWaitCancelled
? "the task was cancelled before your persisted permission rules could be read"
: tightened.tightened === "deny"
? `a standing deny rule of yours (${disclosedRuleSet(read.hit?.rules ?? [])}) now refuses it`
: `it could not be read against your standing deny/ask rules (${read.reason})`;
const ruleDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: ${why}. This approval is spent — the call has to be re-issued and approved again.`, prepared.reminderMark);
await settleEnd(true, { content: ruleDenial }, vetoed("persisted_rule"));
const eid = await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, ruleDenial, true));
emitCommitted(eid, "toolResult", pendingAction.toolCallId);
return;
}
}
if (prepared.shellReadCheck !== undefined) {
const readCall = { toolName: pendingAction.toolName, ...callFaceSeat(parkedRowLiveFace(prepared.toolRosterDeltas.current, pendingAction)) };
const judged = prepared.shellReadCheck.judge(readCall, executedArgs, prepared.cwdRef?.current, prepared.abortController.signal, {
toolCallId: pendingAction.toolCallId,
...(unseen ? { seat: "rejudge" } : {}),
});
if (judged !== null) {
let verdict;
let answered = true;
try {
verdict = await withGateTimeout(judged, ORG_ADJUDICATION_TIMEOUT_MS, prepared.abortController.signal, "shellReadStation");
}
catch {
answered = false;
verdict = prepared.shellReadCheck.unanswered(readCall, "the read station could not answer on the resumed leg");
}
if (!answered || verdict.disposition === "refuse" || (unseen && verdict.disposition !== "vouch")) {
const readDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: ${verdict.sentence ?? "the read boundary does not vouch for what it reads on this leg"} This approval is spent — the call has to be re-issued and approved again.`, prepared.reminderMark);
await settleEnd(true, { content: readDenial, ...(verdict.details !== undefined ? { details: verdict.details } : {}) }, vetoed("read_boundary"));
const eid = await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, readDenial, true));
emitCommitted(eid, "toolResult", pendingAction.toolCallId);
return;
}
verdict.admit?.();
}
}
const grantRefusal = parkedSkillApprovalRefusal(pendingAction, executedArgs, prepared.skillSpecs, SKILL_TOOL_NAME, "execution");
if (grantRefusal !== undefined) {
const grantDenial = formatHookFeedback(grantRefusal, prepared.reminderMark);
await settleEnd(true, { content: grantDenial }, vetoed("policy"));
emitCommitted(await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, grantDenial, true)), "toolResult", pendingAction.toolCallId);
return;
}
const tool = prepared.tools.find((t) => t.name === pendingAction.toolName);
if (!tool) {
const e = new Error(`the approved tool "${pendingAction.toolName}" is no longer available on resume`);
e.code = "resume.tool_unavailable";
throw e;
}
const args = executedArgs;
screened?.admit();
onExecuteStart?.(pendingAction.toolCallId);
prepared.toolProgressRef.current?.noteStart(pendingAction.toolCallId, pendingAction.toolName);
prepared.suspendProgressRef.executedApproved = true;
const finalize = (executed) => prepared.harness.finalizeToolCall({ type: "toolCall", id: pendingAction.toolCallId, name: spelledName, arguments: executedArgs }, executedArgs, executed);
let res;
try {
res = await tool.execute(pendingAction.toolCallId, args, prepared.abortController.signal);
}
catch (err) {
const execError = `Error: ${thrownText(err)}`;
const marks = thrownMarksOf(err);
const failed = await finalize({ result: { content: [{ type: "text", text: execError }], details: marks ?? {} }, isError: true });
const failedText = failed.result.content.flatMap((c) => (c.type === "text" ? [c.text] : [])).join("\n");
await settleEnd(true, { content: failedText, ...(marks !== undefined ? { details: marks } : {}) });
const eid = await prepared.session.appendMessage(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, failedText, true));
emitCommitted(eid, "toolResult", pendingAction.toolCallId);
return;
}
const ran = await finalize({ result: res, isError: res.isError === true });
await settleEnd(ran.isError, ran.result);
onResolvedToolSuccess?.(pendingAction.toolName, ran.isError ? undefined : ran.result.details);
const eid = await prepared.session.appendMessage({
role: "toolResult",
toolCallId: pendingAction.toolCallId,
toolName: pendingAction.toolName,
content: ran.result.content,
details: ran.result.details,
isError: ran.isError,
timestamp: Date.now(),
});
emitCommitted(eid, "toolResult", pendingAction.toolCallId);
}