UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

86 lines (85 loc) • 4.56 kB
import { buildSessionContext } from "../../internal/harness.js"; import { closableByAppend } from "../session-reconcile.js"; import { defaultTaskRegistry } from "../task-registry.js"; import { owedDateAnchor } from "./conversation-segment.js"; import { rewindTargetNamed } from "./rewind-target.js"; import { raceTeardownLegOr, settleTeardownLeg, teardownLegBudget } from "./teardown-bounded.js"; export async function closableByAppendAt(session, leafId) { return closableByAppend(buildSessionContext(await session.getBranch(leafId)).messages).map(({ toolCallId, toolName }) => ({ toolCallId, toolName })); } export async function refuseOpenToolCallAt(session, leafId, target, asker) { const open = await closableByAppendAt(session, leafId); if (open.length === 0) return; const e = new Error(`${rewindTargetNamed(target, asker)} lands where the conversation still holds ${open.length === 1 ? "a tool call" : `${open.length} tool calls`} with no result after it (${open.map((o) => `${o.toolName} "${o.toolCallId}"`).join(", ")}): a run continued from there would first close ${open.length === 1 ? "it" : "them"} with a synthetic interruption — rewind to an entry after the results, or before the call; for a call above the entry on the branch the session is on, continue the session once without resumeAt (a run closes it) and rewind to an entry of that run`); e.code = "resume_at.open_tool_call"; throw e; } export function settleBound() { let until; return (ahead) => { const now = Date.now(); until ??= now + teardownLegBudget(); return Math.max(1, Math.floor((until - now) / ahead)); }; } export function legEndRecords(prepared, rs, runner, bound) { let written = false; const report = (phase) => (e) => { try { runner.deps.onError?.(e, { phase, sessionId: prepared.sessionId }); } catch { } }; return async () => { if (written) return; written = true; const dateSeat = prepared.dateChange; const dateState = rs.attach.dateState; const writeDateAnchor = owedDateAnchor(prepared.session, prepared.prefixAnchor?.read ?? dateSeat?.anchor, dateSeat !== undefined && dateState !== undefined ? { legDate: dateSeat.legDate, announcedDate: dateState.announcedDate } : undefined, prepared.prefixAnchor?.head(), prepared.prefixAnchor?.memory); if (writeDateAnchor !== undefined) await settleTeardownLeg(writeDateAnchor, "date anchor (settle leg)", report("degraded"), bound(prepared.crossBoundary !== undefined ? 3 : 2)); if (prepared.crossBoundary !== undefined) await prepared.crossBoundary.settle(() => defaultTaskRegistry.owedDeliveries({ ...prepared.registryAccess, sessionId: prepared.sessionId }), bound(2)).catch(report("config")); }; } export async function settledContinuesFrom(input) { const { closed, runOpen, session, sessionId } = input; const report = (err) => { try { input.report(err); } catch { } }; if (runOpen) return { none: "run_open" }; if (closed.inFlight) return { none: "unsettled" }; const leaf = closed.lastLanded; if (leaf === undefined) return { none: "nothing_taken_in" }; if (closed.strayed !== undefined) { report(new Error(`session "${sessionId}": a ${closed.strayed} write of the leg landed on a leaf another writer had moved the session to, not on the one the leg's previous write left — the branch at its last write is not this leg's conversation; the run's landing reads as unsettled`)); return { none: "unsettled" }; } if (leaf === null) { report(new Error(`session "${sessionId}": the leg's last write left the session on the empty branch — no entry to continue from; the run's landing reads as unsettled`)); return { none: "unsettled" }; } try { const closable = await raceTeardownLegOr(() => closableByAppendAt(session, leaf), "continuesFrom branch read (settle leg)", (timeout) => (report(timeout), undefined), input.bound(1)); if (closable === undefined || closable.length > 0) return { none: "unsettled" }; } catch (err) { report(err); return { none: "unsettled" }; } return { sessionId, entryId: leaf }; } export function unsettledLegContinuesFrom(closed) { return !closed.inFlight && closed.lastLanded === undefined ? { none: "nothing_taken_in" } : { none: "unsettled" }; }