UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

193 lines (192 loc) • 13 kB
import { ABSOLUTE_HOST_PATH_MAX, isAbsoluteHostPath } from "@sema-agent/primitives"; import { strayMembersOf } from "../own-property-receipt.js"; import { ENV_PURPOSE_UNSUPPORTED, hasDestroy } from "../remote-env.js"; import { boundedTail } from "../session.js"; import { CHANGES_CHECKPOINTS_PAGE_MAX, CHANGES_CONTENT_OF_MAX } from "../session-changes.js"; import { readElements, readMember } from "../thrown-value.js"; import { readCheckpointItem, readCheckpointList, readSince } from "./changes-history.js"; import { readGitChanges } from "./changes-git.js"; import { resolveDeploymentFileHistory } from "./file-history-request.js"; import { restoreFailedError } from "./file-history-restore.js"; import { prepareExecutionEnv } from "./prepare-execution-env.js"; import { createRollbackStack } from "./rollback-stack.js"; import { acquireExistingSession, readOccupantExpectation, readPlainRequest, shownValue } from "./session-verb-doors.js"; import { openSessionFiles } from "./session-files-open.js"; import { settleTeardownLeg } from "./teardown-bounded.js"; const VERB = "Runner.readSessionChanges"; const REQUEST_KEYS = new Set(["sessionId", "source", "contentOf", "cwd", "expect", "signal"]); const SOURCE_KEYS = new Set(["kind", "limit", "before", "entryId", "base"]); const SOURCE_MEMBERS = { checkpoints: ["kind", "limit", "before"], checkpoint: ["kind", "entryId"], since: ["kind", "entryId"], git: ["kind", "base"] }; export async function readSessionChanges(seats, request) { const req = screenSessionChangesRequest(request); const { deps } = seats; const source = req.source; const store = source.kind === "git" ? undefined : resolveDeploymentFileHistory(deps).fileHistoryStore; if (source.kind !== "git" && store === undefined) return answered(req, { kind: "unavailable", source, reason: "store_unconfigured" }); const acquired = await acquireExistingSession(seats.sessions, req.sessionId, VERB, "nothing was read", req.expect); const report = (err) => { try { deps.onError?.(err, { phase: "config", sessionId: req.sessionId }); } catch { } }; const owned = []; const takeEnv = async () => { const rollback = createRollbackStack(report); let phase; try { phase = await prepareExecutionEnv({ deps, spec: {}, internals: req.cwd !== undefined ? { requestedCwd: req.cwd } : undefined, resume: undefined, placementRootResolved: req.sessionId, sessionId: req.sessionId, forgetOnThrow: async () => { }, rollback, startsEnv: true, purpose: "read_changes" }); } catch (err) { await rollback.unwindAll(); if (readMember(err, "code") === ENV_PURPOSE_UNSUPPORTED) return undefined; throw err; } rollback.commit(); if (phase.ownedEnvSeat.current !== undefined) owned.push(phase.ownedEnvSeat.current); return { env: phase.executionEnv, handsEnabled: phase.handsEnabled, baseRoot: phase.taskRootInitial }; }; try { return answered(req, source.kind === "git" || store === undefined ? await readGit(req, acquired.session, seats.sessions, takeEnv) : await readSource(req, source, store, acquired.session, seats.sessions, takeEnv)); } finally { for (const env of owned) if (hasDestroy(env)) await settleTeardownLeg(() => env.destroy(), "ownedEnv.destroy (readSessionChanges)", report); } } function checkoutRefusedAs(sessionId) { return `${VERB}: where session "${sessionId}"'s files stand cannot be resolved from its checkout (TaskSpec.workspace), so nothing was read — the base checkout is never read in place of the session's own tree; a session that works in its own tree is read while that checkout stands (before releaseSessionCheckout, its tree on disk).`; } function unaddressed(sessionId) { return () => restoreFailedError({ outcome: "failed", filesChanged: [], identicalSkipped: [], refused: [], failed: [] }, `${VERB}: the row of session "${sessionId}" could not be read, so its file history has no address and nothing was read; retry once the session store answers`, { permanence: "transient" }); } async function readGit(req, session, sessions, takeEnv) { const { source, sessionId } = req; const env = await takeEnv(); if (env === undefined || !env.handsEnabled) return { kind: "unavailable", source, reason: "files_env_unsupported" }; const opened = await openSessionFiles({ session, sessionId, tree: { hands: { env: env.env, baseRoot: env.baseRoot }, refusedAs: checkoutRefusedAs(sessionId), sessions } }); if (opened.kind !== "opened" || opened.sessionRoot === undefined) return { kind: "unavailable", source, reason: "files_env_unsupported" }; const read = await readGitChanges({ env: env.env, root: opened.sessionRoot, contentOf: req.contentOf, signal: req.signal }); return { ...read, source }; } async function readSource(req, source, store, session, sessions, takeEnv) { const { sessionId, contentOf } = req; const unavailable = (reason, fault) => ({ kind: "unavailable", source, reason, ...(fault !== undefined ? { fault } : {}) }); const sinceOn = (env, entryId, opened) => readSince(store, { scope: opened.historyScope, entryId, env, root: opened.historyRoot, signal: req.signal, ...(opened.row.forkedFrom !== undefined && opened.row.forkedFrom !== sessionId ? { forkedSession: true } : {}) }, contentOf); const treeOf = (env) => ({ hands: env !== undefined && env.handsEnabled ? { env: env.env, baseRoot: env.baseRoot } : undefined, refusedAs: checkoutRefusedAs(sessionId), sessions }); if (source.kind === "since") { const env = await takeEnv(); const opened = await openSessionFiles({ session, sessionId, target: source.entryId, tree: treeOf(env), history: { unaddressed: unaddressed(sessionId) } }); if (opened.kind === "no_hands") return unavailable("files_env_unsupported"); if (opened.kind !== "opened") return unavailable("no_checkpoint"); const read = await sinceOn(env.env, source.entryId, opened.history); return read.kind === "rows" ? { kind: "rows", source, before: { kind: "checkpoint", entryId: source.entryId }, after: { kind: "working_tree" }, rows: read.rows } : unavailable(read.reason, read.fault); } const pathOf = async () => boundedTail(await session.getBranch()).tail; const newestOn = (on) => async (entryId, skipped) => { if (on === undefined) return { kind: "unavailable", entryId, reason: "files_env_unsupported" }; const read = await sinceOn(on.env, entryId, on.history); if (read.kind === "rows") return { kind: "rows", before: { kind: "checkpoint", entryId }, after: { kind: "working_tree", ...(skipped !== undefined ? { skipped } : {}) }, rows: read.rows }; return { kind: "unavailable", entryId, reason: "history_unreadable", fault: read.fault ?? { code: read.reason === "no_checkpoint" ? "not_found" : "restore_failed" } }; }; if (source.kind === "checkpoints") { const env = source.before === undefined ? await takeEnv() : undefined; const hands = env !== undefined && env.handsEnabled; const opened = await openSessionFiles({ session, sessionId, ...(hands ? { tree: treeOf(env) } : {}), history: { unaddressed: unaddressed(sessionId) } }); if (opened.kind !== "opened") return { kind: "checkpoints", source, items: [] }; const history = opened.history; const read = await readCheckpointList({ store, scope: history.historyScope, path: await pathOf(), contentOf, newest: newestOn(hands ? { env: env.env, history } : undefined), limit: source.limit ?? CHANGES_CHECKPOINTS_PAGE_MAX, before: source.before }); if (read.kind === "unavailable") return unavailable(read.reason, read.fault); return { kind: "checkpoints", source, items: read.items, ...(read.nextBefore !== undefined ? { nextBefore: read.nextBefore } : {}) }; } const own = await openSessionFiles({ session, sessionId, target: source.entryId, history: { unaddressed: unaddressed(sessionId) } }); if (own.kind !== "opened") return unavailable("no_checkpoint"); const newest = async (entryId, skipped) => { const env = await takeEnv(); const opened = await openSessionFiles({ session, sessionId, tree: treeOf(env), history: { unaddressed: unaddressed(sessionId) } }); if (opened.kind !== "opened") return { kind: "unavailable", entryId, reason: "files_env_unsupported" }; return newestOn({ env: env.env, history: opened.history })(entryId, skipped); }; const item = await readCheckpointItem({ store, scope: own.history.historyScope, path: await pathOf(), contentOf, newest, entryId: source.entryId }); if (item.kind === "rows") return { kind: "rows", source, before: item.before, after: item.after, rows: item.rows }; return unavailable(item.reason, item.fault); } function answered(req, answer) { req.signal?.throwIfAborted(); return answer; } function screenSessionChangesRequest(request) { const bad = (what) => { const e = new Error(`${VERB}: ${what} — nothing was read. The request is { sessionId, source, contentOf?, cwd?, expect?, signal? }.`); e.code = "changes.invalid_spec"; throw e; }; const { sessionId, source, contentOf, cwd, expect, signal } = readPlainRequest(request, REQUEST_KEYS, bad); if (typeof sessionId !== "string" || sessionId === "") return bad(`sessionId must be a non-empty string, got ${shownValue(sessionId)}`); if (signal !== undefined && !(signal instanceof AbortSignal)) return bad(`signal must be an AbortSignal when given, got ${shownValue(signal)}`); if (cwd !== undefined && !isAbsoluteHostPath(cwd)) return bad(`cwd must be an absolute host path when given (posix "/…", a Windows drive "C:\\…" or UNC "\\\\server\\share\\…"; no ".." segment, no NUL, at most ${ABSOLUTE_HOST_PATH_MAX} characters), got ${shownValue(cwd)}`); const screened = screenSource(source, bad); const named = screenContentOf(contentOf, bad); if (named.size > 0 && screened.kind === "checkpoints") return bad(`contentOf is not taken with source "checkpoints" — one item's texts are source "checkpoint"'s`); return { sessionId, source: screened, contentOf: named, cwd, expect: readOccupantExpectation(expect, bad), signal }; } function screenSource(raw, bad) { const members = readPlainRequest(raw, SOURCE_KEYS, (what) => bad(`source: ${what}`)); const kind = members.kind; if (typeof kind !== "string" || !Object.prototype.hasOwnProperty.call(SOURCE_MEMBERS, kind)) return bad(`source.kind must be one of ${Object.keys(SOURCE_MEMBERS).map((k) => JSON.stringify(k)).join(", ")}, got ${shownValue(kind)}`); const stray = strayMembersOf(members, { subject: `source "${kind}"`, unit: "member", moment: "before anything is read" }, SOURCE_MEMBERS[kind]); if (stray !== undefined) return bad(stray.sentence); if (kind === "checkpoints") { const { limit, before } = members; if (limit !== undefined && !(typeof limit === "number" && Number.isInteger(limit) && limit >= 1 && limit <= CHANGES_CHECKPOINTS_PAGE_MAX)) return bad(`source.limit must be an integer from 1 to ${CHANGES_CHECKPOINTS_PAGE_MAX} when given, got ${shownValue(limit)}`); if (before !== undefined && (typeof before !== "string" || before === "")) return bad(`source.before must be a non-empty entry id when given, got ${shownValue(before)}`); return { kind, ...(limit !== undefined ? { limit: limit } : {}), ...(before !== undefined ? { before: before } : {}) }; } if (kind === "git") { const { base } = members; if (base !== undefined && base !== "head") return bad(`source.base must be "head" when given (the one base this engine reads), got ${shownValue(base)}`); return base === undefined ? { kind } : { kind, base }; } const { entryId } = members; if (typeof entryId !== "string" || entryId === "") return bad(`source.entryId must be a non-empty entry id, got ${shownValue(entryId)}`); return { kind: kind, entryId }; } function screenContentOf(raw, bad) { if (raw === undefined) return new Set(); const paths = readElements(raw); if (paths === undefined) return bad(`contentOf must be a list of paths when given, got ${shownValue(raw)}`); if (paths.length > CHANGES_CONTENT_OF_MAX) return bad(`contentOf names at most ${CHANGES_CONTENT_OF_MAX} paths, got ${paths.length}`); for (const p of paths) if (typeof p !== "string" || p === "") return bad(`contentOf must hold non-empty strings, got ${shownValue(p)}`); return new Set(paths); }