@superdurable/dex-agents 0.2.0 → 0.4.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 (92) hide show
  1. package/README.md +143 -6
  2. package/dist/src/agent-context-compaction.d.ts +150 -4
  3. package/dist/src/agent-context-compaction.js +253 -5
  4. package/dist/src/agent-context-compaction.js.map +1 -1
  5. package/dist/src/agent-framework-runner.d.ts +89 -0
  6. package/dist/src/agent-framework-runner.js +26 -0
  7. package/dist/src/agent-framework-runner.js.map +1 -1
  8. package/dist/src/agent-session-codecs.js +9 -0
  9. package/dist/src/agent-session-codecs.js.map +1 -1
  10. package/dist/src/agent-session-failure.d.ts +58 -0
  11. package/dist/src/agent-session-failure.js +126 -0
  12. package/dist/src/agent-session-failure.js.map +1 -0
  13. package/dist/src/agent-session-flow-graph-cli.d.ts +2 -0
  14. package/dist/src/agent-session-flow-graph-cli.js +47 -0
  15. package/dist/src/agent-session-flow-graph-cli.js.map +1 -0
  16. package/dist/src/agent-session-flow-graph.d.ts +38 -0
  17. package/dist/src/agent-session-flow-graph.js +54 -0
  18. package/dist/src/agent-session-flow-graph.js.map +1 -0
  19. package/dist/src/agent-session-flow-graph.json +2204 -0
  20. package/dist/src/agent-session-flow.d.ts +23 -2
  21. package/dist/src/agent-session-flow.js +5 -0
  22. package/dist/src/agent-session-flow.js.map +1 -1
  23. package/dist/src/agent-session-spend-limit.d.ts +156 -0
  24. package/dist/src/agent-session-spend-limit.js +42 -0
  25. package/dist/src/agent-session-spend-limit.js.map +1 -0
  26. package/dist/src/agent-session-start.d.ts +49 -0
  27. package/dist/src/agent-session-start.js +67 -0
  28. package/dist/src/agent-session-start.js.map +1 -0
  29. package/dist/src/agent-session-step-options.d.ts +52 -1
  30. package/dist/src/agent-session-step-options.js +34 -2
  31. package/dist/src/agent-session-step-options.js.map +1 -1
  32. package/dist/src/agent-session-steps.d.ts +9 -0
  33. package/dist/src/agent-session-steps.js +247 -50
  34. package/dist/src/agent-session-steps.js.map +1 -1
  35. package/dist/src/agent-session-transitions.d.ts +14 -1
  36. package/dist/src/agent-session-transitions.js +61 -1
  37. package/dist/src/agent-session-transitions.js.map +1 -1
  38. package/dist/src/agent-session-values.d.ts +43 -2
  39. package/dist/src/agent-session-values.js +6 -0
  40. package/dist/src/agent-session-values.js.map +1 -1
  41. package/dist/src/agent-session-wait-steps.js +3 -3
  42. package/dist/src/agent-session-wait-steps.js.map +1 -1
  43. package/dist/src/connectors/connector-input-schema.d.ts +19 -0
  44. package/dist/src/connectors/connector-input-schema.js +228 -0
  45. package/dist/src/connectors/connector-input-schema.js.map +1 -0
  46. package/dist/src/connectors/connector-step-context.d.ts +77 -0
  47. package/dist/src/connectors/connector-step-context.js +124 -0
  48. package/dist/src/connectors/connector-step-context.js.map +1 -0
  49. package/dist/src/connectors/connector-tool-source.d.ts +353 -0
  50. package/dist/src/connectors/connector-tool-source.js +541 -0
  51. package/dist/src/connectors/connector-tool-source.js.map +1 -0
  52. package/dist/src/connectors/index.d.ts +3 -0
  53. package/dist/src/connectors/index.js +11 -0
  54. package/dist/src/connectors/index.js.map +1 -0
  55. package/dist/src/index.d.ts +10 -3
  56. package/dist/src/index.js +8 -2
  57. package/dist/src/index.js.map +1 -1
  58. package/dist/src/stepwise/agent-definition.d.ts +8 -0
  59. package/dist/src/stepwise/index.d.ts +2 -1
  60. package/dist/src/stepwise/index.js +2 -1
  61. package/dist/src/stepwise/index.js.map +1 -1
  62. package/dist/src/stepwise/stepwise-agent-runner.d.ts +15 -32
  63. package/dist/src/stepwise/stepwise-agent-runner.js +37 -200
  64. package/dist/src/stepwise/stepwise-agent-runner.js.map +1 -1
  65. package/dist/src/stepwise/stepwise-agent-session-flow.js +1 -0
  66. package/dist/src/stepwise/stepwise-agent-session-flow.js.map +1 -1
  67. package/dist/src/stepwise/tool-source.d.ts +11 -1
  68. package/dist/src/testing/agent-session-test-client.js +2 -5
  69. package/dist/src/testing/agent-session-test-client.js.map +1 -1
  70. package/dist/src/testing/context-window.d.ts +194 -0
  71. package/dist/src/testing/context-window.js +360 -0
  72. package/dist/src/testing/context-window.js.map +1 -0
  73. package/dist/src/testing/index.d.ts +1 -0
  74. package/dist/src/testing/index.js +1 -0
  75. package/dist/src/testing/index.js.map +1 -1
  76. package/dist/src/tool-source-router.d.ts +211 -0
  77. package/dist/src/tool-source-router.js +380 -0
  78. package/dist/src/tool-source-router.js.map +1 -0
  79. package/dist/src/ui-stream/agent-event-sse.d.ts +3 -2
  80. package/dist/src/ui-stream/agent-event-sse.js +11 -3
  81. package/dist/src/ui-stream/agent-event-sse.js.map +1 -1
  82. package/dist/src/ui-stream/agent-session-record-reader.d.ts +2 -0
  83. package/dist/src/ui-stream/agent-session-record-reader.js +5 -0
  84. package/dist/src/ui-stream/agent-session-record-reader.js.map +1 -1
  85. package/dist/src/ui-stream/agent-ui-message-stream-responses.js +3 -2
  86. package/dist/src/ui-stream/agent-ui-message-stream-responses.js.map +1 -1
  87. package/dist/src/ui-stream/agent-ui-message-stream.js +17 -3
  88. package/dist/src/ui-stream/agent-ui-message-stream.js.map +1 -1
  89. package/dist/src/ui-stream/agent-ui-messages.d.ts +2 -0
  90. package/dist/src/ui-stream/agent-ui-messages.js +5 -3
  91. package/dist/src/ui-stream/agent-ui-messages.js.map +1 -1
  92. package/package.json +15 -3
