@sema-agent/core
Version:
Stateless, task-oriented AI agent core
108 lines (107 loc) • 8.23 kB
TypeScript
/**
* Open Responses adapter (design/163) — a **stateless** Brain for the Open Responses wire shape
* (`POST /responses`: typed input items in, typed output items out, an SSE stream that ends on
* `response.completed` / `response.incomplete` / `response.failed` with NO `[DONE]` sentinel).
*
* Why this lane exists at all: it is ONE wire form spoken by a whole family of endpoints (the
* spec's reference implementations plus the gateways that adopted it), so a deployment reaches
* them through a single adapter instead of one per vendor. It is NOT a second way to talk to an
* endpoint the chat-completions lane already serves well — pick one per model.
*
* ── The one invariant this file is built around: **it is always stateless.** ─────────────────
* The wire form offers server-held conversation state (`store` / `previous_response_id` /
* `conversation`). This engine is the transcript authority; a second authority is how transcripts
* silently fork. So:
* · the request body NEVER carries any of those three fields — it is assembled from a closed,
* typed key set inside the sentinel-marked region below, which the source-scan pin reads;
* · `Model.extraBody` cannot carry across them back in — all three are members of
* {@link RESPONSES_RESERVED}, so the passthrough merge strips them (and prepare-task warns);
* · every turn replays the FULL input. Measured, not assumed: server-side state saves BANDWIDTH,
* not money (the linked history is billed as input either way), and prefix caching keeps the
* replay's cost close to the linked form.
* · the response envelope is CHECKED, not trusted — see the echo audit below.
*
* ── Capability posture: nothing is "sent and assumed" ────────────────────────────────────────
* The spec has no capability-discovery call, and endpoints have been observed to accept a
* parameter, ignore it, and echo back the value they actually used. This adapter therefore
* (a) sends only what it can account for, and (b) AUDITS the `response.created` envelope, which
* echoes the effective request parameters, against what it asked for. Divergences ride the final
* message as a `responses_capability` diagnostic — machine-readable, one per turn, never injected
* into the model's context. Audited: the three statelessness fields (must come back off/absent),
* the reasoning effort tier (asked vs honored), and parallel tool calls (the wire form cannot turn
* it off, so a lane reporting it off is a fact the caller needs). Deliberately NOT sent, because
* this adapter cannot verify the effect and the caller has no knob for it here: `tool_choice`,
* `text.format` (structured output), `parallel_tool_calls` — a deployment that wants those sends
* them through `Model.extraBody` and owns the outcome (the endpoint's own loud rejection).
*
* ── Reasoning ────────────────────────────────────────────────────────────────────────────────
* Reasoning comes back as a first-class `reasoning` output item with plaintext `reasoning_text`
* parts. It is stored as a normal `thinking` block (item id kept in `thinkingSignature`) and
* replayed as a `reasoning` input item on the turns that carry tool calls, never on plain text
* turns (which ignore it, so replaying there is pure window bloat).
*
* That condition is a provider REQUIREMENT, not an optimization, and its measured trigger is
* narrower than it looks: an endpoint in thinking mode rejects a replayed `function_call` whose
* reasoning item is missing ("the reasoning_text in the thinking mode must be passed back") ONLY
* when it does not recognize the call's `call_id` as one of its own. Replay the endpoint's
* verbatim id and the same body is accepted with no reasoning item at all. So on the happy path —
* this engine carries that id through untouched — the requirement is never reached, and the
* conditional replay is insurance for the paths where the id is NOT the endpoint's: a wire frame
* that carried no `call_id` and got a locally minted fallback, a transcript imported from another
* provider, a call rebuilt by a repair path. Those are the paths where losing the model's own
* reasoning would also hurt most.
*
* A tool-call turn that genuinely has no thinking block (a non-reasoning model, a turn whose
* thinking was dropped upstream) is sent AS IS, and on the narrow path above the endpoint refuses
* it loudly — deliberately not papered over, since synthesizing a reasoning item would be
* fabricating model output and a placeholder is the same fabrication with a label. An EMPTY
* thinking block is likewise not forwarded: a reasoning item with empty content is refused
* outright (measured), so forwarding it would turn a harmless empty block into a failed request.
*
* TODO(design/163, encrypted reasoning): endpoints in the OpenAI lineage can return reasoning as
* `encrypted_content` instead of plaintext, handed straight back on the next turn. NOT implemented
* here — no endpoint this lane serves emits it today, and a decode path with no producer is one no
* test can hold honest. The carrier when one does: the existing
* `ThinkingContent.thinkingSignature` + `redacted` pair (the anthropic lane is the precedent).
*
* ── Custom tools ─────────────────────────────────────────────────────────────────────────────
* The wire form has a `custom` tool type alongside `function`. Endpoints restrict it hard (one
* observed lane accepts exactly one built-in custom tool and rejects every other name with a 400).
* Every tool this engine mounts is projected as a `function` tool, so the restriction is not
* reachable from here; the `custom` type is not emitted at all.
*
* The connect/retry/timeout/read-loop machinery is the shared {@link runStreamingBrain} engine
* (design/32) — this adapter owns request shaping, Responses SSE parsing, and finalization.
*/
import { type RoutePairingConfig } from "../internal/llm.js";
import type { Brain } from "../core/types.js";
import { type StreamEngineConfig } from "./stream-engine.js";
export interface OpenResponsesBrainConfig extends StreamEngineConfig, Pick<RoutePairingConfig, "requireCredential"> {
/** Base URL of the Open Responses endpoint, WITHOUT the trailing `/responses`. Overridden by `model.baseUrl`. */
baseUrl?: string;
/** API key. Overridden by per-call `options.apiKey`. */
apiKey?: string;
/** Extra headers merged into every request (auth + content-type are hard-locked after the merge). */
headers?: Record<string, string>;
/** Inject a custom fetch (tests / proxies); the default transport and the `fetchImpl` seat are
* `resolveFetch` (transport.ts). */
fetchImpl?: typeof fetch;
/**
* Replay prior assistant reasoning items back to the endpoint on the turns that carry tool calls
* (see the file header — an endpoint in thinking mode REQUIRES it there and ignores it elsewhere).
* **On by default.** Set `false` only for an endpoint that rejects the `reasoning` input item;
* with it off, a thinking-mode endpoint refuses every replayed tool-call turn.
*/
replayReasoning?: boolean;
/**
* Detect **degenerate repetition** (the model looping on the same char/phrase forever) mid-stream
* and cut it off — the turn ends `error` (`errorKind:"degenerate"`) so the loop stops paying.
* Default true. Same detector, same cadence, same salvage rules as the other two lanes.
*/
detectRepetition?: boolean;
}
/**
* Create a Brain that talks to an Open Responses endpoint. See the file header for the stateless
* invariant, the capability-audit posture, and the reasoning-replay rule.
*/
export declare function createOpenResponsesBrain(given?: OpenResponsesBrainConfig): Brain;