@valerypopoff/rivet2-core 2.1.7 → 2.1.9

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 (115) hide show
  1. package/dist/cjs/bundle.cjs +4911 -2546
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +45 -4
  4. package/dist/esm/exports.js +2 -0
  5. package/dist/esm/integrations/KnowledgeStoreFieldPolicy.js +216 -0
  6. package/dist/esm/integrations/KnowledgeStoreProvider.js +14 -90
  7. package/dist/esm/integrations/ManagedKnowledgeStore.js +0 -8
  8. package/dist/esm/model/DataBusPorts.js +26 -0
  9. package/dist/esm/model/DataBusTopology.js +207 -0
  10. package/dist/esm/model/DataValue.js +22 -7
  11. package/dist/esm/model/GraphPreprocessor.js +9 -3
  12. package/dist/esm/model/GraphProcessor.js +164 -366
  13. package/dist/esm/model/NodeIO.js +1 -0
  14. package/dist/esm/model/NodePrefabResolver.js +16 -0
  15. package/dist/esm/model/Nodes.js +7 -0
  16. package/dist/esm/model/SplitRunProcessor.js +19 -10
  17. package/dist/esm/model/ToolCallContinuationBranchPlanner.js +165 -0
  18. package/dist/esm/model/ToolCallContinuationCoordinator.js +206 -0
  19. package/dist/esm/model/chat/aiSdkMessages.js +8 -0
  20. package/dist/esm/model/chat-v2/chatV2CallObserver.js +142 -0
  21. package/dist/esm/model/chat-v2/chatV2EditorCache.js +22 -0
  22. package/dist/esm/model/chat-v2/chatV2Errors.js +23 -6
  23. package/dist/esm/model/chat-v2/chatV2Outputs.js +41 -31
  24. package/dist/esm/model/chat-v2/chatV2Pipeline.js +167 -56
  25. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +1 -0
  26. package/dist/esm/model/chat-v2/chatV2ProviderTypes.js +1 -0
  27. package/dist/esm/model/chat-v2/chatV2RequestPlan.js +6 -5
  28. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +2 -2
  29. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -6
  30. package/dist/esm/model/chat-v2/chatV2Types.js +11 -1
  31. package/dist/esm/model/chat-v2/developerMessageRoles.js +45 -0
  32. package/dist/esm/model/chat-v2/index.js +1 -0
  33. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +53 -3
  34. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +53 -19
  35. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +232 -68
  36. package/dist/esm/model/chat-v2/llmProfile.js +212 -0
  37. package/dist/esm/model/chat-v2/llmProfileFallback.js +288 -0
  38. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +73 -0
  39. package/dist/esm/model/chat-v2/llmProfileTypes.js +45 -0
  40. package/dist/esm/model/chat-v2/messageConverter.js +14 -0
  41. package/dist/esm/model/chat-v2/providerOptions.js +44 -11
  42. package/dist/esm/model/chat-v2/toolContinuation.js +0 -4
  43. package/dist/esm/model/nodes/AssembleMessageNode.js +6 -0
  44. package/dist/esm/model/nodes/DataBusNode.js +81 -0
  45. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -0
  46. package/dist/esm/model/nodes/GetGlobalNode.js +7 -11
  47. package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +1 -1
  48. package/dist/esm/model/nodes/LLMChatV2Node.js +156 -18
  49. package/dist/esm/model/nodes/LLMProfileNode.js +132 -0
  50. package/dist/esm/model/nodes/PassthroughNode.js +1 -11
  51. package/dist/esm/model/nodes/PromptNode.js +9 -2
  52. package/dist/esm/model/nodes/SearchKnowledgeNode.js +1 -1
  53. package/dist/esm/model/nodes/SetGlobalNode.js +6 -6
  54. package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +0 -1
  55. package/dist/esm/model/nodes/toolCallDelegation.js +31 -4
  56. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +22 -28
  57. package/dist/esm/plugins/google/google.js +20 -9
  58. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +17 -6
  59. package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +0 -4
  60. package/dist/esm/plugins/pinecone/plugin.js +1 -1
  61. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +4 -0
  62. package/dist/esm/utils/coerceType.js +84 -41
  63. package/dist/esm/utils/expectType.js +45 -8
  64. package/dist/esm/utils/fetchEventSource.js +18 -0
  65. package/dist/esm/utils/serialization/serialization.js +37 -7
  66. package/dist/esm/vendor/fnv1a.js +6 -3
  67. package/dist/types/api/createProcessor.d.ts +2 -0
  68. package/dist/types/exports.d.ts +2 -0
  69. package/dist/types/integrations/KnowledgeStore.d.ts +0 -2
  70. package/dist/types/integrations/KnowledgeStoreFieldPolicy.d.ts +38 -0
  71. package/dist/types/integrations/KnowledgeStoreProvider.d.ts +6 -3
  72. package/dist/types/model/DataBusPorts.d.ts +6 -0
  73. package/dist/types/model/DataBusTopology.d.ts +16 -0
  74. package/dist/types/model/DataValue.d.ts +22 -6
  75. package/dist/types/model/GraphPreprocessor.d.ts +2 -1
  76. package/dist/types/model/GraphProcessor.d.ts +4 -3
  77. package/dist/types/model/NodeBase.d.ts +6 -0
  78. package/dist/types/model/NodeIO.d.ts +5 -0
  79. package/dist/types/model/NodePrefabResolver.d.ts +9 -0
  80. package/dist/types/model/Nodes.d.ts +5 -2
  81. package/dist/types/model/ProcessContext.d.ts +64 -0
  82. package/dist/types/model/SplitRunProcessor.d.ts +2 -1
  83. package/dist/types/model/ToolCallContinuationBranchPlanner.d.ts +43 -0
  84. package/dist/types/model/ToolCallContinuationCoordinator.d.ts +70 -0
  85. package/dist/types/model/chat-v2/chatV2CallObserver.d.ts +10 -0
  86. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +4 -0
  87. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +5 -5
  88. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +33 -0
  89. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +1 -0
  90. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -0
  91. package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +2 -2
  92. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +8 -0
  93. package/dist/types/model/chat-v2/chatV2Shared.d.ts +0 -1
  94. package/dist/types/model/chat-v2/chatV2Types.d.ts +27 -3
  95. package/dist/types/model/chat-v2/developerMessageRoles.d.ts +10 -0
  96. package/dist/types/model/chat-v2/index.d.ts +1 -0
  97. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
  98. package/dist/types/model/chat-v2/llmChatV2NodeEditors.d.ts +5 -1
  99. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +18 -2
  100. package/dist/types/model/chat-v2/llmProfile.d.ts +10 -0
  101. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +79 -0
  102. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +9 -0
  103. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +18 -0
  104. package/dist/types/model/chat-v2/providerOptions.d.ts +1 -0
  105. package/dist/types/model/nodes/AssembleMessageNode.d.ts +2 -1
  106. package/dist/types/model/nodes/DataBusNode.d.ts +19 -0
  107. package/dist/types/model/nodes/LLMProfileNode.d.ts +20 -0
  108. package/dist/types/model/nodes/PassthroughNode.d.ts +2 -15
  109. package/dist/types/model/nodes/PromptNode.d.ts +2 -2
  110. package/dist/types/model/nodes/SetGlobalNode.d.ts +2 -2
  111. package/dist/types/model/nodes/toolCallDelegation.d.ts +9 -0
  112. package/dist/types/plugins/google/google.d.ts +12 -1
  113. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +2 -1
  114. package/dist/types/vendor/fnv1a.d.ts +5 -5
  115. package/package.json +1 -1
