UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

337 lines (336 loc) • 23.3 kB
import { isRemoteExecutionEnv, pathsAreHostLocal } from "../remote-env.js"; import { fileHistoryScopeOf, isOccupantToken } from "../../engine/session/repo-utils.js"; import { FILE_HISTORY_ERROR_CODES, FileHistoryStoreError } from "../file-history-store.js"; import { readMember, thrownText } from "../thrown-value.js"; import { isGovernanceRetryClass } from "../governance-codes.js"; import { boundaryUnrecordedNotice, fileHistoryRestoreLedgerLine, refuseRestoreOnForkWithOwnTree, refuseTargetOutsideOwnLog, restoreFailedError, restoreOutsideRootNote, RUN_STOPPED_RESTORE, settleFileHistoryRestore } from "./file-history-restore.js"; import { tellLeftAsIs } from "./left-as-is-seat.js"; import { deliverEngineNotice } from "../engine-notice.js"; import { canonicalOrSelf } from "./child-tree.js"; import { describeToolCatalog } from "../tool-registry.js"; import { A2A_NAMESPACE, mintNamespacePrefix } from "@sema-agent/primitives"; import { mcpServerReached } from "../mounted-mcp.js"; export function legMayWriteFiles(input) { for (const entry of describeToolCatalog()) if ((entry.face.effect ?? "write") === "write" && input.leaves({ name: entry.name })) return true; if ((input.callerTools ?? []).some((tool) => input.leaves(tool))) return true; const mcpReached = mcpServerReached(input.leaves, input.leavesPeer); return (input.mcp ?? []).some((s) => mcpReached(s.name)) || (input.a2a ?? []).some((p) => input.leavesPeer(mintNamespacePrefix(A2A_NAMESPACE, p.name))); } export async function prepareFileHistory(input) { const { deps, spec, request, internals, executionEnv, sessionRoot, forkSourceRoot, handsEnabled, sessionId, session, forkWithOwnTree, row, abortController, onceLedger } = input; const rewindNotes = []; const { onTrackFailure, captureOff, declaredOff, fileHistoryStore, captureStore, rewindTarget, rewindBefore } = request; const own = row !== undefined ? ownScopeOf(sessionId, row) : { unaddressed: "this session's row was not read (the run has no history store)" }; const ownScope = "scope" in own ? own.scope : undefined; if (spec.resumeAt !== undefined && spec.restoreFiles !== true) { rewindNotes.push({ code: "conversation_only", message: `the conversation was branched at entry "${spec.resumeAt}" but the working tree was NOT rewound — this task set resumeAt without restoreFiles, so files remain at their current state`, }); } const live = captureStore !== undefined && handsEnabled && !forkWithOwnTree; const livenessArm = fileHistoryStore === undefined ? "file-history-no-store" : "file-history-no-env"; if (!live && !forkWithOwnTree && !declaredOff && !captureOff && (handsEnabled || fileHistoryStore !== undefined) && deps.onError !== undefined && !toldAlready(deps.onError, livenessArm)) { const reason = livenessArm === "file-history-no-store" ? `this deployment wired no RunnerDeps.fileHistoryStore, so NOTHING is recorded: no first-touch snapshot before an edit, no turn boundary, and a later restoreFiles / rewindFilesTo has nothing to restore from and will refuse (rewind.store_unconfigured). Supply a store, or accept an unrecoverable working tree knowingly (fileHistoryStore: "disabled" says so and silences this line)` : `RunnerDeps.fileHistoryStore is wired but this run mounts no filesystem-capable ExecutionEnv, so the store is INERT: there is no working tree to snapshot and nothing will ever be written to it. Wire RunnerDeps.executionEnv, or drop the store from this deployment shape`; try { deps.onError(new Error(`file history is not live for this run — ${reason}.`), { phase: "config", sessionId, classification: livenessArm }); } catch { } } let keyedRead; const keyedRoot = () => (keyedRead ??= sessionRoot()); const keyed = live || (rewindTarget !== undefined && fileHistoryStore !== undefined && handsEnabled) ? await keyedRoot() : undefined; const outside = keyed !== undefined && "outside" in keyed ? keyed.outside : undefined; if (outside !== undefined && rewindTarget !== undefined) throw outside.refusal; try { if (outside !== undefined) deps.onError?.(new Error(outside.notice), { phase: "config", sessionId, classification: "file-history-outside-checkout" }); } catch { } const fileHistoryEnabled = live && outside === undefined; const { historyRoot, historyScope, historyFs } = await resolveFileHistoryCoordinates(executionEnv, keyed !== undefined && "root" in keyed ? keyed.root : undefined, internals?.fileHistoryLineage, ownScope, internals?.callerRoot); try { if (fileHistoryEnabled && historyScope === undefined && "unaddressed" in own) deps.onError?.(new Error(`file history has no scope for this run — ${own.unaddressed}: first-touch backups fail (track_failed), no turn boundary is recorded, and a rewind is refused.`), { phase: "rewind", sessionId }); } catch { } const carryRoots = { own: async () => (await keyedRoot().then((k) => ("root" in k ? canonicalOrSelf(executionEnv, k.root) : undefined), () => undefined)), source: async (origin) => { const r = await forkSourceRoot(origin); return r === undefined ? undefined : canonicalOrSelf(executionEnv, r); } }; if (captureStore !== undefined && row !== undefined && internals?.fileHistoryLineage === undefined && ownScope !== undefined) await adoptForkedFileHistory(captureStore, row, sessionId, ownScope, deps.onError, carryRoots); if (rewindTarget !== undefined && historyScope !== undefined && historyScope !== ownScope) throw childScopeRewindRefusal(historyScope, rewindTarget); if (fileHistoryStore !== undefined && !handsEnabled) { if (rewindTarget !== undefined) { rewindNotes.push({ code: "files_env_unsupported", message: "the file side of rewind was inert: this deployment mounts no filesystem-capable ExecutionEnv, so no file history was recorded or restored", }); } } if (rewindTarget !== undefined && fileHistoryStore !== undefined && handsEnabled) { const restoreSignal = spec.signal ? AbortSignal.any([abortController.signal, spec.signal]) : abortController.signal; if ("unaddressed" in own) throw own.refused ?? unaddressedRewindRefusal(sessionId, rewindTarget); await refuseTargetOutsideOwnLog(session, sessionId, rewindTarget, rewindBefore ? "before" : "restore"); refuseRestoreOnForkWithOwnTree(forkWithOwnTree, sessionId, rewindTarget, rewindBefore ? "before" : "restore"); const restored = await settleFileHistoryRestore({ store: fileHistoryStore, sessionId, scope: own.scope, target: rewindTarget, before: rewindBefore, env: executionEnv, root: historyRoot, signal: restoreSignal, readStates: internals?.sessionReadStates, options: request.restoreOptions, wholeOrNothing: spec.acceptPartialRestore !== true, ...(row !== undefined && row.origin !== undefined && row.origin !== sessionId ? { forkedSession: true } : {}), ...(input.rewindOutcome !== undefined ? { outcome: input.rewindOutcome } : {}) }); tellLeftAsIs({ restored, target: rewindTarget, scope: own.scope, sessionId, rewindNotes, onceLedger, onNotice: deps.onNotice }); const outsideRoot = restoreOutsideRootNote(restored, rewindTarget); if (outsideRoot !== undefined) rewindNotes.push(outsideRoot); if (restored.outcome === "partial") { if (spec.acceptPartialRestore === true) { rewindNotes.push({ code: "restore_partial", message: `file restore to entry "${rewindTarget}" was PARTIAL and was tolerated by acceptPartialRestore — ledger: ${fileHistoryRestoreLedgerLine(restored)}. Re-running the same restore converges (per-file idempotent).`, }); } else { throw restoreFailedError(restored, `rewind-files: restore to entry "${rewindTarget}" was PARTIAL after its plan passed — a write failed or the files changed between the plan and the restore, so the tree is now partly restored (the files written or deleted are named in the ledger): ${fileHistoryRestoreLedgerLine(restored)}. The task did not run on it (a run spec that accepts a partial restore, acceptPartialRestore, runs on a partly restored tree and discloses it, where its host offers that member). Do not send it again on its own: a person decides whether to — a repeat restores the rest and writes over any file changed since (files already restored are skipped by content).`, RUN_STOPPED_RESTORE); } } if (input.rewindOutcome !== undefined) input.rewindOutcome.restore = restored; } const trackFileEdit = fileHistoryEnabled ? async (req) => { const scope = historyScope; const r = scope === undefined ? unaddressedTrack("unaddressed" in own ? own.unaddressed : "") : await answerOf(() => fileHistoryStore.trackEdit(scope, req.key, executionEnv, historyRoot, req.signal), "track_failed"); if (r.ok) { if (!r.minted) return { ok: true }; return { ok: true, annul: async (proof) => { const a = await answerOf(() => fileHistoryStore.annulTrack(scope, req.key, historyRoot, proof === "verify" ? { env: executionEnv, ...(req.signal !== undefined ? { signal: req.signal } : {}) } : undefined), "track_failed"); if (a.ok) return; try { deps.onError?.(new FileHistoryStoreError(a.error, `file-history could not retract the first-touch record for "${req.key}" after its edit failed to land (${a.error.code}: ${a.error.message}) — the path stays tracked, so a rewind to a boundary below it may converge bytes this engine never wrote`, "thrown" in a ? a.thrown : undefined), { phase: "rewind", sessionId }); } catch { } }, }; } if (onTrackFailure === "proceed-unprotected") { try { deps.onError?.(new FileHistoryStoreError(r.error, `file-history first-touch backup for "${req.key}" failed (${r.error.code}: ${r.error.message}) — proceeding UNPROTECTED per RunnerDeps.onTrackFailure: the pristine promise for this path is void, and only in this process's memory (no durable trace exists, so after a process restart the next edit can still mint already-modified bytes as pristine v1)`, "thrown" in r ? r.thrown : undefined), { phase: "rewind", sessionId }); } catch { } return { ok: true }; } const lead = r.error.permanence === "terminal" ? "The history store reports this failure as permanent: do not retry this edit until the store is fixed." : "Retry when the file-history store is healthy."; return { ok: false, refusal: `Error (${req.tool}): the edit was refused because its first-touch file-history backup could not be persisted (${r.error.code}). ${lead} Proceeding would leave the file with no durable pristine record. ${r.error.message}` }; } : undefined; const fileHistoryBoundary = fileHistoryEnabled && ownScope !== undefined && historyScope === ownScope ? createFileHistoryBoundarySeat({ store: fileHistoryStore, sessionId, scope: ownScope, env: executionEnv, root: historyRoot, onError: deps.onError, onNotice: deps.onNotice }) : undefined; const fileHistoryFact = fileHistoryEnabled ? "on" : "disabled"; return { trackFileEdit, fileHistoryBoundary, rewindNotes, fileHistoryEnabled, fileHistoryFact, historyScope, historyRoot, historyFs }; } const FILE_HISTORY_BOUNDARY_TIMEOUT_MS = 30_000; const FILE_HISTORY_LIVENESS_MEMO = new WeakMap(); export function announceForkCheckoutUnrecorded(onceOnError, request, sessionId) { if (request.declaredOff || request.captureOff) return; try { onceOnError(new Error(`file history is not live for this session — session "${sessionId}" is a fork that works in a tree of its own (TaskSpec.workspace): in this version such a session records no file history (no first-touch backup before an edit, no turn boundary) and a rewind of its files is refused; its edits in the tree are not recoverable by a rewind, and its conversation is still branched by resumeAt.`), { phase: "config", sessionId, classification: "file-history-fork-checkout" }); } catch { } } function toldAlready(sink, arm) { const heard = FILE_HISTORY_LIVENESS_MEMO.get(sink) ?? new Set(); FILE_HISTORY_LIVENESS_MEMO.set(sink, heard); if (heard.has(arm)) return true; heard.add(arm); return false; } const FILE_HISTORY_CARRY_MEMO = new WeakMap(); function answerOf(call, code) { const unanswered = (message, thrown) => ({ ok: false, error: { code, message }, ...(thrown === undefined ? {} : { thrown }) }); return Promise.resolve().then(call).then((r) => { const ok = readMember(r, "ok"); if (ok === true) return { ok: true, minted: readMember(r, "minted") === true }; const error = readMember(r, "error"), stated = readMember(error, "code"), message = readMember(error, "message"), permanence = readMember(error, "permanence"); if (ok !== false || typeof stated !== "string") return unanswered("the history store answered something that is not a result"); const text = typeof message === "string" ? message : "(the history store gave no message)", known = FILE_HISTORY_ERROR_CODES.find((c) => c === stated); if (known === undefined) return unanswered(`the history store answered a code outside the closed set (${JSON.stringify(stated)}): ${text}`); return { ok: false, error: { code: known, message: text, ...(isGovernanceRetryClass(permanence) ? { permanence } : {}) } }; }, (value) => unanswered(`the history store threw: ${thrownText(value)}`, { value })); } export async function adoptForkedFileHistory(store, lineage, sessionId, ownScope, onError, roots) { const memo = FILE_HISTORY_CARRY_MEMO.get(store) ?? { settled: new Set(), disclosed: new Set(), inFlight: new Map() }; FILE_HISTORY_CARRY_MEMO.set(store, memo); const discloseOnce = (err) => { if (memo.disclosed.has(ownScope)) return; memo.disclosed.add(ownScope); onError?.(err, { phase: "rewind", sessionId }); }; const { origin: forkedFrom, originIncarnation: forkedFromIncarnation } = lineage; try { if (forkedFrom === undefined || forkedFrom === sessionId) return; if (memo.settled.has(ownScope)) return; let sourceScope; let why = "this fork's row records no occupant of its source (it was cut before rows named their occupants, or its store mints none), so the source's history has no address"; try { if (isOccupantToken(forkedFromIncarnation)) sourceScope = fileHistoryScopeOf(forkedFrom, forkedFromIncarnation); } catch (refused) { why = thrownText(refused); } if (sourceScope === undefined) { memo.settled.add(ownScope); discloseOnce(new FileHistoryStoreError({ code: "adopt_failed" }, `file-history fork carry from session "${forkedFrom}" was not made — ${why}. Nothing was carried into this session (the run itself proceeds; a fork that already holds history keeps it)`)); return; } const [own, source] = [await roots.own(), await roots.source(forkedFrom)]; if (own === undefined || source === undefined || own !== source) { if (own !== undefined && source !== undefined) memo.settled.add(ownScope); const apart = source === undefined ? "this session's copy of the source's log shows the source working in a tree of its own, or cannot vouch for where its history is keyed" : own === undefined ? "where this session's history is keyed cannot be read" : `the source's history is keyed against ${source} and this session's against ${own}`; discloseOnce(new FileHistoryStoreError({ code: "adopt_failed" }, `file-history fork carry from session "${forkedFrom}" was not made — ${apart}: carried records would be joined on this session's root, where a version the source recorded under its own directory is never written (left as it is, or refused where that directory lies inside this session's root), so none is carried. Nothing was carried by this session; a rewind to a point before the fork is refused as a point with no boundary on this session — or, where this session's history already holds the source's versions through another channel (a host's deletion cascade or import), each such file is left as it is or refused, nothing written (the run itself proceeds)`)); return; } const shared = memo.inFlight.get(ownScope); if (shared !== undefined) return await shared; const attempt = (async () => { const carried = await answerOf(() => store.adoptScope(sourceScope, ownScope), "adopt_failed"); if (carried.ok || carried.error.code === "conflict") { memo.settled.add(ownScope); return; } discloseOnce(new FileHistoryStoreError(carried.error, `file-history fork carry from session "${forkedFrom}" failed (${carried.error.code}): ${carried.error.message} — the parent's history was not carried, so boundaries recorded before the fork are not restorable from this session (the run itself proceeds; the carry is retried on this session's next turn)`, "thrown" in carried ? carried.thrown : undefined)); })(); memo.inFlight.set(ownScope, attempt); try { await attempt; } finally { memo.inFlight.delete(ownScope); } } catch { } } function ownScopeOf(sessionId, row) { if (row.fault) return { unaddressed: "this session's row could not be read" }; try { return { scope: fileHistoryScopeOf(sessionId, row.own) }; } catch (err) { return { unaddressed: thrownText(err), refused: err instanceof Error ? err : new Error(thrownText(err)) }; } } function unaddressedTrack(why) { return { ok: false, error: { code: "track_failed", message: `${why} — the run has no file-history scope to record the backup in` } }; } export function unaddressedRewindRefusal(sessionId, target) { return restoreFailedError({ outcome: "failed", filesChanged: [], identicalSkipped: [], refused: [], failed: [] }, `rewind-files: the row of session "${sessionId}" could not be read, so its file history has no address and nothing can be restored to entry "${target}" — the working tree was NOT rewound; retry once the session store answers`, { permanence: "transient" }); } function createFileHistoryBoundarySeat(opts) { let inFlight; let begun = false; return { begin(entryId) { if (begun) return; begun = true; const ac = new AbortController(); let timer; const timeout = new Promise((resolve) => { timer = setTimeout(() => { ac.abort(); resolve({ ok: false }); }, FILE_HISTORY_BOUNDARY_TIMEOUT_MS); }); const work = answerOf(() => opts.store.snapshot(opts.scope, entryId, opts.env, opts.root, ac.signal), "snapshot_failed"); const disclose = (failure, what, thrown) => new FileHistoryStoreError(failure, `file-history ${what} — this turn has no boundary and cannot be rewound to (the turn itself proceeds)`, thrown); inFlight = Promise.race([ work.then((r) => (r.ok ? undefined : disclose(r.error, `boundary capture failed (${r.error.code}): ${r.error.message}`, "thrown" in r ? r.thrown : undefined))), timeout.then(() => disclose({ code: "aborted" }, `boundary capture timed out after ${FILE_HISTORY_BOUNDARY_TIMEOUT_MS / 1000}s (fenced — the attempt can never publish)`)), ]) .then((failure) => { if (failure === undefined) return; try { opts.onError?.(failure, { phase: "rewind", sessionId: opts.sessionId }); } catch { } try { deliverEngineNotice(opts.onNotice, boundaryUnrecordedNotice({ sessionId: opts.sessionId, entryId, cause: failure.code })); } catch { } }) .finally(() => clearTimeout(timer)); }, async settle() { if (inFlight !== undefined) await inFlight; }, }; } export async function resolveFileHistoryCoordinates(env, sessionRoot, lineage, ownScope, callerRoot) { if (sessionRoot === undefined) return { historyRoot: "", historyScope: ownScope, historyFs: "" }; const canonRoot = await env.canonicalPath(sessionRoot); const ownRoot = canonRoot.ok ? canonRoot.value : sessionRoot; const historyFs = fileHistoryFilesystemIdentity(env); const atCaller = lineage !== undefined && lineage.fs === historyFs && callerRoot !== undefined && ownRoot === (await canonicalOrSelf(env, callerRoot)); const historyRoot = atCaller ? lineage.root : ownRoot; return { historyRoot, historyScope: resolveFileHistoryScope(lineage, historyRoot, historyFs, ownScope), historyFs }; } export function resolveFileHistoryScope(lineage, historyRoot, historyFs, ownScope) { if (lineage === undefined || lineage.scope === "" || lineage.root !== historyRoot || lineage.fs !== historyFs) return ownScope; return lineage.scope; } const envFilesystemTokens = new WeakMap(); let envFilesystemSeq = 0; export function fileHistoryFilesystemIdentity(env) { if (pathsAreHostLocal(env)) return "host"; if (isRemoteExecutionEnv(env)) { try { const h = env.workspaceHandle(); return JSON.stringify(["remote", h.provider, h.sandboxId, h.deviceId !== undefined && h.deviceId !== "" ? h.deviceId : null]); } catch { } } let token = envFilesystemTokens.get(env); if (token === undefined) { token = `instance:${++envFilesystemSeq}`; envFilesystemTokens.set(env, token); } return token; } function childScopeRewindRefusal(rootScope, target) { const e = new Error(`rewind-files: this run is a delegated child recording its edits into its ROOT session's file history (scope "${rootScope}"), so restoring files to entry "${target}" is the root session's action (rewindFilesTo / resumeAt+restoreFiles on that session), not the child's — the files were NOT rewound`); e.code = "rewind.child_scope_unsupported"; return e; }