@valerypopoff/rivet2-core 2.1.10 → 2.3.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 (86) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +2101 -867
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +37 -3
  5. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  6. package/dist/esm/api/createProcessor.js +2 -0
  7. package/dist/esm/integrations/CodeRunner.js +2 -7
  8. package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
  9. package/dist/esm/model/AgentResponseTrace.js +121 -11
  10. package/dist/esm/model/GraphProcessor.js +14 -0
  11. package/dist/esm/model/RecordingPlayer.js +50 -5
  12. package/dist/esm/model/SubprocessorBridge.js +1 -0
  13. package/dist/esm/model/UiGraphActionProtocol.js +1 -0
  14. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  15. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -0
  16. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  17. package/dist/esm/model/chat-v2/chatV2EditorCache.js +6 -5
  18. package/dist/esm/model/chat-v2/chatV2Pipeline.js +41 -4
  19. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +31 -2
  20. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +10 -2
  21. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -11
  22. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  23. package/dist/esm/model/chat-v2/chatV2Types.js +16 -0
  24. package/dist/esm/model/chat-v2/customProviderApi.js +0 -2
  25. package/dist/esm/model/chat-v2/index.js +3 -0
  26. package/dist/esm/model/chat-v2/llmChatV2Body.js +9 -1
  27. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +5 -0
  28. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +7 -0
  29. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +95 -14
  30. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +32 -9
  31. package/dist/esm/model/chat-v2/llmModelCandidate.js +5 -1
  32. package/dist/esm/model/chat-v2/llmProfile.js +42 -0
  33. package/dist/esm/model/chat-v2/llmProfileBody.js +10 -0
  34. package/dist/esm/model/chat-v2/llmProfileFallback.js +390 -4
  35. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +7 -0
  36. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
  37. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +53 -34
  38. package/dist/esm/model/chat-v2/providerOptions.js +33 -7
  39. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  40. package/dist/esm/model/nodes/CodeNode.js +4 -46
  41. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  42. package/dist/esm/model/nodes/LLMChatV2Node.js +10 -1
  43. package/dist/esm/model/nodes/MatchNode.js +86 -41
  44. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  45. package/dist/esm/plugins/gentrace/index.js +0 -1
  46. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  47. package/dist/esm/plugins.js +1 -2
  48. package/dist/esm/recording/ExecutionRecorder.js +49 -8
  49. package/dist/types/api/createProcessor.d.ts +3 -0
  50. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  51. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  52. package/dist/types/model/AgentResponseTrace.d.ts +14 -1
  53. package/dist/types/model/EditorDefinition.d.ts +16 -0
  54. package/dist/types/model/ExecutorProtocol.d.ts +9 -6
  55. package/dist/types/model/GraphProcessor.d.ts +15 -5
  56. package/dist/types/model/NodeBase.d.ts +0 -10
  57. package/dist/types/model/Nodes.d.ts +2 -2
  58. package/dist/types/model/ProcessContext.d.ts +52 -0
  59. package/dist/types/model/UiGraphActionProtocol.d.ts +1 -0
  60. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  61. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -0
  62. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +3 -0
  63. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +8 -2
  64. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  65. package/dist/types/model/chat-v2/chatV2Types.d.ts +24 -0
  66. package/dist/types/model/chat-v2/customProviderApi.d.ts +0 -1
  67. package/dist/types/model/chat-v2/index.d.ts +3 -0
  68. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +1 -1
  69. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
  70. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +2 -0
  71. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  72. package/dist/types/model/chat-v2/llmProfileBody.d.ts +1 -1
  73. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +21 -2
  74. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +26 -6
  75. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +111 -0
  76. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  77. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +3 -0
  78. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -0
  79. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  80. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  81. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  82. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  83. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  84. package/dist/types/plugins.d.ts +1 -1
  85. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  86. package/package.json +2 -2
@@ -138,6 +138,8 @@ export function coreCreateProcessor(project, options, internalOptions = {}) {
138
138
  settings: resolveProcessSettings(options),
139
139
  getChatNodeEndpoint: options.getChatNodeEndpoint,
140
140
  onChatV2CallFinished: options.onChatV2CallFinished,
141
+ llmProfileHealthStore: options.llmProfileHealthStore,
142
+ evaluation: options.evaluation,
141
143
  }, resolvedInputs, resolvedContextValues, { returnWhenGraphOutputsReady: options.returnWhenGraphOutputsReady });
