@rudderjs/ai 1.11.2 → 1.13.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.
@@ -0,0 +1,161 @@
1
+ import type { AiMessage, ToolCall } from './types.js';
2
+ /**
3
+ * Discriminator for the kind of pause a standalone run is parked on.
4
+ * Mirrors {@link SubAgentPauseKind} — the two run-store families share a
5
+ * vocabulary so a host can persist sub-agent and top-level pauses the same way.
6
+ *
7
+ * - `'client_tool'` — the run surfaced one or more client tools; resume must
8
+ * carry one tool-result per id in `pendingToolCallIds`. The default when the
9
+ * field is absent (older snapshots stay readable after an upgrade).
10
+ * - `'approval'` — the run stopped on an approval gate; resume must carry an
11
+ * approve/reject decision covering the single id in `pendingToolCallIds`.
12
+ */
13
+ export type AgentPauseKind = 'client_tool' | 'approval';
14
+ /**
15
+ * Snapshot of a paused **standalone** (top-level) agent run — the state a host
16
+ * persists between an `agent.stream()` that parks on a client tool or approval
17
+ * gate and the follow-up request that resumes it.
18
+ *
19
+ * This is the standalone sibling of {@link SubAgentRunSnapshot}: same idea, but
20
+ * for a top-level `stream()` rather than an `Agent.asTool` sub-run. The shape is
21
+ * intentionally replay-ready — `messages` is the full conversation up to the
22
+ * pause point, so resume only appends the incoming client-tool results (or
23
+ * injects the approval decision) and re-enters `stream()` in `messages` mode.
24
+ */
25
+ export interface AgentRunState {
26
+ /** Full conversation history at suspend time (system + user + every interleaved assistant/tool message). */
27
+ messages: AiMessage[];
28
+ /**
29
+ * Tool-call ids the run is waiting on.
30
+ *
31
+ * - `pauseKind === 'client_tool'` (default): one entry per client tool the
32
+ * loop surfaced; resume appends one result per id.
33
+ * - `pauseKind === 'approval'`: a single entry for the approval-gated tool
34
+ * call; resume injects the id into the approve or reject set.
35
+ */
36
+ pendingToolCallIds: string[];
37
+ /** Total steps the run has executed across all suspends so far. */
38
+ stepsSoFar: number;
39
+ /** Total prompt+completion tokens accumulated across all suspends. */
40
+ tokensSoFar: number;
41
+ /**
42
+ * Discriminator for the resume contract. Defaults to `'client_tool'` when
43
+ * absent so snapshots written before approval-pause support stay readable.
44
+ */
45
+ pauseKind?: AgentPauseKind;
46
+ /**
47
+ * Approval pauses only. The full pending tool-call payload (name + args + id)
48
+ * so a renderer can show "approve `delete_user(id=42)`?" without re-running
49
+ * the agent. Mirrors `AgentResponse.pendingApprovalToolCall`.
50
+ */
51
+ pendingApprovalToolCall?: {
52
+ toolCall: ToolCall;
53
+ isClientTool: boolean;
54
+ };
55
+ /**
56
+ * Opaque metadata the host can pass through. The framework treats this as
57
+ * JSON and never reads it — useful for rehydrating request context
58
+ * (e.g. `{ userId, threadId, agentSlug }`) around the resume call.
59
+ */
60
+ meta?: unknown;
61
+ }
62
+ /**
63
+ * Pluggable persistence backend for paused standalone agent runs. The framework
64
+ * ships two reference implementations:
65
+ *
66
+ * - {@link InMemoryAgentRunStore} — a `Map`-backed store. Single-process only;
67
+ * fine for unit tests and small dev setups, lossy across worker processes and
68
+ * restarts.
69
+ * - {@link CachedAgentRunStore} — lazy adapter on top of `@rudderjs/cache`.
70
+ * Cross-process / cross-restart when the cache is configured with redis or any
71
+ * non-memory driver.
72
+ *
73
+ * Hosts may implement their own (Redis directly, Prisma, etc.) by satisfying
74
+ * this interface.
75
+ *
76
+ * The split between {@link load} (non-destructive peek) and {@link consume}
77
+ * (atomic single-use read+delete) matters: a host can `load()` to render a
78
+ * "waiting for approval" view on a GET without burning the run, then `consume()`
79
+ * on the resume POST so a forged or replayed `runId` cannot read data twice.
80
+ */
81
+ export interface AgentRunStore {
82
+ /** Persist a snapshot under `runId`. Implementations MAY apply a TTL. */
83
+ store(runId: string, state: AgentRunState): Promise<void>;
84
+ /**
85
+ * Non-destructive read. Returns `null` if the id is unknown or the snapshot
86
+ * has expired. Leaves the snapshot in place — use for read-only peeks
87
+ * (rendering a pending-run view); use {@link consume} when resuming.
88
+ */
89
+ load(runId: string): Promise<AgentRunState | null>;
90
+ /**
91
+ * Atomic read + delete. Returns `null` if the id is unknown or the snapshot
92
+ * has expired. Single-use semantics matter: a forged or replayed `runId` must
93
+ * not return data twice.
94
+ */
95
+ consume(runId: string): Promise<AgentRunState | null>;
96
+ }
97
+ /**
98
+ * Generate a fresh, hard-to-guess run id. Uses `crypto.randomUUID()` where the
99
+ * runtime exposes it (Node ≥ 16.7, every modern browser, Deno, Bun), falling
100
+ * back to a timestamp + random suffix. Run ids are unguessable on purpose — a
101
+ * `runId` is a capability handle to a parked conversation, so a predictable id
102
+ * would let a third party `consume()` someone else's run.
103
+ */
104
+ export declare function newAgentRunId(): string;
105
+ /**
106
+ * `Map`-backed implementation suitable for tests and single-process dev.
107
+ * Loses state across restarts and worker processes — for any multi-worker
108
+ * deployment, use {@link CachedAgentRunStore} or a custom backend.
109
+ */
110
+ export declare class InMemoryAgentRunStore implements AgentRunStore {
111
+ private readonly states;
112
+ store(runId: string, state: AgentRunState): Promise<void>;
113
+ load(runId: string): Promise<AgentRunState | null>;
114
+ consume(runId: string): Promise<AgentRunState | null>;
115
+ /** Test helper — clears all snapshots without consuming. */
116
+ clear(): void;
117
+ }
118
+ /**
119
+ * Minimal structural shape of a cache adapter (the methods this store touches).
120
+ * Mirrors `@rudderjs/cache`'s `CacheAdapter` so the dep stays structural — the
121
+ * framework's main entry stays runtime-agnostic.
122
+ */
123
+ interface CacheStoreLike {
124
+ get<T = unknown>(key: string): Promise<T | null>;
125
+ set(key: string, value: unknown, ttlSeconds?: number): Promise<void>;
126
+ forget(key: string): Promise<void>;
127
+ }
128
+ export interface CachedAgentRunStoreOptions {
129
+ /**
130
+ * Cache adapter to use. When omitted, the store loads `@rudderjs/cache`
131
+ * lazily and falls back to the registered global adapter
132
+ * (`CacheRegistry.get()`); throws if neither resolves.
133
+ */
134
+ cache?: CacheStoreLike;
135
+ /** Key namespace prefix. Default `'rudderjs:ai:agent-run:'`. */
136
+ keyPrefix?: string;
137
+ /** Time-to-live in seconds. Default 5 minutes. */
138
+ ttlSeconds?: number;
139
+ }
140
+ /**
141
+ * Standalone agent run store backed by `@rudderjs/cache`. Loads the cache
142
+ * adapter lazily so `@rudderjs/ai`'s main entry stays runtime-agnostic (no
143
+ * static import on the cache package).
144
+ *
145
+ * Default TTL is 5 minutes — long enough for a browser to round-trip a few
146
+ * client tool calls or an approval decision, short enough that abandoned runs
147
+ * garbage-collect promptly and the storage bill stays bounded.
148
+ */
149
+ export declare class CachedAgentRunStore implements AgentRunStore {
150
+ private readonly explicitCache?;
151
+ private readonly keyPrefix;
152
+ private readonly ttlSeconds;
153
+ private resolvedCache?;
154
+ constructor(opts?: CachedAgentRunStoreOptions);
155
+ private getCache;
156
+ store(runId: string, state: AgentRunState): Promise<void>;
157
+ load(runId: string): Promise<AgentRunState | null>;
158
+ consume(runId: string): Promise<AgentRunState | null>;
159
+ }
160
+ export {};
161
+ //# sourceMappingURL=agent-run-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-run-store.d.ts","sourceRoot":"","sources":["../src/agent-run-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAErD;;;;;;;;;;GAUG;AACH,MAAM,MAAM,cAAc,GAAG,aAAa,GAAG,UAAU,CAAA;AAEvD;;;;;;;;;;GAUG;AACH,MAAM,WAAW,aAAa;IAC5B,4GAA4G;IAC5G,QAAQ,EAAY,SAAS,EAAE,CAAA;IAC/B;;;;;;;OAOG;IACH,kBAAkB,EAAE,MAAM,EAAE,CAAA;IAC5B,mEAAmE;IACnE,UAAU,EAAU,MAAM,CAAA;IAC1B,sEAAsE;IACtE,WAAW,EAAS,MAAM,CAAA;IAC1B;;;OAGG;IACH,SAAS,CAAC,EAAU,cAAc,CAAA;IAClC;;;;OAIG;IACH,uBAAuB,CAAC,EAAE;QAAE,QAAQ,EAAE,QAAQ,CAAC;QAAC,YAAY,EAAE,OAAO,CAAA;KAAE,CAAA;IACvE;;;;OAIG;IACH,IAAI,CAAC,EAAE,OAAO,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,cAAc,CAAA;IAC3B,gEAAgE;IAChE,SAAS,CAAC,EAAG,MAAM,CAAA;IACnB,kDAAkD;IAClD,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED;;;;;;;;GAQG;AACH,qBAAa,mBAAoB,YAAW,aAAa;IACvD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAgB;IAC/C,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAa;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAY;IACvC,OAAO,CAAC,aAAa,CAAC,CAAyB;gBAEnC,IAAI,GAAE,0BAA+B;YAMnC,QAAQ;IAuBhB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAKzD,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;IAKlD,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;CAQ5D"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Generate a fresh, hard-to-guess run id. Uses `crypto.randomUUID()` where the
3
+ * runtime exposes it (Node ≥ 16.7, every modern browser, Deno, Bun), falling
4
+ * back to a timestamp + random suffix. Run ids are unguessable on purpose — a
5
+ * `runId` is a capability handle to a parked conversation, so a predictable id
6
+ * would let a third party `consume()` someone else's run.
7
+ */
8
+ export function newAgentRunId() {
9
+ if (typeof globalThis.crypto?.randomUUID === 'function')
10
+ return globalThis.crypto.randomUUID();
11
+ return `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
12
+ }
13
+ // ─── In-memory ─────────────────────────────────────────────
14
+ /**
15
+ * `Map`-backed implementation suitable for tests and single-process dev.
16
+ * Loses state across restarts and worker processes — for any multi-worker
17
+ * deployment, use {@link CachedAgentRunStore} or a custom backend.
18
+ */
19
+ export class InMemoryAgentRunStore {
20
+ states = new Map();
21
+ async store(runId, state) {
22
+ this.states.set(runId, state);
23
+ }
24
+ async load(runId) {
25
+ return this.states.get(runId) ?? null;
26
+ }
27
+ async consume(runId) {
28
+ const state = this.states.get(runId);
29
+ if (!state)
30
+ return null;
31
+ this.states.delete(runId);
32
+ return state;
33
+ }
34
+ /** Test helper — clears all snapshots without consuming. */
35
+ clear() {
36
+ this.states.clear();
37
+ }
38
+ }
39
+ /**
40
+ * Standalone agent run store backed by `@rudderjs/cache`. Loads the cache
41
+ * adapter lazily so `@rudderjs/ai`'s main entry stays runtime-agnostic (no
42
+ * static import on the cache package).
43
+ *
44
+ * Default TTL is 5 minutes — long enough for a browser to round-trip a few
45
+ * client tool calls or an approval decision, short enough that abandoned runs
46
+ * garbage-collect promptly and the storage bill stays bounded.
47
+ */
48
+ export class CachedAgentRunStore {
49
+ explicitCache;
50
+ keyPrefix;
51
+ ttlSeconds;
52
+ resolvedCache;
53
+ constructor(opts = {}) {
54
+ if (opts.cache)
55
+ this.explicitCache = opts.cache;
56
+ this.keyPrefix = opts.keyPrefix ?? 'rudderjs:ai:agent-run:';
57
+ this.ttlSeconds = opts.ttlSeconds ?? 5 * 60;
58
+ }
59
+ async getCache() {
60
+ if (this.resolvedCache)
61
+ return this.resolvedCache;
62
+ if (this.explicitCache) {
63
+ this.resolvedCache = this.explicitCache;
64
+ return this.resolvedCache;
65
+ }
66
+ // Lazy-import @rudderjs/cache and ask the registry for the active adapter.
67
+ // This keeps the static import surface zero — the import only fires when the
68
+ // host actually opts into suspendable standalone runs. We dodge static
69
+ // module-resolution by using an indirected specifier so `@rudderjs/cache`
70
+ // doesn't need to be a declared dep of `@rudderjs/ai` (optional runtime peer).
71
+ const cacheSpecifier = '@rudderjs/cache';
72
+ const mod = await import(/* @vite-ignore */ cacheSpecifier);
73
+ const adapter = mod.CacheRegistry?.get?.();
74
+ if (!adapter) {
75
+ throw new Error('[RudderJS AI] CachedAgentRunStore needs a cache adapter. Install `@rudderjs/cache`, register a driver, or pass `{ cache }` explicitly.');
76
+ }
77
+ this.resolvedCache = adapter;
78
+ return adapter;
79
+ }
80
+ async store(runId, state) {
81
+ const cache = await this.getCache();
82
+ await cache.set(this.keyPrefix + runId, state, this.ttlSeconds);
83
+ }
84
+ async load(runId) {
85
+ const cache = await this.getCache();
86
+ return (await cache.get(this.keyPrefix + runId)) ?? null;
87
+ }
88
+ async consume(runId) {
89
+ const cache = await this.getCache();
90
+ const key = this.keyPrefix + runId;
91
+ const state = await cache.get(key);
92
+ if (!state)
93
+ return null;
94
+ await cache.forget(key);
95
+ return state;
96
+ }
97
+ }
98
+ //# sourceMappingURL=agent-run-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-run-store.js","sourceRoot":"","sources":["../src/agent-run-store.ts"],"names":[],"mappings":"AAiGA;;;;;;GAMG;AACH,MAAM,UAAU,aAAa;IAC3B,IAAI,OAAO,UAAU,CAAC,MAAM,EAAE,UAAU,KAAK,UAAU;QAAE,OAAO,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,CAAA;IAC9F,OAAO,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAA;AACpF,CAAC;AAED,8DAA8D;AAE9D;;;;GAIG;AACH,MAAM,OAAO,qBAAqB;IACf,MAAM,GAAG,IAAI,GAAG,EAAyB,CAAA;IAE1D,KAAK,CAAC,KAAK,CAAC,KAAa,EAAE,KAAoB;QAC7C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;IAC/B,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,KAAa;QACtB,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,IAAI,CAAA;IACvC,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,KAAa;QAC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AE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,wIAAwI,CAAC,CAAA;QAC3J,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,OAAO,CAAA;QAC5B,OAAO,OAAO,CAAA;IAChB,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,KAAa,EAAE,KAAoB;QAC7C,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,CAAA;QACnC,MAAM,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,GAAG,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;IACjE,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,KAAa;QACtB,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,CAAA;QACnC,OAAO,CAAC,MAAM,KAAK,CAAC,GAAG,CAAgB,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,CAAC,IAAI,IAAI,CAAA;IACzE,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,KAAa;QACzB,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,CAAA;QACnC,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,GAAG,KAAK,CAAA;QAClC,MAAM,KAAK,GAAG,MAAM,KAAK,CAAC,GAAG,CAAgB,GAAG,CAAC,CAAA;QACjD,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAA;QACvB,MAAM,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QACvB,OAAO,KAAK,CAAA;IACd,CAAC;CACF"}
package/dist/agent.d.ts CHANGED
@@ -9,6 +9,146 @@ import type { AgentPromptOptions, AiMessage, AiMiddleware, AgentResponse, AgentS
9
9
  export declare function stepCountIs(n: number): StopCondition;
10
10
  /** Stop when a specific tool is called in the latest step */
11
11
  export declare function hasToolCall(toolName: string): StopCondition;
12
+ /** Options for {@link Agent.resumeAsTool}. */
13
+ export interface SubAgentResumeOptions {
14
+ /** Shared run store the snapshot lives in. */
15
+ runStore: SubAgentRunStore;
16
+ /** The sub-agent instance to resume. */
17
+ agent: Agent;
18
+ /** Approved ids for an `approval` pause. */
19
+ approvedToolCallIds?: string[];
20
+ /** Rejected ids for an `approval` pause. */
21
+ rejectedToolCallIds?: string[];
22
+ /**
23
+ * Opt-in live progress during the resume. When set, the resumed inner loop
24
+ * runs via `stream()` instead of `prompt()` and each chunk is projected into
25
+ * a {@link SubAgentUpdate} forwarded to {@link onUpdate}. `true` uses
26
+ * {@link defaultSubAgentProjector} (emits `tool_call` / `agent_pending_approval`);
27
+ * a function is your own projector. Mirrors {@link Agent.asTool}'s `streaming`
28
+ * on the initial-dispatch path. Unset → the legacy non-streaming `prompt()`
29
+ * resume (no behavior change). The pause/completion partition is identical
30
+ * either way — this only adds a progress channel.
31
+ */
32
+ streaming?: AsToolStreamingOption;
33
+ /**
34
+ * Sink for projected updates. Only fires when {@link streaming} is set, once
35
+ * per non-null projection, in stream order. Awaited, so a slow sink applies
36
+ * backpressure to the resume.
37
+ */
38
+ onUpdate?: (update: SubAgentUpdate) => void | Promise<void>;
39
+ }
40
+ /**
41
+ * One entry in a {@link Agent.resumeManyAsTool} batch — a single paused
42
+ * sub-agent to resume. Mirrors the positional args of the singular
43
+ * {@link Agent.resumeAsTool}, plus an optional host `key` echoed back on the
44
+ * matching outcome so callers can correlate results without relying on array
45
+ * order.
46
+ */
47
+ export interface SubAgentResumeRequest {
48
+ /** The paused run's id (the `subRunId` from its pause chunk/snapshot). */
49
+ subRunId: string;
50
+ /** The sub-agent instance to resume (each item may be a different agent). */
51
+ agent: Agent;
52
+ /** Client tool-results for a `client_tool` pause (one per pending id). */
53
+ clientToolResults?: ReadonlyArray<{
54
+ toolCallId: string;
55
+ result: unknown;
56
+ }>;
57
+ /** Approved ids for an `approval` pause. */
58
+ approvedToolCallIds?: string[];
59
+ /** Rejected ids for an `approval` pause. */
60
+ rejectedToolCallIds?: string[];
61
+ /** Opaque correlation key echoed back on this item's outcome. */
62
+ key?: string;
63
+ }
64
+ /** Outcome for a single item in a {@link Agent.resumeManyAsTool} batch. */
65
+ export type SubAgentResumeOutcome = {
66
+ key?: string;
67
+ originalSubRunId: string;
68
+ kind: 'completed';
69
+ response: AgentResponse;
70
+ } | {
71
+ key?: string;
72
+ originalSubRunId: string;
73
+ kind: 'paused';
74
+ subRunId: string;
75
+ pauseKind: SubAgentPauseKind;
76
+ pendingToolCallIds: string[];
77
+ toolCall?: ToolCall;
78
+ isClientTool?: boolean;
79
+ } | {
80
+ key?: string;
81
+ originalSubRunId: string;
82
+ kind: 'error';
83
+ error: Error;
84
+ };
85
+ export interface SubAgentResumeManyOptions {
86
+ /** Shared run store all the snapshots live in. */
87
+ runStore: SubAgentRunStore;
88
+ /**
89
+ * What to do when one item fails (expired/forged `subRunId`, duplicate
90
+ * result id, inner error):
91
+ * - `'capture'` (default) — record it as a `{ kind: 'error' }` outcome and
92
+ * let the rest of the batch resume; the aggregated round-trip still
93
+ * returns.
94
+ * - `'throw'` — reject the whole call on the first failure, matching the
95
+ * singular `resumeAsTool` strictness.
96
+ */
97
+ onError?: 'capture' | 'throw';
98
+ /**
99
+ * - `'parallel'` (default) — resume all snapshots concurrently. Snapshots
100
+ * are independent and `consume()` is per-id atomic, so this is safe and
101
+ * fastest.
102
+ * - `'serial'` — resume one at a time in array order, for deterministic
103
+ * side-effect ordering when sub-agents touch shared state.
104
+ */
105
+ concurrency?: 'parallel' | 'serial';
106
+ /**
107
+ * Shared live-progress projector applied to every resumed item — same option
108
+ * as {@link SubAgentResumeOptions.streaming}. Unset → every item resumes
109
+ * non-streaming (legacy behavior). Set → each item streams and its projected
110
+ * updates flow to {@link onUpdate} tagged with the originating request.
111
+ */
112
+ streaming?: AsToolStreamingOption;
113
+ /**
114
+ * Sink for projected updates across the whole batch. Only fires when
115
+ * {@link streaming} is set. Each call carries the originating item's `key`
116
+ * (when supplied) and `originalSubRunId`, so a host can correlate a chunk
117
+ * back to its request and fan it out (e.g. to a per-sub-agent SSE channel).
118
+ */
119
+ onUpdate?: (update: SubAgentUpdate, ctx: {
120
+ key?: string;
121
+ originalSubRunId: string;
122
+ }) => void | Promise<void>;
123
+ }
124
+ /** Aggregated result of a {@link Agent.resumeManyAsTool} batch. */
125
+ export interface SubAgentResumeManyResult {
126
+ /** Every item's outcome, in input order. */
127
+ results: SubAgentResumeOutcome[];
128
+ /** The items that paused again (need another client round-trip). */
129
+ paused: Extract<SubAgentResumeOutcome, {
130
+ kind: 'paused';
131
+ }>[];
132
+ /** The items that ran to completion. */
133
+ completed: Extract<SubAgentResumeOutcome, {
134
+ kind: 'completed';
135
+ }>[];
136
+ /** The items that failed (only populated under `onError: 'capture'`). */
137
+ errors: Extract<SubAgentResumeOutcome, {
138
+ kind: 'error';
139
+ }>[];
140
+ /**
141
+ * All pending tool-call ids across every paused item, flattened — the
142
+ * single set the host gathers client results / approvals for before the
143
+ * next `resumeManyAsTool`. Empty when nothing paused.
144
+ */
145
+ pendingToolCallIds: string[];
146
+ /**
147
+ * `true` when nothing is still paused and no item errored — i.e. there is
148
+ * no further round-trip to do. Loop `resumeManyAsTool` until this is `true`.
149
+ */
150
+ allCompleted: boolean;
151
+ }
12
152
  export declare abstract class Agent {
13
153
  /** System instructions for this agent */
14
154
  abstract instructions(): string;
@@ -204,12 +344,7 @@ export declare abstract class Agent {
204
344
  static resumeAsTool(subRunId: string, clientToolResults: ReadonlyArray<{
205
345
  toolCallId: string;
206
346
  result: unknown;
207
- }>, options: {
208
- runStore: SubAgentRunStore;
209
- agent: Agent;
210
- approvedToolCallIds?: string[];
211
- rejectedToolCallIds?: string[];
212
- }): Promise<{
347
+ }>, options: SubAgentResumeOptions): Promise<{
213
348
  kind: 'completed';
214
349
  response: AgentResponse;
215
350
  } | {
@@ -220,9 +355,43 @@ export declare abstract class Agent {
220
355
  toolCall?: ToolCall;
221
356
  isClientTool?: boolean;
222
357
  }>;
358
+ /**
359
+ * Resume MANY paused sub-agents in one call and aggregate their pending
360
+ * tool calls into a single client round-trip.
361
+ *
362
+ * When an orchestrator dispatches several sub-agents in one parent turn
363
+ * and more than one pauses on a client tool (or approval gate), the host
364
+ * would otherwise loop over {@link Agent.resumeAsTool} by hand and stitch
365
+ * the pending sets back together. This does that: each request resumes its
366
+ * own `(subRunId, agent)` snapshot, and the result carries the combined
367
+ * `completed` / `paused` / `errors` partition plus the flattened
368
+ * `pendingToolCallIds` the host collects the next batch of results for.
369
+ *
370
+ * Re-entrant: feed the next round of `clientToolResults` / approvals back
371
+ * in as a fresh batch keyed off each paused item's NEW `subRunId` until
372
+ * `allCompleted` is `true`.
373
+ *
374
+ * @example
375
+ * let batch = await Agent.resumeManyAsTool(
376
+ * paused.map(p => ({ subRunId: p.subRunId, agent: p.agent, clientToolResults: results[p.subRunId] })),
377
+ * { runStore },
378
+ * )
379
+ * // batch.pendingToolCallIds → gather the next round from the browser, repeat.
380
+ */
381
+ static resumeManyAsTool(requests: ReadonlyArray<SubAgentResumeRequest>, options: SubAgentResumeManyOptions): Promise<SubAgentResumeManyResult>;
223
382
  }
224
- type ChunkProjector = (chunk: StreamChunk) => SubAgentUpdate | null;
225
- type AsToolStreamingOption = boolean | ChunkProjector;
383
+ /**
384
+ * Projects an inner-agent {@link StreamChunk} into a {@link SubAgentUpdate} the
385
+ * host can render, or `null` to suppress it. Used by both {@link Agent.asTool}
386
+ * (`streaming`) and the streaming resume path ({@link SubAgentResumeOptions.streaming}).
387
+ */
388
+ export type ChunkProjector = (chunk: StreamChunk) => SubAgentUpdate | null;
389
+ /**
390
+ * Live-progress option shared by {@link Agent.asTool} and the streaming resume
391
+ * surface: `true` uses {@link defaultSubAgentProjector}; a function is your own
392
+ * {@link ChunkProjector}.
393
+ */
394
+ export type AsToolStreamingOption = boolean | ChunkProjector;
226
395
  type AsToolSuspendableOption = {
227
396
  runStore: SubAgentRunStore;
228
397
  };
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AA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AQ,CAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAA;IAGxG,QAAQ,CAAC,QAAQ,EAAkB,SAAS,EAAE,CAAA;IAC9C,QAAQ,CAAC,KAAK,EAAqB,SAAS,EAAE,CAAA;IAC9C,QAAQ,CAAC,UAAU,EAAgB,UAAU,CAAA;IAC7C,QAAQ,CAAC,sBAAsB,EAAI,QAAQ,EAAE,CAAA;IAC7C,uBAAuB,EAAY;QAAE,QAAQ,EAAE,QAAQ,CAAC;QAAC,YAAY,EAAE,OAAO,CAAA;KAAE,GAAG,SAAS,CAAA;IAC5F,gBAAgB,EAAmB,YAAY,GAAG,SAAS,CAAA;IAC3D,kBAAkB,EAAiB,OAAO,CAAA;IAC1C,eAAe,EAAoB,OAAO,CAAA;IAC1C,mBAAmB,EAAgB,SAAS,EAAE,CAAA;IAC9C,gBAAgB,EAAmB,MAAM,CAAA;IACzC;;;;OAIG;IACH,cAAc,CAAC,EAAoB,cAAc,CAAA;IACjD,cAAc,EAAqB,OAAO,CAAA;CAC3C;AAED,YAAY,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAgrB1D,YAAY,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAA"}
package/dist/agent.js CHANGED
@@ -360,7 +360,25 @@ export class Agent {
360
360
  promptOpts.rejectedToolCallIds = rejected;
361
361
  }
362
362
  promptOpts.messages = messages;
363
- const result = await options.agent.prompt('', promptOpts);
363
+ // Default path: non-streaming resume — one prompt() call, one response.
364
+ // Opt-in streaming path: run the inner loop via stream() and forward each
365
+ // projected chunk to onUpdate, so a host can keep a resumed sub-agent's
366
+ // progress live across the round-trip. Either way `result` is the same
367
+ // AgentResponse and the pause/completion partition below is unchanged.
368
+ let result;
369
+ if (options.streaming) {
370
+ const project = options.streaming === true ? defaultSubAgentProjector : options.streaming;
371
+ const { stream, response } = options.agent.stream('', promptOpts);
372
+ for await (const chunk of stream) {
373
+ const update = project(chunk);
374
+ if (update && options.onUpdate)
375
+ await options.onUpdate(update);
376
+ }
377
+ result = await response;
378
+ }
379
+ else {
380
+ result = await options.agent.prompt('', promptOpts);
381
+ }
364
382
  if (result.finishReason === 'client_tool_calls' &&
365
383
  result.pendingClientToolCalls?.length) {
366
384
  const newSubRunId = generateSubRunId();
@@ -405,6 +423,87 @@ export class Agent {
405
423
  }
406
424
  return { kind: 'completed', response: result };
407
425
  }
426
+ /**
427
+ * Resume MANY paused sub-agents in one call and aggregate their pending
428
+ * tool calls into a single client round-trip.
429
+ *
430
+ * When an orchestrator dispatches several sub-agents in one parent turn
431
+ * and more than one pauses on a client tool (or approval gate), the host
432
+ * would otherwise loop over {@link Agent.resumeAsTool} by hand and stitch
433
+ * the pending sets back together. This does that: each request resumes its
434
+ * own `(subRunId, agent)` snapshot, and the result carries the combined
435
+ * `completed` / `paused` / `errors` partition plus the flattened
436
+ * `pendingToolCallIds` the host collects the next batch of results for.
437
+ *
438
+ * Re-entrant: feed the next round of `clientToolResults` / approvals back
439
+ * in as a fresh batch keyed off each paused item's NEW `subRunId` until
440
+ * `allCompleted` is `true`.
441
+ *
442
+ * @example
443
+ * let batch = await Agent.resumeManyAsTool(
444
+ * paused.map(p => ({ subRunId: p.subRunId, agent: p.agent, clientToolResults: results[p.subRunId] })),
445
+ * { runStore },
446
+ * )
447
+ * // batch.pendingToolCallIds → gather the next round from the browser, repeat.
448
+ */
449
+ static async resumeManyAsTool(requests, options) {
450
+ const onError = options.onError ?? 'capture';
451
+ const concurrency = options.concurrency ?? 'parallel';
452
+ const runOne = async (req) => {
453
+ const base = { originalSubRunId: req.subRunId, ...(req.key !== undefined ? { key: req.key } : {}) };
454
+ try {
455
+ const opts = { runStore: options.runStore, agent: req.agent };
456
+ if (req.approvedToolCallIds)
457
+ opts.approvedToolCallIds = req.approvedToolCallIds;
458
+ if (req.rejectedToolCallIds)
459
+ opts.rejectedToolCallIds = req.rejectedToolCallIds;
460
+ // Thread the shared projector + correlate each update back to this item.
461
+ if (options.streaming !== undefined)
462
+ opts.streaming = options.streaming;
463
+ if (options.onUpdate) {
464
+ const batchOnUpdate = options.onUpdate;
465
+ opts.onUpdate = (update) => batchOnUpdate(update, base);
466
+ }
467
+ const r = await Agent.resumeAsTool(req.subRunId, req.clientToolResults ?? [], opts);
468
+ if (r.kind === 'completed')
469
+ return { ...base, kind: 'completed', response: r.response };
470
+ return {
471
+ ...base,
472
+ kind: 'paused',
473
+ subRunId: r.subRunId,
474
+ pauseKind: r.pauseKind,
475
+ pendingToolCallIds: r.pendingToolCallIds,
476
+ ...(r.toolCall !== undefined ? { toolCall: r.toolCall } : {}),
477
+ ...(r.isClientTool !== undefined ? { isClientTool: r.isClientTool } : {}),
478
+ };
479
+ }
480
+ catch (err) {
481
+ if (onError === 'throw')
482
+ throw err;
483
+ return { ...base, kind: 'error', error: err instanceof Error ? err : new Error(String(err)) };
484
+ }
485
+ };
486
+ let results;
487
+ if (concurrency === 'serial') {
488
+ results = [];
489
+ for (const req of requests)
490
+ results.push(await runOne(req));
491
+ }
492
+ else {
493
+ results = await Promise.all(requests.map(runOne));
494
+ }
495
+ const paused = results.filter((o) => o.kind === 'paused');
496
+ const completed = results.filter((o) => o.kind === 'completed');
497
+ const errors = results.filter((o) => o.kind === 'error');
498
+ return {
499
+ results,
500
+ paused,
501
+ completed,
502
+ errors,
503
+ pendingToolCallIds: paused.flatMap((p) => p.pendingToolCallIds),
504
+ allCompleted: paused.length === 0 && errors.length === 0,
505
+ };
506
+ }
408
507
  }
409
508
  /**
410
509
  * Default projection from inner-agent stream chunks to {@link SubAgentUpdate}