UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

228 lines (227 loc) • 15.1 kB
import { createHash } from "node:crypto"; import { textContentHashOf } from "../canonical-json.js"; import { SEND_MESSAGE_TOOL_NAME } from "../../agents/send-message-tool.js"; import { assemblePrompt } from "../../prompt-assembly/assemble.js"; import { adoptCenter, centerOverlaysOf, verifyPromptArtifactBody } from "../../prompt-assembly/artifact.js"; import { copyRefusal, isRetiredRefusal, refusalClause, storedArtifactLine } from "../../prompt-assembly/artifact-store.js"; import { catalogDigestOf, digestOf, prepareEpochRecord } from "../../prompt-assembly/epoch.js"; import { rendererVector } from "../../prompt-assembly/renderers.js"; import { SEMA_DEFAULT_CATALOG } from "../../prompt-assembly/catalog/index.js"; import { describeCatalog } from "../../prompt-assembly/explain.js"; import { engineTextFor } from "../../prompt-assembly/engine-text.js"; import { selectorRecordOf, selectorsOf } from "../../prompt-assembly/select.js"; import { auditToolCollisions, projectToolManifest } from "../../prompt-assembly/tool-catalog.js"; import { buildEnvironmentContext, envFactsForFace } from "../../prompts/default.js"; import { raisePromptCompose } from "../mods/stations.js"; import { protocolOf } from "@sema-agent/primitives"; import { thrownText } from "../thrown-value.js"; import { hasConversationContent } from "../session.js"; import { resolvePromptHashSalt } from "./session-hash-salt.js"; import { prefixHeadBlocksOf } from "./conversation-segment.js"; const CATALOG_DIGEST = catalogDigestOf(SEMA_DEFAULT_CATALOG); const TASK_TEXT_DIGEST_SCHEME = "sid-sha256:"; function taskLayerDigestOf(sessionId, text) { return `${TASK_TEXT_DIGEST_SCHEME}${createHash("sha256").update(sessionId).update("\u0000").update(text).digest("hex")}`; } function taskLayerOf(task, sessionId) { return task.map(({ overlay: o, origin }) => ({ by: origin.by, id: o.id, op: o.op, target: o.target, ...(o.text !== undefined ? { text: taskLayerDigestOf(sessionId, o.text) } : {}), ...(o.message !== undefined ? { message: o.message } : {}), ...(o.when !== undefined ? { when: o.when } : {}), })); } export async function preparePromptAssembly(input) { const { session, deps, internals, resume, sugar, host, binding, locale, modBus, featureFlags, deferred, toolFace, mcpInstructionsBlock, memoryBlock, envFacts, promptTraits, shellFirstSession, skillsAnnounced, tools, model, sessionId, onceLedger } = input; const topLevel = internals?.parentTaskId === undefined && internals?.parentSessionId === undefined && internals?.parentCenterArtifactDigest === undefined; const stored = await session.getPromptEpoch(); const promptHashSalt = await resolvePromptHashSalt(session, (error, step) => onceLedger.onError(new Error(`prompt digests: the session's hash salt could not be ${step === "read" ? "read" : "stored"} (${thrownText(error)}) — this leg's prompt.assembled hashes, turn-snapshot digests and request heads compare within this leg only (hashScope "leg"), and this leg sends no prompt-cache key`), { phase: "config", sessionId })); let centerAdoption; let retiredCenterReplaced; { const failUnavailable = (what, refusal) => { const why = refusal !== undefined ? `the source's copy is ${refusalClause(refusal)}` : `artifact source miss / not verifiable here${deps.promptSource === undefined ? "; RunnerDeps.promptSource is not configured" : ""}`; throw Object.assign(new Error(`prompt snapshot unavailable: ${what} (${why}) — refusing to recompose a hybrid prompt`), { code: "prompt.snapshot_unavailable" }); }; const emitLine = (digest, refusal, consequence) => { deps.onError?.(new Error(storedArtifactLine(digest, refusal, consequence)), { phase: "prompt-constitution", sessionId }); }; const FAIL_CONSEQUENCE = "the session fails prompt.snapshot_unavailable (a hybrid prompt is never recomposed)"; const readPinned = async (digest, sourceRevision) => { const told = {}; const art = await deps.promptSource?.get(digest, (r) => void (told.current = r)); const adopted = art !== undefined ? adoptCenter(art, sourceRevision) : undefined; if (adopted !== undefined) return { adoption: adopted }; const checked = art !== undefined ? verifyPromptArtifactBody(art) : undefined; return { refusal: told.current ?? (checked !== undefined && !checked.ok ? copyRefusal(checked, art, digest) : undefined) }; }; const resolvePinned = async (digest, sourceRevision, via) => { const res = await readPinned(digest, sourceRevision); if ("adoption" in res) return res.adoption; if (res.refusal !== undefined) emitLine(digest, res.refusal, FAIL_CONSEQUENCE); return failUnavailable(`${via} center prompt artifact ${digest.slice(0, 23)}… has no verified resolvable copy`, res.refusal); }; const adoptBySourceState = (retiredPin) => { const state = deps.promptSource?.sourceState() ?? "unavailable"; if (state === "unavailable") { if (retiredPin !== undefined) emitLine(retiredPin.digest, retiredPin.refusal, FAIL_CONSEQUENCE); failUnavailable("this session's center pin is of a retired shape and the center source has no verified state; the pin is kept", retiredPin?.refusal); } const cand = state === "active" ? deps.promptSource.current() : undefined; const adopted = state === "active" ? ((cand !== undefined ? adoptCenter(cand, cand.sourceRevision) : undefined) ?? failUnavailable("this session's center pin is of a retired shape and the current candidate")) : undefined; if (retiredPin !== undefined) emitLine(retiredPin.digest, retiredPin.refusal, `the session's center pin is a retired shape and is replaced by the center source's ${state === "active" ? "current artifact" : "empty center layer"} (recorded as published_schema)`); return adopted; }; const pinned = stored?.kind === "pin" ? stored.descriptor : undefined; let retiredOwnPin; if (pinned?.layers.center !== undefined) { const res = await readPinned(pinned.layers.center, pinned.sourceRevision); if ("adoption" in res) centerAdoption = res.adoption; else if (isRetiredRefusal(res.refusal)) retiredOwnPin = { digest: pinned.layers.center, refusal: res.refusal }; else { if (res.refusal !== undefined) emitLine(pinned.layers.center, res.refusal, FAIL_CONSEQUENCE); failUnavailable(`this session is pinned to center prompt artifact ${pinned.layers.center.slice(0, 23)}… has no verified resolvable copy`, res.refusal); } } const retiredCenterPin = (stored?.kind === "legacy" && stored.centerPinned) || retiredOwnPin !== undefined; if (retiredCenterPin && topLevel) { centerAdoption = adoptBySourceState(retiredOwnPin); if (retiredOwnPin !== undefined) retiredCenterReplaced = true; } else if (stored === undefined || retiredCenterPin) { if (internals?.parentCenterArtifactDigest !== undefined) { centerAdoption = await resolvePinned(internals.parentCenterArtifactDigest, internals.parentCenterSourceRevision, "the spawning parent adopted"); } else if (stored === undefined && topLevel && resume === undefined) { const cand = deps.promptSource?.current(); if (cand !== undefined && !hasConversationContent(await session.getBranch())) { centerAdoption = adoptCenter(cand, cand.sourceRevision); if (centerAdoption === undefined) deps.onError?.(new Error(`center prompt candidate ${cand.artifactDigest.slice(0, 23)}… does not verify on this engine; the session starts with no center layer`), { phase: "prompt-constitution", sessionId }); } } if (retiredOwnPin !== undefined) { emitLine(retiredOwnPin.digest, retiredOwnPin.refusal, `the session's center pin is a retired shape and is replaced by the spawning parent's ${centerAdoption !== undefined ? "layer" : "empty center layer"} (recorded as published_schema)`); retiredCenterReplaced = true; } } } const orchestrationEnabled = featureFlags.orchestrationEnabled && tools.some((t) => t.name === "Workflow"); const facts = { supervisorEnabled: false, teammateEnabled: internals?.explicitAgentName !== undefined && tools.some((t) => t.name === SEND_MESSAGE_TOOL_NAME), ...featureFlags, orchestrationEnabled, orchestrationDeferred: orchestrationEnabled && deferred.has("Workflow"), skillToolMounted: skillsAnnounced, shellFirstSession, toolFace, }; const selectors = selectorsOf(facts, host, binding, promptTraits, locale); const selectorRecord = selectorRecordOf(selectors); const centerOverlays = centerOverlaysOf(centerAdoption); const lowerAdds = new Map(); for (const { overlay } of [...sugar, ...centerOverlays]) if (overlay.op === "add") lowerAdds.set(overlay.id, overlay.target); const composed = await raisePromptCompose(modBus, { model: model.id, catalog: describeCatalog().sections, selectors: selectorRecord }, { lowerAdds, ...(input.signal !== undefined ? { signal: input.signal } : {}) }); for (const w of composed.warnings) deps.onError?.(new Error(w), { phase: "prompt-constitution", sessionId }); const taskOverlays = [...sugar, ...composed.task]; const buildAssembleInputs = (center) => ({ taskOverlays, centerOverlays: centerOverlaysOf(center), deployOverlays: composed.deploy, selectors, tools, facts, ...(envFacts.cwd !== undefined ? { workspaceFolder: envFacts.cwd } : {}), mcpInstructionsBlock, memoryBlock, buildEnvBlock: (date) => buildEnvironmentContext({ ...envFactsForFace(envFacts, selectors.facts.actingToolsAbsent), date }, engineTextFor(selectors.locale)) || undefined, date: envFacts.date, onWarn: (message, phase) => deps.onError?.(new Error(message), { phase, sessionId }), }); const deployLayer = composed.deploy.length > 0 ? digestOf(composed.deploy.map(({ overlay, origin }) => ({ by: origin.by, overlay }))) : undefined; const taskLayer = taskOverlays.length > 0 ? digestOf(taskLayerOf(taskOverlays, sessionId)) : undefined; const bindingLayer = digestOf(selectorRecord); const renderers = rendererVector(); const identityFor = (center) => ({ layers: { catalog: CATALOG_DIGEST, renderers, ...(center !== undefined ? { center: center.artifact.artifactDigest } : {}), ...(deployLayer !== undefined ? { deploy: deployLayer } : {}), ...(taskLayer !== undefined ? { task: taskLayer } : {}), binding: bindingLayer, }, ...(center?.sourceRevision !== undefined ? { sourceRevision: center.sourceRevision } : {}), }); const assembled = assemblePrompt(buildAssembleInputs(centerAdoption)); let systemPrompt = assembled.systemPrompt; const renderWithDate = (date) => (systemPrompt = assembled.renderWithDate(date)); const promptBlocks = assembled.blocks; const collisionAudit = auditToolCollisions(tools); for (const y of collisionAudit.yields) { onceLedger.onError(new Error(`tool mount: caller tool "${y.name}" shadows another tool with the same canonical name (deliberate last-write-wins yield — the later mount serves)`), { phase: "config", sessionId }); } for (const c of collisionAudit.aliasCollisions) { onceLedger.onError(new Error(`tool mount: alias "${c.alias}" is claimed by both "${c.owners[0]}" and "${c.owners[1]}" (a call by that name reaches the tool whose own name it is, else the first tool carrying it as an alias) — rename or drop the conflicting alias`), { phase: "config", sessionId }); } const promptIdentity = identityFor(centerAdoption); const priorConversation = stored === undefined ? hasConversationContent(await session.getBranch()) : true; const record = prepareEpochRecord(stored, promptIdentity.layers, { priorConversation, ...(promptIdentity.sourceRevision !== undefined ? { sourceRevision: promptIdentity.sourceRevision } : {}), ...(retiredCenterReplaced !== undefined ? { retiredCenterReplaced } : {}) }); if (record !== undefined) await session.appendPromptEpoch(record); const current = record ?? (stored?.kind === "pin" ? stored.descriptor : undefined); const { salt } = promptHashSalt; const saltedHash = (text) => createHash("sha256").update(salt).update(text).digest("hex").slice(0, 12); const contentHashOf = (s) => s.renderer !== undefined || s.chain.some((l) => l.source === "task") ? `salted:${createHash("sha256").update(salt).update(s.text).digest("hex")}` : textContentHashOf(s.text); const promptManifest = { identity: { artifact: current.identity, layers: current.layers, epoch: current.epoch, activatedBy: current.activatedBy }, selectors: selectorRecord, blocks: promptBlocks.map((b) => ({ id: b.id, chars: b.text.length, hash: saltedHash(b.text) })), hashScope: promptHashSalt.scope, sections: assembled.sections.map((s) => ({ id: s.id, band: s.band, rank: s.rank, ...(s.variant !== undefined ? { variant: s.variant } : {}), ...(s.renderer !== undefined ? { renderer: { ...s.renderer } } : {}), chars: s.text.length, locale: s.chain.some((l) => l.source !== "bundled" && l.superseded !== true) ? "overlay" : s.variant !== undefined ? selectors.locale : "canonical", contentHash: contentHashOf(s), chain: s.chain.map((l) => ({ ...l })), })), ...(assembled.superseded.length > 0 ? { superseded: assembled.superseded.map((s) => ({ ...s })) } : {}), tools: projectToolManifest(tools, (t) => protocolOf(t.name)?.id ?? "caller"), }; return { systemPromptSeat: { get current() { return systemPrompt; }, set current(v) { systemPrompt = v; } }, renderWithDate, systemBlocks: assembled.systemBlocks, prefixHeadBlocks: prefixHeadBlocksOf(promptBlocks), promptHashSalt, promptManifest, promptIdentity, buildAssembleInputs, identityFor, adoptsCandidates: topLevel, eventCopy: assembled.eventCopy, centerAdoptionRef: { get current() { return centerAdoption; }, set current(v) { centerAdoption = v; } }, }; }