import {
  S as ConnectionContext,
  T as WSMessage,
  _ as LifecycleJobContext,
  o as MemoryLimitContext,
  s as LifecycleCapability,
  t as CapabilityRequestContext,
  u as LifecycleRouteAddress,
  v as LifecycleJobOutcome,
  x as Connection
} from "./capability-runner-BUBa6Ake.js";
import { t as RetryOptions } from "./retries-D9B2UCq3.js";
import {
  r as LifecycleRouteEnvelope,
  t as Lifecycle
} from "./durable-object-lifecycle-ei7M7lqB.js";
import { n as CurrentAgentContext } from "./current-agent-C4w86kcN.js";
import { t as AgentEmail } from "./internal_context-BlxFEWfn.js";
import { r as EmailResolver, s as SendEmailOptions } from "./email-7TatiTnl.js";
import {
  n as Observability,
  r as ObservabilityEvent,
  s as MCPObservabilityEvent
} from "./index-YSKgfgg9.js";
import { t as AgentMcpOAuthProvider } from "./do-oauth-client-provider-Tmf1vgKz.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-DxYpJ_XF.js";
import { n as LegacyCallToolResultSchema } from "./invoker-CG0_p_Wq.js";
import { t as MessageType } from "./types-6Zo2zfoO.js";
import {
  a as ScheduleCriteria,
  i as Schedule,
  o as ScheduleOptions,
  t as Scheduler
} from "./scheduler-BGq6M5Kd.js";
import { i as QueueItem } from "./types-DCD6BNZH.js";
import { l as TaskHandlers, r as Tasks } from "./tasks-V2lCT8ZV.js";
import { t as State } from "./index-Dlgtd3Mj.js";
import { t as CallableMetadata } from "./callable-decorator-DP__HhBA.js";
import { AsyncLocalStorage } from "node:async_hooks";
import {
  DurableObject,
  RpcTarget,
  WorkflowEvent,
  WorkflowSleepDuration,
  WorkflowStep
} from "cloudflare:workers";
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$1 } 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";
/** One agent identity in a root-first address chain. */
interface AgentPathStep {
  /** Agent class name as exported by the Worker. */
  className: string;
  /** Logical Agent instance name. */
  name: string;
}
interface BuildAgentPathOptions {
  /** Top-level route prefix. Must match `routeAgentRequest`; defaults to `agents`. */
  prefix?: string;
  /** Pathname suffix appended after the destination Agent identity. */
  leafPath?: string;
  /** Root Durable Object binding name, when it differs from the root class name. */
  rootBinding?: string;
}
/** @internal Build the strictly validated path tail for sub-agent routing. */
declare function buildSubAgentPath(
  path: ReadonlyArray<AgentPathStep>,
  leafPath?: string
): string;
/** @internal Preserve React's tolerant path composition for disabled placeholders. */
declare function buildSubAgentPathUnchecked(
  path: ReadonlyArray<AgentPathStep>,
  leafPath?: string
): string;
/**
 * Build the canonical pathname for a root Agent or nested sub-agent.
 *
 * The address is root-first and accepts `Agent#selfPath`. Pass
 * `rootBinding` when the root Durable Object binding and class names differ.
 */
declare function buildAgentPath(
  path: ReadonlyArray<AgentPathStep>,
  options?: BuildAgentPathOptions
): string;
/** Build an absolute URL for a root Agent or nested sub-agent. */
declare function buildAgentUrl(
  origin: string | URL,
  path: ReadonlyArray<AgentPathStep>,
  options?: BuildAgentPathOptions
): URL;
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: DynamicAgentClass<T>,
  name: string
): Promise<DynamicAgentStub<T>>;
//#endregion
//#region src/dynamic-agents/types.d.ts
type DynamicAgentConnectionMeta = {
  id: string;
  uri: string | null;
  tags: string[];
  state: unknown;
  requestHeaders?: [string, string][];
};
type DynamicAgentConnectionBridgeLike = {
  send(message: string | ArrayBuffer | ArrayBufferView): void | Promise<void>;
  close(code?: number, reason?: string): void | Promise<void>;
  setState(state: unknown): unknown | Promise<unknown>;
  broadcast(
    ownerPath: ReadonlyArray<{
      className: string;
      name: string;
    }>,
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): void | Promise<void>;
};
type DynamicAgentConnectionOperationName = "send" | "setState" | "close";
/**
 * Constructor type for a dynamic agent (facet-backed child) class.
 * Used by {@link Agent.dynamicAgents} 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 DynamicAgentClass<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 dynamic agent. Exposes all public instance
 * methods as callable RPC methods with Promise-wrapped return types.
 *
 * Methods owned by `Agent`, its lifecycle, or `DurableObject` internals
 * are excluded — only user-defined methods on the subclass are exposed.
 */
type DynamicAgentStub<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;
};
type FacetRunStorageRow = {
  owner_path: string;
  owner_path_key: string;
  run_id: string;
  created_at: number;
};
/**
 * Internal RPC surface exposed by the root agent for facets to
 * delegate alarm-owning operations (schedules + facet teardown).
 * @internal
 */
