UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

146 lines (145 loc) • 8.09 kB
import { RETIRED_TASK_SPEC_KEYS, retiredKeyOf, retiredKeyRefusal } from "./retired-keys.js"; import { codedRefusal, thrownText } from "./thrown-value.js"; import { screenProjectSeat } from "./project-seat.js"; import { retainSeatError, screenRetainSeat } from "./retain-seat.js"; import { callerKey } from "./caller-text.js"; import { strayMembersOf } from "./own-property-receipt.js"; const SESSION = "session"; const ENTRY = "entry"; const SPEC_MEMBER_TABLE = { taskId: 0, objective: 0, wake: ENTRY, principal: 0, isolationScope: 0, actor: 0, runOrigin: 0, interactionPosture: 0, approvalReach: 0, interactiveQuestionFallback: 0, images: 0, userAttachments: 0, sessionId: SESSION, project: 0, workspace: 0, requireExistingSession: SESSION, oneShot: 0, clientContext: 0, resumeAt: ENTRY, resumeAtMode: ENTRY, model: 0, modelRole: 0, roles: 0, advisorModel: 0, thinking: 0, fastMode: 0, systemPrompt: 0, promptRole: 0, promptForm: 0, promptBinding: 0, promptLocale: 0, appendSystemPrompt: 0, outputStyle: 0, memory: 0, suggestNextPrompts: 0, fileHistory: 0, projectMemory: 0, instructionFamily: 0, restoreFiles: ENTRY, acceptPartialRestore: ENTRY, unplacedHistoryRecordedUnder: ENTRY, rewindFilesTo: ENTRY, tools: 0, allowTools: 0, excludeTools: 0, excludeAllTools: 0, deferTools: 0, toolMaterializeStrategy: 0, alwaysLoadTools: 0, restoreGatedTools: 0, deferSelfResolve: 0, promptLean: 0, agents: 0, toolPolicy: 0, basePolicyForResumeEdit: 0, onAsk: 0, onQuestion: 0, lspManager: 0, lspDiagnostics: 0, mods: 0, peerPresence: 0, durableApproval: 0, resourceSuspend: 0, preemptSignal: 0, resilience: 0, finalVerification: 0, maxSuspends: 0, checkpointStore: 0, handsReadOnly: 0, ownHandsReadOnly: 0, runLedger: 0, managerApproves: 0, team: 0, memoryPersistenceCapable: 0, additionalDirectories: 0, additionalReadDirectories: 0, readDenyPatterns: 0, readDenyBuiltinExclude: 0, writeProtectedAdditions: 0, agentConfigDirs: 0, agentHomeDirs: 0, complianceAdditionalDenies: 0, readFace: 0, writeFace: 0, enablePlanMode: 0, planFile: 0, interactiveTools: 0, enableFork: 0, shellGate: 0, permissionMode: 0, classifyAllShell: 0, blockReadsOutsideRoots: 0, mcp: 0, a2a: 0, skills: 0, userInvokedSkills: 0, allowedTools: 0, skillListingBudgetFraction: 0, skillListingMaxDescChars: 0, backgroundScope: 0, sandbox: 0, envFacts: 0, limits: 0, configOverrides: 0, forwardSubagentEvents: 0, retainSubagentSessions: 0, retainBackgroundProcesses: 0, outputSchema: 0, outputRetries: 0, tracer: 0, toolResultThresholdChars: 0, compaction: 0, attachments: 0, enableBlockedReport: 0, selfOrchestration: 0, getApiKeyAndHeaders: 0, signal: 0, language: 0, }; export const TASK_SPEC_MEMBERS = Object.keys(SPEC_MEMBER_TABLE); export const SESSION_BOUND_SPEC_MEMBERS = TASK_SPEC_MEMBERS.filter((name) => Reflect.get(SPEC_MEMBER_TABLE, name) !== 0); export const SESSION_ENTRY_SPEC_MEMBERS = SESSION_BOUND_SPEC_MEMBERS.filter((name) => Reflect.get(SPEC_MEMBER_TABLE, name) === ENTRY); export function withoutSessionBinding(spec) { const own = { ...spec }; for (const name of SESSION_BOUND_SPEC_MEMBERS) Reflect.deleteProperty(own, name); return own; } export function enteringMembersOf(spec) { return SESSION_ENTRY_SPEC_MEMBERS.filter((name) => { const value = Reflect.get(spec, name); return value !== undefined && value !== false; }); } export function continuingSession(spec, session) { return session !== undefined && session !== "" ? { ...spec, requireExistingSession: true } : spec; } export function withOpeningObjective(spec, objective, continues) { const own = { ...spec, objective, ...(continues !== undefined ? { sessionId: continues } : {}) }; for (const name of continues !== undefined ? SESSION_ENTRY_SPEC_MEMBERS : ["wake"]) Reflect.deleteProperty(own, name); return continuingSession(own, continues); } const MEMBERS = new Set(TASK_SPEC_MEMBERS); const RETIRED_NAMES = [...new Set(Object.keys(RETIRED_TASK_SPEC_KEYS).map((key) => key.split(".")[0].replace(/\[\]$/, "")))]; const READ_NAMES = [...TASK_SPEC_MEMBERS, ...RETIRED_NAMES.filter((name) => !MEMBERS.has(name))]; const READS = new WeakMap(); function specRefusal(code, message, detail) { const e = new Error(message); e.code = code; e.detail = detail; return e; } function unreadable(member, cause) { const why = thrownText(cause); return specRefusal("config.spec_member_unreadable", `TaskSpec.${member} could not be read (${why}) — a run reads each member of its spec once, at its start; a member whose read throws is refused rather than read as absent. Pass the value as a plain data member.`, { member }); } function unknownKeys(names) { const keys = names.map((name) => String(name)); return specRefusal("config.spec_unknown_key", `TaskSpec carries ${keys.length === 1 ? "a key" : "keys"} this engine does not read: ${names.map((name) => callerKey(name)).join(", ")}. Refused rather than ignored: a key that is silently dropped reads to the caller as configured. Drop ${keys.length === 1 ? "it" : "them"}, or spell the member the engine declares.`, { keys: [...keys] }); } export function readCallerSpec(spec, takeSeat) { const known = READS.get(spec); if (known !== undefined) return known; if (spec === null || (typeof spec !== "object" && typeof spec !== "function")) { throw new TypeError(`TaskSpec must be an object (got ${spec === null ? "null" : typeof spec})`); } let own; try { own = { stray: strayMembersOf(spec, { subject: "TaskSpec", unit: "member", moment: "when the run reads its spec" }, READ_NAMES) }; } catch (cause) { own = { cause }; } const values = Object.create(null); let refusal; for (const name of READ_NAMES) { let value; try { value = Reflect.get(spec, name); } catch (cause) { refusal ??= unreadable(name, cause); continue; } if (value !== undefined) values[name] = value; } for (const [key, replacement] of refusal === undefined ? Object.entries(RETIRED_TASK_SPEC_KEYS) : []) { let hit; try { hit = retiredKeyOf(values, { [key]: replacement }); } catch (cause) { refusal = unreadable(key, cause); break; } if (hit !== undefined) { refusal = retiredKeyRefusal(hit, "TaskSpec"); break; } } if (refusal === undefined) { if ("cause" in own) refusal = unreadable("[own keys]", own.cause); else if (own.stray !== undefined) refusal = unknownKeys(own.stray.names); } if (refusal === undefined && "project" in values) { const screened = screenProjectSeat(values["project"]); if (screened.ok) values["project"] = screened.seat; else refusal = codedRefusal(screened.code, screened.message); } if (refusal === undefined && "retainSubagentSessions" in values) { const screened = screenRetainSeat(values["retainSubagentSessions"]); if (!screened.ok) refusal = retainSeatError(screened); else if (screened.seat !== undefined) values["retainSubagentSessions"] = screened.seat; } const members = {}; for (const name of TASK_SPEC_MEMBERS) if (name in values) members[name] = values[name]; if (takeSeat !== undefined && "getApiKeyAndHeaders" in members) members["getApiKeyAndHeaders"] = takeSeat(members["getApiKeyAndHeaders"]); const snapshot = Object.freeze(members); const read = Object.freeze({ spec: snapshot, caller: spec, refusal }); READS.set(snapshot, read); return read; } export function rereadWith(snapshot, members) { const read = readCallerSpec(snapshot); const next = Object.freeze({ ...read.spec, ...members }); READS.set(next, Object.freeze({ spec: next, caller: read.caller, refusal: read.refusal })); return next; }