UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

689 lines (688 loc) • 32.4 kB
import { mintCompletionId } from "./completion-id.js"; import { ANONYMOUS_SCOPE } from "./isolation-scope.js"; import { receiveRetentionPolicy } from "./retention-policy.js"; import { assertDeletionSessionId } from "./retention.js"; import { readExtensionRequester } from "./extension-requester.js"; import { engineAgentName, occupantAdmits } from "./task-registry-shared.js"; import { deliverEngineNotice } from "./engine-notice.js"; import { isMemberOutcome, memberRowStatusOf, outcomeOfLegacyRow, sealMemberOutcome } from "./member-outcome.js"; import { absentReads, isBoolean, isCount, isFiniteNumber, isRecord, isRowCorrupt, isString, isWord, optional, pair, required, rowShapeReader, takesExit, via, } from "./row-shape.js"; export const BACKGROUND_AGENT_SETTLED_STATUSES = Object.freeze(["completed", "failed", "killed"]); export const BACKGROUND_AGENT_LIVE_STATUSES = Object.freeze(["running", "parked"]); export const BACKGROUND_AGENT_STATUSES = Object.freeze([...BACKGROUND_AGENT_LIVE_STATUSES, ...BACKGROUND_AGENT_SETTLED_STATUSES]); export function isBackgroundAgentSettledStatus(status) { return SETTLED_WORDS.has(status); } export function isBackgroundAgentLiveStatus(status) { return LIVE_WORDS.has(status); } const SETTLED_WORDS = new Set(BACKGROUND_AGENT_SETTLED_STATUSES); const LIVE_WORDS = new Set(BACKGROUND_AGENT_LIVE_STATUSES); import { receiptRefusal } from "./own-property-receipt.js"; import { agentScopeOf, readScopeRekeyInput, rekeyAnswerOf } from "./identity-rekey.js"; export const REVIVED_ROW_CLEARED_FIELDS = Object.freeze([ "settledAt", "stoppedBy", "completionId", "finalOutput", "finalOutputFull", "error", "errorCode", "errorRetryable", "errorKind", "errorRetryAfterMs", "resultIsPartial", "outcome", "refusedAsks", "summary", "recentSteps", "editedFiles", "usage", ]); export function clearRevivedRowTerminalPayload(record) { for (const field of REVIVED_ROW_CLEARED_FIELDS) delete record[field]; } export function nextCycleSeq(row) { return (row.seq ?? 1) + 1; } export const declaresTranscriptDurability = (tier) => tier === "full"; const transcriptIntegrityAnnounced = new Set(); export function announceTranscriptIntegrityGapOnce(handle, scope, sink, tier) { if (sink === undefined || !declaresTranscriptDurability(tier)) return; const key = `${scope ?? ANONYMOUS_SCOPE}\u0000${handle}`; if (transcriptIntegrityAnnounced.has(key)) return; transcriptIntegrityAnnounced.add(key); try { sink(handle, scope); } catch { } } export class BackgroundAgentStoreError extends Error { code; constructor(code, message) { super(message); this.code = code; this.name = "BackgroundAgentStoreError"; } } export const BACKGROUND_AGENT_ROW_MALFORMED_CODE = "agent_record.row_malformed"; const isNonEmptyString = (v) => (typeof v === "string" && v !== "" ? undefined : "is not a non-empty string"); const isCycleNumber = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 1 ? undefined : "is not a stop-cycle number (a safe integer from 1)"); const isSpawnDepth = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 1 ? undefined : "is not a delegation depth (a safe integer from 1)"); const isTrue = (v) => (v === true ? undefined : "is not `true` (the member is `true` or absent)"); export const BACKGROUND_AGENT_ROW_SHAPE = rowShapeReader({ family: "background-agent", code: BACKGROUND_AGENT_ROW_MALFORMED_CODE, sentence: "This background agent's stored row does not read the way this engine reads an agent row — an earlier engine release wrote it before a member it now reads existed, or it was changed in storage. It stays as stored: it is listed as unreadable, not revived, settled or reconciled here, and it can be deleted by its handle.", exit: "list-damaged", segments: [ { name: "rowKey", entries: [required("handle", isString), required("scope", isString)] }, { name: "members", entries: [ required("owner", isString), required("sessionScoped", isBoolean), required("status", isWord(BACKGROUND_AGENT_STATUSES)), required("spawnedAt", isFiniteNumber), required("updatedAt", isFiniteNumber), optional("settledAt", isFiniteNumber), optional("rev", isCount), optional("writerId", isString), optional("writerEpoch", isCount), optional("seq", isCycleNumber), optional("spawnDepth", isSpawnDepth), optional("bornInLedgerRun", isTrue), optional("parkClaimId", isString), optional("parkedCheckpointToken", isString), optional("parkedAt", isFiniteNumber), optional("sessionId", isString), optional("parentSessionId", isString), optional("rootSessionId", isString), optional("agentType", isString), absentReads("name", (row) => engineAgentName(String(row.handle)), isNonEmptyString), via("requestedBy", readExtensionRequester), optional("usage", isRecord), optional("completionId", isString), ], }, ], admitOnly: [pair("scope", (row) => (agentScopeOf(row.scope) === undefined ? "its scope is empty — refusing a row without a scope (world-readable through the fallback)" : undefined))], }); function backgroundAgentRefusal(corrupt) { return new BackgroundAgentStoreError(BACKGROUND_AGENT_ROW_MALFORMED_CODE, BACKGROUND_AGENT_ROW_SHAPE.refusalText(corrupt)); } function agentRowName(raw) { const handle = typeof raw === "object" && raw !== null ? Reflect.get(raw, "handle") : undefined; return `background agent ${typeof handle === "string" ? JSON.stringify(handle) : "(unreadable handle)"}`; } export function readStoredBackgroundAgent(raw, ctx, disclose) { const answer = BACKGROUND_AGENT_ROW_SHAPE.read(raw, ctx); if (!isRowCorrupt(answer)) return answer.row; disclose?.(`${agentRowName(raw)}: ${answer.why} — refused in ${BACKGROUND_AGENT_ROW_MALFORMED_CODE}`); throw backgroundAgentRefusal(answer); } export function admitBackgroundAgent(candidate, ctx) { const answer = BACKGROUND_AGENT_ROW_SHAPE.admit(candidate, ctx); if (isRowCorrupt(answer)) throw backgroundAgentRefusal(answer); return answer.row; } export function canAccessAgentRecord(record, access) { if (access.scope === undefined || record.scope !== access.scope) return false; if (!occupantAdmits(record, access)) return false; if (access.owner !== undefined && access.owner === record.owner) return true; if (access.sessionId !== undefined) { const sessionAnchor = record.sessionScoped ? record.owner : record.parentSessionId; if (sessionAnchor !== undefined && access.sessionId === sessionAnchor) return true; if (record.rootSessionId !== undefined && access.sessionId === record.rootSessionId) return true; } return false; } export const STALE_RUNNING_REAP_ATTRIBUTION = "the host process was interrupted while this agent was running — its in-process state was lost. Check its worktree / output file for partial work before assuming the task landed (stale running row reaped)."; export const BACKGROUND_AGENT_REAP_KNOBS = Object.freeze(["maxAgeMs", "keep", "staleRunningMaxAgeMs"]); export function receiveBackgroundAgentReapOptions(opts) { return receiveRetentionPolicy("BackgroundAgentStore.reap", opts, BACKGROUND_AGENT_REAP_KNOBS); } function canonicalRecord(record) { return JSON.stringify(record, (_key, value) => value !== null && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : value); } export function scopeRekeyCopyOf(source, toScope) { return { ...structuredClone(source), scope: toScope, ...(source.rootSessionScope === source.scope ? { rootSessionScope: toScope } : {}), rev: source.rev + 1 }; } export function planScopeRekey(rows, targetOf, input) { const moves = []; if (input.fromScope !== input.toScope) { for (const source of rows) { const target = targetOf(source.handle); moves.push({ source, target, arrived: target !== null && canonicalRecord(target) === canonicalRecord(scopeRekeyCopyOf(source, input.toScope)) }); } } moves.sort((a, b) => (a.source.handle < b.source.handle ? -1 : a.source.handle > b.source.handle ? 1 : 0)); const conflicting = moves.filter((m) => m.target !== null && !m.arrived).length; const acted = input.mode === "leave" || input.mode === "withdraw" ? moves.filter((m) => m.arrived).length : 0; return { moves, answer: rekeyAnswerOf(input.mode, { rows: moves.length, conflicting, acted }) }; } export function readScopeRekeyPlan(stored, keyOf, input, opts = {}) { const filedUnder = keyOf("", input.fromScope); const sources = []; if (input.fromScope !== input.toScope) { for (const [k, raw] of stored) if (k.startsWith(filedUnder) && (opts.only === undefined || opts.only.has(k))) sources.push(readStoredBackgroundAgent(raw, { key: k }, opts.disclose)); } const targets = new Map(); for (const source of sources) { const k = keyOf(source.handle, input.toScope); targets.set(source.handle, stored.has(k) ? readStoredBackgroundAgent(stored.get(k), { key: k }, opts.disclose) : null); } return planScopeRekey(sources, (handle) => targets.get(handle) ?? null, input); } export function scopeRekeyWritesOf(mode, plan, toScope, keyOf) { switch (mode) { case "plan": return { puts: [], deletes: [] }; case "arrive": return { puts: plan.answer.kind === "conflict" ? [] : plan.moves.filter((m) => !m.arrived).map((m) => { const key = keyOf(m.source.handle, toScope); return { key, row: admitBackgroundAgent(scopeRekeyCopyOf(m.source, toScope), { key }) }; }), deletes: [], }; case "leave": return { puts: [], deletes: plan.moves.filter((m) => m.arrived).map((m) => ({ key: keyOf(m.source.handle, m.source.scope), rev: m.source.rev })) }; case "withdraw": return { puts: [], deletes: plan.moves.flatMap((m) => (m.arrived && m.target !== null ? [{ key: keyOf(m.target.handle, m.target.scope), rev: m.target.rev }] : [])) }; default: { const unhandled = mode; return unhandled; } } } const isCardStatus = (word) => word === "pending" || word === "resolved" || word === "expired"; async function listedCardStatus(store, token, sessionId) { if (store.listBySession === undefined || sessionId === undefined) return undefined; try { let after; for (;;) { const answer = await store.listBySession({ sessionId, ...(after !== undefined ? { after } : {}) }); for (const row of answer.rows) { if ((row.kind === "row" ? row.checkpoint.token : row.token) !== token) continue; const word = row.kind === "row" ? row.checkpoint.status : row.status; return isCardStatus(word) ? word : undefined; } const next = answer.next; if (next === undefined || answer.rows.length === 0 || (after !== undefined && next.createdAt === after.createdAt && next.token === after.token)) return undefined; after = next; } } catch { } return undefined; } const unreadableCardAnnounced = new Set(); export async function parkedCardState(store, card) { let threw = false; try { const cp = await store.get(card.token); if (cp === null) return "missing"; if (isCardStatus(cp.status)) return cp.status; } catch { threw = true; } const listed = await listedCardStatus(store, card.token, card.sessionId); if (listed !== undefined) return listed; const key = `${card.scope}\u0000${card.handle}`; if (!unreadableCardAnnounced.has(key)) { unreadableCardAnnounced.add(key); deliverEngineNotice(undefined, { code: "delegation.parked_card_unreadable", message: `sema durable-agents: parked agent ${card.handle} (scope ${card.scope}) — the state of its approval card cannot be read (${threw ? "the checkpoint store could not decode the card's body" : "the card carries no state word"}, ` + `and the store's session listing did not state its status); the row is left parked, because nothing in this sweep can tell a voided card from a pending one. ` + `A store that lists an unreadable row with its stored status (CheckpointStore.listBySession) lets the sweep settle the row.`, detail: { handle: card.handle, scope: card.scope, cause: threw ? "decode" : "no_state" }, }); } return "unreadable"; } export async function reconcileParkedAgents(stores, scope, now, opts) { const out = { failed: 0, rolledBack: 0 }; const unreadable = new Set(); const isMalformedRowError = (e) => e?.code === BACKGROUND_AGENT_ROW_MALFORMED_CODE; const readRow = async (handle) => { try { return await stores.agentStore.get(handle, scope); } catch (e) { if (isMalformedRowError(e)) { unreadable.add(handle); return null; } throw e; } }; const updateRowIf = async (row, next, expect) => { try { return await stores.agentStore.updateIf(row.handle, scope, next, expect); } catch (e) { if (isMalformedRowError(e)) { unreadable.add(row.handle); return false; } throw e; } }; const excluded = (row) => (opts?.excludeHandles?.has(row.handle) ?? false) || (opts?.excludeWriterId !== undefined && row.writerId === opts.excludeWriterId); const failRow = async (row, why) => { const next = structuredClone(row); next.status = "failed"; next.error = why; next.stoppedBy = "system"; next.settledAt = now; next.updatedAt = now; mintCompletionId(next); delete next.parkedCheckpointToken; delete next.parkClaimId; delete next.parkedAt; try { return await stores.agentStore.update(row.handle, scope, next, { rev: row.rev }); } catch (e) { if (isMalformedRowError(e)) { unreadable.add(row.handle); return false; } throw e; } }; const checkpointState = (row, token) => parkedCardState(stores.checkpointStore, { token, handle: row.handle, scope, sessionId: row.sessionId }); for (const summary of await stores.agentStore.listByScope(scope, { status: "parked" })) { if ("rowVerdict" in summary) { unreadable.add(summary.handle); continue; } const row = await readRow(summary.handle); if (!row || row.status !== "parked") continue; if (excluded(row)) continue; const token = row.parkedCheckpointToken; if (token === undefined) { if (await failRow(row, "parked row lost its approval-checkpoint binding (reconciled)")) out.failed++; continue; } const state = await checkpointState(row, token); if (state === "expired" || state === "missing") { if (await failRow(row, `approval checkpoint ${state} while parked (reconciled)`)) out.failed++; } } const staleMs = opts?.staleClaimMaxAgeMs; if (staleMs !== undefined) { const staleClaims = []; for (const status of ["parked", "running"]) { for (const summary of await stores.agentStore.listByScope(scope, { status })) { if ("rowVerdict" in summary) { unreadable.add(summary.handle); continue; } if (now - summary.updatedAt <= staleMs) continue; const row = await readRow(summary.handle); if (!row || row.status !== status) continue; if (row.parkClaimId === undefined && !(status === "parked" && row.parkedCheckpointToken !== undefined)) continue; if (status === "running" && (row.parkClaimId === undefined || row.parkedCheckpointToken === undefined)) continue; if (excluded(row)) continue; if (now - row.updatedAt <= staleMs) continue; staleClaims.push(row); } } for (const row of staleClaims) { const token = row.parkedCheckpointToken; const state = token === undefined ? "missing" : await checkpointState(row, token); if (row.status === "parked") { if (row.parkClaimId === undefined) { if (state === "resolved") { if (await failRow(row, "approval consumed but the park flip was lost — outcome unknown (reconciled)")) out.failed++; } continue; } if (state === "pending") { const next = structuredClone(row); next.writerEpoch = (row.writerEpoch ?? 0) + 1; next.updatedAt = now; delete next.parkClaimId; if (await updateRowIf(row, next, { rev: row.rev, status: "parked", parkClaimId: row.parkClaimId })) out.rolledBack++; } else if (state === "resolved") { if (await failRow(row, "approval consumed but the resume claimer died before finalize — outcome unknown (reconciled)")) out.failed++; } } else { if (state === "pending") { const next = structuredClone(row); next.writerEpoch = (row.writerEpoch ?? 0) + 1; next.status = "parked"; next.updatedAt = now; delete next.parkClaimId; if (await updateRowIf(row, next, { rev: row.rev, status: "running", parkClaimId: row.parkClaimId })) out.rolledBack++; } else if (state === "expired" || state === "missing") { if (await failRow(row, `approval checkpoint ${state} under a stale resume claim (reconciled)`)) out.failed++; } else if (state === "resolved") { if (await failRow(row, "approval consumed but the resume claimer died before finalize — outcome unknown (reconciled)")) out.failed++; } } } } return { failed: out.failed, rolledBack: out.rolledBack, unreadable: unreadable.size }; } export function agentOutcomeOf(row) { if (!isBackgroundAgentSettledStatus(row.status)) return undefined; const stored = row.outcome; if (stored !== undefined && isMemberOutcome(stored) && memberRowStatusOf(stored.outcome) === row.status) return sealMemberOutcome(stored); const outcomeUnreadable = stored !== undefined && !isMemberOutcome(stored); const read = outcomeOfLegacyRow(row, "background_agent", outcomeUnreadable); if (read?.refused?.unreadable === true) announceUnreadableRowEnding(row, outcomeUnreadable ? "outcome" : "refusedAsks"); return read; } const unreadableRowEndingAnnounced = new Set(); function announceUnreadableRowEnding(row, member) { const handle = typeof row.handle === "string" ? row.handle : "(unnamed row)"; const scope = typeof row.scope === "string" ? row.scope : "(unscoped)"; const key = `${scope}\u0000${handle}`; if (unreadableRowEndingAnnounced.has(key)) return; unreadableRowEndingAnnounced.add(key); deliverEngineNotice(undefined, { code: "delegation.agent_row_ending_unreadable", message: `sema durable-agents: background agent ${handle} (scope ${scope}) — the ${member === "outcome" ? "ending its row stored" : "refused asks its row stored under their old key"} ` + `does not read (changed in storage); the row is answered from its status words, and what the agent did not get done is reported as not known.`, detail: { handle, scope, member }, }); } function toSummary(r) { const requestedBy = readExtensionRequester(r.requestedBy); const refused = agentOutcomeOf(r)?.refused; return { handle: r.handle, scope: r.scope, owner: r.owner, sessionScoped: r.sessionScoped, ...(r.sessionId !== undefined ? { sessionId: r.sessionId } : {}), ...(r.parentSessionId !== undefined ? { parentSessionId: r.parentSessionId } : {}), ...(r.rootSessionId !== undefined ? { rootSessionId: r.rootSessionId } : {}), name: r.name, ...(r.agentType !== undefined ? { agentType: r.agentType } : {}), ...(requestedBy !== undefined ? { requestedBy } : {}), status: r.status, spawnedAt: r.spawnedAt, updatedAt: r.updatedAt, ...(r.settledAt !== undefined ? { settledAt: r.settledAt } : {}), ...(r.usage !== undefined ? { usage: structuredClone(r.usage) } : {}), ...(r.completionId !== undefined ? { completionId: r.completionId } : {}), ...(refused !== undefined ? { refused } : {}), }; } export function delegationRootOf(row) { return row.rootSessionId ?? row.parentSessionId ?? (row.sessionScoped ? row.owner : undefined); } const DELEGATION_ROOT_MAX_CHARS = 256; const CONTROL_CHARACTER = /\p{Cc}/u; export function assertDelegationRoot(rootSessionId) { if (typeof rootSessionId !== "string" || rootSessionId === "" || rootSessionId.length > DELEGATION_ROOT_MAX_CHARS || CONTROL_CHARACTER.test(rootSessionId)) { throw receiptRefusal(`a delegation tree root must be a non-empty string of at most ${DELEGATION_ROOT_MAX_CHARS} characters with no control character, got ${typeof rootSessionId === "string" ? `a string of ${rootSessionId.length} characters` : typeof rootSessionId}`); } } export function queryBackgroundAgents(rows, query, disclose) { let root; if ("root" in query) { const named = query.root; assertDelegationRoot(named); root = named; } const inPartition = (r) => { if (root !== undefined) return delegationRootOf(r) === root; if (r.scope !== query.scope) return false; if (query.sessionId === undefined) return true; const scoped = r.sessionScoped; const anchor = scoped === true ? r.owner : scoped === false ? r.parentSessionId : undefined; return anchor === query.sessionId || r.rootSessionId === query.sessionId; }; const hits = []; for (const r of rows) { if (!inPartition(r)) continue; if (query.status !== undefined && r.status !== query.status) continue; hits.push(r); } hits.sort((a, b) => { const [ka, kb] = [orderKey(a.spawnedAt), orderKey(b.spawnedAt)]; return ka === kb ? 0 : ka < kb ? 1 : -1; }); const page = query.limit !== undefined ? hits.slice(0, Math.max(0, query.limit)) : hits; return page.map((r) => summarizeStoredBackgroundAgent(r, { key: `${String(r.scope)}\u0000${String(r.handle)}` }, disclose)); } export function backgroundAgentSessionRows(rows, scope, sessionId, disclose) { assertDeletionSessionId(sessionId, "BackgroundAgentStore.deleteBySession"); return queryBackgroundAgents(rows, { scope, sessionId }, disclose).flatMap((s) => (!("rowVerdict" in s) && isBackgroundAgentSettledStatus(s.status) ? [s.handle] : [])); } function orderKey(value) { return typeof value === "number" && Number.isFinite(value) ? value : -Infinity; } export function summarizeStoredBackgroundAgent(raw, ctx, disclose) { const answer = BACKGROUND_AGENT_ROW_SHAPE.read(raw, ctx); if (!isRowCorrupt(answer)) return toSummary(answer.row); takesExit(answer, "list-damaged", "background agent listing"); disclose?.(`${agentRowName(raw)}: ${answer.why} — listed as unreadable`); const handle = ctx.authoritative?.handle ?? (typeof raw === "object" && raw !== null ? Reflect.get(raw, "handle") : undefined); return { rowVerdict: BACKGROUND_AGENT_ROW_SHAPE.damagedVerdict(answer), handle: typeof handle === "string" ? handle : "" }; } export function nextBackgroundAgentOnUpdate(live, key, handle, scope, record, expect, disclose) { if (!live || live.scope !== scope) return null; const row = readStoredBackgroundAgent(live, { key }, disclose); if (row.rev !== expect.rev) return null; if (expect.status !== undefined && row.status !== expect.status) return null; if (expect.parkedCheckpointToken !== undefined && (expect.parkedCheckpointToken === null ? row.parkedCheckpointToken !== undefined : row.parkedCheckpointToken !== expect.parkedCheckpointToken)) return null; if (expect.parkClaimId !== undefined && (expect.parkClaimId === null ? row.parkClaimId !== undefined : row.parkClaimId !== expect.parkClaimId)) return null; const stored = structuredClone(record); stored.handle = handle; stored.scope = scope; stored.rev = row.rev + 1; return admitBackgroundAgent(stored, { key }); } export function staleRunningFlip(live, key, scope, now, staleMs, disclose) { if (!live || live.scope !== scope || live.status !== "running") return undefined; const answer = BACKGROUND_AGENT_ROW_SHAPE.read(live, { key }); if (isRowCorrupt(answer)) { disclose?.(`${agentRowName(live)}: ${answer.why} — the stale-running sweep leaves it as stored`); return undefined; } const row = answer.row; if (now - row.updatedAt <= staleMs) return undefined; const next = staleRunningFlipOf(row, now); next.rev = row.rev + 1; return next; } export function staleRunningFlipOf(live, now) { const next = structuredClone(live); next.status = "failed"; next.stoppedBy = "system"; next.summary = next.summary ?? STALE_RUNNING_REAP_ATTRIBUTION; next.error = next.error ?? STALE_RUNNING_REAP_ATTRIBUTION; next.settledAt = now; next.updatedAt = now; mintCompletionId(next); return next; } export function backgroundAgentReapCandidates(rows, scope, disclose) { const out = []; for (const [key, r] of rows) { if (r.scope !== scope) continue; const spawnedAt = r.spawnedAt; const settledAt = r.settledAt; const terminal = isBackgroundAgentSettledStatus(r.status); const stamped = typeof spawnedAt === "number" && Number.isFinite(spawnedAt) && (settledAt === undefined || (typeof settledAt === "number" && Number.isFinite(settledAt))); if (!terminal || !stamped) { if (terminal || !isBackgroundAgentLiveStatus(r.status)) disclose?.(`${agentRowName(r)}: its status or stamps do not read — the retention sweep leaves it in place`); continue; } out.push({ key, spawnedAt: r.spawnedAt, age: r.settledAt ?? r.spawnedAt }); } return out.sort((a, b) => (a.spawnedAt === b.spawnedAt ? 0 : a.spawnedAt < b.spawnedAt ? 1 : -1)); } export class InMemoryBackgroundAgentStore { rows = new Map(); key(handle, scope) { return `${scope}\u0000${handle}`; } async put(record) { const stored = structuredClone(record); stored.rev = record.rev ?? 0; const k = this.key(record.handle, record.scope); const admitted = admitBackgroundAgent(stored, { key: k }); if (this.rows.has(k)) { throw new BackgroundAgentStoreError("agent_record.already_exists", "agent record already exists"); } this.rows.set(k, admitted); } async get(handle, scope) { const k = this.key(handle, scope); const row = this.rows.get(k); return row ? structuredClone(readStoredBackgroundAgent(row, { key: k })) : null; } async update(handle, scope, record, expect) { return this.updateIf(handle, scope, record, { rev: expect.rev }); } async updateIf(handle, scope, record, expect) { const k = this.key(handle, scope); const next = nextBackgroundAgentOnUpdate(this.rows.get(k), k, handle, scope, record, expect); if (next === null) return false; this.rows.set(k, next); return true; } async listBySession(scope, sessionId, opts) { return queryBackgroundAgents(this.rows.values(), { scope, sessionId, status: opts?.status, limit: opts?.limit }); } async listByScope(scope, opts) { return queryBackgroundAgents(this.rows.values(), { scope, status: opts?.status, limit: opts?.limit }); } async listByRoot(rootSessionId, opts) { return queryBackgroundAgents(this.rows.values(), { root: rootSessionId, status: opts?.status, limit: opts?.limit }); } async delete(handle, scope, expect) { const k = this.key(handle, scope); const live = this.rows.get(k); if (!live) return false; if (expect !== undefined && live.rev !== expect.rev) return false; return this.rows.delete(k); } async deleteBySession(scope, sessionId) { const doomed = backgroundAgentSessionRows(this.rows.values(), scope, sessionId); for (const handle of doomed) this.rows.delete(this.key(handle, scope)); return doomed; } async listScopes() { return [...new Set([...this.rows.values()].map((r) => r.scope))].sort(); } async rekeyScope(input) { const read = readScopeRekeyInput("BackgroundAgentStore.rekeyScope", input); const keyOf = (handle, scope) => this.key(handle, scope); const plan = readScopeRekeyPlan(this.rows, keyOf, read); const { puts, deletes } = scopeRekeyWritesOf(read.mode, plan, read.toScope, keyOf); for (const p of puts) this.rows.set(p.key, p.row); for (const d of deletes) if (this.rows.get(d.key)?.rev === d.rev) this.rows.delete(d.key); return plan.answer; } async reap(scope, now, opts) { const policy = receiveBackgroundAgentReapOptions(opts); if (policy.maxAgeMs === undefined && policy.keep === undefined && policy.staleRunningMaxAgeMs === undefined) return 0; const flippedKeys = new Set(); if (policy.staleRunningMaxAgeMs !== undefined) { for (const [k, r] of [...this.rows]) { const flipped = staleRunningFlip(r, k, scope, now, policy.staleRunningMaxAgeMs); if (flipped === undefined) continue; this.rows.set(k, flipped); flippedKeys.add(k); } } const terminal = backgroundAgentReapCandidates(this.rows.entries(), scope); const doomed = new Set(); if (policy.maxAgeMs !== undefined) { for (const r of terminal) { if (r.age < now - policy.maxAgeMs) doomed.add(r.key); } } if (policy.keep !== undefined) { for (const r of terminal.slice(Math.max(0, policy.keep))) doomed.add(r.key); } for (const k of doomed) this.rows.delete(k); return new Set([...flippedKeys, ...doomed]).size; } }