@valerypopoff/rivet2-core 2.3.0 → 2.5.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 (105) hide show
  1. package/dist/cjs/bundle.cjs +1947 -765
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +1578 -0
  4. package/dist/cjs/interpolationRuntime.cjs.map +7 -0
  5. package/dist/cjs/interpolationSyntax.cjs +186 -0
  6. package/dist/cjs/interpolationSyntax.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs +1537 -121
  8. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  9. package/dist/esm/api/createProcessor.js +2 -0
  10. package/dist/esm/exports.js +4 -1
  11. package/dist/esm/integrations/CodeRunner.js +5 -0
  12. package/dist/esm/integrations/mcp/MCPBase.js +16 -6
  13. package/dist/esm/interpolationRuntime.js +5 -0
  14. package/dist/esm/model/AgentResponseTrace.js +16 -0
  15. package/dist/esm/model/GraphBoundaryCache.js +0 -6
  16. package/dist/esm/model/GraphBoundaryEffects.js +5 -1
  17. package/dist/esm/model/GraphOutputSelection.js +34 -0
  18. package/dist/esm/model/GraphProcessor.js +150 -44
  19. package/dist/esm/model/NodeExclusionPolicy.js +9 -1
  20. package/dist/esm/model/ProcessContextBuilder.js +4 -1
  21. package/dist/esm/model/RecordingPlayer.js +19 -6
  22. package/dist/esm/model/StoredValueStore.js +4 -3
  23. package/dist/esm/model/SubprocessorBridge.js +1 -0
  24. package/dist/esm/model/UiGraphActionProtocol.js +46 -4
  25. package/dist/esm/model/UiGraphBrowserRuntime.js +15 -1
  26. package/dist/esm/model/UiGraphIndexedDbPersistence.js +523 -0
  27. package/dist/esm/model/UiGraphRendererStyles.js +14 -0
  28. package/dist/esm/model/WebAppBrowserStorage.js +653 -0
  29. package/dist/esm/model/WebAppBrowserStorageRpc.js +200 -0
  30. package/dist/esm/model/chat-v2/chatV2CallObserver.js +1 -0
  31. package/dist/esm/model/chat-v2/chatV2EditorCache.js +2 -33
  32. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +1 -0
  33. package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +42 -0
  34. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +31 -2
  35. package/dist/esm/model/chat-v2/llmProfile.js +17 -1
  36. package/dist/esm/model/chat-v2/llmProfileFallback.js +17 -5
  37. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +2 -0
  38. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +4 -0
  39. package/dist/esm/model/chat-v2/toolContinuation.js +27 -1
  40. package/dist/esm/model/nodes/CodeNewNode.js +16 -16
  41. package/dist/esm/model/nodes/DestructureNode.js +2 -2
  42. package/dist/esm/model/nodes/ExpressionNode.js +16 -16
  43. package/dist/esm/model/nodes/ExtractObjectPathNode.js +2 -2
  44. package/dist/esm/model/nodes/ExtractYamlNode.js +5 -5
  45. package/dist/esm/model/nodes/JSFilterNode.js +3 -1
  46. package/dist/esm/model/nodes/JSMapNode.js +3 -1
  47. package/dist/esm/model/nodes/LLMChatV2Node.js +21 -2
  48. package/dist/esm/model/nodes/MCPGetPromptNode.js +6 -2
  49. package/dist/esm/model/nodes/MCPToolCallNode.js +6 -2
  50. package/dist/esm/model/nodes/ObjectNode.js +19 -20
  51. package/dist/esm/model/nodes/PromptNode.js +10 -11
  52. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +2 -40
  53. package/dist/esm/model/nodes/SubGraphNode.js +40 -26
  54. package/dist/esm/model/nodes/TextNode.js +11 -32
  55. package/dist/esm/model/nodes/ToTreeNode.js +6 -13
  56. package/dist/esm/model/nodes/ToolNode.js +33 -16
  57. package/dist/esm/model/nodes/jsListCallbackHelpers.js +19 -15
  58. package/dist/esm/model/nodes/jsValueInterpolation.js +83 -30
  59. package/dist/esm/model/nodes/nodeBodyPreview.js +23 -0
  60. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +14 -11
  61. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  62. package/dist/esm/utils/index.js +2 -0
  63. package/dist/esm/utils/interpolation.js +478 -221
  64. package/dist/esm/utils/interpolationSyntax.js +175 -0
  65. package/dist/esm/utils/jsonPath.js +129 -0
  66. package/dist/esm/webAppRuntime.js +5 -2
  67. package/dist/types/api/createProcessor.d.ts +2 -0
  68. package/dist/types/exports.d.ts +5 -1
  69. package/dist/types/integrations/CodeRunnerOptions.d.ts +9 -0
  70. package/dist/types/integrations/mcp/MCPBase.d.ts +3 -1
  71. package/dist/types/interpolationRuntime.d.ts +5 -0
  72. package/dist/types/model/AgentResponseTrace.d.ts +1 -0
  73. package/dist/types/model/ExecutorProtocol.d.ts +9 -1
  74. package/dist/types/model/GraphBoundaryCache.d.ts +0 -2
  75. package/dist/types/model/GraphOutputSelection.d.ts +8 -0
  76. package/dist/types/model/GraphProcessor.d.ts +7 -4
  77. package/dist/types/model/NodeExclusionPolicy.d.ts +6 -0
  78. package/dist/types/model/ProcessContext.d.ts +36 -2
  79. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  80. package/dist/types/model/UiGraphActionProtocol.d.ts +8 -3
  81. package/dist/types/model/UiGraphBrowserRuntime.d.ts +6 -0
  82. package/dist/types/model/UiGraphIndexedDbPersistence.d.ts +50 -0
  83. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  84. package/dist/types/model/WebAppBrowserStorage.d.ts +90 -0
  85. package/dist/types/model/WebAppBrowserStorageRpc.d.ts +85 -0
  86. package/dist/types/model/chat-v2/chatV2Types.d.ts +3 -1
  87. package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -0
  88. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +5 -1
  89. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +4 -0
  90. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +10 -0
  91. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +6 -0
  92. package/dist/types/model/chat-v2/toolContinuation.d.ts +14 -0
  93. package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
  94. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  95. package/dist/types/model/nodes/ToTreeNode.d.ts +5 -2
  96. package/dist/types/model/nodes/ToolNode.d.ts +13 -1
  97. package/dist/types/model/nodes/jsValueInterpolation.d.ts +16 -8
  98. package/dist/types/model/nodes/nodeBodyPreview.d.ts +7 -0
  99. package/dist/types/recording/RecordedEvents.d.ts +11 -0
  100. package/dist/types/utils/index.d.ts +2 -0
  101. package/dist/types/utils/interpolation.d.ts +93 -8
  102. package/dist/types/utils/interpolationSyntax.d.ts +21 -0
  103. package/dist/types/utils/jsonPath.d.ts +15 -0
  104. package/dist/types/webAppRuntime.d.ts +8 -2
  105. package/package.json +11 -1
