agents 0.13.3 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +6 -4
  2. package/dist/{agent-tool-types-l98LCbBl.d.ts → agent-tool-types-BAJWu8s4.d.ts} +474 -117
  3. package/dist/agent-tool-types.d.ts +13 -11
  4. package/dist/{agent-tools-Bg5ilERh.d.ts → agent-tools-0R6KEert.d.ts} +2 -2
  5. package/dist/{agent-tools-BAdX1vdI.js → agent-tools-DYrkT-Kx.js} +46 -6
  6. package/dist/agent-tools-DYrkT-Kx.js.map +1 -0
  7. package/dist/agent-tools.d.ts +14 -20
  8. package/dist/agent-tools.js +10 -6
  9. package/dist/agent-tools.js.map +1 -1
  10. package/dist/browser/ai.d.ts +1 -1
  11. package/dist/browser/ai.js +1 -1
  12. package/dist/browser/index.d.ts +1 -1
  13. package/dist/browser/index.js +1 -1
  14. package/dist/browser/tanstack-ai.d.ts +1 -1
  15. package/dist/browser/tanstack-ai.js +1 -1
  16. package/dist/chat/index.d.ts +162 -19
  17. package/dist/chat/index.js +97 -13
  18. package/dist/chat/index.js.map +1 -1
  19. package/dist/chat-sdk/index.d.ts +5 -5
  20. package/dist/chat-sdk/index.js +2 -2
  21. package/dist/chat-sdk/index.js.map +1 -1
  22. package/dist/{classPrivateFieldGet2-Evpt0SEr.js → classPrivateFieldGet2-D_obpP6O.js} +5 -5
  23. package/dist/classPrivateMethodInitSpec-10iTYB7F.js +7 -0
  24. package/dist/{client-D1kFXo80.js → client-FUizKzj2.js} +299 -95
  25. package/dist/client-FUizKzj2.js.map +1 -0
  26. package/dist/client.d.ts +1 -1
  27. package/dist/{compaction-helpers-B-pG5J22.d.ts → compaction-helpers-BEUILPss.d.ts} +59 -33
  28. package/dist/{compaction-helpers-fJyf8j4m.js → compaction-helpers-iiKMr2TQ.js} +22 -3
  29. package/dist/compaction-helpers-iiKMr2TQ.js.map +1 -0
  30. package/dist/{do-oauth-client-provider-4OKQU9rT.d.ts → do-oauth-client-provider-D4ZwyBDu.d.ts} +21 -1
  31. package/dist/{email-J0GGS3sa.d.ts → email-CL27preh.d.ts} +1 -1
  32. package/dist/email.d.ts +2 -2
  33. package/dist/experimental/memory/session/index.d.ts +30 -25
  34. package/dist/experimental/memory/session/index.js +7 -2
  35. package/dist/experimental/memory/session/index.js.map +1 -1
  36. package/dist/experimental/memory/utils/index.d.ts +12 -10
  37. package/dist/experimental/memory/utils/index.js +2 -2
  38. package/dist/{index-DKey3P4s.d.ts → index-RJ4OxMOe.d.ts} +270 -1
  39. package/dist/index.d.ts +74 -67
  40. package/dist/index.js +485 -64
  41. package/dist/index.js.map +1 -1
  42. package/dist/{internal_context-BZrMS0B5.d.ts → internal_context-Dg4Cgjcu.d.ts} +1 -1
  43. package/dist/internal_context.d.ts +1 -1
  44. package/dist/mcp/client.d.ts +17 -13
  45. package/dist/mcp/client.js +2 -2
  46. package/dist/mcp/do-oauth-client-provider.d.ts +1 -1
  47. package/dist/mcp/do-oauth-client-provider.js +143 -17
  48. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  49. package/dist/mcp/index.d.ts +35 -27
  50. package/dist/mcp/index.js +402 -69
  51. package/dist/mcp/index.js.map +1 -1
  52. package/dist/observability/index.d.ts +1 -1
  53. package/dist/observability/index.js +15 -1
  54. package/dist/observability/index.js.map +1 -1
  55. package/dist/react.d.ts +3 -3
  56. package/dist/react.js +1 -1
  57. package/dist/{retries-BVdRl5ZE.d.ts → retries-CF_HKSlJ.d.ts} +1 -1
  58. package/dist/retries.d.ts +1 -1
  59. package/dist/serializable.d.ts +1 -1
  60. package/dist/{shared-Cvj92byG.d.ts → shared-4CAYLCTO.d.ts} +1 -1
  61. package/dist/{shared-CiKaIK4h.js → shared-BIpUk4G5.js} +3 -7
  62. package/dist/{shared-CiKaIK4h.js.map → shared-BIpUk4G5.js.map} +1 -1
  63. package/dist/skills/index.d.ts +236 -0
  64. package/dist/skills/index.js +1326 -0
  65. package/dist/skills/index.js.map +1 -0
  66. package/dist/sub-routing.d.ts +6 -6
  67. package/dist/{tool-output-truncation-CH-khbZ3.js → tool-output-truncation-CNnnGZQ3.js} +1 -1
  68. package/dist/{tool-output-truncation-CH-khbZ3.js.map → tool-output-truncation-CNnnGZQ3.js.map} +1 -1
  69. package/dist/{types-_JjKmv-l.d.ts → types-6Zo2zfoO.d.ts} +1 -1
  70. package/dist/types.d.ts +1 -1
  71. package/dist/vite.d.ts +1 -1
  72. package/dist/vite.js +248 -2
  73. package/dist/vite.js.map +1 -1
  74. package/dist/{workflow-types-Dkzg4hAx.d.ts → workflow-types-SrZK_o9p.d.ts} +1 -1
  75. package/dist/workflow-types.d.ts +1 -1
  76. package/dist/workflows.d.ts +13 -3
  77. package/dist/workflows.js +10 -1
  78. package/dist/workflows.js.map +1 -1
  79. package/package.json +31 -13
  80. package/skills-module.d.ts +22 -0
  81. package/dist/agent-tools-BAdX1vdI.js.map +0 -1
  82. package/dist/client-D1kFXo80.js.map +0 -1
  83. package/dist/compaction-helpers-fJyf8j4m.js.map +0 -1
