agents 0.11.9 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +47 -1
  2. package/dist/{index-DSwOzhhd.d.ts → agent-tool-types-CB7nISDE.d.ts} +706 -100
  3. package/dist/agent-tool-types.d.ts +34 -0
  4. package/dist/agent-tool-types.js +1 -0
  5. package/dist/agent-tools-BAdX1vdI.js +425 -0
  6. package/dist/agent-tools-BAdX1vdI.js.map +1 -0
  7. package/dist/agent-tools-Bb1O8blK.d.ts +14 -0
  8. package/dist/agent-tools.d.ts +68 -0
  9. package/dist/agent-tools.js +51 -0
  10. package/dist/agent-tools.js.map +1 -0
  11. package/dist/browser/ai.d.ts +1 -1
  12. package/dist/browser/ai.js +2 -2
  13. package/dist/browser/index.d.ts +1 -1
  14. package/dist/browser/index.js +1 -1
  15. package/dist/browser/tanstack-ai.d.ts +1 -1
  16. package/dist/browser/tanstack-ai.js +1 -1
  17. package/dist/chat/index.d.ts +4 -1
  18. package/dist/chat/index.js +34 -300
  19. package/dist/chat/index.js.map +1 -1
  20. package/dist/client.d.ts +2 -2
  21. package/dist/{compaction-helpers-C_cN3z55.js → compaction-helpers-CSaqCmdE.js} +1 -1
  22. package/dist/{compaction-helpers-C_cN3z55.js.map → compaction-helpers-CSaqCmdE.js.map} +1 -1
  23. package/dist/{compaction-helpers-YzCLvunJ.d.ts → compaction-helpers-D92Ipstp.d.ts} +1 -1
  24. package/dist/experimental/memory/session/index.d.ts +1 -1
  25. package/dist/experimental/memory/session/index.js +1 -1
  26. package/dist/experimental/memory/utils/index.d.ts +1 -1
  27. package/dist/experimental/memory/utils/index.js +1 -1
  28. package/dist/index.d.ts +74 -42
  29. package/dist/index.js +1803 -284
  30. package/dist/index.js.map +1 -1
  31. package/dist/mcp/client.d.ts +1 -1
  32. package/dist/mcp/index.d.ts +1 -1
  33. package/dist/react.d.ts +16 -2
  34. package/dist/react.js +51 -1
  35. package/dist/react.js.map +1 -1
  36. package/dist/{serializable-Bg8ARWlN.d.ts → serializable-Brg7fRds.d.ts} +1 -1
  37. package/dist/serializable.d.ts +1 -1
  38. package/dist/{shared-mfBbxjS1.js → shared-C6l4ZKRN.js} +1 -1
  39. package/dist/{shared-mfBbxjS1.js.map → shared-C6l4ZKRN.js.map} +1 -1
  40. package/dist/{shared-BUHZFGTk.d.ts → shared-Ch9slKdI.d.ts} +1 -1
  41. package/dist/sub-routing.d.ts +6 -6
  42. package/dist/sub-routing.js +7 -1
  43. package/dist/sub-routing.js.map +1 -1
  44. package/dist/workflows.d.ts +1 -1
  45. package/package.json +10 -5
@@ -16,6 +16,7 @@ import {
16
16
  } from "./workflow-types-DHs0L0KP.js";
17
17
  import { t as MessageType } from "./types-DAHCZC_W.js";
18
18
  import { r as EmailResolver } from "./email-X72-zjuq.js";
19
+ import { ToolSet, UIMessage } from "ai";
19
20
  import { RpcTarget } from "cloudflare:workers";