@@ -338,15 +338,16 @@ export const ChatAnthropicNodeImpl = {
338
338
  return acc;
339
339
  }, '');
340
340
  prompt += '\n\nAssistant:';
341
- // Get the "System" prompt input for Claude 3 models
342
- const system = data.model.startsWith('claude-3') ? getSystemPrompt(inputs) : undefined;
341
+ const useMessageApi = model.startsWith('claude-3') || model.startsWith('claude-sonnet') || model.startsWith('claude-opus');
342
+ const system = useMessageApi ? getSystemPrompt(inputs) : undefined;
343
343
  let { maxTokens } = data;
344
344
  const tokenizerInfo = {
345
345
  node: context.node,
346
346
  model,
347
347
  endpoint: undefined,
348
348
  };
349
- const tokenCountEstimate = await context.tokenizer.getTokenCountForString(prompt, tokenizerInfo);
349
+ const systemText = typeof system === 'string' ? system : system?.map((message) => message.text).join('\n\n');
350
+ const tokenCountEstimate = await context.tokenizer.getTokenCountForString([systemText, prompt].filter(Boolean).join('\n\n'), tokenizerInfo);
350
351
  const modelInfo = anthropicModels[model] ?? {
351
352
  maxTokens: Number.MAX_SAFE_INTEGER,
352
353
  cost: {
@@ -389,7 +390,6 @@ export const ChatAnthropicNodeImpl = {
389
390
  ? tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.parameters }))
390
391
  : undefined,
391
392
  };
392
- const useMessageApi = model.startsWith('claude-3') || model.startsWith('claude-sonnet') || model.startsWith('claude-opus');
393
393
  const cacheKey = JSON.stringify(useMessageApi ? messageOptions : completionOptions);
