UNPKG

agents

Version:

A home for your AI agents

6,148 lines 238 kB
import { n as AgentEmail } from "./internal_context-Dg4Cgjcu.js";
import { t as RetryOptions } from "./retries-CAvxtG9d.js";
import {
  n as Observability,
  r as ObservabilityEvent,
  s as MCPObservabilityEvent
} from "./index-BRnybD6X.js";
import { t as AgentMcpOAuthProvider } from "./do-oauth-client-provider-VTZj2VtM.js";
import {
  a as McpAuthContext,
  c as CORSOptions,
  d as ServeOptions,
  f as TransportType,
  l as MaybePromise,
  n as StatelessMcpHandler,
  s as BaseTransportType,
  t as CreateStatelessMcpHandlerOptions,
  u as McpClientOptions
} from "./handler-stateless-C_bo-Ytq.js";
import { n as LegacyCallToolResultSchema } from "./client-invoker-BNSZxAkv.js";
import {
  _ as WorkflowEventPayload,
  d as WorkflowCallback,
  l as RunWorkflowOptions,
  v as WorkflowInfo,
  x as WorkflowQueryCriteria,
  y as WorkflowPage
} from "./workflow-types-Baz_PO5v.js";
import { t as MessageType } from "./types-6Zo2zfoO.js";
import { r as EmailResolver } from "./email-CL27preh.js";
import { RpcTarget } from "cloudflare:workers";
import {
  Connection,
  Connection as Connection$1,
  ConnectionContext,
  ConnectionContext as ConnectionContext$1,
  PartyServerOptions,
  RoutingRetryOptions,
  Server,
  WSMessage,
  WSMessage as WSMessage$1
} from "partyserver";
import { z } from "zod";
import {
  CacheableRequestOptions,
  CallToolRequest,
  CallToolRequestOptions,
  Client,
  ClientCapabilities,
  DiscoverResult,
  ElicitRequest,
  ElicitRequest as ElicitRequest$1,
  ElicitRequest as ElicitRequest$2,
  ElicitResult,
  ElicitResult as ElicitResult$2,
  ElicitResult as ElicitResult$3,
  GetPromptRequest,
  JSONRPCMessage,
  MessageExtraInfo,
  Prompt,
  ReadResourceRequest,
  RequestOptions,
  Resource,
  ResourceTemplateType,
  SSEClientTransport,
  SSEClientTransportOptions,
  ServerCapabilities,
  StreamableHTTPClientTransport,
  StreamableHTTPClientTransportOptions,
  StreamableHTTPReconnectionOptions,
  Tool,
  Transport,
  TransportSendOptions
} from "@modelcontextprotocol/client";
import {
  ElicitRequestSchema,
  ElicitResult as ElicitResult$1,
  InitializeRequestParams,
  JSONRPCMessage as JSONRPCMessage$1,
  MessageExtraInfo as MessageExtraInfo$1,
  RequestId
} from "@modelcontextprotocol/sdk/types.js";
import { McpServerFactory } from "@modelcontextprotocol/server";
import { McpServer as McpServer$1 } from "@modelcontextprotocol/sdk/server/mcp.js";
import { Server as Server$2 } from "@modelcontextprotocol/sdk/server/index.js";
import {
  EventStore as EventStore$1,
  StreamId as StreamId$1,
  WebStandardStreamableHTTPServerTransport as WebStandardStreamableHTTPServerTransport$1,
  WebStandardStreamableHTTPServerTransportOptions
} from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import {
  Transport as Transport$1,
  TransportSendOptions as TransportSendOptions$1
} from "@modelcontextprotocol/sdk/shared/transport.js";
import {
  EventId,
  EventStore,
  StreamId
} from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";

//#region src/observability/tracing/tracer.d.ts
type InvocationScopeOptions = {
  /**
   * Open a scope even inside a live one, for work deliberately detached from
   * the handler that started it — `ctx.waitUntil` bodies, queue drains — which
   * runs on past that handler and must not be cut off with it.
   */
  readonly detached?: boolean;
};
/**
 * Runs `body` as one traced invocation.
 *
 * Work that escapes its native invocation cannot be traced from the context it
 * started in: the still-open span is force-closed against the invocation that
 * owned that context, which reports a negative duration or `span_not_ended`.
 * Spans opened with {@link SpanLifetime.boundToInvocation} inside this scope
 * are therefore closed before `body` settles — but not one moment earlier, so
 * everything that completes during the invocation (the normal case: a chat
 * turn is awaited by the handler that received it) still records its finish
 * attributes. A span truncated this way is marked
 * `cloudflare.agents.span.truncated` rather than passing as complete.
 */
declare function withInvocationScope<T>(
  body: () => T,
  options?: InvocationScopeOptions
): T;
//#endregion
//#region src/sub-routing.d.ts
/**
 * URL segment marking a parent↔child boundary.
 *
 * Exposed as a constant so callers can build URLs symbolically, but
 * not configurable — the routing layer matches on the literal `sub`
 * token everywhere (parent fetch, client, helpers).
 */
declare const SUB_PREFIX = "sub";
interface SubAgentPathMatch {
  /** CamelCase class name of the child, as it appears in `ctx.exports`. */
  childClass: string;
  /** URL-decoded child name. */
  childName: string;
  /**
   * Request path to forward to the child, with the
   * `/sub/{class}/{name}` segment stripped. Always begins with `/`;
   * may itself contain further `/sub/...` markers when a
   * recursively nested sub-agent is being routed.
   */
  remainingPath: string;
}
/**
 * Parse a URL and extract the first `/sub/{class}/{name}` segment,
 * if any. Recursive nesting is handled naturally: callers parse one
 * level at a time; the child then parses its own URL (which still
 * contains any deeper `/sub/...` markers).
 *
 * Names are URL-decoded. Classes are kebab-to-CamelCase converted
 * via a best-effort match against a provided lookup — pass
 * `ctx.exports` keys to get exact CamelCase; pass `undefined` for
 * a tolerant conversion without validation.
 *
 * Returns `null` when the URL doesn't contain the marker at a
 * recognized position, or when the marker has no following
 * class+name pair.
 */
declare function parseSubAgentPath(
  url: string,
  options?: {
    /** CamelCase class names to match against (usually `ctx.exports` keys). */ knownClasses?: readonly string[];
  }
): SubAgentPathMatch | null;
/**
 * Route a request into a sub-agent via its parent DO.
 *
 * Use this in a custom fetch handler when your URL shape doesn't
 * match the `/agents/{class}/{name}` default — you identify and
 * fetch the parent yourself, then let this helper parse the
 * `/sub/{child}/...` tail and forward it.
 *
 * Runs `onBeforeSubAgent` on the parent DO (authorization / request
 * mutation / short-circuit response).
 *
 * For the default `/agents/...` URL shape, use `routeAgentRequest`
 * instead — it handles the parent lookup and this dispatch in one
 * call.
 *
 * @example
 * ```ts
 * export default {
 *   async fetch(req, env) {
 *     const { parentName, rest } = myCustomParse(req.url);
 *     const parent = await getAgentByName(env.Inbox, parentName);
 *     return routeSubAgentRequest(req, parent, { fromPath: rest });
 *   }
 * };
 * ```
 *
 * @experimental The API surface may change before stabilizing.
 */
declare function routeSubAgentRequest(
  req: Request,
  parent: unknown,
  options?: {
    /**
     * Path to route on. Defaults to `req.url`'s pathname. Useful
     * when your outer URL is custom (e.g. `/api/v1/...`) and you
     * want to route the sub-agent tail without rewriting the
     * Request first.
     */
    fromPath?: string;
  }
): Promise<Response>;
/**
 * Get a typed RPC stub for a sub-agent from outside the parent DO.
 *
 * The returned stub proxies method calls through the parent via a
 * stateless per-call bridge (caller → parent → facet), so each
 * method invocation costs one extra RPC hop. Works across parent
 * hibernation — no cached references to go stale.
 *
 * Limitations:
 *   - RPC methods only. `.fetch()` is not supported (will throw).
 *     Use `routeSubAgentRequest` for external HTTP/WS.
 *   - Arguments and return values must be structured-cloneable,
 *     same as any DO RPC call.
 *   - Does not run `onBeforeSubAgent` on the parent — analogous to
 *     `getAgentByName` not running `onBeforeConnect`. The caller is
 *     assumed to have performed whatever access checks are needed.
 *
 * @example
 * ```ts
 * const inbox = await getAgentByName(env.MyInbox, userId);
 * const chat = await getSubAgentByName(inbox, MyChat, chatId);
 * await chat.addMessage({ role: "user", content: "hi" });
 * ```
 *
 * @experimental The API surface may change before stabilizing.
 */
declare function getSubAgentByName<T extends Agent>(
  parent: unknown,
  cls: SubAgentClass<T>,
  name: string
): Promise<SubAgentStub<T>>;
//#endregion
//#region src/core/events.d.ts
interface Disposable {
  dispose(): void;
}
type Event<T> = (listener: (e: T) => void) => Disposable;
declare class Emitter<T> implements Disposable {
  private _listeners;
  readonly event: Event<T>;
  fire(data: T): void;
  dispose(): void;
}
//#endregion
//#region src/mcp/client-transports.d.ts
/**
 * @deprecated Use SSEClientTransport from @modelcontextprotocol/client instead. This alias will be removed in the next major version.
 */
declare class SSEEdgeClientTransport extends SSEClientTransport {
  constructor(url: URL, options: SSEClientTransportOptions);
}
/**
 * @deprecated Use StreamableHTTPClientTransport from @modelcontextprotocol/client instead. This alias will be removed in the next major version.
 */
declare class StreamableHTTPEdgeClientTransport extends StreamableHTTPClientTransport {
  constructor(url: URL, options: StreamableHTTPClientTransportOptions);
}
//#endregion
//#region src/mcp/worker-transport.d.ts
/**
 * Pluggable storage adapter for persisting `WorkerTransport` state across
 * Durable Object hibernation / restart cycles.
 *
 * A typical implementation reads/writes a single key on `this.ctx.storage`
 * inside a Durable Object or Agent.
 */
interface MCPStorageApi {
  get(): Promise<TransportState | undefined> | TransportState | undefined;
  set(state: TransportState): Promise<void> | void;
}
/** Shape of the persisted transport state. */
interface TransportState {
  sessionId?: string;
  initialized: boolean;
  initializeParams?: InitializeRequestParams;
}
interface WorkerTransportOptions extends WebStandardStreamableHTTPServerTransportOptions {
  /**
   * CORS options applied to every response and to OPTIONS preflight.
   * Defaults: `origin: *`, expose `mcp-session-id`, allow the standard MCP
   * methods/headers, max-age 86400.
   */
  corsOptions?: CORSOptions;
  /**
   * Optional storage adapter for persisting transport state across DO
   * hibernation / restart. Use this to keep an MCP session alive across
   * Durable Object wake-ups.
   */
  storage?: MCPStorageApi;
}
declare class WorkerTransport extends WebStandardStreamableHTTPServerTransport$1 {
  private readonly _corsOptions?;
  private readonly _storage?;
  private _stateRestored;
  private _capturedInitializeParams?;
  private _userOnSessionInitialized?;
  private _bridgeInstalled;
  /**
   * Request ids whose SSE stream was deliberately torn down via
   * `closeSSEStream`. The SDK's `send()` throws "No connection established"
   * when a request id has no stream — a race that surfaces whenever the
   * server's tool handler resolves *after* the caller closed the stream
   * (e.g. polling-style early-close, or test fixtures closing mid-flight).
   * We swallow `send()` for these ids so the rejection doesn't bubble out
   * of the protocol layer as an unhandled rejection. Mirrors the
   * silent-noop behaviour of the pre-refactor `WorkerTransport`.
   */
  private readonly _closedRequestIds;
  constructor(options?: WorkerTransportOptions);
  /**
   * Backwards-compatible alias for the SDK's internal `_started` flag.
   * Several callers and tests check `transport.started` directly.
   */
  get started(): boolean;
  /**
   * Top-level request entry point. Handles CORS preflight, restores any
   * persisted state on first invocation, then delegates to the SDK transport
   * and finally appends CORS headers to whatever response comes back.
   */
  handleRequest(
    request: Request,
    options?: {
      parsedBody?: unknown;
      authInfo?: AuthInfo;
    }
  ): Promise<Response>;
  /**
   * The SDK's 405 responses advertise `Allow: GET, POST, DELETE` because
   * OPTIONS is handled outside the SDK. Since our wrapper *does* handle
   * OPTIONS, advertise it in `Allow` so clients can probe accurately.
   */
  private normalizeAllowHeader;
  closeSSEStream(requestId: RequestId): void;
  close(): Promise<void>;
  /**
   * Swallow two classes of message that would otherwise surface as
   * unhandled rejections from the SDK transport's `send()`:
   *
   *   1. Replayed initialize responses (the `RESTORE_REQUEST_ID` sentinel)
   *      — we synthesise these in `restoreState()` to rebuild server
   *      capabilities; there's no real client waiting for the response.
   *   2. Sends for a request id whose SSE stream has been deliberately
   *      closed via `closeSSEStream`. The protocol layer's tool-handler
   *      promise may settle after the close, and the SDK's `send()` throws
   *      "No connection established" — a race the pre-refactor transport
   *      silently swallowed.
   *
   * Everything else is delegated. We use `await super.send(...)` rather
   * than `return super.send(...)` so any rejection is observed inside this
   * async frame; without the await, the test runner's
   * unhandled-rejection tracker can fire before the caller's own `await`
   * observes it.
   */
  send(
    message: JSONRPCMessage$1,
    options?: TransportSendOptions$1
  ): Promise<void>;
  private getCorsHeaders;
  private withCorsHeaders;
  private installOnSessionInitializedBridge;
  private captureInitializeParams;
  private restoreState;
  private saveState;
}
//#endregion
//#region src/mcp/handler-legacy.d.ts
/** Options for the retained SDK v1, sessionful handler. */
interface CreateLegacyMcpHandlerOptions extends WorkerTransportOptions {
  /** Exact route handled by this handler. @default "/mcp" */
  route?: string;
  /** Application props exposed through {@link getMcpAuthContext}. */
  authContext?: McpAuthContext;
  /** Pre-created sessionful transport. */
  transport?: WorkerTransport;
}
type CreateMcpHandlerOptions$1 = CreateLegacyMcpHandlerOptions;
type LegacyMcpHandler = (
  request: Request,
  env: unknown,
  ctx: ExecutionContext
) => Promise<Response>;
/**
 * Create a sessionful Legacy MCP handler backed by SDK v1.
 *
 * New Stateless servers should use `createMcpHandler` from
 * `agents/mcp/server` instead.
 */
declare function createLegacyMcpHandler(
  server: McpServer$1 | Server$2,
  options?: CreateLegacyMcpHandlerOptions
): LegacyMcpHandler;
//#endregion
//#region src/mcp/handler-compat.d.ts
/**
 * @deprecated Passing an SDK v1 server to createMcpHandler is deprecated and
 * will be removed in the next major version. Pass an SDK v2 factory to
 * createMcpHandler. Use createLegacyMcpHandler only to temporarily retain
 * sessionful SDK v1 behavior while migrating.
 */
declare function createMcpHandler$1(
  server: McpServer$1 | Server$2,
  options?: CreateMcpHandlerOptions$1
): LegacyMcpHandler;
declare function createMcpHandler$1(
  factory: McpServerFactory,
  options?: CreateStatelessMcpHandlerOptions
): StatelessMcpHandler;
/**
 * @deprecated Pass an SDK v2 factory to createMcpHandler.
 * experimental_createMcpHandler will be removed in the next major version.
 * Use createLegacyMcpHandler only to temporarily retain sessionful SDK v1
 * behavior while migrating.
 */
declare function experimental_createMcpHandler(
  server: McpServer$1 | Server$2,
  options?: CreateMcpHandlerOptions$1
): LegacyMcpHandler;
//#endregion
//#region src/mcp/event-store.d.ts
/**
 * Durable Object–backed {@link EventStore} for SSE resumability.
 *
 * Default for `McpAgent`. Override `McpAgent.getEventStore()` to swap
 * or disable.
 *
 * ## Storage layout
 *
 * Events are stored under `__mcp_event__:<streamId>:<seqHex>`, where
 * `<seqHex>` is a 16-char zero-padded counter so events in a stream
 * sort lexicographically and `getStreamIdForEventId` can recover the
 * stream from `eventId` without a storage hit.
 *
 * ## Lifecycle
 *
 * Each POST tool-call stream's events live only until the final
 * response is delivered. The transport calls {@link clearStream}
 * immediately after writing the close frame, so storage growth is
 * bounded by the in-flight POST streams plus the standalone GET
 * stream. There is no background sweep — quiescent agents do no work,
 * and the DO itself dies with the session.
 *
 * Standalone GET stream events (`_GET_stream`) are *not* cleared
 * automatically; they accumulate for the lifetime of the DO. Bounded
 * by session length in practice.
 *
 * Trade-off: if the client TCP connection dies *after* the close
 * frame has been enqueued on the WS but before the bytes reach the
 * client, the final message is unreplayable. Every earlier event in
 * the stream is still replayable while the in-flight stream is open.
 *
 * ## Stream id constraints
 *
 * `streamId` MUST NOT contain `:`. `storeEvent` asserts this so
 * embedders using custom stream ids fail loudly rather than risk
 * prefix-scan collisions (e.g. clearing `a` accidentally hitting
 * `a:b`). Default ids (`connection.id` UUIDs and the literal
 * `_GET_stream`) already satisfy this.
 */
declare class DurableObjectEventStore implements EventStore {
  private static readonly EVENT_KEY_PREFIX;
  private static readonly SEQ_PAD;
  /** DO storage caps multi-key delete at 128. */
  private static readonly DELETE_CHUNK;
  /** Defensive ceiling on a single replay batch. A live stream's
   *  event count is small (progress notifications + final result);
   *  this is here so a pathological history can't OOM the DO. */
  private static readonly REPLAY_LIMIT;
  private readonly storage;
  /** In-memory seq counters per stream, rehydrated lazily from storage. */
  private readonly seqByStream;
  private readonly seqInit;
  constructor(storage: DurableObjectStorage);
  storeEvent(streamId: StreamId, message: JSONRPCMessage$1): Promise<EventId>;
  getStreamIdForEventId(eventId: EventId): Promise<StreamId | undefined>;
  replayEventsAfter(
    lastEventId: EventId,
    {
      send
    }: {
      send: (eventId: EventId, message: JSONRPCMessage$1) => Promise<void>;
    }
  ): Promise<StreamId>;
  /**
   * Drop the event log for a single stream. Called by the transport
   * immediately after a POST's final response has been written to the
   * wire — no future `Last-Event-ID` for this stream is expected to
   * resolve.
   *
   * Lists and deletes in chunks of {@link DELETE_CHUNK} (128, the DO
   * storage cap) so we never load the entire event log into memory.
   * After deleting, the next `list` call won't see the deleted keys,
   * so passing `start: <prefix>` again is enough — no cursor bookkeeping.
   */
  clearStream(streamId: StreamId): Promise<void>;
  private ensureSeqLoaded;
}
//#endregion
//#region src/mcp/transport.d.ts
/**
 * An {@link EventStore} that supports dropping all events for a single
 * stream id. Implemented by {@link DurableObjectEventStore}.
 */
interface ClearableEventStore extends EventStore$1 {
  clearStream(streamId: StreamId$1): Promise<void>;
}
//#endregion
//#region src/mcp/legacy-agent.d.ts
/**
 * @deprecated McpAgent is feature-frozen. Migrate to an SDK v2 factory with
 * createMcpHandler from agents/mcp/server. When sessionful features prevent an
 * immediate migration, run the stateless route beside the existing McpAgent
 * route until clients transition and sessions drain.
 */
declare abstract class McpAgent<
  Env extends Cloudflare.Env = Cloudflare.Env,
  State = unknown,
  Props extends Record<string, unknown> = Record<string, unknown>
> extends Agent<Env, State, Props> {
  private _transport?;
  private _pendingElicitations;
  props?: Props;
  shouldSendProtocolMessages(
    _connection: Connection$1,
    ctx: ConnectionContext$1
  ): boolean;
  abstract server: MaybePromise<McpServer$1 | Server$2>;
  abstract init(): Promise<void>;
  setInitializeRequest(initializeRequest: JSONRPCMessage$1): Promise<void>;
  getInitializeRequest(): Promise<JSONRPCMessage$1 | undefined>;
  /**
   * Storage key prefix for the `streamId -> requestIds` mapping used
   * to support POST stream resumption across WebSocket reconnects.
   *
   * @internal
   */
  private static readonly STREAM_REQS_KEY_PREFIX;
  /** Persist the `requestIds` for a POST stream. @internal */
  setStreamRequestIds(streamId: string, requestIds: RequestId[]): Promise<void>;
  /** Read the persisted `requestIds` for a POST stream. @internal */
  getStreamRequestIds(streamId: string): Promise<RequestId[] | undefined>;
  /** Drop the persisted `requestIds` for a POST stream. @internal */
  deleteStreamRequestIds(streamId: string): Promise<void>;
  /**
   * Reverse lookup: find which POST stream a given `requestId` belongs
   * to, and return the stream's full `requestIds` list in the same
   * pass. Used by the transport when the originating WS has dropped,
   * so `send()` can still record events for replay and decide whether
   * the stream is fully responded — mirrors the SDK's
   * `_requestToStreamMapping` which outlives connection loss.
   *
   * Returning `requestIds` alongside `streamId` lets `send()` skip a
   * second `getStreamRequestIds` read on the same key.
   *
   * O(n) in the number of in-flight POST streams — single-digit in
   * practice since each stream is cleaned up on its final response.
   * The `limit` is a defensive ceiling so an abandoned-POST leak can't
   * unbounded-load this scan; if you hit it, something else has gone
   * wrong and `send()` will throw `No active stream found`.
   *
   * @internal
   */
  getStreamForRequestId(requestId: RequestId): Promise<
    | {
        streamId: string;
        requestIds: RequestId[];
      }
    | undefined
  >;
  /** Read the transport type for this agent.
   * This relies on the naming scheme being `sse:${sessionId}`,
   * `streamable-http:${sessionId}`, or `rpc:${sessionId}`.
   */
  getTransportType(): BaseTransportType;
  /** Read the sessionId for this agent.
   * This relies on the naming scheme being `sse:${sessionId}`
   * or `streamable-http:${sessionId}`.
   */
  getSessionId(): string;
  /** Get the unique WebSocket. SSE transport only. */
  getWebSocket(): Connection$1<unknown> | null;
  /**
   * Returns options for configuring the RPC server transport.
   * Override this method to customize RPC transport behavior (e.g., timeout).
   *
   * @example
   * ```typescript
   * class MyMCP extends McpAgent {
   *   protected getRpcTransportOptions() {
   *     return { timeout: 120000 }; // 2 minutes
   *   }
   * }
   * ```
   */
  protected getRpcTransportOptions(): RPCServerTransportOptions;
  /**
   * Returns the {@link EventStore} for SSE resumability. Defaults to a
   * {@link DurableObjectEventStore} backed by this agent's storage,
   * letting clients reconnect with `Last-Event-ID` after the Cloudflare
   * edge closes an idle SSE stream (~5 minute watchdog) instead of
   * relying on a server-side keepalive that would block hibernation.
   *
   * Per-stream events are cleared by the transport immediately after
   * the final response is written to the wire, so there's no
   * background cleanup — storage cost is bounded by the in-flight
   * streams alone.
   *
   * Override to disable (`return undefined`) or swap implementations.
   */
  protected getEventStore(): EventStore | undefined;
  /** Returns a new transport matching the type of the Agent. */
  private initTransport;
  /** Update and store the props */
  updateProps(props?: Props): Promise<void>;
  reinitializeServer(): Promise<void>;
  /** Sets up the MCP transport and server every time the Agent is started.*/
  onStart(props?: Props): Promise<void>;
  /** Validates new WebSocket connections. */
  onConnect(
    conn: Connection$1,
    { request: req }: ConnectionContext$1
  ): Promise<void>;
  /** Handles MCP Messages for the legacy SSE transport. */
  onSSEMcpMessage(
    _sessionId: string,
    messageBody: unknown,
    extraInfo?: MessageExtraInfo$1
  ): Promise<Error | null>;
  /** Elicit user input with a message and schema */
  elicitInput(
    params: {
      message: string;
      requestedSchema: unknown;
    },
    options?: {
      relatedRequestId?: RequestId;
    }
  ): Promise<ElicitResult$1>;
  /** Handle elicitation responses via in-memory resolver */
  private _handleElicitationResponse;
  /**
   * Handle an RPC message for MCP
   * This method is called by the RPC stub to process MCP messages
   * @param message The JSON-RPC message(s) to handle
   * @returns The response message(s) or undefined
   */
  handleMcpMessage(
    message: JSONRPCMessage$1 | JSONRPCMessage$1[]
  ): Promise<JSONRPCMessage$1 | JSONRPCMessage$1[] | undefined>;
  /** Return a handler for the given path for this MCP.
   * Defaults to Streamable HTTP transport.
   */
  static serve(
    path: string,
    { binding, corsOptions, transport, jurisdiction }?: ServeOptions
  ): {
    fetch<Env>(
      this: void,
      request: Request,
      env: Env,
      ctx: ExecutionContext
    ): Promise<Response>;
  };
  /**
   * Legacy api
   **/
  static mount(
    path: string,
    opts?: Omit<ServeOptions, "transport">
  ): {
    fetch<Env>(
      this: void,
      request: Request,
      env: Env,
      ctx: ExecutionContext
    ): Promise<Response>;
  };
  static serveSSE(
    path: string,
    opts?: Omit<ServeOptions, "transport">
  ): {
    fetch<Env>(
      this: void,
      request: Request,
      env: Env,
      ctx: ExecutionContext
    ): Promise<Response>;
  };
}
//#endregion
//#region src/mcp/rpc.d.ts
type JSONRPCMessage$2 = JSONRPCMessage$1;
type MessageExtraInfo$2 = MessageExtraInfo$1;
declare const RPC_DO_PREFIX = "rpc:";
interface RPCClientTransportOptions<T extends McpAgent = McpAgent> {
  namespace: DurableObjectNamespace<T>;
  name: string;
  props?: Record<string, unknown>;
}
declare class RPCClientTransport implements Transport {
  private _namespace;
  private _name;
  private _props?;
  private _stub?;
  private _started;
  private _protocolVersion?;
  sessionId?: string;
  onclose?: () => void;
  onerror?: (error: Error) => void;
  onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void;
  constructor(options: RPCClientTransportOptions<McpAgent>);
  setProtocolVersion(version: string): void;
  getProtocolVersion(): string | undefined;
  start(): Promise<void>;
  close(): Promise<void>;
  send(
    message: JSONRPCMessage | JSONRPCMessage[],
    options?: TransportSendOptions
  ): Promise<void>;
}
interface RPCServerTransportOptions {
  timeout?: number;
}
declare class RPCServerTransport implements Transport$1 {
  private _started;
  private _protocolVersion?;
  private _timeout;
  private _pendingRequests;
  private _pendingContinuations;
  sessionId?: string;
  onclose?: () => void;
  onerror?: (error: Error) => void;
  onmessage?: (message: JSONRPCMessage$2, extra?: MessageExtraInfo$2) => void;
  constructor(options?: RPCServerTransportOptions);
  setProtocolVersion(version: string): void;
  getProtocolVersion(): string | undefined;
  start(): Promise<void>;
  close(): Promise<void>;
  private _makeTimeout;
  private _appendPending;
  private _completePending;
  private _completeRequest;
  private _appendRequest;
  private _completeContinuation;
  private _appendContinuation;
  send(
    message: JSONRPCMessage$2,
    options?: TransportSendOptions$1
  ): Promise<void>;
  /**
   * @internal Called by McpAgent.handleMcpMessage() — not for external use.
   *
   * Wait for the next unmatched send() call that expects a client response or
   * completes a resumed tool call.
   *
   * Used after resolving an elicitation response: the original tool call has
   * already returned the elicitation request to the RPC client, and the resumed
   * tool handler will eventually send the final tool result. That final response
   * has the original tool request id, so there is no active handle() waiter left
   * for id-based routing; this continuation waiter receives it instead.
   */
  _awaitPendingResponse(): Promise<
    JSONRPCMessage$2 | JSONRPCMessage$2[] | undefined
  >;
  handle(
    message: JSONRPCMessage$2 | JSONRPCMessage$2[]
  ): Promise<JSONRPCMessage$2 | JSONRPCMessage$2[] | undefined>;
}
//#endregion
//#region src/mcp/client-connection.d.ts
/**
 * Connection state machine for MCP client connections.
 *
 * State transitions:
 * - Non-OAuth: init() → CONNECTING → DISCOVERING → READY
 * - OAuth: init() → AUTHENTICATING → (callback) → CONNECTING → DISCOVERING → READY
 * - Any state can transition to FAILED on error
 */
