agents 0.21.0 → 0.23.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 (258) hide show
  1. package/README.md +21 -1
  2. package/dist/{agent-tool-types-CzGGB-20.d.ts → agent-routing-DE5zmCQ8.d.ts} +1844 -1336
  3. package/dist/agent-routing.d.ts +14 -0
  4. package/dist/agent-routing.js +187 -0
  5. package/dist/agent-routing.js.map +1 -0
  6. package/dist/agent-tool-types.d.ts +26 -26
  7. package/dist/{agent-tools-zR2d5uij.d.ts → agent-tools-DtXMTDGM.d.ts} +7 -7
  8. package/dist/agent-tools.d.ts +21 -21
  9. package/dist/agent-tools.js +2 -1
  10. package/dist/agent-tools.js.map +1 -1
  11. package/dist/browser/ai.js +6 -2
  12. package/dist/browser/ai.js.map +1 -1
  13. package/dist/browser/tanstack-ai.js.map +1 -1
  14. package/dist/callable-decorator-DP__HhBA.d.ts +72 -0
  15. package/dist/callable-decorator.d.ts +18 -0
  16. package/dist/callable-decorator.js +71 -0
  17. package/dist/callable-decorator.js.map +1 -0
  18. package/dist/capability-BjSKYpzg.js +42 -0
  19. package/dist/capability-BjSKYpzg.js.map +1 -0
  20. package/dist/capability-runner-Be_-PLR1.d.ts +459 -0
  21. package/dist/channel-Bnm4S7T2.d.ts +491 -0
  22. package/dist/channels/ai-sdk.d.ts +46 -0
  23. package/dist/channels/ai-sdk.js +120 -0
  24. package/dist/channels/ai-sdk.js.map +1 -0
  25. package/dist/channels/email.d.ts +95 -0
  26. package/dist/channels/email.js +323 -0
  27. package/dist/channels/email.js.map +1 -0
  28. package/dist/channels/index.d.ts +233 -0
  29. package/dist/channels/index.js +608 -0
  30. package/dist/channels/index.js.map +1 -0
  31. package/dist/channels/slack.d.ts +140 -0
  32. package/dist/channels/slack.js +614 -0
  33. package/dist/channels/slack.js.map +1 -0
  34. package/dist/channels/tanstack-ai.d.ts +39 -0
  35. package/dist/channels/tanstack-ai.js +17 -0
  36. package/dist/channels/tanstack-ai.js.map +1 -0
  37. package/dist/channels/telegram.d.ts +106 -0
  38. package/dist/channels/telegram.js +427 -0
  39. package/dist/channels/telegram.js.map +1 -0
  40. package/dist/channels/voice.d.ts +45 -0
  41. package/dist/channels/voice.js +122 -0
  42. package/dist/channels/voice.js.map +1 -0
  43. package/dist/chat/index.d.ts +2328 -2015
  44. package/dist/chat/index.js +891 -521
  45. package/dist/chat/index.js.map +1 -1
  46. package/dist/chat/react.d.ts +14 -1
  47. package/dist/chat/react.js +82 -52
  48. package/dist/chat/react.js.map +1 -1
  49. package/dist/chat/transport.js +1 -1
  50. package/dist/chat-sdk/index.d.ts +7 -7
  51. package/dist/chat-sdk/index.js +1 -1
  52. package/dist/{client-zqKcsyFa.js → client-jagG8a9_.js} +129 -37
  53. package/dist/client-jagG8a9_.js.map +1 -0
  54. package/dist/client.d.ts +1 -1
  55. package/dist/client.js +1 -1
  56. package/dist/{cloudflare-BduZwmYK.js → cloudflare-Dzvc7V2N.js} +10 -3
  57. package/dist/{cloudflare-BduZwmYK.js.map → cloudflare-Dzvc7V2N.js.map} +1 -1
  58. package/dist/context/index.d.ts +216 -0
  59. package/dist/context/index.js +454 -0
  60. package/dist/context/index.js.map +1 -0
  61. package/dist/current-agent-Da_C9a3b.d.ts +266 -0
  62. package/dist/current-agent-DhoDkSnH.js +51 -0
  63. package/dist/current-agent-DhoDkSnH.js.map +1 -0
  64. package/dist/diagnostics-BzvaX2UT.js +45 -0
  65. package/dist/diagnostics-BzvaX2UT.js.map +1 -0
  66. package/dist/diagnostics-C4jcz3VK.js +360 -0
  67. package/dist/diagnostics-C4jcz3VK.js.map +1 -0
  68. package/dist/{do-oauth-client-provider-VTZj2VtM.d.ts → do-oauth-client-provider-Tmf1vgKz.d.ts} +2 -2
  69. package/dist/{email-CL27preh.d.ts → email-7TatiTnl.d.ts} +38 -9
  70. package/dist/email-send.d.ts +15 -0
  71. package/dist/email-send.js +32 -0
  72. package/dist/email-send.js.map +1 -0
  73. package/dist/email.d.ts +14 -10
  74. package/dist/email.js.map +1 -1
  75. package/dist/{handler-stateless-C_bo-Ytq.d.ts → handler-stateless-DxYpJ_XF.d.ts} +3 -3
  76. package/dist/{handler-stateless-CIkKPETH.js → handler-stateless-VvrWSAVA.js} +5 -5
  77. package/dist/handler-stateless-VvrWSAVA.js.map +1 -0
  78. package/dist/index-BB0kqhIz.d.ts +101 -0
  79. package/dist/index-XDkuQ7zm.d.ts +89 -0
  80. package/dist/{index-BRnybD6X.d.ts → index-YSKgfgg9.d.ts} +21 -31
  81. package/dist/index.d.ts +113 -101
  82. package/dist/index.js +11 -7234
  83. package/dist/ingress-BfetZbMO.js +83 -0
  84. package/dist/ingress-BfetZbMO.js.map +1 -0
  85. package/dist/internal-CYlgHl1l.js +59 -0
  86. package/dist/internal-CYlgHl1l.js.map +1 -0
  87. package/dist/internal_context-BlxFEWfn.d.ts +19 -0
  88. package/dist/internal_context.d.ts +10 -4
  89. package/dist/internal_context.js +1 -10
  90. package/dist/{client-invoker-BNSZxAkv.d.ts → invoker-CG0_p_Wq.d.ts} +2 -2
  91. package/dist/{client-invoker-VNZ7X0nn.js → invoker-CHMnoxIA.js} +2 -2
  92. package/dist/invoker-CHMnoxIA.js.map +1 -0
  93. package/dist/lifecycle/index.d.ts +66 -0
  94. package/dist/lifecycle/index.js +4 -0
  95. package/dist/lifecycle-CMRGjZdw.js +1299 -0
  96. package/dist/lifecycle-CMRGjZdw.js.map +1 -0
  97. package/dist/mcp/{do-oauth-client-provider.d.ts → client/do-oauth-client-provider.d.ts} +1 -1
  98. package/dist/mcp/{do-oauth-client-provider.js → client/do-oauth-client-provider.js} +1 -1
  99. package/dist/mcp/client/do-oauth-client-provider.js.map +1 -0
  100. package/dist/mcp/client/index.d.ts +42 -0
  101. package/dist/mcp/{client.js → client/index.js} +1 -1
  102. package/dist/mcp/{x402.d.ts → client/x402.d.ts} +2 -2
  103. package/dist/mcp/{x402.js → client/x402.js} +2 -2
  104. package/dist/mcp/client/x402.js.map +1 -0
  105. package/dist/mcp/index.d.ts +36 -36
  106. package/dist/mcp/index.js +14 -16
  107. package/dist/mcp/index.js.map +1 -1
  108. package/dist/mcp/{server.d.ts → server/index.d.ts} +1 -1
  109. package/dist/mcp/{server.js → server/index.js} +1 -1
  110. package/dist/observability/ai/index.js +50 -35
  111. package/dist/observability/ai/index.js.map +1 -1
  112. package/dist/observability/index.d.ts +4 -4
  113. package/dist/observability/index.js +3 -50
  114. package/dist/observability/index.js.map +1 -1
  115. package/dist/{protocol-Dqc2MQxo.js → protocol-B0nh6KNf.js} +19 -21
  116. package/dist/protocol-B0nh6KNf.js.map +1 -0
  117. package/dist/react.d.ts +4 -4
  118. package/dist/react.js +1 -1
  119. package/dist/{retries-CAvxtG9d.d.ts → retries-D9Ds-1lz.d.ts} +17 -6
  120. package/dist/retries.d.ts +8 -6
  121. package/dist/retries.js +13 -1
  122. package/dist/retries.js.map +1 -1
  123. package/dist/routing/index.d.ts +137 -0
  124. package/dist/routing/index.js +244 -0
  125. package/dist/routing/index.js.map +1 -0
  126. package/dist/sanitize-D9TujEK8.js +79 -0
  127. package/dist/sanitize-D9TujEK8.js.map +1 -0
  128. package/dist/schedule.d.ts +25 -94
  129. package/dist/schedule.js +1 -98
  130. package/dist/schedule.js.map +1 -1
  131. package/dist/scheduler-DD9NdYbF.js +665 -0
  132. package/dist/scheduler-DD9NdYbF.js.map +1 -0
  133. package/dist/scheduler-Dwh85ZGl.d.ts +223 -0
  134. package/dist/schedules/index.d.ts +22 -0
  135. package/dist/schedules/index.js +2 -0
  136. package/dist/schedules/parser.d.ts +79 -0
  137. package/dist/schedules/parser.js +103 -0
  138. package/dist/schedules/parser.js.map +1 -0
  139. package/dist/sentence-chunker-BAidJ4DA.d.ts +68 -0
  140. package/dist/serializable.d.ts +1 -1
  141. package/dist/sessions/index.d.ts +441 -0
  142. package/dist/sessions/index.js +2063 -0
  143. package/dist/sessions/index.js.map +1 -0
  144. package/dist/skills/index.d.ts +99 -0
  145. package/dist/skills/index.js +254 -5
  146. package/dist/skills/index.js.map +1 -1
  147. package/dist/sql-error-CPY-GXyI.d.ts +12 -0
  148. package/dist/sql-error.d.ts +2 -0
  149. package/dist/sql-error.js +16 -0
  150. package/dist/sql-error.js.map +1 -0
  151. package/dist/src-DlSHshb2.js +6963 -0
  152. package/dist/src-DlSHshb2.js.map +1 -0
  153. package/dist/streams/index.d.ts +120 -0
  154. package/dist/streams/index.js +107 -0
  155. package/dist/streams/index.js.map +1 -0
  156. package/dist/streams-D6tJ0NN9.d.ts +370 -0
  157. package/dist/streams-DZKgAj9b.js +709 -0
  158. package/dist/streams-DZKgAj9b.js.map +1 -0
  159. package/dist/sub-routing.d.ts +12 -12
  160. package/dist/surface-bZZJqBka.js +17 -0
  161. package/dist/surface-bZZJqBka.js.map +1 -0
  162. package/dist/tasks/index.d.ts +64 -0
  163. package/dist/tasks/index.js +2 -0
  164. package/dist/tasks-BRJ5zgya.d.ts +517 -0
  165. package/dist/tasks-ylZgBjhj.js +1656 -0
  166. package/dist/tasks-ylZgBjhj.js.map +1 -0
  167. package/dist/text-segment-joiner-BtAFQSA_.js +57 -0
  168. package/dist/text-segment-joiner-BtAFQSA_.js.map +1 -0
  169. package/dist/text-stream-CpdiKrJB.js +272 -0
  170. package/dist/text-stream-CpdiKrJB.js.map +1 -0
  171. package/dist/tokens-nHAKcN6M.js +52 -0
  172. package/dist/tokens-nHAKcN6M.js.map +1 -0
  173. package/dist/tool-schema-CBjGPrsQ.js +31 -0
  174. package/dist/tool-schema-CBjGPrsQ.js.map +1 -0
  175. package/dist/types-B7LojTe4.d.ts +202 -0
  176. package/dist/types-_Faxb570.d.ts +439 -0
  177. package/dist/voice/client.d.ts +226 -0
  178. package/dist/voice/client.js +932 -0
  179. package/dist/voice/client.js.map +1 -0
  180. package/dist/voice/errors.d.ts +43 -0
  181. package/dist/voice/errors.js +41 -0
  182. package/dist/voice/errors.js.map +1 -0
  183. package/dist/voice/index.d.ts +271 -0
  184. package/dist/voice/index.js +1812 -0
  185. package/dist/voice/index.js.map +1 -0
  186. package/dist/voice/react.d.ts +167 -0
  187. package/dist/voice/react.js +234 -0
  188. package/dist/voice/react.js.map +1 -0
  189. package/dist/voice/sfu.d.ts +71 -0
  190. package/dist/voice/sfu.js +157 -0
  191. package/dist/voice/sfu.js.map +1 -0
  192. package/dist/voice/text.d.ts +6 -0
  193. package/dist/voice/text.js +2 -0
  194. package/dist/voice/types.d.ts +58 -0
  195. package/dist/voice/types.js +18 -0
  196. package/dist/voice/types.js.map +1 -0
  197. package/dist/voice/workers-ai.d.ts +136 -0
  198. package/dist/voice/workers-ai.js +568 -0
  199. package/dist/voice/workers-ai.js.map +1 -0
  200. package/dist/websockets/index.d.ts +192 -0
  201. package/dist/websockets/index.js +2 -0
  202. package/dist/websockets-DUfRHPRq.js +502 -0
  203. package/dist/websockets-DUfRHPRq.js.map +1 -0
  204. package/dist/workflow-types.d.ts +25 -25
  205. package/dist/workflows.d.ts +22 -22
  206. package/dist/workflows.js +2 -1
  207. package/dist/workflows.js.map +1 -1
  208. package/dist/{ws-chat-transport-CIoOBbO7.js → ws-chat-transport-rWwta645.js} +152 -15
  209. package/dist/ws-chat-transport-rWwta645.js.map +1 -0
  210. package/docs/agent-class.md +29 -87
  211. package/docs/agent-tools.md +2 -1
  212. package/docs/channels.md +323 -0
  213. package/docs/chat-agents.md +19 -25
  214. package/docs/context.md +131 -0
  215. package/docs/durable-execution.md +1 -1
  216. package/docs/http-websockets.md +1 -11
  217. package/docs/human-in-the-loop.md +1 -1
  218. package/docs/index.md +16 -12
  219. package/docs/lifecycle.md +370 -0
  220. package/docs/long-running-agents.md +4 -6
  221. package/docs/mcp-client.md +55 -0
  222. package/docs/mcp-servers.md +5 -1
  223. package/docs/observability.md +11 -11
  224. package/docs/resumable-streaming.md +2 -2
  225. package/docs/routing.md +105 -0
  226. package/docs/scheduling.md +175 -15
  227. package/docs/server-driven-messages.md +1 -1
  228. package/docs/sessions.md +237 -871
  229. package/docs/streams.md +213 -0
  230. package/docs/sub-agents.md +185 -125
  231. package/docs/tasks.md +246 -0
  232. package/docs/voice.md +745 -0
  233. package/package.json +144 -33
  234. package/dist/cli/index.js +0 -26
  235. package/dist/cli/index.js.map +0 -1
  236. package/dist/client-invoker-VNZ7X0nn.js.map +0 -1
  237. package/dist/client-zqKcsyFa.js.map +0 -1
  238. package/dist/compaction-helpers-iiKMr2TQ.js +0 -340
  239. package/dist/compaction-helpers-iiKMr2TQ.js.map +0 -1
  240. package/dist/compaction-helpers-wUz6M3us.d.ts +0 -621
  241. package/dist/experimental/memory/session/index.d.ts +0 -670
  242. package/dist/experimental/memory/session/index.js +0 -2374
  243. package/dist/experimental/memory/session/index.js.map +0 -1
  244. package/dist/experimental/memory/utils/index.d.ts +0 -96
  245. package/dist/experimental/memory/utils/index.js +0 -79
  246. package/dist/experimental/memory/utils/index.js.map +0 -1
  247. package/dist/handler-stateless-CIkKPETH.js.map +0 -1
  248. package/dist/index.js.map +0 -1
  249. package/dist/internal_context-Dg4Cgjcu.d.ts +0 -37
  250. package/dist/internal_context.js.map +0 -1
  251. package/dist/mcp/client.d.ts +0 -42
  252. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  253. package/dist/mcp/x402.js.map +0 -1
  254. package/dist/protocol-Dqc2MQxo.js.map +0 -1
  255. package/dist/tool-output-truncation-CNnnGZQ3.js +0 -98
  256. package/dist/tool-output-truncation-CNnnGZQ3.js.map +0 -1
  257. package/dist/ws-chat-transport-CIoOBbO7.js.map +0 -1
  258. /package/dist/{cli/index.d.ts → index-BVVgDSdq.d.ts} +0 -0
@@ -1,11 +1,28 @@
1
- import { n as AgentEmail } from "./internal_context-Dg4Cgjcu.js";
2
- import { t as RetryOptions } from "./retries-CAvxtG9d.js";
1
+ import {
2
+ _ as LifecycleJobOutcome,
3
+ b as Connection,
4
+ g as LifecycleJobContext,
5
+ o as MemoryLimitContext,
6
+ s as LifecycleCapability,
7
+ t as CapabilityRequestContext,
8
+ u as LifecycleRouteAddress,
9
+ w as WSMessage,
10
+ x as ConnectionContext
11
+ } from "./capability-runner-Be_-PLR1.js";
12
+ import { t as RetryOptions } from "./retries-D9Ds-1lz.js";
13
+ import {
14
+ c as LifecycleRouteEnvelope,
15
+ n as CurrentAgentContext,
16
+ o as Lifecycle
17
+ } from "./current-agent-Da_C9a3b.js";
18
+ import { t as AgentEmail } from "./internal_context-BlxFEWfn.js";
19
+ import { r as EmailResolver, s as SendEmailOptions } from "./email-7TatiTnl.js";
3
20
  import {
4
21
  n as Observability,
5
22
  r as ObservabilityEvent,
6
23
  s as MCPObservabilityEvent
7
- } from "./index-BRnybD6X.js";
8
- import { t as AgentMcpOAuthProvider } from "./do-oauth-client-provider-VTZj2VtM.js";
24
+ } from "./index-YSKgfgg9.js";
25
+ import { t as AgentMcpOAuthProvider } from "./do-oauth-client-provider-Tmf1vgKz.js";
9
26
  import {
10
27
  a as McpAuthContext,
11
28
  c as CORSOptions,
@@ -16,27 +33,25 @@ import {
16
33
  s as BaseTransportType,
17
34
  t as CreateStatelessMcpHandlerOptions,
18
35
  u as McpClientOptions
19
- } from "./handler-stateless-C_bo-Ytq.js";
20
- import { n as LegacyCallToolResultSchema } from "./client-invoker-BNSZxAkv.js";
36
+ } from "./handler-stateless-DxYpJ_XF.js";
37
+ import { n as LegacyCallToolResultSchema } from "./invoker-CG0_p_Wq.js";
21
38
  import { t as MessageType } from "./types-6Zo2zfoO.js";
22
- import { r as EmailResolver } from "./email-CL27preh.js";
23
39
  import {
40
+ a as ScheduleCriteria,
41
+ i as Schedule,
42
+ o as ScheduleOptions,
43
+ t as Scheduler
44
+ } from "./scheduler-Dwh85ZGl.js";
45
+ import { l as TaskHandlers, r as Tasks } from "./tasks-BRJ5zgya.js";
46
+ import { t as CallableMetadata } from "./callable-decorator-DP__HhBA.js";
47
+ import { AsyncLocalStorage } from "node:async_hooks";
48
+ import {
49
+ DurableObject,
24
50
  RpcTarget,
25
51
  WorkflowEvent,
26
52
  WorkflowSleepDuration,
27
53
  WorkflowStep
28
54
  } from "cloudflare:workers";
29
- import {
30
- Connection,
31
- Connection as Connection$1,
32
- ConnectionContext,
33
- ConnectionContext as ConnectionContext$1,
34
- PartyServerOptions,
35
- RoutingRetryOptions,
36
- Server,
37
- WSMessage,
38
- WSMessage as WSMessage$1
39
- } from "partyserver";
40
55
  import { z } from "zod";
