@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
@@ -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
+ }
@@ -456,7 +456,9 @@ export function createLLMProfileFallbackRunner(params) {
456
456
  healthDisposition: 'deny',
457
457
  ...(begin.retryAt == null ? {} : { retryAt: begin.retryAt }),
458
458
  });
459
- clearPartialResponse(roundOptions);
459
+ if (profileIndex + 1 < params.candidates.length) {
460
+ clearPartialResponse(roundOptions);
461
+ }
460
462
  continue;
461
463
  }
462
464
  const permitId = begin.permitId;
@@ -530,7 +532,9 @@ export function createLLMProfileFallbackRunner(params) {
530
532
  outcome: 'failure',
531
533
  error: getLLMAttemptErrorMessage(error),
532
534
  });
533
- clearPartialResponse(roundOptions);
535
+ if (profileIndex + 1 < params.candidates.length) {
536
+ clearPartialResponse(roundOptions);
537
+ }
534
538
  await healthPermit?.finish('ignored');
535
539
  continue;
536
540
  }
@@ -617,7 +621,9 @@ export function createLLMProfileFallbackRunner(params) {
617
621
  outcome: 'failure',
618
622
  error: getLLMAttemptErrorMessage(error),
619
623
  });
620
- clearPartialResponse(roundOptions);
624
+ if (profileIndex + 1 < params.candidates.length) {
625
+ clearPartialResponse(roundOptions);
626
+ }
621
627
  await healthPermit?.finish('ignored');
622
628
  continue;
623
629
  }
@@ -629,7 +635,9 @@ export function createLLMProfileFallbackRunner(params) {
629
635
  }
630
636
  lastError = execution.failure.normalizedError;
631
637
  await healthPermit?.finish(isUnhealthyLLMProfileProviderFailure(execution.failure.normalizedError) ? 'unhealthy' : 'ignored');
632
- clearPartialResponse(roundOptions);
638
+ if (profileIndex + 1 < params.candidates.length) {
639
+ clearPartialResponse(roundOptions);
640
+ }
633
641
  }
634
642
  exhausted = true;
635
643
  // A scalar profile keeps its underlying provider/configuration error.
@@ -9,7 +9,7 @@ import { getLLMChatV2BodySections } from '../chat-v2/llmChatV2Body.js';
9
9
  import { isLLMChatV2StructuredResponseFormat } from '../chat-v2/chatV2FeatureCompatibility.js';
10
10
  import { LLMInvocationJournal } from '../chat-v2/llmInvocationJournal.js';
11
11
  import { executeLLMInvocation } from '../chat-v2/llmInvocationCoordinator.js';
12
- import { projectLLMInvocationDiagnostics, projectLLMInvocationResult, } from '../chat-v2/llmInvocationResultProjector.js';
12
+ import { mergeLLMInvocationFailureOutputs, projectLLMInvocationDiagnostics, projectLLMInvocationResult, } from '../chat-v2/llmInvocationResultProjector.js';
13
13
  import { isChatV2PipelineProviderFailureResult } from '../chat-v2/chatV2Pipeline.js';
14
14
  import { shouldOutputChatV2RequestBody, shouldOutputChatV2ResponseBody } from '../chat-v2/chatV2Types.js';
15
15
  import { buildLLMChatV2EditorCacheKey, resolveLLMChatV2RuntimeConfig, resolveLLMChatV2RuntimeProviderOptions, } from '../chat-v2/llmChatV2NodeRuntime.js';
