@statelyai/agent 2.0.0-alpha.34 → 2.0.0-alpha.36

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 (130) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/dist/act-B9hLQls6.mjs +19 -0
  3. package/dist/act-CrX0JwWY.cjs +42 -0
  4. package/dist/ai-sdk.cjs +63 -7
  5. package/dist/ai-sdk.d.cts +13 -3
  6. package/dist/ai-sdk.d.mts +13 -3
  7. package/dist/ai-sdk.mjs +63 -7
  8. package/dist/{decision-BEsATcr1.cjs → decision-CMeuNZ1g.cjs} +262 -4
  9. package/dist/{decision-COkJNjOW.mjs → decision-m5hGmHpF.mjs} +239 -5
  10. package/dist/decision-object-B5zGSPFp.d.mts +15 -0
  11. package/dist/decision-object-DBcLWVvv.d.cts +15 -0
  12. package/dist/{run-agent-s5D32w99.cjs → effects-B23bFZEs.cjs} +948 -102
  13. package/dist/{run-agent-Ct_GZw_f.mjs → effects-CuOUNYtZ.mjs} +914 -104
  14. package/dist/{event-log-C7jeH0y8.mjs → event-log-DkVlk3Rh.mjs} +30 -15
  15. package/dist/{event-log-BWSSLUff.cjs → event-log-Dkc-yIYu.cjs} +41 -14
  16. package/dist/{event-log-store-BzXehP7R.d.cts → event-log-store-BBS8so8a.d.mts} +2 -2
  17. package/dist/{event-log-store-W49TCJXi.mjs → event-log-store-Brx9tOHt.mjs} +1 -1
  18. package/dist/{event-log-store-CleWpsp5.cjs → event-log-store-Cl-YWDnq.cjs} +1 -1
  19. package/dist/{event-log-store-CWjN6lmM.d.mts → event-log-store-bc4ICGcS.d.cts} +2 -2
  20. package/dist/index.cjs +660 -286
  21. package/dist/index.d.cts +168 -9
  22. package/dist/index.d.mts +168 -9
  23. package/dist/index.mjs +639 -271
  24. package/dist/internal-C3Lqu538.d.cts +43 -0
  25. package/dist/internal-DUcdhk-i.d.mts +43 -0
  26. package/dist/log.cjs +2 -2
  27. package/dist/log.d.cts +1 -1
  28. package/dist/log.d.mts +1 -1
  29. package/dist/log.mjs +2 -2
  30. package/dist/machines.cjs +457 -41
  31. package/dist/machines.d.cts +114 -43
  32. package/dist/machines.d.mts +114 -43
  33. package/dist/machines.mjs +457 -42
  34. package/dist/{model-source-DmhTMK39.cjs → model-source-B4WQ8Idp.cjs} +1 -1
  35. package/dist/{model-source-CK3F4YuU.mjs → model-source-kjGwqAV8.mjs} +1 -1
  36. package/dist/openai.cjs +149 -36
  37. package/dist/openai.d.cts +28 -10
  38. package/dist/openai.d.mts +28 -10
  39. package/dist/openai.mjs +149 -36
  40. package/dist/otel.d.cts +1 -1
  41. package/dist/otel.d.mts +1 -1
  42. package/dist/{run-agent-BGdx5913.d.mts → run-agent-BcQ-9NRT.d.cts} +91 -9
  43. package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-C86drZtN.d.mts} +91 -9
  44. package/dist/{setup-agent-05uw4dPZ.mjs → setup-agent-BDmNr6PC.mjs} +9 -3
  45. package/dist/{setup-agent-BtfeFfF6.d.cts → setup-agent-BIKcbVXV.d.mts} +4 -4
  46. package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
  47. package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-jlo4vtaZ.d.cts} +4 -4
  48. package/dist/tanstack-ai.cjs +62 -4
  49. package/dist/tanstack-ai.d.cts +18 -6
  50. package/dist/tanstack-ai.d.mts +18 -6
  51. package/dist/tanstack-ai.mjs +62 -4
  52. package/dist/testing.cjs +536 -67
  53. package/dist/testing.d.cts +197 -180
  54. package/dist/testing.d.mts +197 -180
  55. package/dist/testing.mjs +532 -67
  56. package/dist/{text-logic-CV_4KGr6.d.cts → text-logic-BqxalgMr.d.mts} +87 -4
  57. package/dist/{text-logic-Ckh-rJFV.d.mts → text-logic-CSf9bqpP.d.cts} +87 -4
  58. package/dist/{types-Dp5_Ru4R.d.cts → types-DQUOOaZO.d.cts} +1 -1
  59. package/dist/{types-Dp5_Ru4R.d.mts → types-DQUOOaZO.d.mts} +1 -1
  60. package/dist/{usage-BDiJKyv9.d.cts → usage-DoP0Oi84.d.mts} +1 -1
  61. package/dist/{usage-DOoVUGVq.d.mts → usage-HtnrUsl9.d.cts} +1 -1
  62. package/dist/utils-7lSa4H-i.d.cts +403 -0
  63. package/dist/utils-CBbKw2fM.d.mts +403 -0
  64. package/dist/validate.cjs +44 -12
  65. package/dist/validate.d.cts +6 -6
  66. package/dist/validate.d.mts +6 -6
  67. package/dist/validate.mjs +44 -12
  68. package/dist/verify-Bink-Drw.cjs +2304 -0
  69. package/dist/{verify-BQpE8hUz.d.cts → verify-Buh8XSUr.d.mts} +208 -14
  70. package/dist/{verify-CqeuEmIk.d.mts → verify-CciG8UP-.d.cts} +208 -14
  71. package/dist/verify-Dpz1u5Pe.mjs +2251 -0
  72. package/dist/with-model-calls-B_WLmOSl.cjs +248 -0
  73. package/dist/with-model-calls-BkOwdroS.mjs +213 -0
  74. package/docs/act.md +102 -0
  75. package/docs/advanced.md +105 -0
  76. package/docs/any-stack.md +62 -0
  77. package/docs/choosing-a-run-mode.md +55 -0
  78. package/docs/debugging.md +29 -0
  79. package/docs/decisions.md +473 -0
  80. package/docs/environment-and-policy.md +188 -0
  81. package/docs/evals.md +509 -0
  82. package/docs/event-log.md +311 -0
  83. package/docs/from-a-loop.md +528 -0
  84. package/docs/generate-machines.md +110 -0
  85. package/docs/hosts.md +414 -0
  86. package/docs/human-in-the-loop.md +177 -0
  87. package/docs/index.md +48 -0
  88. package/docs/judgments.md +281 -0
  89. package/docs/langgraph-comparison.md +198 -0
  90. package/docs/machines-as-data.md +454 -0
  91. package/docs/machines-presets.md +198 -0
  92. package/docs/machines.md +497 -0
  93. package/docs/messages.md +67 -0
  94. package/docs/meta.json +52 -0
  95. package/docs/models-and-providers.md +268 -0
  96. package/docs/multi-agent.md +68 -0
  97. package/docs/observability.md +109 -0
  98. package/docs/patterns.md +31 -0
  99. package/docs/persistence.md +136 -0
  100. package/docs/quickstart.md +121 -0
  101. package/docs/roadmap.md +22 -0
  102. package/docs/scope.md +75 -0
  103. package/docs/statechart-policy-examples.md +69 -0
  104. package/docs/steps.md +54 -0
  105. package/docs/strangler-fig.md +323 -0
  106. package/docs/text-requests.md +250 -0
  107. package/docs/thinking-in-state-machines.md +324 -0
  108. package/docs/tools.md +249 -0
  109. package/docs/upgrading.md +37 -0
  110. package/docs/usage-and-budgets.md +516 -0
  111. package/docs/validate-and-repair.md +253 -0
  112. package/docs/verify.md +487 -0
  113. package/docs/xstate-4-and-5-apps.md +161 -0
  114. package/llms.txt +53 -0
  115. package/package.json +10 -3
  116. package/readme.md +30 -15
  117. package/skills/add-evals/SKILL.md +3 -1
  118. package/skills/add-traces/SKILL.md +6 -1
  119. package/skills/build-machine/SKILL.md +81 -0
  120. package/skills/generate-machine/SKILL.md +1 -1
  121. package/skills/graph-engineering/SKILL.md +13 -3
  122. package/skills/improve-machine/SKILL.md +21 -2
  123. package/skills/loop-to-machine/SKILL.md +147 -190
  124. package/skills/loop-to-machine/reference.md +260 -0
  125. package/dist/utils-BnXdWih3.d.mts +0 -108
  126. package/dist/utils-ebVpCYoF.d.cts +0 -108
  127. package/dist/verify-Bpahmr34.mjs +0 -1241
  128. package/dist/verify-DCLZa9R0.cjs +0 -1288
  129. package/dist/with-model-calls-BXYdBdcu.cjs +0 -45
  130. package/dist/with-model-calls-Bv4V4EHC.mjs +0 -34
