@sema-agent/core
Version:
Stateless, task-oriented AI agent core
105 lines (104 loc) • 7.68 kB
JavaScript
import { MEMORY_ENGINE_TOOL_NAMES } from "../memory-engine/tools.js";
import { createSharedMemoryTools } from "../shared-memory/tools.js";
import { SHARED_MEMORY_TOOL_NAMES } from "../shared-memory/types.js";
import { defineTool } from "../tools.js";
import { readFrozenSkillGrants, seedSkillGrants, skillSeatReader, tellRetiredSkillDeny } from "../skill-grant.js";
import { allowedToolsNotGrantedNotices, classifiesAllShell, seedAllowEntryTables } from "../allow-entry.js";
import { deliverEngineNotice } from "../engine-notice.js";
import { announceMemoryNotMounted, noticeOncePerSink } from "./announce-once-ledger.js";
import { INSTRUCTIONS_FAMILY_UNDECLARED, instructionFamilyOf, instructionsFamilyUndeclaredNotice } from "./nested-memory-lane.js";
import { SKILL_CONTENT_MAX_CHARS, SKILL_TOOL_NAME, createSkillTool } from "./synthetic-tools.js";
import { loadedSkills } from "./loaded-skills.js";
import { RosterBuilder } from "../tool-roster.js";
import { mountedToolNames } from "../tool-name-aliases.js";
import { valveLeaves } from "../../agents/tool-filter.js";
import { refusalAbout } from "../config-refusal-input.js";
export async function prepareProjectContext(input) {
const { deps, spec, internals, sessionId, hostTaskId, skillGrants, allowedTools, allowedToolTables, roster, toolFaceSnapshot, retiredNames, onceLedger, memoryTools, memoryEngineSession, memorySearchToolsPlanned, memoryPairExcludedName, memoryPairOccupiedName, resume, skillListingBudget } = input;
const tools = roster.tools;
const leaves = valveLeaves(toolFaceSnapshot.selector);
const projectMemoryFact = instructionFamilyOf(spec) === undefined ? "absent" : spec.projectMemory === "disabled" ? "disabled" : "on";
if (projectMemoryFact === "absent" && spec.projectMemory !== "disabled")
noticeOncePerSink(deps.onNotice, INSTRUCTIONS_FAMILY_UNDECLARED, () => deliverEngineNotice(deps.onNotice, instructionsFamilyUndeclaredNotice(sessionId)));
const declaredSkillRank = new Map();
for (const s of spec.skills ?? [])
if (!declaredSkillRank.has(s.name))
declaredSkillRank.set(s.name, declaredSkillRank.size);
const skillSpecs = loadedSkills(spec.skills ?? [], (s, delivered) => {
deps.onError?.(new Error(`Skill "${s.name}" content is ${delivered} chars${delivered === s.content.length ? "" : ` once its base directory resolves (${s.content.length} as written)`}, over the ${SKILL_CONTENT_MAX_CHARS}-char load limit — skill not loaded (skills are never truncated; shrink the body or move material to attachments/files).`), { phase: "config", sessionId });
});
const frozenSkillGrants = readFrozenSkillGrants(resume?.seed.skillGrants);
if (frozenSkillGrants === undefined)
throw new Error("the resumed checkpoint's skill-grant section does not read as grant rows — refusing to seed the run without the refusals it carries (the resume screen refuses this row before the claim)");
const mounted = () => mountedToolNames(tools);
skillGrants.bindMountedNames(mounted, retiredNames);
skillGrants.bindSkills(skillSpecs, SKILL_TOOL_NAME);
const inert = seedAllowEntryTables(allowedToolTables, { skillInert: tellRetiredSkillDeny(deps.onNotice, seedSkillGrants(skillGrants, { skills: skillSpecs, userInvokedSkills: spec.userInvokedSkills, inherited: [...(internals?.inheritedSkillGrants ?? []), ...frozenSkillGrants] }), sessionId, mounted()), inherited: internals?.inheritedAllowedTools, request: allowedTools, deployment: deps.allowedTools }, mounted(), retiredNames);
for (const notice of allowedToolsNotGrantedNotices(inert, sessionId))
deliverEngineNotice(deps.onNotice, notice);
roster.mounts.know({ "listing.skills": skillSpecs.length > 0 });
if (roster.mounts.judge("skill")) {
if (tools.some((t) => t.name === SKILL_TOOL_NAME)) {
const e = new Error(`Tool name "${SKILL_TOOL_NAME}" is reserved when spec.skills is present.`);
e.code = "config.reserved_tool_name";
throw refusalAbout("taskConfig", e);
}
roster.mount(createSkillTool(skillSpecs, skillGrants), { source: "builtin", mountedBy: "optional" });
}
const skillSeatOf = skillSeatReader(skillSpecs, classifiesAllShell(spec), mounted, retiredNames);
const sharedMemoryProvider = deps.sharedMemoryStores;
let sharedMemoryPairMounted = false;
if (sharedMemoryProvider !== undefined) {
const mountedNameDomain = new Set();
for (const t of tools) {
mountedNameDomain.add(t.name);
for (const alias of t.aliases ?? [])
mountedNameDomain.add(alias);
}
const occupiedName = SHARED_MEMORY_TOOL_NAMES.find((n) => mountedNameDomain.has(n));
roster.mounts.know({ "names.occupied.sharedMemory": occupiedName !== undefined });
if (roster.mounts.holds("memory-list")) {
roster.mountAll(createSharedMemoryTools({
provider: sharedMemoryProvider,
context: { sessionId, taskId: hostTaskId, ...(spec.principal !== undefined ? { principal: spec.principal } : {}) },
})
.map((s) => defineTool(s))
.filter((t) => roster.mounts.judgeTool(t)), { source: "builtin", mountedBy: "memory" });
sharedMemoryPairMounted = true;
}
else {
const excludedName = SHARED_MEMORY_TOOL_NAMES.find((n) => !leaves({ name: n }));
announceMemoryNotMounted(onceLedger, sessionId, "shared", SHARED_MEMORY_TOOL_NAMES, excludedName !== undefined
? `the run's tool face (allowTools / excludeTools / excludeAllTools) does not admit "${excludedName}"`
: `this task already declares a tool named "${occupiedName}" (the built-in yields to it)`);
}
}
let memoryEnginePairMounted = false;
roster.mounts.know({ "seat.memoryEngine": memoryEngineSession !== undefined && (memoryTools !== undefined || !memorySearchToolsPlanned) });
if (roster.mounts.holds("memory-search") && memoryTools !== undefined) {
roster.mountAll(memoryTools.map((s) => defineTool(s)).filter((t) => roster.mounts.judgeTool(t)), { source: "builtin", mountedBy: "memory" });
memoryEnginePairMounted = true;
}
else if (memoryEngineSession !== undefined && !memorySearchToolsPlanned) {
announceMemoryNotMounted(onceLedger, sessionId, "engine", MEMORY_ENGINE_TOOL_NAMES, memoryPairExcludedName !== undefined
? `the run's tool face (allowTools / excludeTools / excludeAllTools) does not admit "${memoryPairExcludedName}"`
: `this task already declares a tool named "${memoryPairOccupiedName}" (the built-in yields to it)`);
}
const skillsListing = skillSpecs.length > 0 && leaves({ name: SKILL_TOOL_NAME })
? {
entries: skillSpecs.map((s) => ({
name: s.name,
description: s.description,
...(s.files !== undefined ? { files: s.files.map((f) => ({ path: f.path })) } : {}),
...(declaredSkillRank.get(s.name) !== undefined ? { declaredRank: declaredSkillRank.get(s.name) } : {}),
})),
seedAnnounced: resume !== undefined || spec.sessionId !== undefined,
budget: skillListingBudget,
}
:
(resume?.seed.announcedListings?.skills?.length ?? 0) > 0 || spec.sessionId !== undefined
?
{ entries: [], seedAnnounced: true, budget: skillListingBudget }
: undefined;
return { projectMemoryFact, skillSpecs, skillSeatOf, skillsListing, sharedMemoryPairMounted, memoryEnginePairMounted };
}