142
144
  if (abortSignal?.aborted) {
143
145
  void processor.abort();
@@ -1,15 +1,10 @@
1
- // eslint-disable-next-line import/no-cycle -- There has to be a cycle if we're to import the entirety of Rivet here.
1
+ // eslint-disable-next-line import/no-cycle -- Authored code receives the complete public Rivet namespace at execution time.
2
2
  import * as Rivet from '../exports.js';
3
+ export { ALL_CODE_RUNNER_OPTIONS } from './CodeRunnerOptions.js';
3
4
  export class IsomorphicCodeRunner {
4
5
  async runCode(code, inputs, options, graphInputs, contextValues) {
5
6
  const argNames = ['inputs'];
6
7
  const args = [inputs];
7
- if (options.includeRequire) {
8
- throw new Error('require() requires the Node executor.');
9
- }
10
- if (options.includeProcess) {
11
- throw new Error('process requires the Node executor.');
12
- }
13
8
  if (options.includeConsole) {
14
9
  argNames.push('console');
15
10
  args.push(console);
@@ -0,0 +1,7 @@
1
+ export const ALL_CODE_RUNNER_OPTIONS = Object.freeze({
2
+ includeRequire: true,
3
+ includeFetch: true,
4
+ includeRivet: true,
5
+ includeProcess: true,
6
+ includeConsole: true,
7
+ });
@@ -1,5 +1,6 @@
1
1
  export const AGENT_RESPONSE_TRACE_SCHEMA_VERSION = 1;
2
2
  export const AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS = 250;
3
+ export const AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS = 1_000;
3
4
  export const AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS = 500;
4
5
  export function buildAgentResponseTrace(options) {
5
6
  const matchingEvents = deduplicateAgentTraceEvents(options.events.filter((event) => {
@@ -12,15 +13,21 @@ export function buildAgentResponseTrace(options) {
12
13
  if (event.type === 'llm-call-finished') {
13
14
  return event.nodeId === options.nodeId && event.processId === options.processId;
14
15
  }
16
+ if (event.type === 'llm-profile-attempt') {
17
+ return event.nodeId === options.nodeId && event.processId === options.processId;
18
+ }
15
19
  return event.sourceNodeId === options.nodeId && event.sourceProcessId === options.processId;
16
20
  }));
17
21
  const allModelCalls = matchingEvents
18
22
  .filter((event) => event.type === 'llm-call-finished')
19
23
  .map(toModelCallTrace);
24
+ const allProfileAttempts = matchingEvents
25
+ .filter((event) => event.type === 'llm-profile-attempt')
26
+ .map(toProfileAttemptTrace);
20
27
  const allToolCalls = matchingEvents
21
28
  .filter((event) => event.type === 'tool-call-finished')
22
29
  .map(toToolCallTrace);
23
- const summary = summarizeAgentCalls(allModelCalls, allToolCalls);
30
+ const summary = summarizeAgentCalls(allModelCalls, allProfileAttempts, allToolCalls);
24
31
  const terminalAt = options.responseReadyAt ?? options.finishedAt;
25
32
  return {
26
33
  schemaVersion: AGENT_RESPONSE_TRACE_SCHEMA_VERSION,
@@ -41,8 +48,10 @@ export function buildAgentResponseTrace(options) {
41
48
  ...(options.backgroundWorkPending == null ? {} : { backgroundWorkPending: options.backgroundWorkPending }),
42
49
  summary,
43
50
  modelCalls: allModelCalls.slice(0, AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS),
51
+ profileAttempts: allProfileAttempts.slice(0, AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS),
44
52
  toolCalls: allToolCalls.slice(0, AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS),
45
53
  omittedModelCallCount: Math.max(0, allModelCalls.length - AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS),
54
+ omittedProfileAttemptCount: Math.max(0, allProfileAttempts.length - AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS),
46
55
  omittedToolCallCount: Math.max(0, allToolCalls.length - AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS),
47
56
  };
48
57
  }
@@ -78,6 +87,9 @@ export function getAgentTraceEventIdentity(event) {
78
87
  if (event.type === 'llm-call-finished') {
79
88
  return `model\u0000${event.execution.rootRunId}\u0000${event.execution.graphRunId}\u0000${event.nodeId}\u0000${event.processId}\u0000${event.callId}`;
80
89
  }
90
+ if (event.type === 'llm-profile-attempt') {
91
+ return `profile-attempt\u0000${event.execution.rootRunId}\u0000${event.execution.graphRunId}\u0000${event.nodeId}\u0000${event.processId}\u0000${event.eventId}`;
92
+ }
81
93
  return event.toolCallId == null
82
94
  ? undefined
83
95
  : `tool\u0000${event.execution.rootRunId}\u0000${event.execution.graphRunId}\u0000${event.sourceNodeId}\u0000${event.sourceProcessId}\u0000${event.toolCallId}`;
@@ -88,6 +100,17 @@ export function getAgentTraceEventIdentity(event) {
88
100
  * later legacy-shaped copy erase result navigation.
89
101
  */
90
102
  export function mergeAgentTraceEvent(existing, incoming) {
103
+ if (existing.type === 'llm-call-finished' && incoming.type === 'llm-call-finished') {
104
+ return {
105
+ ...incoming,
106
+ ...(incoming.profileHealthKey == null && existing.profileHealthKey != null
107
+ ? { profileHealthKey: existing.profileHealthKey }
108
+ : {}),
109
+ ...(incoming.profileHealthState == null && existing.profileHealthState != null
110
+ ? { profileHealthState: existing.profileHealthState }
111
+ : {}),
112
+ };
113
+ }
91
114
  if (existing.type === 'tool-call-finished' &&
92
115
  incoming.type === 'tool-call-finished' &&
93
116
  existing.resultOwner != null &&
@@ -108,6 +131,8 @@ function toModelCallTrace(event) {
108
131
  outcome: event.outcome,
109
132
  attemptIndex: event.attemptIndex,
110
133
  ...(event.profileIndex == null ? {} : { profileIndex: event.profileIndex }),
134
+ ...(event.profileHealthKey == null ? {} : { profileHealthKey: event.profileHealthKey }),
135
+ ...(event.profileHealthState == null ? {} : { profileHealthState: event.profileHealthState }),
111
136
  ...(event.roundIndex == null ? {} : { roundIndex: event.roundIndex }),
112
137
  ...(event.startedAt == null ? {} : { startedAt: event.startedAt }),
113
138
  ...(event.durationMs == null ? {} : { durationMs: event.durationMs }),
@@ -131,7 +156,11 @@ function toToolCallTrace(event) {
131
156
  ...(event.durationMs == null ? {} : { durationMs: event.durationMs }),
132
157
  };
133
158
  }
134
- function summarizeAgentCalls(modelCalls, toolCalls) {
159
+ function toProfileAttemptTrace(event) {
160
+ const { type: _type, execution: _execution, ...trace } = event;
161
+ return trace;
162
+ }
163
+ function summarizeAgentCalls(modelCalls, profileAttempts, toolCalls) {
135
164
  const usageKeys = ['promptTokens', 'completionTokens', 'totalTokens', 'cachedTokens', 'reasoningTokens'];
136
165
  const usage = Object.fromEntries(usageKeys.flatMap((key) => {
137
166
  const values = modelCalls.map((call) => call.usage?.[key]).filter((value) => value != null);
@@ -141,7 +170,7 @@ function summarizeAgentCalls(modelCalls, toolCalls) {
141
170
  .map((call) => call.pricing.costUsd)
142
171
  .filter((value) => value != null && Number.isFinite(value));
143
172
  const unknownCostCount = modelCalls.filter((call) => call.pricing.status === 'unknown' || !Number.isFinite(call.pricing.costUsd)).length;
144
- const profileTransitions = countProfileFallbacks(modelCalls);
173
+ const profileTransitions = countProfileFallbacks(modelCalls, profileAttempts);
145
174
  return {
146
175
  modelCallCount: modelCalls.length,
147
176
  toolCallCount: toolCalls.length,
@@ -162,18 +191,24 @@ function summarizeAgentCalls(modelCalls, toolCalls) {
162
191
  * profile across continuation rounds. Using that invariant also accounts for
163
192
  * configuration-failed profiles that never produced a physical-call event.
164
193
  */
165
- function countProfileFallbacks(modelCalls) {
194
+ function countProfileFallbacks(modelCalls, profileAttempts) {
166
195
  const highestProfileByInvocation = new Map();
167
196
  let count = 0;
168
- for (const call of modelCalls) {
169
- if (call.profileIndex == null)
170
- continue;
171
- const key = `${call.nodeId}\u0000${call.processId}`;
197
+ const candidates = [
198
+ ...modelCalls.flatMap((call) => call.profileIndex == null
199
+ ? []
200
+ : [{ nodeId: call.nodeId, processId: call.processId, profileIndex: call.profileIndex }]),
201
+ ...profileAttempts.flatMap((attempt) => attempt.profileIndex == null
202
+ ? []
203
+ : [{ nodeId: attempt.nodeId, processId: attempt.processId, profileIndex: attempt.profileIndex }]),
204
+ ];
205
+ for (const candidate of candidates) {
206
+ const key = `${candidate.nodeId}\u0000${candidate.processId}`;
172
207
  const highestProfile = highestProfileByInvocation.get(key) ?? 0;
173
- if (call.profileIndex <= highestProfile)
208
+ if (candidate.profileIndex <= highestProfile)
174
209
  continue;
175
- count += call.profileIndex - highestProfile;
176
- highestProfileByInvocation.set(key, call.profileIndex);
210
+ count += candidate.profileIndex - highestProfile;
211
+ highestProfileByInvocation.set(key, candidate.profileIndex);
177
212
  }
178
213
  return count;
179
214
  }
@@ -197,8 +232,10 @@ export function isAgentResponseTrace(value) {
197
232
  'backgroundWorkPending',
198
233
  'summary',
199
234
  'modelCalls',
235
+ 'profileAttempts',
200
236
  'toolCalls',
201
237
  'omittedModelCallCount',
238
+ 'omittedProfileAttemptCount',
202
239
  'omittedToolCallCount',
203
240
  ]))
204
241
  return false;
@@ -210,8 +247,13 @@ export function isAgentResponseTrace(value) {
210
247
  return false;
211
248
  if (!isRecord(value.summary) || !Array.isArray(value.modelCalls) || !Array.isArray(value.toolCalls))
212
249
  return false;
250
+ if (value.profileAttempts !== undefined && !Array.isArray(value.profileAttempts))
251
+ return false;
213
252
  if (value.modelCalls.length > AGENT_RESPONSE_TRACE_MAX_MODEL_CALLS)
214
253
  return false;
254
+ if (Array.isArray(value.profileAttempts) &&
255
+ value.profileAttempts.length > AGENT_RESPONSE_TRACE_MAX_PROFILE_ATTEMPTS)
256
+ return false;
215
257
  if (value.toolCalls.length > AGENT_RESPONSE_TRACE_MAX_TOOL_CALLS)
216
258
  return false;
217
259
  return (isOptionalString(value.nodeId) &&
@@ -223,9 +265,11 @@ export function isAgentResponseTrace(value) {
223
265
  isOptionalBoolean(value.backgroundWorkPending) &&
224
266
  ['running', 'response-ready', 'completed', 'error', 'aborted', 'unavailable'].includes(String(value.status)) &&
225
267
  isNonNegativeInteger(value.omittedModelCallCount) &&
268
+ (value.omittedProfileAttemptCount === undefined || isNonNegativeInteger(value.omittedProfileAttemptCount)) &&
226
269
  isNonNegativeInteger(value.omittedToolCallCount) &&
227
270
  isAgentTraceSummary(value.summary) &&
228
271
  value.modelCalls.every(isAgentModelCallTrace) &&
272
+ (value.profileAttempts === undefined || value.profileAttempts.every(isAgentLLMProfileAttemptTrace)) &&
229
273
  value.toolCalls.every(isAgentToolCallTrace));
230
274
  }
231
275
  /**
@@ -248,6 +292,9 @@ export class AgentResponseTraceCollector {
248
292
  }), processor.on('llmCallFinished', (event) => {
249
293
  this.#execution ??= event.execution;
250
294
  this.#events.push({ type: 'llm-call-finished', ...event });
295
+ }), processor.on('llmProfileAttempt', (event) => {
296
+ this.#execution ??= event.execution;
297
+ this.#events.push({ type: 'llm-profile-attempt', ...event });
251
298
  }), processor.on('toolCallFinished', (event) => {
252
299
  this.#execution ??= event.execution;
253
300
  this.#events.push({ type: 'tool-call-finished', ...event });
@@ -313,6 +360,8 @@ function isAgentModelCallTrace(value) {
313
360
  'outcome',
314
361
  'attemptIndex',
315
362
  'profileIndex',
363
+ 'profileHealthKey',
364
+ 'profileHealthState',
316
365
  'roundIndex',
317
366
  'startedAt',
318
367
  'durationMs',
@@ -331,6 +380,11 @@ function isAgentModelCallTrace(value) {
331
380
  (value.outcome === 'success' || value.outcome === 'provider-failure' || value.outcome === 'aborted') &&
332
381
  isNonNegativeInteger(value.attemptIndex) &&
333
382
  isOptionalNonNegativeInteger(value.profileIndex) &&
383
+ isOptionalString(value.profileHealthKey) &&
384
+ (value.profileHealthState === undefined ||
385
+ value.profileHealthState === 'closed' ||
386
+ value.profileHealthState === 'open' ||
387
+ value.profileHealthState === 'half-open') &&
334
388
  isOptionalNonNegativeInteger(value.roundIndex) &&
335
389
  isOptionalNonNegativeFiniteNumber(value.startedAt) &&
336
390
  isOptionalNonNegativeFiniteNumber(value.durationMs) &&
@@ -338,6 +392,62 @@ function isAgentModelCallTrace(value) {
338
392
  (value.usage === undefined || isAgentTraceUsage(value.usage)) &&
339
393
  isAgentTracePricing(value.pricing));
340
394
  }
395
+ function isAgentLLMProfileAttemptTrace(value) {
396
+ return (isRecord(value) &&
397
+ hasOnlyKeys(value, [
398
+ 'eventId',
399
+ 'roundIndex',
400
+ 'profileIndex',
401
+ 'nodeId',
402
+ 'processId',
403
+ 'provider',
404
+ 'model',
405
+ 'customProviderApi',
406
+ 'stage',
407
+ 'outcome',
408
+ 'attemptIndex',
409
+ 'status',
410
+ 'error',
411
+ 'profileHealthKey',
412
+ 'healthState',
413
+ 'healthDisposition',
414
+ 'healthOutcome',
415
+ 'retryAt',
416
+ 'timeoutKind',
417
+ ]) &&
418
+ typeof value.eventId === 'string' &&
419
+ isNonNegativeInteger(value.roundIndex) &&
420
+ isOptionalNonNegativeInteger(value.profileIndex) &&
421
+ typeof value.nodeId === 'string' &&
422
+ typeof value.processId === 'string' &&
423
+ typeof value.provider === 'string' &&
424
+ typeof value.model === 'string' &&
425
+ (value.customProviderApi === undefined ||
426
+ value.customProviderApi === 'completions' ||
427
+ value.customProviderApi === 'responses') &&
428
+ ['configuration', 'request', 'response-validation', 'health-gate', 'health-update'].includes(String(value.stage)) &&
429
+ ['success', 'failure', 'aborted', 'skipped'].includes(String(value.outcome)) &&
430
+ isOptionalNonNegativeInteger(value.attemptIndex) &&
431
+ isOptionalNonNegativeFiniteNumber(value.status) &&
432
+ isOptionalString(value.error) &&
433
+ isOptionalString(value.profileHealthKey) &&
434
+ (value.healthState === undefined ||
435
+ value.healthState === 'closed' ||
436
+ value.healthState === 'open' ||
437
+ value.healthState === 'half-open') &&
438
+ (value.healthDisposition === undefined ||
439
+ value.healthDisposition === 'allow' ||
440
+ value.healthDisposition === 'deny' ||
441
+ value.healthDisposition === 'fail-open') &&
442
+ (value.healthOutcome === undefined ||
443
+ value.healthOutcome === 'healthy' ||
444
+ value.healthOutcome === 'unhealthy' ||
445
+ value.healthOutcome === 'ignored') &&
446
+ isOptionalNonNegativeFiniteNumber(value.retryAt) &&
447
+ (value.timeoutKind === undefined ||
448
+ value.timeoutKind === 'first-output' ||
449
+ value.timeoutKind === 'stream-inactivity'));
450
+ }
341
451
  function isAgentToolCallTrace(value) {
342
452
  const hasKnownOutcome = isRecord(value) &&
343
453
  (value.outcome === 'success' ||
@@ -410,6 +410,7 @@ export class GraphProcessor {
410
410
  splitIndex: this.#executor.index,
411
411
  }
412
412
  : undefined,
413
+ ...(this.#context?.evaluation === undefined ? {} : { evaluation: this.#context.evaluation }),
413
414
  };
414
415
  }
415
416
  #withExecution(data, execution = this.#buildExecutionMetadata()) {
@@ -824,6 +825,7 @@ export class GraphProcessor {
824
825
  // observer from the root run so nested LLM calls are not emitted once by
825
826
  // every ancestor before their own event is bridged to the root emitter.
826
827
  const hostChatV2Observer = this.getRootProcessor().#context.onChatV2CallFinished;
828
+ const hostLLMProfileAttemptObserver = this.getRootProcessor().#context.onLLMProfileAttempt;
827
829
  this.#nodeProcessContextBase = {
828
830
  ...this.#context,
829
831
  abortGraph: (error) => {
@@ -858,6 +860,18 @@ export class GraphProcessor {
858
860
  const { rawUsage: _rawUsage, ...traceEvent } = event;
859
861
  emitDetached(this.#emitter, 'llmCallFinished', this.#withExecution(traceEvent));
860
862
  },
863
+ onLLMProfileAttempt: (event) => {
864
+ try {
865
+ const observerResult = hostLLMProfileAttemptObserver?.(event);
866
+ if (observerResult != null && typeof observerResult.then === 'function') {
867
+ void Promise.resolve(observerResult).catch(() => undefined);
868
+ }
869
+ }
870
+ catch {
871
+ // Host observers must never change graph execution.
872
+ }
873
+ emitDetached(this.#emitter, 'llmProfileAttempt', this.#withExecution(event));
874
+ },
861
875
  onToolCallFinished: (event) => {
862
876
  emitDetached(this.#emitter, 'toolCallFinished', this.#withExecution(event));
863
877
  },
@@ -8,6 +8,31 @@ function withOptionalDuration(payload, durationMs, splitRunDurationMs) {
8
8
  ...(splitRunDurationMs === undefined ? {} : { splitRunDurationMs }),
9
9
  };
10
10
  }
11
+ function withReplayRecordedAt(data, replayRecordedAt) {
12
+ if (typeof replayRecordedAt !== 'number' ||
13
+ !Number.isFinite(replayRecordedAt) ||
14
+ data == null ||
15
+ typeof data !== 'object') {
16
+ return data;
17
+ }
18
+ return { ...data, replayRecordedAt };
19
+ }
20
+ const REPLAY_TIMED_LIFECYCLE_EVENTS = new Set([
21
+ 'start',
22
+ 'graphStart',
23
+ 'graphOutputsReady',
24
+ 'graphFinish',
25
+ 'graphError',
26
+ 'graphAbort',
27
+ 'nodeStart',
28
+ 'userInput',
29
+ 'progress',
30
+ 'partialOutput',
31
+ 'nodeFinish',
32
+ 'nodeError',
33
+ 'nodeExcluded',
34
+ 'nodeOutputsCleared',
35
+ ]);
11
36
  export async function replayExecutionRecording(options) {
12
37
  const { emitter, erroredNodes, graphOutputs, fallbackGraphId, initialReplayExecution, project, recorder, recordingPlaybackChatLatency, setContextValues, setGraphInputs, setGraphOutputs, setRunning, visitedNodes, waitUntilUnpaused, nodeResults, isAborted, } = options;
13
38
  const nodesByIdAllGraphs = {};
@@ -20,6 +45,7 @@ export async function replayExecutionRecording(options) {
20
45
  }
21
46
  let hasEmittedRunActivityExecution = false;
22
47
  let getFallbackExecution;
48
+ let currentReplayRecordedAt;
23
49
  const getReplayFallbackGraph = () => {
24
50
  const replayTargetGraph = fallbackGraphId == null ? undefined : project.graphs[fallbackGraphId];
25
51
  const projectMainGraph = project.metadata.mainGraphId == null ? undefined : project.graphs[project.metadata.mainGraphId];
@@ -31,7 +57,13 @@ export async function replayExecutionRecording(options) {
31
57
  // playback error remains attached to that root instead of synthesizing a
32
58
  // second one.
33
59
  hasEmittedRunActivityExecution = true;
34
- emitDetached(emitter, event, data);
60
+ const payload = REPLAY_TIMED_LIFECYCLE_EVENTS.has(event)
61
+ ? withReplayRecordedAt(data, currentReplayRecordedAt)
62
+ : data;
63
+ emitDetached(emitter, event, payload);
64
+ };
65
+ const emitReplayTerminalEvent = (event, data) => {
66
+ emitDetached(emitter, event, withReplayRecordedAt(data, currentReplayRecordedAt));
35
67
  };
36
68
  const emitFallbackRootTerminal = (status, data) => {
37
69
  // Older recordings and preflight-error recordings can contain only the
@@ -168,6 +200,7 @@ export async function replayExecutionRecording(options) {
168
200
  break;
169
201
  }
170
202
  await waitUntilUnpaused();
203
+ currentReplayRecordedAt = event.ts;
171
204
  switch (event.type) {
172
205
  case 'start': {
173
206
  const { data } = event;
@@ -184,7 +217,7 @@ export async function replayExecutionRecording(options) {
184
217
  }
185
218
  case 'abort': {
186
219
  emitFallbackRootTerminal('aborted', event.data);
187
- emitDetached(emitter, 'abort', event.data);
220
+ emitReplayTerminalEvent('abort', event.data);
188
221
  break;
189
222
  }
190
223
  case 'pause': {
@@ -200,14 +233,14 @@ export async function replayExecutionRecording(options) {
200
233
  }
201
234
  case 'done': {
202
235
  emitFallbackRootTerminal('completed', { outputs: event.data.results });
203
- emitDetached(emitter, 'done', event.data);
236
+ emitReplayTerminalEvent('done', event.data);
204
237
  setGraphOutputs(event.data.results);
205
238
  setRunning(false);
206
239
  break;
207
240
  }
208
241
  case 'error': {
209
242
  emitFallbackRootTerminal('error', event.data);
210
- emitDetached(emitter, 'error', event.data);
243
+ emitReplayTerminalEvent('error', event.data);
211
244
  break;
212
245
  }
213
246
  case 'globalSet': {
@@ -381,6 +414,14 @@ export async function replayExecutionRecording(options) {
381
414
  });
382
415
  break;
383
416
  }
417
+ case 'llmProfileAttempt': {
418
+ const { data } = event;
419
+ emitReplayExecutionEvent('llmProfileAttempt', {
420
+ ...data,
421
+ execution: getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution),
422
+ });
423
+ break;
424
+ }
384
425
  case 'toolCallFinished': {
385
426
  const { data } = event;
386
427
  emitReplayExecutionEvent('toolCallFinished', {
@@ -434,7 +475,11 @@ export async function replayExecutionRecording(options) {
434
475
  // normal root-level `error` event is intentionally unscoped, so Run
435
476
  // Activity has no active root to attach it to in that case.
436
477
  emitFallbackRootTerminal('error', { error: replayError });
437
- emitDetached(emitter, 'error', { error: replayError });
478
+ // This is a fresh playback failure, not a historical event from the last
479
+ // successful dispatch. Do not accidentally attribute it to that event's
480
+ // recording timestamp.
481
+ currentReplayRecordedAt = undefined;
482
+ emitReplayTerminalEvent('error', { error: replayError });
438
483
  }
439
484
  finally {
440
485
  setRunning(false);
@@ -30,6 +30,7 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
30
30
  processor.on('partialOutput', (event) => parentEmitter.emit('partialOutput', event)),
31
31
  processor.on('progress', (event) => parentEmitter.emit('progress', event)),
32
32
  processor.on('llmCallFinished', (event) => parentEmitter.emit('llmCallFinished', event)),
33
+ processor.on('llmProfileAttempt', (event) => parentEmitter.emit('llmProfileAttempt', event)),
33
34
  processor.on('toolCallFinished', (event) => parentEmitter.emit('toolCallFinished', event)),
34
35
  processor.on('nodeExcluded', (event) => parentEmitter.emit('nodeExcluded', event)),
35
36
  processor.on('nodeStart', (event) => parentEmitter.emit('nodeStart', event)),
@@ -104,6 +104,7 @@ export function parseRivetWebAppServerMessage(value) {
104
104
  ...base,
105
105
  error: value.error,
106
106
  ...(typeof value.code === 'string' ? { code: value.code } : {}),
107
+ ...(isAgentResponseTrace(value.responseTrace) ? { responseTrace: value.responseTrace } : {}),
107
108
  }
108
109
  : undefined;
109
110
  case 'action.interrupted':