@@ -1,11 +1,11 @@
1
- import { n as AgentEmail } from "./internal_context-BZrMS0B5.js";
2
- import { t as RetryOptions } from "./retries-BVdRl5ZE.js";
1
+ import { n as AgentEmail } from "./internal_context-Dg4Cgjcu.js";
2
+ import { t as RetryOptions } from "./retries-CF_HKSlJ.js";
3
3
  import {
4
4
  n as Observability,
5
5
  r as ObservabilityEvent,
6
6
  s as MCPObservabilityEvent
7
- } from "./index-DKey3P4s.js";
8
- import { t as AgentMcpOAuthProvider } from "./do-oauth-client-provider-4OKQU9rT.js";
7
+ } from "./index-RJ4OxMOe.js";
8
+ import { t as AgentMcpOAuthProvider } from "./do-oauth-client-provider-D4ZwyBDu.js";
9
9
  import {
10
10
  _ as WorkflowPage,
11
11
  g as WorkflowInfo,
@@ -13,9 +13,9 @@ import {
13
13
  l as WorkflowCallback,
14
14
  s as RunWorkflowOptions,
15
15
  y as WorkflowQueryCriteria
16
- } from "./workflow-types-Dkzg4hAx.js";
17
- import { t as MessageType } from "./types-_JjKmv-l.js";
18
- import { r as EmailResolver } from "./email-J0GGS3sa.js";
16
+ } from "./workflow-types-SrZK_o9p.js";
17
+ import { t as MessageType } from "./types-6Zo2zfoO.js";
18
+ import { r as EmailResolver } from "./email-CL27preh.js";
19
19
  import { ToolSet, UIMessage } from "ai";
20
20
  import { RpcTarget } from "cloudflare:workers";
