UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

578 lines (577 loc) • 25 kB
import { asAgentMessage, createCompactionSummaryMessage, createCustomMessage, } from "../harness/messages.js"; import { SessionError, isRunLedgerRecord, isSessionCheckoutStand, isSyntheticApiErrorMessage, isValidModelChange, normalizeAnnouncedListing, normalizeCompactionStateCarrier, normalizeGitAnnouncement, normalizeReminderMark, normalizeSessionCheckoutFact, normalizeSessionCheckoutStatement, normalizeWorkspaceState } from "../harness/types.js"; import { readStoredPromptEpoch, walkPromptEpochCarriers } from "../../prompt-assembly/epoch.js"; import { budgetInvokedSkillsRetention, readElidedMessages, readRetainedInvokedSkills, readUnsummarizedMessages, renderInvokedSkillsRetention, } from "../compaction/utils.js"; import { thrownText } from "../../core/thrown-value.js"; const RETENTION_CLAMP_DEFAULT_CHARS_PER_TOKEN = 3; const RETENTION_CLAMP_WINDOW_FRACTION = 0.5; export const ENTRY_RENDERS_INTO_CONTEXT = { message: true, custom_message: true, compaction: true, thinking_level_change: false, model_change: false, custom: false, label: false, session_info: false, leaf: false, prompt_epoch: false, announced_listing: false, workspace_state: false, reminder_mark: false, git_announcement: false, session_checkout: false, run_ledger: false, }; export function entryRendersIntoContext(entry) { return ENTRY_RENDERS_INTO_CONTEXT[entry.type] ?? true; } export function buildSessionContext(pathEntries, opts) { let thinkingLevel = "off"; let model = null; let compaction = null; for (const entry of pathEntries) { if (entry.type !== "compaction") continue; const carried = normalizeCompactionStateCarrier(entry.details); if (carried.thinkingLevel !== undefined) thinkingLevel = carried.thinkingLevel; if (carried.model !== undefined) model = carried.model; } for (const entry of pathEntries) { if (entry.type === "thinking_level_change") { thinkingLevel = entry.thinkingLevel; } else if (entry.type === "model_change") { model = { provider: entry.provider, modelId: entry.modelId }; } else if (entry.type === "message" && entry.message.role === "assistant") { if (!isSyntheticApiErrorMessage(entry.message) && isValidModelChange({ provider: entry.message.provider, modelId: entry.message.model })) { model = { provider: entry.message.provider, modelId: entry.message.model }; } } else if (entry.type === "compaction") { compaction = entry; } } const messages = []; const isAssistantMessage = (m) => m.role === "assistant"; const stripAssistantUsage = (message) => { if (!isAssistantMessage(message)) { return message; } return { ...message, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, }, }; }; const appendMessage = (entry, stripUsage = false) => { if (!entryRendersIntoContext(entry)) return; if (entry.type === "message") { messages.push(stripUsage ? stripAssistantUsage(entry.message) : entry.message); } else if (entry.type === "custom_message") { messages.push(asAgentMessage(createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp))); } }; if (compaction) { let retainedSkills = readRetainedInvokedSkills(compaction.details); if (opts?.windowTokens !== undefined && opts.windowTokens > 0 && retainedSkills.length > 0) { const cpt = opts.charsPerToken ?? RETENTION_CLAMP_DEFAULT_CHARS_PER_TOKEN; const budgetChars = Math.max(0, Math.floor(opts.windowTokens * cpt * RETENTION_CLAMP_WINDOW_FRACTION) - compaction.summary.length); retainedSkills = budgetInvokedSkillsRetention(retainedSkills, budgetChars); } const retainedSkillsBlock = renderInvokedSkillsRetention(retainedSkills); messages.push(asAgentMessage(createCompactionSummaryMessage(compaction.summary + retainedSkillsBlock, compaction.tokensBefore, compaction.timestamp, readElidedMessages(compaction.details), readUnsummarizedMessages(compaction.details), compaction.id))); const compactionIdx = pathEntries.findIndex((e) => e.type === "compaction" && e.id === compaction.id); let foundFirstKept = false; for (let i = 0; i < compactionIdx; i++) { const entry = pathEntries[i]; if (entry.id === compaction.firstKeptEntryId) { foundFirstKept = true; } if (foundFirstKept) { appendMessage(entry, true); } } if (!foundFirstKept) { throw new SessionError("corrupt_session", `Compaction ${compaction.id} firstKeptEntryId (${compaction.firstKeptEntryId}) not found before the compaction entry — session may be corrupt or need migration`, undefined, "kept_start_missing"); } for (let i = compactionIdx + 1; i < pathEntries.length; i++) { appendMessage(pathEntries[i]); } } else { for (const entry of pathEntries) { appendMessage(entry); } } return { messages, thinkingLevel, model }; } export class StoredSession { storage; constructor(storage) { this.storage = storage; } getMetadata() { return this.storage.getMetadata(); } getStorage() { return this.storage; } getLeafId() { return this.storage.getLeafId(); } getEntry(id) { return this.storage.getEntry(id); } getEntries() { return this.storage.getEntries(); } async getBranch(fromId) { const leafId = fromId ?? (await this.storage.getLeafId()); return this.storage.getPathToRoot(leafId); } async buildContext(opts) { return buildSessionContext(await this.getBranch(), opts); } getLabel(id) { return this.storage.getLabel(id); } async getSessionName() { const entries = await this.storage.findEntries("session_info"); return entries[entries.length - 1]?.name?.trim() || undefined; } async appendTypedEntry(entry) { await this.storage.appendEntry(entry, { expectedLeafId: entry.parentId }); return entry.id; } async appendMessage(message) { return this.appendTypedEntry({ type: "message", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), message, }); } async appendThinkingLevelChange(thinkingLevel) { return this.appendTypedEntry({ type: "thinking_level_change", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), thinkingLevel, }); } async appendModelChange(provider, modelId) { return this.appendTypedEntry({ type: "model_change", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), provider, modelId, }); } async appendPromptEpoch(descriptor) { return this.appendTypedEntry({ type: "prompt_epoch", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), ...descriptor, }); } async appendAnnouncedListing(snapshot) { const shaped = normalizeAnnouncedListing(snapshot); if (!shaped) { throw new SessionError("invalid_entry", "appendAnnouncedListing: snapshot is not a structurally valid announced-listing (string arrays, bounded)"); } return this.appendTypedEntry({ type: "announced_listing", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), ...shaped, }); } async appendGitAnnouncement(state) { const shaped = normalizeGitAnnouncement(state); if (!shaped) { throw new SessionError("invalid_entry", "appendGitAnnouncement: state is not a structurally valid git announcement (closed kind, sha256 hash, bounded entryId)"); } return this.appendTypedEntry({ type: "git_announcement", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), ...shaped, }); } async getGitAnnouncement() { const branch = await this.getBranch(); for (let i = branch.length - 1; i >= 0; i--) { const entry = branch[i]; let carried; if (entry.type === "git_announcement") { carried = normalizeGitAnnouncement(entry); } else if (entry.type === "compaction") { carried = normalizeGitAnnouncement(entry.details?.gitAnnouncement); } if (carried === undefined) continue; const announced = carried.pending !== true && carried.entryId !== undefined && gitFrameContextVisible(branch, carried.entryId); return announced ? { kind: carried.kind, hash: carried.hash, status: "announced", entryId: carried.entryId } : { kind: carried.kind, hash: carried.hash, status: "pending" }; } return undefined; } async appendWorkspaceState(state) { const shaped = normalizeWorkspaceState(state); if (!shaped) { throw new SessionError("invalid_entry", "appendWorkspaceState: state is not a structurally valid workspace-state snapshot (bounded absolute paths + a git sha)"); } return this.appendTypedEntry({ type: "workspace_state", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), ...shaped, }); } async appendReminderMark(mark) { const shaped = normalizeReminderMark({ mark }); if (shaped === undefined) { throw new SessionError("invalid_entry", "appendReminderMark: mark is not a bounded url-safe token"); } return this.appendTypedEntry({ type: "reminder_mark", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), mark: shaped, }); } async appendRunLedger(ledger) { let copy; try { copy = structuredClone(ledger); } catch { copy = undefined; } if (!isRunLedgerRecord(copy)) throw new SessionError("invalid_entry", "appendRunLedger: the ledger is not a plain ledger record"); return this.appendTypedEntry({ type: "run_ledger", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), ledger: copy, }); } async getRunLedgers() { const branch = await this.getBranch(); return branch.flatMap((e) => (e.type === "run_ledger" && isRunLedgerRecord(e.ledger) ? [e.ledger] : [])); } async getReminderMark() { const branch = await this.getBranch(); for (let i = branch.length - 1; i >= 0; i--) { const entry = branch[i]; if (entry.type === "reminder_mark") { const shaped = normalizeReminderMark(entry); if (shaped !== undefined) return shaped; } } return undefined; } async getWorkspaceState() { const branch = await this.getBranch(); for (let i = branch.length - 1; i >= 0; i--) { const entry = branch[i]; const carried = entry.type === "workspace_state" ? entry : entry.type === "compaction" ? entry.details?.workspaceState : undefined; if (carried === undefined) continue; const shaped = normalizeWorkspaceState(carried); if (shaped) return shaped; } return undefined; } async getAnnouncedListing() { const branch = await this.getBranch(); for (let i = branch.length - 1; i >= 0; i--) { const entry = branch[i]; if (entry.type === "announced_listing") { const shaped = normalizeAnnouncedListing(entry); if (shaped) return shaped; } else if (entry.type === "compaction") { const restated = normalizeAnnouncedListing(entry.details?.announcedListings); if (restated) return restated; } } return undefined; } async getPromptEpoch() { const branch = await this.getBranch(); const inBranch = await walkPromptEpochCarriers((below) => (below > 0 ? { entry: branch[below - 1], seq: below - 1 } : undefined), branch.length); if (inBranch.found !== undefined) return inBranch.found.stored; const anchor = await this.storage.getEpochAnchor?.(); return anchor === undefined ? undefined : readStoredPromptEpoch(anchor); } async appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook) { const callerObject = details === undefined || (typeof details === "object" && details !== null && !Array.isArray(details)); if (callerObject && details?.sessionCheckout !== undefined) { throw new SessionError("invalid_entry", "appendCompaction: details.sessionCheckout is the engine's restatement of the session's checkout record; a caller does not write it"); } const parentId = await this.storage.getLeafId(); const carried = await (async () => { try { const ctx = buildSessionContext(await this.getBranch()); return { thinkingLevel: ctx.thinkingLevel, ...(ctx.model !== null ? { model: ctx.model } : {}) }; } catch { return undefined; } })(); const standing = {}; if (callerObject) { standing.workspaceState = await this.getWorkspaceState().catch(() => undefined); try { const metadata = await this.storage.getMetadata(); const read = foldSessionCheckout(await sessionCheckoutCopiesOf(this.storage), metadata.id); standing.sessionCheckout = sessionCheckoutStatementOf(read, metadata.id, await checkoutDeclarationClosed(this.storage, metadata, true)); } catch { } } const definedOverrides = Object.fromEntries(Object.entries(details ?? {}).filter(([, v]) => v !== undefined)); const restated = { ...(carried ?? {}), ...(standing.workspaceState !== undefined ? { workspaceState: standing.workspaceState } : {}) }; const mergedDetails = !callerObject ? details : details === undefined && Object.keys(restated).length === 0 && standing.sessionCheckout === undefined ? undefined : { ...restated, ...definedOverrides, ...(standing.sessionCheckout !== undefined ? { sessionCheckout: standing.sessionCheckout } : {}) }; return this.appendTypedEntry({ type: "compaction", id: await this.storage.createEntryId(), parentId, timestamp: new Date().toISOString(), summary, firstKeptEntryId, tokensBefore, details: mergedDetails, fromHook, }); } async appendCustomEntry(customType, data) { return this.appendTypedEntry({ type: "custom", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), customType, data, }); } async appendCustomMessageEntry(customType, content, display, details) { return this.appendTypedEntry({ type: "custom_message", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), customType, content, display, details, }); } async appendLabel(targetId, label) { if (!(await this.storage.getEntry(targetId))) { throw new SessionError("not_found", `Entry ${targetId} not found`); } return this.appendTypedEntry({ type: "label", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), targetId, label, }); } async appendSessionName(name) { return this.appendTypedEntry({ type: "session_info", id: await this.storage.createEntryId(), parentId: await this.storage.getLeafId(), timestamp: new Date().toISOString(), name: name.trim(), }); } } export function gitFrameContextVisible(branch, entryId) { let frameIdx = -1; let compactionIdx = -1; let firstKeptId; for (let i = 0; i < branch.length; i++) { const e = branch[i]; if (e.id === entryId) frameIdx = i; if (e.type === "compaction") { compactionIdx = i; firstKeptId = e.firstKeptEntryId; } } if (frameIdx === -1) return false; if (compactionIdx === -1 || frameIdx > compactionIdx) return true; if (firstKeptId === undefined) return false; const keptIdx = branch.findIndex((e) => e.id === firstKeptId); return keptIdx !== -1 && frameIdx >= keptIdx; } export async function readSessionCheckout(session, sessionId) { let id = sessionId; if (id === undefined) { try { id = (await session.getMetadata()).id; } catch (err) { return { kind: "unreadable", detail: `the session row could not be read (${thrownText(err)})` }; } } try { return foldSessionCheckout(await sessionCheckoutCopiesOf(session.getStorage()), id); } catch (err) { return { kind: "unreadable", detail: `the session log could not be read (${thrownText(err)})` }; } } async function sessionCheckoutCopiesOf(storage) { const floor = storage.getFloorId?.() ?? null; const entries = await storage.findEntries("session_checkout"); return { entries, compactions: await storage.findEntries("compaction"), floor }; } function foldSessionCheckout({ entries, compactions, floor }, sessionId) { let allocation; const releases = []; let stated = false; const take = (record) => { if (record.released === true) { releases.push(record.allocationId); return undefined; } if (allocation === undefined) allocation = record; else if (allocation.allocationId !== record.allocationId) return { kind: "unreadable", detail: `the session holds two checkout allocations (${allocation.allocationId}, ${record.allocationId})` }; else if (JSON.stringify(allocation) !== JSON.stringify(record)) return { kind: "unreadable", detail: `the session's checkout allocation ${record.allocationId} is recorded two different ways` }; return undefined; }; let stand; const takeStand = (next) => { if (stand === undefined) stand = next; else if (stand.standsIn !== next.standsIn || stand.allocationId !== next.allocationId) return { kind: "unreadable", detail: `the session records two different stands (in ${stand.standsIn}, in ${next.standsIn})` }; return undefined; }; for (const entry of entries) { const shaped = normalizeSessionCheckoutFact(entry); if (shaped === undefined) { const owner = entry.sessionId; if (typeof owner === "string" && owner !== sessionId) continue; return { kind: "unreadable", detail: `session_checkout entry "${entry.id}" is not a valid checkout record` }; } if (shaped.sessionId !== sessionId) continue; const refused = isSessionCheckoutStand(shaped) ? takeStand(shaped) : take(shaped); if (refused !== undefined) return refused; } for (const compaction of compactions) { const carried = compaction.details?.sessionCheckout; if (carried === undefined) continue; const statement = normalizeSessionCheckoutStatement(carried); if (statement === undefined) { const owner = carried?.sessionId; if (typeof owner === "string" && owner !== sessionId) continue; return { kind: "unreadable", detail: `compaction "${compaction.id}" restates the session's checkout in a shape that is not valid` }; } if (statement.sessionId !== sessionId) continue; stated = true; if (statement.kind === "unreadable") return { kind: "unreadable", detail: `compaction "${compaction.id}" restates the session's checkout record as unreadable` }; if (statement.kind === "record") { const { released, ...held } = statement.record; const refused = take(held) ?? (released === true ? take(statement.record) : undefined); if (refused !== undefined) return refused; } if (statement.kind === "stands") { const refused = takeStand(statement.stand); if (refused !== undefined) return refused; } } const unvouched = floor !== null && !stated ? { window: { floor } } : {}; if (stand !== undefined) { if (allocation !== undefined || releases.length > 0) return { kind: "unreadable", detail: "the session records both a checkout of its own and a stand in another session's checkout" }; return { kind: "stands", standsIn: stand.standsIn, allocationId: stand.allocationId }; } if (allocation === undefined) return releases.length === 0 ? { kind: "none", ...unvouched } : { kind: "unreadable", detail: "the session holds a checkout release with no allocation", ...unvouched }; const held = allocation; if (releases.some((id) => id !== held.allocationId)) return { kind: "unreadable", detail: "a checkout release names another allocation" }; return { kind: "record", record: releases.length > 0 ? { ...held, released: true } : held }; } export function sessionCheckoutStatementOf(read, sessionId, closed) { if (read.kind === "record") return { sessionId, kind: "record", record: read.record }; if (read.kind === "stands") return { sessionId, kind: "stands", stand: { allocationId: read.allocationId, sessionId, standsIn: read.standsIn } }; if (read.window !== undefined) return undefined; return read.kind === "unreadable" ? { sessionId, kind: "unreadable" } : closed ? { sessionId, kind: "none" } : undefined; } export async function checkoutDeclarationClosed(storage, metadata, landing = false) { if (metadata.forkedFrom !== undefined) return false; return landing || (await storage.findEntries("message")).length > 0 || (await storage.findEntries("compaction")).length > 0; } export async function appendSessionCheckout(session, record, observedLeafId) { const shaped = normalizeSessionCheckoutFact(record); if (shaped === undefined) throw new SessionError("invalid_entry", "appendSessionCheckout: the record is not a structurally valid session checkout"); const storage = session.getStorage(); const parentId = observedLeafId !== undefined ? observedLeafId : await storage.getLeafId(); const entry = { type: "session_checkout", id: await storage.createEntryId(), parentId, timestamp: new Date().toISOString(), ...shaped }; await storage.appendEntry(entry, { expectedLeafId: entry.parentId }); return entry.id; }