UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

110 lines (109 loc) • 9.55 kB
/** * PrepareTask's session acquire+reconcile phase. Acquire the session * and, when resuming, reconcile any interrupted (orphan) tool call before the turn. Both are retried * together on a F2 optimistic-lock conflict: a concurrent writer on another instance can move the * leaf during reconcile's append, and the fix can't be applied to a now-stale in-memory view — so we * drop it and **re-wake**. Bounded; exhaustion → the conflict propagates and the task fails with * `errorCode="conflict"` for the caller to retry. The retry loop's WHOLENESS is the T4 invariant * (resume-at validation + rebranch + reconcile re-run as one unit against the fresh view) — pinned * in `prepare-task-phase-pins`. * * Ownership: on SUCCESS the acquired session's ownership transfers whole to the caller (the driver's forgetOnThrow / the Runner's finish own the cleanup from then on); * every failure path INSIDE this phase drops its own cached view first (`forget`, never `release` — * audit B-17: release deletes the history on the default store), so a throw here never strands a * cached view and never hands out a half-acquired resource. * * Throws pass through unchanged: `delegation.owner_mismatch` (a leg holding a seat resolved a row that is not its tree's — its cached view * dropped first), the session store's fault of that judgement (`config.invalid_session_store` / `storage`), `resume.session_not_found` (requireExisting fail-loud mapping), * the `resume_at.*` target-validation refusals (`judgeRewindTarget`, then the landing's: the window, `refuseOpenToolCallAt`), `corrupt_session` * for a log that does not hold together (the path reads after the branch), `holder.superseded` (a write the store refused for the * leg's grant: never re-woken — a superseded leg stops), and — after the * bounded re-wake budget — the session conflict itself. A throw after a `resumeAt` branch landed first writes that branch * back (`settleBranchWriteBack`); on success the branch is handed over with the session. */ import { StoredSession } from "../session.js"; import type { AcquiredSession, SessionStore } from "../session.js"; import { type RecoveredOrphan } from "../session-reconcile.js"; import type { TaskSpec, ToolEffect } from "../types.js"; import type { PrepareResume } from "./contracts.js"; import { type ResumeAtBranch, type WriteRefusal } from "./branch-writeback.js"; import { type LegWrites } from "./session-write-ledger.js"; import { replayLossLeg } from "./lineage-reroot-view.js"; import type { RewindOutcome } from "./rewind-outcome.js"; export interface PrepareAcquireReconcileInput { /** borrowed-mutable (service port) — the deployment's session store. This phase's verbs on it are * the acquire/forget half of the session resource protocol: `acquire` per attempt, `forget` to * drop a stale cached view on a lost CAS and on the throw path (never `release` — B-17). */ sessions: SessionStore; /** borrowed-readonly — the REBOUND spec's four session-addressing fields (窄输入: exactly what the * slice reads; a new read here must widen this Pick). `sessionId`/`requireExistingSession` drive * the acquire, `resumeAt`/`resumeAtMode` the §E18 rebranch validation. */ spec: Pick<TaskSpec, "sessionId" | "requireExistingSession" | "resumeAt" | "resumeAtMode">; /** borrowed-readonly — the durable-resume seats this phase reads: `leafId` (rewind to the * suspension point BEFORE reconcile) and `suspendedBatch` (wake-reconcile SKIPS those calls — * they are resumed, not crash-interrupted). Absent for a fresh/non-durable run. */ resume: Pick<PrepareResume, "leafId" | "suspendedBatch"> | undefined; /** borrowed-readonly — the safety scan's pre-mount reading ({@link import("./prepare-safety-scan.js").PrepareSafetyScanResult.wakeEffects}): * this reconcile runs before any tool mounts, so a contested name reads its least repeat-safe member; it classifies an orphan's retry-safety. */ wakeEffects: Map<string, ToolEffect>; /** borrowed-readonly — subagent transcript persistence: the trusted spawner's placement * declaration for THIS run's session ({@link RunInternals.sessionPlacement}), forwarded verbatim * into the create-form acquire so the store creates the child's transcript into its subagent * partition. Never combined with `requireExistingSession` semantics: the require-existing form * re-opens and placement is first-write immutable, so it rides only the create-capable arm. */ placement?: import("../session.js").SessionPlacement; /** borrowed-readonly — what this leg's row is judged by (read before this phase from the spawner's seat; absent = the leg holds no seat: * its row is not judged). Its owner, when a name, is named on the create-capable acquire; the row every attempt resolves — either form — * is judged before anything is written to it ({@link judgeLegRow}: under the leg's stop). */ judged?: import("./delegation-owner.js").JudgedLeg; /** borrowed-readonly — told once that the acquired row may be named: the row of the attempt the phase ends on, when that attempt's * judgement held (or the leg holds no seat) — never an attempt a lost CAS re-woke from. */ verified?: (sessionId: string) => void; /** borrowed-readonly — the durable-park TOPOLOGY gap sentence for this * deployment (`durableParkGapFor`), or `undefined` when the topology is whole / does not apply. * Read ONLY on the fail-loud missing-session path below, where it turns a symptom into a named * absent seat; nothing in the phase's control flow depends on it. Computed by the driver (which * holds `deps`) rather than here, keeping this slice's input the narrow Pick its contract says. */ durableParkGap?: string; /** borrowed-readonly — the incident channel for this phase's own cleanup legs: a `resumeAt` branch it could not write back, a forget that did not settle. */ report?: (err: Error, sessionId: string) => void; /** borrowed-mutable (the Runner's) — this leg's view of the session write ledger, every storage write issued through it ({@link writesThroughLeg}); absent for a standalone prepare. */ legWrites?: LegWrites; /** borrowed-readonly — the holder this leg's session writes carry ({@link stampHolder}, installed nearest the storage, with or * without a ledger): `writeHolderOf` the leg's internals; absent when it carries none. With `engineLane`, the handed storage is asked * first whether it judges (`sessionStorageJudges`: a store's `durableFence`, station 2) — inside the attempt, so a refusal forgets it. */ holder?: string; /** borrowed-readonly — an engine lane started the leg (`engineLaneLegOf`), as its prepare says: the storage answers for itself. */ engineLane?: boolean; /** borrowed-readonly — where the leg says what the log's replay dropped, and re-rooted a branch at it ({@link replayLossLeg}): absent ⇒ nothing said and no re-root (a break is refused). */ replayLossNotice?: Parameters<typeof replayLossLeg>[0]; /** borrowed-mutable — the leg's record of where its request left the conversation's leaf ({@link RewindOutcome.branch}): the * `resumeAt` branch states it moved once its leaf write lands, and the branch it hands on carries the record to its write-back. */ rewindOutcome?: Pick<RewindOutcome, "branch">; } /** The phase's outputs (four-class form). All six are fresh bindings — * the driver destructures them into consts, so a consumer moved ahead of this call is a lexical * error, which is the static guarantee the extraction keeps. */ export interface PrepareAcquireReconcileResult { /** owned (resource handover) — the store's acquired session. Handover happens ONLY on return: * every throw inside the phase already forgot its own cached view. */ acquired: AcquiredSession; /** owned — the conflict-proxy-wrapped view over `acquired`'s storage (engine-internal: prepare * always wraps storage in the concrete built-in — the epoch pin needs its * append/getPromptEpoch). Aliases `acquired.session`'s storage through the proxy. */ session: StoredSession; /** owned cell — the leg's write-boundary latch ({@link WriteRefusal}), set by the proxy installed inside `session` whenever a * RUN-time write is refused with `conflict` or `holder.superseded` (identity is contract: the proxy closes over this exact * object; the run loop reads its word into `errorCode`). */ writeRefusal: WriteRefusal; /** owned — scan-1/A5: what the wake/crash reconcile closed, handed to the run loop so it can mint * the matching stream frames (see `Prepared.wakeRecovered`). Written by the acquire attempt that * SUCCEEDS (a conflict-losing attempt re-wakes and re-derives the whole set from the fresh * branch), and stays empty for a fresh session / a clean one with nothing to reconcile. */ wakeRecovered: RecoveredOrphan[]; /** owned (handed over with the session) — the `resumeAt` branch this phase wrote, absent when it wrote * none; the driver's throw cleanup writes it back on any later prepare refusal. */ branch: ResumeAtBranch | undefined; } /** The B-3 phase body — the acquire+reconcile slice, verbatim (see the module header for the contract). */ export declare function prepareAcquireReconcile(input: PrepareAcquireReconcileInput): Promise<PrepareAcquireReconcileResult>;