20
21
  import {
21
22
  Connection,
@@ -24,7 +25,8 @@ import {
24
25
  ConnectionContext as ConnectionContext$1,
25
26
  PartyServerOptions,
26
27
  Server,
27
- WSMessage
28
+ WSMessage,
29
+ WSMessage as WSMessage$1
28
30
  } from "partyserver";
29
31
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
30
32
  import {
@@ -54,9 +56,8 @@ import {
54
56
  Resource,
55
57
  ResourceTemplate,
56
58
  ServerCapabilities,
57
- Tool
59
+ Tool as Tool$1
58
60
  } from "@modelcontextprotocol/sdk/types.js";
59
- import { ToolSet } from "ai";
60
61
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
61
62
  import { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
62
63
  import {
@@ -615,7 +616,7 @@ declare class MCPClientConnection {
615
616
  connectionError: string | null;
616
617
  lastConnectedTransport: BaseTransportType | undefined;
617
618
  instructions?: string;
618
- tools: Tool[];
619
+ tools: Tool$1[];
619
620
  private _transport?;
620
621
  prompts: Prompt[];
621
622
  resources: Resource[];
@@ -675,7 +676,7 @@ declare class MCPClientConnection {
675
676
  * Notification handler registration for tools
676
677
  * Should only be called if serverCapabilities.tools exists
677
678
  */
678
- registerTools(): Promise<Tool[]>;
679
+ registerTools(): Promise<Tool$1[]>;
679
680
  /**
680
681
  * Notification handler registration for resources
681
682
  * Should only be called if serverCapabilities.resources exists
@@ -1517,7 +1518,7 @@ declare class MCPClientManager {
1517
1518
  }>;
1518
1519
  }
1519
1520
  type NamespacedData = {
1520
- tools: (Tool & {
1521
+ tools: (Tool$1 & {
1521
1522
  serverId: string;
1522
1523
  })[];
1523
1524
  prompts: (Prompt & {
@@ -1647,6 +1648,54 @@ declare class SqlError extends Error {
1647
1648
  readonly query: string;
1648
1649
  constructor(query: string, cause: unknown);
1649
1650
  }
1651
+ type SubAgentConnectionMeta = {
1652
+ id: string;
1653
+ uri: string | null;
1654
+ tags: string[];
1655
+ state: unknown;
1656
+ requestHeaders?: [string, string][];
1657
+ };
1658
+ type SubAgentConnectionBridgeLike = {
1659
+ send(message: string | ArrayBuffer | ArrayBufferView): void;
1660
+ close(code?: number, reason?: string): void;
1661
+ setState(state: unknown): unknown;
1662
+ broadcast(
1663
+ ownerPath: ReadonlyArray<{
1664
+ className: string;
1665
+ name: string;
1666
+ }>,
1667
+ message: string | ArrayBuffer | ArrayBufferView,
1668
+ without?: string[]
1669
+ ): void;
1670
+ };
1671
+ declare class SubAgentConnectionBridge
1672
+ extends RpcTarget
1673
+ implements SubAgentConnectionBridgeLike
1674
+ {
1675
+ #private;
1676
+ constructor(
1677
+ connection: Connection,
1678
+ broadcast?: (
1679
+ ownerPath: ReadonlyArray<{
1680
+ className: string;
1681
+ name: string;
1682
+ }>,
1683
+ message: string | ArrayBuffer | ArrayBufferView,
1684
+ without?: string[]
1685
+ ) => void
1686
+ );
1687
+ send(message: string | ArrayBuffer | ArrayBufferView): void;
1688
+ close(code?: number, reason?: string): void;
1689
+ setState(state: unknown): unknown;
1690
+ broadcast(
1691
+ ownerPath: ReadonlyArray<{
1692
+ className: string;
1693
+ name: string;
1694
+ }>,
1695
+ message: string | ArrayBuffer | ArrayBufferView,
1696
+ without?: string[]
1697
+ ): void;
1698
+ }
1650
1699
  /**
1651
1700
  * Constructor type for a sub-agent class.
1652
1701
  * Used by {@link Agent.subAgent} to reference the child class
@@ -1737,6 +1786,34 @@ type Schedule<T = string> = {
1737
1786
  intervalSeconds: number;
1738
1787
  }
1739
1788
  );
1789
+ type AgentPathStep = {
1790
+ className: string;
1791
+ name: string;
1792
+ };
1793
+ type ScheduleStorageRow = {
1794
+ id: string;
1795
+ callback: string;
1796
+ payload: string;
1797
+ type: "scheduled" | "delayed" | "cron" | "interval";
1798
+ time: number;
1799
+ delayInSeconds?: number;
1800
+ cron?: string;
1801
+ intervalSeconds?: number;
1802
+ retry?: RetryOptions;
1803
+ running?: number;
1804
+ execution_started_at?: number | null;
1805
+ retry_options?: string | null;
1806
+ owner_path?: string | null;
1807
+ owner_path_key?: string | null;
1808
+ };
1809
+ type ScheduleCriteria = {
1810
+ id?: string;
1811
+ type?: "scheduled" | "delayed" | "cron" | "interval";
1812
+ timeRange?: {
1813
+ start?: Date;
1814
+ end?: Date;
1815
+ };
1816
+ };
1740
1817
  /**
1741
1818
  * Context passed to the `runFiber` callback. Provides checkpoint
1742
1819
  * and identity for durable execution.
@@ -1774,7 +1851,7 @@ type MCPServersState = {
1774
1851
  servers: {
1775
1852
  [id: string]: MCPServer;
1776
1853
  };
1777
- tools: (Tool & {
1854
+ tools: (Tool$1 & {
1778
1855
  serverId: string;
1779
1856
  })[];
1780
1857
  prompts: (Prompt & {
@@ -1912,6 +1989,15 @@ declare class Agent<
1912
1989
  private _persistenceHookMode;
1913
1990
  /** True when this agent runs as a facet (sub-agent) inside a parent. */
1914
1991
  private _isFacet;
1992
+ /**
1993
+ * True only while the internal facet bootstrap RPC runs startup.
1994
+ * Startup may happen while the parent is handling a WebSocket
1995
+ * message, so protocol broadcasts must not touch any ambient
1996
+ * parent-owned WebSocket handles during this window.
1997
+ */
1998
+ private _suppressProtocolBroadcasts;
1999
+ private _cf_currentSubAgentBridge?;
2000
+ private _cf_virtualSubAgentConnections;
1915
2001
  /**
1916
2002
  * Ancestor chain, root-first. Empty for top-level DOs; populated at
1917
2003
  * facet init time from the parent's own `selfPath`. Exposed publicly
@@ -1931,6 +2017,13 @@ declare class Agent<
1931
2017
  * @internal
1932
2018
  */
1933
2019
  _keepAliveRefs: number;
2020
+ /**
2021
+ * In-memory tokens for keepAlive leases acquired by facets and held
2022
+ * on the root alarm owner. Lost on eviction, like `_keepAliveRefs`,
2023
+ * because the in-memory work those leases were protecting is also gone.
2024
+ * @internal
2025
+ */
2026
+ private _facetKeepAliveTokens;
1934
2027
  /** @internal In-memory set of fiber IDs running in this process. */
1935
2028
  private _runFiberActiveFibers;
1936
2029
  /** @internal Prevents re-entrant recovery from overlapping alarm ticks. */
@@ -2301,6 +2394,152 @@ declare class Agent<
2301
2394
  * @returns Array of matching QueueItem objects
2302
2395
  */
2303
2396
  getQueues(key: string, value: string): QueueItem<string>[];
2397
+ private _scheduleOwnerPathKey;
2398
+ private _facetRunRowsForPrefix;
2399
+ private _deleteFacetRunRowsForPrefix;
2400
+ private _rootAlarmOwner;
2401
+ private _validateScheduleCallback;
2402
+ /**
2403
+ * Insert (or, for idempotent calls, return the existing row for) a
2404
+ * schedule owned by either this top-level agent (`ownerPath === null`)
2405
+ * or a descendant facet. Returns `{ schedule, created }` — `created`
2406
+ * is `false` when an idempotent insert deduplicates onto an existing
2407
+ * row, so callers can suppress the `schedule:create` event in that
2408
+ * case to match historic semantics.
2409
+ * @internal
2410
+ */
2411
+ private _insertScheduleForOwner;
2412
+ /**
2413
+ * Insert a schedule row owned by a descendant facet. Called via RPC
2414
+ * from the facet's `schedule()`. Returns `{ schedule, created }`
2415
+ * so the originating facet can suppress `schedule:create` on
2416
+ * idempotent dedup. This method does not emit observability
2417
+ * events itself.
2418
+ * @internal
2419
+ */
2420
+ _cf_scheduleForFacet<T = string>(
2421
+ ownerPath: ReadonlyArray<AgentPathStep>,
2422
+ when: Date | string | number,
2423
+ callback: string,
2424
+ payload?: T,
2425
+ options?: {
2426
+ retry?: RetryOptions;
2427
+ idempotent?: boolean;
2428
+ }
2429
+ ): Promise<{
2430
+ schedule: Schedule<T>;
2431
+ created: boolean;
2432
+ }>;
2433
+ /**
2434
+ * Insert (or, for idempotent calls, return the existing row for) an
2435
+ * interval schedule. Mirrors {@link _insertScheduleForOwner} —
2436
+ * returns `{ schedule, created }` so callers can suppress
2437
+ * `schedule:create` on dedup.
2438
+ * @internal
2439
+ */
2440
+ private _insertIntervalScheduleForOwner;
2441
+ /**
2442
+ * Insert an interval schedule row owned by a descendant facet.
2443
+ * Called via RPC from the facet's `scheduleEvery()`. Returns
2444
+ * `{ schedule, created }` so the originating facet can suppress
2445
+ * `schedule:create` on idempotent dedup. This method does not
2446
+ * emit observability events itself.
2447
+ * @internal
2448
+ */
2449
+ _cf_scheduleEveryForFacet<T = string>(
2450
+ ownerPath: ReadonlyArray<AgentPathStep>,
2451
+ intervalSeconds: number,
2452
+ callback: string,
2453
+ payload?: T,
2454
+ options?: {
2455
+ retry?: RetryOptions;
2456
+ _idempotent?: boolean;
2457
+ }
2458
+ ): Promise<{
2459
+ schedule: Schedule<T>;
2460
+ created: boolean;
2461
+ }>;
2462
+ /**
2463
+ * Cancel a schedule row owned by a descendant facet, scoped by
2464
+ * `owner_path_key` so siblings can't reach each other's rows.
2465
+ * Returns the canceled row's callback name so the originating
2466
+ * facet can emit `schedule:cancel`. This method does not emit
2467
+ * observability events itself.
2468
+ * @internal
2469
+ */
2470
+ _cf_cancelScheduleForFacet(
2471
+ ownerPath: ReadonlyArray<AgentPathStep>,
2472
+ id: string
2473
+ ): Promise<{
2474
+ ok: boolean;
2475
+ callback?: string;
2476
+ }>;
2477
+ /**
2478
+ * Clean root-owned bookkeeping for a sub-tree of facets. This
2479
+ * bulk-cancels schedules whose `owner_path` starts with the given
2480
+ * prefix and deletes root-side facet fiber recovery leases for the
2481
+ * same sub-tree. Used by `deleteSubAgent` and recursive facet
2482
+ * destroy. Emits `schedule:cancel` on this agent (the alarm-owning
2483
+ * root) for each schedule row removed — the facets being torn down
2484
+ * may not be alive to receive the events themselves.
2485
+ * @internal
2486
+ */
2487
+ _cf_cleanupFacetPrefix(
2488
+ ownerPath: ReadonlyArray<AgentPathStep>
2489
+ ): Promise<void>;
2490
+ private _scheduleRowToSchedule;
2491
+ private _getScheduleForOwner;
2492
+ private _listSchedulesForOwner;
2493
+ /**
2494
+ * Read a single schedule row owned by a descendant facet.
2495
+ * @internal
2496
+ */
2497
+ _cf_getScheduleForFacet(
2498
+ ownerPath: ReadonlyArray<AgentPathStep>,
2499
+ id: string
2500
+ ): Promise<Schedule<unknown> | undefined>;
2501
+ /**
2502
+ * List schedule rows owned by a descendant facet, scoped by
2503
+ * `owner_path_key` so siblings remain isolated from each other.
2504
+ * @internal
2505
+ */
2506
+ _cf_listSchedulesForFacet(
2507
+ ownerPath: ReadonlyArray<AgentPathStep>,
2508
+ criteria?: ScheduleCriteria
2509
+ ): Promise<Schedule<unknown>[]>;
2510
+ /**
2511
+ * Acquire a root-owned keepAlive ref on behalf of a descendant facet.
2512
+ * Facets share the root isolate but cannot set their own physical
2513
+ * alarm, so this lets facet work use the root alarm heartbeat.
2514
+ * @internal
2515
+ */
2516
+ _cf_acquireFacetKeepAlive(
2517
+ ownerPath: ReadonlyArray<AgentPathStep>
2518
+ ): Promise<string>;
2519
+ /**
2520
+ * Release a root-owned keepAlive ref previously acquired for a facet.
2521
+ * Idempotent so disposer calls can safely race or run twice.
2522
+ * @internal
2523
+ */
2524
+ _cf_releaseFacetKeepAlive(token: string): Promise<void>;
2525
+ /**
2526
+ * Register a facet's durable run row in the root-side index so root
2527
+ * alarm housekeeping can dispatch recovery checks into idle facets.
2528
+ * The facet remains authoritative for snapshots and recovery hooks.
2529
+ * @internal
2530
+ */
2531
+ _cf_registerFacetRun(
2532
+ ownerPath: ReadonlyArray<AgentPathStep>,
2533
+ runId: string
2534
+ ): Promise<void>;
2535
+ /**
2536
+ * Remove a completed facet fiber from the root-side index.
2537
+ * @internal
2538
+ */
2539
+ _cf_unregisterFacetRun(
2540
+ ownerPath: ReadonlyArray<AgentPathStep>,
2541
+ runId: string
2542
+ ): Promise<void>;
2304
2543
  /**
2305
2544
  * Schedule a task to be executed in the future
2306
2545
  *
@@ -2372,24 +2611,52 @@ declare class Agent<
2372
2611
  * @template T Type of the payload data
2373
2612
  * @param id ID of the scheduled task
2374
2613
  * @returns The Schedule object or undefined if not found
2614
+ * @deprecated Use {@link getScheduleById}. This synchronous API cannot cross
2615
+ * Durable Object boundaries and throws inside sub-agents.
2375
2616
  */
2376
2617
  getSchedule<T = string>(id: string): Schedule<T> | undefined;
2618
+ /**
2619
+ * Get a scheduled task by ID.
2620
+ *
2621
+ * Unlike the deprecated synchronous {@link getSchedule}, this works inside
2622
+ * sub-agents by delegating to the top-level parent that owns the alarm.
2623
+ *
2624
+ * @template T Type of the payload data
2625
+ * @param id ID of the scheduled task
2626
+ * @returns The Schedule object or undefined if not found
2627
+ */
2628
+ getScheduleById(id: string): Promise<Schedule<unknown> | undefined>;
2377
2629
  /**
2378
2630
  * Get scheduled tasks matching the given criteria
2379
2631
  * @template T Type of the payload data
2380
2632
  * @param criteria Criteria to filter schedules
2381
2633
  * @returns Array of matching Schedule objects
2634
+ * @deprecated Use {@link listSchedules}. This synchronous API cannot cross
2635
+ * Durable Object boundaries and throws inside sub-agents.
2382
2636
  */
2383
- getSchedules<T = string>(criteria?: {
2384
- id?: string;
2385
- type?: "scheduled" | "delayed" | "cron" | "interval";
2386
- timeRange?: {
2387
- start?: Date;
2388
- end?: Date;
2389
- };
2390
- }): Schedule<T>[];
2637
+ getSchedules<T = string>(criteria?: ScheduleCriteria): Schedule<T>[];
2638
+ /**
2639
+ * List scheduled tasks matching the given criteria.
2640
+ *
2641
+ * Unlike the deprecated synchronous {@link getSchedules}, this works inside
2642
+ * sub-agents by delegating to the top-level parent that owns the alarm.
2643
+ *
2644
+ * @template T Type of the payload data
2645
+ * @param criteria Criteria to filter schedules
2646
+ * @returns Array of matching Schedule objects
2647
+ */
2648
+ listSchedules(criteria?: ScheduleCriteria): Promise<Schedule<unknown>[]>;
2391
2649
  /**
2392
- * Cancel a scheduled task
2650
+ * Cancel a scheduled task.
2651
+ *
2652
+ * Schedules are isolated by owner: a top-level agent's
2653
+ * `cancelSchedule(id)` only matches its own schedules, and a
2654
+ * sub-agent's `cancelSchedule(id)` only matches schedules it
2655
+ * created. To clear every schedule under a sub-agent (and its
2656
+ * descendants), call `parent.deleteSubAgent(Cls, name)` from the
2657
+ * parent — that bulk-cleans root-owned bookkeeping via
2658
+ * {@link _cf_cleanupFacetPrefix}.
2659
+ *
2393
2660
  * @param id ID of the task to cancel
2394
2661
  * @returns true if the task was cancelled, false if the task was not found
2395
2662
  */
@@ -2404,11 +2671,8 @@ declare class Agent<
2404
2671
  * alarm system, without creating schedule rows or emitting observability
2405
2672
  * events. Configure via `static options = { keepAliveIntervalMs: 5000 }`.
2406
2673
  *
2407
- * No-op on facets. Facets share the parent's isolate and don't
2408
- * need a separate alarm heartbeat the parent's own activity,
2409
- * any open WebSocket to the facet, and any in-flight Promise
2410
- * already keep the shared machine alive for the duration of
2411
- * real work.
2674
+ * In facets, delegates the physical heartbeat to the root parent
2675
+ * because facets do not have independent alarm slots.
2412
2676
  *
2413
2677
  * @example
2414
2678
  * ```ts
@@ -2482,6 +2746,55 @@ declare class Agent<
2482
2746
  private _checkRunFibers;
2483
2747
  /** @internal */
2484
2748
  _onAlarmHousekeeping(): Promise<void>;
2749
+ private _isSameAgentPathPrefix;
2750
+ /**
2751
+ * Root-side scan for durable fibers owned by descendant facets.
2752
+ * `cf_agents_facet_runs` is only an index; actual snapshots and
2753
+ * recovery hooks live in each facet's own `cf_agents_runs` table.
2754
+ * @internal
2755
+ */
2756
+ private _checkFacetRunFibers;
2757
+ /**
2758
+ * Dispatch a runFiber recovery check into the facet identified by
2759
+ * `ownerPath`. Returns the number of remaining local `cf_agents_runs`
2760
+ * rows on the target facet after recovery.
2761
+ * @internal
2762
+ */
2763
+ _cf_checkRunFibersForFacet(
2764
+ ownerPath: ReadonlyArray<AgentPathStep>
2765
+ ): Promise<number>;
2766
+ /**
2767
+ * Dispatch a scheduled callback into the facet identified by
2768
+ * `ownerPath`. Walks one step at a time: if `ownerPath` matches
2769
+ * `selfPath`, executes the callback locally; otherwise resolves
2770
+ * the next descendant facet and recurses through its own RPC.
2771
+ *
2772
+ * Called by the root's `alarm()` (which owns the physical alarm
2773
+ * for facet-owned schedules) and by intermediate facets while
2774
+ * walking down the chain.
2775
+ * @internal
2776
+ */
2777
+ _cf_dispatchScheduledCallback(
2778
+ ownerPath: ReadonlyArray<AgentPathStep>,
2779
+ row: ScheduleStorageRow
2780
+ ): Promise<void>;
2781
+ /**
2782
+ * Recursively destroy a descendant facet identified by
2783
+ * `targetPath`. Walks down from `selfPath` until reaching the
2784
+ * target's immediate parent, where it cancels the target's
2785
+ * parent-owned schedules (and any descendants), removes the
2786
+ * target from the registry, and calls `ctx.facets.delete` to
2787
+ * wipe the target's storage.
2788
+ *
2789
+ * Called by a facet's own `destroy()` (via the root) so that
2790
+ * `this.destroy()` inside a sub-agent results in the same
2791
+ * cleanup as `parent.deleteSubAgent(Cls, name)` from the parent.
2792
+ * @internal
2793
+ */
2794
+ _cf_destroyDescendantFacet(
2795
+ targetPath: ReadonlyArray<AgentPathStep>
2796
+ ): Promise<void>;
2797
+ private _executeScheduleCallback;
2485
2798
  private _scheduleNextAlarm;
2486
2799
  /**
2487
2800
  * Override PartyServer's onAlarm hook as a no-op.
@@ -2520,6 +2833,76 @@ declare class Agent<
2520
2833
  * @experimental The API surface may change before stabilizing.
2521
2834
  */
2522
2835
  fetch(request: Request): Promise<Response>;
2836
+ broadcast(
2837
+ msg: string | ArrayBuffer | ArrayBufferView,
2838
+ without?: string[]
2839
+ ): void;
2840
+ getConnection<TState = unknown>(id: string): Connection<TState> | undefined;
2841
+ getConnections<TState = unknown>(tag?: string): Iterable<Connection<TState>>;
2842
+ private _cf_broadcastToParentSubAgent;
2843
+ _cf_broadcastToSubAgent(
2844
+ ownerPath: ReadonlyArray<AgentPathStep>,
2845
+ message: string | ArrayBuffer | ArrayBufferView,
2846
+ without?: string[]
2847
+ ): Promise<void>;
2848
+ _cf_subAgentConnectionMetas(
2849
+ ownerPath: ReadonlyArray<AgentPathStep>
2850
+ ): Promise<SubAgentConnectionMeta[]>;
2851
+ _cf_sendToSubAgentConnection(
2852
+ connectionId: string,
2853
+ message: string | ArrayBuffer | ArrayBufferView
2854
+ ): Promise<void>;
2855
+ _cf_closeSubAgentConnection(
2856
+ connectionId: string,
2857
+ code?: number,
2858
+ reason?: string
2859
+ ): Promise<void>;
2860
+ _cf_setSubAgentConnectionState(
2861
+ connectionId: string,
2862
+ state: unknown
2863
+ ): Promise<unknown>;
2864
+ private _cf_subAgentConnectionMetaForPath;
2865
+ private _cf_subAgentTargetPath;
2866
+ private _cf_subAgentPathFromOuterUri;
2867
+ private _isSameAgentPath;
2868
+ private _cf_connectionHasSubAgentTarget;
2869
+ protected _cf_connectionTargetsSubAgent(connection: Connection): boolean;
2870
+ /**
2871
+ * Returns true when the current request is addressed to a child facet of
2872
+ * this agent rather than to this agent itself.
2873
+ *
2874
+ * Chat-style subclasses wrap `onConnect` before the base Agent forwarding
2875
+ * wrapper runs, so they need a request-level check to avoid sending their
2876
+ * own protocol frames on sockets that are about to be forwarded to a child.
2877
+ */
2878
+ protected _cf_requestTargetsSubAgent(request: Request): boolean;
2879
+ private _cf_forwardSubAgentWebSocketConnect;
2880
+ private _cf_createSubAgentConnectionBridge;
2881
+ private _cf_forwardSubAgentWebSocketMessage;
2882
+ private _cf_forwardSubAgentWebSocketClose;
2883
+ private _cf_resolveSubAgentConnection;
2884
+ _cf_handleSubAgentWebSocketConnect(
2885
+ bridge: SubAgentConnectionBridge,
2886
+ meta: SubAgentConnectionMeta
2887
+ ): Promise<void>;
2888
+ _cf_handleSubAgentWebSocketMessage(
2889
+ message: WSMessage,
2890
+ bridge: SubAgentConnectionBridge,
2891
+ meta: SubAgentConnectionMeta
2892
+ ): Promise<void>;
2893
+ _cf_handleSubAgentWebSocketClose(
2894
+ code: number,
2895
+ reason: string,
2896
+ wasClean: boolean,
2897
+ bridge: SubAgentConnectionBridge,
2898
+ meta: SubAgentConnectionMeta
2899
+ ): Promise<void>;
2900
+ private _cf_runWithSubAgentBridge;
2901
+ private _cf_createSubAgentBridgeConnection;
2902
+ private _cf_storeVirtualSubAgentConnection;
2903
+ protected _cf_hydrateSubAgentConnectionsFromRoot(): Promise<void>;
2904
+ private _cf_getRawConnectionState;
2905
+ private _cf_getForwardedSubAgentState;
2523
2906
  /**
2524
2907
  * Parent-side middleware hook. Fires before a request is
2525
2908
  * forwarded into a facet sub-agent. Mirrors `onBeforeConnect` /
@@ -2602,10 +2985,10 @@ declare class Agent<
2602
2985
  * We set `_isFacet` eagerly (before `__unsafe_ensureInitialized`
2603
2986
  * runs `onStart()`) so any code that legitimately branches on it
2604
2987
  * — e.g. skipping parent-owned alarms in schedule guards — sees
2605
- * the flag during the first `onStart()` run. Broadcast paths no
2606
- * longer special-case facets, since facets can be directly
2607
- * addressed via sub-agent routing and have their own WebSocket
2608
- * connections.
2988
+ * the flag during the first `onStart()` run. Protocol broadcasts are
2989
+ * suppressed only during this bootstrap window; afterward, facets can
2990
+ * broadcast to their own WebSocket clients reached via sub-agent
2991
+ * routing.
2609
2992
  *
2610
2993
  * The facet's name (and `this.name` getter) is handled entirely by
2611
2994
  * partyserver via `ctx.id.name`, which is populated because the
@@ -2721,6 +3104,45 @@ declare class Agent<
2721
3104
  cls: SubAgentClass<T>,
2722
3105
  name: string
2723
3106
  ): Promise<SubAgentStub<T>>;
3107
+ /** Maximum number of non-terminal agent-tool runs this parent may own at once. */
3108
+ maxConcurrentAgentTools: number;
3109
+ onAgentToolStart(_run: AgentToolRunInfo): Promise<void>;
3110
+ onAgentToolFinish(
3111
+ _run: AgentToolRunInfo,
3112
+ _result: AgentToolLifecycleResult
3113
+ ): Promise<void>;
3114
+ runAgentTool<Input = unknown, Output = unknown>(
3115
+ cls: ChatCapableAgentClass,
3116
+ options: RunAgentToolOptions<Input>
3117
+ ): Promise<RunAgentToolResult<Output>>;
3118
+ hasAgentToolRun<T extends Agent>(
3119
+ cls: SubAgentClass<T>,
3120
+ runId: string
3121
+ ): boolean;
3122
+ hasAgentToolRun(agentType: string, runId: string): boolean;
3123
+ clearAgentToolRuns(options?: {
3124
+ olderThan?: number;
3125
+ status?: AgentToolRunStatus[];
3126
+ }): Promise<void>;
3127
+ private _isAgentToolTerminal;
3128
+ private _activeAgentToolRunCount;
3129
+ private _defaultAgentToolPreview;
3130
+ private _readAgentToolRun;
3131
+ private _resultFromAgentToolRow;
3132
+ private _terminalResultFromInspection;
3133
+ private _updateAgentToolTerminal;
3134
+ private _markAgentToolRunning;
3135
+ private _parseAgentToolJson;
3136
+ private _stringifyAgentToolOutput;
3137
+ private _broadcastAgentToolEvent;
3138
+ private _broadcastAgentToolChunks;
3139
+ private _forwardAgentToolStream;
3140
+ private _broadcastAgentToolTerminal;
3141
+ private _asAgentToolChildAdapter;
3142
+ private _agentToolClassByName;
3143
+ private _replayAndInterruptAgentToolRun;
3144
+ private _replayAgentToolRuns;
3145
+ private _reconcileAgentToolRuns;
2724
3146
  /**
2725
3147
  * Shared facet resolution — takes a CamelCase class name string
2726
3148
  * (matching `ctx.exports`) rather than a class reference. Both
@@ -2753,7 +3175,7 @@ declare class Agent<
2753
3175
  * @param cls The Agent subclass used when creating the child
2754
3176
  * @param name Name of the child to delete
2755
3177
  */
2756
- deleteSubAgent(cls: SubAgentClass, name: string): void;
3178
+ deleteSubAgent(cls: SubAgentClass, name: string): Promise<void>;
2757
3179
  /** @internal */
2758
3180
  private _subAgentRegistryReady;
2759
3181
  /** @internal */
@@ -2803,9 +3225,23 @@ declare class Agent<
2803
3225
  createdAt: number;
2804
3226
  }>;
2805
3227
  /**
2806
- * Destroy the Agent, removing all state and scheduled tasks
3228
+ * Destroy the Agent, removing all state and scheduled tasks.
3229
+ *
3230
+ * On a top-level agent: drops every table, clears the alarm, and
3231
+ * aborts the isolate.
3232
+ *
3233
+ * On a sub-agent (facet): delegates teardown to the immediate
3234
+ * parent so the parent-owned schedule rows for this sub-agent
3235
+ * (and any of its descendants) are cancelled, the parent's
3236
+ * `cf_agents_sub_agents` registry entry is cleared, and
3237
+ * `ctx.facets.delete` wipes the facet's own storage. The
3238
+ * `ctx.facets.delete` call aborts this isolate, so this method
3239
+ * may not return cleanly when invoked from inside the facet —
3240
+ * callers should treat it as fire-and-forget.
2807
3241
  */
2808
3242
  destroy(): Promise<void>;
3243
+ /** @internal Drop every internal Agents SDK table during top-level destroy. */
3244
+ protected _dropInternalTablesForDestroy(): void;
2809
3245
  /**
2810
3246
  * Check if a method is callable
2811
3247
  * @param method The method name to check
@@ -3391,78 +3827,248 @@ declare class StreamingResponse {
3391
3827
  error(message: string): boolean;
3392
3828
  }
3393
3829
  //#endregion
3830
+ //#region src/agent-tool-types.d.ts
3831
+ type AgentToolRunStatus =
3832
+ | "starting"
3833
+ | "running"
3834
+ | "completed"
3835
+ | "error"
3836
+ | "aborted"
3837
+ | "interrupted";
3838
+ type AgentToolTerminalStatus = Extract<
3839
+ AgentToolRunStatus,
3840
+ "completed" | "error" | "aborted" | "interrupted"
3841
+ >;
3842
+ type AgentToolDisplayMetadata = {
3843
+ name?: string;
3844
+ icon?: string;
3845
+ } & Record<string, unknown>;
3846
+ type AgentToolRunInfo = {
3847
+ runId: string;
3848
+ parentToolCallId?: string;
3849
+ agentType: string;
3850
+ inputPreview?: unknown;
3851
+ status: AgentToolRunStatus;
3852
+ display?: AgentToolDisplayMetadata;
3853
+ displayOrder: number;
3854
+ startedAt: number;
3855
+ completedAt?: number;
3856
+ };
3857
+ type AgentToolLifecycleResult = {
3858
+ status: AgentToolTerminalStatus;
3859
+ summary?: string;
3860
+ error?: string;
3861
+ };
3862
+ type RunAgentToolOptions<Input = unknown> = {
3863
+ input: Input;
3864
+ runId?: string;
3865
+ parentToolCallId?: string;
3866
+ displayOrder?: number;
3867
+ signal?: AbortSignal;
3868
+ inputPreview?: unknown;
3869
+ display?: AgentToolDisplayMetadata;
3870
+ };
3871
+ type RunAgentToolResult<Output = unknown> = {
3872
+ runId: string;
3873
+ agentType: string;
3874
+ status: AgentToolTerminalStatus;
3875
+ output?: Output;
3876
+ summary?: string;
3877
+ error?: string;
3878
+ };
3879
+ type ChatCapableAgentClass<T extends Agent = Agent> = SubAgentClass<T>;
3880
+ type AgentToolRunInspection<Output = unknown> = {
3881
+ runId: string;
3882
+ status: Exclude<AgentToolRunStatus, "interrupted">;
3883
+ requestId?: string;
3884
+ streamId?: string;
3885
+ output?: Output;
3886
+ summary?: string;
3887
+ error?: string;
3888
+ startedAt: number;
3889
+ completedAt?: number;
3890
+ };
3891
+ type AgentToolStoredChunk = {
3892
+ sequence: number;
3893
+ body: string;
3894
+ };
3895
+ type AgentToolChildAdapter<Input = unknown, Output = unknown> = {
3896
+ startAgentToolRun(
3897
+ input: Input,
3898
+ options: {
3899
+ runId: string;
3900
+ signal?: AbortSignal;
3901
+ }
3902
+ ): Promise<AgentToolRunInspection<Output>>;
3903
+ cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
3904
+ inspectAgentToolRun(
3905
+ runId: string
3906
+ ): Promise<AgentToolRunInspection<Output> | null>;
3907
+ getAgentToolChunks(
3908
+ runId: string,
3909
+ options?: {
3910
+ afterSequence?: number;
3911
+ }
3912
+ ): Promise<AgentToolStoredChunk[]>;
3913
+ tailAgentToolRun?(
3914
+ runId: string,
3915
+ options?: {
3916
+ afterSequence?: number;
3917
+ signal?: AbortSignal;
3918
+ }
3919
+ ): Promise<ReadableStream<AgentToolStoredChunk>>;
3920
+ };
3921
+ type AgentToolEvent =
3922
+ | {
3923
+ kind: "started";
3924
+ runId: string;
3925
+ agentType: string;
3926
+ inputPreview?: unknown;
3927
+ order: number;
3928
+ display?: AgentToolDisplayMetadata;
3929
+ }
3930
+ | {
3931
+ kind: "chunk";
3932
+ runId: string;
3933
+ body: string;
3934
+ }
3935
+ | {
3936
+ kind: "finished";
3937
+ runId: string;
3938
+ summary: string;
3939
+ }
3940
+ | {
3941
+ kind: "error";
3942
+ runId: string;
3943
+ error: string;
3944
+ }
3945
+ | {
3946
+ kind: "aborted";
3947
+ runId: string;
3948
+ reason?: string;
3949
+ }
3950
+ | {
3951
+ kind: "interrupted";
3952
+ runId: string;
3953
+ error: string;
3954
+ };
3955
+ type AgentToolEventMessage = {
3956
+ type: "agent-tool-event";
3957
+ parentToolCallId?: string;
3958
+ sequence: number;
3959
+ replay?: true;
3960
+ event: AgentToolEvent;
3961
+ };
3962
+ type AgentToolRunState = {
3963
+ runId: string;
3964
+ agentType: string;
3965
+ parentToolCallId?: string;
3966
+ inputPreview?: unknown;
3967
+ order: number;
3968
+ display?: AgentToolDisplayMetadata;
3969
+ status: "running" | "completed" | "error" | "aborted" | "interrupted";
3970
+ parts: UIMessage["parts"];
3971
+ summary?: string;
3972
+ error?: string;
3973
+ subAgent: {
3974
+ agent: string;
3975
+ name: string;
3976
+ };
3977
+ };
3978
+ type AgentToolEventState = {
3979
+ runsById: Record<string, AgentToolRunState>;
3980
+ runsByToolCallId: Record<string, AgentToolRunState[]>;
3981
+ unboundRuns: AgentToolRunState[];
3982
+ };
3983
+ //#endregion
3394
3984
  export {
3395
- ElicitRequestSchema$1 as $,
3396
- callable as A,
3397
- MCPConnectionResult as B,
3398
- SendEmailOptions as C,
3399
- SubAgentClass as D,
3400
- StreamingResponse as E,
3401
- unstable_callable as F,
3402
- RegisterServerOptions as G,
3403
- MCPOAuthCallbackResult as H,
3404
- MCPClientManager as I,
3405
- RPCClientTransportOptions as J,
3406
- getNamespacedData as K,
3407
- MCPClientManagerOptions as L,
3408
- getCurrentAgent as M,
3409
- routeAgentEmail as N,
3410
- SubAgentStub as O,
3411
- routeAgentRequest as P,
3412
- ElicitRequest$1 as Q,
3413
- MCPClientOAuthCallbackConfig as R,
3414
- Schedule as S,
3415
- StateUpdateMessage as T,
3416
- MCPServerFilter as U,
3417
- MCPDiscoverResult as V,
3418
- MCPServerOptions as W,
3419
- RPCServerTransportOptions as X,
3420
- RPCServerTransport as Y,
3421
- RPC_DO_PREFIX as Z,
3422
- MCPServerMessage as _,
3423
- parseSubAgentPath as _t,
3424
- AgentNamespace as a,
3425
- McpAuthContext as at,
3426
- RPCRequest as b,
3427
- CallableMetadata as c,
3428
- WorkerTransport as ct,
3429
- DEFAULT_AGENT_STATIC_OPTIONS as d,
3430
- StreamableHTTPEdgeClientTransport as dt,
3431
- ElicitResult$1 as et,
3432
- EmailRoutingOptions as f,
3433
- McpClientOptions as ft,
3434
- MCPServer as g,
3435
- getSubAgentByName as gt,
3436
- FiberRecoveryContext as h,
3437
- SubAgentPathMatch as ht,
3438
- AgentContext as i,
3439
- experimental_createMcpHandler as it,
3440
- getAgentByName as j,
3441
- WSMessage as k,
3442
- Connection$1 as l,
3443
- WorkerTransportOptions as lt,
3444
- FiberContext as m,
3445
- SUB_PREFIX as mt,
3446
- AddRpcMcpServerOptions as n,
3447
- CreateMcpHandlerOptions as nt,
3448
- AgentOptions as o,
3449
- getMcpAuthContext as ot,
3450
- EmailSendBinding as p,
3451
- TransportType as pt,
3452
- RPCClientTransport as q,
3453
- Agent as r,
3454
- createMcpHandler as rt,
3455
- AgentStaticOptions as s,
3456
- TransportState as st,
3457
- AddMcpServerOptions as t,
3458
- McpAgent as tt,
3459
- ConnectionContext$1 as u,
3460
- SSEEdgeClientTransport as ut,
3461
- MCPServersState as v,
3462
- routeSubAgentRequest as vt,
3463
- SqlError as w,
3464
- RPCResponse as x,
3465
- QueueItem as y,
3466
- MCPClientOAuthResult as z
3985
+ MCPClientManagerOptions as $,
3986
+ FiberRecoveryContext as A,
3987
+ SUB_PREFIX as At,
3988
+ SqlError as B,
3989
+ CallableMetadata as C,
3990
+ TransportState as Ct,
3991
+ EmailRoutingOptions as D,
3992
+ StreamableHTTPEdgeClientTransport as Dt,
3993
+ DEFAULT_AGENT_STATIC_OPTIONS as E,
3994
+ SSEEdgeClientTransport as Et,
3995
+ RPCRequest as F,
3996
+ WSMessage$1 as G,
3997
+ StreamingResponse as H,
3998
+ RPCResponse as I,
3999
+ getCurrentAgent as J,
4000
+ callable as K,
4001
+ Schedule as L,
4002
+ MCPServerMessage as M,
4003
+ getSubAgentByName as Mt,
4004
+ MCPServersState as N,
4005
+ parseSubAgentPath as Nt,
4006
+ EmailSendBinding as O,
4007
+ McpClientOptions as Ot,
4008
+ QueueItem as P,
4009
+ routeSubAgentRequest as Pt,
4010
+ MCPClientManager as Q,
4011
+ ScheduleCriteria as R,
4012
+ AgentStaticOptions as S,
4013
+ getMcpAuthContext as St,
4014
+ ConnectionContext$1 as T,
4015
+ WorkerTransportOptions as Tt,
4016
+ SubAgentClass as U,
4017
+ StateUpdateMessage as V,
4018
+ SubAgentStub as W,
4019
+ routeAgentRequest as X,
4020
+ routeAgentEmail as Y,
4021
+ unstable_callable as Z,
4022
+ AddRpcMcpServerOptions as _,
4023
+ McpAgent as _t,
4024
+ AgentToolEventState as a,
4025
+ MCPServerFilter as at,
4026
+ AgentNamespace as b,
4027
+ experimental_createMcpHandler as bt,
4028
+ AgentToolRunInspection as c,
4029
+ getNamespacedData as ct,
4030
+ AgentToolStoredChunk as d,
4031
+ RPCServerTransport as dt,
4032
+ MCPClientOAuthCallbackConfig as et,
4033
+ AgentToolTerminalStatus as f,
4034
+ RPCServerTransportOptions as ft,
4035
+ AddMcpServerOptions as g,
4036
+ ElicitResult$1 as gt,
4037
+ RunAgentToolResult as h,
4038
+ ElicitRequestSchema$1 as ht,
4039
+ AgentToolEventMessage as i,
4040
+ MCPOAuthCallbackResult as it,
4041
+ MCPServer as j,
4042
+ SubAgentPathMatch as jt,
4043
+ FiberContext as k,
4044
+ TransportType as kt,
4045
+ AgentToolRunState as l,
4046
+ RPCClientTransport as lt,
4047
+ RunAgentToolOptions as m,
4048
+ ElicitRequest$1 as mt,
4049
+ AgentToolDisplayMetadata as n,
4050
+ MCPConnectionResult as nt,
4051
+ AgentToolLifecycleResult as o,
4052
+ MCPServerOptions as ot,
4053
+ ChatCapableAgentClass as p,
4054
+ RPC_DO_PREFIX as pt,
4055
+ getAgentByName as q,
4056
+ AgentToolEvent as r,
4057
+ MCPDiscoverResult as rt,
4058
+ AgentToolRunInfo as s,
4059
+ RegisterServerOptions as st,
4060
+ AgentToolChildAdapter as t,
4061
+ MCPClientOAuthResult as tt,
4062
+ AgentToolRunStatus as u,
4063
+ RPCClientTransportOptions as ut,
4064
+ Agent as v,
4065
+ CreateMcpHandlerOptions as vt,
4066
+ Connection$1 as w,
4067
+ WorkerTransport as wt,
4068
+ AgentOptions as x,
4069
+ McpAuthContext as xt,
4070
+ AgentContext as y,
4071
+ createMcpHandler as yt,
4072
+ SendEmailOptions as z
3467
4073
  };
3468
- //# sourceMappingURL=index-DSwOzhhd.d.ts.map
4074
+ //# sourceMappingURL=agent-tool-types-CB7nISDE.d.ts.map