agents 0.22.0 → 0.24.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 (215) hide show
  1. package/README.md +20 -1
  2. package/dist/{agent-routing-CnkaHb-v.d.ts → agent-routing-B2XLNMxq.d.ts} +1094 -443
  3. package/dist/agent-routing.d.ts +1 -1
  4. package/dist/agent-tool-types.d.ts +26 -26
  5. package/dist/{agent-tools-C0XJqWzB.d.ts → agent-tools-Dj5Mzlw7.d.ts} +7 -7
  6. package/dist/agent-tools.d.ts +21 -21
  7. package/dist/browser/ai.js +4 -1
  8. package/dist/browser/ai.js.map +1 -1
  9. package/dist/browser/tanstack-ai.js.map +1 -1
  10. package/dist/callable-decorator-DP__HhBA.d.ts +72 -0
  11. package/dist/callable-decorator.d.ts +18 -0
  12. package/dist/callable-decorator.js +71 -0
  13. package/dist/callable-decorator.js.map +1 -0
  14. package/dist/{capability-BjSKYpzg.js → capability-B4WbF81e.js} +2 -1
  15. package/dist/capability-B4WbF81e.js.map +1 -0
  16. package/dist/capability-runner-BUBa6Ake.d.ts +484 -0
  17. package/dist/channel-Bnm4S7T2.d.ts +491 -0
  18. package/dist/channels/ai-sdk.d.ts +46 -0
  19. package/dist/channels/ai-sdk.js +120 -0
  20. package/dist/channels/ai-sdk.js.map +1 -0
  21. package/dist/channels/email.d.ts +95 -0
  22. package/dist/channels/email.js +323 -0
  23. package/dist/channels/email.js.map +1 -0
  24. package/dist/channels/index.d.ts +233 -0
  25. package/dist/channels/index.js +608 -0
  26. package/dist/channels/index.js.map +1 -0
  27. package/dist/channels/slack.d.ts +140 -0
  28. package/dist/channels/slack.js +614 -0
  29. package/dist/channels/slack.js.map +1 -0
  30. package/dist/channels/tanstack-ai.d.ts +39 -0
  31. package/dist/channels/tanstack-ai.js +17 -0
  32. package/dist/channels/tanstack-ai.js.map +1 -0
  33. package/dist/channels/telegram.d.ts +106 -0
  34. package/dist/channels/telegram.js +427 -0
  35. package/dist/channels/telegram.js.map +1 -0
  36. package/dist/channels/voice.d.ts +45 -0
  37. package/dist/channels/voice.js +122 -0
  38. package/dist/channels/voice.js.map +1 -0
  39. package/dist/chat/index.d.ts +2319 -2010
  40. package/dist/chat/index.js +892 -518
  41. package/dist/chat/index.js.map +1 -1
  42. package/dist/chat-sdk/index.d.ts +7 -7
  43. package/dist/chat-sdk/index.js +1 -1
  44. package/dist/client-BxdkCuVy.d.ts +411 -0
  45. package/dist/client-C9DAjZIY.js +518 -0
  46. package/dist/client-C9DAjZIY.js.map +1 -0
  47. package/dist/{client-jagG8a9_.js → client-fyQrLGkD.js} +2 -2
  48. package/dist/{client-jagG8a9_.js.map → client-fyQrLGkD.js.map} +1 -1
  49. package/dist/client.d.ts +27 -283
  50. package/dist/client.js +2 -274
  51. package/dist/context/index.d.ts +216 -0
  52. package/dist/context/index.js +454 -0
  53. package/dist/context/index.js.map +1 -0
  54. package/dist/current-agent-C4w86kcN.d.ts +93 -0
  55. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  56. package/dist/{diagnostics-CaBjfz4J.js → diagnostics-BzvaX2UT.js} +5 -1
  57. package/dist/diagnostics-BzvaX2UT.js.map +1 -0
  58. package/dist/diagnostics-C4jcz3VK.js +360 -0
  59. package/dist/diagnostics-C4jcz3VK.js.map +1 -0
  60. package/dist/durable-object-lifecycle-ei7M7lqB.d.ts +157 -0
  61. package/dist/index-BB0kqhIz.d.ts +101 -0
  62. package/dist/index-BVVgDSdq.d.ts +1 -0
  63. package/dist/index-Dlgtd3Mj.d.ts +78 -0
  64. package/dist/index-XDkuQ7zm.d.ts +89 -0
  65. package/dist/{index-DcSAZKsB.d.ts → index-YSKgfgg9.d.ts} +3 -1
  66. package/dist/index.d.ts +92 -83
  67. package/dist/index.js +4 -3
  68. package/dist/ingress-BfetZbMO.js +83 -0
  69. package/dist/ingress-BfetZbMO.js.map +1 -0
  70. package/dist/internal-CYlgHl1l.js +59 -0
  71. package/dist/internal-CYlgHl1l.js.map +1 -0
  72. package/dist/internal_context.d.ts +1 -1
  73. package/dist/lifecycle/index.d.ts +39 -19
  74. package/dist/lifecycle/index.js +2 -2
  75. package/dist/lifecycle-Mm_jQh7r.js +1314 -0
  76. package/dist/lifecycle-Mm_jQh7r.js.map +1 -0
  77. package/dist/mcp/client/index.d.ts +20 -20
  78. package/dist/mcp/client/index.js +1 -1
  79. package/dist/mcp/index.d.ts +35 -35
  80. package/dist/mcp/index.js +2 -2
  81. package/dist/observability/index.d.ts +1 -1
  82. package/dist/observability/index.js +1 -1
  83. package/dist/queue/index.d.ts +123 -0
  84. package/dist/queue/index.js +2 -0
  85. package/dist/queue-BC9F5cUo.js +406 -0
  86. package/dist/queue-BC9F5cUo.js.map +1 -0
  87. package/dist/react.d.ts +34 -16
  88. package/dist/react.js +31 -8
  89. package/dist/react.js.map +1 -1
  90. package/dist/{retries-CAvxtG9d.d.ts → retries-D9B2UCq3.d.ts} +23 -6
  91. package/dist/retries.d.ts +10 -6
  92. package/dist/retries.js +21 -1
  93. package/dist/retries.js.map +1 -1
  94. package/dist/routing/index.d.ts +137 -0
  95. package/dist/routing/index.js +244 -0
  96. package/dist/routing/index.js.map +1 -0
  97. package/dist/sanitize-D9TujEK8.js +79 -0
  98. package/dist/sanitize-D9TujEK8.js.map +1 -0
  99. package/dist/{scheduler-DQoTGoAW.d.ts → scheduler-BGq6M5Kd.d.ts} +20 -21
  100. package/dist/scheduler-D_KHqxBa.js +658 -0
  101. package/dist/scheduler-D_KHqxBa.js.map +1 -0
  102. package/dist/schedules/index.d.ts +1 -1
  103. package/dist/schedules/index.js +1 -1
  104. package/dist/sentence-chunker-BAidJ4DA.d.ts +68 -0
  105. package/dist/serializable.d.ts +1 -1
  106. package/dist/sessions/index.d.ts +441 -0
  107. package/dist/sessions/index.js +2063 -0
  108. package/dist/sessions/index.js.map +1 -0
  109. package/dist/skills/index.d.ts +99 -0
  110. package/dist/skills/index.js +254 -5
  111. package/dist/skills/index.js.map +1 -1
  112. package/dist/{src-5W6JNKVb.js → src-BNU3ZiJM.js} +1524 -1441
  113. package/dist/src-BNU3ZiJM.js.map +1 -0
  114. package/dist/state/index.d.ts +6 -0
  115. package/dist/state/index.js +137 -0
  116. package/dist/state/index.js.map +1 -0
  117. package/dist/streams/index.d.ts +120 -0
  118. package/dist/streams/index.js +107 -0
  119. package/dist/streams/index.js.map +1 -0
  120. package/dist/streams-BcE8JP2X.d.ts +370 -0
  121. package/dist/streams-CCPRV6dt.js +709 -0
  122. package/dist/streams-CCPRV6dt.js.map +1 -0
  123. package/dist/sub-routing.d.ts +12 -12
  124. package/dist/surface-bZZJqBka.js +17 -0
  125. package/dist/surface-bZZJqBka.js.map +1 -0
  126. package/dist/tasks/index.d.ts +64 -0
  127. package/dist/tasks/index.js +2 -0
  128. package/dist/tasks-D4nLqVSI.js +1656 -0
  129. package/dist/tasks-D4nLqVSI.js.map +1 -0
  130. package/dist/tasks-V2lCT8ZV.d.ts +517 -0
  131. package/dist/text-segment-joiner-BtAFQSA_.js +57 -0
  132. package/dist/text-segment-joiner-BtAFQSA_.js.map +1 -0
  133. package/dist/text-stream-CpdiKrJB.js +272 -0
  134. package/dist/text-stream-CpdiKrJB.js.map +1 -0
  135. package/dist/tokens-nHAKcN6M.js +52 -0
  136. package/dist/tokens-nHAKcN6M.js.map +1 -0
  137. package/dist/tool-schema-CBjGPrsQ.js +31 -0
  138. package/dist/tool-schema-CBjGPrsQ.js.map +1 -0
  139. package/dist/transport-protocol-BxyngQ_R.js +25 -0
  140. package/dist/transport-protocol-BxyngQ_R.js.map +1 -0
  141. package/dist/transport-protocol-ZTew5Wso.d.ts +27 -0
  142. package/dist/types-B7LojTe4.d.ts +202 -0
  143. package/dist/types-DCD6BNZH.d.ts +70 -0
  144. package/dist/types-_Faxb570.d.ts +439 -0
  145. package/dist/voice/client.d.ts +226 -0
  146. package/dist/voice/client.js +932 -0
  147. package/dist/voice/client.js.map +1 -0
  148. package/dist/voice/errors.d.ts +43 -0
  149. package/dist/voice/errors.js +41 -0
  150. package/dist/voice/errors.js.map +1 -0
  151. package/dist/voice/index.d.ts +271 -0
  152. package/dist/voice/index.js +1812 -0
  153. package/dist/voice/index.js.map +1 -0
  154. package/dist/voice/react.d.ts +167 -0
  155. package/dist/voice/react.js +234 -0
  156. package/dist/voice/react.js.map +1 -0
  157. package/dist/voice/sfu.d.ts +71 -0
  158. package/dist/voice/sfu.js +157 -0
  159. package/dist/voice/sfu.js.map +1 -0
  160. package/dist/voice/text.d.ts +6 -0
  161. package/dist/voice/text.js +2 -0
  162. package/dist/voice/types.d.ts +58 -0
  163. package/dist/voice/types.js +18 -0
  164. package/dist/voice/types.js.map +1 -0
  165. package/dist/voice/workers-ai.d.ts +136 -0
  166. package/dist/voice/workers-ai.js +568 -0
  167. package/dist/voice/workers-ai.js.map +1 -0
  168. package/dist/websockets/index.d.ts +301 -0
  169. package/dist/websockets/index.js +3 -0
  170. package/dist/websockets-D7IzWbZb.js +1005 -0
  171. package/dist/websockets-D7IzWbZb.js.map +1 -0
  172. package/dist/workflow-types.d.ts +25 -25
  173. package/dist/workflows.d.ts +21 -21
  174. package/dist/workflows.js +1 -1
  175. package/docs/agent-class.md +4 -4
  176. package/docs/agent-tools.md +2 -1
  177. package/docs/channels.md +323 -0
  178. package/docs/chat-agents.md +6 -13
  179. package/docs/client-sdk.md +30 -0
  180. package/docs/context.md +131 -0
  181. package/docs/index.md +16 -13
  182. package/docs/lifecycle.md +179 -57
  183. package/docs/long-running-agents.md +2 -2
  184. package/docs/mcp-servers.md +5 -1
  185. package/docs/queue.md +135 -241
  186. package/docs/resumable-streaming.md +1 -1
  187. package/docs/retries.md +1 -1
  188. package/docs/routing.md +105 -0
  189. package/docs/sessions.md +237 -871
  190. package/docs/streams.md +213 -0
  191. package/docs/sub-agents.md +184 -124
  192. package/docs/tasks.md +246 -0
  193. package/docs/voice.md +745 -0
  194. package/package.json +126 -14
  195. package/dist/capability-BjSKYpzg.js.map +0 -1
  196. package/dist/capability-runner-CvHGZqUu.d.ts +0 -150
  197. package/dist/client.js.map +0 -1
  198. package/dist/compaction-helpers-iiKMr2TQ.js +0 -340
  199. package/dist/compaction-helpers-iiKMr2TQ.js.map +0 -1
  200. package/dist/compaction-helpers-wUz6M3us.d.ts +0 -621
  201. package/dist/current-agent-CuMErtly.d.ts +0 -283
  202. package/dist/diagnostics-CaBjfz4J.js.map +0 -1
  203. package/dist/durable-object-lifecycle-D6nNQJJd.js +0 -862
  204. package/dist/durable-object-lifecycle-D6nNQJJd.js.map +0 -1
  205. package/dist/experimental/memory/session/index.d.ts +0 -671
  206. package/dist/experimental/memory/session/index.js +0 -2379
  207. package/dist/experimental/memory/session/index.js.map +0 -1
  208. package/dist/experimental/memory/utils/index.d.ts +0 -96
  209. package/dist/experimental/memory/utils/index.js +0 -79
  210. package/dist/experimental/memory/utils/index.js.map +0 -1
  211. package/dist/scheduler-CR9RHGos.js +0 -857
  212. package/dist/scheduler-CR9RHGos.js.map +0 -1
  213. package/dist/src-5W6JNKVb.js.map +0 -1
  214. package/dist/tool-output-truncation-CNnnGZQ3.js +0 -98
  215. package/dist/tool-output-truncation-CNnnGZQ3.js.map +0 -1
