@valerypopoff/rivet2-core 2.5.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 (30) hide show
  1. package/dist/cjs/bundle.cjs +370 -84
  2. package/dist/cjs/bundle.cjs.map +3 -3
  3. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  4. package/dist/esm/model/AgentResponseTrace.js +8 -3
  5. package/dist/esm/model/GraphProcessor.js +41 -6
  6. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  7. package/dist/esm/model/RecordingPlayer.js +37 -10
  8. package/dist/esm/model/SplitRunProcessor.js +37 -16
  9. package/dist/esm/model/UiGraphRendererStyles.js +20 -0
  10. package/dist/esm/model/chat/aiSdkStreaming.js +3 -2
  11. package/dist/esm/model/chat-v2/aiSdkBridge.js +63 -5
  12. package/dist/esm/model/chat-v2/chatV2Pipeline.js +66 -3
  13. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +20 -7
  14. package/dist/esm/model/chat-v2/llmProfileFallback.js +12 -4
  15. package/dist/esm/model/nodes/LLMChatV2Node.js +30 -4
  16. package/dist/esm/recording/ExecutionRecorder.js +55 -23
  17. package/dist/types/model/AgentResponseTrace.d.ts +2 -0
  18. package/dist/types/model/ExecutorProtocol.d.ts +4 -0
  19. package/dist/types/model/GraphProcessor.d.ts +8 -0
  20. package/dist/types/model/ProcessContext.d.ts +6 -0
  21. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  22. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  23. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  24. package/dist/types/model/chat/aiSdkStreaming.d.ts +1 -1
  25. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +1 -1
  26. package/dist/types/model/chat-v2/chatV2Types.d.ts +29 -0
  27. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +5 -1
  28. package/dist/types/recording/ExecutionRecorder.d.ts +6 -1
  29. package/dist/types/recording/RecordedEvents.d.ts +2 -0
  30. package/package.json +1 -1
@@ -29,6 +29,13 @@ export function buildAgentResponseTrace(options) {
29
29
  .map(toToolCallTrace);
30
30
  const summary = summarizeAgentCalls(allModelCalls, allProfileAttempts, allToolCalls);
31
31
  const terminalAt = options.responseReadyAt ?? options.finishedAt;
32
+ const durationMs = options.scope === 'llm-invocation' && isNonNegativeFiniteNumber(options.invocationDurationMs)
33
+ ? options.invocationDurationMs
34
+ : isNonNegativeFiniteNumber(options.startedAt) &&
35
+ isNonNegativeFiniteNumber(terminalAt) &&
36
+ terminalAt >= options.startedAt
37
+ ? terminalAt - options.startedAt
38
+ : undefined;
32
39
  return {
33
40
  schemaVersion: AGENT_RESPONSE_TRACE_SCHEMA_VERSION,
34
41
  traceId: options.execution.rootRunId,
@@ -41,9 +48,7 @@ export function buildAgentResponseTrace(options) {
41
48
  ...(options.startedAt == null ? {} : { startedAt: options.startedAt }),
42
49
  ...(options.responseReadyAt == null ? {} : { responseReadyAt: options.responseReadyAt }),
43
50
  ...(options.finishedAt == null ? {} : { finishedAt: options.finishedAt }),
44
- ...(options.startedAt == null || terminalAt == null
45
- ? {}
46
- : { durationMs: Math.max(0, terminalAt - options.startedAt) }),
51
+ ...(durationMs === undefined ? {} : { durationMs }),
47
52
  status: options.status,
48
53
  ...(options.backgroundWorkPending == null ? {} : { backgroundWorkPending: options.backgroundWorkPending }),
49
54
  summary,
@@ -186,6 +186,7 @@ export class GraphProcessor {
186
186
  warnOnInvalidGraph = false;
187
187
  // Per-process state
188
188
  #erroredNodes = undefined; // Values are strings in recordings
189
+ #failureOutputsByProcessId = undefined;
189
190
  #remainingNodes = undefined;
190
191
  #visitedNodes = undefined;
191
192
  #currentlyProcessing = undefined;
@@ -642,6 +643,7 @@ export class GraphProcessor {
642
643
  this.#visitedNodes = new Set(this.#preloadedNodeResults.keys());
643
644
  this.#hasPreloadedData = this.#preloadedNodeResults.size > 0;
644
645
  this.#erroredNodes = new Map();
646
+ this.#failureOutputsByProcessId = new Map();
645
647
  this.#currentlyProcessing = new Set();
646
648
  // A processor may be constructed with a reusable execution plan. In that
647
649
  // case preprocessing happened before this run, so retain the compiled
@@ -1160,7 +1162,6 @@ export class GraphProcessor {
1160
1162
  }
1161
1163
  async #finalizeGraphRun() {
1162
1164
  const outputValues = this.#graphOutputs;
1163
- this.#lifecycle.complete();
1164
1165
  if (this.#suppressGraphLifecycleEvents) {
1165
1166
  return outputValues;
1166
1167
  }
@@ -1168,7 +1169,6 @@ export class GraphProcessor {
1168
1169
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
1169
1170
  if (!this.#isSubProcessor) {
1170
1171
  await this.#emitter.emit('done', { results: outputValues });
1171
- await this.#emitFinishIfNeeded();
1172
1172
  }
1173
1173
  return outputValues;
1174
1174
  }
@@ -1700,7 +1700,8 @@ export class GraphProcessor {
1700
1700
  accumulateCost: (output) => this.#accumulateCost(output),
1701
1701
  setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
1702
1702
  markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
1703
- nodeErrored: (n, err, pid, durationMs, splitRunDurationMs, resultOrigin) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs, resultOrigin),
1703
+ nodeErrored: (n, err, pid, durationMs, splitRunDurationMs, resultOrigin, splitOutputs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs, resultOrigin, undefined, splitOutputs),
1704
+ takeFailureOutputs: (pid, index) => this.#takeFailureOutputs(pid, index),
1704
1705
  isAborted: () => this.#lifecycle.isAborted,
1705
1706
  getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
1706
1707
  emit: (event, data) => {
@@ -1782,11 +1783,15 @@ export class GraphProcessor {
1782
1783
  }, this.#finishNodeTiming(timingStart))));
1783
1784
  }
1784
1785
  catch (error) {
1785
- await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart), undefined, resultOrigin);
1786
+ await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart), undefined, resultOrigin, this.#takeFailureOutputs(processId, 0));
1786
1787
  }
1787
1788
  }
1788
- async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs, resultOrigin = 'executed') {
1789
+ async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs, resultOrigin = 'executed', outputs, splitOutputs) {
1789
1790
  const error = getError(e);
1791
+ // Most callers are ordinary (non-split) node executions. Let those retain
1792
+ // any checkpoint without requiring every error path to know about the
1793
+ // internal map. Split callers provide their per-index map explicitly.
1794
+ const retainedOutputs = splitOutputs === undefined ? (outputs ?? this.#takeFailureOutputs(processId, 0)) : outputs;
1790
1795
  const exclusionReason = this.#getErrorExclusionReason(node, error, processId);
1791
1796
  if (exclusionReason) {
1792
1797
  await this.#emitNodeExcluded(node, processId, this.#getInputValuesForNode(node), exclusionReason, resultOrigin);
@@ -1794,12 +1799,39 @@ export class GraphProcessor {
1794
1799
  return;
1795
1800
  }
1796
1801
  this.#erroredNodes.set(node.id, error);
1797
- await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({ node, error, processId, resultOrigin }, durationMs, splitRunDurationMs)));
1802
+ await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({
1803
+ node,
1804
+ error,
1805
+ processId,
1806
+ resultOrigin,
1807
+ ...(retainedOutputs === undefined ? {} : { outputs: retainedOutputs }),
1808
+ ...(splitOutputs === undefined ? {} : { splitOutputs }),
1809
+ }, durationMs, splitRunDurationMs)));
1798
1810
  this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);
