UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

331 lines (330 loc) • 27.1 kB
import { type BrainCallGuardrailRef } from "../../brain/timeout.js"; import type { Model } from "../../internal/llm.js"; import type { ThinkingLevel } from "../../internal/harness.js"; import { type MicroCompactMachine } from "../context-edit.js"; import { type CrossBoundaryPosture } from "../cross-boundary-taint.js"; import { type HostFloor } from "../host-floor.js"; import { type ResourceLedger } from "../checkpoint-store.js"; import { runOriginOfLeg, type RunOrigin } from "../run-origin.js"; import { type FastTierTell } from "../fast-tier-door.js"; import { type LockedPreflight, type ReceivedPeerDeclarations } from "../locked-config.js"; import { type ConfigRefusalInput } from "../config-refusal-input.js"; import type { LegReceipt } from "./leg-receipt.js"; import { type ResolvedRole } from "../roles.js"; import { type ResolvedSkillListingBudget } from "../skill-listing-budget.js"; import type { SessionStore } from "../session.js"; import type { RunnerDeps, TaskLimits, TaskSpec } from "../types.js"; import { type UsageWindow } from "../usage-window-store.js"; import { type AskSeat } from "../wiring-manifest.js"; import type { PrepareResume, RunInternals, ToolFaceLists } from "./contracts.js"; import { resolveHost } from "../../prompt-assembly/select.js"; import type { PromptTraitName, RenderedLocale } from "../../prompt-assembly/catalog/schema.js"; import { type CallerRosterSpec, type RosterSpec } from "./caller-roster.js"; import { type ScreenedNestedMemory } from "./nested-memory-lane.js"; export declare function limitConfigError(code: string, message: string): Error & { code?: string; }; /** * THE one judge of a task-declared quantity that must be evaluable when it is declared: absent (`undefined`: the quantity is not declared, nothing * to judge) or a finite number >= 0. NaN, Infinity, a negative, a numeric string, a boolean and `null` are refused, naming `member` (the path after * `TaskSpec.`) in the sentence and in `detail.field` — a number nobody can evaluate is not a bound, and folding it to a default would run the task * under a bound nobody chose. `0` stays legal. Read by the `limits` object's numeric keys and the `resourceSuspend` allocation's four numbers (their * own code, `config.limit_invalid`) and by the durable-approval opt-in's `ttlMs` (`config.invalid_argument`, the opt-in door's code): every member * one reading, one sentence; `because` is the consequence clause only the member can say. */ export declare function assertFiniteNonNegativeWhenPresent(value: unknown, member: string, code: string, because: string): void; /** * `TaskSpec.principal`: absent (omitted, or the empty string the engine has always read as no principal) or a principal name. A * principal that was PROVIDED and is no name (white space, an invisible or control character, a non-string) is refused at the task, on * every leg a resume's re-supplied config included — read as "no principal" it would reach the unauthenticated floor, or, on a * deployment that declared local-owner rules, the machine owner's standing approvals. * * `TaskSpec.isolationScope` is judged by this same rule (`member`): it falls to the principal through `||`, so a provided value * that names nothing would key the run's working state on a string no name rule ever admitted. */ export declare function assertPrincipalValue(raw: unknown, member?: "principal" | "isolationScope"): void; /** * The checkpoint scopes a task declares beside an isolation scope: each must be absent or equal to it. `durableApproval.scope` outranks * the isolation scope on the checkpoint scope's ladder and `resourceSuspend.scope` outranks the leg's scope outright, so a different * value there would file this scope's parked rows under another one's bucket — refused (`config.invalid_argument`, `detail.field`), * never silently resolved to either. A scope that is ABSENT constrains nothing here: for `durableApproval` the whole object is the opt-in * (omitted, there is none), and an opt-in without its scope never reaches this check — {@link assertDurableApprovalDeclaresScope} * refuses it first; a `resourceSuspend` without its scope never reaches it either — its own door above refuses it. */ export declare function assertCheckpointScopesFollowIsolationScope(spec: Pick<TaskSpec, "isolationScope" | "durableApproval" | "resourceSuspend">): void; /** * `TaskSpec.durableApproval` is the task's durable-park opt-in, and the scope it names is the key its approvals are filed under — the * first rung of the checkpoint-scope ladder and the one the revival of a delegated child reads the opt-in back by. A declaration that * names no scope ({@link readDeclaredCheckpointScope}: not an object, not plain data, no `scope`, a non-string, or a string that is no * name — `""`, white space, a control, separator or format character; the shapes only an untyped host can write, the type requires a * string) is refused here, `config.invalid_argument` with `detail.field` naming the member and the sentence naming the fault — an object is * never described by looking at it (its `constructor`, its keys: a getter or a trap there is the host's code), only by what the reading found — the way a * `resourceSuspend` without its scope is refused by its own door: it was read as the isolation scope on the park path and as no opt-in * on the revival path. The scope is judged by the rule `TaskSpec.isolationScope` is judged by ({@link assertPrincipalValue}), so the * two keys a task can set beside each other are names by one reading. */ export declare function assertDurableApprovalDeclaresScope(declared: unknown): void; /** * The durable-approval opt-in's whole declaration: it names its scope ({@link assertDurableApprovalDeclaresScope}) and its `ttlMs`, when * declared, is evaluable — absent or a finite number >= 0 ({@link assertFiniteNonNegativeWhenPresent}, the judge the `resourceSuspend` * allocation's numbers are judged by). `config.invalid_argument`, `detail.field` = `durableApproval.ttlMs`. The record is plain data once the * scope reading passed (an accessor, a Proxy, a non-own member or a nested container refused it there), so `ttlMs` is read as the value it is. * Run on every leg — a fresh task, a delegated child, a resume's re-supplied config — before any side effect. */ export declare function assertDurableApprovalDeclaration(declared: unknown): void; /** * Validate `TaskSpec.limits` at the door and return it unchanged. * * Two refusals, both fail-loud (the {@link resolveStallTimeoutMs} posture: a bound nobody can evaluate is * not a bound, and folding it to a default would silently run the task under limits nobody chose): * - **unknown key** ⇒ `config.limit_unknown_key`. TypeScript already rejects a stale key, but a wire / * plain-JS caller does not go through TypeScript, and the retired names (`timeoutSec` above all) used * to be honored — accepting them silently is how a caller keeps believing a limit is armed when the * engine has stopped reading it. * - **unevaluable numeric value** (non-number / non-finite / negative) ⇒ `config.limit_invalid`, naming * the key. `0` is legal on every numeric axis: on `maxTurns` it is the documented "unbounded" * sentinel, and on the budget axes it is an exhausted window (absurd but honest). */ export declare function resolveTaskLimits(limits: TaskLimits | undefined): TaskLimits | undefined; /** * Validate the members of `TaskSpec.attachments` that refuse a value they cannot read at the same door, and return the * config unchanged. Today that is the mode-valued `totalTokensReminderMode` and the boolean switches `mcpUnavailable`, * `silentTurnReminder` and `elapsedTimeReminder` (each read by the one switch reader, `attachmentSwitchOn`, which the leg asks * as well). * * WHY A DOOR AT ALL (坏值响亮度律): a knob whose bad value silently folds to the default is a knob the * deployment believes is armed. `totalTokensReminderMode: "padded_countdown"` (underscore) or * `"Countdown"` are the near-misses a hand-written config produces, and both would otherwise read as * "absent" and take the default arm — a DIFFERENT readout than the one that was asked for, with nothing * anywhere saying so. * * DELIBERATELY NARROW, twice over: * - no unknown-KEY refusal (the `resolveTaskLimits` half that has no counterpart here): a wire caller * that sends an attachment flag this engine does not know is asking for a lane that stays off, which * is the family's own default posture — not a ceiling silently disarmed. Widening it would also be a * behavior change for every existing caller, which this additive lane does not license. * - the pre-existing `todoReminderMode` is NOT validated here. It has the same shape and the same * weakness, but tightening it would refuse specs that run today; recorded as a follow-up rather than * folded into this lane's change. * * A NON-OBJECT CONTAINER (`attachments: null` off a wire, above all) is neither refused nor crashed on * (verified by reading): every consumer reads this config through `attachmentsCfg?.…`, * so a null container already means "no lanes are wired" and the spec RUNS today. An unguarded property * read here — the first cut — turned that running spec into an untyped `TypeError` from inside a door * that promises a typed `config.attachment_invalid`, and refusing it instead would newly reject a spec * that works. There is no container-shape door in this family yet; that is a separate widening, not * something this lane gets to invent on the way past. * * The bypass is narrowed to values that CANNOT supply attachment fields: a * plain-JS caller can hand this a FUNCTION carrying `totalTokensReminderMode` as a property, and every * downstream `attachmentsCfg?.…` read would happily find it — so skipping a function here would fold a * typo'd mode to the default through exactly the hole this door exists to close. Functions are * property-bearing containers and are validated like objects; only `null` and primitives pass through. */ export declare function resolveAttachmentsConfig(attachments: TaskSpec["attachments"]): TaskSpec["attachments"]; /** * The run's prompt traits — the one place prepare forms them: the model's declared set (`Model.promptTraits`, read * through the model door: a retired `promptGuidance` or a name that is no trait refuses the task by name) with the * task's switch on `lean_prompt` (`promptLean`, as the spec writes it — an engine-built child's spec carries its * parent's), bundles expanded ({@link effectiveTraitsOf}). The reference's counterpart is a model registry's capability list; sema is * BYOM, so the model entry carries the list and no model id is read. */ export declare function resolvePromptTraits(model: Model, promptLean: boolean | undefined): ReadonlySet<PromptTraitName>; export interface PrepareConfigDoorsInput { /** borrowed-readonly — the snapshot spec (its roster is faces). NEVER mutated here: the per-task agents rebind returns a * SHALLOW COPY on {@link PrepareConfigDoorsResult.spec} (only `tools` replaced, each rebuilt entry through the snapshot). */ spec: CallerRosterSpec; /** borrowed-readonly — deployment seats. Read for: the two containment-face value screens, locked-config preflight, * retention door, interaction-posture door (its disclosure goes to `refusalSink`), usage windows, * brain-call guardrail default, model/role maps. */ deps: RunnerDeps; /** borrowed-readonly — the retention door validates THIS store's declaration (it is one of the * effective stores the leg would run over). No acquire happens in this phase. */ sessions: SessionStore; /** borrowed-readonly — presence gates the resumeAt-conflict door and exempts the empty-objective * door (a checkpoint resume passes `objective: ""` by design). */ resume?: PrepareResume | undefined; /** borrowed-readonly — trusted engine channel: the spawning run's * interaction posture, the engine question-strip flag. */ internals?: RunInternals | undefined; /** borrowed-readonly — the leg's receipt of its spec (leg-receipt.ts): the lock door judges its lists and the per-task agents door its * definitions — the copies the leg holds, never a second read of the caller's. */ receipt: LegReceipt; /** borrowed-readonly — the seat the interaction-posture refusal is also disclosed on (prepare hands `deps.onError`); absent ⇒ the * refusal is only thrown (a judge asking the doors writes to no sink). */ refusalSink?: RunnerDeps["onError"] | undefined; } export interface PrepareConfigDoorsResult { /** owned (by the caller, from here on) — the REBOUND spec: identical to the input object unless * `spec.agents` was set, in which case it is a shallow copy whose `tools` is the * withAgents-rebuilt roster. Every later phase (the safety scan above all — T21) must read THIS, never the original input. */ spec: RosterSpec; /** The deps the leg reads from here on: the caller's, with the deployment role map's one receipt in place of the live map. */ deps: RunnerDeps; /** owned — the frozen task-start copies of the caller's tool-face control arrays; the driver compiles the leg's selector * from them, and the selector (with the disclosure lists) is the ONLY thing later face reads consult. Frozen-immutable. */ toolFaceLists: ToolFaceLists; /** owned — the task-level switch on the lean shape (`TaskSpec.promptLean`, validated; an engine-built child's spec * carries its parent's): what the run hands its children and workflow agents, never its effective traits. */ promptLean: boolean | undefined; /** owned, frozen-by-contract — the run's effective prompt traits ({@link resolvePromptTraits}): the catalog's * variants, every overlay's `when.traits` and each tool's description variants select on them. */ promptTraits: ReadonlySet<PromptTraitName>; /** owned — the one formation of a model's prompt traits for this run ({@link resolvePromptTraits} with the run's * {@link promptLean}): {@link promptTraits} is its answer for the run's model; the write tools' read-first waiver and the * tool cards read it off the model the harness requests with now (a switch mid-run — a budget degrade — moves them, as * the reference reads its model at each call). */ traitsOf: (model: Model) => ReadonlySet<PromptTraitName>; /** owned — the host selector values (`TaskSpec.promptRole` / `TaskSpec.promptForm`, validated) the assembly selects on. */ promptHost: ReturnType<typeof resolveHost>; /** owned — the run's binding (`TaskSpec.promptBinding`, validated): the selector value every overlay's `when.binding` reads. */ promptBinding: string | undefined; /** owned — the run's rendering of the catalog (`TaskSpec.promptLocale`, validated; absent ⇒ the catalog's own text). */ promptLocale: RenderedLocale | undefined; /** owned — the administrator lock snapshot; the rest of prepare reads guarded slots through it. */ lockedPreflight: LockedPreflight; /** owned — the resolved interaction posture (spec > spawning run > deployment); the * AskUserQuestion mount and the child-ctx injection read this same value. */ resolvedInteractionPosture: "interactive" | "headless" | undefined; /** owned, frozen — the run's approval seat ({@link resolveAskSeat}), the one read of the seats; later phases read only this. */ askSeat: AskSeat; /** owned — the validated/resolved microCompact knob ({@link resolveMicroCompactKnob} for the door + placement reasoning). The per-run * state builder consumes exactly these values — the deps bag is never re-read after this door. */ microCompactKnob: { machine: MicroCompactMachine; clearOnRejection: boolean; }; /** owned — the resolved role; its `systemPrompt` seat is still read at prompt-input time. */ resolvedRole: ResolvedRole; /** owned — the resolved main model (`resolvedRole.model`, re-exposed as the name every later phase reads). */ model: Model; /** owned — the input the main model's own declarations came from (the request's Model object, else the deployment's catalog or role * map): the word every door judging what the model declares is entered with. */ modelInput: ConfigRefusalInput; /** owned — caller-explicit > role default > model default; undefined = off. */ thinking: ThinkingLevel | undefined; /** owned, frozen — model-gate DISCLOSURE data (the application itself already * happened on {@link spec}: its `tools` is the survivor rebind when anything was removed). * prepareTask emits the notices from this after the doors return (the onNotice station); * the doors stay side-effect-free on the announcement axis. */ modelGate: { /** gate-class → removed wire names (sorted, unique); empty map = nothing removed. */ removedByClass: ReadonlyMap<string, readonly string[]>; /** stamped classes with no merged-table row (inert tags, fail-open — announce material). */ unknownClasses: readonly string[]; /** a not-in-force `SEMA_TOOL_MODEL_GATE` value outside the closed set (discard-announce * material; the in-force arm never lands here — it throws at the door). */ discardedEnvRaw: string | undefined; }; /** owned — the NORMALIZED per-leg delegation-evidence standard: the deps seat read * ONCE, in this synchronous pre-await stretch, screened, and absent folded to the "static-face" * default. The delegation wrap consumes THIS value, never the live deps object — a deps seat * mutated (or getter-backed) after the door must not present an unscreened value to the mark branch (the read-once posture). */ memoryDelegationEvidence: "static-face" | "attested-only"; /** owned — the lowered skills-listing budget seats (`TaskSpec.skillListingBudgetFraction` / * `skillListingMaxDescChars`): the renderer's two numbers, resolved once against the resolved main * model's window. Read at the door so a bad value refuses BEFORE session acquisition, and carried so * the listing phase and the boundary renderer measure against the same resolution. */ skillListingBudget: ResolvedSkillListingBudget; /** owned — the NORMALIZED memory-provenance mode: the deps seat read ONCE in * the synchronous pre-await stretch, screened, absent folded to the `"carry"` default. * The memory phase constructs every engine with THIS value — never a live deps re-read. */ memoryProvenance: "off" | "carry"; /** owned — the NORMALIZED memory-capture posture: the deps seat read ONCE, * screened (a bad value refuses, never folds), absent folded to `"open"`. The capture * opt-out adjudicator consumes THIS value on every leg (declaration, resume record re-check, * and the flip verb's frozen closure) — never a live deps re-read. */ memoryCapturePolicy: "open" | "governed" | "capture-required"; /** owned — validated deployment governance windows (undefined = ungoverned). */ usageWindows: readonly UsageWindow[] | undefined; /** owned, out-param cell — created EMPTY here; the brain-call wiring later installs into * `.current`. Returned so driver and harness share one cell identity. */ brainCallGuardrailRef: BrainCallGuardrailRef; /** owned — the resolved outer brain-call guardrail (task > deployment > default; undefined per the resolver's off states). */ brainCallGuardrailMs: number | undefined; /** owned — the screened cross-boundary posture: the deps seat read ONCE, a bad value refused; absent stays `undefined` (undeclared is its own fact). */ crossBoundaryPosture: CrossBoundaryPosture | undefined; advisorTool: "disabled" | undefined; hostFloor: HostFloor | undefined; /** owned — the instruction-file family (`NESTED_MEMORY_LANE.declaration`) as its door read it, once; absent ⇒ undeclared. */ nestedMemory: ScreenedNestedMemory | undefined; runOrigin: RunOrigin | undefined; /** owned — the host declared this leg's decision parks cannot be resumed (`TaskSpec.durableApproval: false`), read ONCE here: the rebound * spec carries the opt-in alone, and this word is the `host` source of the leg's one fact (`approvalParkNotResumableOf`). */ hostApprovalParksNotResumable: boolean; } /** The microCompact knob door (坏值响亮度默认律, the sibling knob doors' form: * interactionPosture / toolModelGate / staleToolResultOffload). Placement is load-bearing: * it runs in THIS pre-first-await config-doors phase so a malformed declaration refuses * BEFORE any resource-bearing preparation — session acquisition, execution-env creation, the MCP * dial — whose external effects a late refusal's teardown cannot undo. SINGLE READ per seat, and * the CONTAINER is judged first (reviews r1/r2): an accessor-backed bag answering a legal value at * one read and junk at another must be caught by whichever read this door takes, and a * `microCompact: "cc"` / null / number / array bag makes both property reads answer undefined — * it must refuse exactly like a malformed field, never fold to the defaults. The RESOLVED values * returned here are immutable and are the state builder's ONLY source — nothing re-reads the bag. */ export declare function resolveMicroCompactKnob(bag: RunnerDeps["microCompact"]): { machine: MicroCompactMachine; clearOnRejection: boolean; }; /** The seat a checkpoint-store resolution is judged at: the store the task's own config names, else the deployment's. */ export declare const checkpointStoreSeat: (spec: { checkpointStore?: unknown; }) => "taskConfig" | "deps"; /** The first door of a resume: its re-supplied config is a record. A `null`, a primitive or an array where the record is declared is refused by name * (`config.invalid_argument`), through the same channel as every door after it, before any of its members is read. */ export declare function assertResumeConfigRecord(config: unknown): void; /** The spec the value doors read: a prepare's (its roster is faces) or a resume's re-supplied config (no objective, no session id). */ type ValueDoorSpec = Omit<TaskSpec, "tools" | "objective" | "sessionId" | "userAttachments"> & Partial<Pick<TaskSpec, "objective" | "sessionId" | "userAttachments">>; type ConfigValueDoorsResult = Pick<PrepareConfigDoorsResult, "toolFaceLists" | "promptHost" | "promptBinding" | "promptLocale" | "lockedPreflight" | "microCompactKnob" | "memoryDelegationEvidence" | "memoryProvenance" | "memoryCapturePolicy" | "usageWindows" | "brainCallGuardrailMs" | "crossBoundaryPosture" | "advisorTool" | "promptLean" | "hostFloor" | "runOrigin" | "nestedMemory" | "resolvedInteractionPosture"> & { skillListingSeats: { fraction: unknown; maxDescChars: unknown; }; skills: TaskSpec["skills"]; projectMemory: TaskSpec["projectMemory"]; deploymentRoles: RunnerDeps["roles"]; hostInstance: RunnerDeps["host"]; taskRoles: TaskSpec["roles"]; interactionPostureInput: ConfigRefusalInput; }; /** * The phase's VALUE doors as ONE function with two callers — each judges a declared value against its own vocabulary, reading only the * spec, the deployment's deps, the session store the Runner was constructed over and whether the leg resumes: {@link prepareConfigDoors} * enters them as they stand, and a resume's screen before the claim (`refuseResumeDoors`) enters them through the resume's refusal * channel, so a resume prepare would refuse here is refused before it consumes the row. `enterConfigDoor(seat, door)` names the input that carries * each value; what a door resolves is returned. Every door is total over what a plain-JSON caller can hand it: a `null`, a primitive or an * array where a record is declared is refused by its own code, never read through. */ export declare function configValueDoors(input: { spec: ValueDoorSpec; deps: RunnerDeps; resumeLeg: boolean; sessions: SessionStore; leg?: HolderDoorLeg | undefined; resumedRow?: Parameters<typeof runOriginOfLeg>[1]; receivedPeers?: ReceivedPeerDeclarations; parentInteractionPosture?: RunInternals["parentInteractionPosture"]; discloseInteractionPosture?: (err: Error) => void; tellFastTier?: FastTierTell; }): ConfigValueDoorsResult; /** * The doors a RESUMED leg's prepare refuses at, run as one screen BEFORE the claim — prepare's own functions, so a refusal carries * the very sentence and code prepare throws: the mode doors (`refusePermissionModeDoors`), the output-style and language seats, the approval * reach, the skills invoked by name (the part no roster changes), the attachments (a resume sends no new human message, so any * entry is refused), the leg declarations of the tools it re-supplies (this phase's first door), and this phase's value doors over the config, the deployment's deps and the session store the Runner holds * ({@link configValueDoors}, the retention capability door and the run-origin door over the config's word included). The words the * row recorded (its mode seed, its run origin) are not this door's: the row's own verdict judged them before it (`judgeCheckpointRow`, * checkpoint-row-verdict.ts), so this door reads nothing off the row. It leaves by the resume's ONE refusal channel (`asResumeConfigRefusal`: * `checkpoint.config_refused`, `detail.code` = prepare's code, `detail.field` = `"taskConfig"`, `"deps"` or `"inheritedGate"`) * where prepare would end the leg `failed` after the claim — the row consumed on a store without `reopen`, replayed as a system * retry on one with it, which a configuration fix cannot reach. Before the claim the row stays `pending` and byte-identical and the * corrected resume redeems the same token. A throw that is none of prepare's codes leaves as it was thrown. Returns the config the * leg is handed: the caller's, its MCP servers and A2A peers the lock layer's judged copies of the lists THIS resume handed (read once, dialed as judged; the row records none). */ /** What the holder doors read off the leg's internals (the ones it was started with, never a row's seed): its grant, and whether an * engine lane started it. */ type HolderDoorLeg = Pick<RunInternals, "holder" | "treeHolder" | "isDelegatedChild" | "observerLeg">; export declare function refuseResumeDoors<C extends ValueDoorSpec & Pick<TaskSpec, "userAttachments">>(config: C, deps: RunnerDeps, sessions: SessionStore, internals?: Pick<RunInternals, "holder" | "treeHolder" | "parentInteractionPosture" | "isDelegatedChild" | "observerLeg">, priorLedger?: ResourceLedger): C; export declare function prepareConfigDoors(input: PrepareConfigDoorsInput): PrepareConfigDoorsResult; export {};