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
package/dist/client.d.ts CHANGED
@@ -1,285 +1,26 @@
1
- import { c as Agent } from "./agent-routing-CnkaHb-v.js";
1
+ import { t as AgentTransport } from "./transport-protocol-ZTew5Wso.js";
2
2
  import {
3
- ClientParameters,
4
- Method,
5
- RPCMethod,
6
- SerializableReturnValue,
7
- SerializableValue
8
- } from "./serializable.js";
9
- import {
10
- PartyFetchOptions,
11
- PartySocket,
12
- PartySocketOptions
13
- } from "partysocket";
14
-
15
- //#region src/client.d.ts
16
- declare class AgentConnectionError extends Error {
17
- code: number;
18
- reason: string;
19
- wasClean: boolean;
20
- constructor(event: CloseEvent);
21
- }
22
- declare function isTerminalCloseEvent(event: CloseEvent): boolean;
23
- type TerminalReconnectOptions = {
24
- shouldReconnectOnClose?: (event: CloseEvent) => boolean;
25
- };
26
- /**
27
- * Options for creating an AgentClient
28
- */
29
- type AgentClientOptions<State = unknown> = Omit<
30
- PartySocketOptions,
31
- "party" | "room"
32
- > &
33
- TerminalReconnectOptions & {
34
- /** Name of the agent to connect to (ignored if basePath is set) */ agent: string /** Name of the specific Agent instance (ignored if basePath is set) */;
35
- name?: string;
36
- /**
37
- * Full URL path - bypasses agent/name URL construction.
38
- * When set, the client connects to this path directly.
39
- * Server must handle routing manually (e.g., with getAgentByName + fetch).
40
- * @example
41
- * // Client connects to /user, server routes based on session
42
- * useAgent({ agent: "UserAgent", basePath: "user" })
43
- */
44
- basePath?: string /** Called when the Agent's state is updated */;
45
- onStateUpdate?: (
46
- state: State,
47
- source: "server" | "client"
48
- ) => void /** Called when a state update fails (e.g., connection is readonly) */;
49
- onStateUpdateError?: (error: string) => void;
50
- /**
51
- * Called when the server sends the agent's identity on connect.
52
- * Useful when using basePath, as the actual instance name is determined server-side.
53
- * @param name The actual agent instance name
54
- * @param agent The agent class name (kebab-case)
55
- */
56
- onIdentity?: (name: string, agent: string) => void;
57
- /**
58
- * Called when identity changes on reconnect (different instance than before).
59
- * If not provided and identity changes, a warning will be logged.
60
- * @param oldName Previous instance name
61
- * @param newName New instance name
62
- * @param oldAgent Previous agent class name
63
- * @param newAgent New agent class name
64
- */
65
- onIdentityChange?: (
66
- oldName: string,
67
- newName: string,
68
- oldAgent: string,
69
- newAgent: string
70
- ) => void;
71
- /**
72
- * Additional path to append to the URL.
73
- * Works with both standard routing and basePath.
74
- * @example
75
- * // With basePath: /user/settings
76
- * { basePath: "user", path: "settings" }
77
- * // Standard: /agents/my-agent/room/settings
78
- * { agent: "MyAgent", name: "room", path: "settings" }
79
- */
80
- path?: string;
81
- /**
82
- * Default timeout (in milliseconds) applied to non-streaming `call()`s
83
- * that don't pass an explicit `timeout`. Defaults to 30 000 ms.
84
- * Set to `0` to disable. Streaming calls never get a default timeout.
85
- */
86
- defaultCallTimeout?: number /** Called when the connection closes with a terminal code and will not reconnect. */;
87
- onConnectionError?: (error: AgentConnectionError) => void;
88
- };
89
- /**
90
- * Default timeout (in milliseconds) applied to non-streaming RPC calls
91
- * that don't pass an explicit `timeout`. Acts as a backstop so calls
92
- * whose response is lost (e.g. the connection drops mid-flight) reject
93
- * instead of hanging forever. Override per client via
94
- * `defaultCallTimeout`, or per call via `timeout` (0 disables).
95
- */
96
- declare const DEFAULT_CALL_TIMEOUT_MS = 30000;
97
- /**
98
- * Options for streaming RPC calls
99
- */
100
- type StreamOptions = {
101
- /** Called when a chunk of data is received */ onChunk?: (
102
- chunk: unknown
103
- ) => void /** Called when the stream ends */;
104
- onDone?: (finalChunk: unknown) => void /** Called when an error occurs */;
105
- onError?: (error: string) => void;
106
- };
107
- /**
108
- * Options for RPC calls
109
- */
110
- type CallOptions = {
111
- /** Timeout in milliseconds. If the call doesn't complete within this time, it will be rejected. */ timeout?: number /** Streaming options for handling streaming responses */;
112
- stream?: StreamOptions;
113
- };
114
- /**
115
- * Options for the agentFetch function
116
- */
117
- type AgentClientFetchOptions = Omit<PartyFetchOptions, "party" | "room"> & {
118
- /** Name of the agent to connect to (ignored if basePath is set) */ agent: string /** Name of the specific Agent instance (ignored if basePath is set) */;
119
- name?: string;
120
- /**
121
- * Full URL path - bypasses agent/name URL construction.
122
- * When set, the request is made to this path directly.
123
- */
124
- basePath?: string;
125
- };
126
- type AllOptional<T> = T extends [infer A, ...infer R]
127
- ? undefined extends A
128
- ? AllOptional<R>
129
- : false
130
- : true;
131
- type RPCMethods<T> = {
132
- [K in keyof T as T[K] extends RPCMethod<T[K]> ? K : never]: RPCMethod<T[K]>;
133
- };
134
- type OptionalParametersMethod<T extends RPCMethod> =
135
- AllOptional<ClientParameters<T>> extends true ? T : never;
136
- type AgentMethods<T> = Omit<RPCMethods<T>, keyof Agent<any, any>>;
137
- type OptionalAgentMethods<T> = {
138
- [K in keyof AgentMethods<T> as AgentMethods<T>[K] extends OptionalParametersMethod<
139
- AgentMethods<T>[K]
140
- >
141
- ? K
142
- : never]: OptionalParametersMethod<AgentMethods<T>[K]>;
143
- };
144
- type RequiredAgentMethods<T> = Omit<
145
- AgentMethods<T>,
146
- keyof OptionalAgentMethods<T>
147
- >;
148
- type AgentPromiseReturnType<T, K extends keyof AgentMethods<T>> =
149
- ReturnType<AgentMethods<T>[K]> extends Promise<any>
150
- ? ReturnType<AgentMethods<T>[K]>
151
- : Promise<ReturnType<AgentMethods<T>[K]>>;
152
- type AgentStub<T> = {
153
- [K in keyof AgentMethods<T>]: (
154
- ...args: ClientParameters<AgentMethods<T>[K]>
155
- ) => AgentPromiseReturnType<AgentMethods<T>, K>;
156
- };
157
- type UntypedAgentStub = Record<string, Method>;
158
- type AgentClientStub<AgentT> = keyof AgentMethods<AgentT> extends never
159
- ? UntypedAgentStub
160
- : AgentStub<AgentT>;
161
- type OptionalArgsAgentClientCall<AgentT> = <
162
- K extends keyof OptionalAgentMethods<AgentT>
163
- >(
164
- method: K,
165
- args?: ClientParameters<OptionalAgentMethods<AgentT>[K]>,
166
- options?: CallOptions | StreamOptions
167
- ) => AgentPromiseReturnType<AgentT, K>;
168
- type RequiredArgsAgentClientCall<AgentT> = <
169
- K extends keyof RequiredAgentMethods<AgentT>
170
- >(
171
- method: K,
172
- args: ClientParameters<RequiredAgentMethods<AgentT>[K]>,
173
- options?: CallOptions | StreamOptions
174
- ) => AgentPromiseReturnType<AgentT, K>;
175
- type TypedAgentClientCall<AgentT> = OptionalArgsAgentClientCall<AgentT> &
176
- RequiredArgsAgentClientCall<AgentT>;
177
- type UntypedAgentClientCall = {
178
- <T extends SerializableReturnValue>(
179
- method: string,
180
- args?: SerializableValue[],
181
- options?: CallOptions | StreamOptions
182
- ): Promise<T>;
183
- <T = unknown>(
184
- method: string,
185
- args?: unknown[],
186
- options?: CallOptions | StreamOptions
187
- ): Promise<T>;
188
- };
189
- type AgentClientCall<AgentT> = keyof AgentMethods<AgentT> extends never
190
- ? UntypedAgentClientCall
191
- : TypedAgentClientCall<AgentT>;
192
- /**
193
- * Creates a proxy that wraps RPC method calls.
194
- * Internal JS methods (toJSON, then, etc.) return undefined to avoid
195
- * triggering RPC calls during serialization (e.g., console.log)
196
- */
197
- declare function createStubProxy<T = Record<string, Method>>(
198
- call: (method: string, args: unknown[]) => unknown
199
- ): T;
200
- /**
201
- * WebSocket client for connecting to an Agent
202
- */
203
- declare class AgentClient<
204
- AgentT = unknown,
205
- State = AgentT extends {
206
- get state(): infer S;
207
- }
208
- ? S
209
- : AgentT
210
- > extends PartySocket {
211
- /**
212
- * @deprecated Use agentFetch instead
213
- */
214
- static fetch(_opts: PartyFetchOptions): Promise<Response>;
215
- agent: string;
216
- name: string;
217
- call: AgentClientCall<AgentT>;
218
- stub: AgentClientStub<AgentT>;
219
- /**
220
- * The current agent state, updated on server broadcasts and client setState calls.
221
- * Starts as undefined until the first state message is received from the server.
222
- */
223
- state: State | undefined;
224
- /**
225
- * Whether the client has received identity from the server.
226
- * Becomes true after the first identity message is received.
227
- * Resets to false on connection close.
228
- */
229
- identified: boolean;
230
- /**
231
- * Terminal connection error, if the server closed the socket with a code
232
- * that should not be retried automatically.
233
- */
234
- connectionError: AgentConnectionError | null;
235
- /**
236
- * Promise that resolves when identity has been received from the server.
237
- * Useful for waiting before making calls that depend on knowing the instance.
238
- * Resets on connection close so it can be awaited again after reconnect.
239
- */
240
- get ready(): Promise<void>;
241
- private options;
242
- private _pendingCalls;
243
- private _readyPromise;
244
- private _resolveReady;
245
- private _previousName;
246
- private _previousAgent;
247
- private _resetReady;
248
- constructor(options: AgentClientOptions<State>);
249
- /**
250
- * Reject pending RPC calls with the given reason.
251
- * With `onlyTransmitted`, calls still sitting in the send buffer are
252
- * kept pending (they'll be flushed on reconnect).
253
- */
254
- private _rejectPendingCalls;
255
- setState(state: State): void;
256
- /**
257
- * Close the connection and immediately reject all pending RPC calls.
258
- * This provides immediate feedback on intentional close rather than
259
- * waiting for the WebSocket close handshake to complete.
260
- *
261
- * Note: Any calls made after `close()` will be rejected when the
262
- * underlying WebSocket close event fires.
263
- */
264
- close(code?: number, reason?: string): void;
265
- /**
266
- * Call a method on the Agent.
267
- * When AgentT is provided, method names are inferred from the agent's methods.
268
- * Falls back to untyped string-based calls when AgentT is not provided.
269
- */
270
- private _callImpl;
271
- }
272
- /**
273
- * Make an HTTP request to an Agent
274
- * @param opts Connection options
275
- * @param init Request initialization options
276
- * @returns Promise resolving to a Response
277
- */
278
- declare function agentFetch(
279
- opts: AgentClientFetchOptions,
280
- init?: RequestInit
281
- ): Promise<Response>;
282
- //#endregion
3
+ _ as createStubProxy,
4
+ a as AgentMethods,
5
+ b as splitCallOptions,
6
+ c as CallOptions,
7
+ d as OptionalAgentMethods,
8
+ f as RPCMethods,
9
+ g as agentFetch,
10
+ h as UntypedAgentStub,
11
+ i as AgentConnectionError,
12
+ l as DEFAULT_CALL_TIMEOUT_MS,
13
+ m as StreamOptions,
14
+ n as AgentClientFetchOptions,
15
+ o as AgentPromiseReturnType,
16
+ p as RequiredAgentMethods,
17
+ r as AgentClientOptions,
18
+ s as AgentStub,
19
+ t as AgentClient,
20
+ u as NativeCallQueue,
21
+ v as isTerminalCloseEvent,
22
+ y as nativeCall
23
+ } from "./client-BxdkCuVy.js";
283
24
  export {
284
25
  AgentClient,
285
26
  AgentClientFetchOptions,
@@ -288,8 +29,10 @@ export {
288
29
  AgentMethods,
289
30
  AgentPromiseReturnType,
290
31
  AgentStub,
32
+ type AgentTransport,
291
33
  CallOptions,
292
34
  DEFAULT_CALL_TIMEOUT_MS,
35
+ NativeCallQueue,
293
36
  OptionalAgentMethods,
294
37
  RPCMethods,
295
38
  RequiredAgentMethods,
@@ -297,6 +40,7 @@ export {
297
40
  UntypedAgentStub,
298
41
  agentFetch,
299
42
  createStubProxy,
300
- isTerminalCloseEvent
43
+ isTerminalCloseEvent,
44
+ nativeCall,
45
+ splitCallOptions
301
46
  };
302
- //# sourceMappingURL=client.d.ts.map
package/dist/client.js CHANGED
@@ -1,274 +1,2 @@
1
- import { camelCaseToKebabCase, isInternalJsStubProp } from "./utils.js";
2
- import "./types.js";
3
- import { PartySocket } from "partysocket";
4
- //#region src/client.ts
5
- var AgentConnectionError = class extends Error {
6
- constructor(event) {
7
- const reason = event.reason || `WebSocket closed with code ${event.code}`;
8
- super(`Agent connection closed: ${reason}`);
9
- this.name = "AgentConnectionError";
10
- this.code = event.code;
11
- this.reason = event.reason;
12
- this.wasClean = event.wasClean;
13
- }
14
- };
15
- function isTerminalCloseEvent(event) {
16
- return event.code === 1008 || event.code >= 4e3 && event.code <= 4999;
17
- }
18
- /**
19
- * Default timeout (in milliseconds) applied to non-streaming RPC calls
20
- * that don't pass an explicit `timeout`. Acts as a backstop so calls
21
- * whose response is lost (e.g. the connection drops mid-flight) reject
22
- * instead of hanging forever. Override per client via
23
- * `defaultCallTimeout`, or per call via `timeout` (0 disables).
24
- */
25
- const DEFAULT_CALL_TIMEOUT_MS = 3e4;
26
- /**
27
- * Creates a proxy that wraps RPC method calls.
28
- * Internal JS methods (toJSON, then, etc.) return undefined to avoid
29
- * triggering RPC calls during serialization (e.g., console.log)
30
- */
31
- function createStubProxy(call) {
32
- return new Proxy({}, { get: (_target, method) => {
33
- if (isInternalJsStubProp(method)) return;
34
- return (...args) => call(method, args);
35
- } });
36
- }
37
- /**
38
- * WebSocket client for connecting to an Agent
39
- */
40
- var AgentClient = class extends PartySocket {
41
- /**
42
- * @deprecated Use agentFetch instead
43
- */
44
- static fetch(_opts) {
45
- throw new Error("AgentClient.fetch is not implemented, use agentFetch instead");
46
- }
47
- /**
48
- * Promise that resolves when identity has been received from the server.
49
- * Useful for waiting before making calls that depend on knowing the instance.
50
- * Resets on connection close so it can be awaited again after reconnect.
51
- */
52
- get ready() {
53
- return this._readyPromise;
54
- }
55
- _resetReady() {
56
- this._readyPromise = new Promise((resolve) => {
57
- this._resolveReady = resolve;
58
- });
59
- }
60
- constructor(options) {
61
- const agentNamespace = camelCaseToKebabCase(options.agent);
62
- const shouldReconnectOnClose = options.shouldReconnectOnClose;
63
- const classifyReconnect = (event) => (shouldReconnectOnClose?.(event) ?? true) && !isTerminalCloseEvent(event);
64
- const socketOptions = options.basePath ? {
65
- basePath: options.basePath,
66
- path: options.path,
67
- ...options,
68
- shouldReconnectOnClose: classifyReconnect
69
- } : {
70
- party: agentNamespace,
71
- prefix: "agents",
72
- room: options.name || "default",
73
- path: options.path,
74
- ...options,
75
- shouldReconnectOnClose: classifyReconnect
76
- };
77
- super(socketOptions);
78
- this.state = void 0;
79
- this.identified = false;
80
- this.connectionError = null;
81
- this._pendingCalls = /* @__PURE__ */ new Map();
82
- this._previousName = null;
83
- this._previousAgent = null;
84
- this.agent = agentNamespace;
85
- this.name = options.name || "default";
86
- this.options = options;
87
- this._resetReady();
88
- this.addEventListener("message", (event) => {
89
- if (typeof event.data === "string") {
90
- let parsedMessage;
91
- try {
92
- parsedMessage = JSON.parse(event.data);
93
- } catch (_error) {
94
- return;
95
- }
96
- if (parsedMessage.type === "cf_agent_identity") {
97
- const oldName = this._previousName;
98
- const oldAgent = this._previousAgent;
99
- const newName = parsedMessage.name;
100
- const newAgent = parsedMessage.agent;
101
- this.identified = true;
102
- this._resolveReady();
103
- if (oldName !== null && oldAgent !== null && (oldName !== newName || oldAgent !== newAgent)) if (this.options.onIdentityChange) this.options.onIdentityChange(oldName, newName, oldAgent, newAgent);
104
- else {
105
- const agentChanged = oldAgent !== newAgent;
106
- const nameChanged = oldName !== newName;
107
- let changeDescription = "";
108
- if (agentChanged && nameChanged) changeDescription = `agent "${oldAgent}" → "${newAgent}", instance "${oldName}" → "${newName}"`;
109
- else if (agentChanged) changeDescription = `agent "${oldAgent}" → "${newAgent}"`;
110
- else changeDescription = `instance "${oldName}" → "${newName}"`;
111
- 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.`);
112
- }
113
- this._previousName = newName;
114
- this._previousAgent = newAgent;
115
- this.name = newName;
116
- this.agent = newAgent;
117
- this.options.onIdentity?.(newName, newAgent);
118
- return;
119
- }
120
- if (parsedMessage.type === "cf_agent_state") {
121
- this.state = parsedMessage.state;
122
- this.options.onStateUpdate?.(parsedMessage.state, "server");
123
- return;
124
- }
125
- if (parsedMessage.type === "cf_agent_state_error") {
126
- this.options.onStateUpdateError?.(parsedMessage.error);
127
- return;
128
- }
129
- if (parsedMessage.type === "rpc") {
130
- const response = parsedMessage;
131
- const pending = this._pendingCalls.get(response.id);
132
- if (!pending) {
133
- 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.`);
134
- return;
135
- }
136
- if (!response.success) {
137
- pending.reject(new Error(response.error));
138
- this._pendingCalls.delete(response.id);
139
- pending.stream?.onError?.(response.error);
140
- return;
141
- }
142
- if ("done" in response) if (response.done) {
143
- pending.resolve(response.result);
144
- this._pendingCalls.delete(response.id);
145
- pending.stream?.onDone?.(response.result);
146
- } else pending.stream?.onChunk?.(response.result);
147
- else {
148
- pending.resolve(response.result);
149
- this._pendingCalls.delete(response.id);
150
- }
151
- }
152
- }
153
- });
154
- this.addEventListener("open", () => {
155
- this.connectionError = null;
156
- for (const pending of this._pendingCalls.values()) pending.transmitted = true;
157
- });
158
- this.addEventListener("close", (event) => {
159
- const terminalClose = isTerminalCloseEvent(event);
160
- this.identified = false;
161
- this._resetReady();
162
- if (this.shouldReconnect) this._rejectPendingCalls("Connection closed", { onlyTransmitted: true });
163
- else {
164
- this._rejectPendingCalls("Connection closed");
165
- if (terminalClose) {
166
- const error = new AgentConnectionError(event);
167
- this.connectionError = error;
168
- this.options.onConnectionError?.(error);
169
- }
170
- }
171
- });
172
- this.call = this._callImpl.bind(this);
173
- this.stub = createStubProxy((method, args) => this._callImpl(method, args));
174
- }
175
- /**
176
- * Reject pending RPC calls with the given reason.
177
- * With `onlyTransmitted`, calls still sitting in the send buffer are
178
- * kept pending (they'll be flushed on reconnect).
179
- */
180
- _rejectPendingCalls(reason, { onlyTransmitted = false } = {}) {
181
- const error = new Error(reason);
182
- for (const [id, pending] of this._pendingCalls) {
183
- if (onlyTransmitted && !pending.transmitted) continue;
184
- this._pendingCalls.delete(id);
185
- pending.reject(error);
186
- pending.stream?.onError?.(reason);
187
- }
188
- }
189
- setState(state) {
190
- this.send(JSON.stringify({
191
- state,
192
- type: "cf_agent_state"
193
- }));
194
- this.state = state;
195
- this.options.onStateUpdate?.(state, "client");
196
- }
197
- /**
198
- * Close the connection and immediately reject all pending RPC calls.
199
- * This provides immediate feedback on intentional close rather than
200
- * waiting for the WebSocket close handshake to complete.
201
- *
202
- * Note: Any calls made after `close()` will be rejected when the
203
- * underlying WebSocket close event fires.
204
- */
205
- close(code, reason) {
206
- this._rejectPendingCalls("Connection closed");
207
- super.close(code, reason);
208
- }
209
- /**
210
- * Call a method on the Agent.
211
- * When AgentT is provided, method names are inferred from the agent's methods.
212
- * Falls back to untyped string-based calls when AgentT is not provided.
213
- */
214
- async _callImpl(method, args = [], options) {
215
- if (this.connectionError && this.readyState === this.CLOSED) throw new Error("Connection closed");
216
- return new Promise((resolve, reject) => {
217
- const id = crypto.randomUUID();
218
- let timeoutId;
219
- const isLegacyFormat = options && ("onChunk" in options || "onDone" in options || "onError" in options);
220
- const streamOptions = isLegacyFormat ? options : options?.stream;
221
- const timeout = isLegacyFormat ? void 0 : options?.timeout;
222
- const effectiveTimeout = timeout !== void 0 ? timeout : streamOptions ? void 0 : this.options.defaultCallTimeout ?? 3e4;
223
- if (effectiveTimeout) timeoutId = setTimeout(() => {
224
- const pending = this._pendingCalls.get(id);
225
- this._pendingCalls.delete(id);
226
- const errorMessage = `RPC call to ${method} timed out after ${effectiveTimeout}ms`;
227
- pending?.stream?.onError?.(errorMessage);
228
- reject(new Error(errorMessage));
229
- }, effectiveTimeout);
230
- this._pendingCalls.set(id, {
231
- reject: (e) => {
232
- if (timeoutId) clearTimeout(timeoutId);
233
- reject(e);
234
- },
235
- resolve: (value) => {
236
- if (timeoutId) clearTimeout(timeoutId);
237
- resolve(value);
238
- },
239
- stream: streamOptions,
240
- transmitted: this.readyState === this.OPEN
241
- });
242
- const request = {
243
- args,
244
- id,
245
- method,
246
- type: "rpc"
247
- };
248
- this.send(JSON.stringify(request));
249
- });
250
- }
251
- };
252
- /**
253
- * Make an HTTP request to an Agent
254
- * @param opts Connection options
255
- * @param init Request initialization options
256
- * @returns Promise resolving to a Response
257
- */
258
- function agentFetch(opts, init) {
259
- const agentNamespace = camelCaseToKebabCase(opts.agent);
260
- if (opts.basePath) return PartySocket.fetch({
261
- basePath: opts.basePath,
262
- ...opts
263
- }, init);
264
- return PartySocket.fetch({
265
- party: agentNamespace,
266
- prefix: "agents",
267
- room: opts.name || "default",
268
- ...opts
269
- }, init);
270
- }
271
- //#endregion
272
- export { AgentClient, AgentConnectionError, DEFAULT_CALL_TIMEOUT_MS, agentFetch, createStubProxy, isTerminalCloseEvent };
273
-
274
- //# sourceMappingURL=client.js.map
1
+ import { a as agentFetch, c as nativeCall, i as NativeCallQueue, l as splitCallOptions, n as AgentConnectionError, o as createStubProxy, r as DEFAULT_CALL_TIMEOUT_MS, s as isTerminalCloseEvent, t as AgentClient } from "./client-C9DAjZIY.js";
2
+ export { AgentClient, AgentConnectionError, DEFAULT_CALL_TIMEOUT_MS, NativeCallQueue, agentFetch, createStubProxy, isTerminalCloseEvent, nativeCall, splitCallOptions };