@sema-agent/core
Version:
Stateless, task-oriented AI agent core
141 lines (140 loc) • 8.57 kB
JavaScript
import { formatLocalDate, judgedUserTimeZone } from "../../prompts/default.js";
import { requestBodySugar } from "../../prompt-assembly/sugar.js";
import { teamAppendOf } from "../../orchestration/team-run.js";
import { valveLeaves } from "../../agents/tool-filter.js";
import { instructionsTaught, toldAtStart } from "../mounted-mcp.js";
import { isIsolated } from "../remote-env.js";
import { probeGitStatusLane } from "./git-status-frame.js";
import { renderMcpInstructionsEntry } from "./turn-attachments.js";
import { cwdAlignmentProbe, cwdMisalignmentMessage, readCwdAlignment } from "./cwd-alignment-probe.js";
import { GIT_READ_ONLY as G } from "../git-read-only.js";
const ULTRA_REASONING_TIERS = new Set(["xhigh", "max"]);
import { compactionEnabled } from "../context-settings.js";
export async function preparePromptInputs(input) {
const { spec, deps, failClosedReason, lockedPreflight, selfOrchestrationActive, executionEnv, reminderMark, resolvedReadFace, resolvedWriteFace, toolFaceSnapshot, internals, thinking, ownedEnv, delegation, resolvedRole, mcp, model, externalContentTargetActive, resume, handsEnabled, readFloor, taskRootFinal, additionalRootsCanonical, additionalReadRootsCanonical, sessionId, dateAnchor, advertisedWritableDirs } = input;
const promptPolicyEnabled = Boolean(lockedPreflight.toolPolicy);
const promptHooksEnabled = input.modBus.hasHandlers("classic.PreToolUse") || input.modBus.hasHandlers("classic.PostToolUse");
if (failClosedReason) {
deps.onError?.(new Error(failClosedReason), { phase: "config", sessionId });
}
const featureFlags = {
policyEnabled: promptPolicyEnabled,
hooksEnabled: promptHooksEnabled,
isolationEnabled: isIsolated(executionEnv),
reminderMark,
readFaceOpen: resolvedReadFace === "open",
writeFaceOpen: resolvedWriteFace === "open",
orchestrationEnabled: selfOrchestrationActive,
goalEnabled: internals?.goalMode === true,
awarenessEnabled: thinking !== undefined && ULTRA_REASONING_TIERS.has(thinking),
worktreeIsolated: internals?.isolation === "worktree" && ownedEnv !== undefined,
withinTaskCompactionEnabled: compactionEnabled("autoCompact", spec.compaction, input.contextOverlay) && (spec.compaction?.withinTask ?? true),
isSubagent: delegation.isNonForkChild,
memoryStoreAbsent: input.memoryStoreAbsent,
};
const teamAppend = teamAppendOf(internals?.receivedPeers);
const sugar = requestBodySugar({ spec, resolvedRole, ...(teamAppend !== undefined ? { teamAppend } : {}), ...(input.taskRole !== undefined ? { taskRole: input.taskRole } : {}) });
const valveLeft = valveLeaves(toolFaceSnapshot.selector);
const taught = mcp.serverInstructions.filter((entry) => instructionsTaught(valveLeft, entry.server, input.roster.tools, mcp.tools));
toldAtStart(mcp.instructionsDelta, taught);
const say = input.engineText;
const mcpInstructionsBlock = taught.length ? `${say("core/engine.mcp-header")}\n${taught.map((entry) => renderMcpInstructionsEntry(entry, say)).join("\n\n")}` : undefined;
const userTz = spec.clientContext?.timeZone;
const tzValid = judgedUserTimeZone(spec.clientContext) !== undefined;
const envFacts = { date: dateAnchor?.current?.prefixDate ?? formatLocalDate(new Date(), tzValid ? userTz : undefined), modelId: model.id };
if (tzValid)
envFacts.timeZone = userTz;
if (spec.clientContext?.userEmail)
envFacts.userEmail = spec.clientContext.userEmail;
const declaredCutoff = deps.modelKnowledgeCutoffs?.[model.id];
if (declaredCutoff)
envFacts.knowledgeCutoff = declaredCutoff;
if (spec.envFacts?.profile)
envFacts.sandboxProfile = spec.envFacts.profile;
if (spec.envFacts?.capabilities && spec.envFacts.capabilities.length > 0)
envFacts.sandboxCapabilities = [...spec.envFacts.capabilities];
if (spec.envFacts?.pkgSource)
envFacts.sandboxPkgSource = spec.envFacts.pkgSource;
if (spec.envFacts?.egress === "none" || spec.envFacts?.egress === "allowlist" || spec.envFacts?.egress === "full")
envFacts.sandboxEgress = spec.envFacts.egress;
if (spec.envFacts?.scratchpadDir && advertisedWritableDirs?.verdictOf("scratchpad") !== "skipped")
envFacts.scratchpadDir = spec.envFacts.scratchpadDir;
if (externalContentTargetActive)
envFacts.externalContentTarget = true;
if (resume !== undefined && spec.envFacts?.resumeFacts) {
const rf = spec.envFacts.resumeFacts;
const copy = {};
if (rf.processes === "preserved" || rf.processes === "lost")
copy.processes = rf.processes;
if (rf.scratch === "preserved" || rf.scratch === "lost")
copy.scratch = rf.scratch;
if (typeof rf.note === "string" && rf.note.length > 0)
copy.note = rf.note;
if (Object.keys(copy).length > 0)
envFacts.resumeFacts = copy;
}
if (handsEnabled) {
envFacts.cwd = taskRootFinal;
if (additionalRootsCanonical.length > 0) {
envFacts.additionalDirectories = [...additionalRootsCanonical];
}
if (resolvedReadFace !== undefined)
envFacts.readFace = resolvedReadFace;
if (resolvedWriteFace !== undefined)
envFacts.writeFace = resolvedWriteFace;
if (additionalReadRootsCanonical.length > 0) {
envFacts.additionalReadDirectories = [...additionalReadRootsCanonical];
}
try {
const probeFloor = readFloor(undefined);
const probe = await executionEnv.exec(`uname -s; uname -r; (${G} rev-parse --is-inside-work-tree 2>/dev/null || echo false); (${G} symbolic-ref --short -q HEAD 2>/dev/null || echo "HEAD (detached)"); (${G} rev-parse --show-toplevel 2>/dev/null || echo); (test -n "$(${G} status --porcelain 2>/dev/null | head -1)" && echo dirty || echo clean); (s=$(ps -p $$ -o comm= 2>/dev/null); s=\${s##*/}; echo "\${s#-}"); (test "$(${G} rev-parse --git-dir 2>/dev/null)" != "$(${G} rev-parse --git-common-dir 2>/dev/null)" && echo linked || echo main); ` + cwdAlignmentProbe(taskRootFinal), { cwd: envFacts.cwd, timeout: 10, ...(probeFloor !== undefined ? { readFloor: probeFloor } : {}) });
if (probe.ok && probe.value.exitCode === 0) {
const lines = probe.value.stdout.split("\n");
if (lines.length >= 6) {
const [osName, osVer, git, branch, worktreeRoot, dirty] = lines;
if (osName?.trim())
envFacts.platform = osName.trim();
if (osVer?.trim())
envFacts.osVersion = osVer.trim();
envFacts.isGitRepo = (git ?? "").trim() === "true";
if (envFacts.isGitRepo) {
const b = (branch ?? "").trim();
if (b)
envFacts.gitBranch = b;
const root = (worktreeRoot ?? "").trim();
if (root)
envFacts.gitWorktreeRoot = root;
const d = (dirty ?? "").trim();
if (d === "dirty" || d === "clean")
envFacts.gitDirty = d === "dirty";
}
const sh = (lines[6] ?? "").trim();
if (sh)
envFacts.shell = sh;
if (envFacts.isGitRepo && (lines[7] ?? "").trim() === "linked")
envFacts.isLinkedWorktree = true;
const alignment = readCwdAlignment(lines);
if (alignment?.verdict === "differ") {
try {
deps.onError?.(new Error(cwdMisalignmentMessage(taskRootFinal, alignment.shellPwd)), { phase: "config", sessionId });
}
catch {
}
}
}
}
}
catch {
}
}
const gitStatusRef = await probeGitStatusLane({
executionEnv,
envFacts,
handsEnabled,
taskRoot: taskRootFinal,
readFloor: () => readFloor(undefined),
onDegrade: (reason) => deps.onError?.(new Error(`env git snapshot degraded — ${reason}`), { phase: "degraded", sessionId, classification: "env-git-snapshot" }),
say,
});
return { featureFlags, sugar, mcpInstructionsBlock, envFacts, tzValid, userTz, gitStatusRef };
}