@@ -264,6 +264,7 @@ export class LLMChatV2NodeImpl extends NodeImpl {
264
264
  async process(inputs, context) {
265
265
  const invocationJournal = new LLMInvocationJournal();
266
266
  let profileAttemptSequence = 0;
267
+ let latestFailureEvidence;
267
268
  // Retries, fallback profiles, and tool continuation produce several
268
269
  // physical provider calls underneath one node invocation. Always observe
269
270
  // them locally so every later output projection shares one truthful
@@ -306,7 +307,18 @@ export class LLMChatV2NodeImpl extends NodeImpl {
306
307
  invocation = await executeLLMInvocation({
307
308
  context,
308
309
  journal: invocationJournal,
309
- runtime,
310
+ runtime: {
311
+ ...runtime,
312
+ runOptions: {
313
+ ...runtime.runOptions,
314
+ onFailureCheckpoint: (outputs) => {
315
+ // The pipeline emits request/response evidence separately from
316
+ // presentation updates. Snapshot it here because streams and
317
+ // tool continuation may keep accumulating after this callback.
318
+ latestFailureEvidence = cloneLLMChatV2Outputs(outputs);
319
+ },
320
+ },
321
+ },
310
322
  toolCallContinuation,
311
323
  });
312
324
  }
@@ -315,11 +327,25 @@ export class LLMChatV2NodeImpl extends NodeImpl {
315
327
  const diagnostics = projectLLMInvocationDiagnostics({
316
328
  runOptions: runtime.runOptions,
317
329
  outputLLMAttempts: this.data.outputLLMAttempts,
330
+ modelCalls: invocationJournal.modelCalls,
331
+ outputUsage: this.data.outputUsage,
318
332
  llmAttempts: invocationJournal.llmAttempts,
319
333
  profileSummary: runtime.getProfileSummary?.(),
320
334
  });
321
- if (Object.keys(diagnostics).length > 0) {
322
- context.onPartialOutputs?.(diagnostics);
335
+ const failureOutputs = mergeLLMInvocationFailureOutputs(latestFailureEvidence, diagnostics);
336
+ if (Object.keys(failureOutputs).length > 0) {
337
+ // This checkpoint is the durable terminal counterpart to the live
338
+ // partial-output stream. GraphProcessor attaches it to nodeError,
339
+ // so recordings and remote executors cannot lose evidence merely
340
+ // because their recorder omits transient partial events.
341
+ if (context.setFailureOutputs) {
342
+ context.setFailureOutputs(failureOutputs);
343
+ }
344
+ else {
345
+ // Keep direct/custom node consumers working without asking them
346
+ // to implement the GraphProcessor-only terminal channel.
347
+ context.onPartialOutputs?.(failureOutputs);
348
+ }
323
349
  }
324
350
  }
325
351
  catch {
@@ -37,13 +37,22 @@ const toRecordedEventMap = {
37
37
  processId,
38
38
  ...(resultOrigin === undefined ? {} : { resultOrigin }),
39
39
  }, durationMs, splitRunDurationMs), execution),
40
- nodeError: ({ node, error, processId, resultOrigin, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
40
+ nodeError: ({ node, error, processId, outputs, splitOutputs, resultOrigin, durationMs, splitRunDurationMs, execution }) => withExecution(withDuration({
41
41
  nodeId: node.id,
42
42
  error: typeof error === 'string' ? error : error.stack,
43
43
  processId,
44
+ ...(outputs === undefined ? {} : { outputs }),
45
+ ...(splitOutputs === undefined ? {} : { splitOutputs }),
44
46
  ...(resultOrigin === undefined ? {} : { resultOrigin }),
45
47
  }, durationMs, splitRunDurationMs), execution),
46
- abort: ({ successful, error }) => ({ successful, error: typeof error === 'string' ? error : error?.stack }),
48
+ // Older debugger servers sent a null abort payload. Preserve that evidence
49
+ // instead of letting a malformed legacy transport message abort the whole
50
+ // recording. An unknown payload is deliberately treated as unsuccessful;
51
+ // it must never be mistaken for a completed graph run during replay.
52
+ abort: (data) => {
53
+ const { successful, error } = data ?? {};
54
+ return { successful: successful === true, error: typeof error === 'string' ? error : error?.stack };
55
+ },
47
56
  graphAbort: ({ successful, error, graph, execution }) => withExecution({
48
57
  successful,
49
58
  error: typeof error === 'string' ? error : error?.stack,
@@ -140,6 +149,10 @@ function omitReplayRecordedAt(data) {
140
149
  function isRecordableProcessEvent(message) {
141
150
  return message in toRecordedEventMap || isPrefix(message, 'globalSet:') || isPrefix(message, 'userEvent:');
142
151
  }
152
+ // WebSocket.OPEN/CLOSED are static browser constants. Core is also used by
153
+ // Node transports that can supply a compatible socket without installing that
154
+ // browser global, so compare the standardized ready-state value directly.
155
+ const CLOSED_WEBSOCKET_READY_STATE = 3;
143
156
  function mapValuesDeep(obj, fn) {
144
157
  if (Array.isArray(obj)) {
145
158
  return obj.map((value) => {
@@ -233,14 +246,22 @@ export class ExecutionRecorder {
233
246
  return new Promise((resolve) => {
234
247
  this.recordingId = nanoid();
235
248
  let settled = false;
236
- const finish = () => {
249
+ const finish = (emitFinishedRecording) => {
237
250
  if (settled)
238
251
  return;
239
252
  settled = true;
240
253
  channel.removeEventListener('message', listener);
241
- options.signal?.removeEventListener('abort', finish);
254
+ channel.removeEventListener('close', onClose);
255
+ options.signal?.removeEventListener('abort', onOwnerDisposed);
256
+ if (emitFinishedRecording) {
257
+ emitDetached(this.#emitter, 'finish', {
258
+ recording: this.getRecording(),
259
+ });
260
+ }
242
261
  resolve();
243
262
  };
263
+ const onClose = () => finish(false);
264
+ const onOwnerDisposed = () => finish(false);
244
265
  const listener = (event) => {
245
266
  let payload;
246
267
  try {
@@ -265,24 +286,39 @@ export class ExecutionRecorder {
265
286
  return;
266
287
  }
267
288
  this.#events.push(toRecordedEvent(message, data));
268
- if (isRecordingTerminalEvent(message, data)) {
269
- emitDetached(this.#emitter, 'finish', {
270
- recording: this.getRecording(),
271
- });
272
- finish();
289
+ if (isSocketRecordingTerminalEvent(message)) {
290
+ finish(true);
273
291
  }
274
292
  };
275
293
  if (options.signal?.aborted) {
276
- finish();
294
+ onOwnerDisposed();
277
295
  return;
278
296
  }
279
297
  channel.addEventListener('message', listener);
280
- options.signal?.addEventListener('abort', finish, { once: true });
298
+ channel.addEventListener('close', onClose, { once: true });
299
+ options.signal?.addEventListener('abort', onOwnerDisposed, { once: true });
300
+ if (channel.readyState === CLOSED_WEBSOCKET_READY_STATE) {
301
+ onClose();
302
+ }
281
303
  });
282
304
  }
283
305
  record(processor) {
284
306
  this.recordingId = nanoid();
285
- processor.onAny((event, data) => {
307
+ let settled = false;
308
+ const finish = () => {
309
+ if (settled)
310
+ return;
311
+ settled = true;
312
+ unsubscribeAny();
313
+ unsubscribeFinish();
314
+ emitDetached(this.#emitter, 'finish', {
315
+ recording: this.getRecording(),
316
+ });
317
+ };
318
+ const unsubscribeAny = processor.onAny((event, data) => {
319
+ if (settled || event === 'finish') {
320
+ return;
321
+ }
286
322
  if (this.#includePartialOutputs === false && event === 'partialOutput') {
287
323
  return;
288
324
  }
@@ -290,17 +326,16 @@ export class ExecutionRecorder {
290
326
  return;
291
327
  }
292
328
  this.#events.push(toRecordedEvent(event, data));
293
- if (isRecordingTerminalEvent(event, data)) {
294
- emitDetached(this.#emitter, 'finish', {
295
- recording: this.getRecording(),
296
- });
297
- }
298
329
  });
330
+ const unsubscribeFinish = processor.on('finish', finish);
299
331
  }
300
332
  getRecording() {
301
333
  return {
302
334
  recordingId: this.recordingId,
303
- events: this.#events,
335
+ // Callers persist and replay recordings asynchronously. Returning the
336
+ // live backing array would let a later event mutate an already-finished
337
+ // recording snapshot.
338
+ events: [...this.#events],
304
339
  startTs: this.#events[0]?.ts ?? 0,
305
340
  finishTs: this.#events[this.#events.length - 1]?.ts ?? 0,
306
341
  };
@@ -334,9 +369,6 @@ export class ExecutionRecorder {
334
369
  return stringifyJsonStream(serializeToObject(this.getRecording()));
335
370
  }
336
371
  }
337
- function isRecordingTerminalEvent(event, data) {
338
- if (event === 'done' || event === 'error') {
339
- return true;
340
- }
341
- return event === 'abort' && data.successful !== true;
372
+ function isSocketRecordingTerminalEvent(event) {
373
+ return event === 'done' || event === 'error';
342
374
  }
@@ -96,6 +96,8 @@ export type BuildAgentResponseTraceOptions = {
96
96
  events: readonly AgentTraceEvent[];
97
97
  nodeId?: NodeId;
98
98
  processId?: ProcessId;
99
+ /** Recorded whole-node duration for an LLM invocation; response traces retain their output-ready duration. */
100
+ invocationDurationMs?: number;
99
101
  startedAt?: number;
100
102
  responseReadyAt?: number;
101
103
  finishedAt?: number;
@@ -71,6 +71,10 @@ export type SerializedProcessEventMap = {
71
71
  node: ChartNode;
72
72
  error: Error | string;
73
73
  processId: ProcessId;
74
+ /** Display-only outputs retained by a failed non-split invocation. */
75
+ outputs?: Outputs;
76
+ /** Display-only outputs retained by individual failed split invocations. */
77
+ splitOutputs?: Record<number, Outputs>;
74
78
  resultOrigin?: NodeResultOrigin;
75
79
  durationMs?: number;
76
80
  splitRunDurationMs?: Record<number, number>;
@@ -84,6 +84,14 @@ export type ProcessEvents = {
84
84
  node: ChartNode;
85
85
  error: Error | string;
86
86
  processId: ProcessId;
87
+ /** Display-only outputs retained by a failed non-split invocation. */
88
+ outputs?: Outputs;
89
+ /**
90
+ * Display-only evidence retained by split items that actually ran. It can
91
+ * contain completed sibling outputs and failed-item checkpoints, but is
92
+ * never a successful aggregate result or downstream input.
93
+ */
94
+ splitOutputs?: Record<number, Outputs>;
87
95
  resultOrigin?: NodeResultOrigin;
88
96
  durationMs?: number;
89
97
  splitRunDurationMs?: Record<number, number>;
@@ -301,6 +301,12 @@ export type InternalProcessContext<T extends ChartNode = ChartNode> = ProcessCon
301
301
  getGraphBoundary?: (project: Project, graphId: GraphId | undefined) => GraphBoundary | undefined;
302
302
  /** Call when the node has partial data but has not finished execution yet. */
303
303
  onPartialOutputs?: (outputs: Outputs) => void;
304
+ /**
305
+ * Preserves display-only outputs for this invocation if it subsequently
306
+ * fails. These values are reported with nodeError, never used as graph
307
+ * results, and must not change the original failure.
308
+ */
309
+ setFailureOutputs?: (outputs: Outputs) => void;
304
310
  /** Creates a subprocessor, for executing subgraphs. */
305
311
  createSubProcessor: (subGraphId: GraphId | undefined, options?: {
306
312
  signal?: AbortSignal;
@@ -4,7 +4,7 @@ import type { ChartNode, PortId } from './NodeBase.js';
4
4
  import type { GraphId } from './NodeGraph.js';
5
5
  import type { Project } from './Project.js';
6
6
  import type { AttachedNodeData, ExternalFunction, Outputs } from './GraphProcessor.js';
7
- export type NodeProcessContextBase = Omit<InternalProcessContext, 'attachedData' | 'activeOutputPortIds' | 'createSubProcessor' | 'execution' | 'externalFunctions' | 'getPluginConfig' | 'node' | 'onPartialOutputs' | 'processId' | 'requestUserInput' | 'reportProgress' | 'isDirectRunTarget' | 'markResultAsEditorCacheHit' | 'setGlobal' | 'signal' | 'splitIndex' | 'toolCallContinuation' | 'toolCallTraceSource' | 'waitEvent'>;
7
+ export type NodeProcessContextBase = Omit<InternalProcessContext, 'attachedData' | 'activeOutputPortIds' | 'createSubProcessor' | 'execution' | 'externalFunctions' | 'getPluginConfig' | 'node' | 'onPartialOutputs' | 'setFailureOutputs' | 'processId' | 'requestUserInput' | 'reportProgress' | 'isDirectRunTarget' | 'markResultAsEditorCacheHit' | 'setGlobal' | 'signal' | 'splitIndex' | 'toolCallContinuation' | 'toolCallTraceSource' | 'waitEvent'>;
8
8
  export declare function buildNodeProcessContext(options: {
9
9
  activeOutputPortIds: ReadonlySet<PortId>;
10
10
  base: NodeProcessContextBase;
@@ -21,6 +21,7 @@ export declare function buildNodeProcessContext(options: {
21
21
  node: ChartNode;
22
22
  nodeAbortController: AbortController;
23
23
  onPartialOutputs: (partialOutputs: Outputs) => void;
24
+ setFailureOutputs?: InternalProcessContext['setFailureOutputs'];
24
25
  processId: ProcessId;
25
26
  requestUserInput: (inputStrings: string[], renderingType: 'text' | 'markdown') => Promise<StringArrayDataValue>;
26
27
  reportProgress: InternalProcessContext['reportProgress'];
@@ -12,7 +12,8 @@ export type SplitRunDeps = {
12
12
  accumulateCost(output: Outputs): void;
13
13
  setNodeResults(nodeId: ChartNode['id'], outputs: Outputs): void;
14
14
  markNodeVisited(nodeId: ChartNode['id']): void;
15
- nodeErrored(node: ChartNode, error: unknown, processId: ProcessId, durationMs?: number, splitRunDurationMs?: Record<number, number>, resultOrigin?: SplitRunResultOrigin): Promise<void>;
15
+ nodeErrored(node: ChartNode, error: unknown, processId: ProcessId, durationMs?: number, splitRunDurationMs?: Record<number, number>, resultOrigin?: SplitRunResultOrigin, splitOutputs?: Record<number, Outputs>): Promise<void>;
16
+ takeFailureOutputs(processId: ProcessId, index: number): Outputs | undefined;
16
17
  isAborted(): boolean;
17
18
  getAbortError(): Error;
18
19
  emit(event: 'nodeStart', data: {