UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

247 lines (246 loc) • 16.9 kB
import type { ExecutionEnv } from "../../internal/harness.js"; import type { ModelFileReader } from "../../tools/fs/fs-read.js"; import { type ReadFileState } from "../../tools/fs/safety.js"; import type { SyntheticServedReadJudge } from "../synthetic-read-verdict.js"; import type { ToolCallFace } from "../tool-policy.js"; import { type FrameFileTools, type InstructionLayer, type MintedAttachmentFrame } from "../user-attachment.js"; import type { ReminderDisclosureCounts } from "../reminder-disclosure.js"; import type { TaskSpec } from "../task-spec.js"; import type { EngineNotice, RunnerDeps, TaskEvent, TaskEventIdentity } from "../types.js"; import type { WiringManifest } from "../wiring-manifest.js"; import type { WiringInstructions } from "../instruction-preview.js"; import type { Prepared } from "./contracts.js"; /** At most this many names in `files` (and in `alternate.files`). */ export declare const NESTED_MEMORY_MAX_NAMES = 8; /** The longest name. */ export declare const NESTED_MEMORY_NAME_MAX = 255; /** At most this many `hostRules` are delivered: the first ones, in the request's order. */ export declare const NESTED_MEMORY_MAX_HOST_RULES = 20; /** At most this many paths of `externalIncludes` are read as approvals: the first ones, in the request's order. Each is at most * `ABSOLUTE_HOST_PATH_MAX` characters (the engine's bound on an absolute host path). */ export declare const NESTED_MEMORY_MAX_APPROVED_PATHS = 32; /** The levels a host text is supplied at, each with whose text its frame says it is: `user` (the user's own, for every project — * its includes follow as if approved), `managed` (the organization's), `project` (a file of a directory above the task root), * `local` (the user's private file of a project, not checked in). */ export declare const HOST_TEXT_LEVELS: readonly ["user", "managed", "project", "local"]; export type HostTextLevel = (typeof HOST_TEXT_LEVELS)[number]; /** The probes one load makes at most, times the number of roots it reads (a stat, a read, a directory listing each count * one; the allowances are pooled): a further root's own level — looked at on every load — brings its own share. */ export declare const NESTED_MEMORY_PROBES_PER_LOAD = 32; /** One load's frames, at most this many files' cap (the frames counted whole: sentences, labels and data). */ export declare const NESTED_MEMORY_FRAME_BUDGET_FILES = 3; /** How many members' stats the lane asks together. */ export declare const NESTED_MEMORY_STAT_BATCH = 8; /** The synthetic-Read judge's probe face (probe id `nested-memory-visibility-probe`). */ export declare const NESTED_MEMORY_PROBE_FACE = "nested-memory"; /** The notice an instruction file the model could not Read was not loaded under — one code for every instruction layer * (the reference tells both of its layers' withheld files through one account). */ export declare const INSTRUCTIONS_WITHHELD = "instructions.withheld"; /** Why an instruction file was not loaded — the notice's `detail.reason`. `outside_roots`: the read face's roots refused a * member the family names (or a file the lane found that `externalIncludes` approves); `outside_its_root`: a file the lane found (a * rules directory's, an include's) really lies, links followed, outside the root it was found under and outside the task * root — on every read face, unless the request's `externalIncludes` approves it; `too_many_texts`: a host text past the first * {@link NESTED_MEMORY_MAX_HOST_RULES} (`path` is the first such text's name); `unanchored`: an include of a host text that names * no file of the run's (a label for a name, or a run with no files), so it has nowhere to resolve. */ export declare const INSTRUCTIONS_WITHHELD_REASONS: readonly ["rule_denied", "outside_roots", "approval_required", "admission_unknown", "target_moved", "outside_its_root", "too_many_texts", "unanchored"]; export type InstructionsWithheldReason = (typeof INSTRUCTIONS_WITHHELD_REASONS)[number]; /** The notice a member the family names was loaded under though it really lies, links followed, outside its root and the task root * (a link to a shared file): read as before — the reference reads it too — and said once per session per (path, target), with no * contents. A found file outside them is not loaded ({@link INSTRUCTIONS_WITHHELD} `outside_its_root`); one the read roots or a rule * refuses is withheld whatever the name. */ export declare const INSTRUCTIONS_OUTSIDE_ROOT = "instructions.outside_root"; /** The notice a run prepared with no instruction family declared is the first, for its notice receiver, to say. */ export declare const INSTRUCTIONS_FAMILY_UNDECLARED = "instructions.family_undeclared"; /** The operator's sentence for that absence: what no run reads, and the one thing that makes them read it. */ export declare function instructionsFamilyUndeclaredNotice(sessionId: string): EngineNotice; /** * The lane's capability descriptor — what a host reads to decide whether to declare the family here and stop loading * instruction files itself: the declaration's seat, the frames' origins (a level below the root; a root's own level — the * task root's, an additional directory's under the opt-in), the echo and the notice it raises, its limits. */ export declare const NESTED_MEMORY_LANE: Readonly<{ declaration: "TaskSpec.instructionFamily"; origin: "nested_memory"; rootOrigin: "project_instructions"; echo: "steering_injected"; notice: "instructions.withheld"; limits: Readonly<{ maxNames: 8; maxNameChars: 255; maxHostRules: 20; maxApprovedPaths: 32; maxApprovedPathChars: 4096; maxIncludeDepth: 5; probesPerLoad: 32; }>; }>; /** The declaration as the door read it: copied members, defaults resolved. */ export interface ScreenedNestedMemory { readonly files: readonly string[]; readonly rulesDirs: readonly string[]; readonly alternate?: { readonly files: readonly string[]; readonly rulesDirs: readonly string[]; readonly when: "absent" | "also"; }; readonly includes: boolean; readonly additionalDirectories: boolean; /** The files the project approved outside the roots a found file is judged against: the first * {@link NESTED_MEMORY_MAX_APPROVED_PATHS} absolute paths the request listed, less those skipped (none: nothing approved). */ readonly externalIncludes: readonly string[]; /** The listed paths not read as approvals: past the count, or over `ABSOLUTE_HOST_PATH_MAX` characters. */ readonly externalIncludesSkipped: ReadonlyArray<{ readonly path: string; readonly why: ApprovalSkip; }>; /** The user's private names each level is also read for, whichever family is active (never the second family's condition). */ readonly localFiles: readonly string[]; /** The host texts the lane delivers: the first {@link NESTED_MEMORY_MAX_HOST_RULES} the request supplied, less those skipped. */ readonly hostRules: readonly HostText[]; /** Every name the request supplied (a text the conversation holds under another name is withdrawn), and the entries skipped. */ readonly hostNames: readonly string[]; readonly hostSkipped: ReadonlyArray<{ readonly name: string; readonly why: HostSkip; }>; } /** A host text as the door read it: `rule` — found in a rules directory, so its frontmatter `paths:` makes it conditional. */ export interface HostText { readonly level: HostTextLevel; readonly name: string; readonly text: string; readonly rule: boolean; } /** Why a well-formed host text is not delivered: past the count, a name an earlier entry has, a name over * `ABSOLUTE_HOST_PATH_MAX`, a text over the read bound — the same bound a file is read at. */ type HostSkip = "over_count" | "repeated" | "long_name" | "large_text"; /** Why a well-formed approved path is not read as an approval: past the count, or over `ABSOLUTE_HOST_PATH_MAX` characters. */ type ApprovalSkip = "over_count" | "long_path"; /** The one read of the declaration off a task spec ({@link FIELD}); absent ⇒ `undefined`. */ export declare function instructionFamilyOf(spec: Pick<TaskSpec, "instructionFamily"> | unknown): unknown; /** * The door of the declaration ({@link FIELD}): absent ⇒ `undefined`; a value it cannot read refuses the task * (`config.invalid_argument`, the spec's own bad-value code — the declaration is not an attachment lane) — never a default. `projectMemory: "disabled"` is the request's off switch for the * project's instructions, this family among them: the declaration is still screened (a bad value refuses), then no lane * is seated — nothing is stat'ed or read (a child that writes the switch silences the family it inherits; a parent's * switch silences a child's own family). */ export declare function screenNestedMemory(spec: Pick<TaskSpec, "instructionFamily"> | unknown, projectMemory: TaskSpec["projectMemory"] | unknown): ScreenedNestedMemory | undefined; /** What the lane reads with: the hands' environment and reader, the run's served-read judge (every ask held: nobody asked * for this file, so it is shown only where the model's own `Read` of it would be served with nobody asked) and the face * the run's roster gives `Read` (read at each judgment; none ⇒ the probe carries no face — never a reason to withhold), the live read * state, the canonical task root and the additional working directories the request declared (each its declared spelling * and the one canonical form the hands resolved it to, in declaration order; read as roots only under the declaration's * opt-in); the prepared leg (read at each load) for the model and the records. A leg with no hands seats the lane without * them: it reads no file and holds the deployment's texts alone. */ export type NestedMemoryLaneSeat = LaneSeatCommon & (LaneHands | { readonly [K in keyof LaneHands]?: undefined; }); interface LaneHands { readonly env: ExecutionEnv; readonly reader: ModelFileReader; readonly judge: SyntheticServedReadJudge; readonly readFace: () => ToolCallFace | undefined; readonly state: ReadFileState; readonly root: string; readonly additionalRoots?: ReadonlyArray<DeclaredRoot>; } /** What the lane reads of the leg it serves: the model it sizes frames for, the transcript's host texts, the leg's ids, its once-told * record and identity. A prepared leg is one; a preview of a leg builds one with nothing behind it to write to. */ export interface InstructionLaneLeg { readonly harness: { getModel(): ReturnType<Prepared["harness"]["getModel"]>; }; readonly session: { buildContext(): ReturnType<Prepared["session"]["buildContext"]>; }; readonly sessionId: string; readonly runId: string; readonly announcedListingsRef: Prepared["announcedListingsRef"]; readonly frameReceipts: Pick<Prepared["frameReceipts"], "listingSnapshotOwed">; readonly hookIdentity: Pick<Prepared["hookIdentity"], "taskId" | "isDelegatedChild">; } interface LaneSeatCommon { readonly declaration: ScreenedNestedMemory; readonly signal: AbortSignal; readonly mark: string | undefined; readonly counts: ReminderDisclosureCounts | undefined; readonly deps: Pick<RunnerDeps, "onNotice" | "onError">; readonly leg: () => InstructionLaneLeg | undefined; /** The file tools the run's roster mounts, read at each mint — what a frame's sentence (a cut file's way to the rest) may send the * model to; absent outside a Runner: every one taken as mounted. */ readonly fileTools?: () => FrameFileTools; } /** An additional working directory as the request declared it (`TaskSpec.additionalDirectories`, the spelling) and as the * hands resolved it (the canonical form the file tools' fence holds). */ export interface DeclaredRoot { readonly directory: string; readonly canonical: string; } /** Told each delivered frame at its receipt: the file's key (a deployment rule's name), the layer it belongs to, and * whether the frame withdrew a file delivered earlier. */ export type InstructionEcho = (label: string, layer: InstructionLayer, withdrawn: boolean) => void; /** The `steering_injected` echo of a delivered instruction frame: the layer's source word, and the file's key (a * withdrawal says so). */ export declare function instructionEchoOf(label: string, layer: InstructionLayer, withdrawn: boolean): { readonly source: "project_instructions" | "nested_memory"; readonly preview: string; }; /** The echo every site that hands a load to a request (or to the transcript) uses: the frame on the run's stream, counted * among the run's injected attachments. */ export declare function instructionEchoTo(queue: { push(e: TaskEvent): unknown; }, ident: () => TaskEventIdentity, attach: { attachmentsInjected: number; }): InstructionEcho; /** * The instruction files' COMPACTION arm: a landed compaction retired the entries of the frames it summarized away, so the * roots' own levels (owed on every load) and every level whose access the kept tail still holds owe again. One load, its * frames written to the transcript as engine messages before any reader of the new baseline (the next request first), each * committed on its own append — what one could not write stays owed for the next load. Never throws. */ export declare function restateInstructionFiles(lane: NestedMemoryLane, seat: { readonly session: Pick<Prepared["session"], "appendMessage">; readonly admitRows: Prepared["admitRows"]; readonly report?: (e: Error) => void; }, echo: InstructionEcho): Promise<void>; /** One load: the frames it owes (one input id), their data characters, and the hand-back of frames that did not go. */ export interface NestedMemoryLoad { readonly inputId: string; readonly frames: readonly MintedAttachmentFrame[]; readonly chars: number; /** The frames were not delivered (their carrier was refused): what they carried is owed again — all of them, or the * frames of these ordinals. */ release(ordinals?: readonly number[]): void; } export interface NestedMemoryLane { /** The leg's first load, before the leg's manifest goes out: what it owes is held for the leg's first request (the next * {@link load}), which leaves out a file an attachment of that request carries itself. */ prime(): Promise<void>; /** Load what the read state owes now. `triggers`: canonical keys accessed but not yet in the read state (an objective's * path attachments, committed with the same request). `echo` is told each delivered frame, at its receipt. */ load(ask: { readonly triggers?: readonly string[]; readonly echo: InstructionEcho; }): Promise<NestedMemoryLoad | undefined>; /** The frames the next {@link load} hands over from the leg's first load (held from before the manifest), for these * `triggers` — minted, nothing loaded, held or handed back: what the objective's window check counts beside its * attachment frames (the request guard holds the task root's). A file a trigger carries is left out, as the load leaves it * out. The load's per-request size cap is not applied (it can only take frames away). Empty once that load is taken. */ owedAhead(triggers: readonly string[]): readonly MintedAttachmentFrame[]; /** Each root's members the conversation holds (a read-state entry) or a load has on its way, relative to that root, * `/`-separated, plus first-load `@`-included and withheld entries (present iff non-empty); `undefined` on a lane with no * hands unless host-text withholds occurred. */ selected(): WiringInstructions | undefined; /** Is this key a member of the declared family — at a root's own level, or at any level — read off the declaration * and the path alone (a member's name, or a markdown file under a rules directory), whoever wrote its entry? */ isMember(key: string, at: "root" | "any"): boolean; } export declare function createNestedMemoryLane(seat: NestedMemoryLaneSeat): NestedMemoryLane; /** One first-load reading over a seated lane — shared by `primeInstructionLane` (manifest) and `Runner.previewInstructions`. */ export declare function primeInstructionReading(lane: NestedMemoryLane, report: (e: Error) => void): Promise<WiringInstructions | undefined>; /** The leg's first load, before its manifest goes out, and the manifest's `instructions` member it answers * ({@link WiringManifest.instructions}). A load that throws leaves the leg's first request to load (the operator hears * why); the manifest then says what the read state holds. */ export declare function primeInstructionLane(lane: NestedMemoryLane, manifest: WiringManifest, report: (e: Error) => void): Promise<void>; export {};