declare const MCPConnectionState: {
  /** Waiting for OAuth authorization to complete */ readonly AUTHENTICATING: "authenticating" /** Establishing transport connection to MCP server */;
  readonly CONNECTING: "connecting" /** Transport connection established */;
  readonly CONNECTED: "connected" /** Discovering server capabilities (tools, resources, prompts) */;
  readonly DISCOVERING: "discovering" /** Fully connected and ready to use */;
  readonly READY: "ready" /** Connection failed at some point */;
  readonly FAILED: "failed";
};
/**
 * Connection state type for MCP client connections.
 */
type MCPConnectionState =
  (typeof MCPConnectionState)[keyof typeof MCPConnectionState];
/**
 * Transport options for MCP client connections.
 * Combines transport-specific options with auth provider and type selection.
 */
type MCPTransportOptions = (
  | SSEClientTransportOptions
  | StreamableHTTPClientTransportOptions
  | RPCClientTransportOptions
) & {
  authProvider?: AgentMcpOAuthProvider;
  type?: TransportType;
};
/** Result of discovering server capabilities. */
type MCPDiscoveryResult =
  | {
      success: true;
    }
  | {
      success: false;
      reason: "error" | "stale-session";
      error: string;
    };
/**
 * Handler for server-initiated `elicitation/create` requests.
 * Held in memory only — never persisted — so it must be re-supplied when a
 * connection is recreated (e.g. after Durable Object hibernation).
 */
type MCPElicitationHandler = (
  request: ElicitRequest /** Aborts when the originating MCP call is cancelled or exhausts its total-time budget. */,

  signal?: AbortSignal
) => Promise<ElicitResult>;
type MCPElicitationHandlers = {
  form?: MCPElicitationHandler;
  url?: MCPElicitationHandler;
};
declare class MCPClientConnection {
  url: URL;
  private readonly _info;
  options: {
    transport: MCPTransportOptions;
    client: NonNullable<McpClientOptions>;
    elicitationHandlers?: MCPElicitationHandlers;
    /**
     * Client capabilities persisted from a previous session, advertised
     * until handlers are reconfigured after a hibernation restore. Cleared
     * by {@link configureElicitationHandlers} — reconfigured handlers are
     * the source of truth. Explicit `client.capabilities` win per key.
     */
    capabilitySeed?: ClientCapabilities /** SDK discovery result paired with a resumed Stateless HTTP session. */;
    discoverResult?: DiscoverResult;
  };
  client: Client;
  connectionState: MCPConnectionState;
  connectionError: string | null;
  lastConnectedTransport: BaseTransportType | undefined;
  instructions?: string;
  tools: Tool[];
  private _transport?;
  /**
   * Transport that received the 401 during the initial connect attempt.
   * Kept so finishAuth() runs on the transport that captured the resource
   * metadata URL from the WWW-Authenticate header — a fresh transport would
   * rediscover from defaults and exchange the code at the wrong token
   * endpoint when the authorization server is not at the default location.
   */
  private _pendingAuthTransport?;
  private _restoredListSubscription?;
  prompts: Prompt[];
  resources: Resource[];
  resourceTemplates: ResourceTemplateType[];
  serverCapabilities: ServerCapabilities | undefined;
  /** True when resuming a streamable-http session without cached capabilities */
  private _probingCapabilities;
  /** Tracks in-flight discovery to allow cancellation */
  private _discoveryAbortController;
  private readonly _onObservabilityEvent;
  readonly onObservabilityEvent: Event<MCPObservabilityEvent>;
  private readonly _onListChanged;
  readonly onListChanged: Event<void>;
  /**
   * Whether the connection advertised the elicitation capability. The SDK
   * client refuses to register an `elicitation/create` request handler when
   * the capability was not declared, so handler registration is gated on
   * this.
   */
  private _elicitationEnabled;
  constructor(
    url: URL,
    _info: ConstructorParameters<typeof Client>[0],
    options?: {
      transport: MCPTransportOptions;
      client: NonNullable<McpClientOptions>;
      elicitationHandlers?: MCPElicitationHandlers;
      /**
       * Client capabilities persisted from a previous session, advertised
       * until handlers are reconfigured after a hibernation restore. Cleared
       * by {@link configureElicitationHandlers} — reconfigured handlers are
       * the source of truth. Explicit `client.capabilities` win per key.
       */
      capabilitySeed?: ClientCapabilities /** SDK discovery result paired with a resumed Stateless HTTP session. */;
      discoverResult?: DiscoverResult;
    }
  );
  private createClient;
  /**
   * Configure the handler used for server-initiated elicitation requests.
   *
   * If the connection has not been initialized yet, rebuild the SDK client so
   * handler-driven elicitation capabilities are reflected in the initial
   * handshake. A rebuild (rather than `Client.registerCapabilities`) is
   * required because SDK capability registration is merge-only — it cannot
   * un-advertise a mode when handlers are cleared before connecting. Active
   * connections keep their negotiated capabilities until they reconnect.
   */
  configureElicitationHandlers(handlers?: MCPElicitationHandlers): void;
  /**
   * Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state
   * Sets connection state based on the result and emits observability events
   *
   * @returns Error message if connection failed, undefined otherwise
   */
  init(): Promise<string | undefined>;
  /**
   * Finish OAuth by probing transports based on configured type.
   * - Explicit: finish on that transport
   * - Auto: try streamable-http, then sse on 404/405/Not Implemented
   */
  private finishAuthProbe;
  /**
   * Complete OAuth authorization
   */
  completeAuthorization(
    callback: string | URLSearchParams,
    options?: {
      alreadyAccepted?: boolean;
    }
  ): Promise<void>;
  /**
   * Discover server capabilities and register tools, resources, prompts, and templates.
   * This method does the work but does not manage connection state - that's handled by discover().
   */
  discoverAndRegister(): Promise<void>;
  /**
   * Discover server capabilities with timeout and cancellation support.
   * If called while a previous discovery is in-flight, the previous discovery will be aborted.
   *
   * @param options Optional configuration
   * @param options.timeoutMs Timeout in milliseconds (default: 15000)
   * @returns Result indicating success/failure with optional error message
   */
  discover(options?: { timeoutMs?: number }): Promise<MCPDiscoveryResult>;
  /**
   * Cancel any in-flight discovery operation.
   * Called when closing the connection.
   */
  cancelDiscovery(): void;
  /**
   * Notification handler registration for tools
   * Should only be called if serverCapabilities.tools exists
   */
  registerTools(): Promise<Tool[]>;
  /**
   * Notification handler registration for resources
   * Should only be called if serverCapabilities.resources exists
   */
  registerResources(): Promise<Resource[]>;
  /**
   * Notification handler registration for prompts
   * Should only be called if serverCapabilities.prompts exists
   */
  registerPrompts(): Promise<Prompt[]>;
  registerResourceTemplates(): Promise<ResourceTemplateType[]>;
  private catalogFetchOptions;
  fetchTools(): Promise<
    {
      inputSchema: {
        [x: string]: unknown;
        type: "object";
        properties?:
          | {
              [x: string]:
                | string
                | number
                | boolean
                | {
                    [x: string]:
                      | string
                      | number
                      | boolean
                      | /*elided*/ any
                      | (
                          | string
                          | number
                          | boolean
                          | /*elided*/ any
                          | (
                              | string
                              | number
                              | boolean
                              | /*elided*/ any
                              | (
                                  | string
                                  | number
                                  | boolean
                                  | /*elided*/ any
                                  | (
                                      | string
                                      | number
                                      | boolean
                                      | /*elided*/ any
                                      | (
                                          | string
                                          | number
                                          | boolean
                                          | /*elided*/ any
                                          | (
                                              | string
                                              | number
                                              | boolean
                                              | /*elided*/ any
                                              | (
                                                  | string
                                                  | number
                                                  | boolean
                                                  | /*elided*/ any
                                                  | (
                                                      | string
                                                      | number
                                                      | boolean
                                                      | /*elided*/ any
                                                      | (
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null
                                                        )[]
                                                      | null
                                                    )[]
                                                  | null
                                                )[]
                                              | null
                                            )[]
                                          | null
                                        )[]
                                      | null
                                    )[]
                                  | null
                                )[]
                              | null
                            )[]
                          | null
                        )[]
                      | null;
                  }
                | (
                    | string
                    | number
                    | boolean
                    | {
                        [x: string]:
                          | string
                          | number
                          | boolean
                          | /*elided*/ any
                          | (
                              | string
                              | number
                              | boolean
                              | /*elided*/ any
                              | (
                                  | string
                                  | number
                                  | boolean
                                  | /*elided*/ any
                                  | (
                                      | string
                                      | number
                                      | boolean
                                      | /*elided*/ any
                                      | (
                                          | string
                                          | number
                                          | boolean
                                          | /*elided*/ any
                                          | (
                                              | string
                                              | number
                                              | boolean
                                              | /*elided*/ any
                                              | (
                                                  | string
                                                  | number
                                                  | boolean
                                                  | /*elided*/ any
                                                  | (
                                                      | string
                                                      | number
                                                      | boolean
                                                      | /*elided*/ any
                                                      | (
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null
                                                        )[]
                                                      | null
                                                    )[]
                                                  | null
                                                )[]
                                              | null
                                            )[]
                                          | null
                                        )[]
                                      | null
                                    )[]
                                  | null
                                )[]
                              | null
                            )[]
                          | null;
                      }
                    | (
                        | string
                        | number
                        | boolean
                        | {
                            [x: string]:
                              | string
                              | number
                              | boolean
                              | /*elided*/ any
                              | (
                                  | string
                                  | number
                                  | boolean
                                  | /*elided*/ any
                                  | (
                                      | string
                                      | number
                                      | boolean
                                      | /*elided*/ any
                                      | (
                                          | string
                                          | number
                                          | boolean
                                          | /*elided*/ any
                                          | (
                                              | string
                                              | number
                                              | boolean
                                              | /*elided*/ any
                                              | (
                                                  | string
                                                  | number
                                                  | boolean
                                                  | /*elided*/ any
                                                  | (
                                                      | string
                                                      | number
                                                      | boolean
                                                      | /*elided*/ any
                                                      | (
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null
                                                        )[]
                                                      | null
                                                    )[]
                                                  | null
                                                )[]
                                              | null
                                            )[]
                                          | null
                                        )[]
                                      | null
                                    )[]
                                  | null
                                )[]
                              | null;
                          }
                        | (
                            | string
                            | number
                            | boolean
                            | {
                                [x: string]:
                                  | string
                                  | number
                                  | boolean
                                  | /*elided*/ any
                                  | (
                                      | string
                                      | number
                                      | boolean
                                      | /*elided*/ any
                                      | (
                                          | string
                                          | number
                                          | boolean
                                          | /*elided*/ any
                                          | (
                                              | string
                                              | number
                                              | boolean
                                              | /*elided*/ any
                                              | (
                                                  | string
                                                  | number
                                                  | boolean
                                                  | /*elided*/ any
                                                  | (
                                                      | string
                                                      | number
                                                      | boolean
                                                      | /*elided*/ any
                                                      | (
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null
                                                        )[]
                                                      | null
                                                    )[]
                                                  | null
                                                )[]
                                              | null
                                            )[]
                                          | null
                                        )[]
                                      | null
                                    )[]
                                  | null;
                              }
                            | (
                                | string
                                | number
                                | boolean
                                | {
                                    [x: string]:
                                      | string
                                      | number
                                      | boolean
                                      | /*elided*/ any
                                      | (
                                          | string
                                          | number
                                          | boolean
                                          | /*elided*/ any
                                          | (
                                              | string
                                              | number
                                              | boolean
                                              | /*elided*/ any
                                              | (
                                                  | string
                                                  | number
                                                  | boolean
                                                  | /*elided*/ any
                                                  | (
                                                      | string
                                                      | number
                                                      | boolean
                                                      | /*elided*/ any
                                                      | (
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null
                                                        )[]
                                                      | null
                                                    )[]
                                                  | null
                                                )[]
                                              | null
                                            )[]
                                          | null
                                        )[]
                                      | null;
                                  }
                                | (
                                    | string
                                    | number
                                    | boolean
                                    | {
                                        [x: string]:
                                          | string
                                          | number
                                          | boolean
                                          | /*elided*/ any
                                          | (
                                              | string
                                              | number
                                              | boolean
                                              | /*elided*/ any
                                              | (
                                                  | string
                                                  | number
                                                  | boolean
                                                  | /*elided*/ any
                                                  | (
                                                      | string
                                                      | number
                                                      | boolean
                                                      | /*elided*/ any
                                                      | (
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null
                                                        )[]
                                                      | null
                                                    )[]
                                                  | null
                                                )[]
                                              | null
                                            )[]
                                          | null;
                                      }
                                    | (
                                        | string
                                        | number
                                        | boolean
                                        | {
                                            [x: string]:
                                              | string
                                              | number
                                              | boolean
                                              | /*elided*/ any
                                              | (
                                                  | string
                                                  | number
                                                  | boolean
                                                  | /*elided*/ any
                                                  | (
                                                      | string
                                                      | number
                                                      | boolean
                                                      | /*elided*/ any
                                                      | (
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null
                                                        )[]
                                                      | null
                                                    )[]
                                                  | null
                                                )[]
                                              | null;
                                          }
                                        | (
                                            | string
                                            | number
                                            | boolean
                                            | {
                                                [x: string]:
                                                  | string
                                                  | number
                                                  | boolean
                                                  | /*elided*/ any
                                                  | (
                                                      | string
                                                      | number
                                                      | boolean
                                                      | /*elided*/ any
                                                      | (
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null
                                                        )[]
                                                      | null
                                                    )[]
                                                  | null;
                                              }
                                            | (
                                                | string
                                                | number
                                                | boolean
                                                | {
                                                    [x: string]:
                                                      | string
                                                      | number
                                                      | boolean
                                                      | /*elided*/ any
                                                      | (
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null
                                                        )[]
                                                      | null;
                                                  }
                                                | (
                                                    | string
                                                    | number
                                                    | boolean
                                                    | {
                                                        [x: string]:
                                                          | string
                                                          | number
                                                          | boolean
                                                          | /*elided*/ any
                                                          | (
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null
                                                            )[]
                                                          | null;
                                                      }
                                                    | (
                                                        | string
                                                        | number
                                                        | boolean
                                                        | {
                                                            [x: string]:
                                                              | string
                                                              | number
                                                              | boolean
                                                              | /*elided*/ any
                                                              | (
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null
                                                                )[]
                                                              | null;
                                                          }
                                                        | (
                                                            | string
                                                            | number
                                                            | boolean
                                                            | {
                                                                [x: string]:
                                                                  | string
                                                                  | number
                                                                  | boolean
                                                                  | /*elided*/ any
                                                                  | /*elided*/ any
                                                                  | null;
                                                              }
                                                            | /*elided*/ any
                                                            | null
                                                          )[]
                                                        | null
                                                      )[]
                                                    | null
                                                  )[]
                                                | null
                                              )[]
                                            | null
                                          )[]
                                        | null
                                      )[]
                                    | null
                                  )[]
                                | null
                              )[]
                            | null
                          )[]
                        | null
                      )[]
                    | null
                  )[]
                | null;
            }
          | undefined;
        required?: string[] | undefined;
      };
      name: string;
      description?: string | undefined;
      outputSchema?:
        | {
            [x: string]: unknown;
            $schema?: string | undefined;
          }
        | undefined;
      annotations?:
        | {
            title?: string | undefined;
            readOnlyHint?: boolean | undefined;
            destructiveHint?: boolean | undefined;
            idempotentHint?: boolean | undefined;
            openWorldHint?: boolean | undefined;
          }
        | undefined;
      execution?:
        | {
            taskSupport?: "optional" | "required" | "forbidden" | undefined;
          }
        | undefined;
      _meta?:
        | {
            [x: string]: unknown;
          }
        | undefined;
      icons?:
        | {
            src: string;
            mimeType?: string | undefined;
            sizes?: string[] | undefined;
            theme?: "light" | "dark" | undefined;
          }[]
        | undefined;
      title?: string | undefined;
    }[]
  >;
  fetchResources(): Promise<
    {
      uri: string;
      name: string;
      description?: string | undefined;
      mimeType?: string | undefined;
      size?: number | undefined;
      annotations?:
        | {
            audience?: ("user" | "assistant")[] | undefined;
            priority?: number | undefined;
            lastModified?: string | undefined;
          }
        | undefined;
      _meta?:
        | {
            [x: string]: unknown;
          }
        | undefined;
      icons?:
        | {
            src: string;
            mimeType?: string | undefined;
            sizes?: string[] | undefined;
            theme?: "light" | "dark" | undefined;
          }[]
        | undefined;
      title?: string | undefined;
    }[]
  >;
  fetchPrompts(): Promise<
    {
      name: string;
      description?: string | undefined;
      arguments?:
        | {
            name: string;
            description?: string | undefined;
            required?: boolean | undefined;
          }[]
        | undefined;
      _meta?:
        | {
            [x: string]: unknown;
          }
        | undefined;
      icons?:
        | {
            src: string;
            mimeType?: string | undefined;
            sizes?: string[] | undefined;
            theme?: "light" | "dark" | undefined;
          }[]
        | undefined;
      title?: string | undefined;
    }[]
  >;
  fetchResourceTemplates(): Promise<
    {
      uriTemplate: string;
      name: string;
      description?: string | undefined;
      mimeType?: string | undefined;
      annotations?:
        | {
            audience?: ("user" | "assistant")[] | undefined;
            priority?: number | undefined;
            lastModified?: string | undefined;
          }
        | undefined;
      _meta?:
        | {
            [x: string]: unknown;
          }
        | undefined;
      icons?:
        | {
            src: string;
            mimeType?: string | undefined;
            sizes?: string[] | undefined;
            theme?: "light" | "dark" | undefined;
          }[]
        | undefined;
      title?: string | undefined;
    }[]
  >;
  /**
   * Handle elicitation request from server.
   *
   * Delegates to the `elicitationHandlers` connection option when provided.
   *
   * @deprecated Overriding or instance-patching this method directly is
   * deprecated — pass the `elicitationHandlers` connection option instead.
   */
  handleElicitationRequest(
    request: ElicitRequest,
    signal?: AbortSignal
  ): Promise<ElicitResult>;
  private isResumedStreamableHttpSession;
  get sessionId(): string | undefined;
  /** @internal Clear a restored session before reconnecting. */
  clearResumedSession(): void;
  get protocolVersion(): string | undefined;
  get discoverResult(): DiscoverResult | undefined;
  private openRestoredListSubscription;
  private getTransportName;
  close(): Promise<void>;
  /**
   * Get the transport for the client
   * @param transportType - The transport type to get
   * @returns The transport for the client
   */
  getTransport(
    transportType: BaseTransportType
  ): StreamableHTTPClientTransport | SSEClientTransport | RPCClientTransport;
  private tryConnect;
  private _capabilityErrorHandler;
}
//#endregion
//#region src/mcp/client-storage.d.ts
/**
 * Represents a row in the cf_agents_mcp_servers table.
 */
type MCPServerRow = {
  id: string;
  name: string;
  server_url: string;
  client_id: string | null;
  auth_url: string | null;
  callback_url: string;
  server_options: string | null;
};
/** Explicitly supported durable subset of MCP SDK client options. */
type PersistedMcpClientOptions = Pick<
  McpClientOptions,
  | "capabilities"
  | "supportedProtocolVersions"
  | "enforceStrictCapabilities"
  | "debouncedNotificationMethods"
  | "versionNegotiation"
  | "inputRequired"
  | "listMaxPages"
  | "cachePartition"
  | "defaultCacheTtlMs"
>;
type PersistedMcpTransportOptions = {
  type?: TransportType;
  headers?: HeadersInit;
  requestInit?: RequestInit;
  reconnectionOptions?: StreamableHTTPReconnectionOptions;
  skipIssuerMetadataValidation?: boolean;
  onInsufficientScope?: "reauthorize" | "throw";
  maxStepUpRetries?: number;
  sessionId?: string;
  protocolVersion?: string;
};
type PersistedMcpServerOptions = {
  client?: PersistedMcpClientOptions;
  transport?: PersistedMcpTransportOptions;
  discoverResult?: DiscoverResult;
  retry?: RetryOptions /** Durable Object binding used to restore an RPC MCP connection. */;
  bindingName?: string /** Application props passed back to a restored RPC MCP connection. */;
  props?: Record<
    string,
    unknown
  > /** One-wake capability seed; handler functions remain memory-only. */;
  capabilities?: ClientCapabilities;
};
//#endregion
//#region src/mcp/client.d.ts
type MCPAITool = {
  description?: string;
  title?: string;
  execute: (
    args: Record<string, unknown>,
    options?: unknown
  ) => Promise<unknown>;
  inputSchema: z.ZodType;
  outputSchema?: z.ZodType;
};
/**
 * Structural tool set returned by {@link MCPClientManager.getAITools}.
 * Compatible with the AI SDK without importing its types into the core
 * `agents` declaration graph.
 */