@@ -0,0 +1,518 @@
1
+ import { camelCaseToKebabCase, isInternalJsStubProp } from "./utils.js";
2
+ import "./types.js";
3
+ import { i as capnWebTransportUrl, n as CAPNWEB_TRANSPORT_SEND } from "./transport-protocol-BxyngQ_R.js";
4
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
5
+ import { PartySocket } from "partysocket";
6
+ import { RpcTarget, newWebSocketRpcSession } from "capnweb";
7
+ //#region src/websockets/capnweb-socket.ts
8
+ /** Local root the host calls to deliver frames. */
9
+ var Inbox = class extends RpcTarget {
10
+ constructor(socket) {
11
+ super();
12
+ this.socket = socket;
13
+ }
14
+ message(value) {
15
+ this.socket.dispatchEvent(new MessageEvent("message", { data: value }));
16
+ }
17
+ };
18
+ var _socket = /* @__PURE__ */ new WeakMap();
19
+ var _root = /* @__PURE__ */ new WeakMap();
20
+ /**
21
+ * A WebSocket-shaped client for the Cap'n Web connection transport.
22
+ *
23
+ * It has the constructor, `readyState`, `send()`, `close()`, and events of
24
+ * a `WebSocket`, so PartySocket (and therefore `useAgent` and
25
+ * `AgentClient`) can drive it as a drop-in socket implementation and keep
26
+ * owning reconnection, buffering, and backoff. Frames sent here travel
27
+ * through the host's pipe method; frames from the host arrive as
28
+ * `message` events.
29
+ *
30
+ * @experimental The transport is experimental.
31
+ */
32
+ var CapnWebSocket = class CapnWebSocket extends EventTarget {
33
+ constructor(url, protocols) {
34
+ super();
35
+ this.CONNECTING = 0;
36
+ this.OPEN = 1;
37
+ this.CLOSING = 2;
38
+ this.CLOSED = 3;
39
+ this.readyState = CapnWebSocket.CONNECTING;
40
+ this.binaryType = "arraybuffer";
41
+ this.bufferedAmount = 0;
42
+ this.extensions = "";
43
+ this.protocol = "";
44
+ this.onopen = null;
45
+ this.onmessage = null;
46
+ this.onclose = null;
47
+ this.onerror = null;
48
+ _classPrivateFieldInitSpec(this, _socket, void 0);
49
+ _classPrivateFieldInitSpec(this, _root, void 0);
50
+ this.url = capnWebTransportUrl(url);
51
+ _classPrivateFieldSet2(_socket, this, protocols ? new WebSocket(this.url, protocols) : new WebSocket(this.url));
52
+ _classPrivateFieldSet2(_root, this, newWebSocketRpcSession(_classPrivateFieldGet2(_socket, this), new Inbox(this)));
53
+ _classPrivateFieldGet2(_socket, this).addEventListener("open", () => {
54
+ this.readyState = CapnWebSocket.OPEN;
55
+ this.protocol = _classPrivateFieldGet2(_socket, this).protocol;
56
+ this.dispatchEvent(new Event("open"));
57
+ });
58
+ _classPrivateFieldGet2(_socket, this).addEventListener("close", (event) => {
59
+ this.readyState = CapnWebSocket.CLOSED;
60
+ this.dispatchEvent(new CloseEvent("close", {
61
+ code: event.code,
62
+ reason: event.reason,
63
+ wasClean: event.wasClean
64
+ }));
65
+ });
66
+ _classPrivateFieldGet2(_socket, this).addEventListener("error", () => {
67
+ this.dispatchEvent(new Event("error"));
68
+ });
69
+ }
70
+ dispatchEvent(event) {
71
+ const handler = Reflect.get(this, `on${event.type}`);
72
+ if (typeof handler === "function") Reflect.apply(handler, this, [event]);
73
+ return super.dispatchEvent(event);
74
+ }
75
+ /**
76
+ * Invoke one of the host's native callables on the session root. The
77
+ * result keeps Cap'n Web semantics: an `RpcTarget` arrives as a live
78
+ * stub, a `ReadableStream` streams, and chained calls pipeline.
79
+ */
80
+ invoke(method, args) {
81
+ if (this.readyState !== CapnWebSocket.OPEN) return Promise.reject(/* @__PURE__ */ new Error("Connection closed"));
82
+ const root = _classPrivateFieldGet2(_root, this);
83
+ return Promise.resolve(root[method](...args));
84
+ }
85
+ send(data) {
86
+ if (this.readyState !== CapnWebSocket.OPEN) throw new DOMException("WebSocket is not open", "InvalidStateError");
87
+ _classPrivateFieldGet2(_root, this)[CAPNWEB_TRANSPORT_SEND](data).catch(() => {
88
+ this.dispatchEvent(new Event("error"));
89
+ });
90
+ }
91
+ close(code, reason) {
92
+ if (this.readyState >= CapnWebSocket.CLOSING) return;
93
+ this.readyState = CapnWebSocket.CLOSING;
94
+ try {
95
+ _classPrivateFieldGet2(_root, this)[Symbol.dispose]();
96
+ } catch {}
97
+ _classPrivateFieldGet2(_socket, this).close(code, reason);
98
+ }
99
+ };
100
+ CapnWebSocket.CONNECTING = 0;
101
+ CapnWebSocket.OPEN = 1;
102
+ CapnWebSocket.CLOSING = 2;
103
+ CapnWebSocket.CLOSED = 3;
104
+ /**
105
+ * A `CapnWebSocket` subclass that reports each instance it constructs.
106
+ * PartySocket instantiates the class it is given; this is how a client
107
+ * gets hold of the live socket to call `invoke()` without reaching into
108
+ * PartySocket internals.
109
+ */
110
+ function boundCapnWebSocket(onCreate) {
111
+ return class BoundCapnWebSocket extends CapnWebSocket {
112
+ constructor(url, protocols) {
113
+ super(url, protocols);
114
+ onCreate(this);
115
+ }
116
+ };
117
+ }
118
+ //#endregion
119
+ //#region src/client.ts
120
+ var AgentConnectionError = class extends Error {
121
+ constructor(event) {
122
+ const reason = event.reason || `WebSocket closed with code ${event.code}`;
123
+ super(`Agent connection closed: ${reason}`);
124
+ this.name = "AgentConnectionError";
125
+ this.code = event.code;
126
+ this.reason = event.reason;
127
+ this.wasClean = event.wasClean;
128
+ }
129
+ };
130
+ function isTerminalCloseEvent(event) {
131
+ return event.code === 1008 || event.code >= 4e3 && event.code <= 4999;
132
+ }
133
+ /**
134
+ * Default timeout (in milliseconds) applied to non-streaming RPC calls
135
+ * that don't pass an explicit `timeout`. Acts as a backstop so calls
136
+ * whose response is lost (e.g. the connection drops mid-flight) reject
137
+ * instead of hanging forever. Override per client via
138
+ * `defaultCallTimeout`, or per call via `timeout` (0 disables).
139
+ */
140
+ const DEFAULT_CALL_TIMEOUT_MS = 3e4;
141
+ /**
142
+ * Normalize `call()` options. The legacy shape is the stream callbacks
143
+ * themselves (`{ onChunk, onDone, onError }`); the current shape nests
144
+ * them under `stream` beside `timeout`.
145
+ */
146
+ function splitCallOptions(options) {
147
+ return options !== void 0 && ("onChunk" in options || "onDone" in options || "onError" in options) ? {
148
+ stream: options,
149
+ timeout: void 0
150
+ } : {
151
+ stream: options?.stream,
152
+ timeout: options?.timeout
153
+ };
154
+ }
155
+ /**
156
+ * One native call on the Cap'n Web transport, with the timeout and
157
+ * stream-callback contract `call()` has on the JSON wire. The timeout
158
+ * covers the whole call, draining included: on expiry the stream reader is
159
+ * cancelled and the promise rejects once. A `ReadableStream` result is
160
+ * drained into the stream callbacks when they are given; any other value,
161
+ * live stubs included, passes straight through.
162
+ */
163
+ async function nativeCall(socket, method, args, options, defaultTimeout) {
164
+ const { stream, timeout } = splitCallOptions(options);
165
+ const effectiveTimeout = timeout !== void 0 ? timeout : stream ? void 0 : defaultTimeout;
166
+ let reader;
167
+ let timer;
168
+ const work = (async () => {
169
+ const result = await socket.invoke(method, args);
170
+ if (stream && result instanceof ReadableStream) {
171
+ reader = result.getReader();
172
+ for (;;) {
173
+ const { done, value } = await reader.read();
174
+ if (done) break;
175
+ stream.onChunk?.(value);
176
+ }
177
+ stream.onDone?.(void 0);
178
+ return;
179
+ }
180
+ return result;
181
+ })();
182
+ const expiry = effectiveTimeout ? new Promise((_, reject) => {
183
+ timer = setTimeout(() => {
184
+ reader?.cancel().catch(() => {});
185
+ reject(/* @__PURE__ */ new Error(`RPC call to ${method} timed out after ${effectiveTimeout}ms`));
186
+ }, effectiveTimeout);
187
+ }) : void 0;
188
+ try {
189
+ return await (expiry ? Promise.race([work, expiry]) : work);
190
+ } catch (error) {
191
+ work.catch(() => {});
192
+ stream?.onError?.(error instanceof Error ? error.message : String(error));
193
+ throw error;
194
+ } finally {
195
+ if (timer) clearTimeout(timer);
196
+ }
197
+ }
198
+ var _pending = /* @__PURE__ */ new WeakMap();
199
+ /**
200
+ * Native calls issued while the Cap'n Web socket is still connecting or
201
+ * between reconnects. They must not fall back to JSON frames — that would
202
+ * change which methods are reachable and lose return-by-reference — so
203
+ * they wait here and run on the next open socket, or reject when the
204
+ * connection ends for good. Their timeout starts when they are issued.
205
+ */
206
+ var NativeCallQueue = class {
207
+ constructor() {
208
+ _classPrivateFieldInitSpec(this, _pending, []);
209
+ }
210
+ enqueue(method, args, options, defaultTimeout) {
211
+ return new Promise((resolve, reject) => {
212
+ const { stream, timeout } = splitCallOptions(options);
213
+ const effectiveTimeout = timeout !== void 0 ? timeout : stream ? void 0 : defaultTimeout;
214
+ const startedAt = Date.now();
215
+ const entry = {
216
+ run: (socket) => {
217
+ const remaining = effectiveTimeout === void 0 ? void 0 : Math.max(1, effectiveTimeout - (Date.now() - startedAt));
218
+ nativeCall(socket, method, args, remaining === void 0 ? options : {
219
+ stream,
220
+ timeout: remaining
221
+ }, defaultTimeout).then(resolve, reject);
222
+ },
223
+ reject: (error) => {
224
+ stream?.onError?.(error.message);
225
+ reject(error);
226
+ }
227
+ };
228
+ _classPrivateFieldGet2(_pending, this).push(entry);
229
+ if (effectiveTimeout) setTimeout(() => {
230
+ const index = _classPrivateFieldGet2(_pending, this).indexOf(entry);
231
+ if (index === -1) return;
232
+ _classPrivateFieldGet2(_pending, this).splice(index, 1);
233
+ entry.reject(/* @__PURE__ */ new Error(`RPC call to ${method} timed out after ${effectiveTimeout}ms`));
234
+ }, effectiveTimeout);
235
+ });
236
+ }
237
+ /** Run everything queued on a socket that just opened. */
238
+ flush(socket) {
239
+ const pending = _classPrivateFieldGet2(_pending, this);
240
+ _classPrivateFieldSet2(_pending, this, []);
241
+ for (const entry of pending) entry.run(socket);
242
+ }
243
+ /** Reject everything queued; the connection will not come back. */
244
+ rejectAll(reason) {
245
+ const pending = _classPrivateFieldGet2(_pending, this);
246
+ _classPrivateFieldSet2(_pending, this, []);
247
+ const error = new Error(reason);
248
+ for (const entry of pending) entry.reject(error);
249
+ }
250
+ };
251
+ /**
252
+ * Creates a proxy that wraps RPC method calls.
253
+ * Internal JS methods (toJSON, then, etc.) return undefined to avoid
254
+ * triggering RPC calls during serialization (e.g., console.log)
255
+ */
256
+ function createStubProxy(call) {
257
+ return new Proxy({}, { get: (_target, method) => {
258
+ if (isInternalJsStubProp(method)) return;
259
+ return (...args) => call(method, args);
260
+ } });
261
+ }
262
+ var _capnWeb = /* @__PURE__ */ new WeakMap();
263
+ var _nativeQueue = /* @__PURE__ */ new WeakMap();
264
+ /**
265
+ * WebSocket client for connecting to an Agent
266
+ */
267
+ var AgentClient = class extends PartySocket {
268
+ /**
269
+ * @deprecated Use agentFetch instead
270
+ */
271
+ static fetch(_opts) {
272
+ throw new Error("AgentClient.fetch is not implemented, use agentFetch instead");
273
+ }
274
+ /**
275
+ * Promise that resolves when identity has been received from the server.
276
+ * Useful for waiting before making calls that depend on knowing the instance.
277
+ * Resets on connection close so it can be awaited again after reconnect.
278
+ */
279
+ get ready() {
280
+ return this._readyPromise;
281
+ }
282
+ _resetReady() {
283
+ this._readyPromise = new Promise((resolve) => {
284
+ this._resolveReady = resolve;
285
+ });
286
+ }
287
+ constructor(options) {
288
+ const capnWeb = { current: null };
289
+ const socketClass = options.transport === "capnweb" ? { WebSocket: boundCapnWebSocket((socket) => {
290
+ capnWeb.current = socket;
291
+ }) } : {};
292
+ const agentNamespace = camelCaseToKebabCase(options.agent);
293
+ const shouldReconnectOnClose = options.shouldReconnectOnClose;
294
+ const classifyReconnect = (event) => (shouldReconnectOnClose?.(event) ?? true) && !isTerminalCloseEvent(event);
295
+ const socketOptions = options.basePath ? {
296
+ basePath: options.basePath,
297
+ path: options.path,
298
+ ...options,
299
+ ...socketClass,
300
+ shouldReconnectOnClose: classifyReconnect
301
+ } : {
302
+ party: agentNamespace,
303
+ prefix: "agents",
304
+ room: options.name || "default",
305
+ path: options.path,
306
+ ...options,
307
+ ...socketClass,
308
+ shouldReconnectOnClose: classifyReconnect
309
+ };
310
+ super(socketOptions);
311
+ this.state = void 0;
312
+ this.identified = false;
313
+ this.connectionError = null;
314
+ this._pendingCalls = /* @__PURE__ */ new Map();
315
+ this._previousName = null;
316
+ this._previousAgent = null;
317
+ _classPrivateFieldInitSpec(this, _capnWeb, void 0);
318
+ _classPrivateFieldInitSpec(this, _nativeQueue, new NativeCallQueue());
319
+ _classPrivateFieldSet2(_capnWeb, this, capnWeb);
320
+ this.agent = agentNamespace;
321
+ this.name = options.name || "default";
322
+ this.options = options;
323
+ this._resetReady();
324
+ this.addEventListener("message", (event) => {
325
+ if (typeof event.data === "string") {
326
+ let parsedMessage;
327
+ try {
328
+ parsedMessage = JSON.parse(event.data);
329
+ } catch (_error) {
330
+ return;
331
+ }
332
+ if (parsedMessage.type === "cf_agent_identity") {
333
+ const oldName = this._previousName;
334
+ const oldAgent = this._previousAgent;
335
+ const newName = parsedMessage.name;
336
+ const newAgent = parsedMessage.agent;
337
+ this.identified = true;
338
+ this._resolveReady();
339
+ if (oldName !== null && oldAgent !== null && (oldName !== newName || oldAgent !== newAgent)) if (this.options.onIdentityChange) this.options.onIdentityChange(oldName, newName, oldAgent, newAgent);
340
+ else {
341
+ const agentChanged = oldAgent !== newAgent;
342
+ const nameChanged = oldName !== newName;
343
+ let changeDescription = "";
344
+ if (agentChanged && nameChanged) changeDescription = `agent "${oldAgent}" → "${newAgent}", instance "${oldName}" → "${newName}"`;
345
+ else if (agentChanged) changeDescription = `agent "${oldAgent}" → "${newAgent}"`;
346
+ else changeDescription = `instance "${oldName}" → "${newName}"`;
347
+ console.warn(`[agents] Identity changed on reconnect: ${changeDescription}. This can happen with server-side routing (e.g., basePath with getAgentByName) where the instance is determined by auth/session. Provide onIdentityChange callback to handle this explicitly, or ignore if this is expected for your routing pattern.`);
348
+ }
349
+ this._previousName = newName;
350
+ this._previousAgent = newAgent;
351
+ this.name = newName;
352
+ this.agent = newAgent;
353
+ this.options.onIdentity?.(newName, newAgent);
354
+ return;
355
+ }
356
+ if (parsedMessage.type === "cf_agent_state") {
357
+ this.state = parsedMessage.state;
358
+ this.options.onStateUpdate?.(parsedMessage.state, "server");
359
+ return;
360
+ }
361
+ if (parsedMessage.type === "cf_agent_state_error") {
362
+ this.options.onStateUpdateError?.(parsedMessage.error);
363
+ return;
364
+ }
365
+ if (parsedMessage.type === "rpc") {
366
+ const response = parsedMessage;
367
+ const pending = this._pendingCalls.get(response.id);
368
+ if (!pending) {
369
+ console.warn(`[AgentClient] Discarded an RPC response with no matching pending call (id "${response.id}"). The call likely timed out or was rejected when its connection closed before the response arrived.`);
370
+ return;
371
+ }
372
+ if (!response.success) {
373
+ pending.reject(new Error(response.error));
374
+ this._pendingCalls.delete(response.id);
375
+ pending.stream?.onError?.(response.error);
376
+ return;
377
+ }
378
+ if ("done" in response) if (response.done) {
379
+ pending.resolve(response.result);
380
+ this._pendingCalls.delete(response.id);
381
+ pending.stream?.onDone?.(response.result);
382
+ } else pending.stream?.onChunk?.(response.result);
383
+ else {
384
+ pending.resolve(response.result);
385
+ this._pendingCalls.delete(response.id);
386
+ }
387
+ }
388
+ }
389
+ });
390
+ this.addEventListener("open", () => {
391
+ this.connectionError = null;
392
+ for (const pending of this._pendingCalls.values()) pending.transmitted = true;
393
+ const native = _classPrivateFieldGet2(_capnWeb, this).current;
394
+ if (native) _classPrivateFieldGet2(_nativeQueue, this).flush(native);
395
+ });
396
+ this.addEventListener("close", (event) => {
397
+ const terminalClose = isTerminalCloseEvent(event);
398
+ this.identified = false;
399
+ this._resetReady();
400
+ if (this.shouldReconnect) this._rejectPendingCalls("Connection closed", { onlyTransmitted: true });
401
+ else {
402
+ this._rejectPendingCalls("Connection closed");
403
+ _classPrivateFieldGet2(_nativeQueue, this).rejectAll("Connection closed");
404
+ if (terminalClose) {
405
+ const error = new AgentConnectionError(event);
406
+ this.connectionError = error;
407
+ this.options.onConnectionError?.(error);
408
+ }
409
+ }
410
+ });
411
+ this.call = this._callImpl.bind(this);
412
+ this.stub = createStubProxy((method, args) => this._callImpl(method, args));
413
+ }
414
+ /**
415
+ * Reject pending RPC calls with the given reason.
416
+ * With `onlyTransmitted`, calls still sitting in the send buffer are
417
+ * kept pending (they'll be flushed on reconnect).
418
+ */
419
+ _rejectPendingCalls(reason, { onlyTransmitted = false } = {}) {
420
+ const error = new Error(reason);
421
+ for (const [id, pending] of this._pendingCalls) {
422
+ if (onlyTransmitted && !pending.transmitted) continue;
423
+ this._pendingCalls.delete(id);
424
+ pending.reject(error);
425
+ pending.stream?.onError?.(reason);
426
+ }
427
+ }
428
+ setState(state) {
429
+ this.send(JSON.stringify({
430
+ state,
431
+ type: "cf_agent_state"
432
+ }));
433
+ this.state = state;
434
+ this.options.onStateUpdate?.(state, "client");
435
+ }
436
+ /**
437
+ * Close the connection and immediately reject all pending RPC calls.
438
+ * This provides immediate feedback on intentional close rather than
439
+ * waiting for the WebSocket close handshake to complete.
440
+ *
441
+ * Note: Any calls made after `close()` will be rejected when the
442
+ * underlying WebSocket close event fires.
443
+ */
444
+ close(code, reason) {
445
+ this._rejectPendingCalls("Connection closed");
446
+ super.close(code, reason);
447
+ }
448
+ /**
449
+ * Call a method on the Agent.
450
+ * When AgentT is provided, method names are inferred from the agent's methods.
451
+ * Falls back to untyped string-based calls when AgentT is not provided.
452
+ */
453
+ async _callImpl(method, args = [], options) {
454
+ if (this.options.transport === "capnweb") {
455
+ const timeout = this.options.defaultCallTimeout ?? 3e4;
456
+ const native = _classPrivateFieldGet2(_capnWeb, this).current;
457
+ if (native && this.readyState === this.OPEN) return nativeCall(native, method, args, options, timeout);
458
+ if (this.connectionError && this.readyState === this.CLOSED) throw new Error("Connection closed");
459
+ return _classPrivateFieldGet2(_nativeQueue, this).enqueue(method, args, options, timeout);
460
+ }
461
+ if (this.connectionError && this.readyState === this.CLOSED) throw new Error("Connection closed");
462
+ return new Promise((resolve, reject) => {
463
+ const id = crypto.randomUUID();
464
+ let timeoutId;
465
+ const { stream: streamOptions, timeout } = splitCallOptions(options);
466
+ const effectiveTimeout = timeout !== void 0 ? timeout : streamOptions ? void 0 : this.options.defaultCallTimeout ?? 3e4;
467
+ if (effectiveTimeout) timeoutId = setTimeout(() => {
468
+ const pending = this._pendingCalls.get(id);
469
+ this._pendingCalls.delete(id);
470
+ const errorMessage = `RPC call to ${method} timed out after ${effectiveTimeout}ms`;
471
+ pending?.stream?.onError?.(errorMessage);
472
+ reject(new Error(errorMessage));
473
+ }, effectiveTimeout);
474
+ this._pendingCalls.set(id, {
475
+ reject: (e) => {
476
+ if (timeoutId) clearTimeout(timeoutId);
477
+ reject(e);
478
+ },
479
+ resolve: (value) => {
480
+ if (timeoutId) clearTimeout(timeoutId);
481
+ resolve(value);
482
+ },
483
+ stream: streamOptions,
484
+ transmitted: this.readyState === this.OPEN
485
+ });
486
+ const request = {
487
+ args,
488
+ id,
489
+ method,
490
+ type: "rpc"
491
+ };
492
+ this.send(JSON.stringify(request));
493
+ });
494
+ }
495
+ };
496
+ /**
497
+ * Make an HTTP request to an Agent
498
+ * @param opts Connection options
499
+ * @param init Request initialization options
500
+ * @returns Promise resolving to a Response
501
+ */
502
+ function agentFetch(opts, init) {
503
+ const agentNamespace = camelCaseToKebabCase(opts.agent);
504
+ if (opts.basePath) return PartySocket.fetch({
505
+ basePath: opts.basePath,
506
+ ...opts
507
+ }, init);
508
+ return PartySocket.fetch({
509
+ party: agentNamespace,
510
+ prefix: "agents",
511
+ room: opts.name || "default",
512
+ ...opts
513
+ }, init);
514
+ }
515
+ //#endregion
516
+ export { agentFetch as a, nativeCall as c, NativeCallQueue as i, splitCallOptions as l, AgentConnectionError as n, createStubProxy as o, DEFAULT_CALL_TIMEOUT_MS as r, isTerminalCloseEvent as s, AgentClient as t, boundCapnWebSocket as u };
517
+
518
+ //# sourceMappingURL=client-C9DAjZIY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-C9DAjZIY.js","names":[],"sources":["../src/websockets/capnweb-socket.ts","../src/client.ts"],"sourcesContent":["import { newWebSocketRpcSession, RpcTarget, type RpcStub } from \"capnweb\";\nimport {\n CAPNWEB_TRANSPORT_SEND,\n capnWebTransportUrl,\n type TransportClientEvents,\n type TransportHostPipe,\n type TransportMessage\n} from \"./transport-protocol\";\n\n/** Local root the host calls to deliver frames. */\nclass Inbox extends RpcTarget implements TransportClientEvents {\n constructor(private readonly socket: CapnWebSocket) {\n super();\n }\n\n message(value: TransportMessage): void {\n this.socket.dispatchEvent(new MessageEvent(\"message\", { data: value }));\n }\n}\n\n/**\n * A WebSocket-shaped client for the Cap'n Web connection transport.\n *\n * It has the constructor, `readyState`, `send()`, `close()`, and events of\n * a `WebSocket`, so PartySocket (and therefore `useAgent` and\n * `AgentClient`) can drive it as a drop-in socket implementation and keep\n * owning reconnection, buffering, and backoff. Frames sent here travel\n * through the host's pipe method; frames from the host arrive as\n * `message` events.\n *\n * @experimental The transport is experimental.\n */\nexport class CapnWebSocket extends EventTarget {\n static readonly CONNECTING = 0;\n static readonly OPEN = 1;\n static readonly CLOSING = 2;\n static readonly CLOSED = 3;\n readonly CONNECTING = 0;\n readonly OPEN = 1;\n readonly CLOSING = 2;\n readonly CLOSED = 3;\n\n readonly url: string;\n readyState = CapnWebSocket.CONNECTING;\n binaryType: BinaryType = \"arraybuffer\";\n bufferedAmount = 0;\n extensions = \"\";\n protocol = \"\";\n onopen: ((event: Event) => void) | null = null;\n onmessage: ((event: MessageEvent) => void) | null = null;\n onclose: ((event: CloseEvent) => void) | null = null;\n onerror: ((event: Event) => void) | null = null;\n\n readonly #socket: WebSocket;\n readonly #root: RpcStub<TransportHostPipe>;\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super();\n this.url = capnWebTransportUrl(url);\n this.#socket = protocols\n ? new WebSocket(this.url, protocols)\n : new WebSocket(this.url);\n this.#root = newWebSocketRpcSession<TransportHostPipe>(\n this.#socket,\n new Inbox(this)\n );\n this.#socket.addEventListener(\"open\", () => {\n this.readyState = CapnWebSocket.OPEN;\n this.protocol = this.#socket.protocol;\n this.dispatchEvent(new Event(\"open\"));\n });\n this.#socket.addEventListener(\"close\", (event) => {\n this.readyState = CapnWebSocket.CLOSED;\n this.dispatchEvent(\n new CloseEvent(\"close\", {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean\n })\n );\n });\n this.#socket.addEventListener(\"error\", () => {\n this.dispatchEvent(new Event(\"error\"));\n });\n }\n\n override dispatchEvent(event: Event): boolean {\n const handler = Reflect.get(this, `on${event.type}`) as unknown;\n if (typeof handler === \"function\") Reflect.apply(handler, this, [event]);\n return super.dispatchEvent(event);\n }\n\n /**\n * Invoke one of the host's native callables on the session root. The\n * result keeps Cap'n Web semantics: an `RpcTarget` arrives as a live\n * stub, a `ReadableStream` streams, and chained calls pipeline.\n */\n invoke(method: string, args: unknown[]): Promise<unknown> {\n if (this.readyState !== CapnWebSocket.OPEN) {\n return Promise.reject(new Error(\"Connection closed\"));\n }\n // The root stub answers every property with a callable, so an unknown\n // method is only detected by the host, which rejects the call. The\n // result is an RpcPromise; resolve through a plain Promise so callers\n // hold nothing exotic.\n const root = this.#root as unknown as Record<\n string,\n (...a: unknown[]) => unknown\n >;\n return Promise.resolve(root[method](...args));\n }\n\n send(data: TransportMessage): void {\n if (this.readyState !== CapnWebSocket.OPEN) {\n throw new DOMException(\"WebSocket is not open\", \"InvalidStateError\");\n }\n void this.#root[CAPNWEB_TRANSPORT_SEND](data).catch(() => {\n this.dispatchEvent(new Event(\"error\"));\n });\n }\n\n close(code?: number, reason?: string): void {\n if (this.readyState >= CapnWebSocket.CLOSING) return;\n this.readyState = CapnWebSocket.CLOSING;\n try {\n this.#root[Symbol.dispose]();\n } catch {\n // The session is already gone; closing the socket is enough.\n }\n this.#socket.close(code, reason);\n }\n}\n\n/**\n * A `CapnWebSocket` subclass that reports each instance it constructs.\n * PartySocket instantiates the class it is given; this is how a client\n * gets hold of the live socket to call `invoke()` without reaching into\n * PartySocket internals.\n */\nexport function boundCapnWebSocket(\n onCreate: (socket: CapnWebSocket) => void\n): typeof CapnWebSocket {\n return class BoundCapnWebSocket extends CapnWebSocket {\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url, protocols);\n onCreate(this);\n }\n };\n}\n","import {\n type PartyFetchOptions,\n PartySocket,\n type PartySocketOptions\n} from \"partysocket\";\nimport type { Agent, RPCRequest, RPCResponse } from \"./\";\nimport type {\n ClientParameters,\n Method,\n RPCMethod,\n SerializableReturnValue,\n SerializableValue\n} from \"./serializable\";\nimport { MessageType } from \"./types\";\nimport { camelCaseToKebabCase, isInternalJsStubProp } from \"./utils\";\nimport {\n boundCapnWebSocket,\n type CapnWebSocket\n} from \"./websockets/capnweb-socket\";\nimport type { AgentTransport } from \"./websockets/transport-protocol\";\n\nexport type { AgentTransport } from \"./websockets/transport-protocol\";\n\nexport class AgentConnectionError extends Error {\n code: number;\n reason: string;\n wasClean: boolean;\n\n constructor(event: CloseEvent) {\n const reason = event.reason || `WebSocket closed with code ${event.code}`;\n super(`Agent connection closed: ${reason}`);\n this.name = \"AgentConnectionError\";\n this.code = event.code;\n this.reason = event.reason;\n this.wasClean = event.wasClean;\n }\n}\n\nexport function isTerminalCloseEvent(event: CloseEvent): boolean {\n return event.code === 1008 || (event.code >= 4000 && event.code <= 4999);\n}\n\ntype TerminalReconnectOptions = {\n shouldReconnectOnClose?: (event: CloseEvent) => boolean;\n};\n\n/**\n * Options for creating an AgentClient\n */\nexport type AgentClientOptions<State = unknown> = Omit<\n PartySocketOptions,\n \"party\" | \"room\"\n> &\n TerminalReconnectOptions & {\n /**\n * Wire the connection travels on. `\"cf-websocket\"` (default) is a\n * hibernating WebSocket where `call()` sends JSON `rpc` frames.\n * `\"capnweb\"` carries protocol frames over a Cap'n Web session whose\n * root also serves the host's `callables` natively, so `call()` and\n * `stub` invoke them directly and an `RpcTarget` result is a live stub.\n * The Durable Object stays in memory while a capnweb connection is open.\n * @experimental The `\"capnweb\"` transport is experimental.\n */\n transport?: AgentTransport;\n /** Name of the agent to connect to (ignored if basePath is set) */\n agent: string;\n /** Name of the specific Agent instance (ignored if basePath is set) */\n name?: string;\n /**\n * Full URL path - bypasses agent/name URL construction.\n * When set, the client connects to this path directly.\n * Server must handle routing manually (e.g., with getAgentByName + fetch).\n * @example\n * // Client connects to /user, server routes based on session\n * useAgent({ agent: \"UserAgent\", basePath: \"user\" })\n */\n basePath?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n /** Called when a state update fails (e.g., connection is readonly) */\n onStateUpdateError?: (error: string) => void;\n /**\n * Called when the server sends the agent's identity on connect.\n * Useful when using basePath, as the actual instance name is determined server-side.\n * @param name The actual agent instance name\n * @param agent The agent class name (kebab-case)\n */\n onIdentity?: (name: string, agent: string) => void;\n /**\n * Called when identity changes on reconnect (different instance than before).\n * If not provided and identity changes, a warning will be logged.\n * @param oldName Previous instance name\n * @param newName New instance name\n * @param oldAgent Previous agent class name\n * @param newAgent New agent class name\n */\n onIdentityChange?: (\n oldName: string,\n newName: string,\n oldAgent: string,\n newAgent: string\n ) => void;\n /**\n * Additional path to append to the URL.\n * Works with both standard routing and basePath.\n * @example\n * // With basePath: /user/settings\n * { basePath: \"user\", path: \"settings\" }\n * // Standard: /agents/my-agent/room/settings\n * { agent: \"MyAgent\", name: \"room\", path: \"settings\" }\n */\n path?: string;\n /**\n * Default timeout (in milliseconds) applied to non-streaming `call()`s\n * that don't pass an explicit `timeout`. Defaults to 30 000 ms.\n * Set to `0` to disable. Streaming calls never get a default timeout.\n */\n defaultCallTimeout?: number;\n /** Called when the connection closes with a terminal code and will not reconnect. */\n onConnectionError?: (error: AgentConnectionError) => void;\n };\n\n/**\n * Default timeout (in milliseconds) applied to non-streaming RPC calls\n * that don't pass an explicit `timeout`. Acts as a backstop so calls\n * whose response is lost (e.g. the connection drops mid-flight) reject\n * instead of hanging forever. Override per client via\n * `defaultCallTimeout`, or per call via `timeout` (0 disables).\n */\nexport const DEFAULT_CALL_TIMEOUT_MS = 30_000;\n\n/**\n * Options for streaming RPC calls\n */\nexport type StreamOptions = {\n /** Called when a chunk of data is received */\n onChunk?: (chunk: unknown) => void;\n /** Called when the stream ends */\n onDone?: (finalChunk: unknown) => void;\n /** Called when an error occurs */\n onError?: (error: string) => void;\n};\n\n/**\n * Options for RPC calls\n */\nexport type CallOptions = {\n /** Timeout in milliseconds. If the call doesn't complete within this time, it will be rejected. */\n timeout?: number;\n /** Streaming options for handling streaming responses */\n stream?: StreamOptions;\n};\n\n/**\n * Normalize `call()` options. The legacy shape is the stream callbacks\n * themselves (`{ onChunk, onDone, onError }`); the current shape nests\n * them under `stream` beside `timeout`.\n */\nexport function splitCallOptions(\n options: CallOptions | StreamOptions | undefined\n): {\n stream: StreamOptions | undefined;\n timeout: number | undefined;\n} {\n const legacy =\n options !== undefined &&\n (\"onChunk\" in options || \"onDone\" in options || \"onError\" in options);\n return legacy\n ? { stream: options as StreamOptions, timeout: undefined }\n : {\n stream: (options as CallOptions | undefined)?.stream,\n timeout: (options as CallOptions | undefined)?.timeout\n };\n}\n\n/**\n * One native call on the Cap'n Web transport, with the timeout and\n * stream-callback contract `call()` has on the JSON wire. The timeout\n * covers the whole call, draining included: on expiry the stream reader is\n * cancelled and the promise rejects once. A `ReadableStream` result is\n * drained into the stream callbacks when they are given; any other value,\n * live stubs included, passes straight through.\n */\nexport async function nativeCall<T>(\n socket: CapnWebSocket,\n method: string,\n args: unknown[],\n options: CallOptions | StreamOptions | undefined,\n defaultTimeout: number\n): Promise<T> {\n const { stream, timeout } = splitCallOptions(options);\n const effectiveTimeout =\n timeout !== undefined ? timeout : stream ? undefined : defaultTimeout;\n let reader: ReadableStreamDefaultReader<unknown> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const work = (async () => {\n const result = await socket.invoke(method, args);\n if (stream && result instanceof ReadableStream) {\n reader = (result as ReadableStream<unknown>).getReader();\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n stream.onChunk?.(value);\n }\n stream.onDone?.(undefined);\n return undefined as T;\n }\n return result as T;\n })();\n\n const expiry = effectiveTimeout\n ? new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n void reader?.cancel().catch(() => {});\n reject(\n new Error(\n `RPC call to ${method} timed out after ${effectiveTimeout}ms`\n )\n );\n }, effectiveTimeout);\n })\n : undefined;\n\n try {\n return await (expiry ? Promise.race([work, expiry]) : work);\n } catch (error) {\n // Keep the rejection observed on the losing side of the race.\n void work.catch(() => {});\n stream?.onError?.(error instanceof Error ? error.message : String(error));\n throw error;\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * Native calls issued while the Cap'n Web socket is still connecting or\n * between reconnects. They must not fall back to JSON frames — that would\n * change which methods are reachable and lose return-by-reference — so\n * they wait here and run on the next open socket, or reject when the\n * connection ends for good. Their timeout starts when they are issued.\n */\nexport class NativeCallQueue {\n #pending: Array<{\n run: (socket: CapnWebSocket) => void;\n reject: (error: Error) => void;\n }> = [];\n\n enqueue<T>(\n method: string,\n args: unknown[],\n options: CallOptions | StreamOptions | undefined,\n defaultTimeout: number\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const { stream, timeout } = splitCallOptions(options);\n const effectiveTimeout =\n timeout !== undefined ? timeout : stream ? undefined : defaultTimeout;\n const startedAt = Date.now();\n const entry = {\n run: (socket: CapnWebSocket) => {\n // Spend the remaining budget, not a fresh one.\n const remaining =\n effectiveTimeout === undefined\n ? undefined\n : Math.max(1, effectiveTimeout - (Date.now() - startedAt));\n const opts =\n remaining === undefined ? options : { stream, timeout: remaining };\n nativeCall<T>(socket, method, args, opts, defaultTimeout).then(\n resolve,\n reject\n );\n },\n reject: (error: Error) => {\n stream?.onError?.(error.message);\n reject(error);\n }\n };\n this.#pending.push(entry);\n if (effectiveTimeout) {\n setTimeout(() => {\n const index = this.#pending.indexOf(entry);\n if (index === -1) return;\n this.#pending.splice(index, 1);\n entry.reject(\n new Error(\n `RPC call to ${method} timed out after ${effectiveTimeout}ms`\n )\n );\n }, effectiveTimeout);\n }\n });\n }\n\n /** Run everything queued on a socket that just opened. */\n flush(socket: CapnWebSocket): void {\n const pending = this.#pending;\n this.#pending = [];\n for (const entry of pending) entry.run(socket);\n }\n\n /** Reject everything queued; the connection will not come back. */\n rejectAll(reason: string): void {\n const pending = this.#pending;\n this.#pending = [];\n const error = new Error(reason);\n for (const entry of pending) entry.reject(error);\n }\n}\n\n/**\n * Options for the agentFetch function\n */\nexport type AgentClientFetchOptions = Omit<\n PartyFetchOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to (ignored if basePath is set) */\n agent: string;\n /** Name of the specific Agent instance (ignored if basePath is set) */\n name?: string;\n /**\n * Full URL path - bypasses agent/name URL construction.\n * When set, the request is made to this path directly.\n */\n basePath?: string;\n};\n\n// ---- Shared RPC Type Utilities ----\n\ntype AllOptional<T> = T extends [infer A, ...infer R]\n ? undefined extends A\n ? AllOptional<R>\n : false\n : true;\n\nexport type RPCMethods<T> = {\n [K in keyof T as T[K] extends RPCMethod<T[K]> ? K : never]: RPCMethod<T[K]>;\n};\n\ntype OptionalParametersMethod<T extends RPCMethod> =\n AllOptional<ClientParameters<T>> extends true ? T : never;\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- generic agent type constraint\nexport type AgentMethods<T> = Omit<RPCMethods<T>, keyof Agent<any, any>>;\n\nexport type OptionalAgentMethods<T> = {\n [K in keyof AgentMethods<T> as AgentMethods<T>[K] extends OptionalParametersMethod<\n AgentMethods<T>[K]\n >\n ? K\n : never]: OptionalParametersMethod<AgentMethods<T>[K]>;\n};\n\nexport type RequiredAgentMethods<T> = Omit<\n AgentMethods<T>,\n keyof OptionalAgentMethods<T>\n>;\n\nexport type AgentPromiseReturnType<T, K extends keyof AgentMethods<T>> =\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any -- generic promise return type\n ReturnType<AgentMethods<T>[K]> extends Promise<any>\n ? ReturnType<AgentMethods<T>[K]>\n : Promise<ReturnType<AgentMethods<T>[K]>>;\n\nexport type AgentStub<T> = {\n [K in keyof AgentMethods<T>]: (\n ...args: ClientParameters<AgentMethods<T>[K]>\n ) => AgentPromiseReturnType<AgentMethods<T>, K>;\n};\n\nexport type UntypedAgentStub = Record<string, Method>;\n\ntype AgentClientStub<AgentT> = keyof AgentMethods<AgentT> extends never\n ? UntypedAgentStub\n : AgentStub<AgentT>;\n\ntype OptionalArgsAgentClientCall<AgentT> = <\n K extends keyof OptionalAgentMethods<AgentT>\n>(\n method: K,\n args?: ClientParameters<OptionalAgentMethods<AgentT>[K]>,\n options?: CallOptions | StreamOptions\n) => AgentPromiseReturnType<AgentT, K>;\n\ntype RequiredArgsAgentClientCall<AgentT> = <\n K extends keyof RequiredAgentMethods<AgentT>\n>(\n method: K,\n args: ClientParameters<RequiredAgentMethods<AgentT>[K]>,\n options?: CallOptions | StreamOptions\n) => AgentPromiseReturnType<AgentT, K>;\n\ntype TypedAgentClientCall<AgentT> = OptionalArgsAgentClientCall<AgentT> &\n RequiredArgsAgentClientCall<AgentT>;\n\ntype UntypedAgentClientCall = {\n <T extends SerializableReturnValue>(\n method: string,\n args?: SerializableValue[],\n options?: CallOptions | StreamOptions\n ): Promise<T>;\n <T = unknown>(\n method: string,\n args?: unknown[],\n options?: CallOptions | StreamOptions\n ): Promise<T>;\n};\n\ntype AgentClientCall<AgentT> = keyof AgentMethods<AgentT> extends never\n ? UntypedAgentClientCall\n : TypedAgentClientCall<AgentT>;\n\n/**\n * Creates a proxy that wraps RPC method calls.\n * Internal JS methods (toJSON, then, etc.) return undefined to avoid\n * triggering RPC calls during serialization (e.g., console.log)\n */\nexport function createStubProxy<T = Record<string, Method>>(\n call: (method: string, args: unknown[]) => unknown\n): T {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any -- proxy needs any for dynamic method access\n return new Proxy<any>(\n {},\n {\n get: (_target, method) => {\n if (isInternalJsStubProp(method)) {\n return undefined;\n }\n return (...args: unknown[]) => call(method as string, args);\n }\n }\n );\n}\n\n/**\n * WebSocket client for connecting to an Agent\n */\nexport class AgentClient<\n AgentT = unknown,\n State = AgentT extends { get state(): infer S } ? S : AgentT\n> extends PartySocket {\n /**\n * @deprecated Use agentFetch instead\n */\n static fetch(_opts: PartyFetchOptions): Promise<Response> {\n throw new Error(\n \"AgentClient.fetch is not implemented, use agentFetch instead\"\n );\n }\n agent: string;\n name: string;\n call: AgentClientCall<AgentT>;\n stub: AgentClientStub<AgentT>;\n\n /**\n * The current agent state, updated on server broadcasts and client setState calls.\n * Starts as undefined until the first state message is received from the server.\n */\n state: State | undefined = undefined;\n\n /**\n * Whether the client has received identity from the server.\n * Becomes true after the first identity message is received.\n * Resets to false on connection close.\n */\n identified = false;\n\n /**\n * Terminal connection error, if the server closed the socket with a code\n * that should not be retried automatically.\n */\n connectionError: AgentConnectionError | null = null;\n\n /**\n * Promise that resolves when identity has been received from the server.\n * Useful for waiting before making calls that depend on knowing the instance.\n * Resets on connection close so it can be awaited again after reconnect.\n */\n get ready(): Promise<void> {\n return this._readyPromise;\n }\n\n private options: AgentClientOptions<State>;\n private _pendingCalls = new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n /**\n * Whether the request was actually transmitted to the server.\n * Requests issued while disconnected sit in PartySocket's internal\n * buffer (transmitted: false) and are flushed on the next open —\n * they survive a transient close instead of being rejected, since\n * the server never saw them and re-delivery can't double-execute.\n */\n transmitted: boolean;\n }\n >();\n private _readyPromise!: Promise<void>;\n private _resolveReady!: () => void;\n private _previousName: string | null = null;\n private _previousAgent: string | null = null;\n\n private _resetReady() {\n this._readyPromise = new Promise((resolve) => {\n this._resolveReady = resolve;\n });\n }\n\n /**\n * The live Cap'n Web socket on the `\"capnweb\"` transport. PartySocket\n * constructs a new one on every reconnect; the bound class reports each\n * into this holder, which exists before `super()` runs.\n */\n readonly #capnWeb: { current: CapnWebSocket | null };\n readonly #nativeQueue = new NativeCallQueue();\n\n constructor(options: AgentClientOptions<State>) {\n const capnWeb: { current: CapnWebSocket | null } = { current: null };\n const socketClass =\n options.transport === \"capnweb\"\n ? {\n WebSocket: boundCapnWebSocket((socket) => {\n capnWeb.current = socket;\n })\n }\n : {};\n const agentNamespace = camelCaseToKebabCase(options.agent);\n const shouldReconnectOnClose = options.shouldReconnectOnClose;\n const classifyReconnect = (event: CloseEvent) =>\n (shouldReconnectOnClose?.(event) ?? true) && !isTerminalCloseEvent(event);\n\n // If basePath is provided, use it directly; otherwise construct from agent/name\n const socketOptions = options.basePath\n ? {\n basePath: options.basePath,\n path: options.path,\n ...options,\n ...socketClass,\n shouldReconnectOnClose: classifyReconnect\n }\n : {\n party: agentNamespace,\n prefix: \"agents\",\n room: options.name || \"default\",\n path: options.path,\n ...options,\n ...socketClass,\n shouldReconnectOnClose: classifyReconnect\n };\n\n super(socketOptions);\n this.#capnWeb = capnWeb;\n this.agent = agentNamespace;\n this.name = options.name || \"default\";\n this.options = options;\n\n // Initialize ready promise\n this._resetReady();\n\n this.addEventListener(\"message\", (event) => {\n if (typeof event.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(event.data);\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (parsedMessage.type === MessageType.CF_AGENT_IDENTITY) {\n const oldName = this._previousName;\n const oldAgent = this._previousAgent;\n const newName = parsedMessage.name as string;\n const newAgent = parsedMessage.agent as string;\n\n // Resolve ready/identified\n this.identified = true;\n this._resolveReady();\n\n // Detect identity change on reconnect\n if (\n oldName !== null &&\n oldAgent !== null &&\n (oldName !== newName || oldAgent !== newAgent)\n ) {\n if (this.options.onIdentityChange) {\n this.options.onIdentityChange(\n oldName,\n newName,\n oldAgent,\n newAgent\n );\n } else {\n const agentChanged = oldAgent !== newAgent;\n const nameChanged = oldName !== newName;\n let changeDescription = \"\";\n if (agentChanged && nameChanged) {\n changeDescription = `agent \"${oldAgent}\" → \"${newAgent}\", instance \"${oldName}\" → \"${newName}\"`;\n } else if (agentChanged) {\n changeDescription = `agent \"${oldAgent}\" → \"${newAgent}\"`;\n } else {\n changeDescription = `instance \"${oldName}\" → \"${newName}\"`;\n }\n console.warn(\n `[agents] Identity changed on reconnect: ${changeDescription}. ` +\n \"This can happen with server-side routing (e.g., basePath with getAgentByName) \" +\n \"where the instance is determined by auth/session. \" +\n \"Provide onIdentityChange callback to handle this explicitly, \" +\n \"or ignore if this is expected for your routing pattern.\"\n );\n }\n }\n\n // Always update from server identity (server is authoritative)\n this._previousName = newName;\n this._previousAgent = newAgent;\n this.name = newName;\n this.agent = newAgent;\n\n // Call onIdentity callback\n this.options.onIdentity?.(newName, newAgent);\n return;\n }\n if (parsedMessage.type === MessageType.CF_AGENT_STATE) {\n this.state = parsedMessage.state as State;\n this.options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === MessageType.CF_AGENT_STATE_ERROR) {\n this.options.onStateUpdateError?.(parsedMessage.error as string);\n return;\n }\n if (parsedMessage.type === MessageType.RPC) {\n const response = parsedMessage as RPCResponse;\n const pending = this._pendingCalls.get(response.id);\n if (!pending) {\n console.warn(\n `[AgentClient] Discarded an RPC response with no matching pending call (id \"${response.id}\"). ` +\n \"The call likely timed out or was rejected when its connection closed before the response arrived.\"\n );\n return;\n }\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n this._pendingCalls.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n }\n }\n }\n });\n\n // PartySocket flushes its internal message buffer right before\n // dispatching \"open\" — anything queued has now been transmitted.\n this.addEventListener(\"open\", () => {\n this.connectionError = null;\n for (const pending of this._pendingCalls.values()) {\n pending.transmitted = true;\n }\n const native = this.#capnWeb.current;\n if (native) this.#nativeQueue.flush(native);\n });\n\n // Clean up pending calls and reset ready state when connection closes\n this.addEventListener(\"close\", (event) => {\n const terminalClose = isTerminalCloseEvent(event);\n // Reset ready state for next connection\n this.identified = false;\n this._resetReady();\n\n if (this.shouldReconnect) {\n // Transient disconnect: reject calls whose request was already\n // transmitted — their response can never arrive. Buffered calls\n // stay pending; PartySocket re-sends them on reconnect.\n this._rejectPendingCalls(\"Connection closed\", {\n onlyTransmitted: true\n });\n } else {\n // Permanent close (close() called or retries exhausted): nothing\n // will ever flush the buffer, so reject everything.\n this._rejectPendingCalls(\"Connection closed\");\n this.#nativeQueue.rejectAll(\"Connection closed\");\n if (terminalClose) {\n const error = new AgentConnectionError(event);\n this.connectionError = error;\n this.options.onConnectionError?.(error);\n }\n }\n });\n\n this.call = this._callImpl.bind(this) as AgentClientCall<AgentT>;\n this.stub = createStubProxy((method, args) =>\n this._callImpl(method, args)\n ) as AgentClientStub<AgentT>;\n }\n\n /**\n * Reject pending RPC calls with the given reason.\n * With `onlyTransmitted`, calls still sitting in the send buffer are\n * kept pending (they'll be flushed on reconnect).\n */\n private _rejectPendingCalls(\n reason: string,\n { onlyTransmitted = false }: { onlyTransmitted?: boolean } = {}\n ) {\n const error = new Error(reason);\n for (const [id, pending] of this._pendingCalls) {\n if (onlyTransmitted && !pending.transmitted) continue;\n this._pendingCalls.delete(id);\n pending.reject(error);\n pending.stream?.onError?.(reason);\n }\n }\n\n setState(state: State) {\n this.send(JSON.stringify({ state, type: MessageType.CF_AGENT_STATE }));\n this.state = state;\n this.options.onStateUpdate?.(state, \"client\");\n }\n\n /**\n * Close the connection and immediately reject all pending RPC calls.\n * This provides immediate feedback on intentional close rather than\n * waiting for the WebSocket close handshake to complete.\n *\n * Note: Any calls made after `close()` will be rejected when the\n * underlying WebSocket close event fires.\n */\n close(code?: number, reason?: string) {\n // Immediately reject all pending calls on intentional close\n this._rejectPendingCalls(\"Connection closed\");\n\n // Then close the underlying socket\n super.close(code, reason);\n }\n\n /**\n * Call a method on the Agent.\n * When AgentT is provided, method names are inferred from the agent's methods.\n * Falls back to untyped string-based calls when AgentT is not provided.\n */\n private async _callImpl(\n method: string,\n args: unknown[] = [],\n options?: CallOptions | StreamOptions\n ): Promise<unknown> {\n // On the Cap'n Web transport, callables are native methods on the\n // session root: invoke them directly so an RpcTarget result arrives as\n // a live stub. The JSON `rpc` frame below is the WebSocket wire's protocol.\n if (this.options.transport === \"capnweb\") {\n const timeout =\n this.options.defaultCallTimeout ?? DEFAULT_CALL_TIMEOUT_MS;\n const native = this.#capnWeb.current;\n if (native && this.readyState === this.OPEN) {\n return nativeCall(native, method, args, options, timeout);\n }\n if (this.connectionError && this.readyState === this.CLOSED) {\n throw new Error(\"Connection closed\");\n }\n // Connecting or between reconnects: hold the call as a native call\n // rather than queueing a JSON frame that would change its meaning.\n return this.#nativeQueue.enqueue(method, args, options, timeout);\n }\n if (this.connectionError && this.readyState === this.CLOSED) {\n throw new Error(\"Connection closed\");\n }\n\n return new Promise((resolve, reject) => {\n const id = crypto.randomUUID();\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const { stream: streamOptions, timeout } = splitCallOptions(options);\n\n // Apply the default timeout as a backstop for non-streaming calls\n // so a lost response rejects instead of hanging forever. An\n // explicit `timeout` (including 0 = disabled) always wins.\n const effectiveTimeout =\n timeout !== undefined\n ? timeout\n : streamOptions\n ? undefined\n : (this.options.defaultCallTimeout ?? DEFAULT_CALL_TIMEOUT_MS);\n\n if (effectiveTimeout) {\n timeoutId = setTimeout(() => {\n const pending = this._pendingCalls.get(id);\n this._pendingCalls.delete(id);\n const errorMessage = `RPC call to ${method} timed out after ${effectiveTimeout}ms`;\n pending?.stream?.onError?.(errorMessage);\n reject(new Error(errorMessage));\n }, effectiveTimeout);\n }\n\n this._pendingCalls.set(id, {\n reject: (e: Error) => {\n if (timeoutId) clearTimeout(timeoutId);\n reject(e);\n },\n resolve: (value: unknown) => {\n if (timeoutId) clearTimeout(timeoutId);\n resolve(value);\n },\n stream: streamOptions,\n // If the socket is open, send() below transmits synchronously;\n // otherwise the request is buffered until the next open event\n // (the \"open\" listener then marks it transmitted).\n transmitted: this.readyState === this.OPEN\n });\n\n const request: RPCRequest = {\n args,\n id,\n method,\n type: MessageType.RPC\n };\n\n this.send(JSON.stringify(request));\n });\n }\n}\n\n/**\n * Make an HTTP request to an Agent\n * @param opts Connection options\n * @param init Request initialization options\n * @returns Promise resolving to a Response\n */\nexport function agentFetch(opts: AgentClientFetchOptions, init?: RequestInit) {\n const agentNamespace = camelCaseToKebabCase(opts.agent);\n\n // If basePath is provided, use it directly; otherwise construct from agent/name\n // When basePath is set, room/party aren't used by PartySocket (basePath replaces the URL)\n if (opts.basePath) {\n return PartySocket.fetch(\n { basePath: opts.basePath, ...opts } as unknown as PartyFetchOptions,\n init\n );\n }\n\n return PartySocket.fetch(\n {\n party: agentNamespace,\n prefix: \"agents\",\n room: opts.name || \"default\",\n ...opts\n },\n init\n );\n}\n"],"mappings":";;;;;;;;AAUA,IAAM,QAAN,cAAoB,UAA2C;CAC7D,YAAY,QAAwC;EAClD,MAAM;EADqB,KAAA,SAAA;CAE7B;CAEA,QAAQ,OAA+B;EACrC,KAAK,OAAO,cAAc,IAAI,aAAa,WAAW,EAAE,MA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WAAW;GACtC,MAAM,KAAK,OAAO,WAAW;GAC7B,IAAI;GAEJ,MAAM,EAAE,QAAQ,eAAe,YAAY,iBAAiB,OAAO;GAKnE,MAAM,mBACJ,YAAY,KAAA,IACR,UACA,gBACE,KAAA,IACC,KAAK,QAAQ,sBAAA;GAEtB,IAAI,kBACF,YAAY,iBAAiB;IAC3B,MAAM,UAAU,KAAK,cAAc,IAAI,EAAE;IACzC,KAAK,cAAc,OAAO,EAAE;IAC5B,MAAM,eAAe,eAAe,OAAO,mBAAmB,iBAAiB;IAC/E,SAAS,QAAQ,UAAU,YAAY;IACvC,OAAO,IAAI,MAAM,YAAY,CAAC;GAChC,GAAG,gBAAgB;GAGrB,KAAK,cAAc,IAAI,IAAI;IACzB,SAAS,MAAa;KACpB,IAAI,WAAW,aAAa,SAAS;KACrC,OAAO,CAAC;IACV;IACA,UAAU,UAAmB;KAC3B,IAAI,WAAW,aAAa,SAAS;KACrC,QAAQ,KAAK;IACf;IACA,QAAQ;IAIR,aAAa,KAAK,eAAe,KAAK;GACxC,CAAC;GAED,MAAM,UAAsB;IAC1B;IACA;IACA;IACA,MAAA;GACF;GAEA,KAAK,KAAK,KAAK,UAAU,OAAO,CAAC;EACnC,CAAC;CACH;AACF;;;;;;;AAQA,SAAgB,WAAW,MAA+B,MAAoB;CAC5E,MAAM,iBAAiB,qBAAqB,KAAK,KAAK;CAItD,IAAI,KAAK,UACP,OAAO,YAAY,MACjB;EAAE,UAAU,KAAK;EAAU,GAAG;CAAK,GACnC,IACF;CAGF,OAAO,YAAY,MACjB;EACE,OAAO;EACP,QAAQ;EACR,MAAM,KAAK,QAAQ;EACnB,GAAG;CACL,GACA,IACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { getAgentByName } from "./agent-routing.js";
2
- import { t as LifecycleCapability } from "./capability-BjSKYpzg.js";
2
+ import { t as LifecycleCapability } from "./capability-B4WbF81e.js";
3
3
  import { tryN } from "./retries.js";
4
4
  import { n as callV2Tool } from "./invoker-CHMnoxIA.js";
5
5
  import { DurableObjectOAuthClientProvider } from "./mcp/client/do-oauth-client-provider.js";
@@ -2474,4 +2474,4 @@ function getNamespacedData(mcpClients, type) {
2474
2474
  //#endregion
2475
2475
  export { ensureMcpServerTable as a, RPCServerTransport as c, DisposableStore as d, normalizeServerId as i, RPC_DO_PREFIX as l, MCP_SERVER_ID_MAX_LENGTH as n, MCPConnectionState as o, getNamespacedData as r, RPCClientTransport as s, MCPClientManager as t, isDurableObjectNamespace as u };
2476
2476
 
2477
- //# sourceMappingURL=client-jagG8a9_.js.map
2477
+ //# sourceMappingURL=client-fyQrLGkD.js.map