@valerypopoff/rivet2-core 2.17.0 → 2.21.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 (120) hide show
  1. package/dist/cjs/bundle.cjs +3197 -1461
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +40 -4
  4. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  5. package/dist/cjs/serialization.cjs +1880 -0
  6. package/dist/cjs/serialization.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs +168 -6
  8. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  9. package/dist/esm/api/processSettings.js +1 -0
  10. package/dist/esm/exports.js +3 -0
  11. package/dist/esm/model/AgentResponseTrace.js +99 -34
  12. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  13. package/dist/esm/model/DataValue.js +11 -2
  14. package/dist/esm/model/GlobalVariables.js +2 -1
  15. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  16. package/dist/esm/model/GraphExecutionState.js +81 -0
  17. package/dist/esm/model/GraphProcessor.js +625 -943
  18. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  19. package/dist/esm/model/Nodes.js +5 -0
  20. package/dist/esm/model/ProjectBundle.js +69 -11
  21. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  22. package/dist/esm/model/ProjectGraphCallSites.js +46 -0
  23. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  24. package/dist/esm/model/SubprocessorBridge.js +125 -87
  25. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
  27. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  28. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  29. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  30. package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
  31. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  32. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  33. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
  34. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  35. package/dist/esm/model/chat-v2/llmChatV2Body.js +3 -3
  36. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  37. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  38. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +25 -15
  39. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  40. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  41. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  42. package/dist/esm/model/chat-v2/llmProfile.js +2 -1
  43. package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
  44. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  45. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  46. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  47. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  48. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  49. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  50. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  51. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  52. package/dist/esm/model/classifier/credentials.js +13 -3
  53. package/dist/esm/model/classifier/limits.js +33 -3
  54. package/dist/esm/model/classifier/perplexity.js +63 -0
  55. package/dist/esm/model/classifier/profile.js +151 -0
  56. package/dist/esm/model/classifier/profileExecution.js +294 -0
  57. package/dist/esm/model/classifier/providers.js +217 -30
  58. package/dist/esm/model/classifier/state.js +4 -1
  59. package/dist/esm/model/classifier/types.js +11 -1
  60. package/dist/esm/model/nodeRunFailure.js +8 -1
  61. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  62. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +257 -66
  63. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  64. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  65. package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
  66. package/dist/esm/model/nodes/SubGraphNode.js +4 -0
  67. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  68. package/dist/esm/model/profileSuspensionHints.js +8 -0
  69. package/dist/esm/serialization.js +2 -0
  70. package/dist/esm/utils/coerceType.js +11 -1
  71. package/dist/esm/webAppRuntime.js +1 -0
  72. package/dist/types/exports.d.ts +3 -0
  73. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  74. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  75. package/dist/types/model/DataValue.d.ts +12 -8
  76. package/dist/types/model/ExecutorProtocol.d.ts +14 -2
  77. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  78. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  79. package/dist/types/model/GraphProcessor.d.ts +1 -0
  80. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  81. package/dist/types/model/Nodes.d.ts +7 -4
  82. package/dist/types/model/ProcessContext.d.ts +12 -3
  83. package/dist/types/model/ProjectBundle.d.ts +18 -4
  84. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  85. package/dist/types/model/ProjectGraphCallSites.d.ts +12 -0
  86. package/dist/types/model/RivetUIContext.d.ts +1 -1
  87. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  88. package/dist/types/model/Settings.d.ts +1 -0
  89. package/dist/types/model/SubgraphProjectTarget.d.ts +6 -0
  90. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  91. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  92. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  93. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  94. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  95. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  96. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
  97. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  98. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  99. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  100. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
  101. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  102. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  103. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  104. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  105. package/dist/types/model/classifier/credentials.d.ts +4 -0
  106. package/dist/types/model/classifier/limits.d.ts +4 -1
  107. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  108. package/dist/types/model/classifier/profile.d.ts +46 -0
  109. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  110. package/dist/types/model/classifier/providers.d.ts +32 -1
  111. package/dist/types/model/classifier/types.d.ts +9 -0
  112. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
  113. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  114. package/dist/types/model/nodes/SubGraphNode.d.ts +1 -1
  115. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  116. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  117. package/dist/types/recording/ExecutionRecorder.d.ts +5 -1
  118. package/dist/types/serialization.d.ts +2 -0
  119. package/dist/types/webAppRuntime.d.ts +1 -0
  120. package/package.json +7 -1
@@ -364,7 +364,7 @@ export class LLMChatV2NodeImpl extends NodeImpl {
364
364
  throw error;
365
365
  }
366
366
  context.signal.throwIfAborted();
