@statelyai/agent 2.0.0-alpha.22 → 2.0.0-alpha.24

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 (48) hide show
  1. package/dist/ai-sdk.cjs +53 -25
  2. package/dist/ai-sdk.d.cts +20 -12
  3. package/dist/ai-sdk.d.mts +20 -12
  4. package/dist/ai-sdk.mjs +53 -25
  5. package/dist/{decision-DxSTqzgZ.mjs → decision-BBZ2jMO1.mjs} +444 -79
  6. package/dist/{decision-1o45_ZrS.cjs → decision-Cv6SfNWl.cjs} +525 -94
  7. package/dist/index.cjs +2224 -1032
  8. package/dist/index.d.cts +413 -275
  9. package/dist/index.d.mts +413 -275
  10. package/dist/index.mjs +2163 -983
  11. package/dist/machines.cjs +30 -2
  12. package/dist/machines.d.cts +1 -1
  13. package/dist/machines.d.mts +1 -1
  14. package/dist/machines.mjs +30 -2
  15. package/dist/openai.cjs +447 -0
  16. package/dist/openai.d.cts +177 -0
  17. package/dist/openai.d.mts +177 -0
  18. package/dist/openai.mjs +437 -0
  19. package/dist/otel.cjs +3 -6
  20. package/dist/otel.d.cts +1 -1
  21. package/dist/otel.d.mts +1 -1
  22. package/dist/otel.mjs +3 -6
  23. package/dist/run-agent-Ck7Sa3Tb.d.mts +968 -0
  24. package/dist/run-agent-DWqA8KiI.d.cts +968 -0
  25. package/dist/setup-agent-CeO2fARv.mjs +639 -0
  26. package/dist/setup-agent-Dl2VELLi.cjs +663 -0
  27. package/dist/{text-logic-BaxPrcLk.d.cts → text-logic-C7bSnH_B.d.cts} +195 -44
  28. package/dist/{text-logic-DhfFWzu9.d.mts → text-logic-DJBK3LbG.d.mts} +195 -44
  29. package/dist/{types-DSdj2tGs.d.cts → types-CjHk5OdH.d.cts} +4 -19
  30. package/dist/{types-CvWRGFxP.d.mts → types-DWA6X9R-.d.mts} +4 -19
  31. package/package.json +17 -21
  32. package/readme.md +32 -17
  33. package/dist/errors-BQRk9eiZ.d.cts +0 -19
  34. package/dist/errors-C9rxnWbX.d.mts +0 -19
  35. package/dist/errors-CeSXQx0v.mjs +0 -23
  36. package/dist/errors-DUBBzRLP.cjs +0 -28
  37. package/dist/event-log-store-Bz7HDBkE.d.cts +0 -145
  38. package/dist/event-log-store-DmIDosD6.mjs +0 -427
  39. package/dist/event-log-store-a_TKy1gk.cjs +0 -468
  40. package/dist/event-log-store-hrA1vqtN.d.mts +0 -145
  41. package/dist/run-agent-0fpEZ1wJ.d.mts +0 -1098
  42. package/dist/run-agent-Zbkx7XP8.d.cts +0 -1098
  43. package/dist/setup-agent-DkCTy5Eu.cjs +0 -1707
  44. package/dist/setup-agent-nSFYrNTP.mjs +0 -1587
  45. package/dist/sqlite.cjs +0 -129
  46. package/dist/sqlite.d.cts +0 -57
  47. package/dist/sqlite.d.mts +0 -57
  48. package/dist/sqlite.mjs +0 -127
package/dist/machines.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_setup_agent = require("./setup-agent-DkCTy5Eu.cjs");
2
+ const require_setup_agent = require("./setup-agent-Dl2VELLi.cjs");
3
3
  //#region src/machines/internal.ts
4
4
  /** The builtin inline text request every preset lowers a request entry to. */
5
5
  const GENERATE_TEXT_SRC = "agent.generateText";