21
21
  import {
@@ -67,7 +67,15 @@ import {
67
67
  } from "@modelcontextprotocol/sdk/shared/transport.js";
68
68
  import { Server as Server$1 } from "@modelcontextprotocol/sdk/server/index.js";
69
69
  import { Client as Client$1 } from "@modelcontextprotocol/sdk/client";
70
- import { EventStore } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
70
+ import {
71
+ EventId,
72
+ EventStore,
73
+ StreamId
74
+ } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
75
+ import {
76
+ EventStore as EventStore$1,
77
+ StreamId as StreamId$1
78
+ } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
71
79
 
72
80
  //#region src/sub-routing.d.ts
73
81
  /**
@@ -268,8 +276,30 @@ interface WorkerTransportOptions {
268
276
  */
269
277
  storage?: MCPStorageApi;
270
278
  /**
271
- * Event store for resumability support.
272
- * If provided, enables clients to reconnect and resume messages using Last-Event-ID.
279
+ * Event store for SSE resumability.
280
+ *
281
+ * When set, the transport assigns a globally-unique `id:` to each SSE
282
+ * event and replays missed events when a client reconnects with the
283
+ * `Last-Event-ID` header. Both GET (standalone listen stream) and POST
284
+ * (tool response stream) events are stored and replayable per the
285
+ * MCP 2025-03-26 spec.
286
+ *
287
+ * Configuring an event store **disables the server-side keepalive**
288
+ * on the standalone GET stream — idle drops are recovered by
289
+ * reconnect rather than prevented by writing bytes. Without an event
290
+ * store, the GET stream still gets the 25s comment-frame keepalive
291
+ * so long-lived idle listeners aren't closed by the Cloudflare edge
292
+ * ~5min watchdog.
293
+ *
294
+ * POST response streams always get the keepalive regardless of this
295
+ * setting: in-progress tool calls have no way to recover
296
+ * mid-execution without staying connected, so we don't let the
297
+ * stream drop in the first place.
298
+ *
299
+ * Bring your own {@link EventStore} implementation — e.g.
300
+ * `new DurableObjectEventStore(this.ctx.storage)` when embedding
301
+ * `WorkerTransport` inside a Durable Object / Agent. See
302
+ * cloudflare/agents#1583.
273
303
  */
274
304
  eventStore?: EventStore;
275
305
  /**
@@ -379,6 +409,94 @@ declare function experimental_createMcpHandler(
379
409
  options?: CreateMcpHandlerOptions
380
410
  ): (request: Request, env: unknown, ctx: ExecutionContext) => Promise<Response>;
381
411
  //#endregion
412
+ //#region src/mcp/event-store.d.ts
413
+ /**
414
+ * Durable Object–backed {@link EventStore} for SSE resumability.
415
+ *
416
+ * Default for `McpAgent`. Override `McpAgent.getEventStore()` to swap
417
+ * or disable.
418
+ *
419
+ * ## Storage layout
420
+ *
421
+ * Events are stored under `__mcp_event__:<streamId>:<seqHex>`, where
422
+ * `<seqHex>` is a 16-char zero-padded counter so events in a stream
423
+ * sort lexicographically and `getStreamIdForEventId` can recover the
424
+ * stream from `eventId` without a storage hit.
425
+ *
426
+ * ## Lifecycle
427
+ *
428
+ * Each POST tool-call stream's events live only until the final
429
+ * response is delivered. The transport calls {@link clearStream}
430
+ * immediately after writing the close frame, so storage growth is
431
+ * bounded by the in-flight POST streams plus the standalone GET
432
+ * stream. There is no background sweep — quiescent agents do no work,
433
+ * and the DO itself dies with the session.
434
+ *
435
+ * Standalone GET stream events (`_GET_stream`) are *not* cleared
436
+ * automatically; they accumulate for the lifetime of the DO. Bounded
437
+ * by session length in practice.
438
+ *
439
+ * Trade-off: if the client TCP connection dies *after* the close
440
+ * frame has been enqueued on the WS but before the bytes reach the
441
+ * client, the final message is unreplayable. Every earlier event in
442
+ * the stream is still replayable while the in-flight stream is open.
443
+ *
444
+ * ## Stream id constraints
445
+ *
446
+ * `streamId` MUST NOT contain `:`. `storeEvent` asserts this so
447
+ * embedders using custom stream ids fail loudly rather than risk
448
+ * prefix-scan collisions (e.g. clearing `a` accidentally hitting
449
+ * `a:b`). Default ids (`connection.id` UUIDs and the literal
450
+ * `_GET_stream`) already satisfy this.
451
+ */
452
+ declare class DurableObjectEventStore implements EventStore {
453
+ private static readonly EVENT_KEY_PREFIX;
454
+ private static readonly SEQ_PAD;
455
+ /** DO storage caps multi-key delete at 128. */
456
+ private static readonly DELETE_CHUNK;
457
+ /** Defensive ceiling on a single replay batch. A live stream's
458
+ * event count is small (progress notifications + final result);
459
+ * this is here so a pathological history can't OOM the DO. */
460
+ private static readonly REPLAY_LIMIT;
461
+ private readonly storage;
462
+ /** In-memory seq counters per stream, rehydrated lazily from storage. */
463
+ private readonly seqByStream;
464
+ private readonly seqInit;
465
+ constructor(storage: DurableObjectStorage);
466
+ storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise<EventId>;
467
+ getStreamIdForEventId(eventId: EventId): Promise<StreamId | undefined>;
468
+ replayEventsAfter(
469
+ lastEventId: EventId,
470
+ {
471
+ send
472
+ }: {
473
+ send: (eventId: EventId, message: JSONRPCMessage) => Promise<void>;
474
+ }
475
+ ): Promise<StreamId>;
476
+ /**
477
+ * Drop the event log for a single stream. Called by the transport
478
+ * immediately after a POST's final response has been written to the
479
+ * wire — no future `Last-Event-ID` for this stream is expected to
480
+ * resolve.
481
+ *
482
+ * Lists and deletes in chunks of {@link DELETE_CHUNK} (128, the DO
483
+ * storage cap) so we never load the entire event log into memory.
484
+ * After deleting, the next `list` call won't see the deleted keys,
485
+ * so passing `start: <prefix>` again is enough — no cursor bookkeeping.
486
+ */
487
+ clearStream(streamId: StreamId): Promise<void>;
488
+ private ensureSeqLoaded;
489
+ }
490
+ //#endregion
491
+ //#region src/mcp/transport.d.ts
492
+ /**
493
+ * An {@link EventStore} that supports dropping all events for a single
494
+ * stream id. Implemented by {@link DurableObjectEventStore}.
495
+ */
496
+ interface ClearableEventStore extends EventStore$1 {
497
+ clearStream(streamId: StreamId$1): Promise<void>;
498
+ }
499
+ //#endregion
382
500
  //#region src/mcp/index.d.ts
383
501
  declare abstract class McpAgent<
384
502
  Env extends Cloudflare.Env = Cloudflare.Env,
@@ -396,6 +514,45 @@ declare abstract class McpAgent<
396
514
  abstract init(): Promise<void>;
397
515
  setInitializeRequest(initializeRequest: JSONRPCMessage): Promise<void>;
398
516
  getInitializeRequest(): Promise<JSONRPCMessage | undefined>;
517
+ /**
518
+ * Storage key prefix for the `streamId -> requestIds` mapping used
519
+ * to support POST stream resumption across WebSocket reconnects.
520
+ *
521
+ * @internal
522
+ */
523
+ private static readonly STREAM_REQS_KEY_PREFIX;
524
+ /** Persist the `requestIds` for a POST stream. @internal */
525
+ setStreamRequestIds(streamId: string, requestIds: RequestId[]): Promise<void>;
526
+ /** Read the persisted `requestIds` for a POST stream. @internal */
527
+ getStreamRequestIds(streamId: string): Promise<RequestId[] | undefined>;
528
+ /** Drop the persisted `requestIds` for a POST stream. @internal */
529
+ deleteStreamRequestIds(streamId: string): Promise<void>;
530
+ /**
531
+ * Reverse lookup: find which POST stream a given `requestId` belongs
532
+ * to, and return the stream's full `requestIds` list in the same
533
+ * pass. Used by the transport when the originating WS has dropped,
534
+ * so `send()` can still record events for replay and decide whether
535
+ * the stream is fully responded — mirrors the SDK's
536
+ * `_requestToStreamMapping` which outlives connection loss.
537
+ *
538
+ * Returning `requestIds` alongside `streamId` lets `send()` skip a
539
+ * second `getStreamRequestIds` read on the same key.
540
+ *
541
+ * O(n) in the number of in-flight POST streams — single-digit in
542
+ * practice since each stream is cleaned up on its final response.
543
+ * The `limit` is a defensive ceiling so an abandoned-POST leak can't
544
+ * unbounded-load this scan; if you hit it, something else has gone
545
+ * wrong and `send()` will throw `No active stream found`.
546
+ *
547
+ * @internal
548
+ */
549
+ getStreamForRequestId(requestId: RequestId): Promise<
550
+ | {
551
+ streamId: string;
552
+ requestIds: RequestId[];
553
+ }
554
+ | undefined
555
+ >;
399
556
  /** Read the transport type for this agent.
400
557
  * This relies on the naming scheme being `sse:${sessionId}`,
401
558
  * `streamable-http:${sessionId}`, or `rpc:${sessionId}`.
@@ -422,6 +579,21 @@ declare abstract class McpAgent<
422
579
  * ```
423
580
  */
424
581
  protected getRpcTransportOptions(): RPCServerTransportOptions;
582
+ /**
583
+ * Returns the {@link EventStore} for SSE resumability. Defaults to a
584
+ * {@link DurableObjectEventStore} backed by this agent's storage,
585
+ * letting clients reconnect with `Last-Event-ID` after the Cloudflare
586
+ * edge closes an idle SSE stream (~5 minute watchdog) instead of
587
+ * relying on a server-side keepalive that would block hibernation.
588
+ *
589
+ * Per-stream events are cleared by the transport immediately after
590
+ * the final response is written to the wire, so there's no
591
+ * background cleanup — storage cost is bounded by the in-flight
592
+ * streams alone.
593
+ *
594
+ * Override to disable (`return undefined`) or swap implementations.
595
+ */
596
+ protected getEventStore(): EventStore | undefined;
425
597
  /** Returns a new transport matching the type of the Agent. */
426
598
  private initTransport;
427
599
  /** Update and store the props */
@@ -535,10 +707,10 @@ interface RPCServerTransportOptions {
535
707
  }
536
708
  declare class RPCServerTransport implements Transport {
537
709
  private _started;
538
- private _pendingResponse;
539
- private _responseResolver;
540
710
  private _protocolVersion?;
541
711
  private _timeout;
712
+ private _pendingRequests;
713
+ private _pendingContinuations;
542
714
  sessionId?: string;
543
715
  onclose?: () => void;
544
716
  onerror?: (error: Error) => void;
@@ -548,17 +720,25 @@ declare class RPCServerTransport implements Transport {
548
720
  getProtocolVersion(): string | undefined;
549
721
  start(): Promise<void>;
550
722
  close(): Promise<void>;
551
- send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void>;
723
+ private _makeTimeout;
724
+ private _appendPending;
725
+ private _completePending;
726
+ private _completeRequest;
727
+ private _appendRequest;
728
+ private _completeContinuation;
729
+ private _appendContinuation;
730
+ send(message: JSONRPCMessage, options?: TransportSendOptions): Promise<void>;
552
731
  /**
553
732
  * @internal Called by McpAgent.handleMcpMessage() — not for external use.
554
733
  *
555
- * Wait for the next send() call and return whatever it produces.
734
+ * Wait for the next unmatched send() call that expects a client response or
735
+ * completes a resumed tool call.
556
736
  *
557
- * Used after resolving an elicitation response: the tool handler is still
558
- * running and will eventually call send() with either another elicitation
559
- * request or the final tool result. This method captures that send() using
560
- * the same _responseResolver / _pendingResponse / timeout mechanism as
561
- * handle().
737
+ * Used after resolving an elicitation response: the original tool call has
738
+ * already returned the elicitation request to the RPC client, and the resumed
739
+ * tool handler will eventually send the final tool result. That final response
740
+ * has the original tool request id, so there is no active handle() waiter left
741
+ * for id-based routing; this continuation waiter receives it instead.
562
742
  */
563
743
  _awaitPendingResponse(): Promise<
564
744
  JSONRPCMessage | JSONRPCMessage[] | undefined
@@ -658,7 +838,12 @@ declare class MCPClientConnection {
658
838
  /**
659
839
  * Complete OAuth authorization
660
840
  */
661
- completeAuthorization(code: string): Promise<void>;
841
+ completeAuthorization(
842
+ code: string,
843
+ options?: {
844
+ alreadyAccepted?: boolean;
845
+ }
846
+ ): Promise<void>;
662
847
  /**
663
848
  * Discover server capabilities and register tools, resources, prompts, and templates.
664
849
  * This method does the work but does not manage connection state - that's handled by discover().
@@ -872,6 +1057,31 @@ type MCPServerRow = {
872
1057
  };
873
1058
  //#endregion
874
1059
  //#region src/mcp/client.d.ts
1060
+ /** Maximum length of a normalized MCP server id. */
1061
+ declare const MCP_SERVER_ID_MAX_LENGTH = 64;
1062
+ /**
1063
+ * Normalize a caller-supplied MCP server id into a stable, storage- and
1064
+ * tool-name-safe form.
1065
+ *
1066
+ * The id is surfaced in several places where the character set matters:
1067
+ * - as the primary key in the `cf_agents_mcp_servers` SQLite table
1068
+ * - embedded in AI SDK tool names as `` `tool_${id.replace(/-/g, "")}_${tool}` ``
1069
+ * (tool names must match `/^[A-Za-z0-9_]+$/`)
1070
+ * - as a key on the `mcpConnections` map and OAuth provider storage
1071
+ *
1072
+ * Rules:
1073
+ * 1. Lowercase.
1074
+ * 2. Replace any run of disallowed characters with a single `-`.
1075
+ * 3. Collapse repeated `-` and trim leading/trailing `-`/`_`.
1076
+ * 4. Prefix with `id-` if the result is empty or doesn't start with a letter.
1077
+ * 5. Truncate to {@link MCP_SERVER_ID_MAX_LENGTH} characters.
1078
+ *
1079
+ * @example
1080
+ * normalizeServerId("my-supplied-id"); // "my-supplied-id"
1081
+ * normalizeServerId("GitHub MCP!"); // "github-mcp"
1082
+ * normalizeServerId("42-things"); // "id-42-things"
1083
+ */
1084
+ declare function normalizeServerId(input: string): string;
875
1085
  /**
876
1086
  * Options that can be stored in the server_options column
877
1087
  * This is what gets JSON.stringify'd and stored in the database
@@ -1009,6 +1219,31 @@ declare class MCPClientManager {
1009
1219
  private sql;
1010
1220
  private saveServerToStorage;
1011
1221
  private removeServerFromStorage;
1222
+ /**
1223
+ * Rename a server's id, in-place, across every place the id is used as a
1224
+ * key. Used to JIT-migrate servers that were originally registered under an
1225
+ * auto-generated nanoid to a caller-supplied stable id (see
1226
+ * `Agent.addMcpServer`'s `{ id }` option).
1227
+ *
1228
+ * Migrates:
1229
+ * - the `cf_agents_mcp_servers` row (primary key)
1230
+ * - the in-memory `mcpConnections` map key
1231
+ * - the connection disposables map key
1232
+ * - the attached `authProvider.serverId`, if any
1233
+ * - OAuth-related storage keys under `/{clientName}/{oldId}/...`
1234
+ *
1235
+ * Safe to call when no OAuth keys exist (RPC / bearer-token HTTP servers).
1236
+ * If `oldId === newId` this is a no-op. If a row already exists under
1237
+ * `newId`, throws — the caller is expected to have verified uniqueness.
1238
+ *
1239
+ * @internal Exposed for `Agent.addMcpServer` JIT-migration.
1240
+ */
1241
+ migrateServerId(
1242
+ oldId: string,
1243
+ newId: string,
1244
+ clientName: string
1245
+ ): Promise<void>;
1246
+ private _renameInMemoryConnection;
1012
1247
  private getServersFromStorage;
1013
1248
  private filterConnections;
1014
1249
  /**
@@ -1018,6 +1253,11 @@ declare class MCPClientManager {
1018
1253
  private clearServerAuthUrl;
1019
1254
  private updateStoredSessionId;
1020
1255
  private failConnection;
1256
+ private isAuthAcceptedConnection;
1257
+ private oauthCallbackSuccess;
1258
+ private runWithCodeVerifierState;
1259
+ private consumeStaleOAuthState;
1260
+ private completeAuthorizationAndCleanupVerifier;
1021
1261
  /**
1022
1262
  * Create an auth provider for a server
1023
1263
  * @internal
@@ -1909,7 +2149,8 @@ type FiberRecoveryContext = {
1909
2149
  * Epoch milliseconds when the fiber row was inserted (when `runFiber`
1910
2150
  * started). Use `Date.now() - createdAt` to gate stale recoveries.
1911
2151
  */
1912
- createdAt: number;
2152
+ createdAt: number /** Why this recovery hook is running. */;
2153
+ recoveryReason: "interrupted";
1913
2154
  [key: string]: unknown;
1914
2155
  };
1915
2156
  type InternalFiberOptions = {
@@ -1962,7 +2203,18 @@ type MCPServer = {
1962
2203
  * Options for adding an MCP server
1963
2204
  */
1964
2205
  type AddMcpServerOptions = {
1965
- /** OAuth callback host (auto-derived from request if omitted) */ callbackHost?: string;
2206
+ /**
2207
+ * Optional caller-supplied stable server id. When provided, this id is used
2208
+ * for storage, restore, and tool-name namespacing instead of a generated
2209
+ * `nanoid`. The value is normalized via {@link normalizeServerId} — for
2210
+ * connector-style integrations this lets `addMcpServer` keep producing
2211
+ * keys like `tool_github_create_pull_request`.
2212
+ *
2213
+ * Throws if an existing server already uses the same (normalized) id but a
2214
+ * different name or url.
2215
+ */
2216
+ id?: string /** OAuth callback host (auto-derived from request if omitted) */;
2217
+ callbackHost?: string;
1966
2218
  /**
1967
2219
  * Custom callback URL path — bypasses the default `/agents/{class}/{name}/callback` construction.
1968
2220
  * Required when `sendIdentityOnConnect` is `false` to prevent leaking the instance name.
@@ -1983,7 +2235,16 @@ type AddMcpServerOptions = {
1983
2235
  * Options for adding an MCP server via RPC (Durable Object binding)
1984
2236
  */
1985
2237
  type AddRpcMcpServerOptions = {
1986
- /** Props to pass to the McpAgent instance */ props?: Record<string, unknown>;
2238
+ /**
2239
+ * Optional caller-supplied stable server id. When provided, this id is used
2240
+ * for storage, restore, and tool-name namespacing instead of a generated
2241
+ * `nanoid`. The value is normalized via {@link normalizeServerId}.
2242
+ *
2243
+ * Throws if an existing server already uses the same (normalized) id but a
2244
+ * different name or url.
2245
+ */
2246
+ id?: string /** Props to pass to the McpAgent instance */;
2247
+ props?: Record<string, unknown>;
1987
2248
  };
1988
2249
  /**
1989
2250
  * Default options for Agent configuration.
@@ -2007,7 +2268,15 @@ declare const DEFAULT_AGENT_STATIC_OPTIONS: {
2007
2268
  maxAttempts: number;
2008
2269
  baseDelayMs: number;
2009
2270
  maxDelayMs: number;
2010
- };
2271
+ } /** Timeout for internal framework fiber recovery hooks. */;
2272
+ fiberRecoveryHookTimeoutMs: number /** Soft deadline for one interrupted-fiber recovery scan. */;
2273
+ fiberRecoveryScanDeadlineMs: number;
2274
+ /**
2275
+ * Maximum age of an unmanaged interrupted-fiber row before recovery gives
2276
+ * up. Bounds repeated retries of a `onFiberRecovered()` hook that keeps
2277
+ * throwing so a poison row cannot re-trigger forever across boots.
2278
+ */
2279
+ fiberRecoveryMaxAgeMs: number;
2011
2280
  };
2012
2281
  /**
2013
2282
  * Configuration options for the Agent.
@@ -2027,6 +2296,19 @@ interface AgentStaticOptions {
2027
2296
  keepAliveIntervalMs?: number;
2028
2297
  /** Default retry options for schedule(), queue(), and this.retry(). */
2029
2298
  retry?: RetryOptions;
2299
+ /**
2300
+ * Timeout in milliseconds for internal framework fiber recovery hooks.
2301
+ * User-defined `onFiberRecovered()` hooks are not timed out by default.
2302
+ */
2303
+ fiberRecoveryHookTimeoutMs?: number;
2304
+ /** Soft deadline in milliseconds for one interrupted-fiber recovery scan. */
2305
+ fiberRecoveryScanDeadlineMs?: number;
2306
+ /**
2307
+ * Maximum age in milliseconds of an unmanaged interrupted-fiber row before
2308
+ * recovery stops retrying a repeatedly-throwing `onFiberRecovered()` hook
2309
+ * and discards the row. Set to `0` to retain rows indefinitely.
2310
+ */
2311
+ fiberRecoveryMaxAgeMs?: number;
2030
2312
  }
2031
2313
  declare function getCurrentAgent<
2032
2314
  T extends Agent<Cloudflare.Env> = Agent<Cloudflare.Env>
@@ -2130,6 +2412,8 @@ declare class Agent<
2130
2412
  private _managedFiberTerminalWaiters;
2131
2413
  /** @internal Prevents re-entrant recovery from overlapping alarm ticks. */
2132
2414
  private _runFiberRecoveryInProgress;
2415
+ /** @internal Single-flight background recovery for parent agent-tool rows. */
2416
+ private _agentToolRunRecoveryPromise;
2133
2417
  private _ParentClass;
2134
2418
  readonly mcp: MCPClientManager;
2135
2419
  /**
@@ -2823,6 +3107,9 @@ declare class Agent<
2823
3107
  private _applyManagedFiberRecoveryResult;
2824
3108
  private _settleManagedFiberExecution;
2825
3109
  private _parseFiberRecoverySnapshot;
3110
+ private _fiberRecoveryPayload;
3111
+ private _withFiberRecoveryTimeout;
3112
+ private _recordFiberRecoveryFailure;
2826
3113
  private _runFiberRecoveryHook;
2827
3114
  private _fiberInspectionFromRow;
2828
3115
  private _waitForManagedFiber;
@@ -3326,13 +3613,58 @@ declare class Agent<
3326
3613
  private _broadcastAgentToolEvent;
3327
3614
  private _broadcastAgentToolChunks;
3328
3615
  private _broadcastAgentToolStoredChunks;
3616
+ private _broadcastAgentToolStoredChunksFromAdapter;
3329
3617
  private _forwardAgentToolStream;
3618
+ /**
3619
+ * Hook invoked by `_forwardAgentToolStream` after a child produces output that
3620
+ * was forwarded to the parent's connections. Forwarding a sub-agent's stream
3621
+ * is genuine forward progress for the *parent* turn (the parent is
3622
+ * orchestrating the child), so chat-recovery subclasses (Think / AIChatAgent)
3623
+ * override this to advance their recovery progress marker.
3624
+ *
3625
+ * Without it, a parent whose turn merely `await`s a sub-agent banks zero
3626
+ * progress of its own, so under deploy churn the parent's no-progress recovery
3627
+ * window exhausts and abandons the turn as `interrupted` — even though the
3628
+ * child is healthily streaming and ultimately completes (observed in the
3629
+ * `deploy-churn --mode subagent` harness: `attempt 6/6, stable_timeout,
3630
+ * progress: 1`).
3631
+ *
3632
+ * Called ONLY after at least one chunk was actually forwarded — never merely
3633
+ * because a child is attached — so a silent / hung child still lets the parent
3634
+ * exhaust on its own timer. The base Agent has no recovery budget, so this is
3635
+ * a no-op; subclasses should throttle the (durable) bump since this can be
3636
+ * called repeatedly while a child streams.
3637
+ */
3638
+ protected _onAgentToolStreamProgress(): Promise<void>;
3330
3639
  private _broadcastAgentToolTerminal;
3331
3640
  private _asAgentToolChildAdapter;
3332
3641
  private _agentToolClassByName;
3333
3642
  private _replayAndInterruptAgentToolRun;
3643
+ /**
3644
+ * Re-attach to a still-running child agent-tool run and tail it to its real
3645
+ * terminal result, instead of abandoning it as `interrupted` (#1630). The
3646
+ * child is a separate facet with its own `chatRecovery`, so resolving it via
3647
+ * the adapter wakes it and lets it self-complete the interrupted turn; we tail
3648
+ * its live stream (forwarding chunks to the parent's connections) until it
3649
+ * reaches terminal, then inspect for the collected result.
3650
+ *
3651
+ * Bounded by {@link DEFAULT_AGENT_TOOL_REATTACH_TIMEOUT_MS}: a child that keeps
3652
+ * advancing toward terminal within the window is collected; a genuinely hung
3653
+ * child returns `{ result: undefined }` once the budget elapses so the caller
3654
+ * falls back to `interrupted` and recovery can never block forever.
3655
+ *
3656
+ * Returns the terminal `result` (and `completedAt`) when the child reaches a
3657
+ * terminal status within the budget, plus the advanced broadcast `sequence`.
3658
+ * Returns `{ result: undefined }` when there is no `tailAgentToolRun` adapter,
3659
+ * the budget is exhausted, or the child is still non-terminal.
3660
+ */
3661
+ private _reattachAgentToolRunToTerminal;
3334
3662
  private _replayAgentToolRuns;
3335
3663
  private _reconcileAgentToolRuns;
3664
+ private _inspectAgentToolRunForRecovery;
3665
+ private _scheduleAgentToolRunRecovery;
3666
+ private _agentToolRunRecoveryRunIds;
3667
+ private _getAgentToolChunksForRecovery;
3336
3668
  /**
3337
3669
  * Shared facet resolution — takes a CamelCase class name string
3338
3670
  * (matching `ctx.exports`) rather than a class reference. Both
@@ -4036,6 +4368,26 @@ type AgentToolTerminalStatus = Extract<
4036
4368
  AgentToolRunStatus,
4037
4369
  "completed" | "error" | "aborted" | "interrupted"
4038
4370
  >;
4371
+ /**
4372
+ * Structured failure envelope an `agentTool()` returns when a sub-agent run
4373
+ * does not complete. Instead of an opaque error string the parent model would
4374
+ * parrot back to the user, the caller (or an orchestration harness) gets a
4375
+ * machine-readable signal:
4376
+ *
4377
+ * - `status` mirrors the underlying terminal status (`error` | `aborted` |
4378
+ * `interrupted`).
4379
+ * - `retryable` is `true` only for a transient interruption — the child was
4380
+ * reset or superseded by a deploy / parent recovery and never reached a
4381
+ * logical outcome, so re-dispatching the same run is the right move. A
4382
+ * genuine `error` or an intentional `aborted` is `false`.
4383
+ * - `error` stays human-readable for logs and UI.
4384
+ */
4385
+ type AgentToolFailure = {
4386
+ ok: false;
4387
+ status: Exclude<AgentToolTerminalStatus, "completed">;
4388
+ error: string;
4389
+ retryable: boolean;
4390
+ };
4039
4391
  type AgentToolDisplayMetadata = {
4040
4392
  name?: string;
4041
4393
  icon?: string;
@@ -4179,102 +4531,107 @@ type AgentToolEventState = {
4179
4531
  };
4180
4532
  //#endregion
4181
4533
  export {
4182
- SubAgentStub as $,
4183
- EmailSendBinding as A,
4184
- McpAuthContext as At,
4185
- QueueItem as B,
4186
- SubAgentPathMatch as Bt,
4187
- AgentStaticOptions as C,
4188
- ElicitRequest$1 as Ct,
4189
- DEFAULT_AGENT_STATIC_OPTIONS as D,
4190
- CreateMcpHandlerOptions as Dt,
4191
- ConnectionContext$1 as E,
4192
- McpAgent as Et,
4193
- FiberStatus as F,
4194
- SSEEdgeClientTransport as Ft,
4195
- ScheduleCriteria as G,
4196
- RPCResponse as H,
4197
- parseSubAgentPath as Ht,
4198
- ListFibersOptions as I,
4199
- StreamableHTTPEdgeClientTransport as It,
4200
- StartFiberOptions as J,
4201
- SendEmailOptions as K,
4202
- MCPServer as L,
4203
- McpClientOptions as Lt,
4204
- FiberInspection as M,
4205
- TransportState as Mt,
4206
- FiberRecoveryContext as N,
4207
- WorkerTransport as Nt,
4208
- DeleteFibersOptions as O,
4209
- createMcpHandler as Ot,
4210
- FiberRecoveryResult as P,
4211
- WorkerTransportOptions as Pt,
4212
- SubAgentClass as Q,
4213
- MCPServerMessage as R,
4214
- TransportType as Rt,
4215
- AgentOptions as S,
4216
- RPC_DO_PREFIX as St,
4217
- Connection$1 as T,
4218
- ElicitResult$1 as Tt,
4219
- RoutingRetryOptions as U,
4220
- routeSubAgentRequest as Ut,
4221
- RPCRequest as V,
4222
- getSubAgentByName as Vt,
4223
- Schedule as W,
4224
- StateUpdateMessage as X,
4225
- StartFiberResult as Y,
4226
- StreamingResponse as Z,
4227
- AddRpcMcpServerOptions as _,
4228
- getNamespacedData as _t,
4534
+ SubAgentClass as $,
4535
+ EmailRoutingOptions as A,
4536
+ ClearableEventStore as At,
4537
+ MCPServersState as B,
4538
+ SSEEdgeClientTransport as Bt,
4539
+ AgentOptions as C,
4540
+ RPCServerTransport as Ct,
4541
+ ConnectionContext$1 as D,
4542
+ ElicitRequestSchema$1 as Dt,
4543
+ Connection$1 as E,
4544
+ ElicitRequest$1 as Et,
4545
+ FiberRecoveryResult as F,
4546
+ McpAuthContext as Ft,
4547
+ Schedule as G,
4548
+ SubAgentPathMatch as Gt,
4549
+ RPCRequest as H,
4550
+ McpClientOptions as Ht,
4551
+ FiberStatus as I,
4552
+ getMcpAuthContext as It,
4553
+ SqlError as J,
4554
+ routeSubAgentRequest as Jt,
4555
+ ScheduleCriteria as K,
4556
+ getSubAgentByName as Kt,
4557
+ ListFibersOptions as L,
4558
+ TransportState as Lt,
4559
+ FiberContext as M,
4560
+ CreateMcpHandlerOptions as Mt,
4561
+ FiberInspection as N,
4562
+ createMcpHandler as Nt,
4563
+ DEFAULT_AGENT_STATIC_OPTIONS as O,
4564
+ ElicitResult$1 as Ot,
4565
+ FiberRecoveryContext as P,
4566
+ experimental_createMcpHandler as Pt,
4567
+ StreamingResponse as Q,
4568
+ MCPServer as R,
4569
+ WorkerTransport as Rt,
4570
+ AgentNamespace as S,
4571
+ RPCClientTransportOptions as St,
4572
+ CallableMetadata as T,
4573
+ RPC_DO_PREFIX as Tt,
4574
+ RPCResponse as U,
4575
+ TransportType as Ut,
4576
+ QueueItem as V,
4577
+ StreamableHTTPEdgeClientTransport as Vt,
4578
+ RoutingRetryOptions as W,
4579
+ SUB_PREFIX as Wt,
4580
+ StartFiberResult as X,
4581
+ StartFiberOptions as Y,
4582
+ StateUpdateMessage as Z,
4583
+ AddMcpServerOptions as _,
4584
+ MCP_SERVER_ID_MAX_LENGTH as _t,
4229
4585
  AgentToolEventState as a,
4230
- routeAgentRequest as at,
4231
- AgentGetOptions as b,
4232
- RPCServerTransport as bt,
4233
- AgentToolRunInspection as c,
4234
- MCPClientManagerOptions as ct,
4235
- AgentToolStoredChunk as d,
4236
- MCPConnectionResult as dt,
4237
- WSMessage$1 as et,
4238
- AgentToolTerminalStatus as f,
4239
- MCPDiscoverResult as ft,
4240
- AddMcpServerOptions as g,
4241
- RegisterServerOptions as gt,
4242
- RunAgentToolResult as h,
4243
- MCPServerOptions as ht,
4586
+ routeAgentEmail as at,
4587
+ AgentContext as b,
4588
+ normalizeServerId as bt,
4589
+ AgentToolRunInfo as c,
4590
+ MCPClientManager as ct,
4591
+ AgentToolRunStatus as d,
4592
+ MCPClientOAuthResult as dt,
4593
+ SubAgentStub as et,
4594
+ AgentToolStoredChunk as f,
4595
+ MCPConnectionResult as ft,
4596
+ RunAgentToolResult as g,
4597
+ MCPServerOptions as gt,
4598
+ RunAgentToolOptions as h,
4599
+ MCPServerFilter as ht,
4244
4600
  AgentToolEventMessage as i,
4245
- routeAgentEmail as it,
4246
- FiberContext as j,
4247
- getMcpAuthContext as jt,
4248
- EmailRoutingOptions as k,
4249
- experimental_createMcpHandler as kt,
4250
- AgentToolRunState as l,
4251
- MCPClientOAuthCallbackConfig as lt,
4252
- RunAgentToolOptions as m,
4253
- MCPServerFilter as mt,
4601
+ getCurrentAgent as it,
4602
+ EmailSendBinding as j,
4603
+ DurableObjectEventStore as jt,
4604
+ DeleteFibersOptions as k,
4605
+ McpAgent as kt,
4606
+ AgentToolRunInspection as l,
4607
+ MCPClientManagerOptions as lt,
4608
+ ChatCapableAgentClass as m,
4609
+ MCPOAuthCallbackResult as mt,
4254
4610
  AgentToolDisplayMetadata as n,
4255
- getAgentByName as nt,
4256
- AgentToolLifecycleResult as o,
4257
- unstable_callable as ot,
4258
- ChatCapableAgentClass as p,
4259
- MCPOAuthCallbackResult as pt,
4260
- SqlError as q,
4611
+ callable as nt,
4612
+ AgentToolFailure as o,
4613
+ routeAgentRequest as ot,
4614
+ AgentToolTerminalStatus as p,
4615
+ MCPDiscoverResult as pt,
4616
+ SendEmailOptions as q,
4617
+ parseSubAgentPath as qt,
4261
4618
  AgentToolEvent as r,
4262
- getCurrentAgent as rt,
4263
- AgentToolRunInfo as s,
4264
- MCPClientManager as st,
4619
+ getAgentByName as rt,
4620
+ AgentToolLifecycleResult as s,
4621
+ unstable_callable as st,
4265
4622
  AgentToolChildAdapter as t,
4266
- callable as tt,
4267
- AgentToolRunStatus as u,
4268
- MCPClientOAuthResult as ut,
4269
- Agent as v,
4270
- RPCClientTransport as vt,
4271
- CallableMetadata as w,
4272
- ElicitRequestSchema$1 as wt,
4273
- AgentNamespace as x,
4274
- RPCServerTransportOptions as xt,
4275
- AgentContext as y,
4276
- RPCClientTransportOptions as yt,
4277
- MCPServersState as z,
4278
- SUB_PREFIX as zt
4623
+ WSMessage$1 as tt,
4624
+ AgentToolRunState as u,
4625
+ MCPClientOAuthCallbackConfig as ut,
4626
+ AddRpcMcpServerOptions as v,
4627
+ RegisterServerOptions as vt,
4628
+ AgentStaticOptions as w,
4629
+ RPCServerTransportOptions as wt,
4630
+ AgentGetOptions as x,
4631
+ RPCClientTransport as xt,
4632
+ Agent as y,
4633
+ getNamespacedData as yt,
4634
+ MCPServerMessage as z,
4635
+ WorkerTransportOptions as zt
4279
4636
  };
4280
- //# sourceMappingURL=agent-tool-types-l98LCbBl.d.ts.map
4637
+ //# sourceMappingURL=agent-tool-types-BAJWu8s4.d.ts.map