@valerypopoff/rivet2-core 2.4.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/cjs/bundle.cjs +1800 -753
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +1578 -0
  4. package/dist/cjs/interpolationRuntime.cjs.map +7 -0
  5. package/dist/cjs/interpolationSyntax.cjs +186 -0
  6. package/dist/cjs/interpolationSyntax.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  8. package/dist/esm/exports.js +2 -1
  9. package/dist/esm/integrations/CodeRunner.js +5 -0
  10. package/dist/esm/integrations/mcp/MCPBase.js +16 -6
  11. package/dist/esm/interpolationRuntime.js +5 -0
  12. package/dist/esm/model/AgentResponseTrace.js +8 -3
  13. package/dist/esm/model/GraphBoundaryCache.js +0 -6
  14. package/dist/esm/model/GraphBoundaryEffects.js +5 -1
  15. package/dist/esm/model/GraphOutputSelection.js +34 -0
  16. package/dist/esm/model/GraphProcessor.js +177 -50
  17. package/dist/esm/model/ProcessContextBuilder.js +4 -1
  18. package/dist/esm/model/RecordingPlayer.js +46 -14
  19. package/dist/esm/model/SplitRunProcessor.js +37 -16
  20. package/dist/esm/model/StoredValueStore.js +4 -3
  21. package/dist/esm/model/UiGraphRendererStyles.js +20 -0
  22. package/dist/esm/model/chat/aiSdkStreaming.js +3 -2
  23. package/dist/esm/model/chat-v2/aiSdkBridge.js +63 -5
  24. package/dist/esm/model/chat-v2/chatV2Pipeline.js +66 -3
  25. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +20 -7
  26. package/dist/esm/model/chat-v2/llmProfileFallback.js +12 -4
  27. package/dist/esm/model/nodes/CodeNewNode.js +16 -16
  28. package/dist/esm/model/nodes/DestructureNode.js +2 -2
  29. package/dist/esm/model/nodes/ExpressionNode.js +16 -16
  30. package/dist/esm/model/nodes/ExtractObjectPathNode.js +2 -2
  31. package/dist/esm/model/nodes/ExtractYamlNode.js +5 -5
  32. package/dist/esm/model/nodes/JSFilterNode.js +3 -1
  33. package/dist/esm/model/nodes/JSMapNode.js +3 -1
  34. package/dist/esm/model/nodes/LLMChatV2Node.js +30 -4
  35. package/dist/esm/model/nodes/MCPGetPromptNode.js +6 -2
  36. package/dist/esm/model/nodes/MCPToolCallNode.js +6 -2
  37. package/dist/esm/model/nodes/ObjectNode.js +19 -20
  38. package/dist/esm/model/nodes/PromptNode.js +10 -11
  39. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +2 -40
  40. package/dist/esm/model/nodes/SubGraphNode.js +40 -26
  41. package/dist/esm/model/nodes/TextNode.js +11 -32
  42. package/dist/esm/model/nodes/ToTreeNode.js +6 -13
  43. package/dist/esm/model/nodes/ToolNode.js +33 -16
  44. package/dist/esm/model/nodes/jsListCallbackHelpers.js +19 -15
  45. package/dist/esm/model/nodes/jsValueInterpolation.js +83 -30
  46. package/dist/esm/model/nodes/nodeBodyPreview.js +23 -0
  47. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +14 -11
  48. package/dist/esm/recording/ExecutionRecorder.js +55 -23
  49. package/dist/esm/utils/index.js +2 -0
  50. package/dist/esm/utils/interpolation.js +478 -221
  51. package/dist/esm/utils/interpolationSyntax.js +175 -0
  52. package/dist/esm/utils/jsonPath.js +129 -0
  53. package/dist/types/exports.d.ts +3 -1
  54. package/dist/types/integrations/CodeRunnerOptions.d.ts +9 -0
  55. package/dist/types/integrations/mcp/MCPBase.d.ts +3 -1
  56. package/dist/types/interpolationRuntime.d.ts +5 -0
  57. package/dist/types/model/AgentResponseTrace.d.ts +2 -0
  58. package/dist/types/model/ExecutorProtocol.d.ts +4 -0
  59. package/dist/types/model/GraphBoundaryCache.d.ts +0 -2
  60. package/dist/types/model/GraphOutputSelection.d.ts +8 -0
  61. package/dist/types/model/GraphProcessor.d.ts +12 -3
  62. package/dist/types/model/ProcessContext.d.ts +9 -2
  63. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  64. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  65. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  66. package/dist/types/model/chat/aiSdkStreaming.d.ts +1 -1
  67. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +1 -1
  68. package/dist/types/model/chat-v2/chatV2Types.d.ts +29 -0
  69. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +5 -1
  70. package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
  71. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  72. package/dist/types/model/nodes/ToTreeNode.d.ts +5 -2
  73. package/dist/types/model/nodes/ToolNode.d.ts +13 -1
  74. package/dist/types/model/nodes/jsValueInterpolation.d.ts +16 -8
  75. package/dist/types/model/nodes/nodeBodyPreview.d.ts +7 -0
  76. package/dist/types/recording/ExecutionRecorder.d.ts +6 -1
  77. package/dist/types/recording/RecordedEvents.d.ts +2 -0
  78. package/dist/types/utils/index.d.ts +2 -0
  79. package/dist/types/utils/interpolation.d.ts +93 -8
  80. package/dist/types/utils/interpolationSyntax.d.ts +21 -0
  81. package/dist/types/utils/jsonPath.d.ts +15 -0
  82. package/package.json +11 -1