@@ -22,7 +22,35 @@ function objectSchema(properties, required = []) {
22
22
  return { "~standard": {
23
23
  version: 1,
24
24
  vendor: "statelyai-agent-machines",
25
- validate: (value) => value !== null && typeof value === "object" ? { value } : { issues: [{ message: "Expected an object" }] },
25
+ validate: (value) => {
26
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return { issues: [{ message: "Expected an object" }] };
27
+ const record = value;
28
+ const issues = [];
29
+ for (const key of required) if (!(key in record) || record[key] === void 0) issues.push({
30
+ message: `Required property '${key}' is missing`,
31
+ path: [key]
32
+ });
33
+ for (const [key, schema] of Object.entries(properties)) {
34
+ const item = record[key];
35
+ if (item === void 0) continue;
36
+ const type = schema?.type;
37
+ const types = Array.isArray(type) ? type : type === void 0 ? [] : [type];
38
+ if (!(types.length === 0 || types.some((candidate) => {
39
+ switch (candidate) {
40
+ case "array": return Array.isArray(item);
41
+ case "object": return item !== null && typeof item === "object" && !Array.isArray(item);
42
+ case "null": return item === null;
43
+ case "integer": return typeof item === "number" && Number.isInteger(item);
44
+ case "number": return typeof item === "number" && Number.isFinite(item);
45
+ default: return typeof item === candidate;
46
+ }
47
+ }))) issues.push({
48
+ message: `Expected '${key}' to be ${String(type)}`,
49
+ path: [key]
50
+ });
51
+ }
52
+ return issues.length > 0 ? { issues } : { value };
53
+ },
26
54
  jsonSchema: { input: () => json }
27
55
  } };
28
56
  }
@@ -1,4 +1,4 @@
1
- import { c as AgentTools, v as StandardSchemaV1 } from "./types-DSdj2tGs.cjs";
1
+ import { _ as StandardSchemaV1, s as AgentTools } from "./types-CjHk5OdH.cjs";
2
2
  import { AnyActorRef, AnyStateMachine, EventObject, MachineContext, MetaObject, StateMachine, StateSchema, StateValue } from "xstate";
3
3
 
4
4
  //#region src/machines/internal.d.ts
@@ -1,4 +1,4 @@
1
- import { c as AgentTools, v as StandardSchemaV1 } from "./types-CvWRGFxP.mjs";
1
+ import { _ as StandardSchemaV1, s as AgentTools } from "./types-DWA6X9R-.mjs";
2
2
  import { AnyActorRef, AnyStateMachine, EventObject, MachineContext, MetaObject, StateMachine, StateSchema, StateValue } from "xstate";
3
3
 
4
4
  //#region src/machines/internal.d.ts
package/dist/machines.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { r as setupAgent } from "./setup-agent-nSFYrNTP.mjs";
1
+ import { r as setupAgent } from "./setup-agent-CeO2fARv.mjs";
2
2
  //#region src/machines/internal.ts
3
3
  /** The builtin inline text request every preset lowers a request entry to. */
4
4
  const GENERATE_TEXT_SRC = "agent.generateText";
@@ -21,7 +21,35 @@ function objectSchema(properties, required = []) {
21
21
  return { "~standard": {
22
22
  version: 1,
23
23
  vendor: "statelyai-agent-machines",
24
- validate: (value) => value !== null && typeof value === "object" ? { value } : { issues: [{ message: "Expected an object" }] },
24
+ validate: (value) => {
25
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return { issues: [{ message: "Expected an object" }] };
26
+ const record = value;
27
+ const issues = [];
28
+ for (const key of required) if (!(key in record) || record[key] === void 0) issues.push({
29
+ message: `Required property '${key}' is missing`,
30
+ path: [key]
31
+ });
32
+ for (const [key, schema] of Object.entries(properties)) {
33
+ const item = record[key];
34
+ if (item === void 0) continue;
35
+ const type = schema?.type;
36
+ const types = Array.isArray(type) ? type : type === void 0 ? [] : [type];
37
+ if (!(types.length === 0 || types.some((candidate) => {
38
+ switch (candidate) {
39
+ case "array": return Array.isArray(item);
40
+ case "object": return item !== null && typeof item === "object" && !Array.isArray(item);
41
+ case "null": return item === null;
42
+ case "integer": return typeof item === "number" && Number.isInteger(item);
43
+ case "number": return typeof item === "number" && Number.isFinite(item);
44
+ default: return typeof item === candidate;
45
+ }
46
+ }))) issues.push({
47
+ message: `Expected '${key}' to be ${String(type)}`,
48
+ path: [key]
49
+ });
50
+ }
51
+ return issues.length > 0 ? { issues } : { value };
52
+ },
25
53
  jsonSchema: { input: () => json }
26
54
  } };
27
55
  }
