@valerypopoff/rivet2-core 2.1.8 → 2.1.9

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 (55) hide show
  1. package/dist/cjs/bundle.cjs +1922 -1125
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/model/GraphProcessor.js +1 -0
  4. package/dist/esm/model/SplitRunProcessor.js +19 -10
  5. package/dist/esm/model/ToolCallContinuationCoordinator.js +6 -1
  6. package/dist/esm/model/chat/aiSdkMessages.js +8 -0
  7. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -0
  8. package/dist/esm/model/chat-v2/chatV2EditorCache.js +22 -0
  9. package/dist/esm/model/chat-v2/chatV2Outputs.js +41 -31
  10. package/dist/esm/model/chat-v2/chatV2Pipeline.js +122 -44
  11. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +1 -0
  12. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +6 -5
  13. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  14. package/dist/esm/model/chat-v2/chatV2Types.js +11 -1
  15. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  16. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +3 -5
  17. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +22 -13
  18. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +224 -68
  19. package/dist/esm/model/chat-v2/llmProfile.js +21 -0
  20. package/dist/esm/model/chat-v2/llmProfileFallback.js +288 -0
  21. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  22. package/dist/esm/model/chat-v2/providerOptions.js +44 -11
  23. package/dist/esm/model/chat-v2/toolContinuation.js +0 -4
  24. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  25. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -0
  26. package/dist/esm/model/nodes/LLMChatV2Node.js +115 -11
  27. package/dist/esm/model/nodes/PromptNode.js +9 -2
  28. package/dist/esm/model/nodes/toolCallDelegation.js +18 -2
  29. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +22 -28
  30. package/dist/esm/plugins/google/google.js +20 -9
  31. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +17 -6
  32. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  33. package/dist/esm/utils/serialization/serialization.js +19 -0
  34. package/dist/types/model/DataValue.d.ts +7 -1
  35. package/dist/types/model/NodeBase.d.ts +6 -0
  36. package/dist/types/model/ProcessContext.d.ts +4 -0
  37. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  38. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +4 -0
  39. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +5 -5
  40. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +33 -0
  41. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +1 -0
  42. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  43. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  44. package/dist/types/model/chat-v2/chatV2Types.d.ts +24 -0
  45. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  46. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +4 -1
  47. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -2
  48. package/dist/types/model/chat-v2/llmProfile.d.ts +7 -0
  49. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +79 -0
  50. package/dist/types/model/chat-v2/providerOptions.d.ts +1 -0
  51. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  52. package/dist/types/model/nodes/PromptNode.d.ts +2 -2
  53. package/dist/types/plugins/google/google.d.ts +12 -1
  54. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  55. package/package.json +1 -1