@@ -1,6 +1,7 @@
1
1
  export { AgentSessionTestClient, type AgentSessionWaitOptions, } from "./agent-session-test-client.js";
2
2
  export { AgentTestEnvironment, type AgentTestEnvironmentOptions, } from "./agent-test-environment.js";
3
3
  export { KillableWorkerProcess, agentWorkerBlobCacheDirectoryVariable, agentWorkerReadyLine, agentWorkerServerAddressVariable, runAgentWorkerProcess, type KillableWorkerProcessOptions, } from "./agent-worker-process.js";
4
+ export { ContextWindowModelScript, ContextWindowSessionScenario, contextWindowExceededError, contextWindowSessionOptions, contextWindowSettingsEnvironment, contextWindowSettingsVariable, contextWindowSummaryGateName, contextWindowToolName, defaultContextWindowSettings, readContextWindowRequests, readContextWindowSettings, type ContextWindowReply, type ContextWindowRequest, type ContextWindowSessionScenarioOptions, type ContextWindowSettings, } from "./context-window.js";
4
5
  export { FileGate, InvocationLog } from "./coordination.js";
5
6
  export { pollUntil, type PollOptions } from "./polling.js";
6
7
  export { ScriptedModelClient, scriptedModelApi, scriptedModelProvider, type ScriptedModelReply, type ScriptedModelResponder, type ScriptedToolCall, } from "./scripted-model-client.js";
@@ -8,6 +8,7 @@
8
8
  export { AgentSessionTestClient, } from "./agent-session-test-client.js";
9
9
  export { AgentTestEnvironment, } from "./agent-test-environment.js";
10
10
  export { KillableWorkerProcess, agentWorkerBlobCacheDirectoryVariable, agentWorkerReadyLine, agentWorkerServerAddressVariable, runAgentWorkerProcess, } from "./agent-worker-process.js";
11
+ export { ContextWindowModelScript, ContextWindowSessionScenario, contextWindowExceededError, contextWindowSessionOptions, contextWindowSettingsEnvironment, contextWindowSettingsVariable, contextWindowSummaryGateName, contextWindowToolName, defaultContextWindowSettings, readContextWindowRequests, readContextWindowSettings, } from "./context-window.js";
11
12
  export { FileGate, InvocationLog } from "./coordination.js";
12
13
  export { pollUntil } from "./polling.js";
13
14
  export { ScriptedModelClient, scriptedModelApi, scriptedModelProvider, } from "./scripted-model-client.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/testing/index.ts"],"names":[],"mappings":"AAAA,yCAAyC;AACzC,EAAE;AACF,kDAAkD;AAClD,mEAAmE;AACnE,+CAA+C;AAC/C,EAAE;AACF,0DAA0D;AAE1D,OAAO,EACL,sBAAsB,GAEvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,oBAAoB,GAErB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,qBAAqB,EACrB,qCAAqC,EACrC,oBAAoB,EACpB,gCAAgC,EAChC,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAoB,MAAM,cAAc,CAAC;AAC3D,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,qBAAqB,GAItB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,qBAAqB,GAGtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,qBAAqB,GAEtB,MAAM,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/testing/index.ts"],"names":[],"mappings":"AAAA,yCAAyC;AACzC,EAAE;AACF,kDAAkD;AAClD,mEAAmE;AACnE,+CAA+C;AAC/C,EAAE;AACF,0DAA0D;AAE1D,OAAO,EACL,sBAAsB,GAEvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,oBAAoB,GAErB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,qBAAqB,EACrB,qCAAqC,EACrC,oBAAoB,EACpB,gCAAgC,EAChC,qBAAqB,GAEtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,0BAA0B,EAC1B,2BAA2B,EAC3B,gCAAgC,EAChC,6BAA6B,EAC7B,4BAA4B,EAC5B,qBAAqB,EACrB,4BAA4B,EAC5B,yBAAyB,EACzB,yBAAyB,GAK1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAoB,MAAM,cAAc,CAAC;AAC3D,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,qBAAqB,GAItB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,qBAAqB,GAGtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,qBAAqB,GAEtB,MAAM,yBAAyB,CAAC"}
