ai-sdk-azure-durable-task 0.0.0 → 1.0.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.
- package/CHANGELOG.md +90 -0
- package/CONTRIBUTING.md +69 -0
- package/LICENSE +22 -0
- package/README.md +324 -2
- package/dist/src/agent.d.ts +110 -0
- package/dist/src/agent.js +1336 -0
- package/dist/src/agent.js.map +1 -0
- package/dist/src/approvals.d.ts +20 -0
- package/dist/src/approvals.js +100 -0
- package/dist/src/approvals.js.map +1 -0
- package/dist/src/client-entry.d.ts +12 -0
- package/dist/src/client-entry.js +7 -0
- package/dist/src/client-entry.js.map +1 -0
- package/dist/src/client.d.ts +109 -0
- package/dist/src/client.js +498 -0
- package/dist/src/client.js.map +1 -0
- package/dist/src/decisions.d.ts +54 -0
- package/dist/src/decisions.js +44 -0
- package/dist/src/decisions.js.map +1 -0
- package/dist/src/durable-chat-transport.d.ts +48 -0
- package/dist/src/durable-chat-transport.js +173 -0
- package/dist/src/durable-chat-transport.js.map +1 -0
- package/dist/src/history-types.d.ts +21 -0
- package/dist/src/history-types.js +6 -0
- package/dist/src/history-types.js.map +1 -0
- package/dist/src/history.d.ts +35 -0
- package/dist/src/history.js +163 -0
- package/dist/src/history.js.map +1 -0
- package/dist/src/http.d.ts +9 -0
- package/dist/src/http.js +67 -0
- package/dist/src/http.js.map +1 -0
- package/dist/src/index.d.ts +25 -0
- package/dist/src/index.js +14 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/logging.d.ts +4 -0
- package/dist/src/logging.js +8 -0
- package/dist/src/logging.js.map +1 -0
- package/dist/src/mcp.d.ts +41 -0
- package/dist/src/mcp.js +112 -0
- package/dist/src/mcp.js.map +1 -0
- package/dist/src/status.d.ts +29 -0
- package/dist/src/status.js +50 -0
- package/dist/src/status.js.map +1 -0
- package/dist/src/steps.d.ts +41 -0
- package/dist/src/steps.js +125 -0
- package/dist/src/steps.js.map +1 -0
- package/dist/src/stores/postgres.d.ts +53 -0
- package/dist/src/stores/postgres.js +140 -0
- package/dist/src/stores/postgres.js.map +1 -0
- package/dist/src/stores/sqlite.d.ts +1 -0
- package/dist/src/stores/sqlite.js +2 -0
- package/dist/src/stores/sqlite.js.map +1 -0
- package/dist/src/streaming/redis.d.ts +33 -0
- package/dist/src/streaming/redis.js +55 -0
- package/dist/src/streaming/redis.js.map +1 -0
- package/dist/src/streaming.d.ts +29 -0
- package/dist/src/streaming.js +64 -0
- package/dist/src/streaming.js.map +1 -0
- package/dist/src/telemetry.d.ts +10 -0
- package/dist/src/telemetry.js +49 -0
- package/dist/src/telemetry.js.map +1 -0
- package/dist/src/testing/index.d.ts +70 -0
- package/dist/src/testing/index.js +165 -0
- package/dist/src/testing/index.js.map +1 -0
- package/dist/src/tools.d.ts +96 -0
- package/dist/src/tools.js +69 -0
- package/dist/src/tools.js.map +1 -0
- package/dist/src/types.d.ts +321 -0
- package/dist/src/types.js +19 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/validation.d.ts +1 -0
- package/dist/src/validation.js +19 -0
- package/dist/src/validation.js.map +1 -0
- package/dist/src/worker-entry.d.ts +7 -0
- package/dist/src/worker-entry.js +6 -0
- package/dist/src/worker-entry.js.map +1 -0
- package/dist/src/worker.d.ts +24 -0
- package/dist/src/worker.js +107 -0
- package/dist/src/worker.js.map +1 -0
- package/docs/Hosted-DTS.md +115 -0
- package/docs/architecture.md +76 -0
- package/docs/decisions/0001-dual-surface-authoring.md +14 -0
- package/docs/decisions/0002-generator-turn-stepper.md +8 -0
- package/docs/decisions/0003-tools-deps-and-mcp.md +19 -0
- package/docs/decisions/0004-approvals-and-status.md +18 -0
- package/docs/decisions/0005-state-streaming-subagents-versioning.md +19 -0
- package/docs/decisions/0006-maf-entity-session-comparison-and-hybrid-model.md +360 -0
- package/docs/decisions/0007-workflow-world-dts-and-durable-functions-sketch.md +191 -0
- package/docs/decisions/README.md +17 -0
- package/docs/development.md +139 -0
- package/docs/getting-started.md +325 -0
- package/docs/limitations.md +130 -0
- package/docs/operations.md +178 -0
- package/docs/security-and-tenancy.md +41 -0
- package/docs/support-matrix.md +26 -0
- package/docs/user-guide.md +1120 -0
- package/package.json +121 -12
- package/index.js +0 -1
|
@@ -0,0 +1,1336 @@
|
|
|
1
|
+
import { generateText, streamText, stepCountIs, asSchema, jsonSchema, NoObjectGeneratedError, ToolLoopAgent, } from "ai";
|
|
2
|
+
import { whenAll, whenAny, TaskFailedError, } from "@microsoft/durabletask-js";
|
|
3
|
+
import { hash, isHistoryRef, isToolOutputRef } from "./history.js";
|
|
4
|
+
import { buildBoundedCustomStatus } from "./status.js";
|
|
5
|
+
import { ToolPolicy, TOOL_POLICY, ToolExecution, LocalToolMode, NonRetryableToolError, FatalToolError, PolicyConflictError, createDepsProxy, toToolResultMessage, durableTool } from "./tools.js";
|
|
6
|
+
import { approvalGates, removePendingExternalEventWaiter } from "./approvals.js";
|
|
7
|
+
import { Limits, } from "./types.js";
|
|
8
|
+
import { DurableAgentClient } from "./client.js";
|
|
9
|
+
import { encodeStep, decodeStep, decodeStepProjection, sumUsage, assertSerializable, appendStepMessages, stepContext, parseContext } from "./steps.js";
|
|
10
|
+
import { validateAgentConfig } from "./validation.js";
|
|
11
|
+
import { assistantMessageId, stepChunk, coalesceChunks } from "./streaming.js";
|
|
12
|
+
import { validateTraceContext, withTraceContext } from "./telemetry.js";
|
|
13
|
+
const workerNames = new WeakMap();
|
|
14
|
+
const CHILD = Symbol.for("ai-sdk-azure-durable-task/subagent");
|
|
15
|
+
function isAsyncIterable(value) {
|
|
16
|
+
return value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
|
|
17
|
+
}
|
|
18
|
+
function callSettings(source) {
|
|
19
|
+
const settings = {};
|
|
20
|
+
for (const key of ["temperature", "maxOutputTokens", "topP", "topK", "presencePenalty", "frequencyPenalty", "stopSequences", "seed", "headers"]) {
|
|
21
|
+
if (source[key] !== undefined)
|
|
22
|
+
Object.assign(settings, { [key]: source[key] });
|
|
23
|
+
}
|
|
24
|
+
return settings;
|
|
25
|
+
}
|
|
26
|
+
function registrationVersion(input) {
|
|
27
|
+
const state = input && typeof input === "object" && "state" in input ? input.state : input;
|
|
28
|
+
if (!state || typeof state !== "object" || !("version" in state) || typeof state.version !== "string")
|
|
29
|
+
throw new Error("Missing registered execution version");
|
|
30
|
+
return state.version;
|
|
31
|
+
}
|
|
32
|
+
export class DurableTaskAgent {
|
|
33
|
+
orchestratorName;
|
|
34
|
+
config;
|
|
35
|
+
registrations = new WeakSet();
|
|
36
|
+
constructor(config) {
|
|
37
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(config.name))
|
|
38
|
+
throw new Error("Agent name must be 1-64 alphanumeric, underscore or hyphen characters");
|
|
39
|
+
this.config = config;
|
|
40
|
+
this.orchestratorName = `agent__${config.name}`;
|
|
41
|
+
assertSerializable(config.runtimeContext ?? config.experimental_context, "runtimeContext");
|
|
42
|
+
assertSerializable(config.toolsContext, "toolsContext");
|
|
43
|
+
validateAgentConfig(config);
|
|
44
|
+
if (config.system !== undefined && config.instructions !== undefined && JSON.stringify(config.system) !== JSON.stringify(config.instructions))
|
|
45
|
+
throw new PolicyConflictError("Conflicting system and instructions");
|
|
46
|
+
if (config.maxConcurrency !== undefined && (!Number.isSafeInteger(config.maxConcurrency) || config.maxConcurrency < 1))
|
|
47
|
+
throw new Error("maxConcurrency must be a positive integer");
|
|
48
|
+
if (config.approvalTimeoutMs !== undefined && (!Number.isFinite(config.approvalTimeoutMs) || config.approvalTimeoutMs <= 0))
|
|
49
|
+
throw new Error("approvalTimeoutMs must be positive");
|
|
50
|
+
if (config.toolOutputOffloadThresholdBytes !== undefined && (!Number.isSafeInteger(config.toolOutputOffloadThresholdBytes) || config.toolOutputOffloadThresholdBytes < 1))
|
|
51
|
+
throw new Error("toolOutputOffloadThresholdBytes must be a positive safe integer");
|
|
52
|
+
for (const [name, definition] of Object.entries(config.tools ?? {})) {
|
|
53
|
+
const inline = TOOL_POLICY in definition ? definition[TOOL_POLICY] : undefined;
|
|
54
|
+
const external = config.toolPolicies?.[name];
|
|
55
|
+
if (inline && external && JSON.stringify(inline) !== JSON.stringify(external))
|
|
56
|
+
throw new PolicyConflictError(`Policy conflict: ${name}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
versionConfig(version) {
|
|
60
|
+
if (version === (this.config.version ?? "v1"))
|
|
61
|
+
return this.config;
|
|
62
|
+
const previous = this.config.previousVersions?.[version];
|
|
63
|
+
if (!previous)
|
|
64
|
+
throw new Error(`Unsupported agent version: ${version}`);
|
|
65
|
+
return previous;
|
|
66
|
+
}
|
|
67
|
+
async messages(history, version) {
|
|
68
|
+
if (!history)
|
|
69
|
+
return [];
|
|
70
|
+
if (isHistoryRef(history)) {
|
|
71
|
+
const store = this.versionConfig(history.version ?? version).historyStore;
|
|
72
|
+
if (!store)
|
|
73
|
+
throw new Error("HistoryStore required for reference");
|
|
74
|
+
return store.get(history.__history_ref__);
|
|
75
|
+
}
|
|
76
|
+
return history;
|
|
77
|
+
}
|
|
78
|
+
async stepHistory(state) {
|
|
79
|
+
if (state.history && isHistoryRef(state.history)) {
|
|
80
|
+
const store = this.versionConfig(state.history.version ?? state.version).historyStore;
|
|
81
|
+
if (!store)
|
|
82
|
+
throw new Error("HistoryStore required for step history");
|
|
83
|
+
return store.getSteps(state.history.__history_ref__);
|
|
84
|
+
}
|
|
85
|
+
return state.stepHistory ?? [];
|
|
86
|
+
}
|
|
87
|
+
async save(state, messages, suffix, instanceId, steps = []) {
|
|
88
|
+
const store = this.versionConfig(state.version).historyStore;
|
|
89
|
+
if (!store)
|
|
90
|
+
return messages;
|
|
91
|
+
const key = hash(`${instanceId}:${this.config.name}:${state.invocationId}:${state.generation}:${state.step}:${state.turns}:${suffix}:${hash(JSON.stringify({ messages, steps }))}`);
|
|
92
|
+
await store.put(key, messages, steps);
|
|
93
|
+
return { __history_ref__: key, version: state.version };
|
|
94
|
+
}
|
|
95
|
+
async finishStep(state, encoded, terminal) {
|
|
96
|
+
const config = this.versionConfig(state.version);
|
|
97
|
+
const steps = encoded.map(data => decodeStep(data)).filter(step => step.stepNumber >= (state.turnStartStep ?? 0));
|
|
98
|
+
const last = steps.at(-1);
|
|
99
|
+
if (!last)
|
|
100
|
+
throw new Error("Missing persisted model step");
|
|
101
|
+
await config.onStepFinish?.(last);
|
|
102
|
+
if (config.onStepEnd !== config.onStepFinish)
|
|
103
|
+
await config.onStepEnd?.(last);
|
|
104
|
+
const conditions = config.stopWhen ? Array.isArray(config.stopWhen) ? config.stopWhen : [config.stopWhen] : [];
|
|
105
|
+
let stop = terminal;
|
|
106
|
+
const limits = config.limits ?? new Limits();
|
|
107
|
+
if (!limits.throwOnMaxSteps && steps.length >= limits.maxSteps)
|
|
108
|
+
stop = true;
|
|
109
|
+
for (const condition of conditions)
|
|
110
|
+
if (await condition({ steps }))
|
|
111
|
+
stop = true;
|
|
112
|
+
return stop;
|
|
113
|
+
}
|
|
114
|
+
async finishRun(state, encoded, output) {
|
|
115
|
+
const steps = encoded.map(data => decodeStep(data)).filter(step => step.stepNumber >= (state.turnStartStep ?? 0));
|
|
116
|
+
const last = steps.at(-1);
|
|
117
|
+
if (!last)
|
|
118
|
+
throw new Error("Missing persisted final model step");
|
|
119
|
+
const config = this.versionConfig(state.version);
|
|
120
|
+
const totalUsage = sumUsage(steps);
|
|
121
|
+
const event = { ...last, steps, usage: totalUsage, totalUsage, finalStep: last,
|
|
122
|
+
output: output,
|
|
123
|
+
content: steps.flatMap(step => step.content),
|
|
124
|
+
files: steps.flatMap(step => step.files), sources: steps.flatMap(step => step.sources),
|
|
125
|
+
toolCalls: steps.flatMap(step => step.toolCalls), staticToolCalls: steps.flatMap(step => step.staticToolCalls),
|
|
126
|
+
dynamicToolCalls: steps.flatMap(step => step.dynamicToolCalls),
|
|
127
|
+
toolResults: steps.flatMap(step => step.toolResults), staticToolResults: steps.flatMap(step => step.staticToolResults),
|
|
128
|
+
dynamicToolResults: steps.flatMap(step => step.dynamicToolResults), warnings: steps.flatMap(step => step.warnings ?? []),
|
|
129
|
+
responseMessages: steps.flatMap(step => step.response.messages) };
|
|
130
|
+
await config.onFinish?.(event);
|
|
131
|
+
if (config.onEnd !== config.onFinish)
|
|
132
|
+
await config.onEnd?.(event);
|
|
133
|
+
}
|
|
134
|
+
async finalizeOutput(state, step) {
|
|
135
|
+
const config = this.versionConfig(state.version);
|
|
136
|
+
try {
|
|
137
|
+
return { output: config.output
|
|
138
|
+
? await config.output.parseCompleteOutput({ text: step.text }, { response: step.response, usage: step.usage, finishReason: step.finishReason })
|
|
139
|
+
: step.text };
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (!NoObjectGeneratedError.isInstance(error))
|
|
143
|
+
throw error;
|
|
144
|
+
return { validationError: `${error.message}${error.cause instanceof Error ? ` ${error.cause.message}` : ""}` };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async modelStep(ctx, input) {
|
|
148
|
+
const { state } = input;
|
|
149
|
+
const config = this.versionConfig(state.version);
|
|
150
|
+
const messages = await this.messages(state.history, state.version);
|
|
151
|
+
const encoded = await this.stepHistory(state);
|
|
152
|
+
const priorSteps = encoded.map(data => decodeStep(data)).filter(step => step.stepNumber >= (state.turnStartStep ?? 0));
|
|
153
|
+
const schemaTools = {};
|
|
154
|
+
for (const [name, definition] of Object.entries(config.tools ?? {})) {
|
|
155
|
+
const { execute: _execute, needsApproval: _approval, toolApproval: _toolApproval, contextSchema: _contextSchema, onInputAvailable: _available, onInputStart: _start, onInputDelta: _delta, ...schema } = definition;
|
|
156
|
+
schemaTools[name] = schema;
|
|
157
|
+
}
|
|
158
|
+
for (const [server, tools] of Object.entries(input.mcpTools)) {
|
|
159
|
+
for (const definition of tools)
|
|
160
|
+
schemaTools[`${server}__${definition.name}`] = { description: definition.description, inputSchema: jsonSchema(await definition.schema) };
|
|
161
|
+
}
|
|
162
|
+
const rawOutput = config.output
|
|
163
|
+
? { ...config.output, parseCompleteOutput: async ({ text }) => text } : undefined;
|
|
164
|
+
const context = "experimental_context" in state ? state.experimental_context : config.experimental_context;
|
|
165
|
+
const prepared = await config.prepareStep?.({
|
|
166
|
+
model: config.model, messages, stepNumber: state.step - (state.turnStartStep ?? 0), totalStepNumber: state.step,
|
|
167
|
+
steps: priorSteps, experimental_context: context, runtimeContext: context, toolsContext: state.toolsContext ?? config.toolsContext,
|
|
168
|
+
instructions: state.instructions ?? config.instructions ?? config.system, initialInstructions: config.instructions ?? config.system,
|
|
169
|
+
initialMessages: messages.slice(0, state.initialTurnMessagesCount ?? messages.length),
|
|
170
|
+
responseMessages: messages.slice(state.initialTurnMessagesCount ?? messages.length),
|
|
171
|
+
});
|
|
172
|
+
const newContext = prepared && stepContext(prepared);
|
|
173
|
+
const preparedContext = newContext === undefined ? context : await parseContext(newContext, config.contextSchema, "runtimeContext");
|
|
174
|
+
let toolsContext = prepared?.toolsContext ?? state.toolsContext ?? config.toolsContext;
|
|
175
|
+
assertSerializable(preparedContext, "prepareStep runtimeContext/experimental_context");
|
|
176
|
+
assertSerializable(toolsContext, "prepareStep toolsContext");
|
|
177
|
+
const telemetry = config.telemetry ?? config.experimental_telemetry;
|
|
178
|
+
const options = {
|
|
179
|
+
...callSettings(config), ...state.callSettings,
|
|
180
|
+
model: config.model, tools: schemaTools, system: state.instructions ?? config.system ?? config.instructions,
|
|
181
|
+
instructions: state.instructions ?? config.instructions ?? config.system, messages,
|
|
182
|
+
toolChoice: config.toolChoice, activeTools: config.activeTools, providerOptions: config.providerOptions,
|
|
183
|
+
experimental_context: preparedContext, runtimeContext: preparedContext, toolsContext,
|
|
184
|
+
headers: prepared?.headers ?? state.callSettings?.headers ?? config.headers,
|
|
185
|
+
experimental_telemetry: telemetry ? { ...telemetry,
|
|
186
|
+
metadata: { ...Reflect.get(telemetry, "metadata"), durable_instance_id: ctx.orchestrationId,
|
|
187
|
+
durable_generation: state.generation, durable_step: state.step, traceparent: state.traceContext?.traceparent ?? "" } } : undefined,
|
|
188
|
+
prepareStep: prepared ? () => ({
|
|
189
|
+
...prepared,
|
|
190
|
+
system: Reflect.get(prepared, "system") ?? Reflect.get(prepared, "instructions"),
|
|
191
|
+
instructions: Reflect.get(prepared, "instructions") ?? Reflect.get(prepared, "system"),
|
|
192
|
+
experimental_context: preparedContext, runtimeContext: preparedContext,
|
|
193
|
+
}) : undefined,
|
|
194
|
+
experimental_include: { requestBody: config.includeRequestResponseBodies === true, responseBody: config.includeRequestResponseBodies === true },
|
|
195
|
+
include: { requestBody: config.includeRequestResponseBodies === true, responseBody: config.includeRequestResponseBodies === true },
|
|
196
|
+
stopWhen: stepCountIs(1), maxRetries: config.maxRetries ?? 2, output: rawOutput,
|
|
197
|
+
};
|
|
198
|
+
Object.assign(options, { telemetry: options.experimental_telemetry });
|
|
199
|
+
if (config.propagateTraceHeaders && state.traceContext)
|
|
200
|
+
options.headers = { ...options.headers, ...state.traceContext };
|
|
201
|
+
let generated;
|
|
202
|
+
const ui = [];
|
|
203
|
+
if (config.streamPublisher) {
|
|
204
|
+
const streamed = streamText(options);
|
|
205
|
+
for await (const chunk of streamed.toUIMessageStream({ sendSources: true })) {
|
|
206
|
+
if (chunk.type !== "start" && chunk.type !== "finish")
|
|
207
|
+
ui.push(stepChunk(chunk, state.step));
|
|
208
|
+
}
|
|
209
|
+
generated = { text: await streamed.text, toolCalls: await streamed.toolCalls, response: await streamed.response, usage: await streamed.usage, finishReason: await streamed.finishReason, steps: await streamed.steps };
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
generated = await generateText(options);
|
|
213
|
+
}
|
|
214
|
+
const next = appendStepMessages(messages, generated.response.messages);
|
|
215
|
+
const nativeStep = generated.steps[0];
|
|
216
|
+
if (!nativeStep)
|
|
217
|
+
throw new Error("AI SDK did not return a model step");
|
|
218
|
+
toolsContext = Reflect.get(nativeStep, "toolsContext") ?? toolsContext;
|
|
219
|
+
assertSerializable(toolsContext, "toolsContext");
|
|
220
|
+
const encodedStep = encodeStep(nativeStep, state.step, config.streamPublisher ? coalesceChunks(ui) : undefined, config.includeRequestResponseBodies);
|
|
221
|
+
encoded.push(encodedStep);
|
|
222
|
+
const history = await this.save(state, next, "model", ctx.orchestrationId, encoded);
|
|
223
|
+
const resolved = new Set(next.slice(messages.length).flatMap(message => typeof message.content === "string" ? [] : message.content.flatMap(part => part.type === "tool-result" ? [part.toolCallId] : [])));
|
|
224
|
+
const pending = generated.toolCalls.filter(call => !resolved.has(call.toolCallId));
|
|
225
|
+
const calls = pending.map(call => ({
|
|
226
|
+
toolCallId: call.toolCallId, toolName: call.toolName, input: call.input,
|
|
227
|
+
validationError: call.invalid ? String(call.error) : undefined,
|
|
228
|
+
providerExecuted: call.providerExecuted, providerOptions: call.providerMetadata,
|
|
229
|
+
}));
|
|
230
|
+
for (const call of calls) {
|
|
231
|
+
if (call.providerExecuted)
|
|
232
|
+
throw new Error(`Provider-executed tool has no completed provider result: ${call.toolName}`);
|
|
233
|
+
const definition = config.tools?.[call.toolName];
|
|
234
|
+
if (call.validationError)
|
|
235
|
+
continue;
|
|
236
|
+
const approval = (definition ? Reflect.get(definition, "toolApproval") ?? definition.needsApproval : undefined);
|
|
237
|
+
const toolContextSchema = definition ? Reflect.get(definition, "contextSchema") : undefined;
|
|
238
|
+
if (toolContextSchema)
|
|
239
|
+
call.context = await parseContext(toolsContext?.[call.toolName], toolContextSchema, `tool context ${call.toolName}`);
|
|
240
|
+
const approvalOptions = { toolCallId: call.toolCallId, messages, experimental_context: preparedContext,
|
|
241
|
+
runtimeContext: preparedContext, toolsContext, context: "context" in call ? call.context : toolsContext?.[call.toolName] };
|
|
242
|
+
let decision;
|
|
243
|
+
if (typeof config.toolApproval === "function")
|
|
244
|
+
decision = await config.toolApproval({
|
|
245
|
+
toolCall: call, tools: config.tools, messages,
|
|
246
|
+
runtimeContext: preparedContext, toolsContext,
|
|
247
|
+
});
|
|
248
|
+
else if (config.toolApproval && typeof config.toolApproval === "object") {
|
|
249
|
+
const rule = config.toolApproval[call.toolName];
|
|
250
|
+
decision = typeof rule === "function" ? await rule(call.input, {
|
|
251
|
+
...approvalOptions, toolContext: approvalOptions.context,
|
|
252
|
+
}) : rule;
|
|
253
|
+
}
|
|
254
|
+
else if (typeof config.toolApproval === "boolean")
|
|
255
|
+
decision = config.toolApproval;
|
|
256
|
+
else
|
|
257
|
+
decision = undefined;
|
|
258
|
+
if (decision === undefined)
|
|
259
|
+
decision = typeof approval === "function" ? await approval(call.input, approvalOptions) : approval;
|
|
260
|
+
const status = typeof decision === "object" ? decision.type : decision;
|
|
261
|
+
call.needsApproval = status === true || status === "user-approval";
|
|
262
|
+
if (status === "denied")
|
|
263
|
+
call.deniedReason = typeof decision === "object" ? decision.reason ?? "Execution denied" : "Execution denied";
|
|
264
|
+
}
|
|
265
|
+
if (calls.some(c => Buffer.byteLength(c.toolCallId) > 128 || Buffer.byteLength(c.toolName) > 128))
|
|
266
|
+
throw new Error("Tool identity exceeds 128-byte status budget");
|
|
267
|
+
if (new Set(calls.map(call => call.toolCallId)).size !== calls.length)
|
|
268
|
+
throw new Error("Duplicate pending tool-call identity");
|
|
269
|
+
const result = { history, preHistory: state.history ?? [], text: generated.text, calls, tokens: generated.usage.totalTokens ?? 0, stepHistory: isHistoryRef(history) ? undefined : encoded, experimental_context: stepContext(nativeStep) ?? preparedContext };
|
|
270
|
+
result.toolsContext = toolsContext;
|
|
271
|
+
result.instructions = (prepared ? Reflect.get(prepared, "instructions") ?? Reflect.get(prepared, "system") : undefined)
|
|
272
|
+
?? state.instructions ?? config.instructions ?? config.system;
|
|
273
|
+
if (config.streamPublisher)
|
|
274
|
+
result.committedProjectionId = hash(encodedStep);
|
|
275
|
+
const { messages: _messages, ...metadata } = generated.response;
|
|
276
|
+
result.outputContext = { response: { ...metadata, timestamp: metadata.timestamp.toISOString() }, usage: generated.usage, finishReason: generated.finishReason };
|
|
277
|
+
result.continueModel = !calls.length && generated.toolCalls.length > 0 && generated.finishReason === "tool-calls";
|
|
278
|
+
if (!calls.length) {
|
|
279
|
+
const stop = await this.finishStep(state, encoded, !result.continueModel || state.corrections > 0);
|
|
280
|
+
if (stop) {
|
|
281
|
+
result.continueModel = false;
|
|
282
|
+
Object.assign(result, await this.finalizeOutput(state, nativeStep));
|
|
283
|
+
if (!result.validationError)
|
|
284
|
+
await this.finishRun(state, encoded, result.output);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return result;
|
|
288
|
+
}
|
|
289
|
+
async publishUI(instanceId, state, chunks, key) {
|
|
290
|
+
const publisher = this.versionConfig(state.version).streamPublisher;
|
|
291
|
+
if (!publisher)
|
|
292
|
+
return;
|
|
293
|
+
chunks = coalesceChunks(chunks);
|
|
294
|
+
for (let index = 0; index < chunks.length; index++) {
|
|
295
|
+
await publisher.publish({ instanceId, step: state.step, generation: state.generation,
|
|
296
|
+
eventId: `${assistantMessageId(instanceId, state)}:${state.generation}:${state.step}:${key}:${index}`, chunk: chunks[index] });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async executeTool(ctx, input) {
|
|
300
|
+
const config = this.versionConfig(input.state.version);
|
|
301
|
+
const policy = this.policyFor(config, input.call.toolName);
|
|
302
|
+
const controller = new AbortController();
|
|
303
|
+
let deps, created = false, cleaned = false;
|
|
304
|
+
const cleanup = async () => {
|
|
305
|
+
if (!created || cleaned)
|
|
306
|
+
return;
|
|
307
|
+
cleaned = true;
|
|
308
|
+
if (config.depsCleanup)
|
|
309
|
+
await config.depsCleanup(deps);
|
|
310
|
+
else if (deps && (typeof deps === "object" || typeof deps === "function")) {
|
|
311
|
+
const asyncDispose = Symbol.asyncDispose in deps ? deps[Symbol.asyncDispose] : undefined;
|
|
312
|
+
const dispose = Symbol.dispose in deps ? deps[Symbol.dispose] : undefined;
|
|
313
|
+
if (typeof asyncDispose === "function")
|
|
314
|
+
await asyncDispose.call(deps);
|
|
315
|
+
else if (typeof dispose === "function")
|
|
316
|
+
dispose.call(deps);
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
let timer;
|
|
320
|
+
const timeout = policy.timeoutMs ? new Promise((_resolve, reject) => {
|
|
321
|
+
timer = setTimeout(() => {
|
|
322
|
+
const error = new Error(`Tool timed out after ${policy.timeoutMs}ms`);
|
|
323
|
+
controller.abort(error);
|
|
324
|
+
reject(error);
|
|
325
|
+
}, policy.timeoutMs);
|
|
326
|
+
}) : undefined;
|
|
327
|
+
const execution = (async () => {
|
|
328
|
+
try {
|
|
329
|
+
if (config.depsFactory) {
|
|
330
|
+
deps = await config.depsFactory(input.state.depsInput, ctx);
|
|
331
|
+
created = true;
|
|
332
|
+
}
|
|
333
|
+
controller.signal.throwIfAborted();
|
|
334
|
+
const options = {
|
|
335
|
+
toolCallId: input.call.toolCallId, messages: await this.messages(input.preHistory, input.state.version),
|
|
336
|
+
deps, abortSignal: controller.signal, experimental_context: input.state.experimental_context,
|
|
337
|
+
context: (input.state.toolsContext ?? config.toolsContext)?.[input.call.toolName],
|
|
338
|
+
durable: { instanceId: ctx.orchestrationId, step: input.state.step, idempotencyKey: this.effectKey(ctx.orchestrationId, input.state, input.call), currentUtcDateTime: input.utc, traceContext: input.state.traceContext },
|
|
339
|
+
};
|
|
340
|
+
Object.assign(options, { runtimeContext: input.state.experimental_context,
|
|
341
|
+
toolsContext: input.state.toolsContext ?? config.toolsContext });
|
|
342
|
+
const nativeDefinition = config.tools?.[input.call.toolName];
|
|
343
|
+
options.context = "context" in input.call ? input.call.context : await parseContext(options.context, nativeDefinition ? Reflect.get(nativeDefinition, "contextSchema") : undefined, `tool context ${input.call.toolName}`);
|
|
344
|
+
controller.signal.throwIfAborted();
|
|
345
|
+
if (input.mcp) {
|
|
346
|
+
const pool = config.mcp?.[input.mcp.serverKey];
|
|
347
|
+
if (!pool)
|
|
348
|
+
throw new Error(`Unknown MCP server: ${input.mcp.serverKey}`);
|
|
349
|
+
return await pool.executeTool(input.mcp.remoteToolName, input.call.input, options);
|
|
350
|
+
}
|
|
351
|
+
const definition = config.tools?.[input.call.toolName];
|
|
352
|
+
if (!definition?.execute)
|
|
353
|
+
throw new Error(`Unknown executable tool: ${input.call.toolName}`);
|
|
354
|
+
const result = await definition.execute(input.call.input, options);
|
|
355
|
+
if (isAsyncIterable(result)) {
|
|
356
|
+
let final;
|
|
357
|
+
let yielded = false;
|
|
358
|
+
for await (const value of result) {
|
|
359
|
+
final = value;
|
|
360
|
+
yielded = true;
|
|
361
|
+
}
|
|
362
|
+
if (!yielded)
|
|
363
|
+
throw new Error("Streaming tool completed without an output");
|
|
364
|
+
return { value: final };
|
|
365
|
+
}
|
|
366
|
+
return { value: result };
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
if (error instanceof NonRetryableToolError && !config.failRunOnToolError)
|
|
370
|
+
return { error: true, value: { error: error.message } };
|
|
371
|
+
throw error;
|
|
372
|
+
}
|
|
373
|
+
finally {
|
|
374
|
+
await cleanup();
|
|
375
|
+
}
|
|
376
|
+
})();
|
|
377
|
+
let outcome, failure, failed = false;
|
|
378
|
+
try {
|
|
379
|
+
outcome = await (timeout ? Promise.race([execution, timeout]) : execution);
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
failed = true;
|
|
383
|
+
failure = error;
|
|
384
|
+
}
|
|
385
|
+
finally {
|
|
386
|
+
clearTimeout(timer);
|
|
387
|
+
try {
|
|
388
|
+
await cleanup();
|
|
389
|
+
}
|
|
390
|
+
catch (error) {
|
|
391
|
+
failure = failed ? new AggregateError([failure, error], "Tool execution and cleanup failed") : error;
|
|
392
|
+
failed = true;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
await config.onToolAttempt?.({
|
|
396
|
+
toolName: input.call.toolName, attempt: input.attempt ?? 1,
|
|
397
|
+
maxAttempts: policy.execution === ToolExecution.LOCAL ? 1 : policy.retryPolicy?.maxNumberOfAttempts ?? 1,
|
|
398
|
+
error: failed ? failure : outcome?.error ? outcome.value : undefined,
|
|
399
|
+
classification: failed ? "infrastructure-failure" : outcome?.error ? "business-rejection" : "succeeded",
|
|
400
|
+
instanceId: ctx.orchestrationId, generation: input.state.generation, step: input.state.step, traceContext: input.state.traceContext,
|
|
401
|
+
});
|
|
402
|
+
if (failed)
|
|
403
|
+
throw failure;
|
|
404
|
+
if (config.historyStore) {
|
|
405
|
+
const serialized = JSON.stringify(outcome.value);
|
|
406
|
+
if (serialized !== undefined && Buffer.byteLength(serialized) > (config.toolOutputOffloadThresholdBytes ?? 32_768)) {
|
|
407
|
+
const key = hash(`tool-output:${this.effectKey(ctx.orchestrationId, input.state, input.call)}:${hash(JSON.stringify(outcome))}`);
|
|
408
|
+
// Persist the whole outcome so MCP model-output variants are also kept off the wire.
|
|
409
|
+
await config.historyStore.put(key, [{ role: "user", content: JSON.stringify(outcome) }]);
|
|
410
|
+
return { value: { __tool_output_ref__: key }, ...(outcome.error ? { error: true } : {}) };
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return outcome;
|
|
414
|
+
}
|
|
415
|
+
async *observeToolBatch(ctx, tasks, observed, config, onChildStatus) {
|
|
416
|
+
const pending = new Map(tasks.map((task, index) => [task, { index, attempt: 1, timer: false }]));
|
|
417
|
+
const values = [], failures = new Map();
|
|
418
|
+
let notification = onChildStatus ? ctx.waitForExternalEvent("vercel_ai.child_status") : undefined;
|
|
419
|
+
while (pending.size) {
|
|
420
|
+
const winner = (yield whenAny([...pending.keys(), ...notification ? [notification] : []]));
|
|
421
|
+
if (winner === notification) {
|
|
422
|
+
yield* onChildStatus(notification.getResult());
|
|
423
|
+
notification = ctx.waitForExternalEvent("vercel_ai.child_status");
|
|
424
|
+
continue;
|
|
425
|
+
}
|
|
426
|
+
const current = pending.get(winner);
|
|
427
|
+
pending.delete(winner);
|
|
428
|
+
const retry = observed.get(current.index);
|
|
429
|
+
if (current.timer) {
|
|
430
|
+
if (!retry)
|
|
431
|
+
throw new Error("Missing observed retry contract");
|
|
432
|
+
pending.set(ctx.callActivity(retry.activity, { ...retry.input, attempt: current.attempt }), { ...current, timer: false });
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
if (!winner.isFailed) {
|
|
436
|
+
values[current.index] = winner.getResult();
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
const failure = winner.getException(), policy = retry?.policy;
|
|
440
|
+
if (!retry || !policy || current.attempt >= policy.maxNumberOfAttempts) {
|
|
441
|
+
failures.set(current.index, failure);
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
const details = failure instanceof TaskFailedError ? failure.details
|
|
445
|
+
: { errorType: failure instanceof Error ? failure.name : "Error", message: String(failure) };
|
|
446
|
+
if (!policy.shouldRetry(details)) {
|
|
447
|
+
failures.set(current.index, failure);
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
const interval = Math.min(policy.firstRetryIntervalInMilliseconds * policy.backoffCoefficient ** (current.attempt - 1), policy.maxRetryIntervalInMilliseconds < 0 ? Infinity : policy.maxRetryIntervalInMilliseconds);
|
|
451
|
+
if (policy.retryTimeoutInMilliseconds >= 0 && ctx.currentUtcDateTime.getTime() - retry.started + interval > policy.retryTimeoutInMilliseconds) {
|
|
452
|
+
failures.set(current.index, failure);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
pending.set(ctx.createTimer(interval / 1000), { ...current, attempt: current.attempt + 1, timer: true });
|
|
456
|
+
}
|
|
457
|
+
while (notification?.isComplete) {
|
|
458
|
+
yield* onChildStatus(notification.getResult());
|
|
459
|
+
notification = ctx.waitForExternalEvent("vercel_ai.child_status");
|
|
460
|
+
}
|
|
461
|
+
if (notification)
|
|
462
|
+
removePendingExternalEventWaiter(ctx, "vercel_ai.child_status", notification);
|
|
463
|
+
for (const [index, failure] of failures)
|
|
464
|
+
values[index] = this.toolFailure(failure, config);
|
|
465
|
+
return values;
|
|
466
|
+
}
|
|
467
|
+
toolFailure(failure, config) {
|
|
468
|
+
const details = failure instanceof TaskFailedError ? failure.details : undefined;
|
|
469
|
+
const type = details?.errorType ?? (failure instanceof Error ? failure.name : "");
|
|
470
|
+
if (type.includes("FatalToolError"))
|
|
471
|
+
throw new FatalToolError(details?.message ?? String(failure));
|
|
472
|
+
if (config.failRunOnToolError || /FatalToolError|NonDeterministicDepsAccessError|PolicyConflictError/.test(type))
|
|
473
|
+
throw failure;
|
|
474
|
+
return { error: true, value: { error: details?.message ?? (failure instanceof Error ? failure.message : String(failure)) } };
|
|
475
|
+
}
|
|
476
|
+
effectKey(instanceId, state, call) {
|
|
477
|
+
return hash(`${instanceId}:${this.config.name}:${state.invocationId ?? "root"}:${state.step}:${call.toolCallId}`);
|
|
478
|
+
}
|
|
479
|
+
policyFor(config, name) {
|
|
480
|
+
const definition = config.tools?.[name];
|
|
481
|
+
const attached = definition && TOOL_POLICY in definition ? definition[TOOL_POLICY] : undefined;
|
|
482
|
+
return config.mcpToolPolicies?.[name] ?? config.toolPolicies?.[name] ?? attached ?? new ToolPolicy();
|
|
483
|
+
}
|
|
484
|
+
collectRegistration(plan, seen) {
|
|
485
|
+
if (seen.has(this))
|
|
486
|
+
return;
|
|
487
|
+
seen.add(this);
|
|
488
|
+
const entry = plan.get(this.orchestratorName) ?? { versions: new Map(), migrations: new Map(), installers: new Map() };
|
|
489
|
+
const versions = [[this.config.version ?? "v1", this.config], ...Object.entries(this.config.previousVersions ?? {})];
|
|
490
|
+
for (const [version, config] of versions) {
|
|
491
|
+
if (entry.versions.has(version) && entry.versions.get(version) !== config)
|
|
492
|
+
throw new PolicyConflictError(`Conflicting registration: ${this.orchestratorName}@${version}`);
|
|
493
|
+
entry.versions.set(version, config);
|
|
494
|
+
for (const [transition, migrate] of Object.entries(config.migrations ?? {})) {
|
|
495
|
+
const existing = entry.migrations.get(transition);
|
|
496
|
+
if (existing && existing !== migrate)
|
|
497
|
+
throw new PolicyConflictError(`Conflicting migration: ${this.orchestratorName}@${transition}`);
|
|
498
|
+
entry.migrations.set(transition, migrate);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
entry.installers.set(this, { versions: versions.map(([version]) => version), install: (worker, canonical) => this.install(worker, canonical) });
|
|
502
|
+
plan.set(this.orchestratorName, entry);
|
|
503
|
+
for (const [, config] of versions) {
|
|
504
|
+
for (const tool of Object.values(config.tools ?? {}))
|
|
505
|
+
if (CHILD in tool)
|
|
506
|
+
tool[CHILD].collect(plan, seen);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
register(worker) {
|
|
510
|
+
if (this.registrations.has(worker))
|
|
511
|
+
return worker;
|
|
512
|
+
const plan = new Map();
|
|
513
|
+
this.collectRegistration(plan, new Set());
|
|
514
|
+
const names = workerNames.get(worker) ?? new Map();
|
|
515
|
+
for (const [name, entry] of plan) {
|
|
516
|
+
for (const [version, config] of entry.versions) {
|
|
517
|
+
const old = names.get(name)?.versions.get(version);
|
|
518
|
+
if (old && old !== config)
|
|
519
|
+
throw new PolicyConflictError(`Conflicting registration: ${name}@${version}`);
|
|
520
|
+
}
|
|
521
|
+
for (const [transition, migrate] of entry.migrations) {
|
|
522
|
+
const old = names.get(name)?.migrations.get(transition);
|
|
523
|
+
if (old && old !== migrate)
|
|
524
|
+
throw new PolicyConflictError(`Conflicting migration: ${name}@${transition}`);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
const staged = new Map();
|
|
528
|
+
for (const [name, entry] of plan) {
|
|
529
|
+
const old = names.get(name);
|
|
530
|
+
const record = {
|
|
531
|
+
versions: new Map([...old?.versions ?? [], ...entry.versions]),
|
|
532
|
+
migrations: new Map([...old?.migrations ?? [], ...entry.migrations]),
|
|
533
|
+
activities: new Map([...old?.activities ?? []].map(([key, handlers]) => [key, new Map(handlers)])),
|
|
534
|
+
orchestrators: new Map([...old?.orchestrators ?? []].map(([key, handlers]) => [key, new Map(handlers)])),
|
|
535
|
+
};
|
|
536
|
+
for (const installer of entry.installers.values()) {
|
|
537
|
+
const capture = {
|
|
538
|
+
addNamedActivity(key, handler) {
|
|
539
|
+
const handlers = record.activities.get(key) ?? new Map();
|
|
540
|
+
for (const version of installer.versions)
|
|
541
|
+
if (!handlers.has(version))
|
|
542
|
+
handlers.set(version, handler);
|
|
543
|
+
record.activities.set(key, handlers);
|
|
544
|
+
},
|
|
545
|
+
addNamedOrchestrator(key, handler) {
|
|
546
|
+
const handlers = record.orchestrators.get(key) ?? new Map();
|
|
547
|
+
for (const version of installer.versions)
|
|
548
|
+
if (!handlers.has(version))
|
|
549
|
+
handlers.set(version, handler);
|
|
550
|
+
record.orchestrators.set(key, handlers);
|
|
551
|
+
},
|
|
552
|
+
};
|
|
553
|
+
installer.install(capture, () => {
|
|
554
|
+
const canonical = names.get(name);
|
|
555
|
+
if (!canonical)
|
|
556
|
+
throw new Error(`Unregistered agent contract: ${name}`);
|
|
557
|
+
return canonical;
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
staged.set(name, record);
|
|
561
|
+
}
|
|
562
|
+
for (const [name, record] of staged) {
|
|
563
|
+
const old = names.get(name);
|
|
564
|
+
for (const key of record.activities.keys())
|
|
565
|
+
if (!old?.activities.has(key)) {
|
|
566
|
+
worker.addNamedActivity(key, (ctx, input) => {
|
|
567
|
+
const handler = names.get(name)?.activities.get(key)?.get(registrationVersion(input));
|
|
568
|
+
if (!handler)
|
|
569
|
+
throw new Error(`Unregistered activity contract: ${key}@${registrationVersion(input)}`);
|
|
570
|
+
const state = input && typeof input === "object" && "state" in input ? input.state : input;
|
|
571
|
+
const traceContext = state && typeof state === "object" && "traceContext" in state ? state.traceContext : undefined;
|
|
572
|
+
return withTraceContext(traceContext, () => handler(ctx, input));
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
for (const key of record.orchestrators.keys())
|
|
576
|
+
if (!old?.orchestrators.has(key)) {
|
|
577
|
+
worker.addNamedOrchestrator(key, async function* (ctx, input) {
|
|
578
|
+
const handler = names.get(name)?.orchestrators.get(key)?.get(registrationVersion(input));
|
|
579
|
+
if (!handler)
|
|
580
|
+
throw new Error(`Unregistered orchestration contract: ${key}@${registrationVersion(input)}`);
|
|
581
|
+
return yield* handler(ctx, input);
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
for (const [name, record] of staged)
|
|
586
|
+
names.set(name, record);
|
|
587
|
+
workerNames.set(worker, names);
|
|
588
|
+
this.registrations.add(worker);
|
|
589
|
+
return worker;
|
|
590
|
+
}
|
|
591
|
+
install(worker, canonical) {
|
|
592
|
+
const self = this;
|
|
593
|
+
worker.addNamedActivity(`${this.orchestratorName}__init`, async (ctx, state) => {
|
|
594
|
+
const store = self.versionConfig(state.version).historyStore;
|
|
595
|
+
let expectedHead = state.expectedHead;
|
|
596
|
+
let history = state.history;
|
|
597
|
+
if (!history && state.threadId && store) {
|
|
598
|
+
expectedHead = await store.head(state.threadId);
|
|
599
|
+
if (expectedHead)
|
|
600
|
+
history = { __history_ref__: expectedHead, version: state.version };
|
|
601
|
+
}
|
|
602
|
+
const steps = state.turns ? await self.stepHistory(state) : [];
|
|
603
|
+
const messages = [...await self.messages(history, state.version), { role: "user", content: state.userContent ?? state.prompt }];
|
|
604
|
+
const saved = await self.save(state, messages, "init", ctx.orchestrationId, steps);
|
|
605
|
+
const config = self.versionConfig(state.version);
|
|
606
|
+
const context = state.contextValidated ? state.experimental_context
|
|
607
|
+
: await parseContext(state.experimental_context, config.contextSchema, "runtimeContext");
|
|
608
|
+
assertSerializable(context, "runtimeContext");
|
|
609
|
+
return { history: saved, stepHistory: isHistoryRef(saved) ? undefined : steps, expectedHead,
|
|
610
|
+
initialTurnMessagesCount: messages.length, experimental_context: context };
|
|
611
|
+
});
|
|
612
|
+
worker.addNamedActivity(`${this.orchestratorName}__model_step`, (ctx, input) => self.modelStep(ctx, input));
|
|
613
|
+
worker.addNamedActivity(`${this.orchestratorName}__project_model`, async (ctx, input) => {
|
|
614
|
+
const { state, projectionId } = input;
|
|
615
|
+
const encoded = (await self.stepHistory(state)).at(-1);
|
|
616
|
+
if (!encoded)
|
|
617
|
+
throw new Error("Missing committed model projection");
|
|
618
|
+
const chunks = decodeStepProjection(encoded);
|
|
619
|
+
if (!chunks)
|
|
620
|
+
throw new Error("Missing UI projection in committed model snapshot");
|
|
621
|
+
if (hash(encoded) !== projectionId)
|
|
622
|
+
throw new Error("Committed model projection identity mismatch");
|
|
623
|
+
if (state.step === (state.turnStartStep ?? 0)) {
|
|
624
|
+
await self.publishUI(ctx.orchestrationId, state, [{ type: "start", messageId: assistantMessageId(ctx.orchestrationId, state) }], "start");
|
|
625
|
+
}
|
|
626
|
+
await self.publishUI(ctx.orchestrationId, state, [{
|
|
627
|
+
type: "data-durable-model-committed", transient: true, data: { projectionId, step: state.step },
|
|
628
|
+
}, ...chunks], `model:${projectionId}`);
|
|
629
|
+
return null;
|
|
630
|
+
});
|
|
631
|
+
worker.addNamedActivity(`${this.orchestratorName}__history_append`, async (ctx, input) => {
|
|
632
|
+
const config = self.versionConfig(input.state.version);
|
|
633
|
+
const steps = await self.stepHistory(input.state);
|
|
634
|
+
let appended = input.messages, stop = false;
|
|
635
|
+
let finalized = {};
|
|
636
|
+
if (input.calls && input.outcomes) {
|
|
637
|
+
input.outcomes = await Promise.all(input.outcomes.map(async (outcome) => {
|
|
638
|
+
if (!isToolOutputRef(outcome.value))
|
|
639
|
+
return outcome;
|
|
640
|
+
if (!config.historyStore)
|
|
641
|
+
throw new Error("HistoryStore required for tool output reference");
|
|
642
|
+
const snapshot = await config.historyStore.get(outcome.value.__tool_output_ref__);
|
|
643
|
+
const stored = snapshot[0];
|
|
644
|
+
if (snapshot.length !== 1 || stored?.role !== "user" || typeof stored.content !== "string")
|
|
645
|
+
throw new Error("Invalid tool output snapshot");
|
|
646
|
+
return JSON.parse(stored.content);
|
|
647
|
+
}));
|
|
648
|
+
const results = await Promise.all(input.calls.map((call, i) => toToolResultMessage(call, input.outcomes[i], config.tools?.[call.toolName])));
|
|
649
|
+
appended = [{ role: "tool", content: results }];
|
|
650
|
+
const last = decodeStep(steps.at(-1));
|
|
651
|
+
const extra = input.calls.map((call, i) => ({
|
|
652
|
+
type: input.outcomes[i].modelOutput?.type === "execution-denied" ? "tool-output-denied"
|
|
653
|
+
: input.outcomes[i].error ? "tool-error" : "tool-result",
|
|
654
|
+
toolCallId: call.toolCallId, toolName: call.toolName, input: call.input,
|
|
655
|
+
output: input.outcomes[i].value, error: input.outcomes[i].error ? input.outcomes[i].value : undefined,
|
|
656
|
+
dynamic: false, providerMetadata: call.providerOptions,
|
|
657
|
+
}));
|
|
658
|
+
const toolResults = [...last.toolResults, ...extra.filter(part => part.type === "tool-result")];
|
|
659
|
+
const updated = {
|
|
660
|
+
...last, content: [...last.content, ...extra], toolResults,
|
|
661
|
+
staticToolResults: toolResults.filter(part => !part.dynamic), dynamicToolResults: toolResults.filter(part => part.dynamic),
|
|
662
|
+
response: { ...last.response, messages: [...last.response.messages, ...appended] },
|
|
663
|
+
};
|
|
664
|
+
steps[steps.length - 1] = encodeStep(updated, updated.stepNumber, decodeStepProjection(steps.at(-1)), config.includeRequestResponseBodies);
|
|
665
|
+
await self.publishUI(ctx.orchestrationId, input.state, input.calls.map((call, i) => {
|
|
666
|
+
const outcome = input.outcomes[i];
|
|
667
|
+
return stepChunk(outcome.modelOutput?.type === "execution-denied"
|
|
668
|
+
? { type: "tool-output-denied", toolCallId: call.toolCallId }
|
|
669
|
+
: outcome.error
|
|
670
|
+
? { type: "tool-output-error", toolCallId: call.toolCallId, errorText: JSON.stringify(outcome.value) }
|
|
671
|
+
: { type: "tool-output-available", toolCallId: call.toolCallId, output: outcome.value ?? null }, input.state.step);
|
|
672
|
+
}), "tools");
|
|
673
|
+
stop = await self.finishStep(input.state, steps, false);
|
|
674
|
+
if (stop) {
|
|
675
|
+
finalized = await self.finalizeOutput(input.state, updated);
|
|
676
|
+
if (!finalized.validationError)
|
|
677
|
+
await self.finishRun(input.state, steps, finalized.output);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
const history = await self.save(input.state, [...await self.messages(input.state.history, input.state.version), ...appended], input.suffix, ctx.orchestrationId, steps);
|
|
681
|
+
return { history, stepHistory: isHistoryRef(history) ? undefined : steps, stop, ...finalized };
|
|
682
|
+
});
|
|
683
|
+
worker.addNamedActivity(`${this.orchestratorName}__validate_override`, async (_ctx, input) => {
|
|
684
|
+
const definition = self.versionConfig(input.version).tools?.[input.call.toolName];
|
|
685
|
+
if (!definition)
|
|
686
|
+
throw new Error("Approval override requires a native tool schema");
|
|
687
|
+
const schema = asSchema(definition.inputSchema);
|
|
688
|
+
const result = schema.validate ? await schema.validate(input.value) : { success: true, value: input.value };
|
|
689
|
+
if (!result.success)
|
|
690
|
+
throw new Error(`Invalid approval override: ${String(result.error)}`);
|
|
691
|
+
return result.value;
|
|
692
|
+
});
|
|
693
|
+
worker.addNamedActivity(`${this.orchestratorName}__commit`, async (ctx, state) => {
|
|
694
|
+
const store = self.versionConfig(state.version).historyStore;
|
|
695
|
+
if (state.threadId && state.history && isHistoryRef(state.history) && store) {
|
|
696
|
+
await store.commitHead(state.threadId, state.expectedHead, state.history.__history_ref__);
|
|
697
|
+
}
|
|
698
|
+
const encoded = (await self.stepHistory(state)).at(-1);
|
|
699
|
+
await self.publishUI(ctx.orchestrationId, state, [{ type: "finish", finishReason: encoded ? decodeStep(encoded).finishReason : "stop" }], "finish");
|
|
700
|
+
return null;
|
|
701
|
+
});
|
|
702
|
+
worker.addNamedActivity(`${this.orchestratorName}__child_tools`, async (ctx, input) => {
|
|
703
|
+
const definition = self.versionConfig(input.state.version).tools?.[input.childToolName];
|
|
704
|
+
if (!definition || !(CHILD in definition))
|
|
705
|
+
throw new Error("Missing child projection contract");
|
|
706
|
+
const chunks = await definition[CHILD].projectToolOutputs(input.completed.history, input.completed.version, input.completed.toolCallIds);
|
|
707
|
+
await self.publishUI(ctx.orchestrationId, input.state, chunks, `child-tools:${input.childToolName}:${hash(JSON.stringify(input.completed))}`);
|
|
708
|
+
return null;
|
|
709
|
+
});
|
|
710
|
+
worker.addNamedActivity(`${this.orchestratorName}__decision`, async (ctx, input) => {
|
|
711
|
+
const config = self.versionConfig(input.state.version);
|
|
712
|
+
if (input.resolved === undefined) {
|
|
713
|
+
await config.decisionStore?.put(input.pending);
|
|
714
|
+
await self.publishUI(ctx.orchestrationId, input.state, [
|
|
715
|
+
...(input.pending.targetInstanceId ? [{
|
|
716
|
+
type: "tool-input-available", toolCallId: input.pending.toolCallId,
|
|
717
|
+
toolName: input.pending.toolName, input: input.pending.input,
|
|
718
|
+
}] : []),
|
|
719
|
+
...(input.pending.kind === "approval" ? [{ type: "tool-approval-request", approvalId: input.pending.approvalToken, toolCallId: input.pending.toolCallId }] : []),
|
|
720
|
+
{ type: "data-durable-approval-pending", id: input.pending.approvalToken, data: input.pending },
|
|
721
|
+
], `approval:${input.pending.approvalToken}`);
|
|
722
|
+
}
|
|
723
|
+
else {
|
|
724
|
+
await self.publishUI(ctx.orchestrationId, input.state, [
|
|
725
|
+
{ type: "data-durable-approval-resolved", id: input.pending.approvalToken,
|
|
726
|
+
data: { approvalToken: input.pending.approvalToken, toolCallId: input.pending.toolCallId, decision: input.resolved } },
|
|
727
|
+
], `resolved:${input.pending.approvalToken}`);
|
|
728
|
+
}
|
|
729
|
+
return null;
|
|
730
|
+
});
|
|
731
|
+
worker.addNamedActivity(`${this.orchestratorName}__run_failed`, async (ctx, input) => {
|
|
732
|
+
await self.versionConfig(input.state.version).onRunFailed?.({
|
|
733
|
+
instanceId: ctx.orchestrationId, version: input.state.version, generation: input.state.generation,
|
|
734
|
+
step: input.state.step, error: input.error, traceContext: input.state.traceContext,
|
|
735
|
+
});
|
|
736
|
+
await self.publishUI(ctx.orchestrationId, input.state, [{ type: "error", errorText: input.error.message }], "failed");
|
|
737
|
+
return null;
|
|
738
|
+
});
|
|
739
|
+
const configs = [this.config, ...Object.values(this.config.previousVersions ?? {})];
|
|
740
|
+
const activities = new Set(), servers = new Set();
|
|
741
|
+
for (const config of configs) {
|
|
742
|
+
for (const [name, definition] of Object.entries(config.tools ?? {})) {
|
|
743
|
+
if (definition.execute && !activities.has(name)) {
|
|
744
|
+
worker.addNamedActivity(`${this.orchestratorName}__tool__${name}`, (ctx, input) => self.executeTool(ctx, input));
|
|
745
|
+
activities.add(name);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
for (const server of Object.keys(config.mcp ?? {}))
|
|
749
|
+
servers.add(server);
|
|
750
|
+
}
|
|
751
|
+
for (const server of servers) {
|
|
752
|
+
worker.addNamedActivity(`${this.orchestratorName}__mcp__${server}__list_tools`, (_ctx, input) => {
|
|
753
|
+
const pool = self.versionConfig(input.version).mcp?.[server];
|
|
754
|
+
if (!pool)
|
|
755
|
+
throw new Error(`Unknown MCP server: ${server}`);
|
|
756
|
+
return pool.listTools();
|
|
757
|
+
});
|
|
758
|
+
worker.addNamedActivity(`${this.orchestratorName}__mcp__${server}__call_tool`, (ctx, input) => self.executeTool(ctx, input));
|
|
759
|
+
}
|
|
760
|
+
worker.addNamedOrchestrator(this.orchestratorName, async function* (ctx, state) { return yield* self.engine(ctx, state, true, canonical); });
|
|
761
|
+
}
|
|
762
|
+
client(client) { return new DurableAgentClient(this, client); }
|
|
763
|
+
initialState(prompt, options = {}) {
|
|
764
|
+
validateTraceContext(options.traceContext);
|
|
765
|
+
const version = options.version ?? this.config.version ?? "v1";
|
|
766
|
+
this.versionConfig(version);
|
|
767
|
+
return { prompt, userContent: options.userContent, depsInput: options.depsInput, threadId: options.threadId, history: options.messages, version,
|
|
768
|
+
step: 0, generation: 0, cursor: 0, corrections: 0, turns: 0, totalTokens: 0,
|
|
769
|
+
experimental_context: this.versionConfig(version).runtimeContext ?? this.versionConfig(version).experimental_context,
|
|
770
|
+
toolsContext: this.versionConfig(version).toolsContext, callSettings: options.callSettings, traceContext: options.traceContext };
|
|
771
|
+
}
|
|
772
|
+
async *runInOrchestration(ctx, prompt, ...args) {
|
|
773
|
+
const state = this.initialState(prompt, args[0]);
|
|
774
|
+
state.invocationId = ctx.newGuid();
|
|
775
|
+
const result = yield* this.engine(ctx, state, false);
|
|
776
|
+
if (!result)
|
|
777
|
+
throw new Error("Unexpected composable rollover");
|
|
778
|
+
return result;
|
|
779
|
+
}
|
|
780
|
+
async *engine(ctx, original, owned, canonical) {
|
|
781
|
+
const state = JSON.parse(JSON.stringify(original));
|
|
782
|
+
try {
|
|
783
|
+
return yield* this.executeEngine(ctx, state, owned, canonical);
|
|
784
|
+
}
|
|
785
|
+
catch (error) {
|
|
786
|
+
const config = this.versionConfig(state.version);
|
|
787
|
+
if (state.parentInstanceId && error instanceof FatalToolError)
|
|
788
|
+
ctx.sendEvent(state.parentInstanceId, "vercel_ai.child_status", {
|
|
789
|
+
instanceId: ctx.instanceId, pendingApprovals: [], fatalError: { message: error.message },
|
|
790
|
+
});
|
|
791
|
+
if (config.onRunFailed || config.streamPublisher)
|
|
792
|
+
yield ctx.callActivity(`${this.orchestratorName}__run_failed`, {
|
|
793
|
+
state, error: { name: error instanceof Error ? error.name : "Error", message: error instanceof Error ? error.message : String(error) },
|
|
794
|
+
});
|
|
795
|
+
throw error;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
async *executeEngine(ctx, state, owned, canonical) {
|
|
799
|
+
const config = this.versionConfig(state.version);
|
|
800
|
+
const limits = config.limits ?? new Limits();
|
|
801
|
+
let generationSteps = 0;
|
|
802
|
+
let generationTurns = 0;
|
|
803
|
+
let generationBytes = 0;
|
|
804
|
+
const accountBytes = (value) => { generationBytes += Buffer.byteLength(JSON.stringify(value) ?? ""); };
|
|
805
|
+
const rolloverNeeded = () => generationBytes >= limits.maxGenerationBytes
|
|
806
|
+
|| Buffer.byteLength(JSON.stringify(state)) >= limits.maxGenerationBytes
|
|
807
|
+
|| !!(limits.stepsPerGeneration && generationSteps >= limits.stepsPerGeneration);
|
|
808
|
+
const rollover = () => {
|
|
809
|
+
if (!owned)
|
|
810
|
+
throw new Error("Composable agent reached generation limits; the owning orchestrator must manage rollover");
|
|
811
|
+
state.generation++;
|
|
812
|
+
if (state.status)
|
|
813
|
+
state.status.generation = state.generation;
|
|
814
|
+
ctx.continueAsNew(state, true);
|
|
815
|
+
};
|
|
816
|
+
const status = state.status ?? { state: "running", step: state.step, generation: state.generation, cursor: state.cursor, pendingApprovals: [], recentEvents: [] };
|
|
817
|
+
const pendingDecisions = new Map();
|
|
818
|
+
const emit = (kind, summary = "", progress = {}) => {
|
|
819
|
+
status.state = kind;
|
|
820
|
+
status.step = state.step;
|
|
821
|
+
status.generation = state.generation;
|
|
822
|
+
status.turnId = state.turnId;
|
|
823
|
+
status.completedTurnIds = state.completedTurnIds;
|
|
824
|
+
status.lastCompletedTurnId = state.completedTurnIds?.at(-1);
|
|
825
|
+
status.cursor = ++state.cursor;
|
|
826
|
+
status.recentEvents.push({ cursor: status.cursor, kind, summary });
|
|
827
|
+
status.recentEvents = status.recentEvents.slice(-15);
|
|
828
|
+
state.status = buildBoundedCustomStatus(status);
|
|
829
|
+
ctx.setCustomStatus(state.status);
|
|
830
|
+
if (state.parentInstanceId)
|
|
831
|
+
ctx.sendEvent(state.parentInstanceId, "vercel_ai.child_status", {
|
|
832
|
+
...progress,
|
|
833
|
+
instanceId: ctx.instanceId, pendingApprovals: state.status.pendingApprovals.map(p => ({
|
|
834
|
+
...p, instanceId: p.instanceId ?? ctx.instanceId,
|
|
835
|
+
})),
|
|
836
|
+
pendingDecisions: state.status.pendingApprovals.flatMap(p => {
|
|
837
|
+
const pending = p.approvalToken ? pendingDecisions.get(p.approvalToken) : undefined;
|
|
838
|
+
return pending ? [pending] : [];
|
|
839
|
+
}),
|
|
840
|
+
});
|
|
841
|
+
};
|
|
842
|
+
const mcpTools = {};
|
|
843
|
+
const routes = new Map();
|
|
844
|
+
for (const server of Object.keys(config.mcp ?? {})) {
|
|
845
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(server))
|
|
846
|
+
throw new PolicyConflictError(`Invalid MCP server key: ${server}`);
|
|
847
|
+
mcpTools[server] = (yield ctx.callActivity(`${this.orchestratorName}__mcp__${server}__list_tools`, { version: state.version }));
|
|
848
|
+
for (const remote of mcpTools[server]) {
|
|
849
|
+
const name = `${server}__${remote.name}`;
|
|
850
|
+
if (Buffer.byteLength(name) > 128 || routes.has(name) || name in (config.tools ?? {}))
|
|
851
|
+
throw new PolicyConflictError(`MCP tool name collision or oversize: ${name}`);
|
|
852
|
+
routes.set(name, { serverKey: server, remoteToolName: remote.name });
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
if (state.session && state.awaitingUser) {
|
|
856
|
+
const first = (yield ctx.waitForExternalEvent("vercel_ai.user_message"));
|
|
857
|
+
if (typeof first.prompt !== "string")
|
|
858
|
+
throw new Error("Session requires an initial user message");
|
|
859
|
+
state.prompt = first.prompt;
|
|
860
|
+
state.userContent = first.userContent;
|
|
861
|
+
state.turnId = first.turnId ?? ctx.newGuid();
|
|
862
|
+
state.awaitingUser = false;
|
|
863
|
+
}
|
|
864
|
+
while (true) {
|
|
865
|
+
if (!state.started) {
|
|
866
|
+
const init = (yield ctx.callActivity(`${this.orchestratorName}__init`, state));
|
|
867
|
+
accountBytes(init);
|
|
868
|
+
state.history = init.history;
|
|
869
|
+
state.stepHistory = init.stepHistory;
|
|
870
|
+
state.expectedHead = init.expectedHead;
|
|
871
|
+
state.started = true;
|
|
872
|
+
state.initialTurnMessagesCount = init.initialTurnMessagesCount;
|
|
873
|
+
state.experimental_context = init.experimental_context;
|
|
874
|
+
state.contextValidated = true;
|
|
875
|
+
state.instructions = config.instructions ?? config.system;
|
|
876
|
+
emit("running");
|
|
877
|
+
}
|
|
878
|
+
if (!state.pendingTurn && state.step - (state.turnStartStep ?? 0) >= limits.maxSteps)
|
|
879
|
+
throw new Error(`Agent exceeded maxSteps=${limits.maxSteps}`);
|
|
880
|
+
const resumed = state.pendingTurn !== undefined;
|
|
881
|
+
const turn = state.pendingTurn ?? (yield ctx.callActivity(`${this.orchestratorName}__model_step`, { state, mcpTools }, { retry: config.modelRetryPolicy }));
|
|
882
|
+
if (!resumed)
|
|
883
|
+
accountBytes(turn);
|
|
884
|
+
delete state.pendingTurn;
|
|
885
|
+
state.history = turn.history;
|
|
886
|
+
state.stepHistory = turn.stepHistory;
|
|
887
|
+
state.experimental_context = turn.experimental_context;
|
|
888
|
+
state.toolsContext = turn.toolsContext;
|
|
889
|
+
state.instructions = turn.instructions ?? state.instructions;
|
|
890
|
+
if (!resumed) {
|
|
891
|
+
state.totalTokens += turn.tokens;
|
|
892
|
+
generationSteps++;
|
|
893
|
+
}
|
|
894
|
+
// Recorded legacy model results have no marker and must retain their original task sequence.
|
|
895
|
+
if (!resumed && turn.committedProjectionId) {
|
|
896
|
+
yield ctx.callActivity(`${this.orchestratorName}__project_model`, {
|
|
897
|
+
state, projectionId: turn.committedProjectionId,
|
|
898
|
+
}, { retry: config.modelRetryPolicy });
|
|
899
|
+
}
|
|
900
|
+
status.latestTextPreview = turn.text;
|
|
901
|
+
emit("model_completed", turn.text);
|
|
902
|
+
if (!turn.calls.length && !turn.validationError && !turn.continueModel) {
|
|
903
|
+
yield ctx.callActivity(`${this.orchestratorName}__commit`, state);
|
|
904
|
+
const result = {
|
|
905
|
+
instanceId: ctx.instanceId, text: turn.text, output: turn.output, history: state.history, steps: state.step + 1,
|
|
906
|
+
generation: state.generation, version: state.version, totalUsage: { totalTokens: state.totalTokens },
|
|
907
|
+
outputContext: turn.outputContext,
|
|
908
|
+
stepHistory: state.stepHistory,
|
|
909
|
+
};
|
|
910
|
+
state.turns++;
|
|
911
|
+
generationTurns++;
|
|
912
|
+
if (state.session && state.turnId)
|
|
913
|
+
state.completedTurnIds = [...(state.completedTurnIds ?? []), state.turnId].slice(-32);
|
|
914
|
+
emit(state.session ? "idle" : "completed", turn.text);
|
|
915
|
+
if (!state.session)
|
|
916
|
+
return result;
|
|
917
|
+
if (isHistoryRef(state.history))
|
|
918
|
+
state.expectedHead = state.history.__history_ref__;
|
|
919
|
+
while (true) {
|
|
920
|
+
const next = (yield ctx.waitForExternalEvent("vercel_ai.user_message"));
|
|
921
|
+
if (next.close) {
|
|
922
|
+
emit("completed", turn.text);
|
|
923
|
+
return result;
|
|
924
|
+
}
|
|
925
|
+
if (typeof next.prompt !== "string")
|
|
926
|
+
throw new Error("Session message must include a prompt");
|
|
927
|
+
if (next.turnId && state.completedTurnIds?.includes(next.turnId))
|
|
928
|
+
continue;
|
|
929
|
+
state.prompt = next.prompt;
|
|
930
|
+
state.userContent = next.userContent;
|
|
931
|
+
state.turnId = next.turnId ?? ctx.newGuid();
|
|
932
|
+
break;
|
|
933
|
+
}
|
|
934
|
+
state.started = false;
|
|
935
|
+
state.step++;
|
|
936
|
+
state.turnStartStep = state.step;
|
|
937
|
+
state.corrections = 0;
|
|
938
|
+
if (generationTurns >= limits.maxTurnsPerGeneration || rolloverNeeded()) {
|
|
939
|
+
rollover();
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
continue;
|
|
943
|
+
}
|
|
944
|
+
if (turn.validationError) {
|
|
945
|
+
if (++state.corrections > (config.structuredOutputRetries ?? 2))
|
|
946
|
+
throw new Error(`Structured output validation failed: ${turn.validationError}`);
|
|
947
|
+
const corrected = (yield ctx.callActivity(`${this.orchestratorName}__history_append`, {
|
|
948
|
+
state, messages: [{ role: "user", content: `Correct the output to match the requested schema: ${turn.validationError}` }], suffix: "correction",
|
|
949
|
+
}));
|
|
950
|
+
accountBytes(corrected);
|
|
951
|
+
state.history = corrected.history;
|
|
952
|
+
state.stepHistory = corrected.stepHistory;
|
|
953
|
+
}
|
|
954
|
+
else if (turn.calls.length) {
|
|
955
|
+
const outputs = [];
|
|
956
|
+
status.pendingApprovals = turn.calls.filter(call => {
|
|
957
|
+
const definition = config.tools?.[call.toolName];
|
|
958
|
+
const server = routes.get(call.toolName);
|
|
959
|
+
return !call.deniedReason && !call.validationError && (definition || server) && !state.approvedCalls?.includes(call.toolCallId)
|
|
960
|
+
&& (call.needsApproval || (definition && !definition.execute && !server && !(CHILD in definition)));
|
|
961
|
+
}).map(call => {
|
|
962
|
+
const definition = config.tools?.[call.toolName];
|
|
963
|
+
return { toolCallId: call.toolCallId, toolName: call.toolName,
|
|
964
|
+
kind: !definition?.execute && !routes.has(call.toolName) && !(definition && CHILD in definition) ? "deferred" : "approval",
|
|
965
|
+
argsPreview: JSON.stringify(call.input),
|
|
966
|
+
approvalToken: hash(`${this.config.name}:${state.invocationId ?? "root"}:${state.version}:${state.generation}:${state.step}:${call.toolCallId}`) };
|
|
967
|
+
});
|
|
968
|
+
for (const gate of status.pendingApprovals) {
|
|
969
|
+
const call = turn.calls.find(call => call.toolCallId === gate.toolCallId);
|
|
970
|
+
const pending = { instanceId: ctx.instanceId, approvalToken: gate.approvalToken,
|
|
971
|
+
toolCallId: gate.toolCallId, toolName: gate.toolName, input: call.input, kind: gate.kind,
|
|
972
|
+
version: state.version, generation: state.generation, step: state.step };
|
|
973
|
+
pendingDecisions.set(gate.approvalToken, pending);
|
|
974
|
+
if (config.decisionStore || config.streamPublisher)
|
|
975
|
+
yield ctx.callActivity(`${this.orchestratorName}__decision`, { state, pending });
|
|
976
|
+
}
|
|
977
|
+
for (let index = 0; index < turn.calls.length; index++) {
|
|
978
|
+
const call = turn.calls[index];
|
|
979
|
+
if (call.deniedReason) {
|
|
980
|
+
outputs[index] = { error: true, value: { error: call.deniedReason },
|
|
981
|
+
modelOutput: { type: "execution-denied", reason: call.deniedReason } };
|
|
982
|
+
continue;
|
|
983
|
+
}
|
|
984
|
+
if (call.validationError) {
|
|
985
|
+
outputs[index] = { error: true, value: { error: call.validationError } };
|
|
986
|
+
continue;
|
|
987
|
+
}
|
|
988
|
+
const definition = config.tools?.[call.toolName];
|
|
989
|
+
const server = routes.get(call.toolName);
|
|
990
|
+
if (!definition && !server) {
|
|
991
|
+
outputs[index] = { error: true, value: { error: `Unknown tool: ${call.toolName}` } };
|
|
992
|
+
continue;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
// Listen to the entire batch, but schedule no effects until every gate resolves.
|
|
996
|
+
const gates = status.pendingApprovals.map(gate => ({ toolCallId: gate.toolCallId, token: gate.approvalToken }));
|
|
997
|
+
if (gates.length)
|
|
998
|
+
emit("waiting");
|
|
999
|
+
const self = this;
|
|
1000
|
+
const upgrade = yield* approvalGates(ctx, gates, config.approvalTimeoutMs ?? 86_400_000, async function* (gate, decision) {
|
|
1001
|
+
const index = turn.calls.findIndex(call => call.toolCallId === gate.toolCallId);
|
|
1002
|
+
const call = turn.calls[index];
|
|
1003
|
+
const pending = pendingDecisions.get(gate.token);
|
|
1004
|
+
status.pendingApprovals = status.pendingApprovals.filter(p => p.approvalToken !== gate.token);
|
|
1005
|
+
pendingDecisions.delete(gate.token);
|
|
1006
|
+
emit(status.pendingApprovals.length ? "waiting" : "approval_resolved", call.toolName, { resolvedDecision: { approvalToken: gate.token, approved: decision.approved, reason: decision.reason } });
|
|
1007
|
+
if (config.decisionStore || config.streamPublisher) {
|
|
1008
|
+
yield ctx.callActivity(`${self.orchestratorName}__decision`, { state, pending, resolved: decision });
|
|
1009
|
+
}
|
|
1010
|
+
if (!decision.approved) {
|
|
1011
|
+
outputs[index] = { error: true, value: { error: decision.reason ?? "Approval rejected" },
|
|
1012
|
+
modelOutput: { type: "execution-denied", reason: decision.reason ?? "Approval rejected" } };
|
|
1013
|
+
}
|
|
1014
|
+
else if (pending.kind === "deferred") {
|
|
1015
|
+
outputs[index] = { value: decision.result };
|
|
1016
|
+
}
|
|
1017
|
+
else {
|
|
1018
|
+
if (decision.overrideArgs !== undefined)
|
|
1019
|
+
call.input = yield ctx.callActivity(`${self.orchestratorName}__validate_override`, { version: state.version, call, value: decision.overrideArgs });
|
|
1020
|
+
(state.approvedCalls ??= []).push(call.toolCallId);
|
|
1021
|
+
}
|
|
1022
|
+
});
|
|
1023
|
+
if (upgrade) {
|
|
1024
|
+
for (const gate of status.pendingApprovals) {
|
|
1025
|
+
const pending = pendingDecisions.get(gate.approvalToken);
|
|
1026
|
+
if (config.decisionStore || config.streamPublisher)
|
|
1027
|
+
yield ctx.callActivity(`${this.orchestratorName}__decision`, { state, pending, resolved: upgrade });
|
|
1028
|
+
}
|
|
1029
|
+
status.pendingApprovals = [];
|
|
1030
|
+
if (!owned)
|
|
1031
|
+
throw new Error("Upgrade requires an owned agent orchestration");
|
|
1032
|
+
const contracts = canonical?.();
|
|
1033
|
+
if (!contracts)
|
|
1034
|
+
throw new Error("Owned upgrade requires canonical registration");
|
|
1035
|
+
const migrate = contracts.migrations.get(`${state.version}->${upgrade.targetVersion}`);
|
|
1036
|
+
if (!migrate)
|
|
1037
|
+
throw new Error(`No migration: ${state.version}->${upgrade.targetVersion}`);
|
|
1038
|
+
if (!contracts.versions.has(upgrade.targetVersion))
|
|
1039
|
+
throw new Error(`Unsupported agent version: ${upgrade.targetVersion}`);
|
|
1040
|
+
state.pendingTurn = turn;
|
|
1041
|
+
const migrated = migrate({ state, payload: upgrade.payload });
|
|
1042
|
+
migrated.version = upgrade.targetVersion;
|
|
1043
|
+
migrated.generation = state.generation + 1;
|
|
1044
|
+
// Migration is not approval: the replacement version must publish its own gate.
|
|
1045
|
+
migrated.approvedCalls = [];
|
|
1046
|
+
if (migrated.pendingTurn)
|
|
1047
|
+
for (const pending of migrated.pendingTurn.calls)
|
|
1048
|
+
pending.needsApproval = true;
|
|
1049
|
+
ctx.continueAsNew(migrated, true);
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
const concurrency = config.maxConcurrency ?? Math.max(turn.calls.length, 1);
|
|
1053
|
+
for (let offset = 0; offset < turn.calls.length; offset += concurrency) {
|
|
1054
|
+
const batch = turn.calls.slice(offset, offset + concurrency);
|
|
1055
|
+
const tasks = [];
|
|
1056
|
+
const observed = new Map();
|
|
1057
|
+
const indices = [];
|
|
1058
|
+
const childInstances = new Set();
|
|
1059
|
+
const childToolNames = new Map();
|
|
1060
|
+
for (let i = 0; i < batch.length; i++) {
|
|
1061
|
+
const call = batch[i];
|
|
1062
|
+
if (outputs[offset + i])
|
|
1063
|
+
continue;
|
|
1064
|
+
const definition = config.tools?.[call.toolName];
|
|
1065
|
+
const server = routes.get(call.toolName);
|
|
1066
|
+
if (definition && CHILD in definition) {
|
|
1067
|
+
const child = definition[CHILD];
|
|
1068
|
+
const childState = child.initialState(call.input, {
|
|
1069
|
+
depsInput: state.depsInput, experimental_context: state.experimental_context, runtimeContext: state.experimental_context,
|
|
1070
|
+
toolsContext: state.toolsContext, traceContext: state.traceContext,
|
|
1071
|
+
durable: { instanceId: ctx.instanceId, step: state.step, idempotencyKey: this.effectKey(ctx.instanceId, state, call), currentUtcDateTime: ctx.currentUtcDateTime.toISOString() },
|
|
1072
|
+
});
|
|
1073
|
+
childState.parentInstanceId = ctx.instanceId;
|
|
1074
|
+
childState.invocationId = ctx.newGuid();
|
|
1075
|
+
childInstances.add(childState.invocationId);
|
|
1076
|
+
childToolNames.set(childState.invocationId, call.toolName);
|
|
1077
|
+
tasks.push(ctx.callSubOrchestrator(child.name, childState, { instanceId: childState.invocationId }));
|
|
1078
|
+
indices.push(offset + i);
|
|
1079
|
+
}
|
|
1080
|
+
else if (server) {
|
|
1081
|
+
const policy = this.policyFor(config, call.toolName);
|
|
1082
|
+
if (policy.execution === ToolExecution.LOCAL && policy.localMode === LocalToolMode.ORCHESTRATOR_INLINE)
|
|
1083
|
+
throw new PolicyConflictError("MCP tools cannot execute inside an orchestrator");
|
|
1084
|
+
const activity = `${this.orchestratorName}__mcp__${server.serverKey}__call_tool`;
|
|
1085
|
+
const input = {
|
|
1086
|
+
state, call, preHistory: turn.preHistory, utc: ctx.currentUtcDateTime.toISOString(), mcp: server,
|
|
1087
|
+
};
|
|
1088
|
+
if (config.onToolAttempt)
|
|
1089
|
+
observed.set(tasks.length, { activity, input, policy: policy.retryPolicy, started: ctx.currentUtcDateTime.getTime() });
|
|
1090
|
+
tasks.push(ctx.callActivity(activity, input, { retry: config.onToolAttempt ? undefined : policy.retryPolicy }));
|
|
1091
|
+
indices.push(offset + i);
|
|
1092
|
+
}
|
|
1093
|
+
else {
|
|
1094
|
+
const policy = this.policyFor(config, call.toolName);
|
|
1095
|
+
if (policy.execution === ToolExecution.LOCAL && policy.localMode === LocalToolMode.ORCHESTRATOR_INLINE) {
|
|
1096
|
+
const options = {
|
|
1097
|
+
toolCallId: call.toolCallId,
|
|
1098
|
+
get messages() {
|
|
1099
|
+
if (isHistoryRef(turn.preHistory))
|
|
1100
|
+
throw new Error("Orchestrator-inline message access requires inline history; use activity-inline with HistoryStore");
|
|
1101
|
+
return turn.preHistory;
|
|
1102
|
+
},
|
|
1103
|
+
deps: createDepsProxy(), experimental_context: state.experimental_context,
|
|
1104
|
+
context: "context" in call ? call.context : (state.toolsContext ?? config.toolsContext)?.[call.toolName], runtimeContext: state.experimental_context,
|
|
1105
|
+
toolsContext: state.toolsContext ?? config.toolsContext,
|
|
1106
|
+
durable: { instanceId: ctx.instanceId, step: state.step, idempotencyKey: this.effectKey(ctx.instanceId, state, call), currentUtcDateTime: ctx.currentUtcDateTime.toISOString(), traceContext: state.traceContext },
|
|
1107
|
+
};
|
|
1108
|
+
let value;
|
|
1109
|
+
try {
|
|
1110
|
+
value = definition.execute(call.input, options);
|
|
1111
|
+
}
|
|
1112
|
+
catch (error) {
|
|
1113
|
+
outputs[offset + i] = this.toolFailure(error, config);
|
|
1114
|
+
continue;
|
|
1115
|
+
}
|
|
1116
|
+
if (value && (typeof value === "object" || typeof value === "function") && "then" in value)
|
|
1117
|
+
throw new Error("Orchestrator-inline tools must return synchronously");
|
|
1118
|
+
if (isAsyncIterable(value))
|
|
1119
|
+
throw new Error("Orchestrator-inline tools cannot stream; use activity-inline or durable execution");
|
|
1120
|
+
outputs[offset + i] = { value };
|
|
1121
|
+
}
|
|
1122
|
+
else {
|
|
1123
|
+
const activity = `${this.orchestratorName}__tool__${call.toolName}`;
|
|
1124
|
+
const input = { state, call, preHistory: turn.preHistory, utc: ctx.currentUtcDateTime.toISOString() };
|
|
1125
|
+
const retry = policy.execution === ToolExecution.LOCAL ? undefined : policy.retryPolicy;
|
|
1126
|
+
if (config.onToolAttempt)
|
|
1127
|
+
observed.set(tasks.length, { activity, input, policy: retry, started: ctx.currentUtcDateTime.getTime() });
|
|
1128
|
+
tasks.push(ctx.callActivity(activity, input, {
|
|
1129
|
+
retry: config.onToolAttempt ? undefined : retry,
|
|
1130
|
+
}));
|
|
1131
|
+
indices.push(offset + i);
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
if (tasks.length) {
|
|
1136
|
+
let values;
|
|
1137
|
+
const childStates = new Map();
|
|
1138
|
+
const surfacedTools = new Map();
|
|
1139
|
+
const hasChildren = batch.some(call => {
|
|
1140
|
+
const definition = config.tools?.[call.toolName];
|
|
1141
|
+
return definition && CHILD in definition;
|
|
1142
|
+
});
|
|
1143
|
+
const decisionActivity = `${this.orchestratorName}__decision`;
|
|
1144
|
+
const onChildStatus = hasChildren ? async function* (data) {
|
|
1145
|
+
const update = data;
|
|
1146
|
+
if (!update || !childInstances.has(update.instanceId) || !Array.isArray(update.pendingApprovals)) {
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
if (update.fatalError)
|
|
1150
|
+
throw new FatalToolError(update.fatalError.message);
|
|
1151
|
+
if (update.resolvedDecision) {
|
|
1152
|
+
const pending = pendingDecisions.get(update.resolvedDecision.approvalToken);
|
|
1153
|
+
if (pending && (config.decisionStore || config.streamPublisher)) {
|
|
1154
|
+
yield ctx.callActivity(decisionActivity, { state, pending, resolved: update.resolvedDecision });
|
|
1155
|
+
pendingDecisions.delete(pending.approvalToken);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
if (update.completedTools && config.streamPublisher) {
|
|
1159
|
+
const surfaced = surfacedTools.get(update.instanceId);
|
|
1160
|
+
const completed = { ...update.completedTools,
|
|
1161
|
+
toolCallIds: update.completedTools.toolCallIds.filter(id => surfaced?.has(id)) };
|
|
1162
|
+
if (completed.toolCallIds.length) {
|
|
1163
|
+
yield ctx.callActivity(`${self.orchestratorName}__child_tools`, {
|
|
1164
|
+
state, childToolName: childToolNames.get(update.instanceId), completed,
|
|
1165
|
+
});
|
|
1166
|
+
for (const id of completed.toolCallIds)
|
|
1167
|
+
surfaced.delete(id);
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
childStates.set(update.instanceId, update.pendingApprovals);
|
|
1171
|
+
for (const pending of update.pendingDecisions ?? []) {
|
|
1172
|
+
const surfaced = surfacedTools.get(update.instanceId) ?? new Set();
|
|
1173
|
+
surfaced.add(pending.toolCallId);
|
|
1174
|
+
surfacedTools.set(update.instanceId, surfaced);
|
|
1175
|
+
const mirror = { ...pending, instanceId: ctx.instanceId, targetInstanceId: pending.targetInstanceId ?? pending.instanceId };
|
|
1176
|
+
pendingDecisions.set(mirror.approvalToken, mirror);
|
|
1177
|
+
if (config.decisionStore || config.streamPublisher)
|
|
1178
|
+
yield ctx.callActivity(decisionActivity, { state, pending: mirror });
|
|
1179
|
+
}
|
|
1180
|
+
status.pendingApprovals = [...childStates.values()].flat();
|
|
1181
|
+
emit(status.pendingApprovals.length ? "waiting" : "running", "", update.resolvedDecision ? { resolvedDecision: update.resolvedDecision } : {});
|
|
1182
|
+
} : undefined;
|
|
1183
|
+
if (observed.size || hasChildren)
|
|
1184
|
+
values = yield* this.observeToolBatch(ctx, tasks, observed, config, onChildStatus);
|
|
1185
|
+
else {
|
|
1186
|
+
try {
|
|
1187
|
+
values = (yield whenAll(tasks));
|
|
1188
|
+
}
|
|
1189
|
+
catch {
|
|
1190
|
+
values = tasks.map(task => task.isFailed ? this.toolFailure(task.getException(), config) : task.getResult());
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
status.pendingApprovals = [];
|
|
1194
|
+
for (let j = 0; j < values.length; j++) {
|
|
1195
|
+
const call = turn.calls[indices[j]];
|
|
1196
|
+
const definition = config.tools?.[call.toolName];
|
|
1197
|
+
if (definition && CHILD in definition && !values[j]?.error) {
|
|
1198
|
+
outputs[indices[j]] = { value: definition[CHILD].summarize(values[j]) };
|
|
1199
|
+
}
|
|
1200
|
+
else
|
|
1201
|
+
outputs[indices[j]] = values[j];
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
accountBytes(outputs);
|
|
1206
|
+
const appended = (yield ctx.callActivity(`${this.orchestratorName}__history_append`, {
|
|
1207
|
+
state, messages: [], suffix: "tools", calls: turn.calls, outcomes: outputs,
|
|
1208
|
+
}));
|
|
1209
|
+
accountBytes(appended);
|
|
1210
|
+
state.history = appended.history;
|
|
1211
|
+
state.stepHistory = appended.stepHistory;
|
|
1212
|
+
emit("tools_completed", "", { completedTools: { history: state.history, version: state.version, toolCallIds: turn.calls.map(call => call.toolCallId) } });
|
|
1213
|
+
state.approvedCalls = [];
|
|
1214
|
+
if (appended.stop) {
|
|
1215
|
+
state.pendingTurn = { ...turn, history: state.history, stepHistory: state.stepHistory, calls: [], continueModel: false, output: appended.output, validationError: appended.validationError, tokens: 0 };
|
|
1216
|
+
if (rolloverNeeded()) {
|
|
1217
|
+
rollover();
|
|
1218
|
+
return;
|
|
1219
|
+
}
|
|
1220
|
+
continue;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
state.step++;
|
|
1224
|
+
if (rolloverNeeded()) {
|
|
1225
|
+
rollover();
|
|
1226
|
+
return;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
asTool(...args) {
|
|
1231
|
+
const options = args[0];
|
|
1232
|
+
const self = this;
|
|
1233
|
+
const definition = {
|
|
1234
|
+
description: options?.description ?? `Delegate to ${this.config.name}`,
|
|
1235
|
+
inputSchema: jsonSchema({ type: "object", properties: { prompt: { type: "string" } }, required: ["prompt"], additionalProperties: false }),
|
|
1236
|
+
outputSchema: jsonSchema({}),
|
|
1237
|
+
};
|
|
1238
|
+
const descriptor = {
|
|
1239
|
+
name: self.orchestratorName,
|
|
1240
|
+
initialState(input, context) {
|
|
1241
|
+
if (!input || typeof input !== "object" || !("prompt" in input) || typeof input.prompt !== "string")
|
|
1242
|
+
throw new Error("Subagent input requires prompt");
|
|
1243
|
+
const depsInput = typeof options?.depsInput === "function"
|
|
1244
|
+
? options.depsInput({ prompt: input.prompt }, context)
|
|
1245
|
+
: options?.depsInput;
|
|
1246
|
+
assertSerializable(depsInput, "Child depsInput");
|
|
1247
|
+
return self.initialState(input.prompt, { version: options?.version, depsInput, traceContext: context.traceContext });
|
|
1248
|
+
},
|
|
1249
|
+
collect: (plan, seen) => self.collectRegistration(plan, seen),
|
|
1250
|
+
summarize: result => options?.toModelOutput ? options.toModelOutput(result) : result.output,
|
|
1251
|
+
projectToolOutputs: async (history, version, toolCallIds) => {
|
|
1252
|
+
const wanted = new Set(toolCallIds);
|
|
1253
|
+
const messages = await self.messages(history, version);
|
|
1254
|
+
return messages.flatMap(message => message.role !== "tool" ? [] : message.content.flatMap(part => {
|
|
1255
|
+
if (part.type !== "tool-result" || !wanted.has(part.toolCallId))
|
|
1256
|
+
return [];
|
|
1257
|
+
const output = part.output;
|
|
1258
|
+
return [output.type === "execution-denied"
|
|
1259
|
+
? { type: "tool-output-denied", toolCallId: part.toolCallId }
|
|
1260
|
+
: output.type === "error-text" || output.type === "error-json"
|
|
1261
|
+
? { type: "tool-output-error", toolCallId: part.toolCallId, errorText: typeof output.value === "string" ? output.value : JSON.stringify(output.value) }
|
|
1262
|
+
: { type: "tool-output-available", toolCallId: part.toolCallId, output: "value" in output ? output.value : output }];
|
|
1263
|
+
}));
|
|
1264
|
+
},
|
|
1265
|
+
};
|
|
1266
|
+
return Object.assign(definition, { [CHILD]: descriptor });
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
export function attachDurability(source, overrides) {
|
|
1270
|
+
if (overrides)
|
|
1271
|
+
return new DurableTaskAgent(extractToolLoopAgentSettings(source, overrides));
|
|
1272
|
+
if (!("model" in source) || !("name" in source))
|
|
1273
|
+
throw new Error("Opaque AI SDK agents require explicit name and model configuration");
|
|
1274
|
+
return new DurableTaskAgent(source);
|
|
1275
|
+
}
|
|
1276
|
+
export function extractToolLoopAgentSettings(source, settings) {
|
|
1277
|
+
let descriptor;
|
|
1278
|
+
for (let owner = source; owner && !descriptor; owner = Object.getPrototypeOf(owner)) {
|
|
1279
|
+
descriptor = Object.getOwnPropertyDescriptor(owner, "settings");
|
|
1280
|
+
}
|
|
1281
|
+
// Current SDK agents emit a TS-private own field. Its presence is NOT a public API.
|
|
1282
|
+
const exposed = descriptor && (!(source instanceof ToolLoopAgent) || descriptor.get)
|
|
1283
|
+
? Reflect.get(source, "settings") : undefined;
|
|
1284
|
+
const defaults = {};
|
|
1285
|
+
if (exposed && typeof exposed === "object") {
|
|
1286
|
+
validateAgentConfig(exposed);
|
|
1287
|
+
for (const key of [
|
|
1288
|
+
"model", "instructions", "system", "stopWhen", "prepareStep", "toolApproval", "output",
|
|
1289
|
+
"onStepFinish", "onStepEnd", "onFinish", "onEnd", "experimental_telemetry", "telemetry",
|
|
1290
|
+
"experimental_context", "runtimeContext", "toolsContext", "contextSchema",
|
|
1291
|
+
"toolChoice", "activeTools", "providerOptions", "maxRetries",
|
|
1292
|
+
"temperature", "maxOutputTokens", "topP", "topK", "presencePenalty", "frequencyPenalty", "stopSequences", "seed", "headers",
|
|
1293
|
+
]) {
|
|
1294
|
+
if (Reflect.get(exposed, key) !== undefined)
|
|
1295
|
+
Object.assign(defaults, { [key]: Reflect.get(exposed, key) });
|
|
1296
|
+
}
|
|
1297
|
+
for (const aliases of [["instructions", "system"], ["runtimeContext", "experimental_context"], ["telemetry", "experimental_telemetry"]]) {
|
|
1298
|
+
if (aliases.some(key => Object.hasOwn(settings, key)))
|
|
1299
|
+
for (const key of aliases)
|
|
1300
|
+
delete defaults[key];
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
const config = { ...defaults, ...settings, tools: source.tools };
|
|
1304
|
+
if (!config.model)
|
|
1305
|
+
throw new Error("Opaque AI SDK agents require explicit name and model configuration; provide model or a public settings wrapper/getter.");
|
|
1306
|
+
return config;
|
|
1307
|
+
}
|
|
1308
|
+
export function defineDurableTaskAgent(config) {
|
|
1309
|
+
if (typeof config.tools === "function") {
|
|
1310
|
+
const bound = definition => durableTool(definition);
|
|
1311
|
+
return new DurableTaskAgent({ ...config, tools: config.tools(bound) });
|
|
1312
|
+
}
|
|
1313
|
+
return new DurableTaskAgent(config);
|
|
1314
|
+
}
|
|
1315
|
+
/**
|
|
1316
|
+
* Legacy alias for {@link DurableTaskAgent}.
|
|
1317
|
+
*
|
|
1318
|
+
* @deprecated Use `DurableTaskAgent`. This name collides with the Vercel AI SDK's own
|
|
1319
|
+
* deprecated `DurableAgent` (renamed to `WorkflowAgent`), so importing both in one module is
|
|
1320
|
+
* ambiguous. The alias is identity-preserving (`DurableAgent === DurableTaskAgent`) and is kept
|
|
1321
|
+
* for backward compatibility; it may be removed in a future major release.
|
|
1322
|
+
*/
|
|
1323
|
+
export const DurableAgent = DurableTaskAgent;
|
|
1324
|
+
/**
|
|
1325
|
+
* Legacy alias for {@link defineDurableTaskAgent}.
|
|
1326
|
+
*
|
|
1327
|
+
* @deprecated Use `defineDurableTaskAgent`. Kept for backward compatibility alongside `DurableAgent`.
|
|
1328
|
+
*/
|
|
1329
|
+
export const defineDurableAgent = defineDurableTaskAgent;
|
|
1330
|
+
export async function* durableGenerateText(ctx, options) {
|
|
1331
|
+
if (options.historyStore && options.historyStore !== options.agent.versionConfig(options.version ?? options.agent.config.version ?? "v1").historyStore) {
|
|
1332
|
+
throw new PolicyConflictError("durableGenerateText historyStore must match the registered agent's worker-bound store");
|
|
1333
|
+
}
|
|
1334
|
+
return yield* options.agent.runInOrchestration(ctx, options.prompt, ...[{ ...options, callSettings: { ...options.callSettings, ...callSettings(options) } }]);
|
|
1335
|
+
}
|
|
1336
|
+
//# sourceMappingURL=agent.js.map
|