UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

171 lines (170 loc) • 7.93 kB
import { bashFirstToolsMountedOn, composePostureFrames, owedPostureRow, postureStandingOf } from "../auto-mode-directive.js"; import { planFileShown } from "./advertised-writable-dirs.js"; import { PRESENT_PLAN_TOOL_NAME } from "../present-plan-tool.js"; import { mintSystemReminder } from "../reminder-mint.js"; import { thrownText } from "../thrown-value.js"; import { rosterEntryNamed } from "../tool-roster.js"; import { delimitUntrusted, sanitizeUntrustedText } from "../untrusted-text.js"; import { appendAdvisorRestate } from "./advisor-instructions.js"; import { languageRestateOption } from "./language-frame.js"; import { sandboxFrameRestateOption } from "./command-sandbox-frame.js"; import { appendAdmittedRow } from "../row-admission.js"; import { adoptHostPromise } from "../host-promise.js"; import { gitRestateOption } from "./git-leg-delivery.js"; import { attachmentEnvelopeTags } from "./turn-attachments.js"; import { restateInstructionFiles } from "./nested-memory-lane.js"; export function postureFactsOf(prepared) { return { mode: prepared.approvalPosture.mode, askEffective: prepared.approvalPosture.askEffective, exitToolMounted: rosterEntryNamed(prepared.toolRoster, PRESENT_PLAN_TOOL_NAME) !== undefined, bashFirstToolsMounted: bashFirstToolsMountedOn(prepared.toolRoster), isChildLeg: prepared.hookIdentity.isDelegatedChild, ...(prepared.advertisedWritableDirs?.planFile !== undefined ? { planFile: planFileShown(prepared.advertisedWritableDirs.planFile.spelled) } : {}), }; } export async function owedPostureText(prepared, ask) { const facts = postureFactsOf(prepared); const owed = owedPostureRow(facts) ?? null; const ref = prepared.postureFrameRef; if (ask === "on_change" && ref.composedFor === owed && owed?.cadence === undefined) return undefined; let messages = []; let read = true; try { messages = (await prepared.session.buildContext()).messages; } catch { read = false; } ref.composedFor = read ? owed : undefined; const frames = composePostureFrames(facts, postureStandingOf(messages, prepared.reminderMark), prepared.engineText); if (frames.length === 0) return undefined; const text = frames.map((frame) => mintSystemReminder(frame, prepared.reminderMark)).join("\n"); ref.protectedText = text; return text; } export function postureRestateOption(prepared) { if (owedPostureRow(postureFactsOf(prepared)) === undefined) return {}; return { postureRestate: () => appendOwedPosture(prepared, "always"), }; } export async function appendOwedPosture(prepared, ask) { if (frameCarried(prepared.frameReceipts, "posture")) return; const ref = prepared.postureFrameRef; const text = await owedPostureText(prepared, ask); if (text === undefined) { if (ref.composedFor !== undefined) ref.unwritten = undefined; return; } const unwritten = () => { ref.composedFor = undefined; ref.unwritten = text; }; if (prepared.batchHaltRef.current !== undefined) return unwritten(); try { await appendAdmittedRow(prepared.admitRows, prepared.session, { role: "user", content: [{ type: "text", text }], timestamp: Date.now(), engineMinted: true }); ref.unwritten = undefined; } catch (err) { unwritten(); try { ref.report?.(new Error(`permission posture frames could not be written to the transcript (stated on the next request's view only; the next boundary writes them): ${thrownText(err)}`)); } catch { } } } export function mintOutputStyleReminder(prepared) { return prepared.outputStyleFrame === undefined ? undefined : mintSystemReminder(sanitizeUntrustedText(prepared.outputStyleFrame, attachmentEnvelopeTags("output_style")), prepared.reminderMark); } async function appendOutputStyleRestate(prepared) { const text = mintOutputStyleReminder(prepared); if (text === undefined) return; try { await appendAdmittedRow(prepared.admitRows, prepared.session, { role: "user", content: [{ type: "text", text }], timestamp: Date.now(), engineMinted: true }); } catch (err) { try { prepared.postureFrameRef.report?.(new Error(`the output style frame could not be written to the transcript (the next boundary a queued input continues asks again): ${thrownText(err)}`)); } catch { } } } export function frameCarried(ledger, source) { return ledger.pending.some((r) => r.source === source); } export function settleFrameReceipts(settled, entryId) { let owed; for (const r of settled) { const step = () => r.commit(entryId); const done = owed === undefined ? step() : owed.then(step); const doneAsync = adoptHostPromise(done); if (doneAsync !== undefined) owed = doneAsync; } return owed; } export function appendBoundaryFrames(prepared, turnOwesRequest) { const styleOwed = prepared.outputStyleFrame !== undefined && !turnOwesRequest && prepared.batchHaltRef.current === undefined && !frameCarried(prepared.frameReceipts, "output_style") && prepared.harness.pendingInjectionCount() > 0; const posture = appendOwedPosture(prepared, "on_change"); return styleOwed ? posture.then(() => appendOutputStyleRestate(prepared)) : posture; } export function planFileRestateOption(prepared) { const seat = prepared.advertisedWritableDirs; const planFile = seat?.planFile; if (seat === undefined || planFile === undefined) return {}; return { planFileRestate: async () => { const read = await seat.readPlanFile(); if (!read.ok || read.text === undefined) return; const body = `A plan file exists from plan mode at: ${planFileShown(planFile.spelled)}\n\nPlan contents:\n\n${delimitUntrusted("plan", read.text)}\n\nIf this plan is relevant to the current work and not already complete, continue working on it.`; try { await appendAdmittedRow(prepared.admitRows, prepared.session, { role: "user", content: [{ type: "text", text: mintSystemReminder(body, prepared.reminderMark) }], timestamp: Date.now(), engineMinted: true }); } catch (err) { try { prepared.postureFrameRef.report?.(new Error(`the plan file reference could not be written to the transcript after the compaction: ${thrownText(err)}`)); } catch { } } }, }; } export function instructionsRestateOption(prepared, echo) { const lane = prepared.nestedMemory; if (lane === undefined) return {}; return { instructionsRestate: async () => { if (prepared.batchHaltRef.current !== undefined) return; await restateInstructionFiles(lane, { session: prepared.session, admitRows: prepared.admitRows, ...(prepared.postureFrameRef.report !== undefined ? { report: prepared.postureFrameRef.report } : {}) }, echo); }, }; } export function compactionRestateOptions(prepared, echo) { const posture = prepared.postureFrameRef.protectedText; const git = prepared.gitStatusRef.protectedText; return { ...gitRestateOption(prepared), ...instructionsRestateOption(prepared, echo), ...postureRestateOption(prepared), ...planFileRestateOption(prepared), ...(prepared.advisorInstruction?.mounted === true ? { advisorRestate: () => appendAdvisorRestate(prepared) } : {}), ...languageRestateOption(prepared), ...sandboxFrameRestateOption(prepared), restatedFrames: { protectedTexts: posture !== undefined ? [posture] : [], restatedTexts: git !== undefined ? [git] : [] }, }; }