@@ -0,0 +1,447 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_decision = require("./decision-Cv6SfNWl.cjs");
3
+ //#region src/openai/index.ts
4
+ /** Thrown for a message part Chat Completions cannot carry — dropping it would
5
+ * silently change what the model sees. */
6
+ function unsupportedPart(role, type) {
7
+ throw new Error(`createOpenAiExecutors: a ${role} message part of type '${type}' has no Chat Completions equivalent. Send text, image, tool-call, or tool-result parts, or convert it before the request.`);
8
+ }
9
+ /** A `DataContent`/`URL` image as the URL string OpenAI's `image_url` part wants:
10
+ * an http(s) or `data:` string and a `URL` pass through, a bare base64 string and
11
+ * raw bytes are wrapped in a data URL. */
12
+ function toImageUrl(image, mediaType) {
13
+ if (image instanceof URL) return image.href;
14
+ const type = mediaType ?? "image/jpeg";
15
+ if (typeof image === "string") return /^(https?:|data:)/.test(image) ? image : `data:${type};base64,${image}`;
16
+ const bytes = image instanceof Uint8Array ? image : new Uint8Array(image);
17
+ const encode = globalThis.btoa;
18
+ if (!encode) throw new Error("createOpenAiExecutors: binary image parts need a global `btoa` to base64-encode. Pass the image as a URL or a base64 string instead.");
19
+ let binary = "";
20
+ for (const byte of bytes) binary += String.fromCharCode(byte);
21
+ return `data:${type};base64,${encode(binary)}`;
22
+ }
23
+ /** One OpenAI tool message per `ToolResultPart` — the tool role is one message per result. */
24
+ function toToolMessage(part) {
25
+ return {
26
+ role: "tool",
27
+ content: part.output.type === "text" || part.output.type === "error-text" ? part.output.value : JSON.stringify(part.output.value),
28
+ tool_call_id: part.toolCallId
29
+ };
30
+ }
31
+ /** Maps `AgentTextRequest.messages`/`system`/`prompt` to OpenAI chat messages. */
32
+ function toOpenAiMessages(request) {
33
+ if (request.messages) return request.messages.flatMap((message) => {
34
+ switch (message.role) {
35
+ case "system": return [{
36
+ role: "system",
37
+ content: message.content
38
+ }];
39
+ case "user":
40
+ if (typeof message.content === "string") return [{
41
+ role: "user",
42
+ content: message.content
43
+ }];
44
+ return [{
45
+ role: "user",
46
+ content: message.content.map((part) => {
47
+ switch (part.type) {
48
+ case "text": return {
49
+ type: "text",
50
+ text: part.text
51
+ };
52
+ case "image": return {
53
+ type: "image_url",
54
+ image_url: { url: toImageUrl(part.image, part.mediaType) }
55
+ };
56
+ default: return unsupportedPart("user", part.type);
57
+ }
58
+ })
59
+ }];
60
+ case "assistant": {
61
+ if (typeof message.content === "string") return [{
62
+ role: "assistant",
63
+ content: message.content
64
+ }];
65
+ let text = "";
66
+ const toolCalls = [];
67
+ const trailing = [];
68
+ for (const part of message.content) switch (part.type) {
69
+ case "text":
70
+ text += part.text;
71
+ break;
72
+ case "tool-call":
73
+ toolCalls.push({
74
+ id: part.toolCallId,
75
+ type: "function",
76
+ function: {
77
+ name: part.toolName,
78
+ arguments: JSON.stringify(part.input ?? {})
79
+ }
80
+ });
81
+ break;
82
+ case "tool-result":
83
+ trailing.push(toToolMessage(part));
84
+ break;
85
+ default: unsupportedPart("assistant", part.type);
86
+ }
87
+ return [{
88
+ role: "assistant",
89
+ content: text,
90
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
91
+ }, ...trailing];
92
+ }
93
+ case "tool": return message.content.map(toToolMessage);
94
+ }
95
+ });
96
+ const messages = [];
97
+ if (request.system) messages.push({
98
+ role: "system",
99
+ content: request.system
100
+ });
101
+ messages.push({
102
+ role: "user",
103
+ content: request.prompt ?? ""
104
+ });
105
+ return messages;
106
+ }
107
+ /** Drops keys whose value is `undefined`, so a spread cannot erase what it lands on. */
108
+ function defined(settings) {
109
+ return Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== void 0));
110
+ }
111
+ /**
112
+ * Maps the generation settings a text and a decision request share onto OpenAI
113
+ * Chat Completions parameters, with unset keys omitted.
114
+ *
115
+ * Omitting matters: these are the top layer of a stack — the host's
116
+ * {@link CreateOpenAiExecutorsOptions.settings}, then the request's — and an
117
+ * `undefined` spread over the layer below would erase it.
118
+ *
119
+ * `max_tokens` is deprecated by OpenAI in favor of `max_completion_tokens`, so
120
+ * that's what `maxOutputTokens` targets. Chat Completions has no `top_k`
121
+ * parameter, so `topK` is dropped.
122
+ */
123
+ function toOpenAiCallSettings(request) {
124
+ return defined({
125
+ temperature: request.temperature,
126
+ max_completion_tokens: request.maxOutputTokens,
127
+ top_p: request.topP,
128
+ seed: request.seed,
129
+ stop: request.stopSequences
130
+ });
131
+ }
132
+ /** A tool `description` may be a string or, for an AI SDK v7 tool, a function
133
+ * of the call's context. A raw JSON payload can only carry the static form. */
134
+ function staticDescription(descriptor) {
135
+ if (typeof descriptor === "function") return;
136
+ return typeof descriptor.description === "string" ? descriptor.description : void 0;
137
+ }
138
+ /** One OpenAI function tool per `AgentTools` entry. */
139
+ function toOpenAiTools(tools) {
140
+ return Object.entries(tools).flatMap(([name, descriptor]) => {
141
+ if (!descriptor) return [];
142
+ const inputSchema = typeof descriptor === "function" ? void 0 : descriptor.inputSchema;
143
+ return [{
144
+ type: "function",
145
+ function: {
146
+ name,
147
+ description: staticDescription(descriptor),
148
+ parameters: (require_decision.isStandardSchema(inputSchema) ? require_decision.getJsonSchemaSync(inputSchema) : void 0) ?? {}
149
+ }
150
+ }];
151
+ });
152
+ }
153
+ /**
154
+ * Maps an {@link AgentToolChoice} onto OpenAI's `tool_choice` —
155
+ * `{ type: 'tool', name }` becomes `{ type: 'function', function: { name } }`;
156
+ * `'auto'`/`'none'`/`'required'` are OpenAI's own vocabulary and pass through.
157
+ * `undefined` stays `undefined`, so the key is omitted.
158
+ */
159
+ function toOpenAiToolChoice(toolChoice) {
160
+ if (toolChoice === void 0) return;
161
+ return typeof toolChoice === "object" ? {
162
+ type: "function",
163
+ function: { name: toolChoice.name }
164
+ } : toolChoice;
165
+ }
166
+ /** One OpenAI function tool per candidate decision event — the "tool-per-event
167
+ * + tool_choice: 'required'" recipe, mirroring `toAiSdkEventTools`. */
168
+ function toOpenAiEventTools(events) {
169
+ return events.map((event) => ({
170
+ type: "function",
171
+ function: {
172
+ name: event.toolName,
173
+ description: `Choose the '${event.type}' move.`,
174
+ parameters: require_decision.getJsonSchemaSync(event.inputSchema) ?? {}
175
+ }
176
+ }));
177
+ }
178
+ /**
179
+ * Messages for a decision request, with prior failed `attempts` rendered as an
180
+ * appended user message so retries converge. Mirrors the AI SDK adapter's
181
+ * `toDecisionMessages`.
182
+ */
183
+ function toDecisionMessages(request) {
184
+ const messages = toOpenAiMessages(request);
185
+ for (const attempt of require_decision.renderDecisionAttempts(request)) messages.push({
186
+ role: "user",
187
+ content: attempt.content
188
+ });
189
+ return messages;
190
+ }
191
+ /**
192
+ * Folds OpenAI's usage payload onto the flat {@link AgentCallUsage} field names
193
+ * core aggregates. OpenAI nests the reasoning count under
194
+ * `completion_tokens_details` and the cache-read count under
195
+ * `prompt_tokens_details`; a field the response omitted stays omitted, so it
196
+ * never contributes a `0` to a run's partial sums.
197
+ */
198
+ function toAgentCallUsage(usage) {
199
+ if (!usage) return;
200
+ const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens;
201
+ const cachedInputTokens = usage.prompt_tokens_details?.cached_tokens;
202
+ return {
203
+ ...usage.prompt_tokens !== void 0 ? { inputTokens: usage.prompt_tokens } : {},
204
+ ...usage.completion_tokens !== void 0 ? { outputTokens: usage.completion_tokens } : {},
205
+ ...usage.total_tokens !== void 0 ? { totalTokens: usage.total_tokens } : {},
206
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
207
+ ...cachedInputTokens !== void 0 ? { cachedInputTokens } : {}
208
+ };
209
+ }
210
+ /**
211
+ * Maps an OpenAI `finish_reason` onto the portable {@link AgentFinishReason}.
212
+ * `'function_call'` (the deprecated legacy path) joins `'tool_calls'` under
213
+ * `'tool-calls'`; anything unrecognized, including a missing reason, lands on
214
+ * `'other'`. OpenAI's own string stays on the result's `raw`.
215
+ */
216
+ function toAgentFinishReason(finishReason) {
217
+ switch (finishReason) {
218
+ case "stop": return "stop";
219
+ case "length": return "length";
220
+ case "tool_calls":
221
+ case "function_call": return "tool-calls";
222
+ case "content_filter": return "content-filter";
223
+ default: return "other";
224
+ }
225
+ }
226
+ /** Resolves the host's `settings` option for one request. */
227
+ function callSettings(options, request) {
228
+ const settings = options.settings;
229
+ if (typeof settings === "function") return settings(request) ?? {};
230
+ const entry = settings?.[request.model];
231
+ if (entry === void 0) return {};
232
+ if (typeof entry !== "object" || entry === null) throw new Error(`createOpenAiExecutors: \`settings\` is keyed by model ref, so every value must be an object of OpenAI parameters, but '${request.model}' is a ${typeof entry}. Pass a function if you want one set of settings for every call.`);
233
+ return entry;
234
+ }
235
+ function truncated(request, info, partialOutput, cause) {
236
+ return new require_decision.AgentTruncatedError(`createOpenAiExecutors: request '${request.name ?? "(unnamed)"}' hit the output token limit — its structured output never completed. Raise \`maxOutputTokens\`, shorten the input, or ask for a smaller output schema.`, {
237
+ requestName: request.name ?? "(unnamed)",
238
+ ...info?.requestId !== void 0 ? { requestId: info.requestId } : {},
239
+ ...partialOutput !== void 0 ? { partialOutput } : {},
240
+ ...cause !== void 0 ? { cause } : {}
241
+ });
242
+ }
243
+ function usageField(usage) {
244
+ return usage ? { usage } : {};
245
+ }
246
+ /**
247
+ * Adds two calls' usage together, field by field. A tool loop makes several
248
+ * OpenAI calls per request, and core folds ONE `usage` per executor result into
249
+ * the run's totals, so the steps' usages have to be summed here or the run
250
+ * undercounts. A field neither call reported stays absent.
251
+ */
252
+ function addAgentCallUsage(total, next) {
253
+ if (!total || !next) return total ?? next;
254
+ const sum = {};
255
+ for (const field of require_decision.AGENT_USAGE_TOKEN_FIELDS) if (total[field] !== void 0 || next[field] !== void 0) sum[field] = (total[field] ?? 0) + (next[field] ?? 0);
256
+ return sum;
257
+ }
258
+ /**
259
+ * The function that runs one of the request's tools host-side, or `undefined`
260
+ * when the tool has no `execute` (a client-side tool: the model's call is
261
+ * handed back to the caller instead of being answered here).
262
+ */
263
+ function toolExecutor(tools, name) {
264
+ const descriptor = tools[name];
265
+ if (!descriptor) return;
266
+ if (typeof descriptor === "function") return (input) => descriptor(input);
267
+ const execute = descriptor.execute;
268
+ return typeof execute === "function" ? (input) => execute(input) : void 0;
269
+ }
270
+ function toToolContent(output) {
271
+ return typeof output === "string" ? output : JSON.stringify(output ?? null);
272
+ }
273
+ /**
274
+ * Builds the `{ generateText, streamText, decide }` executor set for the raw
275
+ * `openai` package's Chat Completions API. Compare `createAiSdkExecutors` —
276
+ * same shape, different SDK underneath.
277
+ *
278
+ * Structured output uses `response_format: { type: 'json_schema' }` around the
279
+ * uniform `{ result, reasoning? }` envelope, and decisions force a tool call
280
+ * with `tool_choice: 'required'`, one function tool per candidate event.
281
+ *
282
+ * @example
283
+ * ```ts
284
+ * const executors = createOpenAiExecutors({
285
+ * client: new OpenAI(),
286
+ * resolveModel: () => 'gpt-5.4-mini',
287
+ * });
288
+ * const result = await runAgent(machine, { input, executors });
289
+ * ```
290
+ */
291
+ function createOpenAiExecutors(options) {
292
+ const { client, resolveModel = (modelRef) => modelRef } = options;
293
+ const textParams = (request, messages, extra = {}) => {
294
+ const tools = toOpenAiTools(request.tools);
295
+ return {
296
+ model: resolveModel(request.model),
297
+ messages,
298
+ ...callSettings(options, request),
299
+ ...toOpenAiCallSettings(request),
300
+ ...tools.length > 0 ? { tools } : {},
301
+ ...extra
302
+ };
303
+ };
304
+ const envelopeSchema = async (request) => {
305
+ if (require_decision.getAgentOutputMode(request.outputSchema) !== "structured") return;
306
+ return require_decision.getJsonSchema(require_decision.buildEnvelopeSchema(request.outputSchema, { reasoning: request.includeReasoning }));
307
+ };
308
+ const generateText = async (request, info) => {
309
+ const jsonSchema = await envelopeSchema(request);
310
+ const responseFormat = jsonSchema ? { response_format: {
311
+ type: "json_schema",
312
+ json_schema: {
313
+ name: "output",
314
+ schema: jsonSchema,
315
+ strict: false
316
+ }
317
+ } } : {};
318
+ const maxSteps = typeof request.maxSteps === "number" && Number.isFinite(request.maxSteps) ? Math.max(1, Math.floor(request.maxSteps)) : 1;
319
+ const messages = toOpenAiMessages(request);
320
+ const toolChoice = toOpenAiToolChoice(request.toolChoice);
321
+ let response;
322
+ let usage;
323
+ let step = 0;
324
+ for (;;) {
325
+ step++;
326
+ response = await client.chat.completions.create(textParams(request, messages, {
327
+ ...responseFormat,
328
+ ...step === 1 && toolChoice !== void 0 ? { tool_choice: toolChoice } : {}
329
+ }), { signal: info?.signal });
330
+ usage = addAgentCallUsage(usage, toAgentCallUsage(response.usage));
331
+ const message = response.choices[0]?.message;
332
+ const toolCalls = message?.tool_calls ?? [];
333
+ if (toolCalls.length === 0 || step >= maxSteps) break;
334
+ const executors = toolCalls.map((call) => call.type === "function" ? toolExecutor(request.tools, call.function.name) : void 0);
335
+ if (executors.some((execute) => !execute)) break;
336
+ messages.push(message);
337
+ for (const [index, call] of toolCalls.entries()) {
338
+ const input = call.type === "function" && call.function.arguments ? JSON.parse(call.function.arguments) : {};
339
+ let content;
340
+ try {
341
+ content = toToolContent(await executors[index](input));
342
+ } catch (error) {
343
+ content = `Error: ${error instanceof Error ? error.message : String(error)}`;
344
+ }
345
+ messages.push({
346
+ role: "tool",
347
+ tool_call_id: call.id,
348
+ content
349
+ });
350
+ }
351
+ }
352
+ const unwrap = (content) => require_decision.parseStructuredEnvelope(request, content ? JSON.parse(content) : void 0);
353
+ const choice = response.choices[0];
354
+ const finishReason = toAgentFinishReason(choice?.finish_reason);
355
+ const content = choice?.message.content;
356
+ if (jsonSchema) {
357
+ if (finishReason === "length") throw truncated(request, info, content ?? void 0);
358
+ const parsed = unwrap(content);
359
+ return {
360
+ output: parsed.result,
361
+ ...typeof parsed.reasoning === "string" ? { reasoning: parsed.reasoning } : {},
362
+ ...usageField(usage),
363
+ finishReason,
364
+ raw: response
365
+ };
366
+ }
367
+ return {
368
+ output: content ?? "",
369
+ ...usageField(usage),
370
+ finishReason,
371
+ raw: response
372
+ };
373
+ };
374
+ const streamText = async (request, info) => {
375
+ if (require_decision.getAgentOutputMode(request.outputSchema) === "structured") throw new Error("createOpenAiExecutors: streamText is text-only — a request declaring a structured output schema must be routed to generateText.");
376
+ if (Object.keys(request.tools ?? {}).length > 0) throw new Error("createOpenAiExecutors: streamText is text-only — a request declaring tools must be routed to generateText.");
377
+ const stream = await client.chat.completions.create({
378
+ model: resolveModel(request.model),
379
+ messages: toOpenAiMessages(request),
380
+ ...callSettings(options, request),
381
+ ...toOpenAiCallSettings(request),
382
+ stream: true,
383
+ stream_options: { include_usage: true }
384
+ }, { signal: info?.signal });
385
+ let text = "";
386
+ let finishReason = "other";
387
+ let usage;
388
+ let last;
389
+ for await (const chunk of stream) {
390
+ last = chunk;
391
+ const choice = chunk.choices[0];
392
+ const delta = choice?.delta.content;
393
+ if (delta) {
394
+ text += delta;
395
+ info?.onChunk?.(delta);
396
+ }
397
+ if (choice?.finish_reason) finishReason = toAgentFinishReason(choice.finish_reason);
398
+ if (chunk.usage) usage = chunk.usage;
399
+ }
400
+ return {
401
+ output: text,
402
+ ...usageField(toAgentCallUsage(usage)),
403
+ finishReason,
404
+ raw: last
405
+ };
406
+ };
407
+ const decide = async (request, info) => {
408
+ const response = await client.chat.completions.create({
409
+ model: resolveModel(request.model),
410
+ messages: toDecisionMessages(request),
411
+ ...callSettings(options, request),
412
+ ...toOpenAiCallSettings(request),
413
+ tools: toOpenAiEventTools(request.events),
414
+ tool_choice: "required"
415
+ }, { signal: info?.signal });
416
+ const toolCall = response.choices[0]?.message.tool_calls?.[0];
417
+ if (!toolCall || toolCall.type !== "function") throw new Error("createOpenAiExecutors: decide — model did not call an event tool.");
418
+ const chosenEvent = request.events.find((event) => event.toolName === toolCall.function.name);
419
+ if (!chosenEvent) throw new Error(`createOpenAiExecutors: decide — model called unknown tool '${toolCall.function.name}'.`);
420
+ const args = toolCall.function.arguments ? JSON.parse(toolCall.function.arguments) : {};
421
+ return {
422
+ event: {
423
+ ...args && typeof args === "object" ? args : {},
424
+ type: chosenEvent.type
425
+ },
426
+ ...usageField(toAgentCallUsage(response.usage)),
427
+ finishReason: toAgentFinishReason(response.choices[0]?.finish_reason),
428
+ raw: response
429
+ };
430
+ };
431
+ return {
432
+ generateText,
433
+ streamText,
434
+ decide
435
+ };
436
+ }
437
+ //#endregion
438
+ exports.addAgentCallUsage = addAgentCallUsage;
439
+ exports.createOpenAiExecutors = createOpenAiExecutors;
440
+ exports.toAgentCallUsage = toAgentCallUsage;
441
+ exports.toAgentFinishReason = toAgentFinishReason;
442
+ exports.toDecisionMessages = toDecisionMessages;
443
+ exports.toOpenAiCallSettings = toOpenAiCallSettings;
444
+ exports.toOpenAiEventTools = toOpenAiEventTools;
445
+ exports.toOpenAiMessages = toOpenAiMessages;
446
+ exports.toOpenAiToolChoice = toOpenAiToolChoice;
447
+ exports.toOpenAiTools = toOpenAiTools;