@valerypopoff/rivet2-core 2.1.10 → 2.4.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 (111) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +2604 -949
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +1549 -99
  5. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  6. package/dist/esm/api/createProcessor.js +4 -0
  7. package/dist/esm/exports.js +2 -0
  8. package/dist/esm/integrations/CodeRunner.js +2 -7
  9. package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
  10. package/dist/esm/model/AgentResponseTrace.js +137 -11
  11. package/dist/esm/model/GraphProcessor.js +28 -0
  12. package/dist/esm/model/NodeExclusionPolicy.js +9 -1
  13. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  14. package/dist/esm/model/RecordingPlayer.js +58 -5
  15. package/dist/esm/model/SubprocessorBridge.js +2 -0
  16. package/dist/esm/model/UiGraphActionProtocol.js +47 -4
  17. package/dist/esm/model/UiGraphBrowserRuntime.js +15 -1
  18. package/dist/esm/model/UiGraphIndexedDbPersistence.js +523 -0
  19. package/dist/esm/model/UiGraphRendererStyles.js +14 -0
  20. package/dist/esm/model/WebAppBrowserStorage.js +653 -0
  21. package/dist/esm/model/WebAppBrowserStorageRpc.js +200 -0
  22. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  23. package/dist/esm/model/chat-v2/chatV2CallObserver.js +3 -0
  24. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  25. package/dist/esm/model/chat-v2/chatV2EditorCache.js +8 -38
  26. package/dist/esm/model/chat-v2/chatV2Pipeline.js +41 -4
  27. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +31 -2
  28. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +10 -2
  29. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -11
  30. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  31. package/dist/esm/model/chat-v2/chatV2Types.js +16 -0
  32. package/dist/esm/model/chat-v2/customProviderApi.js +0 -2
  33. package/dist/esm/model/chat-v2/index.js +3 -0
  34. package/dist/esm/model/chat-v2/llmChatV2Body.js +9 -1
  35. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +5 -0
  36. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +7 -0
  37. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +95 -14
  38. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +33 -9
  39. package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +42 -0
  40. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +31 -2
  41. package/dist/esm/model/chat-v2/llmModelCandidate.js +5 -1
  42. package/dist/esm/model/chat-v2/llmProfile.js +58 -0
  43. package/dist/esm/model/chat-v2/llmProfileBody.js +10 -0
  44. package/dist/esm/model/chat-v2/llmProfileFallback.js +406 -8
  45. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +7 -0
  46. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +328 -0
  47. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +57 -34
  48. package/dist/esm/model/chat-v2/providerOptions.js +33 -7
  49. package/dist/esm/model/chat-v2/toolContinuation.js +27 -1
  50. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  51. package/dist/esm/model/nodes/CodeNode.js +4 -46
  52. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  53. package/dist/esm/model/nodes/LLMChatV2Node.js +31 -3
  54. package/dist/esm/model/nodes/MatchNode.js +86 -41
  55. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  56. package/dist/esm/plugins/gentrace/index.js +0 -1
  57. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  58. package/dist/esm/plugins.js +1 -2
  59. package/dist/esm/recording/ExecutionRecorder.js +50 -8
  60. package/dist/esm/webAppRuntime.js +5 -2
  61. package/dist/types/api/createProcessor.d.ts +5 -0
  62. package/dist/types/exports.d.ts +2 -0
  63. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  64. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  65. package/dist/types/model/AgentResponseTrace.d.ts +15 -1
  66. package/dist/types/model/EditorDefinition.d.ts +16 -0
  67. package/dist/types/model/ExecutorProtocol.d.ts +17 -6
  68. package/dist/types/model/GraphProcessor.d.ts +17 -5
  69. package/dist/types/model/NodeBase.d.ts +0 -10
  70. package/dist/types/model/NodeExclusionPolicy.d.ts +6 -0
  71. package/dist/types/model/Nodes.d.ts +2 -2
  72. package/dist/types/model/ProcessContext.d.ts +85 -0
  73. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  74. package/dist/types/model/UiGraphActionProtocol.d.ts +9 -3
  75. package/dist/types/model/UiGraphBrowserRuntime.d.ts +6 -0
  76. package/dist/types/model/UiGraphIndexedDbPersistence.d.ts +50 -0
  77. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  78. package/dist/types/model/WebAppBrowserStorage.d.ts +90 -0
  79. package/dist/types/model/WebAppBrowserStorageRpc.d.ts +85 -0
  80. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  81. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -0
  82. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +3 -0
  83. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +8 -2
  84. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  85. package/dist/types/model/chat-v2/chatV2Types.d.ts +27 -1
  86. package/dist/types/model/chat-v2/customProviderApi.d.ts +0 -1
  87. package/dist/types/model/chat-v2/index.d.ts +3 -0
  88. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +1 -1
  89. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
  90. package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -0
  91. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +5 -1
  92. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +2 -0
  93. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  94. package/dist/types/model/chat-v2/llmProfileBody.d.ts +1 -1
  95. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +25 -2
  96. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +26 -6
  97. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +121 -0
  98. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  99. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +9 -0
  100. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -0
  101. package/dist/types/model/chat-v2/toolContinuation.d.ts +14 -0
  102. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  103. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  104. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  105. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  106. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  107. package/dist/types/plugins.d.ts +1 -1
  108. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  109. package/dist/types/recording/RecordedEvents.d.ts +11 -0
  110. package/dist/types/webAppRuntime.d.ts +8 -2
  111. package/package.json +2 -2