type MCPAIToolSet = Record<string, MCPAITool>;
/** Maximum length of a normalized MCP server id. */
declare const MCP_SERVER_ID_MAX_LENGTH = 64;
/**
 * Normalize a caller-supplied MCP server id into a stable, storage- and
 * tool-name-safe form.
 *
 * The id is surfaced in several places where the character set matters:
 *  - as the primary key in the `cf_agents_mcp_servers` SQLite table
 *  - embedded in AI SDK tool names as `` `tool_${id.replace(/-/g, "")}_${tool}` ``
 *    (tool names must match `/^[A-Za-z0-9_]+$/`)
 *  - as a key on the `mcpConnections` map and OAuth provider storage
 *
 * Rules:
 *  1. Lowercase.
 *  2. Replace any run of disallowed characters with a single `-`.
 *  3. Collapse repeated `-` and trim leading/trailing `-`/`_`.
 *  4. Prefix with `id-` if the result is empty or doesn't start with a letter.
 *  5. Truncate to {@link MCP_SERVER_ID_MAX_LENGTH} characters.
 *
 * @example
 * normalizeServerId("my-supplied-id");  // "my-supplied-id"
 * normalizeServerId("GitHub MCP!");     // "github-mcp"
 * normalizeServerId("42-things");       // "id-42-things"
 */
declare function normalizeServerId(input: string): string;
type MCPServerOptions = PersistedMcpServerOptions;
/**
 * Result of an OAuth callback request
 */
type MCPOAuthCallbackResult =
  | {
      serverId: string;
      authSuccess: true;
      authError?: undefined;
    }
  | {
      serverId?: string;
      authSuccess: false;
      authError: string;
    };
/**
 * Options for registering an MCP server
 */
type RegisterServerOptions = {
  url: string;
  name: string;
  callbackUrl?: string;
  client?: McpClientOptions;
  transport?: MCPTransportOptions;
  authUrl?: string;
  clientId?: string /** Retry options for connection and reconnection attempts */;
  retry?: RetryOptions;
};
/**
 * Result of attempting to connect to an MCP server.
 * Discriminated union ensures error is present only on failure.
 */
type MCPConnectionResult =
  | {
      state: typeof MCPConnectionState.FAILED;
      error: string;
    }
  | {
      state: typeof MCPConnectionState.AUTHENTICATING;
      authUrl: string;
      clientId?: string;
    }
  | {
      state: typeof MCPConnectionState.CONNECTED;
    };
/**
 * Result of discovering server capabilities.
 * success indicates whether discovery completed successfully.
 * state is the current connection state at time of return.
 * error is present when success is false.
 */
type MCPDiscoverResult = {
  success: boolean;
  state: MCPConnectionState;
  error?: string;
};
type MCPClientOAuthCallbackConfig = {
  successRedirect?: string;
  errorRedirect?: string;
  customHandler?: (result: MCPClientOAuthResult) => Response;
};
type MCPClientOAuthResult =
  | {
      serverId: string;
      authSuccess: true;
      authError?: undefined;
    }
  | {
      serverId?: string;
      authSuccess: false /** May contain untrusted content from external OAuth providers. Escape appropriately for your output context. */;
      authError: string;
    };
type MCPClientElicitationHandler = (
  request: ElicitRequest,
  serverId: string /** Aborts when the originating MCP operation is cancelled. */,

  signal?: AbortSignal
) => Promise<ElicitResult>;
type MCPClientElicitationHandlers = {
  form?: MCPClientElicitationHandler;
  url?: MCPClientElicitationHandler;
};
type MCPClientManagerOptions = {
  storage: DurableObjectStorage;
  createAuthProvider?: (callbackUrl: string) => AgentMcpOAuthProvider;
};
/**
 * Filter options for scoping tools, prompts, resources, and resource templates
 * to a subset of connected MCP servers. All specified criteria are AND'd together.
 */
type MCPServerFilter = {
  /** Include only connections matching this server ID (or IDs). */ serverId?:
    | string
    | string[] /** Include only connections whose stored name matches (or is in) this value. */;
  serverName?:
    | string
    | string[] /** Include only connections currently in this state (or states). */;
  state?: MCPConnectionState | MCPConnectionState[];
};
/**
 * Utility class that aggregates multiple MCP clients into one
 */
declare class MCPClientManager {
  private _name;
  private _version;
  mcpConnections: Record<string, MCPClientConnection>;
  /** Cache only the current catalog so old schema graphs are not retained. */
  private readonly _aiToolSchemas;
  private _didWarnAboutUnstableGetAITools;
  private _oauthCallbackConfig?;
  private _connectionDisposables;
  private _storage;
  private _createAuthProviderFn?;
  private _isRestored;
  private _pendingConnections;
  private _elicitationHandlers?;
  /** @internal Protected for testing purposes. */
  protected readonly _onObservabilityEvent: Emitter<MCPObservabilityEvent>;
  readonly onObservabilityEvent: Event<MCPObservabilityEvent>;
  private readonly _onServerStateChanged;
  /**
   * Event that fires whenever any MCP server state changes (registered, connected, removed, etc.)
   * This is useful for broadcasting server state to clients.
   */
  readonly onServerStateChanged: Event<void>;
  /**
   * @param _name Name of the MCP client
   * @param _version Version of the MCP Client
   * @param options Storage adapter for persisting MCP server state
   */
  constructor(
    _name: string,
    _version: string,
    options: MCPClientManagerOptions
  );
  /**
   * Scope the manager-level elicitation handler to a single connection.
   * Returns undefined when no handler is configured so the connection keeps
   * its default throwing behavior.
   */
  private scopedElicitationHandlers;
  private sql;
  private saveServerToStorage;
  private removeServerFromStorage;
  /**
   * Rename a server's id, in-place, across every place the id is used as a
   * key. Used to JIT-migrate servers that were originally registered under an
   * auto-generated nanoid to a caller-supplied stable id (see
   * `Agent.addMcpServer`'s `{ id }` option).
   *
   * Migrates:
   *  - the `cf_agents_mcp_servers` row (primary key)
   *  - the in-memory `mcpConnections` map key
   *  - the connection disposables map key
   *  - the attached `authProvider.serverId`, if any
   *  - OAuth-related storage keys under `/{clientName}/{oldId}/...`
   *
   * Safe to call when no OAuth keys exist (RPC / bearer-token HTTP servers).
   * If `oldId === newId` this is a no-op. If a row already exists under
   * `newId`, throws — the caller is expected to have verified uniqueness.
   *
   * @internal Exposed for `Agent.addMcpServer` JIT-migration.
   */
  migrateServerId(
    oldId: string,
    newId: string,
    clientName: string
  ): Promise<void>;
  private _renameInMemoryConnection;
  private getServersFromStorage;
  private filterConnections;
  /**
   * Get the parsed server_options for a stored server, if any.
   */
  private getStoredServerOptions;
  /**
   * Clear the capabilities persisted on a stored server row. Called once a
   * seeded connection's handshake completes (see `createConnection`): the
   * stamp is valid for one successful restore — sessions that configure
   * handlers re-stamp every row, so a deploy that stops configuring them
   * stops advertising stale modes after its first connected wake instead of
   * forever, while wakes that never handshake don't burn the stamp.
   */
  private clearStoredCapabilities;
  /**
   * Get the retry options for a server from stored server_options
   */
  private getServerRetryOptions;
  private clearServerAuthUrl;
  private updateStoredSession;
  private failConnection;
  private isAuthAcceptedConnection;
  private oauthCallbackSuccess;
  private runWithCodeVerifierState;
  private hasRedeemableOAuthState;
  private ignoreUnverifiedCallback;
  private consumeStaleOAuthState;
  private completeAuthorizationAndCleanupVerifier;
  /**
   * Create an auth provider for a server
   * @internal
   */
  private createAuthProvider;
  /**
   * Get saved RPC servers from storage (servers with rpc:// URLs).
   * These are restored separately by the Agent class since they need env bindings.
   */
  getRpcServersFromStorage(): MCPServerRow[];
  /**
   * Save an RPC server to storage for hibernation recovery.
   * The bindingName is stored in server_options so the Agent can look up
   * the namespace from env during restore.
   */
  saveRpcServerToStorage(
    id: string,
    name: string,
    normalizedName: string,
    bindingName: string,
    props?: Record<string, unknown>
  ): void;
  /**
   * Restore MCP server connections from storage
   * This method is called on Agent initialization to restore previously connected servers.
   * RPC servers (rpc:// URLs) are skipped here -- they are restored by the Agent class
   * which has access to env bindings.
   *
   * @param clientName Name to use for OAuth client (typically the agent instance name)
   */
  restoreConnectionsFromStorage(clientName: string): Promise<void>;
  /**
   * Track a pending connection promise for a server.
   * The promise is removed from the map when it settles.
   */
  private _trackConnection;
  /**
   * Wait for all in-flight connection and discovery operations to settle.
   * This is useful when you need MCP tools to be available before proceeding,
   * e.g. before calling getAITools() after the agent wakes from hibernation.
   *
   * Returns once every pending connection has either connected and discovered,
   * failed, or timed out. Never rejects.
   *
   * @param options.timeout - Maximum time in milliseconds to wait.
   *   `0` returns immediately without waiting.
   *   `undefined` (default) waits indefinitely.
   */
  waitForConnections(options?: { timeout?: number }): Promise<void>;
  private _connectWithRetry;
  /**
   * Internal method to restore a single server connection and discovery
   */
  private _restoreServer;
  /**
   * Connect to and register an MCP server
   *
   * @deprecated This method is maintained for backward compatibility.
   * For new code, use registerServer() and connectToServer() separately.
   *
   * @param url Server URL
   * @param options Connection options
   * @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)
   */
  connect(
    url: string,
    options?: {
      reconnect?: {
        id: string;
        oauthClientId?: string;
        oauthCode?: string;
      };
      transport?: MCPTransportOptions;
      client?: McpClientOptions;
    }
  ): Promise<{
    id: string;
    authUrl?: string;
    clientId?: string;
  }>;
  /**
   * Create an in-memory connection object and set up observability
   * Does NOT save to storage - use registerServer() for that
   * @returns The connection object (existing or newly created)
   */
  private createConnection;
  /**
   * Register an MCP server connection without connecting
   * Creates the connection object, sets up observability, and saves to storage
   *
   * @param id Server ID
   * @param options Registration options including URL, name, callback URL, and connection config
   * @returns Server ID
   */
  registerServer(id: string, options: RegisterServerOptions): Promise<string>;
  /** Persist and emit an OAuth continuation produced by connect or discovery. */
  private persistAuthContinuation;
  /**
   * Connect to an already registered MCP server and initialize the connection.
   *
   * For OAuth servers, returns `{ state: "authenticating", authUrl, clientId? }`.
   * The user must complete the OAuth flow via the authUrl, which triggers a
   * callback handled by `handleCallbackRequest()`.
   *
   * For non-OAuth servers, establishes the transport connection and returns
   * `{ state: "connected" }`. Call `discoverIfConnected()` afterwards to
   * discover capabilities and transition to "ready" state.
   *
   * @param id Server ID (must be registered first via registerServer())
   * @returns Connection result with current state and OAuth info (if applicable)
   */
  connectToServer(id: string): Promise<MCPConnectionResult>;
  private extractServerIdFromState;
  isCallbackRequest(req: Request): boolean;
  private validateCallbackRequest;
  handleCallbackRequest(req: Request): Promise<MCPOAuthCallbackResult>;
  /**
   * Discover server capabilities if connection is in CONNECTED or READY state.
   * Transitions to DISCOVERING then READY (or CONNECTED on error).
   * Can be called to refresh server capabilities (e.g., from a UI refresh button).
   *
   * If called while a previous discovery is in-flight for the same server,
   * the previous discovery will be aborted.
   *
   * @param serverId The server ID to discover
   * @param options Optional configuration
   * @param options.timeoutMs Timeout in milliseconds (default: 30000)
   * @returns Result with current state and optional error, or undefined if connection not found
   */
  discoverIfConnected(
    serverId: string,
    options?: {
      timeoutMs?: number;
    }
  ): Promise<MCPDiscoverResult | undefined>;
  private _toDiscoverResult;
  private _recoverStaleSession;
  /**
   * Establish connection in the background after OAuth completion.
   * This method connects to the server and discovers its capabilities.
   * The connection is automatically tracked so that `waitForConnections()`
   * will include it.
   * @param serverId The server ID to establish connection for
   */
  establishConnection(serverId: string): Promise<void>;
  private _doEstablishConnection;
  /**
   * Configure OAuth callback handling
   * @param config OAuth callback configuration
   */
  configureOAuthCallback(config: MCPClientOAuthCallbackConfig): void;
  /**
   * Configure handling for server-initiated `elicitation/create` requests.
   *
   * The handler is held in memory only and applied to every MCP connection
   * created or restored by this manager. Call this before registering
   * connections when you want the initial MCP handshake to advertise
   * handler-driven form- and url-mode elicitation. Existing active connections
   * keep their negotiated capabilities until they reconnect.
   *
   * The advertised modes are persisted with each stored server, so
   * connections restored after hibernation re-advertise them at the handshake
   * even when this is called later in the wake-up (e.g. from onStart) — the
   * handlers attach to the live connections as soon as this runs.
   *
   * Pass undefined to clear the handler.
   *
   * @param handlers Elicitation handlers keyed by mode, each scoped with the server id that sent the request
   */
  configureElicitationHandlers(handlers?: MCPClientElicitationHandlers): void;
  /** Client capabilities advertised from the currently configured handlers. */
  private advertisedHandlerCapabilities;
  /**
   * Record the handler-derived capabilities on every stored server row so a
   * restore after hibernation re-advertises them before the handlers
   * themselves are reconfigured.
   */
  private persistAdvertisedCapabilities;
  /**
   * Get the current OAuth callback configuration
   * @returns The current OAuth callback configuration
   */
  getOAuthCallbackConfig(): MCPClientOAuthCallbackConfig | undefined;
  /**
   * @param filter - Optional filter to scope results to specific servers
   * @returns namespaced list of tools
   */
  listTools(filter?: MCPServerFilter): NamespacedData["tools"];
  /**
   * Convert connected MCP tools for the AI SDK. Converted schemas are reused
   * while a live connection retains the same catalog array and schema-source
   * identities; tool records and execute closures are rebuilt on every call.
   *
   * @param filter - Optional filter to scope results to specific servers
   * @returns a set of tools that you can use with the AI SDK
   */
  getAITools(filter?: MCPServerFilter): MCPAIToolSet;
  /**
   * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
   * @param filter - Optional filter to scope results to specific servers
   * @returns a set of tools that you can use with the AI SDK
   */
  unstable_getAITools(filter?: MCPServerFilter): MCPAIToolSet;
  /**
   * Closes all active in-memory connections to MCP servers.
   *
   * Note: This only closes the transport connections - it does NOT remove
   * servers from storage. Servers will still be listed and their callback
   * URLs will still match incoming OAuth requests.
   *
   * Use removeServer() instead if you want to fully clean up a server
   * (closes connection AND removes from storage).
   */
  private cleanupClosedConnection;
  closeAllConnections(): Promise<void>;
  /**
   * Closes a connection to an MCP server
   * @param id The id of the connection to close
   */
  closeConnection(id: string): Promise<void>;
  /**
   * Remove an MCP server - closes connection if active and removes from storage.
   */
  removeServer(serverId: string): Promise<void>;
  /**
   * List all MCP servers from storage
   */
  listServers(): MCPServerRow[];
  /**
   * Dispose the manager and all resources.
   */
  dispose(): Promise<void>;
  /**
   * @param filter - Optional filter to scope results to specific servers
   * @returns namespaced list of prompts
   */
  listPrompts(filter?: MCPServerFilter): NamespacedData["prompts"];
  /**
   * @param filter - Optional filter to scope results to specific servers
   * @returns namespaced list of resources
   */
  listResources(filter?: MCPServerFilter): NamespacedData["resources"];
  /**
   * @param filter - Optional filter to scope results to specific servers
   * @returns namespaced list of resource templates
   */
  listResourceTemplates(
    filter?: MCPServerFilter
  ): NamespacedData["resourceTemplates"];
  /**
   * Namespaced version of callTool
   */
  callTool(
    params: CallToolRequest["params"] & {
      serverId: string;
    },
    options?: CallToolRequestOptions
  ): ReturnType<Client["callTool"]>;
  /**
   * @deprecated Prefer the v2 request-options overload. Explicit legacy result
   * schemas remain honored through the v2 SDK request funnel.
   */
  callTool(
    params: CallToolRequest["params"] & {
      serverId: string;
    },
    resultSchema: LegacyCallToolResultSchema,
    options?: CallToolRequestOptions
  ): ReturnType<Client["callTool"]>;
  /**
   * Namespaced version of readResource
   */
  readResource(
    params: ReadResourceRequest["params"] & {
      serverId: string;
    },
    options?: CacheableRequestOptions
  ): Promise<{
    [x: string]: unknown;
    contents: (
      | {
          uri: string;
          text: string;
          mimeType?: string | undefined;
          _meta?:
            | {
                [x: string]: unknown;
              }
            | undefined;
        }
      | {
          uri: string;
          blob: string;
          mimeType?: string | undefined;
          _meta?:
            | {
                [x: string]: unknown;
              }
            | undefined;
        }
    )[];
    _meta?:
      | {
          [x: string]: unknown;
          "io.modelcontextprotocol/serverInfo"?:
            | {
                version: string;
                name: string;
                websiteUrl?: string | undefined;
                description?: string | undefined;
                icons?:
                  | {
                      src: string;
                      mimeType?: string | undefined;
                      sizes?: string[] | undefined;
                      theme?: "light" | "dark" | undefined;
                    }[]
                  | undefined;
                title?: string | undefined;
              }
            | undefined;
        }
      | undefined;
  }>;
  /**
   * Namespaced version of getPrompt
   */
  getPrompt(
    params: GetPromptRequest["params"] & {
      serverId: string;
    },
    options?: RequestOptions
  ): Promise<{
    [x: string]: unknown;
    messages: {
      role: "user" | "assistant";
      content:
        | {
            type: "text";
            text: string;
            annotations?:
              | {
                  audience?: ("user" | "assistant")[] | undefined;
                  priority?: number | undefined;
                  lastModified?: string | undefined;
                }
              | undefined;
            _meta?:
              | {
                  [x: string]: unknown;
                }
              | undefined;
          }
        | {
            type: "image";
            data: string;
            mimeType: string;
            annotations?:
              | {
                  audience?: ("user" | "assistant")[] | undefined;
                  priority?: number | undefined;
                  lastModified?: string | undefined;
                }
              | undefined;
            _meta?:
              | {
                  [x: string]: unknown;
                }
              | undefined;
          }
        | {
            type: "audio";
            data: string;
            mimeType: string;
            annotations?:
              | {
                  audience?: ("user" | "assistant")[] | undefined;
                  priority?: number | undefined;
                  lastModified?: string | undefined;
                }
              | undefined;
            _meta?:
              | {
                  [x: string]: unknown;
                }
              | undefined;
          }
        | {
            uri: string;
            name: string;
            type: "resource_link";
            description?: string | undefined;
            mimeType?: string | undefined;
            size?: number | undefined;
            annotations?:
              | {
                  audience?: ("user" | "assistant")[] | undefined;
                  priority?: number | undefined;
                  lastModified?: string | undefined;
                }
              | undefined;
            _meta?:
              | {
                  [x: string]: unknown;
                }
              | undefined;
            icons?:
              | {
                  src: string;
                  mimeType?: string | undefined;
                  sizes?: string[] | undefined;
                  theme?: "light" | "dark" | undefined;
                }[]
              | undefined;
            title?: string | undefined;
          }
        | {
            type: "resource";
            resource:
              | {
                  uri: string;
                  text: string;
                  mimeType?: string | undefined;
                  _meta?:
                    | {
                        [x: string]: unknown;
                      }
                    | undefined;
                }
              | {
                  uri: string;
                  blob: string;
                  mimeType?: string | undefined;
                  _meta?:
                    | {
                        [x: string]: unknown;
                      }
                    | undefined;
                };
            annotations?:
              | {
                  audience?: ("user" | "assistant")[] | undefined;
                  priority?: number | undefined;
                  lastModified?: string | undefined;
                }
              | undefined;
            _meta?:
              | {
                  [x: string]: unknown;
                }
              | undefined;
          };
    }[];
    _meta?:
      | {
          [x: string]: unknown;
          "io.modelcontextprotocol/serverInfo"?:
            | {
                version: string;
                name: string;
                websiteUrl?: string | undefined;
                description?: string | undefined;
                icons?:
                  | {
                      src: string;
                      mimeType?: string | undefined;
                      sizes?: string[] | undefined;
                      theme?: "light" | "dark" | undefined;
                    }[]
                  | undefined;
                title?: string | undefined;
              }
            | undefined;
        }
      | undefined;
    description?: string | undefined;
  }>;
}
type NamespacedData = {
  tools: (Tool & {
    serverId: string;
  })[];
  prompts: (Prompt & {
    serverId: string;
  })[];
  resources: (Resource & {
    serverId: string;
  })[];
  resourceTemplates: (ResourceTemplateType & {
    serverId: string;
  })[];
};
declare function getNamespacedData<T extends keyof NamespacedData>(
  mcpClients: Record<string, MCPClientConnection>,
  type: T
): NamespacedData[T];
//#endregion
//#region src/index.d.ts
/**
 * Structural type for Cloudflare's `send_email` binding.
 * Accepts both raw MIME messages and structured builder objects.
 */
type EmailSendBinding = {
  send(
    message:
      | EmailMessage
      | {
          from:
            | string
            | {
                email: string;
                name?: string;
              };
          to: string | string[];
          subject: string;
          replyTo?:
            | string
            | {
                email: string;
                name?: string;
              };
          cc?: string | string[];
          bcc?: string | string[];
          headers?: Record<string, string>;
          text?: string;
          html?: string;
        }
  ): Promise<EmailSendResult>;
};
/**
 * Options for Agent.sendEmail()
 */
type SendEmailOptions = {
  binding: EmailSendBinding;
  to: string | string[];
  from:
    | string
    | {
        email: string;
        name?: string;
      };
  subject: string;
  text?: string;
  html?: string;
  replyTo?:
    | string
    | {
        email: string;
        name?: string;
      };
  cc?: string | string[];
  bcc?: string | string[];
  inReplyTo?: string;
  headers?: Record<string, string>;
  secret?: string;
};
/**
 * RPC request message from client
 */
type RPCRequest = {
  type: "rpc";
  id: string;
  method: string;
  args: unknown[];
};
/**
 * State update message from client
 */
type StateUpdateMessage = {
  type: MessageType.CF_AGENT_STATE;
  state: unknown;
};
/**
 * RPC response message to client
 */
type RPCResponse = {
  type: MessageType.RPC;
  id: string;
} & (
  | {
      success: true;
      result: unknown;
      done?: false;
    }
  | {
      success: true;
      result: unknown;
      done: true;
    }
  | {
      success: false;
      error: string;
    }
);
/**
 * Metadata for a callable method
 */
type CallableMetadata = {
  /** Optional description of what the method does */ description?: string /** Whether the method supports streaming responses */;
  streaming?: boolean;
};
/**
 * Error class for SQL execution failures, containing the query that failed
 */
declare class SqlError extends Error {
  /** The SQL query that failed */
  readonly query: string;
  constructor(query: string, cause: unknown);
}
type SubAgentConnectionMeta = {
  id: string;
  uri: string | null;
  tags: string[];
  state: unknown;
  requestHeaders?: [string, string][];
};
type SubAgentConnectionBridgeLike = {
  send(message: string | ArrayBuffer | ArrayBufferView): void;
  close(code?: number, reason?: string): void;
  setState(state: unknown): unknown;
  broadcast(
    ownerPath: ReadonlyArray<{
      className: string;
      name: string;
    }>,
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): void;
};
declare class SubAgentConnectionBridge
  extends RpcTarget
  implements SubAgentConnectionBridgeLike
{
  #private;
  constructor(
    connection: Connection,
    broadcast?: (
      ownerPath: ReadonlyArray<{
        className: string;
        name: string;
      }>,
      message: string | ArrayBuffer | ArrayBufferView,
      without?: string[]
    ) => void
  );
  send(message: string | ArrayBuffer | ArrayBufferView): void;
  close(code?: number, reason?: string): void;
  setState(state: unknown): unknown;
  broadcast(
    ownerPath: ReadonlyArray<{
      className: string;
      name: string;
    }>,
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): void;
}
/**
 * Constructor type for a sub-agent class.
 * Used by {@link Agent.subAgent} to reference the child class
 * via `ctx.exports`.
 *
 * The class name (`cls.name`) must match the export name in the
 * worker entry point — re-exports under a different name
 * (e.g. `export { Foo as Bar }`) are not supported.
 */
type SubAgentClass<T extends Agent = Agent> = {
  new (ctx: DurableObjectState, env: never): T;
};
/**
 * Wraps `T` in a `Promise` unless it already is one.
 */
type Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;
/**
 * A typed RPC stub for a sub-agent. Exposes all public instance methods
 * as callable RPC methods with Promise-wrapped return types.
 *
 * Methods inherited from `Agent` / `Server` / `DurableObject` internals
 * are excluded — only user-defined methods on the subclass are exposed.
 */
type SubAgentStub<T extends Agent> = {
  [K in keyof T as K extends keyof Agent
    ? never
    : T[K] extends (...args: never[]) => unknown
      ? K
      : never]: T[K] extends (...args: infer A) => infer R
    ? (...args: A) => Promisify<R>
    : never;
};
/**
 * Decorator that marks a method as callable by clients
 * @param metadata Optional metadata about the callable method
 */