41
56
  import {
42
57
  CacheableRequestOptions,
@@ -79,7 +94,7 @@ import {
79
94
  } from "@modelcontextprotocol/sdk/types.js";
80
95
  import { McpServerFactory } from "@modelcontextprotocol/server";
81
96
  import { McpServer as McpServer$1 } from "@modelcontextprotocol/sdk/server/mcp.js";
82
- import { Server as Server$2 } from "@modelcontextprotocol/sdk/server/index.js";
97
+ import { Server as Server$1 } from "@modelcontextprotocol/sdk/server/index.js";
83
98
  import {
84
99
  EventStore as EventStore$1,
85
100
  StreamId as StreamId$1,
@@ -277,78 +292,800 @@ declare function routeSubAgentRequest(
277
292
  */
278
293
  declare function getSubAgentByName<T extends Agent>(
279
294
  parent: unknown,
280
- cls: SubAgentClass<T>,
295
+ cls: DynamicAgentClass<T>,
281
296
  name: string
282
- ): Promise<SubAgentStub<T>>;
297
+ ): Promise<DynamicAgentStub<T>>;
283
298
  //#endregion
284
- //#region src/core/events.d.ts
285
- interface Disposable {
286
- dispose(): void;
287
- }
288
- type Event<T> = (listener: (e: T) => void) => Disposable;
289
- declare class Emitter<T> implements Disposable {
290
- private _listeners;
291
- readonly event: Event<T>;
292
- fire(data: T): void;
293
- dispose(): void;
294
- }
299
+ //#region src/dynamic-agents/types.d.ts
300
+ type DynamicAgentConnectionMeta = {
301
+ id: string;
302
+ uri: string | null;
303
+ tags: string[];
304
+ state: unknown;
305
+ requestHeaders?: [string, string][];
306
+ };
307
+ type DynamicAgentConnectionBridgeLike = {
308
+ send(message: string | ArrayBuffer | ArrayBufferView): void | Promise<void>;
309
+ close(code?: number, reason?: string): void | Promise<void>;
310
+ setState(state: unknown): unknown | Promise<unknown>;
311
+ broadcast(
312
+ ownerPath: ReadonlyArray<{
313
+ className: string;
314
+ name: string;
315
+ }>,
316
+ message: string | ArrayBuffer | ArrayBufferView,
317
+ without?: string[]
318
+ ): void | Promise<void>;
319
+ };
320
+ type DynamicAgentConnectionOperationName = "send" | "setState" | "close";
321
+ /**
322
+ * Constructor type for a dynamic agent (facet-backed child) class.
323
+ * Used by {@link Agent.dynamicAgents} to reference the child class
324
+ * via `ctx.exports`.
325
+ *
326
+ * The class name (`cls.name`) must match the export name in the
327
+ * worker entry point — re-exports under a different name
328
+ * (e.g. `export { Foo as Bar }`) are not supported.
329
+ */
330
+ type DynamicAgentClass<T extends Agent = Agent> = {
331
+ new (ctx: DurableObjectState, env: never): T;
332
+ };
333
+ /**
334
+ * Wraps `T` in a `Promise` unless it already is one.
335
+ */
336
+ type Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;
337
+ /**
338
+ * A typed RPC stub for a dynamic agent. Exposes all public instance
339
+ * methods as callable RPC methods with Promise-wrapped return types.
340
+ *
341
+ * Methods owned by `Agent`, its lifecycle, or `DurableObject` internals
342
+ * are excluded — only user-defined methods on the subclass are exposed.
343
+ */
344
+ type DynamicAgentStub<T extends Agent> = {
345
+ [K in keyof T as K extends keyof Agent
346
+ ? never
347
+ : T[K] extends (...args: never[]) => unknown
348
+ ? K
349
+ : never]: T[K] extends (...args: infer A) => infer R
350
+ ? (...args: A) => Promisify<R>
351
+ : never;
352
+ };
353
+ type FacetRunStorageRow = {
354
+ owner_path: string;
355
+ owner_path_key: string;
356
+ run_id: string;
357
+ created_at: number;
358
+ };
359
+ /**
360
+ * Internal RPC surface exposed by the root agent for facets to
361
+ * delegate alarm-owning operations (schedules + facet teardown).
362
+ * @internal
363
+ */
364
+ type RootFacetRpcSurface = {
365
+ _cf_routeLifecycle(
366
+ target: LifecycleRouteAddress | undefined,
367
+ envelope: LifecycleRouteEnvelope
368
+ ): Promise<unknown>;
369
+ _cf_cleanupFacetPrefix(
370
+ ownerPath: ReadonlyArray<AgentPathStep>
371
+ ): Promise<void>;
372
+ _cf_destroyDescendantFacet(
373
+ targetPath: ReadonlyArray<AgentPathStep>
374
+ ): Promise<void>;
375
+ _cf_acquireFacetKeepAlive(
376
+ ownerPath: ReadonlyArray<AgentPathStep>
377
+ ): Promise<string>;
378
+ _cf_releaseFacetKeepAlive(token: string): Promise<void>;
379
+ _cf_registerFacetRun(
380
+ ownerPath: ReadonlyArray<AgentPathStep>,
381
+ runId: string
382
+ ): Promise<void>;
383
+ _cf_unregisterFacetRun(
384
+ ownerPath: ReadonlyArray<AgentPathStep>,
385
+ runId: string
386
+ ): Promise<void>;
387
+ _cf_broadcastToSubAgent(
388
+ ownerPath: ReadonlyArray<AgentPathStep>,
389
+ message: string | ArrayBuffer | ArrayBufferView,
390
+ without?: string[]
391
+ ): Promise<void>;
392
+ _cf_subAgentConnectionMetas(
393
+ ownerPath: ReadonlyArray<AgentPathStep>
394
+ ): Promise<DynamicAgentConnectionMeta[]>;
395
+ _cf_sendToSubAgentConnection(
396
+ connectionId: string,
397
+ message: string | ArrayBuffer | ArrayBufferView
398
+ ): Promise<void>;
399
+ _cf_closeSubAgentConnection(
400
+ connectionId: string,
401
+ code?: number,
402
+ reason?: string
403
+ ): Promise<void>;
404
+ _cf_setSubAgentConnectionState(
405
+ connectionId: string,
406
+ state: unknown
407
+ ): Promise<unknown>;
408
+ };
295
409
  //#endregion
296
- //#region src/mcp/client-transports.d.ts
410
+ //#region src/dynamic-agents/bridges.d.ts
297
411
  /**
298
- * @deprecated Use SSEClientTransport from @modelcontextprotocol/client instead. This alias will be removed in the next major version.
412
+ * Parent-side bridge handed to a facet over RPC: wraps a live root-owned
413
+ * `Connection` so the facet can send/close/setState on it, and carries
414
+ * the root's broadcast entry point for facet-scoped broadcasts.
299
415
  */
300
- declare class SSEEdgeClientTransport extends SSEClientTransport {
301
- constructor(url: URL, options: SSEClientTransportOptions);
416
+ declare class DynamicAgentConnectionBridge
417
+ extends RpcTarget
418
+ implements DynamicAgentConnectionBridgeLike
419
+ {
420
+ #private;
421
+ constructor(
422
+ connection: Connection,
423
+ broadcast?: (
424
+ ownerPath: ReadonlyArray<{
425
+ className: string;
426
+ name: string;
427
+ }>,
428
+ message: string | ArrayBuffer | ArrayBufferView,
429
+ without?: string[]
430
+ ) => void | Promise<void>
431
+ );
432
+ send(message: string | ArrayBuffer | ArrayBufferView): void;
433
+ close(code?: number, reason?: string): void;
434
+ setState(state: unknown): unknown;
435
+ broadcast(
436
+ ownerPath: ReadonlyArray<{
437
+ className: string;
438
+ name: string;
439
+ }>,
440
+ message: string | ArrayBuffer | ArrayBufferView,
441
+ without?: string[]
442
+ ): void | Promise<void>;
302
443
  }
444
+ //#endregion
445
+ //#region src/dynamic-agents/identity.d.ts
446
+ declare const SUB_AGENT_IDENTITY_VERSION_LEGACY = "legacy";
447
+ declare const SUB_AGENT_IDENTITY_VERSION_PATH_V2 = "path-v2";
448
+ type SubAgentIdentityVersion =
449
+ | typeof SUB_AGENT_IDENTITY_VERSION_LEGACY
450
+ | typeof SUB_AGENT_IDENTITY_VERSION_PATH_V2;
451
+ //#endregion
452
+ //#region src/dynamic-agents/registry.d.ts
303
453
  /**
304
- * @deprecated Use StreamableHTTPClientTransport from @modelcontextprotocol/client instead. This alias will be removed in the next major version.
454
+ * SQL access the registry needs from its owning Agent: the tagged
455
+ * template helper plus raw DDL execution (for additive column
456
+ * migrations whose errors must be inspected).
305
457
  */
306
- declare class StreamableHTTPEdgeClientTransport extends StreamableHTTPClientTransport {
307
- constructor(url: URL, options: StreamableHTTPClientTransportOptions);
458
+ type DynamicAgentRegistrySqlHost = {
459
+ sql<T = Record<string, string | number | boolean | null>>(
460
+ strings: TemplateStringsArray,
461
+ ...values: (string | number | boolean | null)[]
462
+ ): T[];
463
+ execRawSql(sql: string): void;
464
+ };
465
+ /**
466
+ * The parent-side registry of spawned dynamic agents (facets), stored
467
+ * in the parent's own SQLite. Backs `hasSubAgent` / `listSubAgents`
468
+ * and the identity-versioning decision (legacy bare-name facets vs
469
+ * path-scoped v2 identities).
470
+ *
471
+ * Table and column names are storage-frozen — never rename them.
472
+ */
473
+ declare class DynamicAgentRegistry {
474
+ #private;
475
+ constructor(host: DynamicAgentRegistrySqlHost);
476
+ ensure(): void;
477
+ record(
478
+ className: string,
479
+ name: string,
480
+ identity: {
481
+ version: SubAgentIdentityVersion;
482
+ name: string;
483
+ }
484
+ ): void;
485
+ row(
486
+ className: string,
487
+ name: string
488
+ ): {
489
+ identity_version: string | null;
490
+ identity_name: string | null;
491
+ } | null;
492
+ identity(
493
+ className: string,
494
+ name: string,
495
+ childPath: ReadonlyArray<AgentPathStep>
496
+ ): Promise<{
497
+ version: SubAgentIdentityVersion;
498
+ name: string;
499
+ existing: boolean;
500
+ }>;
501
+ forget(className: string, name: string): void;
502
+ has(className: string, name: string): boolean;
503
+ list(className?: string): Array<{
504
+ className: string;
505
+ name: string;
506
+ createdAt: number;
507
+ }>;
308
508
  }
309
509
  //#endregion
310
- //#region src/mcp/worker-transport.d.ts
510
+ //#region src/dynamic-agents/host.d.ts
311
511
  /**
312
- * Pluggable storage adapter for persisting `WorkerTransport` state across
313
- * Durable Object hibernation / restart cycles.
512
+ * The Agent internals the dynamic-agents (facet) machinery reaches
513
+ * into. Agent implements this structurally and passes itself at
514
+ * construction — the interface exists to make the coupling explicit
515
+ * and reviewable, and is the seam a later capability refactor would
516
+ * shrink.
314
517
  *
315
- * A typical implementation reads/writes a single key on `this.ctx.storage`
316
- * inside a Durable Object or Agent.
518
+ * Members named `_cf_*` are cross-facet RPC entry points that must
519
+ * stay on the Agent prototype; the module calls back into them when
520
+ * traversal continues on another agent instance.
521
+ *
522
+ * @internal
317
523
  */
318
- interface MCPStorageApi {
319
- get(): Promise<TransportState | undefined> | TransportState | undefined;
320
- set(state: TransportState): Promise<void> | void;
321
- }
322
- /** Shape of the persisted transport state. */
323
- interface TransportState {
324
- sessionId?: string;
325
- initialized: boolean;
326
- initializeParams?: InitializeRequestParams;
524
+ interface DynamicAgentHostPort {
525
+ readonly ctx: DurableObjectState;
526
+ readonly lifecycle: {
527
+ route(envelope: LifecycleRouteEnvelope): Promise<unknown>;
528
+ readonly name: string;
529
+ };
530
+ sql<T = Record<string, string | number | boolean | null>>(
531
+ strings: TemplateStringsArray,
532
+ ...values: (string | number | boolean | null)[]
533
+ ): T[];
534
+ /** Facet identity — written by `initAsFacet` and startup restore. */
535
+ _isFacet: boolean;
536
+ _facetName?: string;
537
+ _parentPath: ReadonlyArray<AgentPathStep>;
538
+ readonly name: string;
539
+ readonly _ParentClass: {
540
+ readonly name: string;
541
+ };
542
+ readonly selfPath: AgentPathStep[];
543
+ _keepAliveRefs: number;
544
+ _isSameAgentPathPrefix(
545
+ prefix: ReadonlyArray<AgentPathStep>,
546
+ path: ReadonlyArray<AgentPathStep>
547
+ ): boolean;
548
+ hasSubAgent(className: string, name: string): boolean;
549
+ _cf_resolveSubAgent(className: string, name: string): Promise<unknown>;
550
+ _cf_cleanupFacetPrefix(
551
+ ownerPath: ReadonlyArray<AgentPathStep>
552
+ ): Promise<void>;
553
+ _cf_routeLifecycle(
554
+ target: LifecycleRouteAddress | undefined,
555
+ envelope: LifecycleRouteEnvelope
556
+ ): Promise<unknown>;
557
+ _syncHostJobs(): Promise<void>;
558
+ readonly scheduler: {
559
+ __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(prefix: string): Promise<void>;
560
+ };
561
+ readonly tasks: {
562
+ __DO_NOT_USE_WILL_BREAK__cleanupRoutePrefix(prefix: string): Promise<void>;
563
+ };
564
+ /** Local (non-facet-index) durable fiber recovery pass. */
565
+ _checkRunFibers(): Promise<void>;
566
+ /** Overridable RPC entry points — call via the host so subclass overrides intercept. */
567
+ _cf_broadcastToSubAgent(
568
+ ownerPath: ReadonlyArray<AgentPathStep>,
569
+ message: string | ArrayBuffer | ArrayBufferView,
570
+ without?: string[]
571
+ ): Promise<void>;
572
+ _cf_checkRunFibersForFacet(
573
+ ownerPath: ReadonlyArray<AgentPathStep>
574
+ ): Promise<number>;
575
+ /** Ensure constructor-time async initialization has completed. */
576
+ __unsafe_ensureInitialized(): Promise<void>;
577
+ /**
578
+ * Run `body` in a fresh invocation scope with no native request/
579
+ * connection context attached, so a child-facet RPC never sees
580
+ * parent-owned I/O handles.
581
+ */
582
+ _runFacetInitInvocation<T>(body: () => Promise<T>): Promise<T>;
583
+ readonly _webSockets: {
584
+ getConnection<TState = unknown>(id: string): Connection<TState> | undefined;
585
+ getConnections<TState = unknown>(
586
+ tag?: string
587
+ ): Iterable<Connection<TState>>;
588
+ };
589
+ _ensureConnectionWrapped(connection: Connection): void;
590
+ _unsafe_getConnectionFlag(connection: Connection, key: string): unknown;
591
+ _unsafe_setConnectionFlag(
592
+ connection: Connection,
593
+ key: string,
594
+ value: unknown
595
+ ): void;
596
+ readonly _rawStateAccessors: {
597
+ get(connection: Connection):
598
+ | {
599
+ getRaw(): unknown;
600
+ }
601
+ | undefined;
602
+ };
603
+ shouldConnectionBeReadonly(
604
+ connection: Connection,
605
+ context: {
606
+ request: Request;
607
+ }
608
+ ): boolean;
609
+ setConnectionReadonly(connection: Connection, readonly: boolean): void;
610
+ shouldSendProtocolMessages(
611
+ connection: Connection,
612
+ context: {
613
+ request: Request;
614
+ }
615
+ ): boolean;
616
+ _setConnectionNoProtocol(connection: Connection): void;
617
+ getConnectionTags(
618
+ connection: Connection,
619
+ context: {
620
+ request: Request;
621
+ }
622
+ ): Promise<string[]> | string[];
623
+ onConnect(
624
+ connection: Connection,
625
+ context: {
626
+ request: Request;
627
+ }
628
+ ): unknown | Promise<unknown>;
629
+ onMessage(
630
+ connection: Connection,
631
+ message: WSMessage
632
+ ): unknown | Promise<unknown>;
633
+ onClose(
634
+ connection: Connection,
635
+ code: number,
636
+ reason: string,
637
+ wasClean: boolean
638
+ ): unknown | Promise<unknown>;
639
+ onBeforeSubAgent(
640
+ request: Request,
641
+ child: {
642
+ className: string;
643
+ name: string;
644
+ }
645
+ ): Promise<Request | Response | void>;
327
646
  }
328
- interface WorkerTransportOptions extends WebStandardStreamableHTTPServerTransportOptions {
647
+ //#endregion
648
+ //#region src/dynamic-agents/dynamic-agents.d.ts
649
+ /**
650
+ * The facet-backed dynamic-agent machinery, extracted from the Agent
651
+ * class. One instance per Agent, installed as a Lifecycle capability
652
+ * (`capabilityId: "dynamic-agents"`); the host port documents exactly
653
+ * which Agent internals it touches.
654
+ *
655
+ * The capability claims no runner hooks — four integration points are
656
+ * deliberately wired directly through the Agent composition root
657
+ * instead, because the runner's dispatch contract cannot express them:
658
+ * the `/sub/` upgrade path rewrites the request and *continues* into
659
+ * `lifecycle.fetch` (onRequest can only claim), forwarded WS frames run
660
+ * inside the host's onMessage wrapper *after* the WebSockets capability
661
+ * has claimed the wake, this module *implements* the lifecycle route
662
+ * transport rather than consuming it, and facet-context restore has
663
+ * load-bearing startup ordering inside the host's startup span.
664
+ *
665
+ * Nothing here renames any wire- or storage-visible identifier: the
666
+ * `cf_agents_facet_runs` table, `_cf_*` RPC method names, and route
667
+ * key formats are frozen.
668
+ *
669
+ * @internal
670
+ */
671
+ declare class DynamicAgentsInternal extends LifecycleCapability {
672
+ #private;
673
+ /** The parent-side registry of spawned dynamic agents. */
674
+ readonly registry: DynamicAgentRegistry;
675
+ constructor(host: DynamicAgentHostPort);
676
+ runRowsForPrefix(
677
+ ownerPath: ReadonlyArray<AgentPathStep>
678
+ ): FacetRunStorageRow[];
679
+ deleteRunRowsForPrefix(ownerPath: ReadonlyArray<AgentPathStep>): void;
680
+ lifecycleRouteAddress(): LifecycleRouteAddress | undefined;
681
+ routeLifecycleToRoot(envelope: LifecycleRouteEnvelope): Promise<unknown>;
682
+ routeLifecycleToTarget(
683
+ target: LifecycleRouteAddress,
684
+ envelope: LifecycleRouteEnvelope
685
+ ): Promise<unknown>;
686
+ /** Body of the single native-RPC aperture for routed Lifecycle capabilities. */
687
+ routeLifecycle(
688
+ target: LifecycleRouteAddress | undefined,
689
+ envelope: LifecycleRouteEnvelope
690
+ ): Promise<unknown>;
691
+ rootAlarmOwner(): Promise<RootFacetRpcSurface>;
692
+ rootResolvesToSelf(): boolean;
329
693
  /**
330
- * CORS options applied to every response and to OPTIONS preflight.
331
- * Defaults: `origin: *`, expose `mcp-session-id`, allow the standard MCP
332
- * methods/headers, max-age 86400.
694
+ * Clean root-owned bookkeeping for a sub-tree of facets: bulk-cancel
695
+ * schedules and routed Task wake mirrors under the owner-path prefix,
696
+ * and delete root-side facet fiber recovery leases for the same sub-tree.
333
697
  */
334
- corsOptions?: CORSOptions;
698
+ cleanupPrefix(ownerPath: ReadonlyArray<AgentPathStep>): Promise<void>;
335
699
  /**
336
- * Optional storage adapter for persisting transport state across DO
337
- * hibernation / restart. Use this to keep an MCP session alive across
338
- * Durable Object wake-ups.
700
+ * Acquire a root-owned keepAlive ref on behalf of a descendant facet.
339
701
  */
340
- storage?: MCPStorageApi;
341
- }
342
- declare class WorkerTransport extends WebStandardStreamableHTTPServerTransport$1 {
343
- private readonly _corsOptions?;
344
- private readonly _storage?;
345
- private _stateRestored;
346
- private _capturedInitializeParams?;
347
- private _userOnSessionInitialized?;
348
- private _bridgeInstalled;
702
+ acquireKeepAlive(ownerPath: ReadonlyArray<AgentPathStep>): Promise<string>;
349
703
  /**
350
- * Request ids whose SSE stream was deliberately torn down via
351
- * `closeSSEStream`. The SDK's `send()` throws "No connection established"
704
+ * Release a root-owned keepAlive ref previously acquired for a facet.
705
+ * Idempotent so disposer calls can safely race or run twice.
706
+ */
707
+ releaseKeepAlive(token: string): Promise<void>;
708
+ /**
709
+ * Register a facet's durable run row in the root-side index so root
710
+ * alarm housekeeping can dispatch recovery checks into idle facets.
711
+ */
712
+ registerRun(
713
+ ownerPath: ReadonlyArray<AgentPathStep>,
714
+ runId: string
715
+ ): Promise<void>;
716
+ /**
717
+ * Root-side scan for durable fibers owned by descendant facets.
718
+ * `cf_agents_facet_runs` is only an index; actual snapshots and
719
+ * recovery hooks live in each facet's own `cf_agents_runs` table.
720
+ */
721
+ checkRunFibers(): Promise<void>;
722
+ /**
723
+ * Dispatch a runFiber recovery check into the facet identified by
724
+ * `ownerPath`. Returns the number of remaining local `cf_agents_runs`
725
+ * rows on the target facet after recovery.
726
+ */
727
+ checkRunFibersAtPath(
728
+ ownerPath: ReadonlyArray<AgentPathStep>
729
+ ): Promise<number>;
730
+ /**
731
+ * Invoke an RPC method on the host Agent or a descendant facet
732
+ * identified by a root-first path. Used by AgentWorkflow to route
733
+ * callbacks and `this.agent` calls back to the exact sub-agent that
734
+ * started a workflow.
735
+ */
736
+ invokeAgentPath(
737
+ targetPath: ReadonlyArray<AgentPathStep>,
738
+ method: string,
739
+ args: unknown[]
740
+ ): Promise<unknown>;
741
+ /**
742
+ * Recursively destroy a descendant facet identified by `targetPath`.
743
+ * Walks down from `selfPath` until reaching the target's immediate
744
+ * parent, where it cancels the target's parent-owned schedules (and
745
+ * any descendants), removes the target from the registry, and calls
746
+ * `ctx.facets.delete` to wipe the target's storage.
747
+ */
748
+ destroyDescendant(targetPath: ReadonlyArray<AgentPathStep>): Promise<void>;
749
+ /**
750
+ * Shared facet resolution — takes a CamelCase class name string
751
+ * (matching `ctx.exports`) rather than a class reference. Both
752
+ * `subAgent(cls, name)` and `_cf_invokeSubAgent(className, ...)`
753
+ * funnel through here so registry bookkeeping and the
754
+ * `_cf_initAsFacet` handshake are consistent.
755
+ */
756
+ resolve(className: string, name: string): Promise<unknown>;
757
+ /**
758
+ * Forcefully abort a running facet. Transitively aborts the child's
759
+ * own children; storage is preserved.
760
+ */
761
+ abort(className: string, name: string, reason?: unknown): void;
762
+ /**
763
+ * Delete a facet: abort it if running, then permanently wipe its
764
+ * storage. Transitively deletes the child's own children.
765
+ */
766
+ delete(className: string, name: string): Promise<void>;
767
+ /** Drop all facet-side virtual connections (test/rehydration hook). */
768
+ clearVirtualConnections(): void;
769
+ /** Facet-side lookup of a virtual connection by id. */
770
+ getVirtualConnection(id: string): Connection | undefined;
771
+ /** Facet-side iteration over virtual connections, optionally by tag. */
772
+ getVirtualConnections(tag?: string): Iterable<Connection>;
773
+ activeBridge(
774
+ connectionId?: string
775
+ ): DynamicAgentConnectionBridgeLike | undefined;
776
+ /**
777
+ * Route a virtual sub-agent connection operation through its live frame
778
+ * bridge, or through the durable root Agent after that frame completes.
779
+ * All operations share one per-connection queue. Facet broadcasts wait for
780
+ * older queued operations; failures do not block later work.
781
+ */
782
+ routeConnectionOperation(
783
+ connectionId: string,
784
+ operationName: DynamicAgentConnectionOperationName,
785
+ operation: (bridge: DynamicAgentConnectionBridgeLike) => unknown
786
+ ): void;
787
+ /**
788
+ * Route a facet broadcast after every older connection operation.
789
+ *
790
+ * This barrier is intentionally one-way: facet startup can broadcast before
791
+ * a child connection has finished initializing its tags and protocol flags.
792
+ * Making those later connection operations wait would let the next frame
793
+ * observe stale root-owned metadata.
794
+ */
795
+ routeBroadcast(
796
+ ownerPath: ReadonlyArray<AgentPathStep>,
797
+ message: string | ArrayBuffer | ArrayBufferView,
798
+ without?: string[],
799
+ upstreamBridge?: DynamicAgentConnectionBridgeLike
800
+ ): Promise<void>;
801
+ broadcastToParent(
802
+ message: string | ArrayBuffer | ArrayBufferView,
803
+ without?: string[]
804
+ ): Promise<void>;
805
+ broadcastToPath(
806
+ ownerPath: ReadonlyArray<AgentPathStep>,
807
+ message: string | ArrayBuffer | ArrayBufferView,
808
+ without?: string[]
809
+ ): Promise<void>;
810
+ connectionMetas(
811
+ ownerPath: ReadonlyArray<AgentPathStep>
812
+ ): Promise<DynamicAgentConnectionMeta[]>;
813
+ sendToConnection(
814
+ connectionId: string,
815
+ message: string | ArrayBuffer | ArrayBufferView
816
+ ): Promise<void>;
817
+ closeConnection(
818
+ connectionId: string,
819
+ code?: number,
820
+ reason?: string
821
+ ): Promise<void>;
822
+ setConnectionState(connectionId: string, state: unknown): Promise<unknown>;
823
+ connectionTargetPath(
824
+ connection: Connection
825
+ ): ReadonlyArray<AgentPathStep> | null;
826
+ isSameAgentPath(
827
+ a: ReadonlyArray<AgentPathStep>,
828
+ b: ReadonlyArray<AgentPathStep>
829
+ ): boolean;
830
+ connectionHasChildTarget(connection: Connection): boolean;
831
+ connectionTargetsChild(connection: Connection): boolean;
832
+ requestTargetsChild(request: Request): boolean;
833
+ forwardWebSocketConnect(
834
+ connection: Connection,
835
+ request: Request,
836
+ options: {
837
+ gate: boolean;
838
+ }
839
+ ): Promise<boolean>;
840
+ forwardWebSocketMessage(
841
+ connection: Connection,
842
+ message: WSMessage,
843
+ replyBridge?: DynamicAgentConnectionBridge
844
+ ): Promise<boolean>;
845
+ forwardWebSocketClose(
846
+ connection: Connection,
847
+ code: number,
848
+ reason: string,
849
+ wasClean: boolean
850
+ ): Promise<boolean>;
851
+ handleWebSocketConnect(
852
+ bridge: DynamicAgentConnectionBridge,
853
+ meta: DynamicAgentConnectionMeta
854
+ ): Promise<void>;
855
+ handleWebSocketMessage(
856
+ message: WSMessage,
857
+ bridge: DynamicAgentConnectionBridge,
858
+ meta: DynamicAgentConnectionMeta,
859
+ replyBridge?: DynamicAgentConnectionBridge
860
+ ): Promise<void>;
861
+ handleWebSocketClose(
862
+ code: number,
863
+ reason: string,
864
+ wasClean: boolean,
865
+ bridge: DynamicAgentConnectionBridge,
866
+ meta: DynamicAgentConnectionMeta
867
+ ): Promise<void>;
868
+ runWithBridge<T>(
869
+ bridge: DynamicAgentConnectionBridgeLike,
870
+ connectionId: string,
871
+ fn: () => Promise<T> | T
872
+ ): Promise<T>;
873
+ createBridgeConnection(meta: DynamicAgentConnectionMeta): Connection;
874
+ storeVirtualConnection(connection: Connection): void;
875
+ /**
876
+ * Restore the facet identity persisted by `init` (wake after
877
+ * hibernation), then best-effort hydrate the virtual connections
878
+ * from the root's WebSocket state.
879
+ */
880
+ restoreFacetContext(): Promise<void>;
881
+ hydrateConnectionsFromRoot(): Promise<void>;
882
+ getRawConnectionState(connection: Connection): unknown;
883
+ getForwardedState(connection: Connection): unknown;
884
+ /**
885
+ * Resolve the facet Fetcher for the match and forward the request to
886
+ * it with `/sub/{class}/{name}` stripped.
887
+ */
888
+ forward(
889
+ req: Request,
890
+ match: {
891
+ childClass: string;
892
+ childName: string;
893
+ remainingPath: string;
894
+ }
895
+ ): Promise<Response>;
896
+ /**
897
+ * Bridge used by `getSubAgentByName`: resolve the facet and dispatch
898
+ * one RPC method. Stateless — no cached references.
899
+ */
900
+ invoke(
901
+ className: string,
902
+ name: string,
903
+ method: string,
904
+ args: unknown[]
905
+ ): Promise<unknown>;
906
+ /**
907
+ * Bridge used by `parentAgent()` when the requested parent is itself
908
+ * a facet (and therefore has no top-level env namespace). The root
909
+ * receives the full root-first target path, then each hop delegates
910
+ * to the next facet using that facet's own `ctx.facets`.
911
+ */
912
+ invokePath(
913
+ path: ReadonlyArray<{
914
+ className: string;
915
+ name: string;
916
+ }>,
917
+ method: string,
918
+ args: unknown[]
919
+ ): Promise<unknown>;
920
+ invokeStubMethod(
921
+ stub: unknown,
922
+ className: string,
923
+ method: string,
924
+ args: unknown[]
925
+ ): Promise<unknown>;
926
+ /**
927
+ * Initialize the host agent as a facet in a single RPC. Runs entirely
928
+ * inside the child's isolate, so every storage write and `onStart()`
929
+ * I/O is owned by the child DO.
930
+ */
931
+ init(
932
+ name: string,
933
+ parentPath?: ReadonlyArray<{
934
+ className: string;
935
+ name: string;
936
+ }>,
937
+ identityName?: string
938
+ ): Promise<void>;
939
+ /** Remove a completed facet fiber from the root-side index. */
940
+ unregisterRun(
941
+ ownerPath: ReadonlyArray<AgentPathStep>,
942
+ runId: string
943
+ ): Promise<void>;
944
+ }
945
+ //#endregion
946
+ //#region src/dynamic-agents/api.d.ts
947
+ /**
948
+ * The public dynamic-agents capability surface, reached via
949
+ * `this.dynamicAgents` on an Agent.
950
+ *
951
+ * A dynamic agent is a facet-backed child: it runs in its own isolate
952
+ * with its own SQLite database, colocated with — and supervised by —
953
+ * its parent Agent. Use dynamic agents for code whose class or
954
+ * lifecycle the parent owns (dynamically-loaded/generated code,
955
+ * per-run tool agents, sandboxed components). For independent peers
956
+ * such as one-DO-per-chat, use `getAgentByName` instead.
957
+ *
958
+ * @experimental The API surface may change before stabilizing.
959
+ */
960
+ declare class DynamicAgents {
961
+ #private;
962
+ /** @internal Constructed by Agent; do not instantiate directly. */
963
+ constructor(internal: DynamicAgentsInternal);
964
+ /**
965
+ * Get (creating or waking if needed) the dynamic agent of the given
966
+ * class and name, as a typed RPC stub. Idempotent — repeated calls
967
+ * with the same class and name return the same child.
968
+ *
969
+ * @experimental
970
+ */
971
+ get<T extends Agent>(
972
+ cls: DynamicAgentClass<T>,
973
+ name: string
974
+ ): Promise<DynamicAgentStub<T>>;
975
+ /**
976
+ * Forcefully abort a running dynamic agent. The child stops
977
+ * executing immediately and restarts on the next {@link get} call;
978
+ * its storage is preserved. Transitively aborts the child's own
979
+ * children. Pending RPC calls receive the reason as an error.
980
+ *
981
+ * @experimental
982
+ */
983
+ abort(cls: DynamicAgentClass, name: string, reason?: unknown): void;
984
+ /**
985
+ * Delete a dynamic agent: abort it if running, then permanently wipe
986
+ * its storage. Transitively deletes the child's own children.
987
+ *
988
+ * @experimental
989
+ */
990
+ delete(cls: DynamicAgentClass, name: string): Promise<void>;
991
+ /**
992
+ * Whether this agent has previously spawned (and not deleted) a
993
+ * dynamic agent of the given class and name. Backed by an
994
+ * auto-maintained SQLite registry in the parent's storage.
995
+ *
996
+ * @experimental
997
+ */
998
+ has<T extends Agent>(cls: DynamicAgentClass<T>, name: string): boolean;
999
+ has(className: string, name: string): boolean;
1000
+ /**
1001
+ * List known dynamic agents, optionally filtered by class. Reflects
1002
+ * the registry rows written by {@link get} and removed by
1003
+ * {@link delete}.
1004
+ *
1005
+ * @experimental
1006
+ */
1007
+ list<T extends Agent>(
1008
+ cls: DynamicAgentClass<T>
1009
+ ): Array<{
1010
+ className: string;
1011
+ name: string;
1012
+ createdAt: number;
1013
+ }>;
1014
+ list(className?: string): Array<{
1015
+ className: string;
1016
+ name: string;
1017
+ createdAt: number;
1018
+ }>;
1019
+ }
1020
+ //#endregion
1021
+ //#region src/core/events.d.ts
1022
+ interface Disposable {
1023
+ dispose(): void;
1024
+ }
1025
+ type Event<T> = (listener: (e: T) => void) => Disposable;
1026
+ declare class Emitter<T> implements Disposable {
1027
+ private _listeners;
1028
+ readonly event: Event<T>;
1029
+ fire(data: T): void;
1030
+ dispose(): void;
1031
+ }
1032
+ //#endregion
1033
+ //#region src/mcp/client/transports.d.ts
1034
+ /**
1035
+ * @deprecated Use SSEClientTransport from @modelcontextprotocol/client instead. This alias will be removed in the next major version.
1036
+ */
1037
+ declare class SSEEdgeClientTransport extends SSEClientTransport {
1038
+ constructor(url: URL, options: SSEClientTransportOptions);
1039
+ }
1040
+ /**
1041
+ * @deprecated Use StreamableHTTPClientTransport from @modelcontextprotocol/client instead. This alias will be removed in the next major version.
1042
+ */
1043
+ declare class StreamableHTTPEdgeClientTransport extends StreamableHTTPClientTransport {
1044
+ constructor(url: URL, options: StreamableHTTPClientTransportOptions);
1045
+ }
1046
+ //#endregion
1047
+ //#region src/mcp/server/worker-transport.d.ts
1048
+ /**
1049
+ * Pluggable storage adapter for persisting `WorkerTransport` state across
1050
+ * Durable Object hibernation / restart cycles.
1051
+ *
1052
+ * A typical implementation reads/writes a single key on `this.ctx.storage`
1053
+ * inside a Durable Object or Agent.
1054
+ */
1055
+ interface MCPStorageApi {
1056
+ get(): Promise<TransportState | undefined> | TransportState | undefined;
1057
+ set(state: TransportState): Promise<void> | void;
1058
+ }
1059
+ /** Shape of the persisted transport state. */
1060
+ interface TransportState {
1061
+ sessionId?: string;
1062
+ initialized: boolean;
1063
+ initializeParams?: InitializeRequestParams;
1064
+ }
1065
+ interface WorkerTransportOptions extends WebStandardStreamableHTTPServerTransportOptions {
1066
+ /**
1067
+ * CORS options applied to every response and to OPTIONS preflight.
1068
+ * Defaults: `origin: *`, expose `mcp-session-id`, allow the standard MCP
1069
+ * methods/headers, max-age 86400.
1070
+ */
1071
+ corsOptions?: CORSOptions;
1072
+ /**
1073
+ * Optional storage adapter for persisting transport state across DO
1074
+ * hibernation / restart. Use this to keep an MCP session alive across
1075
+ * Durable Object wake-ups.
1076
+ */
1077
+ storage?: MCPStorageApi;
1078
+ }
1079
+ declare class WorkerTransport extends WebStandardStreamableHTTPServerTransport$1 {
1080
+ private readonly _corsOptions?;
1081
+ private readonly _storage?;
1082
+ private _stateRestored;
1083
+ private _capturedInitializeParams?;
1084
+ private _userOnSessionInitialized?;
1085
+ private _bridgeInstalled;
1086
+ /**
1087
+ * Request ids whose SSE stream was deliberately torn down via
1088
+ * `closeSSEStream`. The SDK's `send()` throws "No connection established"
352
1089
  * when a request id has no stream — a race that surfaces whenever the
353
1090
  * server's tool handler resolves *after* the caller closed the stream
354
1091
  * (e.g. polling-style early-close, or test fixtures closing mid-flight).
@@ -414,7 +1151,7 @@ declare class WorkerTransport extends WebStandardStreamableHTTPServerTransport$1
414
1151
  private saveState;
415
1152
  }
416
1153
  //#endregion
417
- //#region src/mcp/handler-legacy.d.ts
1154
+ //#region src/mcp/server/handler-legacy.d.ts
418
1155
  /** Options for the retained SDK v1, sessionful handler. */
419
1156
  interface CreateLegacyMcpHandlerOptions extends WorkerTransportOptions {
420
1157
  /** Exact route handled by this handler. @default "/mcp" */
@@ -437,11 +1174,11 @@ type LegacyMcpHandler = (
437
1174
  * `agents/mcp/server` instead.
438
1175
  */
439
1176
  declare function createLegacyMcpHandler(
440
- server: McpServer$1 | Server$2,
1177
+ server: McpServer$1 | Server$1,
441
1178
  options?: CreateLegacyMcpHandlerOptions
442
1179
  ): LegacyMcpHandler;
443
1180
  //#endregion
444
- //#region src/mcp/handler-compat.d.ts
1181
+ //#region src/mcp/server/handler-compat.d.ts
445
1182
  /**
446
1183
  * @deprecated Passing an SDK v1 server to createMcpHandler is deprecated and
447
1184
  * will be removed in the next major version. Pass an SDK v2 factory to
@@ -449,7 +1186,7 @@ declare function createLegacyMcpHandler(
449
1186
  * sessionful SDK v1 behavior while migrating.
450
1187
  */
451
1188
  declare function createMcpHandler$1(
452
- server: McpServer$1 | Server$2,
1189
+ server: McpServer$1 | Server$1,
453
1190
  options?: CreateMcpHandlerOptions$1
454
1191
  ): LegacyMcpHandler;
455
1192
  declare function createMcpHandler$1(
@@ -463,11 +1200,11 @@ declare function createMcpHandler$1(
463
1200
  * behavior while migrating.
464
1201
  */
465
1202
  declare function experimental_createMcpHandler(
466
- server: McpServer$1 | Server$2,
1203
+ server: McpServer$1 | Server$1,
467
1204
  options?: CreateMcpHandlerOptions$1
468
1205
  ): LegacyMcpHandler;
469
1206
  //#endregion
470
- //#region src/mcp/event-store.d.ts
1207
+ //#region src/mcp/server/event-store.d.ts
471
1208
  /**
472
1209
  * Durable Object–backed {@link EventStore} for SSE resumability.
473
1210
  *
@@ -546,7 +1283,7 @@ declare class DurableObjectEventStore implements EventStore {
546
1283
  private ensureSeqLoaded;
547
1284
  }
548
1285
  //#endregion
549
- //#region src/mcp/transport.d.ts
1286
+ //#region src/mcp/server/transport.d.ts
550
1287
  /**
551
1288
  * An {@link EventStore} that supports dropping all events for a single
552
1289
  * stream id. Implemented by {@link DurableObjectEventStore}.
@@ -555,7 +1292,7 @@ interface ClearableEventStore extends EventStore$1 {
555
1292
  clearStream(streamId: StreamId$1): Promise<void>;
556
1293
  }
557
1294
  //#endregion
558
- //#region src/mcp/legacy-agent.d.ts
1295
+ //#region src/mcp/server/legacy-agent.d.ts
559
1296
  /**
560
1297
  * @deprecated McpAgent is feature-frozen. Migrate to an SDK v2 factory with
561
1298
  * createMcpHandler from agents/mcp/server. When sessionful features prevent an
@@ -571,10 +1308,10 @@ declare abstract class McpAgent<
571
1308
  private _pendingElicitations;
572
1309
  props?: Props;
573
1310
  shouldSendProtocolMessages(
574
- _connection: Connection$1,
575
- ctx: ConnectionContext$1
1311
+ _connection: Connection,
1312
+ ctx: ConnectionContext
576
1313
  ): boolean;
577
- abstract server: MaybePromise<McpServer$1 | Server$2>;
1314
+ abstract server: MaybePromise<McpServer$1 | Server$1>;
578
1315
  abstract init(): Promise<void>;
579
1316
  setInitializeRequest(initializeRequest: JSONRPCMessage$1): Promise<void>;
580
1317
  getInitializeRequest(): Promise<JSONRPCMessage$1 | undefined>;
@@ -628,7 +1365,7 @@ declare abstract class McpAgent<
628
1365
  */
629
1366
  getSessionId(): string;
630
1367
  /** Get the unique WebSocket. SSE transport only. */
631
- getWebSocket(): Connection$1<unknown> | null;
1368
+ getWebSocket(): Connection<unknown> | null;
632
1369
  /**
633
1370
  * Returns options for configuring the RPC server transport.
634
1371
  * Override this method to customize RPC transport behavior (e.g., timeout).
@@ -667,8 +1404,8 @@ declare abstract class McpAgent<
667
1404
  onStart(props?: Props): Promise<void>;
668
1405
  /** Validates new WebSocket connections. */
669
1406
  onConnect(
670
- conn: Connection$1,
671
- { request: req }: ConnectionContext$1
1407
+ conn: Connection,
1408
+ { request: req }: ConnectionContext
672
1409
  ): Promise<void>;
673
1410
  /** Handles MCP Messages for the legacy SSE transport. */
674
1411
  onSSEMcpMessage(
@@ -817,7 +1554,7 @@ declare class RPCServerTransport implements Transport$1 {
817
1554
  ): Promise<JSONRPCMessage$2 | JSONRPCMessage$2[] | undefined>;
818
1555
  }
819
1556
  //#endregion
820
- //#region src/mcp/client-connection.d.ts
1557
+ //#region src/mcp/client/connection.d.ts
821
1558
  /**
822
1559
  * Connection state machine for MCP client connections.
823
1560
  *
@@ -1823,7 +2560,7 @@ declare class MCPClientConnection {
1823
2560
  private _capabilityErrorHandler;
1824
2561
  }
1825
2562
  //#endregion
1826
- //#region src/mcp/client-storage.d.ts
2563
+ //#region src/mcp/client/storage.d.ts
1827
2564
  /**
1828
2565
  * Represents a row in the cf_agents_mcp_servers table.
1829
2566
  */
@@ -1873,7 +2610,7 @@ type PersistedMcpServerOptions = {
1873
2610
  capabilities?: ClientCapabilities;
1874
2611
  };
1875
2612
  //#endregion
1876
- //#region src/mcp/client.d.ts
2613
+ //#region src/mcp/client/index.d.ts
1877
2614
  type MCPAITool = {
1878
2615
  description?: string;
1879
2616
  title?: string;
@@ -1997,9 +2734,14 @@ type MCPClientElicitationHandlers = {
1997
2734
  form?: MCPClientElicitationHandler;
1998
2735
  url?: MCPClientElicitationHandler;
1999
2736
  };
2737
+ /** Dependencies used by {@link MCPClientManager} across Durable Object wakes. */
2000
2738
  type MCPClientManagerOptions = {
2001
- storage: DurableObjectStorage;
2002
- createAuthProvider?: (callbackUrl: string) => AgentMcpOAuthProvider;
2739
+ /**
2740
+ * Runtime bindings used to restore persisted RPC MCP connections.
2741
+ * Required when the durable catalog contains `rpc://` servers.
2742
+ */
2743
+ readonly env?: Cloudflare.Env /** Construct the OAuth provider used for a persisted HTTP server. */;
2744
+ readonly createAuthProvider?: (callbackUrl: string) => AgentMcpOAuthProvider;
2003
2745
  };
2004
2746
  /**
2005
2747
  * Filter options for scoping tools, prompts, resources, and resource templates
@@ -2015,19 +2757,21 @@ type MCPServerFilter = {
2015
2757
  state?: MCPConnectionState | MCPConnectionState[];
2016
2758
  };
2017
2759
  /**
2018
- * Utility class that aggregates multiple MCP clients into one
2760
+ * A Durable Object capability that persists and aggregates MCP client
2761
+ * connections. Installing it directly on a Lifecycle (outside `agent.mcp`)
2762
+ * is experimental: that capability surface may change before stabilizing.
2019
2763
  */
2020
- declare class MCPClientManager {
2021
- private _name;
2022
- private _version;
2764
+ declare class MCPClientManager extends LifecycleCapability {
2765
+ private readonly _name;
2766
+ private readonly _version;
2023
2767
  mcpConnections: Record<string, MCPClientConnection>;
2024
2768
  /** Cache only the current catalog so old schema graphs are not retained. */
2025
2769
  private readonly _aiToolSchemas;
2026
2770
  private _didWarnAboutUnstableGetAITools;
2027
2771
  private _oauthCallbackConfig?;
2028
2772
  private _connectionDisposables;
2029
- private _storage;
2030
- private _createAuthProviderFn?;
2773
+ private readonly _env;
2774
+ private readonly _createAuthProviderFn;
2031
2775
  private _isRestored;
2032
2776
  private _pendingConnections;
2033
2777
  private _elicitationHandlers?;
@@ -2041,15 +2785,22 @@ declare class MCPClientManager {
2041
2785
  */
2042
2786
  readonly onServerStateChanged: Event<void>;
2043
2787
  /**
2044
- * @param _name Name of the MCP client
2045
- * @param _version Version of the MCP Client
2046
- * @param options Storage adapter for persisting MCP server state
2788
+ * Construct a reusable Durable Object MCP client capability.
2789
+ *
2790
+ * @param _name - MCP client implementation name sent during negotiation.
2791
+ * @param _version - MCP client implementation version sent during negotiation.
2792
+ * @param options - Optional runtime bindings and OAuth configuration.
2047
2793
  */
2048
2794
  constructor(
2049
2795
  _name: string,
2050
2796
  _version: string,
2051
- options: MCPClientManagerOptions
2797
+ options?: MCPClientManagerOptions
2052
2798
  );
2799
+ /** Restore persisted HTTP and RPC connections before the host handles work. */
2800
+ onStart(): Promise<void>;
2801
+ /** Intercept a registered MCP OAuth callback request. */
2802
+ onRequest(context: CapabilityRequestContext): Promise<Response | undefined>;
2803
+ private oauthCallbackResponse;
2053
2804
  /**
2054
2805
  * Scope the manager-level elicitation handler to a single connection.
2055
2806
  * Returns undefined when no handler is configured so the connection keeps
@@ -2118,15 +2869,12 @@ declare class MCPClientManager {
2118
2869
  * @internal
2119
2870
  */
2120
2871
  private createAuthProvider;
2121
- /**
2122
- * Get saved RPC servers from storage (servers with rpc:// URLs).
2123
- * These are restored separately by the Agent class since they need env bindings.
2124
- */
2872
+ /** Get saved RPC servers from storage (servers with `rpc://` URLs). */
2125
2873
  getRpcServersFromStorage(): MCPServerRow[];
2126
2874
  /**
2127
2875
  * Save an RPC server to storage for hibernation recovery.
2128
- * The bindingName is stored in server_options so the Agent can look up
2129
- * the namespace from env during restore.
2876
+ * The binding name is stored so this manager can resolve the namespace from
2877
+ * its runtime environment during restore.
2130
2878
  */
2131
2879
  saveRpcServerToStorage(
2132
2880
  id: string,
@@ -2136,12 +2884,9 @@ declare class MCPClientManager {
2136
2884
  props?: Record<string, unknown>
2137
2885
  ): void;
2138
2886
  /**
2139
- * Restore MCP server connections from storage
2140
- * This method is called on Agent initialization to restore previously connected servers.
2141
- * RPC servers (rpc:// URLs) are skipped here -- they are restored by the Agent class
2142
- * which has access to env bindings.
2887
+ * Restore persisted HTTP MCP connections.
2143
2888
  *
2144
- * @param clientName Name to use for OAuth client (typically the agent instance name)
2889
+ * @param clientName - Durable Object identity used to scope OAuth state.
2145
2890
  */
2146
2891
  restoreConnectionsFromStorage(clientName: string): Promise<void>;
2147
2892
  /**
@@ -2855,351 +3600,567 @@ declare class WorkflowRejectedError extends Error {
2855
3600
  constructor(reason?: string | undefined, workflowId?: string | undefined);
2856
3601
  }
2857
3602
  //#endregion
2858
- //#region src/index.d.ts
2859
- /**
2860
- * Structural type for Cloudflare's `send_email` binding.
2861
- * Accepts both raw MIME messages and structured builder objects.
2862
- */
2863
- type EmailSendBinding = {
2864
- send(
2865
- message:
2866
- | EmailMessage
2867
- | {
2868
- from:
2869
- | string
2870
- | {
2871
- email: string;
2872
- name?: string;
2873
- };
2874
- to: string | string[];
2875
- subject: string;
2876
- replyTo?:
2877
- | string
2878
- | {
2879
- email: string;
2880
- name?: string;
2881
- };
2882
- cc?: string | string[];
2883
- bcc?: string | string[];
2884
- headers?: Record<string, string>;
2885
- text?: string;
2886
- html?: string;
2887
- }
2888
- ): Promise<EmailSendResult>;
2889
- };
3603
+ //#region src/agent-tool-types.d.ts
3604
+ type AgentToolRunStatus =
3605
+ | "starting"
3606
+ | "running"
3607
+ | "completed"
3608
+ | "error"
3609
+ | "aborted"
3610
+ | "interrupted";
3611
+ type AgentToolTerminalStatus = Extract<
3612
+ AgentToolRunStatus,
3613
+ "completed" | "error" | "aborted" | "interrupted"
3614
+ >;
2890
3615
  /**
2891
- * Options for Agent.sendEmail()
2892
- */
2893
- type SendEmailOptions = {
2894
- binding: EmailSendBinding;
2895
- to: string | string[];
2896
- from:
2897
- | string
2898
- | {
2899
- email: string;
2900
- name?: string;
2901
- };
2902
- subject: string;
2903
- text?: string;
2904
- html?: string;
2905
- replyTo?:
2906
- | string
2907
- | {
2908
- email: string;
2909
- name?: string;
2910
- };
2911
- cc?: string | string[];
2912
- bcc?: string | string[];
2913
- inReplyTo?: string;
2914
- headers?: Record<string, string>;
2915
- secret?: string;
2916
- };
2917
- /**
2918
- * RPC request message from client
3616
+ * Machine-readable cause of an `interrupted` seal (#1630 follow-up). Lets a
3617
+ * caller branch on WHY a run was abandoned without parsing the human-readable
3618
+ * `error` prose, which is not a stable contract.
3619
+ *
3620
+ * - `no-progress` — the child went silent for a full no-progress window while
3621
+ * the parent was tailing it (genuinely stalled / hung).
3622
+ * - `window-exceeded` — a finite `agentToolReattachMaxWindowMs` ceiling elapsed
3623
+ * while the child was still non-terminal. Only fires when an integrator opts
3624
+ * into a hard wall-clock cap (the default ceiling is `Infinity`).
3625
+ * - `not-tailable` — the child runtime cannot live-tail, so the parent could
3626
+ * not re-attach to its stream to follow it to terminal.
3627
+ * - `inspect-timeout` — inspecting the child timed out during parent recovery.
3628
+ * - `inspect-failed` — inspecting the child failed during parent recovery.
3629
+ * - `recovery-deadline` — the overall parent-recovery deadline elapsed before
3630
+ * this run could be reconciled.
3631
+ * - `budget-exceeded` — a detached run's absolute `maxBudgetMs` ceiling elapsed
3632
+ * before it reached a terminal. The parent gave up watching and tore the
3633
+ * child down. Like `window-exceeded` this is a soft seal: a child that
3634
+ * completes anyway can still repair the run and re-fire the completion hook.
2919
3635
  */
2920
- type RPCRequest = {
2921
- type: "rpc";
2922
- id: string;
2923
- method: string;
2924
- args: unknown[];
2925
- };
3636
+ type AgentToolInterruptedReason =
3637
+ | "no-progress"
3638
+ | "window-exceeded"
3639
+ | "not-tailable"
3640
+ | "inspect-timeout"
3641
+ | "inspect-failed"
3642
+ | "recovery-deadline"
3643
+ | "budget-exceeded";
2926
3644
  /**
2927
- * State update message from client
3645
+ * Structured failure envelope an `agentTool()` returns when a sub-agent run
3646
+ * does not complete. Instead of an opaque error string the parent model would
3647
+ * parrot back to the user, the caller (or an orchestration harness) gets a
3648
+ * machine-readable signal:
3649
+ *
3650
+ * - `status` mirrors the underlying terminal status (`error` | `aborted` |
3651
+ * `interrupted`).
3652
+ * - `retryable` is `true` only for a transient interruption — the child was
3653
+ * reset or superseded by a deploy / parent recovery and never reached a
3654
+ * logical outcome, so re-dispatching the same run is the right move. A
3655
+ * genuine `error` or an intentional `aborted` is `false`.
3656
+ * - `error` stays human-readable for logs and UI.
2928
3657
  */
2929
- type StateUpdateMessage = {
2930
- type: MessageType.CF_AGENT_STATE;
2931
- state: unknown;
3658
+ type AgentToolFailure = {
3659
+ ok: false;
3660
+ status: Exclude<AgentToolTerminalStatus, "completed">;
3661
+ error: string;
3662
+ retryable: boolean /** Present only when `status` is `interrupted` — machine-readable cause. */;
3663
+ reason?: AgentToolInterruptedReason;
3664
+ /**
3665
+ * Present only when `status` is `interrupted`. `true` when the child facet was
3666
+ * still non-terminal (running / advancing) at the moment the parent stopped
3667
+ * waiting; `false` once the parent has torn the child down so it is no longer
3668
+ * doing work. Lets a caller decide between re-dispatching vs. reconnecting.
3669
+ */
3670
+ childStillRunning?: boolean;
2932
3671
  };
3672
+ type AgentToolDisplayMetadata = {
3673
+ name?: string;
3674
+ icon?: string;
3675
+ } & Record<string, unknown>;
2933
3676
  /**
2934
- * RPC response message to client
3677
+ * Reserved chunk type a sub-agent emits via `reportProgress` while it runs.
3678
+ * Rides the child's own UI-message stream as a **transient** data part, so it
3679
+ * re-broadcasts to the parent's clients (via the parent's tail) and surfaces in
3680
+ * `useAgentToolEvents` without persisting into the child's stored message parts.
3681
+ * See `design/rfc-detached-agent-tools.md` §"Progress and milestone signaling".
2935
3682
  */
2936
- type RPCResponse = {
2937
- type: MessageType.RPC;
2938
- id: string;
2939
- } & (
2940
- | {
2941
- success: true;
2942
- result: unknown;
2943
- done?: false;
2944
- }
2945
- | {
2946
- success: true;
2947
- result: unknown;
2948
- done: true;
2949
- }
2950
- | {
2951
- success: false;
2952
- error: string;
2953
- }
2954
- );
3683
+ declare const AGENT_TOOL_PROGRESS_PART = "data-agent-progress";
2955
3684
  /**
2956
- * Metadata for a callable method
3685
+ * Reserved chunk type a sub-agent emits via `reportProgress({ milestone })`.
3686
+ * Unlike the ephemeral progress part this rides the child's stream as a
3687
+ * **persisted** data part, so it survives eviction, replays on drill-in, and
3688
+ * re-resolves milestone waiters. See `design/rfc-detached-agent-tools.md`.
2957
3689
  */
2958
- type CallableMetadata = {
2959
- /** Optional description of what the method does */ description?: string /** Whether the method supports streaming responses */;
2960
- streaming?: boolean;
2961
- };
3690
+ declare const AGENT_TOOL_MILESTONE_PART = "data-agent-milestone";
2962
3691
  /**
2963
- * Error class for SQL execution failures, containing the query that failed
3692
+ * Ephemeral progress signal a running sub-agent emits with `reportProgress`. The
3693
+ * well-known fields drive generic UI (a bar + status line) with no per-app
3694
+ * convention; `data` is an app-specific escape hatch that is **live-only** by
3695
+ * default (not persisted) unless `reportProgress(p, { persist: true })`. Naming a
3696
+ * `milestone` promotes the signal to the **durable** tier: it persists as one row
3697
+ * per milestone, replays, and (with `data`) is retained.
2964
3698
  */
2965
- declare class SqlError extends Error {
2966
- /** The SQL query that failed */
2967
- readonly query: string;
2968
- constructor(query: string, cause: unknown);
2969
- }
2970
- type SubAgentConnectionMeta = {
2971
- id: string;
2972
- uri: string | null;
2973
- tags: string[];
2974
- state: unknown;
2975
- requestHeaders?: [string, string][];
2976
- };
2977
- type SubAgentConnectionBridgeLike = {
2978
- send(message: string | ArrayBuffer | ArrayBufferView): void;
2979
- close(code?: number, reason?: string): void;
2980
- setState(state: unknown): unknown;
2981
- broadcast(
2982
- ownerPath: ReadonlyArray<{
2983
- className: string;
2984
- name: string;
2985
- }>,
2986
- message: string | ArrayBuffer | ArrayBufferView,
2987
- without?: string[]
2988
- ): void;
3699
+ type AgentToolProgress<T = unknown> = {
3700
+ /** 0..1 drives a progress bar. */ fraction?: number /** Human-readable status line, e.g. "Ingested 40k/80k rows". */;
3701
+ message?: string /** Coarse stage label, e.g. "scaffolding" | "deploying". */;
3702
+ phase?: string;
3703
+ /**
3704
+ * Present a **durable** milestone: persisted, replayable, and surfaced as a
3705
+ * distinct row in `AgentToolRunState.milestones` / `inspectAgentToolRun`. Use
3706
+ * for named phase boundaries ("schema-ready", "preview-ready", "deployed").
3707
+ */
3708
+ milestone?: string /** App-specific payload; live-only for progress, persisted for milestones. */;
3709
+ data?: T;
2989
3710
  };
2990
- declare class SubAgentConnectionBridge
2991
- extends RpcTarget
2992
- implements SubAgentConnectionBridgeLike
2993
- {
2994
- #private;
2995
- constructor(
2996
- connection: Connection,
2997
- broadcast?: (
2998
- ownerPath: ReadonlyArray<{
2999
- className: string;
3000
- name: string;
3001
- }>,
3002
- message: string | ArrayBuffer | ArrayBufferView,
3003
- without?: string[]
3004
- ) => void
3005
- );
3006
- send(message: string | ArrayBuffer | ArrayBufferView): void;
3007
- close(code?: number, reason?: string): void;
3008
- setState(state: unknown): unknown;
3009
- broadcast(
3010
- ownerPath: ReadonlyArray<{
3011
- className: string;
3012
- name: string;
3013
- }>,
3014
- message: string | ArrayBuffer | ArrayBufferView,
3015
- without?: string[]
3016
- ): void;
3017
- }
3018
3711
  /**
3019
- * Constructor type for a sub-agent class.
3020
- * Used by {@link Agent.subAgent} to reference the child class
3021
- * via `ctx.exports`.
3022
- *
3023
- * The class name (`cls.name`) must match the export name in the
3024
- * worker entry point — re-exports under a different name
3025
- * (e.g. `export { Foo as Bar }`) are not supported.
3712
+ * A durable milestone a sub-agent reached, projected onto `AgentToolRunState`
3713
+ * and `inspectAgentToolRun`. `sequence` is monotonic per run so replay/live
3714
+ * races dedupe on `(runId, sequence)`.
3026
3715
  */
3027
- type SubAgentClass<T extends Agent = Agent> = {
3028
- new (ctx: DurableObjectState, env: never): T;
3716
+ type AgentToolMilestone = {
3717
+ name: string /** Monotonic per-run ordinal; dedupe key for replay vs live races. */;
3718
+ sequence: number /** Epoch ms the milestone was reached. */;
3719
+ at: number /** App-specific payload carried with the milestone (persisted). */;
3720
+ data?: unknown;
3029
3721
  };
3030
3722
  /**
3031
- * Wraps `T` in a `Promise` unless it already is one.
3032
- */
3033
- type Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;
3034
- /**
3035
- * A typed RPC stub for a sub-agent. Exposes all public instance methods
3036
- * as callable RPC methods with Promise-wrapped return types.
3037
- *
3038
- * Methods inherited from `Agent` / `Server` / `DurableObject` internals
3039
- * are excluded — only user-defined methods on the subclass are exposed.
3723
+ * Latest progress snapshot persisted on the child run row and surfaced through
3724
+ * `inspectAgentToolRun` + `AgentToolRunState`. Only the safe-to-inspect fields
3725
+ * are retained by default; `at` is the emit timestamp (drives the resetting
3726
+ * no-progress budget).
3040
3727
  */
3041
- type SubAgentStub<T extends Agent> = {
3042
- [K in keyof T as K extends keyof Agent
3043
- ? never
3044
- : T[K] extends (...args: never[]) => unknown
3045
- ? K
3046
- : never]: T[K] extends (...args: infer A) => infer R
3047
- ? (...args: A) => Promisify<R>
3048
- : never;
3728
+ type AgentToolProgressSnapshot = {
3729
+ fraction?: number;
3730
+ message?: string;
3731
+ phase?: string;
3732
+ /**
3733
+ * Set when this signal was a durable milestone (`reportProgress({ milestone })`).
3734
+ * Lets an `onProgress` consumer branch on milestone vs. ephemeral progress.
3735
+ */
3736
+ milestone?: string /** Epoch ms of the latest signal. */;
3737
+ at: number /** Present only when the emitter opted into persisting `data`. */;
3738
+ data?: unknown;
3049
3739
  };
3050
- /**
3051
- * Decorator that marks a method as callable by clients
3052
- * @param metadata Optional metadata about the callable method
3053
- */
3054
- declare function callable(
3055
- metadata?: CallableMetadata
3056
- ): <This, Args extends unknown[], Return>(
3057
- target: (this: This, ...args: Args) => Return,
3058
- _context: ClassMethodDecoratorContext
3059
- ) => (this: This, ...args: Args) => Return;
3060
- /**
3061
- * Decorator that marks a method as callable by clients
3062
- * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
3063
- * @param metadata Optional metadata about the callable method
3064
- */
3065
- declare const unstable_callable: (
3066
- metadata?: CallableMetadata
3067
- ) => <This, Args extends unknown[], Return>(
3068
- target: (this: This, ...args: Args) => Return,
3069
- _context: ClassMethodDecoratorContext
3070
- ) => (this: This, ...args: Args) => Return;
3071
- type QueueItem<T = string> = {
3072
- id: string;
3073
- payload: T;
3074
- callback: keyof Agent<Cloudflare.Env>;
3075
- created_at: number;
3076
- retry?: RetryOptions;
3740
+ type AgentToolRunInfo = {
3741
+ runId: string;
3742
+ parentToolCallId?: string;
3743
+ agentType: string;
3744
+ inputPreview?: unknown;
3745
+ status: AgentToolRunStatus;
3746
+ display?: AgentToolDisplayMetadata;
3747
+ /**
3748
+ * Caller-controlled `metadata.source` for chat-agent `detached.notify`
3749
+ * completions. Present only for detached notify runs that supplied one.
3750
+ */
3751
+ notifySource?: string;
3752
+ displayOrder: number;
3753
+ startedAt: number;
3754
+ completedAt?: number;
3755
+ };
3756
+ type AgentToolLifecycleResult = {
3757
+ status: AgentToolTerminalStatus;
3758
+ summary?: string;
3759
+ error?: string /** Present only when `status` is `interrupted` — machine-readable cause. */;
3760
+ reason?: AgentToolInterruptedReason;
3761
+ /**
3762
+ * Present only when `status` is `interrupted`. Whether the child facet was
3763
+ * still non-terminal when the parent stopped waiting (before any teardown).
3764
+ */
3765
+ childStillRunning?: boolean;
3077
3766
  };
3078
3767
  /**
3079
- * Represents a scheduled task within an Agent
3080
- * @template T Type of the payload data
3768
+ * Configuration for a detached ("background") agent-tool run. See
3769
+ * `design/rfc-detached-agent-tools.md`.
3770
+ *
3771
+ * Callbacks are referenced by **method name** on the dispatching agent (the same
3772
+ * durable, eviction-surviving pattern as `Agent.schedule`) — never closures,
3773
+ * which cannot be rehydrated after the Durable Object is evicted.
3774
+ *
3775
+ * `Self` is threaded from `runAgentTool(cls, options)` so the method names are
3776
+ * type-checked against the calling agent's own methods.
3081
3777
  */
3082
- type Schedule<T = string> = {
3083
- /** Unique identifier for the schedule */ id: string /** Name of the method to be called */;
3084
- callback: string /** Data to be passed to the callback */;
3085
- payload: T /** Retry options for callback execution */;
3086
- retry?: RetryOptions;
3087
- } & (
3088
- | {
3089
- /** Type of schedule for one-time execution at a specific time */ type: "scheduled" /** Timestamp when the task should execute */;
3090
- time: number;
3091
- }
3092
- | {
3093
- /** Type of schedule for delayed execution */ type: "delayed" /** Timestamp when the task should execute */;
3094
- time: number /** Number of seconds to delay execution */;
3095
- delayInSeconds: number;
3096
- }
3097
- | {
3098
- /** Type of schedule for recurring execution based on cron expression */ type: "cron" /** Timestamp for the next execution */;
3099
- time: number /** Cron expression defining the schedule */;
3100
- cron: string;
3101
- }
3102
- | {
3103
- /** Type of schedule for recurring execution at fixed intervals */ type: "interval" /** Timestamp for the next execution */;
3104
- time: number /** Number of seconds between executions */;
3105
- intervalSeconds: number;
3106
- }
3107
- );
3108
- type ScheduleStorageRow = {
3109
- id: string;
3110
- callback: string;
3111
- payload: string;
3112
- type: "scheduled" | "delayed" | "cron" | "interval";
3113
- time: number;
3114
- delayInSeconds?: number;
3115
- cron?: string;
3116
- intervalSeconds?: number;
3117
- retry?: RetryOptions;
3118
- running?: number;
3119
- execution_started_at?: number | null;
3120
- retry_options?: string | null;
3121
- owner_path?: string | null;
3122
- owner_path_key?: string | null;
3123
- };
3124
- type DetachedReconcilePayload = {
3125
- cadenceIndex?: number;
3778
+ type DetachedAgentToolConfig<Self = Record<string, unknown>> = {
3779
+ /**
3780
+ * Method invoked once per terminal delivery. Branch on `result.status`:
3781
+ * `"completed" | "error" | "aborted" | "interrupted"`. A budget give-up
3782
+ * arrives as `status: "interrupted"` with `reason: "budget-exceeded"`; because
3783
+ * `interrupted` is soft, a child that later completes can fire the hook again
3784
+ * with `"completed"`, so a give-up never hides a late real result. Make the
3785
+ * handler idempotent.
3786
+ */
3787
+ onFinish?: Extract<keyof Self, string>;
3788
+ /**
3789
+ * Absolute safety ceiling a backstop against a child that runs forever. On
3790
+ * expiry the parent gives up watching (delivers `onFinish` with
3791
+ * `interrupted` / `budget-exceeded`) and tears the child down. Defaults to the
3792
+ * parent-level `detachedMaxBudgetMs`.
3793
+ */
3794
+ maxBudgetMs?: number;
3795
+ /**
3796
+ * Per-run override of the resetting no-progress window (ms). Once the child
3797
+ * emits its first `reportProgress`, the parent gives up if it then goes silent
3798
+ * for this long (resets on each signal). Defaults to the parent-level
3799
+ * `detachedNoProgressBudgetMs` (1h). `0`/`Infinity` disables it.
3800
+ */
3801
+ noProgressBudgetMs?: number;
3802
+ /**
3803
+ * Chat-agent convenience (`@cloudflare/think` / `AIChatAgent`): when the run
3804
+ * finishes, inject a message into the chat so the model can react to the
3805
+ * result, instead of you wiring `onFinish` by hand. Sugar that auto-targets
3806
+ * the agent's `_cfDetachedNotifyFinish` hook; ignored on a base `Agent` that
3807
+ * does not implement it, and ignored when `onFinish` is also set (an explicit
3808
+ * `onFinish` wins). Pass `{ source }` to fit the injected message into your
3809
+ * app's existing metadata taxonomy. Override `formatDetachedCompletion()` to
3810
+ * customize the injected text.
3811
+ */
3812
+ notify?:
3813
+ | boolean
3814
+ | {
3815
+ source?: string;
3816
+ };
3817
+ /**
3818
+ * Chat-agent convenience: milestone names that, when the detached run reaches
3819
+ * them, surface an idempotent synthetic message in the chat BEFORE the run
3820
+ * finishes. Each `(runId, name)` fires at most once (idempotency-keyed),
3821
+ * whether observed live or reconciled after eviction. Override the wording via
3822
+ * `formatDetachedMilestone()`. Requires a chat host (`@cloudflare/think`); a
3823
+ * no-op on a base `Agent`.
3824
+ *
3825
+ * Two delivery modes (the string-array shorthand defaults to `"narrate"`):
3826
+ * - `"narrate"` (default) — inject a synthetic **assistant** message directly
3827
+ * (no inference): a cheap, honest status line ("Found 2 sources…") that does
3828
+ * not trigger a model turn. Best for pure progress narration.
3829
+ * - `"react"` — inject a **user-role** turn so the model responds to the
3830
+ * milestone (steer, start dependent work, narrate with context). Costs a
3831
+ * model turn. Opt in for milestones the agent should *act on*.
3832
+ */
3833
+ onMilestones?:
3834
+ | string[]
3835
+ | {
3836
+ names: string[];
3837
+ mode?: "react" | "narrate";
3838
+ };
3126
3839
  };
3127
- type ScheduleCriteria = {
3128
- id?: string;
3129
- type?: "scheduled" | "delayed" | "cron" | "interval";
3130
- timeRange?: {
3131
- start?: Date;
3132
- end?: Date;
3133
- };
3840
+ type RunAgentToolOptions<Input = unknown, Self = Record<string, unknown>> = {
3841
+ input: Input;
3842
+ runId?: string;
3843
+ parentToolCallId?: string;
3844
+ displayOrder?: number;
3845
+ signal?: AbortSignal;
3846
+ inputPreview?: unknown;
3847
+ display?: AgentToolDisplayMetadata;
3848
+ /**
3849
+ * Run the sub-agent **detached**: dispatch it, let the current turn continue,
3850
+ * and (optionally) get a durable callback when it finishes. `true` is
3851
+ * fire-and-forget (observe via `agent-tool-event` frames + the global
3852
+ * `onAgentToolFinish` hook); an object adds the targeted, eviction-surviving
3853
+ * `onFinish` callback. A detached run does NOT inherit `options.signal` — it
3854
+ * must outlive the spawning turn; cancel it explicitly via `cancelAgentTool`.
3855
+ */
3856
+ detached?: boolean | DetachedAgentToolConfig<Self>;
3134
3857
  };
3135
3858
  /**
3136
- * Context passed to the `runFiber` callback. Provides checkpoint
3137
- * and identity for durable execution.
3859
+ * Result of dispatching a detached run. Returns immediately after dispatch
3860
+ * rather than after completion.
3138
3861
  */
3139
- type FiberContext = {
3140
- /** Unique identifier for this fiber execution. */ id: string /** Cooperative cancellation signal for managed fiber callers. */;
3141
- signal: AbortSignal /** Checkpoint data during execution. Synchronous SQLite write. */;
3142
- stash(
3143
- data: unknown
3144
- ): void /** Currently null during execution; recovered snapshots are passed to onFiberRecovered(). */;
3145
- snapshot: unknown | null;
3862
+ type DetachedRunAgentToolResult = {
3863
+ runId: string;
3864
+ agentType: string;
3865
+ /**
3866
+ * `"running"` on a successful dispatch; `"error"` if dispatch itself failed
3867
+ * (e.g. the `maxConcurrentAgentTools` cap was exceeded rejected
3868
+ * synchronously, no child started, no callback wired).
3869
+ */
3870
+ status: "running" | "error";
3871
+ error?: string;
3146
3872
  };
3147
- type FiberStatus =
3148
- | "pending"
3149
- | "running"
3150
- | "completed"
3151
- | "aborted"
3152
- | "interrupted"
3153
- | "error";
3154
- type StartFiberOptions = {
3155
- fiberId?: string;
3156
- idempotencyKey?: string;
3157
- metadata?: Record<string, unknown>;
3158
- waitForCompletion?: boolean;
3873
+ type RunAgentToolResult<Output = unknown> = {
3874
+ runId: string;
3875
+ agentType: string;
3876
+ status: AgentToolTerminalStatus;
3877
+ output?: Output;
3878
+ summary?: string;
3879
+ error?: string;
3880
+ /**
3881
+ * Present only when `status` is `interrupted` — a machine-readable cause so
3882
+ * callers don't pattern-match the `error` prose (#1630 follow-up).
3883
+ */
3884
+ reason?: AgentToolInterruptedReason;
3885
+ /**
3886
+ * Present only when `status` is `interrupted`. `true` when the child facet was
3887
+ * still non-terminal (running / advancing) at the moment the parent stopped
3888
+ * waiting and before any teardown; `false` once the parent has torn the child
3889
+ * down so it is no longer doing work.
3890
+ */
3891
+ childStillRunning?: boolean;
3159
3892
  };
3160
- type FiberInspection = {
3161
- fiberId: string;
3162
- name: string;
3163
- idempotencyKey?: string;
3164
- status: FiberStatus;
3165
- snapshot?: unknown;
3893
+ type ChatCapableAgentClass<T extends Agent = Agent> = DynamicAgentClass<T>;
3894
+ type AgentToolRunInspection<Output = unknown> = {
3895
+ runId: string;
3896
+ status: Exclude<AgentToolRunStatus, "interrupted">;
3897
+ requestId?: string;
3898
+ streamId?: string;
3899
+ output?: Output;
3900
+ summary?: string;
3166
3901
  error?: string;
3167
- metadata?: Record<string, unknown>;
3168
- createdAt: number;
3169
- startedAt?: number;
3170
- settledAt?: number;
3902
+ startedAt: number;
3903
+ completedAt?: number;
3904
+ /**
3905
+ * Latest progress snapshot the child has persisted, so a rehydrated parent
3906
+ * (recovery / backbone reconcile) can reconstruct "where is this run" and
3907
+ * reset the resetting no-progress budget without having tailed the live
3908
+ * stream. Absent until the child emits its first `reportProgress`.
3909
+ */
3910
+ progress?: AgentToolProgressSnapshot;
3911
+ /**
3912
+ * Durable milestones the child has persisted, ordered by `sequence`. Lets a
3913
+ * rehydrated parent (recovery / backbone reconcile) replay milestone-gated
3914
+ * work and milestone notifications without having observed the live stream.
3915
+ */
3916
+ milestones?: AgentToolMilestone[];
3171
3917
  };
3172
- type StartFiberResult = FiberInspection & {
3173
- accepted: boolean;
3918
+ type AgentToolStoredChunk = {
3919
+ sequence: number;
3920
+ body: string;
3174
3921
  };
3175
- type FiberRecoveryResult =
3922
+ type AgentToolChildAdapter<Input = unknown, Output = unknown> = {
3923
+ startAgentToolRun(
3924
+ input: Input,
3925
+ options: {
3926
+ runId: string;
3927
+ signal?: AbortSignal;
3928
+ }
3929
+ ): Promise<AgentToolRunInspection<Output>>;
3930
+ cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
3931
+ inspectAgentToolRun(
3932
+ runId: string
3933
+ ): Promise<AgentToolRunInspection<Output> | null>;
3934
+ getAgentToolChunks(
3935
+ runId: string,
3936
+ options?: {
3937
+ afterSequence?: number;
3938
+ }
3939
+ ): Promise<AgentToolStoredChunk[]>;
3940
+ tailAgentToolRun?(
3941
+ runId: string,
3942
+ options?: {
3943
+ afterSequence?: number;
3944
+ signal?: AbortSignal;
3945
+ }
3946
+ ): Promise<ReadableStream<AgentToolStoredChunk>>;
3947
+ };
3948
+ type AgentToolEvent =
3176
3949
  | {
3177
- status: "completed";
3178
- snapshot?: unknown;
3179
- metadata?: Record<string, unknown>;
3950
+ kind: "started";
3951
+ runId: string;
3952
+ agentType: string;
3953
+ inputPreview?: unknown;
3954
+ order: number;
3955
+ display?: AgentToolDisplayMetadata;
3180
3956
  }
3181
3957
  | {
3182
- status: "error";
3183
- error?: unknown;
3184
- snapshot?: unknown;
3958
+ kind: "chunk";
3959
+ runId: string;
3960
+ body: string;
3185
3961
  }
3186
3962
  | {
3187
- status: "aborted";
3188
- reason?: string;
3189
- snapshot?: unknown;
3963
+ kind: "finished";
3964
+ runId: string;
3965
+ summary: string;
3190
3966
  }
3191
3967
  | {
3192
- status: "interrupted";
3968
+ kind: "error";
3969
+ runId: string;
3970
+ error: string;
3971
+ }
3972
+ | {
3973
+ kind: "aborted";
3974
+ runId: string;
3193
3975
  reason?: string;
3194
- snapshot?: unknown;
3976
+ }
3977
+ | {
3978
+ kind: "interrupted";
3979
+ runId: string;
3980
+ error: string /** Machine-readable cause of the interrupt (#1630 follow-up). */;
3981
+ reason?: AgentToolInterruptedReason;
3982
+ /**
3983
+ * Whether the child facet was still non-terminal when the parent stopped
3984
+ * waiting (before any teardown). Lets a UI distinguish a still-running
3985
+ * child from one the parent has torn down.
3986
+ */
3987
+ childStillRunning?: boolean;
3195
3988
  };
3196
- type ListFibersOptions = {
3197
- status?: FiberStatus | FiberStatus[];
3198
- name?: string;
3199
- limit?: number;
3200
- };
3201
- type DeleteFibersOptions = {
3202
- status?: FiberStatus | FiberStatus[];
3989
+ type AgentToolEventMessage = {
3990
+ type: "agent-tool-event";
3991
+ parentToolCallId?: string;
3992
+ sequence: number;
3993
+ replay?: true;
3994
+ event: AgentToolEvent;
3995
+ };
3996
+ type AgentToolRunPart = {
3997
+ type: string;
3998
+ };
3999
+ type AgentToolRunState<Part extends AgentToolRunPart = AgentToolRunPart> = {
4000
+ runId: string;
4001
+ agentType: string;
4002
+ parentToolCallId?: string;
4003
+ inputPreview?: unknown;
4004
+ order: number;
4005
+ display?: AgentToolDisplayMetadata;
4006
+ status: "running" | "completed" | "error" | "aborted" | "interrupted";
4007
+ /**
4008
+ * Message parts reconstructed from the child agent's streamed chunks.
4009
+ *
4010
+ * The default stays framework-neutral so importing `agents` does not require
4011
+ * an AI SDK peer. AI SDK consumers can use
4012
+ * `AgentToolRunState<UIMessage["parts"][number]>` when they need its exact
4013
+ * discriminated union.
4014
+ */
4015
+ parts: Part[];
4016
+ summary?: string;
4017
+ error?: string;
4018
+ /**
4019
+ * Present only when `status` is `interrupted` — machine-readable cause and
4020
+ * whether the child is still running, mirrored from the wire event so a UI
4021
+ * can render the reason without parsing `error` (#1630 follow-up).
4022
+ */
4023
+ reason?: AgentToolInterruptedReason;
4024
+ childStillRunning?: boolean;
4025
+ /**
4026
+ * Latest progress snapshot, projected from the child's transient
4027
+ * `data-agent-progress` signals so a UI can render a bar / ETA / phase label
4028
+ * for a running (especially detached / background) run without drilling in.
4029
+ */
4030
+ progress?: AgentToolProgressSnapshot;
4031
+ /**
4032
+ * Durable milestones the run has reached, ordered by `sequence` (deduped
4033
+ * across replay/live races). Drives milestone chips / a phase timeline.
4034
+ */
4035
+ milestones?: AgentToolMilestone[];
4036
+ subAgent: {
4037
+ agent: string;
4038
+ name: string;
4039
+ };
4040
+ };
4041
+ type AgentToolEventState<Part extends AgentToolRunPart = AgentToolRunPart> = {
4042
+ runsById: Record<string, AgentToolRunState<Part>>;
4043
+ runsByToolCallId: Record<string, AgentToolRunState<Part>[]>;
4044
+ unboundRuns: AgentToolRunState<Part>[];
4045
+ };
4046
+ //#endregion
4047
+ //#region src/index.d.ts
4048
+ /**
4049
+ * RPC request message from client
4050
+ */
4051
+ type RPCRequest = {
4052
+ type: "rpc";
4053
+ id: string;
4054
+ method: string;
4055
+ args: unknown[];
4056
+ };
4057
+ /**
4058
+ * State update message from client
4059
+ */
4060
+ type StateUpdateMessage = {
4061
+ type: MessageType.CF_AGENT_STATE;
4062
+ state: unknown;
4063
+ };
4064
+ /**
4065
+ * RPC response message to client
4066
+ */
4067
+ type RPCResponse = {
4068
+ type: MessageType.RPC;
4069
+ id: string;
4070
+ } & (
4071
+ | {
4072
+ success: true;
4073
+ result: unknown;
4074
+ done?: false;
4075
+ }
4076
+ | {
4077
+ success: true;
4078
+ result: unknown;
4079
+ done: true;
4080
+ }
4081
+ | {
4082
+ success: false;
4083
+ error: string;
4084
+ }
4085
+ );
4086
+ type QueueItem<T = string> = {
4087
+ id: string;
4088
+ payload: T;
4089
+ callback: keyof Agent<Cloudflare.Env>;
4090
+ created_at: number;
4091
+ retry?: RetryOptions;
4092
+ };
4093
+ type DetachedReconcilePayload = {
4094
+ cadenceIndex?: number;
4095
+ };
4096
+ /**
4097
+ * Context passed to the `runFiber` callback. Provides checkpoint
4098
+ * and identity for durable execution.
4099
+ */
4100
+ type FiberContext = {
4101
+ /** Unique identifier for this fiber execution. */ id: string /** Cooperative cancellation signal for managed fiber callers. */;
4102
+ signal: AbortSignal /** Checkpoint data during execution. Synchronous SQLite write. */;
4103
+ stash(
4104
+ data: unknown
4105
+ ): void /** Currently null during execution; recovered snapshots are passed to onFiberRecovered(). */;
4106
+ snapshot: unknown | null;
4107
+ };
4108
+ type FiberStatus =
4109
+ | "pending"
4110
+ | "running"
4111
+ | "completed"
4112
+ | "aborted"
4113
+ | "interrupted"
4114
+ | "error";
4115
+ type StartFiberOptions = {
4116
+ fiberId?: string;
4117
+ idempotencyKey?: string;
4118
+ metadata?: Record<string, unknown>;
4119
+ waitForCompletion?: boolean;
4120
+ };
4121
+ type FiberInspection = {
4122
+ fiberId: string;
4123
+ name: string;
4124
+ idempotencyKey?: string;
4125
+ status: FiberStatus;
4126
+ snapshot?: unknown;
4127
+ error?: string;
4128
+ metadata?: Record<string, unknown>;
4129
+ createdAt: number;
4130
+ startedAt?: number;
4131
+ settledAt?: number;
4132
+ };
4133
+ type StartFiberResult = FiberInspection & {
4134
+ accepted: boolean;
4135
+ };
4136
+ type FiberRecoveryResult =
4137
+ | {
4138
+ status: "completed";
4139
+ snapshot?: unknown;
4140
+ metadata?: Record<string, unknown>;
4141
+ }
4142
+ | {
4143
+ status: "error";
4144
+ error?: unknown;
4145
+ snapshot?: unknown;
4146
+ }
4147
+ | {
4148
+ status: "aborted";
4149
+ reason?: string;
4150
+ snapshot?: unknown;
4151
+ }
4152
+ | {
4153
+ status: "interrupted";
4154
+ reason?: string;
4155
+ snapshot?: unknown;
4156
+ };
4157
+ type ListFibersOptions = {
4158
+ status?: FiberStatus | FiberStatus[];
4159
+ name?: string;
4160
+ limit?: number;
4161
+ };
4162
+ type DeleteFibersOptions = {
4163
+ status?: FiberStatus | FiberStatus[];
3203
4164
  settledBefore?: Date;
3204
4165
  limit?: number;
3205
4166
  };
@@ -3329,8 +4290,7 @@ type AddRpcMcpServerOptions = {
3329
4290
  * Child classes can override specific options without spreading.
3330
4291
  */
3331
4292
  declare const DEFAULT_AGENT_STATIC_OPTIONS: {
3332
- /** Whether the Agent should hibernate when inactive */ hibernate: boolean /** Whether to send identity (name, agent) to clients on connect */;
3333
- sendIdentityOnConnect: boolean;
4293
+ /** Whether to send identity (name, agent) to clients on connect */ sendIdentityOnConnect: boolean;
3334
4294
  /**
3335
4295
  * Timeout in seconds before a running interval schedule is considered "hung"
3336
4296
  * and force-reset. Increase this if you have callbacks that legitimately
@@ -3391,10 +4351,8 @@ declare const DEFAULT_AGENT_STATIC_OPTIONS: {
3391
4351
  * Configuration options for the Agent.
3392
4352
  * Override in subclasses via `static options`.
3393
4353
  * All fields are optional - defaults are applied at runtime.
3394
- * Note: `hibernate` defaults to `true` if not specified.
3395
4354
  */
3396
4355
  interface AgentStaticOptions {
3397
- hibernate?: boolean;
3398
4356
  sendIdentityOnConnect?: boolean;
3399
4357
  hungScheduleTimeoutSeconds?: number;
3400
4358
  /**
@@ -3488,14 +4446,10 @@ interface AgentStaticOptions {
3488
4446
  */
3489
4447
  maxAlarmMemoryLimitStrikes?: number;
3490
4448
  }
3491
- declare function getCurrentAgent<
3492
- T extends Agent<Cloudflare.Env> = Agent<Cloudflare.Env>
3493
- >(): {
3494
- agent: T | undefined;
3495
- connection: Connection | undefined;
3496
- request: Request | undefined;
3497
- email: AgentEmail | undefined;
3498
- };
4449
+ /** Compatibility alias for the lifecycle-owned current Agent accessor. */
4450
+ declare const getCurrentAgent: <
4451
+ T extends DurableObject = Agent<Cloudflare.Env>
4452
+ >() => CurrentAgentContext<T, AgentEmail>;
3499
4453
  /**
3500
4454
  * Extract string keys from Env where the value is a Workflow binding.
3501
4455
  */
@@ -3518,7 +4472,49 @@ declare class Agent<
3518
4472
  Env extends Cloudflare.Env = Cloudflare.Env,
3519
4473
  State = unknown,
3520
4474
  Props extends Record<string, unknown> = Record<string, unknown>
3521
- > extends Server<Env, Props> {
4475
+ > extends DurableObject<Env> {
4476
+ /**
4477
+ * Runtime lifecycle and reusable durable capabilities for this Agent.
4478
+ *
4479
+ * @experimental The API surface may change before stabilizing.
4480
+ */
4481
+ readonly lifecycle: Lifecycle<Env, Props>;
4482
+ /**
4483
+ * WebSocket connection subsystem. Constructed as a field initializer
4484
+ * so it exists before the constructor installs it; the handler arrows
4485
+ * defer to `this.*`, so they always hit the framework-wrapped hooks.
4486
+ * Those wrappers still open their own invocation scope even though
4487
+ * the capability's dispatch already entered one via the host invoker
4488
+ * — the inner wrap is kept because the wrapped hooks are also invoked
4489
+ * from paths that do not pass through the capability (facet bridging,
4490
+ * direct calls).
4491
+ */
4492
+ private readonly _webSockets;
4493
+ /** Run user initialization after lifecycle components have started. */
4494
+ onStart(_props?: Props): void | Promise<void>;
4495
+ /** Handle an HTTP request not claimed by a lifecycle component. */
4496
+ onRequest(_request: Request): Response | Promise<Response>;
4497
+ /** Handle a newly accepted hibernating WebSocket connection. */
4498
+ onConnect(
4499
+ _connection: Connection,
4500
+ _context: ConnectionContext
4501
+ ): void | Promise<void>;
4502
+ /** Handle a message from a hibernating WebSocket connection. */
4503
+ onMessage(_connection: Connection, _message: WSMessage): void | Promise<void>;
4504
+ /** Handle a hibernating WebSocket connection closing. */
4505
+ onClose(
4506
+ _connection: Connection,
4507
+ _code: number,
4508
+ _reason: string,
4509
+ _wasClean: boolean
4510
+ ): void | Promise<void>;
4511
+ /** Return tags persisted with a hibernating WebSocket connection. */
4512
+ getConnectionTags(
4513
+ _connection: Connection,
4514
+ _context: ConnectionContext
4515
+ ): string[] | Promise<string[]>;
4516
+ /** @internal Ensure lifecycle startup before a native RPC implementation. */
4517
+ __unsafe_ensureInitialized(props?: Props): Promise<void>;
3522
4518
  private _state;
3523
4519
  private _disposables;
3524
4520
  private _destroyed;
@@ -3538,8 +4534,6 @@ declare class Agent<
3538
4534
  /** True when this agent runs as a facet (sub-agent) inside a parent. */
3539
4535
  private _isFacet;
3540
4536
  private _protocolBroadcastExcludeIds;
3541
- private _cf_currentSubAgentBridge?;
3542
- private _cf_virtualSubAgentConnections;
3543
4537
  /**
3544
4538
  * User-facing facet name. For legacy facets this is the same as
3545
4539
  * `ctx.id.name`; path-scoped facets use an internal routing id and
@@ -3554,27 +4548,42 @@ declare class Agent<
3554
4548
  * @internal
3555
4549
  */
3556
4550
  private _parentPath;
3557
- /** True while user's onStart() is executing. Used to warn about non-idempotent schedule() calls. */
3558
- private _insideOnStart;
3559
- /** Tracks callbacks already warned about during this onStart() to avoid log spam. */
3560
- private _warnedScheduleInOnStart;
3561
4551
  /** Warn-once guard: `chatRecovery` reassigned during onStart() (too late for wake recovery). */
3562
4552
  private _warnedChatRecoveryInOnStart;
3563
4553
  /**
3564
- * Number of active keepAlive() callers. When > 0, `_scheduleNextAlarm()`
4554
+ * Number of active keepAlive() callers. When > 0, `_syncHostJobs()`
3565
4555
  * caps the next alarm at `keepAliveIntervalMs` so the DO stays alive.
3566
4556
  * Purely in-memory — lost on eviction, which is correct because the
3567
4557
  * in-memory work keepAlive was protecting is also lost.
3568
4558
  * @internal
3569
4559
  */
3570
4560
  _keepAliveRefs: number;
4561
+ /** @internal The extracted dynamic-agent (facet) machinery. */
4562
+ private _dynamicAgentsInstance;
4563
+ /** @internal */
4564
+ private get _dynamicAgents();
4565
+ /** @internal */
4566
+ private _dynamicAgentsApi;
3571
4567
  /**
3572
- * In-memory tokens for keepAlive leases acquired by facets and held
3573
- * on the root alarm owner. Lost on eviction, like `_keepAliveRefs`,
3574
- * because the in-memory work those leases were protecting is also gone.
3575
- * @internal
4568
+ * The dynamic-agents capability: facet-backed child agents that run
4569
+ * in their own isolate with their own SQLite database, colocated
4570
+ * with and supervised by this agent.
4571
+ *
4572
+ * Use dynamic agents for code whose class or lifecycle this agent
4573
+ * owns: dynamically-loaded or AI-generated code, per-run tool
4574
+ * agents, sandboxed components. For independent peers (for example
4575
+ * one Durable Object per chat), use `getAgentByName` instead.
4576
+ *
4577
+ * ```ts
4578
+ * const child = await this.dynamicAgents.get(Researcher, id);
4579
+ * await child.doWork();
4580
+ * this.dynamicAgents.abort(Researcher, id, reason);
4581
+ * await this.dynamicAgents.delete(Researcher, id);
4582
+ * ```
4583
+ *
4584
+ * @experimental The API surface may change before stabilizing.
3576
4585
  */
3577
- private _facetKeepAliveTokens;
4586
+ get dynamicAgents(): DynamicAgents;
3578
4587
  /** @internal In-memory set of fiber IDs running in this process. */
3579
4588
  private _runFiberActiveFibers;
3580
4589
  /** @internal In-memory abort controllers for managed running fibers. */
@@ -3599,6 +4608,40 @@ declare class Agent<
3599
4608
  /** @internal Edge-trigger latch for the live-detached-count warning. */
3600
4609
  private _detachedLiveCountWarned;
3601
4610
  private _ParentClass;
4611
+ /**
4612
+ * Durable scheduling capability installed into this Agent's Lifecycle.
4613
+ *
4614
+ * @experimental The API surface may change before stabilizing. Agent's
4615
+ * schedule()/scheduleEvery()/getScheduleById()/listSchedules()/
4616
+ * cancelSchedule() methods are the stable surface.
4617
+ */
4618
+ readonly scheduler: Scheduler;
4619
+ /**
4620
+ * Durable replayable execution capability installed into this Agent's
4621
+ * Lifecycle. Declare definitions on the overridable
4622
+ * {@link taskDefinitions} property and start runs with
4623
+ * `this.tasks.run(name, input, options)`.
4624
+ *
4625
+ * @experimental The API surface may change before stabilizing.
4626
+ */
4627
+ readonly tasks: Tasks;
4628
+ /**
4629
+ * Named Task definitions for this Agent, resolved lazily on every
4630
+ * dispatch. Declare as a field so the map is rebuilt on every Durable
4631
+ * Object wake — that is what lets in-flight runs resolve their persisted
4632
+ * definition names after a restart:
4633
+ *
4634
+ * ```ts
4635
+ * readonly taskDefinitions = {
4636
+ * "build-report@v1": async (input: ReportInput, step: TaskStep) => {
4637
+ * // ...
4638
+ * }
4639
+ * } satisfies TaskHandlers;
4640
+ * ```
4641
+ *
4642
+ * @experimental The API surface may change before stabilizing.
4643
+ */
4644
+ readonly taskDefinitions?: TaskHandlers;
3602
4645
  readonly mcp: MCPClientManager;
3603
4646
  /**
3604
4647
  * Initial state for the Agent
@@ -3680,6 +4723,7 @@ declare class Agent<
3680
4723
  */
3681
4724
  protected _ensureSchema(): void;
3682
4725
  constructor(ctx: AgentContext, env: Env);
4726
+ private _restoreAgentFacetContext;
3683
4727
  /**
3684
4728
  * Check for workflows referencing unknown bindings and warn with migration suggestion.
3685
4729
  */
@@ -3897,8 +4941,8 @@ declare class Agent<
3897
4941
  sendEmail(options: SendEmailOptions): Promise<EmailSendResult>;
3898
4942
  private _tryCatch;
3899
4943
  /**
3900
- * Automatically wrap custom methods with agent context
3901
- * This ensures getCurrentAgent() works in all custom methods without decorators
4944
+ * Wrap public subclass methods that may be entered outside Lifecycle, such as
4945
+ * native Durable Object RPC. Lifecycle hooks already have Agent context.
3902
4946
  */
3903
4947
  private _autoWrapCustomMethods;
3904
4948
  onError(connection: Connection, error: unknown): void | Promise<void>;
@@ -3973,87 +5017,15 @@ declare class Agent<
3973
5017
  * @returns Array of matching QueueItem objects
3974
5018
  */
3975
5019
  getQueues(key: string, value: string): QueueItem<string>[];
3976
- private _scheduleOwnerPathKey;
3977
- private _facetRunRowsForPrefix;
3978
- private _deleteFacetRunRowsForPrefix;
5020
+ private _lifecycleRouteAddress;
5021
+ private _routeLifecycleToRoot;
5022
+ private _routeLifecycleToTarget;
5023
+ /** Single native-RPC aperture for routed Lifecycle capabilities. */
5024
+ _cf_routeLifecycle(
5025
+ target: LifecycleRouteAddress | undefined,
5026
+ envelope: LifecycleRouteEnvelope
5027
+ ): Promise<unknown>;
3979
5028
  private _rootAlarmOwner;
3980
- private _cf_rootResolvesToSelf;
3981
- private _validateScheduleCallback;
3982
- /**
3983
- * Insert (or, for idempotent calls, return the existing row for) a
3984
- * schedule owned by either this top-level agent (`ownerPath === null`)
3985
- * or a descendant facet. Returns `{ schedule, created }` — `created`
3986
- * is `false` when an idempotent insert deduplicates onto an existing
3987
- * row, so callers can suppress the `schedule:create` event in that
3988
- * case to match historic semantics.
3989
- * @internal
3990
- */
3991
- private _insertScheduleForOwner;
3992
- /**
3993
- * Insert a schedule row owned by a descendant facet. Called via RPC
3994
- * from the facet's `schedule()`. Returns `{ schedule, created }`
3995
- * so the originating facet can suppress `schedule:create` on
3996
- * idempotent dedup. This method does not emit observability
3997
- * events itself.
3998
- * @internal
3999
- */
4000
- _cf_scheduleForFacet<T = string>(
4001
- ownerPath: ReadonlyArray<AgentPathStep>,
4002
- when: Date | string | number,
4003
- callback: string,
4004
- payload?: T,
4005
- options?: {
4006
- retry?: RetryOptions;
4007
- idempotent?: boolean;
4008
- }
4009
- ): Promise<{
4010
- schedule: Schedule<T>;
4011
- created: boolean;
4012
- }>;
4013
- /**
4014
- * Insert (or, for idempotent calls, return the existing row for) an
4015
- * interval schedule. Mirrors {@link _insertScheduleForOwner} —
4016
- * returns `{ schedule, created }` so callers can suppress
4017
- * `schedule:create` on dedup.
4018
- * @internal
4019
- */
4020
- private _insertIntervalScheduleForOwner;
4021
- /**
4022
- * Insert an interval schedule row owned by a descendant facet.
4023
- * Called via RPC from the facet's `scheduleEvery()`. Returns
4024
- * `{ schedule, created }` so the originating facet can suppress
4025
- * `schedule:create` on idempotent dedup. This method does not
4026
- * emit observability events itself.
4027
- * @internal
4028
- */
4029
- _cf_scheduleEveryForFacet<T = string>(
4030
- ownerPath: ReadonlyArray<AgentPathStep>,
4031
- intervalSeconds: number,
4032
- callback: string,
4033
- payload?: T,
4034
- options?: {
4035
- retry?: RetryOptions;
4036
- _idempotent?: boolean;
4037
- }
4038
- ): Promise<{
4039
- schedule: Schedule<T>;
4040
- created: boolean;
4041
- }>;
4042
- /**
4043
- * Cancel a schedule row owned by a descendant facet, scoped by
4044
- * `owner_path_key` so siblings can't reach each other's rows.
4045
- * Returns the canceled row's callback name so the originating
4046
- * facet can emit `schedule:cancel`. This method does not emit
4047
- * observability events itself.
4048
- * @internal
4049
- */
4050
- _cf_cancelScheduleForFacet(
4051
- ownerPath: ReadonlyArray<AgentPathStep>,
4052
- id: string
4053
- ): Promise<{
4054
- ok: boolean;
4055
- callback?: string;
4056
- }>;
4057
5029
  /**
4058
5030
  * Clean root-owned bookkeeping for a sub-tree of facets. This
4059
5031
  * bulk-cancels schedules whose `owner_path` starts with the given
@@ -4067,30 +5039,10 @@ declare class Agent<
4067
5039
  _cf_cleanupFacetPrefix(
4068
5040
  ownerPath: ReadonlyArray<AgentPathStep>
4069
5041
  ): Promise<void>;
4070
- private _scheduleRowToSchedule;
4071
- private _getScheduleForOwner;
4072
- private _listSchedulesForOwner;
4073
- /**
4074
- * Read a single schedule row owned by a descendant facet.
4075
- * @internal
4076
- */
4077
- _cf_getScheduleForFacet(
4078
- ownerPath: ReadonlyArray<AgentPathStep>,
4079
- id: string
4080
- ): Promise<Schedule<unknown> | undefined>;
4081
- /**
4082
- * List schedule rows owned by a descendant facet, scoped by
4083
- * `owner_path_key` so siblings remain isolated from each other.
4084
- * @internal
4085
- */
4086
- _cf_listSchedulesForFacet(
4087
- ownerPath: ReadonlyArray<AgentPathStep>,
4088
- criteria?: ScheduleCriteria
4089
- ): Promise<Schedule<unknown>[]>;
4090
5042
  /**
4091
5043
  * Acquire a root-owned keepAlive ref on behalf of a descendant facet.
4092
- * Facets share the root isolate but cannot set their own physical
4093
- * alarm, so this lets facet work use the root alarm heartbeat.
5044
+ * Facets run in separate colocated isolates but cannot set their own
5045
+ * physical alarm, so this lets facet work use the root alarm heartbeat.
4094
5046
  * @internal
4095
5047
  */
4096
5048
  _cf_acquireFacetKeepAlive(
@@ -4146,10 +5098,7 @@ declare class Agent<
4146
5098
  when: Date | string | number,
4147
5099
  callback: keyof this,
4148
5100
  payload?: T,
4149
- options?: {
4150
- retry?: RetryOptions;
4151
- idempotent?: boolean;
4152
- }
5101
+ options?: ScheduleOptions
4153
5102
  ): Promise<Schedule<T>>;
4154
5103
  /**
4155
5104
  * Schedule a task to run repeatedly at a fixed interval.
@@ -4201,7 +5150,6 @@ declare class Agent<
4201
5150
  * Unlike the deprecated synchronous {@link getSchedule}, this works inside
4202
5151
  * sub-agents by delegating to the top-level parent that owns the alarm.
4203
5152
  *
4204
- * @template T Type of the payload data
4205
5153
  * @param id ID of the scheduled task
4206
5154
  * @returns The Schedule object or undefined if not found
4207
5155
  */
@@ -4221,7 +5169,6 @@ declare class Agent<
4221
5169
  * Unlike the deprecated synchronous {@link getSchedules}, this works inside
4222
5170
  * sub-agents by delegating to the top-level parent that owns the alarm.
4223
5171
  *
4224
- * @template T Type of the payload data
4225
5172
  * @param criteria Criteria to filter schedules
4226
5173
  * @returns Array of matching Schedule objects
4227
5174
  */
@@ -4355,6 +5302,20 @@ declare class Agent<
4355
5302
  * Throws if called outside a `runFiber` callback.
4356
5303
  */
4357
5304
  stash(data: unknown): void;
5305
+ /**
5306
+ * Run `fn` inside the fiber stash context so `this.stash()` keeps working
5307
+ * for turns executing on the `tasks` capability exactly as it does inside
5308
+ * legacy `runFiber()` closures.
5309
+ * @internal
5310
+ */
5311
+ protected _withFiberStash<T>(
5312
+ context: {
5313
+ id: string;
5314
+ signal: AbortSignal;
5315
+ stash: (data: unknown) => void;
5316
+ },
5317
+ fn: () => Promise<T>
5318
+ ): Promise<T>;
4358
5319
  /**
4359
5320
  * Called when an interrupted fiber is detected after restart.
4360
5321
  * Override to implement recovery (re-invoke work, notify clients, etc.).
@@ -4396,21 +5357,6 @@ declare class Agent<
4396
5357
  _cf_checkRunFibersForFacet(
4397
5358
  ownerPath: ReadonlyArray<AgentPathStep>
4398
5359
  ): Promise<number>;
4399
- /**
4400
- * Dispatch a scheduled callback into the facet identified by
4401
- * `ownerPath`. Walks one step at a time: if `ownerPath` matches
4402
- * `selfPath`, executes the callback locally; otherwise resolves
4403
- * the next descendant facet and recurses through its own RPC.
4404
- *
4405
- * Called by the root's `alarm()` (which owns the physical alarm
4406
- * for facet-owned schedules) and by intermediate facets while
4407
- * walking down the chain.
4408
- * @internal
4409
- */
4410
- _cf_dispatchScheduledCallback(
4411
- ownerPath: ReadonlyArray<AgentPathStep>,
4412
- row: ScheduleStorageRow
4413
- ): Promise<boolean>;
4414
5360
  /**
4415
5361
  * Invoke an RPC method on this Agent or a descendant facet identified
4416
5362
  * by a root-first path. Used by AgentWorkflow to route callbacks and
@@ -4438,103 +5384,77 @@ declare class Agent<
4438
5384
  _cf_destroyDescendantFacet(
4439
5385
  targetPath: ReadonlyArray<AgentPathStep>
4440
5386
  ): Promise<void>;
4441
- private _executeScheduleCallback;
4442
5387
  /**
4443
5388
  * Whether any runFiber recovery work is still outstanding: orphaned
4444
5389
  * `cf_agents_runs` rows left by a dead process (excluding fibers currently
4445
5390
  * executing in memory, which already hold a keepAlive ref) or managed
4446
5391
  * ledger fibers stuck in a non-terminal state with no live run row.
4447
5392
  *
4448
- * Used by `_scheduleNextAlarm` to arm a follow-up alarm so multi-pass
5393
+ * Used by `_syncHostJobs` to arm a follow-up alarm so multi-pass
4449
5394
  * recovery (e.g. after a scan-deadline yield, or while retrying a throwing
4450
5395
  * recovery hook) resumes instead of starving.
4451
5396
  * @internal
4452
5397
  */
4453
5398
  private _hasPendingFiberRecovery;
4454
- private _scheduleNextAlarm;
4455
- private _scheduleNextAlarmBody;
4456
5399
  /**
4457
- * Override PartyServer's onAlarm hook as a no-op.
4458
- * Agent handles alarm logic directly in the alarm() method override,
4459
- * but super.alarm() calls onAlarm() after #ensureInitialized(),
4460
- * so we suppress the default "Implement onAlarm" warning.
4461
- */
4462
- onAlarm(): void;
4463
- /**
4464
- * Method called when an alarm fires.
4465
- * Executes any scheduled tasks that are due.
4466
- *
4467
- * Calls super.alarm() first to ensure PartyServer's #ensureInitialized()
4468
- * runs, which resolves this.name from ctx.id.name (including for
4469
- * facets, which are spawned with an explicit id so they have their
4470
- * own ctx.id.name; pre-2026-03-15 alarms fall back to the legacy
4471
- * __ps_name storage record) and calls onStart() if needed.
5400
+ * Synchronize Agent-owned host jobs with current durable state.
4472
5401
  *
4473
- * @remarks
4474
- * To schedule a task, please use the `this.schedule` method instead.
4475
- * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
4476
- */
4477
- alarm(): Promise<void>;
4478
- /**
4479
- * The alarm body: PartyServer init + due-schedule processing + housekeeping +
4480
- * next-alarm arm. Extracted from {@link alarm} so the memory-limit circuit
4481
- * breaker can wrap it at the outermost frame (see {@link alarm}).
4482
- */
4483
- private _cf_runAlarmBody;
4484
- /**
4485
- * Durable storage key for the alarm memory-limit strike counter (#1825).
5402
+ * Replaces the old pull-based `getNextAlarm()` contribution: keep-alive
5403
+ * refs hold a `cf:keep-alive` job, and fiber-recovery / facet-run state
5404
+ * holds a `cf:housekeeping` job. Every state change that used to trigger
5405
+ * an alarm recalculation now re-pushes or cancels these jobs; queue
5406
+ * mutations re-arm the physical alarm automatically.
5407
+ * @internal
4486
5408
  */
4487
- private static readonly _CF_OOM_ALARM_STRIKES_KEY;
5409
+ private _syncHostJobs;
4488
5410
  /**
4489
- * The schedule row id currently executing in the alarm loop, so the
4490
- * memory-limit circuit breaker can purge the exact looping row (#1825).
4491
- * `undefined` outside a callback (e.g. an OOM from `super.alarm()`/onStart).
5411
+ * The next wake fiber-recovery or facet-run housekeeping needs, or `null`
5412
+ * when neither has pending durable state.
4492
5413
  */
4493
- private _cf_executingScheduleRowId?;
5414
+ private _nextHousekeepingWakeMs;
5415
+ /** Lifecycle alarm callback; Agent housekeeping runs after user alarm work. */
5416
+ onAlarm(): void;
4494
5417
  /**
4495
- * The schedule-callback names whose alarm rows drive a recovery loop that can
4496
- * deterministically OOM. The base agent has none; chat hosts (`Think`,
4497
- * `AIChatAgent`) override this to return their recovery continuation callbacks
4498
- * so the circuit breaker can surgically back them off / purge them WITHOUT
4499
- * disturbing unrelated scheduled tasks. See {@link _cf_handleAlarmMemoryLimitReset}.
5418
+ * Drive one Agent-owned host job from the Lifecycle queue.
5419
+ * @internal Dispatched by Lifecycle's alarm event loop; extensions add
5420
+ * job fns through {@link _onHostJob}.
4500
5421
  */
4501
- protected _cf_recoveryAlarmCallbacks(): string[];
5422
+ onJob(
5423
+ context: LifecycleJobContext
5424
+ ): LifecycleJobOutcome | void | Promise<LifecycleJobOutcome | void>;
4502
5425
  /**
4503
- * Hook for a host to terminalize ("seal") any in-flight recovery work as an
4504
- * out-of-memory exhaustion when the alarm circuit breaker trips at its strike
4505
- * budget (#1825). Runs at the outermost alarm frame (post-unwind, so writes
4506
- * can land). Default: no-op. Chat hosts override to fire `onExhausted` + the
4507
- * terminal banner and persist the sealed incident.
5426
+ * @internal Dispatch one host job fn. Agent extensions (Think) override
5427
+ * this to add fns and delegate unknown ones to `super`.
4508
5428
  */
4509
- protected _cf_sealMemoryLimitedRecovery(): Promise<void>;
5429
+ protected _onHostJob(
5430
+ fn: string,
5431
+ _context: LifecycleJobContext
5432
+ ): LifecycleJobOutcome | void | Promise<LifecycleJobOutcome | void>;
4510
5433
  /**
4511
- * Clear the durable memory-limit strike counter after a clean alarm so the
4512
- * circuit breaker counts CONSECUTIVE resets rather than lifetime ones
4513
- * (#1825). Reads first (cheap, usually cached) and only writes when a strike
4514
- * is actually recorded, so the common no-strike path costs no write.
4515
- * Best-effort: a stale strike only costs one extra tolerated spike later.
5434
+ * Apply host policy after the alarm memory-limit breaker records a strike.
5435
+ *
5436
+ * New chat hosts override this hook directly. The sealed-only fallback keeps
5437
+ * `agents` 0.23 compatible with already-published chat packages whose peer
5438
+ * ranges accept it but which implement only the former
5439
+ * `_cf_sealMemoryLimitedRecovery` template method. Queue membership remains
5440
+ * job-row policy; this invokes terminalization only and can be removed once
5441
+ * old chat releases no longer accept the current `agents` range.
5442
+ *
5443
+ * @internal
4516
5444
  */
4517
- private _cf_clearAlarmMemoryLimitStrikes;
5445
+ protected onAlarmMemoryLimit(context: MemoryLimitContext): Promise<void>;
4518
5446
  /**
4519
- * Alarm-boundary circuit breaker for Durable Object memory-limit resets
4520
- * (#1825). The in-DO recovery budgets (`chatRecovery.maxOomRetries` /
4521
- * `maxRecoveryWork`) only engage if their code runs AND its writes land; a
4522
- * severe OOM can defeat both — thrown before the budget runs (boot hydration),
4523
- * or its own small writes also OOM under memory pressure. In that case the
4524
- * error reaches {@link alarm} and, unhandled, the platform auto-retries the
4525
- * alarm indefinitely (re-running the doomed, billable turn each cycle).
5447
+ * Run Lifecycle's alarm event loop after the pending-destroy preamble.
4526
5448
  *
4527
- * This runs at the OUTERMOST frame: the heavy turn has unwound and GC has
4528
- * reclaimed its footprint, so the small writes here can land where mid-turn
4529
- * ones (e.g. give-up's incident read) OOMed. A durable strike counter tolerates
4530
- * a few resets (a transient spike may clear), backing off the recovery rows so
4531
- * the retry is not a hot loop. At the `maxAlarmMemoryLimitStrikes` budget it
4532
- * seals the recovery work and purges the looping rows so the loop — and the
4533
- * bill stops. Each step is best-effort: even these tiny writes can OOM, but
4534
- * swallowing (not re-throwing) still halts the platform's auto-retry, and a
4535
- * later wake re-arms legitimate schedules.
5449
+ * The alarm memory-limit circuit breaker (#1825) lives inside
5450
+ * `Lifecycle.alarm()`; capabilities and hosts opt into extra domain
5451
+ * policy via their `onMemoryLimit` / `onAlarmMemoryLimit` hooks and the
5452
+ * `recoveryLoop` schedule option.
5453
+ *
5454
+ * @remarks Use `this.schedule()` for named Agent callbacks. Reusable durable
5455
+ * work belongs in a capability that pushes jobs and implements `onJob()`.
4536
5456
  */
4537
- private _cf_handleAlarmMemoryLimitReset;
5457
+ alarm(): Promise<void>;
4538
5458
  /**
4539
5459
  * Intercept incoming HTTP/WS requests whose URL contains a
4540
5460
  * `/sub/{child-class}/{child-name}` marker and forward them to
@@ -4543,9 +5463,9 @@ declare class Agent<
4543
5463
  * Response, the framework resolves the facet and hands the
4544
5464
  * request off.
4545
5465
  *
4546
- * After a WebSocket upgrade completes, subsequent frames route
4547
- * directly to the child the parent is only on the path for the
4548
- * initial request.
5466
+ * The parent owns an upgraded WebSocket for its lifetime. Subsequent
5467
+ * frames wake the root parent, which forwards them to the child over
5468
+ * RPC and routes replies back to the native socket.
4549
5469
  *
4550
5470
  * @experimental The API surface may change before stabilizing.
4551
5471
  */
@@ -4556,7 +5476,6 @@ declare class Agent<
4556
5476
  ): void;
4557
5477
  getConnection<TState = unknown>(id: string): Connection<TState> | undefined;
4558
5478
  getConnections<TState = unknown>(tag?: string): Iterable<Connection<TState>>;
4559
- private _cf_broadcastToParentSubAgent;
4560
5479
  _cf_broadcastToSubAgent(
4561
5480
  ownerPath: ReadonlyArray<AgentPathStep>,
4562
5481
  message: string | ArrayBuffer | ArrayBufferView,
@@ -4564,7 +5483,7 @@ declare class Agent<
4564
5483
  ): Promise<void>;
4565
5484
  _cf_subAgentConnectionMetas(
4566
5485
  ownerPath: ReadonlyArray<AgentPathStep>
4567
- ): Promise<SubAgentConnectionMeta[]>;
5486
+ ): Promise<DynamicAgentConnectionMeta[]>;
4568
5487
  _cf_sendToSubAgentConnection(
4569
5488
  connectionId: string,
4570
5489
  message: string | ArrayBuffer | ArrayBufferView
@@ -4578,11 +5497,6 @@ declare class Agent<
4578
5497
  connectionId: string,
4579
5498
  state: unknown
4580
5499
  ): Promise<unknown>;
4581
- private _cf_subAgentConnectionMetaForPath;
4582
- private _cf_subAgentTargetPath;
4583
- private _cf_subAgentPathFromOuterUri;
4584
- private _isSameAgentPath;
4585
- private _cf_connectionHasSubAgentTarget;
4586
5500
  protected _cf_connectionTargetsSubAgent(connection: Connection): boolean;
4587
5501
  /**
4588
5502
  * Returns true when the current request is addressed to a child facet of
@@ -4594,32 +5508,26 @@ declare class Agent<
4594
5508
  */
4595
5509
  protected _cf_requestTargetsSubAgent(request: Request): boolean;
4596
5510
  private _cf_forwardSubAgentWebSocketConnect;
4597
- private _cf_createSubAgentConnectionBridge;
4598
5511
  private _cf_forwardSubAgentWebSocketMessage;
4599
5512
  private _cf_forwardSubAgentWebSocketClose;
4600
- private _cf_resolveSubAgentConnection;
4601
5513
  _cf_handleSubAgentWebSocketConnect(
4602
- bridge: SubAgentConnectionBridge,
4603
- meta: SubAgentConnectionMeta
5514
+ bridge: DynamicAgentConnectionBridge,
5515
+ meta: DynamicAgentConnectionMeta
4604
5516
  ): Promise<void>;
4605
5517
  _cf_handleSubAgentWebSocketMessage(
4606
5518
  message: WSMessage,
4607
- bridge: SubAgentConnectionBridge,
4608
- meta: SubAgentConnectionMeta
5519
+ bridge: DynamicAgentConnectionBridge,
5520
+ meta: DynamicAgentConnectionMeta,
5521
+ replyBridge?: DynamicAgentConnectionBridge
4609
5522
  ): Promise<void>;
4610
5523
  _cf_handleSubAgentWebSocketClose(
4611
5524
  code: number,
4612
5525
  reason: string,
4613
5526
  wasClean: boolean,
4614
- bridge: SubAgentConnectionBridge,
4615
- meta: SubAgentConnectionMeta
5527
+ bridge: DynamicAgentConnectionBridge,
5528
+ meta: DynamicAgentConnectionMeta
4616
5529
  ): Promise<void>;
4617
- private _cf_runWithSubAgentBridge;
4618
- private _cf_createSubAgentBridgeConnection;
4619
- private _cf_storeVirtualSubAgentConnection;
4620
5530
  protected _cf_hydrateSubAgentConnectionsFromRoot(): Promise<void>;
4621
- private _cf_getRawConnectionState;
4622
- private _cf_getForwardedSubAgentState;
4623
5531
  /**
4624
5532
  * Parent-side middleware hook. Fires before a request is
4625
5533
  * forwarded into a facet sub-agent. Mirrors `onBeforeConnect` /
@@ -4655,7 +5563,7 @@ declare class Agent<
4655
5563
  * class Inbox extends Agent {
4656
5564
  * override async onBeforeSubAgent(req, { className, name }) {
4657
5565
  * // Strict registry gate
4658
- * if (!this.hasSubAgent(className, name)) {
5566
+ * if (!this.dynamicAgents.has(className, name)) {
4659
5567
  * return new Response("Not found", { status: 404 });
4660
5568
  * }
4661
5569
  * }
@@ -4705,7 +5613,6 @@ declare class Agent<
4705
5613
  method: string,
4706
5614
  args: unknown[]
4707
5615
  ): Promise<unknown>;
4708
- private _cf_invokeStubMethod;
4709
5616
  /**
4710
5617
  * Initialize this agent as a facet in a single RPC.
4711
5618
  *
@@ -4812,7 +5719,7 @@ declare class Agent<
4812
5719
  * ```
4813
5720
  */
4814
5721
  parentAgent<T extends Agent>(
4815
- cls: SubAgentClass<T>
5722
+ cls: DynamicAgentClass<T>
4816
5723
  ): Promise<DurableObjectStub<T>>;
4817
5724
  private _cf_getTopLevelNamespaceByClassName;
4818
5725
  private _cf_asDurableObjectNamespace;
@@ -4837,11 +5744,13 @@ declare class Agent<
4837
5744
  * const searcher = await this.subAgent(SearchAgent, "main-search");
4838
5745
  * const results = await searcher.search("cloudflare agents");
4839
5746
  * ```
5747
+ *
5748
+ * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.get()} instead.
4840
5749
  */
4841
5750
  subAgent<T extends Agent>(
4842
- cls: SubAgentClass<T>,
5751
+ cls: DynamicAgentClass<T>,
4843
5752
  name: string
4844
- ): Promise<SubAgentStub<T>>;
5753
+ ): Promise<DynamicAgentStub<T>>;
4845
5754
  /** Maximum number of non-terminal agent-tool runs this parent may own at once. */
4846
5755
  maxConcurrentAgentTools: number;
4847
5756
  onAgentToolStart(_run: AgentToolRunInfo): Promise<void>;
@@ -4976,7 +5885,7 @@ declare class Agent<
4976
5885
  */
4977
5886
  _cfDetachedReconcileTick(payload?: DetachedReconcilePayload): Promise<void>;
4978
5887
  hasAgentToolRun<T extends Agent>(
4979
- cls: SubAgentClass<T>,
5888
+ cls: DynamicAgentClass<T>,
4980
5889
  runId: string
4981
5890
  ): boolean;
4982
5891
  hasAgentToolRun(agentType: string, runId: string): boolean;
@@ -5130,6 +6039,13 @@ declare class Agent<
5130
6039
  * @internal
5131
6040
  */
5132
6041
  private _cf_resolveSubAgent;
6042
+ /**
6043
+ * Run `body` in a fresh invocation scope with no native request/
6044
+ * connection context attached, so a child-facet RPC never sees
6045
+ * parent-owned I/O handles.
6046
+ * @internal
6047
+ */
6048
+ private _runFacetInitInvocation;
5133
6049
  /**
5134
6050
  * Forcefully abort a running sub-agent. The child stops executing
5135
6051
  * immediately and will be restarted on next {@link subAgent} call.
@@ -5141,8 +6057,10 @@ declare class Agent<
5141
6057
  * @param cls The Agent subclass used when creating the child
5142
6058
  * @param name Name of the child to abort
5143
6059
  * @param reason Error thrown to pending/future RPC callers
6060
+ *
6061
+ * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.abort()} instead.
5144
6062
  */
5145
- abortSubAgent(cls: SubAgentClass, name: string, reason?: unknown): void;
6063
+ abortSubAgent(cls: DynamicAgentClass, name: string, reason?: unknown): void;
5146
6064
  /**
5147
6065
  * Delete a sub-agent: abort it if running, then permanently wipe its
5148
6066
  * storage. Transitively deletes the child's own children.
@@ -5151,20 +6069,10 @@ declare class Agent<
5151
6069
  *
5152
6070
  * @param cls The Agent subclass used when creating the child
5153
6071
  * @param name Name of the child to delete
6072
+ *
6073
+ * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.delete()} instead.
5154
6074
  */
5155
- deleteSubAgent(cls: SubAgentClass, name: string): Promise<void>;
5156
- /** @internal */
5157
- private _subAgentRegistryReady;
5158
- private _addColumnIfNotExists;
5159
- /** @internal */
5160
- private _ensureSubAgentRegistry;
5161
- /** @internal */
5162
- private _recordSubAgent;
5163
- /** @internal */
5164
- private _subAgentRegistryRow;
5165
- private _cf_subAgentIdentity;
5166
- /** @internal */
5167
- private _forgetSubAgent;
6075
+ deleteSubAgent(cls: DynamicAgentClass, name: string): Promise<void>;
5168
6076
  /**
5169
6077
  * Whether this agent has previously spawned (and not deleted) a
5170
6078
  * sub-agent of the given class and name. Backed by an
@@ -5183,8 +6091,13 @@ declare class Agent<
5183
6091
  * }
5184
6092
  * }
5185
6093
  * ```
6094
+ *
6095
+ * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.has()} instead.
5186
6096
  */
5187
- hasSubAgent<T extends Agent>(cls: SubAgentClass<T>, name: string): boolean;
6097
+ hasSubAgent<T extends Agent>(
6098
+ cls: DynamicAgentClass<T>,
6099
+ name: string
6100
+ ): boolean;
5188
6101
  hasSubAgent(className: string, name: string): boolean;
5189
6102
  /**
5190
6103
  * List known sub-agents, optionally filtered by class. Reflects
@@ -5192,9 +6105,11 @@ declare class Agent<
5192
6105
  * {@link deleteSubAgent}.
5193
6106
  *
5194
6107
  * @experimental The API surface may change before stabilizing.
6108
+ *
6109
+ * @deprecated Use {@link Agent.dynamicAgents | this.dynamicAgents.list()} instead.
5195
6110
  */
5196
6111
  listSubAgents<T extends Agent>(
5197
- cls: SubAgentClass<T>
6112
+ cls: DynamicAgentClass<T>
5198
6113
  ): Array<{
5199
6114
  className: string;
5200
6115
  name: string;
@@ -5246,9 +6161,8 @@ declare class Agent<
5246
6161
  * durable marker directly — the in-memory `_isFacet` flag may not be
5247
6162
  * hydrated yet at the call sites, but facets never write the marker.
5248
6163
  */
6164
+ private _pendingDestroyAlarm;
5249
6165
  private _hasPendingDestroy;
5250
- /** @internal Drop every internal Agents SDK table during top-level destroy. */
5251
- protected _dropInternalTablesForDestroy(): void;
5252
6166
  /**
5253
6167
  * Check if a method is callable
5254
6168
  * @param method The method name to check
@@ -5559,7 +6473,6 @@ declare class Agent<
5559
6473
  private _workflowOrigin;
5560
6474
  private _findAgentBindingNameForClass;
5561
6475
  private _findBindingNameForNamespace;
5562
- private _restoreRpcMcpServers;
5563
6476
  /**
5564
6477
  * Handle a callback from a workflow.
5565
6478
  * Invoked via the internal `_workflow_handleCallback` RPC whenever an
@@ -5711,27 +6624,6 @@ declare class Agent<
5711
6624
  */
5712
6625
  createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider;
5713
6626
  private broadcastMcpServers;
5714
- /**
5715
- * Handle MCP OAuth callback request if it's an OAuth callback.
5716
- *
5717
- * This method encapsulates the entire OAuth callback flow:
5718
- * 1. Checks if the request is an MCP OAuth callback
5719
- * 2. Processes the OAuth code exchange
5720
- * 3. Establishes the connection if successful
5721
- * 4. Broadcasts MCP server state updates
5722
- * 5. Returns the appropriate HTTP response
5723
- *
5724
- * @param request The incoming HTTP request
5725
- * @returns Response if this was an OAuth callback, null otherwise
5726
- */
5727
- private handleMcpOAuthCallback;
5728
- /**
5729
- * Handle OAuth callback response using MCPClientManager configuration
5730
- * @param result OAuth callback result
5731
- * @param request The original request (needed for base URL)
5732
- * @returns Response for the OAuth callback
5733
- */
5734
- private handleOAuthCallbackResponse;
5735
6627
  }
5736
6628
  /**
5737
6629
  * Namespace for creating Agent instances
@@ -5744,29 +6636,6 @@ type AgentNamespace<Agentic extends Agent<Cloudflare.Env>> =
5744
6636
  * Agent's durable context
5745
6637
  */
5746
6638
  type AgentContext = DurableObjectState;
5747
- /**
5748
- * Configuration options for Agent routing
5749
- */
5750
- type AgentOptions<Env> = PartyServerOptions<Env>;
5751
- type AgentGetOptions<
5752
- Env,
5753
- Props extends Record<string, unknown> = Record<string, unknown>
5754
- > = Pick<
5755
- PartyServerOptions<Env, Props>,
5756
- "jurisdiction" | "locationHint" | "props" | "routingRetry"
5757
- >;
5758
- /**
5759
- * Route a request to the appropriate Agent
5760
- * @param request Request to route
5761
- * @param env Environment containing Agent bindings
5762
- * @param options Routing options
5763
- * @returns Response from the Agent or undefined if no route matched
5764
- */
5765
- declare function routeAgentRequest<Env>(
5766
- request: Request,
5767
- env: Env,
5768
- options?: AgentOptions<Env>
5769
- ): Promise<Response | null>;
5770
6639
  type EmailRoutingOptions<Env> = AgentOptions<Env> & {
5771
6640
  resolver: EmailResolver<Env>;
5772
6641
  /**
@@ -5801,24 +6670,6 @@ declare function routeAgentEmail<Env extends Cloudflare.Env = Cloudflare.Env>(
5801
6670
  env: Env,
5802
6671
  options: EmailRoutingOptions<Env>
5803
6672
  ): Promise<void>;
5804
- /**
5805
- * Get or create an Agent by name
5806
- * @template Env Environment type containing bindings
5807
- * @template T Type of the Agent class
5808
- * @param namespace Agent namespace
5809
- * @param name Name of the Agent instance
5810
- * @param options Options for Agent creation
5811
- * @returns Promise resolving to an Agent instance stub
5812
- */
5813
- declare function getAgentByName<
5814
- Env extends Cloudflare.Env = Cloudflare.Env,
5815
- T extends Agent<Env> = Agent<Env>,
5816
- Props extends Record<string, unknown> = Record<string, unknown>
5817
- >(
5818
- namespace: DurableObjectNamespace<T>,
5819
- name: string,
5820
- options?: AgentGetOptions<Env, Props>
5821
- ): Promise<DurableObjectStub<T>>;
5822
6673
  /**
5823
6674
  * A wrapper for streaming responses in callable methods
5824
6675
  */
@@ -5827,6 +6678,7 @@ declare class StreamingResponse {
5827
6678
  private _id;
5828
6679
  private _closed;
5829
6680
  constructor(connection: Connection, id: string);
6681
+ private _send;
5830
6682
  /**
5831
6683
  * Whether the stream has been closed (via end() or error())
5832
6684
  */
@@ -5851,600 +6703,256 @@ declare class StreamingResponse {
5851
6703
  error(message: string): boolean;
5852
6704
  }
5853
6705
  //#endregion
5854
- //#region src/agent-tool-types.d.ts
5855
- type AgentToolRunStatus =
5856
- | "starting"
5857
- | "running"
5858
- | "completed"
5859
- | "error"
5860
- | "aborted"
5861
- | "interrupted";
5862
- type AgentToolTerminalStatus = Extract<
5863
- AgentToolRunStatus,
5864
- "completed" | "error" | "aborted" | "interrupted"
5865
- >;
5866
- /**
5867
- * Machine-readable cause of an `interrupted` seal (#1630 follow-up). Lets a
5868
- * caller branch on WHY a run was abandoned without parsing the human-readable
5869
- * `error` prose, which is not a stable contract.
5870
- *
5871
- * - `no-progress` the child went silent for a full no-progress window while
5872
- * the parent was tailing it (genuinely stalled / hung).
5873
- * - `window-exceeded` — a finite `agentToolReattachMaxWindowMs` ceiling elapsed
5874
- * while the child was still non-terminal. Only fires when an integrator opts
5875
- * into a hard wall-clock cap (the default ceiling is `Infinity`).
5876
- * - `not-tailable` — the child runtime cannot live-tail, so the parent could
5877
- * not re-attach to its stream to follow it to terminal.
5878
- * - `inspect-timeout` — inspecting the child timed out during parent recovery.
5879
- * - `inspect-failed` — inspecting the child failed during parent recovery.
5880
- * - `recovery-deadline` — the overall parent-recovery deadline elapsed before
5881
- * this run could be reconciled.
5882
- * - `budget-exceeded` a detached run's absolute `maxBudgetMs` ceiling elapsed
5883
- * before it reached a terminal. The parent gave up watching and tore the
5884
- * child down. Like `window-exceeded` this is a soft seal: a child that
5885
- * completes anyway can still repair the run and re-fire the completion hook.
5886
- */
5887
- type AgentToolInterruptedReason =
5888
- | "no-progress"
5889
- | "window-exceeded"
5890
- | "not-tailable"
5891
- | "inspect-timeout"
5892
- | "inspect-failed"
5893
- | "recovery-deadline"
5894
- | "budget-exceeded";
5895
- /**
5896
- * Structured failure envelope an `agentTool()` returns when a sub-agent run
5897
- * does not complete. Instead of an opaque error string the parent model would
5898
- * parrot back to the user, the caller (or an orchestration harness) gets a
5899
- * machine-readable signal:
5900
- *
5901
- * - `status` mirrors the underlying terminal status (`error` | `aborted` |
5902
- * `interrupted`).
5903
- * - `retryable` is `true` only for a transient interruption — the child was
5904
- * reset or superseded by a deploy / parent recovery and never reached a
5905
- * logical outcome, so re-dispatching the same run is the right move. A
5906
- * genuine `error` or an intentional `aborted` is `false`.
5907
- * - `error` stays human-readable for logs and UI.
5908
- */
5909
- type AgentToolFailure = {
5910
- ok: false;
5911
- status: Exclude<AgentToolTerminalStatus, "completed">;
5912
- error: string;
5913
- retryable: boolean /** Present only when `status` is `interrupted` — machine-readable cause. */;
5914
- reason?: AgentToolInterruptedReason;
6706
+ //#region src/agent-routing.d.ts
6707
+ interface RoutingRetryEvent {
6708
+ error: unknown;
6709
+ attempt: number;
6710
+ maxAttempts: number;
6711
+ delayMs: number;
6712
+ name: string;
6713
+ className?: string;
6714
+ }
6715
+ /** Retry policy for Agent routing infrastructure failures. */
6716
+ interface RoutingRetryOptions {
6717
+ /** Max number of attempts, including the first. Default: 3. */
6718
+ maxAttempts?: number;
6719
+ /** Base delay in milliseconds for exponential backoff. Default: 100. */
6720
+ baseDelayMs?: number;
6721
+ /** Maximum delay in milliseconds. Default: 800. */
6722
+ maxDelayMs?: number;
6723
+ /** Optional callback invoked before each retry delay. */
6724
+ onRetry?: (event: RoutingRetryEvent) => void | Promise<void>;
6725
+ }
6726
+ interface AgentRouteMatch<Env = Cloudflare.Env> {
6727
+ /** The Durable Object environment binding name. */
6728
+ className: Extract<keyof Env, string>;
6729
+ /** The named Durable Object instance extracted from the URL. */
6730
+ name: string;
6731
+ }
6732
+ interface AgentRouteOptions<
6733
+ Env = Cloudflare.Env,
6734
+ Props extends Record<string, unknown> = Record<string, unknown>
6735
+ > {
6736
+ /** URL prefix before the binding and instance name. Default: `agents`. */
6737
+ prefix?: string;
6738
+ jurisdiction?: DurableObjectJurisdiction;
6739
+ locationHint?: DurableObjectLocationHint;
6740
+ /** Properties supplied before lifecycle startup. */
6741
+ props?: Props;
5915
6742
  /**
5916
- * Present only when `status` is `interrupted`. `true` when the child facet was
5917
- * still non-terminal (running / advancing) at the moment the parent stopped
5918
- * waiting; `false` once the parent has torn the child down so it is no longer
5919
- * doing work. Lets a caller decide between re-dispatching vs. reconnecting.
6743
+ * Whether to enable CORS for matched routes.
6744
+ *
6745
+ * When `true`, uses default permissive CORS headers:
6746
+ * - Access-Control-Allow-Origin: *
6747
+ * - Access-Control-Allow-Methods: GET, POST, HEAD, OPTIONS
6748
+ * - Access-Control-Allow-Headers: *
6749
+ * - Access-Control-Max-Age: 86400
6750
+ *
6751
+ * For credentialed requests, pass explicit headers with a specific origin.
6752
+ * When set to a `HeadersInit` value, uses those as the CORS headers instead.
6753
+ * CORS preflight requests are handled automatically for matched routes.
5920
6754
  */
5921
- childStillRunning?: boolean;
5922
- };
5923
- type AgentToolDisplayMetadata = {
5924
- name?: string;
5925
- icon?: string;
5926
- } & Record<string, unknown>;
5927
- /**
5928
- * Reserved chunk type a sub-agent emits via `reportProgress` while it runs.
5929
- * Rides the child's own UI-message stream as a **transient** data part, so it
5930
- * re-broadcasts to the parent's clients (via the parent's tail) and surfaces in
5931
- * `useAgentToolEvents` without persisting into the child's stored message parts.
5932
- * See `design/rfc-detached-agent-tools.md` §"Progress and milestone signaling".
5933
- */
5934
- declare const AGENT_TOOL_PROGRESS_PART = "data-agent-progress";
5935
- /**
5936
- * Reserved chunk type a sub-agent emits via `reportProgress({ milestone })`.
5937
- * Unlike the ephemeral progress part this rides the child's stream as a
5938
- * **persisted** data part, so it survives eviction, replays on drill-in, and
5939
- * re-resolves milestone waiters. See `design/rfc-detached-agent-tools.md`.
5940
- */
5941
- declare const AGENT_TOOL_MILESTONE_PART = "data-agent-milestone";
5942
- /**
5943
- * Ephemeral progress signal a running sub-agent emits with `reportProgress`. The
5944
- * well-known fields drive generic UI (a bar + status line) with no per-app
5945
- * convention; `data` is an app-specific escape hatch that is **live-only** by
5946
- * default (not persisted) unless `reportProgress(p, { persist: true })`. Naming a
5947
- * `milestone` promotes the signal to the **durable** tier: it persists as one row
5948
- * per milestone, replays, and (with `data`) is retained.
5949
- */
5950
- type AgentToolProgress<T = unknown> = {
5951
- /** 0..1 — drives a progress bar. */ fraction?: number /** Human-readable status line, e.g. "Ingested 40k/80k rows". */;
5952
- message?: string /** Coarse stage label, e.g. "scaffolding" | "deploying". */;
5953
- phase?: string;
6755
+ cors?: boolean | HeadersInit;
5954
6756
  /**
5955
- * Present a **durable** milestone: persisted, replayable, and surfaced as a
5956
- * distinct row in `AgentToolRunState.milestones` / `inspectAgentToolRun`. Use
5957
- * for named phase boundaries ("schema-ready", "preview-ready", "deployed").
6757
+ * Retry transient Durable Object infrastructure errors thrown while routing.
6758
+ * Enabled by default; pass `false` to disable.
5958
6759
  */
5959
- milestone?: string /** App-specific payload; live-only for progress, persisted for milestones. */;
5960
- data?: T;
5961
- };
6760
+ routingRetry?: false | RoutingRetryOptions;
6761
+ onBeforeConnect?: (
6762
+ request: Request,
6763
+ route: AgentRouteMatch<Env>
6764
+ ) => Response | Request | void | Promise<Response | Request | void>;
6765
+ onBeforeRequest?: (
6766
+ request: Request,
6767
+ route: AgentRouteMatch<Env>
6768
+ ) =>
6769
+ | Response
6770
+ | Request
6771
+ | void
6772
+ | Promise<Response | Request | undefined | void>;
6773
+ }
6774
+ /** Configuration options for {@link routeAgentRequest}. */
6775
+ type AgentOptions<Env> = AgentRouteOptions<Env>;
6776
+ /** Options for resolving and starting a named Agent. */
6777
+ type AgentGetOptions<
6778
+ Env,
6779
+ Props extends Record<string, unknown> = Record<string, unknown>
6780
+ > = Pick<
6781
+ AgentRouteOptions<Env, Props>,
6782
+ "jurisdiction" | "locationHint" | "props" | "routingRetry"
6783
+ >;
5962
6784
  /**
5963
- * A durable milestone a sub-agent reached, projected onto `AgentToolRunState`
5964
- * and `inspectAgentToolRun`. `sequence` is monotonic per run so replay/live
5965
- * races dedupe on `(runId, sequence)`.
6785
+ * Route `/agents/:binding/:name` HTTP and WebSocket requests to a named
6786
+ * Durable Object. The target may extend `Agent` or compose `Lifecycle`
6787
+ * directly into a plain `DurableObject`.
6788
+ *
6789
+ * @param request - Incoming Worker request.
6790
+ * @param env - Worker environment containing Durable Object bindings.
6791
+ * @param options - Routing options.
6792
+ * @returns The matched response, or `null` when the path does not match.
5966
6793
  */
5967
- type AgentToolMilestone = {
5968
- name: string /** Monotonic per-run ordinal; dedupe key for replay vs live races. */;
5969
- sequence: number /** Epoch ms the milestone was reached. */;
5970
- at: number /** App-specific payload carried with the milestone (persisted). */;
5971
- data?: unknown;
5972
- };
6794
+ declare function routeAgentRequest<Env>(
6795
+ request: Request,
6796
+ env: Env,
6797
+ options?: AgentOptions<Env>
6798
+ ): Promise<Response | null>;
5973
6799
  /**
5974
- * Latest progress snapshot persisted on the child run row and surfaced through
5975
- * `inspectAgentToolRun` + `AgentToolRunState`. Only the safe-to-inspect fields
5976
- * are retained by default; `at` is the emit timestamp (drives the resetting
5977
- * no-progress budget).
6800
+ * Get a named Agent stub after its lifecycle startup has completed.
6801
+ *
6802
+ * @param namespace - Agent Durable Object namespace.
6803
+ * @param name - Agent instance name.
6804
+ * @param options - Placement, startup properties, and retry options.
6805
+ * @returns The initialized Agent stub.
5978
6806
  */
5979
- type AgentToolProgressSnapshot = {
5980
- fraction?: number;
5981
- message?: string;
5982
- phase?: string;
5983
- /**
5984
- * Set when this signal was a durable milestone (`reportProgress({ milestone })`).
5985
- * Lets an `onProgress` consumer branch on milestone vs. ephemeral progress.
5986
- */
5987
- milestone?: string /** Epoch ms of the latest signal. */;
5988
- at: number /** Present only when the emitter opted into persisting `data`. */;
5989
- data?: unknown;
5990
- };
5991
- type AgentToolRunInfo = {
5992
- runId: string;
5993
- parentToolCallId?: string;
5994
- agentType: string;
5995
- inputPreview?: unknown;
5996
- status: AgentToolRunStatus;
5997
- display?: AgentToolDisplayMetadata;
5998
- /**
5999
- * Caller-controlled `metadata.source` for chat-agent `detached.notify`
6000
- * completions. Present only for detached notify runs that supplied one.
6001
- */
6002
- notifySource?: string;
6003
- displayOrder: number;
6004
- startedAt: number;
6005
- completedAt?: number;
6006
- };
6007
- type AgentToolLifecycleResult = {
6008
- status: AgentToolTerminalStatus;
6009
- summary?: string;
6010
- error?: string /** Present only when `status` is `interrupted` — machine-readable cause. */;
6011
- reason?: AgentToolInterruptedReason;
6012
- /**
6013
- * Present only when `status` is `interrupted`. Whether the child facet was
6014
- * still non-terminal when the parent stopped waiting (before any teardown).
6015
- */
6016
- childStillRunning?: boolean;
6017
- };
6018
- /**
6019
- * Configuration for a detached ("background") agent-tool run. See
6020
- * `design/rfc-detached-agent-tools.md`.
6021
- *
6022
- * Callbacks are referenced by **method name** on the dispatching agent (the same
6023
- * durable, eviction-surviving pattern as `Agent.schedule`) — never closures,
6024
- * which cannot be rehydrated after the Durable Object is evicted.
6025
- *
6026
- * `Self` is threaded from `runAgentTool(cls, options)` so the method names are
6027
- * type-checked against the calling agent's own methods.
6028
- */
6029
- type DetachedAgentToolConfig<Self = Record<string, unknown>> = {
6030
- /**
6031
- * Method invoked once per terminal delivery. Branch on `result.status`:
6032
- * `"completed" | "error" | "aborted" | "interrupted"`. A budget give-up
6033
- * arrives as `status: "interrupted"` with `reason: "budget-exceeded"`; because
6034
- * `interrupted` is soft, a child that later completes can fire the hook again
6035
- * with `"completed"`, so a give-up never hides a late real result. Make the
6036
- * handler idempotent.
6037
- */
6038
- onFinish?: Extract<keyof Self, string>;
6039
- /**
6040
- * Absolute safety ceiling — a backstop against a child that runs forever. On
6041
- * expiry the parent gives up watching (delivers `onFinish` with
6042
- * `interrupted` / `budget-exceeded`) and tears the child down. Defaults to the
6043
- * parent-level `detachedMaxBudgetMs`.
6044
- */
6045
- maxBudgetMs?: number;
6046
- /**
6047
- * Per-run override of the resetting no-progress window (ms). Once the child
6048
- * emits its first `reportProgress`, the parent gives up if it then goes silent
6049
- * for this long (resets on each signal). Defaults to the parent-level
6050
- * `detachedNoProgressBudgetMs` (1h). `0`/`Infinity` disables it.
6051
- */
6052
- noProgressBudgetMs?: number;
6053
- /**
6054
- * Chat-agent convenience (`@cloudflare/think` / `AIChatAgent`): when the run
6055
- * finishes, inject a message into the chat so the model can react to the
6056
- * result, instead of you wiring `onFinish` by hand. Sugar that auto-targets
6057
- * the agent's `_cfDetachedNotifyFinish` hook; ignored on a base `Agent` that
6058
- * does not implement it, and ignored when `onFinish` is also set (an explicit
6059
- * `onFinish` wins). Pass `{ source }` to fit the injected message into your
6060
- * app's existing metadata taxonomy. Override `formatDetachedCompletion()` to
6061
- * customize the injected text.
6062
- */
6063
- notify?:
6064
- | boolean
6065
- | {
6066
- source?: string;
6067
- };
6068
- /**
6069
- * Chat-agent convenience: milestone names that, when the detached run reaches
6070
- * them, surface an idempotent synthetic message in the chat BEFORE the run
6071
- * finishes. Each `(runId, name)` fires at most once (idempotency-keyed),
6072
- * whether observed live or reconciled after eviction. Override the wording via
6073
- * `formatDetachedMilestone()`. Requires a chat host (`@cloudflare/think`); a
6074
- * no-op on a base `Agent`.
6075
- *
6076
- * Two delivery modes (the string-array shorthand defaults to `"narrate"`):
6077
- * - `"narrate"` (default) — inject a synthetic **assistant** message directly
6078
- * (no inference): a cheap, honest status line ("Found 2 sources…") that does
6079
- * not trigger a model turn. Best for pure progress narration.
6080
- * - `"react"` — inject a **user-role** turn so the model responds to the
6081
- * milestone (steer, start dependent work, narrate with context). Costs a
6082
- * model turn. Opt in for milestones the agent should *act on*.
6083
- */
6084
- onMilestones?:
6085
- | string[]
6086
- | {
6087
- names: string[];
6088
- mode?: "react" | "narrate";
6089
- };
6090
- };
6091
- type RunAgentToolOptions<Input = unknown, Self = Record<string, unknown>> = {
6092
- input: Input;
6093
- runId?: string;
6094
- parentToolCallId?: string;
6095
- displayOrder?: number;
6096
- signal?: AbortSignal;
6097
- inputPreview?: unknown;
6098
- display?: AgentToolDisplayMetadata;
6099
- /**
6100
- * Run the sub-agent **detached**: dispatch it, let the current turn continue,
6101
- * and (optionally) get a durable callback when it finishes. `true` is
6102
- * fire-and-forget (observe via `agent-tool-event` frames + the global
6103
- * `onAgentToolFinish` hook); an object adds the targeted, eviction-surviving
6104
- * `onFinish` callback. A detached run does NOT inherit `options.signal` — it
6105
- * must outlive the spawning turn; cancel it explicitly via `cancelAgentTool`.
6106
- */
6107
- detached?: boolean | DetachedAgentToolConfig<Self>;
6108
- };
6109
- /**
6110
- * Result of dispatching a detached run. Returns immediately after dispatch
6111
- * rather than after completion.
6112
- */
6113
- type DetachedRunAgentToolResult = {
6114
- runId: string;
6115
- agentType: string;
6116
- /**
6117
- * `"running"` on a successful dispatch; `"error"` if dispatch itself failed
6118
- * (e.g. the `maxConcurrentAgentTools` cap was exceeded — rejected
6119
- * synchronously, no child started, no callback wired).
6120
- */
6121
- status: "running" | "error";
6122
- error?: string;
6123
- };
6124
- type RunAgentToolResult<Output = unknown> = {
6125
- runId: string;
6126
- agentType: string;
6127
- status: AgentToolTerminalStatus;
6128
- output?: Output;
6129
- summary?: string;
6130
- error?: string;
6131
- /**
6132
- * Present only when `status` is `interrupted` — a machine-readable cause so
6133
- * callers don't pattern-match the `error` prose (#1630 follow-up).
6134
- */
6135
- reason?: AgentToolInterruptedReason;
6136
- /**
6137
- * Present only when `status` is `interrupted`. `true` when the child facet was
6138
- * still non-terminal (running / advancing) at the moment the parent stopped
6139
- * waiting and before any teardown; `false` once the parent has torn the child
6140
- * down so it is no longer doing work.
6141
- */
6142
- childStillRunning?: boolean;
6143
- };
6144
- type ChatCapableAgentClass<T extends Agent = Agent> = SubAgentClass<T>;
6145
- type AgentToolRunInspection<Output = unknown> = {
6146
- runId: string;
6147
- status: Exclude<AgentToolRunStatus, "interrupted">;
6148
- requestId?: string;
6149
- streamId?: string;
6150
- output?: Output;
6151
- summary?: string;
6152
- error?: string;
6153
- startedAt: number;
6154
- completedAt?: number;
6155
- /**
6156
- * Latest progress snapshot the child has persisted, so a rehydrated parent
6157
- * (recovery / backbone reconcile) can reconstruct "where is this run" and
6158
- * reset the resetting no-progress budget without having tailed the live
6159
- * stream. Absent until the child emits its first `reportProgress`.
6160
- */
6161
- progress?: AgentToolProgressSnapshot;
6162
- /**
6163
- * Durable milestones the child has persisted, ordered by `sequence`. Lets a
6164
- * rehydrated parent (recovery / backbone reconcile) replay milestone-gated
6165
- * work and milestone notifications without having observed the live stream.
6166
- */
6167
- milestones?: AgentToolMilestone[];
6168
- };
6169
- type AgentToolStoredChunk = {
6170
- sequence: number;
6171
- body: string;
6172
- };
6173
- type AgentToolChildAdapter<Input = unknown, Output = unknown> = {
6174
- startAgentToolRun(
6175
- input: Input,
6176
- options: {
6177
- runId: string;
6178
- signal?: AbortSignal;
6179
- }
6180
- ): Promise<AgentToolRunInspection<Output>>;
6181
- cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
6182
- inspectAgentToolRun(
6183
- runId: string
6184
- ): Promise<AgentToolRunInspection<Output> | null>;
6185
- getAgentToolChunks(
6186
- runId: string,
6187
- options?: {
6188
- afterSequence?: number;
6189
- }
6190
- ): Promise<AgentToolStoredChunk[]>;
6191
- tailAgentToolRun?(
6192
- runId: string,
6193
- options?: {
6194
- afterSequence?: number;
6195
- signal?: AbortSignal;
6196
- }
6197
- ): Promise<ReadableStream<AgentToolStoredChunk>>;
6198
- };
6199
- type AgentToolEvent =
6200
- | {
6201
- kind: "started";
6202
- runId: string;
6203
- agentType: string;
6204
- inputPreview?: unknown;
6205
- order: number;
6206
- display?: AgentToolDisplayMetadata;
6207
- }
6208
- | {
6209
- kind: "chunk";
6210
- runId: string;
6211
- body: string;
6212
- }
6213
- | {
6214
- kind: "finished";
6215
- runId: string;
6216
- summary: string;
6217
- }
6218
- | {
6219
- kind: "error";
6220
- runId: string;
6221
- error: string;
6222
- }
6223
- | {
6224
- kind: "aborted";
6225
- runId: string;
6226
- reason?: string;
6227
- }
6228
- | {
6229
- kind: "interrupted";
6230
- runId: string;
6231
- error: string /** Machine-readable cause of the interrupt (#1630 follow-up). */;
6232
- reason?: AgentToolInterruptedReason;
6233
- /**
6234
- * Whether the child facet was still non-terminal when the parent stopped
6235
- * waiting (before any teardown). Lets a UI distinguish a still-running
6236
- * child from one the parent has torn down.
6237
- */
6238
- childStillRunning?: boolean;
6239
- };
6240
- type AgentToolEventMessage = {
6241
- type: "agent-tool-event";
6242
- parentToolCallId?: string;
6243
- sequence: number;
6244
- replay?: true;
6245
- event: AgentToolEvent;
6246
- };
6247
- type AgentToolRunPart = {
6248
- type: string;
6249
- };
6250
- type AgentToolRunState<Part extends AgentToolRunPart = AgentToolRunPart> = {
6251
- runId: string;
6252
- agentType: string;
6253
- parentToolCallId?: string;
6254
- inputPreview?: unknown;
6255
- order: number;
6256
- display?: AgentToolDisplayMetadata;
6257
- status: "running" | "completed" | "error" | "aborted" | "interrupted";
6258
- /**
6259
- * Message parts reconstructed from the child agent's streamed chunks.
6260
- *
6261
- * The default stays framework-neutral so importing `agents` does not require
6262
- * an AI SDK peer. AI SDK consumers can use
6263
- * `AgentToolRunState<UIMessage["parts"][number]>` when they need its exact
6264
- * discriminated union.
6265
- */
6266
- parts: Part[];
6267
- summary?: string;
6268
- error?: string;
6269
- /**
6270
- * Present only when `status` is `interrupted` — machine-readable cause and
6271
- * whether the child is still running, mirrored from the wire event so a UI
6272
- * can render the reason without parsing `error` (#1630 follow-up).
6273
- */
6274
- reason?: AgentToolInterruptedReason;
6275
- childStillRunning?: boolean;
6276
- /**
6277
- * Latest progress snapshot, projected from the child's transient
6278
- * `data-agent-progress` signals so a UI can render a bar / ETA / phase label
6279
- * for a running (especially detached / background) run without drilling in.
6280
- */
6281
- progress?: AgentToolProgressSnapshot;
6282
- /**
6283
- * Durable milestones the run has reached, ordered by `sequence` (deduped
6284
- * across replay/live races). Drives milestone chips / a phase timeline.
6285
- */
6286
- milestones?: AgentToolMilestone[];
6287
- subAgent: {
6288
- agent: string;
6289
- name: string;
6290
- };
6291
- };
6292
- type AgentToolEventState<Part extends AgentToolRunPart = AgentToolRunPart> = {
6293
- runsById: Record<string, AgentToolRunState<Part>>;
6294
- runsByToolCallId: Record<string, AgentToolRunState<Part>[]>;
6295
- unboundRuns: AgentToolRunState<Part>[];
6296
- };
6807
+ declare function getAgentByName<
6808
+ Env extends Cloudflare.Env = Cloudflare.Env,
6809
+ T extends Agent<Env> = Agent<Env>,
6810
+ Props extends Record<string, unknown> = Record<string, unknown>
6811
+ >(
6812
+ namespace: DurableObjectNamespace<T>,
6813
+ name: string,
6814
+ options?: AgentGetOptions<Env, Props>
6815
+ ): Promise<DurableObjectStub<T>>;
6297
6816
  //#endregion
6298
6817
  export {
6299
- RoutingRetryOptions as $,
6300
- MCPOAuthCallbackResult as $t,
6301
- AgentGetOptions as A,
6302
- StreamableHTTPEdgeClientTransport as An,
6303
- WorkflowCompleteCallback as At,
6304
- EmailSendBinding as B,
6305
- parseSubAgentPath as Bn,
6306
- WorkflowTrackingRow as Bt,
6307
- DetachedRunAgentToolResult as C,
6308
- LegacyMcpHandler as Cn,
6309
- ApprovalEventPayload as Ct,
6310
- AddRpcMcpServerOptions as D,
6311
- WorkerTransport as Dn,
6312
- WorkflowCallback as Dt,
6313
- AddMcpServerOptions as E,
6314
- TransportState as En,
6315
- WaitForApprovalOptions as Et,
6316
- Connection$1 as F,
6317
- buildAgentPath as Fn,
6318
- WorkflowPage as Ft,
6319
- FiberStatus as G,
6320
- MCPClientElicitationHandler as Gt,
6321
- FiberInspection as H,
6322
- withInvocationScope as Hn,
6323
- ElicitResult$2 as Ht,
6324
- ConnectionContext$1 as I,
6325
- buildAgentUrl as In,
6326
- WorkflowProgressCallback as It,
6327
- MCPServerMessage as J,
6328
- MCPClientManagerOptions as Jt,
6329
- ListFibersOptions as K,
6330
- MCPClientElicitationHandlers as Kt,
6331
- DEFAULT_AGENT_STATIC_OPTIONS as L,
6332
- buildSubAgentPath as Ln,
6333
- WorkflowQueryCriteria as Lt,
6334
- AgentOptions as M,
6335
- BuildAgentPathOptions as Mn,
6336
- WorkflowEventCallback as Mt,
6337
- AgentStaticOptions as N,
6338
- SUB_PREFIX as Nn,
6339
- WorkflowEventPayload as Nt,
6340
- Agent as O,
6341
- WorkerTransportOptions as On,
6342
- WorkflowCallbackBase as Ot,
6343
- CallableMetadata as P,
6344
- SubAgentPathMatch as Pn,
6345
- WorkflowInfo as Pt,
6346
- RPCResponse as Q,
6347
- MCPDiscoverResult as Qt,
6348
- DeleteFibersOptions as R,
6349
- buildSubAgentPathUnchecked as Rn,
6350
- WorkflowRejectedError as Rt,
6351
- DetachedAgentToolConfig as S,
6352
- CreateMcpHandlerOptions$1 as Sn,
6353
- AgentWorkflowStep as St,
6354
- RunAgentToolResult as T,
6355
- MCPStorageApi as Tn,
6356
- RunWorkflowOptions as Tt,
6357
- FiberRecoveryContext as U,
6358
- MCPAITool as Ut,
6359
- FiberContext as V,
6360
- routeSubAgentRequest as Vn,
6361
- ElicitRequest$1 as Vt,
6362
- FiberRecoveryResult as W,
6363
- MCPAIToolSet as Wt,
6364
- QueueItem as X,
6365
- MCPClientOAuthResult as Xt,
6366
- MCPServersState as Y,
6367
- MCPClientOAuthCallbackConfig as Yt,
6368
- RPCRequest as Z,
6369
- MCPConnectionResult as Zt,
6370
- AgentToolRunState as _,
6371
- ClearableEventStore as _n,
6372
- AgentWorkflowEvent as _t,
6373
- AgentToolEvent as a,
6374
- normalizeServerId as an,
6375
- StartFiberResult as at,
6376
- AgentToolTerminalStatus as b,
6377
- experimental_createMcpHandler as bn,
6378
- AgentWorkflowParams as bt,
6379
- AgentToolFailure as c,
6380
- RPCClientTransport as cn,
6381
- SubAgentClass as ct,
6382
- AgentToolMilestone as d,
6383
- RPCServerTransportOptions as dn,
6384
- callable as dt,
6385
- MCPServerFilter as en,
6386
- Schedule as et,
6387
- AgentToolProgress as f,
6388
- RPC_DO_PREFIX as fn,
6389
- getAgentByName as ft,
6390
- AgentToolRunPart as g,
6391
- McpAgent as gn,
6392
- unstable_callable as gt,
6393
- AgentToolRunInspection as h,
6394
- ElicitResult$3 as hn,
6395
- routeAgentRequest as ht,
6396
- AgentToolDisplayMetadata as i,
6397
- getNamespacedData as in,
6398
- StartFiberOptions as it,
6399
- AgentNamespace as j,
6400
- AgentPathStep as jn,
6401
- WorkflowErrorCallback as jt,
6402
- AgentContext as k,
6403
- SSEEdgeClientTransport as kn,
6404
- WorkflowCallbackType as kt,
6405
- AgentToolInterruptedReason as l,
6406
- RPCClientTransportOptions as ln,
6407
- SubAgentStub as lt,
6408
- AgentToolRunInfo as m,
6409
- ElicitRequestSchema as mn,
6410
- routeAgentEmail as mt,
6411
- AGENT_TOOL_PROGRESS_PART as n,
6412
- MCP_SERVER_ID_MAX_LENGTH as nn,
6413
- SendEmailOptions as nt,
6414
- AgentToolEventMessage as o,
6415
- MCPElicitationHandler as on,
6416
- StateUpdateMessage as ot,
6417
- AgentToolProgressSnapshot as p,
6418
- ElicitRequest$2 as pn,
6419
- getCurrentAgent as pt,
6420
- MCPServer as q,
6421
- MCPClientManager as qt,
6422
- AgentToolChildAdapter as r,
6423
- RegisterServerOptions as rn,
6424
- SqlError as rt,
6425
- AgentToolEventState as s,
6426
- MCPElicitationHandlers as sn,
6427
- StreamingResponse as st,
6428
- AGENT_TOOL_MILESTONE_PART as t,
6429
- MCPServerOptions as tn,
6430
- ScheduleCriteria as tt,
6431
- AgentToolLifecycleResult as u,
6432
- RPCServerTransport as un,
6433
- WSMessage$1 as ut,
6434
- AgentToolRunStatus as v,
6435
- DurableObjectEventStore as vn,
6436
- AgentWorkflowInternalParams as vt,
6437
- RunAgentToolOptions as w,
6438
- createLegacyMcpHandler as wn,
6439
- DefaultProgress as wt,
6440
- ChatCapableAgentClass as x,
6441
- CreateLegacyMcpHandlerOptions as xn,
6442
- AgentWorkflowPathStep as xt,
6443
- AgentToolStoredChunk as y,
6444
- createMcpHandler$1 as yn,
6445
- AgentWorkflowOrigin as yt,
6446
- EmailRoutingOptions as z,
6447
- getSubAgentByName as zn,
6448
- WorkflowStatus as zt
6818
+ ChatCapableAgentClass as $,
6819
+ RPC_DO_PREFIX as $t,
6820
+ StreamingResponse as A,
6821
+ routeSubAgentRequest as An,
6822
+ MCPAITool as At,
6823
+ AgentToolFailure as B,
6824
+ MCPOAuthCallbackResult as Bt,
6825
+ MCPServersState as C,
6826
+ SubAgentPathMatch as Cn,
6827
+ WorkflowProgressCallback as Ct,
6828
+ StartFiberOptions as D,
6829
+ buildSubAgentPathUnchecked as Dn,
6830
+ WorkflowTrackingRow as Dt,
6831
+ RPCResponse as E,
6832
+ buildSubAgentPath as En,
6833
+ WorkflowStatus as Et,
6834
+ AgentToolChildAdapter as F,
6835
+ MCPClientManagerOptions as Ft,
6836
+ AgentToolProgressSnapshot as G,
6837
+ getNamespacedData as Gt,
6838
+ AgentToolLifecycleResult as H,
6839
+ MCPServerOptions as Ht,
6840
+ AgentToolDisplayMetadata as I,
6841
+ MCPClientOAuthCallbackConfig as It,
6842
+ AgentToolRunPart as J,
6843
+ MCPElicitationHandlers as Jt,
6844
+ AgentToolRunInfo as K,
6845
+ normalizeServerId as Kt,
6846
+ AgentToolEvent as L,
6847
+ MCPClientOAuthResult as Lt,
6848
+ routeAgentEmail as M,
6849
+ MCPClientElicitationHandler as Mt,
6850
+ AGENT_TOOL_MILESTONE_PART as N,
6851
+ MCPClientElicitationHandlers as Nt,
6852
+ StartFiberResult as O,
6853
+ getSubAgentByName as On,
6854
+ ElicitRequest$1 as Ot,
6855
+ AGENT_TOOL_PROGRESS_PART as P,
6856
+ MCPClientManager as Pt,
6857
+ AgentToolTerminalStatus as Q,
6858
+ RPCServerTransportOptions as Qt,
6859
+ AgentToolEventMessage as R,
6860
+ MCPConnectionResult as Rt,
6861
+ MCPServerMessage as S,
6862
+ SUB_PREFIX as Sn,
6863
+ WorkflowPage as St,
6864
+ RPCRequest as T,
6865
+ buildAgentUrl as Tn,
6866
+ WorkflowRejectedError as Tt,
6867
+ AgentToolMilestone as U,
6868
+ MCP_SERVER_ID_MAX_LENGTH as Ut,
6869
+ AgentToolInterruptedReason as V,
6870
+ MCPServerFilter as Vt,
6871
+ AgentToolProgress as W,
6872
+ RegisterServerOptions as Wt,
6873
+ AgentToolRunStatus as X,
6874
+ RPCClientTransportOptions as Xt,
6875
+ AgentToolRunState as Y,
6876
+ RPCClientTransport as Yt,
6877
+ AgentToolStoredChunk as Z,
6878
+ RPCServerTransport as Zt,
6879
+ FiberRecoveryContext as _,
6880
+ StreamableHTTPEdgeClientTransport as _n,
6881
+ WorkflowCompleteCallback as _t,
6882
+ routeAgentRequest as a,
6883
+ DurableObjectEventStore as an,
6884
+ AgentWorkflowInternalParams as at,
6885
+ ListFibersOptions as b,
6886
+ AgentPathStep as bn,
6887
+ WorkflowEventPayload as bt,
6888
+ Agent as c,
6889
+ CreateLegacyMcpHandlerOptions as cn,
6890
+ AgentWorkflowPathStep as ct,
6891
+ AgentStaticOptions as d,
6892
+ createLegacyMcpHandler as dn,
6893
+ DefaultProgress as dt,
6894
+ ElicitRequest$2 as en,
6895
+ DetachedAgentToolConfig as et,
6896
+ DEFAULT_AGENT_STATIC_OPTIONS as f,
6897
+ MCPStorageApi as fn,
6898
+ RunWorkflowOptions as ft,
6899
+ FiberInspection as g,
6900
+ SSEEdgeClientTransport as gn,
6901
+ WorkflowCallbackType as gt,
6902
+ FiberContext as h,
6903
+ WorkerTransportOptions as hn,
6904
+ WorkflowCallbackBase as ht,
6905
+ getAgentByName as i,
6906
+ ClearableEventStore as in,
6907
+ AgentWorkflowEvent as it,
6908
+ getCurrentAgent as j,
6909
+ withInvocationScope as jn,
6910
+ MCPAIToolSet as jt,
6911
+ StateUpdateMessage as k,
6912
+ parseSubAgentPath as kn,
6913
+ ElicitResult$2 as kt,
6914
+ AgentContext as l,
6915
+ CreateMcpHandlerOptions$1 as ln,
6916
+ AgentWorkflowStep as lt,
6917
+ EmailRoutingOptions as m,
6918
+ WorkerTransport as mn,
6919
+ WorkflowCallback as mt,
6920
+ AgentOptions as n,
6921
+ ElicitResult$3 as nn,
6922
+ RunAgentToolOptions as nt,
6923
+ AddMcpServerOptions as o,
6924
+ createMcpHandler$1 as on,
6925
+ AgentWorkflowOrigin as ot,
6926
+ DeleteFibersOptions as p,
6927
+ TransportState as pn,
6928
+ WaitForApprovalOptions as pt,
6929
+ AgentToolRunInspection as q,
6930
+ MCPElicitationHandler as qt,
6931
+ RoutingRetryOptions as r,
6932
+ McpAgent as rn,
6933
+ RunAgentToolResult as rt,
6934
+ AddRpcMcpServerOptions as s,
6935
+ experimental_createMcpHandler as sn,
6936
+ AgentWorkflowParams as st,
6937
+ AgentGetOptions as t,
6938
+ ElicitRequestSchema as tn,
6939
+ DetachedRunAgentToolResult as tt,
6940
+ AgentNamespace as u,
6941
+ LegacyMcpHandler as un,
6942
+ ApprovalEventPayload as ut,
6943
+ FiberRecoveryResult as v,
6944
+ DynamicAgentClass as vn,
6945
+ WorkflowErrorCallback as vt,
6946
+ QueueItem as w,
6947
+ buildAgentPath as wn,
6948
+ WorkflowQueryCriteria as wt,
6949
+ MCPServer as x,
6950
+ BuildAgentPathOptions as xn,
6951
+ WorkflowInfo as xt,
6952
+ FiberStatus as y,
6953
+ DynamicAgentStub as yn,
6954
+ WorkflowEventCallback as yt,
6955
+ AgentToolEventState as z,
6956
+ MCPDiscoverResult as zt
6449
6957
  };
6450
- //# sourceMappingURL=agent-tool-types-CzGGB-20.d.ts.map
6958
+ //# sourceMappingURL=agent-routing-DE5zmCQ8.d.ts.map