@genkit-ai/ai
Version:
Genkit AI framework generative AI APIs.
700 lines (694 loc) • 29.7 kB
TypeScript
import { BidiAction, ActionContext, Action, z, GenkitError } from '@genkit-ai/core';
import { Registry } from '@genkit-ai/core/registry';
import { MessageData } from './model-types.js';
import { Media, ToolRequestPart, ToolResponsePart } from './parts.js';
import { Artifact, SessionState, AgentFinishReason, AgentInputSchema, AgentOutputSchema, AgentStreamChunkSchema, AgentInitSchema, SessionSnapshot, AgentAbortRequestSchema, AgentAbortResponseSchema, AgentStreamChunk, AgentInput, AgentResult, AgentInit } from './agent-types.js';
export { AgentResultSchema, GetSnapshotRequestSchema, JsonPatchOperationSchema, JsonPatchSchema, TurnEnd, TurnEndSchema } from './agent-types.js';
import { n as PromptConfig } from './prompt-DdE7Y6ZH.js';
import { SessionStoreOptions, SessionStore, Session } from './session.js';
import 'handlebars';
import './document-CeF1EEx1.js';
import './generate/chunk.js';
import './generate/response.js';
import './message.js';
import './formats/types.js';
import './resource.js';
import '@genkit-ai/core/async';
/**
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Result returned by a single turn handler passed to {@link SessionRunner.run}.
*
* Returning a `finishReason` lets a custom agent explicitly state why the turn
* ended (e.g. `interrupted`, `length`). When omitted, no per-turn reason is
* reported.
*/
interface TurnResult {
finishReason?: AgentFinishReason;
}
/**
* Per-turn context handed to the handler passed to {@link SessionRunner.run}.
*
* The `snapshotId` is *reserved at turn start* (before the handler runs) and is
* the id the snapshot persisted at turn end will reuse. This lets a handler
* name external, snapshot-correlated resources - e.g. a git branch / worktree
* named after the snapshot - up front, then commit them under that id, so a
* later rollback to the snapshot can restore the external state too.
*/
interface TurnContext {
/**
* The id the snapshot produced by this turn will be saved under (reserved
* ahead of time so it is known before the turn runs).
*/
snapshotId: string;
/**
* The id of the parent snapshot this turn continues from, or `undefined` on
* the first turn of a fresh session.
*/
parentSnapshotId?: string;
/** Zero-based index of this turn within the current invocation. */
turnIndex: number;
}
/**
* Output returned at turn completion.
*/
interface AgentOutput<S = unknown> {
sessionId?: string;
artifacts?: Artifact[];
message?: MessageData;
snapshotId?: string;
state?: SessionState<S>;
finishReason?: AgentFinishReason;
/**
* Present when `finishReason` is `failed`. Carries the original error
* details (RuntimeError shape); `state`/`snapshotId` hold the last-good state.
*/
error?: {
status?: string;
message: string;
details?: any;
};
}
/**
* Structured error details surfaced on the failure path.
*/
interface AgentErrorDetails {
status: string;
message: string;
details?: any;
}
/**
* Executor responsible for running turns over input streams and persisting state.
*/
declare class SessionRunner<State = unknown> {
readonly session: Session<State>;
readonly inputCh: AsyncIterable<AgentInput>;
turnIndex: number;
onEndTurn?: (snapshotId?: string, finishReason?: AgentFinishReason) => void;
onDetach?: (snapshotId: string) => void;
newSnapshotId?: string;
/** The finish reason of the most recently completed turn. */
lastTurnFinishReason?: AgentFinishReason;
/**
* Error details of the most recent failed turn. Set when a turn throws and
* the runner resolves gracefully instead of propagating the exception.
*/
lastTurnError?: AgentErrorDetails;
/**
* The state the most recently *successful* turn left behind. On a failed
* turn this is the state the failed turn started with - the last-good state
* returned to the caller (for client-managed agents).
*/
lastGoodState?: SessionState<State>;
/**
* The snapshotId of the most recently *successful* (persisted, `done`) turn.
* On a failed turn this is the last-good snapshot the caller resumes from;
* `undefined` when no turn has succeeded yet (e.g. a first-turn failure).
*/
lastGoodSnapshotId?: string;
private lastSnapshot?;
private lastSnapshotVersion;
private store?;
isDetached: boolean;
/**
* Aborts in-flight turns. When set and aborted, a turn that rejects out of
* `generate` is reported as `aborted` (not `failed`) and its failed snapshot
* write is skipped (the abort path already persisted the `aborted` status).
*/
private abortSignal?;
/**
* True until the first `customPatch` chunk of the current turn has been
* emitted. The first patch of every turn is a whole-document replace
* (re-basing clients that may not share the server's baseline); reset to
* `true` at the start of each turn.
*/
firstCustomPatchInTurn: boolean;
constructor(session: Session<State>, inputCh: AsyncIterable<AgentInput>, options?: {
lastSnapshot?: SessionSnapshot<State>;
store?: SessionStore<State>;
abortSignal?: AbortSignal;
onEndTurn?: (snapshotId?: string, finishReason?: AgentFinishReason) => void;
onDetach?: (snapshotId: string) => void;
});
/** Returns a deep copy of the current session state. */
getState(): SessionState<State>;
/** Retrieves all messages associated with the session. */
getMessages(): MessageData[];
/** Appends messages to the session. */
addMessages(messages: MessageData[]): void;
/** Overwrites the session messages. */
setMessages(messages: MessageData[]): void;
/** Retrieves the custom state of the session. */
getCustom(): State | undefined;
/** Updates the custom state using a mutator function. */
updateCustom(fn: (custom?: State) => State): void;
/** Retrieves the list of artifacts generated during the session. */
getArtifacts(): Artifact[];
/** Adds artifacts to the session, deduplicating by name. */
addArtifacts(artifacts: Artifact[]): void;
/** Invokes the end-of-turn callback, absorbing errors from a closed stream. */
private notifyEndTurn;
/**
* Executes the flow handler against incoming input messages sequentially.
*
* The handler receives the turn's {@link AgentInput} and a {@link TurnContext}
* whose `snapshotId` is *reserved up front* - it is the id the snapshot
* persisted at turn end will reuse. This lets a handler set up external,
* snapshot-correlated state (e.g. a git branch/worktree named after the
* snapshot) before generating, then commit it under that id.
*
* The handler may return a {@link TurnResult} carrying an explicit
* `finishReason` for the just-completed turn. When omitted, no per-turn
* reason is reported. Failures always report `failed`.
*/
run(fn: (input: AgentInput, ctx: TurnContext) => Promise<TurnResult | void>): Promise<void>;
/**
* Saves a snapshot of the current session state to the persistent store.
*
* When a store is configured every turn is persisted (snapshotting is no
* longer opt-out). Uses the mutator-based `saveSnapshot` to atomically check
* that the snapshot has not been concurrently aborted before writing -
* preventing a race where a "done" write could overwrite a concurrent
* "aborted" status.
*/
maybeSnapshot(status?: 'pending' | 'completed' | 'failed', error?: {
status?: string;
message: string;
details?: any;
}, snapshotId?: string, finishReason?: AgentFinishReason): Promise<string | undefined>;
}
/**
* Projects an agent's server-side data onto the view a client should see.
*
* Every member is optional; an omitted member passes the corresponding data
* through unchanged. Use this to redact sensitive fields or reshape data
* before it leaves the server - covering both data at rest and data in flight:
*
* - `state` reshapes/redacts session state at rest. Applied to
* `AgentOutput.state` (client-managed agents), to snapshots returned by
* `getSnapshotData`, and as the baseline for streamed `customPatch` diffs
* (so streamed custom-state deltas stay consistent with the transformed
* full state). Note: `state.artifacts` is part of session state, so artifact
* redaction at rest happens here too.
* - `chunk` reshapes/redacts each stream chunk in flight (`modelChunk`,
* `artifact`, `customPatch`, `turnEnd`) - e.g. filtering "internal" tool
* request/response parts out of model chunks, or redacting streamed
* artifacts. Return `null`/`undefined` to drop the chunk entirely.
*
* When both `state` and `chunk` touch the same data (e.g. artifacts), keeping
* the two projections consistent is the author's responsibility.
*/
interface ClientTransform<S = unknown> {
/**
* Reshapes/redacts session state before it is exposed to the client (at
* rest: `AgentOutput.state`, snapshots, and the streamed `customPatch`
* baseline).
*/
state?: (state: SessionState<S>) => SessionState;
/**
* Reshapes/redacts each stream chunk before it is sent to the client.
* Return `null`/`undefined` to drop the chunk entirely.
*/
chunk?: (chunk: AgentStreamChunk) => AgentStreamChunk | null | undefined;
}
/**
* Function handler definition for custom agent actions.
*/
type AgentFn<State> = (sess: SessionRunner<State>, options: {
sendChunk: (chunk: AgentStreamChunk) => void;
abortSignal?: AbortSignal;
context?: ActionContext;
}) => Promise<AgentResult>;
/**
* Lookup input for the `getSnapshotData` action / method.
*
* Mirrors {@link GetSnapshotOptions}: provide exactly one of `snapshotId`
* (an exact snapshot) or `sessionId` (the session's latest leaf snapshot).
*/
declare const GetSnapshotDataInputSchema: z.ZodObject<{
snapshotId: z.ZodOptional<z.ZodString>;
sessionId: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
sessionId?: string | undefined;
snapshotId?: string | undefined;
}, {
sessionId?: string | undefined;
snapshotId?: string | undefined;
}>;
/**
* Lookup input for `getSnapshotData`.
*/
interface GetSnapshotDataInput {
snapshotId?: string;
sessionId?: string;
context?: ActionContext;
}
type GetSnapshotDataAction<S = unknown> = Action<typeof GetSnapshotDataInputSchema, z.ZodType<SessionSnapshot<S>>>;
/**
* Represents a configured, registered Agent.
*
* An `Agent` exposes two surfaces:
*
* 1. The ergonomic, transport-agnostic {@link AgentAPI} (`chat`, `loadChat`,
* `getSnapshot`, `abort`) - the same surface returned by `remoteAgent` on
* the client, so server- and client-side code share one interface.
* 2. The lower-level {@link BidiAction} surface (`run`, `streamBidi`, …) for
* advanced use and for serving over HTTP.
*/
interface Agent<State = unknown> extends BidiAction<typeof AgentInputSchema, typeof AgentOutputSchema, typeof AgentStreamChunkSchema, typeof AgentInitSchema>, AgentAPI<State> {
getSnapshotData(opts: GetSnapshotDataInput): Promise<SessionSnapshot<State> | undefined>;
abort(snapshotId: string, options?: SessionStoreOptions): Promise<SessionSnapshot['status'] | undefined>;
readonly getSnapshotDataAction: GetSnapshotDataAction<State>;
readonly abortAgentAction: Action<typeof AgentAbortRequestSchema, typeof AgentAbortResponseSchema>;
}
/**
* Error thrown for agent init *API misuse* that should surface to the caller as
* a real, thrown error (mapped to an HTTP status by the server handler) rather
* than being absorbed into a graceful `finishReason: 'failed'` result.
*
* Covers calling an agent with an init that does not match its state-management
* mode (e.g. sending `state` to a server-managed agent, or `snapshotId`/
* `sessionId` to a client-managed one) and the snapshot/session ownership
* guard. Other pre-turn failures (missing snapshot, non-resumable snapshot,
* invalid custom state) remain graceful.
*/
declare class AgentInitError extends GenkitError {
}
/**
* Registers a multi-turn custom agent action capable of maintaining persistent state.
*
* When `stateSchema` is provided the custom state is validated at load time
* (from a snapshot store or from the client-supplied `init.state`) and the
* JSON Schema representation is included in the action metadata so that
* tooling (e.g. the Dev UI) can inspect / validate the state shape.
*/
declare function defineCustomAgent<State = unknown>(registry: Registry, config: {
name: string;
description?: string;
stateSchema?: z.ZodType<State>;
store?: SessionStore<State>;
clientTransform?: ClientTransform<State>;
}, fn: AgentFn<State>): Agent<State>;
/**
* Registers an agent from an existing PromptAction.
*
* The `promptInput` option supplies values for the referenced prompt's input
* variables, so a single prompt can be reused and customized by multiple
* agents. Provide the prompt's input schema as the `I` type parameter to get
* a type-checked `promptInput`.
*/
declare function definePromptAgent<State = unknown, I extends z.ZodTypeAny = z.ZodTypeAny>(registry: Registry, config: {
promptName: string;
/** Human-readable description, surfaced on the agent action's metadata. */
description?: string;
/**
* Input values for the referenced prompt's input variables. Lets a single
* prompt be reused/customized across multiple agents (e.g. supplying a
* different `role` or `tone` to a shared dotprompt template).
*/
promptInput?: z.infer<I>;
stateSchema?: z.ZodType<State>;
store?: SessionStore<State>;
clientTransform?: ClientTransform<State>;
}): Agent<State>;
/**
* Validates that every `resume.restart` and `resume.respond` entry references
* a tool request that actually exists in the session history.
*
* For **restart** entries, also validates that the `input` has not been modified
* compared to the original tool request - preventing a malicious client from
* forging tool inputs.
*
* For **respond** entries, validates that a matching tool request (by name + ref)
* exists in history.
*
* Searches the **entire history** (all model messages), not just the last one.
*/
declare function validateResumeAgainstHistory(resume: {
restart?: Array<{
toolRequest: {
name: string;
ref?: string;
input?: unknown;
};
metadata?: Record<string, unknown>;
}>;
respond?: Array<{
toolResponse: {
name: string;
ref?: string;
output?: unknown;
};
}>;
}, history: MessageData[]): void;
/**
* Configuration for `defineAgent`, which combines prompt definition and agent
* registration into a single call.
*/
interface AgentConfig<State = unknown, I extends z.ZodTypeAny = z.ZodTypeAny> extends PromptConfig<I> {
/**
* Optional Zod schema describing the shape of the custom session state.
*
* When provided:
* - The `State` type is inferred from the schema (no explicit generic needed).
* - The JSON Schema is included in action metadata (`metadata.agent.stateSchema`)
* so the Dev UI and other tooling can inspect / validate the state.
* - Custom state is validated at load time (from a snapshot store or from the
* client-supplied `init.state`).
*/
stateSchema?: z.ZodType<State>;
store?: SessionStore<State>;
clientTransform?: ClientTransform<State>;
/**
* Input values for the prompt's input variables. Lets the same prompt
* definition power differently-customized agents (e.g. supplying a different
* `role` or `tone`). Type-checked against the prompt's `input.schema`.
*/
promptInput?: z.infer<I>;
}
/**
* Defines and registers an agent by creating a prompt and wiring it into a
* multi-turn agent in one step.
*
* This is a convenience shortcut for:
* ```ts
* definePrompt(registry, promptConfig);
* definePromptAgent(registry, { promptName: promptConfig.name, ... });
* ```
*/
declare function defineAgent<State = unknown, I extends z.ZodTypeAny = z.ZodTypeAny>(registry: Registry, config: AgentConfig<State, I>): Agent<State>;
/**
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Transport-agnostic agent client core.
*
* This module is browser-safe: it has **no** runtime dependency on the rest of
* `@genkit-ai/ai` (it only imports types, which are erased at compile time) and
* no Node-specific APIs. Both the in-process server agent (`ai.defineAgent`)
* and the HTTP `remoteAgent` client compose the same {@link AgentChatImpl} /
* {@link createAgentAPI} core over a transport that implements
* {@link AgentTransport}.
*
* @module agent-core
*/
/**
* Identifies a snapshot to load: an exact `snapshotId`, or a `sessionId` (the
* session's latest leaf snapshot). Provide exactly one.
*/
type SnapshotLookup = {
snapshotId: string;
} | {
sessionId: string;
};
/**
* The transport-agnostic surface for talking to an agent. The same shape is
* returned by `ai.defineAgent(...)` on the server and by `remoteAgent(...)` on
* the client.
*/
interface AgentAPI<State = unknown> {
/** Starts a new chat, or attaches to one via init. */
chat(init?: AgentInit<State>): AgentChat<State>;
/**
* Loads a server snapshot and returns a chat with history restored. Accepts
* either a `snapshotId` (an exact snapshot) or a `sessionId` (the session's
* latest snapshot).
*/
loadChat(opts: SnapshotLookup): Promise<AgentChat<State>>;
/**
* Reads a snapshot without starting a chat. Requires a server store. Accepts
* a `snapshotId` string, or a lookup object (`{ snapshotId }` /
* `{ sessionId }`).
*/
getSnapshot(lookup: string | SnapshotLookup): Promise<SessionSnapshot<State> | undefined>;
/** Aborts a running snapshot. Requires a server store. */
abort(snapshotId: string): Promise<SessionSnapshot['status'] | undefined>;
}
/**
* A stateful conversation with an agent. Tracks state across turns so callers
* do not have to thread `snapshotId`/`state` by hand.
*/
interface AgentChat<State = unknown> {
/**
* Runs a single turn and resolves with the completed {@link AgentResponse}.
* The non-streaming analog of {@link generate}; for incremental chunks use
* {@link sendStream}.
*/
send(input: string | AgentInput, opts?: {
abortSignal?: AbortSignal;
}): Promise<AgentResponse<State>>;
/**
* Runs a single turn and returns an {@link AgentTurn} exposing `.stream` and
* `.response`. The streaming analog of {@link generateStream}.
*/
sendStream(input: string | AgentInput, opts?: {
abortSignal?: AbortSignal;
}): AgentTurn<State>;
/** Resumes after an interrupt. Sugar for `send({ resume })`. */
resume(resume: AgentInput['resume'], opts?: {
abortSignal?: AbortSignal;
}): Promise<AgentResponse<State>>;
/** Streaming resume. Sugar for `sendStream({ resume })`. */
resumeStream(resume: AgentInput['resume'], opts?: {
abortSignal?: AbortSignal;
}): AgentTurn<State>;
/** Submits a detached (background) turn. */
detach(input: string | AgentInput): Promise<DetachedTask<State>>;
/** Aborts the current snapshot. */
abort(): Promise<SessionSnapshot['status'] | undefined>;
readonly snapshotId?: string;
/** Stable identifier correlating snapshots/turns of this conversation. */
readonly sessionId?: string;
readonly state?: State;
readonly messages: MessageData[];
readonly artifacts: Artifact[];
}
/**
* A single in-flight turn - the analog of `ai.generateStream`'s
* `{ stream, response }`.
*/
interface AgentTurn<State = unknown, O = unknown> {
/** Chunks as the turn progresses. */
readonly stream: AsyncIterable<AgentChunk<State>>;
/** The completed turn, with generate-style accessors. */
readonly response: Promise<AgentResponse<State, O>>;
/** Aborts this in-flight turn. */
abort(): void;
}
/**
* The completed result of a turn. Mirrors `GenerateResponse` and adds the
* agent fields (`snapshotId`, `state`, `artifacts`).
*/
interface AgentResponse<State = unknown, O = unknown> {
readonly message?: MessageData;
readonly text: string;
readonly reasoning: string;
readonly media: Media | null;
readonly data: O | null;
readonly toolRequests: ToolRequestPart[];
readonly interrupts: AgentInterrupt[];
readonly messages: MessageData[];
readonly finishReason: AgentFinishReason;
readonly finishMessage?: string;
readonly raw: AgentOutput<State>;
assertValid(): void;
readonly snapshotId?: string;
/** Stable identifier correlating snapshots/turns of this conversation. */
readonly sessionId?: string;
readonly state?: State;
readonly artifacts: Artifact[];
}
/**
* A streamed chunk. Mirrors `GenerateResponseChunk` and adds the agent fields
* (`artifact`, `custom`).
*/
interface AgentChunk<State = unknown> {
readonly text: string;
readonly reasoning: string;
readonly accumulatedText: string;
readonly toolRequests: ToolRequestPart[];
readonly data: unknown;
readonly media: Media | null;
readonly artifact?: Artifact;
/**
* The full, post-patch custom state. Present only on chunks that carry a
* custom-state update; `undefined` on text / model chunks. Each value is a
* fresh object reference (the client applies the streamed RFC 6902 JSON Patch
* onto a clone), so it is safe to use for `===` change detection in UI
* frameworks. Equivalent to the value {@link AgentChat.state} returns at the
* moment this chunk is yielded.
*/
readonly custom?: State;
readonly raw: AgentStreamChunk;
}
/**
* A single tool request a turn paused on. `respond`/`restart` are builders:
* they return the part to put into a `resume` payload, they do not send.
*/
interface AgentInterrupt<Input = unknown, Output = unknown> {
name: string;
ref?: string;
input: Input;
/** Builds a `respond` entry for this interrupt. Does not send. */
respond(output: Output): ToolResponsePart;
/** Builds a `restart` entry re-issuing the original tool request. */
restart(): ToolRequestPart;
}
/**
* A handle to a background (detached) task.
*/
interface DetachedTask<State = unknown> {
readonly snapshotId: string;
/** Yields status until a terminal state. */
poll(opts?: {
intervalMs?: number;
}): AsyncIterable<SessionSnapshot<State>>;
/** Resolves when the task reaches a terminal state. */
wait(opts?: {
intervalMs?: number;
}): Promise<SessionSnapshot<State>>;
/** Aborts the task. */
abort(): Promise<SessionSnapshot['status'] | undefined>;
}
/**
* Thrown when a turn fails. Carries the last-good state so the session is
* recoverable.
*/
declare class AgentError<State = unknown> extends Error {
readonly status: string;
readonly details?: unknown;
readonly state?: State;
readonly snapshotId?: string;
readonly response: AgentResponse<State>;
constructor(opts: {
message: string;
status: string;
details?: unknown;
state?: State;
snapshotId?: string;
response: AgentResponse<State>;
});
}
/**
* The pluggable backend the agent-client core runs over. Implementations exist
* for the in-process server agent (driving the agent action directly) and for
* the HTTP `remoteAgent` (driving `streamFlow`/`runFlow`).
*/
interface AgentTransport {
/** Declares server- vs client-managed state; auto-detected when omitted. */
stateManagement?: 'server' | 'client';
/**
* Runs a single turn. Returns the streamed chunks plus a promise for the
* final, non-throwing {@link AgentOutput} (failures resolve with
* `finishReason: 'failed'`).
*/
runTurn(input: AgentInput, init: AgentInit, opts: {
abortSignal: AbortSignal;
}): {
stream: AsyncIterable<AgentStreamChunk>;
output: Promise<AgentOutput>;
};
/** Reads a snapshot. Requires a server store. */
getSnapshot(lookup: SnapshotLookup): Promise<SessionSnapshot<any> | undefined>;
/** Aborts a running snapshot. Requires a server store. */
abort(snapshotId: string): Promise<SessionSnapshot['status'] | undefined>;
}
declare class AgentChatImpl<State = unknown> implements AgentChat<State> {
private readonly transport;
private readonly connectInit?;
snapshotId?: string;
sessionId?: string;
messages: MessageData[];
artifacts: Artifact[];
private clientState?;
constructor(transport: AgentTransport, connectInit?: AgentInit<State> | undefined);
get state(): State | undefined;
/**
* Replaces the tracked `clientState`/`messages`/`artifacts` aggregates with
* (copies of) those carried by a session state.
*/
private hydrateFromState;
/** Loads aggregates from a server snapshot (used by `loadChat`). */
_loadFromSnapshot(snapshot: SessionSnapshot<State>): void;
/**
* Builds the init for the next turn from tracked aggregates. Always returns
* an object (never `undefined`) because the agent validates `init` against
* `AgentInitSchema` - an empty object is the valid "fresh session" init.
*/
private buildInit;
/** Applies a completed turn's output to the running aggregates. */
private applyOutput;
/**
* Wires an optional external abort signal to a fresh {@link AbortController}
* and returns it alongside a getter for whether the turn was aborted.
*/
private setupAbort;
/**
* Resolves a turn's raw `output` into an {@link AgentResponse}, applying it to
* the running aggregates and throwing an {@link AgentError} on a failed turn.
* Aborted turns resolve to a synthetic `aborted` response. Shared by both
* {@link send} and {@link sendStream}.
*/
private buildResponse;
send(input: string | AgentInput, opts?: {
abortSignal?: AbortSignal;
}): Promise<AgentResponse<State>>;
sendStream(input: string | AgentInput, opts?: {
abortSignal?: AbortSignal;
}): AgentTurn<State>;
resume(resume: AgentInput['resume'], opts?: {
abortSignal?: AbortSignal;
}): Promise<AgentResponse<State>>;
resumeStream(resume: AgentInput['resume'], opts?: {
abortSignal?: AbortSignal;
}): AgentTurn<State>;
/**
* Applies a streamed RFC 6902 JSON Patch to the locally tracked custom
* state, keeping {@link state} live as the turn streams. The first patch of
* a turn is a whole-document replace (rooted at `""`) that re-bases the
* client onto the server's current baseline.
*
* Transport requirement: `customPatch` chunks carry no sequence number and
* are applied positionally, so the transport MUST deliver them in order with
* no loss. The in-order SSE channel used today satisfies this; a lossy or
* reordering transport would yield silently-wrong state (each turn does begin
* with a whole-document replace, so corruption cannot persist past a turn
* boundary).
*/
private applyCustomPatch;
detach(input: string | AgentInput): Promise<DetachedTask<State>>;
abort(): Promise<SessionSnapshot['status'] | undefined>;
private toAgentError;
}
/**
* Composes the {@link AgentAPI} surface (`chat`/`loadChat`/`getSnapshot`/
* `abort`) over a {@link AgentTransport}. Shared by the in-process server agent
* and the HTTP `remoteAgent`.
*/
declare function createAgentAPI<State = unknown>(transport: AgentTransport): AgentAPI<State>;
export { type AgentAPI as A, type Agent, AgentAbortRequestSchema, AgentAbortResponseSchema, type AgentConfig, type AgentFn, AgentInit, AgentInitError, AgentInitSchema, AgentInput, AgentInputSchema, type AgentOutput, AgentOutputSchema, AgentResult, AgentStreamChunk, AgentStreamChunkSchema, type ClientTransform, type DetachedTask as D, type GetSnapshotDataAction, type GetSnapshotDataInput, GetSnapshotDataInputSchema, type SnapshotLookup as S, SessionRunner, type TurnContext, type TurnResult, type AgentChat as a, AgentChatImpl as b, type AgentChunk as c, AgentError as d, defineAgent, defineCustomAgent, definePromptAgent, type AgentInterrupt as e, type AgentResponse as f, type AgentTransport as g, type AgentTurn as h, createAgentAPI as i, validateResumeAgainstHistory };