@@ -0,0 +1,200 @@
1
+ import { cloneRivetStoredValue, cloneRivetStoredValueRecord, } from './StoredValueStore.js';
2
+ export const RIVET_WEB_APP_BROWSER_STORAGE_RPC_CAPABILITY = 'browser-storage-rpc-v2';
3
+ export const RIVET_WEB_APP_BROWSER_STORAGE_RPC_VERSION = 2;
4
+ export const RIVET_WEB_APP_BROWSER_STORAGE_SAFE_FALLBACK_BYTES = 4 * 1024 * 1024;
5
+ export const RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_VALUE_BYTES = 256 * 1024 * 1024;
6
+ export const RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTION_BYTES = 512 * 1024 * 1024;
7
+ export const RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_MAX_ACTIVE_BYTES = 512 * 1024 * 1024;
8
+ export const RIVET_WEB_APP_BROWSER_STORAGE_DEFAULT_TRANSFER_TIMEOUT_MS = 60_000;
9
+ export const RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES = 256 * 1024;
10
+ export const RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES = 40;
11
+ const FRAME_MAGIC = new Uint8Array([0x52, 0x56, 0x42, 0x53]); // RVBS
12
+ export function parseRivetWebAppBrowserStorageClientMessage(value) {
13
+ if (!isRecord(value) || !hasActionIds(value) || typeof value.type !== 'string')
14
+ return undefined;
15
+ if (!isUuid(value.storageSessionId))
16
+ return undefined;
17
+ if (value.type === 'storage.transfer.start') {
18
+ return isNonEmptyString(value.storageRequestId) &&
19
+ isUuid(value.transferId) &&
20
+ isSafeByteLength(value.byteLength) &&
21
+ isSafeChunkCount(value.chunkCount) &&
22
+ typeof value.found === 'boolean'
23
+ ? {
24
+ type: value.type,
25
+ requestId: value.requestId,
26
+ runId: value.runId,
27
+ storageSessionId: value.storageSessionId,
28
+ storageRequestId: value.storageRequestId,
29
+ transferId: value.transferId,
30
+ byteLength: value.byteLength,
31
+ chunkCount: value.chunkCount,
32
+ found: value.found,
33
+ }
34
+ : undefined;
35
+ }
36
+ if (value.type === 'storage.commit.ack') {
37
+ return isUuid(value.transferId)
38
+ ? {
39
+ type: value.type,
40
+ requestId: value.requestId,
41
+ runId: value.runId,
42
+ storageSessionId: value.storageSessionId,
43
+ transferId: value.transferId,
44
+ }
45
+ : undefined;
46
+ }
47
+ if (value.type === 'storage.error')
48
+ return parseStorageError(value);
49
+ return undefined;
50
+ }
51
+ export function parseRivetWebAppBrowserStorageServerMessage(value) {
52
+ if (!isRecord(value) || !hasActionIds(value) || typeof value.type !== 'string')
53
+ return undefined;
54
+ if (!isUuid(value.storageSessionId))
55
+ return undefined;
56
+ if (value.type === 'storage.get') {
57
+ return isNonEmptyString(value.storageRequestId) && typeof value.key === 'string' && value.key.length > 0
58
+ ? {
59
+ type: value.type,
60
+ requestId: value.requestId,
61
+ runId: value.runId,
62
+ storageSessionId: value.storageSessionId,
63
+ storageRequestId: value.storageRequestId,
64
+ key: value.key,
65
+ }
66
+ : undefined;
67
+ }
68
+ if (value.type === 'storage.transfer.ack') {
69
+ return isNonEmptyString(value.storageRequestId) && isUuid(value.transferId)
70
+ ? {
71
+ type: value.type,
72
+ requestId: value.requestId,
73
+ runId: value.runId,
74
+ storageSessionId: value.storageSessionId,
75
+ storageRequestId: value.storageRequestId,
76
+ transferId: value.transferId,
77
+ }
78
+ : undefined;
79
+ }
80
+ if (value.type === 'storage.commit.start') {
81
+ return isUuid(value.transferId) && isSafeByteLength(value.byteLength) && isSafeChunkCount(value.chunkCount)
82
+ ? {
83
+ type: value.type,
84
+ requestId: value.requestId,
85
+ runId: value.runId,
86
+ storageSessionId: value.storageSessionId,
87
+ transferId: value.transferId,
88
+ byteLength: value.byteLength,
89
+ chunkCount: value.chunkCount,
90
+ }
91
+ : undefined;
92
+ }
93
+ if (value.type === 'storage.error')
94
+ return parseStorageError(value);
95
+ return undefined;
96
+ }
97
+ export function serializeRivetWebAppStoredValue(value) {
98
+ return new TextEncoder().encode(JSON.stringify(value));
99
+ }
100
+ export function deserializeRivetWebAppStoredValue(bytes) {
101
+ return cloneRivetStoredValue(JSON.parse(new TextDecoder().decode(bytes)), 'Browser Stored Value transfer');
102
+ }
103
+ export function serializeRivetWebAppStoredValuePatch(patch) {
104
+ return new TextEncoder().encode(JSON.stringify(patch));
105
+ }
106
+ export function deserializeRivetWebAppStoredValuePatch(bytes) {
107
+ return cloneRivetStoredValueRecord(JSON.parse(new TextDecoder().decode(bytes)), 'Browser Stored Value commit');
108
+ }
109
+ export function splitRivetWebAppStorageTransfer(bytes) {
110
+ if (bytes.byteLength === 0)
111
+ return [];
112
+ const chunks = [];
113
+ for (let offset = 0; offset < bytes.byteLength; offset += RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES) {
114
+ chunks.push(bytes.slice(offset, Math.min(bytes.byteLength, offset + RIVET_WEB_APP_BROWSER_STORAGE_TRANSFER_CHUNK_BYTES)));
115
+ }
116
+ return chunks;
117
+ }
118
+ export function encodeRivetWebAppStorageBinaryFrame(storageSessionId, transferId, chunkIndex, bytes) {
119
+ const sessionUuid = uuidToBytes(storageSessionId);
120
+ const transferUuid = uuidToBytes(transferId);
121
+ if (!Number.isSafeInteger(chunkIndex) || chunkIndex < 0 || chunkIndex > 0xffff_ffff) {
122
+ throw new RangeError('Storage transfer chunk index is invalid.');
123
+ }
124
+ const frame = new Uint8Array(RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES + bytes.byteLength);
125
+ frame.set(FRAME_MAGIC, 0);
126
+ frame.set(sessionUuid, 4);
127
+ frame.set(transferUuid, 20);
128
+ new DataView(frame.buffer).setUint32(36, chunkIndex, false);
129
+ frame.set(bytes, RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES);
130
+ return frame;
131
+ }
132
+ export function decodeRivetWebAppStorageBinaryFrame(frame) {
133
+ const source = frame instanceof ArrayBuffer
134
+ ? new Uint8Array(frame)
135
+ : new Uint8Array(frame.buffer, frame.byteOffset, frame.byteLength);
136
+ if (source.byteLength < RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES)
137
+ return undefined;
138
+ for (let index = 0; index < FRAME_MAGIC.length; index += 1) {
139
+ if (source[index] !== FRAME_MAGIC[index])
140
+ return undefined;
141
+ }
142
+ return {
143
+ storageSessionId: bytesToUuid(source.slice(4, 20)),
144
+ transferId: bytesToUuid(source.slice(20, 36)),
145
+ chunkIndex: new DataView(source.buffer, source.byteOffset, RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES).getUint32(36, false),
146
+ bytes: source.slice(RIVET_WEB_APP_BROWSER_STORAGE_BINARY_FRAME_HEADER_BYTES),
147
+ };
148
+ }
149
+ function parseStorageError(value) {
150
+ return isStorageErrorCode(value.code) && typeof value.error === 'string' && typeof value.retryable === 'boolean'
151
+ ? {
152
+ type: 'storage.error',
153
+ requestId: value.requestId,
154
+ runId: value.runId,
155
+ storageSessionId: value.storageSessionId,
156
+ code: value.code,
157
+ error: value.error,
158
+ retryable: value.retryable,
159
+ ...(isNonEmptyString(value.storageRequestId) ? { storageRequestId: value.storageRequestId } : {}),
160
+ ...(isUuid(value.transferId) ? { transferId: value.transferId } : {}),
161
+ }
162
+ : undefined;
163
+ }
164
+ function hasActionIds(value) {
165
+ return isNonEmptyString(value.requestId) && isNonEmptyString(value.runId);
166
+ }
167
+ function isStorageErrorCode(value) {
168
+ return (value === 'storage_unavailable' ||
169
+ value === 'storage_invalid' ||
170
+ value === 'storage_too_large' ||
171
+ value === 'storage_capacity');
172
+ }
173
+ function isSafeByteLength(value) {
174
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
175
+ }
176
+ function isSafeChunkCount(value) {
177
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
178
+ }
179
+ function isUuid(value) {
180
+ return (typeof value === 'string' &&
181
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value));
182
+ }
183
+ function uuidToBytes(value) {
184
+ if (!isUuid(value))
185
+ throw new Error('Storage transfer ID must be a UUID.');
186
+ return Uint8Array.from(value
187
+ .replaceAll('-', '')
188
+ .match(/.{2}/g)
189
+ .map((part) => Number.parseInt(part, 16)));
190
+ }
191
+ function bytesToUuid(value) {
192
+ const hex = [...value].map((byte) => byte.toString(16).padStart(2, '0')).join('');
193
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
194
+ }
195
+ function isRecord(value) {
196
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
197
+ }
198
+ function isNonEmptyString(value) {
199
+ return typeof value === 'string' && value.length > 0;
200
+ }
@@ -120,6 +120,7 @@ export function notifyChatV2CallFinished(options, params) {
120
120
  callId: params.callId,
121
121
  attemptIndex: params.attemptIndex,
122
122
  ...(options.profileIndex == null ? {} : { profileIndex: options.profileIndex }),
123
+ ...(options.profileName == null ? {} : { profileName: options.profileName }),
123
124
  ...(options.profileHealthKey == null ? {} : { profileHealthKey: options.profileHealthKey }),
124
125
  ...(options.profileHealthState == null ? {} : { profileHealthState: options.profileHealthState }),
125
126
  ...(options.roundIndex == null ? {} : { roundIndex: options.roundIndex }),
@@ -2,44 +2,13 @@ import stableStringify from 'safe-stable-stringify';
2
2
  import CryptoJS from 'crypto-js';
3
3
  import { normalizeOpenAICompatibleEndpoint } from './providerOptions.js';
4
4
  import { parseCustomProviderApi } from './customProviderApi.js';
5
+ import { cloneLLMChatV2Outputs } from './llmChatV2OutputClone.js';
5
6
  export function buildLLMChatV2EditorCacheKey(parts) {
6
7
  const { cacheVersion = 3, ...keyParts } = parts;
7
8
  return stableStringify({ cacheVersion, ...keyParts }) ?? '';
8
9
  }
9
- function cloneEditorCacheValue(value, seen = new WeakMap()) {
10
- if (value == null || typeof value !== 'object') {
11
- return value;
12
- }
13
- if (value instanceof Uint8Array) {
14
- return new Uint8Array(value);
15
- }
16
- const existing = seen.get(value);
17
- if (existing != null) {
18
- return existing;
19
- }
20
- if (Array.isArray(value)) {
21
- const clone = [];
22
- seen.set(value, clone);
23
- clone.push(...value.map((item) => cloneEditorCacheValue(item, seen)));
24
- return clone;
25
- }
26
- const clone = {};
27
- seen.set(value, clone);
28
- for (const [key, item] of Object.entries(value)) {
29
- clone[key] = cloneEditorCacheValue(item, seen);
30
- }
31
- return clone;
32
- }
33
10
  export function cloneLLMChatV2EditorCacheOutputs(outputs) {
34
- if (typeof structuredClone === 'function') {
35
- try {
36
- return structuredClone(outputs);
37
- }
38
- catch {
39
- // Fall through to the small object/array clone for values structuredClone cannot copy.
40
- }
41
- }
42
- return cloneEditorCacheValue(outputs);
11
+ return cloneLLMChatV2Outputs(outputs);
43
12
  }
44
13
  function fingerprintSecret(secret) {
45
14
  if (!secret) {
@@ -160,6 +160,7 @@ export async function resolveLLMChatV2RuntimeConfig(params) {
160
160
  return {
161
161
  provider: parseChatV2Provider(profile.configuration.provider),
162
162
  model: profile.configuration.model,
163
+ ...(profile.profileName == null ? {} : { profileName: profile.profileName }),
163
164
  ...(profile.configuration.provider === 'custom'
164
165
  ? { customProviderApi: parseCustomProviderApi(profile.configuration.customProviderApi) }
165
166
  : {}),
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Copies displayed LLM Chat outputs at an ownership boundary. Provider and
3
+ * continuation code intentionally continues to accumulate messages, usage,
4
+ * reasoning, and direct results after intermediate rounds complete; historical
5
+ * pages must therefore never retain those mutable references.
6
+ */
7
+ function cloneOutputValue(value, seen = new WeakMap()) {
8
+ if (value == null || typeof value !== 'object') {
9
+ return value;
10
+ }
11
+ if (value instanceof Uint8Array) {
12
+ return new Uint8Array(value);
13
+ }
14
+ const existing = seen.get(value);
15
+ if (existing != null) {
16
+ return existing;
17
+ }
18
+ if (Array.isArray(value)) {
19
+ const clone = [];
20
+ seen.set(value, clone);
21
+ clone.push(...value.map((item) => cloneOutputValue(item, seen)));
22
+ return clone;
23
+ }
24
+ const clone = {};
25
+ seen.set(value, clone);
26
+ for (const [key, item] of Object.entries(value)) {
27
+ clone[key] = cloneOutputValue(item, seen);
28
+ }
29
+ return clone;
30
+ }
31
+ /** Cycle-safe clone shared by the editor cache and LLM logical-round snapshots. */
32
+ export function cloneLLMChatV2Outputs(outputs) {
33
+ if (typeof structuredClone === 'function') {
34
+ try {
35
+ return structuredClone(outputs);
36
+ }
37
+ catch {
38
+ // Fall through for values structuredClone cannot copy.
39
+ }
40
+ }
41
+ return cloneOutputValue(outputs);
42
+ }
@@ -1,5 +1,5 @@
1
1
  import { delegateToolCall } from '../nodes/toolCallDelegation.js';
2
- import { runChatV2PipelineWithToolContinuation } from './toolContinuation.js';
2
+ import { runChatV2PipelineWithToolContinuation, } from './toolContinuation.js';
3
3
  import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
4
4
  /**
5
5
  * Owns the LLM-level recovery and continuation decision boundary. The node
@@ -9,6 +9,7 @@ import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
9
9
  export async function executeLLMInvocation(params) {
10
10
  const { context, journal, runtime, toolCallContinuation } = params;
11
11
  try {
12
+ let terminalSnapshot;
12
13
  const result = runtime.shouldAutoContinueToolCalls
13
14
  ? await runChatV2PipelineWithToolContinuation({
14
15
  ...runtime.runOptions,
@@ -42,8 +43,36 @@ export async function executeLLMInvocation(params) {
42
43
  };
43
44
  },
44
45
  runPipeline: runtime.runPipeline,
46
+ onCompletedModelRound: (snapshot) => {
47
+ try {
48
+ const observerResult = context.onLLMChatOutputSnapshot?.({
49
+ ...snapshot,
50
+ nodeId: context.node.id,
51
+ processId: context.processId,
52
+ splitIndex: context.splitIndex ?? 0,
53
+ });
54
+ // GraphProcessor already isolates its own observer. Preserve the
55
+ // same guarantee for direct node callers that provide an async
56
+ // observer themselves.
57
+ void Promise.resolve(observerResult).catch(() => undefined);
58
+ }
59
+ catch {
60
+ // History is observational; snapshot delivery cannot affect a graph run.
61
+ }
62
+ },
63
+ onTerminalRound: (snapshot) => {
64
+ terminalSnapshot = snapshot;
65
+ },
45
66
  })
46
67
  : await runtime.runPipeline(runtime.runOptions);
68
+ if (!runtime.shouldAutoContinueToolCalls && !isChatV2PipelineProviderFailureResult(result)) {
69
+ terminalSnapshot = {
70
+ entryId: 'model-round:0',
71
+ roundIndex: 0,
72
+ kind: 'model-round',
73
+ outcome: result.functionCalls.length > 0 ? 'unresolved-tool-calls' : 'final-answer',
74
+ };
75
+ }
47
76
  journal.recordTerminal({
48
77
  kind: isChatV2PipelineProviderFailureResult(result)
49
78
  ? 'failed'
@@ -51,7 +80,7 @@ export async function executeLLMInvocation(params) {
51
80
  ? 'released-unresolved-calls'
52
81
  : 'final-model-answer',
53
82
  });
54
- return result;
83
+ return { result, terminalSnapshot };
55
84
  }
56
85
  catch (error) {
57
86
  journal.recordTerminal({ kind: context.signal.aborted ? 'cancelled' : 'failed' });
@@ -38,14 +38,17 @@ export function normalizeLLMProfileValue(value) {
38
38
  model: model.trim(),
39
39
  });
40
40
  const sourceIdentity = normalizeSourceIdentity(value.healthIdentity);
41
+ const profileName = normalizeProfileName(value.profileName) ?? sourceIdentity.profileName;
41
42
  return {
42
43
  version: LLM_PROFILE_VALUE_VERSION,
43
44
  configuration,
44
45
  credential,
46
+ ...(profileName == null ? {} : { profileName }),
45
47
  healthIdentity: createRivetLLMProfileHealthIdentity({
46
48
  configuration,
47
49
  credential,
48
50
  ...sourceIdentity,
51
+ ...(profileName == null ? {} : { profileName }),
49
52
  }),
50
53
  };
51
54
  }
@@ -79,18 +82,23 @@ export function normalizeLLMProfileChainInput(value) {
79
82
  */
80
83
  export function scopeLLMProfileHealthIdentity(profile, fallback) {
81
84
  const profileNodeId = profile.healthIdentity?.profileNodeId ?? fallback.profileNodeId;
85
+ const profileName = normalizeProfileName(profile.profileName) ?? normalizeProfileName(profile.healthIdentity?.profileName);
82
86
  const healthIdentity = createRivetLLMProfileHealthIdentity({
83
87
  configuration: profile.configuration,
84
88
  credential: profile.credential,
85
89
  chatNodeHeaders: fallback.chatNodeHeaders,
86
90
  projectId: fallback.projectId,
87
91
  profileNodeId,
92
+ ...(profileName == null ? {} : { profileName }),
88
93
  });
89
- if (profile.healthIdentity?.key === healthIdentity.key) {
94
+ if (profile.healthIdentity?.key === healthIdentity.key &&
95
+ profile.profileName === profileName &&
96
+ profile.healthIdentity?.profileName === profileName) {
90
97
  return profile;
91
98
  }
92
99
  return {
93
100
  ...profile,
101
+ ...(profileName == null ? {} : { profileName }),
94
102
  healthIdentity,
95
103
  };
96
104
  }
@@ -189,11 +197,19 @@ function normalizeSourceIdentity(value) {
189
197
  if (!isRecord(value)) {
190
198
  return {};
191
199
  }
200
+ const profileName = normalizeProfileName(value.profileName);
192
201
  return {
193
202
  ...(typeof value.projectId === 'string' ? { projectId: value.projectId } : {}),
194
203
  ...(typeof value.profileNodeId === 'string' ? { profileNodeId: value.profileNodeId } : {}),
204
+ ...(profileName == null ? {} : { profileName }),
195
205
  };
196
206
  }
207
+ function normalizeProfileName(value) {
208
+ if (typeof value !== 'string')
209
+ return undefined;
210
+ const normalized = value.trim();
211
+ return normalized === '' ? undefined : normalized;
212
+ }
197
213
  function isRecord(value) {
198
214
  return typeof value === 'object' && value != null && !Array.isArray(value);
199
215
  }
@@ -87,6 +87,11 @@ export function getLLMAttemptErrorMessage(error) {
87
87
  return 'Provider request failed with unreadable error metadata.';
88
88
  }
89
89
  }
90
+ function formatCandidateProfileIdentity(candidate, profileIndex) {
91
+ const profileName = candidate.profileName?.trim();
92
+ const identity = formatCandidateIdentity(candidate);
93
+ return profileName ? `${profileName} (profile ${profileIndex + 1}; ${identity})` : `Profile ${profileIndex + 1} (${identity})`;
94
+ }
90
95
  function buildExhaustedMessage(attempts) {
91
96
  const details = attempts
92
97
  .map((attempt) => {
@@ -101,7 +106,7 @@ function buildExhaustedMessage(attempts) {
101
106
  : 'configuration';
102
107
  const status = attempt.status == null ? '' : ` (${attempt.status})`;
103
108
  const error = attempt.error ? `: ${attempt.error.replace(/\r\n|\r|\n/g, '\n ')}` : '';
104
- return `Profile ${attempt.profileIndex} (${formatCandidateIdentity(attempt)}), round ${attempt.roundIndex}, ${stage} ${attempt.outcome}${status}${error}`;
109
+ return `${formatCandidateProfileIdentity(attempt, attempt.profileIndex ?? 0)}, round ${attempt.roundIndex + 1}, ${stage} ${attempt.outcome}${status}${error}`;
105
110
  })
106
111
  .join('\n');
107
112
  return details
@@ -120,7 +125,7 @@ export function buildLLMProfileFallbackSummary(candidates, attempts) {
120
125
  return candidates
121
126
  .map((candidate, profileIndex) => {
122
127
  const profileAttempts = attempts.filter((attempt) => attempt.profileIndex === profileIndex);
123
- const identity = `Profile ${profileIndex} (${formatCandidateIdentity(candidate)})`;
128
+ const identity = formatCandidateProfileIdentity(candidate, profileIndex);
124
129
  if (profileAttempts.length === 0) {
125
130
  return `${identity}: not attempted.`;
126
131
  }
@@ -253,7 +258,7 @@ export function isUnhealthyLLMProfileProviderFailure(error) {
253
258
  return status === 408 || status === 429 || (status != null && status >= 500);
254
259
  }
255
260
  function createHealthPermit(params) {
256
- const { candidate, healthStore, permitId, state, roundIndex, profileIndex, operationTimeoutMs, signal, recordAttempt, } = params;
261
+ const { candidate, healthStore, permitId, state, roundIndex, profileIndex, operationTimeoutMs, executionCorrelationId, signal, recordAttempt, } = params;
257
262
  let finished = false;
258
263
  let renewalInFlight = false;
259
264
  let lastRenewalAt = 0;
@@ -341,6 +346,7 @@ function createHealthPermit(params) {
341
346
  policy: candidate.health.policy,
342
347
  permitId,
343
348
  outcome,
349
+ ...(executionCorrelationId == null ? {} : { executionCorrelationId }),
344
350
  }),
345
351
  });
346
352
  recordAttempt({
@@ -381,9 +387,13 @@ function throwIfAborted(signal) {
381
387
  export function createLLMProfileFallbackRunner(params) {
382
388
  const attempts = [];
383
389
  const recordAttempt = (attempt) => {
384
- attempts.push(attempt);
390
+ const candidate = attempt.profileIndex == null ? undefined : params.candidates[attempt.profileIndex];
391
+ const completedAttempt = attempt.profileName == null && candidate?.profileName != null
392
+ ? { ...attempt, profileName: candidate.profileName }
393
+ : attempt;
394
+ attempts.push(completedAttempt);
385
395
  try {
386
- params.onAttempt?.(attempt);
396
+ params.onAttempt?.(completedAttempt);
387
397
  }
388
398
  catch {
389
399
  // Diagnostics must not alter profile recovery.
@@ -473,6 +483,7 @@ export function createLLMProfileFallbackRunner(params) {
473
483
  roundIndex,
474
484
  profileIndex,
475
485
  operationTimeoutMs: healthOperationTimeoutMs,
486
+ executionCorrelationId: roundOptions.context.llmProfileHealthExecutionCorrelationId,
476
487
  signal: roundOptions.context.signal,
477
488
  recordAttempt,
478
489
  });
@@ -540,6 +551,7 @@ export function createLLMProfileFallbackRunner(params) {
540
551
  ...candidateOptions,
541
552
  profileIndex,
542
553
  roundIndex,
554
+ ...(candidate.profileName == null ? {} : { profileName: candidate.profileName }),
543
555
  ...(activeHealth == null
544
556
  ? {}
545
557
  : {
@@ -43,6 +43,7 @@ function sha256(value) {
43
43
  return `sha256:${CryptoJS.SHA256(value).toString(CryptoJS.enc.Hex)}`;
44
44
  }
45
45
  export function createRivetLLMProfileHealthIdentity(params) {
46
+ const profileName = params.profileName?.trim();
46
47
  // Circuit health belongs to the physical provider route and credentials,
47
48
  // not to generation policy. A temperature/cooldown edit must not silently
48
49
  // create a fresh circuit, while changing the model, endpoint, auth, or
@@ -75,6 +76,7 @@ export function createRivetLLMProfileHealthIdentity(params) {
75
76
  key: `llm-profile:${key}`,
76
77
  ...(params.projectId == null ? {} : { projectId: params.projectId }),
77
78
  ...(params.profileNodeId == null ? {} : { profileNodeId: params.profileNodeId }),
79
+ ...(profileName === '' || profileName == null ? {} : { profileName }),
78
80
  provider: params.configuration.provider,
79
81
  model: params.configuration.model,
80
82
  ...(params.configuration.provider !== 'custom'
@@ -76,10 +76,13 @@ export function resolveLLMProfileNodeValue(params) {
76
76
  // project-scoped, so defer attaching it until LLM Chat binds the profile to
77
77
  // the executing project in that case.
78
78
  const projectId = context.project?.metadata?.id;
79
+ const profileTitle = context.node?.title;
80
+ const profileName = typeof profileTitle === 'string' ? profileTitle.trim() : '';
79
81
  return {
80
82
  version: LLM_PROFILE_VALUE_VERSION,
81
83
  credential,
82
84
  configuration,
85
+ ...(profileName === '' ? {} : { profileName }),
83
86
  ...(projectId == null
84
87
  ? {}
85
88
  : {
@@ -89,6 +92,7 @@ export function resolveLLMProfileNodeValue(params) {
89
92
  chatNodeHeaders: context.settings.chatNodeHeaders,
90
93
  projectId,
91
94
  profileNodeId: context.node.id,
95
+ ...(profileName === '' ? {} : { profileName }),
92
96
  }),
93
97
  }),
94
98
  };
@@ -3,6 +3,7 @@ import { materializeLLMResponse } from './llmResponseMaterializer.js';
3
3
  import { createCallbackToolRoundExecutor } from './toolRoundExecutor.js';
4
4
  import { decideLLMInvocationRound } from './llmInvocationDecision.js';
5
5
  import { isChatV2PipelineProviderFailureResult } from './chatV2Pipeline.js';
6
+ import { cloneLLMChatV2Outputs } from './llmChatV2OutputClone.js';
6
7
  function shouldReturnToolResultDirectly(functionCalls, registry) {
7
8
  if (functionCalls.length !== 1) {
8
9
  return false;
@@ -74,7 +75,7 @@ function applyTerminalContinuationOutputs(result, delegatedToolCalls, accumulate
74
75
  }
75
76
  }
76
77
  export async function runChatV2PipelineWithToolContinuation(options) {
77
- const { autoContinue, maxToolRounds, functions, delegateToolCall, delegateToolCallRound, runPipeline, ...pipelineOptions } = options;
78
+ const { autoContinue, maxToolRounds, functions, delegateToolCall, delegateToolCallRound, onCompletedModelRound, onTerminalRound, runPipeline, ...pipelineOptions } = options;
78
79
  const toolRegistry = createRivetToolRegistry(functions);
79
80
  const toolRoundExecutor = createCallbackToolRoundExecutor({
80
81
  delegateOne: delegateToolCall,
@@ -127,8 +128,27 @@ export async function runChatV2PipelineWithToolContinuation(options) {
127
128
  outputReasoning: pipelineOptions.outputReasoning,
128
129
  includeFunctionCalls: pipelineOptions.includeFunctionCalls,
129
130
  });
131
+ onTerminalRound?.({
132
+ entryId: `model-round:${completedRounds}`,
133
+ roundIndex: completedRounds,
134
+ kind: 'model-round',
135
+ outcome: decision.kind === 'final-model-answer'
136
+ ? 'final-answer'
137
+ : decision.kind === 'release-unresolved-calls'
138
+ ? 'unresolved-tool-calls'
139
+ : 'max-rounds',
140
+ });
130
141
  return result;
131
142
  }
143
+ // Snapshot before delegate execution: subsequent rounds accumulate tool
144
+ // messages, usage, and reasoning that must not mutate this page.
145
+ onCompletedModelRound?.({
146
+ entryId: `model-round:${completedRounds}`,
147
+ roundIndex: completedRounds,
148
+ kind: 'model-round',
149
+ outcome: 'tool-calls',
150
+ outputs: cloneLLMChatV2Outputs(result.commonOutputs),
151
+ });
132
152
  const toolResultMessages = await toolRoundExecutor.executeRound({
133
153
  calls: result.functionCalls,
134
154
  assistantMessage: result.response,
@@ -170,6 +190,12 @@ export async function runChatV2PipelineWithToolContinuation(options) {
170
190
  }
171
191
  applyAccumulatedUsage(result, accumulatedUsage, pipelineOptions.outputUsage);
172
192
  applyAccumulatedReasoning(result, reasoningRounds, pipelineOptions.outputReasoning);
193
+ onTerminalRound?.({
194
+ entryId: `direct-tool-result:${completedRounds}`,
195
+ roundIndex: completedRounds,
196
+ kind: 'direct-tool-result',
197
+ outcome: 'direct-tool-result',
198
+ });
173
199
  return result;
174
200
  }
175
201
  currentPrompt = {