type RootFacetRpcSurface = {
  _cf_routeLifecycle(
    target: LifecycleRouteAddress | undefined,
    envelope: LifecycleRouteEnvelope
  ): Promise<unknown>;
  _cf_cleanupFacetPrefix(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<void>;
  _cf_destroyDescendantFacet(
    targetPath: ReadonlyArray<AgentPathStep>
  ): Promise<void>;
  _cf_acquireFacetKeepAlive(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<string>;
  _cf_releaseFacetKeepAlive(token: string): Promise<void>;
  _cf_registerFacetRun(
    ownerPath: ReadonlyArray<AgentPathStep>,
    runId: string
  ): Promise<void>;
  _cf_unregisterFacetRun(
    ownerPath: ReadonlyArray<AgentPathStep>,
    runId: string
  ): Promise<void>;
  _cf_broadcastToSubAgent(
    ownerPath: ReadonlyArray<AgentPathStep>,
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): Promise<void>;
  _cf_subAgentConnectionMetas(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<DynamicAgentConnectionMeta[]>;
  _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>;
};
//#endregion
//#region src/dynamic-agents/bridges.d.ts
/**
 * Parent-side bridge handed to a facet over RPC: wraps a live root-owned
 * `Connection` so the facet can send/close/setState on it, and carries
 * the root's broadcast entry point for facet-scoped broadcasts.
 */
declare class DynamicAgentConnectionBridge
  extends RpcTarget
  implements DynamicAgentConnectionBridgeLike
{
  #private;
  constructor(
    connection: Connection,
    broadcast?: (
      ownerPath: ReadonlyArray<{
        className: string;
        name: string;
      }>,
      message: string | ArrayBuffer | ArrayBufferView,
      without?: string[]
    ) => void | Promise<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 | Promise<void>;
}
//#endregion
//#region src/dynamic-agents/identity.d.ts
declare const SUB_AGENT_IDENTITY_VERSION_LEGACY = "legacy";
declare const SUB_AGENT_IDENTITY_VERSION_PATH_V2 = "path-v2";
type SubAgentIdentityVersion =
  | typeof SUB_AGENT_IDENTITY_VERSION_LEGACY
  | typeof SUB_AGENT_IDENTITY_VERSION_PATH_V2;
//#endregion
//#region src/dynamic-agents/registry.d.ts
/**
 * SQL access the registry needs from its owning Agent: the tagged
 * template helper plus raw DDL execution (for additive column
 * migrations whose errors must be inspected).
 */
type DynamicAgentRegistrySqlHost = {
  sql<T = Record<string, string | number | boolean | null>>(
    strings: TemplateStringsArray,
    ...values: (string | number | boolean | null)[]
  ): T[];
  execRawSql(sql: string): void;
};
/**
 * The parent-side registry of spawned dynamic agents (facets), stored
 * in the parent's own SQLite. Backs `hasSubAgent` / `listSubAgents`
 * and the identity-versioning decision (legacy bare-name facets vs
 * path-scoped v2 identities).
 *
 * Table and column names are storage-frozen — never rename them.
 */
declare class DynamicAgentRegistry {
  #private;
  constructor(host: DynamicAgentRegistrySqlHost);
  ensure(): void;
  record(
    className: string,
    name: string,
    identity: {
      version: SubAgentIdentityVersion;
      name: string;
    }
  ): void;
  row(
    className: string,
    name: string
  ): {
    identity_version: string | null;
    identity_name: string | null;
  } | null;
  identity(
    className: string,
    name: string,
    childPath: ReadonlyArray<AgentPathStep>
  ): Promise<{
    version: SubAgentIdentityVersion;
    name: string;
    existing: boolean;
  }>;
  forget(className: string, name: string): void;
  has(className: string, name: string): boolean;
  list(className?: string): Array<{
    className: string;
    name: string;
    createdAt: number;
  }>;
}
//#endregion
//#region src/dynamic-agents/host.d.ts
/**
 * The Agent internals the dynamic-agents (facet) machinery reaches
 * into. Agent implements this structurally and passes itself at
 * construction — the interface exists to make the coupling explicit
 * and reviewable, and is the seam a later capability refactor would
 * shrink.
 *
 * Members named `_cf_*` are cross-facet RPC entry points that must
 * stay on the Agent prototype; the module calls back into them when
 * traversal continues on another agent instance.
 *
 * @internal
 */
interface DynamicAgentHostPort {
  readonly ctx: DurableObjectState;
  readonly lifecycle: {
    route(envelope: LifecycleRouteEnvelope): Promise<unknown>;
    readonly name: string;
  };
  sql<T = Record<string, string | number | boolean | null>>(
    strings: TemplateStringsArray,
    ...values: (string | number | boolean | null)[]
  ): T[];
  /** Facet identity — written by `initAsFacet` and startup restore. */
  _isFacet: boolean;
  _facetName?: string;
  _parentPath: ReadonlyArray<AgentPathStep>;
  readonly name: string;
  readonly _ParentClass: {
    readonly name: string;
  };
  readonly selfPath: AgentPathStep[];
  _keepAliveRefs: number;
  _isSameAgentPathPrefix(
    prefix: ReadonlyArray<AgentPathStep>,
    path: ReadonlyArray<AgentPathStep>
  ): boolean;
  hasSubAgent(className: string, name: string): boolean;
  _cf_resolveSubAgent(className: string, name: string): Promise<unknown>;
  _cf_cleanupFacetPrefix(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<void>;
  _cf_routeLifecycle(
    target: LifecycleRouteAddress | undefined,
    envelope: LifecycleRouteEnvelope
  ): Promise<unknown>;
  _syncHostJobs(): Promise<void>;
  readonly scheduler: {
    __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(prefix: string): Promise<void>;
  };
  readonly tasks: {
    __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(prefix: string): Promise<void>;
  };
  readonly _queue: {
    __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(prefix: string): Promise<void>;
  };
  /** Local (non-facet-index) durable fiber recovery pass. */
  _checkRunFibers(): Promise<void>;
  /** Overridable RPC entry points — call via the host so subclass overrides intercept. */
  _cf_broadcastToSubAgent(
    ownerPath: ReadonlyArray<AgentPathStep>,
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): Promise<void>;
  _cf_checkRunFibersForFacet(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<number>;
  /** Ensure constructor-time async initialization has completed. */
  __unsafe_ensureInitialized(): Promise<void>;
  /**
   * Run `body` in a fresh invocation scope with no native request/
   * connection context attached, so a child-facet RPC never sees
   * parent-owned I/O handles.
   */
  _runFacetInitInvocation<T>(body: () => Promise<T>): Promise<T>;
  readonly _webSockets: {
    getConnection<TState = unknown>(id: string): Connection<TState> | undefined;
    getConnections<TState = unknown>(
      tag?: string
    ): Iterable<Connection<TState>>;
  };
  _unsafe_getConnectionFlag(connection: Connection, key: string): unknown;
  _unsafe_setConnectionFlag(
    connection: Connection,
    key: string,
    value: unknown
  ): void;
  shouldConnectionBeReadonly(
    connection: Connection,
    context: {
      request: Request;
    }
  ): boolean;
  setConnectionReadonly(connection: Connection, readonly: boolean): void;
  shouldSendProtocolMessages(
    connection: Connection,
    context: {
      request: Request;
    }
  ): boolean;
  getConnectionTags(
    connection: Connection,
    context: {
      request: Request;
    }
  ): Promise<string[]> | string[];
  onConnect(
    connection: Connection,
    context: {
      request: Request;
    }
  ): unknown | Promise<unknown>;
  onMessage(
    connection: Connection,
    message: WSMessage
  ): unknown | Promise<unknown>;
  onClose(
    connection: Connection,
    code: number,
    reason: string,
    wasClean: boolean
  ): unknown | Promise<unknown>;
  onBeforeSubAgent(
    request: Request,
    child: {
      className: string;
      name: string;
    }
  ): Promise<Request | Response | void>;
}
//#endregion
//#region src/dynamic-agents/dynamic-agents.d.ts
/**
 * The facet-backed dynamic-agent machinery, extracted from the Agent
 * class. One instance per Agent, installed as a Lifecycle capability
 * (`capabilityId: "dynamic-agents"`); the host port documents exactly
 * which Agent internals it touches.
 *
 * The capability claims no runner hooks — four integration points are
 * deliberately wired directly through the Agent composition root
 * instead, because the runner's dispatch contract cannot express them:
 * the `/sub/` upgrade path rewrites the request and *continues* into
 * `lifecycle.fetch` (onRequest can only claim), forwarded WS frames run
 * inside the host's onMessage wrapper *after* the WebSockets capability
 * has claimed the wake, this module *implements* the lifecycle route
 * transport rather than consuming it, and facet-context restore has
 * load-bearing startup ordering inside the host's startup span.
 *
 * Nothing here renames any wire- or storage-visible identifier: the
 * `cf_agents_facet_runs` table, `_cf_*` RPC method names, and route
 * key formats are frozen.
 *
 * @internal
 */
declare class DynamicAgentsInternal extends LifecycleCapability {
  #private;
  /** The parent-side registry of spawned dynamic agents. */
  readonly registry: DynamicAgentRegistry;
  constructor(host: DynamicAgentHostPort);
  runRowsForPrefix(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): FacetRunStorageRow[];
  deleteRunRowsForPrefix(ownerPath: ReadonlyArray<AgentPathStep>): void;
  lifecycleRouteAddress(): LifecycleRouteAddress | undefined;
  routeLifecycleToRoot(envelope: LifecycleRouteEnvelope): Promise<unknown>;
  routeLifecycleToTarget(
    target: LifecycleRouteAddress,
    envelope: LifecycleRouteEnvelope
  ): Promise<unknown>;
  /** Body of the single native-RPC aperture for routed Lifecycle capabilities. */
  routeLifecycle(
    target: LifecycleRouteAddress | undefined,
    envelope: LifecycleRouteEnvelope
  ): Promise<unknown>;
  rootAlarmOwner(): Promise<RootFacetRpcSurface>;
  rootResolvesToSelf(): boolean;
  /**
   * Clean root-owned bookkeeping for a sub-tree of facets: bulk-cancel
   * schedules, queue items, and routed Task wake mirrors under the
   * owner-path prefix, and delete root-side facet fiber recovery leases for
   * the same sub-tree.
   */
  cleanupPrefix(ownerPath: ReadonlyArray<AgentPathStep>): Promise<void>;
  /**
   * Acquire a root-owned keepAlive ref on behalf of a descendant facet.
   */
  acquireKeepAlive(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.
   */
  releaseKeepAlive(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.
   */
  registerRun(
    ownerPath: ReadonlyArray<AgentPathStep>,
    runId: string
  ): Promise<void>;
  /**
   * 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.
   */
  checkRunFibers(): Promise<void>;
  /**
   * 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.
   */
  checkRunFibersAtPath(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<number>;
  /**
   * Invoke an RPC method on the host 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.
   */
  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.
   */
  destroyDescendant(targetPath: ReadonlyArray<AgentPathStep>): Promise<void>;
  /**
   * 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.
   */
  resolve(className: string, name: string): Promise<unknown>;
  /**
   * Forcefully abort a running facet. Transitively aborts the child's
   * own children; storage is preserved.
   */
  abort(className: string, name: string, reason?: unknown): void;
  /**
   * Delete a facet: abort it if running, then permanently wipe its
   * storage. Transitively deletes the child's own children.
   */
  delete(className: string, name: string): Promise<void>;
  /** Drop all facet-side virtual connections (test/rehydration hook). */
  clearVirtualConnections(): void;
  /** Facet-side lookup of a virtual connection by id. */
  getVirtualConnection(id: string): Connection | undefined;
  /** Facet-side iteration over virtual connections, optionally by tag. */
  getVirtualConnections(tag?: string): Iterable<Connection>;
  activeBridge(
    connectionId?: string
  ): DynamicAgentConnectionBridgeLike | undefined;
  /**
   * Route a virtual sub-agent connection operation through its live frame
   * bridge, or through the durable root Agent after that frame completes.
   * All operations share one per-connection queue. Facet broadcasts wait for
   * older queued operations; failures do not block later work.
   */
  routeConnectionOperation(
    connectionId: string,
    operationName: DynamicAgentConnectionOperationName,
    operation: (bridge: DynamicAgentConnectionBridgeLike) => unknown
  ): void;
  /**
   * Route a facet broadcast after every older connection operation.
   *
   * This barrier is intentionally one-way: facet startup can broadcast before
   * a child connection has finished initializing its tags and protocol flags.
   * Making those later connection operations wait would let the next frame
   * observe stale root-owned metadata.
   */
  routeBroadcast(
    ownerPath: ReadonlyArray<AgentPathStep>,
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[],
    upstreamBridge?: DynamicAgentConnectionBridgeLike
  ): Promise<void>;
  broadcastToParent(
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): Promise<void>;
  broadcastToPath(
    ownerPath: ReadonlyArray<AgentPathStep>,
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): Promise<void>;
  connectionMetas(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<DynamicAgentConnectionMeta[]>;
  sendToConnection(
    connectionId: string,
    message: string | ArrayBuffer | ArrayBufferView
  ): Promise<void>;
  closeConnection(
    connectionId: string,
    code?: number,
    reason?: string
  ): Promise<void>;
  setConnectionState(connectionId: string, state: unknown): Promise<unknown>;
  connectionTargetPath(
    connection: Connection
  ): ReadonlyArray<AgentPathStep> | null;
  isSameAgentPath(
    a: ReadonlyArray<AgentPathStep>,
    b: ReadonlyArray<AgentPathStep>
  ): boolean;
  connectionHasChildTarget(connection: Connection): boolean;
  connectionTargetsChild(connection: Connection): boolean;
  requestTargetsChild(request: Request): boolean;
  forwardWebSocketConnect(
    connection: Connection,
    request: Request,
    options: {
      gate: boolean;
    }
  ): Promise<boolean>;
  forwardWebSocketMessage(
    connection: Connection,
    message: WSMessage,
    replyBridge?: DynamicAgentConnectionBridge
  ): Promise<boolean>;
  forwardWebSocketClose(
    connection: Connection,
    code: number,
    reason: string,
    wasClean: boolean
  ): Promise<boolean>;
  handleWebSocketConnect(
    bridge: DynamicAgentConnectionBridge,
    meta: DynamicAgentConnectionMeta
  ): Promise<void>;
  handleWebSocketMessage(
    message: WSMessage,
    bridge: DynamicAgentConnectionBridge,
    meta: DynamicAgentConnectionMeta,
    replyBridge?: DynamicAgentConnectionBridge
  ): Promise<void>;
  handleWebSocketClose(
    code: number,
    reason: string,
    wasClean: boolean,
    bridge: DynamicAgentConnectionBridge,
    meta: DynamicAgentConnectionMeta
  ): Promise<void>;
  runWithBridge<T>(
    bridge: DynamicAgentConnectionBridgeLike,
    connectionId: string,
    fn: () => Promise<T> | T
  ): Promise<T>;
  createBridgeConnection(meta: DynamicAgentConnectionMeta): Connection;
  storeVirtualConnection(connection: Connection): void;
  /**
   * Restore the facet identity persisted by `init` (wake after
   * hibernation), then best-effort hydrate the virtual connections
   * from the root's WebSocket state.
   */
  restoreFacetContext(): Promise<void>;
  hydrateConnectionsFromRoot(): Promise<void>;
  getRawConnectionState(connection: Connection): unknown;
  getForwardedState(connection: Connection): unknown;
  /**
   * Resolve the facet Fetcher for the match and forward the request to
   * it with `/sub/{class}/{name}` stripped.
   */
  forward(
    req: Request,
    match: {
      childClass: string;
      childName: string;
      remainingPath: string;
    }
  ): Promise<Response>;
  /**
   * Bridge used by `getSubAgentByName`: resolve the facet and dispatch
   * one RPC method. Stateless — no cached references.
   */
  invoke(
    className: string,
    name: string,
    method: string,
    args: unknown[]
  ): Promise<unknown>;
  /**
   * Bridge 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`.
   */
  invokePath(
    path: ReadonlyArray<{
      className: string;
      name: string;
    }>,
    method: string,
    args: unknown[]
  ): Promise<unknown>;
  invokeStubMethod(
    stub: unknown,
    className: string,
    method: string,
    args: unknown[]
  ): Promise<unknown>;
  /**
   * Initialize the host 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.
   */
  init(
    name: string,
    parentPath?: ReadonlyArray<{
      className: string;
      name: string;
    }>,
    identityName?: string
  ): Promise<void>;
  /** Remove a completed facet fiber from the root-side index. */
  unregisterRun(
    ownerPath: ReadonlyArray<AgentPathStep>,
    runId: string
  ): Promise<void>;
}
//#endregion
//#region src/dynamic-agents/api.d.ts
/**
 * The public dynamic-agents capability surface, reached via
 * `this.dynamicAgents` on an Agent.
 *
 * A dynamic agent is a facet-backed child: it runs in its own isolate
 * with its own SQLite database, colocated with — and supervised by —
 * its parent Agent. Use dynamic agents for code whose class or
 * lifecycle the parent owns (dynamically-loaded/generated code,
 * per-run tool agents, sandboxed components). For independent peers
 * such as one-DO-per-chat, use `getAgentByName` instead.
 *
 * @experimental The API surface may change before stabilizing.
 */
declare class DynamicAgents {
  #private;
  /** @internal Constructed by Agent; do not instantiate directly. */
  constructor(internal: DynamicAgentsInternal);
  /**
   * Get (creating or waking if needed) the dynamic agent of the given
   * class and name, as a typed RPC stub. Idempotent — repeated calls
   * with the same class and name return the same child.
   *
   * @experimental
   */
  get<T extends Agent>(
    cls: DynamicAgentClass<T>,
    name: string
  ): Promise<DynamicAgentStub<T>>;
  /**
   * Forcefully abort a running dynamic agent. The child stops
   * executing immediately and restarts on the next {@link get} call;
   * its storage is preserved. Transitively aborts the child's own
   * children. Pending RPC calls receive the reason as an error.
   *
   * @experimental
   */
  abort(cls: DynamicAgentClass, name: string, reason?: unknown): void;
  /**
   * Delete a dynamic agent: abort it if running, then permanently wipe
   * its storage. Transitively deletes the child's own children.
   *
   * @experimental
   */
  delete(cls: DynamicAgentClass, name: string): Promise<void>;
  /**
   * Whether this agent has previously spawned (and not deleted) a
   * dynamic agent of the given class and name. Backed by an
   * auto-maintained SQLite registry in the parent's storage.
   *
   * @experimental
   */
  has<T extends Agent>(cls: DynamicAgentClass<T>, name: string): boolean;
  has(className: string, name: string): boolean;
  /**
   * List known dynamic agents, optionally filtered by class. Reflects
   * the registry rows written by {@link get} and removed by
   * {@link delete}.
   *
   * @experimental
   */
  list<T extends Agent>(
    cls: DynamicAgentClass<T>
  ): Array<{
    className: string;
    name: string;
    createdAt: number;
  }>;
  list(className?: string): Array<{
    className: string;
    name: string;
    createdAt: number;
  }>;
}
//#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/server/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/server/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$1,
  options?: CreateLegacyMcpHandlerOptions
): LegacyMcpHandler;
//#endregion
//#region src/mcp/server/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$1,
  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$1,
  options?: CreateMcpHandlerOptions$1
): LegacyMcpHandler;
//#endregion
//#region src/mcp/server/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/server/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/server/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,
    ctx: ConnectionContext
  ): boolean;
  abstract server: MaybePromise<McpServer$1 | Server$1>;
  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<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,
    { request: req }: ConnectionContext
  ): 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/index.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;
};
/** Dependencies used by {@link MCPClientManager} across Durable Object wakes. */
type MCPClientManagerOptions = {
  /**
   * Runtime bindings used to restore persisted RPC MCP connections.
   * Required when the durable catalog contains `rpc://` servers.
   */
  readonly env?: Cloudflare.Env /** Construct the OAuth provider used for a persisted HTTP server. */;
  readonly 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[];
};
/**
 * A Durable Object capability that persists and aggregates MCP client
 * connections. Installing it directly on a Lifecycle (outside `agent.mcp`)
 * is experimental: that capability surface may change before stabilizing.
 */
declare class MCPClientManager extends LifecycleCapability {
  private readonly _name;
  private readonly _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 readonly _env;
  private readonly _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>;
  /**
   * Construct a reusable Durable Object MCP client capability.
   *
   * @param _name - MCP client implementation name sent during negotiation.
   * @param _version - MCP client implementation version sent during negotiation.
   * @param options - Optional runtime bindings and OAuth configuration.
   */
  constructor(
    _name: string,
    _version: string,
    options?: MCPClientManagerOptions
  );
  /** Restore persisted HTTP and RPC connections before the host handles work. */
  onStart(): Promise<void>;
  /** Intercept a registered MCP OAuth callback request. */
  onRequest(context: CapabilityRequestContext): Promise<Response | undefined>;
  private oauthCallbackResponse;
  /**
   * 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). */
  getRpcServersFromStorage(): MCPServerRow[];
  /**
   * Save an RPC server to storage for hibernation recovery.
   * The binding name is stored so this manager can resolve the namespace from
   * its runtime environment during restore.
   */
  saveRpcServerToStorage(
    id: string,
    name: string,
    normalizedName: string,
    bindingName: string,
    props?: Record<string, unknown>
  ): void;
  /**
   * Restore persisted HTTP MCP connections.
   *
   * @param clientName - Durable Object identity used to scope OAuth state.
   */
  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/workflow-types.d.ts
type AgentWorkflowPathStep = AgentPathStep;
type AgentWorkflowOrigin =
  | {
      kind: "agent";
      version: 1 /** Environment binding name for the top-level Agent namespace */;
      binding: string /** Name/ID of the top-level Agent */;
      name: string;
    }
  | {
      kind: "facet";
      version: 1 /** Environment binding name for the root Agent namespace */;
      rootBinding: string /** Root-first path to the originating facet, including itself */;
      path: AgentWorkflowPathStep[];
    };
/**
 * Type alias for WorkflowEvent in AgentWorkflow context.
 * Identical to WorkflowEvent - provided for naming consistency with AgentWorkflowStep.
 */
type AgentWorkflowEvent<Params = unknown> = WorkflowEvent<Params>;
/**
 * Extended WorkflowStep with durable Agent communication methods.
 * All added methods on this interface are durable - they're idempotent and won't
 * repeat on workflow retry.
 */
interface AgentWorkflowStep extends WorkflowStep {
  /**
   * Report successful completion to the Agent (durable).
   * Triggers onWorkflowComplete() on the Agent.
   * @param result - Optional result data
   */
  reportComplete<T = unknown>(result?: T): Promise<void>;
  /**
   * Report an error to the Agent (durable).
   * Triggers onWorkflowError() on the Agent.
   * @param error - Error or error message
   */
  reportError(error: Error | string): Promise<void>;
  /**
   * Send a custom event to the Agent (durable).
   * Triggers onWorkflowEvent() on the Agent.
   * @param event - Custom event payload
   */
  sendEvent<T = unknown>(event: T): Promise<void>;
  /**
   * Update the Agent's state entirely (durable).
   * This will replace the Agent's state and broadcast to all connected clients.
   * @param state - New state to set
   */
  updateAgentState(state: unknown): Promise<void>;
  /**
   * Merge partial state into the Agent's existing state (durable).
   * Performs a shallow merge and broadcasts to all connected clients.
   * @param partialState - Partial state to merge
   */
  mergeAgentState(partialState: Record<string, unknown>): Promise<void>;
  /**
   * Reset the Agent's state to its initialState (durable).
   * Broadcasts the reset state to all connected clients.
   */
  resetAgentState(): Promise<void>;
}
/**
 * Internal parameters injected by runWorkflow() to identify the originating Agent
 */
type AgentWorkflowInternalParams = {
  /** Name/ID of the Agent that started this workflow */ __agentName: string /** Environment binding name for the Agent's namespace */;
  __agentBinding: string /** Workflow binding name (for callbacks) */;
  __workflowName: string /** Versioned origin identity for top-level Agents and sub-agent facets */;
  __agentOrigin?: AgentWorkflowOrigin;
};
/**
 * Combined workflow params: user params + internal agent params
 */
type AgentWorkflowParams<T = unknown> = T & AgentWorkflowInternalParams;
/**
 * Workflow callback types for Agent-Workflow communication
 */
type WorkflowCallbackType = "progress" | "complete" | "error" | "event";
/**
 * Base callback structure sent from Workflow to Agent
 */
type WorkflowCallbackBase = {
  /** Workflow binding name */ workflowName: string /** ID of the workflow instance */;
  workflowId: string /** Type of callback */;
  type: WorkflowCallbackType /** Timestamp when callback was sent */;
  timestamp: number;
};
/**
 * Default progress type - covers common use cases.
 * Developers can define their own progress type for domain-specific needs.
 */
type DefaultProgress = {
  /** Current step name */ step?: string /** Step/overall status */;
  status?:
    | "pending"
    | "running"
    | "complete"
    | "error" /** Human-readable message */;
  message?: string /** Progress percentage (0-1) */;
  percent?: number /** Allow additional custom fields */;
  [key: string]: unknown;
};
/**
 * Progress callback - reports workflow progress with typed payload
 */
type WorkflowProgressCallback<P = DefaultProgress> = WorkflowCallbackBase & {
  type: "progress" /** Typed progress data */;
  progress: P;
};
/**
 * Complete callback - workflow finished successfully
 */
type WorkflowCompleteCallback = WorkflowCallbackBase & {
  type: "complete" /** Result of the workflow */;
  result?: unknown;
};
/**
 * Error callback - workflow encountered an error
 */
type WorkflowErrorCallback = WorkflowCallbackBase & {
  type: "error" /** Error message */;
  error: string;
};
/**
 * Event callback - custom event from workflow
 */
type WorkflowEventCallback = WorkflowCallbackBase & {
  type: "event" /** Custom event payload */;
  event: unknown;
};
/**
 * Union of all callback types
 */
type WorkflowCallback<P = DefaultProgress> =
  | WorkflowProgressCallback<P>
  | WorkflowCompleteCallback
  | WorkflowErrorCallback
  | WorkflowEventCallback;
/**
 * Workflow status values - derived from Cloudflare's InstanceStatus
 */
type WorkflowStatus = InstanceStatus["status"];
/**
 * Row structure for cf_agents_workflows tracking table
 */
type WorkflowTrackingRow = {
  /** Internal row ID (UUID) */ id: string /** Cloudflare Workflow instance ID */;
  workflow_id: string /** Workflow binding name */;
  workflow_name: string /** Current workflow status */;
  status: WorkflowStatus /** JSON-serialized metadata for querying */;
  metadata: string | null /** Error name if workflow failed */;
  error_name: string | null /** Error message if workflow failed */;
  error_message: string | null /** Unix timestamp when workflow was created */;
  created_at: number /** Unix timestamp when workflow was last updated */;
  updated_at: number /** Unix timestamp when workflow completed (null if not complete) */;
  completed_at: number | null;
};
/**
 * Options for runWorkflow()
 */
type RunWorkflowOptions = {
  /** Custom workflow instance ID (auto-generated if not provided) */ id?: string /** Optional metadata for querying (stored as JSON) */;
  metadata?: Record<
    string,
    unknown
  > /** Agent binding name (auto-detected from class name if not provided) */;
  agentBinding?: string /** Retention policy for the underlying Workflow instance */;
  retention?: WorkflowInstanceCreateOptions["retention"];
};
/**
 * Event payload for sendWorkflowEvent()
 */
type WorkflowEventPayload = {
  /** Event type name */ type: string /** Event payload data */;
  payload: unknown;
};
/**
 * Parsed workflow tracking info returned by getWorkflow()
 */
type WorkflowInfo = {
  /** Internal row ID */ id: string /** Cloudflare Workflow instance ID */;
  workflowId: string /** Workflow binding name */;
  workflowName: string /** Current workflow status */;
  status: WorkflowStatus /** Metadata (parsed from JSON) */;
  metadata: Record<string, unknown> | null /** Error info if workflow failed */;
  error: {
    name: string;
    message: string;
  } | null /** When workflow was created */;
  createdAt: Date /** When workflow was last updated */;
  updatedAt: Date /** When workflow completed (null if not complete) */;
  completedAt: Date | null;
};
/**
 * Criteria for querying tracked workflows
 */
type WorkflowQueryCriteria = {
  /** Filter by status */ status?:
    | WorkflowStatus
    | WorkflowStatus[] /** Filter by workflow binding name */;
  workflowName?: string /** Filter by metadata key-value pairs (exact match) */;
  metadata?: Record<
    string,
    string | number | boolean
  > /** Limit number of results (default 50, max 100) */;
  limit?: number /** Order by created_at */;
  orderBy?:
    | "asc"
    | "desc" /** Cursor for pagination (from previous WorkflowPage.nextCursor) */;
  cursor?: string;
};
/**
 * Paginated result from getWorkflows()
 */
type WorkflowPage = {
  /** Workflows for this page */ workflows: WorkflowInfo[] /** Total count of workflows matching the criteria (ignoring pagination) */;
  total: number /** Cursor for next page, or null if no more pages */;
  nextCursor: string | null;
};
/**
 * Standard approval event payload used by approveWorkflow/rejectWorkflow
 */
type ApprovalEventPayload = {
  /** Whether the workflow was approved */ approved: boolean /** Optional reason for approval/rejection */;
  reason?: string /** Optional additional metadata */;
  metadata?: Record<string, unknown>;
};
/**
 * Options for waitForApproval()
 */
type WaitForApprovalOptions = {
  /** Step name for waitForEvent (default: "wait-for-approval") */ stepName?: string /** Timeout duration (e.g., "7 days") */;
  timeout?: WorkflowSleepDuration /** Event type to wait for (default: "approval") */;
  eventType?: string;
};
/**
 * Error thrown when a workflow is rejected via rejectWorkflow()
 */
declare class WorkflowRejectedError extends Error {
  readonly reason?: string | undefined;
  readonly workflowId?: string | undefined;
  constructor(reason?: string | undefined, workflowId?: string | undefined);
}
//#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> = DynamicAgentClass<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
//#region src/index.d.ts
/**
 * 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;
    }
);
type DetachedReconcilePayload = {
  cadenceIndex?: number;
};
/**
 * 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 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.
 */
interface AgentStaticOptions {
  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;
}
/** Compatibility alias for the lifecycle-owned current Agent accessor. */
declare const getCurrentAgent: <
  T extends DurableObject = Agent<Cloudflare.Env>
>() => CurrentAgentContext<T, AgentEmail>;
/**
 * 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 TState State type to store within the Agent
 */
declare class Agent<
  Env extends Cloudflare.Env = Cloudflare.Env,
  TState = unknown,
  Props extends Record<string, unknown> = Record<string, unknown>
> extends DurableObject<Env> {
  /**
   * Runtime lifecycle and reusable durable capabilities for this Agent.
   *
   * @experimental The API surface may change before stabilizing.
   */
  readonly lifecycle: Lifecycle<Env, Props>;
  /**
   * WebSocket connection subsystem. Constructed as a field initializer
   * so it exists before the constructor installs it; the handler arrows
   * defer to `this.*`, so they always hit the framework-wrapped hooks.
   * Those wrappers still open their own invocation scope even though
   * the capability's dispatch already entered one via the host invoker
   * — the inner wrap is kept because the wrapped hooks are also invoked
   * from paths that do not pass through the capability (facet bridging,
   * direct calls).
   */
  /**
   * Durable state: the `cf_agents_state` row, lazy load, validated persistence.
   * `initialState` stays on Agent (a subclass field, initialized after this
   * one) and is seeded by the `state` getter. Typed `<unknown>` rather than
   * `<TState>` because `TState` appears in both `get()` and `set()` positions,
   * which would make `Agent`'s own `TState` parameter invariant and break
   * `Subclass -> Agent<Env, unknown>` assignability; the typed boundary is
   * re-established in `state` / `setState`.
   */
  readonly _state: State<unknown>;
  private readonly _webSockets;
  /** Run user initialization after lifecycle components have started. */
  onStart(_props?: Props): void | Promise<void>;
  /** Handle an HTTP request not claimed by a lifecycle component. */
  onRequest(_request: Request): Response | Promise<Response>;
  /** Handle a newly accepted hibernating WebSocket connection. */
  onConnect(
    _connection: Connection,
    _context: ConnectionContext
  ): void | Promise<void>;
  /** Handle a message from a hibernating WebSocket connection. */
  onMessage(_connection: Connection, _message: WSMessage): void | Promise<void>;
  /** Handle a hibernating WebSocket connection closing. */
  onClose(
    _connection: Connection,
    _code: number,
    _reason: string,
    _wasClean: boolean
  ): void | Promise<void>;
  /** Return tags persisted with a hibernating WebSocket connection. */
  getConnectionTags(
    _connection: Connection,
    _context: ConnectionContext
  ): string[] | Promise<string[]>;
  /** @internal Ensure lifecycle startup before a native RPC implementation. */
  __unsafe_ensureInitialized(props?: Props): Promise<void>;
  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.
   */
  /**
   * 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;
  /**
   * 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;
  /** Warn-once guard: `chatRecovery` reassigned during onStart() (too late for wake recovery). */
  private _warnedChatRecoveryInOnStart;
  /**
   * Number of active keepAlive() callers. When > 0, `_syncHostJobs()`
   * 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;
  /** @internal The extracted dynamic-agent (facet) machinery. */
  private _dynamicAgentsInstance;
  /** @internal */
  private get _dynamicAgents();
  /** @internal */
  private _dynamicAgentsApi;
  /**
   * The dynamic-agents capability: facet-backed child agents that run
   * in their own isolate with their own SQLite database, colocated
   * with — and supervised by — this agent.
   *
   * Use dynamic agents for code whose class or lifecycle this agent
   * owns: dynamically-loaded or AI-generated code, per-run tool
   * agents, sandboxed components. For independent peers (for example
   * one Durable Object per chat), use `getAgentByName` instead.
   *
   * ```ts
   * const child = await this.dynamicAgents.get(Researcher, id);
   * await child.doWork();
   * this.dynamicAgents.abort(Researcher, id, reason);
   * await this.dynamicAgents.delete(Researcher, id);
   * ```
   *
   * @experimental The API surface may change before stabilizing.
   */
  get dynamicAgents(): DynamicAgents;
  /** @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;
  /**
   * Durable scheduling capability installed into this Agent's Lifecycle.
   *
   * @experimental The API surface may change before stabilizing. Agent's
   * schedule()/scheduleEvery()/getScheduleById()/listSchedules()/
   * cancelSchedule() methods are the stable surface.
   */
  readonly scheduler: Scheduler;
  /**
   * Durable background-work capability installed into this Agent's
   * Lifecycle. Agent's queue()/dequeue()/dequeueAll()/dequeueAllByCallback()/
   * getQueue()/getQueues() methods are its surface.
   */
  private readonly _queue;
  /**
   * Durable replayable execution capability installed into this Agent's
   * Lifecycle. Declare definitions on the overridable
   * {@link taskDefinitions} property and start runs with
   * `this.tasks.run(name, input, options)`.
   *
   * @experimental The API surface may change before stabilizing.
   */
  readonly tasks: Tasks;
  /**
   * Named Task definitions for this Agent, resolved lazily on every
   * dispatch. Declare as a field so the map is rebuilt on every Durable
   * Object wake — that is what lets in-flight runs resolve their persisted
   * definition names after a restart:
   *
   * ```ts
   * readonly taskDefinitions = {
   *   "build-report@v1": async (input: ReportInput, step: TaskStep) => {
   *     // ...
   *   }
   * } satisfies TaskHandlers;
   * ```
   *
   * @experimental The API surface may change before stabilizing.
   */
  readonly taskDefinitions?: TaskHandlers;
  readonly mcp: MCPClientManager;
  /**
   * Initial state for the Agent
   * Override to provide default state values
   */
  initialState: TState;
  /**
   * 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.
   *
   * Delegates to the State capability, which owns lazy load and the
   * in-memory cache; Agent seeds `initialState` on first access.
   */
  get state(): TState;
  /**
   * 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;
  /**
   * Read the Agent's schema version from its KV key. A DO created before the
   * State capability owned `cf_agents_state` has the version as a row in that
   * table instead: read it once, move it to the key, and delete the row so the
   * table is left with a single owner. Synchronous (`storage.kv`) because the
   * constructor gates DDL on it.
   */
  private _readSchemaVersion;
  constructor(ctx: AgentContext, env: Env);
  private _restoreAgentFacetContext;
  /**
   * 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;
  /**
   * React to a persisted state change from the State capability.
   *
   * Reproduces the pre-migration steps 3-4: broadcast the new state to
   * protocol-enabled connections (excluding the originating connection) and
   * run the notification hook off the invocation tail.
   */
  private _handleStateChanged;
  /**
   * Update the Agent's state
   * @param state New state to set
   * @throws Error if called from a readonly connection context
   */
  setState(state: TState): void;
  /**
   * 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
   * with `registerInternalConnectionKeys` 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;
  /**
   * 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: TState, _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: TState | 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: TState | 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;
  /**
   * Wrap public subclass methods that may be entered outside Lifecycle, such as
   * native Durable Object RPC. Lifecycle hooks already have Agent context.
   */
  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 run in the background.
   *
   * The item is durable: it runs from the Lifecycle alarm event loop after
   * this call returns, in push order, one at a time, with retries per
   * `options.retry`, and survives the Durable Object leaving memory.
   * @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
   * @param options.id Stable id; a push with an existing id replaces that item
   * @returns The ID of the queued task
   */
  queue<T = unknown>(
    callback: keyof this,
    payload: T,
    options?: {
      retry?: RetryOptions;
      id?: string;
    }
  ): Promise<string>;
  /**
   * Dequeue a task by ID
   * @param id ID of the task to dequeue
   */
  dequeue(id: string): Promise<boolean>;
  /**
   * Dequeue all tasks
   */
  dequeueAll(): Promise<number>;
  /**
   * Dequeue all tasks by callback
   * @param callback Name of the callback to dequeue
   */
  dequeueAllByCallback(callback: string): Promise<number>;
  /**
   * Get a queued task by ID
   * @param id ID of the task to get
   * @returns The task or undefined if not found
   */
  getQueue<T = unknown>(id: string): Promise<QueueItem<T> | undefined>;
  /**
   * Get all queued tasks whose payload has `key` equal to `value`
   * @param key Key to filter by
   * @param value Value to filter by
   * @returns Array of matching QueueItem objects
   */
  getQueues<T = unknown>(key: string, value: string): Promise<QueueItem<T>[]>;
  private _lifecycleRouteAddress;
  private _routeLifecycleToRoot;
  private _routeLifecycleToTarget;
  /** Single native-RPC aperture for routed Lifecycle capabilities. */
  _cf_routeLifecycle(
    target: LifecycleRouteAddress | undefined,
    envelope: LifecycleRouteEnvelope
  ): Promise<unknown>;
  private _rootAlarmOwner;
  /**
   * 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>;
  /**
   * Acquire a root-owned keepAlive ref on behalf of a descendant facet.
   * Facets run in separate colocated isolates 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?: ScheduleOptions
  ): 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.
   *
   * @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.
   *
   * @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;
  /**
   * Run `fn` inside the fiber stash context so `this.stash()` keeps working
   * for turns executing on the `tasks` capability exactly as it does inside
   * legacy `runFiber()` closures.
   * @internal
   */
  protected _withFiberStash<T>(
    context: {
      id: string;
      signal: AbortSignal;
      stash: (data: unknown) => void;
    },
    fn: () => Promise<T>
  ): Promise<T>;
  /**
   * 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>;
  /**
   * 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>;
  /**
   * 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 `_syncHostJobs` 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;
  /**
   * Synchronize Agent-owned host jobs with current durable state.
   *
   * Replaces the old pull-based `getNextAlarm()` contribution: keep-alive
   * refs hold a `cf:keep-alive` job, and fiber-recovery / facet-run state
   * holds a `cf:housekeeping` job. Every state change that used to trigger
   * an alarm recalculation now re-pushes or cancels these jobs; queue
   * mutations re-arm the physical alarm automatically.
   * @internal
   */
  private _syncHostJobs;
  /**
   * The next wake fiber-recovery or facet-run housekeeping needs, or `null`
   * when neither has pending durable state.
   */
  private _nextHousekeepingWakeMs;
  /** Lifecycle alarm callback; Agent housekeeping runs after user alarm work. */
  onAlarm(): void;
  /**
   * Drive one Agent-owned host job from the Lifecycle queue.
   * @internal Dispatched by Lifecycle's alarm event loop; extensions add
   * job fns through {@link _onHostJob}.
   */
  onJob(
    context: LifecycleJobContext
  ): LifecycleJobOutcome | void | Promise<LifecycleJobOutcome | void>;
  /**
   * @internal Dispatch one host job fn. Agent extensions (Think) override
   * this to add fns and delegate unknown ones to `super`.
   */
  protected _onHostJob(
    fn: string,
    _context: LifecycleJobContext
  ): LifecycleJobOutcome | void | Promise<LifecycleJobOutcome | void>;
  /**
   * Apply host policy after the alarm memory-limit breaker records a strike.
   *
   * New chat hosts override this hook directly. The sealed-only fallback keeps
   * `agents` 0.23 compatible with already-published chat packages whose peer
   * ranges accept it but which implement only the former
   * `_cf_sealMemoryLimitedRecovery` template method. Queue membership remains
   * job-row policy; this invokes terminalization only and can be removed once
   * old chat releases no longer accept the current `agents` range.
   *
   * @internal
   */
  protected onAlarmMemoryLimit(context: MemoryLimitContext): Promise<void>;
  /**
   * Run Lifecycle's alarm event loop after the pending-destroy preamble.
   *
   * The alarm memory-limit circuit breaker (#1825) lives inside
   * `Lifecycle.alarm()`; capabilities and hosts opt into extra domain
   * policy via their `onMemoryLimit` / `onAlarmMemoryLimit` hooks and the
   * `recoveryLoop` schedule option.
   *
   * @remarks Use `this.schedule()` for named Agent callbacks. Reusable durable
   * work belongs in a capability that pushes jobs and implements `onJob()`.
   */
  alarm(): Promise<void>;
  /**
   * 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.
   *
   * The parent owns an upgraded WebSocket for its lifetime. Subsequent
   * frames wake the root parent, which forwards them to the child over
   * RPC and routes replies back to the native socket.
   *
   * @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>>;
  _cf_broadcastToSubAgent(
    ownerPath: ReadonlyArray<AgentPathStep>,
    message: string | ArrayBuffer | ArrayBufferView,
    without?: string[]
  ): Promise<void>;
  _cf_subAgentConnectionMetas(
    ownerPath: ReadonlyArray<AgentPathStep>
  ): Promise<DynamicAgentConnectionMeta[]>;
  _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>;
  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_forwardSubAgentWebSocketMessage;
  private _cf_forwardSubAgentWebSocketClose;
  _cf_handleSubAgentWebSocketConnect(
    bridge: DynamicAgentConnectionBridge,
    meta: DynamicAgentConnectionMeta
  ): Promise<void>;
  _cf_handleSubAgentWebSocketMessage(
    message: WSMessage,
    bridge: DynamicAgentConnectionBridge,
    meta: DynamicAgentConnectionMeta,
    replyBridge?: DynamicAgentConnectionBridge
  ): Promise<void>;
  _cf_handleSubAgentWebSocketClose(
    code: number,
    reason: string,
    wasClean: boolean,
    bridge: DynamicAgentConnectionBridge,
    meta: DynamicAgentConnectionMeta
  ): Promise<void>;
  protected _cf_hydrateSubAgentConnectionsFromRoot(): Promise<void>;
  /**
   * 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.dynamicAgents.has(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>;
  /**
   * 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<AgentPathStep>;
  /**
   * Ancestor chain + self, root-first. Convenient for logging.
   *
   * @experimental The API surface may change before stabilizing.
   */
  get selfPath(): ReadonlyArray<AgentPathStep>;
  /**
   * 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: DynamicAgentClass<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");
   * ```
   *
   * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.get()} instead.
   */
  subAgent<T extends Agent>(
    cls: DynamicAgentClass<T>,
    name: string
  ): Promise<DynamicAgentStub<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: DynamicAgentClass<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;
  /**
   * Run `body` in a fresh invocation scope with no native request/
   * connection context attached, so a child-facet RPC never sees
   * parent-owned I/O handles.
   * @internal
   */
  private _runFacetInitInvocation;
  /**
   * 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
   *
   * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.abort()} instead.
   */
  abortSubAgent(cls: DynamicAgentClass, 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
   *
   * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.delete()} instead.
   */
  deleteSubAgent(cls: DynamicAgentClass, name: string): Promise<void>;
  /**
   * 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 });
   *   }
   * }
   * ```
   *
   * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.has()} instead.
   */
  hasSubAgent<T extends Agent>(
    cls: DynamicAgentClass<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.
   *
   * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.list()} instead.
   */
  listSubAgents<T extends Agent>(
    cls: DynamicAgentClass<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 _pendingDestroyAlarm;
  private _hasPendingDestroy;
  /**
   * 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;
  /**
   * 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;
}
/**
 * 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;
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>;
/**
 * A wrapper for streaming responses in callable methods
 */
declare class StreamingResponse {
  private _connection;
  private _id;
  private _closed;
  constructor(connection: Connection, id: string);
  private _send;
  /**
   * 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-routing.d.ts
interface RoutingRetryEvent {
  error: unknown;
  attempt: number;
  maxAttempts: number;
  delayMs: number;
  name: string;
  className?: string;
}
/** Retry policy for Agent routing infrastructure failures. */
interface RoutingRetryOptions {
  /** Max number of attempts, including the first. Default: 3. */
  maxAttempts?: number;
  /** Base delay in milliseconds for exponential backoff. Default: 100. */
  baseDelayMs?: number;
  /** Maximum delay in milliseconds. Default: 800. */
  maxDelayMs?: number;
  /** Optional callback invoked before each retry delay. */
  onRetry?: (event: RoutingRetryEvent) => void | Promise<void>;
}
interface AgentRouteMatch<Env = Cloudflare.Env> {
  /** The Durable Object environment binding name. */
  className: Extract<keyof Env, string>;
  /** The named Durable Object instance extracted from the URL. */
  name: string;
}
interface AgentRouteOptions<
  Env = Cloudflare.Env,
  Props extends Record<string, unknown> = Record<string, unknown>
> {
  /** URL prefix before the binding and instance name. Default: `agents`. */
  prefix?: string;
  jurisdiction?: DurableObjectJurisdiction;
  locationHint?: DurableObjectLocationHint;
  /** Properties supplied before lifecycle startup. */
  props?: Props;
  /**
   * Whether to enable CORS for matched routes.
   *
   * When `true`, uses default permissive CORS headers:
   * - Access-Control-Allow-Origin: *
   * - Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS
   * - Access-Control-Allow-Headers: *
   * - Access-Control-Max-Age: 86400
   *
   * For credentialed requests, pass explicit headers with a specific origin.
   * When set to a `HeadersInit` value, uses those as the CORS headers instead.
   * CORS preflight requests are handled automatically for matched routes.
   */
  cors?: boolean | HeadersInit;
  /**
   * Retry transient Durable Object infrastructure errors thrown while routing.
   * Enabled by default; pass `false` to disable.
   */
  routingRetry?: false | RoutingRetryOptions;
  onBeforeConnect?: (
    request: Request,
    route: AgentRouteMatch<Env>
  ) => Response | Request | void | Promise<Response | Request | void>;
  onBeforeRequest?: (
    request: Request,
    route: AgentRouteMatch<Env>
  ) =>
    | Response
    | Request
    | void
    | Promise<Response | Request | undefined | void>;
}
/** Configuration options for {@link routeAgentRequest}. */
type AgentOptions<Env> = AgentRouteOptions<Env>;
/** Options for resolving and starting a named Agent. */
type AgentGetOptions<
  Env,
  Props extends Record<string, unknown> = Record<string, unknown>
> = Pick<
  AgentRouteOptions<Env, Props>,
  "jurisdiction" | "locationHint" | "props" | "routingRetry"
>;
/**
 * Route `/agents/:binding/:name` HTTP and WebSocket requests to a named
 * Durable Object. The target may extend `Agent` or compose `Lifecycle`
 * directly into a plain `DurableObject`.
 *
 * @param request - Incoming Worker request.
 * @param env - Worker environment containing Durable Object bindings.
 * @param options - Routing options.
 * @returns The matched response, or `null` when the path does not match.
 */
declare function routeAgentRequest<Env>(
  request: Request,
  env: Env,
  options?: AgentOptions<Env>
): Promise<Response | null>;
/**
 * Get a named Agent stub after its lifecycle startup has completed.
 *
 * @param namespace - Agent Durable Object namespace.
 * @param name - Agent instance name.
 * @param options - Placement, startup properties, and retry options.
 * @returns The initialized Agent 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>>;
//#endregion
export {
  DetachedAgentToolConfig as $,
  ElicitRequest$2 as $t,
  getCurrentAgent as A,
  withInvocationScope as An,
  MCPAIToolSet as At,
  AgentToolInterruptedReason as B,
  MCPServerFilter as Bt,
  MCPServersState as C,
  buildAgentPath as Cn,
  WorkflowQueryCriteria as Ct,
  StartFiberResult as D,
  getSubAgentByName as Dn,
  ElicitRequest$1 as Dt,
  StartFiberOptions as E,
  buildSubAgentPathUnchecked as En,
  WorkflowTrackingRow as Et,
  AgentToolDisplayMetadata as F,
  MCPClientOAuthCallbackConfig as Ft,
  AgentToolRunInfo as G,
  normalizeServerId as Gt,
  AgentToolMilestone as H,
  MCP_SERVER_ID_MAX_LENGTH as Ht,
  AgentToolEvent as I,
  MCPClientOAuthResult as It,
  AgentToolRunState as J,
  RPCClientTransport as Jt,
  AgentToolRunInspection as K,
  MCPElicitationHandler as Kt,
  AgentToolEventMessage as L,
  MCPConnectionResult as Lt,
  AGENT_TOOL_MILESTONE_PART as M,
  MCPClientElicitationHandlers as Mt,
  AGENT_TOOL_PROGRESS_PART as N,
  MCPClientManager as Nt,
  StateUpdateMessage as O,
  parseSubAgentPath as On,
  ElicitResult$2 as Ot,
  AgentToolChildAdapter as P,
  MCPClientManagerOptions as Pt,
  ChatCapableAgentClass as Q,
  RPC_DO_PREFIX as Qt,
  AgentToolEventState as R,
  MCPDiscoverResult as Rt,
  MCPServerMessage as S,
  SubAgentPathMatch as Sn,
  WorkflowProgressCallback as St,
  RPCResponse as T,
  buildSubAgentPath as Tn,
  WorkflowStatus as Tt,
  AgentToolProgress as U,
  RegisterServerOptions as Ut,
  AgentToolLifecycleResult as V,
  MCPServerOptions as Vt,
  AgentToolProgressSnapshot as W,
  getNamespacedData as Wt,
  AgentToolStoredChunk as X,
  RPCServerTransport as Xt,
  AgentToolRunStatus as Y,
  RPCClientTransportOptions as Yt,
  AgentToolTerminalStatus as Z,
  RPCServerTransportOptions as Zt,
  FiberRecoveryContext as _,
  DynamicAgentClass as _n,
  WorkflowErrorCallback as _t,
  routeAgentRequest as a,
  createMcpHandler$1 as an,
  AgentWorkflowOrigin as at,
  ListFibersOptions as b,
  BuildAgentPathOptions as bn,
  WorkflowInfo as bt,
  Agent as c,
  CreateMcpHandlerOptions$1 as cn,
  AgentWorkflowStep as ct,
  AgentStaticOptions as d,
  MCPStorageApi as dn,
  RunWorkflowOptions as dt,
  ElicitRequestSchema as en,
  DetachedRunAgentToolResult as et,
  DEFAULT_AGENT_STATIC_OPTIONS as f,
  TransportState as fn,
  WaitForApprovalOptions as ft,
  FiberInspection as g,
  StreamableHTTPEdgeClientTransport as gn,
  WorkflowCompleteCallback as gt,
  FiberContext as h,
  SSEEdgeClientTransport as hn,
  WorkflowCallbackType as ht,
  getAgentByName as i,
  DurableObjectEventStore as in,
  AgentWorkflowInternalParams as it,
  routeAgentEmail as j,
  MCPClientElicitationHandler as jt,
  StreamingResponse as k,
  routeSubAgentRequest as kn,
  MCPAITool as kt,
  AgentContext as l,
  LegacyMcpHandler as ln,
  ApprovalEventPayload as lt,
  EmailRoutingOptions as m,
  WorkerTransportOptions as mn,
  WorkflowCallbackBase as mt,
  AgentOptions as n,
  McpAgent as nn,
  RunAgentToolResult as nt,
  AddMcpServerOptions as o,
  experimental_createMcpHandler as on,
  AgentWorkflowParams as ot,
  DeleteFibersOptions as p,
  WorkerTransport as pn,
  WorkflowCallback as pt,
  AgentToolRunPart as q,
  MCPElicitationHandlers as qt,
  RoutingRetryOptions as r,
  ClearableEventStore as rn,
  AgentWorkflowEvent as rt,
  AddRpcMcpServerOptions as s,
  CreateLegacyMcpHandlerOptions as sn,
  AgentWorkflowPathStep as st,
  AgentGetOptions as t,
  ElicitResult$3 as tn,
  RunAgentToolOptions as tt,
  AgentNamespace as u,
  createLegacyMcpHandler as un,
  DefaultProgress as ut,
  FiberRecoveryResult as v,
  DynamicAgentStub as vn,
  WorkflowEventCallback as vt,
  RPCRequest as w,
  buildAgentUrl as wn,
  WorkflowRejectedError as wt,
  MCPServer as x,
  SUB_PREFIX as xn,
  WorkflowPage as xt,
  FiberStatus as y,
  AgentPathStep as yn,
  WorkflowEventPayload as yt,
  AgentToolFailure as z,
  MCPOAuthCallbackResult as zt
};
//# sourceMappingURL=agent-routing-B2XLNMxq.d.ts.map