367
- const { result, terminalSnapshot } = invocation;
367
+ const { result, terminalSnapshot, toolCost } = invocation;
368
368
  projectLLMInvocationResult({
369
369
  result,
370
370
  modelCalls: invocationJournal.modelCalls,
@@ -372,6 +372,7 @@ export class LLMChatV2NodeImpl extends NodeImpl {
372
372
  outputLLMAttempts: this.data.outputLLMAttempts,
373
373
  llmAttempts: invocationJournal.llmAttempts,
374
374
  profileSummary: runtime.getProfileSummary?.(),
375
+ toolCost,
375
376
  });
376
377
  result.commonOutputs = withRunSuccessOutputs(this.data, result.commonOutputs);
377
378
  // The final display page is taken after result projection, so it exactly
@@ -303,6 +303,7 @@ export class SubGraphNodeImpl extends NodeImpl {
303
303
  // upload before reporting the caller run complete, so closing its tab
304
304
  // immediately after completion cannot discard the called-project run.
305
305
  await context.onSubgraphProjectRun?.({
306
+ createdAt: new Date(startedAt).toISOString(),
306
307
  target: { projectId: this.data.targetProjectId, version: this.data.targetVersion ?? 'latest' },
307
308
  resolved: recordingTarget,
308
309
  graphId: this.data.graphId,
@@ -355,6 +356,9 @@ function buildOptimizedSubgraphOutputs(boundary, requestedOutputIds, graphOutput
355
356
  if (!boundary.outputs.some((output) => output.id === 'cost')) {
356
357
  outputs['cost'] = graphOutputs['cost'] ?? { type: 'number', value: 0 };
357
358
  }
359
+ if (!boundary.outputs.some((output) => output.id === 'costBreakdown') && graphOutputs['costBreakdown']) {
360
+ outputs['costBreakdown'] = graphOutputs['costBreakdown'];
361
+ }
358
362
  if (!boundary.outputs.some((output) => output.id === 'duration')) {
359
363
  outputs['duration'] = { type: 'number', value: duration };
360
364
  }
@@ -1,4 +1,5 @@
1
1
  import { omit } from 'lodash-es';
2
+ import { readGraphCostBreakdown } from '../GraphBoundaryEffects.js';
2
3
  import { coerceTypeOptional } from '../../utils/coerceType.js';
3
4
  import { getError } from '../../utils/errors.js';
4
5
  import { createDelegatedToolCallRecord, createToolResultMessage, normalizeToolCall, stringifyToolResult, } from '../chat-v2/toolCallCodec.js';
@@ -36,7 +37,7 @@ export function isDelegatedToolCallRecord(input) {
36
37
  typeof maybeMessage.name === 'string' &&
37
38
  (maybeMessage.toolName == null || typeof maybeMessage.toolName === 'string'));
38
39
  }
39
- export function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
40
+ export function buildDelegatedToolCallOutputs(records, preToolMessage, cost, costBreakdown) {
40
41
  const preToolMessageOutput = preToolMessage == null
41
42
  ? {
42
43
  type: 'control-flow-excluded',
@@ -107,6 +108,8 @@ export function buildDelegatedToolCallOutputs(records, preToolMessage, cost) {
107
108
  };
108
109
  if (cost != null) {
109
110
  outputs['cost'] = { type: 'number', value: cost };
111
+ if (costBreakdown)
112
+ outputs['costBreakdown'] = { type: 'object', value: { ...costBreakdown } };
110
113
  }
111
114
  return outputs;
112
115
  }
@@ -275,6 +278,7 @@ async function delegateResolvedToolCall(functionCall, context, config, trace) {
275
278
  message: createToolResultMessage(functionCall, outputString),
276
279
  record: createDelegatedToolCallRecord(functionCall, outputString, executionTimeMs),
277
280
  cost,
281
+ costBreakdown: readGraphCostBreakdown(outputs),
278
282
  };
279
283
  }
280
284
  function notifyToolCallFinished(context, event) {
@@ -0,0 +1,8 @@
1
+ /** Shared inspector wording for LLM and Classifier profile suspension. */
2
+ export const profileSuspensionHints = {
3
+ host: 'Requires Studio Server or a host with shared profile health. Not available in standalone Rivet.',
4
+ enable: 'Suspend this profile after provider failures or timeouts. After suspension, allow one recovery attempt.',
5
+ threshold: 'Failures or timeouts within the failure window needed to suspend this profile.',
6
+ window: 'Rolling period for counting failures and timeouts.',
7
+ duration: 'Time to suspend this profile before one recovery attempt.',
8
+ };
@@ -0,0 +1,2 @@
1
+ /** Lightweight entry point for file preparation without model/provider runtime initialization. */
2
+ export { deserializeProject, deserializeGraph, deserializeDatasets, serializeProject, serializeGraph, serializeDatasets, } from './utils/serialization/serialization.js';
@@ -6,7 +6,8 @@ function isValidatedObjectValueType(type) {
6
6
  return (type === 'knowledge-source' ||
7
7
  type === 'knowledge-document' ||
8
8
  type === 'knowledge-evidence' ||
9
- type === 'llm-config');
9
+ type === 'llm-config' ||
10
+ type === 'classifier-config');
10
11
  }
11
12
  function canAttemptGeneralCoercion(from, to) {
12
13
  return !isValidatedObjectValueType(from) || to === 'object' || to === 'string';
@@ -53,6 +54,8 @@ const scalarCoercionRules = {
53
54
  'knowledge-document': sameTypeOrObjectScalarRule('knowledge-document', (value) => coerceValidatedObjectValue(value, normalizeKnowledgeDocument)),
54
55
  'knowledge-evidence': sameTypeOrObjectScalarRule('knowledge-evidence', (value) => coerceValidatedObjectValue(value, normalizeKnowledgeEvidence)),
55
56
  'llm-config': sameTypeOrObjectScalarRule('llm-config', (value) => coerceValidatedObjectValue(value, normalizeLLMProfileValue)),
57
+ // Provider-specific validation belongs to Evaluate's bounded snapshot boundary.
58
+ 'classifier-config': sameTypeOrObjectScalarRule('classifier-config', (value) => value?.value != null && typeof value.value === 'object' && !Array.isArray(value.value) ? value.value : undefined),
56
59
  document: generalScalarRule('document'),
57
60
  };
58
61
  export function coerceTypeOptional(wrapped, type) {
@@ -60,6 +63,13 @@ export function coerceTypeOptional(wrapped, type) {
60
63
  return expectTypeOptional(wrapped, type);
61
64
  }
62
65
  const value = wrapped ? unwrapDataValue(wrapped) : undefined;
66
+ // These profiles share a versioned object envelope but configure different
67
+ // APIs. Do not reinterpret a typed chat profile as a classifier (or vice versa),
68
+ // including after unwrapping a deferred value. Object/any imports remain valid.
69
+ if ((type === 'classifier-config' && value?.type === 'llm-config') ||
70
+ (type === 'llm-config' && value?.type === 'classifier-config')) {
71
+ return undefined;
72
+ }
63
73
  // Coerce 'true' to [true] for example
64
74
  if (isArrayDataType(type) && !isArrayDataValue(value)) {
65
75
  const coerced = coerceTypeOptional(value, getScalarTypeOf(type));
@@ -1,4 +1,5 @@
1
1
  export { isAgentResponseTrace } from './model/AgentResponseTrace.js';
2
+ export { buildAgentProfileAttemptInspectorRows, getClassifierRequestCount, formatClassifierRequestCount, getProfileAttemptOmissionNotice, isClassifierRequest, } from './model/AgentResponseTracePresentation.js';
2
3
  export { IndexedDbWebAppBrowserStorage, RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DATABASE, RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION, RIVET_WEB_APP_LEGACY_RETENTION_MS, WebAppBrowserStoragePersistenceError, } from './model/WebAppBrowserStorage.js';
3
4
  export { decodeRivetWebAppStorageBinaryFrame, deserializeRivetWebAppStoredValue, deserializeRivetWebAppStoredValuePatch, encodeRivetWebAppStorageBinaryFrame, parseRivetWebAppBrowserStorageClientMessage, parseRivetWebAppBrowserStorageServerMessage, RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTION_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTIVE_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_VALUE_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_TRANSFER_TIMEOUT_MS, RIVET_WEB_APP_BROWSER_STORAGE_RPC_CAPABILITY, RIVET_WEB_APP_BROWSER_STORAGE_RPC_VERSION, RIVET_WEB_APP_BROWSER_STORAGE_SAFE_FALLBACK_BYTES, RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES, serializeRivetWebAppStoredValue, serializeRivetWebAppStoredValuePatch, splitRivetWebAppStorageTransfer, } from './model/WebAppBrowserStorageRpc.js';
4
5
  export { UiGraphBrowserPersistence } from './model/UiGraphIndexedDbPersistence.js';
@@ -32,10 +32,13 @@ export * from './native/NativeApi.js';
32
32
  export * from './native/BrowserNativeApi.js';
33
33
  export * from './model/ProcessContext.js';
34
34
  export * from './model/AgentResponseTrace.js';
35
+ export * from './model/AgentResponseTracePresentation.js';
35
36
  export * from './model/DebuggerTransportSentinel.js';
36
37
  export * from './model/ProjectReferenceLoader.js';
37
38
  export * from './model/SubgraphProjectTarget.js';
39
+ export * from './model/ProjectGraphCallSites.js';
38
40
  export * from './model/ProjectBundle.js';
41
+ export * from './model/ProjectBundleRuntime.js';
39
42
  export * from './model/RivetUIContext.js';
40
43
  export * from './model/chat-v2/index.js';
41
44
  export * from './integrations/integrations.js';
@@ -46,7 +46,7 @@ export type AgentLLMProfileAttemptTrace = Omit<LLMProfileAttemptTraceEvent, 'eve
46
46
  export type AgentResponseTrace = {
47
47
  schemaVersion: typeof AGENT_RESPONSE_TRACE_SCHEMA_VERSION;
48
48
  traceId: RootRunId;
49
- scope: 'response' | 'llm-invocation';
49
+ scope: 'response' | 'llm-invocation' | 'classifier-invocation';
50
50
  rootRunId: RootRunId;
51
51
  graphRunId: GraphRunId;
52
52
  graphId: GraphId;
@@ -60,6 +60,8 @@ export type AgentResponseTrace = {
60
60
  backgroundWorkPending?: boolean;
61
61
  summary: {
62
62
  modelCallCount: number;
63
+ /** Physical classifier requests, including retries; absent in older traces. */
64
+ classifierRequestCount?: number;
63
65
  toolCallCount: number;
64
66
  retryCount: number;
65
67
  fallbackCount: number;
@@ -96,7 +98,7 @@ export type BuildAgentResponseTraceOptions = {
96
98
  events: readonly AgentTraceEvent[];
97
99
  nodeId?: NodeId;
98
100
  processId?: ProcessId;
99
- /** Recorded whole-node duration for an LLM invocation; response traces retain their output-ready duration. */
101
+ /** Recorded whole-node duration for a model invocation; response traces retain their output-ready duration. */
100
102
  invocationDurationMs?: number;
101
103
  startedAt?: number;
102
104
  responseReadyAt?: number;
@@ -108,10 +110,19 @@ export declare function buildAgentResponseTrace(options: BuildAgentResponseTrace
108
110
  export declare function getAgentTraceEventIdentity(event: AgentTraceEvent): string | undefined;
109
111
  /**
110
112
  * Redelivery is allowed to omit newly added optional observability fields. Keep
111
- * an exact Delegate result pointer once it was observed instead of making a
112
- * later legacy-shaped copy erase result navigation.
113
+ * observed profile metadata and exact Delegate result pointers instead of
114
+ * making a later legacy-shaped copy erase diagnostics or result navigation.
113
115
  */
114
116
  export declare function mergeAgentTraceEvent(existing: AgentTraceEvent, incoming: AgentTraceEvent): AgentTraceEvent;
117
+ /** Redelivery may omit optional receipts, but supplied pricing remains authoritative. */
118
+ export declare function mergeAgentModelCall<T extends ChatV2CallTraceEvent>(existing: Omit<ChatV2CallTraceEvent, 'callId' | 'provider'> & {
119
+ callId: string;
120
+ provider: string;
121
+ }, incoming: T): T;
122
+ /** Merge one identified attempt, retaining additive metadata omitted by older transports. */
123
+ export declare function mergeAgentProfileAttempt<T extends LLMProfileAttemptTraceEvent>(existing: LLMProfileAttemptTraceEvent, incoming: T): T;
124
+ /** Shared metadata accounting for response inspectors and the bounded activity journal. */
125
+ export declare function summarizeAgentResponseCalls(modelCalls: readonly AgentModelCallTrace[], profileAttempts: readonly AgentLLMProfileAttemptTrace[], toolCalls: readonly AgentToolCallTrace[]): AgentResponseTrace['summary'];
115
126
  export declare function isAgentResponseTrace(value: unknown): value is AgentResponseTrace;
116
127
  /**
117
128
  * Collects privacy-bounded response metadata for one root processor run.
@@ -0,0 +1,15 @@
1
+ import type { AgentLLMProfileAttemptTrace, AgentResponseTrace } from './AgentResponseTrace.js';
2
+ export type AgentProfileAttemptInspectorRow = Readonly<{
3
+ context: string;
4
+ error?: string;
5
+ eventId: string;
6
+ providerAndModel: string;
7
+ }>;
8
+ export declare function buildAgentProfileAttemptInspectorRows(attempts: readonly AgentLLMProfileAttemptTrace[]): AgentProfileAttemptInspectorRow[];
9
+ /** Physical classifier requests share profile evidence, not LLM chat-round semantics. */
10
+ export declare function isClassifierRequest(attempt: AgentLLMProfileAttemptTrace): boolean;
11
+ export declare function getClassifierRequestCount(trace: AgentResponseTrace): number | undefined;
12
+ /** Older trace counters inferred from capped rows are lower bounds, not exact totals. */
13
+ export declare function formatClassifierRequestCount(trace: AgentResponseTrace): string | undefined;
14
+ /** One shared cap covers both physical classifier requests and profile decisions. */
15
+ export declare function getProfileAttemptOmissionNotice(trace: AgentResponseTrace): string | undefined;
@@ -2,6 +2,7 @@ import type { GraphId } from '../index.js';
2
2
  import type { DataId } from './Project.js';
3
3
  import type { RivetKnowledgeDocument, RivetKnowledgeEvidence, RivetKnowledgeSourceReference } from '../integrations/KnowledgeStore.js';
4
4
  import { type LLMProfileValue } from './chat-v2/llmProfileTypes.js';
5
+ import type { ClassifierProfileValue } from './classifier/profile.js';
5
6
  export type DataValueDef<Type extends string, RuntimeType> = {
6
7
  type: Type;
7
8
  value: RuntimeType;
@@ -12,19 +13,19 @@ export type BoolDataValue = DataValueDef<'boolean', boolean>;
12
13
  export type SystemChatMessage = {
13
14
  type: 'system';
14
15
  message: ChatMessageMessagePart | ChatMessageMessagePart[];
15
- /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */
16
+ /** Prompt-cache breakpoint for Anthropic or supported OpenRouter endpoints. */
16
17
  isCacheBreakpoint?: boolean;
17
18
  };
18
19
  export type DeveloperChatMessage = {
19
20
  type: 'developer';
20
21
  message: ChatMessageMessagePart | ChatMessageMessagePart[];
21
- /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */
22
+ /** Prompt-cache breakpoint for Anthropic or supported OpenRouter endpoints. */
22
23
  isCacheBreakpoint?: boolean;
23
24
  };
24
25
  export type UserChatMessage = {
25
26
  type: 'user';
26
27
  message: ChatMessageMessagePart | ChatMessageMessagePart[];
27
- /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */
28
+ /** Prompt-cache breakpoint for Anthropic or supported OpenRouter endpoints. */
28
29
  isCacheBreakpoint?: boolean;
29
30
  };
30
31
  export type AssistantChatMessageFunctionCall = {
@@ -40,10 +41,12 @@ export type ParsedAssistantChatMessageFunctionCall = {
40
41
  export type AssistantChatMessage = {
41
42
  type: 'assistant';
42
43
  message: ChatMessageMessagePart | ChatMessageMessagePart[];
44
+ /** Provider-returned reasoning continuity, including opaque encrypted blocks; not an API credential. */
45
+ openRouterReasoningDetails?: Record<string, unknown>[];
43
46
  /** @deprecated use function_calls instead */
44
47
  function_call: AssistantChatMessageFunctionCall | undefined;
45
48
  function_calls: AssistantChatMessageFunctionCall[] | undefined;
46
- /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */
49
+ /** Prompt-cache breakpoint for Anthropic or supported OpenRouter endpoints. */
47
50
  isCacheBreakpoint?: boolean;
48
51
  };
49
52
  export type FunctionResponseChatMessage = {
@@ -51,7 +54,7 @@ export type FunctionResponseChatMessage = {
51
54
  message: ChatMessageMessagePart | ChatMessageMessagePart[];
52
55
  name: string;
53
56
  toolName?: string;
54
- /** If true, this message marks a breakpoint when used with prompt caching (as of right now, Anthropic-only). */
57
+ /** Prompt-cache breakpoint for Anthropic or supported OpenRouter endpoints. */
55
58
  isCacheBreakpoint?: boolean;
56
59
  };
57
60
  export type ChatMessage = SystemChatMessage | DeveloperChatMessage | UserChatMessage | AssistantChatMessage | FunctionResponseChatMessage;
@@ -96,6 +99,7 @@ export type KnowledgeSourceDataValue = DataValueDef<'knowledge-source', RivetKno
96
99
  export type KnowledgeDocumentDataValue = DataValueDef<'knowledge-document', RivetKnowledgeDocument>;
97
100
  export type KnowledgeEvidenceDataValue = DataValueDef<'knowledge-evidence', RivetKnowledgeEvidence>;
98
101
  export type LLMProfileDataValue = DataValueDef<'llm-config', LLMProfileValue>;
102
+ export type ClassifierProfileDataValue = DataValueDef<'classifier-config', ClassifierProfileValue>;
99
103
  export type DocumentDataValue = DataValueDef<'document', {
100
104
  mediaType: SupportedDocumentMediaTypes;
101
105
  data: Uint8Array;
@@ -116,7 +120,7 @@ export type GptFunction = {
116
120
  };
117
121
  export type GptFunctionDataValue = DataValueDef<'gpt-function', GptFunction>;
118
122
  export type ControlFlowExcludedDataValue = DataValueDef<'control-flow-excluded', undefined | 'loop-not-broken'>;
119
- export type ScalarDataValue = StringDataValue | NumberDataValue | DateDataValue | TimeDataValue | DateTimeDataValue | BoolDataValue | ChatMessageDataValue | ControlFlowExcludedDataValue | AnyDataValue | ObjectDataValue | GptFunctionDataValue | VectorDataValue | ImageDataValue | BinaryDataValue | AudioDataValue | GraphReferenceValue | KnowledgeSourceDataValue | KnowledgeDocumentDataValue | KnowledgeEvidenceDataValue | LLMProfileDataValue | DocumentDataValue;
123
+ export type ScalarDataValue = StringDataValue | NumberDataValue | DateDataValue | TimeDataValue | DateTimeDataValue | BoolDataValue | ChatMessageDataValue | ControlFlowExcludedDataValue | AnyDataValue | ObjectDataValue | GptFunctionDataValue | VectorDataValue | ImageDataValue | BinaryDataValue | AudioDataValue | GraphReferenceValue | KnowledgeSourceDataValue | KnowledgeDocumentDataValue | KnowledgeEvidenceDataValue | LLMProfileDataValue | ClassifierProfileDataValue | DocumentDataValue;
120
124
  export type ScalarType = ScalarDataValue['type'];
121
125
  export type ArrayDataValue<T extends ScalarDataValue> = DataValueDef<`${T['type']}[]`, T['value'][]>;
122
126
  export type FunctionDataValue<T extends ScalarOrArrayDataValue> = DataValueDef<`fn<${T['type']}>`, () => T['value']>;
@@ -150,8 +154,8 @@ export type GetDataValue<Type extends DataType> = Extract<DataValue, {
150
154
  export type DataRef = {
151
155
  refId: DataId;
152
156
  };
153
- export declare const dataTypes: ["any", "any[]", "boolean", "boolean[]", "string", "string[]", "number", "number[]", "date", "date[]", "time", "time[]", "datetime", "datetime[]", "chat-message", "chat-message[]", "control-flow-excluded", "control-flow-excluded[]", "object", "object[]", "fn<string>", "fn<number>", "fn<boolean>", "fn<date>", "fn<time>", "fn<datetime>", "fn<any>", "fn<object>", "fn<chat-message>", "fn<control-flow-excluded>", "fn<string[]>", "fn<number[]>", "fn<boolean[]>", "fn<date[]>", "fn<time[]>", "fn<datetime[]>", "fn<any[]>", "fn<object[]>", "fn<chat-message[]>", "fn<control-flow-excluded[]>", "gpt-function", "gpt-function[]", "fn<gpt-function[]>", "fn<gpt-function>", "vector", "vector[]", "fn<vector>", "fn<vector[]>", "image", "image[]", "fn<image>", "fn<image[]>", "binary", "binary[]", "fn<binary>", "fn<binary[]>", "audio", "audio[]", "fn<audio>", "fn<audio[]>", "graph-reference", "graph-reference[]", "fn<graph-reference>", "fn<graph-reference[]>", "knowledge-source", "knowledge-source[]", "fn<knowledge-source>", "fn<knowledge-source[]>", "knowledge-document", "knowledge-document[]", "fn<knowledge-document>", "fn<knowledge-document[]>", "knowledge-evidence", "knowledge-evidence[]", "fn<knowledge-evidence>", "fn<knowledge-evidence[]>", "llm-config", "llm-config[]", "fn<llm-config>", "fn<llm-config[]>", "document", "document[]", "fn<document>", "fn<document[]>"];
154
- export declare const scalarTypes: ["any", "boolean", "string", "number", "date", "time", "datetime", "chat-message", "control-flow-excluded", "object", "gpt-function", "vector", "image", "binary", "audio", "graph-reference", "knowledge-source", "knowledge-document", "knowledge-evidence", "llm-config", "document"];
157
+ export declare const dataTypes: ["any", "any[]", "boolean", "boolean[]", "string", "string[]", "number", "number[]", "date", "date[]", "time", "time[]", "datetime", "datetime[]", "chat-message", "chat-message[]", "control-flow-excluded", "control-flow-excluded[]", "object", "object[]", "fn<string>", "fn<number>", "fn<boolean>", "fn<date>", "fn<time>", "fn<datetime>", "fn<any>", "fn<object>", "fn<chat-message>", "fn<control-flow-excluded>", "fn<string[]>", "fn<number[]>", "fn<boolean[]>", "fn<date[]>", "fn<time[]>", "fn<datetime[]>", "fn<any[]>", "fn<object[]>", "fn<chat-message[]>", "fn<control-flow-excluded[]>", "gpt-function", "gpt-function[]", "fn<gpt-function[]>", "fn<gpt-function>", "vector", "vector[]", "fn<vector>", "fn<vector[]>", "image", "image[]", "fn<image>", "fn<image[]>", "binary", "binary[]", "fn<binary>", "fn<binary[]>", "audio", "audio[]", "fn<audio>", "fn<audio[]>", "graph-reference", "graph-reference[]", "fn<graph-reference>", "fn<graph-reference[]>", "knowledge-source", "knowledge-source[]", "fn<knowledge-source>", "fn<knowledge-source[]>", "knowledge-document", "knowledge-document[]", "fn<knowledge-document>", "fn<knowledge-document[]>", "knowledge-evidence", "knowledge-evidence[]", "fn<knowledge-evidence>", "fn<knowledge-evidence[]>", "llm-config", "llm-config[]", "fn<llm-config>", "fn<llm-config[]>", "classifier-config", "classifier-config[]", "fn<classifier-config>", "fn<classifier-config[]>", "document", "document[]", "fn<document>", "fn<document[]>"];
158
+ export declare const scalarTypes: ["any", "boolean", "string", "number", "date", "time", "datetime", "chat-message", "control-flow-excluded", "object", "gpt-function", "vector", "image", "binary", "audio", "graph-reference", "knowledge-source", "knowledge-document", "knowledge-evidence", "llm-config", "classifier-config", "document"];
155
159
  export declare const dataTypeDisplayNames: Record<DataType, string>;
156
160
  export declare function isScalarDataValue(value: DataValue | undefined): value is ScalarDataValue;
157
161
  export declare function isScalarDataType(type: DataType): type is ScalarDataType;
@@ -9,6 +9,7 @@ import type { EventOccurrenceTiming, FrozenNodeOutputsByGraph, NodeResultOrigin,
9
9
  import type { GraphProgress } from './GraphProgress.js';
10
10
  import type { StreamingOutputWatchHistorySummary } from './StreamingOutputWatchHistory.js';
11
11
  import type { RivetWebAppStorage } from './UiGraphWebAppStorage.js';
12
+ import type { CombinedDataset } from '../utils/index.js';
12
13
  export type GraphInputs = Record<string, DataValue>;
13
14
  export type GraphOutputs = Record<string, DataValue>;
14
15
  export type Inputs = Record<PortId, DataValue | undefined>;
@@ -124,23 +125,28 @@ export type SerializedProcessEventMap = {
124
125
  }>;
125
126
  error: {
126
127
  error: Error | string;
128
+ execution?: GraphExecutionMetadata;
127
129
  } & ReplayEventTiming;
128
130
  done: {
129
131
  results: GraphOutputs;
132
+ execution?: GraphExecutionMetadata;
130
133
  } & ReplayEventTiming;
131
134
  abort: {
132
135
  successful: boolean;
133
136
  error?: string | Error;
137
+ execution?: GraphExecutionMetadata;
134
138
  } & ReplayEventTiming;
135
139
  finish: void;
136
140
  trace: string;
137
- /** Present only when RecordingPlayer re-emits a historical lifecycle transition. */
141
+ /** Replay marker is recording-only; live debuggers may identify the owning root. */
138
142
  pause: {
139
143
  isReplay?: true;
144
+ execution?: GraphExecutionMetadata;
140
145
  } | undefined;
141
- /** Present only when RecordingPlayer re-emits a historical lifecycle transition. */
146
+ /** Replay marker is recording-only; live debuggers may identify the owning root. */
142
147
  resume: {
143
148
  isReplay?: true;
149
+ execution?: GraphExecutionMetadata;
144
150
  } | undefined;
145
151
  globalSet: WithExecution<{
146
152
  id: string;
@@ -251,6 +257,12 @@ export type OutgoingMessageMap = {
251
257
  contextValues: Record<string, DataValue>;
252
258
  inputs?: GraphInputs;
253
259
  projectPath?: string | null;
260
+ /** Local desktop executor only. Hosted executors reject client filesystem bundle paths. */
261
+ projectBundle?: {
262
+ manifestPath: string;
263
+ artifactId: string;
264
+ entryDatasets: CombinedDataset[];
265
+ };
254
266
  useEditorCache?: boolean;
255
267
  captureNodeTimings?: boolean;
256
268
  /** Hosted editor setting; only the authenticated Node executor uses it. */
@@ -19,5 +19,14 @@ export type FrozenGraphBoundaryEffect = FrozenSetGlobalEffect | FrozenSetStoredV
19
19
  * single boundary rule.
20
20
  */
21
21
  export declare function commitGraphOutputValue(graphOutputs: GraphOutputs, outputId: string, value: DataValue): void;
22
- export declare function ensureGraphCostOutput(graphOutputs: GraphOutputs, totalCost: number): void;
22
+ export type GraphCostBreakdown = {
23
+ llm: number;
24
+ classifier: number;
25
+ other: number;
26
+ };
27
+ /** Safe family totals carried across graph and tool boundaries, separate from node diagnostics. */
28
+ export declare function readGraphCostBreakdown(outputs: Outputs): GraphCostBreakdown | undefined;
29
+ export declare function graphCostBreakdownMatchesCost(breakdown: GraphCostBreakdown, cost: number): boolean;
30
+ export declare function addGraphCostBreakdown(current: GraphCostBreakdown | undefined, addition: GraphCostBreakdown): GraphCostBreakdown;
31
+ export declare function ensureGraphCostOutput(graphOutputs: GraphOutputs, totalCost: number, breakdown?: GraphCostBreakdown): void;
23
32
  export declare function applyFrozenGraphBoundaryEffects(graphOutputs: GraphOutputs, node: ChartNode, outputValues: Outputs): FrozenGraphBoundaryEffect | undefined;
@@ -0,0 +1,68 @@
1
+ import type { DataValue, StringArrayDataValue, ScalarOrArrayDataValue } from './DataValue.js';
2
+ import type { NodeId } from './NodeBase.js';
3
+ import type { Project, ProjectId } from './Project.js';
4
+ import type { ProcessContext, ProcessId, RootRunId, GraphRunId } from './ProcessContext.js';
5
+ import type { AttachedNodeData, GraphProcessor, GraphInputs, GraphOutputs, NodeResults, Outputs, NodeAbortControllerEntry } from './GraphProcessor.js';
6
+ import type PQueue from '../utils/pQueueCompat.js';
7
+ import type { NodeProcessContextBase } from './ProcessContextBuilder.js';
8
+ import type { GraphOutputSelection } from './GraphOutputSelection.js';
9
+ import type { RivetStoredValueController } from './StoredValueStore.js';
10
+ import type { KnowledgeStoreController } from '../integrations/KnowledgeStoreProvider.js';
11
+ import type { ResolvedSubgraphProject } from './SubgraphProjectTarget.js';
12
+ import type { GraphCostBreakdown } from './GraphBoundaryEffects.js';
13
+ /** Invocation-owned fields; GraphProcessor resets them at the established initialization boundaries. */
14
+ export declare class GraphInvocationState {
15
+ rootRunId: RootRunId;
16
+ graphRunId: GraphRunId;
17
+ parentGraphRunId: GraphRunId | undefined;
18
+ erroredNodes: Map<NodeId, Error | string>;
19
+ failureOutputsByProcessId: Map<ProcessId, Map<number, Outputs>>;
20
+ remainingNodes: Set<NodeId>;
21
+ visitedNodes: Set<NodeId>;
22
+ currentlyProcessing: Set<NodeId>;
23
+ context: ProcessContext;
24
+ nodeResults: NodeResults;
25
+ abortController: AbortController;
26
+ processingQueue: InstanceType<typeof PQueue>;
27
+ graphInputs: GraphInputs;
28
+ graphOutputs: GraphOutputs;
29
+ queuedNodes: Set<NodeId>;
30
+ /** Run To quiescence may defer nodes that a later streaming Stop resumes. */
31
+ deferredRunToIgnoredNodes: Set<NodeId>;
32
+ loopControllersSeen: Set<NodeId>;
33
+ subprocessors: Set<GraphProcessor>;
34
+ attachedNodeData: Map<NodeId, AttachedNodeData>;
35
+ successfulAbortTerminalProcessIds: Set<ProcessId>;
36
+ totalCost: number;
37
+ costBreakdown: GraphCostBreakdown | undefined;
38
+ ignoreNodes: Set<NodeId>;
39
+ hasPreloadedData: boolean;
40
+ loadedProjects: Record<ProjectId, Project>;
41
+ nodeProcessContextBase: NodeProcessContextBase;
42
+ runToRelevantNodeIds: Set<NodeId> | undefined;
43
+ graphOutputSelection: GraphOutputSelection | undefined;
44
+ nodeAbortControllers: Map<NodeId, NodeAbortControllerEntry>;
45
+ graphInputNodeValues: Record<string, DataValue>;
46
+ /** User input nodes awaiting interactive input for this invocation. */
47
+ pendingUserInputs: Record<NodeId, {
48
+ resolve: (values: StringArrayDataValue) => void;
49
+ }>;
50
+ /** Mutate the owner in place: late child cost/events still address this invocation. */
51
+ initialize(options: {
52
+ preloadedNodeResults: NodeResults;
53
+ remainingNodeIds: Iterable<NodeId>;
54
+ processingQueue: InstanceType<typeof PQueue>;
55
+ createAbortController: () => AbortController;
56
+ loadedProjects: Record<ProjectId, Project>;
57
+ sharedOverride?: Pick<GraphInvocationState, 'graphOutputs' | 'attachedNodeData' | 'graphInputNodeValues'>;
58
+ }): void;
59
+ }
60
+ /** Shared by every child kind; retained caches/globals deliberately keep existing reuse semantics. */
61
+ export declare class GraphSharedExecutionState {
62
+ globals: Map<string, ScalarOrArrayDataValue>;
63
+ executionCache: Map<string, unknown>;
64
+ storedValueController: RivetStoredValueController;
65
+ knowledgeStoreController: KnowledgeStoreController;
66
+ subgraphTargetCache: Map<ProjectId, ResolvedSubgraphProject>;
67
+ nextRootRun(): GraphSharedExecutionState;
68
+ }
@@ -34,6 +34,7 @@ export type EventOccurrenceTiming = {
34
34
  type WithExecution<T extends object> = T & {
35
35
  execution: GraphExecutionMetadata;
36
36
  } & ReplayEventTiming & EventOccurrenceTiming;
37
+ export type NodeAbortControllerEntry = AbortController | Set<AbortController>;
37
38
  declare const graphProcessorGraphOverride: unique symbol;
38
39
  declare const consumedAsyncBranchTriggerOverride: unique symbol;
39
40
  declare const asyncBranchInputAnchorsOverride: unique symbol;
@@ -0,0 +1,96 @@
1
+ import type { DataType, DataValue } from './DataValue.js';
2
+ import type { ChartNode, NodeId, PortId } from './NodeBase.js';
3
+ import type { NodeGraph } from './NodeGraph.js';
4
+ import type { CatchStreamingChunksNode } from './nodes/CatchStreamingChunksNode.js';
5
+ import type { StreamingOutputWatch } from './StreamingOutputWatch.js';
6
+ import type { StreamingOutputWatchHistory, StreamingOutputWatchHistoryIteration } from './StreamingOutputWatchHistory.js';
7
+ import type { GraphInputStream, GraphInputStreamRelay } from './GraphInputStream.js';
8
+ export type SchedulerBoundaryFailure = {
9
+ error: Error;
10
+ triggerNode: ChartNode;
11
+ nodeErrors: Array<{
12
+ error: Error | string;
13
+ node: ChartNode;
14
+ }>;
15
+ };
16
+ export type StreamingOutputWatchPlan = {
17
+ graph: NodeGraph;
18
+ /** Only retain and snapshot the cumulative history when a branch consumes it. */
19
+ includeAllStreamedOutput: boolean;
20
+ sourceOutputId: PortId;
21
+ /**
22
+ * A Stop boundary is optional. Without one, every snapshot runs the entire
23
+ * contained branch and the watch completes normally with its producer.
24
+ */
25
+ stopNodeId?: NodeId;
26
+ /**
27
+ * Immutable stream increments observed for this run. Cumulative string
28
+ * snapshots contribute only their new suffix so an LLM response does not
29
+ * retain N copies of its whole prefix.
30
+ */
31
+ streamedOutput: unknown[];
32
+ previousStreamedValue: unknown;
33
+ watchNode: ChartNode;
34
+ nextUpdateIndex: number;
35
+ history: StreamingOutputWatchHistory;
36
+ historySummaryEmitted: boolean;
37
+ /** True once normal stream exhaustion has excluded the parent Stop boundary. */
38
+ unmatchedStopResolved: boolean;
39
+ };
40
+ export type StreamingOutputCatchPlan = {
41
+ node: CatchStreamingChunksNode;
42
+ sourceOutputId: PortId;
43
+ count: number;
44
+ chunks: DataValue[];
45
+ settled: boolean;
46
+ };
47
+ export type StreamingOutputWatchInvocation = {
48
+ plan: StreamingOutputWatchPlan;
49
+ historyIteration: StreamingOutputWatchHistoryIteration;
50
+ /**
51
+ * Atomically claims the parent Watch's one accepted Stop value. The claim is
52
+ * made before the child's nodeFinish is emitted so that event can identify
53
+ * the actual terminal branch, but its parent-dataflow effects are committed
54
+ * only after that lifecycle event has been published.
55
+ */
56
+ claimStop: (value: DataValue) => StreamingOutputWatchStopClaim | undefined;
57
+ /**
58
+ * Set only by the live Stop node implementation. The output that re-enters
59
+ * the parent is deliberately taken from the completed node result instead:
60
+ * split nodes aggregate their per-item outputs only at that boundary.
61
+ */
62
+ stopReached: boolean;
63
+ };
64
+ export type StreamingOutputWatchStopClaim = {
65
+ commit: () => void;
66
+ };
67
+ export type GraphOutputPartialBinding = {
68
+ dataType: DataType;
69
+ graphOutputId: string;
70
+ sourceOutputId: PortId;
71
+ };
72
+ /** Invocation-owned boundary resources; no scheduling or event-emission policy. */
73
+ export declare class GraphSchedulerBoundaryState {
74
+ streamingWatchPlansBySourceNodeId: Map<NodeId, StreamingOutputWatchPlan[]>;
75
+ streamingWatchPlansByWatchNodeId: Map<NodeId, StreamingOutputWatchPlan>;
76
+ streamingOutputWatches: Map<NodeId, StreamingOutputWatch>;
77
+ streamingCatchPlansBySourceNodeId: Map<NodeId, StreamingOutputCatchPlan[]>;
78
+ streamingCatchTasks: Set<Promise<void>>;
79
+ graphOutputPartialBindingsBySourceNodeId: Map<NodeId, GraphOutputPartialBinding[]>;
80
+ graphInputStreams: Readonly<Record<string, GraphInputStream>>;
81
+ callerInputStreams: Map<NodeId, Record<string, GraphInputStreamRelay>>;
82
+ inputStreamRoutes: Map<NodeId, {
83
+ port: PortId;
84
+ relay: GraphInputStreamRelay;
85
+ }[]>;
86
+ streamCallerTasks: Set<Promise<unknown>>;
87
+ inputStreamDisposers: Array<() => void>;
88
+ pendingGraphInputFinals: Map<NodeId, import("./NodeIO.js").NodeOutputs>;
89
+ streamingWatchFailures: SchedulerBoundaryFailure[];
90
+ resetTopology(): void;
91
+ /** Called after invocation initialization, before subscriptions can be admitted. */
92
+ initializeInputStreams(streams?: Readonly<Record<string, GraphInputStream>>): void;
93
+ /** Release every subscription/relay, even if one host-provided disposer fails. */
94
+ releaseInputStreams(): void;
95
+ drainCatchTasks(waitForQueue: () => Promise<unknown>): Promise<void>;
96
+ }