UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

141 lines (140 loc) • 8.32 kB
import { checkpointRevOf } from "./checkpoint-generation.js"; import { corruptSessionWayOutSentence, isCorruptSessionForm } from "../internal/harness.js"; import { parkNounOf } from "./park-noun.js"; import { isDeploymentEnvCode } from "./remote-env.js"; import { egressThrownText } from "./untrusted-egress.js"; export const REOPEN_REASONS = Object.freeze(["env_failed", "tool_unavailable", "constraint_rejected", "config_refused"]); export const RESUME_STARTUP_CAUSES = Object.freeze(["environment", "session_gone", "transcript_corrupt", "tool_unavailable", "configuration", "decision_rejected", "superseded"]); const CAUSE_OF_CODE = new Map([ ["resume.env_failed", "environment"], ["checkpoint.resume_aborted", "environment"], ["resume.session_not_found", "session_gone"], ["corrupt_session", "transcript_corrupt"], ["invalid_session", "transcript_corrupt"], ["resume.tool_unavailable", "tool_unavailable"], ["resume.tool_contract_mismatch", "tool_unavailable"], ["checkpoint.config_refused", "configuration"], ["resume.parent_constraint_missing", "configuration"], ["resume.parent_constraint_mismatch", "configuration"], ["resume.parent_constraint_unrebuildable", "configuration"], ["revive.policy_floor_unreadable", "configuration"], ["resume.agent_definition_mismatch", "configuration"], ["checkpoint.gate_mismatch", "decision_rejected"], ["checkpoint.invalid_outcome", "decision_rejected"], ["resume.constraint_rejected", "decision_rejected"], ["resume.constraint_unprojectable", "decision_rejected"], ["holder.superseded", "superseded"], ["holder.malformed", "configuration"], ["env.lifetime_expired", "environment"], ]); export function resumeStartupCauseOf(code, refusal) { if (code === undefined) return undefined; if (code === "checkpoint.invalid_outcome" && refusal?.reason !== undefined) return undefined; return CAUSE_OF_CODE.get(code) ?? (code.startsWith("config.") || isDeploymentEnvCode(code) ? "configuration" : code.startsWith("env.") ? "environment" : undefined); } export const RESUME_REFUSAL_MEMBERS = Object.freeze(["code", "field", "reason", "form"]); export function resumeRefusalDetailOf(account) { if (account === undefined || account.kind !== "coded") return undefined; const out = {}; for (const member of RESUME_REFUSAL_MEMBERS) { const value = Object.hasOwn(account.detail, member) ? account.detail[member] : undefined; if (member === "form" ? isCorruptSessionForm(value) : typeof value === "string") out[member] = value; } return Object.keys(out).length > 0 ? out : undefined; } const REOPEN_REASON_OF_CAUSE = { environment: "env_failed", session_gone: "env_failed", transcript_corrupt: "env_failed", tool_unavailable: "tool_unavailable", configuration: "config_refused", decision_rejected: "constraint_rejected", superseded: "env_failed", }; export function reopenReasonOf(cause) { return cause === undefined ? "env_failed" : REOPEN_REASON_OF_CAUSE[cause]; } const RESUME_AGAIN_MAY_CURE = { environment: true, session_gone: false, transcript_corrupt: false, tool_unavailable: false, configuration: false, decision_rejected: false, superseded: undefined, }; export function resumeAgainMayCure(cause) { return cause === undefined ? true : RESUME_AGAIN_MAY_CURE[cause]; } export function unstartedFailureOf(code, account, sessions, resume) { const form = resumeRefusalDetailOf(account)?.form; const replays = resume !== undefined && (resume.decisionDelivered === true || resume.cp.reopenReason === "env_failed"); const cause = replays && isDeploymentEnvCode(code) ? "environment" : resumeStartupCauseOf(code); return { cause, ...(isCorruptSessionForm(form) ? { form } : {}), sessions }; } export async function compensateUnstarted(reopen, reason, claimedRowPending) { try { return (await reopen(reason)) === "reopened" ? { kind: "reopened", reason } : { kind: "declined" }; } catch (thrown) { const landed = await claimedRowPending().then((pending) => pending, () => false); return landed ? { kind: "reopened", reason } : { kind: "unknown", thrown }; } } export function rowKeepsWhatItsRetryNeeds(row) { return row === "reopened" || row === "unknown"; } export function claimedRowPendingOf(store, token, claimed) { const claimedRev = checkpointRevOf(claimed); return async () => { const row = await store.get(token); return row !== null && row.status === "pending" && checkpointRevOf(row) > claimedRev; }; } export function unstartedRowSentence(row, parked, failure) { const noun = parkNounOf(parked); const fact = unstartedRowFact(row, noun); if (failure !== undefined && failure.cause !== undefined && resumeAgainMayCure(failure.cause) === undefined) return `${fact}. This run's grant is no longer current, so the next step on it is not this run's (no second resume, no fresh ${noun.grant}, no expire): where it stands now is for the run's current holder`; switch (row.kind) { case "reopened": return reopenedUnstartedSentence(fact, row.reason, noun, failure); case "declined": return `${fact}. Check where it stands now before deciding anything: if it is waiting again, ${noun.again}; if it is gone or already used, carrying on needs a fresh ${noun.grant}`; case "unknown": return `${fact}. Check where it stands before deciding anything, and do not ask for a fresh ${noun.grant} until that is known: the old one may still be usable`; } } function unstartedRowFact(row, noun) { switch (row.kind) { case "reopened": return `${noun.started} never started, so the checkpoint was REOPENED (pending)`; case "declined": return `${noun.started} never started, and ${noun.waiting} could not be put back to waiting: it is no longer the one this resume took (it is gone, has expired, was already used, or is waiting again)`; case "unknown": return `${noun.started} never started, and putting ${noun.waiting} back to waiting failed partway (${egressThrownText("same-principal", row.thrown)}), so it is not known whether it is waiting now`; } } const UNCURED_RETRY_SENTENCE = { session_gone: (lead, noun) => `${lead}: the transcript it resumes on is gone, so resuming it again fails the same way until the transcript is restored — restore it and then ${noun.again}, or give up the parked step (expire the checkpoint)`, transcript_corrupt: (lead, _noun, failure) => `${lead}: the transcript it resumes on is damaged, so resuming it again fails the same way until that is dealt with — ${failure.form !== undefined ? corruptSessionWayOutSentence(failure.form, failure.sessions ?? {}) : "restore the transcript, or remove it and give up the parked step (expire the checkpoint)"}`, }; function reopenedUnstartedSentence(lead, reason, noun, failure) { const cause = failure?.cause; if (cause !== undefined && Object.hasOwn(UNCURED_RETRY_SENTENCE, cause)) return UNCURED_RETRY_SENTENCE[cause](lead, noun, failure); switch (reason) { case "env_failed": return `${lead}: the same ${noun.grant} can be resumed again — ${noun.again}; do not ask for a fresh one`; case "config_refused": return `${lead}: the deployment refused the resumed leg (its configuration, or its execution environment refusing itself), so resuming under the same deployment fails the same way — correct the deployment, then ${noun.again}, or decide afresh`; case "tool_unavailable": return `${lead}: the tool it needs is not available to the resumed leg in the form it was parked with, so this ${noun.grant} cannot run there, and the same ${noun.grant} is answered the same until a leg mounts that tool as recorded again (for one of the engine's own tools, a worker of the release that parked it); to carry on without it, deny it (a note with the deny tells the model what to do instead) or give up the parked step (expire the checkpoint)`; case "constraint_rejected": return `${lead}: the decided input was refused, so decide afresh`; } }