@sema-agent/core
Version:
Stateless, task-oriented AI agent core
222 lines (221 loc) • 16 kB
JavaScript
import { createHash } from "node:crypto";
import { fastModeUnavailableFor } from "../../brain/fast-mode.js";
import { assemblePrompt } from "../../prompt-assembly/assemble.js";
import { buildTurnPromptSnapshot } from "../../prompt-assembly/turn-snapshot.js";
import { adoptCenter } from "../../prompt-assembly/artifact.js";
import { toolsToFingerprintInputs } from "../prefix-declaration.js";
import { defaultTaskRegistry } from "../task-registry.js";
import { callOccupant } from "../task-registry-shared.js";
import { createSyntheticFetchJudge, createSyntheticReadJudge, createSyntheticServedReadJudge, legScreeningOf } from "../synthetic-read-verdict.js";
import { createConsolidationWriteJudge } from "./memory-consolidation-write-judge.js";
import { toolCallFaceOf } from "../tool-roster.js";
import { ORG_ADJUDICATION_TIMEOUT_MS } from "../permission-rule-org.js";
import { retireRead } from "../../tools/fs/fs-shared.js";
import { applyContextShrinkToReadFileState } from "../../tools/fs/index.js";
import { resolveKey } from "../../tools/fs/safety.js";
import { headSegmentsChanged } from "./conversation-segment.js";
import { CHANGED_FILES_MTIME_EPS_MS } from "./turn-attachments.js";
import { frameFileToolsOf, isInstructionLaneEntry, readCompactionRestore } from "../user-attachment.js";
import { createNestedMemoryLane } from "./nested-memory-lane.js";
export const seatInstructionLane = (seat) => createNestedMemoryLane(seat);
export function declaringCallPolicy(turnSnapshotRef, stream) {
return (model, context, options) => {
turnSnapshotRef.current?.refreshRequestPolicy({ thinkingLevel: options?.reasoning ?? null, maxTokens: options?.maxTokens ?? model.maxTokens ?? null, fastSpeed: options?.fastMode?.requested === true && fastModeUnavailableFor(model) === undefined });
return stream(model, context, options);
};
}
export function prepareTurnWiring(input) {
const { deps, dateAnchor, memoryTailOwed, prefixHeadBlocks, systemPromptSeat, harnessTools, promptHashSalt, prefixLedger, model, promptIdentityDigest, systemBlocks, thinking, spec, sessionId, turnSnapshotRef, promptManifest, charsPerToken, handsEnabled, executionEnv, attachmentRootCanonical, readRoots, modelFileReader, existingTargetSeat, hookEnvFace, reminderMark, reminderDisclosureCounts, resolvedReadFace, handsCwdRef, readFileStateForCheckpoint, denyNarrowingPolicy, skillGrants, callerPolicy, inheritedPolicies, ruleSessionInTree, persistedRuleLane, ruleLaneFacts, personRowsBeyondRun, orgRuleLane, stampCallTarget, abortController, hostTaskId, taskScope, buildAssembleInputs, identityFor, adoptsCandidates, centerAdoptionRef, replacedTemplates, harnessRef, carrierReadFace, carrierWriteFace, readDenyAdditionsNormalized, preparedHolder, budgetSnapshot } = input;
const turnSnapshot = buildTurnPromptSnapshot({
provider: model.provider,
modelId: model.id,
artifactDigest: promptIdentityDigest,
layoutGroups: (systemBlocks ?? [{ groupId: "body", cacheControlBoundary: true }]).map((b) => ({ groupId: b.groupId, cacheControlBoundary: b.cacheControlBoundary })),
stableSystemText: systemPromptSeat.current,
toolWire: toolsToFingerprintInputs(harnessTools),
thinkingLevel: thinking ?? null,
maxTokens: model.maxTokens,
hasOutputSchema: spec.outputSchema !== undefined,
cacheRetention: deps.cacheRetention,
sessionId,
taskId: spec.taskId,
}, model.api, (text) => `salted:${createHash("sha256").update(promptHashSalt).update(text).digest("hex")}`);
turnSnapshot.onDeclared = (d) => prefixLedger.declare(d.cause, d.from !== undefined ? { from: d.from } : undefined);
const anchoredHead = dateAnchor?.lastHead;
const headNow = () => ({ blocks: prefixHeadBlocks, tools: turnSnapshot.mountedToolWireDigest });
const segments = anchoredHead !== undefined ? headSegmentsChanged(anchoredHead, headNow()) : [];
prefixLedger.declare("leg_start_inputs", { segments });
const prefixAnchor = { read: dateAnchor, head: headNow, ...(memoryTailOwed !== undefined ? { memory: memoryTailOwed } : {}) };
turnSnapshotRef.current = turnSnapshot;
promptManifest.snapshot = { cacheIdentity: turnSnapshot.cacheIdentity, elements: { ...turnSnapshot.elements } };
promptManifest.lowering = turnSnapshot.lowering;
const promptOverheadTokens = Math.ceil((systemPromptSeat.current.length +
harnessTools.reduce((a, t) => a + t.name.length + (t.description?.length ?? 0) + JSON.stringify(t.parameters ?? {}).length, 0)) / charsPerToken);
const normalizeAttachmentPath = handsEnabled
? async (path) => {
if (attachmentRootCanonical === undefined)
return path;
try {
await readRoots.ready(abortController.signal);
if (abortController.signal.aborted)
return path;
const rk = await resolveKey(executionEnv, attachmentRootCanonical, path, abortController.signal, handsCwdRef?.current, readRoots(), undefined, undefined, resolvedReadFace);
return rk.ok ? rk.key : path;
}
catch {
return path;
}
}
: undefined;
const recentlyReadFiles = handsEnabled && readFileStateForCheckpoint
? () => [...readFileStateForCheckpoint.entries()]
.filter(([, v]) => v.seededFromContext !== true)
.sort((a, b) => (b[1].lastReadAt ?? 0) - (a[1].lastReadAt ?? 0))
.map(([path]) => path)
: undefined;
const onCompactionApplied = handsEnabled && readFileStateForCheckpoint
? (preserveReadState) => applyContextShrinkToReadFileState(readFileStateForCheckpoint, { kind: "summarized", preserveKeys: preserveReadState })
: undefined;
const syntheticLayers = {
skillGrants,
...(denyNarrowingPolicy !== undefined ? { denyNarrowingPolicy } : {}),
...(callerPolicy !== undefined ? { callerPolicy } : {}),
inheritedPolicies, ...(ruleSessionInTree ? { inTreeRuleSession: true } : {}),
...(persistedRuleLane !== undefined ? { persistedRuleLane } : {}),
...(orgRuleLane !== undefined ? { orgRuleLane } : {}),
...(stampCallTarget !== undefined ? { stampCallTarget } : {}),
};
const legFacts = () => {
const p = preparedHolder.current;
return { ...(p?.cwdRef?.current !== undefined ? { cwd: p.cwdRef.current } : {}), ...(p?.handsRoot !== undefined ? { root: p.handsRoot } : {}), ...(p?.advertisedWritableDirs !== undefined ? { advertisedWritableDirs: p.advertisedWritableDirs } : {}), ...(p?.exemptRoots !== undefined ? { exemptRoots: p.exemptRoots } : {}) };
};
const rosterReadFace = () => toolCallFaceOf(preparedHolder.current?.toolRoster, "Read");
const syntheticReadVerdict = createSyntheticReadJudge({ ...syntheticLayers, signal: abortController.signal }, () => ({ ...legFacts(), budget: budgetSnapshot, face: rosterReadFace() }));
const syntheticFetchVerdict = createSyntheticFetchJudge({ ...syntheticLayers, signal: abortController.signal }, () => ({ ...legFacts(), budget: budgetSnapshot, face: toolCallFaceOf(preparedHolder.current?.toolRoster, "WebFetch") }));
const servedReadVerdict = createSyntheticServedReadJudge({ ...syntheticLayers, signal: abortController.signal }, () => ({ ...legFacts(), budget: budgetSnapshot }));
if (handsEnabled && modelFileReader !== undefined) {
existingTargetSeat.current = { judge: createSyntheticServedReadJudge({ ...syntheticLayers, screening: legScreeningOf(() => preparedHolder.current, handsCwdRef, hookEnvFace), signal: abortController.signal }, () => ({ ...legFacts(), budget: budgetSnapshot })), reader: modelFileReader, rulesOnlyJudge: servedReadVerdict };
}
const nestedDeclaration = input.nestedDeclaration;
const laneHands = handsEnabled && modelFileReader !== undefined && readFileStateForCheckpoint !== undefined && attachmentRootCanonical !== undefined ? { env: executionEnv, reader: modelFileReader, judge: servedReadVerdict, readFace: rosterReadFace, state: readFileStateForCheckpoint, root: attachmentRootCanonical, additionalRoots: input.declaredAdditionalRoots } : undefined;
const rosterFileTools = () => frameFileToolsOf(preparedHolder.current?.toolRoster);
const laneCommon = nestedDeclaration === undefined ? undefined : { declaration: nestedDeclaration, signal: abortController.signal, mark: reminderMark, counts: reminderDisclosureCounts, deps, leg: () => preparedHolder.current, fileTools: rosterFileTools };
const nestedMemory = laneCommon === undefined ? undefined : seatInstructionLane(laneHands !== undefined ? { ...laneCommon, ...laneHands } : laneCommon);
const announceRestoreSkip = (path, reason) => {
deps.onError?.(new Error(`compaction restore did not deliver ${path}: ${reason}`), { phase: "degraded", sessionId, classification: "attachment-read" });
};
const restorable = async (candidates, maxFiles) => {
if (nestedMemory === undefined)
return [...candidates];
const kept = [];
for (const path of candidates) {
if (kept.length >= maxFiles)
break;
const key = normalizeAttachmentPath !== undefined ? await normalizeAttachmentPath(path) : path;
if (!nestedMemory.isMember(key, "any"))
kept.push(path);
}
return kept;
};
const compactionRestore = handsEnabled && modelFileReader !== undefined
? {
restore: async (ask) => readCompactionRestore({ reader: modelFileReader, judge: syntheticReadVerdict, mark: reminderMark, counts: reminderDisclosureCounts, signal: abortController.signal, fileTools: rosterFileTools }, { candidates: await restorable(ask.candidates, ask.maxFiles), maxFiles: ask.maxFiles, perFileChars: ask.perFileChars, totalChars: ask.totalChars, charsPerToken: ask.charsPerToken }),
undelivered: announceRestoreSkip,
}
: undefined;
const consolidationWriteJudge = createConsolidationWriteJudge({ ruleStoreProvider: deps.permissionRuleStore, principal: spec.principal, localOwnerDeclared: deps.localOwnerRules === true, ...(callerPolicy !== undefined ? { callerPolicy } : {}) }, { rows: personRowsBeyondRun, lanes: ruleLaneFacts, layers: { skillGrants, ...(denyNarrowingPolicy !== undefined ? { denyNarrowingPolicy } : {}), inheritedPolicies, ...(ruleSessionInTree ? { inTreeRuleSession: true } : {}), ...(stampCallTarget !== undefined ? { stampCallTarget } : {}) }, facts: () => ({ ...legFacts(), face: toolCallFaceOf(preparedHolder.current?.toolRoster, "Write") }) });
const changedFilesReadDenied = async (paths) => {
const deadlineAt = Date.now() + ORG_ADJUDICATION_TIMEOUT_MS;
return Promise.all(paths.map(async (path) => (await syntheticReadVerdict({ file_path: path }, "changed-files", { deadlineAt })).verdict === "deny"));
};
const detectExternalChanges = handsEnabled && readFileStateForCheckpoint
? async (maxFiles) => {
const candidates = [...readFileStateForCheckpoint.entries()]
.filter(([, e]) => e.lastReadAt !== undefined)
.filter(([path]) => nestedMemory?.isMember(path, "root") !== true)
.filter(([, e]) => e.truncated !== true)
.sort((a, b) => (b[1].lastReadAt ?? 0) - (a[1].lastReadAt ?? 0))
.slice(0, Math.max(0, maxFiles));
const changed = [];
const denied = await changedFilesReadDenied(candidates.map(([path]) => path));
for (const [i, [path, entry]] of candidates.entries()) {
if (denied[i] === true)
continue;
try {
const info = await executionEnv.fileInfo(path, abortController.signal);
if (!info.ok) {
if (info.error.code === "not_found" && !(nestedMemory !== undefined && isInstructionLaneEntry(entry)))
retireRead(readFileStateForCheckpoint, path);
continue;
}
if (info.value.mtimeMs > (entry.lastReadAt ?? 0) + CHANGED_FILES_MTIME_EPS_MS) {
changed.push({ path, mtimeMs: info.value.mtimeMs });
}
}
catch {
}
}
return { changed };
}
: undefined;
const taskAccess = { owner: hostTaskId, scope: taskScope, sessionId, ...callOccupant(undefined, { occupant: input.legOccupant }) };
const taskReadHandleOf = (id) => defaultTaskRegistry.readHandleOf(id, taskAccess);
const listBackgroundTasks = (opts) => (opts?.settled === true ? defaultTaskRegistry.list(taskAccess, { limit: 500 }) : defaultTaskRegistry.liveTasks(taskAccess)).map((t) => {
const read = taskReadHandleOf(t.task_id);
return { id: t.task_id, ...(t.description !== undefined ? { description: t.description } : {}), status: t.status, ...(read !== undefined ? { read } : {}) };
});
const overheadState = { promptChars: 0 };
const centerCompactionCandidate = deps.promptSource !== undefined && adoptsCandidates
? () => {
const state = deps.promptSource.sourceState();
const now = centerAdoptionRef.current;
let next;
if (state === "disabled") {
if (now === undefined)
return undefined;
next = undefined;
}
else if (state === "active") {
const cand = deps.promptSource.current();
if (cand === undefined || cand.artifactDigest === now?.artifact.artifactDigest)
return undefined;
next = adoptCenter(cand, cand.sourceRevision);
if (next === undefined)
return undefined;
}
else {
return undefined;
}
let a2;
try {
a2 = assemblePrompt(buildAssembleInputs(next));
}
catch {
return undefined;
}
const promptIdentity = identityFor(next);
const overheadTokensAfter = preparedHolder.current.promptOverheadTokens -
Math.ceil(overheadState.promptChars / charsPerToken) +
Math.ceil(a2.systemPrompt.length / charsPerToken);
return {
promptIdentity,
overheadTokensAfter,
apply: (committedIdentity) => {
systemPromptSeat.current = a2.systemPrompt;
harnessRef.current?.setSystemPrompt(a2.systemPrompt, a2.systemBlocks);
turnSnapshotRef.current?.refreshStableSystem(a2.systemPrompt, committedIdentity);
preparedHolder.current.promptIdentity = promptIdentity;
preparedHolder.current.promptOverheadTokens = overheadTokensAfter;
overheadState.promptChars = a2.systemPrompt.length;
centerAdoptionRef.current = next;
replacedTemplates.current = a2.eventCopy;
},
};
}
: undefined;
overheadState.promptChars = systemPromptSeat.current.length;
const effectiveReadFaceObserved = carrierReadFace();
const effectiveWriteFaceObserved = carrierWriteFace();
const effectiveReadDenyObserved = readDenyAdditionsNormalized.length > 0 ? readDenyAdditionsNormalized.map((e) => ({ ...e })) : undefined;
return { nestedMemory, promptOverheadTokens, compactionRestore, normalizeAttachmentPath, recentlyReadFiles, onCompactionApplied, detectExternalChanges, syntheticReadVerdict, syntheticFetchVerdict, consolidationWriteJudge, listBackgroundTasks, taskReadHandleOf, centerCompactionCandidate, effectiveReadFaceObserved, effectiveWriteFaceObserved, effectiveReadDenyObserved, prefixAnchor };
}