@@ -433,6 +433,7 @@ __export(src_exports, {
433
433
  looseDataValueToDataValue: () => looseDataValueToDataValue,
434
434
  looseDataValuesToDataValues: () => looseDataValuesToDataValues,
435
435
  matchNode: () => matchNode,
436
+ materializeChatV2PipelineFailure: () => materializeChatV2PipelineFailure,
436
437
  mcpDiscoveryNode: () => mcpDiscoveryNode,
437
438
  mcpGetPromptNode: () => mcpGetPromptNode,
438
439
  mcpToolCallNode: () => mcpToolCallNode,
@@ -525,6 +526,7 @@ __export(src_exports, {
525
526
  restoreEscapedInterpolationTokens: () => restoreEscapedInterpolationTokens,
526
527
  rivetWebAppStatusExternalFunction: () => rivetWebAppStatusExternalFunction,
527
528
  runChatV2Pipeline: () => runChatV2Pipeline,
529
+ runChatV2PipelineExecution: () => runChatV2PipelineExecution,
528
530
  runGentraceTests: () => runGentraceTests,
529
531
  runRemoteGentraceTests: () => runRemoteGentraceTests,
530
532
  sanitizeIdentifierPortValue: () => sanitizeIdentifierPortValue,
@@ -536,6 +538,8 @@ __export(src_exports, {
536
538
  serializeProject: () => serializeProject,
537
539
  setGlobalNode: () => setGlobalNode,
538
540
  setStoredValueNode: () => setStoredValueNode,
541
+ shouldOutputChatV2RequestBody: () => shouldOutputChatV2RequestBody,
542
+ shouldOutputChatV2RequestError: () => shouldOutputChatV2RequestError,
539
543
  shuffleNode: () => shuffleNode,
540
544
  sliceNode: () => sliceNode,
541
545
  splitNode: () => splitNode,
@@ -978,6 +982,7 @@ __export(exports_exports, {
978
982
  looseDataValueToDataValue: () => looseDataValueToDataValue,
979
983
  looseDataValuesToDataValues: () => looseDataValuesToDataValues,
980
984
  matchNode: () => matchNode,
985
+ materializeChatV2PipelineFailure: () => materializeChatV2PipelineFailure,
981
986
  mcpDiscoveryNode: () => mcpDiscoveryNode,
982
987
  mcpGetPromptNode: () => mcpGetPromptNode,
983
988
  mcpToolCallNode: () => mcpToolCallNode,
@@ -1070,6 +1075,7 @@ __export(exports_exports, {
1070
1075
  restoreEscapedInterpolationTokens: () => restoreEscapedInterpolationTokens,
1071
1076
  rivetWebAppStatusExternalFunction: () => rivetWebAppStatusExternalFunction,
1072
1077
  runChatV2Pipeline: () => runChatV2Pipeline,
1078
+ runChatV2PipelineExecution: () => runChatV2PipelineExecution,
1073
1079
  runGentraceTests: () => runGentraceTests,
1074
1080
  runRemoteGentraceTests: () => runRemoteGentraceTests,
1075
1081
  sanitizeIdentifierPortValue: () => sanitizeIdentifierPortValue,
@@ -1081,6 +1087,8 @@ __export(exports_exports, {
1081
1087
  serializeProject: () => serializeProject,
1082
1088
  setGlobalNode: () => setGlobalNode,
1083
1089
  setStoredValueNode: () => setStoredValueNode,
1090
+ shouldOutputChatV2RequestBody: () => shouldOutputChatV2RequestBody,
1091
+ shouldOutputChatV2RequestError: () => shouldOutputChatV2RequestError,
1084
1092
  shuffleNode: () => shuffleNode,
1085
1093
  sliceNode: () => sliceNode,
1086
1094
  splitNode: () => splitNode,
@@ -1262,7 +1270,6 @@ function getCommonChatV2Outputs(data, options2 = {}) {
1262
1270
  inMessagesPortId = "in-messages",
1263
1271
  allMessagesPortId = "all-messages",
1264
1272
  functionCallsPortId = "function-calls",
1265
- responseTokensPortId = "responseTokens",
1266
1273
  usagePortId = "usage",
1267
1274
  reasoningPortId = "reasoning",
1268
1275
  includeFunctionCalls = data.useToolCalling,
@@ -1284,11 +1291,6 @@ function getCommonChatV2Outputs(data, options2 = {}) {
1284
1291
  id: allMessagesPortId,
1285
1292
  title: "All Messages",
1286
1293
  dataType: "chat-message[]"
1287
- },
1288
- {
1289
- id: responseTokensPortId,
1290
- title: "Response Tokens",
1291
- dataType: "number"
1292
1294
  }
1293
1295
  ];
1294
1296
  if (includeFunctionCalls) {
@@ -1572,14 +1574,13 @@ function createLLMChatV2NodeData() {
1572
1574
  retryOnNon200: false,
1573
1575
  retryOnNon200RepeatTimes: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES,
1574
1576
  retryOnNon200CooldownMs: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS,
1575
- outputRequestStatus: false
1577
+ outputRequestStatus: false,
1578
+ outputRequestError: false,
1579
+ outputRequestBody: false
1576
1580
  };
1577
1581
  }
1578
- function hasLLMChatV2BuiltInToolsEnabled(data) {
1579
- return data.provider === "openai" && (data.enableOpenAIWebSearch || data.enableOpenAICodeInterpreter) || data.provider === "google" && (data.enableGoogleSearchGrounding || data.enableGoogleUrlContext);
1580
- }
1581
1582
  function shouldIncludeLLMChatV2ToolCalls(data) {
1582
- return data.configurationMode === "profile" || data.useToolCalling || hasLLMChatV2BuiltInToolsEnabled(data);
1583
+ return data.useToolCalling;
1583
1584
  }
1584
1585
 
1585
1586
  // src/model/chat-v2/llmProfileTypes.ts
@@ -2477,6 +2478,20 @@ function normalizeLLMProfileValue(value) {
2477
2478
  credential
2478
2479
  };
2479
2480
  }
2481
+ function normalizeLLMProfileChainInput(value) {
2482
+ const rawProfiles = Array.isArray(value) ? value : [value];
2483
+ if (rawProfiles.length === 0) {
2484
+ throw new Error("LLM Profiles input must contain at least one LLM Profile.");
2485
+ }
2486
+ return rawProfiles.map((profile, index) => {
2487
+ try {
2488
+ return normalizeLLMProfileValue(profile);
2489
+ } catch (error) {
2490
+ const message = error instanceof Error ? error.message : String(error);
2491
+ throw new Error(`LLM Profiles input item ${index} is invalid: ${message}`);
2492
+ }
2493
+ });
2494
+ }
2480
2495
  function normalizeConfiguration(data) {
2481
2496
  var _a, _b;
2482
2497
  for (const field of stringFields) {
@@ -4188,6 +4203,21 @@ function hasLegacyDataBusFlag(node) {
4188
4203
  const data = node.data;
4189
4204
  return node.type === "passthrough" && data != null && Object.hasOwn(data, "renderAsDataBus");
4190
4205
  }
4206
+ function migrateLegacyLLMChatV2Diagnostics(node) {
4207
+ if (node.type !== "llmChatV2" || node.data == null || typeof node.data !== "object") {
4208
+ return;
4209
+ }
4210
+ const data = node.data;
4211
+ if (data.outputRequestStatus !== true) {
4212
+ return;
4213
+ }
4214
+ if (!Object.hasOwn(data, "outputRequestError")) {
4215
+ data.outputRequestError = true;
4216
+ }
4217
+ if (!Object.hasOwn(data, "outputRequestBody")) {
4218
+ data.outputRequestBody = true;
4219
+ }
4220
+ }
4191
4221
  function normalizeDeserializedNode(node) {
4192
4222
  if (node.type === "code" && node.title === "Code") {
4193
4223
  node.title = "Code (legacy)";
@@ -4198,6 +4228,7 @@ function normalizeDeserializedNode(node) {
4198
4228
  const { renderAsDataBus: _legacyFlag, ...data } = node.data;
4199
4229
  node.data = data;
4200
4230
  }
4231
+ migrateLegacyLLMChatV2Diagnostics(node);
4201
4232
  }
4202
4233
  function deserializeProjectByVersion(serializedProject, version) {
4203
4234
  switch (version) {
@@ -6267,8 +6298,16 @@ async function processSplitRunNode(node, processId, deps) {
6267
6298
  if (deps.isExcludedDueToControlFlow(node, inputValues, processId)) {
6268
6299
  return;
6269
6300
  }
6301
+ const inputDefinitionsById = new Map(deps.getInputDefinitions(node).map((definition) => [definition.id, definition]));
6270
6302
  const splittingAmount = Math.min(
6271
- (0, import_lodash_es3.max)(values(inputValues).map((value) => Array.isArray(value == null ? void 0 : value.value) ? value == null ? void 0 : value.value.length : 1)) ?? 1,
6303
+ (0, import_lodash_es3.max)(
6304
+ entries(inputValues).map(
6305
+ ([portId, value]) => {
6306
+ var _a2;
6307
+ return ((_a2 = inputDefinitionsById.get(portId)) == null ? void 0 : _a2.splitRunBehavior) === "preserve-array" ? 1 : Array.isArray(value == null ? void 0 : value.value) ? value.value.length : 1;
6308
+ }
6309
+ )
6310
+ ) ?? 1,
6272
6311
  node.splitRunMax ?? 10
6273
6312
  );
6274
6313
  await deps.emit("nodeStart", { node, inputs: inputValues, processId });
@@ -6277,9 +6316,9 @@ async function processSplitRunNode(node, processId, deps) {
6277
6316
  try {
6278
6317
  let results;
6279
6318
  if (node.isSplitSequential) {
6280
- results = await runSequential(node, inputValues, splittingAmount, processId, deps);
6319
+ results = await runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
6281
6320
  } else {
6282
- results = await runParallel(node, inputValues, splittingAmount, processId, deps);
6321
+ results = await runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
6283
6322
  }
6284
6323
  splitRunDurationMs = getSplitRunDurationMs(results);
6285
6324
  const errors = results.filter((r) => r.type === "error").map((r) => r.error);
@@ -6310,14 +6349,14 @@ async function processSplitRunNode(node, processId, deps) {
6310
6349
  await deps.nodeErrored(node, error, processId, (_c = deps.finishNodeTiming) == null ? void 0 : _c.call(deps, timingStart), splitRunDurationMs);
6311
6350
  }
6312
6351
  }
6313
- async function runSequential(node, inputValues, splittingAmount, processId, deps) {
6352
+ async function runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
6314
6353
  var _a, _b, _c;
6315
6354
  const results = [];
6316
6355
  for (let i = 0; i < splittingAmount; i++) {
6317
6356
  if (deps.isAborted()) {
6318
6357
  throw deps.getAbortError();
6319
6358
  }
6320
- const inputs = splitInputsAtIndex(inputValues, i);
6359
+ const inputs = splitInputsAtIndex(inputValues, inputDefinitionsById, i);
6321
6360
  const splitTimingStart = (_a = deps.startNodeTiming) == null ? void 0 : _a.call(deps);
6322
6361
  try {
6323
6362
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
@@ -6331,7 +6370,7 @@ async function runSequential(node, inputValues, splittingAmount, processId, deps
6331
6370
  }
6332
6371
  return results;
6333
6372
  }
6334
- async function runParallel(node, inputValues, splittingAmount, processId, deps) {
6373
+ async function runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
6335
6374
  const queue = new pQueueCompat_default({ concurrency: getParallelSplitRunConcurrency(node, deps.splitRunConcurrency) });
6336
6375
  return Promise.all(
6337
6376
  (0, import_lodash_es3.range)(0, splittingAmount).map(async (i) => {
@@ -6342,7 +6381,7 @@ async function runParallel(node, inputValues, splittingAmount, processId, deps)
6342
6381
  if (deps.isAborted()) {
6343
6382
  throw deps.getAbortError();
6344
6383
  }
6345
- const inputs = splitInputsAtIndex(inputValues, i);
6384
+ const inputs = splitInputsAtIndex(inputValues, inputDefinitionsById, i);
6346
6385
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
6347
6386
  deps.emit("partialOutput", { node: n, outputs: partialOutputs, index, processId });
6348
6387
  });
@@ -6367,12 +6406,15 @@ function getParallelSplitRunConcurrency(node, defaultConcurrency) {
6367
6406
  const value = node.splitRunConcurrency;
6368
6407
  return typeof value === "number" && Number.isFinite(value) && value >= 2 ? Math.floor(value) : defaultConcurrency;
6369
6408
  }
6370
- function splitInputsAtIndex(inputValues, index) {
6409
+ function splitInputsAtIndex(inputValues, inputDefinitionsById, index) {
6371
6410
  return fromEntries(
6372
- entries(inputValues).map(([port, value]) => [
6373
- port,
6374
- isArrayDataValue(value) ? arrayizeDataValue(value)[index] ?? void 0 : value
6375
- ])
6411
+ entries(inputValues).map(([port, value]) => {
6412
+ var _a;
6413
+ return [
6414
+ port,
6415
+ ((_a = inputDefinitionsById.get(port)) == null ? void 0 : _a.splitRunBehavior) === "preserve-array" ? value : isArrayDataValue(value) ? arrayizeDataValue(value)[index] ?? void 0 : value
6416
+ ];
6417
+ })
6376
6418
  );
6377
6419
  }
6378
6420
  function aggregateOutputs(results) {
@@ -7111,6 +7153,15 @@ function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
7111
7153
  value: preToolMessage
7112
7154
  };
7113
7155
  const outputs = records.length === 1 ? {
7156
+ ["assistant-message"]: preToolMessageOutput,
7157
+ ["tool-name"]: {
7158
+ type: "string",
7159
+ value: records[0].name
7160
+ },
7161
+ ["tool-arguments"]: {
7162
+ type: "object",
7163
+ value: records[0].arguments
7164
+ },
7114
7165
  ["output"]: {
7115
7166
  type: "string",
7116
7167
  value: records[0].output
@@ -7118,9 +7169,17 @@ function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
7118
7169
  ["message"]: {
7119
7170
  type: "chat-message",
7120
7171
  value: records[0].message
7121
- },
7122
- ["assistant-message"]: preToolMessageOutput
7172
+ }
7123
7173
  } : {
7174
+ ["assistant-message"]: preToolMessageOutput,
7175
+ ["tool-name"]: {
7176
+ type: "string[]",
7177
+ value: records.map((record) => record.name)
7178
+ },
7179
+ ["tool-arguments"]: {
7180
+ type: "object[]",
7181
+ value: records.map((record) => record.arguments)
7182
+ },
7124
7183
  ["output"]: {
7125
7184
  type: "string[]",
7126
7185
  value: records.map((record) => record.output)
@@ -7128,8 +7187,7 @@ function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
7128
7187
  ["message"]: {
7129
7188
  type: "chat-message[]",
7130
7189
  value: records.map((record) => record.message)
7131
- },
7132
- ["assistant-message"]: preToolMessageOutput
7190
+ }
7133
7191
  };
7134
7192
  if (cost != null) {
7135
7193
  outputs["cost"] = { type: "number", value: cost };
@@ -7432,7 +7490,12 @@ var ToolCallContinuationCoordinator = class {
7432
7490
  await this.#adapter.emitDelegateFinish(delegateNode, outputs, processId, timingStart);
7433
7491
  delegateFinished = true;
7434
7492
  const finalBranch = canRunContinuationBranches ? await branchAdapter.runOutputBranch({
7435
- activeOutputPortIds: /* @__PURE__ */ new Set(["output", "message"]),
7493
+ activeOutputPortIds: /* @__PURE__ */ new Set([
7494
+ "tool-name",
7495
+ "tool-arguments",
7496
+ "output",
7497
+ "message"
7498
+ ]),
7436
7499
  availableNodeOutputs: preToolBranch.nodeOutputs,
7437
7500
  deferGraphOutputCommit: true,
7438
7501
  excludedNodeIds: continuationBranchBoundaries,
@@ -9675,6 +9738,10 @@ ${errors.map(({ node }) => `- ${node.title} (${node.id})`).join("\n")}`;
9675
9738
  async #processSplitRunNode(node, processId) {
9676
9739
  return processSplitRunNode(node, processId, {
9677
9740
  getInputValues: (n) => this.#getInputValuesForNode(n),
9741
+ getInputDefinitions: (n) => {
9742
+ var _a;
9743
+ return ((_a = this.#definitions[n.id]) == null ? void 0 : _a.inputs) ?? [];
9744
+ },
9678
9745
  isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid) !== false,
9679
9746
  processNodeWithInputData: (n, inputs, idx, pid, partial) => this.#processNodeWithInputData(n, inputs, idx, pid, partial),
9680
9747
  splitRunConcurrency: this.#concurrency.splitRunConcurrency,
@@ -14746,7 +14813,13 @@ async function chatMessageToOpenAIChatCompletionMessage(message, options2) {
14746
14813
  content: onlyStringContent(m)
14747
14814
  };
14748
14815
  }
14749
- }).with({ type: "user" }, async (m) => {
14816
+ }).with(
14817
+ { type: "developer" },
14818
+ (m) => ({
14819
+ role: "developer",
14820
+ content: onlyStringContent(m)
14821
+ })
14822
+ ).with({ type: "user" }, async (m) => {
14750
14823
  const parts = Array.isArray(m.message) ? m.message : [m.message];
14751
14824
  if (parts.length === 1 && typeof parts[0] === "string") {
14752
14825
  return { role: m.type, content: parts[0] };
@@ -16552,6 +16625,18 @@ var generativeAiOptions = Object.entries(generativeAiGoogleModels).map(([id, { d
16552
16625
  value: id,
16553
16626
  label: displayName
16554
16627
  }));
16628
+ function getVertexGenerativeModelOptions(options2) {
16629
+ return {
16630
+ model: options2.model,
16631
+ systemInstruction: options2.systemPrompt,
16632
+ generationConfig: {
16633
+ maxOutputTokens: options2.max_output_tokens,
16634
+ temperature: options2.temperature,
16635
+ topP: options2.top_p,
16636
+ topK: options2.top_k
16637
+ }
16638
+ };
16639
+ }
16555
16640
  async function* streamGenerativeAi({
16556
16641
  apiKey,
16557
16642
  model,
@@ -16620,21 +16705,23 @@ async function* streamChatCompletions3({
16620
16705
  temperature,
16621
16706
  top_p,
16622
16707
  top_k,
16708
+ systemPrompt,
16623
16709
  prompt
16624
16710
  }) {
16625
16711
  var _a, _b;
16626
16712
  const { VertexAI } = await import("@google-cloud/vertexai");
16627
16713
  process.env.GOOGLE_APPLICATION_CREDENTIALS = applicationCredentials;
16628
16714
  const vertexAi = new VertexAI({ project, location });
16629
- const generativeModel = vertexAi.preview.getGenerativeModel({
16630
- model,
16631
- generationConfig: {
16632
- maxOutputTokens: max_output_tokens,
16715
+ const generativeModel = vertexAi.preview.getGenerativeModel(
16716
+ getVertexGenerativeModelOptions({
16717
+ model,
16718
+ systemPrompt,
16719
+ max_output_tokens,
16633
16720
  temperature,
16634
- topP: top_p,
16635
- topK: top_k
16636
- }
16637
- });
16721
+ top_p,
16722
+ top_k
16723
+ })
16724
+ );
16638
16725
  const response = await generativeModel.generateContentStream({
16639
16726
  contents: prompt
16640
16727
  });
@@ -16812,18 +16899,46 @@ function cloneCapturedRequestBody(body) {
16812
16899
  return body;
16813
16900
  }
16814
16901
  }
16815
- function createRequestBodyCapturingFetch(onRequestBody) {
16902
+ function serializeTransformedFetchBody(originalBody, transformedBody) {
16903
+ const serialized = JSON.stringify(transformedBody);
16904
+ if (serialized === void 0) {
16905
+ throw new Error("Provider request-body transformation returned a non-serializable value.");
16906
+ }
16907
+ if (originalBody instanceof ArrayBuffer) {
16908
+ return new TextEncoder().encode(serialized);
16909
+ }
16910
+ if (ArrayBuffer.isView(originalBody)) {
16911
+ return new TextEncoder().encode(serialized);
16912
+ }
16913
+ return serialized;
16914
+ }
16915
+ function removeStaleContentLength(headers) {
16916
+ if (headers == null) {
16917
+ return void 0;
16918
+ }
16919
+ const nextHeaders = new Headers(headers);
16920
+ nextHeaders.delete("content-length");
16921
+ return nextHeaders;
16922
+ }
16923
+ function createRequestBodyProcessingFetch(options2) {
16816
16924
  return async (input, init2) => {
16817
- const body = parseFetchBody(init2 == null ? void 0 : init2.body);
16818
- if (body !== void 0) {
16819
- onRequestBody(cloneCapturedRequestBody(body));
16925
+ var _a;
16926
+ const parsedBody = parseFetchBody(init2 == null ? void 0 : init2.body);
16927
+ const processedBody = parsedBody !== void 0 && options2.transformRequestBody != null ? options2.transformRequestBody(parsedBody) : parsedBody;
16928
+ if (processedBody !== void 0) {
16929
+ (_a = options2.onRequestBody) == null ? void 0 : _a.call(options2, cloneCapturedRequestBody(processedBody));
16820
16930
  }
16821
16931
  const nativeFetch = globalThis.fetch;
16822
- return nativeFetch(input, init2);
16932
+ const processedInit = processedBody !== parsedBody ? {
16933
+ ...init2,
16934
+ body: serializeTransformedFetchBody(init2 == null ? void 0 : init2.body, processedBody),
16935
+ headers: removeStaleContentLength(init2 == null ? void 0 : init2.headers)
16936
+ } : init2;
16937
+ return nativeFetch(input, processedInit);
16823
16938
  };
16824
16939
  }
16825
- function maybeCreateRequestBodyCapturingFetch(options2) {
16826
- return options2.onRequestBody == null ? void 0 : createRequestBodyCapturingFetch(options2.onRequestBody);
16940
+ function maybeCreateRequestBodyProcessingFetch(options2) {
16941
+ return options2.onRequestBody == null && options2.transformRequestBody == null ? void 0 : createRequestBodyProcessingFetch(options2);
16827
16942
  }
16828
16943
  async function resolveChatV2ProviderConfig(provider, _modelId, context, options2 = {}) {
16829
16944
  var _a;
@@ -16867,7 +16982,7 @@ function createChatV2Model(provider, modelId, context, options2 = {}) {
16867
16982
  organization: context.settings.openAiOrganization || void 0,
16868
16983
  baseURL: void 0,
16869
16984
  headers: options2.headers,
16870
- fetch: maybeCreateRequestBodyCapturingFetch(options2)
16985
+ fetch: maybeCreateRequestBodyProcessingFetch(options2)
16871
16986
  });
16872
16987
  return providerInstance.responses(modelId);
16873
16988
  }
@@ -16876,7 +16991,7 @@ function createChatV2Model(provider, modelId, context, options2 = {}) {
16876
16991
  apiKey: options2.apiKey || context.settings.anthropicApiKey || context.getPluginConfig("anthropicApiKey") || void 0,
16877
16992
  baseURL: void 0,
16878
16993
  headers: options2.headers,
16879
- fetch: maybeCreateRequestBodyCapturingFetch(options2)
16994
+ fetch: maybeCreateRequestBodyProcessingFetch(options2)
16880
16995
  });
16881
16996
  return providerInstance.messages(modelId);
16882
16997
  }
@@ -16885,7 +17000,7 @@ function createChatV2Model(provider, modelId, context, options2 = {}) {
16885
17000
  apiKey: options2.apiKey || context.settings.googleApiKey || context.getPluginConfig("googleApiKey") || void 0,
16886
17001
  baseURL: void 0,
16887
17002
  headers: options2.headers,
16888
- fetch: maybeCreateRequestBodyCapturingFetch(options2)
17003
+ fetch: maybeCreateRequestBodyProcessingFetch(options2)
16889
17004
  });
16890
17005
  return providerInstance.chat(modelId);
16891
17006
  }
@@ -16899,7 +17014,7 @@ function createChatV2Model(provider, modelId, context, options2 = {}) {
16899
17014
  baseURL: options2.baseURL,
16900
17015
  headers: options2.headers,
16901
17016
  includeUsage: false,
16902
- fetch: maybeCreateRequestBodyCapturingFetch(options2)
17017
+ fetch: maybeCreateRequestBodyProcessingFetch(options2)
16903
17018
  });
16904
17019
  const model = providerInstance.chatModel(modelId);
16905
17020
  model.supportsStructuredOutputs = true;
@@ -17048,11 +17163,7 @@ function getModelEditors(modelOptions) {
17048
17163
  );
17049
17164
  }
17050
17165
  function getProviderEditors() {
17051
- return [
17052
- getOpenAIProviderEditors(),
17053
- getAnthropicProviderEditors(),
17054
- getGoogleProviderEditors()
17055
- ];
17166
+ return [getOpenAIProviderEditors(), getAnthropicProviderEditors(), getGoogleProviderEditors()];
17056
17167
  }
17057
17168
  function getOpenAIProviderEditors() {
17058
17169
  return providerGroup("openai", "OpenAI", [
@@ -17362,6 +17473,18 @@ function getOutputEditors() {
17362
17473
  dataKey: "outputUsage",
17363
17474
  helperMessage: "Adds a Usage output built from Vercel AI SDK usage metadata: prompt, completion, total, cached, reasoning tokens, and estimated cost when available."
17364
17475
  },
17476
+ {
17477
+ type: "toggle",
17478
+ label: "Output response status",
17479
+ dataKey: "outputRequestStatus",
17480
+ helperMessage: "Adds a Response Status output. Retry mode returns statuses for each physical request. An LLM Profile array groups values by profile, while a profile with one request stays a number."
17481
+ },
17482
+ {
17483
+ type: "toggle",
17484
+ label: "Output request body",
17485
+ dataKey: "outputRequestBody",
17486
+ helperMessage: "Adds an LLM request body output. It can contain prompts and non-secret provider options; it never includes authorization headers or API keys."
17487
+ },
17365
17488
  {
17366
17489
  type: "toggle",
17367
17490
  label: "Stream response",
@@ -17370,9 +17493,10 @@ function getOutputEditors() {
17370
17493
  },
17371
17494
  {
17372
17495
  type: "toggle",
17373
- label: "Cache outputs (editor only)",
17496
+ label: "Cache outputs (editor only) (legacy)",
17374
17497
  dataKey: "cache",
17375
- helperMessage: "Reuses this node's previous outputs if the input is the same (provider config, prompt and generation settings). The cache persists while the Rivet app is open."
17498
+ helperMessage: "Legacy editor-only cache. It reuses this node's previous outputs for the same input while the Rivet app is open. Turn it off to retire it from this node.",
17499
+ hideIf: (data) => data.cache !== true
17376
17500
  }
17377
17501
  ]);
17378
17502
  }
@@ -17397,8 +17521,8 @@ function getProviderAdvancedEditors() {
17397
17521
  }
17398
17522
  ]);
17399
17523
  }
17400
- function getTechnicalDetailsEditors() {
17401
- return group("Technical details", [
17524
+ function getErrorBehaviorEditors() {
17525
+ return group("Error behavior", [
17402
17526
  {
17403
17527
  type: "toggle",
17404
17528
  label: "Retry on non-200",
@@ -17429,9 +17553,9 @@ function getTechnicalDetailsEditors() {
17429
17553
  },
17430
17554
  {
17431
17555
  type: "toggle",
17432
- label: "Output request details",
17433
- dataKey: "outputRequestStatus",
17434
- helperMessage: "Adds Response Status, Response Error, and LLM request body outputs. Retry mode changes status/error to per-attempt arrays, and LLM request body becomes an array when multiple provider calls are made."
17556
+ label: "Output response error",
17557
+ dataKey: "outputRequestError",
17558
+ helperMessage: "Adds a Response Error output. Provider request failures become excluded outputs instead of node errors. Retry mode returns errors for each physical request; an LLM Profile array groups errors by profile."
17435
17559
  }
17436
17560
  ]);
17437
17561
  }
@@ -17453,7 +17577,7 @@ async function getLLMChatV2Editors(data, context) {
17453
17577
  getToolEditors(),
17454
17578
  getOutputEditors(),
17455
17579
  ...!usesProfile ? [getProviderAdvancedEditors()] : [],
17456
- getTechnicalDetailsEditors()
17580
+ getErrorBehaviorEditors()
17457
17581
  ];
17458
17582
  }
17459
17583
  async function getLLMProfileEditors(data, context) {
@@ -17620,783 +17744,283 @@ function createsLLMChatV2ToolResponseFormatConflictForEdit(previousData, nextDat
17620
17744
  return hasLLMChatV2ToolResponseFormatConflict(nextData) && !hasLLMChatV2ToolResponseFormatConflict(previousData);
17621
17745
  }
17622
17746
 
17623
- // src/model/chat-v2/chatV2ProviderProfile.ts
17624
- function getStringSetting(settings, key) {
17625
- const value = settings[key];
17626
- return typeof value === "string" && value.trim() ? value : void 0;
17627
- }
17628
- function resolveConfiguredCredential(provider, context, options2) {
17629
- var _a, _b, _c, _d, _e;
17630
- switch (provider) {
17631
- case "openai": {
17632
- const value = context.settings.openAiApiKey || context.settings.openAiKey || void 0;
17633
- return { value, reference: { source: value ? "settings" : "none" } };
17634
- }
17635
- case "anthropic": {
17636
- const settingsValue = context.settings.anthropicApiKey || void 0;
17637
- if (settingsValue) return { value: settingsValue, reference: { source: "settings" } };
17638
- const pluginValue = context.getPluginConfig("anthropicApiKey") || void 0;
17639
- return { value: pluginValue, reference: { source: pluginValue ? "plugin" : "none" } };
17640
- }
17641
- case "google": {
17642
- const settingsValue = context.settings.googleApiKey || void 0;
17643
- if (settingsValue) return { value: settingsValue, reference: { source: "settings" } };
17644
- const pluginValue = context.getPluginConfig("googleApiKey") || void 0;
17645
- return { value: pluginValue, reference: { source: pluginValue ? "plugin" : "none" } };
17747
+ // src/model/chat-v2/aiSdkBridge.ts
17748
+ var import_ai2 = require("ai");
17749
+
17750
+ // src/model/chat/aiSdkStreaming.ts
17751
+ function buildResponseText(textBlocks, dedupeDuplicateTextBlocks) {
17752
+ const blockTexts = Array.from(textBlocks.values()).filter((text) => text.length > 0);
17753
+ if (blockTexts.length === 0) {
17754
+ return "";
17755
+ }
17756
+ if (dedupeDuplicateTextBlocks && blockTexts.length > 1) {
17757
+ const longestText = blockTexts.reduce((longest, text) => text.length > longest.length ? text : longest);
17758
+ if (blockTexts.every((text) => longestText.startsWith(text))) {
17759
+ return longestText;
17646
17760
  }
17647
- case "custom": {
17648
- const programmaticName = (_a = options2.customProgrammaticName) == null ? void 0 : _a.trim();
17649
- const environmentName = (_b = options2.customEnvironmentName) == null ? void 0 : _b.trim();
17650
- const programmaticValue = programmaticName ? getStringSetting(context.settings, programmaticName) : void 0;
17651
- if (programmaticValue) {
17652
- return {
17653
- value: programmaticValue,
17654
- reference: { source: "programmatic", name: programmaticName }
17655
- };
17656
- }
17657
- if (environmentName) {
17658
- const pluginEnvValue = (_c = context.settings.pluginEnv) == null ? void 0 : _c[environmentName];
17659
- if (pluginEnvValue) {
17660
- return { value: pluginEnvValue, reference: { source: "environment", name: environmentName } };
17661
- }
17662
- const processValue = (_e = (_d = globalThis.process) == null ? void 0 : _d.env) == null ? void 0 : _e[environmentName];
17663
- if (processValue) {
17664
- return { value: processValue, reference: { source: "environment", name: environmentName } };
17761
+ }
17762
+ return blockTexts.join("");
17763
+ }
17764
+ async function consumeAiSdkStream(fullStream, onPartialOutputs, options2 = {}) {
17765
+ let responseText = "";
17766
+ let reasoning = "";
17767
+ const functionCalls = [];
17768
+ let usage;
17769
+ const textBlocks = /* @__PURE__ */ new Map();
17770
+ for await (const part of fullStream) {
17771
+ switch (part.type) {
17772
+ case "text-start": {
17773
+ if (!textBlocks.has(part.id)) {
17774
+ textBlocks.set(part.id, "");
17665
17775
  }
17776
+ break;
17666
17777
  }
17667
- const value = context.settings.customAiApiKey || void 0;
17668
- if (value) return { value, reference: { source: "settings" } };
17669
- const missing = [
17670
- programmaticName ? `programmatic key ${programmaticName}` : void 0,
17671
- environmentName ? `env var ${environmentName}` : void 0
17672
- ].filter(Boolean);
17673
- if (missing.length > 0) {
17674
- const hint = programmaticName ? `pass ${programmaticName}` : "set Alternative programmatic key name and pass that named run option";
17675
- throw new Error(
17676
- `Custom provider API key ${missing.join(" and ")} is not set. Use Input port, configure Settings > LLM, ${hint}, or configure the environment variable.`
17677
- );
17778
+ case "text-delta": {
17779
+ textBlocks.set(part.id, `${textBlocks.get(part.id) ?? ""}${part.text}`);
17780
+ responseText = buildResponseText(textBlocks, !!options2.dedupeDuplicateTextBlocks);
17781
+ onPartialOutputs(responseText, functionCalls);
17782
+ break;
17783
+ }
17784
+ case "reasoning-delta": {
17785
+ reasoning += part.text;
17786
+ break;
17787
+ }
17788
+ case "tool-call": {
17789
+ functionCalls.push({
17790
+ type: "function",
17791
+ id: part.toolCallId,
17792
+ name: part.toolName,
17793
+ arguments: JSON.stringify(part.input),
17794
+ lastParsedArguments: part.input
17795
+ });
17796
+ onPartialOutputs(responseText, functionCalls);
17797
+ break;
17798
+ }
17799
+ case "finish": {
17800
+ usage = part.totalUsage;
17801
+ break;
17802
+ }
17803
+ case "error": {
17804
+ throw part.error instanceof Error ? part.error : new Error(String(part.error));
17678
17805
  }
17679
- return { reference: { source: "none" } };
17680
17806
  }
17681
17807
  }
17808
+ return { responseText, functionCalls, usage, reasoning };
17682
17809
  }
17683
- function resolveChatV2Credential(options2) {
17684
- var _a, _b;
17685
- if (options2.apiKeySource === "input") {
17686
- const value = (_b = coerceTypeOptional((_a = options2.inputs) == null ? void 0 : _a["apiKey"], "string")) == null ? void 0 : _b.trim();
17687
- if (!value) throw new Error("API Key input is required when API key source is Input port.");
17688
- return { value, reference: { source: "input" } };
17810
+
17811
+ // src/model/chat-v2/aiSdkBridge.ts
17812
+ function keepPromiseHandled(value) {
17813
+ const promise = Promise.resolve(value);
17814
+ void promise.catch(() => void 0);
17815
+ return promise;
17816
+ }
17817
+ function isPromiseLike(value) {
17818
+ return value != null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
17819
+ }
17820
+ function markOptionalPromiseHandled(value) {
17821
+ if (isPromiseLike(value)) {
17822
+ void keepPromiseHandled(value);
17689
17823
  }
17690
- return resolveConfiguredCredential(options2.provider, options2.context, options2);
17691
17824
  }
17692
- async function createResolvedChatV2Provider(options2) {
17693
- const config = await resolveChatV2ProviderConfig(options2.provider, options2.modelId, options2.context, {
17694
- baseURL: options2.baseURL,
17695
- headers: options2.headers
17696
- });
17697
- const model = createChatV2Model(options2.provider, options2.modelId, options2.context, {
17698
- ...config,
17699
- apiKey: options2.credential.value,
17700
- onRequestBody: options2.onRequestBody
17701
- });
17825
+ function defaultStreamExecutor(args) {
17826
+ const result = (0, import_ai2.streamText)(args);
17702
17827
  return {
17703
- profile: {
17704
- provider: options2.provider,
17705
- modelId: options2.modelId,
17706
- baseURL: config.baseURL,
17707
- hasCustomHeaders: Object.keys(config.headers ?? {}).length > 0,
17708
- credential: options2.credential.reference,
17709
- capabilities: {
17710
- builtInTools: options2.provider === "openai" || options2.provider === "google",
17711
- structuredOutput: true
17712
- }
17713
- },
17714
- model,
17715
- config
17828
+ fullStream: result.fullStream,
17829
+ finishReason: "finishReason" in result ? keepPromiseHandled(
17830
+ Promise.resolve(result.finishReason).then((value) => value == null ? void 0 : String(value))
17831
+ ) : void 0,
17832
+ output: args.output != null && "output" in result ? keepPromiseHandled(Promise.resolve(result.output)) : void 0,
17833
+ providerMetadata: "providerMetadata" in result ? keepPromiseHandled(
17834
+ Promise.resolve(result.providerMetadata)
17835
+ ) : void 0,
17836
+ requestStatus: 200,
17837
+ usage: "usage" in result ? keepPromiseHandled(Promise.resolve(result.usage)) : void 0
17716
17838
  };
17717
17839
  }
17718
-
17719
- // src/model/chat-v2/chatV2EditorCache.ts
17720
- var import_safe_stable_stringify4 = __toESM(require("safe-stable-stringify"), 1);
17721
- function buildLLMChatV2EditorCacheKey(parts) {
17722
- return (0, import_safe_stable_stringify4.default)(parts) ?? "";
17840
+ async function defaultGenerateExecutor(args) {
17841
+ return await (0, import_ai2.generateText)(args);
17723
17842
  }
17724
- function cloneEditorCacheValue(value, seen = /* @__PURE__ */ new WeakMap()) {
17725
- if (value == null || typeof value !== "object") {
17726
- return value;
17727
- }
17728
- if (value instanceof Uint8Array) {
17729
- return new Uint8Array(value);
17730
- }
17731
- const existing = seen.get(value);
17732
- if (existing != null) {
17733
- return existing;
17734
- }
17735
- if (Array.isArray(value)) {
17736
- const clone2 = [];
17737
- seen.set(value, clone2);
17738
- clone2.push(...value.map((item) => cloneEditorCacheValue(item, seen)));
17739
- return clone2;
17843
+ async function resolveOptionalValue(value) {
17844
+ return value == null ? void 0 : await value;
17845
+ }
17846
+ async function resolveOptionalStructuredOutput(value) {
17847
+ if (value == null) {
17848
+ return void 0;
17740
17849
  }
17741
- const clone = {};
17742
- seen.set(value, clone);
17743
- for (const [key, item] of Object.entries(value)) {
17744
- clone[key] = cloneEditorCacheValue(item, seen);
17850
+ try {
17851
+ return await value;
17852
+ } catch {
17853
+ return void 0;
17745
17854
  }
17746
- return clone;
17747
17855
  }
17748
- function cloneLLMChatV2EditorCacheOutputs(outputs) {
17749
- if (typeof structuredClone === "function") {
17750
- try {
17751
- return structuredClone(outputs);
17752
- } catch {
17753
- }
17856
+ async function resolveGenerateStructuredOutput(result, responseOutput, finishReason) {
17857
+ if (responseOutput == null || finishReason != null && finishReason !== "stop") {
17858
+ return void 0;
17859
+ }
17860
+ try {
17861
+ return await resolveOptionalStructuredOutput(result.output);
17862
+ } catch {
17863
+ return void 0;
17754
17864
  }
17755
- return cloneEditorCacheValue(outputs);
17756
17865
  }
17757
- function fingerprintSecret(secret) {
17758
- if (!secret) {
17866
+ function recoverGenerateStructuredOutputError(error, options2, toolCalls) {
17867
+ if (options2.responseOutput == null || !isChatV2StructuredResponseFormat(options2.responseFormat)) {
17759
17868
  return void 0;
17760
17869
  }
17761
- let hash = 2166136261;
17762
- for (let i = 0; i < secret.length; i++) {
17763
- hash ^= secret.charCodeAt(i);
17764
- hash = Math.imul(hash, 16777619);
17870
+ if (!import_ai2.NoObjectGeneratedError.isInstance(error)) {
17871
+ return void 0;
17765
17872
  }
17766
- return `${secret.length}:${(hash >>> 0).toString(36)}`;
17767
- }
17768
- function fingerprintProviderConfigForCache(config) {
17769
- if (config.headers == null) {
17770
- return config;
17873
+ if (typeof error.text !== "string") {
17874
+ return void 0;
17771
17875
  }
17876
+ const rawText = error.text;
17877
+ const responseText = collapseRepeatedStructuredJsonText(rawText);
17772
17878
  return {
17773
- ...config,
17774
- headers: Object.fromEntries(
17775
- Object.entries(config.headers).map(([key, value]) => [key, fingerprintSecret(value) ?? ""])
17776
- )
17879
+ responseText,
17880
+ structuredOutput: void 0,
17881
+ functionCalls: toStreamedFunctionCalls(toolCalls),
17882
+ usage: error.usage,
17883
+ reasoning: "",
17884
+ finishReason: error.finishReason == null ? void 0 : String(error.finishReason),
17885
+ providerMetadata: void 0,
17886
+ requestStatus: void 0
17777
17887
  };
17778
17888
  }
17779
- function fingerprintNodeDataForCache(data) {
17780
- const isCustomProvider = data.provider === "custom";
17781
- return {
17782
- ...data,
17783
- baseURL: "",
17784
- useBaseURLInput: false,
17785
- customProviderBaseURL: isCustomProvider ? data.customProviderBaseURL : "",
17786
- useCustomProviderBaseURLInput: isCustomProvider ? data.useCustomProviderBaseURLInput : false,
17787
- extraProviderOptions: data.useExtraProviderOptionsInput ? "" : fingerprintSecret(data.extraProviderOptions) ?? "",
17788
- headers: (data.headers ?? []).map(({ key, value }) => ({
17789
- key,
17790
- value: fingerprintSecret(value) ?? ""
17791
- }))
17889
+ function attachGenerateStepToolCallCollector(args) {
17890
+ const toolCalls = [];
17891
+ const previousOnStepFinish = args.onStepFinish;
17892
+ args.onStepFinish = async (event) => {
17893
+ const stepToolCalls = event.toolCalls;
17894
+ if (stepToolCalls != null) {
17895
+ toolCalls.push(...stepToolCalls);
17896
+ }
17897
+ await (previousOnStepFinish == null ? void 0 : previousOnStepFinish(event));
17792
17898
  };
17899
+ return toolCalls;
17793
17900
  }
17794
- function fingerprintProviderOptionsForCache(providerOptions) {
17795
- if (providerOptions == null) {
17796
- return void 0;
17901
+ function collapseRepeatedStructuredJsonText(responseText) {
17902
+ if (responseText.length === 0 || responseText.length % 2 !== 0) {
17903
+ return responseText;
17904
+ }
17905
+ const midpoint = responseText.length / 2;
17906
+ const firstHalf = responseText.slice(0, midpoint);
17907
+ const firstNonWhitespaceCharacter = firstHalf.trimStart()[0];
17908
+ if (firstHalf !== responseText.slice(midpoint)) {
17909
+ return responseText;
17910
+ }
17911
+ if (firstNonWhitespaceCharacter !== "{" && firstNonWhitespaceCharacter !== "[") {
17912
+ return responseText;
17913
+ }
17914
+ try {
17915
+ JSON.parse(firstHalf);
17916
+ return firstHalf;
17917
+ } catch {
17918
+ return responseText;
17797
17919
  }
17798
- return fingerprintSecret((0, import_safe_stable_stringify4.default)(providerOptions) ?? "");
17799
17920
  }
17800
- function resolveLLMChatV2EditorCache(params) {
17801
- const { editorCache } = params;
17802
- if (editorCache == null) {
17803
- return { cacheKey: void 0, cachedOutputs: void 0 };
17921
+ function buildTextArgs(options2) {
17922
+ const args = {
17923
+ model: options2.model,
17924
+ messages: options2.messages,
17925
+ maxRetries: options2.maxRetries ?? 0
17926
+ };
17927
+ if (options2.tools !== void 0) args.tools = options2.tools;
17928
+ if (options2.maxTokens !== void 0) args.maxOutputTokens = options2.maxTokens;
17929
+ if (options2.temperature !== void 0) args.temperature = options2.temperature;
17930
+ if (options2.topP !== void 0) args.topP = options2.topP;
17931
+ if (options2.topK !== void 0) args.topK = options2.topK;
17932
+ if (options2.presencePenalty !== void 0) args.presencePenalty = options2.presencePenalty;
17933
+ if (options2.frequencyPenalty !== void 0) args.frequencyPenalty = options2.frequencyPenalty;
17934
+ if (options2.stopSequences !== void 0) args.stopSequences = options2.stopSequences;
17935
+ if (options2.seed !== void 0) args.seed = options2.seed;
17936
+ if (options2.responseOutput !== void 0) args.output = options2.responseOutput;
17937
+ if (options2.providerOptions !== void 0) args.providerOptions = options2.providerOptions;
17938
+ if (options2.toolChoice !== void 0) args.toolChoice = options2.toolChoice;
17939
+ if (options2.abortSignal !== void 0) args.abortSignal = options2.abortSignal;
17940
+ return args;
17941
+ }
17942
+ function toStreamedFunctionCalls(toolCalls) {
17943
+ return (toolCalls ?? []).map((toolCall) => ({
17944
+ type: "function",
17945
+ id: toolCall.toolCallId,
17946
+ name: toolCall.toolName,
17947
+ arguments: JSON.stringify(toolCall.input),
17948
+ lastParsedArguments: toolCall.input
17949
+ }));
17950
+ }
17951
+ async function resolveGenerateReasoning(result) {
17952
+ var _a;
17953
+ const reasoningText = await resolveOptionalValue(result.reasoningText);
17954
+ if (reasoningText != null && reasoningText.trim().length > 0) {
17955
+ return reasoningText;
17804
17956
  }
17805
- const cacheKey = buildLLMChatV2EditorCacheKey({
17806
- nodeId: params.nodeId,
17807
- nodeData: fingerprintNodeDataForCache(params.data),
17808
- provider: params.provider,
17809
- modelId: params.modelId,
17810
- providerConfig: fingerprintProviderConfigForCache(params.providerConfig),
17811
- apiKeyFingerprint: fingerprintSecret(params.apiKey),
17812
- prompt: params.prompt,
17813
- systemPrompt: params.systemPrompt,
17814
- functions: params.functions,
17815
- generationParameters: params.generationParameters,
17816
- responseFormatParameters: params.responseFormatParameters,
17817
- providerOptions: fingerprintProviderOptionsForCache(params.providerOptions),
17818
- toolChoice: params.toolChoice
17819
- });
17957
+ return ((_a = await resolveOptionalValue(result.reasoning)) == null ? void 0 : _a.map((part) => part.text).join("")) ?? "";
17958
+ }
17959
+ async function executeStream(options2, executor) {
17960
+ const args = buildTextArgs(options2);
17961
+ const handle = await executor(args);
17962
+ markOptionalPromiseHandled(handle.finishReason);
17963
+ markOptionalPromiseHandled(handle.output);
17964
+ markOptionalPromiseHandled(handle.providerMetadata);
17965
+ markOptionalPromiseHandled(handle.requestStatus);
17966
+ markOptionalPromiseHandled(handle.usage);
17967
+ const isStructuredOutput = isChatV2StructuredResponseFormat(options2.responseFormat);
17968
+ const streamed = await consumeAiSdkStream(
17969
+ handle.fullStream,
17970
+ (text, functionCalls) => {
17971
+ var _a;
17972
+ (_a = options2.onPartialOutput) == null ? void 0 : _a.call(options2, {
17973
+ text: isStructuredOutput ? collapseRepeatedStructuredJsonText(text) : text,
17974
+ functionCalls
17975
+ });
17976
+ },
17977
+ {
17978
+ dedupeDuplicateTextBlocks: isStructuredOutput
17979
+ }
17980
+ );
17981
+ const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(streamed.responseText) : streamed.responseText;
17820
17982
  return {
17821
- cacheKey,
17822
- cachedOutputs: editorCache.has(cacheKey) ? cloneLLMChatV2EditorCacheOutputs(editorCache.get(cacheKey)) : void 0
17983
+ responseText,
17984
+ structuredOutput: options2.responseOutput != null ? await resolveOptionalStructuredOutput(handle.output) : void 0,
17985
+ functionCalls: streamed.functionCalls,
17986
+ usage: streamed.usage ?? await resolveOptionalValue(handle.usage),
17987
+ reasoning: streamed.reasoning,
17988
+ finishReason: await resolveOptionalValue(handle.finishReason),
17989
+ providerMetadata: await resolveOptionalValue(handle.providerMetadata),
17990
+ requestStatus: await resolveOptionalValue(handle.requestStatus)
17823
17991
  };
17824
17992
  }
17825
-
17826
- // src/model/chat-v2/chatV2RuntimeOptions.ts
17827
- var import_google3 = require("@ai-sdk/google");
17828
- var import_openai4 = require("@ai-sdk/openai");
17829
- function resolveLLMChatV2Headers(data, inputs) {
17830
- const resolvedHeaders = data.useHeadersInput && inputs["headers"] != null ? coerceTypeOptional(inputs["headers"], "object") : Object.fromEntries((data.headers ?? []).map(({ key, value }) => [key, value]));
17831
- const cleaned = cleanHeaders(resolvedHeaders ?? {});
17832
- return Object.keys(cleaned).length > 0 ? cleaned : void 0;
17993
+ async function streamChatV2(options2) {
17994
+ return executeStream(options2, options2.executeStream ?? defaultStreamExecutor);
17833
17995
  }
17834
- function parseExtraProviderOptionsText(rawText) {
17835
- const raw = rawText.trim();
17836
- if (!raw) {
17837
- return void 0;
17838
- }
17839
- let parsed;
17996
+ async function generateChatV2(options2) {
17997
+ const args = buildTextArgs(options2);
17998
+ const stepToolCalls = attachGenerateStepToolCallCollector(args);
17999
+ let result;
17840
18000
  try {
17841
- parsed = JSON.parse(raw);
18001
+ result = await (options2.executeGenerate ?? defaultGenerateExecutor)(args);
17842
18002
  } catch (error) {
17843
- const message = error instanceof Error ? error.message : String(error);
17844
- throw new Error(`Extra provider options must be valid JSON: ${message}`);
18003
+ const recovered = recoverGenerateStructuredOutputError(error, options2, stepToolCalls);
18004
+ if (recovered != null) {
18005
+ return recovered;
18006
+ }
18007
+ throw error;
17845
18008
  }
17846
- return normalizeExtraProviderOptions(parsed);
17847
- }
17848
- function normalizeExtraProviderOptions(value) {
17849
- if (value == null) {
17850
- return void 0;
17851
- }
17852
- if (typeof value === "string") {
17853
- return parseExtraProviderOptionsText(value);
17854
- }
17855
- if (typeof value !== "object" || Array.isArray(value)) {
17856
- throw new Error("Extra provider options must be a JSON object.");
17857
- }
17858
- return value;
17859
- }
17860
- function resolveLLMChatV2ExtraProviderOptions(data, inputs) {
17861
- if (!data.useExtraProviderOptionsInput) {
17862
- return parseExtraProviderOptionsText(data.extraProviderOptions ?? "");
17863
- }
17864
- return normalizeExtraProviderOptions(coerceTypeOptional(inputs["extraProviderOptions"], "object"));
17865
- }
17866
- function resolveProviderOptions(data, inputs) {
17867
- const providerOptions = {};
17868
- const extraProviderOptions = resolveLLMChatV2ExtraProviderOptions(data, inputs);
17869
- if (extraProviderOptions) {
17870
- providerOptions[data.provider] = extraProviderOptions;
17871
- }
17872
- if (data.provider === "openai") {
17873
- const previousResponseId = data.useOpenAIPreviousResponseIdInput && inputs["previousResponseId"] != null ? coerceTypeOptional(inputs["previousResponseId"], "string") : data.openAIPreviousResponseId;
17874
- const openAIOptions = {
17875
- ...data.openAIReasoningEffort ? { reasoningEffort: data.openAIReasoningEffort } : {},
17876
- ...data.openAIReasoningSummary ? { reasoningSummary: data.openAIReasoningSummary } : {},
17877
- ...(previousResponseId == null ? void 0 : previousResponseId.trim()) ? { previousResponseId: previousResponseId.trim() } : {}
17878
- };
17879
- if (Object.keys(openAIOptions).length > 0) {
17880
- providerOptions.openai = {
17881
- ...providerOptions.openai ?? {},
17882
- ...openAIOptions
17883
- };
17884
- }
17885
- }
17886
- if (data.provider === "anthropic") {
17887
- const thinkingBudget = data.useAnthropicThinkingBudgetInput && inputs["anthropicThinkingBudget"] != null ? coerceTypeOptional(inputs["anthropicThinkingBudget"], "number") : data.anthropicThinkingBudget;
17888
- const anthropicOptions = {
17889
- ...data.anthropicEffort ? { effort: data.anthropicEffort } : {},
17890
- ...data.anthropicThinkingMode === "enabled" ? {
17891
- thinking: {
17892
- type: "enabled",
17893
- ...thinkingBudget != null ? { budgetTokens: thinkingBudget } : {}
17894
- }
17895
- } : data.anthropicThinkingMode === "disabled" ? { thinking: { type: "disabled" } } : data.anthropicThinkingMode === "adaptive" ? { thinking: { type: "adaptive" } } : {}
17896
- };
17897
- if (Object.keys(anthropicOptions).length > 0) {
17898
- providerOptions.anthropic = {
17899
- ...providerOptions.anthropic ?? {},
17900
- ...anthropicOptions
17901
- };
17902
- }
17903
- }
17904
- if (data.provider === "google") {
17905
- const thinkingBudget = data.useGoogleThinkingBudgetInput && inputs["googleThinkingBudget"] != null ? coerceTypeOptional(inputs["googleThinkingBudget"], "number") : data.googleThinkingBudget;
17906
- const thinkingConfig = {
17907
- ...thinkingBudget != null ? { thinkingBudget } : {},
17908
- ...data.googleThinkingLevel ? { thinkingLevel: data.googleThinkingLevel } : {},
17909
- ...data.googleIncludeThoughts ? { includeThoughts: true } : {}
17910
- };
17911
- const googleOptions = {
17912
- ...Object.keys(thinkingConfig).length > 0 ? { thinkingConfig } : {}
17913
- };
17914
- if (Object.keys(googleOptions).length > 0) {
17915
- providerOptions.google = {
17916
- ...providerOptions.google ?? {},
17917
- ...googleOptions
17918
- };
17919
- }
17920
- }
17921
- return Object.keys(providerOptions).length > 0 ? providerOptions : void 0;
17922
- }
17923
- function resolveLLMChatV2RuntimeProviderOptions(data, inputs) {
17924
- const providerOptions = applyLLMChatV2ParallelToolCallProviderOptions({
17925
- provider: data.provider,
17926
- useToolCalling: data.useToolCalling,
17927
- parallelToolCalls: data.parallelToolCalls,
17928
- providerOptions: resolveProviderOptions(data, inputs)
17929
- });
17930
- return providerOptions != null && Object.keys(providerOptions).length > 0 ? providerOptions : void 0;
17931
- }
17932
- function resolveLLMChatV2ToolChoice(data) {
17933
- var _a;
17934
- if (!data.useToolCalling || !data.toolChoice) {
17935
- return void 0;
17936
- }
17937
- if (data.toolChoice === "function") {
17938
- const toolName = (_a = data.toolChoiceFunction) == null ? void 0 : _a.trim();
17939
- if (!toolName) {
17940
- throw new Error("Tool name is required when Tool choice is Specific tool.");
17941
- }
17942
- return {
17943
- type: "tool",
17944
- toolName
17945
- };
17946
- }
17947
- return data.toolChoice;
17948
- }
17949
- function normalizeStopSequences(stopSequences) {
17950
- const normalized = (stopSequences ?? []).filter((sequence) => sequence.length > 0);
17951
- return normalized.length > 0 ? normalized : void 0;
17952
- }
17953
- function resolveStopSequences(data, inputs) {
17954
- const stopSequences = data.useStopSequencesInput && inputs["stopSequences"] != null ? coerceTypeOptional(inputs["stopSequences"], "string[]") : data.stopSequences;
17955
- return normalizeStopSequences(stopSequences);
17956
- }
17957
- function resolveLLMChatV2GenerationParameters(data, inputs) {
17958
- return {
17959
- maxTokens: getInputOrData(data, inputs, "maxTokens", "number"),
17960
- temperature: getInputOrData(data, inputs, "temperature", "number"),
17961
- topP: getInputOrData(data, inputs, "topP", "number"),
17962
- topK: getInputOrData(data, inputs, "topK", "number"),
17963
- presencePenalty: getInputOrData(data, inputs, "presencePenalty", "number"),
17964
- frequencyPenalty: getInputOrData(data, inputs, "frequencyPenalty", "number"),
17965
- stopSequences: resolveStopSequences(data, inputs),
17966
- seed: getInputOrData(data, inputs, "seed", "number")
17967
- };
17968
- }
17969
- function resolveLLMChatV2BuiltInTools(data, context, config, apiKey) {
17970
- switch (data.provider) {
17971
- case "openai": {
17972
- if (!data.enableOpenAIWebSearch && !data.enableOpenAICodeInterpreter) {
17973
- return void 0;
17974
- }
17975
- const provider = (0, import_openai4.createOpenAI)({
17976
- apiKey: apiKey || context.settings.openAiApiKey || context.settings.openAiKey || void 0,
17977
- organization: context.settings.openAiOrganization || void 0,
17978
- baseURL: void 0,
17979
- headers: config.headers
17980
- });
17981
- const tools = {};
17982
- if (data.enableOpenAIWebSearch) {
17983
- tools.openaiWebSearch = provider.tools.webSearch({
17984
- searchContextSize: data.openAIWebSearchContextSize
17985
- });
17986
- }
17987
- if (data.enableOpenAICodeInterpreter) {
17988
- tools.openaiCodeInterpreter = provider.tools.codeInterpreter();
17989
- }
17990
- return tools;
17991
- }
17992
- case "google": {
17993
- if (!data.enableGoogleSearchGrounding && !data.enableGoogleUrlContext) {
17994
- return void 0;
17995
- }
17996
- const provider = (0, import_google3.createGoogleGenerativeAI)({
17997
- apiKey: apiKey || context.settings.googleApiKey || context.getPluginConfig("googleApiKey") || void 0,
17998
- baseURL: void 0,
17999
- headers: config.headers
18000
- });
18001
- const tools = {};
18002
- if (data.enableGoogleSearchGrounding) {
18003
- tools.googleSearch = provider.tools.googleSearch({});
18004
- }
18005
- if (data.enableGoogleUrlContext) {
18006
- tools.googleUrlContext = provider.tools.urlContext({});
18007
- }
18008
- return tools;
18009
- }
18010
- case "anthropic":
18011
- return void 0;
18012
- case "custom":
18013
- return void 0;
18014
- }
18015
- }
18016
-
18017
- // src/model/chat-v2/llmChatV2NodeRuntime.ts
18018
- function resolveLLMChatV2BaseURL(data, inputs) {
18019
- var _a;
18020
- return data.provider === "custom" ? ((_a = getInputOrData(data, inputs, "customProviderBaseURL", "string", "useCustomProviderBaseURLInput")) == null ? void 0 : _a.trim()) || void 0 : void 0;
18021
- }
18022
- async function resolveLLMChatV2RuntimeConfig(params) {
18023
- const { data, nodeId, inputs, context } = params;
18024
- const profileInput = inputs["llmProfile"];
18025
- if (data.configurationMode === "profile" && profileInput == null) {
18026
- throw new Error("LLM Profile input is required when Configuration is From profile.");
18027
- }
18028
- const profile = data.configurationMode === "profile" ? normalizeLLMProfileValue(profileInput == null ? void 0 : profileInput.value) : void 0;
18029
- const effectiveData = profile ? applyLLMProfileToNodeData(data, profile) : data;
18030
- if (hasLLMChatV2ToolResponseFormatConflict(effectiveData)) {
18031
- throw new Error(LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY.paragraphs[0]);
18032
- }
18033
- const provider = parseChatV2Provider(effectiveData.provider);
18034
- const modelId = getInputOrData(effectiveData, inputs, "model", "string");
18035
- const baseURL = resolveLLMChatV2BaseURL(effectiveData, inputs);
18036
- const nodeHeaders = resolveLLMChatV2Headers(effectiveData, inputs);
18037
- const credential = (profile == null ? void 0 : profile.credential) ?? resolveChatV2Credential({
18038
- provider,
18039
- context,
18040
- apiKeySource: effectiveData.apiKeySource === "input" ? "input" : "configured",
18041
- inputs,
18042
- customProgrammaticName: effectiveData.customProviderApiKeyProgrammaticName,
18043
- customEnvironmentName: effectiveData.customProviderApiKeyEnvVarName
18044
- });
18045
- const apiKey = credential.value;
18046
- const requestBodies = effectiveData.outputRequestStatus ? [] : void 0;
18047
- const resolvedProvider = await createResolvedChatV2Provider({
18048
- provider,
18049
- modelId,
18050
- context,
18051
- baseURL,
18052
- headers: nodeHeaders,
18053
- credential,
18054
- onRequestBody: requestBodies == null ? void 0 : (body) => requestBodies.push(body)
18055
- });
18056
- const providerConfig = resolvedProvider.config;
18057
- const model = resolvedProvider.model;
18058
- const prompt = inputs["prompt"];
18059
- const systemPrompt = inputs["systemPrompt"];
18060
- const functions = effectiveData.useToolCalling && inputs["functions"] != null ? coerceTypeOptional(inputs["functions"], "gpt-function[]") : void 0;
18061
- const toolChoice = resolveLLMChatV2ToolChoice(effectiveData);
18062
- const responseFormatParameters = resolveChatV2ResponseFormatParameters(effectiveData, inputs);
18063
- const providerOptions = mergeCustomProviderResponseFormatOptions(
18064
- provider,
18065
- resolveLLMChatV2RuntimeProviderOptions(effectiveData, inputs),
18066
- responseFormatParameters
18067
- );
18068
- const generationParameters = resolveLLMChatV2GenerationParameters(effectiveData, inputs);
18069
- const runOptions = {
18070
- provider,
18071
- model,
18072
- modelId,
18073
- prompt,
18074
- systemPrompt,
18075
- functions,
18076
- additionalTools: resolveLLMChatV2BuiltInTools(effectiveData, context, providerConfig, apiKey),
18077
- ...generationParameters,
18078
- responseOutput: createChatV2ResponseOutput(responseFormatParameters, provider),
18079
- responseFormat: responseFormatParameters == null ? void 0 : responseFormatParameters.responseFormat,
18080
- outputUsage: effectiveData.outputUsage,
18081
- outputReasoning: effectiveData.outputReasoning,
18082
- outputRequestStatus: effectiveData.outputRequestStatus,
18083
- includeFunctionCalls: shouldIncludeLLMChatV2ToolCalls(effectiveData),
18084
- emitPartialOutputs: effectiveData.useAsGraphPartialOutput,
18085
- providerOptions,
18086
- toolChoice,
18087
- anthropicCacheControlTtl: provider === "anthropic" ? effectiveData.anthropicCacheControlTtl || void 0 : void 0,
18088
- requestBodies,
18089
- retryOnNon200: effectiveData.retryOnNon200,
18090
- retryOnNon200RepeatTimes: effectiveData.retryOnNon200RepeatTimes,
18091
- retryOnNon200CooldownMs: effectiveData.retryOnNon200CooldownMs,
18092
- context
18093
- };
18094
- const editorCache = effectiveData.cache ? context.editorExecutionCache : void 0;
18095
- const { cacheKey, cachedOutputs } = resolveLLMChatV2EditorCache({
18096
- apiKey,
18097
- data: effectiveData,
18098
- editorCache,
18099
- functions,
18100
- generationParameters,
18101
- modelId,
18102
- nodeId,
18103
- prompt,
18104
- provider,
18105
- providerConfig,
18106
- providerOptions,
18107
- responseFormatParameters,
18108
- systemPrompt,
18109
- toolChoice
18110
- });
18111
- return {
18112
- providerProfile: resolvedProvider.profile,
18113
- runOptions,
18114
- functions,
18115
- cacheKey,
18116
- cachedOutputs,
18117
- editorCache,
18118
- shouldAutoContinueToolCalls: !!effectiveData.autoContinueToolCalls && effectiveData.useToolCalling,
18119
- maxToolRounds: effectiveData.maxToolRounds ?? 3
18120
- };
18121
- }
18122
-
18123
- // src/model/chat-v2/aiSdkBridge.ts
18124
- var import_ai2 = require("ai");
18125
-
18126
- // src/model/chat/aiSdkStreaming.ts
18127
- function buildResponseText(textBlocks, dedupeDuplicateTextBlocks) {
18128
- const blockTexts = Array.from(textBlocks.values()).filter((text) => text.length > 0);
18129
- if (blockTexts.length === 0) {
18130
- return "";
18131
- }
18132
- if (dedupeDuplicateTextBlocks && blockTexts.length > 1) {
18133
- const longestText = blockTexts.reduce((longest, text) => text.length > longest.length ? text : longest);
18134
- if (blockTexts.every((text) => longestText.startsWith(text))) {
18135
- return longestText;
18136
- }
18137
- }
18138
- return blockTexts.join("");
18139
- }
18140
- async function consumeAiSdkStream(fullStream, onPartialOutputs, options2 = {}) {
18141
- let responseText = "";
18142
- let reasoning = "";
18143
- const functionCalls = [];
18144
- let usage;
18145
- const textBlocks = /* @__PURE__ */ new Map();
18146
- for await (const part of fullStream) {
18147
- switch (part.type) {
18148
- case "text-start": {
18149
- if (!textBlocks.has(part.id)) {
18150
- textBlocks.set(part.id, "");
18151
- }
18152
- break;
18153
- }
18154
- case "text-delta": {
18155
- textBlocks.set(part.id, `${textBlocks.get(part.id) ?? ""}${part.text}`);
18156
- responseText = buildResponseText(textBlocks, !!options2.dedupeDuplicateTextBlocks);
18157
- onPartialOutputs(responseText, functionCalls);
18158
- break;
18159
- }
18160
- case "reasoning-delta": {
18161
- reasoning += part.text;
18162
- break;
18163
- }
18164
- case "tool-call": {
18165
- functionCalls.push({
18166
- type: "function",
18167
- id: part.toolCallId,
18168
- name: part.toolName,
18169
- arguments: JSON.stringify(part.input),
18170
- lastParsedArguments: part.input
18171
- });
18172
- onPartialOutputs(responseText, functionCalls);
18173
- break;
18174
- }
18175
- case "finish": {
18176
- usage = part.totalUsage;
18177
- break;
18178
- }
18179
- case "error": {
18180
- throw part.error instanceof Error ? part.error : new Error(String(part.error));
18181
- }
18182
- }
18183
- }
18184
- return { responseText, functionCalls, usage, reasoning };
18185
- }
18186
-
18187
- // src/model/chat-v2/aiSdkBridge.ts
18188
- function keepPromiseHandled(value) {
18189
- const promise = Promise.resolve(value);
18190
- void promise.catch(() => void 0);
18191
- return promise;
18192
- }
18193
- function isPromiseLike(value) {
18194
- return value != null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
18195
- }
18196
- function markOptionalPromiseHandled(value) {
18197
- if (isPromiseLike(value)) {
18198
- void keepPromiseHandled(value);
18199
- }
18200
- }
18201
- function defaultStreamExecutor(args) {
18202
- const result = (0, import_ai2.streamText)(args);
18203
- return {
18204
- fullStream: result.fullStream,
18205
- finishReason: "finishReason" in result ? keepPromiseHandled(
18206
- Promise.resolve(result.finishReason).then((value) => value == null ? void 0 : String(value))
18207
- ) : void 0,
18208
- output: args.output != null && "output" in result ? keepPromiseHandled(Promise.resolve(result.output)) : void 0,
18209
- providerMetadata: "providerMetadata" in result ? keepPromiseHandled(
18210
- Promise.resolve(result.providerMetadata)
18211
- ) : void 0,
18212
- requestStatus: 200,
18213
- usage: "usage" in result ? keepPromiseHandled(Promise.resolve(result.usage)) : void 0
18214
- };
18215
- }
18216
- async function defaultGenerateExecutor(args) {
18217
- return await (0, import_ai2.generateText)(args);
18218
- }
18219
- async function resolveOptionalValue(value) {
18220
- return value == null ? void 0 : await value;
18221
- }
18222
- async function resolveOptionalStructuredOutput(value) {
18223
- if (value == null) {
18224
- return void 0;
18225
- }
18226
- try {
18227
- return await value;
18228
- } catch {
18229
- return void 0;
18230
- }
18231
- }
18232
- async function resolveGenerateStructuredOutput(result, responseOutput, finishReason) {
18233
- if (responseOutput == null || finishReason != null && finishReason !== "stop") {
18234
- return void 0;
18235
- }
18236
- try {
18237
- return await resolveOptionalStructuredOutput(result.output);
18238
- } catch {
18239
- return void 0;
18240
- }
18241
- }
18242
- function recoverGenerateStructuredOutputError(error, options2, toolCalls) {
18243
- if (options2.responseOutput == null || !isChatV2StructuredResponseFormat(options2.responseFormat)) {
18244
- return void 0;
18245
- }
18246
- if (!import_ai2.NoObjectGeneratedError.isInstance(error)) {
18247
- return void 0;
18248
- }
18249
- if (typeof error.text !== "string") {
18250
- return void 0;
18251
- }
18252
- const rawText = error.text;
18253
- const responseText = collapseRepeatedStructuredJsonText(rawText);
18254
- return {
18255
- responseText,
18256
- structuredOutput: void 0,
18257
- functionCalls: toStreamedFunctionCalls(toolCalls),
18258
- usage: error.usage,
18259
- reasoning: "",
18260
- finishReason: error.finishReason == null ? void 0 : String(error.finishReason),
18261
- providerMetadata: void 0,
18262
- requestStatus: void 0
18263
- };
18264
- }
18265
- function attachGenerateStepToolCallCollector(args) {
18266
- const toolCalls = [];
18267
- const previousOnStepFinish = args.onStepFinish;
18268
- args.onStepFinish = async (event) => {
18269
- const stepToolCalls = event.toolCalls;
18270
- if (stepToolCalls != null) {
18271
- toolCalls.push(...stepToolCalls);
18272
- }
18273
- await (previousOnStepFinish == null ? void 0 : previousOnStepFinish(event));
18274
- };
18275
- return toolCalls;
18276
- }
18277
- function collapseRepeatedStructuredJsonText(responseText) {
18278
- if (responseText.length === 0 || responseText.length % 2 !== 0) {
18279
- return responseText;
18280
- }
18281
- const midpoint = responseText.length / 2;
18282
- const firstHalf = responseText.slice(0, midpoint);
18283
- const firstNonWhitespaceCharacter = firstHalf.trimStart()[0];
18284
- if (firstHalf !== responseText.slice(midpoint)) {
18285
- return responseText;
18286
- }
18287
- if (firstNonWhitespaceCharacter !== "{" && firstNonWhitespaceCharacter !== "[") {
18288
- return responseText;
18289
- }
18290
- try {
18291
- JSON.parse(firstHalf);
18292
- return firstHalf;
18293
- } catch {
18294
- return responseText;
18295
- }
18296
- }
18297
- function buildTextArgs(options2) {
18298
- const args = {
18299
- model: options2.model,
18300
- messages: options2.messages,
18301
- maxRetries: options2.maxRetries ?? 0
18302
- };
18303
- if (options2.tools !== void 0) args.tools = options2.tools;
18304
- if (options2.maxTokens !== void 0) args.maxOutputTokens = options2.maxTokens;
18305
- if (options2.temperature !== void 0) args.temperature = options2.temperature;
18306
- if (options2.topP !== void 0) args.topP = options2.topP;
18307
- if (options2.topK !== void 0) args.topK = options2.topK;
18308
- if (options2.presencePenalty !== void 0) args.presencePenalty = options2.presencePenalty;
18309
- if (options2.frequencyPenalty !== void 0) args.frequencyPenalty = options2.frequencyPenalty;
18310
- if (options2.stopSequences !== void 0) args.stopSequences = options2.stopSequences;
18311
- if (options2.seed !== void 0) args.seed = options2.seed;
18312
- if (options2.responseOutput !== void 0) args.output = options2.responseOutput;
18313
- if (options2.providerOptions !== void 0) args.providerOptions = options2.providerOptions;
18314
- if (options2.toolChoice !== void 0) args.toolChoice = options2.toolChoice;
18315
- if (options2.abortSignal !== void 0) args.abortSignal = options2.abortSignal;
18316
- return args;
18317
- }
18318
- function toStreamedFunctionCalls(toolCalls) {
18319
- return (toolCalls ?? []).map((toolCall) => ({
18320
- type: "function",
18321
- id: toolCall.toolCallId,
18322
- name: toolCall.toolName,
18323
- arguments: JSON.stringify(toolCall.input),
18324
- lastParsedArguments: toolCall.input
18325
- }));
18326
- }
18327
- async function resolveGenerateReasoning(result) {
18328
- var _a;
18329
- const reasoningText = await resolveOptionalValue(result.reasoningText);
18330
- if (reasoningText != null && reasoningText.trim().length > 0) {
18331
- return reasoningText;
18332
- }
18333
- return ((_a = await resolveOptionalValue(result.reasoning)) == null ? void 0 : _a.map((part) => part.text).join("")) ?? "";
18334
- }
18335
- async function executeStream(options2, executor) {
18336
- const args = buildTextArgs(options2);
18337
- const handle = await executor(args);
18338
- markOptionalPromiseHandled(handle.finishReason);
18339
- markOptionalPromiseHandled(handle.output);
18340
- markOptionalPromiseHandled(handle.providerMetadata);
18341
- markOptionalPromiseHandled(handle.requestStatus);
18342
- markOptionalPromiseHandled(handle.usage);
18343
- const isStructuredOutput = isChatV2StructuredResponseFormat(options2.responseFormat);
18344
- const streamed = await consumeAiSdkStream(
18345
- handle.fullStream,
18346
- (text, functionCalls) => {
18347
- var _a;
18348
- (_a = options2.onPartialOutput) == null ? void 0 : _a.call(options2, {
18349
- text: isStructuredOutput ? collapseRepeatedStructuredJsonText(text) : text,
18350
- functionCalls
18351
- });
18352
- },
18353
- {
18354
- dedupeDuplicateTextBlocks: isStructuredOutput
18355
- }
18356
- );
18357
- const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(streamed.responseText) : streamed.responseText;
18358
- return {
18359
- responseText,
18360
- structuredOutput: options2.responseOutput != null ? await resolveOptionalStructuredOutput(handle.output) : void 0,
18361
- functionCalls: streamed.functionCalls,
18362
- usage: streamed.usage ?? await resolveOptionalValue(handle.usage),
18363
- reasoning: streamed.reasoning,
18364
- finishReason: await resolveOptionalValue(handle.finishReason),
18365
- providerMetadata: await resolveOptionalValue(handle.providerMetadata),
18366
- requestStatus: await resolveOptionalValue(handle.requestStatus)
18367
- };
18368
- }
18369
- async function streamChatV2(options2) {
18370
- return executeStream(options2, options2.executeStream ?? defaultStreamExecutor);
18371
- }
18372
- async function generateChatV2(options2) {
18373
- const args = buildTextArgs(options2);
18374
- const stepToolCalls = attachGenerateStepToolCallCollector(args);
18375
- let result;
18376
- try {
18377
- result = await (options2.executeGenerate ?? defaultGenerateExecutor)(args);
18378
- } catch (error) {
18379
- const recovered = recoverGenerateStructuredOutputError(error, options2, stepToolCalls);
18380
- if (recovered != null) {
18381
- return recovered;
18382
- }
18383
- throw error;
18384
- }
18385
- const isStructuredOutput = isChatV2StructuredResponseFormat(options2.responseFormat);
18386
- const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(result.text) : result.text;
18387
- const finishReason = await resolveOptionalValue(result.finishReason);
18388
- return {
18389
- responseText,
18390
- structuredOutput: await resolveGenerateStructuredOutput(result, options2.responseOutput, finishReason),
18391
- functionCalls: toStreamedFunctionCalls(
18392
- result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls
18393
- ),
18394
- usage: await resolveOptionalValue(result.totalUsage) ?? await resolveOptionalValue(result.usage),
18395
- reasoning: await resolveGenerateReasoning(result),
18396
- finishReason,
18397
- providerMetadata: await resolveOptionalValue(result.providerMetadata),
18398
- requestStatus: await resolveOptionalValue(result.requestStatus)
18399
- };
18009
+ const isStructuredOutput = isChatV2StructuredResponseFormat(options2.responseFormat);
18010
+ const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(result.text) : result.text;
18011
+ const finishReason = await resolveOptionalValue(result.finishReason);
18012
+ return {
18013
+ responseText,
18014
+ structuredOutput: await resolveGenerateStructuredOutput(result, options2.responseOutput, finishReason),
18015
+ functionCalls: toStreamedFunctionCalls(
18016
+ result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls
18017
+ ),
18018
+ usage: await resolveOptionalValue(result.totalUsage) ?? await resolveOptionalValue(result.usage),
18019
+ reasoning: await resolveGenerateReasoning(result),
18020
+ finishReason,
18021
+ providerMetadata: await resolveOptionalValue(result.providerMetadata),
18022
+ requestStatus: await resolveOptionalValue(result.requestStatus)
18023
+ };
18400
18024
  }
18401
18025
 
18402
18026
  // src/model/chat-v2/chatV2CallObserver.ts
@@ -18524,6 +18148,8 @@ function notifyChatV2CallFinished(options2, params) {
18524
18148
  const event = {
18525
18149
  callId: params.callId,
18526
18150
  attemptIndex: params.attemptIndex,
18151
+ ...options2.profileIndex == null ? {} : { profileIndex: options2.profileIndex },
18152
+ ...options2.roundIndex == null ? {} : { roundIndex: options2.roundIndex },
18527
18153
  nodeId,
18528
18154
  processId,
18529
18155
  provider: options2.provider,
@@ -18629,10 +18255,7 @@ function applyAnthropicCacheBreakpoint(parts, enabled, ttl) {
18629
18255
  if (lastPart == null) {
18630
18256
  return parts;
18631
18257
  }
18632
- lastPart.providerOptions = mergeProviderMetadata(
18633
- lastPart.providerOptions,
18634
- getAnthropicCacheMetadata(true, ttl)
18635
- );
18258
+ lastPart.providerOptions = mergeProviderMetadata(lastPart.providerOptions, getAnthropicCacheMetadata(true, ttl));
18636
18259
  return parts;
18637
18260
  }
18638
18261
  async function chatMessagesToModelMessages(messages, options2) {
@@ -18647,6 +18270,14 @@ async function chatMessagesToModelMessages(messages, options2) {
18647
18270
  });
18648
18271
  break;
18649
18272
  }
18273
+ case "developer": {
18274
+ result.push({
18275
+ role: "system",
18276
+ content: stringifyParts(msg.message),
18277
+ providerOptions: options2.provider === "anthropic" ? getAnthropicCacheMetadata(!!msg.isCacheBreakpoint, options2.anthropicCacheControlTtl) : void 0
18278
+ });
18279
+ break;
18280
+ }
18650
18281
  case "user": {
18651
18282
  const parts = Array.isArray(msg.message) ? msg.message : [msg.message];
18652
18283
  if (parts.length === 1 && typeof parts[0] === "string" && !msg.isCacheBreakpoint) {
@@ -18743,6 +18374,14 @@ function chatV2ToolsToAiSdk(functions) {
18743
18374
  return rivetToolsToAiSdk(functions);
18744
18375
  }
18745
18376
 
18377
+ // src/model/chat-v2/chatV2Types.ts
18378
+ function shouldOutputChatV2RequestError(options2) {
18379
+ return options2.outputRequestError ?? options2.outputRequestStatus ?? false;
18380
+ }
18381
+ function shouldOutputChatV2RequestBody(options2) {
18382
+ return options2.outputRequestBody ?? options2.outputRequestStatus ?? false;
18383
+ }
18384
+
18746
18385
  // src/model/chat-v2/chatV2RequestPlan.ts
18747
18386
  function buildChatV2RequestPlan(options2) {
18748
18387
  const shouldStream = options2.emitPartialOutputs !== false;
@@ -18776,7 +18415,9 @@ function buildChatV2RequestPlan(options2) {
18776
18415
  output: {
18777
18416
  outputUsage: options2.outputUsage,
18778
18417
  outputReasoning: options2.outputReasoning,
18779
- outputRequestStatus: options2.outputRequestStatus,
18418
+ outputRequestStatus: options2.outputRequestStatus === true,
18419
+ outputRequestError: shouldOutputChatV2RequestError(options2),
18420
+ outputRequestBody: shouldOutputChatV2RequestBody(options2),
18780
18421
  includeFunctionCalls: options2.includeFunctionCalls,
18781
18422
  functionCallMode: options2.functionCallMode
18782
18423
  }
@@ -19186,6 +18827,8 @@ function createChatV2CommonOutputs({
19186
18827
  outputUsage,
19187
18828
  outputReasoning,
19188
18829
  outputRequestStatus,
18830
+ outputRequestError,
18831
+ outputRequestBody,
19189
18832
  includeFunctionCalls,
19190
18833
  functionCallMode,
19191
18834
  retryOnNon200,
@@ -19196,16 +18839,13 @@ function createChatV2CommonOutputs({
19196
18839
  ["in-messages"]: { type: "chat-message[]", value: requestMessages },
19197
18840
  ["all-messages"]: createAssistantMessagesOutput(requestMessages, response, functionCalls, {
19198
18841
  functionCallMode
19199
- }),
19200
- ["responseTokens"]: { type: "number", value: (usage == null ? void 0 : usage.completionTokens) ?? 0 }
18842
+ })
19201
18843
  };
19202
- if (functionCalls.length > 0) {
19203
- outputs["function-calls"] = {
18844
+ if (includeFunctionCalls) {
18845
+ outputs["function-calls"] = functionCalls.length > 0 ? {
19204
18846
  type: "object[]",
19205
18847
  value: functionCalls.map(toFunctionCallOutputValue)
19206
- };
19207
- } else if (includeFunctionCalls) {
19208
- outputs["function-calls"] = createControlFlowExcludedOutput();
18848
+ } : createControlFlowExcludedOutput();
19209
18849
  }
19210
18850
  if (outputUsage) {
19211
18851
  outputs["usage"] = {
@@ -19229,17 +18869,24 @@ function createChatV2CommonOutputs({
19229
18869
  "number[]",
19230
18870
  requestStatuses.length > 0 ? requestStatuses : [requestStatus ?? 200]
19231
18871
  );
19232
- outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = createChatV2RetryAttemptOutput("string[]", requestErrors);
19233
18872
  } else {
19234
18873
  outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = {
19235
18874
  type: "number",
19236
18875
  value: requestStatus ?? 200
19237
18876
  };
18877
+ }
18878
+ }
18879
+ if (shouldOutputChatV2RequestError({ outputRequestStatus, outputRequestError })) {
18880
+ if (retryOnNon200) {
18881
+ outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = createChatV2RetryAttemptOutput("string[]", requestErrors);
18882
+ } else {
19238
18883
  outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = responseError != null ? {
19239
18884
  type: "string",
19240
18885
  value: responseError
19241
18886
  } : createControlFlowExcludedOutput();
19242
18887
  }
18888
+ }
18889
+ if (shouldOutputChatV2RequestBody({ outputRequestStatus, outputRequestBody })) {
19243
18890
  outputs[CHAT_V2_REQUEST_BODY_PORT_ID] = createChatV2RequestBodyOutput(requestBodies);
19244
18891
  }
19245
18892
  return outputs;
@@ -19253,21 +18900,13 @@ function createChatV2ProviderFailureOutputs({
19253
18900
  requestBodies,
19254
18901
  outputUsage,
19255
18902
  outputReasoning,
18903
+ outputRequestStatus,
18904
+ outputRequestError,
18905
+ outputRequestBody,
19256
18906
  includeFunctionCalls,
19257
18907
  retryOnNon200
19258
18908
  }) {
19259
18909
  const outputs = {
19260
- [CHAT_V2_REQUEST_ERROR_PORT_ID]: retryOnNon200 ? createChatV2RetryAttemptOutput("string[]", requestErrors) : {
19261
- type: "string",
19262
- value: responseError
19263
- },
19264
- [CHAT_V2_REQUEST_STATUS_PORT_ID]: retryOnNon200 ? createChatV2RetryAttemptOutput("number[]", requestStatuses) : responseStatus == null ? {
19265
- type: "control-flow-excluded",
19266
- value: void 0
19267
- } : {
19268
- type: "number",
19269
- value: responseStatus
19270
- },
19271
18910
  ["response"]: createControlFlowExcludedOutput(),
19272
18911
  ["in-messages"]: {
19273
18912
  type: "chat-message[]",
@@ -19276,280 +18915,1320 @@ function createChatV2ProviderFailureOutputs({
19276
18915
  ["all-messages"]: {
19277
18916
  type: "chat-message[]",
19278
18917
  value: requestMessages
19279
- },
19280
- ["responseTokens"]: createControlFlowExcludedOutput()
18918
+ }
19281
18919
  };
19282
- outputs[CHAT_V2_REQUEST_BODY_PORT_ID] = createChatV2RequestBodyOutput(requestBodies);
18920
+ if (outputRequestStatus) {
18921
+ outputs[CHAT_V2_REQUEST_STATUS_PORT_ID] = retryOnNon200 ? createChatV2RetryAttemptOutput("number[]", requestStatuses) : responseStatus == null ? createControlFlowExcludedOutput() : {
18922
+ type: "number",
18923
+ value: responseStatus
18924
+ };
18925
+ }
18926
+ if (shouldOutputChatV2RequestError({ outputRequestStatus, outputRequestError })) {
18927
+ outputs[CHAT_V2_REQUEST_ERROR_PORT_ID] = retryOnNon200 ? createChatV2RetryAttemptOutput("string[]", requestErrors) : {
18928
+ type: "string",
18929
+ value: responseError
18930
+ };
18931
+ }
18932
+ if (shouldOutputChatV2RequestBody({ outputRequestStatus, outputRequestBody })) {
18933
+ outputs[CHAT_V2_REQUEST_BODY_PORT_ID] = createChatV2RequestBodyOutput(requestBodies);
18934
+ }
19283
18935
  if (includeFunctionCalls) {
19284
18936
  outputs["function-calls"] = createControlFlowExcludedOutput();
19285
18937
  }
19286
- if (outputUsage) {
19287
- outputs["usage"] = createControlFlowExcludedOutput();
18938
+ if (outputUsage) {
18939
+ outputs["usage"] = createControlFlowExcludedOutput();
18940
+ }
18941
+ if (outputReasoning) {
18942
+ outputs["reasoning"] = createControlFlowExcludedOutput();
18943
+ }
18944
+ return outputs;
18945
+ }
18946
+
18947
+ // src/model/chat-v2/chatV2Pipeline.ts
18948
+ var ChatV2RetryFailure = class extends Error {
18949
+ constructor(error, requestStatuses, requestErrors) {
18950
+ super("Chat v2 retry attempts failed");
18951
+ this.error = error;
18952
+ this.requestStatuses = requestStatuses;
18953
+ this.requestErrors = requestErrors;
18954
+ this.name = "ChatV2RetryFailure";
18955
+ }
18956
+ };
18957
+ function isChatV2RetryFailure(error) {
18958
+ return error instanceof ChatV2RetryFailure;
18959
+ }
18960
+ function getProviderFailureMessage(error) {
18961
+ try {
18962
+ if (error instanceof Error && typeof error.message === "string") {
18963
+ return error.message;
18964
+ }
18965
+ } catch {
18966
+ return "Provider request failed with unreadable error metadata.";
18967
+ }
18968
+ try {
18969
+ return String(error);
18970
+ } catch {
18971
+ return "Provider request failed with unreadable error metadata.";
18972
+ }
18973
+ }
18974
+ function buildNon200StatusError(statusCode) {
18975
+ const error = new Error(`Provider request returned non-200 status: ${statusCode}`);
18976
+ error.name = "AI_APICallError";
18977
+ error.statusCode = statusCode;
18978
+ return error;
18979
+ }
18980
+ function normalizeProviderFailureMessage(error, options2) {
18981
+ return getProviderFailureMessage(normalizeProviderFailure(error, options2));
18982
+ }
18983
+ function normalizeProviderFailure(error, options2) {
18984
+ try {
18985
+ return normalizeChatV2ProviderError(error, {
18986
+ provider: options2.provider,
18987
+ modelId: options2.modelId
18988
+ });
18989
+ } catch {
18990
+ return error;
18991
+ }
18992
+ }
18993
+ function normalizeProviderFailureMessages(errors, options2) {
18994
+ return errors.map((error) => normalizeProviderFailureMessage(error, options2));
18995
+ }
18996
+ function notifyProviderAttempt(options2, attempt) {
18997
+ var _a;
18998
+ try {
18999
+ (_a = options2.onProviderAttempt) == null ? void 0 : _a.call(options2, attempt);
19000
+ } catch {
19001
+ }
19002
+ }
19003
+ async function runChatV2WithRetry(options2, chatOptions, retryPlan, signal, transportMode) {
19004
+ const requestStatuses = [];
19005
+ const requestErrors = [];
19006
+ for (let attempt = 0; ; attempt++) {
19007
+ const callId = createObservedChatV2CallId(options2);
19008
+ let callWasObserved = false;
19009
+ try {
19010
+ const result = transportMode === "generate" ? await generateChatV2(chatOptions) : await streamChatV2(chatOptions);
19011
+ const statusCode = result.requestStatus ?? 200;
19012
+ notifyChatV2CallFinished(options2, {
19013
+ callId,
19014
+ attemptIndex: attempt,
19015
+ outcome: statusCode === 200 ? "success" : "provider-failure",
19016
+ result
19017
+ });
19018
+ callWasObserved = true;
19019
+ notifyProviderAttempt(options2, {
19020
+ attemptIndex: attempt,
19021
+ outcome: statusCode === 200 ? "success" : "provider-failure",
19022
+ status: statusCode,
19023
+ ...statusCode === 200 ? {} : { error: buildNon200StatusError(statusCode) }
19024
+ });
19025
+ if (retryPlan.enabled) {
19026
+ requestStatuses.push(statusCode);
19027
+ }
19028
+ if (!retryPlan.enabled || statusCode === 200) {
19029
+ return { result, requestStatuses, requestErrors };
19030
+ }
19031
+ const responseError = buildNon200StatusError(statusCode);
19032
+ requestErrors.push(responseError);
19033
+ if (attempt >= retryPlan.repeatTimes) {
19034
+ return { result, requestStatuses, requestErrors, responseError };
19035
+ }
19036
+ await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
19037
+ } catch (error) {
19038
+ if (!callWasObserved) {
19039
+ notifyChatV2CallFinished(options2, {
19040
+ callId,
19041
+ attemptIndex: attempt,
19042
+ outcome: signal.aborted ? "aborted" : "provider-failure",
19043
+ error
19044
+ });
19045
+ }
19046
+ const statusCode = getChatV2ProviderErrorStatusCode(error);
19047
+ notifyProviderAttempt(options2, {
19048
+ attemptIndex: attempt,
19049
+ outcome: "provider-failure",
19050
+ ...statusCode == null ? {} : { status: statusCode },
19051
+ error
19052
+ });
19053
+ if (!retryPlan.enabled || statusCode == null || statusCode === 200) {
19054
+ throw error;
19055
+ }
19056
+ requestStatuses.push(statusCode);
19057
+ requestErrors.push(error);
19058
+ if (attempt >= retryPlan.repeatTimes) {
19059
+ throw new ChatV2RetryFailure(error, requestStatuses, requestErrors);
19060
+ }
19061
+ await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
19062
+ }
19063
+ }
19064
+ }
19065
+ function buildProviderFailureResult(requestMessages, options2, plan, normalizedError, rawError, requestStatuses, requestErrors) {
19066
+ if (!plan.output.outputRequestStatus && !plan.output.outputRequestError) {
19067
+ return void 0;
19068
+ }
19069
+ const statusCode = getChatV2ProviderErrorStatusCode(normalizedError);
19070
+ if (statusCode == null && !isChatV2ProviderApiCallError(rawError) && !isChatV2ProviderFetchError(rawError)) {
19071
+ return void 0;
19072
+ }
19073
+ const responseError = getProviderFailureMessage(normalizedError);
19074
+ const retryRequestStatuses = plan.retry.enabled ? requestStatuses.length > 0 ? requestStatuses : statusCode == null ? [] : [statusCode] : [];
19075
+ const retryRequestErrors = plan.retry.enabled ? requestErrors.length > 0 ? requestErrors : [responseError] : [];
19076
+ const commonOutputs = createChatV2ProviderFailureOutputs({
19077
+ requestMessages,
19078
+ responseStatus: statusCode,
19079
+ responseError,
19080
+ requestStatuses: retryRequestStatuses,
19081
+ requestErrors: retryRequestErrors,
19082
+ requestBodies: options2.requestBodies,
19083
+ outputUsage: plan.output.outputUsage,
19084
+ outputReasoning: plan.output.outputReasoning,
19085
+ outputRequestStatus: plan.output.outputRequestStatus,
19086
+ outputRequestError: plan.output.outputRequestError,
19087
+ outputRequestBody: plan.output.outputRequestBody,
19088
+ includeFunctionCalls: plan.output.includeFunctionCalls,
19089
+ retryOnNon200: plan.retry.enabled
19090
+ });
19091
+ const allMessagesOutput = commonOutputs["all-messages"];
19092
+ if ((allMessagesOutput == null ? void 0 : allMessagesOutput.type) !== "chat-message[]") {
19093
+ throw new Error("Chat v2 provider failure expected all-messages output to be chat-message[].");
19094
+ }
19095
+ return {
19096
+ commonOutputs,
19097
+ requestMessages,
19098
+ allMessages: allMessagesOutput.value,
19099
+ response: "",
19100
+ functionCalls: [],
19101
+ reasoning: "",
19102
+ usage: void 0,
19103
+ rawUsage: void 0,
19104
+ finishReason: void 0,
19105
+ providerMetadata: void 0,
19106
+ requestStatus: statusCode
19107
+ };
19108
+ }
19109
+ async function runChatV2PipelineExecution(options2) {
19110
+ const requestMessages = prependSystemPrompt(
19111
+ coercePromptToChatMessages(options2.prompt, { requirePrompt: true }),
19112
+ options2.systemPrompt
19113
+ );
19114
+ const modelMessages = await chatMessagesToModelMessages(requestMessages, {
19115
+ provider: options2.provider,
19116
+ anthropicCacheControlTtl: options2.anthropicCacheControlTtl
19117
+ });
19118
+ const functionTools = options2.functions != null && options2.functions.length > 0 ? chatV2ToolsToAiSdk(options2.functions) : void 0;
19119
+ const tools = functionTools == null ? options2.additionalTools : options2.additionalTools == null ? functionTools : { ...functionTools, ...options2.additionalTools };
19120
+ const plan = buildChatV2RequestPlan({
19121
+ ...options2,
19122
+ messages: modelMessages,
19123
+ tools
19124
+ });
19125
+ const shouldStreamResponse = plan.transportMode === "stream";
19126
+ let chatResponse;
19127
+ try {
19128
+ chatResponse = await runChatV2WithRetry(
19129
+ options2,
19130
+ {
19131
+ ...plan.request,
19132
+ abortSignal: options2.context.signal,
19133
+ executeStream: options2.executeStream,
19134
+ executeGenerate: options2.executeGenerate,
19135
+ onPartialOutput: !shouldStreamResponse ? void 0 : ({ text, functionCalls }) => {
19136
+ var _a, _b;
19137
+ (_b = (_a = options2.context).onPartialOutputs) == null ? void 0 : _b.call(
19138
+ _a,
19139
+ createChatV2CommonOutputs({
19140
+ requestMessages,
19141
+ response: text,
19142
+ structuredOutput: void 0,
19143
+ functionCalls,
19144
+ usage: void 0,
19145
+ reasoning: "",
19146
+ requestStatus: void 0,
19147
+ responseError: void 0,
19148
+ requestStatuses: [],
19149
+ requestErrors: [],
19150
+ requestBodies: void 0,
19151
+ outputUsage: false,
19152
+ outputReasoning: false,
19153
+ outputRequestStatus: false,
19154
+ outputRequestError: false,
19155
+ outputRequestBody: false,
19156
+ includeFunctionCalls: plan.output.includeFunctionCalls,
19157
+ functionCallMode: plan.output.functionCallMode,
19158
+ retryOnNon200: false,
19159
+ responseFormat: void 0
19160
+ })
19161
+ );
19162
+ }
19163
+ },
19164
+ plan.retry,
19165
+ options2.context.signal,
19166
+ plan.transportMode
19167
+ );
19168
+ } catch (caughtError) {
19169
+ if (options2.context.signal.aborted) {
19170
+ throw caughtError;
19171
+ }
19172
+ const retryFailure = isChatV2RetryFailure(caughtError) ? caughtError : void 0;
19173
+ const rawError = (retryFailure == null ? void 0 : retryFailure.error) ?? caughtError;
19174
+ return {
19175
+ outcome: "provider-failure",
19176
+ failure: {
19177
+ requestMessages,
19178
+ options: options2,
19179
+ plan,
19180
+ normalizedError: normalizeProviderFailure(rawError, options2),
19181
+ rawError,
19182
+ requestStatuses: (retryFailure == null ? void 0 : retryFailure.requestStatuses) ?? [],
19183
+ requestErrors: normalizeProviderFailureMessages((retryFailure == null ? void 0 : retryFailure.requestErrors) ?? [], options2)
19184
+ }
19185
+ };
19186
+ }
19187
+ const usage = normalizeChatV2Usage(chatResponse.result.usage, options2);
19188
+ const requestStatuses = chatResponse.requestStatuses;
19189
+ const requestStatus = chatResponse.result.requestStatus ?? 200;
19190
+ const requestErrors = normalizeProviderFailureMessages(chatResponse.requestErrors, options2);
19191
+ const responseError = chatResponse.responseError ? normalizeProviderFailureMessage(chatResponse.responseError, options2) : void 0;
19192
+ const commonOutputs = createChatV2CommonOutputs({
19193
+ requestMessages,
19194
+ response: chatResponse.result.responseText,
19195
+ structuredOutput: chatResponse.result.structuredOutput,
19196
+ functionCalls: chatResponse.result.functionCalls,
19197
+ usage,
19198
+ reasoning: chatResponse.result.reasoning,
19199
+ requestStatus,
19200
+ responseError,
19201
+ requestStatuses,
19202
+ requestErrors,
19203
+ requestBodies: options2.requestBodies,
19204
+ outputUsage: plan.output.outputUsage,
19205
+ outputReasoning: plan.output.outputReasoning,
19206
+ outputRequestStatus: plan.output.outputRequestStatus,
19207
+ outputRequestError: plan.output.outputRequestError,
19208
+ outputRequestBody: plan.output.outputRequestBody,
19209
+ includeFunctionCalls: plan.output.includeFunctionCalls,
19210
+ functionCallMode: plan.output.functionCallMode,
19211
+ retryOnNon200: plan.retry.enabled,
19212
+ responseFormat: plan.request.responseFormat
19213
+ });
19214
+ const allMessagesOutput = commonOutputs["all-messages"];
19215
+ if ((allMessagesOutput == null ? void 0 : allMessagesOutput.type) !== "chat-message[]") {
19216
+ throw new Error("Chat v2 pipeline expected all-messages output to be chat-message[].");
19217
+ }
19218
+ const result = {
19219
+ commonOutputs,
19220
+ requestMessages,
19221
+ allMessages: allMessagesOutput.value,
19222
+ response: chatResponse.result.responseText,
19223
+ functionCalls: chatResponse.result.functionCalls,
19224
+ reasoning: chatResponse.result.reasoning,
19225
+ usage,
19226
+ rawUsage: chatResponse.result.usage,
19227
+ finishReason: chatResponse.result.finishReason,
19228
+ providerMetadata: chatResponse.result.providerMetadata,
19229
+ requestStatus
19230
+ };
19231
+ const providerRoundFailure = chatResponse.responseError ?? (requestStatus === 200 ? void 0 : buildNon200StatusError(requestStatus));
19232
+ if (providerRoundFailure != null) {
19233
+ const rawError = providerRoundFailure;
19234
+ return {
19235
+ outcome: "provider-failure",
19236
+ failure: {
19237
+ requestMessages,
19238
+ options: options2,
19239
+ plan,
19240
+ normalizedError: normalizeProviderFailure(rawError, options2),
19241
+ rawError,
19242
+ requestStatuses: chatResponse.requestStatuses,
19243
+ requestErrors: normalizeProviderFailureMessages(chatResponse.requestErrors, options2),
19244
+ diagnosticResult: result
19245
+ }
19246
+ };
19247
+ }
19248
+ return { outcome: "success", result };
19249
+ }
19250
+ function materializeChatV2PipelineFailure(failure) {
19251
+ if (failure.diagnosticResult != null) {
19252
+ return failure.diagnosticResult;
19253
+ }
19254
+ const failureResult = buildProviderFailureResult(
19255
+ failure.requestMessages,
19256
+ failure.options,
19257
+ failure.plan,
19258
+ failure.normalizedError,
19259
+ failure.rawError,
19260
+ failure.requestStatuses,
19261
+ failure.requestErrors
19262
+ );
19263
+ if (failureResult != null) {
19264
+ return failureResult;
19265
+ }
19266
+ throw failure.normalizedError;
19267
+ }
19268
+ async function runChatV2Pipeline(options2) {
19269
+ const execution = await runChatV2PipelineExecution(options2);
19270
+ return execution.outcome === "success" ? execution.result : materializeChatV2PipelineFailure(execution.failure);
19271
+ }
19272
+
19273
+ // src/model/chat-v2/llmProfileFallback.ts
19274
+ var LLMProfileFallbackExhaustedError = class extends Error {
19275
+ constructor(attempts) {
19276
+ super(buildExhaustedMessage(attempts));
19277
+ this.attempts = attempts;
19278
+ this.name = "LLMProfileFallbackExhaustedError";
19279
+ }
19280
+ };
19281
+ function getSafeErrorMessage(error, candidate) {
19282
+ let message;
19283
+ try {
19284
+ message = error instanceof Error ? error.message : String(error);
19285
+ } catch {
19286
+ message = "Provider request failed with unreadable error metadata.";
19287
+ }
19288
+ const redactionValues = [candidate.credential, ...candidate.redactionValues ?? []].filter((value) => typeof value === "string" && value.length > 0).sort((left, right) => right.length - left.length);
19289
+ for (const value of new Set(redactionValues)) {
19290
+ message = message.split(value).join("[redacted]");
19291
+ }
19292
+ return message.length > 1e3 ? `${message.slice(0, 997)}...` : message;
19293
+ }
19294
+ function buildExhaustedMessage(attempts) {
19295
+ const details = attempts.map((attempt) => {
19296
+ const request = attempt.attemptIndex == null ? "" : ` attempt ${attempt.attemptIndex}`;
19297
+ const status = attempt.status == null ? "" : ` (${attempt.status})`;
19298
+ const error = attempt.error ? `: ${attempt.error}` : "";
19299
+ return `Profile ${attempt.profileIndex} (${attempt.provider}/${attempt.model}), round ${attempt.roundIndex}${request}${status}${error}`;
19300
+ }).join("\n");
19301
+ return details ? `LLM Profile fallback chain exhausted.
19302
+ ${details}` : "LLM Profile fallback chain exhausted before a provider request could be made.";
19303
+ }
19304
+ function pluralize(count, singular, plural = `${singular}s`) {
19305
+ return `${count} ${count === 1 ? singular : plural}`;
19306
+ }
19307
+ function buildLLMProfileFallbackSummary(candidates, attempts) {
19308
+ return candidates.map((candidate, profileIndex) => {
19309
+ const profileAttempts = attempts.filter((attempt) => attempt.profileIndex === profileIndex);
19310
+ const identity = `Profile ${profileIndex} (${candidate.provider}/${candidate.model})`;
19311
+ if (profileAttempts.length === 0) {
19312
+ return `${identity}: not attempted.`;
19313
+ }
19314
+ const successfulRounds = [
19315
+ ...new Set(
19316
+ profileAttempts.filter((attempt) => attempt.stage === "request" && attempt.outcome === "success").map((attempt) => attempt.roundIndex)
19317
+ )
19318
+ ];
19319
+ const failedConfiguration = profileAttempts.some(
19320
+ (attempt) => attempt.stage === "configuration" && attempt.outcome === "failure"
19321
+ );
19322
+ const failedRequestAttempts = profileAttempts.filter(
19323
+ (attempt) => attempt.stage === "request" && attempt.outcome === "failure"
19324
+ );
19325
+ const clauses = [];
19326
+ if (successfulRounds.length > 0) {
19327
+ clauses.push(
19328
+ `succeeded in model ${pluralize(successfulRounds.length, "round")} (${successfulRounds.join(", ")})`
19329
+ );
19330
+ }
19331
+ if (failedConfiguration) {
19332
+ clauses.push("failed during configuration");
19333
+ }
19334
+ if (failedRequestAttempts.length > 0) {
19335
+ const lastFailedRequest = failedRequestAttempts.at(-1);
19336
+ const status = lastFailedRequest.status == null ? "" : `; last status ${lastFailedRequest.status}`;
19337
+ clauses.push(`failed after ${pluralize(failedRequestAttempts.length, "provider attempt")}${status}`);
19338
+ }
19339
+ return `${identity}: ${clauses.join("; ")}.`;
19340
+ }).join("\n");
19341
+ }
19342
+ function buildLLMProfileRequestDiagnostics(profileCount, attempts) {
19343
+ const statuses = Array.from({ length: profileCount }, () => []);
19344
+ const errors = Array.from({ length: profileCount }, () => []);
19345
+ for (const attempt of attempts) {
19346
+ if (attempt.stage !== "request" || attempt.profileIndex < 0 || attempt.profileIndex >= profileCount) {
19347
+ continue;
19348
+ }
19349
+ if (attempt.status != null) {
19350
+ statuses[attempt.profileIndex].push(attempt.status);
19351
+ }
19352
+ if (attempt.error != null) {
19353
+ errors[attempt.profileIndex].push(attempt.error);
19354
+ }
19355
+ }
19356
+ return {
19357
+ statuses: compactLLMProfileRequestStatuses(statuses),
19358
+ errors: compactLLMProfileRequestErrors(errors)
19359
+ };
19360
+ }
19361
+ function compactLLMProfileRequestStatuses(statuses) {
19362
+ return statuses.map(
19363
+ (profileStatuses) => Array.isArray(profileStatuses) && profileStatuses.length === 1 ? profileStatuses[0] : profileStatuses
19364
+ );
19365
+ }
19366
+ function compactLLMProfileRequestErrors(errors) {
19367
+ if (errors.every((profileErrors) => Array.isArray(profileErrors) && profileErrors.length === 0)) {
19368
+ return [];
19369
+ }
19370
+ const compacted = errors.map(
19371
+ (profileErrors) => Array.isArray(profileErrors) && profileErrors.length === 1 ? profileErrors[0] : profileErrors
19372
+ );
19373
+ return compacted.length === 1 ? compacted[0] ?? [] : compacted;
19374
+ }
19375
+ function clearPartialResponse(options2) {
19376
+ var _a, _b;
19377
+ if (!options2.emitPartialOutputs) {
19378
+ return;
19379
+ }
19380
+ try {
19381
+ (_b = (_a = options2.context).onPartialOutputs) == null ? void 0 : _b.call(_a, {
19382
+ ["response"]: {
19383
+ type: "string",
19384
+ value: ""
19385
+ }
19386
+ });
19387
+ } catch {
19388
+ }
19389
+ }
19390
+ function throwIfAborted(signal) {
19391
+ if (!signal.aborted) {
19392
+ return;
19393
+ }
19394
+ throw signal.reason instanceof Error ? signal.reason : new Error("LLM Chat request was aborted.");
19395
+ }
19396
+ function createLLMProfileFallbackRunner(params) {
19397
+ const attempts = [];
19398
+ let activeProfileIndex = 0;
19399
+ let nextRoundIndex = 0;
19400
+ let exhausted = false;
19401
+ return {
19402
+ attempts,
19403
+ summary: () => buildLLMProfileFallbackSummary(params.candidates, attempts),
19404
+ wasExhausted: () => exhausted,
19405
+ run: async (roundOptions) => {
19406
+ const roundIndex = nextRoundIndex;
19407
+ let terminalProviderFailure;
19408
+ let lastError;
19409
+ for (let profileIndex = activeProfileIndex; profileIndex < params.candidates.length; profileIndex++) {
19410
+ throwIfAborted(roundOptions.context.signal);
19411
+ const candidate = params.candidates[profileIndex];
19412
+ let candidateOptions;
19413
+ try {
19414
+ candidateOptions = await params.resolveCandidate(profileIndex, roundOptions);
19415
+ } catch (error) {
19416
+ if (roundOptions.context.signal.aborted) {
19417
+ throw error;
19418
+ }
19419
+ lastError = error;
19420
+ terminalProviderFailure = void 0;
19421
+ attempts.push({
19422
+ roundIndex,
19423
+ profileIndex,
19424
+ provider: candidate.provider,
19425
+ model: candidate.model,
19426
+ stage: "configuration",
19427
+ outcome: "failure",
19428
+ error: getSafeErrorMessage(error, candidate)
19429
+ });
19430
+ clearPartialResponse(roundOptions);
19431
+ continue;
19432
+ }
19433
+ throwIfAborted(roundOptions.context.signal);
19434
+ const previousOnProviderAttempt = candidateOptions.onProviderAttempt;
19435
+ candidateOptions = {
19436
+ ...candidateOptions,
19437
+ profileIndex,
19438
+ roundIndex,
19439
+ onProviderAttempt: (attempt) => {
19440
+ try {
19441
+ previousOnProviderAttempt == null ? void 0 : previousOnProviderAttempt(attempt);
19442
+ } catch {
19443
+ }
19444
+ attempts.push({
19445
+ roundIndex,
19446
+ profileIndex,
19447
+ provider: candidate.provider,
19448
+ model: candidate.model,
19449
+ stage: "request",
19450
+ outcome: attempt.outcome === "success" ? "success" : "failure",
19451
+ attemptIndex: attempt.attemptIndex,
19452
+ ...attempt.status == null ? {} : { status: attempt.status },
19453
+ ...attempt.error == null ? {} : { error: getSafeErrorMessage(attempt.error, candidate) }
19454
+ });
19455
+ }
19456
+ };
19457
+ let execution;
19458
+ try {
19459
+ execution = await runChatV2PipelineExecution(candidateOptions);
19460
+ } catch (error) {
19461
+ if (roundOptions.context.signal.aborted) {
19462
+ throw error;
19463
+ }
19464
+ lastError = error;
19465
+ terminalProviderFailure = void 0;
19466
+ attempts.push({
19467
+ roundIndex,
19468
+ profileIndex,
19469
+ provider: candidate.provider,
19470
+ model: candidate.model,
19471
+ stage: "configuration",
19472
+ outcome: "failure",
19473
+ error: getSafeErrorMessage(error, candidate)
19474
+ });
19475
+ clearPartialResponse(roundOptions);
19476
+ continue;
19477
+ }
19478
+ if (execution.outcome === "success") {
19479
+ activeProfileIndex = profileIndex;
19480
+ nextRoundIndex += 1;
19481
+ return execution.result;
19482
+ }
19483
+ terminalProviderFailure = execution.failure;
19484
+ lastError = execution.failure.normalizedError;
19485
+ clearPartialResponse(roundOptions);
19486
+ }
19487
+ exhausted = true;
19488
+ if (params.candidates.length === 1 && terminalProviderFailure != null) {
19489
+ return materializeChatV2PipelineFailure(terminalProviderFailure);
19490
+ }
19491
+ if (params.candidates.length === 1 && lastError !== void 0) {
19492
+ throw lastError;
19493
+ }
19494
+ if (terminalProviderFailure != null && (terminalProviderFailure.options.outputRequestStatus || shouldOutputChatV2RequestError(terminalProviderFailure.options))) {
19495
+ try {
19496
+ return materializeChatV2PipelineFailure(terminalProviderFailure);
19497
+ } catch {
19498
+ }
19499
+ }
19500
+ throw new LLMProfileFallbackExhaustedError(attempts);
19501
+ }
19502
+ };
19503
+ }
19504
+
19505
+ // src/model/chat-v2/developerMessageRoles.ts
19506
+ function getInstructionMessageRoles(messages) {
19507
+ return messages.filter(
19508
+ (message) => message.type === "system" || message.type === "developer"
19509
+ ).map((message) => message.type);
19510
+ }
19511
+ function restoreOpenAICompatibleInstructionRoles(body, roles) {
19512
+ if (roles.length === 0) {
19513
+ return body;
19514
+ }
19515
+ if (body == null || typeof body !== "object" || Array.isArray(body)) {
19516
+ throw new Error("Could not preserve developer messages: provider request body is not a JSON object.");
19517
+ }
19518
+ const record = body;
19519
+ const listKey = Array.isArray(record.messages) ? "messages" : Array.isArray(record.input) ? "input" : void 0;
19520
+ if (listKey == null) {
19521
+ throw new Error("Could not preserve developer messages: provider request body has no messages or input array.");
19522
+ }
19523
+ const items = record[listKey];
19524
+ const instructionIndexes = items.flatMap(
19525
+ (item, index) => item != null && typeof item === "object" && !Array.isArray(item) && (item.role === "system" || item.role === "developer") ? [index] : []
19526
+ );
19527
+ if (instructionIndexes.length !== roles.length) {
19528
+ throw new Error(
19529
+ `Could not preserve developer messages: expected ${roles.length} instruction message(s), but the provider request contains ${instructionIndexes.length}.`
19530
+ );
19531
+ }
19532
+ const rewrittenItems = [...items];
19533
+ instructionIndexes.forEach((itemIndex, roleIndex) => {
19534
+ rewrittenItems[itemIndex] = {
19535
+ ...rewrittenItems[itemIndex],
19536
+ role: roles[roleIndex]
19537
+ };
19538
+ });
19539
+ return {
19540
+ ...record,
19541
+ [listKey]: rewrittenItems
19542
+ };
19543
+ }
19544
+
19545
+ // src/model/chat-v2/chatV2ProviderProfile.ts
19546
+ function getStringSetting(settings, key) {
19547
+ const value = settings[key];
19548
+ return typeof value === "string" && value.trim() ? value : void 0;
19549
+ }
19550
+ function resolveConfiguredCredential(provider, context, options2) {
19551
+ var _a, _b, _c, _d, _e;
19552
+ switch (provider) {
19553
+ case "openai": {
19554
+ const value = context.settings.openAiApiKey || context.settings.openAiKey || void 0;
19555
+ return { value, reference: { source: value ? "settings" : "none" } };
19556
+ }
19557
+ case "anthropic": {
19558
+ const settingsValue = context.settings.anthropicApiKey || void 0;
19559
+ if (settingsValue) return { value: settingsValue, reference: { source: "settings" } };
19560
+ const pluginValue = context.getPluginConfig("anthropicApiKey") || void 0;
19561
+ return { value: pluginValue, reference: { source: pluginValue ? "plugin" : "none" } };
19562
+ }
19563
+ case "google": {
19564
+ const settingsValue = context.settings.googleApiKey || void 0;
19565
+ if (settingsValue) return { value: settingsValue, reference: { source: "settings" } };
19566
+ const pluginValue = context.getPluginConfig("googleApiKey") || void 0;
19567
+ return { value: pluginValue, reference: { source: pluginValue ? "plugin" : "none" } };
19568
+ }
19569
+ case "custom": {
19570
+ const programmaticName = (_a = options2.customProgrammaticName) == null ? void 0 : _a.trim();
19571
+ const environmentName = (_b = options2.customEnvironmentName) == null ? void 0 : _b.trim();
19572
+ const programmaticValue = programmaticName ? getStringSetting(context.settings, programmaticName) : void 0;
19573
+ if (programmaticValue) {
19574
+ return {
19575
+ value: programmaticValue,
19576
+ reference: { source: "programmatic", name: programmaticName }
19577
+ };
19578
+ }
19579
+ if (environmentName) {
19580
+ const pluginEnvValue = (_c = context.settings.pluginEnv) == null ? void 0 : _c[environmentName];
19581
+ if (pluginEnvValue) {
19582
+ return { value: pluginEnvValue, reference: { source: "environment", name: environmentName } };
19583
+ }
19584
+ const processValue = (_e = (_d = globalThis.process) == null ? void 0 : _d.env) == null ? void 0 : _e[environmentName];
19585
+ if (processValue) {
19586
+ return { value: processValue, reference: { source: "environment", name: environmentName } };
19587
+ }
19588
+ }
19589
+ const value = context.settings.customAiApiKey || void 0;
19590
+ if (value) return { value, reference: { source: "settings" } };
19591
+ const missing = [
19592
+ programmaticName ? `programmatic key ${programmaticName}` : void 0,
19593
+ environmentName ? `env var ${environmentName}` : void 0
19594
+ ].filter(Boolean);
19595
+ if (missing.length > 0) {
19596
+ const hint = programmaticName ? `pass ${programmaticName}` : "set Alternative programmatic key name and pass that named run option";
19597
+ throw new Error(
19598
+ `Custom provider API key ${missing.join(" and ")} is not set. Use Input port, configure Settings > LLM, ${hint}, or configure the environment variable.`
19599
+ );
19600
+ }
19601
+ return { reference: { source: "none" } };
19602
+ }
19603
+ }
19604
+ }
19605
+ function resolveChatV2Credential(options2) {
19606
+ var _a, _b;
19607
+ if (options2.apiKeySource === "input") {
19608
+ const value = (_b = coerceTypeOptional((_a = options2.inputs) == null ? void 0 : _a["apiKey"], "string")) == null ? void 0 : _b.trim();
19609
+ if (!value) throw new Error("API Key input is required when API key source is Input port.");
19610
+ return { value, reference: { source: "input" } };
19611
+ }
19612
+ return resolveConfiguredCredential(options2.provider, options2.context, options2);
19613
+ }
19614
+ async function createResolvedChatV2Provider(options2) {
19615
+ const config = await resolveChatV2ProviderConfig(options2.provider, options2.modelId, options2.context, {
19616
+ baseURL: options2.baseURL,
19617
+ headers: options2.headers
19618
+ });
19619
+ const model = createChatV2Model(options2.provider, options2.modelId, options2.context, {
19620
+ ...config,
19621
+ apiKey: options2.credential.value,
19622
+ onRequestBody: options2.onRequestBody,
19623
+ transformRequestBody: options2.transformRequestBody
19624
+ });
19625
+ return {
19626
+ profile: {
19627
+ provider: options2.provider,
19628
+ modelId: options2.modelId,
19629
+ baseURL: config.baseURL,
19630
+ hasCustomHeaders: Object.keys(config.headers ?? {}).length > 0,
19631
+ credential: options2.credential.reference,
19632
+ capabilities: {
19633
+ builtInTools: options2.provider === "openai" || options2.provider === "google",
19634
+ structuredOutput: true
19635
+ }
19636
+ },
19637
+ model,
19638
+ config
19639
+ };
19640
+ }
19641
+
19642
+ // src/model/chat-v2/chatV2EditorCache.ts
19643
+ var import_safe_stable_stringify4 = __toESM(require("safe-stable-stringify"), 1);
19644
+ function buildLLMChatV2EditorCacheKey(parts) {
19645
+ return (0, import_safe_stable_stringify4.default)(parts) ?? "";
19646
+ }
19647
+ function cloneEditorCacheValue(value, seen = /* @__PURE__ */ new WeakMap()) {
19648
+ if (value == null || typeof value !== "object") {
19649
+ return value;
19650
+ }
19651
+ if (value instanceof Uint8Array) {
19652
+ return new Uint8Array(value);
19653
+ }
19654
+ const existing = seen.get(value);
19655
+ if (existing != null) {
19656
+ return existing;
19657
+ }
19658
+ if (Array.isArray(value)) {
19659
+ const clone2 = [];
19660
+ seen.set(value, clone2);
19661
+ clone2.push(...value.map((item) => cloneEditorCacheValue(item, seen)));
19662
+ return clone2;
19663
+ }
19664
+ const clone = {};
19665
+ seen.set(value, clone);
19666
+ for (const [key, item] of Object.entries(value)) {
19667
+ clone[key] = cloneEditorCacheValue(item, seen);
19668
+ }
19669
+ return clone;
19670
+ }
19671
+ function cloneLLMChatV2EditorCacheOutputs(outputs) {
19672
+ if (typeof structuredClone === "function") {
19673
+ try {
19674
+ return structuredClone(outputs);
19675
+ } catch {
19676
+ }
19677
+ }
19678
+ return cloneEditorCacheValue(outputs);
19679
+ }
19680
+ function fingerprintSecret(secret) {
19681
+ if (!secret) {
19682
+ return void 0;
19683
+ }
19684
+ let hash = 2166136261;
19685
+ for (let i = 0; i < secret.length; i++) {
19686
+ hash ^= secret.charCodeAt(i);
19687
+ hash = Math.imul(hash, 16777619);
19688
+ }
19689
+ return `${secret.length}:${(hash >>> 0).toString(36)}`;
19690
+ }
19691
+ function fingerprintProviderConfigForCache(config) {
19692
+ if (config.headers == null) {
19693
+ return config;
19694
+ }
19695
+ return {
19696
+ ...config,
19697
+ headers: Object.fromEntries(
19698
+ Object.entries(config.headers).map(([key, value]) => [key, fingerprintSecret(value) ?? ""])
19699
+ )
19700
+ };
19701
+ }
19702
+ function fingerprintNodeDataForCache(data) {
19703
+ const isCustomProvider = data.provider === "custom";
19704
+ return {
19705
+ ...data,
19706
+ baseURL: "",
19707
+ useBaseURLInput: false,
19708
+ customProviderBaseURL: isCustomProvider ? data.customProviderBaseURL : "",
19709
+ useCustomProviderBaseURLInput: isCustomProvider ? data.useCustomProviderBaseURLInput : false,
19710
+ extraProviderOptions: data.useExtraProviderOptionsInput ? "" : fingerprintSecret(data.extraProviderOptions) ?? "",
19711
+ headers: (data.headers ?? []).map(({ key, value }) => ({
19712
+ key,
19713
+ value: fingerprintSecret(value) ?? ""
19714
+ }))
19715
+ };
19716
+ }
19717
+ function fingerprintProviderOptionsForCache(providerOptions) {
19718
+ if (providerOptions == null) {
19719
+ return void 0;
19720
+ }
19721
+ return fingerprintSecret((0, import_safe_stable_stringify4.default)(providerOptions) ?? "");
19722
+ }
19723
+ function fingerprintProfileChainForCache(data, profiles) {
19724
+ if (profiles == null) {
19725
+ return void 0;
19726
+ }
19727
+ return profiles.map((profile) => ({
19728
+ configuration: fingerprintNodeDataForCache({
19729
+ ...data,
19730
+ ...profile.configuration,
19731
+ configurationMode: "profile"
19732
+ }),
19733
+ credential: {
19734
+ reference: profile.credential.reference,
19735
+ value: fingerprintSecret(profile.credential.value)
19736
+ }
19737
+ }));
19738
+ }
19739
+ function resolveLLMChatV2EditorCache(params) {
19740
+ const { editorCache } = params;
19741
+ if (editorCache == null) {
19742
+ return { cacheKey: void 0, cachedOutputs: void 0 };
19743
+ }
19744
+ const cacheKey = buildLLMChatV2EditorCacheKey({
19745
+ nodeId: params.nodeId,
19746
+ nodeData: fingerprintNodeDataForCache(params.data),
19747
+ provider: params.provider,
19748
+ modelId: params.modelId,
19749
+ providerConfig: fingerprintProviderConfigForCache(params.providerConfig),
19750
+ apiKeyFingerprint: fingerprintSecret(params.apiKey),
19751
+ prompt: params.prompt,
19752
+ systemPrompt: params.systemPrompt,
19753
+ functions: params.functions,
19754
+ generationParameters: params.generationParameters,
19755
+ responseFormatParameters: params.responseFormatParameters,
19756
+ providerOptions: fingerprintProviderOptionsForCache(params.providerOptions),
19757
+ toolChoice: params.toolChoice,
19758
+ profileChain: params.profileChain == null ? void 0 : {
19759
+ inputWasArray: params.profileChainUsesArray ?? false,
19760
+ profiles: fingerprintProfileChainForCache(params.data, params.profileChain)
19761
+ }
19762
+ });
19763
+ return {
19764
+ cacheKey,
19765
+ cachedOutputs: editorCache.has(cacheKey) ? cloneLLMChatV2EditorCacheOutputs(editorCache.get(cacheKey)) : void 0
19766
+ };
19767
+ }
19768
+
19769
+ // src/model/chat-v2/chatV2RuntimeOptions.ts
19770
+ var import_google3 = require("@ai-sdk/google");
19771
+ var import_openai4 = require("@ai-sdk/openai");
19772
+ function resolveLLMChatV2Headers(data, inputs) {
19773
+ const resolvedHeaders = data.useHeadersInput && inputs["headers"] != null ? coerceTypeOptional(inputs["headers"], "object") : Object.fromEntries((data.headers ?? []).map(({ key, value }) => [key, value]));
19774
+ const cleaned = cleanHeaders(resolvedHeaders ?? {});
19775
+ return Object.keys(cleaned).length > 0 ? cleaned : void 0;
19776
+ }
19777
+ function parseExtraProviderOptionsText(rawText) {
19778
+ const raw = rawText.trim();
19779
+ if (!raw) {
19780
+ return void 0;
19781
+ }
19782
+ let parsed;
19783
+ try {
19784
+ parsed = JSON.parse(raw);
19785
+ } catch (error) {
19786
+ const message = error instanceof Error ? error.message : String(error);
19787
+ throw new Error(`Extra provider options must be valid JSON: ${message}`);
19288
19788
  }
19289
- if (outputReasoning) {
19290
- outputs["reasoning"] = createControlFlowExcludedOutput();
19789
+ return normalizeExtraProviderOptions(parsed);
19790
+ }
19791
+ function normalizeExtraProviderOptions(value) {
19792
+ if (value == null) {
19793
+ return void 0;
19291
19794
  }
19292
- return outputs;
19795
+ if (typeof value === "string") {
19796
+ return parseExtraProviderOptionsText(value);
19797
+ }
19798
+ if (typeof value !== "object" || Array.isArray(value)) {
19799
+ throw new Error("Extra provider options must be a JSON object.");
19800
+ }
19801
+ return value;
19293
19802
  }
19294
-
19295
- // src/model/chat-v2/chatV2Pipeline.ts
19296
- var ChatV2RetryFailure = class extends Error {
19297
- constructor(error, requestStatuses, requestErrors) {
19298
- super("Chat v2 retry attempts failed");
19299
- this.error = error;
19300
- this.requestStatuses = requestStatuses;
19301
- this.requestErrors = requestErrors;
19302
- this.name = "ChatV2RetryFailure";
19803
+ function resolveLLMChatV2ExtraProviderOptions(data, inputs) {
19804
+ if (!data.useExtraProviderOptionsInput) {
19805
+ return parseExtraProviderOptionsText(data.extraProviderOptions ?? "");
19303
19806
  }
19304
- };
19305
- function isChatV2RetryFailure(error) {
19306
- return error instanceof ChatV2RetryFailure;
19807
+ return normalizeExtraProviderOptions(coerceTypeOptional(inputs["extraProviderOptions"], "object"));
19307
19808
  }
19308
- function getProviderFailureMessage(error) {
19309
- try {
19310
- if (error instanceof Error && typeof error.message === "string") {
19311
- return error.message;
19809
+ function resolveProviderOptions(data, inputs) {
19810
+ const providerOptions = {};
19811
+ const extraProviderOptions = resolveLLMChatV2ExtraProviderOptions(data, inputs);
19812
+ if (extraProviderOptions) {
19813
+ providerOptions[data.provider] = extraProviderOptions;
19814
+ }
19815
+ if (data.provider === "openai") {
19816
+ const previousResponseId = data.useOpenAIPreviousResponseIdInput && inputs["previousResponseId"] != null ? coerceTypeOptional(inputs["previousResponseId"], "string") : data.openAIPreviousResponseId;
19817
+ const openAIOptions = {
19818
+ ...data.openAIReasoningEffort ? { reasoningEffort: data.openAIReasoningEffort } : {},
19819
+ ...data.openAIReasoningSummary ? { reasoningSummary: data.openAIReasoningSummary } : {},
19820
+ ...(previousResponseId == null ? void 0 : previousResponseId.trim()) ? { previousResponseId: previousResponseId.trim() } : {}
19821
+ };
19822
+ if (Object.keys(openAIOptions).length > 0) {
19823
+ providerOptions.openai = {
19824
+ ...providerOptions.openai ?? {},
19825
+ ...openAIOptions
19826
+ };
19312
19827
  }
19313
- } catch {
19314
- return "Provider request failed with unreadable error metadata.";
19315
19828
  }
19316
- try {
19317
- return String(error);
19318
- } catch {
19319
- return "Provider request failed with unreadable error metadata.";
19829
+ if (data.provider === "anthropic") {
19830
+ const thinkingBudget = data.useAnthropicThinkingBudgetInput && inputs["anthropicThinkingBudget"] != null ? coerceTypeOptional(inputs["anthropicThinkingBudget"], "number") : data.anthropicThinkingBudget;
19831
+ const anthropicOptions = {
19832
+ ...data.anthropicEffort ? { effort: data.anthropicEffort } : {},
19833
+ ...data.anthropicThinkingMode === "enabled" ? {
19834
+ thinking: {
19835
+ type: "enabled",
19836
+ ...thinkingBudget != null ? { budgetTokens: thinkingBudget } : {}
19837
+ }
19838
+ } : data.anthropicThinkingMode === "disabled" ? { thinking: { type: "disabled" } } : data.anthropicThinkingMode === "adaptive" ? { thinking: { type: "adaptive" } } : {}
19839
+ };
19840
+ if (Object.keys(anthropicOptions).length > 0) {
19841
+ providerOptions.anthropic = {
19842
+ ...providerOptions.anthropic ?? {},
19843
+ ...anthropicOptions
19844
+ };
19845
+ }
19320
19846
  }
19847
+ if (data.provider === "google") {
19848
+ const thinkingBudget = data.useGoogleThinkingBudgetInput && inputs["googleThinkingBudget"] != null ? coerceTypeOptional(inputs["googleThinkingBudget"], "number") : data.googleThinkingBudget;
19849
+ const thinkingConfig = {
19850
+ ...thinkingBudget != null ? { thinkingBudget } : {},
19851
+ ...data.googleThinkingLevel ? { thinkingLevel: data.googleThinkingLevel } : {},
19852
+ ...data.googleIncludeThoughts ? { includeThoughts: true } : {}
19853
+ };
19854
+ const googleOptions = {
19855
+ ...Object.keys(thinkingConfig).length > 0 ? { thinkingConfig } : {}
19856
+ };
19857
+ if (Object.keys(googleOptions).length > 0) {
19858
+ providerOptions.google = {
19859
+ ...providerOptions.google ?? {},
19860
+ ...googleOptions
19861
+ };
19862
+ }
19863
+ }
19864
+ return Object.keys(providerOptions).length > 0 ? providerOptions : void 0;
19321
19865
  }
19322
- function buildNon200StatusError(statusCode) {
19323
- const error = new Error(`Provider request returned non-200 status: ${statusCode}`);
19324
- error.name = "AI_APICallError";
19325
- error.statusCode = statusCode;
19326
- return error;
19327
- }
19328
- function normalizeProviderFailureMessage(error, options2) {
19329
- return getProviderFailureMessage(normalizeProviderFailure(error, options2));
19866
+ function resolveLLMChatV2RuntimeProviderOptions(data, inputs) {
19867
+ const providerOptions = applyLLMChatV2ParallelToolCallProviderOptions({
19868
+ provider: data.provider,
19869
+ useToolCalling: data.useToolCalling,
19870
+ parallelToolCalls: data.parallelToolCalls,
19871
+ providerOptions: resolveProviderOptions(data, inputs)
19872
+ });
19873
+ return providerOptions != null && Object.keys(providerOptions).length > 0 ? providerOptions : void 0;
19330
19874
  }
19331
- function normalizeProviderFailure(error, options2) {
19332
- try {
19333
- return normalizeChatV2ProviderError(error, {
19334
- provider: options2.provider,
19335
- modelId: options2.modelId
19336
- });
19337
- } catch {
19338
- return error;
19875
+ function resolveLLMChatV2ToolChoice(data) {
19876
+ var _a;
19877
+ if (!data.useToolCalling || !data.toolChoice) {
19878
+ return void 0;
19879
+ }
19880
+ if (data.toolChoice === "function") {
19881
+ const toolName = (_a = data.toolChoiceFunction) == null ? void 0 : _a.trim();
19882
+ if (!toolName) {
19883
+ throw new Error("Tool name is required when Tool choice is Specific tool.");
19884
+ }
19885
+ return {
19886
+ type: "tool",
19887
+ toolName
19888
+ };
19339
19889
  }
19890
+ return data.toolChoice;
19340
19891
  }
19341
- function normalizeProviderFailureMessages(errors, options2) {
19342
- return errors.map((error) => normalizeProviderFailureMessage(error, options2));
19892
+ function normalizeStopSequences(stopSequences) {
19893
+ const normalized = (stopSequences ?? []).filter((sequence) => sequence.length > 0);
19894
+ return normalized.length > 0 ? normalized : void 0;
19343
19895
  }
19344
- async function runChatV2WithRetry(options2, chatOptions, retryPlan, signal, transportMode) {
19345
- const requestStatuses = [];
19346
- const requestErrors = [];
19347
- for (let attempt = 0; ; attempt++) {
19348
- const callId = createObservedChatV2CallId(options2);
19349
- let callWasObserved = false;
19350
- try {
19351
- const result = transportMode === "generate" ? await generateChatV2(chatOptions) : await streamChatV2(chatOptions);
19352
- const statusCode = result.requestStatus ?? 200;
19353
- notifyChatV2CallFinished(options2, {
19354
- callId,
19355
- attemptIndex: attempt,
19356
- outcome: statusCode === 200 ? "success" : "provider-failure",
19357
- result
19358
- });
19359
- callWasObserved = true;
19360
- if (retryPlan.enabled) {
19361
- requestStatuses.push(statusCode);
19896
+ function resolveStopSequences(data, inputs) {
19897
+ const stopSequences = data.useStopSequencesInput && inputs["stopSequences"] != null ? coerceTypeOptional(inputs["stopSequences"], "string[]") : data.stopSequences;
19898
+ return normalizeStopSequences(stopSequences);
19899
+ }
19900
+ function resolveLLMChatV2GenerationParameters(data, inputs) {
19901
+ return {
19902
+ maxTokens: getInputOrData(data, inputs, "maxTokens", "number"),
19903
+ temperature: getInputOrData(data, inputs, "temperature", "number"),
19904
+ topP: getInputOrData(data, inputs, "topP", "number"),
19905
+ topK: getInputOrData(data, inputs, "topK", "number"),
19906
+ presencePenalty: getInputOrData(data, inputs, "presencePenalty", "number"),
19907
+ frequencyPenalty: getInputOrData(data, inputs, "frequencyPenalty", "number"),
19908
+ stopSequences: resolveStopSequences(data, inputs),
19909
+ seed: getInputOrData(data, inputs, "seed", "number")
19910
+ };
19911
+ }
19912
+ function resolveLLMChatV2BuiltInTools(data, context, config, apiKey) {
19913
+ switch (data.provider) {
19914
+ case "openai": {
19915
+ if (!data.enableOpenAIWebSearch && !data.enableOpenAICodeInterpreter) {
19916
+ return void 0;
19362
19917
  }
19363
- if (!retryPlan.enabled || statusCode === 200) {
19364
- return { result, requestStatuses, requestErrors };
19918
+ const provider = (0, import_openai4.createOpenAI)({
19919
+ apiKey: apiKey || context.settings.openAiApiKey || context.settings.openAiKey || void 0,
19920
+ organization: context.settings.openAiOrganization || void 0,
19921
+ baseURL: void 0,
19922
+ headers: config.headers
19923
+ });
19924
+ const tools = {};
19925
+ if (data.enableOpenAIWebSearch) {
19926
+ tools.openaiWebSearch = provider.tools.webSearch({
19927
+ searchContextSize: data.openAIWebSearchContextSize
19928
+ });
19365
19929
  }
19366
- const responseError = buildNon200StatusError(statusCode);
19367
- requestErrors.push(responseError);
19368
- if (attempt >= retryPlan.repeatTimes) {
19369
- return { result, requestStatuses, requestErrors, responseError };
19930
+ if (data.enableOpenAICodeInterpreter) {
19931
+ tools.openaiCodeInterpreter = provider.tools.codeInterpreter();
19370
19932
  }
19371
- await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
19372
- } catch (error) {
19373
- if (!callWasObserved) {
19374
- notifyChatV2CallFinished(options2, {
19375
- callId,
19376
- attemptIndex: attempt,
19377
- outcome: signal.aborted ? "aborted" : "provider-failure",
19378
- error
19379
- });
19933
+ return tools;
19934
+ }
19935
+ case "google": {
19936
+ if (!data.enableGoogleSearchGrounding && !data.enableGoogleUrlContext) {
19937
+ return void 0;
19380
19938
  }
19381
- const statusCode = getChatV2ProviderErrorStatusCode(error);
19382
- if (!retryPlan.enabled || statusCode == null || statusCode === 200) {
19383
- throw error;
19939
+ const provider = (0, import_google3.createGoogleGenerativeAI)({
19940
+ apiKey: apiKey || context.settings.googleApiKey || context.getPluginConfig("googleApiKey") || void 0,
19941
+ baseURL: void 0,
19942
+ headers: config.headers
19943
+ });
19944
+ const tools = {};
19945
+ if (data.enableGoogleSearchGrounding) {
19946
+ tools.googleSearch = provider.tools.googleSearch({});
19384
19947
  }
19385
- requestStatuses.push(statusCode);
19386
- requestErrors.push(error);
19387
- if (attempt >= retryPlan.repeatTimes) {
19388
- throw new ChatV2RetryFailure(error, requestStatuses, requestErrors);
19948
+ if (data.enableGoogleUrlContext) {
19949
+ tools.googleUrlContext = provider.tools.urlContext({});
19389
19950
  }
19390
- await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
19951
+ return tools;
19391
19952
  }
19953
+ case "anthropic":
19954
+ return void 0;
19955
+ case "custom":
19956
+ return void 0;
19392
19957
  }
19393
19958
  }
19394
- function buildProviderFailureResult(requestMessages, options2, plan, normalizedError, rawError, requestStatuses, requestErrors) {
19395
- if (!plan.output.outputRequestStatus) {
19396
- return void 0;
19397
- }
19398
- const statusCode = getChatV2ProviderErrorStatusCode(normalizedError);
19399
- if (statusCode == null && !isChatV2ProviderApiCallError(rawError) && !isChatV2ProviderFetchError(rawError)) {
19400
- return void 0;
19401
- }
19402
- const responseError = getProviderFailureMessage(normalizedError);
19403
- const retryRequestStatuses = plan.retry.enabled ? requestStatuses.length > 0 ? requestStatuses : statusCode == null ? [] : [statusCode] : [];
19404
- const retryRequestErrors = plan.retry.enabled ? requestErrors.length > 0 ? requestErrors : [responseError] : [];
19405
- const commonOutputs = createChatV2ProviderFailureOutputs({
19406
- requestMessages,
19407
- responseStatus: statusCode,
19408
- responseError,
19409
- requestStatuses: retryRequestStatuses,
19410
- requestErrors: retryRequestErrors,
19411
- requestBodies: options2.requestBodies,
19412
- outputUsage: plan.output.outputUsage,
19413
- outputReasoning: plan.output.outputReasoning,
19414
- includeFunctionCalls: plan.output.includeFunctionCalls,
19415
- retryOnNon200: plan.retry.enabled
19416
- });
19417
- const allMessagesOutput = commonOutputs["all-messages"];
19418
- if ((allMessagesOutput == null ? void 0 : allMessagesOutput.type) !== "chat-message[]") {
19419
- throw new Error("Chat v2 provider failure expected all-messages output to be chat-message[].");
19420
- }
19959
+
19960
+ // src/model/chat-v2/llmChatV2NodeRuntime.ts
19961
+ function resolveLLMChatV2BaseURL(data, inputs) {
19962
+ var _a;
19963
+ return data.provider === "custom" ? ((_a = getInputOrData(data, inputs, "customProviderBaseURL", "string", "useCustomProviderBaseURLInput")) == null ? void 0 : _a.trim()) || void 0 : void 0;
19964
+ }
19965
+ function createSharedRunOptions(params) {
19966
+ var _a;
19967
+ const { shared, provider, modelId } = params;
19421
19968
  return {
19422
- commonOutputs,
19423
- requestMessages,
19424
- allMessages: allMessagesOutput.value,
19425
- response: "",
19426
- functionCalls: [],
19427
- reasoning: "",
19428
- usage: void 0,
19429
- rawUsage: void 0,
19430
- finishReason: void 0,
19431
- providerMetadata: void 0,
19432
- requestStatus: statusCode
19969
+ provider,
19970
+ // From profile mode replaces this before a provider request. Keeping the
19971
+ // field populated preserves the established Tool Continuation contract.
19972
+ model: void 0,
19973
+ modelId,
19974
+ prompt: shared.prompt,
19975
+ systemPrompt: shared.systemPrompt,
19976
+ functions: shared.functions,
19977
+ responseOutput: createChatV2ResponseOutput(shared.responseFormatParameters, provider),
19978
+ responseFormat: (_a = shared.responseFormatParameters) == null ? void 0 : _a.responseFormat,
19979
+ outputUsage: shared.data.outputUsage,
19980
+ outputReasoning: shared.data.outputReasoning,
19981
+ outputRequestStatus: shared.data.outputRequestStatus,
19982
+ outputRequestError: shouldOutputChatV2RequestError(shared.data),
19983
+ outputRequestBody: shouldOutputChatV2RequestBody(shared.data),
19984
+ includeFunctionCalls: shouldIncludeLLMChatV2ToolCalls(shared.data),
19985
+ emitPartialOutputs: shared.data.useAsGraphPartialOutput,
19986
+ toolChoice: shared.toolChoice,
19987
+ requestBodies: shared.requestBodies,
19988
+ retryOnNon200: shared.data.retryOnNon200,
19989
+ retryOnNon200RepeatTimes: shared.data.retryOnNon200RepeatTimes,
19990
+ retryOnNon200CooldownMs: shared.data.retryOnNon200CooldownMs,
19991
+ context: shared.context
19433
19992
  };
19434
19993
  }
19435
- async function runChatV2Pipeline(options2) {
19436
- const requestMessages = prependSystemPrompt(
19437
- coercePromptToChatMessages(options2.prompt, { requirePrompt: true }),
19438
- options2.systemPrompt
19439
- );
19440
- const modelMessages = await chatMessagesToModelMessages(requestMessages, {
19441
- provider: options2.provider,
19442
- anthropicCacheControlTtl: options2.anthropicCacheControlTtl
19994
+ function createRuntimeProviderProfile(params) {
19995
+ const provider = parseChatV2Provider(params.data.provider);
19996
+ return {
19997
+ provider,
19998
+ modelId: getInputOrData(params.data, params.inputs, "model", "string"),
19999
+ baseURL: resolveLLMChatV2BaseURL(params.data, params.inputs),
20000
+ hasCustomHeaders: Object.keys(resolveLLMChatV2Headers(params.data, params.inputs) ?? {}).length > 0,
20001
+ credential: params.credential.reference,
20002
+ capabilities: {
20003
+ builtInTools: provider === "openai" || provider === "google",
20004
+ structuredOutput: true
20005
+ }
20006
+ };
20007
+ }
20008
+ async function resolveCandidateRunOptions(params) {
20009
+ var _a;
20010
+ const { shared, profile, roundOptions } = params;
20011
+ const effectiveData = profile ? applyLLMProfileToNodeData(shared.data, profile) : shared.data;
20012
+ if (hasLLMChatV2ToolResponseFormatConflict(effectiveData)) {
20013
+ throw new Error(LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY.paragraphs[0]);
20014
+ }
20015
+ const provider = parseChatV2Provider(effectiveData.provider);
20016
+ const modelId = getInputOrData(effectiveData, shared.inputs, "model", "string");
20017
+ const baseURL = resolveLLMChatV2BaseURL(effectiveData, shared.inputs);
20018
+ const headers = resolveLLMChatV2Headers(effectiveData, shared.inputs);
20019
+ const credential = (profile == null ? void 0 : profile.credential) ?? resolveChatV2Credential({
20020
+ provider,
20021
+ context: shared.context,
20022
+ apiKeySource: effectiveData.apiKeySource === "input" ? "input" : "configured",
20023
+ inputs: shared.inputs,
20024
+ customProgrammaticName: effectiveData.customProviderApiKeyProgrammaticName,
20025
+ customEnvironmentName: effectiveData.customProviderApiKeyEnvVarName
19443
20026
  });
19444
- const functionTools = options2.functions != null && options2.functions.length > 0 ? chatV2ToolsToAiSdk(options2.functions) : void 0;
19445
- const tools = functionTools == null ? options2.additionalTools : options2.additionalTools == null ? functionTools : { ...functionTools, ...options2.additionalTools };
19446
- const plan = buildChatV2RequestPlan({
19447
- ...options2,
19448
- messages: modelMessages,
19449
- tools
20027
+ const transformRequestBody = (provider === "openai" || provider === "custom") && shared.instructionRoles.includes("developer") ? (body) => restoreOpenAICompatibleInstructionRoles(body, shared.instructionRoles) : void 0;
20028
+ const resolvedProvider = await createResolvedChatV2Provider({
20029
+ provider,
20030
+ modelId,
20031
+ context: shared.context,
20032
+ baseURL,
20033
+ headers,
20034
+ credential,
20035
+ onRequestBody: shared.requestBodies == null ? void 0 : (body) => shared.requestBodies.push(body),
20036
+ transformRequestBody
19450
20037
  });
19451
- const shouldStreamResponse = plan.transportMode === "stream";
19452
- const chatResponse = await runChatV2WithRetry(
19453
- options2,
19454
- {
19455
- ...plan.request,
19456
- abortSignal: options2.context.signal,
19457
- executeStream: options2.executeStream,
19458
- executeGenerate: options2.executeGenerate,
19459
- onPartialOutput: !shouldStreamResponse ? void 0 : ({ text, functionCalls }) => {
19460
- var _a, _b;
19461
- (_b = (_a = options2.context).onPartialOutputs) == null ? void 0 : _b.call(
19462
- _a,
19463
- createChatV2CommonOutputs({
19464
- requestMessages,
19465
- response: text,
19466
- structuredOutput: void 0,
19467
- functionCalls,
19468
- usage: void 0,
19469
- reasoning: "",
19470
- requestStatus: void 0,
19471
- responseError: void 0,
19472
- requestStatuses: [],
19473
- requestErrors: [],
19474
- requestBodies: void 0,
19475
- outputUsage: false,
19476
- outputReasoning: false,
19477
- outputRequestStatus: false,
19478
- includeFunctionCalls: plan.output.includeFunctionCalls,
19479
- functionCallMode: plan.output.functionCallMode,
19480
- retryOnNon200: false,
19481
- responseFormat: void 0
19482
- })
19483
- );
20038
+ const generationParameters = resolveLLMChatV2GenerationParameters(effectiveData, shared.inputs);
20039
+ const providerOptions = mergeCustomProviderResponseFormatOptions(
20040
+ provider,
20041
+ resolveLLMChatV2RuntimeProviderOptions(effectiveData, shared.inputs),
20042
+ shared.responseFormatParameters
20043
+ );
20044
+ return {
20045
+ ...roundOptions,
20046
+ provider,
20047
+ model: resolvedProvider.model,
20048
+ modelId,
20049
+ additionalTools: resolveLLMChatV2BuiltInTools(
20050
+ effectiveData,
20051
+ shared.context,
20052
+ resolvedProvider.config,
20053
+ credential.value
20054
+ ),
20055
+ ...generationParameters,
20056
+ responseOutput: createChatV2ResponseOutput(shared.responseFormatParameters, provider),
20057
+ responseFormat: (_a = shared.responseFormatParameters) == null ? void 0 : _a.responseFormat,
20058
+ providerOptions,
20059
+ anthropicCacheControlTtl: provider === "anthropic" ? effectiveData.anthropicCacheControlTtl || void 0 : void 0,
20060
+ requestBodies: shared.requestBodies
20061
+ };
20062
+ }
20063
+ function createSharedRuntimeValues(params) {
20064
+ const { data, inputs, context } = params;
20065
+ const prompt = inputs["prompt"];
20066
+ const systemPrompt = inputs["systemPrompt"];
20067
+ return {
20068
+ data,
20069
+ inputs,
20070
+ context,
20071
+ prompt,
20072
+ systemPrompt,
20073
+ functions: data.useToolCalling && inputs["functions"] != null ? coerceTypeOptional(inputs["functions"], "gpt-function[]") : void 0,
20074
+ responseFormatParameters: resolveChatV2ResponseFormatParameters(data, inputs),
20075
+ toolChoice: resolveLLMChatV2ToolChoice(data),
20076
+ requestBodies: shouldOutputChatV2RequestBody(data) ? [] : void 0,
20077
+ instructionRoles: getInstructionMessageRoles(prependSystemPrompt(coercePromptToChatMessages(prompt), systemPrompt))
20078
+ };
20079
+ }
20080
+ async function resolveLLMChatV2RuntimeConfig(params) {
20081
+ var _a;
20082
+ const { data, nodeId, inputs, context } = params;
20083
+ const profileInput = inputs["llmProfile"];
20084
+ if (data.configurationMode === "profile" && profileInput == null) {
20085
+ throw new Error("LLM Profile input is required when Configuration is From profile.");
20086
+ }
20087
+ const shared = createSharedRuntimeValues({ data, inputs, context });
20088
+ const editorCache = data.cache ? context.editorExecutionCache : void 0;
20089
+ if (data.configurationMode !== "profile") {
20090
+ const inlineRunOptions = await resolveCandidateRunOptions({
20091
+ shared,
20092
+ profile: void 0,
20093
+ roundOptions: createSharedRunOptions({
20094
+ shared,
20095
+ provider: parseChatV2Provider(data.provider),
20096
+ modelId: data.model
20097
+ })
20098
+ });
20099
+ const generationParameters = resolveLLMChatV2GenerationParameters(data, inputs);
20100
+ const inlineCredential = resolveChatV2Credential({
20101
+ provider: inlineRunOptions.provider,
20102
+ context,
20103
+ apiKeySource: data.apiKeySource === "input" ? "input" : "configured",
20104
+ inputs,
20105
+ customProgrammaticName: data.customProviderApiKeyProgrammaticName,
20106
+ customEnvironmentName: data.customProviderApiKeyEnvVarName
20107
+ });
20108
+ const inlineProviderConfig = await resolveChatV2ProviderConfig(
20109
+ inlineRunOptions.provider,
20110
+ inlineRunOptions.modelId,
20111
+ context,
20112
+ {
20113
+ baseURL: resolveLLMChatV2BaseURL(data, inputs),
20114
+ headers: resolveLLMChatV2Headers(data, inputs)
19484
20115
  }
19485
- },
19486
- plan.retry,
19487
- options2.context.signal,
19488
- plan.transportMode
19489
- ).catch((caughtError) => {
19490
- const retryFailure = isChatV2RetryFailure(caughtError) ? caughtError : void 0;
19491
- const rawError = (retryFailure == null ? void 0 : retryFailure.error) ?? caughtError;
19492
- const normalizedError = normalizeProviderFailure(rawError, options2);
19493
- const requestStatuses2 = (retryFailure == null ? void 0 : retryFailure.requestStatuses) ?? [];
19494
- const requestErrors2 = normalizeProviderFailureMessages((retryFailure == null ? void 0 : retryFailure.requestErrors) ?? [], options2);
19495
- const failureResult = buildProviderFailureResult(
19496
- requestMessages,
19497
- options2,
19498
- plan,
19499
- normalizedError,
19500
- rawError,
19501
- requestStatuses2,
19502
- requestErrors2
19503
20116
  );
19504
- if (failureResult) {
19505
- return failureResult;
19506
- }
19507
- throw normalizedError;
20117
+ const { cacheKey: cacheKey2, cachedOutputs: cachedOutputs2 } = resolveLLMChatV2EditorCache({
20118
+ apiKey: inlineCredential.value,
20119
+ data,
20120
+ editorCache,
20121
+ functions: shared.functions,
20122
+ generationParameters,
20123
+ modelId: inlineRunOptions.modelId,
20124
+ nodeId,
20125
+ prompt: shared.prompt,
20126
+ provider: inlineRunOptions.provider,
20127
+ providerConfig: inlineProviderConfig,
20128
+ providerOptions: inlineRunOptions.providerOptions,
20129
+ responseFormatParameters: shared.responseFormatParameters,
20130
+ systemPrompt: shared.systemPrompt,
20131
+ toolChoice: shared.toolChoice
20132
+ });
20133
+ return {
20134
+ runOptions: inlineRunOptions,
20135
+ providerProfile: createRuntimeProviderProfile({
20136
+ data,
20137
+ inputs,
20138
+ credential: inlineCredential
20139
+ }),
20140
+ runPipeline: runChatV2Pipeline,
20141
+ functions: shared.functions,
20142
+ cacheKey: cacheKey2,
20143
+ cachedOutputs: cachedOutputs2,
20144
+ editorCache,
20145
+ shouldAutoContinueToolCalls: !!data.autoContinueToolCalls && data.useToolCalling,
20146
+ maxToolRounds: data.maxToolRounds ?? 3,
20147
+ profileAttempts: void 0,
20148
+ profileChainUsesArray: false,
20149
+ profileChainLength: void 0,
20150
+ getProfileSummary: void 0,
20151
+ isProfileFallbackExhausted: () => false
20152
+ };
20153
+ }
20154
+ const profiles = normalizeLLMProfileChainInput(profileInput == null ? void 0 : profileInput.value);
20155
+ const firstProfile = profiles[0];
20156
+ const firstProvider = parseChatV2Provider(firstProfile.configuration.provider);
20157
+ const profileRunOptions = createSharedRunOptions({
20158
+ shared,
20159
+ provider: firstProvider,
20160
+ modelId: firstProfile.configuration.model
19508
20161
  });
19509
- if ("commonOutputs" in chatResponse) {
19510
- return chatResponse;
19511
- }
19512
- const usage = normalizeChatV2Usage(chatResponse.result.usage, options2);
19513
- const requestStatuses = chatResponse.requestStatuses;
19514
- const requestStatus = chatResponse.result.requestStatus ?? 200;
19515
- const requestErrors = normalizeProviderFailureMessages(chatResponse.requestErrors, options2);
19516
- const responseError = chatResponse.responseError ? normalizeProviderFailureMessage(chatResponse.responseError, options2) : void 0;
19517
- const commonOutputs = createChatV2CommonOutputs({
19518
- requestMessages,
19519
- response: chatResponse.result.responseText,
19520
- structuredOutput: chatResponse.result.structuredOutput,
19521
- functionCalls: chatResponse.result.functionCalls,
19522
- usage,
19523
- reasoning: chatResponse.result.reasoning,
19524
- requestStatus,
19525
- responseError,
19526
- requestStatuses,
19527
- requestErrors,
19528
- requestBodies: options2.requestBodies,
19529
- outputUsage: plan.output.outputUsage,
19530
- outputReasoning: plan.output.outputReasoning,
19531
- outputRequestStatus: plan.output.outputRequestStatus,
19532
- includeFunctionCalls: plan.output.includeFunctionCalls,
19533
- functionCallMode: plan.output.functionCallMode,
19534
- retryOnNon200: plan.retry.enabled,
19535
- responseFormat: plan.request.responseFormat
20162
+ const firstProfileData = applyLLMProfileToNodeData(data, firstProfile);
20163
+ Object.assign(profileRunOptions, {
20164
+ ...resolveLLMChatV2GenerationParameters(firstProfileData, inputs),
20165
+ providerOptions: mergeCustomProviderResponseFormatOptions(
20166
+ firstProvider,
20167
+ resolveLLMChatV2RuntimeProviderOptions(firstProfileData, inputs),
20168
+ shared.responseFormatParameters
20169
+ ),
20170
+ anthropicCacheControlTtl: firstProvider === "anthropic" ? firstProfileData.anthropicCacheControlTtl || void 0 : void 0
20171
+ });
20172
+ const fallbackRunner = createLLMProfileFallbackRunner({
20173
+ candidates: profiles.map((profile) => {
20174
+ var _a2;
20175
+ return {
20176
+ provider: parseChatV2Provider(profile.configuration.provider),
20177
+ model: profile.configuration.model,
20178
+ credential: profile.credential.value,
20179
+ redactionValues: [
20180
+ ...profile.configuration.headers.map((header) => header.value),
20181
+ ...Object.values(cleanHeaders(((_a2 = context.settings) == null ? void 0 : _a2.chatNodeHeaders) ?? {}))
20182
+ ]
20183
+ };
20184
+ }),
20185
+ resolveCandidate: (profileIndex, roundOptions) => resolveCandidateRunOptions({
20186
+ shared,
20187
+ profile: profiles[profileIndex],
20188
+ roundOptions
20189
+ })
20190
+ });
20191
+ const { cacheKey, cachedOutputs } = resolveLLMChatV2EditorCache({
20192
+ apiKey: void 0,
20193
+ data: firstProfileData,
20194
+ editorCache,
20195
+ functions: shared.functions,
20196
+ generationParameters: void 0,
20197
+ modelId: firstProfile.configuration.model,
20198
+ nodeId,
20199
+ prompt: shared.prompt,
20200
+ provider: firstProvider,
20201
+ // Profile headers are part of the individual profile fingerprints, but
20202
+ // provider resolution also merges project-wide Chat headers. Include those
20203
+ // values through the existing redacted provider-config fingerprint so a
20204
+ // global-header edit cannot reuse a stale profile-mode editor cache entry.
20205
+ providerConfig: { headers: cleanHeaders(((_a = context.settings) == null ? void 0 : _a.chatNodeHeaders) ?? {}) },
20206
+ providerOptions: void 0,
20207
+ responseFormatParameters: shared.responseFormatParameters,
20208
+ systemPrompt: shared.systemPrompt,
20209
+ toolChoice: shared.toolChoice,
20210
+ profileChain: profiles,
20211
+ profileChainUsesArray: Array.isArray(profileInput == null ? void 0 : profileInput.value)
19536
20212
  });
19537
- const allMessagesOutput = commonOutputs["all-messages"];
19538
- if ((allMessagesOutput == null ? void 0 : allMessagesOutput.type) !== "chat-message[]") {
19539
- throw new Error("Chat v2 pipeline expected all-messages output to be chat-message[].");
19540
- }
19541
20213
  return {
19542
- commonOutputs,
19543
- requestMessages,
19544
- allMessages: allMessagesOutput.value,
19545
- response: chatResponse.result.responseText,
19546
- functionCalls: chatResponse.result.functionCalls,
19547
- reasoning: chatResponse.result.reasoning,
19548
- usage,
19549
- rawUsage: chatResponse.result.usage,
19550
- finishReason: chatResponse.result.finishReason,
19551
- providerMetadata: chatResponse.result.providerMetadata,
19552
- requestStatus
20214
+ runOptions: profileRunOptions,
20215
+ providerProfile: createRuntimeProviderProfile({
20216
+ data: firstProfileData,
20217
+ inputs,
20218
+ credential: firstProfile.credential
20219
+ }),
20220
+ runPipeline: fallbackRunner.run,
20221
+ functions: shared.functions,
20222
+ cacheKey,
20223
+ cachedOutputs,
20224
+ editorCache,
20225
+ shouldAutoContinueToolCalls: !!data.autoContinueToolCalls && data.useToolCalling,
20226
+ maxToolRounds: data.maxToolRounds ?? 3,
20227
+ profileAttempts: fallbackRunner.attempts,
20228
+ profileChainUsesArray: Array.isArray(profileInput == null ? void 0 : profileInput.value),
20229
+ profileChainLength: profiles.length,
20230
+ getProfileSummary: fallbackRunner.summary,
20231
+ isProfileFallbackExhausted: fallbackRunner.wasExhausted
19553
20232
  };
19554
20233
  }
19555
20234
 
@@ -19593,10 +20272,6 @@ function applyAccumulatedUsage(result, usage, outputUsage) {
19593
20272
  return;
19594
20273
  }
19595
20274
  result.usage = usage;
19596
- result.commonOutputs["responseTokens"] = {
19597
- type: "number",
19598
- value: usage.completionTokens
19599
- };
19600
20275
  if (outputUsage) {
19601
20276
  result.commonOutputs["usage"] = {
19602
20277
  type: "object",
@@ -19791,9 +20466,12 @@ var LLMChatV2NodeImpl = class extends NodeImpl {
19791
20466
  if (usesProfile) {
19792
20467
  inputs.unshift({
19793
20468
  id: "llmProfile",
19794
- title: "LLM Profile",
19795
- dataType: "llm-config",
19796
- required: true
20469
+ title: "LLM Profiles",
20470
+ dataType: ["llm-config", "llm-config[]"],
20471
+ required: true,
20472
+ coerced: true,
20473
+ splitRunBehavior: "preserve-array",
20474
+ description: "One LLM Profile or an ordered fallback chain. Profiles are tried left to right."
19797
20475
  });
19798
20476
  }
19799
20477
  if (!usesProfile && this.data.apiKeySource === "input") {
@@ -19902,21 +20580,47 @@ var LLMChatV2NodeImpl = class extends NodeImpl {
19902
20580
  ];
19903
20581
  }
19904
20582
  if (this.data.outputRequestStatus) {
20583
+ const profileArrayRequestDetails = this.data.configurationMode === "profile" ? ["number", "number[]", "any"] : this.data.retryOnNon200 ? "number[]" : "number";
20584
+ outputs.push({
20585
+ id: "requestStatus",
20586
+ title: "Response Status",
20587
+ dataType: profileArrayRequestDetails,
20588
+ ...this.data.configurationMode === "profile" ? {
20589
+ description: "A scalar profile keeps the normal status shape. An LLM Profile array groups values by profile: one request is a number, retries are a number array."
20590
+ } : {}
20591
+ });
20592
+ }
20593
+ if (shouldOutputChatV2RequestError(this.data)) {
20594
+ const profileArrayRequestErrors = this.data.configurationMode === "profile" ? ["string", "string[]", "any"] : this.data.retryOnNon200 ? "string[]" : "string";
20595
+ outputs.push({
20596
+ id: "requestError",
20597
+ title: "Response Error",
20598
+ dataType: profileArrayRequestErrors,
20599
+ ...this.data.configurationMode === "profile" ? {
20600
+ description: "A scalar profile keeps the normal error shape. An LLM Profile array keeps profile positions when errors occur: one error is a string and retries are an array."
20601
+ } : {}
20602
+ });
20603
+ }
20604
+ if (shouldOutputChatV2RequestBody(this.data)) {
20605
+ outputs.push({
20606
+ id: "requestBody",
20607
+ title: "LLM request body",
20608
+ dataType: ["object", "object[]", "string", "string[]", "any", "any[]"]
20609
+ });
20610
+ }
20611
+ if (this.data.configurationMode === "profile") {
19905
20612
  outputs.push(
19906
20613
  {
19907
- id: "requestStatus",
19908
- title: "Response Status",
19909
- dataType: this.data.retryOnNon200 ? "number[]" : "number"
19910
- },
19911
- {
19912
- id: "requestError",
19913
- title: "Response Error",
19914
- dataType: this.data.retryOnNon200 ? "string[]" : "string"
20614
+ id: "llmProfileSummary",
20615
+ title: "LLM Profile Summary",
20616
+ dataType: "string",
20617
+ description: "Human-readable profile fallback outcome for this LLM Chat run."
19915
20618
  },
19916
20619
  {
19917
- id: "requestBody",
19918
- title: "LLM request body",
19919
- dataType: ["object", "object[]", "string", "string[]", "any", "any[]"]
20620
+ id: "llmProfileAttempts",
20621
+ title: "LLM Profile Attempts",
20622
+ dataType: "object[]",
20623
+ description: "Chronological provider/profile attempts for this LLM Chat run."
19920
20624
  }
19921
20625
  );
19922
20626
  }
@@ -19944,7 +20648,7 @@ var LLMChatV2NodeImpl = class extends NodeImpl {
19944
20648
  type: "markdown",
19945
20649
  disableLinks: true,
19946
20650
  text: [
19947
- getBodyLine("Configuration", "From LLM Profile input"),
20651
+ getBodyLine("Configuration", "From LLM Profiles input"),
19948
20652
  ...this.data.useToolCalling ? [getBodyLine("Tools", "Enabled")] : [],
19949
20653
  ...this.data.responseFormat ? [getBodyLine("Response format", this.data.responseFormat)] : []
19950
20654
  ].join("\n")
@@ -19986,6 +20690,28 @@ var LLMChatV2NodeImpl = class extends NodeImpl {
19986
20690
  });
19987
20691
  const toolCallContinuation = context.toolCallContinuation;
19988
20692
  if (runtime.cachedOutputs != null) {
20693
+ if (runtime.profileChainUsesArray && this.data.outputRequestStatus) {
20694
+ const cachedStatus = runtime.cachedOutputs["requestStatus"];
20695
+ if ((cachedStatus == null ? void 0 : cachedStatus.type) === "any" && Array.isArray(cachedStatus.value)) {
20696
+ cachedStatus.value = compactLLMProfileRequestStatuses(cachedStatus.value);
20697
+ }
20698
+ }
20699
+ if (runtime.profileChainUsesArray && shouldOutputChatV2RequestError(this.data)) {
20700
+ const cachedError = runtime.cachedOutputs["requestError"];
20701
+ if ((cachedError == null ? void 0 : cachedError.type) === "any" && Array.isArray(cachedError.value)) {
20702
+ cachedError.value = compactLLMProfileRequestErrors(cachedError.value);
20703
+ }
20704
+ }
20705
+ if (runtime.profileAttempts != null) {
20706
+ runtime.cachedOutputs["llmProfileAttempts"] = {
20707
+ type: "object[]",
20708
+ value: []
20709
+ };
20710
+ runtime.cachedOutputs["llmProfileSummary"] = {
20711
+ type: "string",
20712
+ value: "Editor cache hit \u2014 no LLM Profile calls were made for this run."
20713
+ };
20714
+ }
19989
20715
  return runtime.cachedOutputs;
19990
20716
  }
19991
20717
  const result = runtime.shouldAutoContinueToolCalls ? await runChatV2PipelineWithToolContinuation({
@@ -20014,13 +20740,42 @@ var LLMChatV2NodeImpl = class extends NodeImpl {
20014
20740
  value: delegated.message,
20015
20741
  delegatedToolCall: delegated.record
20016
20742
  };
20743
+ },
20744
+ runPipeline: runtime.runPipeline
20745
+ }) : await runtime.runPipeline(runtime.runOptions);
20746
+ if (runtime.profileAttempts != null) {
20747
+ result.commonOutputs["llmProfileAttempts"] = {
20748
+ type: "object[]",
20749
+ value: runtime.profileAttempts
20750
+ };
20751
+ result.commonOutputs["llmProfileSummary"] = {
20752
+ type: "string",
20753
+ value: runtime.getProfileSummary()
20754
+ };
20755
+ if (runtime.profileChainUsesArray && runtime.profileChainLength != null) {
20756
+ const diagnostics = buildLLMProfileRequestDiagnostics(runtime.profileChainLength, runtime.profileAttempts);
20757
+ if (this.data.outputRequestStatus) {
20758
+ result.commonOutputs["requestStatus"] = {
20759
+ type: "any",
20760
+ value: diagnostics.statuses
20761
+ };
20762
+ }
20763
+ if (shouldOutputChatV2RequestError(this.data)) {
20764
+ result.commonOutputs["requestError"] = {
20765
+ type: "any",
20766
+ value: diagnostics.errors
20767
+ };
20768
+ }
20017
20769
  }
20018
- }) : await runChatV2Pipeline(runtime.runOptions);
20770
+ }
20019
20771
  if (toolCallContinuation && result.functionCalls.length > 0) {
20020
20772
  toolCallContinuation.release();
20021
20773
  }
20022
- if (runtime.cacheKey != null && runtime.editorCache != null) {
20023
- runtime.editorCache.set(runtime.cacheKey, cloneLLMChatV2EditorCacheOutputs(result.commonOutputs));
20774
+ if (runtime.cacheKey != null && runtime.editorCache != null && !runtime.isProfileFallbackExhausted()) {
20775
+ const cacheOutputs = cloneLLMChatV2EditorCacheOutputs(result.commonOutputs);
20776
+ delete cacheOutputs["llmProfileAttempts"];
20777
+ delete cacheOutputs["llmProfileSummary"];
20778
+ runtime.editorCache.set(runtime.cacheKey, cacheOutputs);
20024
20779
  }
20025
20780
  return result.commonOutputs;
20026
20781
  }
@@ -20322,6 +21077,7 @@ var PromptNodeImpl = class extends NodeImpl {
20322
21077
  label: "Type",
20323
21078
  options: [
20324
21079
  { value: "system", label: "System" },
21080
+ { value: "developer", label: "Developer" },
20325
21081
  { value: "user", label: "User" },
20326
21082
  { value: "assistant", label: "Assistant" },
20327
21083
  { value: "function", label: "Function" }
@@ -20382,7 +21138,7 @@ var PromptNodeImpl = class extends NodeImpl {
20382
21138
  static getUIData() {
20383
21139
  return {
20384
21140
  infoBoxBody: import_ts_dedent7.dedent`
20385
- Outputs a chat message, which is a string of text with an attached "type" saying who sent the message (User, Assistant, System) and optionally an attached "name".
21141
+ Outputs a chat message, which is a string of text with an attached "type" saying who sent the message (User, Assistant, System, Developer) and optionally an attached "name".
20386
21142
 
20387
21143
  Also provides the same <span style="color: var(--primary)">{{interpolation}}</span> capabilities as a Text node.
20388
21144
 
@@ -20410,7 +21166,7 @@ var PromptNodeImpl = class extends NodeImpl {
20410
21166
  outputValue = outputValue.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
20411
21167
  const type = getInputOrData(this.data, inputs, "type", "string");
20412
21168
  const isCacheBreakpoint = getInputOrData(this.data, inputs, "isCacheBreakpoint", "boolean");
20413
- if (["assistant", "system", "user", "function"].includes(type) === false) {
21169
+ if (["assistant", "system", "developer", "user", "function"].includes(type) === false) {
20414
21170
  throw new Error(`Invalid type: ${type}`);
20415
21171
  }
20416
21172
  const message = (0, import_ts_pattern2.match)(type).with(
@@ -20420,6 +21176,13 @@ var PromptNodeImpl = class extends NodeImpl {
20420
21176
  message: outputValue,
20421
21177
  isCacheBreakpoint
20422
21178
  })
21179
+ ).with(
21180
+ "developer",
21181
+ (type2) => ({
21182
+ type: type2,
21183
+ message: outputValue,
21184
+ isCacheBreakpoint
21185
+ })
20423
21186
  ).with(
20424
21187
  "user",
20425
21188
  (type2) => ({
@@ -20474,6 +21237,7 @@ var PromptNodeImpl = class extends NodeImpl {
20474
21237
  var promptNode = nodeDefinition(PromptNodeImpl, "Prompt");
20475
21238
  var typeDisplay = {
20476
21239
  assistant: "Assistant",
21240
+ developer: "Developer",
20477
21241
  system: "System",
20478
21242
  user: "User",
20479
21243
  function: "Function"
@@ -30049,6 +30813,7 @@ var import_lodash_es14 = require("lodash");
30049
30813
  var import_ts_pattern6 = require("ts-pattern");
30050
30814
  var messageTypeToTitle = {
30051
30815
  assistant: "Assistant",
30816
+ developer: "Developer",
30052
30817
  function: "Function Tool Call",
30053
30818
  system: "System",
30054
30819
  user: "User"
@@ -30120,6 +30885,7 @@ var AssembleMessageNodeImpl = class extends NodeImpl {
30120
30885
  dataKey: "type",
30121
30886
  options: [
30122
30887
  { value: "system", label: "System" },
30888
+ { value: "developer", label: "Developer" },
30123
30889
  { value: "user", label: "User" },
30124
30890
  { value: "assistant", label: "Assistant" },
30125
30891
  { value: "function", label: "Function" }
@@ -30162,6 +30928,12 @@ var AssembleMessageNodeImpl = class extends NodeImpl {
30162
30928
  type: type2,
30163
30929
  message: []
30164
30930
  })
30931
+ ).with(
30932
+ "developer",
30933
+ (type2) => ({
30934
+ type: type2,
30935
+ message: []
30936
+ })
30165
30937
  ).with(
30166
30938
  "user",
30167
30939
  (type2) => ({
@@ -30909,6 +31681,18 @@ var DelegateFunctionCallNodeImpl = class extends NodeImpl {
30909
31681
  title: "Message (fires before tool call invocation)",
30910
31682
  description: "Nonblank text the assistant emitted alongside a connected tool-call round. This output fires before the tools are invoked."
30911
31683
  });
31684
+ outputs.push({
31685
+ id: "tool-name",
31686
+ dataType: ["string", "string[]"],
31687
+ title: "Tool Name",
31688
+ description: "The name of the tool selected by the LLM."
31689
+ });
31690
+ outputs.push({
31691
+ id: "tool-arguments",
31692
+ dataType: ["object", "object[]"],
31693
+ title: "Tool Arguments",
31694
+ description: "The resolved arguments passed to the selected tool."
31695
+ });
30912
31696
  outputs.push({
30913
31697
  id: "output",
30914
31698
  dataType: ["string", "string[]"],
@@ -33361,7 +34145,7 @@ var ManagedKnowledgeStore = class {
33361
34145
  queries,
33362
34146
  request.maxConcurrency ?? Math.min(queries.length, 3),
33363
34147
  async (query) => {
33364
- throwIfAborted(searchContext.signal);
34148
+ throwIfAborted2(searchContext.signal);
33365
34149
  const evidence2 = await this.driver.search(
33366
34150
  { sourceId: source.sourceId, version, query, topK, filter, rerank },
33367
34151
  searchContext
@@ -33409,7 +34193,7 @@ var ManagedKnowledgeStore = class {
33409
34193
  const chunks = await chunkDocuments(documents, documentIds, version, chunking, context);
33410
34194
  if (chunks.length === 0) throw new Error("Sync Knowledge Source produced no non-empty chunks.");
33411
34195
  await this.driver.upsertChunks(source.sourceId, version, chunks, context);
33412
- throwIfAborted(context.signal);
34196
+ throwIfAborted2(context.signal);
33413
34197
  const manifest = {
33414
34198
  schemaVersion: MANAGED_SCHEMA_VERSION,
33415
34199
  sourceId: source.sourceId,
@@ -33434,7 +34218,7 @@ var ManagedKnowledgeStore = class {
33434
34218
  try {
33435
34219
  stillActive = await this.#getManifest(source.sourceId, context);
33436
34220
  } catch (error) {
33437
- throwIfAborted(context.signal);
34221
+ throwIfAborted2(context.signal);
33438
34222
  cleanupVerificationFailed = true;
33439
34223
  warnings.push(`The new version is active, but cleanup verification failed: ${errorMessage(error)}`);
33440
34224
  }
@@ -33447,7 +34231,7 @@ var ManagedKnowledgeStore = class {
33447
34231
  try {
33448
34232
  await this.driver.deleteVersion(source.sourceId, existing.activeVersion, context);
33449
34233
  } catch (error) {
33450
- throwIfAborted(context.signal);
34234
+ throwIfAborted2(context.signal);
33451
34235
  warnings.push(`The new version is active, but stale-version cleanup failed: ${errorMessage(error)}`);
33452
34236
  }
33453
34237
  }
@@ -33551,7 +34335,7 @@ function normalizePositiveManifestCount(value, label, sourceId) {
33551
34335
  return value;
33552
34336
  }
33553
34337
  async function waitForPromiseOrAbort(promise, signal) {
33554
- throwIfAborted(signal);
34338
+ throwIfAborted2(signal);
33555
34339
  await new Promise((resolve, reject) => {
33556
34340
  const abort = () => {
33557
34341
  signal.removeEventListener("abort", abort);
@@ -33603,7 +34387,7 @@ function createManifestCommitId() {
33603
34387
  async function chunkDocuments(documents, documentIds, version, options2, context) {
33604
34388
  const chunks = [];
33605
34389
  for (let documentIndex = 0; documentIndex < documents.length; documentIndex += 1) {
33606
- throwIfAborted(context.signal);
34390
+ throwIfAborted2(context.signal);
33607
34391
  const document = documents[documentIndex];
33608
34392
  const documentId = documentIds[documentIndex];
33609
34393
  const pieces = options2.unit === "tokens" ? await splitByTokens(document.text, options2, context) : splitByCharacters(document.text, options2);
@@ -33665,7 +34449,7 @@ async function splitByTokens(text, options2, context) {
33665
34449
  let high = text.length;
33666
34450
  let best = low;
33667
34451
  while (low <= high) {
33668
- throwIfAborted(context.signal);
34452
+ throwIfAborted2(context.signal);
33669
34453
  const middle = Math.floor((low + high) / 2);
33670
34454
  const count = await getTokenCount(text.slice(start, middle));
33671
34455
  if (count <= options2.targetSize) {
@@ -33693,7 +34477,7 @@ async function findTokenOverlapStart(text, chunkStart, chunkEnd, overlapTokens,
33693
34477
  let high = chunkEnd;
33694
34478
  let best = chunkEnd;
33695
34479
  while (low <= high) {
33696
- throwIfAborted(signal);
34480
+ throwIfAborted2(signal);
33697
34481
  const middle = Math.floor((low + high) / 2);
33698
34482
  const count = await getTokenCount(text.slice(middle, chunkEnd));
33699
34483
  if (count <= overlapTokens) {
@@ -33771,7 +34555,7 @@ function createShortHash(value) {
33771
34555
  function sameManifestActivation(actual, expected) {
33772
34556
  return (actual == null ? void 0 : actual.activeVersion) === expected.activeVersion && actual.commitId === expected.commitId;
33773
34557
  }
33774
- function throwIfAborted(signal) {
34558
+ function throwIfAborted2(signal) {
33775
34559
  if (signal.aborted) throw signal.reason ?? new Error("Knowledge operation was cancelled.");
33776
34560
  }
33777
34561
  function errorMessage(error) {
@@ -34501,14 +35285,19 @@ Assistant: ${content}`;
34501
35285
  return acc;
34502
35286
  }, "");
34503
35287
  prompt += "\n\nAssistant:";
34504
- const system = data.model.startsWith("claude-3") ? getSystemPrompt(inputs) : void 0;
35288
+ const useMessageApi = model.startsWith("claude-3") || model.startsWith("claude-sonnet") || model.startsWith("claude-opus");
35289
+ const system = useMessageApi ? getSystemPrompt(inputs) : void 0;
34505
35290
  let { maxTokens } = data;
34506
35291
  const tokenizerInfo = {
34507
35292
  node: context.node,
34508
35293
  model,
34509
35294
  endpoint: void 0
34510
35295
  };
34511
- const tokenCountEstimate = await context.tokenizer.getTokenCountForString(prompt, tokenizerInfo);
35296
+ const systemText = typeof system === "string" ? system : system == null ? void 0 : system.map((message) => message.text).join("\n\n");
35297
+ const tokenCountEstimate = await context.tokenizer.getTokenCountForString(
35298
+ [systemText, prompt].filter(Boolean).join("\n\n"),
35299
+ tokenizerInfo
35300
+ );
34512
35301
  const modelInfo = anthropicModels[model] ?? {
34513
35302
  maxTokens: Number.MAX_SAFE_INTEGER,
34514
35303
  cost: {
@@ -34551,7 +35340,6 @@ Assistant: ${content}`;
34551
35340
  messages,
34552
35341
  tools: tools ? tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.parameters })) : void 0
34553
35342
  };
34554
- const useMessageApi = model.startsWith("claude-3") || model.startsWith("claude-sonnet") || model.startsWith("claude-opus");
34555
35343
  const cacheKey = JSON.stringify(useMessageApi ? messageOptions : completionOptions);
34556
35344
  if (data.cache) {
34557
35345
  const cached = cache2.get(cacheKey);
@@ -34767,30 +35555,24 @@ var chatAnthropicNode = pluginNodeDefinition(ChatAnthropicNodeImpl, "Chat (Anthr
34767
35555
  function getSystemPrompt(inputs) {
34768
35556
  const systemInput = inputs["system"];
34769
35557
  const system = coerceTypeOptional(systemInput, "string");
35558
+ const systemMessages = [];
34770
35559
  if (system) {
34771
- return [
34772
- {
34773
- type: "text",
34774
- text: system,
34775
- cache_control: (systemInput == null ? void 0 : systemInput.type) === "chat-message" ? systemInput.value.isCacheBreakpoint ? { type: "ephemeral" } : null : null
34776
- }
34777
- ];
35560
+ systemMessages.push({
35561
+ type: "text",
35562
+ text: system,
35563
+ cache_control: (systemInput == null ? void 0 : systemInput.type) === "chat-message" ? systemInput.value.isCacheBreakpoint ? { type: "ephemeral" } : null : null
35564
+ });
34778
35565
  }
34779
- const prompt = inputs["prompt"];
34780
- if (prompt && prompt.type === "chat-message[]") {
34781
- const systemMessages = prompt.value.filter((message) => message.type === "system");
34782
- if (systemMessages.length) {
34783
- const converted = systemMessages.map((message) => {
34784
- return {
34785
- type: "text",
34786
- text: coerceType({ type: "chat-message", value: message }, "string"),
34787
- cache_control: message.isCacheBreakpoint ? { type: "ephemeral" } : null
34788
- };
35566
+ for (const message of coercePromptToChatMessages(inputs["prompt"])) {
35567
+ if (message.type === "system" || message.type === "developer") {
35568
+ systemMessages.push({
35569
+ type: "text",
35570
+ text: coerceType({ type: "chat-message", value: message }, "string"),
35571
+ cache_control: message.isCacheBreakpoint ? { type: "ephemeral" } : null
34789
35572
  });
34790
- return converted;
34791
35573
  }
34792
35574
  }
34793
- return void 0;
35575
+ return systemMessages.length > 0 ? systemMessages : void 0;
34794
35576
  }
34795
35577
  function getChatMessages(inputs) {
34796
35578
  const prompt = inputs["prompt"];
@@ -34813,7 +35595,7 @@ async function chatMessagesToClaude3ChatMessages(chatMessages) {
34813
35595
  return combinedMessages;
34814
35596
  }
34815
35597
  async function chatMessageToClaude3ChatMessage(message) {
34816
- if (message.type === "system") {
35598
+ if (message.type === "system" || message.type === "developer") {
34817
35599
  return void 0;
34818
35600
  }
34819
35601
  if (message.type === "function") {
@@ -40210,14 +40992,13 @@ var ChatGoogleNodeImpl = {
40210
40992
  },
40211
40993
  async process(data, inputs, context) {
40212
40994
  const output = {};
40213
- const systemPrompt = coerceTypeOptional(inputs["systemPrompt"], "string");
40214
40995
  const rawModel = getInputOrData(data, inputs, "model");
40215
40996
  const model = rawModel;
40216
40997
  const temperature = getInputOrData(data, inputs, "temperature", "number");
40217
40998
  const topP = getInputOrData(data, inputs, "top_p", "number");
40218
40999
  const useTopP = getInputOrData(data, inputs, "useTopP", "boolean");
40219
41000
  const thinkingBudget = getInputOrData(data, inputs, "thinkingBudget", "number");
40220
- const { messages } = getChatGoogleNodeMessages(inputs);
41001
+ const { messages, systemPrompt } = getChatGoogleNodeMessages(inputs);
40221
41002
  let prompt = await Promise.all(
40222
41003
  messages.map(async (message) => {
40223
41004
  var _a;
@@ -40278,7 +41059,7 @@ var ChatGoogleNodeImpl = {
40278
41059
  ]
40279
41060
  };
40280
41061
  }
40281
- throw new Error(`Google Vertex AI does not support message type ${message.type}`);
41062
+ throw new Error("Google Vertex AI received an unsupported message type.");
40282
41063
  })
40283
41064
  );
40284
41065
  prompt = prompt.reduce((acc, message) => {
@@ -40296,7 +41077,8 @@ var ChatGoogleNodeImpl = {
40296
41077
  model,
40297
41078
  endpoint: void 0
40298
41079
  };
40299
- const tokenCount = await context.tokenizer.getTokenCountForMessages(messages, void 0, tokenizerInfo);
41080
+ const tokenMessages = systemPrompt ? [{ type: "system", message: systemPrompt }, ...messages] : messages;
41081
+ const tokenCount = await context.tokenizer.getTokenCountForMessages(tokenMessages, void 0, tokenizerInfo);
40300
41082
  if (generativeAiGoogleModels[model]) {
40301
41083
  maxTokens = clampMaxTokensToModelLimit(
40302
41084
  output,
@@ -40415,6 +41197,7 @@ var ChatGoogleNodeImpl = {
40415
41197
  temperature: useTopP ? void 0 : temperature,
40416
41198
  top_p: useTopP ? topP : void 0,
40417
41199
  top_k: void 0,
41200
+ systemPrompt,
40418
41201
  project,
40419
41202
  location,
40420
41203
  applicationCredentials
@@ -40518,8 +41301,18 @@ var ChatGoogleNodeImpl = {
40518
41301
  };
40519
41302
  var chatGoogleNode = pluginNodeDefinition(ChatGoogleNodeImpl, "Chat (Google, Legacy)");
40520
41303
  function getChatGoogleNodeMessages(inputs) {
40521
- const prompt = inputs["prompt"];
40522
- return { messages: coercePromptToChatMessages(prompt, { requirePrompt: true }) };
41304
+ const promptMessages = coercePromptToChatMessages(inputs["prompt"], { requirePrompt: true });
41305
+ const instructionMessages = promptMessages.filter(
41306
+ (message) => message.type === "system" || message.type === "developer"
41307
+ );
41308
+ const systemPromptParts = [
41309
+ coerceTypeOptional(inputs["systemPrompt"], "string"),
41310
+ ...instructionMessages.map((message) => coerceTypeOptional({ type: "chat-message", value: message }, "string"))
41311
+ ].filter((part) => !!part);
41312
+ return {
41313
+ messages: promptMessages.filter((message) => message.type !== "system" && message.type !== "developer"),
41314
+ systemPrompt: systemPromptParts.length > 0 ? systemPromptParts.join("\n\n") : void 0
41315
+ };
40523
41316
  }
40524
41317
 
40525
41318
  // src/plugins/google/plugin.ts
@@ -41378,6 +42171,7 @@ var Rivet = void 0;
41378
42171
  looseDataValueToDataValue,
41379
42172
  looseDataValuesToDataValues,
41380
42173
  matchNode,
42174
+ materializeChatV2PipelineFailure,
41381
42175
  mcpDiscoveryNode,
41382
42176
  mcpGetPromptNode,
41383
42177
  mcpToolCallNode,
@@ -41470,6 +42264,7 @@ var Rivet = void 0;
41470
42264
  restoreEscapedInterpolationTokens,
41471
42265
  rivetWebAppStatusExternalFunction,
41472
42266
  runChatV2Pipeline,
42267
+ runChatV2PipelineExecution,
41473
42268
  runGentraceTests,
41474
42269
  runRemoteGentraceTests,
41475
42270
  sanitizeIdentifierPortValue,
@@ -41481,6 +42276,8 @@ var Rivet = void 0;
41481
42276
  serializeProject,
41482
42277
  setGlobalNode,
41483
42278
  setStoredValueNode,
42279
+ shouldOutputChatV2RequestBody,
42280
+ shouldOutputChatV2RequestError,
41484
42281
  shuffleNode,
41485
42282
  sliceNode,
41486
42283
  splitNode,