declare function callable(
  metadata?: CallableMetadata
): <This, Args extends unknown[], Return>(
  target: (this: This, ...args: Args) => Return,
  _context: ClassMethodDecoratorContext
) => (this: This, ...args: Args) => Return;
/**
 * Decorator that marks a method as callable by clients
 * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
 * @param metadata Optional metadata about the callable method
 */
declare const unstable_callable: (
  metadata?: CallableMetadata
) => <This, Args extends unknown[], Return>(
  target: (this: This, ...args: Args) => Return,
  _context: ClassMethodDecoratorContext
) => (this: This, ...args: Args) => Return;
type QueueItem<T = string> = {
  id: string;
  payload: T;
  callback: keyof Agent<Cloudflare.Env>;
  created_at: number;
  retry?: RetryOptions;
};
/**
 * Represents a scheduled task within an Agent
 * @template T Type of the payload data
 */
type Schedule<T = string> = {
  /** Unique identifier for the schedule */ id: string /** Name of the method to be called */;
  callback: string /** Data to be passed to the callback */;
  payload: T /** Retry options for callback execution */;
  retry?: RetryOptions;
} & (
  | {
      /** Type of schedule for one-time execution at a specific time */ type: "scheduled" /** Timestamp when the task should execute */;
      time: number;
    }
  | {
      /** Type of schedule for delayed execution */ type: "delayed" /** Timestamp when the task should execute */;
      time: number /** Number of seconds to delay execution */;
      delayInSeconds: number;
    }
  | {
      /** Type of schedule for recurring execution based on cron expression */ type: "cron" /** Timestamp for the next execution */;
      time: number /** Cron expression defining the schedule */;
      cron: string;
    }
  | {
      /** Type of schedule for recurring execution at fixed intervals */ type: "interval" /** Timestamp for the next execution */;
      time: number /** Number of seconds between executions */;
      intervalSeconds: number;
    }
);
type AgentPathStep = {
  className: string;
  name: string;
};
type ScheduleStorageRow = {
  id: string;
  callback: string;
  payload: string;
  type: "scheduled" | "delayed" | "cron" | "interval";
  time: number;
  delayInSeconds?: number;
  cron?: string;
  intervalSeconds?: number;
  retry?: RetryOptions;
  running?: number;
  execution_started_at?: number | null;
  retry_options?: string | null;
  owner_path?: string | null;
  owner_path_key?: string | null;
};
type DetachedReconcilePayload = {
  cadenceIndex?: number;
};
type ScheduleCriteria = {
  id?: string;
  type?: "scheduled" | "delayed" | "cron" | "interval";
  timeRange?: {
    start?: Date;
    end?: Date;
  };
};
/**
 * Context passed to the `runFiber` callback. Provides checkpoint
 * and identity for durable execution.
 */
type FiberContext = {
  /** Unique identifier for this fiber execution. */ id: string /** Cooperative cancellation signal for managed fiber callers. */;
  signal: AbortSignal /** Checkpoint data during execution. Synchronous SQLite write. */;
  stash(
    data: unknown
  ): void /** Currently null during execution; recovered snapshots are passed to onFiberRecovered(). */;
  snapshot: unknown | null;
};
type FiberStatus =
  | "pending"
  | "running"
  | "completed"
  | "aborted"
  | "interrupted"
  | "error";
type StartFiberOptions = {
  fiberId?: string;
  idempotencyKey?: string;
  metadata?: Record<string, unknown>;
  waitForCompletion?: boolean;
};
type FiberInspection = {
  fiberId: string;
  name: string;
  idempotencyKey?: string;
  status: FiberStatus;
  snapshot?: unknown;
  error?: string;
  metadata?: Record<string, unknown>;
  createdAt: number;
  startedAt?: number;
  settledAt?: number;
};
type StartFiberResult = FiberInspection & {
  accepted: boolean;
};
type FiberRecoveryResult =
  | {
      status: "completed";
      snapshot?: unknown;
      metadata?: Record<string, unknown>;
    }
  | {
      status: "error";
      error?: unknown;
      snapshot?: unknown;
    }
  | {
      status: "aborted";
      reason?: string;
      snapshot?: unknown;
    }
  | {
      status: "interrupted";
      reason?: string;
      snapshot?: unknown;
    };
type ListFibersOptions = {
  status?: FiberStatus | FiberStatus[];
  name?: string;
  limit?: number;
};
type DeleteFibersOptions = {
  status?: FiberStatus | FiberStatus[];
  settledBefore?: Date;
  limit?: number;
};
/**
 * Context passed to the `onFiberRecovered` hook when an interrupted
 * fiber is detected after DO restart.
 */
type FiberRecoveryContext = {
  /** Fiber ID. */ id: string /** Name passed to `runFiber`. */;
  name: string /** Status for managed fibers recovered through the retained ledger. */;
  status?: FiberStatus /** Idempotency key for managed fibers, if one was supplied. */;
  idempotencyKey?: string /** Metadata for managed fibers, if one was supplied. */;
  metadata?: Record<
    string,
    unknown
  > | null /** Last checkpoint data from `stash()`, or null if never stashed. */;
  snapshot: unknown | null;
  /**
   * Epoch milliseconds when the fiber row was inserted (when `runFiber`
   * started). Use `Date.now() - createdAt` to gate stale recoveries.
   */
  createdAt: number /** Why this recovery hook is running. */;
  recoveryReason: "interrupted";
  [key: string]: unknown;
};
type InternalFiberOptions = {
  signal?: AbortSignal;
  managed?: boolean;
  initialSnapshot?: unknown;
  wrapStash?: (data: unknown) => unknown;
  beforeRunCleanup?: (
    outcome:
      | {
          ok: true;
        }
      | {
          ok: false;
          error: unknown;
        }
  ) => void;
};
/**
 * MCP Server state update message from server -> Client
 */
type MCPServerMessage = {
  type: MessageType.CF_AGENT_MCP_SERVERS;
  mcp: MCPServersState;
};
type MCPServersState = {
  servers: {
    [id: string]: MCPServer;
  };
  tools: (Tool & {
    serverId: string;
  })[];
  prompts: (Prompt & {
    serverId: string;
  })[];
  resources: (Resource & {
    serverId: string;
  })[];
};
type MCPServer = {
  name: string;
  server_url: string;
  auth_url: string | null;
  state: MCPConnectionState /** May contain untrusted content from external OAuth providers. Escape appropriately for your output context. */;
  error: string | null;
  instructions: string | null;
  capabilities: ServerCapabilities | null;
};
/**
 * Options for adding an MCP server
 */
type AddMcpServerOptions = {
  /**
   * Optional caller-supplied stable server id. When provided, this id is used
   * for storage, restore, and tool-name namespacing instead of a generated
   * `nanoid`. The value is normalized via {@link normalizeServerId} — for
   * connector-style integrations this lets `addMcpServer` keep producing
   * keys like `tool_github_create_pull_request`.
   *
   * Throws if an existing server already uses the same (normalized) id but a
   * different name or url.
   */
  id?: string /** OAuth callback host (auto-derived from request if omitted) */;
  callbackHost?: string;
  /**
   * Custom callback URL path — bypasses the default `/agents/{class}/{name}/callback` construction.
   * Required when `sendIdentityOnConnect` is `false` to prevent leaking the instance name.
   * When set, the callback URL becomes `{callbackHost}/{callbackPath}`.
   * The developer must route this path to the agent instance via `getAgentByName`.
   * Should be a plain path (e.g., `/mcp-callback`) — do not include query strings or fragments.
   */
  callbackPath?: string /** Agents routing prefix (default: "agents") */;
  agentsPrefix?: string /** MCP client options */;
  client?: McpClientOptions /** Transport options */;
  transport?: {
    /** Custom headers for authentication (e.g., bearer tokens, CF Access) */ headers?: HeadersInit /** Transport type: "sse", "streamable-http", or "auto" (default) */;
    type?: TransportType;
    /**
     * Compatibility escape hatch for a trusted legacy authorization server
     * whose RFC 8414 issuer does not match its metadata discovery URL.
     * Security-weakening; leave false unless the server is explicitly known.
     */
    skipIssuerMetadataValidation?: boolean;
  } /** Retry options for connection and reconnection attempts */;
  retry?: RetryOptions;
};
/**
 * Options for adding an MCP server via RPC (Durable Object binding)
 */
type AddRpcMcpServerOptions = {
  /**
   * Optional caller-supplied stable server id. When provided, this id is used
   * for storage, restore, and tool-name namespacing instead of a generated
   * `nanoid`. The value is normalized via {@link normalizeServerId}.
   *
   * Throws if an existing server already uses the same (normalized) id but a
   * different name or url.
   */
  id?: string /** Props to pass to the McpAgent instance */;
  props?: Record<string, unknown>;
};
/**
 * Default options for Agent configuration.
 * Child classes can override specific options without spreading.
 */
declare const DEFAULT_AGENT_STATIC_OPTIONS: {
  /** Whether the Agent should hibernate when inactive */ hibernate: boolean /** Whether to send identity (name, agent) to clients on connect */;
  sendIdentityOnConnect: boolean;
  /**
   * Timeout in seconds before a running interval schedule is considered "hung"
   * and force-reset. Increase this if you have callbacks that legitimately
   * take longer than 30 seconds.
   */
  hungScheduleTimeoutSeconds: number;
  /**
   * Interval in milliseconds for keepAlive() alarm heartbeats.
   * Lower values mean faster recovery after eviction but more frequent alarms.
   */
  keepAliveIntervalMs: number /** Default retry options for schedule(), queue(), and this.retry() */;
  retry: {
    maxAttempts: number;
    baseDelayMs: number;
    maxDelayMs: number;
  } /** Timeout for internal framework fiber recovery hooks. */;
  fiberRecoveryHookTimeoutMs: number /** Soft deadline for one interrupted-fiber recovery scan. */;
  fiberRecoveryScanDeadlineMs: number;
  /**
   * Maximum age of an unmanaged interrupted-fiber row before recovery gives
   * up. Bounds repeated retries of a `onFiberRecovered()` hook that keeps
   * throwing so a poison row cannot re-trigger forever across boots.
   */
  fiberRecoveryMaxAgeMs: number;
  /**
   * No-progress budget (ms) for re-attaching to a still-running agent-tool
   * child after a deploy / parent recovery (#1630). Bounds how long the parent
   * waits with NO forward progress from the child; it resets on every forwarded
   * chunk, so a child that keeps streaming is never abandoned mid-flight. Only a
   * genuinely silent/hung child seals `interrupted` after a full window. Raise
   * for children with long quiet stretches between outputs.
   */
  agentToolReattachNoProgressTimeoutMs: number;
  /**
   * Optional hard wall-clock ceiling (ms) on a single agent-tool re-attach
   * (#1630). Caps the total wait even as the no-progress budget re-arms across
   * stream-closes. Defaults to `Infinity` (no implicit cap), mirroring
   * chat-recovery's `maxRecoveryWork` (#1672): a healthy, still-advancing child
   * is followed for as long as it makes progress — a hung child is bounded by
   * the no-progress budget, and a content-runaway by the child's own
   * `maxRecoveryWork` / `shouldKeepRecovering`. Set a finite value to impose a
   * wall-clock cap (which also tears the child down on `window-exceeded`).
   */
  agentToolReattachMaxWindowMs: number;
  detachedMaxBudgetMs: number;
  detachedNoProgressBudgetMs: number;
  /**
   * Consecutive alarm invocations that may end in a Durable Object memory-limit
   * reset (the isolate exceeded its 128 MB limit) before the alarm-boundary
   * circuit breaker stops the platform's auto-retry loop and seals the looping
   * work (#1825). A small budget tolerates a genuinely transient memory spike;
   * a deterministic OOM (the work's footprint, not the platform, is the cause)
   * is bounded here regardless of whether the in-DO recovery budgets could run.
   */
  maxAlarmMemoryLimitStrikes: number;
};
/**
 * Configuration options for the Agent.
 * Override in subclasses via `static options`.
 * All fields are optional - defaults are applied at runtime.
 * Note: `hibernate` defaults to `true` if not specified.
 */
interface AgentStaticOptions {
  hibernate?: boolean;
  sendIdentityOnConnect?: boolean;
  hungScheduleTimeoutSeconds?: number;
  /**
   * Interval in milliseconds for keepAlive() alarm heartbeats.
   * Default: 30000 (30 seconds). Lower values mean faster recovery
   * after eviction but more frequent alarms.
   */
  keepAliveIntervalMs?: number;
  /** Default retry options for schedule(), queue(), and this.retry(). */
  retry?: RetryOptions;
  /**
   * Timeout in milliseconds for internal framework fiber recovery hooks.
   * User-defined `onFiberRecovered()` hooks are not timed out by default.
   */
  fiberRecoveryHookTimeoutMs?: number;
  /** Soft deadline in milliseconds for one interrupted-fiber recovery scan. */
  fiberRecoveryScanDeadlineMs?: number;
  /**
   * Maximum age in milliseconds of an unmanaged interrupted-fiber row before
   * recovery stops retrying a repeatedly-throwing `onFiberRecovered()` hook
   * and discards the row (emitting `fiber:recovery:skipped` with reason
   * `max_age_exceeded`). Defaults to 24h.
   *
   * Set to `0` to retain rows indefinitely. NOTE: with `0`, a hook that keeps
   * throwing is retried forever — the recovery alarm backs off exponentially
   * (capped at 5 minutes) so it is not a busy-loop, but the Durable Object
   * stays warm (never idle-evicts) for as long as the un-recoverable row
   * exists. Prefer a finite age unless you intend to inspect/clear such rows
   * yourself.
   */
  fiberRecoveryMaxAgeMs?: number;
  /**
   * No-progress budget in milliseconds for re-attaching to a still-running
   * agent-tool child after a deploy / parent recovery (#1630). Resets on every
   * forwarded chunk, so a steadily-streaming child is never abandoned; only a
   * genuinely silent child seals `interrupted` after a full window.
   * Default: 120000 (2 minutes). Set to `0` to skip waiting (collect only an
   * already-terminal child). Set to `Infinity` to never seal on no-progress —
   * a silent-but-alive child is then followed until its stream closes (or the
   * `agentToolReattachMaxWindowMs` ceiling fires), mirroring that knob's
   * "Infinity = off" convention.
   */
  agentToolReattachNoProgressTimeoutMs?: number;
  /**
   * Optional hard wall-clock ceiling in milliseconds on a single agent-tool
   * re-attach (#1630). Caps the total wait even as the no-progress budget
   * re-arms across stream-closes. Default: `Infinity` (no implicit cap),
   * mirroring chat-recovery's `maxRecoveryWork` (#1672) — a healthy,
   * still-advancing child is followed for as long as it makes progress, exactly
   * as on the live (never-evicted) path. Set a finite value to impose a
   * wall-clock cap (which also tears the child down on `window-exceeded`); `0`
   * also disables the ceiling.
   */
  agentToolReattachMaxWindowMs?: number;
  /**
   * Absolute safety ceiling in milliseconds for a DETACHED ("background")
   * agent-tool run dispatched via `runAgentTool(cls, { detached: ... })`
   * (rfc-detached-agent-tools). A detached run has no awaiting parent turn, so
   * on expiry the parent gives up watching — delivers the completion hook with
   * `interrupted` / `budget-exceeded` and tears the child down — rather than
   * holding a concurrency slot + live facet forever. Unlike the re-attach
   * window this defaults to a FINITE value (24h) precisely because an abandoned
   * detached run has no observer to notice the leak. Override per-run via
   * `detached: { maxBudgetMs }`.
   */
  detachedMaxBudgetMs?: number;
  /**
   * Resetting no-progress window in milliseconds for a DETACHED agent-tool run
   * (rfc-detached-agent-tools §progress). Once the child has emitted at least
   * one `reportProgress` signal, the parent gives up if the run then goes
   * silent for this long; the window resets on every subsequent signal. A child
   * that never reports progress is bounded only by `detachedMaxBudgetMs` — we
   * never give up on a run merely for taking a long time, only for going silent
   * after it began reporting. Default: 1h. Set `0`/`Infinity` to disable (rely
   * on the absolute ceiling only). Override per-run via
   * `detached: { noProgressBudgetMs }`.
   */
  detachedNoProgressBudgetMs?: number;
  /**
   * Consecutive alarm invocations that may end in a Durable Object memory-limit
   * reset (the isolate exceeded its 128 MB limit) before the alarm-boundary
   * circuit breaker stops the platform's auto-retry loop and seals the looping
   * recovery work (#1825). Default: 3. Set to `0` to seal on the first such
   * reset. This is the universal backstop for the case where the in-DO recovery
   * budgets (`chatRecovery.maxOomRetries` / `maxRecoveryWork`) can't engage
   * because the OOM bypasses them — e.g. it is thrown before the budget code
   * runs, or its own writes also OOM. The boundary handler runs at the outermost
   * alarm frame, after the heavy turn has unwound and GC has reclaimed its
   * footprint, so its small seal/purge writes can land where mid-turn writes
   * could not.
   */
  maxAlarmMemoryLimitStrikes?: number;
}
declare function getCurrentAgent<
  T extends Agent<Cloudflare.Env> = Agent<Cloudflare.Env>
>(): {
  agent: T | undefined;
  connection: Connection | undefined;
  request: Request | undefined;
  email: AgentEmail | undefined;
};
/**
 * Extract string keys from Env where the value is a Workflow binding.
 */
type WorkflowBinding<E> = {
  [K in keyof E & string]: E[K] extends Workflow ? K : never;
}[keyof E & string];
/**
 * Type for workflow name parameter.
 * When Env has typed Workflow bindings, provides autocomplete for those keys.
 * Also accepts any string for dynamic use cases and compatibility.
 * The `string & {}` trick preserves autocomplete while allowing any string.
 */
type WorkflowName<E> = WorkflowBinding<E> | (string & {});
/**
 * Base class for creating Agent implementations
 * @template Env Environment type containing bindings
 * @template State State type to store within the Agent
 */
declare class Agent<
  Env extends Cloudflare.Env = Cloudflare.Env,
  State = unknown,
  Props extends Record<string, unknown> = Record<string, unknown>
