@sema-agent/core
Version:
Stateless, task-oriented AI agent core
190 lines (189 loc) • 9.67 kB
JavaScript
import { isBackgroundAgentSettledStatus } from "./background-agent-store.js";
import { checkpointStoreOfSeat } from "./checkpoint-seat.js";
import { isResourceLimitReason } from "./resource-limit-reasons.js";
import { MAX_CHECKPOINT_ID_CHARS, readGateIdentity } from "./checkpoint-identity.js";
import { deliverEngineNotice } from "./engine-notice.js";
import { inlineUntrusted } from "./untrusted-text.js";
import { ANONYMOUS_SCOPE } from "./isolation-scope.js";
const STATUS_WORDS = { pending: true, running: true, parked: true, completed: true, failed: true, killed: true, cancelled: true };
export const AGENT_PARK_UNREADABLE_CAUSES = Object.freeze(["no_seat", "store_failed", "status_unknown"]);
export const APPROVAL_WAIT_FIELD_MAX = 128;
export function approvalHeldOfHandle(h) {
return (h.status === "running" ? h.approvalHolds?.() : undefined) ?? [];
}
export function agentStateSourceOfHandle(h) {
const held = approvalHeldOfHandle(h);
return {
status: h.status,
row: "live_row",
handle: h.id,
...(h.scope !== undefined ? { scope: h.scope } : {}),
lastActivityAt: h.updatedAt,
...(h.parkedCheckpointToken !== undefined ? { parkedCheckpointToken: h.parkedCheckpointToken } : {}),
...(held.length > 0 ? { approvalHeld: held } : {}),
};
}
export function agentStateSourceOfRecord(r) {
const at = r.status === "parked" ? r.parkedAt : isBackgroundAgentSettledStatus(r.status) ? r.settledAt : undefined;
return {
status: r.status,
row: "durable_row",
handle: r.handle,
scope: r.scope,
...(at !== undefined ? { lastActivityAt: at } : {}),
...(r.parkedCheckpointToken !== undefined ? { parkedCheckpointToken: r.parkedCheckpointToken } : {}),
};
}
const finite = (n) => typeof n === "number" && Number.isFinite(n);
const PARK_GATE_WORDS = {
human: "approval",
irreversible_ask: "approval",
needs_review: "review",
plan_review: "review",
task_done: "awaiting task",
resource_limit: null,
};
function parkGateOf(gate) {
const g = gate;
if (typeof g?.kind !== "string" || !Object.hasOwn(PARK_GATE_WORDS, g.kind))
return undefined;
if (g.kind !== "resource_limit")
return { kind: g.kind };
const reason = g.reason;
return isResourceLimitReason(reason) ? { kind: "resource_limit", reason } : undefined;
}
export function committedParkOf(pause) {
const gate = parkGateOf(pause.gate);
return { state: "pending", ...(gate !== undefined ? { gate } : {}), ...readGateIdentity(pause.checkpointId, pause.token) };
}
const untrustedIdAnnounced = new Set();
async function readParkCard(store, token, agent) {
let cp;
try {
cp = (await store.get(token));
}
catch {
return { state: "unreadable", unreadableCause: "store_failed" };
}
if (cp === null || cp === undefined)
return { state: "missing" };
const state = cp.status === "pending" || cp.status === "resolved" || cp.status === "expired" ? cp.status : "unreadable";
const gate = parkGateOf(cp.gate);
const identity = readGateIdentity(cp.checkpointId, token);
if (identity.checkpointIdMissing === "untrusted")
announceUntrustedCardId(agent);
return {
state,
...(state === "unreadable" ? { unreadableCause: "status_unknown" } : {}),
...(gate !== undefined ? { gate } : {}),
...identity,
...(finite(cp.deadline) ? { deadline: cp.deadline } : {}),
};
}
function announceUntrustedCardId(agent) {
const key = `${agent.scope ?? ANONYMOUS_SCOPE}\u0000${agent.handle}`;
if (untrustedIdAnnounced.has(key))
return;
untrustedIdAnnounced.add(key);
deliverEngineNotice(undefined, {
code: "delegation.parked_card_id_untrusted",
message: `sema durable-agents: parked agent ${agent.handle}${agent.scope !== undefined ? ` (scope ${agent.scope})` : ""} — its approval card carries an id that does not pass the identity check ` +
`(a non-empty string of at most ${MAX_CHECKPOINT_ID_CHARS} characters that does not contain the card's resume token); the agent's state is read without the id. ` +
`The card's other facts are unaffected; the id cell of the stored row is what to repair.`,
detail: { handle: agent.handle, ...(agent.scope !== undefined ? { scope: agent.scope } : {}) },
});
}
function approvalWaitOf(src) {
const first = src.approvalHeld?.[0];
if (first === undefined || src.status !== "running")
return {};
return { approvalWait: { tool: first.tool.slice(0, APPROVAL_WAIT_FIELD_MAX), toolCallId: first.toolCallId.slice(0, APPROVAL_WAIT_FIELD_MAX), count: src.approvalHeld.length } };
}
export function readAgentState(src, seat, now) {
const base = {
status: Object.hasOwn(STATUS_WORDS, src.status) ? src.status : "unknown",
readAt: now,
row: src.row,
...(finite(src.lastActivityAt) ? { lastActivityAt: src.lastActivityAt } : {}),
...approvalWaitOf(src),
};
if (base.status !== "parked")
return base;
if (src.parkedCheckpointToken === undefined)
return { ...base, park: { state: "missing" } };
const store = checkpointStoreOfSeat(seat);
if (store === undefined)
return { ...base, park: { state: "unreadable", unreadableCause: "no_seat" } };
return readParkCard(store, src.parkedCheckpointToken, src).then((park) => ({ ...base, park }));
}
export function formatAgo(ms) {
const sec = Math.max(0, Math.floor(ms / 1000));
if (sec < 60)
return `${sec}s`;
const min = Math.floor(sec / 60);
if (min < 60)
return `${min}m`;
const h = Math.floor(min / 60);
if (h < 48)
return `${h}h`;
return `${Math.floor(h / 24)}d`;
}
export function agentActivityClause(s) {
if (s.lastActivityAt !== undefined)
return `last activity ${formatAgo(s.readAt - s.lastActivityAt)} ago`;
return s.row === "durable_row" && s.status === "running" ? "last activity unknown (recorded as running by another engine process)" : "last activity unknown (not recorded)";
}
const APPROVAL_SENTENCE = "The agent is durably suspended, waiting for an approval decision. It resumes when the pending approval is decided (durable approval inbox), or lands failed if the approval expires.";
const REVIEW_SENTENCE = "The agent is durably suspended, waiting for a review decision.";
const PARK_GATE_SENTENCES = {
human: APPROVAL_SENTENCE,
irreversible_ask: APPROVAL_SENTENCE,
needs_review: REVIEW_SENTENCE,
plan_review: REVIEW_SENTENCE,
task_done: "The agent is durably suspended, waiting for a background task to complete.",
};
function parkWord(gate) {
if (gate === undefined)
return "park";
if (gate.kind !== "resource_limit")
return PARK_GATE_WORDS[gate.kind];
return gate.reason === "preempt" ? "yielded" : `paused (${gate.reason})`;
}
export function agentParkClause(p, readAt) {
const id = p.checkpointId !== undefined ? ` ${inlineUntrusted(p.checkpointId, 64)}` : "";
const deadline = p.deadline === undefined ? "" : p.deadline > readAt ? ` (deadline in ${formatAgo(p.deadline - readAt)})` : ` (deadline passed ${formatAgo(readAt - p.deadline)} ago)`;
const continues = p.state === "pending" && p.gate?.kind === "resource_limit" && p.gate.reason === "preempt" ? " — continues when its owner runs again" : "";
return `${parkWord(p.gate)}${id} ${p.state}${deadline}${continues}`;
}
const PARK_BLIND_CLOSING = "it may be waiting for an approval decision.";
const PARK_BLIND_SENTENCE = `What this agent is waiting on cannot be read here; ${PARK_BLIND_CLOSING}`;
const AGENT_PARK_UNREADABLE_SENTENCES = {
no_seat: `This run keeps no record of parked steps, so whether the agent is waiting on a decision cannot be read here, and asking again will not change that; ${PARK_BLIND_CLOSING}`,
store_failed: `The record of the parked step could not be read just now (a later read may succeed, and if it keeps failing the record itself may be damaged); ${PARK_BLIND_CLOSING}`,
status_unknown: `The parked step carries a state this engine version does not know; ${PARK_BLIND_CLOSING}`,
};
export function agentParkSentence(p) {
if (p === undefined || p.state === "missing")
return PARK_BLIND_SENTENCE;
if (p.state === "unreadable") {
return p.unreadableCause !== undefined && Object.hasOwn(AGENT_PARK_UNREADABLE_SENTENCES, p.unreadableCause)
? AGENT_PARK_UNREADABLE_SENTENCES[p.unreadableCause]
: PARK_BLIND_SENTENCE;
}
if (p.state !== "pending")
return "What this agent waited on is no longer pending (the state line says how it ended); its row has not been settled yet.";
const gate = p.gate;
if (gate === undefined)
return PARK_BLIND_SENTENCE;
if (gate.kind !== "resource_limit")
return PARK_GATE_SENTENCES[gate.kind];
if (gate.reason === "preempt")
return "The agent yielded along with its owner and continues when its owner runs again. No approval decision is pending for it.";
return `The agent is durably suspended: it paused at a resource limit (${gate.reason}).`;
}
export function agentApprovalWaitClause(w) {
return `awaiting approval for ${inlineUntrusted(w.tool, 64)} call ${inlineUntrusted(w.toolCallId, 64)}${w.count > 1 ? ` (+${w.count - 1} more)` : ""}`;
}
export function agentStateSummary(s) {
return [s.status, agentActivityClause(s), ...(s.park !== undefined ? [agentParkClause(s.park, s.readAt)] : []), ...(s.approvalWait !== undefined ? [agentApprovalWaitClause(s.approvalWait)] : [])].join(" · ");
}