@sema-agent/core
Version:
Stateless, task-oriented AI agent core
219 lines (218 loc) • 17.3 kB
TypeScript
import type { AgentHarness, AgentTool, ExecutionEnv, ThinkingLevel } from "../../internal/harness.js";
import type { Model, StreamFn } from "../../internal/llm.js";
import { type AssembledPrompt, type AssembleInputs } from "../../prompt-assembly/assemble.js";
import { type TurnPromptSnapshot } from "../../prompt-assembly/turn-snapshot.js";
import { type CenterAdoption } from "../../prompt-assembly/artifact.js";
import type { RunPromptIdentity } from "../../prompt-assembly/epoch.js";
import type { SessionPrefixLedger } from "./prefix-ledger.js";
import type { ToolCallRequest, ToolPolicy } from "../tool-policy.js";
import { type SyntheticFetchJudge, type SyntheticReadJudge } from "../synthetic-read-verdict.js";
import type { ExistingTargetSeat } from "../existing-target.js";
import type { ConsolidationWriteJudge } from "../memory-engine/consolidation-driver.js";
import { type ConsolidationWriteJudgeLeg } from "./memory-consolidation-write-judge.js";
import type { RunnerDeps, TaskSpec } from "../types.js";
import { type CwdRef } from "../../tools/fs/fs-shared.js";
import { type ContainmentFace } from "../../tools/fs/index.js";
import type { ReadRootsSeat } from "./person-path-rows.js";
import { type ReadFileState } from "../../tools/fs/safety.js";
import type { DateAnchorRead, MemoryTailSnapshot, Prepared } from "./contracts.js";
import { type DeclaredRoot, type NestedMemoryLane, type NestedMemoryLaneSeat, type ScreenedNestedMemory } from "./nested-memory-lane.js";
/** Single construction site for the instruction-file lane (live legs and `Runner.previewInstructions`). */
export declare const seatInstructionLane: (seat: NestedMemoryLaneSeat) => NestedMemoryLane;
import type { ModelFileReader } from "../../tools/fs/fs-read.js";
import type { ReminderDisclosureCounts } from "../reminder-disclosure.js";
export interface PrepareTurnWiringInput {
/** borrowed-readonly — the occupant this leg acts for (`OccupantMount.occupant`): the leg's lists of its background tasks show that occupant's only. */
legOccupant: () => string | undefined;
/** borrowed-readonly — the deployment seats: `onError` (the attachment-skip degraded line), `promptSource` (the center
* candidate's state and current artifact), `permissionRuleStore` and `localOwnerRules` (the consolidation write judge's
* owner of the rows). Receiver preserved. */
deps: Pick<RunnerDeps, "onError" | "onNotice" | "promptSource" | "permissionRuleStore" | "localOwnerRules" | "cacheRetention">;
/** borrowed-readonly — the session's epoch anchor as prepare read it (undefined ⇒ the branch was unreadable): the leg-start comparison reads it. */
dateAnchor: DateAnchorRead | undefined;
/** borrowed-readonly — the memory store content this leg read live and owes the anchor (the memory phase's composition), or undefined. */
memoryTailOwed: MemoryTailSnapshot | undefined;
/** borrowed-readonly — the head's per-block digests (the prompt-assembly phase's): the leg-start comparison reads them. */
prefixHeadBlocks: Readonly<Record<string, string>>;
/** borrowed-mutable — the LIVE system prompt (the prompt-assembly phase's accessor cell). Read: the snapshot's stable text,
* the overhead term. Writer here: the center candidate's `apply` (the boundary swap). */
systemPromptSeat: {
current: string;
};
/** borrowed-readonly — the FINAL wire tool list (the snapshot's tool wire, the overhead sum). */
harnessTools: ReadonlyArray<AgentTool>;
/** borrowed-readonly — the session's hash salt (the prompt-assembly phase's): the snapshot's prompt-text digests. */
promptHashSalt: Uint8Array;
/** borrowed-mutable — the session's prefix ledger: every declaration the leg's snapshot takes, and the leg start's
* opening against the session's anchor, are declared to it (the next main request's change carries them). */
prefixLedger: Pick<SessionPrefixLedger, "declare">;
/** borrowed-readonly — the task model: `provider` / `id` / `maxTokens` / `api` (the snapshot's identity elements). */
model: Pick<Model, "provider" | "id" | "maxTokens" | "api">;
/** borrowed-readonly — the run's prompt identity (the snapshot's `artifactDigest` element). */
promptIdentityDigest: string;
/** borrowed-readonly — the assembled prompt's physical block face, or undefined (the snapshot's layout groups). */
systemBlocks: AssembledPrompt["systemBlocks"];
/** borrowed-readonly — the resolved thinking level, or undefined (a snapshot element). */
thinking: ThinkingLevel | undefined;
/** borrowed-readonly — the REBOUND spec; only `outputSchema` (presence), `taskId` (the snapshot's identity) and `principal`
* (whose rows the consolidation write judge reads). */
spec: Pick<TaskSpec, "outputSchema" | "taskId" | "principal">;
/** borrowed-readonly — the acquired session id (the snapshot; the attachment-skip attribution). */
sessionId: string;
/** borrowed-mutable — the snapshot ref the tool-disclosure phase minted. Writers: THIS phase seeds `current`; the candidate's
* `apply` calls `refreshStableSystem`; the disclosure phase's rebuild seam calls `refreshTools`; the run loop assigns
* `current.onChange` (the snapshot-changed trace emitter) once Prepared is built. */
turnSnapshotRef: {
current?: TurnPromptSnapshot;
};
/** borrowed-mutable — the composition manifest (`Prepared.promptManifest`). Writer here: the identity/lowering BACKFILL
* (the snapshot needs the final wire list, which exists only now). */
promptManifest: Prepared["promptManifest"];
/** borrowed-readonly — the model's structural coefficient (the context lane's), the overhead term's coordinate. */
charsPerToken: number;
/** borrowed-readonly — whether an execution env is wired (every reader exists only then). */
handsEnabled: boolean;
/** borrowed-readonly — the run's resolved env (the readers read and stat through it). */
executionEnv: ExecutionEnv;
/** borrowed-readonly — the canonical attachment root, or undefined (the readers' containment fence). */
attachmentRootCanonical: string | undefined;
/** borrowed-readonly — the read face's root set beside the attachment root, read per use: the write roots, the read
* roots with the run's grants, the person's read directories as the run read them last (no call: `ready` first). */
readRoots: (() => readonly string[]) & Pick<ReadRootsSeat, "ready">;
/** borrowed-readonly — the leg's one file reader (the hands band's), or undefined without hands: the restore reads through it. */
modelFileReader: ModelFileReader | undefined;
/** borrowed-mutable — the run's card-target source. Writer here, once: with hands and a reader, `current` is set to the
* served-read judge over the run's layers and the reader above (the ask and park lanes read it per card). */
existingTargetSeat: ExistingTargetSeat; /** borrowed-readonly — the leg's one hook environment face (the live gate's), handed to the screened judge's probes. */
hookEnvFace?: import("../hooks.js").HookEnvCapabilities;
/** borrowed-readonly — the run's reminder mark (the restore frames' marked blocks). */
reminderMark: string | undefined;
/** borrowed-mutable — the run's disclosure counters; the restore frames' scans bump them when a frame is delivered. */
reminderDisclosureCounts: ReminderDisclosureCounts | undefined;
/** borrowed-readonly — the resolved read face, or undefined (the fence's ninth argument). */
resolvedReadFace: ContainmentFace | undefined;
/** borrowed-readonly — the tracked-cwd seat, read per call by the kept-tail normalizer (never written here). */
handsCwdRef: CwdRef | undefined;
/** borrowed-mutable — the live read-file state, or undefined. Writers here, at RUN time: `detectExternalChanges` evicts a
* not-found entry; `onCompactionApplied` applies a landed compaction to it. The hands phase mints it. */
readFileStateForCheckpoint: ReadFileState | undefined;
/** borrowed-readonly — the deny-narrowing fold, or undefined (a layer of the synthetic-Read judge). */
denyNarrowingPolicy: ToolPolicy | undefined;
/** borrowed-readonly — the skill lane: the run's skill deny rows (a layer of the judge; only `denying` is read). */
skillGrants: Prepared["skillGrants"];
/** borrowed-readonly — the deployment's caller policy as resolved through the lock layer, or undefined (a layer of the
* judge, asked with a request that states nobody can be asked about it — never an approver). */
callerPolicy: ToolPolicy | undefined;
/** borrowed-readonly — each live inherited parent policy (a layer of the judge, consulted like the caller policy). */
inheritedPolicies: readonly ToolPolicy[];
/** borrowed-readonly — whether the leg is in its delegation tree's rule session (`ruleSessionOf(...).inTree`): the judge's layers say so. */
ruleSessionInTree: boolean;
/** borrowed-readonly — the person's persisted-rule lane, or undefined (a layer of the judge). */
persistedRuleLane: Prepared["persistedRuleLane"];
/** borrowed-readonly — the leg's facts the rule lanes judge against: the consolidation write judge builds its two lanes on them. */
ruleLaneFacts: ConsolidationWriteJudgeLeg["lanes"];
/** borrowed-readonly — a reader of the person's rows the run's cut does not end (the consolidation judge is asked after the run). */
personRowsBeyondRun: ConsolidationWriteJudgeLeg["rows"];
/** borrowed-readonly — the org rule lane, or undefined (a layer of the judge). */
orgRuleLane: Prepared["permissionRuleOrg"];
/** borrowed-readonly — the leg's target-reading stamp, or undefined (hands-less): the visibility judge stamps its request. */
stampCallTarget: Prepared["stampCallTarget"];
/** borrowed-readonly — the run's abort controller; only `signal` (the deny door's and the stat's signal). */
abortController: Pick<AbortController, "signal">;
/** borrowed-readonly — the per-task identity (the background listing's owner). */
hostTaskId: string;
/** borrowed-readonly — the registry scope the background listing reads under. */
taskScope: string;
/** borrowed-readonly — the prompt-assembly phase's re-invokable assemble-inputs builder (the candidate re-assembles). */
buildAssembleInputs: (center: CenterAdoption | undefined) => AssembleInputs;
/** borrowed-readonly — the prompt-assembly phase's identity inputs under another center layer (the candidate's record). */
identityFor: (center: CenterAdoption | undefined) => RunPromptIdentity;
/** borrowed-readonly — whether this run adopts center candidates at its boundaries (a child never does). */
adoptsCandidates: boolean;
/** borrowed-mutable — the LIVE center adoption (the prompt-assembly phase's accessor cell). Read: the candidate's
* same-artifact test. Writer here: the candidate's `apply` (the boundary adoption / the explicit-disable emptying). */
centerAdoptionRef: {
current: CenterAdoption | undefined;
};
/** borrowed-mutable — the event templates the run's overlays replaced, read per call by the run's engine text reading
* (`Prepared.engineText`). Writer here: the candidate's `apply` (the adopted layer's replacements, or none). */
replacedTemplates: {
current: ReadonlyMap<string, string>;
};
/** borrowed-readonly — the harness ref (the candidate's `apply` calls `setSystemPrompt` on the current harness). */
harnessRef: {
current?: AgentHarness;
};
/** borrowed-readonly — the ONE carrier-face expression both delegation mounts consume (the observation seat). */
carrierReadFace: () => ContainmentFace | undefined;
/** borrowed-readonly — the same carrier expression on the WRITE seat. */
carrierWriteFace: () => ContainmentFace | undefined;
/** borrowed-readonly — the normalized deny additions (the observation seat copies them). */
readDenyAdditionsNormalized: ReadonlyArray<{
pattern: string;
caseSensitive: boolean;
}>;
/** borrowed-mutable — the holder of the built Prepared. Writer: the DRIVER fills `current` right after `buildPrepared()`;
* the candidate's `apply` then writes `current.promptIdentity` and `current.promptOverheadTokens` at a boundary. */
preparedHolder: {
current?: Prepared;
};
/** owned — the instruction-file family as the config door read it (its one reading); absent ⇒ no lane. */
nestedDeclaration: ScreenedNestedMemory | undefined;
/** borrowed-readonly — the additional working directories the spec declared, as the hands resolved them (the lane's further roots under the family's opt-in). */
declaredAdditionalRoots: readonly DeclaredRoot[]; /** borrowed-readonly — the leg's budget snapshot the live gate stamps on every request (the card's probe carries it too). */
budgetSnapshot: NonNullable<ToolCallRequest["budget"]>;
}
export interface PrepareTurnWiringResult {
/** owned — the fixed prompt-overhead term in the compaction trigger's coordinate (`Prepared.promptOverheadTokens`). */
promptOverheadTokens: number;
/** owned — the post-compaction restore, or undefined without hands (`Prepared.compactionRestore`). */
compactionRestore: Prepared["compactionRestore"];
/** owned — the kept-tail path normalizer, or undefined without hands. */
normalizeAttachmentPath: Prepared["normalizeAttachmentPath"];
/** owned — the most-recently-read files projection, or undefined without read state. */
recentlyReadFiles: Prepared["recentlyReadFiles"];
/** owned — the landed-compaction read-state hook, or undefined without read state. */
onCompactionApplied: Prepared["onCompactionApplied"];
/** owned — the changed-files scan (a turn boundary's and a leg's first request's), or undefined without read state. */
detectExternalChanges: Prepared["detectExternalChanges"];
/** owned — the instruction-file lane (`Prepared.nestedMemory`: the task root's level and the accessed directories'), or undefined without hands or the declaration. */
nestedMemory: Prepared["nestedMemory"];
/** owned — the run's ONE synthetic-Read deny judge over every layer that can refuse a model's `Read` (the
* changed-files door reads it; a face that delivers a file the model did not ask for reads the same one). */
syntheticReadVerdict: SyntheticReadJudge;
/** owned — the same layers' FETCH face: the run's own `WebFetch` of a host (the run's host questions read it). */
syntheticFetchVerdict: SyntheticFetchJudge;
/** owned — the consolidation write judge (`Prepared.consolidationWriteJudge`): the same layers' WRITE face, an `ask` an objection. */
consolidationWriteJudge: ConsolidationWriteJudge;
/** owned — the post-compact background-task listing (`Prepared.listBackgroundTasks`). */
listBackgroundTasks: Prepared["listBackgroundTasks"];
/** owned — one task's read handle under the same identity (`Prepared.taskReadHandleOf`). */
taskReadHandleOf: Prepared["taskReadHandleOf"];
/** owned — the compaction-boundary center adoption candidate, or undefined (no source, or no adoption). */
centerCompactionCandidate: Prepared["centerCompactionCandidate"];
/** owned — the effective read face observed for the result seats (`Prepared.effectiveReadFace`), or undefined. */
effectiveReadFaceObserved: ContainmentFace | undefined;
/** owned — the same observation on the WRITE seat (`Prepared.effectiveWriteFace`), or undefined. */
effectiveWriteFaceObserved: ContainmentFace | undefined;
/** owned — the effective read-deny patterns observed (fresh copies), or undefined when none. */
effectiveReadDenyObserved: Array<{
pattern: string;
caseSensitive: boolean;
}> | undefined;
/** owned — the leg's epoch-anchor seat (`Prepared.prefixAnchor`). */
prefixAnchor: NonNullable<Prepared["prefixAnchor"]>;
}
/**
* The main lane's caller-side request-policy declaration point: every main-loop call refreshes the turn snapshot's policy
* element with the controls it carries (thinking level, output cap — the model's own when the call names none), and the
* snapshot's dedup declares `request_policy` only for a call whose controls moved. The leg's first call may move it too:
* the prepare-time value is the model's cap, the wire's is the run's limit when one is set (the first observation has no
* baseline, so nothing is judged by it). Fast speed: the call asks for it and its model's entry serves it (`fastModeUnavailableFor`).
* A re-shape inside one call (a lower cap on a context-overflow re-send, a re-send at standard speed) is not visible here.
*/
export declare function declaringCallPolicy(turnSnapshotRef: {
readonly current?: Pick<TurnPromptSnapshot, "refreshRequestPolicy">;
}, stream: StreamFn): StreamFn;
/** The M22 phase body — prepareTask's turn-wiring stretch, verbatim (see the module header). */
export declare function prepareTurnWiring(input: PrepareTurnWiringInput): PrepareTurnWiringResult;