> extends Server<Env, Props> {
  private _state;
  private _disposables;
  private _destroyed;
  /**
   * Stores raw state accessors for wrapped connections.
   * Used by internal flag methods (readonly, no-protocol) to read/write
   * _cf_-prefixed keys without going through the user-facing state/setState.
   */
  private _rawStateAccessors;
  /**
   * Cached persistence-hook dispatch mode, computed once in the constructor.
   * - "new"  → call onStateChanged
   * - "old"  → call onStateUpdate (deprecated)
   * - "none" → neither hook is overridden, skip entirely
   */
  private _persistenceHookMode;
  /** True when this agent runs as a facet (sub-agent) inside a parent. */
  private _isFacet;
  private _protocolBroadcastExcludeIds;
  private _cf_currentSubAgentBridge?;
  private _cf_virtualSubAgentConnections;
  /**
   * User-facing facet name. For legacy facets this is the same as
   * `ctx.id.name`; path-scoped facets use an internal routing id and
   * keep the logical name here instead.
   * @internal
   */
  private _facetName?;
  /**
   * Ancestor chain, root-first. Empty for top-level DOs; populated at
   * facet init time from the parent's own `selfPath`. Exposed publicly
   * via the `parentPath` getter.
   * @internal
   */
  private _parentPath;
  /** True while user's onStart() is executing. Used to warn about non-idempotent schedule() calls. */
  private _insideOnStart;
  /** Tracks callbacks already warned about during this onStart() to avoid log spam. */
  private _warnedScheduleInOnStart;
  /** Warn-once guard: `chatRecovery` reassigned during onStart() (too late for wake recovery). */
  private _warnedChatRecoveryInOnStart;
  /**
   * Number of active keepAlive() callers. When > 0, `_scheduleNextAlarm()`
   * caps the next alarm at `keepAliveIntervalMs` so the DO stays alive.
   * Purely in-memory — lost on eviction, which is correct because the
   * in-memory work keepAlive was protecting is also lost.
   * @internal
   */
  _keepAliveRefs: number;
  /**
   * In-memory tokens for keepAlive leases acquired by facets and held
   * on the root alarm owner. Lost on eviction, like `_keepAliveRefs`,
   * because the in-memory work those leases were protecting is also gone.
   * @internal
   */
  private _facetKeepAliveTokens;
  /** @internal In-memory set of fiber IDs running in this process. */
  private _runFiberActiveFibers;
  /** @internal In-memory abort controllers for managed running fibers. */
  private _managedFiberAbortControllers;
  /** @internal In-memory executions for callers that want to await accepted work. */
  private _managedFiberExecutions;
  /** @internal In-memory waiters for managed fibers reaching terminal ledger state. */
  private _managedFiberTerminalWaiters;
  /** @internal Prevents re-entrant recovery from overlapping alarm ticks. */
  private _runFiberRecoveryInProgress;
  /**
   * @internal Consecutive runFiber-recovery scans that made NO forward progress
   * while work was still pending. Drives the exponential backoff of the
   * recovery follow-up alarm so a repeatedly-throwing recovery hook does not
   * busy-loop the DO. Reset to 0 whenever a scan recovers anything.
   */
  private _recoveryNoProgressScans;
  /** @internal Single-flight background recovery for parent agent-tool rows. */
  private _agentToolRunRecoveryPromise;
  /** @internal Serializes detached-backbone arming against concurrent dispatch. */
  private _detachedBackboneArming;
  /** @internal Edge-trigger latch for the live-detached-count warning. */
  private _detachedLiveCountWarned;
  private _ParentClass;
  readonly mcp: MCPClientManager;
  /**
   * Initial state for the Agent
   * Override to provide default state values
   */
  initialState: State;
  /**
   * Stable key for Workers AI session affinity (prefix-cache optimization).
   *
   * Uses the Durable Object ID, which is globally unique across all agent
   * classes and stable for the lifetime of the instance. Pass this value as
   * the `sessionAffinity` option when creating a Workers AI model so that
   * requests from the same agent instance are routed to the same backend
   * replica, improving KV-prefix-cache hit rates across conversation turns.
   *
   * @example
   * ```typescript
   * const workersai = createWorkersAI({ binding: this.env.AI });
   * const model = workersai("@cf/meta/llama-3.3-70b-instruct-fp8-fast", {
   *   sessionAffinity: this.sessionAffinity,
   * });
   * ```
   */
  get sessionAffinity(): string;
  /**
   * Current state of the Agent
   */
  get state(): State;
  /**
   * Agent configuration options.
   * Override in subclasses - only specify what you want to change.
   * @example
   * class SecureAgent extends Agent {
   *   static options = { sendIdentityOnConnect: false };
   * }
   */
  static options: AgentStaticOptions;
  /**
   * Resolved options (merges defaults with subclass overrides).
   * Cached after first access — static options never change during the
   * lifetime of a Durable Object instance.
   */
  private _cachedOptions?;
  private get _resolvedOptions();
  /**
   * The observability implementation to use for the Agent
   */
  observability?: Observability;
  /**
   * Emit an observability event with auto-generated timestamp.
   * @internal
   */
  protected _emit(
    type: ObservabilityEvent["type"],
    payload?: Record<string, unknown>
  ): void;
  /** Run SDK work under a stable parent for platform child spans. */
  private _withAgentSpan;
  /**
   * Execute SQL queries against the Agent's database
   * @template T Type of the returned rows
   * @param strings SQL query template strings
   * @param values Values to be inserted into the query
   * @returns Array of query results
   */
  sql<T = Record<string, string | number | boolean | null>>(
    strings: TemplateStringsArray,
    ...values: (string | number | boolean | null)[]
  ): T[];
  private _schemaInitialization;
  /**
   * Create all internal tables and run migrations if needed.
   * Called by the constructor on every wake. Idempotent — skips DDL when
   * the stored schema version matches CURRENT_SCHEMA_VERSION.
   *
   * Protected so that test agents can re-run the real migration path
   * after manipulating DB state (since ctx.abort() is unavailable in
   * local dev and the constructor only runs once per DO instance).
   */
  protected _ensureSchema(): void;
  constructor(ctx: AgentContext, env: Env);
  /**
   * Check for workflows referencing unknown bindings and warn with migration suggestion.
   */
  private _checkOrphanedWorkflows;
  /**
   * Broadcast a protocol message only to connections that have protocol
   * messages enabled. Connections where shouldSendProtocolMessages returned
   * false are excluded automatically.
   * @param msg The JSON-encoded protocol message
   * @param excludeIds Additional connection IDs to exclude (e.g. the source)
   */
  private _broadcastProtocol;
  private _setStateInternal;
  /**
   * Update the Agent's state
   * @param state New state to set
   * @throws Error if called from a readonly connection context
   */
  setState(state: State): void;
  /**
   * Wraps connection.state and connection.setState so that internal
   * _cf_-prefixed flags (readonly, no-protocol) are hidden from user code
   * and cannot be accidentally overwritten.
   *
   * Idempotent — safe to call multiple times on the same connection.
   * After hibernation, the _rawStateAccessors WeakMap is empty but the
   * connection's state getter still reads from the persisted WebSocket
   * attachment. Calling this method re-captures the raw getter so that
   * predicate methods (isConnectionReadonly, isConnectionProtocolEnabled)
   * work correctly post-hibernation.
   */
  private _ensureConnectionWrapped;
  /**
   * Mark a connection as readonly or readwrite
   * @param connection The connection to mark
   * @param readonly Whether the connection should be readonly (default: true)
   */
  setConnectionReadonly(connection: Connection, readonly?: boolean): void;
  /**
   * Check if a connection is marked as readonly.
   *
   * Safe to call after hibernation — re-wraps the connection if the
   * in-memory accessor cache was cleared.
   * @param connection The connection to check
   * @returns True if the connection is readonly
   */
  isConnectionReadonly(connection: Connection): boolean;
  /**
   * ⚠️ INTERNAL — DO NOT USE IN APPLICATION CODE. ⚠️
   *
   * Read an internal `_cf_`-prefixed flag from the raw connection state,
   * bypassing the user-facing state wrapper that strips internal keys.
   *
   * This exists for framework mixins (e.g. voice) that need to persist
   * flags in the connection attachment across hibernation. Application
   * code should use `connection.state` and `connection.setState()` instead.
   *
   * @internal
   */
  _unsafe_getConnectionFlag(connection: Connection, key: string): unknown;
  /**
   * ⚠️ INTERNAL — DO NOT USE IN APPLICATION CODE. ⚠️
   *
   * Write an internal `_cf_`-prefixed flag to the raw connection state,
   * bypassing the user-facing state wrapper. The key must be registered
   * in `CF_INTERNAL_KEYS` so it is preserved across user `setState` calls
   * and hidden from `connection.state`.
   *
   * @internal
   */
  _unsafe_setConnectionFlag(
    connection: Connection,
    key: string,
    value: unknown
  ): void;
  /**
   * Override this method to determine if a connection should be readonly on connect
   * @param _connection The connection that is being established
   * @param _ctx Connection context
   * @returns True if the connection should be readonly
   */
  shouldConnectionBeReadonly(
    _connection: Connection,
    _ctx: ConnectionContext
  ): boolean;
  /**
   * Override this method to control whether protocol messages are sent to a
   * connection. Protocol messages include identity (CF_AGENT_IDENTITY), state
   * sync (CF_AGENT_STATE), and MCP server lists (CF_AGENT_MCP_SERVERS).
   *
   * When this returns `false` for a connection, that connection will not
   * receive any protocol text frames — neither on connect nor via broadcasts.
   * This is useful for binary-only clients (e.g. MQTT devices) that cannot
   * handle JSON text frames.
   *
   * The connection can still send and receive regular messages, use RPC, and
   * participate in all non-protocol communication.
   *
   * @param _connection The connection that is being established
   * @param _ctx Connection context (includes the upgrade request)
   * @returns True if protocol messages should be sent (default), false to suppress them
   */
  shouldSendProtocolMessages(
    _connection: Connection,
    _ctx: ConnectionContext
  ): boolean;
  /**
   * Check if a connection has protocol messages enabled.
   * Protocol messages include identity, state sync, and MCP server lists.
   *
   * Safe to call after hibernation — re-wraps the connection if the
   * in-memory accessor cache was cleared.
   * @param connection The connection to check
   * @returns True if the connection receives protocol messages
   */
  isConnectionProtocolEnabled(connection: Connection): boolean;
  /**
   * Mark a connection as having protocol messages disabled.
   * Called internally when shouldSendProtocolMessages returns false.
   */
  private _setConnectionNoProtocol;
  /**
   * Called before the Agent's state is persisted and broadcast.
   * Override to validate or reject an update by throwing an error.
   *
   * IMPORTANT: This hook must be synchronous.
   */
  validateStateChange(_nextState: State, _source: Connection | "server"): void;
  /**
   * Called after the Agent's state has been persisted and broadcast to all clients.
   * This is a notification hook — errors here are routed to onError and do not
   * affect state persistence or client broadcasts.
   *
   * @param state Updated state
   * @param source Source of the state update ("server" or a client connection)
   */
  onStateChanged(
    _state: State | undefined,
    _source: Connection | "server"
  ): void;
  /**
   * @deprecated Renamed to `onStateChanged` — the behavior is identical.
   * `onStateUpdate` will be removed in the next major version.
   *
   * Called after the Agent's state has been persisted and broadcast to all clients.
   * This is a server-side notification hook. For the client-side state callback,
   * see the `onStateUpdate` option in `useAgent` / `AgentClient`.
   *
   * @param state Updated state
   * @param source Source of the state update ("server" or a client connection)
   */
  onStateUpdate(
    _state: State | undefined,
    _source: Connection | "server"
  ): void;
  /**
   * Dispatch to the appropriate persistence hook based on the mode
   * cached in the constructor. No prototype walks at call time.
   */
  private _callStatePersistenceHook;
  /**
   * Called when the Agent receives an email via routeAgentEmail()
   * Override this method to handle incoming emails
   * @param payload Internal wire format — plain data + RpcTarget bridge
   */
  _onEmail(payload: {
    from: string;
    to: string;
    headers: Headers;
    rawSize: number;
    _secureRouted?: boolean;
    _bridge: EmailBridge;
  }): Promise<void>;
  /**
   * Reply to an email
   * @param email The email to reply to
   * @param options Options for the reply
   * @param options.secret Secret for signing agent headers (enables secure reply routing).
   *   Required if the email was routed via createSecureReplyEmailResolver.
   *   Pass explicit `null` to opt-out of signing (not recommended for secure routing).
   * @returns void
   */
  replyToEmail(
    email: AgentEmail,
    options: {
      fromName: string;
      subject?: string | undefined;
      body: string;
      contentType?: string;
      headers?: Record<string, string>;
      secret?: string | null;
    }
  ): Promise<void>;
  /**
   * Send an outbound email via an Email Service binding.
   *
   * Automatically injects agent routing headers (X-Agent-Name, X-Agent-ID).
   * When `secret` is provided, signs headers with HMAC-SHA256 so that replies
   * can be routed back to this agent instance via createSecureReplyEmailResolver.
   *
   * @param options.binding The send_email binding (e.g. this.env.EMAIL)
   * @param options.to Recipient address(es)
   * @param options.from Sender address or {email, name} object
   * @param options.subject Email subject line
   * @param options.text Plain text body (at least one of text/html required)
   * @param options.html HTML body (at least one of text/html required)
   * @param options.replyTo Reply-to address
   * @param options.cc CC recipient(s)
   * @param options.bcc BCC recipient(s)
   * @param options.inReplyTo Message-ID of the email this is replying to (for threading)
   * @param options.headers Additional custom headers
   * @param options.secret Secret for signing agent routing headers
   * @returns The messageId from Email Service
   */
  sendEmail(options: SendEmailOptions): Promise<EmailSendResult>;
  private _tryCatch;
  /**
   * Automatically wrap custom methods with agent context
   * This ensures getCurrentAgent() works in all custom methods without decorators
   */
  private _autoWrapCustomMethods;
  onError(connection: Connection, error: unknown): void | Promise<void>;
  onError(error: unknown): void | Promise<void>;
  /**
   * Render content (not implemented in base class)
   */
  render(): void;
  /**
   * Retry an async operation with exponential backoff and jitter.
   * Retries on all errors by default. Use `shouldRetry` to bail early on non-retryable errors.
   *
   * @param fn The async function to retry. Receives the current attempt number (1-indexed).
   * @param options Retry configuration.
   * @param options.maxAttempts Maximum number of attempts (including the first). Falls back to static options, then 3.
   * @param options.baseDelayMs Base delay in ms for exponential backoff. Falls back to static options, then 100.
   * @param options.maxDelayMs Maximum delay cap in ms. Falls back to static options, then 3000.
   * @param options.shouldRetry Predicate called with the error and next attempt number. Return false to stop retrying immediately. Default: retry all errors.
   * @returns The result of fn on success.
   * @throws The last error if all attempts fail or shouldRetry returns false.
   */
  retry<T>(
    fn: (attempt: number) => Promise<T>,
    options?: RetryOptions & {
      /** Return false to stop retrying a specific error. Receives the error and the next attempt number. Default: retry all errors. */ shouldRetry?: (
        err: unknown,
        nextAttempt: number
      ) => boolean;
    }
  ): Promise<T>;
  /**
   * Queue a task to be executed in the future
   * @param callback Name of the method to call
   * @param payload Payload to pass to the callback
   * @param options Options for the queued task
   * @param options.retry Retry options for the callback execution
   * @returns The ID of the queued task
   */
  queue<T = unknown>(
    callback: keyof this,
    payload: T,
    options?: {
      retry?: RetryOptions;
    }
  ): Promise<string>;
  private _flushingQueue;
  private _flushQueue;
  /**
   * Dequeue a task by ID
   * @param id ID of the task to dequeue
   */
  dequeue(id: string): void;
  /**
   * Dequeue all tasks
   */
  dequeueAll(): void;
  /**
   * Dequeue all tasks by callback
   * @param callback Name of the callback to dequeue
   */
  dequeueAllByCallback(callback: string): void;
  /**
   * Get a queued task by ID
   * @param id ID of the task to get
   * @returns The task or undefined if not found
   */
  getQueue(id: string): QueueItem<string> | undefined;
  /**
   * Get all queues by key and value
   * @param key Key to filter by
   * @param value Value to filter by
   * @returns Array of matching QueueItem objects
   */
  getQueues(key: string, value: string): QueueItem<string>[];
  private _scheduleOwnerPathKey;
  private _facetRunRowsForPrefix;
  private _deleteFacetRunRowsForPrefix;
  private _rootAlarmOwner;
  private _cf_rootResolvesToSelf;
  private _validateScheduleCallback;
  /**
   * Insert (or, for idempotent calls, return the existing row for) a
   * schedule owned by either this top-level agent (`ownerPath === null`)
   * or a descendant facet. Returns `{ schedule, created }` — `created`
   * is `false` when an idempotent insert deduplicates onto an existing
   * row, so callers can suppress the `schedule:create` event in that
   * case to match historic semantics.
   * @internal
   */
  private _insertScheduleForOwner;
  /**
   * Insert a schedule row owned by a descendant facet. Called via RPC
   * from the facet's `schedule()`. Returns `{ schedule, created }`
   * so the originating facet can suppress `schedule:create` on
   * idempotent dedup. This method does not emit observability
   * events itself.
   * @internal
   */
  _cf_scheduleForFacet<T = string>(
    ownerPath: ReadonlyArray<AgentPathStep>,
    when: Date | string | number,
    callback: string,
    payload?: T,
    options?: {
      retry?: RetryOptions;
      idempotent?: boolean;
    }
  ): Promise<{
    schedule: Schedule<T>;
    created: boolean;
  }>;
  /**
   * Insert (or, for idempotent calls, return the existing row for) an
   * interval schedule. Mirrors {@link _insertScheduleForOwner} —
   * returns `{ schedule, created }` so callers can suppress
   * `schedule:create` on dedup.
   * @internal
   */
  private _insertIntervalScheduleForOwner;
  /**
   * Insert an interval schedule row owned by a descendant facet.
   * Called via RPC from the facet's `scheduleEvery()`. Returns
   * `{ schedule, created }` so the originating facet can suppress
   * `schedule:create` on idempotent dedup. This method does not
   * emit observability events itself.
   * @internal
   */
  _cf_scheduleEveryForFacet<T = string>(
    ownerPath: ReadonlyArray<AgentPathStep>,
    intervalSeconds: number,
    callback: string,
    payload?: T,
    options?: {
      retry?: RetryOptions;
      _idempotent?: boolean;
    }
  ): Promise<{
    schedule: Schedule<T>;
    created: boolean;
  }>;
  /**
   * Cancel a schedule row owned by a descendant facet, scoped by
   * `owner_path_key` so siblings can't reach each other's rows.
   * Returns the canceled row's callback name so the originating
   * facet can emit `schedule:cancel`. This method does not emit
   * observability events itself.
   * @internal
   */
  _cf_cancelScheduleForFacet(
    ownerPath: ReadonlyArray<AgentPathStep>,
    id: string
  ): Promise<{
    ok: boolean;
    callback?: string;
  }>;
  /**
   * Clean root-owned bookkeeping for a sub-tree of facets. This
   * bulk-cancels schedules whose `owner_path` starts with the given
   * prefix and deletes root-side facet fiber recovery leases for the
   * same sub-tree. Used by `deleteSubAgent` and recursive facet
   * destroy. Emits `schedule:cancel` on this agent (the alarm-owning
   * root) for each schedule row removed — the facets being torn down
   * may not be alive to receive the events themselves.
   * @internal
   */
  _cf_cleanupFacetPrefix(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<void>;
  private _scheduleRowToSchedule;
  private _getScheduleForOwner;
  private _listSchedulesForOwner;
  /**
   * Read a single schedule row owned by a descendant facet.
   * @internal
   */
  _cf_getScheduleForFacet(
    ownerPath: ReadonlyArray<AgentPathStep>,
    id: string
  ): Promise<Schedule<unknown> | undefined>;
  /**
   * List schedule rows owned by a descendant facet, scoped by
   * `owner_path_key` so siblings remain isolated from each other.
   * @internal
   */
  _cf_listSchedulesForFacet(
    ownerPath: ReadonlyArray<AgentPathStep>,
    criteria?: ScheduleCriteria
  ): Promise<Schedule<unknown>[]>;
  /**
   * Acquire a root-owned keepAlive ref on behalf of a descendant facet.
   * Facets share the root isolate but cannot set their own physical
   * alarm, so this lets facet work use the root alarm heartbeat.
   * @internal
   */
  _cf_acquireFacetKeepAlive(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<string>;
  /**
   * Release a root-owned keepAlive ref previously acquired for a facet.
   * Idempotent so disposer calls can safely race or run twice.
   * @internal
   */
  _cf_releaseFacetKeepAlive(token: string): Promise<void>;
  /**
   * Register a facet's durable run row in the root-side index so root
   * alarm housekeeping can dispatch recovery checks into idle facets.
   * The facet remains authoritative for snapshots and recovery hooks.
   * @internal
   */
  _cf_registerFacetRun(
    ownerPath: ReadonlyArray<AgentPathStep>,
    runId: string
  ): Promise<void>;
  /**
   * Remove a completed facet fiber from the root-side index.
   * @internal
   */
  _cf_unregisterFacetRun(
    ownerPath: ReadonlyArray<AgentPathStep>,
    runId: string
  ): Promise<void>;
  /**
   * Schedule a task to be executed in the future
   *
   * Cron schedules are **idempotent by default** — calling `schedule("0 * * * *", "tick")`
   * multiple times with the same callback, cron expression, and payload returns
   * the existing schedule instead of creating a duplicate. Set `idempotent: false`
   * to override this.
   *
   * For delayed and scheduled (Date) types, set `idempotent: true` to opt in
   * to the same dedup behavior (matched on callback + payload). This is useful
   * when calling `schedule()` in `onStart()` to avoid accumulating duplicate
   * rows across Durable Object restarts.
   *
   * @template T Type of the payload data
   * @param when When to execute the task (Date, seconds delay, or cron expression)
   * @param callback Name of the method to call
   * @param payload Data to pass to the callback
   * @param options Options for the scheduled task
   * @param options.retry Retry options for the callback execution
   * @param options.idempotent Dedup by callback+payload. Defaults to `true` for cron, `false` otherwise.
   * @returns Schedule object representing the scheduled task
   */
  schedule<T = string>(
    when: Date | string | number,
    callback: keyof this,
    payload?: T,
    options?: {
      retry?: RetryOptions;
      idempotent?: boolean;
    }
  ): Promise<Schedule<T>>;
  /**
   * Schedule a task to run repeatedly at a fixed interval.
   *
   * This method is **idempotent** — calling it multiple times with the same
   * `callback`, `intervalSeconds`, and `payload` returns the existing schedule
   * instead of creating a duplicate. A different interval or payload is
   * treated as a distinct schedule and creates a new row.
   *
   * This makes it safe to call in `onStart()`, which runs on every Durable
   * Object wake:
   *
   * ```ts
   * async onStart() {
   *   // Only one schedule is created, no matter how many times the DO wakes
   *   await this.scheduleEvery(30, "tick");
   * }
   * ```
   *
   * @template T Type of the payload data
   * @param intervalSeconds Number of seconds between executions
   * @param callback Name of the method to call
   * @param payload Data to pass to the callback
   * @param options Options for the scheduled task
   * @param options.retry Retry options for the callback execution
   * @returns Schedule object representing the scheduled task
   */
  scheduleEvery<T = string>(
    intervalSeconds: number,
    callback: keyof this,
    payload?: T,
    options?: {
      retry?: RetryOptions;
      _idempotent?: boolean;
    }
  ): Promise<Schedule<T>>;
  /**
   * Get a scheduled task by ID
   * @template T Type of the payload data
   * @param id ID of the scheduled task
   * @returns The Schedule object or undefined if not found
   * @deprecated Use {@link getScheduleById}. This synchronous API cannot cross
   * Durable Object boundaries and throws inside sub-agents.
   */
  getSchedule<T = string>(id: string): Schedule<T> | undefined;
  /**
   * Get a scheduled task by ID.
   *
   * Unlike the deprecated synchronous {@link getSchedule}, this works inside
   * sub-agents by delegating to the top-level parent that owns the alarm.
   *
   * @template T Type of the payload data
   * @param id ID of the scheduled task
   * @returns The Schedule object or undefined if not found
   */
  getScheduleById(id: string): Promise<Schedule<unknown> | undefined>;
  /**
   * Get scheduled tasks matching the given criteria
   * @template T Type of the payload data
   * @param criteria Criteria to filter schedules
   * @returns Array of matching Schedule objects
   * @deprecated Use {@link listSchedules}. This synchronous API cannot cross
   * Durable Object boundaries and throws inside sub-agents.
   */
  getSchedules<T = string>(criteria?: ScheduleCriteria): Schedule<T>[];
  /**
   * List scheduled tasks matching the given criteria.
   *
   * Unlike the deprecated synchronous {@link getSchedules}, this works inside
   * sub-agents by delegating to the top-level parent that owns the alarm.
   *
   * @template T Type of the payload data
   * @param criteria Criteria to filter schedules
   * @returns Array of matching Schedule objects
   */
  listSchedules(criteria?: ScheduleCriteria): Promise<Schedule<unknown>[]>;
  /**
   * Cancel a scheduled task.
   *
   * Schedules are isolated by owner: a top-level agent's
   * `cancelSchedule(id)` only matches its own schedules, and a
   * sub-agent's `cancelSchedule(id)` only matches schedules it
   * created. To clear every schedule under a sub-agent (and its
   * descendants), call `parent.deleteSubAgent(Cls, name)` from the
   * parent — that bulk-cleans root-owned bookkeeping via
   * {@link _cf_cleanupFacetPrefix}.
   *
   * @param id ID of the task to cancel
   * @returns true if the task was cancelled, false if the task was not found
   */
  cancelSchedule(id: string): Promise<boolean>;
  /**
   * Keep the Durable Object alive via alarm heartbeats.
   * Returns a disposer function that stops the heartbeat when called.
   *
   * Use this when you have long-running work and need to prevent the
   * DO from going idle (eviction after ~70-140s of inactivity).
   * The heartbeat fires every `keepAliveIntervalMs` (default 30s) via the
   * alarm system, without creating schedule rows or emitting observability
   * events. Configure via `static options = { keepAliveIntervalMs: 5000 }`.
   *
   * In facets, delegates the physical heartbeat to the root parent
   * because facets do not have independent alarm slots.
   *
   * @example
   * ```ts
   * const dispose = await this.keepAlive();
   * try {
   *   // ... long-running work ...
   * } finally {
   *   dispose();
   * }
   * ```
   */
  keepAlive(): Promise<() => void>;
  /**
   * Run an async function while keeping the Durable Object alive.
   * The heartbeat is automatically stopped when the function completes
   * (whether it succeeds or throws).
   *
   * This is the recommended way to use keepAlive — it guarantees cleanup
   * so you cannot forget to dispose the heartbeat.
   *
   * @example
   * ```ts
   * const result = await this.keepAliveWhile(async () => {
   *   const data = await longRunningComputation();
   *   return data;
   * });
   * ```
   */
  keepAliveWhile<T>(fn: () => Promise<T>): Promise<T>;
  private _isTerminalFiberStatus;
  private _notifyManagedFiberTerminal;
  private _waitForManagedFiberTerminal;
  private _normalizeFiberStatusFilter;
  private _parseFiberJsonObject;
  private _parseFiberSnapshot;
  private _fiberErrorMessage;
  private _stringifyFiberSnapshot;
  private _fiberRecoveryErrorMessage;
  private _applyManagedFiberRecoveryResult;
  private _settleManagedFiberExecution;
  private _parseFiberRecoverySnapshot;
  private _fiberRecoveryPayload;
  private _withFiberRecoveryTimeout;
  private _recordFiberRecoveryFailure;
  private _runFiberRecoveryHook;
  private _fiberInspectionFromRow;
  private _waitForManagedFiber;
  private _readFiber;
  private _readFiberByKey;
  private _listFiberRows;
  private _listFiberRowsByStatus;
  inspectFiber(fiberId: string): Promise<FiberInspection | null>;
  inspectFiberByKey(idempotencyKey: string): Promise<FiberInspection | null>;
  listFibers(options?: ListFibersOptions): Promise<FiberInspection[]>;
  cancelFiber(fiberId: string, reason?: string): Promise<boolean>;
  cancelFiberByKey(idempotencyKey: string, reason?: string): Promise<boolean>;
  resolveFiber(fiberId: string, result: FiberRecoveryResult): Promise<boolean>;
  deleteFibers(options?: DeleteFibersOptions): Promise<number>;
  private _listTerminalFiberRowsForDelete;
  /**
   * Run a function as a durable fiber. The fiber is registered in SQLite
   * before execution, checkpointable during execution via `ctx.stash()`,
   * and recoverable after eviction via `onFiberRecovered`.
   *
   * - Row created in `cf_agents_runs` at start, deleted on completion
   * - `keepAlive()` held for the duration — prevents idle eviction
   * - Inline (await result) or fire-and-forget (`void this.runFiber(...)`)
   *
   * @param name Informational name for debugging and recovery filtering
   * @param fn Async function to execute. Receives a FiberContext with stash/snapshot.
   * @returns The return value of fn
   */
  runFiber<T>(name: string, fn: (ctx: FiberContext) => Promise<T>): Promise<T>;
  /**
   * Internal framework entry point for fibers that need to compose their own
   * recovery metadata with user checkpoint data while preserving the public
   * `this.stash()` behavior.
   *
   * This deliberately stays protected/internal rather than becoming a public
   * `runFiber()` option until the durable execution API needs this generality.
   * @internal
   */
  protected _runFiberWithStashWrapper<T>(
    name: string,
    fn: (ctx: FiberContext) => Promise<T>,
    options: Pick<InternalFiberOptions, "initialSnapshot" | "wrapStash">
  ): Promise<T>;
  startFiber(
    name: string,
    fn: (ctx: FiberContext) => Promise<void>,
    options?: StartFiberOptions
  ): Promise<StartFiberResult>;
  private _executeManagedFiber;
  private _runFiberInternal;
  /**
   * Checkpoint data for the currently executing fiber.
   * Uses AsyncLocalStorage to identify the correct fiber,
   * so it works correctly even with concurrent fibers.
   *
   * Throws if called outside a `runFiber` callback.
   */
  stash(data: unknown): void;
  /**
   * Called when an interrupted fiber is detected after restart.
   * Override to implement recovery (re-invoke work, notify clients, etc.).
   *
   * Internal framework fibers are filtered by `_handleInternalFiberRecovery`
   * before this hook runs — users only see their own fibers.
   *
   * Default: logs a warning.
   */
  onFiberRecovered(
    _ctx: FiberRecoveryContext
  ): Promise<void | FiberRecoveryResult>;
  /**
   * Override point for subclasses to handle internal (framework) fibers
   * before the user's recovery hook fires. Return `true` if handled.
   * @internal
   */
  protected _handleInternalFiberRecovery(
    _ctx: FiberRecoveryContext
  ): Promise<boolean>;
  /** @internal Detect fibers left by a dead process (runFiber system). */
  private _checkRunFibers;
  /** @internal */
  _onAlarmHousekeeping(): Promise<void>;
  private _isSameAgentPathPrefix;
  /**
   * Root-side scan for durable fibers owned by descendant facets.
   * `cf_agents_facet_runs` is only an index; actual snapshots and
   * recovery hooks live in each facet's own `cf_agents_runs` table.
   * @internal
   */
  private _checkFacetRunFibers;
  /**
   * Dispatch a runFiber recovery check into the facet identified by
   * `ownerPath`. Returns the number of remaining local `cf_agents_runs`
   * rows on the target facet after recovery.
   * @internal
   */
  _cf_checkRunFibersForFacet(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<number>;
  /**
   * Dispatch a scheduled callback into the facet identified by
   * `ownerPath`. Walks one step at a time: if `ownerPath` matches
   * `selfPath`, executes the callback locally; otherwise resolves
   * the next descendant facet and recurses through its own RPC.
   *
   * Called by the root's `alarm()` (which owns the physical alarm
   * for facet-owned schedules) and by intermediate facets while
   * walking down the chain.
   * @internal
   */
  _cf_dispatchScheduledCallback(
    ownerPath: ReadonlyArray<AgentPathStep>,
    row: ScheduleStorageRow
  ): Promise<boolean>;
  /**
   * Invoke an RPC method on this Agent or a descendant facet identified
   * by a root-first path. Used by AgentWorkflow to route callbacks and
   * `this.agent` calls back to the exact sub-agent that started a workflow.
   * @internal
   */
  _cf_invokeAgentPath(
    targetPath: ReadonlyArray<AgentPathStep>,
    method: string,
    args: unknown[]
  ): Promise<unknown>;
  /**
   * Recursively destroy a descendant facet identified by
   * `targetPath`. Walks down from `selfPath` until reaching the
   * target's immediate parent, where it cancels the target's
   * parent-owned schedules (and any descendants), removes the
   * target from the registry, and calls `ctx.facets.delete` to
   * wipe the target's storage.
   *
   * Called by a facet's own `destroy()` (via the root) so that
   * `this.destroy()` inside a sub-agent results in the same
   * cleanup as `parent.deleteSubAgent(Cls, name)` from the parent.
   * @internal
   */
  _cf_destroyDescendantFacet(
    targetPath: ReadonlyArray<AgentPathStep>
  ): Promise<void>;
  private _executeScheduleCallback;
  /**
   * Whether any runFiber recovery work is still outstanding: orphaned
   * `cf_agents_runs` rows left by a dead process (excluding fibers currently
   * executing in memory, which already hold a keepAlive ref) or managed
   * ledger fibers stuck in a non-terminal state with no live run row.
   *
   * Used by `_scheduleNextAlarm` to arm a follow-up alarm so multi-pass
   * recovery (e.g. after a scan-deadline yield, or while retrying a throwing
   * recovery hook) resumes instead of starving.
   * @internal
   */
  private _hasPendingFiberRecovery;
  private _scheduleNextAlarm;
  private _scheduleNextAlarmBody;
  /**
   * Override PartyServer's onAlarm hook as a no-op.
   * Agent handles alarm logic directly in the alarm() method override,
   * but super.alarm() calls onAlarm() after #ensureInitialized(),
   * so we suppress the default "Implement onAlarm" warning.
   */
  onAlarm(): void;
  /**
   * Method called when an alarm fires.
   * Executes any scheduled tasks that are due.
   *
   * Calls super.alarm() first to ensure PartyServer's #ensureInitialized()
   * runs, which resolves this.name from ctx.id.name (including for
   * facets, which are spawned with an explicit id so they have their
   * own ctx.id.name; pre-2026-03-15 alarms fall back to the legacy
   * __ps_name storage record) and calls onStart() if needed.
   *
   * @remarks
   * To schedule a task, please use the `this.schedule` method instead.
   * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
   */
  alarm(): Promise<void>;
  /**
   * The alarm body: PartyServer init + due-schedule processing + housekeeping +
   * next-alarm arm. Extracted from {@link alarm} so the memory-limit circuit
   * breaker can wrap it at the outermost frame (see {@link alarm}).
   */
  private _cf_runAlarmBody;
  /**
   * Durable storage key for the alarm memory-limit strike counter (#1825).
   */
  private static readonly _CF_OOM_ALARM_STRIKES_KEY;
  /**
   * The schedule row id currently executing in the alarm loop, so the
   * memory-limit circuit breaker can purge the exact looping row (#1825).
   * `undefined` outside a callback (e.g. an OOM from `super.alarm()`/onStart).
   */
  private _cf_executingScheduleRowId?;
  /**
   * The schedule-callback names whose alarm rows drive a recovery loop that can
   * deterministically OOM. The base agent has none; chat hosts (`Think`,
   * `AIChatAgent`) override this to return their recovery continuation callbacks
   * so the circuit breaker can surgically back them off / purge them WITHOUT
   * disturbing unrelated scheduled tasks. See {@link _cf_handleAlarmMemoryLimitReset}.
   */
  protected _cf_recoveryAlarmCallbacks(): string[];
  /**
   * Hook for a host to terminalize ("seal") any in-flight recovery work as an
   * out-of-memory exhaustion when the alarm circuit breaker trips at its strike
   * budget (#1825). Runs at the outermost alarm frame (post-unwind, so writes
   * can land). Default: no-op. Chat hosts override to fire `onExhausted` + the
   * terminal banner and persist the sealed incident.
   */
  protected _cf_sealMemoryLimitedRecovery(): Promise<void>;
  /**
   * Clear the durable memory-limit strike counter after a clean alarm so the
   * circuit breaker counts CONSECUTIVE resets rather than lifetime ones
   * (#1825). Reads first (cheap, usually cached) and only writes when a strike
   * is actually recorded, so the common no-strike path costs no write.
   * Best-effort: a stale strike only costs one extra tolerated spike later.
   */
  private _cf_clearAlarmMemoryLimitStrikes;
  /**
   * Alarm-boundary circuit breaker for Durable Object memory-limit resets
   * (#1825). The in-DO recovery budgets (`chatRecovery.maxOomRetries` /
   * `maxRecoveryWork`) only engage if their code runs AND its writes land; a
   * severe OOM can defeat both — thrown before the budget runs (boot hydration),
   * or its own small writes also OOM under memory pressure. In that case the
   * error reaches {@link alarm} and, unhandled, the platform auto-retries the
   * alarm indefinitely (re-running the doomed, billable turn each cycle).
   *
   * This runs at the OUTERMOST frame: the heavy turn has unwound and GC has
   * reclaimed its footprint, so the small writes here can land where mid-turn
   * ones (e.g. give-up's incident read) OOMed. A durable strike counter tolerates
   * a few resets (a transient spike may clear), backing off the recovery rows so
   * the retry is not a hot loop. At the `maxAlarmMemoryLimitStrikes` budget it
   * seals the recovery work and purges the looping rows so the loop — and the
   * bill — stops. Each step is best-effort: even these tiny writes can OOM, but
   * swallowing (not re-throwing) still halts the platform's auto-retry, and a
   * later wake re-arms legitimate schedules.
   */
  private _cf_handleAlarmMemoryLimitReset;
  /**
   * Intercept incoming HTTP/WS requests whose URL contains a
   * `/sub/{child-class}/{child-name}` marker and forward them to
   * the facet. The `onBeforeSubAgent` hook fires first (authorize,
   * mutate, or short-circuit). If the hook doesn't return a
   * Response, the framework resolves the facet and hands the
   * request off.
   *
   * After a WebSocket upgrade completes, subsequent frames route
   * directly to the child — the parent is only on the path for the
   * initial request.
   *
   * @experimental The API surface may change before stabilizing.
   */
  fetch(request: Request): Promise<Response>;
  broadcast(
    msg: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): void;
  getConnection<TState = unknown>(id: string): Connection<TState> | undefined;
  getConnections<TState = unknown>(tag?: string): Iterable<Connection<TState>>;
  private _cf_broadcastToParentSubAgent;
  _cf_broadcastToSubAgent(
    ownerPath: ReadonlyArray<AgentPathStep>,
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): Promise<void>;
  _cf_subAgentConnectionMetas(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<SubAgentConnectionMeta[]>;
  _cf_sendToSubAgentConnection(
    connectionId: string,
    message: string | ArrayBuffer | ArrayBufferView
  ): Promise<void>;
  _cf_closeSubAgentConnection(
    connectionId: string,
    code?: number,
    reason?: string
  ): Promise<void>;
  _cf_setSubAgentConnectionState(
    connectionId: string,
    state: unknown
  ): Promise<unknown>;
  private _cf_subAgentConnectionMetaForPath;
  private _cf_subAgentTargetPath;
  private _cf_subAgentPathFromOuterUri;
  private _isSameAgentPath;
  private _cf_connectionHasSubAgentTarget;
  protected _cf_connectionTargetsSubAgent(connection: Connection): boolean;
  /**
   * Returns true when the current request is addressed to a child facet of
   * this agent rather than to this agent itself.
   *
   * Chat-style subclasses wrap `onConnect` before the base Agent forwarding
   * wrapper runs, so they need a request-level check to avoid sending their
   * own protocol frames on sockets that are about to be forwarded to a child.
   */
  protected _cf_requestTargetsSubAgent(request: Request): boolean;
  private _cf_forwardSubAgentWebSocketConnect;
  private _cf_createSubAgentConnectionBridge;
  private _cf_forwardSubAgentWebSocketMessage;
  private _cf_forwardSubAgentWebSocketClose;
  private _cf_resolveSubAgentConnection;
  _cf_handleSubAgentWebSocketConnect(
    bridge: SubAgentConnectionBridge,
    meta: SubAgentConnectionMeta
  ): Promise<void>;
  _cf_handleSubAgentWebSocketMessage(
    message: WSMessage,
    bridge: SubAgentConnectionBridge,
    meta: SubAgentConnectionMeta
  ): Promise<void>;
  _cf_handleSubAgentWebSocketClose(
    code: number,
    reason: string,
    wasClean: boolean,
    bridge: SubAgentConnectionBridge,
    meta: SubAgentConnectionMeta
  ): Promise<void>;
  private _cf_runWithSubAgentBridge;
  private _cf_createSubAgentBridgeConnection;
  private _cf_storeVirtualSubAgentConnection;
  protected _cf_hydrateSubAgentConnectionsFromRoot(): Promise<void>;
  private _cf_getRawConnectionState;
  private _cf_getForwardedSubAgentState;
  /**
   * Parent-side middleware hook. Fires before a request is
   * forwarded into a facet sub-agent. Mirrors `onBeforeConnect` /
   * `onBeforeRequest`.
   *
   *   - return `void` (default) → forward the original request
   *   - return `Request`        → forward this (modified) request
   *   - return `Response`       → return this response to the
   *                               client; do not wake the child
   *
   * Default implementation: return void (permissive).
   *
   * The hook receives the **original** request with its URL intact —
   * including the `/sub/{class}/{name}` segment. The routing
   * decision for which facet to wake is fixed at parse time, so if
   * you return a modified `Request`, its headers, body, method, and
   * query string flow through to the child, but the **pathname**
   * the child sees is always the tail after `/sub/{class}/{name}`.
   * Customize via headers/body rather than URL-rewriting.
   *
   * WebSocket upgrade requests flow through this hook the same way as
   * plain HTTP. If you return a mutated `Request`, make sure it still
   * carries the original `Upgrade: websocket` and `Sec-WebSocket-*`
   * headers — the simplest safe recipe is to clone the incoming
   * request's headers (via `new Headers(req.headers)`) and only add
   * or replace entries, rather than constructing a fresh `Headers`
   * object from scratch.
   *
   * @experimental The API surface may change before stabilizing.
   *
   * @example
   * ```ts
   * class Inbox extends Agent {
   *   override async onBeforeSubAgent(req, { className, name }) {
   *     // Strict registry gate
   *     if (!this.hasSubAgent(className, name)) {
   *       return new Response("Not found", { status: 404 });
   *     }
   *   }
   * }
   * ```
   */
  onBeforeSubAgent(
    _request: Request,
    _child: {
      className: string;
      name: string;
    }
  ): Promise<Request | Response | void>;
  /**
   * Resolve the facet Fetcher for the match and forward the
   * request to it with `/sub/{class}/{name}` stripped.
   *
   * @internal
   */
  private _cf_forwardToFacet;
  /**
   * Bridge method used by `getSubAgentByName`. Resolves the facet
   * on each call (idempotent via `subAgent`) and dispatches one
   * RPC method. Stateless — no cached references.
   *
   * @internal
   */
  _cf_invokeSubAgent(
    className: string,
    name: string,
    method: string,
    args: unknown[]
  ): Promise<unknown>;
  /**
   * Bridge method used by `parentAgent()` when the requested parent is
   * itself a facet (and therefore has no top-level env namespace).
   * The root receives the full root-first target path, then each hop
   * delegates to the next facet using that facet's own `ctx.facets`.
   *
   * @internal
   */
  _cf_invokeSubAgentPath(
    path: ReadonlyArray<{
      className: string;
      name: string;
    }>,
    method: string,
    args: unknown[]
  ): Promise<unknown>;
  private _cf_invokeStubMethod;
  /**
   * Initialize this agent as a facet in a single RPC.
   *
   * Runs entirely inside the child's isolate, so every storage write
   * and `onStart()` I/O is owned by the child DO. This replaces the
   * previous "construct a Request in the parent DO and `stub.fetch()`
   * it on the child" handshake, whose native I/O was tied to the
   * parent and triggered "Cannot perform I/O on behalf of a different
   * Durable Object" on the child.
   *
   * We set `_isFacet` eagerly (before `__unsafe_ensureInitialized`
   * runs `onStart()`) so any code that legitimately branches on it
   * — e.g. skipping parent-owned alarms in schedule guards — sees
   * the flag during the first `onStart()` run. Protocol broadcasts are
   * suppressed only during this bootstrap window; afterward, facets can
   * broadcast to their own WebSocket clients reached via sub-agent
   * routing.
   *
   * The facet's logical name is persisted separately from its routing id.
   * Legacy facets used the logical name directly as `ctx.id.name`; newer
   * facets can use path-scoped routing ids while preserving `this.name`.
   *
   * @internal Called by {@link subAgent}.
   */
  _cf_initAsFacet(
    name: string,
    parentPath?: ReadonlyArray<{
      className: string;
      name: string;
    }>,
    identityName?: string
  ): Promise<void>;
  get name(): string;
  /**
   * Ancestor chain for this agent, root-first. Empty for top-level
   * DOs. Populated at facet init time; survives hibernation.
   *
   * @example
   * ```ts
   * class Chat extends Agent {
   *   onStart() {
   *     console.log("chat started under:", this.parentPath);
   *     // → [{ className: "Tenant", name: "acme" }, { className: "Inbox", name: "alice" }]
   *   }
   * }
   * ```
   *
   * @experimental The API surface may change before stabilizing.
   */
  get parentPath(): ReadonlyArray<{
    className: string;
    name: string;
  }>;
  /**
   * Ancestor chain + self, root-first. Convenient for logging.
   *
   * @experimental The API surface may change before stabilizing.
   */
  get selfPath(): ReadonlyArray<{
    className: string;
    name: string;
  }>;
  /**
   * Resolve a typed parent stub for this facet's **immediate** parent
   * agent.
   *
   * Symmetric with `subAgent(Cls, name)`: while `subAgent` opens a
   * stub from parent to child, `parentAgent` opens one from child
   * to parent. Pass the direct parent's class reference — the
   * framework verifies it matches the last entry of
   * `this.parentPath` at runtime. If the parent is a top-level
   * Durable Object, the framework returns the normal namespace stub.
   * If the parent is itself a facet, the framework returns a bridge
   * proxy that routes method calls through the root/supervisor and
   * then down the recorded facet path.
   *
   * `this.parentPath` is root-first, so the direct parent is the
   * **last** entry: `this.parentPath.at(-1)`. For grandparents and
   * further ancestors, iterate `this.parentPath` and use
   * `getAgentByName(env.X, this.parentPath[i].name)` directly.
   *
   * For top-level parents, the framework first checks `env[Cls.name]`,
   * then falls back to the Worker `exports` object. This supports
   * custom binding names as long as the parent class is exported under
   * its class name.
   *
   * Facet-parent stubs route normal HTTP `.fetch()` calls through the
   * same root bridge as RPC methods. WebSocket upgrade requests are
   * not supported yet because WebSocket handles cannot be serialized
   * over RPC.
   *
   * @experimental The API surface may change before stabilizing.
   *
   * @throws If this agent is not a facet (no parent).
   * @throws If `Cls.name` doesn't match the recorded direct-parent
   *         class (guards against accidentally reaching the wrong
   *         DO, especially in nested Root → Mid → Leaf chains).
   * @throws If no namespace is found for a top-level parent, or no
   *         root namespace is available for a facet parent bridge.
   *
   * @example
   * ```ts
   * class Chat extends AIChatAgent<Env> {
   *   async onChatMessage(...) {
   *     const inbox = await this.parentAgent(Inbox);
   *     const memory = await inbox.getSharedMemory("facts");
   *     // ...
   *   }
   * }
   * ```
   */
  parentAgent<T extends Agent>(
    cls: SubAgentClass<T>
  ): Promise<DurableObjectStub<T>>;
  private _cf_getTopLevelNamespaceByClassName;
  private _cf_asDurableObjectNamespace;
  private _cf_parentAgentFacetProxy;
  private _cf_isWebSocketUpgradeRequest;
  /**
   * Get or create a named sub-agent — a child Durable Object (facet)
   * with its own isolated SQLite storage running on the same machine.
   *
   * The child class must extend `Agent` and be exported from the worker
   * entry point. The first call for a given name triggers the child's
   * `onStart()`. Subsequent calls return the existing instance.
   *
   * @experimental The API surface may change before stabilizing.
   *
   * @param cls The Agent subclass (must be exported from the worker)
   * @param name Unique name for this child instance
   * @returns A typed RPC stub for calling methods on the child
   *
   * @example
   * ```typescript
   * const searcher = await this.subAgent(SearchAgent, "main-search");
   * const results = await searcher.search("cloudflare agents");
   * ```
   */
  subAgent<T extends Agent>(
    cls: SubAgentClass<T>,
    name: string
  ): Promise<SubAgentStub<T>>;
  /** Maximum number of non-terminal agent-tool runs this parent may own at once. */
  maxConcurrentAgentTools: number;
  onAgentToolStart(_run: AgentToolRunInfo): Promise<void>;
  onAgentToolFinish(
    _run: AgentToolRunInfo,
    _result: AgentToolLifecycleResult
  ): Promise<void>;
  /**
   * Parent hook fired (best-effort) whenever a child agent-tool run emits a
   * `reportProgress` signal that is forwarded through this parent's tail. Use it
   * to meter / steer / surface progress server-side. Fires for both awaited and
   * detached runs; it is NOT durable — after eviction a detached run's latest
   * snapshot is read from `inspectAgentToolRun().progress` on reconcile instead.
   */
  onProgress(
    _run: AgentToolRunInfo,
    _progress: AgentToolProgressSnapshot
  ): Promise<void>;
  /**
   * Emit an ephemeral progress signal from a sub-agent that is currently running
   * as an agent tool. Rides the child's active turn stream as a transient
   * `data-agent-progress` part (re-broadcast to the parent's clients + surfaced
   * in `useAgentToolEvents`) and persists a latest-wins snapshot for recovery /
   * inspection. A no-op (with a dev warning) on the base `Agent`, which has no
   * streaming turn — overridden by chat hosts (`@cloudflare/think`,
   * `AIChatAgent`). See `design/rfc-detached-agent-tools.md`.
   */
  reportProgress<T = unknown>(
    _progress: AgentToolProgress<T>,
    _options?: {
      persist?: boolean;
    }
  ): Promise<void>;
  runAgentTool<Input = unknown>(
    cls: ChatCapableAgentClass,
    options: RunAgentToolOptions<Input> & {
      detached: true | DetachedAgentToolConfig;
    }
  ): Promise<DetachedRunAgentToolResult>;
  runAgentTool<Input = unknown, Output = unknown>(
    cls: ChatCapableAgentClass,
    options: RunAgentToolOptions<Input>
  ): Promise<RunAgentToolResult<Output>>;
  /**
   * Cancel an agent-tool run by id. Idempotent: cancelling an already-terminal
   * run is a no-op. Detached runs deliver through the guarded ledger so a wired
   * `onFinish` fires once with `status: "aborted"`; awaited runs leave terminal
   * observation to the awaiting/recovery path, avoiding duplicate finish hooks.
   */
  cancelAgentTool(runId: string, reason?: unknown): Promise<void>;
  /**
   * Parse + validate the `detached` option. Returns `null` for a non-detached
   * run, or the normalized config (with the validated `onFinish` method name)
   * for a detached one. Throws if `onFinish` does not name a method on this
   * agent — closures cannot survive Durable Object eviction, so the durable
   * hook is referenced by method name (the same contract as `schedule`).
   */
  private _parseDetachedOption;
  private _isAgentToolRowHardTerminal;
  private _hasOutstandingDetachedRuns;
  /** Detached runs still holding a concurrency slot (non-terminal). */
  private _liveDetachedRunCount;
  /**
   * Edge-triggered warning when live detached runs cross
   * `DETACHED_LIVE_COUNT_WARN_THRESHOLD`. Fires once on the up-crossing and
   * re-arms only after the count falls back below the threshold, so a parent
   * accumulating long-lived background runs surfaces a signal without spamming.
   */
  private _maybeWarnDetachedLiveCount;
  /**
   * Warm fast path for a detached run: tail the child to terminal (so the
   * parent re-broadcasts its live stream to clients) and deliver the completion
   * with low latency while the isolate stays alive. Best-effort — the durable
   * `_cfDetachedReconcileTick` backbone is the guarantee; anything this misses
   * (eviction, a child that has not yet reached terminal) the backbone collects.
   */
  private _detachedFastPath;
  /**
   * Single delivery funnel for a detached terminal. Both the warm fast path and
   * the durable backbone route through here, with INDEPENDENT ledger slots for
   * `finish` (the real terminal) vs `give_up` (budget exhausted). Each slot is
   * delivered at-least-once via a claim + lease:
   *
   * - Concurrent double-fire is prevented by the guarded CAS claim (RETURNING
   *   yields the row only to the winner).
   * - A crash after the side effect but before `*_delivered_at` is written lets
   *   the lease expire so a later reconcile re-delivers — hence handlers must be
   *   idempotent.
   * - Two slots, not one, because `interrupted` is SOFT: a give-up followed by a
   *   real completion is legitimate, and a single shared "delivered" bit would
   *   dedupe the child's real late result away (the #1752 production incident).
   */
  private _deliverDetachedTerminal;
  private _safeRunOnError;
  /**
   * Run a detached terminal delivery (the `onAgentToolFinish` + per-run
   * `onFinish` callbacks) in an appropriate execution context. The base `Agent`
   * has no turn queue, so it only establishes `agentContext` — a handler that
   * calls `runAgentTool` / `setState` therefore works regardless of where the
   * delivery fired from.
   *
   * Chat-layer subclasses (`@cloudflare/think`, `@cloudflare/ai-chat`) override
   * this to additionally serialize delivery against their turn queue when
   * `serialize` is set: a fast-path push or backbone tick can land mid-turn, and
   * a state-mutating `onFinish` running concurrently with an active LLM turn is a
   * data race. The fast path and backbone never run synchronously inside a turn
   * (they fire from `waitUntil` / a scheduled alarm), so enqueuing them on the
   * turn queue is deadlock-free. An explicit `cancelAgentTool` runs with
   * `serialize` unset because it may be called from inside the very turn that
   * triggers it, where enqueuing would self-deadlock.
   */
  protected _runDetachedDelivery(
    invoke: () => Promise<void>,
    _options?: {
      serialize?: boolean;
    }
  ): Promise<void>;
  /**
   * Arm the self-scheduling detached reconcile backbone. Existing schedules are
   * reused for recovery/startup calls, but a fresh detached dispatch resets the
   * pending cadence to the fast end so new work is noticed promptly.
   */
  private _armDetachedBackbone;
  private _armDetachedBackboneInner;
  /**
   * Durable backbone for detached runs. Runs on a self-rescheduling alarm:
   * collects any detached run that has reached terminal but was not yet
   * delivered (e.g. the parent was evicted before the fast path landed), gives
   * up on any run past its absolute budget (tearing the child down), and
   * reschedules itself while any detached run remains undelivered — cancelling
   * itself once everything has settled (zero steady-state cost).
   */
  _cfDetachedReconcileTick(payload?: DetachedReconcilePayload): Promise<void>;
  hasAgentToolRun<T extends Agent>(
    cls: SubAgentClass<T>,
    runId: string
  ): boolean;
  hasAgentToolRun(agentType: string, runId: string): boolean;
  clearAgentToolRuns(options?: {
    olderThan?: number;
    status?: AgentToolRunStatus[];
  }): Promise<void>;
  private _isAgentToolTerminal;
  private _activeAgentToolRunCount;
  private _defaultAgentToolPreview;
  private _readAgentToolRun;
  /**
   * Reconstruct the typed interrupted cause (`reason` / `childStillRunning`,
   * #1630 follow-up) from a stored row so a row→result/event rebuild — e.g. a
   * reconnect replay — carries the same fields a live client saw. Only
   * `interrupted` rows store a cause; everything else yields `{}` (the columns
   * are cleared whenever a row settles to a hard terminal).
   */
  private _agentToolInterruptedExtrasFromRow;
  private _resultFromAgentToolRow;
  private _agentToolRunInfoFromRow;
  private _terminalResultFromInspection;
  private _finishAgentToolRun;
  private _runDeferredAgentToolFinishHooks;
  private _updateAgentToolTerminal;
  private _markAgentToolRunning;
  private _parseAgentToolJson;
  private _stringifyAgentToolOutput;
  private _broadcastAgentToolEvent;
  private _broadcastAgentToolChunks;
  private _broadcastAgentToolStoredChunks;
  private _broadcastAgentToolStoredChunksFromAdapter;
  private _forwardAgentToolStream;
  /**
   * Hook invoked by `_forwardAgentToolStream` after a child produces output that
   * was forwarded to the parent's connections. Forwarding a sub-agent's stream
   * is genuine forward progress for the *parent* turn (the parent is
   * orchestrating the child), so chat-recovery subclasses (Think / AIChatAgent)
   * override this to advance their recovery progress marker.
   *
   * Without it, a parent whose turn merely `await`s a sub-agent banks zero
   * progress of its own, so under deploy churn the parent's no-progress recovery
   * window exhausts and abandons the turn as `interrupted` — even though the
   * child is healthily streaming and ultimately completes (observed in the
   * `deploy-churn --mode subagent` harness: `attempt 6/6, stable_timeout,
   * progress: 1`).
   *
   * Called ONLY after at least one chunk was actually forwarded — never merely
   * because a child is attached — so a silent / hung child still lets the parent
   * exhaust on its own timer. The base Agent has no recovery budget, so this is
   * a no-op; subclasses should throttle the (durable) bump since this can be
   * called repeatedly while a child streams.
   */
  protected _onAgentToolStreamProgress(): Promise<void>;
  /**
   * Best-effort observation of a forwarded child chunk: if it is a reserved
   * `data-agent-progress` frame, refresh the cached liveness timestamp on the
   * run row (a hint for a still-warm parent) and fire the public `onProgress`
   * hook. Never throws into the forward loop — the child's own persisted
   * snapshot (read via `inspectAgentToolRun`) remains authoritative for the
   * resetting no-progress budget after eviction.
   */
  private _observeForwardedProgress;
  /**
   * Deliver a milestone notification IF this run opted into it via
   * `detached: { onMilestones }` and the milestone name is in that set. Routes
   * to the overridable `_deliverDetachedMilestone` seam (a no-op on the base
   * `Agent`; chat hosts inject an idempotent synthetic chat message).
   */
  private _maybeDeliverDetachedMilestone;
  /**
   * Overridable seam for the `detached: { onMilestones }` convenience. The base
   * `Agent` has no chat surface, so this is a no-op; chat hosts
   * (`@cloudflare/think`, `AIChatAgent`) override it to submit an idempotent
   * synthetic message keyed on `(runId, milestone.name)`. Called from both the
   * warm tail and the backbone reconcile, so it MUST be idempotent.
   */
  protected _deliverDetachedMilestone(
    _run: AgentToolRunInfo,
    _milestone: AgentToolMilestone,
    _mode: "react" | "narrate"
  ): Promise<void>;
  private _broadcastAgentToolTerminal;
  private _asAgentToolChildAdapter;
  private _agentToolClassByName;
  private _replayAndInterruptAgentToolRun;
  /**
   * Human-readable prose for an `interrupted` seal. Kept in sync with
   * {@link AgentToolInterruptedReason}; callers branch on the typed `reason`
   * field, not this string.
   */
  private _interruptedMessageForReason;
  /**
   * Tear down a child agent-tool run the parent has genuinely given up on
   * (#1630 follow-up). Teardown is scoped to `window-exceeded` ONLY — the hard
   * ceiling, where the child has had its full recovery window and is therefore
   * truly exhausted, so cancelling it reclaims its fiber / keep-alive. Every
   * other give-up is deliberately left repairable: `no-progress` seals stay
   * SOFT (`interrupted`, `childStillRunning: true`) so a re-issue can still
   * re-attach and collect the child if it self-heals — tearing those down would
   * defeat the repair-on-re-issue path and convert a retryable interrupt into a
   * non-retryable `aborted`. Reasons where the child's state is unknown
   * (`inspect-*`, `recovery-deadline`, `not-tailable`) are also left alone.
   * Returns whether the child was torn down (so the caller reports
   * `childStillRunning: false`).
   */
  private _teardownGivenUpAgentToolChild;
  /**
   * Re-attach to a still-running child agent-tool run and tail it to its real
   * terminal result, instead of abandoning it as `interrupted` (#1630). The
   * child is a separate facet with its own `chatRecovery`, so resolving it via
   * the adapter wakes it and lets it self-complete the interrupted turn; we tail
   * its live stream (forwarding chunks to the parent's connections) until it
   * reaches terminal, then inspect for the collected result.
   *
   * The wait is PROGRESS-KEYED, not a flat wall clock (which previously abandoned
   * healthy, still-advancing children whose recovery simply outran a fixed
   * budget). `noProgressTimeoutMs` bounds how long the parent waits with NO
   * forward progress; it is reset on every forwarded chunk. As long as the child
   * keeps streaming it is followed through to terminal. The loop also RE-ARMS
   * across stream-closes (a child re-evicted mid-recovery, or a tail that ends
   * before terminal) as long as the prior attempt made progress, so a child that
   * dies and recovers again during deploy churn is still collected. A genuinely
   * silent/hung child can never block recovery forever: it seals `interrupted`
   * after one `noProgressTimeoutMs` window. `maxWindowMs` is an OPTIONAL hard
   * wall-clock ceiling (default `Infinity` — uncapped, mirroring #1672's
   * `maxRecoveryWork`); set it finite to also bound a child that keeps
   * progressing, which seals `window-exceeded` and tears the child down.
   *
   * Returns the terminal `result` (and `completedAt`) when the child reaches a
   * terminal status, plus the advanced broadcast `sequence`. Returns
   * `{ result: undefined }` when there is no `tailAgentToolRun` adapter, the
   * child makes no progress within a full no-progress window, or the ceiling is
   * reached while the child is still non-terminal — the caller then seals
   * `interrupted`.
   */
  private _reattachAgentToolRunToTerminal;
  private _replayAgentToolRuns;
  private _reconcileAgentToolRuns;
  private _inspectAgentToolRunForRecovery;
  private _scheduleAgentToolRunRecovery;
  private _agentToolRunRecoveryRunIds;
  private _getAgentToolChunksForRecovery;
  /**
   * Shared facet resolution — takes a CamelCase class name string
   * (matching `ctx.exports`) rather than a class reference. Both
   * `subAgent(cls, name)` and `_cf_invokeSubAgent(className, ...)`
   * funnel through here so registry bookkeeping and the
   * `_cf_initAsFacet` handshake are consistent.
   *
   * @internal
   */
  private _cf_resolveSubAgent;
  /**
   * Forcefully abort a running sub-agent. The child stops executing
   * immediately and will be restarted on next {@link subAgent} call.
   * Pending RPC calls receive the reason as an error.
   * Transitively aborts the child's own children.
   *
   * @experimental The API surface may change before stabilizing.
   *
   * @param cls The Agent subclass used when creating the child
   * @param name Name of the child to abort
   * @param reason Error thrown to pending/future RPC callers
   */
  abortSubAgent(cls: SubAgentClass, name: string, reason?: unknown): void;
  /**
   * Delete a sub-agent: abort it if running, then permanently wipe its
   * storage. Transitively deletes the child's own children.
   *
   * @experimental The API surface may change before stabilizing.
   *
   * @param cls The Agent subclass used when creating the child
   * @param name Name of the child to delete
   */
  deleteSubAgent(cls: SubAgentClass, name: string): Promise<void>;
  /** @internal */
  private _subAgentRegistryReady;
  private _addColumnIfNotExists;
  /** @internal */
  private _ensureSubAgentRegistry;
  /** @internal */
  private _recordSubAgent;
  /** @internal */
  private _subAgentRegistryRow;
  private _cf_subAgentIdentity;
  /** @internal */
  private _forgetSubAgent;
  /**
   * Whether this agent has previously spawned (and not deleted) a
   * sub-agent of the given class and name. Backed by an
   * auto-maintained SQLite registry in the parent's storage.
   *
   * Intended for strict-registry access patterns in
   * `onBeforeSubAgent` or similar gating logic.
   *
   * @experimental The API surface may change before stabilizing.
   *
   * @example
   * ```ts
   * async onBeforeSubAgent(req, { className, name }) {
   *   if (!this.hasSubAgent(className, name)) {
   *     return new Response("Not found", { status: 404 });
   *   }
   * }
   * ```
   */
  hasSubAgent<T extends Agent>(cls: SubAgentClass<T>, name: string): boolean;
  hasSubAgent(className: string, name: string): boolean;
  /**
   * List known sub-agents, optionally filtered by class. Reflects
   * the registry rows written by {@link subAgent} and removed by
   * {@link deleteSubAgent}.
   *
   * @experimental The API surface may change before stabilizing.
   */
  listSubAgents<T extends Agent>(
    cls: SubAgentClass<T>
  ): Array<{
    className: string;
    name: string;
    createdAt: number;
  }>;
  listSubAgents(className?: string): Array<{
    className: string;
    name: string;
    createdAt: number;
  }>;
  /**
   * Destroy the Agent, removing all state and scheduled tasks.
   *
   * On a top-level agent: drops every table, clears the alarm, and
   * aborts the isolate.
   *
   * On a sub-agent (facet): delegates teardown to the immediate
   * parent so the parent-owned schedule rows for this sub-agent
   * (and any of its descendants) are cancelled, the parent's
   * `cf_agents_sub_agents` registry entry is cleared, and
   * `ctx.facets.delete` wipes the facet's own storage. The
   * `ctx.facets.delete` call aborts this isolate, so this method
   * may not return cleanly when invoked from inside the facet —
   * callers should treat it as fire-and-forget.
   */
  destroy(): Promise<void>;
  /**
   * @internal Defer this agent's destruction to its own alarm invocation
   * instead of running it inline (#1625).
   *
   * `destroy()` is a multi-step I/O sequence (drop tables, delete alarm,
   * delete all storage, dispose connections). Running it on the `waitUntil`
   * of a request whose client has already disconnected — the MCP
   * Streamable-HTTP session-DELETE path — gives it little to no
   * post-invocation grace, so the runtime routinely cancels it mid-flight.
   * This method instead performs two fast storage writes (a durable
   * "condemned" marker and an immediate alarm) that the caller can await
   * before responding; the alarm then fires as a fresh invocation with its
   * own full execution budget and runs `destroy()` there. If even that
   * invocation is interrupted, the marker survives and the next wake
   * finishes teardown — see the `alarm()` preamble.
   *
   * Unlike `destroy()`, this method does not abort the isolate, so RPC
   * callers don't need to swallow an abort error.
   */
  _cf_scheduleDestroy(): Promise<void>;
  /**
   * Whether a (deferred or interrupted) destroy is pending. Reads the
   * durable marker directly — the in-memory `_isFacet` flag may not be
   * hydrated yet at the call sites, but facets never write the marker.
   */
  private _hasPendingDestroy;
  /** @internal Drop every internal Agents SDK table during top-level destroy. */
  protected _dropInternalTablesForDestroy(): void;
  /**
   * Check if a method is callable
   * @param method The method name to check
   * @returns True if the method is marked as callable
   */
  private _isCallable;
  /**
   * Get all methods marked as callable on this Agent
   * @returns A map of method names to their metadata
   */
  getCallableMethods(): Map<string, CallableMetadata>;
  /**
   * Start a workflow and track it in this Agent's database.
   * Automatically injects agent identity into the workflow params.
   *
   * The originating Agent identity is persisted in the workflow params so
   * callbacks (`this.agent` RPC, progress/completion/error, state updates)
   * route back to the exact Agent or sub-agent facet that started the run.
   * Note the following constraints:
   *
   * - **Resolution is by name.** Callbacks re-resolve the originating Agent via
   *   `getAgentByName(...)`. Agents addressed by a raw Durable Object id
   *   (`idFromString`/`get(id)`) rather than by name will not receive
   *   callbacks on the same instance.
   * - **Sub-agent runs are facet-local.** A workflow started from a sub-agent
   *   is tracked in that facet's own storage; the parent's `getWorkflows()` /
   *   `getWorkflowById()` do not see it. Aggregate across facets yourself if
   *   you need a combined view.
   * - **Class names must survive bundling.** The originating path is keyed by
   *   `constructor.name`. Ensure your bundler preserves class names
   *   (e.g. esbuild `keepNames: true`) so callbacks can be routed.
   *
   * @template P - Type of params to pass to the workflow
   * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
   * @param params - Params to pass to the workflow
   * @param options - Optional workflow options. For sub-agents, pass
   *   `agentBinding` as the **root** Agent's Durable Object binding name, not a
   *   child binding.
   * @returns The workflow instance ID
   *
   * @example
   * ```typescript
   * const workflowId = await this.runWorkflow(
   *   'MY_WORKFLOW',
   *   { taskId: '123', data: 'process this' }
   * );
   * ```
   */
  runWorkflow<P = unknown>(
    workflowName: WorkflowName<Env>,
    params: P,
    options?: RunWorkflowOptions
  ): Promise<string>;
  /**
   * Send an event to a running workflow.
   * The workflow can wait for this event using step.waitForEvent().
   *
   * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
   * @param workflowId - ID of the workflow instance
   * @param event - Event to send
   *
   * @example
   * ```typescript
   * await this.sendWorkflowEvent(
   *   'MY_WORKFLOW',
   *   workflowId,
   *   { type: 'approval', payload: { approved: true } }
   * );
   * ```
   */
  sendWorkflowEvent(
    workflowName: WorkflowName<Env>,
    workflowId: string,
    event: WorkflowEventPayload
  ): Promise<void>;
  /**
   * Approve a waiting workflow.
   * Sends an approval event to the workflow that can be received by waitForApproval().
   *
   * @param workflowId - ID of the workflow to approve
   * @param data - Optional approval data (reason, metadata)
   *
   * @example
   * ```typescript
   * await this.approveWorkflow(workflowId, {
   *   reason: 'Approved by admin',
   *   metadata: { approvedBy: userId }
   * });
   * ```
   */
  approveWorkflow(
    workflowId: string,
    data?: {
      reason?: string;
      metadata?: Record<string, unknown>;
    }
  ): Promise<void>;
  /**
   * Reject a waiting workflow.
   * Sends a rejection event to the workflow that will cause waitForApproval() to throw.
   *
   * @param workflowId - ID of the workflow to reject
   * @param data - Optional rejection data (reason)
   *
   * @example
   * ```typescript
   * await this.rejectWorkflow(workflowId, {
   *   reason: 'Request denied by admin'
   * });
   * ```
   */
  rejectWorkflow(
    workflowId: string,
    data?: {
      reason?: string;
    }
  ): Promise<void>;
  /**
   * Terminate a running workflow.
   * This immediately stops the workflow and sets its status to "terminated".
   *
   * @param workflowId - ID of the workflow to terminate (must be tracked via runWorkflow)
   * @throws Error if workflow not found in tracking table
   * @throws Error if workflow binding not found in environment
   * @throws Error if workflow is already completed/errored/terminated (from Cloudflare)
   *
   * @example
   * ```typescript
   * await this.terminateWorkflow(workflowId);
   * ```
   */
  terminateWorkflow(workflowId: string): Promise<void>;
  /**
   * Pause a running workflow.
   * The workflow can be resumed later with resumeWorkflow().
   *
   * @param workflowId - ID of the workflow to pause (must be tracked via runWorkflow)
   * @throws Error if workflow not found in tracking table
   * @throws Error if workflow binding not found in environment
   * @throws Error if workflow is not running (from Cloudflare)
   *
   * @example
   * ```typescript
   * await this.pauseWorkflow(workflowId);
   * ```
   */
  pauseWorkflow(workflowId: string): Promise<void>;
  /**
   * Resume a paused workflow.
   *
   * @param workflowId - ID of the workflow to resume (must be tracked via runWorkflow)
   * @throws Error if workflow not found in tracking table
   * @throws Error if workflow binding not found in environment
   * @throws Error if workflow is not paused (from Cloudflare)
   *
   * @example
   * ```typescript
   * await this.resumeWorkflow(workflowId);
   * ```
   */
  resumeWorkflow(workflowId: string): Promise<void>;
  /**
   * Restart a workflow instance.
   * This re-runs the workflow from the beginning with the same ID.
   *
   * @param workflowId - ID of the workflow to restart (must be tracked via runWorkflow)
   * @param options - Optional settings
   * @param options.resetTracking - If true (default), resets created_at and clears error fields.
   *                                If false, preserves original timestamps.
   * @throws Error if workflow not found in tracking table
   * @throws Error if workflow binding not found in environment
   *
   * @example
   * ```typescript
   * // Reset tracking (default)
   * await this.restartWorkflow(workflowId);
   *
   * // Preserve original timestamps
   * await this.restartWorkflow(workflowId, { resetTracking: false });
   * ```
   */
  restartWorkflow(
    workflowId: string,
    options?: {
      resetTracking?: boolean;
    }
  ): Promise<void>;
  /**
   * Find a workflow binding by its name.
   */
  private _findWorkflowBindingByName;
  /**
   * Get all workflow binding names from the environment.
   */
  private _getWorkflowBindingNames;
  /**
   * Get the status of a workflow and update the tracking record.
   *
   * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')
   * @param workflowId - ID of the workflow instance
   * @returns The workflow status
   */
  getWorkflowStatus(
    workflowName: WorkflowName<Env>,
    workflowId: string
  ): Promise<InstanceStatus>;
  /**
   * Get a tracked workflow by ID.
   *
   * @param workflowId - Workflow instance ID
   * @returns Workflow info or undefined if not found
   */
  getWorkflow(workflowId: string): WorkflowInfo | undefined;
  /**
   * Query tracked workflows with cursor-based pagination.
   *
   * @param criteria - Query criteria including optional cursor for pagination
   * @returns WorkflowPage with workflows, total count, and next cursor
   *
   * @example
   * ```typescript
   * // First page
   * const page1 = this.getWorkflows({ status: 'running', limit: 20 });
   *
   * // Next page
   * if (page1.nextCursor) {
   *   const page2 = this.getWorkflows({
   *     status: 'running',
   *     limit: 20,
   *     cursor: page1.nextCursor
   *   });
   * }
   * ```
   */
  getWorkflows(criteria?: WorkflowQueryCriteria): WorkflowPage;
  /**
   * Count workflows matching criteria (for pagination total).
   */
  private _countWorkflows;
  /**
   * Encode a cursor from workflow info for pagination.
   * Stores createdAt as Unix timestamp in seconds (matching DB storage).
   */
  private _encodeCursor;
  /**
   * Decode a pagination cursor.
   * Returns createdAt as Unix timestamp in seconds (matching DB storage).
   */
  private _decodeCursor;
  /**
   * Delete a workflow tracking record.
   *
   * @param workflowId - ID of the workflow to delete
   * @returns true if a record was deleted, false if not found
   */
  deleteWorkflow(workflowId: string): boolean;
  /**
   * Delete workflow tracking records matching criteria.
   * Useful for cleaning up old completed/errored workflows.
   *
   * @param criteria - Criteria for which workflows to delete
   * @returns Number of records matching criteria (expected deleted count)
   *
   * @example
   * ```typescript
   * // Delete all completed workflows created more than 7 days ago
   * const deleted = this.deleteWorkflows({
   *   status: 'complete',
   *   createdBefore: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
   * });
   *
   * // Delete all errored and terminated workflows
   * const deleted = this.deleteWorkflows({
   *   status: ['errored', 'terminated']
   * });
   * ```
   */
  deleteWorkflows(
    criteria?: Omit<WorkflowQueryCriteria, "limit" | "orderBy"> & {
      createdBefore?: Date;
    }
  ): number;
  /**
   * Migrate workflow tracking records from an old binding name to a new one.
   * Use this after renaming a workflow binding in wrangler.toml.
   *
   * @param oldName - Previous workflow binding name
   * @param newName - New workflow binding name
   * @returns Number of records migrated
   *
   * @example
   * ```typescript
   * // After renaming OLD_WORKFLOW to NEW_WORKFLOW in wrangler.toml
   * async onStart() {
   *   const migrated = this.migrateWorkflowBinding('OLD_WORKFLOW', 'NEW_WORKFLOW');
   * }
   * ```
   */
  migrateWorkflowBinding(oldName: string, newName: string): number;
  /**
   * Update workflow tracking record from InstanceStatus
   */
  private _updateWorkflowTracking;
  /**
   * Convert a database row to WorkflowInfo
   */
  private _rowToWorkflowInfo;
  private _workflowOrigin;
  private _findAgentBindingNameForClass;
  private _findBindingNameForNamespace;
  private _restoreRpcMcpServers;
  /**
   * Handle a callback from a workflow.
   * Invoked via the internal `_workflow_handleCallback` RPC whenever an
   * {@link AgentWorkflow} reports progress, completion, an error, or a custom
   * event back to its originating Agent (or sub-agent facet).
   * Override this to handle all callback types in one place.
   *
   * @param callback - The callback payload
   */
  onWorkflowCallback(callback: WorkflowCallback): Promise<void>;
  /**
   * Called when a workflow reports progress.
   * Override to handle progress updates.
   *
   * @param workflowName - Workflow binding name
   * @param workflowId - ID of the workflow
   * @param progress - Typed progress data (default: DefaultProgress)
   */
  onWorkflowProgress(
    workflowName: string,
    workflowId: string,
    progress: unknown
  ): Promise<void>;
  /**
   * Called when a workflow completes successfully.
   * Override to handle completion.
   *
   * @param workflowName - Workflow binding name
   * @param workflowId - ID of the workflow
   * @param result - Optional result data
   */
  onWorkflowComplete(
    workflowName: string,
    workflowId: string,
    result?: unknown
  ): Promise<void>;
  /**
   * Called when a workflow encounters an error.
   * Override to handle errors.
   *
   * @param workflowName - Workflow binding name
   * @param workflowId - ID of the workflow
   * @param error - Error message
   */
  onWorkflowError(
    workflowName: string,
    workflowId: string,
    error: string
  ): Promise<void>;
  /**
   * Called when a workflow sends a custom event.
   * Override to handle custom events.
   *
   * @param workflowName - Workflow binding name
   * @param workflowId - ID of the workflow
   * @param event - Custom event payload
   */
  onWorkflowEvent(
    workflowName: string,
    workflowId: string,
    event: unknown
  ): Promise<void>;
  /**
   * Handle a workflow callback via RPC.
   * @internal - Called by AgentWorkflow, do not call directly
   */
  _workflow_handleCallback(callback: WorkflowCallback): Promise<void>;
  /**
   * Broadcast a message to all connected clients via RPC.
   * @internal - Called by AgentWorkflow, do not call directly
   */
  _workflow_broadcast(message: unknown): Promise<void>;
  /**
   * Update agent state via RPC.
   * @internal - Called by AgentWorkflow, do not call directly
   */
  _workflow_updateState(
    action: "set" | "merge" | "reset",
    state?: unknown
  ): Promise<void>;
  /**
   * Connect to a new MCP Server via RPC (Durable Object binding)
   *
   * The binding name and props are persisted to storage so the connection
   * is automatically restored after Durable Object hibernation.
   *
   * @example
   * await this.addMcpServer("counter", env.MY_MCP);
   * await this.addMcpServer("counter", env.MY_MCP, { props: { userId: "123" } });
   */
  addMcpServer<T extends McpAgent>(
    serverName: string,
    binding: DurableObjectNamespace<T>,
    options?: AddRpcMcpServerOptions
  ): Promise<{
    id: string;
    state: typeof MCPConnectionState.READY;
  }>;
  /**
   * Connect to a new MCP Server via HTTP (SSE or Streamable HTTP)
   *
   * @example
   * await this.addMcpServer("github", "https://mcp.github.com");
   * await this.addMcpServer("github", "https://mcp.github.com", { transport: { type: "sse" } });
   * await this.addMcpServer("github", url, callbackHost, agentsPrefix, options); // legacy
   */
  addMcpServer(
    serverName: string,
    url: string,
    callbackHostOrOptions?: string | AddMcpServerOptions,
    agentsPrefix?: string,
    options?: Pick<AddMcpServerOptions, "client" | "transport">
  ): Promise<
    | {
        id: string;
        state: typeof MCPConnectionState.AUTHENTICATING;
        authUrl: string;
      }
    | {
        id: string;
        state: typeof MCPConnectionState.READY;
      }
  >;
  private _redeemableAuthUrl;
  private _isAbsoluteHttpUrl;
  removeMcpServer(id: string): Promise<void>;
  getMcpServers(): MCPServersState;
  /**
   * Create the OAuth provider used when connecting to MCP servers that require authentication.
   *
   * Override this method in a subclass to supply a custom OAuth provider implementation,
   * for example to use pre-registered client credentials, mTLS-based authentication,
   * or any other OAuth flow beyond dynamic client registration.
   *
   * @example
   * // Custom OAuth provider
   * class MyAgent extends Agent {
   *   createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {
   *     return new MyCustomOAuthProvider(
   *       this.ctx.storage,
   *       this.name,
   *       callbackUrl
   *     );
   *   }
   * }
   *
   * @param callbackUrl The OAuth callback URL for the authorization flow
   * @returns An {@link AgentMcpOAuthProvider} instance used by {@link addMcpServer}
   */
  createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider;
  private broadcastMcpServers;
  /**
   * Handle MCP OAuth callback request if it's an OAuth callback.
   *
   * This method encapsulates the entire OAuth callback flow:
   * 1. Checks if the request is an MCP OAuth callback
   * 2. Processes the OAuth code exchange
   * 3. Establishes the connection if successful
   * 4. Broadcasts MCP server state updates
   * 5. Returns the appropriate HTTP response
   *
   * @param request The incoming HTTP request
   * @returns Response if this was an OAuth callback, null otherwise
   */
  private handleMcpOAuthCallback;
  /**
   * Handle OAuth callback response using MCPClientManager configuration
   * @param result OAuth callback result
   * @param request The original request (needed for base URL)
   * @returns Response for the OAuth callback
   */
  private handleOAuthCallbackResponse;
}
/**
 * Namespace for creating Agent instances
 * @template Agentic Type of the Agent class
 * @deprecated Use DurableObjectNamespace instead
 */
type AgentNamespace<Agentic extends Agent<Cloudflare.Env>> =
  DurableObjectNamespace<Agentic>;
/**
 * Agent's durable context
 */
type AgentContext = DurableObjectState;
/**
 * Configuration options for Agent routing
 */
type AgentOptions<Env> = PartyServerOptions<Env>;
type AgentGetOptions<
  Env,
  Props extends Record<string, unknown> = Record<string, unknown>
> = Pick<
  PartyServerOptions<Env, Props>,
  "jurisdiction" | "locationHint" | "props" | "routingRetry"
>;
/**
 * Route a request to the appropriate Agent
 * @param request Request to route
 * @param env Environment containing Agent bindings
 * @param options Routing options
 * @returns Response from the Agent or undefined if no route matched
 */
declare function routeAgentRequest<Env>(
  request: Request,
  env: Env,
  options?: AgentOptions<Env>
): Promise<Response | null>;
type EmailRoutingOptions<Env> = AgentOptions<Env> & {
  resolver: EmailResolver<Env>;
  /**
   * Callback invoked when no routing information is found for an email.
   * Use this to reject the email or perform custom handling.
   * If not provided, a warning is logged and the email is dropped.
   */
  onNoRoute?: (email: ForwardableEmailMessage) => void | Promise<void>;
};
declare class EmailBridge extends RpcTarget {
  #private;
  constructor(email: ForwardableEmailMessage);
  getRaw(): Promise<Uint8Array>;
  setReject(reason: string): void;
  forward(rcptTo: string, headers?: Headers): Promise<EmailSendResult>;
  reply(options: {
    from: string;
    to: string;
    raw: string;
  }): Promise<EmailSendResult>;
  [Symbol.dispose](): void;
}
/**
 * Route an email to the appropriate Agent
 * @param email The email to route
 * @param env The environment containing the Agent bindings
 * @param options The options for routing the email
 * @returns A promise that resolves when the email has been routed
 */
declare function routeAgentEmail<Env extends Cloudflare.Env = Cloudflare.Env>(
  email: ForwardableEmailMessage,
  env: Env,
  options: EmailRoutingOptions<Env>
): Promise<void>;
/**
 * Get or create an Agent by name
 * @template Env Environment type containing bindings
 * @template T Type of the Agent class
 * @param namespace Agent namespace
 * @param name Name of the Agent instance
 * @param options Options for Agent creation
 * @returns Promise resolving to an Agent instance stub
 */
declare function getAgentByName<
  Env extends Cloudflare.Env = Cloudflare.Env,
  T extends Agent<Env> = Agent<Env>,
  Props extends Record<string, unknown> = Record<string, unknown>
>(
  namespace: DurableObjectNamespace<T>,
  name: string,
  options?: AgentGetOptions<Env, Props>
): Promise<DurableObjectStub<T>>;
/**
 * A wrapper for streaming responses in callable methods
 */
declare class StreamingResponse {
  private _connection;
  private _id;
  private _closed;
  constructor(connection: Connection, id: string);
  /**
   * Whether the stream has been closed (via end() or error())
   */
  get isClosed(): boolean;
  /**
   * Send a chunk of data to the client
   * @param chunk The data to send
   * @returns false if stream is already closed (no-op), true if sent
   */
  send(chunk: unknown): boolean;
  /**
   * End the stream and send the final chunk (if any)
   * @param finalChunk Optional final chunk of data to send
   * @returns false if stream is already closed (no-op), true if sent
   */
  end(finalChunk?: unknown): boolean;
  /**
   * Send an error to the client and close the stream
   * @param message Error message to send
   * @returns false if stream is already closed (no-op), true if sent
   */
  error(message: string): boolean;
}
//#endregion
//#region src/agent-tool-types.d.ts
type AgentToolRunStatus =
  | "starting"
  | "running"
  | "completed"
  | "error"
  | "aborted"
  | "interrupted";
type AgentToolTerminalStatus = Extract<
  AgentToolRunStatus,
  "completed" | "error" | "aborted" | "interrupted"
>;
/**
 * Machine-readable cause of an `interrupted` seal (#1630 follow-up). Lets a
 * caller branch on WHY a run was abandoned without parsing the human-readable
 * `error` prose, which is not a stable contract.
 *
 * - `no-progress` — the child went silent for a full no-progress window while
 *   the parent was tailing it (genuinely stalled / hung).
 * - `window-exceeded` — a finite `agentToolReattachMaxWindowMs` ceiling elapsed
 *   while the child was still non-terminal. Only fires when an integrator opts
 *   into a hard wall-clock cap (the default ceiling is `Infinity`).
 * - `not-tailable` — the child runtime cannot live-tail, so the parent could
 *   not re-attach to its stream to follow it to terminal.
 * - `inspect-timeout` — inspecting the child timed out during parent recovery.
 * - `inspect-failed` — inspecting the child failed during parent recovery.
 * - `recovery-deadline` — the overall parent-recovery deadline elapsed before
 *   this run could be reconciled.
 * - `budget-exceeded` — a detached run's absolute `maxBudgetMs` ceiling elapsed
 *   before it reached a terminal. The parent gave up watching and tore the
 *   child down. Like `window-exceeded` this is a soft seal: a child that
 *   completes anyway can still repair the run and re-fire the completion hook.
 */
type AgentToolInterruptedReason =
  | "no-progress"
  | "window-exceeded"
  | "not-tailable"
  | "inspect-timeout"
  | "inspect-failed"
  | "recovery-deadline"
  | "budget-exceeded";
/**
 * Structured failure envelope an `agentTool()` returns when a sub-agent run
 * does not complete. Instead of an opaque error string the parent model would
 * parrot back to the user, the caller (or an orchestration harness) gets a
 * machine-readable signal:
 *
 * - `status` mirrors the underlying terminal status (`error` | `aborted` |
 *   `interrupted`).
 * - `retryable` is `true` only for a transient interruption — the child was
 *   reset or superseded by a deploy / parent recovery and never reached a
 *   logical outcome, so re-dispatching the same run is the right move. A
 *   genuine `error` or an intentional `aborted` is `false`.
 * - `error` stays human-readable for logs and UI.
 */
type AgentToolFailure = {
  ok: false;
  status: Exclude<AgentToolTerminalStatus, "completed">;
  error: string;
  retryable: boolean /** Present only when `status` is `interrupted` — machine-readable cause. */;
  reason?: AgentToolInterruptedReason;
  /**
   * Present only when `status` is `interrupted`. `true` when the child facet was
   * still non-terminal (running / advancing) at the moment the parent stopped
   * waiting; `false` once the parent has torn the child down so it is no longer
   * doing work. Lets a caller decide between re-dispatching vs. reconnecting.
   */
  childStillRunning?: boolean;
};
type AgentToolDisplayMetadata = {
  name?: string;
  icon?: string;
} & Record<string, unknown>;
/**
 * Reserved chunk type a sub-agent emits via `reportProgress` while it runs.
 * Rides the child's own UI-message stream as a **transient** data part, so it
 * re-broadcasts to the parent's clients (via the parent's tail) and surfaces in
 * `useAgentToolEvents` without persisting into the child's stored message parts.
 * See `design/rfc-detached-agent-tools.md` §"Progress and milestone signaling".
 */
declare const AGENT_TOOL_PROGRESS_PART = "data-agent-progress";
/**
 * Reserved chunk type a sub-agent emits via `reportProgress({ milestone })`.
 * Unlike the ephemeral progress part this rides the child's stream as a
 * **persisted** data part, so it survives eviction, replays on drill-in, and
 * re-resolves milestone waiters. See `design/rfc-detached-agent-tools.md`.
 */
declare const AGENT_TOOL_MILESTONE_PART = "data-agent-milestone";
/**
 * Ephemeral progress signal a running sub-agent emits with `reportProgress`. The
 * well-known fields drive generic UI (a bar + status line) with no per-app
 * convention; `data` is an app-specific escape hatch that is **live-only** by
 * default (not persisted) unless `reportProgress(p, { persist: true })`. Naming a
 * `milestone` promotes the signal to the **durable** tier: it persists as one row
 * per milestone, replays, and (with `data`) is retained.
 */
type AgentToolProgress<T = unknown> = {
  /** 0..1 — drives a progress bar. */ fraction?: number /** Human-readable status line, e.g. "Ingested 40k/80k rows". */;
  message?: string /** Coarse stage label, e.g. "scaffolding" | "deploying". */;
  phase?: string;
  /**
   * Present ⇒ a **durable** milestone: persisted, replayable, and surfaced as a
   * distinct row in `AgentToolRunState.milestones` / `inspectAgentToolRun`. Use
   * for named phase boundaries ("schema-ready", "preview-ready", "deployed").
   */
  milestone?: string /** App-specific payload; live-only for progress, persisted for milestones. */;
  data?: T;
};
/**
 * A durable milestone a sub-agent reached, projected onto `AgentToolRunState`
 * and `inspectAgentToolRun`. `sequence` is monotonic per run so replay/live
 * races dedupe on `(runId, sequence)`.
 */
type AgentToolMilestone = {
  name: string /** Monotonic per-run ordinal; dedupe key for replay vs live races. */;
  sequence: number /** Epoch ms the milestone was reached. */;
  at: number /** App-specific payload carried with the milestone (persisted). */;
  data?: unknown;
};
/**
 * Latest progress snapshot persisted on the child run row and surfaced through
 * `inspectAgentToolRun` + `AgentToolRunState`. Only the safe-to-inspect fields
 * are retained by default; `at` is the emit timestamp (drives the resetting
 * no-progress budget).
 */
type AgentToolProgressSnapshot = {
  fraction?: number;
  message?: string;
  phase?: string;
  /**
   * Set when this signal was a durable milestone (`reportProgress({ milestone })`).
   * Lets an `onProgress` consumer branch on milestone vs. ephemeral progress.
   */
  milestone?: string /** Epoch ms of the latest signal. */;
  at: number /** Present only when the emitter opted into persisting `data`. */;
  data?: unknown;
};
type AgentToolRunInfo = {
  runId: string;
  parentToolCallId?: string;
  agentType: string;
  inputPreview?: unknown;
  status: AgentToolRunStatus;
  display?: AgentToolDisplayMetadata;
  /**
   * Caller-controlled `metadata.source` for chat-agent `detached.notify`
   * completions. Present only for detached notify runs that supplied one.
   */
  notifySource?: string;
  displayOrder: number;
  startedAt: number;
  completedAt?: number;
};
type AgentToolLifecycleResult = {
  status: AgentToolTerminalStatus;
  summary?: string;
  error?: string /** Present only when `status` is `interrupted` — machine-readable cause. */;
  reason?: AgentToolInterruptedReason;
  /**
   * Present only when `status` is `interrupted`. Whether the child facet was
   * still non-terminal when the parent stopped waiting (before any teardown).
   */
  childStillRunning?: boolean;
};
/**
 * Configuration for a detached ("background") agent-tool run. See
 * `design/rfc-detached-agent-tools.md`.
 *
 * Callbacks are referenced by **method name** on the dispatching agent (the same
 * durable, eviction-surviving pattern as `Agent.schedule`) — never closures,
 * which cannot be rehydrated after the Durable Object is evicted.
 *
 * `Self` is threaded from `runAgentTool(cls, options)` so the method names are
 * type-checked against the calling agent's own methods.
 */
type DetachedAgentToolConfig<Self = Record<string, unknown>> = {
  /**
   * Method invoked once per terminal delivery. Branch on `result.status`:
   * `"completed" | "error" | "aborted" | "interrupted"`. A budget give-up
   * arrives as `status: "interrupted"` with `reason: "budget-exceeded"`; because
   * `interrupted` is soft, a child that later completes can fire the hook again
   * with `"completed"`, so a give-up never hides a late real result. Make the
   * handler idempotent.
   */
  onFinish?: Extract<keyof Self, string>;
  /**
   * Absolute safety ceiling — a backstop against a child that runs forever. On
   * expiry the parent gives up watching (delivers `onFinish` with
   * `interrupted` / `budget-exceeded`) and tears the child down. Defaults to the
   * parent-level `detachedMaxBudgetMs`.
   */
  maxBudgetMs?: number;
  /**
   * Per-run override of the resetting no-progress window (ms). Once the child
   * emits its first `reportProgress`, the parent gives up if it then goes silent
   * for this long (resets on each signal). Defaults to the parent-level
   * `detachedNoProgressBudgetMs` (1h). `0`/`Infinity` disables it.
   */
  noProgressBudgetMs?: number;
  /**
   * Chat-agent convenience (`@cloudflare/think` / `AIChatAgent`): when the run
   * finishes, inject a message into the chat so the model can react to the
   * result, instead of you wiring `onFinish` by hand. Sugar that auto-targets
   * the agent's `_cfDetachedNotifyFinish` hook; ignored on a base `Agent` that
   * does not implement it, and ignored when `onFinish` is also set (an explicit
   * `onFinish` wins). Pass `{ source }` to fit the injected message into your
   * app's existing metadata taxonomy. Override `formatDetachedCompletion()` to
   * customize the injected text.
   */
  notify?:
    | boolean
    | {
        source?: string;
      };
  /**
   * Chat-agent convenience: milestone names that, when the detached run reaches
   * them, surface an idempotent synthetic message in the chat BEFORE the run
   * finishes. Each `(runId, name)` fires at most once (idempotency-keyed),
   * whether observed live or reconciled after eviction. Override the wording via
   * `formatDetachedMilestone()`. Requires a chat host (`@cloudflare/think`); a
   * no-op on a base `Agent`.
   *
   * Two delivery modes (the string-array shorthand defaults to `"narrate"`):
   * - `"narrate"` (default) — inject a synthetic **assistant** message directly
   *   (no inference): a cheap, honest status line ("Found 2 sources…") that does
   *   not trigger a model turn. Best for pure progress narration.
   * - `"react"` — inject a **user-role** turn so the model responds to the
   *   milestone (steer, start dependent work, narrate with context). Costs a
   *   model turn. Opt in for milestones the agent should *act on*.
   */
  onMilestones?:
    | string[]
    | {
        names: string[];
        mode?: "react" | "narrate";
      };
};
type RunAgentToolOptions<Input = unknown, Self = Record<string, unknown>> = {
  input: Input;
  runId?: string;
  parentToolCallId?: string;
  displayOrder?: number;
  signal?: AbortSignal;
  inputPreview?: unknown;
  display?: AgentToolDisplayMetadata;
  /**
   * Run the sub-agent **detached**: dispatch it, let the current turn continue,
   * and (optionally) get a durable callback when it finishes. `true` is
   * fire-and-forget (observe via `agent-tool-event` frames + the global
   * `onAgentToolFinish` hook); an object adds the targeted, eviction-surviving
   * `onFinish` callback. A detached run does NOT inherit `options.signal` — it
   * must outlive the spawning turn; cancel it explicitly via `cancelAgentTool`.
   */
  detached?: boolean | DetachedAgentToolConfig<Self>;
};
/**
 * Result of dispatching a detached run. Returns immediately after dispatch
 * rather than after completion.
 */
type DetachedRunAgentToolResult = {
  runId: string;
  agentType: string;
  /**
   * `"running"` on a successful dispatch; `"error"` if dispatch itself failed
   * (e.g. the `maxConcurrentAgentTools` cap was exceeded — rejected
   * synchronously, no child started, no callback wired).
   */
  status: "running" | "error";
  error?: string;
};
type RunAgentToolResult<Output = unknown> = {
  runId: string;
  agentType: string;
  status: AgentToolTerminalStatus;
  output?: Output;
  summary?: string;
  error?: string;
  /**
   * Present only when `status` is `interrupted` — a machine-readable cause so
   * callers don't pattern-match the `error` prose (#1630 follow-up).
   */
  reason?: AgentToolInterruptedReason;
  /**
   * Present only when `status` is `interrupted`. `true` when the child facet was
   * still non-terminal (running / advancing) at the moment the parent stopped
   * waiting and before any teardown; `false` once the parent has torn the child
   * down so it is no longer doing work.
   */
  childStillRunning?: boolean;
};
type ChatCapableAgentClass<T extends Agent = Agent> = SubAgentClass<T>;
type AgentToolRunInspection<Output = unknown> = {
  runId: string;
  status: Exclude<AgentToolRunStatus, "interrupted">;
  requestId?: string;
  streamId?: string;
  output?: Output;
  summary?: string;
  error?: string;
  startedAt: number;
  completedAt?: number;
  /**
   * Latest progress snapshot the child has persisted, so a rehydrated parent
   * (recovery / backbone reconcile) can reconstruct "where is this run" and
   * reset the resetting no-progress budget without having tailed the live
   * stream. Absent until the child emits its first `reportProgress`.
   */
  progress?: AgentToolProgressSnapshot;
  /**
   * Durable milestones the child has persisted, ordered by `sequence`. Lets a
   * rehydrated parent (recovery / backbone reconcile) replay milestone-gated
   * work and milestone notifications without having observed the live stream.
   */
  milestones?: AgentToolMilestone[];
};
type AgentToolStoredChunk = {
  sequence: number;
  body: string;
};
type AgentToolChildAdapter<Input = unknown, Output = unknown> = {
  startAgentToolRun(
    input: Input,
    options: {
      runId: string;
      signal?: AbortSignal;
    }
  ): Promise<AgentToolRunInspection<Output>>;
  cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
  inspectAgentToolRun(
    runId: string
  ): Promise<AgentToolRunInspection<Output> | null>;
  getAgentToolChunks(
    runId: string,
    options?: {
      afterSequence?: number;
    }
  ): Promise<AgentToolStoredChunk[]>;
  tailAgentToolRun?(
    runId: string,
    options?: {
      afterSequence?: number;
      signal?: AbortSignal;
    }
  ): Promise<ReadableStream<AgentToolStoredChunk>>;
};
type AgentToolEvent =
  | {
      kind: "started";
      runId: string;
      agentType: string;
      inputPreview?: unknown;
      order: number;
      display?: AgentToolDisplayMetadata;
    }
  | {
      kind: "chunk";
      runId: string;
      body: string;
    }
  | {
      kind: "finished";
      runId: string;
      summary: string;
    }
  | {
      kind: "error";
      runId: string;
      error: string;
    }
  | {
      kind: "aborted";
      runId: string;
      reason?: string;
    }
  | {
      kind: "interrupted";
      runId: string;
      error: string /** Machine-readable cause of the interrupt (#1630 follow-up). */;
      reason?: AgentToolInterruptedReason;
      /**
       * Whether the child facet was still non-terminal when the parent stopped
       * waiting (before any teardown). Lets a UI distinguish a still-running
       * child from one the parent has torn down.
       */
      childStillRunning?: boolean;
    };
type AgentToolEventMessage = {
  type: "agent-tool-event";
  parentToolCallId?: string;
  sequence: number;
  replay?: true;
  event: AgentToolEvent;
};
type AgentToolRunPart = {
  type: string;
};
type AgentToolRunState<Part extends AgentToolRunPart = AgentToolRunPart> = {
  runId: string;
  agentType: string;
  parentToolCallId?: string;
  inputPreview?: unknown;
  order: number;
  display?: AgentToolDisplayMetadata;
  status: "running" | "completed" | "error" | "aborted" | "interrupted";
  /**
   * Message parts reconstructed from the child agent's streamed chunks.
   *
   * The default stays framework-neutral so importing `agents` does not require
   * an AI SDK peer. AI SDK consumers can use
   * `AgentToolRunState<UIMessage["parts"][number]>` when they need its exact
   * discriminated union.
   */
  parts: Part[];
  summary?: string;
  error?: string;
  /**
   * Present only when `status` is `interrupted` — machine-readable cause and
   * whether the child is still running, mirrored from the wire event so a UI
   * can render the reason without parsing `error` (#1630 follow-up).
   */
  reason?: AgentToolInterruptedReason;
  childStillRunning?: boolean;
  /**
   * Latest progress snapshot, projected from the child's transient
   * `data-agent-progress` signals so a UI can render a bar / ETA / phase label
   * for a running (especially detached / background) run without drilling in.
   */
  progress?: AgentToolProgressSnapshot;
  /**
   * Durable milestones the run has reached, ordered by `sequence` (deduped
   * across replay/live races). Drives milestone chips / a phase timeline.
   */
  milestones?: AgentToolMilestone[];
  subAgent: {
    agent: string;
    name: string;
  };
};
type AgentToolEventState<Part extends AgentToolRunPart = AgentToolRunPart> = {
  runsById: Record<string, AgentToolRunState<Part>>;
  runsByToolCallId: Record<string, AgentToolRunState<Part>[]>;
  unboundRuns: AgentToolRunState<Part>[];
};
//#endregion
export {
  RoutingRetryOptions as $,
  LegacyMcpHandler as $t,
  AgentGetOptions as A,
  MCPServerFilter as At,
  EmailSendBinding as B,
  RPCServerTransport as Bt,
  DetachedRunAgentToolResult as C,
  MCPClientManager as Ct,
  AddRpcMcpServerOptions as D,
  MCPConnectionResult as Dt,
  AddMcpServerOptions as E,
  MCPClientOAuthResult as Et,
  Connection$1 as F,
  normalizeServerId as Ft,
  FiberStatus as G,
  ElicitResult$3 as Gt,
  FiberInspection as H,
  RPC_DO_PREFIX as Ht,
  ConnectionContext$1 as I,
  MCPElicitationHandler as It,
  MCPServerMessage as J,
  DurableObjectEventStore as Jt,
  ListFibersOptions as K,
  McpAgent as Kt,
  DEFAULT_AGENT_STATIC_OPTIONS as L,
  MCPElicitationHandlers as Lt,
  AgentOptions as M,
  MCP_SERVER_ID_MAX_LENGTH as Mt,
  AgentStaticOptions as N,
  RegisterServerOptions as Nt,
  Agent as O,
  MCPDiscoverResult as Ot,
  CallableMetadata as P,
  getNamespacedData as Pt,
  RPCResponse as Q,
  CreateMcpHandlerOptions$1 as Qt,
  DeleteFibersOptions as R,
  RPCClientTransport as Rt,
  DetachedAgentToolConfig as S,
  MCPClientElicitationHandlers as St,
  RunAgentToolResult as T,
  MCPClientOAuthCallbackConfig as Tt,
  FiberRecoveryContext as U,
  ElicitRequest$2 as Ut,
  FiberContext as V,
  RPCServerTransportOptions as Vt,
  FiberRecoveryResult as W,
  ElicitRequestSchema as Wt,
  QueueItem as X,
  experimental_createMcpHandler as Xt,
  MCPServersState as Y,
  createMcpHandler$1 as Yt,
  RPCRequest as Z,
  CreateLegacyMcpHandlerOptions as Zt,
  AgentToolRunState as _,
  ElicitRequest$1 as _t,
  AgentToolEvent as a,
  SSEEdgeClientTransport as an,
  StartFiberResult as at,
  AgentToolTerminalStatus as b,
  MCPAIToolSet as bt,
  AgentToolFailure as c,
  SubAgentPathMatch as cn,
  SubAgentClass as ct,
  AgentToolMilestone as d,
  routeSubAgentRequest as dn,
  callable as dt,
  createLegacyMcpHandler as en,
  Schedule as et,
  AgentToolProgress as f,
  withInvocationScope as fn,
  getAgentByName as ft,
  AgentToolRunPart as g,
  unstable_callable as gt,
  AgentToolRunInspection as h,
  routeAgentRequest as ht,
  AgentToolDisplayMetadata as i,
  WorkerTransportOptions as in,
  StartFiberOptions as it,
  AgentNamespace as j,
  MCPServerOptions as jt,
  AgentContext as k,
  MCPOAuthCallbackResult as kt,
  AgentToolInterruptedReason as l,
  getSubAgentByName as ln,
  SubAgentStub as lt,
  AgentToolRunInfo as m,
  routeAgentEmail as mt,
  AGENT_TOOL_PROGRESS_PART as n,
  TransportState as nn,
  SendEmailOptions as nt,
  AgentToolEventMessage as o,
  StreamableHTTPEdgeClientTransport as on,
  StateUpdateMessage as ot,
  AgentToolProgressSnapshot as p,
  getCurrentAgent as pt,
  MCPServer as q,
  ClearableEventStore as qt,
  AgentToolChildAdapter as r,
  WorkerTransport as rn,
  SqlError as rt,
  AgentToolEventState as s,
  SUB_PREFIX as sn,
  StreamingResponse as st,
  AGENT_TOOL_MILESTONE_PART as t,
  MCPStorageApi as tn,
  ScheduleCriteria as tt,
  AgentToolLifecycleResult as u,
  parseSubAgentPath as un,
  WSMessage$1 as ut,
  AgentToolRunStatus as v,
  ElicitResult$2 as vt,
  RunAgentToolOptions as w,
  MCPClientManagerOptions as wt,
  ChatCapableAgentClass as x,
  MCPClientElicitationHandler as xt,
  AgentToolStoredChunk as y,
  MCPAITool as yt,
  EmailRoutingOptions as z,
  RPCClientTransportOptions as zt
};
//# sourceMappingURL=agent-tool-types-BC-WFlsz.d.ts.map