package/dist/openai.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_event_log = require("./event-log-BWSSLUff.cjs");
3
- const require_decision = require("./decision-BEsATcr1.cjs");
4
- const require_with_model_calls = require("./with-model-calls-BXYdBdcu.cjs");
2
+ const require_event_log = require("./event-log-Dkc-yIYu.cjs");
3
+ const require_decision = require("./decision-CMeuNZ1g.cjs");
4
+ const require_with_model_calls = require("./with-model-calls-B_WLmOSl.cjs");
5
5
  //#region src/openai/index.ts
6
6
  /** Thrown for a message part Chat Completions cannot carry — dropping it would
7
7
  * silently change what the model sees. */
@@ -177,6 +177,26 @@ function toOpenAiEventTools(events) {
177
177
  strict: false
178
178
  }));
179
179
  }
180
+ /** Responses API function tools as Chat Completions tools, for `api: 'chat'`. */
181
+ function toChatTools(tools) {
182
+ return tools.map(({ name, description, parameters, strict }) => ({
183
+ type: "function",
184
+ function: {
185
+ name,
186
+ ...description != null ? { description } : {},
187
+ parameters: parameters ?? {},
188
+ ...strict != null ? { strict } : {}
189
+ }
190
+ }));
191
+ }
192
+ /** {@link toOpenAiToolChoice} in Chat Completions' shape, for `api: 'chat'`. */
193
+ function toChatToolChoice(toolChoice) {
194
+ if (toolChoice === void 0) return;
195
+ return typeof toolChoice === "object" ? {
196
+ type: "function",
197
+ function: { name: toolChoice.name }
198
+ } : toolChoice;
199
+ }
180
200
  /** A Chat Completions content part as a Responses input part. `toOpenAiMessages`
181
201
  * only emits text and image parts. */