@@ -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
+ }
@@ -1,5 +1,6 @@
1
1
  import { generateText, NoObjectGeneratedError, streamText } from 'ai';
2
2
  import { consumeAiSdkStream } from '../chat/aiSdkStreaming.js';
3
+ import { ChatV2ProviderTimeoutError } from './chatV2Types.js';
3
4
  import { isChatV2StructuredResponseFormat } from './chatV2ResponseFormat.js';
4
5
  function keepPromiseHandled(value) {
5
6
  const promise = Promise.resolve(value);
@@ -153,6 +154,109 @@ function buildTextArgs(options) {
153
154
  args.abortSignal = options.abortSignal;
154
155
  return args;
155
156
  }
157
+ function isUsefulStreamPart(part) {
158
+ const event = part;
159
+ if (event?.type === 'tool-call')
160
+ return true;
161
+ if (event?.type === 'text-delta' || event?.type === 'reasoning-delta') {
162
+ return typeof event.text === 'string' && event.text.length > 0;
163
+ }
164
+ if (event?.type === 'tool-input-delta') {
165
+ return typeof event.delta === 'string' && event.delta.length > 0;
166
+ }
167
+ return false;
168
+ }
169
+ function timeoutPromise(timeoutMs, kind, onTimeout) {
170
+ let timer;
171
+ const promise = new Promise((_resolve, reject) => {
172
+ timer = setTimeout(() => {
173
+ const error = new ChatV2ProviderTimeoutError(kind, timeoutMs);
174
+ reject(error);
175
+ try {
176
+ onTimeout?.(error);
177
+ }
178
+ catch {
179
+ // Timeout notification is cleanup-only and cannot replace the deadline.
180
+ }
181
+ }, timeoutMs);
182
+ });
183
+ return {
184
+ promise,
185
+ cancel: () => {
186
+ if (timer != null)
187
+ clearTimeout(timer);
188
+ },
189
+ };
190
+ }
191
+ async function* streamWithDeadlines(stream, options, firstOutputStartedAt) {
192
+ const iterator = stream[Symbol.asyncIterator]();
193
+ let hasUsefulOutput = false;
194
+ let lastUsefulOutputAt = firstOutputStartedAt;
195
+ try {
196
+ for (;;) {
197
+ const kind = hasUsefulOutput ? 'stream-inactivity' : 'first-output';
198
+ const configuredTimeout = hasUsefulOutput ? options.streamInactivityTimeoutMs : options.firstOutputTimeoutMs;
199
+ const timeoutMs = configuredTimeout == null
200
+ ? undefined
201
+ : Math.max(1, configuredTimeout - (Date.now() - lastUsefulOutputAt));
202
+ const timeout = timeoutMs == null ? undefined : timeoutPromise(timeoutMs, kind, options.onTimeout);
203
+ let next;
204
+ try {
205
+ next = await (timeout == null ? iterator.next() : Promise.race([iterator.next(), timeout.promise]));
206
+ }
207
+ finally {
208
+ timeout?.cancel();
209
+ }
210
+ if (next.done)
211
+ return;
212
+ if (isUsefulStreamPart(next.value)) {
213
+ hasUsefulOutput = true;
214
+ lastUsefulOutputAt = Date.now();
215
+ try {
216
+ options.onStreamActivity?.();
217
+ }
218
+ catch {
219
+ // Health lease renewal is observational and cannot break the stream.
220
+ }
221
+ }
222
+ yield next.value;
223
+ }
224
+ }
225
+ finally {
226
+ try {
227
+ const cleanup = iterator.return?.();
228
+ if (cleanup != null) {
229
+ void Promise.resolve(cleanup).catch(() => undefined);
230
+ }
231
+ }
232
+ catch {
233
+ // The deadline/consumer error remains authoritative over iterator cleanup.
234
+ }
235
+ }
236
+ }
237
+ async function waitForGeneratedResponse(executorPromise, options) {
238
+ if (options.firstOutputTimeoutMs == null)
239
+ return await executorPromise;
240
+ const timeout = timeoutPromise(options.firstOutputTimeoutMs, 'first-output', options.onTimeout);
241
+ try {
242
+ return await Promise.race([executorPromise, timeout.promise]);
243
+ }
244
+ finally {
245
+ timeout.cancel();
246
+ }
247
+ }
248
+ async function waitForPostResponseFinalization(finalization, options) {
249
+ const timeoutMs = options.streamInactivityTimeoutMs ?? options.firstOutputTimeoutMs;
250
+ if (timeoutMs == null)
251
+ return await finalization;
252
+ const timeout = timeoutPromise(timeoutMs, options.streamInactivityTimeoutMs == null ? 'first-output' : 'stream-inactivity', options.onTimeout);
253
+ try {
254
+ return await Promise.race([finalization, timeout.promise]);
255
+ }
256
+ finally {
257
+ timeout.cancel();
258
+ }
259
+ }
156
260
  function toStreamedFunctionCalls(toolCalls) {
157
261
  return (toolCalls ?? []).map((toolCall) => ({
158
262
  type: 'function',
@@ -171,14 +275,25 @@ async function resolveGenerateReasoning(result) {
171
275
  }
172
276
  async function executeStream(options, executor) {
173
277
  const args = buildTextArgs(options);
174
- const handle = await executor(args);
278
+ const firstOutputStartedAt = Date.now();
279
+ const handlePromise = Promise.resolve(executor(args));
280
+ const handleTimeout = options.firstOutputTimeoutMs == null
281
+ ? undefined
282
+ : timeoutPromise(options.firstOutputTimeoutMs, 'first-output', options.onTimeout);
283
+ let handle;
284
+ try {
285
+ handle = await (handleTimeout == null ? handlePromise : Promise.race([handlePromise, handleTimeout.promise]));
286
+ }
287
+ finally {
288
+ handleTimeout?.cancel();
289
+ }
175
290
  markOptionalPromiseHandled(handle.finishReason);
176
291
  markOptionalPromiseHandled(handle.output);
177
292
  markOptionalPromiseHandled(handle.providerMetadata);
178
293
  markOptionalPromiseHandled(handle.requestStatus);
179
294
  markOptionalPromiseHandled(handle.usage);
180
295
  const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
181
- const streamed = await consumeAiSdkStream(handle.fullStream, (text, functionCalls) => {
296
+ const streamed = await consumeAiSdkStream(streamWithDeadlines(handle.fullStream, options, firstOutputStartedAt), (text, functionCalls) => {
182
297
  options.onPartialOutput?.({
183
298
  text: isStructuredOutput ? collapseRepeatedStructuredJsonText(text) : text,
184
299
  functionCalls,
@@ -189,15 +304,22 @@ async function executeStream(options, executor) {
189
304
  const responseText = isStructuredOutput
190
305
  ? collapseRepeatedStructuredJsonText(streamed.responseText)
191
306
  : streamed.responseText;
307
+ const [structuredOutput, usage, finishReason, providerMetadata, requestStatus] = await waitForPostResponseFinalization(Promise.all([
308
+ options.responseOutput != null ? resolveOptionalStructuredOutput(handle.output) : undefined,
309
+ streamed.usage != null ? streamed.usage : resolveOptionalValue(handle.usage),
310
+ resolveOptionalValue(handle.finishReason),
311
+ resolveOptionalValue(handle.providerMetadata),
312
+ resolveOptionalValue(handle.requestStatus),
313
+ ]), options);
192
314
  return {
193
315
  responseText,
194
- structuredOutput: options.responseOutput != null ? await resolveOptionalStructuredOutput(handle.output) : undefined,
316
+ structuredOutput,
195
317
  functionCalls: streamed.functionCalls,
196
- usage: streamed.usage ?? (await resolveOptionalValue(handle.usage)),
318
+ usage,
197
319
  reasoning: streamed.reasoning,
198
- finishReason: await resolveOptionalValue(handle.finishReason),
199
- providerMetadata: await resolveOptionalValue(handle.providerMetadata),
200
- requestStatus: await resolveOptionalValue(handle.requestStatus),
320
+ finishReason,
321
+ providerMetadata,
322
+ requestStatus,
201
323
  };
202
324
  }
203
325
  export async function streamChatV2(options) {
@@ -208,7 +330,7 @@ export async function generateChatV2(options) {
208
330
  const stepToolCalls = attachGenerateStepToolCallCollector(args);
209
331
  let result;
210
332
  try {
211
- result = await (options.executeGenerate ?? defaultGenerateExecutor)(args);
333
+ result = await waitForGeneratedResponse(Promise.resolve((options.executeGenerate ?? defaultGenerateExecutor)(args)), options);
212
334
  }
213
335
  catch (error) {
214
336
  const recovered = recoverGenerateStructuredOutputError(error, options, stepToolCalls);
@@ -219,15 +341,25 @@ export async function generateChatV2(options) {
219
341
  }
220
342
  const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
221
343
  const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(result.text) : result.text;
222
- const finishReason = await resolveOptionalValue(result.finishReason);
344
+ const [finishReason, structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await waitForPostResponseFinalization((async () => {
345
+ const finishReason = await resolveOptionalValue(result.finishReason);
346
+ const [structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await Promise.all([
347
+ resolveGenerateStructuredOutput(result, options.responseOutput, finishReason),
348
+ (async () => (await resolveOptionalValue(result.totalUsage)) ?? (await resolveOptionalValue(result.usage)))(),
349
+ resolveGenerateReasoning(result),
350
+ resolveOptionalValue(result.providerMetadata),
351
+ resolveOptionalValue(result.requestStatus),
352
+ ]);
353
+ return [finishReason, structuredOutput, usage, reasoning, providerMetadata, requestStatus];
354
+ })(), options);
223
355
  return {
224
356
  responseText,
225
- structuredOutput: await resolveGenerateStructuredOutput(result, options.responseOutput, finishReason),
357
+ structuredOutput,
226
358
  functionCalls: toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls),
227
- usage: (await resolveOptionalValue(result.totalUsage)) ?? (await resolveOptionalValue(result.usage)),
228
- reasoning: await resolveGenerateReasoning(result),
359
+ usage,
360
+ reasoning,
229
361
  finishReason,
230
- providerMetadata: await resolveOptionalValue(result.providerMetadata),
231
- requestStatus: await resolveOptionalValue(result.requestStatus),
362
+ providerMetadata,
363
+ requestStatus,
232
364
  };
233
365
  }
@@ -120,6 +120,9 @@ 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 }),
124
+ ...(options.profileHealthKey == null ? {} : { profileHealthKey: options.profileHealthKey }),
125
+ ...(options.profileHealthState == null ? {} : { profileHealthState: options.profileHealthState }),
123
126
  ...(options.roundIndex == null ? {} : { roundIndex: options.roundIndex }),
124
127
  nodeId,
125
128
  processId,
@@ -0,0 +1,93 @@
1
+ export const CHAT_V2_DEFAULT_CREDENTIAL_NAMES = {
2
+ openai: {
3
+ programmaticName: 'openAiApiKey',
4
+ environmentVariableName: 'OPENAI_API_KEY',
5
+ },
6
+ anthropic: {
7
+ programmaticName: 'anthropicApiKey',
8
+ environmentVariableName: 'ANTHROPIC_API_KEY',
9
+ },
10
+ google: {
11
+ programmaticName: 'googleApiKey',
12
+ environmentVariableName: 'GOOGLE_GENERATIVE_AI_API_KEY',
13
+ },
14
+ };
15
+ const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
16
+ const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
17
+ export function isChatV2BuiltInProvider(provider) {
18
+ return Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider);
19
+ }
20
+ export function isValidChatV2ProgrammaticCredentialName(name) {
21
+ return programmaticNamePattern.test(name);
22
+ }
23
+ export function isValidChatV2EnvironmentCredentialName(name) {
24
+ return environmentVariableNamePattern.test(name);
25
+ }
26
+ export function getChatV2DefaultCredentialNames(provider) {
27
+ return { ...CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider] };
28
+ }
29
+ export function getChatV2CredentialNamesForDisplay(provider, value) {
30
+ try {
31
+ return normalizeChatV2CredentialNames(provider, value);
32
+ }
33
+ catch {
34
+ return getChatV2DefaultCredentialNames(provider);
35
+ }
36
+ }
37
+ export function normalizeChatV2CredentialNames(provider, value) {
38
+ if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
39
+ throw new Error(`${provider} API key names must be an object.`);
40
+ }
41
+ const raw = value;
42
+ if (raw?.programmaticName != null && typeof raw.programmaticName !== 'string') {
43
+ throw new Error(`${provider} programmatic API key name must be a string.`);
44
+ }
45
+ if (raw?.environmentVariableName != null && typeof raw.environmentVariableName !== 'string') {
46
+ throw new Error(`${provider} API key environment variable must be a string.`);
47
+ }
48
+ const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];
49
+ const programmaticName = raw?.programmaticName?.trim() || defaults.programmaticName;
50
+ const environmentVariableName = raw?.environmentVariableName?.trim() || defaults.environmentVariableName;
51
+ if (!isValidChatV2ProgrammaticCredentialName(programmaticName)) {
52
+ throw new Error(`${provider} programmatic API key name must be a JavaScript-style identifier (letters, digits, _, or $, and not starting with a digit).`);
53
+ }
54
+ if (!isValidChatV2EnvironmentCredentialName(environmentVariableName)) {
55
+ throw new Error(`${provider} API key environment variable must contain only letters, digits, and _, and must not start with a digit.`);
56
+ }
57
+ return { programmaticName, environmentVariableName };
58
+ }
59
+ export function normalizeChatV2CredentialNamesByProvider(value) {
60
+ if (value == null)
61
+ return undefined;
62
+ if (typeof value !== 'object' || Array.isArray(value)) {
63
+ throw new Error('Built-in provider API key names must be an object.');
64
+ }
65
+ const raw = value;
66
+ const unsupportedProvider = Object.keys(raw).find((provider) => !Object.hasOwn(CHAT_V2_DEFAULT_CREDENTIAL_NAMES, provider));
67
+ if (unsupportedProvider) {
68
+ throw new Error(`Unsupported provider API key names entry: ${unsupportedProvider}.`);
69
+ }
70
+ const normalized = {};
71
+ for (const provider of ['openai', 'anthropic', 'google']) {
72
+ if (raw[provider] != null) {
73
+ normalized[provider] = normalizeChatV2CredentialNames(provider, raw[provider]);
74
+ }
75
+ }
76
+ return Object.keys(normalized).length === 0 ? undefined : normalized;
77
+ }
78
+ export function isDefaultChatV2CredentialNames(provider, names) {
79
+ const defaults = CHAT_V2_DEFAULT_CREDENTIAL_NAMES[provider];
80
+ return (names.programmaticName === defaults.programmaticName &&
81
+ names.environmentVariableName === defaults.environmentVariableName);
82
+ }
83
+ export function getNonDefaultChatV2CredentialNames(provider, namesByProvider) {
84
+ if (!isChatV2BuiltInProvider(provider) || namesByProvider?.[provider] == null)
85
+ return undefined;
86
+ try {
87
+ const names = normalizeChatV2CredentialNames(provider, namesByProvider[provider]);
88
+ return isDefaultChatV2CredentialNames(provider, names) ? undefined : names;
89
+ }
90
+ catch {
91
+ return undefined;
92
+ }
93
+ }
@@ -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
- const { cacheVersion = 2, ...keyParts } = parts;
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) {
@@ -103,11 +72,11 @@ function fingerprintNodeDataForCache(data) {
103
72
  })),
104
73
  };
105
74
  }
106
- function fingerprintProviderOptionsForCache(providerOptions) {
107
- if (providerOptions == null) {
75
+ function fingerprintRuntimeValueForCache(value) {
76
+ if (value == null) {
108
77
  return undefined;
109
78
  }
110
- return fingerprintSecret(stableStringify(providerOptions) ?? '');
79
+ return fingerprintSecret(stableStringify(value) ?? '');
111
80
  }
112
81
  function fingerprintProfileChainForCache(data, profiles) {
113
82
  if (profiles == null) {
@@ -142,7 +111,8 @@ export function resolveLLMChatV2EditorCache(params) {
142
111
  functions: params.functions,
143
112
  generationParameters: params.generationParameters,
144
113
  responseFormatParameters: params.responseFormatParameters,
145
- providerOptions: fingerprintProviderOptionsForCache(params.providerOptions),
114
+ providerOptions: fingerprintRuntimeValueForCache(params.providerOptions),
115
+ requestBodyOverlay: fingerprintRuntimeValueForCache(params.requestBodyOverlay),
146
116
  toolChoice: params.toolChoice,
147
117
  profileChain: params.profileChain == null ? undefined : fingerprintProfileChainForCache(params.data, params.profileChain),
148
118
  });
@@ -2,6 +2,7 @@ import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMes
2
2
  import { generateChatV2, streamChatV2 } from './aiSdkBridge.js';
3
3
  import { createObservedChatV2CallId, notifyChatV2CallFinished } from './chatV2CallObserver.js';
4
4
  import { chatMessagesToModelMessages } from './messageConverter.js';
5
+ import { isChatV2ProviderTimeoutError } from './chatV2Types.js';
5
6
  import { chatV2ToolsToAiSdk } from './toolConverter.js';
6
7
  import { buildChatV2RequestPlan } from './chatV2RequestPlan.js';
7
8
  import { getChatV2ProviderErrorStatusCode, normalizeChatV2ProviderError, } from './chatV2Errors.js';
@@ -54,12 +55,38 @@ function notifyProviderAttempt(options, attempt) {
54
55
  }
55
56
  }
56
57
  async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, transportMode) {
58
+ const prepareProviderRetry = async () => {
59
+ try {
60
+ await options.onBeforeProviderRetry?.(retryPlan.cooldownMs);
61
+ }
62
+ catch {
63
+ // Circuit-health persistence is observational and must fail open.
64
+ }
65
+ };
57
66
  for (let attempt = 0;; attempt++) {
58
67
  const callId = createObservedChatV2CallId(options);
59
68
  const callStartedAt = Date.now();
60
69
  let callWasObserved = false;
70
+ const attemptController = new AbortController();
71
+ const abortAttemptFromCaller = () => attemptController.abort(signal.reason);
72
+ if (signal.aborted) {
73
+ abortAttemptFromCaller();
74
+ }
75
+ else {
76
+ signal.addEventListener('abort', abortAttemptFromCaller, { once: true });
77
+ }
61
78
  try {
62
- const result = transportMode === 'generate' ? await generateChatV2(chatOptions) : await streamChatV2(chatOptions);
79
+ const attemptChatOptions = {
80
+ ...chatOptions,
81
+ abortSignal: attemptController.signal,
82
+ firstOutputTimeoutMs: options.firstOutputTimeoutMs,
83
+ streamInactivityTimeoutMs: options.streamInactivityTimeoutMs,
84
+ onStreamActivity: options.onStreamActivity,
85
+ onTimeout: (error) => attemptController.abort(error),
86
+ };
87
+ const result = transportMode === 'generate'
88
+ ? await generateChatV2(attemptChatOptions)
89
+ : await streamChatV2(attemptChatOptions);
63
90
  await options.responseBodyCapture?.flush();
64
91
  const statusCode = result.requestStatus ?? 200;
65
92
  notifyChatV2CallFinished(options, {
@@ -84,10 +111,16 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
84
111
  if (attempt >= retryPlan.repeatTimes) {
85
112
  return { result, responseError };
86
113
  }
114
+ await prepareProviderRetry();
87
115
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
88
116
  }
89
- catch (error) {
90
- await options.responseBodyCapture?.flush();
117
+ catch (caughtError) {
118
+ const error = !signal.aborted && isChatV2ProviderTimeoutError(attemptController.signal.reason)
119
+ ? attemptController.signal.reason
120
+ : caughtError;
121
+ await options.responseBodyCapture?.flush({
122
+ waitForPending: !signal.aborted && !isChatV2ProviderTimeoutError(error),
123
+ });
91
124
  if (!callWasObserved) {
92
125
  notifyChatV2CallFinished(options, {
93
126
  callId,
@@ -111,14 +144,18 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
111
144
  // provider failure to profile fallback and run activity.
112
145
  throw createLLMChatV2RetryAbortError();
113
146
  }
114
- if (!retryPlan.enabled || statusCode == null || statusCode === 200) {
147
+ if (isChatV2ProviderTimeoutError(error) || !retryPlan.enabled || statusCode == null || statusCode === 200) {
115
148
  throw error;
116
149
  }
117
150
  if (attempt >= retryPlan.repeatTimes) {
118
151
  throw error;
119
152
  }
153
+ await prepareProviderRetry();
120
154
  await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
121
155
  }
156
+ finally {
157
+ signal.removeEventListener('abort', abortAttemptFromCaller);
158
+ }
122
159
  }
123
160
  }
124
161
  /**