1799
1811
  }
1800
1812
  #emitNodePartialOutput(node, outputs, index, processId) {
1801
1813
  emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs, index, processId, resultOrigin: 'executed' }));
1802
1814
  }
1815
+ #setFailureOutputs(processId, index, outputs) {
1816
+ let outputsByIndex = this.#failureOutputsByProcessId.get(processId);
1817
+ if (!outputsByIndex) {
1818
+ outputsByIndex = new Map();
1819
+ this.#failureOutputsByProcessId.set(processId, outputsByIndex);
1820
+ }
1821
+ outputsByIndex.set(index, outputs);
1822
+ }
1823
+ #takeFailureOutputs(processId, index) {
1824
+ const outputsByIndex = this.#failureOutputsByProcessId.get(processId);
1825
+ const outputs = outputsByIndex?.get(index);
1826
+ outputsByIndex?.delete(index);
1827
+ if (outputsByIndex?.size === 0) {
1828
+ this.#failureOutputsByProcessId.delete(processId);
1829
+ }
1830
+ return outputs;
1831
+ }
1832
+ #discardFailureOutputs(processId, index) {
1833
+ this.#takeFailureOutputs(processId, index);
1834
+ }
1803
1835
  #getErrorExclusionReason(node, error, processId) {
1804
1836
  if (this.#getAttachedDataTo(node).races?.completed) {
1805
1837
  return RACE_LOSER_EXCLUSION_REASON;
@@ -1939,6 +1971,7 @@ export class GraphProcessor {
1939
1971
  if (nodeAbortController.signal.aborted) {
1940
1972
  if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
1941
1973
  this.#successfulAbortTerminalProcessIds.add(processId);
1974
+ this.#discardFailureOutputs(processId, index);
1942
1975
  return results;
1943
1976
  }
1944
1977
  else {
@@ -1947,6 +1980,7 @@ export class GraphProcessor {
1947
1980
  }
1948
1981
  this.#finalizeToolCallContinuation(processId, index, results);
1949
1982
  continuationFinalized = true;
1983
+ this.#discardFailureOutputs(processId, index);
1950
1984
  return results;
1951
1985
  }
1952
1986
  finally {
@@ -1978,6 +2012,7 @@ export class GraphProcessor {
1978
2012
  partialOutput?.(node, partialOutputs, index);
1979
2013
  this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
1980
2014
  },
2015
+ setFailureOutputs: (outputs) => this.#setFailureOutputs(processId, index, outputs),
1981
2016
  processId,
1982
2017
  requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId, nodeAbortController.signal),
1983
2018
  reportProgress: (progress) => {
@@ -1,5 +1,5 @@
1
1
  export function buildNodeProcessContext(options) {
2
- const { attachedData, activeOutputPortIds, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, markResultAsEditorCacheHit, node, nodeAbortController, onPartialOutputs, processId, requestUserInput, reportProgress, setGlobal, splitIndex, toolCallContinuation, toolCallTraceSource, waitEvent, } = options;
2
+ const { attachedData, activeOutputPortIds, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, markResultAsEditorCacheHit, node, nodeAbortController, onPartialOutputs, setFailureOutputs, processId, requestUserInput, reportProgress, setGlobal, splitIndex, toolCallContinuation, toolCallTraceSource, waitEvent, } = options;
3
3
  return {
4
4
  ...base,
5
5
  node,
@@ -12,6 +12,7 @@ export function buildNodeProcessContext(options) {
12
12
  waitForStoredValue: (key, signal = nodeAbortController.signal) => base.waitForStoredValue(key, signal),
13
13
  externalFunctions: { ...externalFunctions },
14
14
  onPartialOutputs,
15
+ setFailureOutputs,
15
16
  signal: nodeAbortController.signal,
16
17
  processId,
17
18
  splitIndex,
@@ -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,6 +32,12 @@ 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
43
  const { emitter, erroredNodes, fallbackGraphId, initialReplayExecution, project, recorder, recordingPlaybackChatLatency, setContextValues, setGraphInputs, setGraphOutputs, setRunning, visitedNodes, waitUntilUnpaused, nodeResults, isAborted, } = options;
@@ -58,9 +64,7 @@ export async function replayExecutionRecording(options) {
58
64
  // playback error remains attached to that root instead of synthesizing a
59
65
  // second one.
60
66
  hasEmittedRunActivityExecution = true;
61
- const payload = REPLAY_TIMED_LIFECYCLE_EVENTS.has(event)
62
- ? withReplayRecordedAt(data, currentReplayRecordedAt)
63
- : data;
67
+ const payload = REPLAY_TIMED_EVENTS.has(event) ? withReplayRecordedAt(data, currentReplayRecordedAt) : data;
64
68
  emitDetached(emitter, event, payload);
65
69
  };
66
70
  const emitReplayTerminalEvent = (event, data) => {
@@ -192,11 +196,14 @@ export async function replayExecutionRecording(options) {
192
196
  };
193
197
  const getNodeRunKey = (execution, nodeId, processId) => `${execution.rootRunId}:${execution.graphRunId}:${nodeId}:${processId}`;
194
198
  const getRecordedDuration = (recordedDuration, execution, nodeId, processId, terminalTs) => {
195
- if (recordedDuration !== undefined) {
199
+ if (isValidRecordedDuration(recordedDuration)) {
196
200
  return recordedDuration;
197
201
  }
198
202
  const startedAt = nodeStartTimestamps.get(getNodeRunKey(execution, nodeId, processId));
199
- 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;
200
207
  };
201
208
  for (const event of recorder.events) {
202
209
  if (isAborted()) {
@@ -236,11 +243,13 @@ export async function replayExecutionRecording(options) {
236
243
  }
237
244
  case 'done': {
238
245
  emitFallbackRootTerminal('completed', { outputs: event.data.results });
239
- emitReplayTerminalEvent('done', event.data);
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));
240
251
  graphOutputs = event.data.results;
241
252
  setGraphOutputs(graphOutputs);
242
- // Keep ownership until playback drains, just like a live graph run.
243
- // A done listener must not start work that final cleanup could clobber.
244
253
  break;
245
254
  }
246
255
  case 'error': {
@@ -353,6 +362,8 @@ export async function replayExecutionRecording(options) {
353
362
  node,
354
363
  error: data.error,
355
364
  processId: data.processId,
365
+ ...(data.outputs === undefined ? {} : { outputs: data.outputs }),
366
+ ...(data.splitOutputs === undefined ? {} : { splitOutputs: data.splitOutputs }),
356
367
  ...(data.resultOrigin === undefined ? {} : { resultOrigin: data.resultOrigin }),
357
368
  execution,
358
369
  }, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event.ts), data.splitRunDurationMs));
@@ -465,7 +476,11 @@ export async function replayExecutionRecording(options) {
465
476
  break;
466
477
  }
467
478
  case 'finish': {
468
- 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.
469
484
  break;
470
485
  }
471
486
  default: {
@@ -496,6 +511,18 @@ export async function replayExecutionRecording(options) {
496
511
  }
497
512
  finally {
498
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);
499
520
  }
500
521
  return graphOutputs;
501
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;
@@ -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,