182
202
  function toResponsesContentPart(part) {
@@ -444,10 +464,12 @@ function toToolContent(output) {
444
464
  * `openai` package. Compare `createAiSdkExecutors` — same shape, different SDK
445
465
  * underneath.
446
466
  *
447
- * Calls with function tools use the Responses API, which reasoning models
448
- * require for tools: decisions force a call with `tool_choice: 'required'`, one
449
- * function tool per candidate event, and `generateText` runs its tool loop
450
- * there. Tool-free calls use Chat Completions. Structured output wraps the
467
+ * By default, calls with function tools use the Responses API, which reasoning
468
+ * models require for tools: a tool-mode decision forces a call with
469
+ * `tool_choice: 'required'`, one function tool per candidate event, and
470
+ * `generateText` runs its tool loop there. Tool-free calls, an object-mode
471
+ * decision among them, use Chat Completions. `api` pins every call to one API
472
+ * (see {@link CreateOpenAiExecutorsOptions.api}). Structured output wraps the
451
473
  * `{ result, reasoning? }` provider output schema in a `json_schema` format on
452
474
  * either API.
453
475
  *
@@ -461,7 +483,7 @@ function toToolContent(output) {
461
483
  * ```
462
484
  */
463
485
  function createOpenAiExecutors(options) {
464
- const { client, api = "chat", resolveModel = (modelRef) => modelRef } = options;
486
+ const { client, api, resolveModel = (modelRef) => modelRef } = options;
465
487
  const warnedSettings = /* @__PURE__ */ new Set();
466
488
  const rejectedSettings = /* @__PURE__ */ new Map();
467
489
  const createResponse = async (params, signal) => {
@@ -498,27 +520,75 @@ function createOpenAiExecutors(options) {
498
520
  if (require_event_log.getAgentOutputMode(request.outputSchema) !== "structured") return;
499
521
  return require_event_log.getJsonSchema(require_event_log.providerOutputSchema(request.outputSchema, { reasoning: request.includeReasoning }));
500
522
  };
501
- const chatCompletion = async (request, jsonSchema, info) => {
502
- const response = await client.chat.completions.create({
503
- model: resolveModel(request.model),
504
- messages: toOpenAiMessages(request),
505
- ...callSettings(options, request),
506
- ...toOpenAiCallSettings(request),
507
- ...jsonSchema ? { response_format: {
508
- type: "json_schema",
509
- json_schema: {
510
- name: "output",
511
- schema: jsonSchema,
512
- strict: false
523
+ const chatResponseFormat = (name, schema) => ({ response_format: {
524
+ type: "json_schema",
525
+ json_schema: {
526
+ name,
527
+ schema,
528
+ strict: false
529
+ }
530
+ } });
531
+ const chatParams = (request, messages, extra) => ({
532
+ model: resolveModel(request.model),
533
+ messages,
534
+ ...callSettings(options, request),
535
+ ...toOpenAiCallSettings(request),
536
+ ...extra
537
+ });
538
+ const chatToolLoop = async (request, tools, jsonSchema, info) => {
539
+ const maxSteps = typeof request.maxSteps === "number" && Number.isFinite(request.maxSteps) ? Math.max(1, Math.floor(request.maxSteps)) : 1;
540
+ const messages = toOpenAiMessages(request);
541
+ const toolChoice = tools.length > 0 ? toChatToolChoice(request.toolChoice) : void 0;
542
+ let response;
543
+ let usage;
544
+ let step = 0;
545
+ try {
546
+ for (;;) {
547
+ step++;
548
+ response = await client.chat.completions.create(chatParams(request, [...messages], {
549
+ ...tools.length > 0 ? { tools: toChatTools(tools) } : {},
550
+ ...jsonSchema ? chatResponseFormat("output", jsonSchema) : {},
551
+ ...step === 1 && toolChoice !== void 0 ? { tool_choice: toolChoice } : {}
552
+ }), { signal: info?.signal });
553
+ usage = addAgentCallUsage(usage, toAgentCallUsage(response.usage));
554
+ const message = response.choices[0]?.message;
555
+ const toolCalls = message?.tool_calls ?? [];
556
+ if (toolCalls.length === 0 || step >= maxSteps || response.choices[0]?.finish_reason === "length") break;
557
+ const offered = (name) => Object.hasOwn(request.tools, name) && request.tools[name] !== void 0;
558
+ if (toolCalls.some((call) => call.type !== "function" || offered(call.function.name) && !toolExecutor(request.tools, call.function.name))) break;
559
+ messages.push(message);
560
+ for (const call of toolCalls) {
561
+ if (call.type !== "function") continue;
562
+ const { name, arguments: args } = call.function;
563
+ let content;
564
+ try {
565
+ if (!offered(name)) throw new Error(`tool '${name}' was not offered; valid tools: ${Object.keys(request.tools).filter(offered).join(", ")}`);
566
+ let toolInput = {};
567
+ if (args) try {
568
+ toolInput = JSON.parse(args);
569
+ } catch {
570
+ throw new Error(`the arguments for tool '${name}' were not valid JSON`);
571
+ }
572
+ content = toToolContent(await toolExecutor(request.tools, name)(toolInput));
573
+ } catch (error) {
574
+ content = `Error: ${error instanceof Error ? error.message : String(error)}`;
575
+ }
576
+ messages.push({
577
+ role: "tool",
578
+ tool_call_id: call.id,
579
+ content
580
+ });
513
581
  }
514
- } } : {}
515
- }, { signal: info?.signal });
582
+ }
583
+ } catch (error) {
584
+ throw require_with_model_calls.withModelCalls(error, step);
585
+ }
516
586
  const choice = response.choices[0];
517
587
  return {
518
588
  content: choice?.message.content,
519
589
  finishReason: toAgentFinishReason(choice?.finish_reason),
520
- usage: toAgentCallUsage(response.usage),
521
- modelCalls: 1,
590
+ usage,
591
+ modelCalls: step,
522
592
  raw: response
523
593
  };
524
594
  };
@@ -594,7 +664,7 @@ function createOpenAiExecutors(options) {
594
664
  const generateText = async (request, info) => {
595
665
  const jsonSchema = await structuredSchema(request);
596
666
  const tools = toOpenAiTools(request.tools);
597
- const { content, finishReason, usage, modelCalls, raw } = tools.length > 0 || api === "responses" ? await responsesToolLoop(request, tools, jsonSchema, info) : await chatCompletion(request, jsonSchema, info);
667
+ const { content, finishReason, usage, modelCalls, raw } = api === "responses" || api === void 0 && tools.length > 0 ? await responsesToolLoop(request, tools, jsonSchema, info) : await chatToolLoop(request, tools, jsonSchema, info);
598
668
  try {
599
669
  if (jsonSchema) {
600
670
  if (finishReason === "length") throw truncated(request, info, content || void 0);
@@ -671,21 +741,17 @@ function createOpenAiExecutors(options) {
671
741
  raw: last
672
742
  };
673
743
  };
674
- const decide = async (request, info) => {
675
- const response = await createResponse(responsesParams(request, toResponsesInput(toDecisionMessages(request)), {
676
- tools: toOpenAiEventTools(request.events),
677
- tool_choice: "required"
678
- }), info?.signal);
679
- assertNotFailed(response, "decide");
680
- if (response.status === "incomplete") throw new Error(`createOpenAiExecutors: decide — the response was incomplete (${response.incomplete_details?.reason ?? "unknown reason"}), so no event was chosen.`);
681
- const toolCall = functionCalls(response)[0];
744
+ const fromToolCalls = (request, calls, meta) => {
682
745
  const unnamed = (call) => ({
683
746
  rejected: require_with_model_calls.rejectedAnswer(call, request.events.map((event) => event.toolName)),
684
- ...usageField(toAgentResponseUsage(response.usage)),
685
- finishReason: toAgentResponseFinishReason(response),
686
- raw: response
747
+ ...meta
687
748
  });
749
+ const toolCall = calls[0];
688
750
  if (!toolCall) return unnamed();
751
+ if (calls.length > 1) return {
752
+ rejected: require_with_model_calls.multipleCallsRejection(calls.map((call) => call.name)),
753
+ ...meta
754
+ };
689
755
  const toolName = toolCall.name;
690
756
  const chosenEvent = request.events.find((event) => event.toolName === toolName);
691
757
  if (!chosenEvent) return unnamed({ toolName });
@@ -703,10 +769,57 @@ function createOpenAiExecutors(options) {
703
769
  ...args && typeof args === "object" ? args : {},
704
770
  type: chosenEvent.type
705
771
  },
772
+ ...meta
773
+ };
774
+ };
775
+ const incomplete = (reason) => /* @__PURE__ */ new Error(`createOpenAiExecutors: decide — the response was incomplete (${reason ?? "unknown reason"}), so no event was chosen.`);
776
+ const decideWithChat = async (request, mode, info) => {
777
+ const response = await client.chat.completions.create(chatParams(request, toDecisionMessages(request), mode === "object" ? chatResponseFormat("decision", require_with_model_calls.decisionObjectSchema(request)) : {
778
+ tools: toChatTools(toOpenAiEventTools(request.events)),
779
+ tool_choice: "required",
780
+ parallel_tool_calls: false
781
+ }), { signal: info?.signal });
782
+ const choice = response.choices[0];
783
+ if (choice?.finish_reason === "length") throw incomplete("max_output_tokens");
784
+ const meta = {
785
+ ...usageField(toAgentCallUsage(response.usage)),
786
+ finishReason: toAgentFinishReason(choice?.finish_reason),
787
+ raw: response
788
+ };
789
+ if (mode === "object") return {
790
+ ...require_with_model_calls.fromDecisionObject(request, choice?.message.content ?? ""),
791
+ ...meta
792
+ };
793
+ const calls = (choice?.message.tool_calls ?? []).flatMap((call) => call.type === "function" ? [call.function] : []);
794
+ return fromToolCalls(request, calls, meta);
795
+ };
796
+ const decideWithResponses = async (request, mode, info) => {
797
+ const response = await createResponse(responsesParams(request, toResponsesInput(toDecisionMessages(request)), mode === "object" ? { text: { format: {
798
+ type: "json_schema",
799
+ name: "decision",
800
+ schema: require_with_model_calls.decisionObjectSchema(request),
801
+ strict: false
802
+ } } } : {
803
+ tools: toOpenAiEventTools(request.events),
804
+ tool_choice: "required",
805
+ parallel_tool_calls: false
806
+ }), info?.signal);
807
+ assertNotFailed(response, "decide");
808
+ if (response.status === "incomplete") throw incomplete(response.incomplete_details?.reason);
809
+ const meta = {
706
810
  ...usageField(toAgentResponseUsage(response.usage)),
707
811
  finishReason: toAgentResponseFinishReason(response),
708
812
  raw: response
709
813
  };
814
+ if (mode === "object") return {
815
+ ...require_with_model_calls.fromDecisionObject(request, outputText(response)),
816
+ ...meta
817
+ };
818
+ return fromToolCalls(request, functionCalls(response), meta);
819
+ };
820
+ const decide = async (request, info) => {
821
+ const mode = require_with_model_calls.resolveDecisionMode(options.decideMode, request);
822
+ return api === "chat" || api === void 0 && mode === "object" ? decideWithChat(request, mode, info) : decideWithResponses(request, mode, info);
710
823
  };
711
824
  return {
712
825
  generateText,
package/dist/openai.d.cts CHANGED
@@ -1,5 +1,6 @@
1
- import { i as AgentToolChoice, n as AgentMessage, s as AgentTools, u as ChosenEvent } from "./types-Dp5_Ru4R.cjs";
2
- import { G as AgentEventDescriptor, N as AgentDecisionRejection, P as AgentDecisionRequest, c as AgentRequestExecutorInfo, f as AgentTextRequest, r as AgentFinishReason, t as AgentCallUsage } from "./text-logic-CV_4KGr6.cjs";
1
+ import { a as AgentToolChoice, l as AgentTools, p as ChosenEvent, r as AgentMessage } from "./types-DQUOOaZO.cjs";
2
+ import { I as AgentDecisionRejection, L as AgentDecisionRequest, Z as AgentEventDescriptor, c as AgentRequestExecutorInfo, f as AgentTextRequest, r as AgentFinishReason, t as AgentCallUsage } from "./text-logic-CSf9bqpP.cjs";
3
+ import { n as DecisionModeOption, t as DecisionMode } from "./decision-object-DBcLWVvv.cjs";
3
4
  import OpenAI from "openai";
4
5
  import { ChatCompletion, ChatCompletionCreateParamsNonStreaming, ChatCompletionMessageParam } from "openai/resources/chat/completions/completions.js";
5
6
  import { FunctionTool, Response, ResponseInputItem, ResponseUsage } from "openai/resources/responses/responses.js";
@@ -120,10 +121,24 @@ export type OpenAiCallSettings = Omit<Partial<ChatCompletionCreateParamsNonStrea
120
121
  */
121
122
  export type CreateOpenAiExecutorsOptions = {
122
123
  client: OpenAI;
123
- /** Where tool-free text calls go: `'chat'` (default, `chat.completions.create`)
124
- * or `'responses'` (`responses.create`), for a host whose recorded traffic uses
125
- * it. Decisions and tool calls always use the Responses API. */
124
+ /**
125
+ * Which OpenAI API the calls use. Unset (the default): calls with function
126
+ * tools — a `generateText` with tools, a tool-mode `decide` — use the
127
+ * Responses API, which reasoning models require for tools, and every other
128
+ * call uses Chat Completions. `'chat'`: every call uses
129
+ * `chat.completions.create`, tools included, for a model or gateway without
130
+ * the Responses API. `'responses'`: every call uses `responses.create`, for a
131
+ * host whose recorded traffic uses it.
132
+ */
126
133
  api?: "chat" | "responses";
134
+ /**
135
+ * How a `decide` request is answered: `'object'` (default), one
136
+ * structured-output object naming the event; or `'tool'`, one function tool
137
+ * per candidate event under `tool_choice: 'required'`, with
138
+ * `parallel_tool_calls: false` and a multi-call answer rejected. A function
139
+ * picks per request.
140
+ */
141
+ decideMode?: DecisionModeOption;
127
142
  resolveModel?: (modelRef: string) => string;
128
143
  settings?: Record<string, OpenAiCallSettings> | ((request: AgentTextRequest | AgentDecisionRequest) => OpenAiCallSettings | undefined);
129
144
  };
@@ -194,10 +209,12 @@ export declare function addAgentCallUsage(total: AgentCallUsage | undefined, nex
194
209
  * `openai` package. Compare `createAiSdkExecutors` — same shape, different SDK
195
210
  * underneath.
196
211
  *
197
- * Calls with function tools use the Responses API, which reasoning models
198
- * require for tools: decisions force a call with `tool_choice: 'required'`, one
199
- * function tool per candidate event, and `generateText` runs its tool loop
200
- * there. Tool-free calls use Chat Completions. Structured output wraps the
212
+ * By default, calls with function tools use the Responses API, which reasoning
213
+ * models require for tools: a tool-mode decision forces a call with
214
+ * `tool_choice: 'required'`, one function tool per candidate event, and
215
+ * `generateText` runs its tool loop there. Tool-free calls, an object-mode
216
+ * decision among them, use Chat Completions. `api` pins every call to one API
217
+ * (see {@link CreateOpenAiExecutorsOptions.api}). Structured output wraps the
201
218
  * `{ result, reasoning? }` provider output schema in a `json_schema` format on
202
219
  * either API.
203
220
  *
@@ -211,4 +228,5 @@ export declare function addAgentCallUsage(total: AgentCallUsage | undefined, nex
211
228
  * ```
212
229
  */
213
230
  export declare function createOpenAiExecutors(options: CreateOpenAiExecutorsOptions): OpenAiExecutors;
214
- //#endregion
231
+ //#endregion
232
+ export type { DecisionMode, DecisionModeOption };
package/dist/openai.d.mts CHANGED
@@ -1,5 +1,6 @@
1
- import { i as AgentToolChoice, n as AgentMessage, s as AgentTools, u as ChosenEvent } from "./types-Dp5_Ru4R.mjs";
2
- import { G as AgentEventDescriptor, N as AgentDecisionRejection, P as AgentDecisionRequest, c as AgentRequestExecutorInfo, f as AgentTextRequest, r as AgentFinishReason, t as AgentCallUsage } from "./text-logic-Ckh-rJFV.mjs";
1
+ import { a as AgentToolChoice, l as AgentTools, p as ChosenEvent, r as AgentMessage } from "./types-DQUOOaZO.mjs";
2
+ import { I as AgentDecisionRejection, L as AgentDecisionRequest, Z as AgentEventDescriptor, c as AgentRequestExecutorInfo, f as AgentTextRequest, r as AgentFinishReason, t as AgentCallUsage } from "./text-logic-BqxalgMr.mjs";
3
+ import { n as DecisionModeOption, t as DecisionMode } from "./decision-object-B5zGSPFp.mjs";
3
4
  import OpenAI from "openai";
4
5
  import { ChatCompletion, ChatCompletionCreateParamsNonStreaming, ChatCompletionMessageParam } from "openai/resources/chat/completions/completions.js";
5
6
  import { FunctionTool, Response, ResponseInputItem, ResponseUsage } from "openai/resources/responses/responses.js";
@@ -120,10 +121,24 @@ export type OpenAiCallSettings = Omit<Partial<ChatCompletionCreateParamsNonStrea
120
121
  */
121
122
  export type CreateOpenAiExecutorsOptions = {
122
123
  client: OpenAI;
123
- /** Where tool-free text calls go: `'chat'` (default, `chat.completions.create`)
124
- * or `'responses'` (`responses.create`), for a host whose recorded traffic uses
125
- * it. Decisions and tool calls always use the Responses API. */
124
+ /**
125
+ * Which OpenAI API the calls use. Unset (the default): calls with function
126
+ * tools — a `generateText` with tools, a tool-mode `decide` — use the
127
+ * Responses API, which reasoning models require for tools, and every other
128
+ * call uses Chat Completions. `'chat'`: every call uses
129
+ * `chat.completions.create`, tools included, for a model or gateway without
130
+ * the Responses API. `'responses'`: every call uses `responses.create`, for a
131
+ * host whose recorded traffic uses it.
132
+ */
126
133
  api?: "chat" | "responses";
134
+ /**
135
+ * How a `decide` request is answered: `'object'` (default), one
136
+ * structured-output object naming the event; or `'tool'`, one function tool
137
+ * per candidate event under `tool_choice: 'required'`, with
138
+ * `parallel_tool_calls: false` and a multi-call answer rejected. A function
139
+ * picks per request.
140
+ */
141
+ decideMode?: DecisionModeOption;
127
142
  resolveModel?: (modelRef: string) => string;
128
143
  settings?: Record<string, OpenAiCallSettings> | ((request: AgentTextRequest | AgentDecisionRequest) => OpenAiCallSettings | undefined);
129
144
  };
@@ -194,10 +209,12 @@ export declare function addAgentCallUsage(total: AgentCallUsage | undefined, nex
194
209
  * `openai` package. Compare `createAiSdkExecutors` — same shape, different SDK
195
210
  * underneath.
196
211
  *
197
- * Calls with function tools use the Responses API, which reasoning models
198
- * require for tools: decisions force a call with `tool_choice: 'required'`, one
199
- * function tool per candidate event, and `generateText` runs its tool loop
200
- * there. Tool-free calls use Chat Completions. Structured output wraps the
212
+ * By default, calls with function tools use the Responses API, which reasoning
213
+ * models require for tools: a tool-mode decision forces a call with
214
+ * `tool_choice: 'required'`, one function tool per candidate event, and
215
+ * `generateText` runs its tool loop there. Tool-free calls, an object-mode
216
+ * decision among them, use Chat Completions. `api` pins every call to one API
217
+ * (see {@link CreateOpenAiExecutorsOptions.api}). Structured output wraps the
201
218
  * `{ result, reasoning? }` provider output schema in a `json_schema` format on
202
219
  * either API.
203
220
  *
@@ -211,4 +228,5 @@ export declare function addAgentCallUsage(total: AgentCallUsage | undefined, nex
211
228
  * ```
212
229
  */
213
230
  export declare function createOpenAiExecutors(options: CreateOpenAiExecutorsOptions): OpenAiExecutors;
214
- //#endregion
231
+ //#endregion
232
+ export type { DecisionMode, DecisionModeOption };
package/dist/openai.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { B as providerOutputSchema, M as getAgentOutputMode, Q as getJsonSchemaSync, T as AGENT_USAGE_TOKEN_FIELDS, Z as getJsonSchema, mt as AgentTruncatedError, rt as isStandardSchema, z as parseProviderOutput } from "./event-log-C7jeH0y8.mjs";
2
- import { c as renderDecisionAttempts } from "./decision-COkJNjOW.mjs";
3
- import { n as rejectedAnswer, t as withModelCalls } from "./with-model-calls-Bv4V4EHC.mjs";
1
+ import { $ as getJsonSchema, D as AGENT_USAGE_TOKEN_FIELDS, H as providerOutputSchema, P as getAgentOutputMode, V as parseProviderOutput, at as isStandardSchema, et as getJsonSchemaSync, gt as AgentTruncatedError } from "./event-log-DkVlk3Rh.mjs";
2
+ import { c as renderDecisionAttempts } from "./decision-m5hGmHpF.mjs";
3
+ import { a as multipleCallsRejection, i as fromDecisionObject, n as rejectedAnswer, o as resolveDecisionMode, r as decisionObjectSchema, t as withModelCalls } from "./with-model-calls-BkOwdroS.mjs";
4
4
  //#region src/openai/index.ts
5
5
  /** Thrown for a message part Chat Completions cannot carry — dropping it would
6
6
  * silently change what the model sees. */
@@ -176,6 +176,26 @@ function toOpenAiEventTools(events) {
176
176
  strict: false
177
177
  }));
178
178
  }
179
+ /** Responses API function tools as Chat Completions tools, for `api: 'chat'`. */
180
+ function toChatTools(tools) {
181
+ return tools.map(({ name, description, parameters, strict }) => ({
182
+ type: "function",
183
+ function: {
184
+ name,
185
+ ...description != null ? { description } : {},
186
+ parameters: parameters ?? {},
187
+ ...strict != null ? { strict } : {}
188
+ }
189
+ }));
190
+ }
191
+ /** {@link toOpenAiToolChoice} in Chat Completions' shape, for `api: 'chat'`. */
192
+ function toChatToolChoice(toolChoice) {
193
+ if (toolChoice === void 0) return;
194
+ return typeof toolChoice === "object" ? {
195
+ type: "function",
196
+ function: { name: toolChoice.name }
197
+ } : toolChoice;
198
+ }
179
199
  /** A Chat Completions content part as a Responses input part. `toOpenAiMessages`
180
200
  * only emits text and image parts. */
181
201
  function toResponsesContentPart(part) {
@@ -443,10 +463,12 @@ function toToolContent(output) {
443
463
  * `openai` package. Compare `createAiSdkExecutors` — same shape, different SDK
444
464
  * underneath.
445
465
  *
446
- * Calls with function tools use the Responses API, which reasoning models
447
- * require for tools: decisions force a call with `tool_choice: 'required'`, one
448
- * function tool per candidate event, and `generateText` runs its tool loop
449
- * there. Tool-free calls use Chat Completions. Structured output wraps the
466
+ * By default, calls with function tools use the Responses API, which reasoning
467
+ * models require for tools: a tool-mode decision forces a call with
468
+ * `tool_choice: 'required'`, one function tool per candidate event, and
469
+ * `generateText` runs its tool loop there. Tool-free calls, an object-mode
470
+ * decision among them, use Chat Completions. `api` pins every call to one API
471
+ * (see {@link CreateOpenAiExecutorsOptions.api}). Structured output wraps the
450
472
  * `{ result, reasoning? }` provider output schema in a `json_schema` format on
451
473
  * either API.
452
474
  *
@@ -460,7 +482,7 @@ function toToolContent(output) {
460
482
  * ```
461
483
  */
462
484
  function createOpenAiExecutors(options) {
463
- const { client, api = "chat", resolveModel = (modelRef) => modelRef } = options;
485
+ const { client, api, resolveModel = (modelRef) => modelRef } = options;
464
486
  const warnedSettings = /* @__PURE__ */ new Set();
465
487
  const rejectedSettings = /* @__PURE__ */ new Map();
466
488
  const createResponse = async (params, signal) => {
@@ -497,27 +519,75 @@ function createOpenAiExecutors(options) {
497
519
  if (getAgentOutputMode(request.outputSchema) !== "structured") return;
498
520
  return getJsonSchema(providerOutputSchema(request.outputSchema, { reasoning: request.includeReasoning }));
499
521
  };
500
- const chatCompletion = async (request, jsonSchema, info) => {
501
- const response = await client.chat.completions.create({
502
- model: resolveModel(request.model),
503
- messages: toOpenAiMessages(request),
504
- ...callSettings(options, request),
505
- ...toOpenAiCallSettings(request),
506
- ...jsonSchema ? { response_format: {
507
- type: "json_schema",
508
- json_schema: {
509
- name: "output",
510
- schema: jsonSchema,
511
- strict: false
522
+ const chatResponseFormat = (name, schema) => ({ response_format: {
523
+ type: "json_schema",
524
+ json_schema: {
525
+ name,
526
+ schema,
527
+ strict: false
528
+ }
529
+ } });
530
+ const chatParams = (request, messages, extra) => ({
531
+ model: resolveModel(request.model),
532
+ messages,
533
+ ...callSettings(options, request),
534
+ ...toOpenAiCallSettings(request),
535
+ ...extra
536
+ });
537
+ const chatToolLoop = async (request, tools, jsonSchema, info) => {
538
+ const maxSteps = typeof request.maxSteps === "number" && Number.isFinite(request.maxSteps) ? Math.max(1, Math.floor(request.maxSteps)) : 1;
539
+ const messages = toOpenAiMessages(request);
540
+ const toolChoice = tools.length > 0 ? toChatToolChoice(request.toolChoice) : void 0;
541
+ let response;
542
+ let usage;
543
+ let step = 0;
544
+ try {
545
+ for (;;) {
546
+ step++;
547
+ response = await client.chat.completions.create(chatParams(request, [...messages], {
548
+ ...tools.length > 0 ? { tools: toChatTools(tools) } : {},
549
+ ...jsonSchema ? chatResponseFormat("output", jsonSchema) : {},
550
+ ...step === 1 && toolChoice !== void 0 ? { tool_choice: toolChoice } : {}
551
+ }), { signal: info?.signal });
552
+ usage = addAgentCallUsage(usage, toAgentCallUsage(response.usage));
553
+ const message = response.choices[0]?.message;
554
+ const toolCalls = message?.tool_calls ?? [];
555
+ if (toolCalls.length === 0 || step >= maxSteps || response.choices[0]?.finish_reason === "length") break;
556
+ const offered = (name) => Object.hasOwn(request.tools, name) && request.tools[name] !== void 0;
557
+ if (toolCalls.some((call) => call.type !== "function" || offered(call.function.name) && !toolExecutor(request.tools, call.function.name))) break;
558
+ messages.push(message);
559
+ for (const call of toolCalls) {
560
+ if (call.type !== "function") continue;
561
+ const { name, arguments: args } = call.function;
562
+ let content;
563
+ try {
564
+ if (!offered(name)) throw new Error(`tool '${name}' was not offered; valid tools: ${Object.keys(request.tools).filter(offered).join(", ")}`);
565
+ let toolInput = {};
566
+ if (args) try {
567
+ toolInput = JSON.parse(args);
568
+ } catch {
569
+ throw new Error(`the arguments for tool '${name}' were not valid JSON`);
570
+ }
571
+ content = toToolContent(await toolExecutor(request.tools, name)(toolInput));
572
+ } catch (error) {
573
+ content = `Error: ${error instanceof Error ? error.message : String(error)}`;
574
+ }
575
+ messages.push({
576
+ role: "tool",
577
+ tool_call_id: call.id,
578
+ content
579
+ });
512
580
  }
513
- } } : {}
514
- }, { signal: info?.signal });
581
+ }
582
+ } catch (error) {
583
+ throw withModelCalls(error, step);
584
+ }
515
585
  const choice = response.choices[0];
516
586
  return {
517
587
  content: choice?.message.content,
518
588
  finishReason: toAgentFinishReason(choice?.finish_reason),
519
- usage: toAgentCallUsage(response.usage),
520
- modelCalls: 1,
589
+ usage,
590
+ modelCalls: step,
521
591
  raw: response
522
592
  };
523
593
  };
@@ -593,7 +663,7 @@ function createOpenAiExecutors(options) {
593
663
  const generateText = async (request, info) => {
594
664
  const jsonSchema = await structuredSchema(request);
595
665
  const tools = toOpenAiTools(request.tools);
596
- const { content, finishReason, usage, modelCalls, raw } = tools.length > 0 || api === "responses" ? await responsesToolLoop(request, tools, jsonSchema, info) : await chatCompletion(request, jsonSchema, info);
666
+ const { content, finishReason, usage, modelCalls, raw } = api === "responses" || api === void 0 && tools.length > 0 ? await responsesToolLoop(request, tools, jsonSchema, info) : await chatToolLoop(request, tools, jsonSchema, info);
597
667
  try {
598
668
  if (jsonSchema) {
599
669
  if (finishReason === "length") throw truncated(request, info, content || void 0);
@@ -670,21 +740,17 @@ function createOpenAiExecutors(options) {
670
740
  raw: last
671
741
  };
672
742
  };
673
- const decide = async (request, info) => {
674
- const response = await createResponse(responsesParams(request, toResponsesInput(toDecisionMessages(request)), {
675
- tools: toOpenAiEventTools(request.events),
676
- tool_choice: "required"
677
- }), info?.signal);
678
- assertNotFailed(response, "decide");
679
- if (response.status === "incomplete") throw new Error(`createOpenAiExecutors: decide — the response was incomplete (${response.incomplete_details?.reason ?? "unknown reason"}), so no event was chosen.`);
680
- const toolCall = functionCalls(response)[0];
743
+ const fromToolCalls = (request, calls, meta) => {
681
744
  const unnamed = (call) => ({
682
745
  rejected: rejectedAnswer(call, request.events.map((event) => event.toolName)),
683
- ...usageField(toAgentResponseUsage(response.usage)),
684
- finishReason: toAgentResponseFinishReason(response),
685
- raw: response
746
+ ...meta
686
747
  });
748
+ const toolCall = calls[0];
687
749
  if (!toolCall) return unnamed();
750
+ if (calls.length > 1) return {
751
+ rejected: multipleCallsRejection(calls.map((call) => call.name)),
752
+ ...meta
753
+ };
688
754
  const toolName = toolCall.name;
689
755
  const chosenEvent = request.events.find((event) => event.toolName === toolName);
690
756
  if (!chosenEvent) return unnamed({ toolName });
@@ -702,10 +768,57 @@ function createOpenAiExecutors(options) {
702
768
  ...args && typeof args === "object" ? args : {},
703
769
  type: chosenEvent.type
704
770
  },
771
+ ...meta
772
+ };
773
+ };
774
+ const incomplete = (reason) => /* @__PURE__ */ new Error(`createOpenAiExecutors: decide — the response was incomplete (${reason ?? "unknown reason"}), so no event was chosen.`);
775
+ const decideWithChat = async (request, mode, info) => {
776
+ const response = await client.chat.completions.create(chatParams(request, toDecisionMessages(request), mode === "object" ? chatResponseFormat("decision", decisionObjectSchema(request)) : {
777
+ tools: toChatTools(toOpenAiEventTools(request.events)),
778
+ tool_choice: "required",
779
+ parallel_tool_calls: false
780
+ }), { signal: info?.signal });
781
+ const choice = response.choices[0];
782
+ if (choice?.finish_reason === "length") throw incomplete("max_output_tokens");
783
+ const meta = {
784
+ ...usageField(toAgentCallUsage(response.usage)),
785
+ finishReason: toAgentFinishReason(choice?.finish_reason),
786
+ raw: response
787
+ };
788
+ if (mode === "object") return {
789
+ ...fromDecisionObject(request, choice?.message.content ?? ""),
790
+ ...meta
791
+ };
792
+ const calls = (choice?.message.tool_calls ?? []).flatMap((call) => call.type === "function" ? [call.function] : []);
793
+ return fromToolCalls(request, calls, meta);
794
+ };
795
+ const decideWithResponses = async (request, mode, info) => {
796
+ const response = await createResponse(responsesParams(request, toResponsesInput(toDecisionMessages(request)), mode === "object" ? { text: { format: {
797
+ type: "json_schema",
798
+ name: "decision",
799
+ schema: decisionObjectSchema(request),
800
+ strict: false
801
+ } } } : {
802
+ tools: toOpenAiEventTools(request.events),
803
+ tool_choice: "required",
804
+ parallel_tool_calls: false
805
+ }), info?.signal);
806
+ assertNotFailed(response, "decide");
807
+ if (response.status === "incomplete") throw incomplete(response.incomplete_details?.reason);
808
+ const meta = {
705
809
  ...usageField(toAgentResponseUsage(response.usage)),
706
810
  finishReason: toAgentResponseFinishReason(response),
707
811
  raw: response
708
812
  };
813
+ if (mode === "object") return {
814
+ ...fromDecisionObject(request, outputText(response)),
815
+ ...meta
816
+ };
817
+ return fromToolCalls(request, functionCalls(response), meta);
818
+ };
819
+ const decide = async (request, info) => {
820
+ const mode = resolveDecisionMode(options.decideMode, request);
821
+ return api === "chat" || api === void 0 && mode === "object" ? decideWithChat(request, mode, info) : decideWithResponses(request, mode, info);
709
822
  };
710
823
  return {
711
824
  generateText,
package/dist/otel.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { g as AgentTraceEvent } from "./run-agent-B1-Eqviq.cjs";
1
+ import { _ as AgentTraceEvent } from "./run-agent-BcQ-9NRT.cjs";
2
2
  import { Attributes, Tracer, TracerProvider } from "@opentelemetry/api";
3
3
  //#region src/otel/index.d.ts
4
4
  /** Options for {@link createOtelTraceHandler}. */
package/dist/otel.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { g as AgentTraceEvent } from "./run-agent-BGdx5913.mjs";
1
+ import { _ as AgentTraceEvent } from "./run-agent-C86drZtN.mjs";
2
2
  import { Attributes, Tracer, TracerProvider } from "@opentelemetry/api";
3
3
  //#region src/otel/index.d.ts
4
4
  /** Options for {@link createOtelTraceHandler}. */