UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

195 lines (194 loc) • 13.2 kB
import type { BrainRetryErrClass, BrainStatus, BrainStatusSeat } from "../core/types.js"; import type { CapabilityDeclaration, CapabilityRequestSpeed } from "./model-capability.js"; import type { ThinkingLevel } from "../internal/harness-types.js"; /** Run `fn` with a per-task brain-status sink in scope. ALS propagates it through the async brain calls * inside `fn` (the harness's prompt → brain.stream → connect/retry loop), so {@link emitBrainStatus} * reaches THIS task's sink and nothing else. */ export declare function runWithStatusSink<T>(emit: (s: BrainStatus) => void, fn: () => Promise<T>): Promise<T>; /** * Run `fn` with every liveness frame its brain calls report stamped with `seat` ({@link BrainStatus.seat}) and, when the seat's * call is about one tool call, that call's id ({@link BrainStatus.toolCallId}): a nested scope over the ACTIVE sink (the frames * still reach the task's stream, unlike a derived leg's no-op shield). A frame that names a seat keeps its own seat and call; the * stamp is applied at emit time, so a timer-fired frame carries it; outside a sink the call runs unchanged. */ export declare function withStatusSeat<T>(seat: BrainStatusSeat, fn: () => T, toolCallId?: string): T; /** * Report a brain-layer liveness status to the active per-task sink, if any. A no-op outside a * {@link runWithStatusSink} scope (e.g. compaction's `complete`, or a brain used standalone). * * HRD-BRN-6: swallow-guarded, like its sibling {@link emitBrainTelemetry} — an ADVISORY frame must never * change a brain call's outcome. It could: the emit forwards straight into deployment-supplied code, and * the circuit breaker's fast-fail emits the `circuit_open` frame from a void-ed async IIFE BEFORE the * error terminal is pushed, so a throwing sink took the whole call down (`result()` pending forever plus * an unhandled rejection) instead of costing one status frame. `stream-engine.ts` already wrapped its own * call site for this exact reason and states the contract ("an advisory frame must never break a settled * call"); the guard belongs HERE so every call site inherits it rather than each remembering. */ /** * #530 — bind the ACTIVE sink now, for an emit that will happen from a timer callback later. The * async-local store propagates through Node's timers, but not through every timer implementation a * process may run under (fake clocks in tests replace `setTimeout` outright and run callbacks from * their own stack, where `getStore()` is empty). A frame scheduled inside the sink's scope must reach * that sink whichever clock fires it, so the scheduler captures the store here and the callback emits * through the bound function. Same swallow guard and the same retryAtMs stamp as {@link emitBrainStatus}; * a no-op function when no sink is active. */ export declare function bindBrainStatusEmitter(): (status: BrainStatus) => void; export declare function emitBrainStatus(status: BrainStatus): void; /** * Silent-fallback telemetry (C1/C4/C5/C6) — the brain→runner TELEMETRY channel, a * SECOND ALS sink parallel to the status one. Statuses are user-facing liveness frames (wire * `status` events); telemetry is operator-facing fallback accounting the Runner bridges to trace * events (`brain.failover` / `breaker.transition` / `brain.retry` / `vision.placeholder` / `brain.echo_dropped`). Kept * separate so widening telemetry never bloats the shell-visible status vocabulary. Same contract: * fire-and-forget, no-op outside a {@link runWithBrainTelemetry} scope, MUST NOT throw. */ export type BrainTelemetry = { kind: "failover"; servedIndex: number; total: number; errorCode?: string; } | { kind: "breaker"; key: string; phase: "open" | "half-open" | "closed"; failures: number; } /** A retried provider call. `errClass` is the same closed bucket the user-facing status frame carries * (so an operator reading traces and a user reading a progress line agree on why); `nextDelayMs` is * the backoff actually about to be slept — 0 for the immediate re-sends that take no backoff. Both * optional so a caller that has no verdict to report is not forced to invent one. */ | { kind: "retry"; attempt: number; phase: "connect" | "midstream"; errClass?: BrainRetryErrClass; nextDelayMs?: number; } | { kind: "vision_placeholder"; count: number; } /** PDF read: a `document` content block was substituted with a text placeholder because the serving * API/model cannot take native document input (openai brain always; anthropic brain when the model * declares no vision). Silent quality loss → frame (same C4 discipline as vision_placeholder). */ | { kind: "document_placeholder"; count: number; } /** A provider echo field ({@link import("./errors.js").PROVIDER_ECHO_SHAPE}) refused by its shape: the value was dropped * and the field is absent. One event per provider response per field. */ | { kind: "echo_dropped"; field: "requestId" | "responseModel" | "apiErrorCode"; }; /** Run `fn` with a per-task brain-telemetry sink in scope (Runner-side; compose with runWithStatusSink). */ export declare function runWithBrainTelemetry<T>(emit: (t: BrainTelemetry) => void, fn: () => Promise<T>): Promise<T>; /** Report a brain-layer fallback/telemetry event to the active per-task sink, if any. */ export declare function emitBrainTelemetry(t: BrainTelemetry): void; /** What a request that is about to be sent had stripped from its model's `extraBody`: the wire adapter's `api`, the catalog id * the request was sent as, and the stripped key NAMES (never a value), in `extraBody`'s order. */ export interface ExtraBodyDroppedReport { api: string; modelId: string; keys: readonly string[]; } /** * Run `fn` with a per-run extraBody-strip sink in scope — the THIRD brain→runner ALS channel, same decoupling contract as * its siblings (no brain-interface field, no per-call option, no-op outside the scope, a report never changes a call's * outcome). Unlike them it spans the WHOLE leg (the Runner scopes it around everything the leg does, the end-of-task * compaction included), is NOT shielded around the leg's internal calls (the compaction summary, a side query fired from a * tool, the classifier: their model specs strip keys too), and is NOT revoked on settlement: it writes to no returned value * (the report is an out-of-band notice, attributed to its run by id), and the lanes that run after the result — the * next-prompt suggestions, a call the guardrail abandoned — strip keys the operator should hear about all the same. */ export declare function runWithExtraBodyDropped<T>(observe: (r: ExtraBodyDroppedReport) => void, fn: () => Promise<T>): Promise<T>; /** Report the strip of the request the engine has SELECTED to send, to the active per-run sink, if any (called at the * engine's commit points, never from `buildRequest`, which is also built speculatively). */ export declare function reportExtraBodyDropped(report: ExtraBodyDroppedReport): void; /** A request refused at the gate because the credential it would carry does not belong to the root it was going to, one member * per refusal code, each naming the catalog id it was for and the roots in their DISPLAY spelling (never a value, never a digest * of one): `route.credential_origin_mismatch` — a per-model credential bound to another origin (that origin and the request's, * and what bound it: the answer's declaration or the table — or, empty origin, `"generation"`: an undeclared answer from a seat * handed in before a catalog swap, for an entry not unchanged across it, bound nowhere it dials; what bound it absent when the * refusal — a host's own judgment — does not say it); * `route.credential_mismatch` — the deployment credential paired with another root (the request's root and the declared root, * empty when the brain declares none; either absent when the refusal — a host's own judgment — does not name it). */ export type CredentialRefusalReport = { code: "route.credential_origin_mismatch"; modelId: string; boundOrigin: string; requestOrigin: string; boundBy?: "declaration" | "table" | "generation"; } | { code: "route.credential_mismatch"; modelId: string; requestBaseUrl?: string; configBaseUrl?: string; }; /** * Run `fn` with a per-run credential refusal sink in scope — the FOURTH brain→runner ALS channel, with the third's * shape and for its reasons: the WHOLE leg (a refused compaction summary, side query or classifier call is refused for the * same reason as a turn), not shielded around the leg's internal calls, not revoked on settlement, no-op outside the scope. * The refusal is already decided when it is reported. */ export declare function runWithCredentialRefusals<T>(observe: (r: CredentialRefusalReport) => void, fn: () => Promise<T>): Promise<T>; /** Report a credential refusal to the active per-run sink, if any (called by the request gate's refusal, * `routeRefusalError`; a judgment that only advises reports nothing). The * observer is the Runner's own seat, whose one delivery is the guarded `deliverEngineNotice` — nothing is swallowed here. */ export declare function reportCredentialRefusal(report: CredentialRefusalReport): void; /** A request that withheld a capability from the model it was sent to — one report per capability, each with its own facts: * {@link ImagesWithheldReport} (the message assemblers), {@link FastModeWithheldReport} (the fast-mode applier) and * {@link ThinkingWithheldReport} (the stream engine). */ export type CapabilityWithheldReport = ImagesWithheldReport | FastModeWithheldReport | ThinkingWithheldReport; /** A request whose images were replaced by placeholders: the model, the model's declaration that withheld them * (`capabilityOf`), and how many blocks it replaced. */ export interface ImagesWithheldReport { modelId: string; capability: "image"; cause: Exclude<CapabilityDeclaration, "declared_on">; count: number; } /** A request that asked for fast speed of a model whose catalog entry cannot serve it went at standard speed: the model, the * reason word `fastModeUnavailableFor` gave (its wire or its declaration), and 1 (the request). */ export interface FastModeWithheldReport { modelId: string; capability: "fast_mode"; cause: import("./fast-mode.js").FastModeEntryReason; count: number; } /** * A call that asked for a thinking tier which did not take effect: the model's entry does not declare reasoning, and the request * without the tier truly succeeded (the call kept its output) after the endpoint refused the request that tried it — on this * call (the stream engine's fall-back) — or because the endpoint memory sends it without the tier (cause `downgraded`). A * fall-back after a failure that refused nothing (a server error, a page, a tear, a stall) is not reported. * - `requested` — the tier the call asked for; * - `why` — what the endpoint did: refused in words naming the thinking parameters (`named`, `thinkingRefusalStated`) or in * words the engine does not read (`refused`), or a request that carried them broke off after it had begun answering * (`broke_off`, remembered at once); * - `remembered` — the endpoint is now remembered: its requests go without the thinking parameters until the process restarts; * - `speed` — the speed the endpoint memory was read at (the one the call's withheld set was decided at): what `why` and * `remembered` say holds for requests at that speed only; * - `budgetForm` — the refused request carried the Messages budget form (`thinking.type: "enabled"`), which an endpoint that * takes only the adaptive form refuses. */ export interface ThinkingWithheldReport { modelId: string; capability: "reasoning"; cause: "downgraded"; requested: ThinkingLevel; why: "named" | "refused" | "broke_off"; remembered: boolean; speed: CapabilityRequestSpeed; budgetForm: boolean; } /** * Run `fn` with a per-run withheld-capability sink in scope — the FIFTH brain→runner ALS channel, with the third's shape * and for its reasons: the WHOLE leg (the end-of-task compaction runs after the leg's prompt, and a child leg running * inside its parent's tool call must report to its own leg, not to the scope it inherited), not shielded around the leg's * internal calls, not revoked on settlement, no-op outside the scope. */ export declare function runWithCapabilityWithheld<T>(observe: (r: CapabilityWithheldReport) => void, fn: () => Promise<T>): Promise<T>; /** Report a withheld capability to the active per-run sink, if any (called by the message assemblers' one emit, * `reportImagesWithheld`, and by the stream engine once a request without an asked thinking tier succeeded). The observer is the Runner's own seat, whose one delivery is the guarded `deliverEngineNotice` * — nothing is swallowed here: a seat that fails otherwise fails the request build, never the person's notice in silence. */ export declare function reportCapabilityWithheld(report: CapabilityWithheldReport): void;