394
394
  if (data.cache) {
395
395
  const cached = cache.get(cacheKey);
@@ -618,34 +618,28 @@ export const chatAnthropicNode = pluginNodeDefinition(ChatAnthropicNodeImpl, 'Ch
618
618
  export function getSystemPrompt(inputs) {
619
619
  const systemInput = inputs['system'];
620
620
  const system = coerceTypeOptional(systemInput, 'string');
621
+ const systemMessages = [];
621
622
  if (system) {
622
- return [
623
- {
624
- type: 'text',
625
- text: system,
626
- cache_control: systemInput?.type === 'chat-message'
627
- ? systemInput.value.isCacheBreakpoint
628
- ? { type: 'ephemeral' }
629
- : null
630
- : null,
631
- },
632
- ];
623
+ systemMessages.push({
624
+ type: 'text',
625
+ text: system,
626
+ cache_control: systemInput?.type === 'chat-message'
627
+ ? systemInput.value.isCacheBreakpoint
628
+ ? { type: 'ephemeral' }
629
+ : null
630
+ : null,
631
+ });
633
632
  }
634
- const prompt = inputs['prompt'];
635
- if (prompt && prompt.type === 'chat-message[]') {
636
- const systemMessages = prompt.value.filter((message) => message.type === 'system');
637
- if (systemMessages.length) {
638
- const converted = systemMessages.map((message) => {
639
- return {
640
- type: 'text',
641
- text: coerceType({ type: 'chat-message', value: message }, 'string'),
642
- cache_control: message.isCacheBreakpoint ? { type: 'ephemeral' } : null,
643
- };
633
+ for (const message of coercePromptToChatMessages(inputs['prompt'])) {
634
+ if (message.type === 'system' || message.type === 'developer') {
635
+ systemMessages.push({
636
+ type: 'text',
637
+ text: coerceType({ type: 'chat-message', value: message }, 'string'),
638
+ cache_control: message.isCacheBreakpoint ? { type: 'ephemeral' } : null,
644
639
  });
645
- return converted;
646
640
  }
647
641
  }
648
- return undefined;
642
+ return systemMessages.length > 0 ? systemMessages : undefined;
649
643
  }
650
644
  function getChatMessages(inputs) {
651
645
  const prompt = inputs['prompt'];
@@ -670,7 +664,7 @@ export async function chatMessagesToClaude3ChatMessages(chatMessages) {
670
664
  return combinedMessages;
671
665
  }
672
666
  async function chatMessageToClaude3ChatMessage(message) {
673
- if (message.type === 'system') {
667
+ if (message.type === 'system' || message.type === 'developer') {
674
668
  return undefined;
675
669
  }
676
670
  if (message.type === 'function') {
@@ -83,6 +83,18 @@ export const generativeAiOptions = Object.entries(generativeAiGoogleModels).map(
83
83
  value: id,
84
84
  label: displayName,
85
85
  }));
86
+ export function getVertexGenerativeModelOptions(options) {
87
+ return {
88
+ model: options.model,
89
+ systemInstruction: options.systemPrompt,
90
+ generationConfig: {
91
+ maxOutputTokens: options.max_output_tokens,
92
+ temperature: options.temperature,
93
+ topP: options.top_p,
94
+ topK: options.top_k,
95
+ },
96
+ };
97
+ }
86
98
  export async function* streamGenerativeAi({ apiKey, model, systemPrompt, prompt, maxOutputTokens, temperature, topP, topK, signal, tools, thinkingBudget, additionalHeaders, }) {
87
99
  const { GoogleGenAI } = await import('@google/genai');
88
100
  const genAi = new GoogleGenAI({ apiKey });
@@ -127,21 +139,20 @@ export async function* streamGenerativeAi({ apiKey, model, systemPrompt, prompt,
127
139
  }
128
140
  }
129
141
  }
130
- export async function* streamChatCompletions({ project, location, applicationCredentials, model, signal, max_output_tokens, temperature, top_p, top_k, prompt, }) {
142
+ export async function* streamChatCompletions({ project, location, applicationCredentials, model, signal, max_output_tokens, temperature, top_p, top_k, systemPrompt, prompt, }) {
131
143
  // Dynamic import: the Google auth library fails under static CJS require.
132
144
  const { VertexAI } = await import('@google-cloud/vertexai');
133
145
  // Can't find a way to pass the credentials path in
134
146
  process.env.GOOGLE_APPLICATION_CREDENTIALS = applicationCredentials;
135
147
  const vertexAi = new VertexAI({ project, location });
136
- const generativeModel = vertexAi.preview.getGenerativeModel({
148
+ const generativeModel = vertexAi.preview.getGenerativeModel(getVertexGenerativeModelOptions({
137
149
  model,
138
- generationConfig: {
139
- maxOutputTokens: max_output_tokens,
140
- temperature,
141
- topP: top_p,
142
- topK: top_k,
143
- },
144
- });
150
+ systemPrompt,
151
+ max_output_tokens,
152
+ temperature,
153
+ top_p,
154
+ top_k,
155
+ }));
145
156
  const response = await generativeModel.generateContentStream({
146
157
  contents: prompt,
147
158
  });
@@ -273,14 +273,13 @@ export const ChatGoogleNodeImpl = {
273
273
  },
274
274
  async process(data, inputs, context) {
275
275
  const output = {};
276
- const systemPrompt = coerceTypeOptional(inputs['systemPrompt'], 'string');
277
276
  const rawModel = getInputOrData(data, inputs, 'model');
278
277
  const model = rawModel;
279
278
  const temperature = getInputOrData(data, inputs, 'temperature', 'number');
280
279
  const topP = getInputOrData(data, inputs, 'top_p', 'number');
281
280
  const useTopP = getInputOrData(data, inputs, 'useTopP', 'boolean');
282
281
  const thinkingBudget = getInputOrData(data, inputs, 'thinkingBudget', 'number');
283
- const { messages } = getChatGoogleNodeMessages(inputs);
282
+ const { messages, systemPrompt } = getChatGoogleNodeMessages(inputs);
284
283
  let prompt = await Promise.all(messages.map(async (message) => {
285
284
  if (message.type === 'user' || message.type === 'assistant') {
286
285
  const parts = await Promise.all([message.message].flat().map(async (part) => {
@@ -343,7 +342,7 @@ export const ChatGoogleNodeImpl = {
343
342
  ],
344
343
  };
345
344
  }
346
- throw new Error(`Google Vertex AI does not support message type ${message.type}`);
345
+ throw new Error('Google Vertex AI received an unsupported message type.');
347
346
  }));
348
347
  // Collapse sequential function responses into a single function response with mutliple parts
349
348
  prompt = prompt.reduce((acc, message) => {
@@ -368,7 +367,10 @@ export const ChatGoogleNodeImpl = {
368
367
  endpoint: undefined,
369
368
  };
370
369
  // TODO Better token counting for Google models.
371
- const tokenCount = await context.tokenizer.getTokenCountForMessages(messages, undefined, tokenizerInfo);
370
+ const tokenMessages = systemPrompt
371
+ ? [{ type: 'system', message: systemPrompt }, ...messages]
372
+ : messages;
373
+ const tokenCount = await context.tokenizer.getTokenCountForMessages(tokenMessages, undefined, tokenizerInfo);
372
374
  if (generativeAiGoogleModels[model]) {
373
375
  maxTokens = clampMaxTokensToModelLimit(output, model, tokenCount, maxTokens, generativeAiGoogleModels[model].maxTokens);
374
376
  }
@@ -478,6 +480,7 @@ export const ChatGoogleNodeImpl = {
478
480
  temperature: useTopP ? undefined : temperature,
479
481
  top_p: useTopP ? topP : undefined,
480
482
  top_k: undefined,
483
+ systemPrompt,
481
484
  project: project,
482
485
  location: location,
483
486
  applicationCredentials: applicationCredentials,
@@ -579,6 +582,14 @@ export const ChatGoogleNodeImpl = {
579
582
  };
580
583
  export const chatGoogleNode = pluginNodeDefinition(ChatGoogleNodeImpl, 'Chat (Google, Legacy)');
581
584
  export function getChatGoogleNodeMessages(inputs) {
582
- const prompt = inputs['prompt'];
583
- return { messages: coercePromptToChatMessages(prompt, { requirePrompt: true }) };
585
+ const promptMessages = coercePromptToChatMessages(inputs['prompt'], { requirePrompt: true });
586
+ const instructionMessages = promptMessages.filter((message) => message.type === 'system' || message.type === 'developer');
587
+ const systemPromptParts = [
588
+ coerceTypeOptional(inputs['systemPrompt'], 'string'),
589
+ ...instructionMessages.map((message) => coerceTypeOptional({ type: 'chat-message', value: message }, 'string')),
590
+ ].filter((part) => !!part);
591
+ return {
592
+ messages: promptMessages.filter((message) => message.type !== 'system' && message.type !== 'developer'),
593
+ systemPrompt: systemPromptParts.length > 0 ? systemPromptParts.join('\n\n') : undefined,
594
+ };
584
595
  }
@@ -100,10 +100,6 @@ class PineconeKnowledgeStoreDriver {
100
100
  const records = chunks.map((chunk) => this.#chunkRecord(sourceId, version, chunk));
101
101
  const batches = batchNdjson(records, 32, 1_500_000);
102
102
  for (let index = 0; index < batches.length; index += 1) {
103
- context.reportProgress?.({
104
- message: `Uploading knowledge batch ${index + 1} of ${batches.length}.`,
105
- percent: 15 + Math.round(((index + 1) / batches.length) * 70),
106
- });
107
103
  const response = await this.#request(`${this.config.indexHost}/records/namespaces/${encodeURIComponent(namespace)}/upsert`, { method: 'POST', body: batches[index], headers: { 'Content-Type': 'application/x-ndjson' } }, context);
108
104
  await response.text();
109
105
  }
@@ -32,7 +32,7 @@ export const pineconePlugin = {
32
32
  key: 'apiKey',
33
33
  label: 'API Key',
34
34
  type: 'secret',
35
- description: 'Stored locally and never written to the project file. Leave blank to use the plugin default.',
35
+ description: 'Stored locally and never written to the project file. Leave blank to use the plugin default. For headless runs, set PINECONE_API_KEY in the host environment (for example, PINECONE_API_KEY=... in a loaded .env file).',
36
36
  },
37
37
  ],
38
38
  createStore: (_connectionId, definition, context) => createPineconeKnowledgeStore(definition, context.settings, context.credentials),
@@ -28,6 +28,10 @@ export async function chatMessageToOpenAIChatCompletionMessage(message, options)
28
28
  };
29
29
  }
30
30
  })
31
+ .with({ type: 'developer' }, (m) => ({
32
+ role: 'developer',
33
+ content: onlyStringContent(m),
34
+ }))
31
35
  .with({ type: 'user' }, async (m) => {
32
36
  const parts = Array.isArray(m.message) ? m.message : [m.message];
33
37
  if (parts.length === 1 && typeof parts[0] === 'string') {
@@ -1,8 +1,64 @@
1
- import { match } from 'ts-pattern';
2
- import { getScalarTypeOf, isArrayDataType, isArrayDataValue, unwrapDataValue, } from '../model/DataValue.js';
1
+ import { getScalarTypeOf, isArrayDataType, isArrayDataValue, isFunctionDataType, isScalarDataType, unwrapDataValue, } from '../model/DataValue.js';
3
2
  import { expectTypeOptional } from './expectType.js';
4
3
  import { normalizeKnowledgeDocument, normalizeKnowledgeEvidence, normalizeKnowledgeSourceReference, } from '../integrations/KnowledgeStoreValidation.js';
4
+ import { normalizeLLMProfileValue } from '../model/chat-v2/llmProfile.js';
5
+ function isValidatedObjectValueType(type) {
6
+ return (type === 'knowledge-source' ||
7
+ type === 'knowledge-document' ||
8
+ type === 'knowledge-evidence' ||
9
+ type === 'llm-config');
10
+ }
11
+ function canAttemptGeneralCoercion(from, to) {
12
+ return !isValidatedObjectValueType(from) || to === 'object' || to === 'string';
13
+ }
14
+ function generalScalarRule(target, coerce) {
15
+ return {
16
+ ...(coerce ? { coerce } : {}),
17
+ canAttempt: (from) => canAttemptGeneralCoercion(from, target),
18
+ };
19
+ }
20
+ function sameTypeOrObjectScalarRule(target, coerce) {
21
+ return {
22
+ ...(coerce ? { coerce } : {}),
23
+ canAttempt: (from) => from === target || from === 'object',
24
+ };
25
+ }
26
+ /**
27
+ * The single scalar coercion policy used by both runtime conversion and
28
+ * type-level port compatibility. Array, function, and `any` wrappers are
29
+ * handled once around this registry because their behavior is structural.
30
+ */
31
+ const scalarCoercionRules = {
32
+ any: {
33
+ canAttempt: () => true,
34
+ },
35
+ boolean: generalScalarRule('boolean', coerceToBoolean),
36
+ string: generalScalarRule('string', coerceToString),
37
+ number: generalScalarRule('number', coerceToNumber),
38
+ date: generalScalarRule('date'),
39
+ time: generalScalarRule('time'),
40
+ datetime: generalScalarRule('datetime'),
41
+ 'chat-message': generalScalarRule('chat-message', coerceToChatMessage),
42
+ 'control-flow-excluded': generalScalarRule('control-flow-excluded'),
43
+ object: generalScalarRule('object', coerceToObject),
44
+ 'gpt-function': {
45
+ canAttempt: (from) => from === 'object',
46
+ },
47
+ vector: generalScalarRule('vector'),
48
+ image: sameTypeOrObjectScalarRule('image'),
49
+ binary: sameTypeOrObjectScalarRule('binary', coerceToBinary),
50
+ audio: sameTypeOrObjectScalarRule('audio'),
51
+ 'graph-reference': generalScalarRule('graph-reference', coerceToGraphReference),
52
+ 'knowledge-source': sameTypeOrObjectScalarRule('knowledge-source', (value) => coerceValidatedObjectValue(value, normalizeKnowledgeSourceReference)),
53
+ 'knowledge-document': sameTypeOrObjectScalarRule('knowledge-document', (value) => coerceValidatedObjectValue(value, normalizeKnowledgeDocument)),
54
+ 'knowledge-evidence': sameTypeOrObjectScalarRule('knowledge-evidence', (value) => coerceValidatedObjectValue(value, normalizeKnowledgeEvidence)),
55
+ 'llm-config': sameTypeOrObjectScalarRule('llm-config', (value) => coerceValidatedObjectValue(value, normalizeLLMProfileValue)),
56
+ document: generalScalarRule('document'),
57
+ };
5
58
  export function coerceTypeOptional(wrapped, type) {
59
+ if (wrapped && isFunctionDataType(type)) {
60
+ return expectTypeOptional(wrapped, type);
61
+ }
6
62
  const value = wrapped ? unwrapDataValue(wrapped) : undefined;
7
63
  // Coerce 'true' to [true] for example
8
64
  if (isArrayDataType(type) && !isArrayDataValue(value)) {
@@ -14,34 +70,30 @@ export function coerceTypeOptional(wrapped, type) {
14
70
  // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.
15
71
  return coercedArray;
16
72
  }
17
- // Coerce foo[] to bar[]
18
- if (isArrayDataType(type) && isArrayDataValue(value) && getScalarTypeOf(type) !== getScalarTypeOf(value.type)) {
73
+ // Preserve arrays whose runtime shape is carried by an any/object wrapper,
74
+ // or coerce each item when the scalar families differ.
75
+ if (isArrayDataType(type) && isArrayDataValue(value)) {
76
+ if (getScalarTypeOf(type) === getScalarTypeOf(value.type)) {
77
+ // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.
78
+ return value.value;
79
+ }
19
80
  const coercedArray = value.value.map((v) => coerceTypeOptional({ type: getScalarTypeOf(value.type), value: v }, getScalarTypeOf(type)));
20
81
  // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.
21
82
  return coercedArray;
22
83
  }
23
- const result = match(type)
24
- .with('string', () => coerceToString(value))
25
- .with('boolean', () => coerceToBoolean(value))
26
- .with('chat-message', () => coerceToChatMessage(value))
27
- .with('number', () => coerceToNumber(value))
28
- .with('object', () => coerceToObject(value))
29
- .with('binary', () => coerceToBinary(value))
30
- .with('graph-reference', () => coerceToGraphReference(value))
31
- .with('knowledge-source', () => coerceKnowledgeValue(value, normalizeKnowledgeSourceReference))
32
- .with('knowledge-document', () => coerceKnowledgeValue(value, normalizeKnowledgeDocument))
33
- .with('knowledge-evidence', () => coerceKnowledgeValue(value, normalizeKnowledgeEvidence))
34
- .otherwise(() => {
35
- if (!value) {
36
- return value;
37
- }
38
- if (getScalarTypeOf(value.type) === 'any' || getScalarTypeOf(type) === 'any') {
39
- return value.value;
40
- }
41
- return expectTypeOptional(value, type);
42
- });
84
+ const scalarRule = isScalarDataType(type) ? scalarCoercionRules[type] : undefined;
85
+ const result = scalarRule?.coerce ? scalarRule.coerce(value) : coerceWithoutSpecializedRule(value, type);
43
86
  return result;
44
87
  }
88
+ function coerceWithoutSpecializedRule(value, type) {
89
+ if (!value) {
90
+ return value;
91
+ }
92
+ if (getScalarTypeOf(value.type) === 'any' || getScalarTypeOf(type) === 'any') {
93
+ return value.value;
94
+ }
95
+ return expectTypeOptional(value, type);
96
+ }
45
97
  export function coerceType(value, type) {
46
98
  const result = coerceTypeOptional(value, type);
47
99
  if (result === undefined) {
@@ -299,7 +351,7 @@ function coerceToGraphReference(value) {
299
351
  }
300
352
  return undefined;
301
353
  }
302
- function coerceKnowledgeValue(value, normalize) {
354
+ function coerceValidatedObjectValue(value, normalize) {
303
355
  if (!value || value.value == null || isArrayDataValue(value))
304
356
  return undefined;
305
357
  try {
@@ -319,9 +371,11 @@ export function canBeCoercedAny(from, to) {
319
371
  }
320
372
  return false;
321
373
  }
322
- // TODO hard to keep in sync with coerceType
323
374
  export function canBeCoerced(from, to) {
324
- if (to === 'any' || from === 'any') {
375
+ if (to === 'any') {
376
+ return scalarCoercionRules.any.canAttempt(from);
377
+ }
378
+ if (from === 'any') {
325
379
  return true;
326
380
  }
327
381
  if (isArrayDataType(to) && isArrayDataType(from)) {
@@ -333,19 +387,8 @@ export function canBeCoerced(from, to) {
333
387
  if (isArrayDataType(from) && !isArrayDataType(to)) {
334
388
  return to === 'string' || to === 'object';
335
389
  }
336
- if (to === 'gpt-function') {
337
- return from === 'object';
338
- }
339
- if (to === 'audio' ||
340
- to === 'binary' ||
341
- to === 'image' ||
342
- to === 'knowledge-source' ||
343
- to === 'knowledge-document' ||
344
- to === 'knowledge-evidence') {
345
- return from === to || from === 'object';
346
- }
347
- if (from === 'knowledge-source' || from === 'knowledge-document' || from === 'knowledge-evidence') {
348
- return to === 'object' || to === 'string';
390
+ if (isScalarDataType(to)) {
391
+ return scalarCoercionRules[to].canAttempt(from);
349
392
  }
350
- return true;
393
+ return canAttemptGeneralCoercion(from, to);
351
394
  }
@@ -1,28 +1,65 @@
1
- import { getScalarTypeOf, isArrayDataType, isFunctionDataType, isScalarDataValue, unwrapDataValue, } from '../model/DataValue.js';
1
+ import { functionTypeToReturnType, getScalarTypeOf, isArrayDataType, isArrayDataValue, isFunctionDataType, isScalarDataValue, unwrapDataValue, } from '../model/DataValue.js';
2
+ function getDeferredValue(value, type) {
3
+ const targetReturnType = functionTypeToReturnType(type);
4
+ if (isFunctionDataType(value.type)) {
5
+ const sourceReturnType = functionTypeToReturnType(value.type);
6
+ return targetReturnType === 'any' || sourceReturnType === 'any' || sourceReturnType === targetReturnType
7
+ ? value.value
8
+ : undefined;
9
+ }
10
+ if (value.type === 'any' && typeof value.value === 'function') {
11
+ return value.value;
12
+ }
13
+ if (targetReturnType === 'any' || value.type === 'any' || value.type === targetReturnType) {
14
+ return () => value.value;
15
+ }
16
+ return undefined;
17
+ }
2
18
  export function expectType(value, type) {
19
+ if (isArrayDataType(type) && isArrayDataValue(value) && getScalarTypeOf(type) === getScalarTypeOf(value.type)) {
20
+ return value.value;
21
+ }
3
22
  // Allow a string to be expected for a string[], just return an array of one element
4
23
  if (isArrayDataType(type) && isScalarDataValue(value) && getScalarTypeOf(type) === value.type) {
5
24
  return [value.value];
6
25
  }
7
- if (type === 'any' || type === 'any[]' || value?.type === 'any' || value?.type === 'any[]') {
8
- return value?.value;
26
+ if (value?.type === type) {
27
+ return value.value;
9
28
  }
10
- if ((isFunctionDataType(type) && value?.type === `fn<${type}>`) || type === 'fn<any>') {
11
- return (() => value.value);
29
+ if (value && isFunctionDataType(type)) {
30
+ const deferredValue = getDeferredValue(value, type);
31
+ if (deferredValue) {
32
+ return deferredValue;
33
+ }
12
34
  }
13
- if (value?.type !== type) {
14
- throw new Error(`Expected value of type ${type} but got ${value?.type}`);
35
+ if (type === 'any' || type === 'any[]' || value?.type === 'any' || value?.type === 'any[]') {
36
+ return value?.value;
15
37
  }
16
- return value.value;
38
+ throw new Error(`Expected value of type ${type} but got ${value?.type}`);
17
39
  }
18
40
  export function expectTypeOptional(value, type) {
19
41
  if (value === undefined) {
20
42
  return undefined;
21
43
  }
44
+ if (isArrayDataType(type) && isArrayDataValue(value) && getScalarTypeOf(type) === getScalarTypeOf(value.type)) {
45
+ // @ts-expect-error Generic T is not narrowed to its array subtype within this runtime-guarded branch.
46
+ return value.value;
47
+ }
22
48
  // Allow a string to be expected for a string[], just return an array of one element
23
49
  if (isArrayDataType(type) && isScalarDataValue(value) && getScalarTypeOf(type) === value.type) {
24
50
  return [value.value];
25
51
  }
52
+ if (value.type === type) {
53
+ // @ts-expect-error Generic T is not narrowed by comparing a DataValue's discriminant to T.
54
+ return value.value;
55
+ }
56
+ if (isFunctionDataType(type)) {
57
+ const deferredValue = getDeferredValue(value, type);
58
+ if (deferredValue) {
59
+ // @ts-expect-error Generic T is not narrowed to its function subtype within this runtime-guarded branch.
60
+ return deferredValue;
61
+ }
62
+ }
26
63
  // We allow a fn<string> to be expected for a string, so unwrap it on demand
27
64
  if (isFunctionDataType(value.type) && value.type === `fn<${type}>`) {
28
65
  value = unwrapDataValue(value);
@@ -27,16 +27,34 @@ export class EventSourceResponse extends Response {
27
27
  return;
28
28
  }
29
29
  const reader = this.streams.eventStream.getReader();
30
+ let reachedEnd = false;
31
+ let emittedEvent = false;
32
+ let rawBranchCancellation;
33
+ const cancelRawBranch = () => {
34
+ rawBranchCancellation ??= this.body?.cancel();
35
+ return rawBranchCancellation;
36
+ };
30
37
  try {
31
38
  while (true) {
32
39
  const { done, value } = await this.raceWithTimeout(reader.read(), this.timeout);
33
40
  if (done) {
41
+ reachedEnd = true;
34
42
  break;
35
43
  }
44
+ if (!emittedEvent) {
45
+ emittedEvent = true;
46
+ // The raw branch only exists for non-SSE provider errors. Once the
47
+ // event branch produces output, retaining it would buffer the entire
48
+ // provider stream for a fallback that cannot be used.
49
+ void cancelRawBranch()?.catch(() => undefined);
50
+ }
36
51
  yield value;
37
52
  }
38
53
  }
39
54
  finally {
55
+ if (!reachedEnd) {
56
+ await Promise.allSettled([reader.cancel(), cancelRawBranch()]);
57
+ }
40
58
  try {
41
59
  reader.releaseLock();
42
60
  }
@@ -16,7 +16,7 @@ export function deserializeProject(serializedProject, path = null) {
16
16
  const { deserializerInput, version } = prepareSerializedInput(serializedProject);
17
17
  try {
18
18
  const result = deserializeProjectByVersion(deserializerInput, version);
19
- normalizeProjectDefaultNodeTitles(result[0]);
19
+ normalizeDeserializedProject(result[0]);
20
20
  if (path !== null) {
21
21
  result[0].metadata.path = path;
22
22
  }
@@ -43,7 +43,7 @@ export function deserializeGraph(serializedGraph) {
43
43
  const { deserializerInput, version } = prepareSerializedInput(serializedGraph);
44
44
  try {
45
45
  const graph = deserializeGraphByVersion(deserializerInput, version);
46
- normalizeGraphDefaultNodeTitles(graph);
46
+ normalizeDeserializedGraph(graph);
47
47
  return graph;
48
48
  }
49
49
  catch (err) {
@@ -54,23 +54,53 @@ export function deserializeGraph(serializedGraph) {
54
54
  throw new Error('Could not deserialize graph');
55
55
  }
56
56
  }
57
- function normalizeProjectDefaultNodeTitles(project) {
57
+ function normalizeDeserializedProject(project) {
58
58
  for (const graph of Object.values(project.graphs)) {
59
- normalizeGraphDefaultNodeTitles(graph);
59
+ normalizeDeserializedGraph(graph);
60
+ }
61
+ for (const prefab of Object.values(project.nodePrefabs ?? {})) {
62
+ normalizeDeserializedNode(prefab.sourceNode);
60
63
  }
61
64
  }
62
- function normalizeGraphDefaultNodeTitles(graph) {
65
+ function normalizeDeserializedGraph(graph) {
63
66
  for (const node of graph.nodes) {
64
- normalizeDefaultCodeNodeTitle(node);
67
+ normalizeDeserializedNode(node);
68
+ }
69
+ }
70
+ function hasLegacyDataBusFlag(node) {
71
+ const data = node.data;
72
+ return node.type === 'passthrough' && data != null && Object.hasOwn(data, 'renderAsDataBus');
73
+ }
74
+ function migrateLegacyLLMChatV2Diagnostics(node) {
75
+ if (node.type !== 'llmChatV2' || node.data == null || typeof node.data !== 'object') {
76
+ return;
77
+ }
78
+ const data = node.data;
79
+ if (data.outputRequestStatus !== true) {
80
+ return;
81
+ }
82
+ // Output request details used to expose all three diagnostics together.
83
+ // Materialize the split settings on load so existing output connections and
84
+ // editor-visible behavior remain unchanged after the setting was separated.
85
+ if (!Object.hasOwn(data, 'outputRequestError')) {
86
+ data.outputRequestError = true;
87
+ }
88
+ if (!Object.hasOwn(data, 'outputRequestBody')) {
89
+ data.outputRequestBody = true;
65
90
  }
66
91
  }
67
- function normalizeDefaultCodeNodeTitle(node) {
92
+ function normalizeDeserializedNode(node) {
68
93
  if (node.type === 'code' && node.title === 'Code') {
69
94
  node.title = 'Code (legacy)';
70
95
  }
71
96
  else if (node.type === 'codeNew' && node.title === 'Code new') {
72
97
  node.title = 'Code';
73
98
  }
99
+ if (hasLegacyDataBusFlag(node)) {
100
+ const { renderAsDataBus: _legacyFlag, ...data } = node.data;
101
+ node.data = data;
102
+ }
103
+ migrateLegacyLLMChatV2Diagnostics(node);
74
104
  }
75
105
  function deserializeProjectByVersion(serializedProject, version) {
76
106
  switch (version) {
@@ -53,6 +53,9 @@ function fnv1aEncodeInto(string, size, utf8Buffer) {
53
53
  let remaining = string;
54
54
  while (remaining.length > 0) {
55
55
  const result = cachedEncoder.encodeInto(remaining, utf8Buffer);
56
+ if (result.read === 0) {
57
+ throw new Error('The `utf8Buffer` option is too small to encode the next character');
58
+ }
56
59
  remaining = remaining.slice(result.read);
57
60
  for (let index = 0; index < result.written; index++) {
58
61
  hash ^= BigInt(utf8Buffer[index]);
@@ -62,9 +65,9 @@ function fnv1aEncodeInto(string, size, utf8Buffer) {
62
65
  return hash;
63
66
  }
64
67
  /**
65
- * @param {string} value
66
- * @param {{ size?: 32 | 64 | 128 | 256 | 512 | 1024, utf8Buffer?: Uint8Array }} options
67
- * @returns {string}
68
+ * @param {string | Uint8Array} value
69
+ * @param {{ size?: 32 | 64 | 128 | 256 | 512 | 1024, utf8Buffer?: Uint8Array }} [options]
70
+ * @returns {bigint}
68
71
  */
69
72
  export default function fnv1a(value, { size = 32, utf8Buffer } = {}) {
70
73
  if (!FNV_PRIMES[size]) {
@@ -37,6 +37,7 @@ export type RunGraphOptions = {
37
37
  includeTrace?: boolean;
38
38
  concurrency?: GraphProcessorConcurrency;
39
39
  getChatNodeEndpoint?: ProcessContext['getChatNodeEndpoint'];
40
+ onChatV2CallFinished?: ProcessContext['onChatV2CallFinished'];
40
41
  tokenizer?: Tokenizer;
41
42
  codeRunner?: ProcessContext['codeRunner'];
42
43
  projectPath?: string;
@@ -63,6 +64,7 @@ export declare function coreCreateProcessor(project: Project, options: RunGraphO
63
64
  getEvents: (spec: RivetEventStreamFilterSpec) => AsyncGenerator<import("./streaming.js").RivetEventStreamEventInfo, void, any>;
64
65
  getSSEStream: (spec: RivetEventStreamFilterSpec) => ReadableStream<Uint8Array<ArrayBufferLike>>;
65
66
  streamNode: (nodeIdOrTitle: string) => ReadableStream<string>;
67
+ dispose(): void;
66
68
  run(): Promise<import("../model/GraphProcessor.js").GraphOutputs>;
67
69
  };
68
70
  export declare function coreRunGraph(project: Project, options: RunGraphOptions): Promise<Record<string, DataValue>>;
@@ -34,6 +34,7 @@ export * from './integrations/integrations.js';
34
34
  import './integrations/enableIntegrations.js';
35
35
  export * from './integrations/VectorDatabase.js';
36
36
  export * from './integrations/KnowledgeStore.js';
37
+ export * from './integrations/KnowledgeStoreFieldPolicy.js';
37
38
  export * from './integrations/KnowledgeStoreProvider.js';
38
39
  export * from './integrations/KnowledgeStoreValidation.js';
39
40
  export * from './integrations/ManagedKnowledgeStore.js';
@@ -63,6 +64,7 @@ export * from './integrations/CodeRunner.js';
63
64
  export * from './integrations/Tokenizer.js';
64
65
  export * from './integrations/GptTokenizerTokenizer.js';
65
66
  export { JS_LIST_CALLBACK_LOCAL_NAMES, interpolateJSListCallbackBody } from './model/nodes/jsListCallbackHelpers.js';
67
+ export { findAutoDelegateGraphCandidate } from './model/nodes/toolCallDelegation.js';
66
68
  export { extractInterpolationVariables, findInterpolationTokenSpans, getInterpolationTokenName, interpolate, protectEscapedInterpolationTokens, restoreEscapedInterpolationTokens, } from './utils/interpolation.js';
67
69
  export { WarningsPort } from './utils/symbols.js';
68
70
  import * as openai from './utils/openai.js';