@@ -17,7 +17,7 @@ function withReplayRecordedAt(data, replayRecordedAt) {
17
17
  }
18
18
  return { ...data, replayRecordedAt };
19
19
  }
20
- const REPLAY_TIMED_LIFECYCLE_EVENTS = new Set([
20
+ const REPLAY_TIMED_EVENTS = new Set([
21
21
  'start',
22
22
  'graphStart',
23
23
  'graphOutputsReady',
@@ -32,9 +32,16 @@ const REPLAY_TIMED_LIFECYCLE_EVENTS = new Set([
32
32
  'nodeError',
33
33
  'nodeExcluded',
34
34
  'nodeOutputsCleared',
35
+ // These records retain their own physical call timestamps, but the replay
36
+ // timestamp lets observers keep them on the same historical recording
37
+ // timeline without borrowing a provider timestamp as a node lifecycle time.
38
+ 'llmCallFinished',
39
+ 'llmProfileAttempt',
40
+ 'toolCallFinished',
35
41
  ]);
36
42
  export async function replayExecutionRecording(options) {
37
- const { emitter, erroredNodes, graphOutputs, fallbackGraphId, initialReplayExecution, project, recorder, recordingPlaybackChatLatency, setContextValues, setGraphInputs, setGraphOutputs, setRunning, visitedNodes, waitUntilUnpaused, nodeResults, isAborted, } = options;
43
+ const { emitter, erroredNodes, fallbackGraphId, initialReplayExecution, project, recorder, recordingPlaybackChatLatency, setContextValues, setGraphInputs, setGraphOutputs, setRunning, visitedNodes, waitUntilUnpaused, nodeResults, isAborted, } = options;
44
+ let graphOutputs = options.graphOutputs;
38
45
  const nodesByIdAllGraphs = {};
39
46
  const graphIdByNodeId = {};
40
47
  for (const graph of Object.values(project.graphs)) {
@@ -57,9 +64,7 @@ export async function replayExecutionRecording(options) {
57
64
  // playback error remains attached to that root instead of synthesizing a
58
65
  // second one.
59
66
  hasEmittedRunActivityExecution = true;
60
- const payload = REPLAY_TIMED_LIFECYCLE_EVENTS.has(event)
61
- ? withReplayRecordedAt(data, currentReplayRecordedAt)
62
- : data;
67
+ const payload = REPLAY_TIMED_EVENTS.has(event) ? withReplayRecordedAt(data, currentReplayRecordedAt) : data;
63
68
  emitDetached(emitter, event, payload);
64
69
  };
65
70
  const emitReplayTerminalEvent = (event, data) => {
@@ -165,13 +170,13 @@ export async function replayExecutionRecording(options) {
165
170
  : nanoid();
166
171
  replayRootRunIds.set(recordedExecution.rootRunId, replayRootRunId);
167
172
  }
168
- const getReplayGraphRunId = (recordedGraphRunId) => {
173
+ const getReplayGraphRunId = (recordedGraphRunId, initialGraphRunId) => {
169
174
  let graphRunIds = replayGraphRunIdsByRoot.get(recordedExecution.rootRunId);
170
175
  if (graphRunIds == null) {
171
176
  graphRunIds = new Map();
172
177
  replayGraphRunIdsByRoot.set(recordedExecution.rootRunId, graphRunIds);
173
178
  }
174
- const replayGraphRunId = graphRunIds.get(recordedGraphRunId) ?? nanoid();
179
+ const replayGraphRunId = initialGraphRunId ?? graphRunIds.get(recordedGraphRunId) ?? nanoid();
175
180
  graphRunIds.set(recordedGraphRunId, replayGraphRunId);
176
181
  return replayGraphRunId;
177
182
  };
@@ -183,17 +188,22 @@ export async function replayExecutionRecording(options) {
183
188
  return {
184
189
  ...rest,
185
190
  rootRunId: replayRootRunId,
186
- graphRunId: isInitialRootGraph ? initialReplayExecution.graphRunId : getReplayGraphRunId(graphRunId),
191
+ // Seed the root mapping too, so child parentGraphRunId references resolve
192
+ // to the same identity already allocated by the playback processor.
193
+ graphRunId: getReplayGraphRunId(graphRunId, isInitialRootGraph ? initialReplayExecution.graphRunId : undefined),
187
194
  ...(parentGraphRunId == null ? {} : { parentGraphRunId: getReplayGraphRunId(parentGraphRunId) }),
188
195
  };
189
196
  };
190
197
  const getNodeRunKey = (execution, nodeId, processId) => `${execution.rootRunId}:${execution.graphRunId}:${nodeId}:${processId}`;
191
198
  const getRecordedDuration = (recordedDuration, execution, nodeId, processId, terminalTs) => {
192
- if (recordedDuration !== undefined) {
199
+ if (isValidRecordedDuration(recordedDuration)) {
193
200
  return recordedDuration;
194
201
  }
195
202
  const startedAt = nodeStartTimestamps.get(getNodeRunKey(execution, nodeId, processId));
196
- return startedAt === undefined ? undefined : Math.max(0, terminalTs - startedAt);
203
+ if (!isValidRecordedTimestamp(startedAt) || !isValidRecordedTimestamp(terminalTs) || terminalTs < startedAt) {
204
+ return undefined;
205
+ }
206
+ return terminalTs - startedAt;
197
207
  };
198
208
  for (const event of recorder.events) {
199
209
  if (isAborted()) {
@@ -233,9 +243,13 @@ export async function replayExecutionRecording(options) {
233
243
  }
234
244
  case 'done': {
235
245
  emitFallbackRootTerminal('completed', { outputs: event.data.results });
236
- emitReplayTerminalEvent('done', event.data);
237
- setGraphOutputs(event.data.results);
238
- setRunning(false);
246
+ // Match a live root run: `done` remains inside the active lifecycle
247
+ // so a done listener cannot start work that replay cleanup would
248
+ // clobber. `finish` is emitted once below, after playback releases
249
+ // ownership, so its listener may start a new run.
250
+ await emitter.emit('done', withReplayRecordedAt(event.data, currentReplayRecordedAt));
251
+ graphOutputs = event.data.results;
252
+ setGraphOutputs(graphOutputs);
239
253
  break;
240
254
  }
241
255
  case 'error': {
@@ -348,6 +362,8 @@ export async function replayExecutionRecording(options) {
348
362
  node,
349
363
  error: data.error,
350
364
  processId: data.processId,
365
+ ...(data.outputs === undefined ? {} : { outputs: data.outputs }),
366
+ ...(data.splitOutputs === undefined ? {} : { splitOutputs: data.splitOutputs }),
351
367
  ...(data.resultOrigin === undefined ? {} : { resultOrigin: data.resultOrigin }),
352
368
  execution,
353
369
  }, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event.ts), data.splitRunDurationMs));
@@ -460,7 +476,11 @@ export async function replayExecutionRecording(options) {
460
476
  break;
461
477
  }
462
478
  case 'finish': {
463
- emitDetached(emitter, 'finish', undefined);
479
+ // Current recordings deliberately exclude root `finish`: the
480
+ // recorder uses it only as its sealing signal. Older recordings can
481
+ // contain it, but replay must emit exactly one finish after it has
482
+ // released the lifecycle below, so defer both formats to that one
483
+ // common boundary.
464
484
  break;
465
485
  }
466
486
  default: {
@@ -491,6 +511,18 @@ export async function replayExecutionRecording(options) {
491
511
  }
492
512
  finally {
493
513
  setRunning(false);
514
+ // This must happen after setRunning(false), not merely as a detached
515
+ // emission from the recorded-event loop. A live root finish listener may
516
+ // start the next run; replay has the same contract. It is also the
517
+ // synthetic finish for current recordings, whose recorder omits finish
518
+ // from the replayable event log and uses it only to seal the recording.
519
+ emitDetached(emitter, 'finish', undefined);
494
520
  }
495
521
  return graphOutputs;
496
522
  }
523
+ function isValidRecordedTimestamp(value) {
524
+ return value != null && Number.isFinite(value) && value >= 0;
525
+ }
526
+ function isValidRecordedDuration(value) {
527
+ return value != null && Number.isFinite(value) && value >= 0;
528
+ }
@@ -31,16 +31,14 @@ export async function processSplitRunNode(node, processId, deps) {
31
31
  resultOrigin: 'executed',
32
32
  });
33
33
  const timingStart = deps.startNodeTiming?.();
34
- let splitRunDurationMs;
35
- let results = [];
34
+ const results = [];
36
35
  try {
37
36
  if (node.isSplitSequential) {
38
- results = await runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
37
+ await runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps, results);
39
38
  }
40
39
  else {
41
- results = await runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps);
40
+ results.push(...(await runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps)));
42
41
  }
43
- splitRunDurationMs = getSplitRunDurationMs(results);
44
42
  const errors = results.filter((r) => r.type === 'error').map((r) => r.error);
45
43
  if (errors.length === 1) {
46
44
  throw errors[0];
@@ -51,7 +49,7 @@ export async function processSplitRunNode(node, processId, deps) {
51
49
  }
52
50
  throw new AggregateError(errors);
53
51
  }
54
- const aggregateResults = aggregateOutputs(results);
52
+ const aggregateResults = aggregateOutputs(results.filter(isSplitOutputResult));
55
53
  deps.setNodeResults(node.id, aggregateResults);
56
54
  deps.markNodeVisited(node.id);
57
55
  await deps.emit('nodeFinish', withOptionalDuration({
@@ -59,14 +57,13 @@ export async function processSplitRunNode(node, processId, deps) {
59
57
  outputs: aggregateResults,
60
58
  processId,
61
59
  resultOrigin: getSplitRunResultOrigin(results),
62
- }, deps.finishNodeTiming?.(timingStart), splitRunDurationMs));
60
+ }, deps.finishNodeTiming?.(timingStart), getSplitRunDurationMs(results)));
63
61
  }
64
62
  catch (error) {
65
- await deps.nodeErrored(node, error, processId, deps.finishNodeTiming?.(timingStart), splitRunDurationMs, getSplitRunResultOrigin(results));
63
+ await deps.nodeErrored(node, error, processId, deps.finishNodeTiming?.(timingStart), getSplitRunDurationMs(results), getSplitRunResultOrigin(results), getSplitTerminalOutputs(results));
66
64
  }
67
65
  }
68
- async function runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
69
- const results = [];
66
+ async function runSequential(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps, results) {
70
67
  for (let i = 0; i < splittingAmount; i++) {
71
68
  if (deps.isAborted()) {
72
69
  throw deps.getAbortError();
@@ -87,29 +84,33 @@ async function runSequential(node, inputValues, inputDefinitionsById, splittingA
87
84
  resultOrigin = 'editor-cache';
88
85
  });
89
86
  deps.accumulateCost(output);
90
- results.push({ type: 'output', output, resultOrigin, durationMs: deps.finishNodeTiming?.(splitTimingStart) });
87
+ results.push({ type: 'output', index: i, output, resultOrigin, durationMs: deps.finishNodeTiming?.(splitTimingStart) });
91
88
  }
92
89
  catch (error) {
93
90
  results.push({
94
91
  type: 'error',
95
92
  error: getError(error),
93
+ index: i,
96
94
  resultOrigin,
97
95
  durationMs: deps.finishNodeTiming?.(splitTimingStart),
96
+ failureOutputs: deps.takeFailureOutputs(processId, i),
98
97
  });
99
98
  }
100
99
  }
101
- return results;
102
100
  }
103
101
  async function runParallel(node, inputValues, inputDefinitionsById, splittingAmount, processId, deps) {
104
102
  const queue = new PQueue({ concurrency: getParallelSplitRunConcurrency(node, deps.splitRunConcurrency) });
105
103
  return Promise.all(range(0, splittingAmount).map(async (i) => {
106
104
  const result = await queue.add(async () => {
107
- const splitTimingStart = deps.startNodeTiming?.();
108
105
  let resultOrigin = 'executed';
106
+ let splitTimingStart;
109
107
  try {
110
108
  if (deps.isAborted()) {
111
109
  throw deps.getAbortError();
112
110
  }
111
+ // Queued items that encounter an already-aborted graph never ran,
112
+ // so they must not receive a synthetic split duration.
113
+ splitTimingStart = deps.startNodeTiming?.();
113
114
  const inputs = splitInputsAtIndex(inputValues, inputDefinitionsById, i);
114
115
  const output = await deps.processNodeWithInputData(node, inputs, i, processId, (n, partialOutputs, index) => {
115
116
  deps.emit('partialOutput', {
@@ -125,6 +126,7 @@ async function runParallel(node, inputValues, inputDefinitionsById, splittingAmo
125
126
  deps.accumulateCost(output);
126
127
  return {
127
128
  type: 'output',
129
+ index: i,
128
130
  output,
129
131
  resultOrigin,
130
132
  durationMs: deps.finishNodeTiming?.(splitTimingStart),
@@ -134,8 +136,10 @@ async function runParallel(node, inputValues, inputDefinitionsById, splittingAmo
134
136
  return {
135
137
  type: 'error',
136
138
  error: getError(error),
139
+ index: i,
137
140
  resultOrigin,
138
- durationMs: deps.finishNodeTiming?.(splitTimingStart),
141
+ durationMs: splitTimingStart === undefined ? undefined : deps.finishNodeTiming?.(splitTimingStart),
142
+ failureOutputs: deps.takeFailureOutputs(processId, i),
139
143
  };
140
144
  }
141
145
  });
@@ -150,6 +154,20 @@ function getSplitRunResultOrigin(results) {
150
154
  ? 'editor-cache'
151
155
  : 'executed';
152
156
  }
157
+ /**
158
+ * A failed split node has no graph-semantic aggregate result, but every item
159
+ * that actually ran still has useful inspection evidence. Keep successful
160
+ * item outputs as well as failed-item checkpoints so a terminal nodeError
161
+ * cannot erase siblings that happened to finish before another item failed.
162
+ */
163
+ function getSplitTerminalOutputs(results) {
164
+ const outputs = Object.fromEntries(results.flatMap((result) => result.type === 'output'
165
+ ? [[result.index, result.output]]
166
+ : result.failureOutputs !== undefined
167
+ ? [[result.index, result.failureOutputs]]
168
+ : []));
169
+ return Object.keys(outputs).length === 0 ? undefined : outputs;
170
+ }
153
171
  function getParallelSplitRunConcurrency(node, defaultConcurrency) {
154
172
  const value = node.splitRunConcurrency;
155
173
  return typeof value === 'number' && Number.isFinite(value) && value >= 2 ? Math.floor(value) : defaultConcurrency;
@@ -173,11 +191,14 @@ function aggregateOutputs(results) {
173
191
  return acc;
174
192
  }, {});
175
193
  }
194
+ function isSplitOutputResult(result) {
195
+ return result.type === 'output';
196
+ }
176
197
  function getSplitRunDurationMs(results) {
177
198
  const durations = {};
178
- for (const [index, result] of results.entries()) {
199
+ for (const result of results) {
179
200
  if (result.durationMs !== undefined) {
180
- durations[index] = result.durationMs;
201
+ durations[result.index] = result.durationMs;
181
202
  }
182
203
  }
183
204
  return Object.keys(durations).length > 0 ? durations : undefined;
@@ -87,10 +87,11 @@ export class RivetStoredValueController {
87
87
  }
88
88
  });
89
89
  });
90
+ // Observe the registered wait before checking cancellation again, or an
91
+ // abort while the key lock releases can orphan its rejected promise.
92
+ const value = waiterPromise === undefined ? immediateValue : await waiterPromise;
90
93
  signal?.throwIfAborted();
91
- if (immediateValue !== undefined)
92
- return immediateValue;
93
- return await waiterPromise;
94
+ return value;
94
95
  }
95
96
  async #getUnlocked(key) {
96
97
  const cached = this.#cache.get(key);
@@ -474,6 +474,7 @@ export const RIVET_WEB_APP_RENDERER_CSS = `
474
474
 
475
475
  .rivet-web-app-chat-pins-button,
476
476
  .rivet-web-app-chat-search-button,
477
+ .rivet-web-app-chat-new-button,
477
478
  .rivet-web-app-chat-menu-button,
478
479
  .rivet-web-app-chat-search-close-button,
479
480
  .rivet-web-app-chat-search-navigation-button {
@@ -499,6 +500,18 @@ export const RIVET_WEB_APP_RENDERER_CSS = `
499
500
  border-radius: 10px;
500
501
  }
501
502
 
503
+ .rivet-web-app-chat-new-button {
504
+ min-height: 30px;
505
+ padding: 0 9px;
506
+ border: 1px solid var(--rivet-web-app-control-border);
507
+ border-radius: 7px;
508
+ background: var(--rivet-web-app-control-background);
509
+ color: var(--rivet-web-app-foreground);
510
+ font-size: 0.875em;
511
+ line-height: 1;
512
+ white-space: nowrap;
513
+ }
514
+
502
515
  .rivet-web-app-chat-pins-button {
503
516
  display: inline-flex;
504
517
  align-items: center;
@@ -544,6 +557,13 @@ export const RIVET_WEB_APP_RENDERER_CSS = `
544
557
  outline: none;
545
558
  }
546
559
 
560
+ .rivet-web-app-chat-new-button:hover,
561
+ .rivet-web-app-chat-new-button:focus-visible {
562
+ background: var(--rivet-web-app-control-hover-background);
563
+ color: var(--rivet-web-app-foreground);
564
+ outline: none;
565
+ }
566
+
547
567
  .rivet-web-app-chat-menu {
548
568
  position: absolute;
549
569
  top: calc(100% + 4px);
@@ -28,11 +28,12 @@ export async function consumeAiSdkStream(fullStream, onPartialOutputs, options =
28
28
  case 'text-delta': {
29
29
  textBlocks.set(part.id, `${textBlocks.get(part.id) ?? ''}${part.text}`);
30
30
  responseText = buildResponseText(textBlocks, !!options.dedupeDuplicateTextBlocks);
31
- onPartialOutputs(responseText, functionCalls);
31
+ onPartialOutputs(responseText, functionCalls, reasoning);
32
32
  break;
33
33
  }
34
34
  case 'reasoning-delta': {
35
35
  reasoning += part.text;
36
+ onPartialOutputs(responseText, functionCalls, reasoning);
36
37
  break;
37
38
  }
38
39
  case 'tool-call': {
@@ -43,7 +44,7 @@ export async function consumeAiSdkStream(fullStream, onPartialOutputs, options =
43
44
  arguments: JSON.stringify(part.input),
44
45
  lastParsedArguments: part.input,
45
46
  });
46
- onPartialOutputs(responseText, functionCalls);
47
+ onPartialOutputs(responseText, functionCalls, reasoning);
47
48
  break;
48
49
  }
49
50
  case 'finish': {
@@ -273,8 +273,25 @@ async function resolveGenerateReasoning(result) {
273
273
  }
274
274
  return (await resolveOptionalValue(result.reasoning))?.map((part) => part.text).join('') ?? '';
275
275
  }
276
+ async function resolveGenerateUsage(result) {
277
+ return (await resolveOptionalValue(result.totalUsage)) ?? (await resolveOptionalValue(result.usage));
278
+ }
279
+ function notifyResponseReceived(options, response) {
280
+ try {
281
+ options.onResponseReceived?.(response);
282
+ }
283
+ catch {
284
+ // Failure evidence is observational and must never block provider cleanup.
285
+ }
286
+ }
276
287
  async function executeStream(options, executor) {
277
288
  const args = buildTextArgs(options);
289
+ try {
290
+ options.onRequestStarted?.();
291
+ }
292
+ catch {
293
+ // Failure evidence is observational and must never block a provider call.
294
+ }
278
295
  const firstOutputStartedAt = Date.now();
279
296
  const handlePromise = Promise.resolve(executor(args));
280
297
  const handleTimeout = options.firstOutputTimeoutMs == null
@@ -293,10 +310,11 @@ async function executeStream(options, executor) {
293
310
  markOptionalPromiseHandled(handle.requestStatus);
294
311
  markOptionalPromiseHandled(handle.usage);
295
312
  const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
296
- const streamed = await consumeAiSdkStream(streamWithDeadlines(handle.fullStream, options, firstOutputStartedAt), (text, functionCalls) => {
313
+ const streamed = await consumeAiSdkStream(streamWithDeadlines(handle.fullStream, options, firstOutputStartedAt), (text, functionCalls, reasoning) => {
297
314
  options.onPartialOutput?.({
298
315
  text: isStructuredOutput ? collapseRepeatedStructuredJsonText(text) : text,
299
316
  functionCalls,
317
+ reasoning,
300
318
  });
301
319
  }, {
302
320
  dedupeDuplicateTextBlocks: isStructuredOutput,
@@ -304,9 +322,25 @@ async function executeStream(options, executor) {
304
322
  const responseText = isStructuredOutput
305
323
  ? collapseRepeatedStructuredJsonText(streamed.responseText)
306
324
  : streamed.responseText;
325
+ const usagePromise = streamed.usage != null ? Promise.resolve(streamed.usage) : resolveOptionalValue(handle.usage);
326
+ let evidence = {
327
+ text: responseText,
328
+ functionCalls: streamed.functionCalls,
329
+ reasoning: streamed.reasoning,
330
+ usage: streamed.usage,
331
+ };
332
+ const notifyCurrentResponseEvidence = () => notifyResponseReceived(options, evidence);
333
+ // The stream has completed, so its response, tool calls, and reasoning are
334
+ // real evidence even if a later usage/metadata/structured-output accessor
335
+ // rejects during finalization.
336
+ notifyCurrentResponseEvidence();
337
+ void usagePromise.then((usage) => {
338
+ evidence = { ...evidence, usage };
339
+ notifyCurrentResponseEvidence();
340
+ }, () => undefined);
307
341
  const [structuredOutput, usage, finishReason, providerMetadata, requestStatus] = await waitForPostResponseFinalization(Promise.all([
308
342
  options.responseOutput != null ? resolveOptionalStructuredOutput(handle.output) : undefined,
309
- streamed.usage != null ? streamed.usage : resolveOptionalValue(handle.usage),
343
+ usagePromise,
310
344
  resolveOptionalValue(handle.finishReason),
311
345
  resolveOptionalValue(handle.providerMetadata),
312
346
  resolveOptionalValue(handle.requestStatus),
@@ -328,6 +362,12 @@ export async function streamChatV2(options) {
328
362
  export async function generateChatV2(options) {
329
363
  const args = buildTextArgs(options);
330
364
  const stepToolCalls = attachGenerateStepToolCallCollector(args);
365
+ try {
366
+ options.onRequestStarted?.();
367
+ }
368
+ catch {
369
+ // Failure evidence is observational and must never block a provider call.
370
+ }
331
371
  let result;
332
372
  try {
333
373
  result = await waitForGeneratedResponse(Promise.resolve((options.executeGenerate ?? defaultGenerateExecutor)(args)), options);
@@ -341,12 +381,30 @@ export async function generateChatV2(options) {
341
381
  }
342
382
  const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
343
383
  const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(result.text) : result.text;
384
+ const functionCalls = toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls);
385
+ const reasoningPromise = resolveGenerateReasoning(result);
386
+ const usagePromise = resolveGenerateUsage(result);
387
+ let evidence = { text: responseText, functionCalls, reasoning: '' };
388
+ const notifyCurrentResponseEvidence = () => notifyResponseReceived(options, evidence);
389
+ // generateText has already returned its complete text/tool response here.
390
+ // Snapshot it before optional metadata, schema output, or usage access can
391
+ // fail. Independently resolved diagnostic fields refresh that snapshot so a
392
+ // different finalization error cannot hide them.
393
+ notifyCurrentResponseEvidence();
394
+ void reasoningPromise.then((reasoning) => {
395
+ evidence = { ...evidence, reasoning };
396
+ notifyCurrentResponseEvidence();
397
+ }, () => undefined);
398
+ void usagePromise.then((usage) => {
399
+ evidence = { ...evidence, usage };
400
+ notifyCurrentResponseEvidence();
401
+ }, () => undefined);
344
402
  const [finishReason, structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await waitForPostResponseFinalization((async () => {
345
403
  const finishReason = await resolveOptionalValue(result.finishReason);
346
404
  const [structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await Promise.all([
347
405
  resolveGenerateStructuredOutput(result, options.responseOutput, finishReason),
348
- (async () => (await resolveOptionalValue(result.totalUsage)) ?? (await resolveOptionalValue(result.usage)))(),
349
- resolveGenerateReasoning(result),
406
+ usagePromise,
407
+ reasoningPromise,
350
408
  resolveOptionalValue(result.providerMetadata),
351
409
  resolveOptionalValue(result.requestStatus),
352
410
  ]);
@@ -355,7 +413,7 @@ export async function generateChatV2(options) {
355
413
  return {
356
414
  responseText,
357
415
  structuredOutput,
358
- functionCalls: toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls),
416
+ functionCalls,
359
417
  usage,
360
418
  reasoning,
361
419
  finishReason,
@@ -67,6 +67,33 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
67
67
  const callId = createObservedChatV2CallId(options);
68
68
  const callStartedAt = Date.now();
69
69
  let callWasObserved = false;
70
+ // AI SDK accessors such as usage and reasoning may settle after a request
71
+ // has otherwise failed. Their diagnostic callbacks belong only to this
72
+ // physical request: never let a retired retry/fallback candidate overwrite
73
+ // evidence collected by the current one.
74
+ let acceptsResponseEvidence = true;
75
+ const retireResponseEvidence = () => {
76
+ acceptsResponseEvidence = false;
77
+ };
78
+ let latestResponseEvidence;
79
+ const reportResponseEvidence = (response) => {
80
+ if (!acceptsResponseEvidence) {
81
+ return;
82
+ }
83
+ latestResponseEvidence = response;
84
+ try {
85
+ chatOptions.onResponseReceived?.(response);
86
+ }
87
+ catch {
88
+ // Diagnostic evidence must not alter a retry/fallback decision.
89
+ }
90
+ };
91
+ const publishAndRetireResponseEvidence = () => {
92
+ if (latestResponseEvidence != null) {
93
+ reportResponseEvidence(latestResponseEvidence);
94
+ }
95
+ retireResponseEvidence();
96
+ };
70
97
  const attemptController = new AbortController();
71
98
  const abortAttemptFromCaller = () => attemptController.abort(signal.reason);
72
99
  if (signal.aborted) {
@@ -83,11 +110,13 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
83
110
  streamInactivityTimeoutMs: options.streamInactivityTimeoutMs,
84
111
  onStreamActivity: options.onStreamActivity,
85
112
  onTimeout: (error) => attemptController.abort(error),
113
+ onResponseReceived: reportResponseEvidence,
86
114
  };
87
115
  const result = transportMode === 'generate'
88
116
  ? await generateChatV2(attemptChatOptions)
89
117
  : await streamChatV2(attemptChatOptions);
90
118
  await options.responseBodyCapture?.flush();
119
+ publishAndRetireResponseEvidence();
91
120
  const statusCode = result.requestStatus ?? 200;
92
121
  notifyChatV2CallFinished(options, {
93
122
  callId,
@@ -121,6 +150,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
121
150
  await options.responseBodyCapture?.flush({
122
151
  waitForPending: !signal.aborted && !isChatV2ProviderTimeoutError(error),
123
152
  });
153
+ publishAndRetireResponseEvidence();
124
154
  if (!callWasObserved) {
125
155
  notifyChatV2CallFinished(options, {
126
156
  callId,
@@ -154,6 +184,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
154
184
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
155
185
  }
156
186
  finally {
187
+ retireResponseEvidence();
157
188
  signal.removeEventListener('abort', abortAttemptFromCaller);
158
189
  }
159
190
  }
@@ -181,6 +212,35 @@ export async function runChatV2PipelineExecution(options) {
181
212
  tools,
182
213
  });
183
214
  const shouldStreamResponse = plan.transportMode === 'stream';
215
+ const emitFailureCheckpoint = (partial) => {
216
+ if (options.onFailureCheckpoint == null) {
217
+ return;
218
+ }
219
+ try {
220
+ options.onFailureCheckpoint(createChatV2CommonOutputs({
221
+ requestMessages,
222
+ response: partial.text,
223
+ structuredOutput: undefined,
224
+ functionCalls: partial.functionCalls,
225
+ usage: normalizeChatV2Usage(partial.usage, options),
226
+ reasoning: partial.reasoning,
227
+ requestBodies: options.requestBodies,
228
+ responseBodies: options.responseBodies,
229
+ outputUsage: plan.output.outputUsage,
230
+ outputReasoning: plan.output.outputReasoning,
231
+ outputRequestBody: plan.output.outputRequestBody,
232
+ outputResponseBody: plan.output.outputResponseBody,
233
+ includeFunctionCalls: plan.output.includeFunctionCalls,
234
+ functionCallMode: plan.output.functionCallMode,
235
+ // An incomplete structured reply is still useful diagnostic text,
236
+ // not a schema-valid graph result.
237
+ responseFormat: undefined,
238
+ }));
239
+ }
240
+ catch {
241
+ // Diagnostic capture must not replace the original provider failure.
242
+ }
243
+ };
184
244
  let chatResponse;
185
245
  try {
186
246
  chatResponse = await runChatV2WithRetry(options, {
@@ -188,20 +248,23 @@ export async function runChatV2PipelineExecution(options) {
188
248
  abortSignal: options.context.signal,
189
249
  executeStream: options.executeStream,
190
250
  executeGenerate: options.executeGenerate,
251
+ onRequestStarted: () => emitFailureCheckpoint({ text: '', functionCalls: [], reasoning: '' }),
252
+ onResponseReceived: emitFailureCheckpoint,
191
253
  onPartialOutput: !shouldStreamResponse
192
254
  ? undefined
193
- : ({ text, functionCalls }) => {
255
+ : ({ text, functionCalls, reasoning }) => {
256
+ emitFailureCheckpoint({ text, functionCalls, reasoning });
194
257
  options.context.onPartialOutputs?.(createChatV2CommonOutputs({
195
258
  requestMessages,
196
259
  response: text,
197
260
  structuredOutput: undefined,
198
261
  functionCalls,
199
262
  usage: undefined,
200
- reasoning: '',
263
+ reasoning,
201
264
  requestBodies: undefined,
202
265
  responseBodies: undefined,
203
266
  outputUsage: false,
204
- outputReasoning: false,
267
+ outputReasoning: plan.output.outputReasoning,
205
268
  outputRequestBody: false,
206
269
  outputResponseBody: false,
207
270
  includeFunctionCalls: plan.output.includeFunctionCalls,
@@ -5,13 +5,18 @@ import { createChatV2CapturedBodyOutputs } from './chatV2Outputs.js';
5
5
  * Captured HTTP bodies are emitted only through their opt-in ports, while
6
6
  * attempts and profile summaries retain the same public shapes as a success.
7
7
  */
8
- export function projectLLMInvocationDiagnostics({ runOptions, outputLLMAttempts, llmAttempts, profileSummary, }) {
8
+ export function projectLLMInvocationDiagnostics({ runOptions, outputLLMAttempts, modelCalls, outputUsage, llmAttempts, profileSummary, }) {
9
9
  const capturedBodies = createChatV2CapturedBodyOutputs(runOptions);
10
10
  return {
11
11
  ...Object.fromEntries(Object.entries(capturedBodies).filter(([, output]) => output?.type !== 'control-flow-excluded')),
12
+ ...projectLLMInvocationUsageOutput({ modelCalls, outputUsage }),
12
13
  ...projectLLMInvocationMetadata({ outputLLMAttempts, llmAttempts, profileSummary }),
13
14
  };
14
15
  }
16
+ /** Combines streamed response state with terminal diagnostics without hiding either. */
17
+ export function mergeLLMInvocationFailureOutputs(partialOutputs, diagnostics) {
18
+ return { ...partialOutputs, ...diagnostics };
19
+ }
15
20
  function projectLLMInvocationMetadata(params) {
16
21
  const { outputLLMAttempts, llmAttempts, profileSummary } = params;
17
22
  const outputs = {};
@@ -32,12 +37,10 @@ function projectLLMInvocationMetadata(params) {
32
37
  /** Applies existing public LLM Chat output shapes from invocation facts. */
33
38
  export function projectLLMInvocationResult(params) {
34
39
  const { result, modelCalls, outputUsage, outputLLMAttempts, llmAttempts, profileSummary } = params;
35
- if (outputUsage && modelCalls.length > 0) {
36
- const physicalUsage = projectLLMInvocationUsage(modelCalls);
37
- if (physicalUsage != null) {
38
- result.usage = physicalUsage;
39
- result.commonOutputs['usage'] = { type: 'object', value: physicalUsage };
40
- }
40
+ const usage = getLLMInvocationUsage({ modelCalls, outputUsage });
41
+ if (usage != null) {
42
+ result.usage = usage;
43
+ result.commonOutputs['usage'] = { type: 'object', value: usage };
41
44
  }
42
45
  Object.assign(result.commonOutputs, projectLLMInvocationMetadata({
43
46
  outputLLMAttempts,
@@ -46,3 +49,13 @@ export function projectLLMInvocationResult(params) {
46
49
  }));
47
50
  return result.commonOutputs;
48
51
  }
52
+ function projectLLMInvocationUsageOutput({ modelCalls, outputUsage, }) {
53
+ const usage = getLLMInvocationUsage({ modelCalls, outputUsage });
54
+ return usage == null ? {} : { ['usage']: { type: 'object', value: usage } };
55
+ }
56
+ function getLLMInvocationUsage({ modelCalls, outputUsage, }) {
57
+ if (!outputUsage || modelCalls.length === 0) {
58
+ return undefined;
59
+ }
60
+ return projectLLMInvocationUsage(modelCalls) ?? undefined;
61
+ }