@@ -0,0 +1,211 @@
1
+ import { type AgentTurnContext, type DeferredToolCall, type DeferredToolExecution, type DeferredToolOutcome, type ToolCallStepOptions, type ToolExecutionResult, type ToolTaskCancellation, type ToolTaskPoll, type ToolTaskPollOutcome } from "./agent-framework-runner.js";
2
+ import type { AgentToolCall } from "./agent-session-values.js";
3
+ import type { SourceToolDefinition, ToolSource } from "./stepwise/tool-source.js";
4
+ /**
5
+ * Default `AgentDefinition.toolSourceListingTimeoutMs`: 10 seconds. It is also the default time one model call of a
6
+ * framework adapter waits for each tool source's listing. Exported from the package root since 0.4.0.
7
+ */
8
+ export declare const defaultToolSourceListingTimeoutMs = 10000;
9
+ /**
10
+ * One tool that a {@link ToolSource} listed for a model call, with the source that listed it.
11
+ * @since 0.4.0
12
+ */
13
+ export interface ListedSourceTool {
14
+ /** The source that listed the tool. */
15
+ readonly source: ToolSource;
16
+ /** The tool definition as the source listed it. */
17
+ readonly tool: SourceToolDefinition;
18
+ }
19
+ /**
20
+ * Options of a {@link ToolSourceRouter}.
21
+ * @since 0.4.0
22
+ */
23
+ export interface ToolSourceRouterOptions {
24
+ /**
25
+ * JSON key under which the router stores the building source's name in each call's `toolSourceReference`,
26
+ * such as `"vercel_ai_tool_source"`. Keep it fixed: stored calls are routed by it.
27
+ */
28
+ readonly sourceNameKey: string;
29
+ /** Names of the runner's own tools, which no source tool may repeat. Defaults to none. */
30
+ readonly localToolNames?: ReadonlySet<string>;
31
+ /**
32
+ * What the runner's own tools are, for the collision error, such as `"a function tool"`. Defaults to
33
+ * `"a tool of the agent"`.
34
+ */
35
+ readonly localToolDescription?: string;
36
+ /** Names of the built-in tools enabled for every session, which no source tool may repeat. Defaults to none. */
37
+ readonly builtInToolNames?: ReadonlySet<string>;
38
+ /**
39
+ * How long one {@link ToolSourceRouter.listSourceTools} waits for each source, in milliseconds. Defaults to
40
+ * {@link defaultToolSourceListingTimeoutMs}.
41
+ */
42
+ readonly listingTimeoutMs?: number;
43
+ }
44
+ /**
45
+ * Serves {@link ToolSource}s from a framework runner, so their calls run in tool Steps as the Stepwise runner runs
46
+ * them.
47
+ *
48
+ * A framework adapter that implements {@link AgentFrameworkRunner} builds one router from its `toolSources`. In each
49
+ * `RunModel` it awaits {@link listSourceTools} and offers every listed tool to its framework as a native tool that
50
+ * never runs inside the model call. When the model calls one, the adapter returns {@link buildDeferredToolCall}, so
51
+ * the source picks the effect, the approval, and whether the call is an ordered write, and the router stores the
52
+ * source's name with the source's own `toolSourceReference`. The tool Step then reaches that source through
53
+ * {@link executeDeferredToolCall} on any Worker, with the full execution: the Step context, the heartbeat
54
+ * checkpoint, and the attempt. {@link toolCallStepOptions}, {@link pollToolTask}, and {@link cancelToolTask} route
55
+ * the same way. A runner whose `executeDeferredToolCall` returns only results, and so polls no tool tasks, uses
56
+ * {@link executeDeferredToolCallForResult} instead. `StepwiseAgentRunner` uses a router too.
57
+ *
58
+ * Construction refuses a source without a {@link ToolSource} method or a non-blank, unique `sourceName`, and a
59
+ * name that a source declares through `declaredToolNames` when it repeats a local tool, a built-in tool, or another
60
+ * source's tool. Each listing refuses the same collisions among the listed names.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const toolSources = new ToolSourceRouter([new ConnectorToolSource([refund])], {
65
+ * sourceNameKey: "my_framework_tool_source",
66
+ * localToolNames: new Set(Object.keys(frameworkTools)),
67
+ * });
68
+ * const listed = await toolSources.listSourceTools();
69
+ * const call = toolSources.buildDeferredToolCall(turn, listed.get("refund")!, modelCall);
70
+ * ```
71
+ * @since 0.4.0
72
+ */
73
+ export declare class ToolSourceRouter {
74
+ private readonly toolSources;
75
+ private readonly toolSourcesByName;
76
+ private readonly sourceNameKey;
77
+ private readonly localToolNames;
78
+ private readonly localToolDescription;
79
+ private readonly listingTimeoutMs;
80
+ /** The last listing of each source, so estimates count its tools without listing again. */
81
+ private readonly lastListings;
82
+ /**
83
+ * Creates the router and checks the sources.
84
+ * @param toolSources - The sources, in the order the model sees their tools.
85
+ * @param options - The envelope key, the names source tools must not repeat, and the listing timeout.
86
+ * @throws {TypeError} When a source lacks a {@link ToolSource} method or a non-blank `sourceName`, two sources
87
+ * share a `sourceName`, `sourceNameKey` is blank, or a declared tool name repeats a local tool, a built-in tool, or
88
+ * another source's tool.
89
+ * @throws {RangeError} When `listingTimeoutMs` is not positive.
90
+ */
91
+ constructor(toolSources: readonly ToolSource[], options: ToolSourceRouterOptions);
92
+ /** Whether the router has at least one source. */
93
+ get hasToolSources(): boolean;
94
+ /**
95
+ * Returns the names the sources always list, from their optional `declaredToolNames`.
96
+ * @returns The names.
97
+ */
98
+ declaredToolNames(): ReadonlySet<string>;
99
+ /**
100
+ * Lists every source's tools for one model call, in source order.
101
+ *
102
+ * A source whose listing throws or takes longer than the listing timeout offers no tools in this call, with a
103
+ * warning, so a down server never fails a turn.
104
+ * @param builtInToolNames - The built-in tools enabled for this turn. Defaults to none.
105
+ * @returns The listed tools by name.
106
+ * @throws {TypeError} When a listed name repeats a local tool, an enabled built-in tool, or another source's tool.
107
+ */
108
+ listSourceTools(builtInToolNames?: ReadonlySet<string>): Promise<ReadonlyMap<string, ListedSourceTool>>;
109
+ /**
110
+ * Returns each source's tools without I/O: its `cachedTools` when it has them, else this router's last listing.
111
+ * A name listed twice keeps its first source. Use it to estimate the model input.
112
+ * @returns The cached tools by name.
113
+ */
114
+ readCachedSourceTools(): ReadonlyMap<string, ListedSourceTool>;
115
+ /**
116
+ * Builds the deferred call for one model call of a listed source tool.
117
+ *
118
+ * The source's `deferredToolCall` decides the policy, the `ordered` flag, and its own reference. The router
119
+ * keeps all of it and wraps the reference with the source's name.
120
+ * @param turn - The `RunModel` context.
121
+ * @param listedTool - The listed tool the model called, from {@link listSourceTools} of this model call.
122
+ * @param modelCall - The model's tool call ID and its arguments as JSON text.
123
+ * @returns The deferred call to return in `ToolCallsRequested`.
124
+ */
125
+ buildDeferredToolCall(turn: AgentTurnContext, listedTool: ListedSourceTool, modelCall: {
126
+ readonly toolCallId: string;
127
+ readonly arguments: string;
128
+ }): DeferredToolCall;
129
+ /**
130
+ * Whether a source built this call, so its tool Step and polls go to a source. It reads only the record, so it
131
+ * answers even when that source is not configured on this Worker; {@link executeDeferredToolCall} then throws.
132
+ * @param toolCall - The call's record.
133
+ * @returns `true` when the record holds this router's envelope, or a reference while the router has sources.
134
+ */
135
+ isSourceToolCall(toolCall: {
136
+ readonly toolName: string;
137
+ readonly toolSourceReference?: string;
138
+ }): boolean;
139
+ /**
140
+ * Runs one call in its tool Step through the source that built it, with the source's own reference and every
141
+ * other field of `call` unchanged, such as the Step context, the heartbeat checkpoint, and the attempt.
142
+ * @param call - The deferred execution from the tool Step.
143
+ * @returns The source's outcome.
144
+ * @throws {RangeError} When no source built the call, or its source is not configured on this Worker, so the
145
+ * effect decides the outcome.
146
+ * @throws Any error of the source, such as `ToolExecutionError` or `ToolOutcomeUnknownError`.
147
+ */
148
+ executeDeferredToolCall(call: DeferredToolExecution): Promise<DeferredToolOutcome>;
149
+ /**
150
+ * Runs one call as {@link executeDeferredToolCall} does, for a runner that polls no tool tasks and asks no tool
151
+ * questions, so its `executeDeferredToolCall` returns only a `ToolExecutionResult`. Such a runner has no
152
+ * `pollToolTask`, so the session tells the source that it cannot start tasks. `ConnectorToolSource` returns only
153
+ * results.
154
+ * @param call - The deferred execution from the tool Step.
155
+ * @returns The source's result.
156
+ * @throws {ToolExecutionError} When the source asked the user a question. A question comes before any effect, so
157
+ * the call records `failed` and the model reads why.
158
+ * @throws {Error} When the source started a tool task anyway. The task may run, so the effect decides the outcome.
159
+ * @throws Any error of {@link executeDeferredToolCall}.
160
+ */
161
+ executeDeferredToolCallForResult(call: DeferredToolExecution): Promise<ToolExecutionResult>;
162
+ /**
163
+ * Polls a source's tool task once, through the source that built the call.
164
+ * @param poll - The call's record from `PollToolTask`.
165
+ * @returns The source's outcome.
166
+ * @throws {RangeError} When no source built the call. The task may still run, so `PollToolTask` retries and then
167
+ * records the call by its effect.
168
+ * @throws Any error of the source.
169
+ */
170
+ pollToolTask(poll: ToolTaskPoll): Promise<ToolTaskPollOutcome>;
171
+ /**
172
+ * Cancels a source's task through the source that built the call; a source without `cancelToolTask` leaves its
173
+ * task running.
174
+ * @param cancellation - The abandoned call's record from `CancelToolTask`.
175
+ * @returns A Promise that resolves once the source took the cancellation.
176
+ * @throws {RangeError} When no source built the call.
177
+ * @throws Any error of the source.
178
+ */
179
+ cancelToolTask(cancellation: ToolTaskCancellation): Promise<void>;
180
+ /**
181
+ * Returns the source's options for one call's tool Step.
182
+ * @param toolCall - The record whose tool Step starts.
183
+ * @returns The source's options, or `undefined` when no source built the call or its source defines none.
184
+ * @throws {RangeError} When a source built the call but it is not configured on this Worker; the session then
185
+ * uses the defaults.
186
+ */
187
+ toolCallStepOptions(toolCall: AgentToolCall): ToolCallStepOptions | undefined;
188
+ private refuseDeclaredToolNameCollisions;
189
+ private refuseSourceToolName;
190
+ private listOneSource;
191
+ private requireToolSource;
192
+ private routeToToolSource;
193
+ }
194
+ /**
195
+ * The router's `toolSourceReference`: the source's name under `sourceNameKey` and its own reference, as JSON text.
196
+ * @param sourceNameKey - The envelope key of the runner.
197
+ * @param sourceName - The building source's name.
198
+ * @param reference - The source's own reference, or `undefined`.
199
+ * @returns The envelope text.
200
+ */
201
+ export declare function writeToolSourceEnvelope(sourceNameKey: string, sourceName: string, reference: string | undefined): string;
202
+ /**
203
+ * Reads an envelope that {@link writeToolSourceEnvelope} wrote with the same key.
204
+ * @param sourceNameKey - The envelope key of the runner.
205
+ * @param toolSourceReference - A record's `toolSourceReference`.
206
+ * @returns The source's name and its own reference, or `undefined` when the text is no such envelope.
207
+ */
208
+ export declare function readToolSourceEnvelope(sourceNameKey: string, toolSourceReference: string | undefined): {
209
+ readonly sourceName: string;
210
+ readonly reference: string | undefined;
211
+ } | undefined;
@@ -0,0 +1,380 @@
1
+ // Copyright (c) 2026 Super Durable, Inc.
2
+ //
3
+ // Licensed under the Sustainable Use License 1.0.
4
+ // You may not use this file except in compliance with the License.
5
+ // See the LICENSE file in the repository root.
6
+ //
7
+ // SPDX-License-Identifier: LicenseRef-Sustainable-Use-1.0
8
+ import { ToolExecutionError, } from "./agent-framework-runner.js";
9
+ /**
10
+ * Default `AgentDefinition.toolSourceListingTimeoutMs`: 10 seconds. It is also the default time one model call of a
11
+ * framework adapter waits for each tool source's listing. Exported from the package root since 0.4.0.
12
+ */
13
+ export const defaultToolSourceListingTimeoutMs = 10_000;
14
+ const toolSourceMethods = ["listTools", "deferredToolCall", "executeDeferredToolCall", "pollToolTask"];
15
+ const toolSourceReferenceKey = "reference";
16
+ /**
17
+ * Serves {@link ToolSource}s from a framework runner, so their calls run in tool Steps as the Stepwise runner runs
18
+ * them.
19
+ *
20
+ * A framework adapter that implements {@link AgentFrameworkRunner} builds one router from its `toolSources`. In each
21
+ * `RunModel` it awaits {@link listSourceTools} and offers every listed tool to its framework as a native tool that
22
+ * never runs inside the model call. When the model calls one, the adapter returns {@link buildDeferredToolCall}, so
23
+ * the source picks the effect, the approval, and whether the call is an ordered write, and the router stores the
24
+ * source's name with the source's own `toolSourceReference`. The tool Step then reaches that source through
25
+ * {@link executeDeferredToolCall} on any Worker, with the full execution: the Step context, the heartbeat
26
+ * checkpoint, and the attempt. {@link toolCallStepOptions}, {@link pollToolTask}, and {@link cancelToolTask} route
27
+ * the same way. A runner whose `executeDeferredToolCall` returns only results, and so polls no tool tasks, uses
28
+ * {@link executeDeferredToolCallForResult} instead. `StepwiseAgentRunner` uses a router too.
29
+ *
30
+ * Construction refuses a source without a {@link ToolSource} method or a non-blank, unique `sourceName`, and a
31
+ * name that a source declares through `declaredToolNames` when it repeats a local tool, a built-in tool, or another
32
+ * source's tool. Each listing refuses the same collisions among the listed names.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const toolSources = new ToolSourceRouter([new ConnectorToolSource([refund])], {
37
+ * sourceNameKey: "my_framework_tool_source",
38
+ * localToolNames: new Set(Object.keys(frameworkTools)),
39
+ * });
40
+ * const listed = await toolSources.listSourceTools();
41
+ * const call = toolSources.buildDeferredToolCall(turn, listed.get("refund")!, modelCall);
42
+ * ```
43
+ * @since 0.4.0
44
+ */
45
+ export class ToolSourceRouter {
46
+ toolSources;
47
+ toolSourcesByName;
48
+ sourceNameKey;
49
+ localToolNames;
50
+ localToolDescription;
51
+ listingTimeoutMs;
52
+ /** The last listing of each source, so estimates count its tools without listing again. */
53
+ lastListings = new Map();
54
+ /**
55
+ * Creates the router and checks the sources.
56
+ * @param toolSources - The sources, in the order the model sees their tools.
57
+ * @param options - The envelope key, the names source tools must not repeat, and the listing timeout.
58
+ * @throws {TypeError} When a source lacks a {@link ToolSource} method or a non-blank `sourceName`, two sources
59
+ * share a `sourceName`, `sourceNameKey` is blank, or a declared tool name repeats a local tool, a built-in tool, or
60
+ * another source's tool.
61
+ * @throws {RangeError} When `listingTimeoutMs` is not positive.
62
+ */
63
+ constructor(toolSources, options) {
64
+ if (typeof options.sourceNameKey !== "string" || options.sourceNameKey.trim() === "") {
65
+ throw new TypeError("ToolSourceRouterOptions.sourceNameKey must be a non-blank string");
66
+ }
67
+ for (const source of toolSources) {
68
+ const missing = toolSourceMethods.find((method) => typeof source?.[method] !== "function");
69
+ if (missing !== undefined) {
70
+ throw new TypeError(`tool source ${String(source)} has no ${missing} method`);
71
+ }
72
+ }
73
+ const toolSourcesByName = new Map();
74
+ for (const source of toolSources) {
75
+ if (typeof source.sourceName !== "string" || source.sourceName.trim() === "") {
76
+ throw new TypeError(`tool source ${String(source)} needs a non-blank sourceName`);
77
+ }
78
+ if (toolSourcesByName.has(source.sourceName)) {
79
+ throw new TypeError(`two tool sources are named ${source.sourceName}`);
80
+ }
81
+ toolSourcesByName.set(source.sourceName, source);
82
+ }
83
+ const listingTimeoutMs = options.listingTimeoutMs ?? defaultToolSourceListingTimeoutMs;
84
+ if (!(listingTimeoutMs > 0)) {
85
+ throw new RangeError("toolSourceListingTimeoutMs must be positive");
86
+ }
87
+ this.toolSources = [...toolSources];
88
+ this.toolSourcesByName = toolSourcesByName;
89
+ this.sourceNameKey = options.sourceNameKey;
90
+ this.localToolNames = new Set(options.localToolNames ?? []);
91
+ this.localToolDescription = options.localToolDescription ?? "a tool of the agent";
92
+ this.listingTimeoutMs = listingTimeoutMs;
93
+ this.refuseDeclaredToolNameCollisions(options.builtInToolNames ?? new Set());
94
+ }
95
+ /** Whether the router has at least one source. */
96
+ get hasToolSources() {
97
+ return this.toolSources.length > 0;
98
+ }
99
+ /**
100
+ * Returns the names the sources always list, from their optional `declaredToolNames`.
101
+ * @returns The names.
102
+ */
103
+ declaredToolNames() {
104
+ const names = new Set();
105
+ for (const source of this.toolSources) {
106
+ for (const toolName of source.declaredToolNames?.() ?? []) {
107
+ names.add(toolName);
108
+ }
109
+ }
110
+ return names;
111
+ }
112
+ /**
113
+ * Lists every source's tools for one model call, in source order.
114
+ *
115
+ * A source whose listing throws or takes longer than the listing timeout offers no tools in this call, with a
116
+ * warning, so a down server never fails a turn.
117
+ * @param builtInToolNames - The built-in tools enabled for this turn. Defaults to none.
118
+ * @returns The listed tools by name.
119
+ * @throws {TypeError} When a listed name repeats a local tool, an enabled built-in tool, or another source's tool.
120
+ */
121
+ async listSourceTools(builtInToolNames = new Set()) {
122
+ const listed = new Map();
123
+ for (const [index, source] of this.toolSources.entries()) {
124
+ for (const tool of await this.listOneSource(index, source)) {
125
+ this.refuseSourceToolName(tool.name, builtInToolNames, listed);
126
+ listed.set(tool.name, { source, tool });
127
+ }
128
+ }
129
+ return listed;
130
+ }
131
+ /**
132
+ * Returns each source's tools without I/O: its `cachedTools` when it has them, else this router's last listing.
133
+ * A name listed twice keeps its first source. Use it to estimate the model input.
134
+ * @returns The cached tools by name.
135
+ */
136
+ readCachedSourceTools() {
137
+ const cached = new Map();
138
+ for (const [index, source] of this.toolSources.entries()) {
139
+ const tools = source.cachedTools?.() ?? this.lastListings.get(index) ?? [];
140
+ for (const tool of tools) {
141
+ if (!cached.has(tool.name)) {
142
+ cached.set(tool.name, { source, tool });
143
+ }
144
+ }
145
+ }
146
+ return cached;
147
+ }
148
+ /**
149
+ * Builds the deferred call for one model call of a listed source tool.
150
+ *
151
+ * The source's `deferredToolCall` decides the policy, the `ordered` flag, and its own reference. The router
152
+ * keeps all of it and wraps the reference with the source's name.
153
+ * @param turn - The `RunModel` context.
154
+ * @param listedTool - The listed tool the model called, from {@link listSourceTools} of this model call.
155
+ * @param modelCall - The model's tool call ID and its arguments as JSON text.
156
+ * @returns The deferred call to return in `ToolCallsRequested`.
157
+ */
158
+ buildDeferredToolCall(turn, listedTool, modelCall) {
159
+ const built = listedTool.source.deferredToolCall(turn, {
160
+ toolCallId: modelCall.toolCallId,
161
+ toolName: listedTool.tool.name,
162
+ arguments: modelCall.arguments,
163
+ listedTool: listedTool.tool,
164
+ });
165
+ return {
166
+ ...built,
167
+ toolSourceReference: writeToolSourceEnvelope(this.sourceNameKey, listedTool.source.sourceName, built.toolSourceReference),
168
+ };
169
+ }
170
+ /**
171
+ * Whether a source built this call, so its tool Step and polls go to a source. It reads only the record, so it
172
+ * answers even when that source is not configured on this Worker; {@link executeDeferredToolCall} then throws.
173
+ * @param toolCall - The call's record.
174
+ * @returns `true` when the record holds this router's envelope, or a reference while the router has sources.
175
+ */
176
+ isSourceToolCall(toolCall) {
177
+ if (readToolSourceEnvelope(this.sourceNameKey, toolCall.toolSourceReference) !== undefined) {
178
+ return true;
179
+ }
180
+ return (toolCall.toolSourceReference ?? undefined) !== undefined && this.hasToolSources;
181
+ }
182
+ /**
183
+ * Runs one call in its tool Step through the source that built it, with the source's own reference and every
184
+ * other field of `call` unchanged, such as the Step context, the heartbeat checkpoint, and the attempt.
185
+ * @param call - The deferred execution from the tool Step.
186
+ * @returns The source's outcome.
187
+ * @throws {RangeError} When no source built the call, or its source is not configured on this Worker, so the
188
+ * effect decides the outcome.
189
+ * @throws Any error of the source, such as `ToolExecutionError` or `ToolOutcomeUnknownError`.
190
+ */
191
+ async executeDeferredToolCall(call) {
192
+ const routed = this.requireToolSource(call.toolCall);
193
+ return routed.source.executeDeferredToolCall({
194
+ ...call,
195
+ toolCall: withToolSourceReference(call.toolCall, routed.reference),
196
+ });
197
+ }
198
+ /**
199
+ * Runs one call as {@link executeDeferredToolCall} does, for a runner that polls no tool tasks and asks no tool
200
+ * questions, so its `executeDeferredToolCall` returns only a `ToolExecutionResult`. Such a runner has no
201
+ * `pollToolTask`, so the session tells the source that it cannot start tasks. `ConnectorToolSource` returns only
202
+ * results.
203
+ * @param call - The deferred execution from the tool Step.
204
+ * @returns The source's result.
205
+ * @throws {ToolExecutionError} When the source asked the user a question. A question comes before any effect, so
206
+ * the call records `failed` and the model reads why.
207
+ * @throws {Error} When the source started a tool task anyway. The task may run, so the effect decides the outcome.
208
+ * @throws Any error of {@link executeDeferredToolCall}.
209
+ */
210
+ async executeDeferredToolCallForResult(call) {
211
+ const outcome = await this.executeDeferredToolCall(call);
212
+ if (!("kind" in outcome)) {
213
+ return outcome;
214
+ }
215
+ const toolName = call.toolCall.toolName;
216
+ if (outcome.kind === "tool_input_requested") {
217
+ throw new ToolExecutionError(`tool ${toolName} asked a question, which this agent cannot ask the user`);
218
+ }
219
+ throw new Error(`tool ${toolName} started a tool task, which this agent cannot poll`);
220
+ }
221
+ /**
222
+ * Polls a source's tool task once, through the source that built the call.
223
+ * @param poll - The call's record from `PollToolTask`.
224
+ * @returns The source's outcome.
225
+ * @throws {RangeError} When no source built the call. The task may still run, so `PollToolTask` retries and then
226
+ * records the call by its effect.
227
+ * @throws Any error of the source.
228
+ */
229
+ async pollToolTask(poll) {
230
+ const routed = this.requireToolSource(poll.toolCall);
231
+ return routed.source.pollToolTask({ ...poll, toolCall: withToolSourceReference(poll.toolCall, routed.reference) });
232
+ }
233
+ /**
234
+ * Cancels a source's task through the source that built the call; a source without `cancelToolTask` leaves its
235
+ * task running.
236
+ * @param cancellation - The abandoned call's record from `CancelToolTask`.
237
+ * @returns A Promise that resolves once the source took the cancellation.
238
+ * @throws {RangeError} When no source built the call.
239
+ * @throws Any error of the source.
240
+ */
241
+ async cancelToolTask(cancellation) {
242
+ const routed = this.requireToolSource(cancellation.toolCall);
243
+ await routed.source.cancelToolTask?.({
244
+ ...cancellation,
245
+ toolCall: withToolSourceReference(cancellation.toolCall, routed.reference),
246
+ });
247
+ }
248
+ /**
249
+ * Returns the source's options for one call's tool Step.
250
+ * @param toolCall - The record whose tool Step starts.
251
+ * @returns The source's options, or `undefined` when no source built the call or its source defines none.
252
+ * @throws {RangeError} When a source built the call but it is not configured on this Worker; the session then
253
+ * uses the defaults.
254
+ */
255
+ toolCallStepOptions(toolCall) {
256
+ const routed = this.routeToToolSource(toolCall);
257
+ return routed?.source.toolCallStepOptions?.(withToolSourceReference(toolCall, routed.reference));
258
+ }
259
+ refuseDeclaredToolNameCollisions(builtInToolNames) {
260
+ const declared = new Map();
261
+ for (const source of this.toolSources) {
262
+ const names = [...(source.declaredToolNames?.() ?? [])].sort();
263
+ for (const toolName of names) {
264
+ this.refuseSourceToolName(toolName, builtInToolNames, declared);
265
+ }
266
+ for (const toolName of names) {
267
+ declared.set(toolName, source);
268
+ }
269
+ }
270
+ }
271
+ refuseSourceToolName(toolName, builtInToolNames, otherSourceTools) {
272
+ if (builtInToolNames.has(toolName)) {
273
+ throw new TypeError(`tool ${toolName} uses the name of an enabled built-in tool`);
274
+ }
275
+ if (this.localToolNames.has(toolName)) {
276
+ throw new TypeError(`tool ${toolName} of a tool source uses the name of ${this.localToolDescription}`);
277
+ }
278
+ if (otherSourceTools.has(toolName)) {
279
+ throw new TypeError(`two tool sources list a tool named ${toolName}`);
280
+ }
281
+ }
282
+ async listOneSource(index, source) {
283
+ const listing = source.listTools();
284
+ // A listing that outlives this call keeps running; nobody else reads its error.
285
+ listing.catch(() => undefined);
286
+ let timer;
287
+ const timedOut = new Promise((resolve) => {
288
+ timer = setTimeout(() => resolve("timed_out"), this.listingTimeoutMs);
289
+ });
290
+ try {
291
+ const tools = await Promise.race([listing, timedOut]);
292
+ if (tools === "timed_out") {
293
+ console.warn(`tool source ${index} listed nothing within ${this.listingTimeoutMs} ms`);
294
+ return [];
295
+ }
296
+ this.lastListings.set(index, tools);
297
+ return tools;
298
+ }
299
+ catch (error) {
300
+ console.warn(`tool source ${index} could not list its tools: ${error instanceof Error ? error.message : String(error)}`);
301
+ return [];
302
+ }
303
+ finally {
304
+ clearTimeout(timer);
305
+ }
306
+ }
307
+ requireToolSource(toolCall) {
308
+ const routed = this.routeToToolSource(toolCall);
309
+ if (routed === undefined) {
310
+ throw new RangeError(`no tool source built the call of tool ${toolCall.toolName}`);
311
+ }
312
+ return routed;
313
+ }
314
+ routeToToolSource(toolCall) {
315
+ const envelope = readToolSourceEnvelope(this.sourceNameKey, toolCall.toolSourceReference);
316
+ if (envelope !== undefined) {
317
+ const source = this.toolSourcesByName.get(envelope.sourceName);
318
+ if (source === undefined) {
319
+ throw new RangeError(`tool source ${envelope.sourceName}, which built the call of tool ${toolCall.toolName}, is not configured on this Worker`);
320
+ }
321
+ return { source, reference: envelope.reference };
322
+ }
323
+ const reference = toolCall.toolSourceReference ?? undefined;
324
+ if (reference === undefined || this.toolSources.length === 0) {
325
+ return undefined;
326
+ }
327
+ const onlySource = this.toolSources.length === 1 ? this.toolSources[0] : undefined;
328
+ if (onlySource !== undefined) {
329
+ // A reference the source built itself, such as in a runner subclass.
330
+ return { source: onlySource, reference };
331
+ }
332
+ throw new RangeError(`cannot tell which tool source built the call of ${toolCall.toolName}`);
333
+ }
334
+ }
335
+ /**
336
+ * The router's `toolSourceReference`: the source's name under `sourceNameKey` and its own reference, as JSON text.
337
+ * @param sourceNameKey - The envelope key of the runner.
338
+ * @param sourceName - The building source's name.
339
+ * @param reference - The source's own reference, or `undefined`.
340
+ * @returns The envelope text.
341
+ */
342
+ export function writeToolSourceEnvelope(sourceNameKey, sourceName, reference) {
343
+ return JSON.stringify({ [sourceNameKey]: sourceName, [toolSourceReferenceKey]: reference ?? null });
344
+ }
345
+ /**
346
+ * Reads an envelope that {@link writeToolSourceEnvelope} wrote with the same key.
347
+ * @param sourceNameKey - The envelope key of the runner.
348
+ * @param toolSourceReference - A record's `toolSourceReference`.
349
+ * @returns The source's name and its own reference, or `undefined` when the text is no such envelope.
350
+ */
351
+ export function readToolSourceEnvelope(sourceNameKey, toolSourceReference) {
352
+ if (toolSourceReference === undefined || toolSourceReference === null) {
353
+ return undefined;
354
+ }
355
+ let envelope;
356
+ try {
357
+ envelope = JSON.parse(toolSourceReference);
358
+ }
359
+ catch {
360
+ return undefined;
361
+ }
362
+ if (typeof envelope !== "object" || envelope === null || Array.isArray(envelope)) {
363
+ return undefined;
364
+ }
365
+ const sourceName = envelope[sourceNameKey];
366
+ const reference = envelope[toolSourceReferenceKey];
367
+ if (typeof sourceName !== "string") {
368
+ return undefined;
369
+ }
370
+ if (reference !== null && reference !== undefined && typeof reference !== "string") {
371
+ return undefined;
372
+ }
373
+ return { sourceName, reference: reference ?? undefined };
374
+ }
375
+ /** The record as the source built it: its own reference instead of the router's envelope. */
376
+ function withToolSourceReference(toolCall, reference) {
377
+ const { toolSourceReference: _envelope, ...rest } = toolCall;
378
+ return (reference === undefined ? rest : { ...rest, toolSourceReference: reference });
379
+ }
380
+ //# sourceMappingURL=tool-source-router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-source-router.js","sourceRoot":"","sources":["../../src/tool-source-router.ts"],"names":[],"mappings":"AAAA,yCAAyC;AACzC,EAAE;AACF,kDAAkD;AAClD,mEAAmE;AACnE,+CAA+C;AAC/C,EAAE;AACF,0DAA0D;AAE1D,OAAO,EACL,kBAAkB,GAUnB,MAAM,6BAA6B,CAAC;AAIrC;;;GAGG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AAExD,MAAM,iBAAiB,GAAG,CAAC,WAAW,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,cAAc,CAAU,CAAC;AAChH,MAAM,sBAAsB,GAAG,WAAW,CAAC;AAuC3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,OAA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ChG,CAAC"}
@@ -63,8 +63,9 @@ export declare function formatAgentEventSseFrame(message: StreamMessage<AgentEve
63
63
  * Each event becomes one frame whose `id` is its Dex resume token and whose data is the `AgentEvent` wire
64
64
  * JSON: `type`, `turn_id`, `attempt`, `step_execution_id`, and `payload` text. Reconnecting with the last
65
65
  * `id` continues with the next event, with no repeated or missing event while the Stream retains them.
66
- * After each empty long poll it yields a keep-alive comment. The stream never ends on its own; stop
67
- * iterating, or abort `signal`, when the browser goes away.
66
+ * After each empty long poll it yields a keep-alive comment. The stream ends on its own only once the
67
+ * session's Flow failed and every event was sent; otherwise stop iterating, or abort `signal`, when the
68
+ * browser goes away.
68
69
  *
69
70
  * The browser applies the event rules of the session contract. Within one `step_execution_id` it keeps
70
71
  * only the highest `attempt` and drops the partial text of lower attempts. After `turn_completed`,