agents 0.33.0 → 0.34.0

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 (169) hide show
  1. package/README.md +1 -1
  2. package/dist/{agent-routing-vVMA7m8Y.d.ts → agent-routing-BSoZzNiP.d.ts} +537 -373
  3. package/dist/agent-routing.d.ts +1 -1
  4. package/dist/agent-tool-types.d.ts +1 -1
  5. package/dist/{agent-tools-gGXXkf1z.d.ts → agent-tools-Be-hpRpH.d.ts} +2 -2
  6. package/dist/agent-tools.d.ts +1 -1
  7. package/dist/{ai-sdk-Kon40i0q.js → ai-sdk-CRMlEBX7.js} +75 -44
  8. package/dist/ai-sdk-CRMlEBX7.js.map +1 -0
  9. package/dist/browser/ai.js +1 -1
  10. package/dist/browser/index.d.ts +7 -3
  11. package/dist/browser/index.js +2 -2
  12. package/dist/browser/tools/ai-sdk.d.ts +68 -3
  13. package/dist/browser/tools/pi.d.ts +2 -2
  14. package/dist/browser/tools/tanstack-ai.d.ts +2 -2
  15. package/dist/{browser-CI97khiJ.d.ts → browser-C9T74n4c.d.ts} +84 -5
  16. package/dist/{browser-tool-Cxtiwfua.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
  17. package/dist/capability-DBAKc6UZ.js.map +1 -1
  18. package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
  19. package/dist/chat/index.d.ts +37 -6
  20. package/dist/chat/index.js +39 -3
  21. package/dist/chat/index.js.map +1 -1
  22. package/dist/chat-sdk/index.d.ts +3 -3
  23. package/dist/chat-sdk/index.js +1 -1
  24. package/dist/cli.js +64 -63
  25. package/dist/client-CkT8voRY.js +3740 -0
  26. package/dist/client-CkT8voRY.js.map +1 -0
  27. package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
  28. package/dist/client.d.ts +1 -1
  29. package/dist/{connector-Dl098To-.js → connector-Bphz6wIw.js} +16 -4
  30. package/dist/connector-Bphz6wIw.js.map +1 -0
  31. package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
  32. package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
  33. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  34. package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
  35. package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
  36. package/dist/experimental/channels/index.d.ts +2 -2
  37. package/dist/experimental/channels/web/index.d.ts +2 -2
  38. package/dist/experimental/channels/web/index.js +1 -1
  39. package/dist/experimental/webmcp.js +1 -1
  40. package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
  41. package/dist/harness/ai-sdk/index.d.ts +2 -2
  42. package/dist/harness/container/index.d.ts +2 -2
  43. package/dist/harness/container/index.js +1 -1
  44. package/dist/harness/container/index.js.map +1 -1
  45. package/dist/harness/opencode/index.d.ts +1 -1
  46. package/dist/harness/pi/index.d.ts +128 -12
  47. package/dist/harness/pi/index.js +128 -20
  48. package/dist/harness/pi/index.js.map +1 -1
  49. package/dist/harness/think/index.d.ts +2 -2
  50. package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
  51. package/dist/images-D4gtE06D.js.map +1 -0
  52. package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
  53. package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
  54. package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
  55. package/dist/index.d.ts +21 -21
  56. package/dist/index.js +2 -2
  57. package/dist/{input-schema-0uUu392-.js → input-schema-D6GilRXI.js} +2 -2
  58. package/dist/{input-schema-0uUu392-.js.map → input-schema-D6GilRXI.js.map} +1 -1
  59. package/dist/{input-schema-waggtYrH.js → input-schema-y8W5bOdM.js} +2 -2
  60. package/dist/{input-schema-waggtYrH.js.map → input-schema-y8W5bOdM.js.map} +1 -1
  61. package/dist/internal_context.d.ts +1 -1
  62. package/dist/lifecycle/index.d.ts +3 -3
  63. package/dist/lifecycle/index.js +1 -1
  64. package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
  65. package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
  66. package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
  67. package/dist/mcp/client/do-oauth-client-provider.js +45 -2
  68. package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
  69. package/dist/mcp/client/index.d.ts +42 -36
  70. package/dist/mcp/client/index.js +2 -2
  71. package/dist/mcp/client/x402.d.ts +8 -8
  72. package/dist/mcp/index.d.ts +17 -17
  73. package/dist/mcp/index.js +5 -5
  74. package/dist/mcp/index.js.map +1 -1
  75. package/dist/models/ai-sdk/index.d.ts +9 -5
  76. package/dist/models/ai-sdk/index.js +1 -1
  77. package/dist/models/opencode/index.d.ts +3 -3
  78. package/dist/models/opencode/index.js +2 -2
  79. package/dist/models/opencode/index.js.map +1 -1
  80. package/dist/models/pi-ai/index.d.ts +4 -4
  81. package/dist/models/pi-ai/index.js +53 -29
  82. package/dist/models/pi-ai/index.js.map +1 -1
  83. package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
  84. package/dist/queue/index.d.ts +1 -1
  85. package/dist/queue/index.js +1 -1
  86. package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
  87. package/dist/queue-B_wl6K0Z.js.map +1 -0
  88. package/dist/react.d.ts +2 -2
  89. package/dist/routing/index.d.ts +2 -2
  90. package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
  91. package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
  92. package/dist/scheduler-DGNEmxQR.js.map +1 -0
  93. package/dist/schedules/index.d.ts +1 -1
  94. package/dist/schedules/index.js +1 -1
  95. package/dist/serializable.d.ts +1 -1
  96. package/dist/session-CRY0bGiI.js.map +1 -1
  97. package/dist/sessions/index.d.ts +1 -1
  98. package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
  99. package/dist/settings-D2F_qONv.js.map +1 -0
  100. package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
  101. package/dist/src-BO1FdLK1.js.map +1 -0
  102. package/dist/state/index.d.ts +1 -1
  103. package/dist/streams/index.d.ts +1 -1
  104. package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
  105. package/dist/sub-routing.d.ts +12 -12
  106. package/dist/tasks/index.d.ts +1 -1
  107. package/dist/tasks/index.js +1 -1
  108. package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
  109. package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
  110. package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
  111. package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
  112. package/dist/tool-CmAGY6Fo.js.map +1 -0
  113. package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
  114. package/dist/tool-Kxcj8_22.js.map +1 -0
  115. package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
  116. package/dist/voice/index.d.ts +2 -2
  117. package/dist/web/fetch/index.js +1 -1
  118. package/dist/web/fetch/tools/ai-sdk.js +2 -2
  119. package/dist/web/fetch/tools/pi.d.ts +5 -0
  120. package/dist/web/fetch/tools/pi.js +25 -2
  121. package/dist/web/fetch/tools/pi.js.map +1 -1
  122. package/dist/web/fetch/tools/tanstack-ai.js +2 -2
  123. package/dist/web/search/index.js +1 -1
  124. package/dist/web/search/tools/ai-sdk.js +2 -2
  125. package/dist/web/search/tools/pi.d.ts +4 -0
  126. package/dist/web/search/tools/pi.js +23 -2
  127. package/dist/web/search/tools/pi.js.map +1 -1
  128. package/dist/web/search/tools/tanstack-ai.js +2 -2
  129. package/dist/websockets/index.d.ts +2 -2
  130. package/dist/websockets/index.js +1 -1
  131. package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
  132. package/dist/websockets-W4uhRg4-.js.map +1 -0
  133. package/dist/workflow-types.d.ts +1 -1
  134. package/dist/workflows.d.ts +1 -1
  135. package/docs/agent-class.md +30 -4
  136. package/docs/browse-the-web.md +14 -0
  137. package/docs/chat-agents.md +13 -10
  138. package/docs/client-tools-continuation.md +1 -1
  139. package/docs/codemode.md +1 -1
  140. package/docs/configuration.md +6 -3
  141. package/docs/cross-domain-authentication.md +1 -1
  142. package/docs/fetch-the-web.md +20 -0
  143. package/docs/harnesses/pi.md +211 -22
  144. package/docs/harnesses/think.md +1 -1
  145. package/docs/http-websockets.md +40 -32
  146. package/docs/human-in-the-loop.md +2 -2
  147. package/docs/lifecycle.md +56 -0
  148. package/docs/mcp-client.md +104 -7
  149. package/docs/models-pi-ai.md +24 -10
  150. package/docs/models.md +42 -17
  151. package/docs/resumable-streaming.md +1 -1
  152. package/docs/retries.md +3 -6
  153. package/docs/search-the-web.md +10 -0
  154. package/docs/voice.md +1 -1
  155. package/package.json +13 -12
  156. package/dist/ai-sdk-CpuRsjP5.d.ts +0 -72
  157. package/dist/ai-sdk-Kon40i0q.js.map +0 -1
  158. package/dist/client-DMWujQJ1.js +0 -2325
  159. package/dist/client-DMWujQJ1.js.map +0 -1
  160. package/dist/connector-Dl098To-.js.map +0 -1
  161. package/dist/images-CfuRCjwq.js.map +0 -1
  162. package/dist/lifecycle-v1rKHV2C.js.map +0 -1
  163. package/dist/queue-CcIjVYTE.js.map +0 -1
  164. package/dist/scheduler-FIHv2-kJ.js.map +0 -1
  165. package/dist/settings-Dk2il2Hf.js.map +0 -1
  166. package/dist/src-DoGNJ4Ud.js.map +0 -1
  167. package/dist/tool-CxKsvxjm.js.map +0 -1
  168. package/dist/tool-DkT_DJBm.js.map +0 -1
  169. package/dist/websockets-C6SJtWCJ.js.map +0 -1
@@ -10,18 +10,18 @@ import { signAgentHeaders } from "./email.js";
10
10
  import { sendAgentEmail } from "./email-send.js";
11
11
  import { i as writeSpanAttributes, n as tracer, r as withInvocationScope } from "./cloudflare-CUUm_9q9.js";
12
12
  import { parseSubAgentPath } from "./sub-routing.js";
13
- import { a as getConnectionFlag, c as isConnectionReadonly, d as setConnectionProtocolEnabled, f as setConnectionReadonly, i as ensureConnectionWrapped, l as registerInternalConnectionKeys, o as getConnectionRawState, s as isConnectionProtocolEnabled, t as WebSockets, u as setConnectionFlag } from "./websockets-C6SJtWCJ.js";
13
+ import { a as getConnectionFlag, c as isConnectionReadonly, d as setConnectionProtocolEnabled, f as setConnectionReadonly, i as ensureConnectionWrapped, l as registerInternalConnectionKeys, o as getConnectionRawState, s as isConnectionProtocolEnabled, t as WebSockets, u as setConnectionFlag } from "./websockets-W4uhRg4-.js";
14
14
  import { t as LifecycleCapability } from "./capability-DBAKc6UZ.js";
15
- import { a as abortWithoutAlarmRetry, i as setLifecycleRouteTransport, n as setLifecycleEventSink, r as setLifecycleHostInvoker, t as Lifecycle } from "./lifecycle-v1rKHV2C.js";
15
+ import { a as abortWithoutAlarmRetry, i as setLifecycleRouteTransport, n as setLifecycleEventSink, r as setLifecycleHostInvoker, t as Lifecycle } from "./lifecycle-CB5Dmtrt.js";
16
16
  import { isErrorRetryable, tryN, validateRetryOptions } from "./retries.js";
17
17
  import { SqlError } from "./sql-error.js";
18
18
  import { t as browserCapabilityId } from "./capability-id-B3J8Nok_.js";
19
- import { a as ensureMcpServerTable, i as normalizeServerId, l as RPC_DO_PREFIX, o as MCPConnectionState, s as DisposableStore, t as MCPClientManager } from "./client-DMWujQJ1.js";
19
+ import { a as MCPConnectionState, f as DisposableStore, i as ensureMcpServerTable, r as normalizeServerId, t as MCPClientManager, u as RPC_DO_PREFIX } from "./client-CkT8voRY.js";
20
20
  import { DurableObjectOAuthClientProvider } from "./mcp/client/do-oauth-client-provider.js";
21
21
  import { t as genericObservability } from "./emitter-DPOVcCln.js";
22
- import { n as setSchedulerCallbackResolver, t as Scheduler } from "./scheduler-FIHv2-kJ.js";
23
- import { n as setQueueCallbackResolver, t as Queue } from "./queue-CcIjVYTE.js";
24
- import { n as setTaskDefinitionResolver, r as setTaskRoutedMemoryLimitHandler, t as Tasks } from "./tasks-BN_5AWqI.js";
22
+ import { n as setSchedulerCallbackResolver, t as Scheduler } from "./scheduler-DGNEmxQR.js";
23
+ import { n as setQueueCallbackResolver, t as Queue } from "./queue-B_wl6K0Z.js";
24
+ import { n as setTaskDefinitionResolver, r as setTaskRoutedMemoryLimitHandler, t as Tasks } from "./tasks-Cf_UfEO4.js";
25
25
  import { State } from "./state/index.js";
26
26
  import { AsyncLocalStorage } from "node:async_hooks";
27
27
  import { DurableObject, RpcTarget, exports } from "cloudflare:workers";
@@ -100,6 +100,9 @@ var DynamicAgentConnectionBridge = class extends RpcTarget {
100
100
  send(message) {
101
101
  _classPrivateFieldGet2(_connection, this).send(message);
102
102
  }
103
+ sendMany(messages) {
104
+ for (const message of messages) _classPrivateFieldGet2(_connection, this).send(message);
105
+ }
103
106
  close(code, reason) {
104
107
  _classPrivateFieldGet2(_connection, this).close(code, reason);
105
108
  }
@@ -126,6 +129,9 @@ var RootDynamicAgentConnectionBridge = class {
126
129
  send(message) {
127
130
  return _classPrivateFieldGet2(_root, this)._cf_sendToSubAgentConnection(_classPrivateFieldGet2(_connectionId, this), message);
128
131
  }
132
+ sendMany(messages) {
133
+ return _classPrivateFieldGet2(_root, this)._cf_sendManyToSubAgentConnection(_classPrivateFieldGet2(_connectionId, this), messages);
134
+ }
129
135
  close(code, reason) {
130
136
  return _classPrivateFieldGet2(_root, this)._cf_closeSubAgentConnection(_classPrivateFieldGet2(_connectionId, this), code, reason);
131
137
  }
@@ -302,6 +308,15 @@ const CF_SUB_AGENT_TAGS_KEY = "_cf_subAgentTags";
302
308
  * replacement created after the delete. Storage-frozen — never rename.
303
309
  */
304
310
  const CF_SUB_AGENT_DELETED_KEY = "_cf_subAgentDeleted";
311
+ /**
312
+ * A batch takes no send that would grow it past this size (string length or
313
+ * byte length), so one root call stays far below the RPC message size limit.
314
+ * A larger send goes alone, as it did before batching.
315
+ */
316
+ const MAX_CONNECTION_SEND_BATCH_SIZE = 1e6;
317
+ function connectionSendSize(message) {
318
+ return typeof message === "string" ? message.length : message.byteLength;
319
+ }
305
320
  /** Wire-frozen internal header carrying the outer URL on WS upgrades. */
306
321
  const SUB_AGENT_OUTER_URL_HEADER = "x-cf-agents-subagent-url";
307
322
  /**
@@ -338,6 +353,7 @@ var _virtualConnections = /* @__PURE__ */ new WeakMap();
338
353
  var _virtualConnectionsHydrated = /* @__PURE__ */ new WeakMap();
339
354
  var _virtualConnectionsHydration = /* @__PURE__ */ new WeakMap();
340
355
  var _connectionOperationTails = /* @__PURE__ */ new WeakMap();
356
+ var _openConnectionSendBatches = /* @__PURE__ */ new WeakMap();
341
357
  var _broadcastOperationTail = /* @__PURE__ */ new WeakMap();
342
358
  var _DynamicAgentsInternal_brand = /* @__PURE__ */ new WeakSet();
343
359
  /**
@@ -373,6 +389,7 @@ var DynamicAgentsInternal = class extends LifecycleCapability {
373
389
  _classPrivateFieldInitSpec(this, _virtualConnectionsHydrated, false);
374
390
  _classPrivateFieldInitSpec(this, _virtualConnectionsHydration, void 0);
375
391
  _classPrivateFieldInitSpec(this, _connectionOperationTails, /* @__PURE__ */ new Map());
392
+ _classPrivateFieldInitSpec(this, _openConnectionSendBatches, /* @__PURE__ */ new Map());
376
393
  _classPrivateFieldInitSpec(this, _broadcastOperationTail, void 0);
377
394
  _classPrivateFieldSet2(_host, this, host);
378
395
  this.registry = new DynamicAgentRegistry({
@@ -715,6 +732,7 @@ var DynamicAgentsInternal = class extends LifecycleCapability {
715
732
  * older queued operations; failures do not block later work.
716
733
  */
717
734
  routeConnectionOperation(connectionId, operationName, operation) {
735
+ _classPrivateFieldGet2(_openConnectionSendBatches, this).delete(connectionId);
718
736
  const activeBridge = this.activeBridge(connectionId);
719
737
  const previousConnectionOperation = _classPrivateFieldGet2(_connectionOperationTails, this).get(connectionId);
720
738
  let pending;
@@ -736,6 +754,38 @@ var DynamicAgentsInternal = class extends LifecycleCapability {
736
754
  });
737
755
  }
738
756
  /**
757
+ * Route a virtual sub-agent connection send. A send that would wait behind
758
+ * another operation joins the waiting send batch instead, so a burst (such
759
+ * as a stream replay) costs one root call, not one per frame (#2820).
760
+ * Order is unchanged: a batch only ever holds consecutive sends.
761
+ */
762
+ routeConnectionSend(connectionId, message) {
763
+ const size = connectionSendSize(message);
764
+ const open = _classPrivateFieldGet2(_openConnectionSendBatches, this).get(connectionId);
765
+ if (open && open.size + size <= MAX_CONNECTION_SEND_BATCH_SIZE) {
766
+ open.messages.push(message);
767
+ open.size += size;
768
+ return;
769
+ }
770
+ const batch = {
771
+ messages: [message],
772
+ size
773
+ };
774
+ let closed = false;
775
+ const close = () => {
776
+ closed = true;
777
+ if (_classPrivateFieldGet2(_openConnectionSendBatches, this).get(connectionId) === batch) _classPrivateFieldGet2(_openConnectionSendBatches, this).delete(connectionId);
778
+ };
779
+ this.routeConnectionOperation(connectionId, "send", (bridge) => {
780
+ close();
781
+ const [only] = batch.messages;
782
+ return batch.messages.length === 1 ? bridge.send(only) : bridge.sendMany(batch.messages);
783
+ });
784
+ if (closed) return;
785
+ _classPrivateFieldGet2(_openConnectionSendBatches, this).set(connectionId, batch);
786
+ _classPrivateFieldGet2(_connectionOperationTails, this).get(connectionId)?.then(close);
787
+ }
788
+ /**
739
789
  * Route a facet broadcast after every older connection operation.
740
790
  *
741
791
  * This barrier is intentionally one-way: facet startup can broadcast before
@@ -798,6 +848,11 @@ var DynamicAgentsInternal = class extends LifecycleCapability {
798
848
  if (!connection || !this.connectionHasChildTarget(connection)) return;
799
849
  connection.send(message);
800
850
  }
851
+ async sendManyToConnection(connectionId, messages) {
852
+ const connection = _classPrivateFieldGet2(_host, this)._webSockets.getConnection(connectionId);
853
+ if (!connection || !this.connectionHasChildTarget(connection)) return;
854
+ for (const message of messages) connection.send(message);
855
+ }
801
856
  async closeConnection(connectionId, code, reason) {
802
857
  const connection = _classPrivateFieldGet2(_host, this)._webSockets.getConnection(connectionId);
803
858
  if (!connection || !this.connectionHasChildTarget(connection)) return;
@@ -937,7 +992,7 @@ var DynamicAgentsInternal = class extends LifecycleCapability {
937
992
  return state;
938
993
  },
939
994
  send(message) {
940
- owner.routeConnectionOperation(meta.id, "send", (bridge) => bridge.send(message));
995
+ owner.routeConnectionSend(meta.id, message);
941
996
  },
942
997
  close(code, reason) {
943
998
  owner.routeConnectionOperation(meta.id, "close", (bridge) => bridge.close(code, reason));
@@ -1535,6 +1590,23 @@ var Agent = class Agent extends DurableObject {
1535
1590
  onRequest(_request) {
1536
1591
  return new Response("Not implemented", { status: 404 });
1537
1592
  }
1593
+ /**
1594
+ * Choose the response for a request or WebSocket upgrade whose handling
1595
+ * threw, including a failed `onStart`. The error is already logged.
1596
+ *
1597
+ * Return a `Response` to send it, or nothing to send the default, which
1598
+ * never carries the error: `500 Internal Server Error`, or for an upgrade a
1599
+ * socket that closes with 1011. For an upgrade, return either an HTTP
1600
+ * error response or a `101` response with your own `WebSocketPair`.
1601
+ *
1602
+ * Errors from `onStart`, `onRequest`, and `onConnect` pass through
1603
+ * `onError` first. If `onError` throws, `error` is what it threw;
1604
+ * otherwise it is the original error. Avoid sending an error's message or
1605
+ * stack to callers you do not trust. If this hook throws, the default is
1606
+ * sent. Whether it returns nothing or throws, an original thrown value
1607
+ * that is not an `Error` is rethrown instead.
1608
+ */
1609
+ onFetchError(_request, _error) {}
1538
1610
  /** Handle a newly accepted hibernating WebSocket connection. */
1539
1611
  onConnect(_connection, _context) {}
1540
1612
  /** Handle a message from a hibernating WebSocket connection. */
@@ -1589,7 +1661,7 @@ var Agent = class Agent extends DurableObject {
1589
1661
  * @example
1590
1662
  * ```typescript
1591
1663
  * const workersai = createWorkersAI({ binding: this.env.AI });
1592
- * const model = workersai("@cf/meta/llama-3.3-70b-instruct-fp8-fast", {
1664
+ * const model = workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017", {
1593
1665
  * sessionAffinity: this.sessionAffinity,
1594
1666
  * });
1595
1667
  * ```
@@ -2513,7 +2585,8 @@ var Agent = class Agent extends DurableObject {
2513
2585
  try {
2514
2586
  return await fn();
2515
2587
  } catch (e) {
2516
- throw this.onError(e);
2588
+ await this.onError(e);
2589
+ throw e;
2517
2590
  }
2518
2591
  }
2519
2592
  /**
@@ -3975,6 +4048,10 @@ var Agent = class Agent extends DurableObject {
3975
4048
  await this.__unsafe_ensureInitialized();
3976
4049
  await this._dynamicAgents.sendToConnection(connectionId, message);
3977
4050
  }
4051
+ async _cf_sendManyToSubAgentConnection(connectionId, messages) {
4052
+ await this.__unsafe_ensureInitialized();
4053
+ await this._dynamicAgents.sendManyToConnection(connectionId, messages);
4054
+ }
3978
4055
  async _cf_closeSubAgentConnection(connectionId, code, reason) {
3979
4056
  await this.__unsafe_ensureInitialized();
3980
4057
  await this._dynamicAgents.closeConnection(connectionId, code, reason);
@@ -6636,41 +6713,7 @@ var Agent = class Agent extends DurableObject {
6636
6713
  existingServer.id = requestedId;
6637
6714
  }
6638
6715
  }
6639
- if (existingServer && this.mcp.mcpConnections[existingServer.id]) {
6640
- const conn = this.mcp.mcpConnections[existingServer.id];
6641
- if (conn.connectionState === MCPConnectionState.AUTHENTICATING) {
6642
- const authProvider = conn.options.transport.authProvider;
6643
- const authUrl = await this._redeemableAuthUrl(existingServer.id, authProvider?.authUrl, authProvider) ?? await this._redeemableAuthUrl(existingServer.id, existingServer.auth_url, authProvider);
6644
- if (authUrl) return {
6645
- id: existingServer.id,
6646
- state: MCPConnectionState.AUTHENTICATING,
6647
- authUrl
6648
- };
6649
- const reconnectResult = await this.mcp.connectToServer(existingServer.id);
6650
- if (reconnectResult.state === MCPConnectionState.AUTHENTICATING) {
6651
- if (!reconnectResult.authUrl) throw new Error("OAuth configuration incomplete: missing authUrl");
6652
- return {
6653
- id: existingServer.id,
6654
- state: reconnectResult.state,
6655
- authUrl: reconnectResult.authUrl
6656
- };
6657
- }
6658
- if (reconnectResult.state === MCPConnectionState.CONNECTED) {
6659
- const discoverResult = await this.mcp.discoverIfConnected(existingServer.id);
6660
- if (!discoverResult?.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult?.error ?? "connection not found"}`);
6661
- return {
6662
- id: existingServer.id,
6663
- state: MCPConnectionState.READY
6664
- };
6665
- }
6666
- throw new Error(`Failed to connect to MCP server at ${normalizedUrl}: ${reconnectResult.error}`);
6667
- }
6668
- if (conn.connectionState === MCPConnectionState.FAILED) throw new Error(`MCP server "${serverName}" is in failed state: ${conn.connectionError}`);
6669
- return {
6670
- id: existingServer.id,
6671
- state: MCPConnectionState.READY
6672
- };
6673
- }
6716
+ if (existingServer && this.mcp.mcpConnections[existingServer.id]) return this._resumeMcpServer(existingServer, serverName);
6674
6717
  if (typeof urlOrBinding !== "string") {
6675
6718
  const rpcOpts = callbackHostOrOptions;
6676
6719
  const normalizedName = serverName.toLowerCase().replace(/\s+/g, "-");
@@ -6738,63 +6781,79 @@ var Agent = class Agent extends DurableObject {
6738
6781
  authProvider.serverId = id;
6739
6782
  }
6740
6783
  const transportType = resolvedOptions?.transport?.type ?? "auto";
6741
- let headerTransportOpts = {};
6742
- if (resolvedOptions?.transport?.headers) headerTransportOpts = {
6743
- eventSourceInit: { fetch: (url, init) => fetch(url, {
6744
- ...init,
6745
- headers: resolvedOptions?.transport?.headers
6746
- }) },
6747
- requestInit: { headers: resolvedOptions?.transport?.headers }
6748
- };
6749
6784
  await this.mcp.registerServer(id, {
6750
6785
  url: normalizedUrl,
6751
6786
  name: serverName,
6752
6787
  callbackUrl,
6753
6788
  client: resolvedOptions?.client,
6754
6789
  transport: {
6755
- ...headerTransportOpts,
6790
+ headers: resolvedOptions?.transport?.headers,
6756
6791
  authProvider,
6757
6792
  type: transportType,
6758
6793
  skipIssuerMetadataValidation: resolvedOptions?.transport?.skipIssuerMetadataValidation
6759
6794
  },
6760
6795
  retry: resolvedOptions?.retry
6761
6796
  });
6762
- const result = await this.mcp.connectToServer(id);
6763
- if (result.state === MCPConnectionState.FAILED) throw new Error(`Failed to connect to MCP server at ${normalizedUrl}: ${result.error}`);
6764
- if (result.state === MCPConnectionState.AUTHENTICATING) {
6765
- if (!callbackUrl) throw new Error("This MCP server requires OAuth authentication. Provide callbackHost in addMcpServer options to enable the OAuth flow.");
6766
- return {
6797
+ return this._connectAndDiscoverMcpServer(id, {
6798
+ name: serverName,
6799
+ url: normalizedUrl,
6800
+ oauth: callbackUrl ? "available" : "unavailable"
6801
+ });
6802
+ }
6803
+ /**
6804
+ * Bring an already-registered server to a result for `addMcpServer`. Work
6805
+ * already queued for it (restore, an OAuth callback, a concurrent
6806
+ * `addMcpServer`) runs first, so a half-connected server is never reported
6807
+ * as ready.
6808
+ */
6809
+ async _resumeMcpServer(server, serverName) {
6810
+ return this._mcpServerResult(server.id, await this.mcp.settleServer(server.id), {
6811
+ name: serverName,
6812
+ url: server.server_url,
6813
+ oauth: server.callback_url ? "available" : "unavailable"
6814
+ });
6815
+ }
6816
+ /** Connect a registered server and discover its capabilities. */
6817
+ async _connectAndDiscoverMcpServer(id, context) {
6818
+ return this._mcpServerResult(id, await this.mcp.connectAndDiscover(id), context);
6819
+ }
6820
+ /** Translate where a server settled into `addMcpServer`'s result or error. */
6821
+ _mcpServerResult(id, settlement, context) {
6822
+ switch (settlement.state) {
6823
+ case MCPConnectionState.READY: return {
6767
6824
  id,
6768
- state: result.state,
6769
- authUrl: result.authUrl
6825
+ state: MCPConnectionState.READY
6770
6826
  };
6771
- }
6772
- const discoverResult = await this.mcp.discoverIfConnected(id);
6773
- if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover MCP server capabilities: ${discoverResult.error}`);
6774
- return {
6775
- id,
6776
- state: MCPConnectionState.READY
6777
- };
6778
- }
6779
- async _redeemableAuthUrl(serverId, authUrl, authProvider) {
6780
- if (!this._isAbsoluteHttpUrl(authUrl) || !authProvider) return;
6781
- const state = new URL(authUrl).searchParams.get("state");
6782
- if (!state) return authUrl;
6783
- authProvider.serverId = serverId;
6784
- try {
6785
- return (await authProvider.checkState(state)).valid ? authUrl : void 0;
6786
- } catch {
6787
- return;
6827
+ case MCPConnectionState.AUTHENTICATING:
6828
+ if (context.oauth === "unavailable") throw new Error("This MCP server requires OAuth authentication. Provide callbackHost in addMcpServer options to enable the OAuth flow.");
6829
+ if (!settlement.authUrl) throw new Error("OAuth configuration incomplete: missing authUrl");
6830
+ return {
6831
+ id,
6832
+ state: MCPConnectionState.AUTHENTICATING,
6833
+ authUrl: settlement.authUrl
6834
+ };
6835
+ case MCPConnectionState.FAILED: throw new Error(settlement.phase === "connect" ? `Failed to connect to MCP server at ${context.url}: ${settlement.error}` : `Failed to discover MCP server capabilities: ${settlement.error}`);
6836
+ case "removed": throw new Error(`MCP server "${context.name}" was removed while it was connecting`);
6788
6837
  }
6789
6838
  }
6790
- _isAbsoluteHttpUrl(value) {
6791
- if (!value) return false;
6792
- try {
6793
- const url = new URL(value);
6794
- return url.protocol === "http:" || url.protocol === "https:";
6795
- } catch {
6796
- return false;
6797
- }
6839
+ /**
6840
+ * Try an MCP server again, for example from a "Reconnect" button: forgets
6841
+ * why it failed (unreachable, authorization refused, step-up limit
6842
+ * reached) and its pending link, then connects now with the quick
6843
+ * attempts. The only way to retry a failed server or get a new link;
6844
+ * `addMcpServer()` for a registered server reports its state as is.
6845
+ *
6846
+ * @returns The same result as `addMcpServer()`: `ready`, or
6847
+ * `authenticating` with a new `authUrl`. Throws when the attempt fails.
6848
+ */
6849
+ async reconnectMcpServer(id) {
6850
+ const server = this.mcp.listServers().find((s) => s.id === id);
6851
+ if (!server) throw new Error(`MCP server "${id}" is not registered`);
6852
+ return this._mcpServerResult(id, await this.mcp.reconnectServer(id), {
6853
+ name: server.name,
6854
+ url: server.server_url,
6855
+ oauth: server.callback_url ? "available" : "unavailable"
6856
+ });
6798
6857
  }
6799
6858
  async removeMcpServer(id) {
6800
6859
  await this.mcp.removeServer(id);
@@ -7016,4 +7075,4 @@ var StreamingResponse = class {
7016
7075
  //#endregion
7017
7076
  export { routeAgentEmail as a, getCurrentAgent as i, DEFAULT_AGENT_STATIC_OPTIONS as n, StreamingResponse as r, Agent as t };
7018
7077
 
7019
- //# sourceMappingURL=src-DoGNJ4Ud.js.map
7078
+ //# sourceMappingURL=src-BO1FdLK1.js.map