UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

180 lines (179 loc) • 14.6 kB
import type { AnnouncedListingSnapshot, AnnouncedListingSnapshotInput } from "../../internal/harness.js"; import type { AnnounceOnceSink } from "./contracts.js"; import type { McpDroppedTool, McpServerStatus } from "../mcp.js"; import { type McpUnavailableEntry } from "../mcp-failure.js"; import type { RunnerDeps } from "../types.js"; import { announceDigest, type NoticeTold } from "../engine-notice.js"; /** Upper bound on the advisory-digest arm kept in the record (oldest dropped past it). A digest is 64 hex chars; the arm * holds a session's distinct advisories (a handful) and the digest of every media block the request budget cut and told * (`media-removed-seat.ts` — a session with many images can pass the bound): past it the oldest go, whichever face wrote * them, and their fact is said again by a later run, never lost. The bound keeps the snapshot finite. */ export declare const ANNOUNCE_ONCE_MAX_DIGESTS = 200; /** Tell a DEPLOYMENT fact once per Runner: `deliver` runs unless `sink` (the Runner's wrapped `onError`, the one object every run of it * reads) was already told `key`; nothing with no sink wired. {@link AnnounceOnceLedger.onErrorOncePerRunner} is this verb over a * warning's digest; the catalog door's notices key on what they are about. */ export declare function oncePerRunner(sink: object | undefined, key: string, deliver: () => void): void; /** The structured-notice twin of the operator sink's record above — what each notice receiver was told once — is the engine's one record, * shared with the memory layer: `../notice-once-per-seat.ts`. */ export { noticeOncePerSink, __resetNoticedOncePerSink } from "../notice-once-per-seat.js"; /** The record's digest form, `sha256(lane \n text)` — defined beside the delivery throat, whose fact keys are digests of the same * form in the same record (one form, so a fact key and a once-arm digest can never be read two ways). */ export { announceDigest }; /** The digest of an operator-lane warning: its `code` (empty when uncoded) and message. The message is * passed through the secret-tier redaction FIRST: an advisory that embeds a credential (a misconfigured * header, a URL with userinfo) must be recognized as the same advisory when the credential rotates, and * the record must never persist a secret-bearing text's exact digest either — the digest is opaque, but * an equality oracle on a secret is still an oracle. The forwarded line itself is untouched (the sink * owns its own redaction posture); only the identity is judged on the redacted form. */ export declare function warningDigest(err: unknown): string; /** The two built-in memory pairs a mount can decline, each with its sentence frame and the `classification` * word its advisory carries on the operator sink. */ declare const MEMORY_MOUNT_ADVISORY: { readonly shared: { readonly label: "Shared memory tools"; readonly classification: "shared-memory-not-mounted"; readonly tail: "the pair mounts together or not at all"; }; readonly engine: { readonly label: "Memory tools"; readonly classification: "memory-tools-not-mounted"; readonly tail: "these tools mount together or not at all"; }; }; /** Which built-in memory pair an advisory is about. */ export type MemoryMountPair = keyof typeof MEMORY_MOUNT_ADVISORY; /** * THE one mint for "a built-in memory pair was NOT mounted": the shared-memory pair and the engine memory trio each * decline to mount when the deployment's selector excludes a name, when a caller tool already occupies one, or when * mounting them would inject the ToolSearch tool under a name the task already declares — four stations, one sentence * frame, one scope. The fact belongs to the deployment's configuration, so it is told once per RUNNER * ({@link AnnounceOnceLedger.onErrorOncePerRunner}), not once per conversation. `reason` is the clause after the * colon; the pair's `names` are the tools that stay unmounted together. */ export declare function announceMemoryNotMounted(sink: Pick<AnnounceOnceSink, "onErrorOncePerRunner">, sessionId: string, pair: MemoryMountPair, names: readonly string[], reason: string): void; /** The digest of one model-facing dropped-tool entry (server, tool, reason — the three fields the * frame prints). */ export declare function droppedToolDigest(d: McpDroppedTool): string; /** `existing ∪ add`, insertion-ordered, bounded to {@link ANNOUNCE_ONCE_MAX_DIGESTS} (oldest first * out). Returns a NEW array; the input arrays are never mutated. */ export declare function withAnnounceDigests(existing: readonly string[] | undefined, add: readonly string[]): string[]; /** The session's announced record and the leg's receipt ledger, as a seat that tells the person something during the run reads them. */ export type RunTimeAnnounced = { readonly announcedListingsRef: AnnouncedListingSnapshotInput; readonly frameReceipts: { listingSnapshotOwed: boolean; }; }; /** The run-time face of the once-per-session record (a fact met during the run — or during prepare: settle folds into the mirror, never over it): `deliver` runs unless * `digest` is in the session's announced record; then the digest joins it and its write is parked for the leg's flush * ({@link flushOwedAnnouncedSnapshot}) — a lost append is the fact said again by a later run. Prepare's face: `oncePerSession`. * `formerly`: the digests the record held for this very telling before its key changed form. One of them in the record is this telling, * told: nothing is delivered, the first one found takes `digest` in its own slot and the others leave — the record never grows for it. */ export declare function tellOncePerSession(announced: RunTimeAnnounced, digest: string, deliver: () => void, formerly?: readonly string[]): void; /** The session face this ledger needs: the nearest announced snapshot and the append. */ export interface AnnounceOnceSession { getAnnouncedListing(): Promise<AnnouncedListingSnapshot | undefined>; appendAnnouncedListing(snapshot: AnnouncedListingSnapshotInput): Promise<string>; } /** * Flush the PARKED announced-listing snapshot write (`FrameReceiptLedger.listingSnapshotOwed`, set by a * frame receipt's commit inside the `message_end` walk) at a serialization point — the boundary's end, * the prompt's settle. Best-effort: a lost append is a duplicate announcement next run. Never while * prepare's branch read failed: a whole-snapshot write would replace the branch's record with this * leg's partial view (the flag is cleared either way — nothing is owed on such a leg). */ export declare function flushOwedAnnouncedSnapshot(prepared: { frameReceipts: { listingSnapshotOwed: boolean; }; announcedSnapshotRecovered: boolean; announcedListingsRef: AnnouncedListingSnapshotInput; session: Pick<AnnounceOnceSession, "appendAnnouncedListing">; }): Promise<void>; /** * The one commit of a delivered `mcp_unavailable` frame — the receipt of the message that carried it (a leg's first request), run * inside the `message_end` walk: the delivered pairs leave the pending list and join the session's told-failure record, whose * snapshot write is parked for the next serialization point. The next prepare on the session announces only what the record lacks. */ export declare function settleMcpUnavailable(prepared: { readonly mcpUnavailable?: { pending: McpUnavailableEntry[]; }; readonly announcedListingsRef: AnnouncedListingSnapshotInput; readonly frameReceipts: { listingSnapshotOwed: boolean; }; }, delivered: ReadonlyArray<McpUnavailableEntry>): void; /** The run-local ledger — see the module header for the two commit disciplines it serves. */ export interface AnnounceOnceLedger { /** The nearest announced snapshot on the branch as read at prepare (undefined = pre-entry * session). Exposed so the listing seed can reuse this ONE read instead of walking the branch again. */ readonly entry: AnnouncedListingSnapshot | undefined; /** Whether the branch read SUCCEEDED (a pre-entry session reads as `undefined` and IS recovered; a * throwing read is not). While false, no whole-snapshot write may happen on this leg — the nearest * `announced_listing` has snapshot semantics, so a write seeded from a failed read would REPLACE * the branch's real record with the few arms this leg happens to know, hiding every other arm. * A skipped write degrades to a duplicate announcement next run, never a loss. The run loop * reads the same flag (`Prepared.announcedSnapshotRecovered`) before its own once-arm flush. */ readonly recovered: boolean; /** The operator-lane sink, deduplicated: a warning whose `(code, message)` digest is already in * the record is dropped; a new one is forwarded to `deps.onError` and recorded. With no sink wired * nothing is recorded either — "announced" means delivered. Same signature as `RunnerDeps.onError`. */ onError: NonNullable<RunnerDeps["onError"]>; /** The record's one dedupe verb, for any announcement of a session fact: `deliver` runs unless `digest` is already in the * record, and the digest is recorded once it ran ({@link onError} is this verb over the operator sink). */ oncePerSession(digest: string, deliver: () => void): void; /** The operator-lane sink for a DEPLOYMENT fact (see {@link AnnounceOnceSink.onErrorOncePerRunner}): the same * `(code, message)` digest, judged against what THIS RUNNER's sink has already been told rather than against * the session's record. Writes no digest into the record and owes the transcript nothing. */ onErrorOncePerRunner: NonNullable<RunnerDeps["onError"]>; /** The MODEL-face pending set for this run: the currently failed servers (name/error neutralized + * bounded at intake, the reminder's own bounds) MINUS the pairs already announced on this branch. * As a side effect the record's `mcpFailed` arm is pruned to the pairs that are STILL failing — * a recovered server leaves the record silently. `remembered` answers whether the session's pool remembers a server's failure * (the entry's `remembered`). `withRemoteWords` false (a multi-tenant deployment): each `error` is the class line ({@link failureClassLine}), the record's `error` unread; true: the remote's words. Call once per prepare. */ mcpFailuresToAnnounce(statuses: ReadonlyArray<McpServerStatus>, remembered: (server: string) => boolean, withRemoteWords: boolean): McpUnavailableEntry[]; /** Remove, IN PLACE, the dropped-tool entries whose model-facing digest is already recorded (the * frame was delivered on an earlier run of this session). The operator line about each entry is a * separate digest — run that loop BEFORE pruning so both faces are judged on the full list. */ pruneDroppedTools(dropped: McpDroppedTool[]): void; /** The whole announced snapshot as it stands — the seed for the run loop's `announcedListingsRef` * mirror. Listing arms (agents/skills/models) are copied from ONE source, the checkpoint mirror * when it carries any of them, else the entry (rung-pure: a roster and its catalog come from the * same commit); the once-per-session arms come from their own rung selection. Present-only: an * empty arm is omitted, so a session that never announced anything serializes no * `announcedListings` at all. The listing arms are a state-only carry: a commit of any ONE arm * rewrites the nearest snapshot whole, so the other arms must already be on the object or the * commit erases them from the branch's record. */ arms(): AnnouncedListingSnapshot; /** The session's told record for the delivery throat's fact keys (`deliverEngineNotice`'s `told`): ONE object for the leg, the * same record {@link oncePerSession} and {@link tellOncePerSession} answer from, in two lives. Until {@link settle} it reads and * writes this prepare's advisory digests (persisted by `settle`, like every prepare-time telling); from `settle` on it reads and * writes the run's mirror (`ref.advisories`) and parks the write on the leg's receipt ledger (`receipts`), as a run-time telling * does. `release` takes a fact out of whichever life is current, so the next notice of it is told again. */ readonly told: NoticeTold; /** End-of-prepare settlement: fold the operator-lane digests recorded during prepare into `ref` * (the mirror the run loop and the checkpoint serializer read) and, when the record advanced, * persist the whole snapshot — the listing arms as they stand on `ref` (or as read at prepare), * plus the two arms this module owns. Best-effort: an append failure degrades to a duplicate * announcement on the next run, never a lost one. From here on {@link told} lives on `ref` and `receipts`. */ settle(session: AnnounceOnceSession, ref: AnnouncedListingSnapshotInput, receipts: { listingSnapshotOwed: boolean; }): Promise<void>; } /** A told record held in memory only, for a caller that has no session record to tell against (a compaction pass outside any run): * the same type as the leg's, living as long as the caller keeps it. */ export declare function inMemoryNoticeTold(): NoticeTold; /** * Load the ledger for this prepare. Read ladder for the two arms: the resume checkpoint's mirror * first (cut atomically with the suspend; the entry is a best-effort write that can lag it), then * the nearest `announced_listing` carrier on the branch. A snapshot without the arms (an entry * written before they existed) reads as the empty set — additive schema, same posture as the * checkpoint's own listing arms. A session read failure also reads as empty: the worst case of * an unseeded ledger is a duplicate announcement, never a lost one. */ export declare function loadAnnounceOnceLedger(session: AnnounceOnceSession, checkpointMirror: AnnouncedListingSnapshot | undefined, onError: RunnerDeps["onError"]): Promise<AnnounceOnceLedger>; /** The suspend-time projection of the run loop's announced mirror onto the checkpoint field: * present-only arms, copied; `undefined` when nothing was announced on any face (the resume seed * then falls to the lower rungs — unchanged contract). */ export declare function serializeAnnouncedListings(ref: AnnouncedListingSnapshotInput): AnnouncedListingSnapshot | undefined;