@valerypopoff/rivet2-core 2.13.0 → 2.15.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 (48) hide show
  1. package/dist/cjs/bundle.cjs +2485 -425
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +5 -0
  4. package/dist/esm/api/processSettings.js +1 -0
  5. package/dist/esm/exports.js +4 -0
  6. package/dist/esm/model/GraphProcessor.js +10 -16
  7. package/dist/esm/model/MarkdownSanitizationPolicy.js +2 -0
  8. package/dist/esm/model/NodeImpl.js +1 -1
  9. package/dist/esm/model/Nodes.js +6 -0
  10. package/dist/esm/model/StreamingWatchTopology.js +98 -61
  11. package/dist/esm/model/classifier/credentials.js +81 -0
  12. package/dist/esm/model/classifier/migration.js +97 -0
  13. package/dist/esm/model/classifier/providers.js +347 -0
  14. package/dist/esm/model/classifier/questionHelpers.js +125 -0
  15. package/dist/esm/model/classifier/types.js +1 -0
  16. package/dist/esm/model/nodeBodyMarkdown.js +37 -0
  17. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +392 -0
  18. package/dist/esm/model/nodes/ClassifierQuestionNode.js +569 -0
  19. package/dist/esm/model/nodes/CodeNewNode.js +33 -9
  20. package/dist/esm/model/nodes/LLMChatV2Node.js +3 -12
  21. package/dist/esm/model/nodes/LLMProfileNode.js +6 -12
  22. package/dist/esm/model/nodes/MatchCaseNode.js +76 -1
  23. package/dist/esm/model/nodes/MatchCaseNodeBase.js +24 -2
  24. package/dist/esm/model/nodes/ObjectNode.js +48 -41
  25. package/dist/esm/model/nodes/PassthroughNode.js +1 -1
  26. package/dist/esm/model/nodes/codeOutputInference.js +292 -0
  27. package/dist/esm/utils/serialization/serialization.js +4 -0
  28. package/dist/types/exports.d.ts +4 -0
  29. package/dist/types/model/EditorDefinition.d.ts +24 -0
  30. package/dist/types/model/MarkdownSanitizationPolicy.d.ts +1 -1
  31. package/dist/types/model/NodeImpl.d.ts +3 -1
  32. package/dist/types/model/Nodes.d.ts +6 -4
  33. package/dist/types/model/Settings.d.ts +4 -0
  34. package/dist/types/model/StreamingWatchTopology.d.ts +6 -0
  35. package/dist/types/model/classifier/credentials.d.ts +24 -0
  36. package/dist/types/model/classifier/migration.d.ts +18 -0
  37. package/dist/types/model/classifier/providers.d.ts +78 -0
  38. package/dist/types/model/classifier/questionHelpers.d.ts +31 -0
  39. package/dist/types/model/classifier/types.d.ts +58 -0
  40. package/dist/types/model/nodeBodyMarkdown.d.ts +19 -0
  41. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +47 -0
  42. package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +60 -0
  43. package/dist/types/model/nodes/CodeNewNode.d.ts +6 -0
  44. package/dist/types/model/nodes/MatchCaseNode.d.ts +8 -1
  45. package/dist/types/model/nodes/MatchCaseNodeBase.d.ts +13 -1
  46. package/dist/types/model/nodes/ObjectNode.d.ts +5 -0
  47. package/dist/types/model/nodes/codeOutputInference.d.ts +31 -0
  48. package/package.json +1 -1
@@ -3,10 +3,15 @@ import { getProcessorEvents, getProcessorSSEStream, getSingleNodeStream } from '
3
3
  // eslint-disable-next-line import/no-cycle -- GraphProcessor depends on CodeRunner, which exposes the package export surface.
4
4
  import { GraphProcessor } from '../model/GraphProcessor.js';
5
5
  import { deserializeProject } from '../utils/serialization/serialization.js';
6
+ import { normalizeClassifierProject } from '../model/classifier/migration.js';
6
7
  import { GptTokenizerTokenizer } from '../integrations/GptTokenizerTokenizer.js';
7
8
  import { looseDataValuesToDataValues } from './looseDataValue.js';
8
9
  import { resolveProcessSettings } from './processSettings.js';
9
10
  export function coreCreateProcessor(project, options, internalOptions = {}) {
11
+ // Public programmatic callers can provide a Project object directly rather
12
+ // than loading YAML through deserializeProject. Keep the legacy Jev
13
+ // compatibility boundary intact for that route as well.
14
+ normalizeClassifierProject(project);
10
15
  const { graph, inputs = {}, context = {} } = options;
11
16
  const graphId = graph
12
17
  ? graph in project.graphs
@@ -16,6 +16,7 @@ export function resolveProcessSettings(settings = {}, fallbacks = {}) {
16
16
  openAiEndpoint: settings.openAiEndpoint ?? fallbacks.openAiEndpoint ?? '',
17
17
  pluginEnv: settings.pluginEnv ?? fallbacks.pluginEnv ?? {},
18
18
  pluginSettings: settings.pluginSettings ?? {},
19
+ classifierProviders: settings.classifierProviders ?? fallbacks.classifierProviders ?? {},
19
20
  recordingPlaybackLatency: settings.recordingPlaybackLatency ?? 1000,
20
21
  defaultNodeColors: settings.defaultNodeColors ?? false,
21
22
  openNodeSettingsOnCreate: settings.openNodeSettingsOnCreate ?? true,
@@ -51,6 +51,10 @@ export * from './recording/RecordedEvents.js';
51
51
  export * from './model/RivetPlugin.js';
52
52
  export * from './model/PluginLoadSpec.js';
53
53
  export * from './plugins.js';
54
+ export * from './model/classifier/credentials.js';
55
+ export * from './model/classifier/migration.js';
56
+ export * from './model/classifier/providers.js';
57
+ export * from './model/classifier/types.js';
54
58
  export * from './model/NodeRegistration.js';
55
59
  export * from './model/RegistryAssembly.js';
56
60
  export * from './model/EditorDefinition.js';
@@ -34,7 +34,7 @@ import { StreamingOutputWatch, } from './StreamingOutputWatch.js';
34
34
  import { StreamingOutputWatchHistory, } from './StreamingOutputWatchHistory.js';
35
35
  import { cloneExecutionOutputs } from './ExecutionOutputClone.js';
36
36
  import { GraphInputStreamRelay } from './GraphInputStream.js';
37
- import { canStreamThroughGraphCaller, canStreamThroughGraphInput, getProjectStreamingOutputWatchConnections, } from './StreamingWatchTopology.js';
37
+ import { canForwardGraphCallerOutputPartials, canForwardGraphOutputPartials, canStreamThroughGraphCaller, canStreamThroughGraphInput, getProjectStreamingOutputWatchConnections, } from './StreamingWatchTopology.js';
38
38
  import { resolveGraphInputValue } from './nodes/GraphInputNode.js';
39
39
  import { KnowledgeStoreController } from '../integrations/KnowledgeStoreProvider.js';
40
40
  import { isDataBusTopologyNode } from './DataBusTopology.js';
@@ -2252,7 +2252,7 @@ export class GraphProcessor {
2252
2252
  const active = this.#nodeAbortControllers.get(node.id);
2253
2253
  return active === nodeAbortController || (active instanceof Set && active.has(nodeAbortController));
2254
2254
  };
2255
- const onGraphOutputPartial = canStreamThroughGraphCaller(node) &&
2255
+ const onGraphOutputPartial = canForwardGraphCallerOutputPartials(node) &&
2256
2256
  (this.#streamingWatchPlansBySourceNodeId.has(node.id) ||
2257
2257
  this.#inputStreamRoutes.has(node.id) ||
2258
2258
  this.#graphOutputPartialBindingsBySourceNodeId.has(node.id))
@@ -2889,13 +2889,18 @@ export class GraphProcessor {
2889
2889
  continue;
2890
2890
  const streams = Object.create(null);
2891
2891
  const incoming = this.#getInputConnectionsForNode(node).filter((edge) => this.#isDefinitionValidConnection(edge));
2892
+ const authoredIncoming = (this.#connections[node.id] ?? []).filter((edge) => edge.inputNodeId === node.id && this.#isDefinitionValidConnection(edge));
2893
+ const authoredProviderCounts = new Map();
2894
+ for (const edge of authoredIncoming) {
2895
+ authoredProviderCounts.set(edge.inputId, (authoredProviderCounts.get(edge.inputId) ?? 0) + 1);
2896
+ }
2892
2897
  for (const edge of incoming) {
2893
2898
  const source = this.#nodesById[edge.outputNodeId];
2894
2899
  if (!inputKeys.get(node.id)?.has(edge.inputId) ||
2895
2900
  !source ||
2896
2901
  source.disabled ||
2897
2902
  source.isSplitRun ||
2898
- incoming.filter((other) => other.inputId === edge.inputId).length !== 1)
2903
+ authoredProviderCounts.get(edge.inputId) !== 1)
2899
2904
  continue;
2900
2905
  const relay = new GraphInputStreamRelay();
2901
2906
  streams[edge.inputId] = relay;
@@ -3007,7 +3012,8 @@ export class GraphProcessor {
3007
3012
  continue;
3008
3013
  }
3009
3014
  const sourceNode = this.#nodesById[connection.outputNodeId];
3010
- if (!sourceNode || !this.#canStreamAcrossGraphOutput(graphOutput, sourceNode)) {
3015
+ if (!sourceNode ||
3016
+ !canForwardGraphOutputPartials(graphOutput, sourceNode, this.#hasFrozenNodeOutputOrUnknownResolver(graphOutput))) {
3011
3017
  continue;
3012
3018
  }
3013
3019
  const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(connection.outputNodeId) ?? [];
@@ -3019,18 +3025,6 @@ export class GraphProcessor {
3019
3025
  this.#graphOutputPartialBindingsBySourceNodeId.set(connection.outputNodeId, bindings);
3020
3026
  }
3021
3027
  }
3022
- /**
3023
- * A named Graph Output can forward a partial only when its terminal result
3024
- * is determined by that same direct producer. Conditions, split aggregation,
3025
- * and frozen replay each introduce an independent boundary decision, so they
3026
- * remain final-only just like an ordinary intermediate node.
3027
- */
3028
- #canStreamAcrossGraphOutput(graphOutput, sourceNode) {
3029
- if (graphOutput.isConditional || graphOutput.isSplitRun || sourceNode.isSplitRun) {
3030
- return false;
3031
- }
3032
- return !this.#hasFrozenNodeOutputOrUnknownResolver(graphOutput);
3033
- }
3034
3028
  #hasFrozenNodeOutputOrUnknownResolver(node) {
3035
3029
  const resolver = this.#frozenNodeOutputResolver;
3036
3030
  if (!resolver) {
@@ -4,6 +4,7 @@ export const RIVET_MARKDOWN_ALLOWED_TAGS = [
4
4
  'br',
5
5
  'code',
6
6
  'del',
7
+ 'div',
7
8
  'em',
8
9
  'h1',
9
10
  'h2',
@@ -16,6 +17,7 @@ export const RIVET_MARKDOWN_ALLOWED_TAGS = [
16
17
  'ol',
17
18
  'p',
18
19
  'pre',
20
+ 'span',
19
21
  'strong',
20
22
  'sub',
21
23
  'sup',
@@ -45,7 +45,7 @@ export class PluginNodeImplClass extends NodeImpl {
45
45
  this.impl = impl;
46
46
  }
47
47
  getInputDefinitions(connections, nodes, project, _referencedProjects, _definitionContext) {
48
- return this.impl.getInputDefinitions(this.data, connections, nodes, project);
48
+ return this.impl.getInputDefinitions(this.data, connections, nodes, project, this.chartNode);
49
49
  }
50
50
  getOutputDefinitions(connections, nodes, project, _referencedProjects, _definitionContext) {
51
51
  return this.impl.getOutputDefinitions(this.data, connections, nodes, project);
@@ -217,6 +217,10 @@ import { referencedGraphAliasNode } from './nodes/ReferencedGraphAliasNode.js';
217
217
  export * from './nodes/ReferencedGraphAliasNode.js';
218
218
  import { nodePrefabInstanceNode } from './nodes/NodePrefabInstanceNode.js';
219
219
  export * from './nodes/NodePrefabInstanceNode.js';
220
+ import { classifierQuestionNode } from './nodes/ClassifierQuestionNode.js';
221
+ export * from './nodes/ClassifierQuestionNode.js';
222
+ import { classifierEvaluateNode } from './nodes/ClassifierEvaluateNode.js';
223
+ export * from './nodes/ClassifierEvaluateNode.js';
220
224
  export const registerBuiltInNodes = (registry) => {
221
225
  return registry
222
226
  .register(toYamlNode)
@@ -326,6 +330,8 @@ export const registerBuiltInNodes = (registry) => {
326
330
  .register(mcpToolCallNode)
327
331
  .register(mcpGetPromptNode)
328
332
  .register(referencedGraphAliasNode)
333
+ .register(classifierQuestionNode)
334
+ .register(classifierEvaluateNode)
329
335
  .register(nodePrefabInstanceNode);
330
336
  };
331
337
  let globalRivetNodeRegistry = registerBuiltInNodes(new NodeRegistration());
@@ -1,13 +1,17 @@
1
1
  import { canRenderDataBusNode, getDataBusInputChannelIndex, getDataBusOutputChannelIndex } from './DataBusTopology.js';
2
2
  import { resolveNodePrefabInstance } from './NodePrefabResolver.js';
3
3
  import { createGraphOutputSelection } from './GraphOutputSelection.js';
4
- export function canStreamThroughGraphCaller(node) {
4
+ /** An executing caller may forward outputs after its condition has passed. */
5
+ export function canForwardGraphCallerOutputPartials(node) {
5
6
  return ((node.type === 'subGraph' || node.type === 'referencedGraphAlias') &&
6
7
  !node.disabled &&
7
- !node.isConditional &&
8
8
  !node.isSplitRun &&
9
9
  !node.data.useErrorOutput);
10
10
  }
11
+ /** Early input delivery must not bypass the caller's ordinary readiness/condition gate. */
12
+ export function canStreamThroughGraphCaller(node) {
13
+ return canForwardGraphCallerOutputPartials(node) && !node.isConditional;
14
+ }
11
15
  export function canStreamThroughGraphInput(node) {
12
16
  return (node.type === 'graphInput' &&
13
17
  !node.disabled &&
@@ -15,6 +19,15 @@ export function canStreamThroughGraphInput(node) {
15
19
  !node.isSplitRun &&
16
20
  !node.data.useDefaultValueInput);
17
21
  }
22
+ /** A named output may forward only when one direct producer determines its terminal value. */
23
+ export function canForwardGraphOutputPartials(graphOutput, sourceNode, graphOutputIsFrozen) {
24
+ return (graphOutput.type === 'graphOutput' &&
25
+ !graphOutput.disabled &&
26
+ !graphOutput.isConditional &&
27
+ !graphOutput.isSplitRun &&
28
+ !sourceNode.isSplitRun &&
29
+ !graphOutputIsFrozen);
30
+ }
18
31
  /** Trace Watch demand through named boundaries without making ordinary nodes repeatable. */
19
32
  export function getProjectStreamingOutputWatchConnections({ project, graph, referencedProjects, registry, frozenNodeOutputs = {}, isNodeFrozen, fullGraphCallers, }) {
20
33
  // Unsaved active graph edits must take precedence over the stored project graph.
@@ -112,7 +125,7 @@ export function getProjectStreamingOutputWatchConnections({ project, graph, refe
112
125
  callers.set(child, entries);
113
126
  }
114
127
  }
115
- const pending = [];
128
+ const watchInputs = [];
116
129
  for (const [candidate, context] of contexts) {
117
130
  for (const node of Object.values(context.nodes)) {
118
131
  if (node.type !== 'watchStreamingOutput' || node.disabled || isFrozen(context.project, candidate, node))
@@ -120,72 +133,96 @@ export function getProjectStreamingOutputWatchConnections({ project, graph, refe
120
133
  const inputs = context.incoming(node.id).filter((edge) => edge.inputId === 'stream');
121
134
  // Multiple providers are rejected by the Watch scheduler, not multiple streams.
122
135
  if (inputs.length === 1)
123
- pending.push({ graph: candidate, edge: inputs[0] });
136
+ watchInputs.push({ graph: candidate, edge: inputs[0] });
124
137
  }
125
138
  }
126
- while (pending.length) {
127
- const { graph: candidate, edge } = pending.pop();
139
+ const visiting = new Map();
140
+ const trace = (candidate, edge) => {
128
141
  const context = contexts.get(candidate);
129
142
  if (context.marked.has(edge))
130
- continue;
131
- const route = new Set([edge]);
132
- let producerEdge = edge;
133
- let source = context.nodes[producerEdge.outputNodeId];
134
- while (source && canRenderDataBusNode(source)) {
135
- const channel = getDataBusOutputChannelIndex(producerEdge.outputId);
136
- const providers = context
137
- .incoming(source.id)
138
- .filter((input) => getDataBusInputChannelIndex(input.inputId) === channel);
139
- if (channel == null || providers.length !== 1 || route.has(providers[0])) {
140
- source = undefined;
141
- break;
143
+ return true;
144
+ const graphVisiting = visiting.get(candidate) ?? new Set();
145
+ if (graphVisiting.has(edge))
146
+ return false;
147
+ graphVisiting.add(edge);
148
+ visiting.set(candidate, graphVisiting);
149
+ try {
150
+ const source = context.nodes[edge.outputNodeId];
151
+ if (!source || source.disabled || source.isSplitRun || isFrozen(context.project, candidate, source))
152
+ return false;
153
+ if (canRenderDataBusNode(source)) {
154
+ const channel = getDataBusOutputChannelIndex(edge.outputId);
155
+ if (channel == null)
156
+ return false;
157
+ const providers = context
158
+ .incoming(source.id)
159
+ .filter((input) => getDataBusInputChannelIndex(input.inputId) === channel);
160
+ if (providers.length !== 1 || !trace(candidate, providers[0]))
161
+ return false;
162
+ context.marked.add(edge);
163
+ return true;
142
164
  }
143
- producerEdge = providers[0];
144
- route.add(producerEdge);
145
- source = context.nodes[producerEdge.outputNodeId];
146
- }
147
- if (!source || source.disabled || source.type === 'dataBus')
148
- continue;
149
- if (context.nodes[edge.inputNodeId]?.type === 'graphOutput' && source.isSplitRun)
150
- continue;
151
- for (const segment of route)
152
- context.marked.add(segment);
153
- if (source.isSplitRun || isFrozen(context.project, candidate, source))
154
- continue;
155
- if (source.type === 'graphInput' && producerEdge.outputId === 'data') {
156
- if (!canStreamThroughGraphInput(source))
157
- continue;
158
- const inputName = source.data.id;
159
- for (const parent of callers.get(candidate) ?? []) {
160
- if (parent.selected && !parent.selected.has(edge.inputNodeId))
161
- continue;
162
- for (const input of contexts.get(parent.graph).incoming(parent.node.id)) {
163
- if (input.inputId === inputName)
164
- pending.push({ graph: parent.graph, edge: input });
165
+ if (source.type === 'graphInput' && edge.outputId === 'data') {
166
+ if (!canStreamThroughGraphInput(source))
167
+ return false;
168
+ const inputName = source.data.id;
169
+ let foundSource = false;
170
+ for (const parent of callers.get(candidate) ?? []) {
171
+ if (parent.selected && !parent.selected.has(edge.inputNodeId))
172
+ continue;
173
+ const inputs = contexts
174
+ .get(parent.graph)
175
+ .incoming(parent.node.id)
176
+ .filter((input) => input.inputId === inputName);
177
+ // Ambiguous authored inputs stay final-only even though ordinary
178
+ // execution retains its established first-provider projection.
179
+ if (inputs.length === 1 && trace(parent.graph, inputs[0]))
180
+ foundSource = true;
165
181
  }
182
+ if (!foundSource)
183
+ return false;
184
+ context.marked.add(edge);
185
+ return true;
166
186
  }
167
- continue;
168
- }
169
- if (!canStreamThroughGraphCaller(source))
170
- continue;
171
- const caller = source;
172
- const childProject = caller.type === 'subGraph' ? context.project : projects[caller.data.projectId];
173
- const child = childProject?.graphs[caller.data.graphId];
174
- const childContext = child && contexts.get(child);
175
- if (!child || !childContext)
176
- continue;
177
- const outputs = Object.values(childContext.nodes).filter((node) => node.type === 'graphOutput' && !node.disabled && node.data.id === producerEdge.outputId);
178
- // Duplicate names have first-final-winner semantics, so cannot relay partials.
179
- if (outputs.length !== 1)
180
- continue;
181
- const output = outputs[0];
182
- if (output.isConditional || output.isSplitRun || isFrozen(childProject, child, output))
183
- continue;
184
- for (const input of childContext.incoming(output.id)) {
185
- if (input.inputId === 'value' && !childContext.nodes[input.outputNodeId]?.isSplitRun) {
186
- pending.push({ graph: child, edge: input });
187
+ if (source.type !== 'subGraph' && source.type !== 'referencedGraphAlias') {
188
+ context.marked.add(edge);
189
+ return true;
187
190
  }
191
+ if (!canForwardGraphCallerOutputPartials(source))
192
+ return false;
193
+ const caller = source;
194
+ const childProject = caller.type === 'subGraph' ? context.project : projects[caller.data.projectId];
195
+ const child = childProject?.graphs[caller.data.graphId];
196
+ const childContext = child && contexts.get(child);
197
+ if (!child || !childContext)
198
+ return false;
199
+ const outputs = Object.values(childContext.nodes).filter((node) => node.type === 'graphOutput' && !node.disabled && node.data.id === edge.outputId);
200
+ // Duplicate names have first-final-winner semantics, so cannot relay partials.
201
+ if (outputs.length !== 1)
202
+ return false;
203
+ const output = outputs[0];
204
+ const outputIsFrozen = isFrozen(childProject, child, output);
205
+ const providers = childContext.incoming(output.id).filter((input) => input.inputId === 'value');
206
+ // As in GraphProcessor's effective connection projection, the first
207
+ // valid provider owns a single-input Graph Output in a malformed graph.
208
+ // Never mark a shadowed provider that cannot determine the final value.
209
+ const provider = providers[0];
210
+ const providerNode = provider && childContext.nodes[provider.outputNodeId];
211
+ if (!provider ||
212
+ !providerNode ||
213
+ !canForwardGraphOutputPartials(output, providerNode, outputIsFrozen) ||
214
+ !trace(child, provider))
215
+ return false;
216
+ context.marked.add(edge);
217
+ return true;
188
218
  }
189
- }
219
+ finally {
220
+ graphVisiting.delete(edge);
221
+ if (graphVisiting.size === 0)
222
+ visiting.delete(candidate);
223
+ }
224
+ };
225
+ for (const { graph: candidate, edge } of watchInputs)
226
+ trace(candidate, edge);
190
227
  return contexts.get(graph)?.marked ?? new Set();
191
228
  }
@@ -0,0 +1,81 @@
1
+ import { coerceTypeOptional } from '../../utils/coerceType.js';
2
+ export const JEV_DEFAULT_CREDENTIAL_NAMES = {
3
+ programmaticName: 'typesafeApiKey',
4
+ environmentVariableName: 'TYPESAFE_API_KEY',
5
+ };
6
+ const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
7
+ const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
8
+ export function isValidClassifierProgrammaticCredentialName(name) {
9
+ return programmaticNamePattern.test(name);
10
+ }
11
+ export function isValidClassifierEnvironmentCredentialName(name) {
12
+ return environmentVariableNamePattern.test(name);
13
+ }
14
+ export function normalizeClassifierCredentialNames(value, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
15
+ if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
16
+ throw new Error('Classifier API key names must be an object.');
17
+ }
18
+ const raw = value;
19
+ if (raw?.programmaticName != null && typeof raw.programmaticName !== 'string') {
20
+ throw new Error('Classifier programmatic API key name must be a string.');
21
+ }
22
+ if (raw?.environmentVariableName != null && typeof raw.environmentVariableName !== 'string') {
23
+ throw new Error('Classifier API key environment variable must be a string.');
24
+ }
25
+ const programmaticName = raw?.programmaticName?.trim() || defaults.programmaticName;
26
+ const environmentVariableName = raw?.environmentVariableName?.trim() || defaults.environmentVariableName;
27
+ if (!isValidClassifierProgrammaticCredentialName(programmaticName)) {
28
+ throw new Error('Classifier programmatic API key name must be a JavaScript-style identifier without a leading digit.');
29
+ }
30
+ if (!isValidClassifierEnvironmentCredentialName(environmentVariableName)) {
31
+ throw new Error('Classifier API key environment variable must contain letters, digits, and _ without a leading digit.');
32
+ }
33
+ return { programmaticName, environmentVariableName };
34
+ }
35
+ export function getClassifierCredentialNamesForDisplay(value, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
36
+ try {
37
+ return normalizeClassifierCredentialNames(value, defaults);
38
+ }
39
+ catch {
40
+ return { ...defaults };
41
+ }
42
+ }
43
+ export function isDefaultClassifierCredentialNames(names, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
44
+ return names.programmaticName === defaults.programmaticName && names.environmentVariableName === defaults.environmentVariableName;
45
+ }
46
+ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, defaults, inputs, providerId, }) {
47
+ if (apiKeySource === 'input') {
48
+ const value = coerceTypeOptional(inputs['apiKey'], 'string')?.trim();
49
+ if (!value)
50
+ throw new Error('API Key input is required when API key source is Input port.');
51
+ return value;
52
+ }
53
+ const names = normalizeClassifierCredentialNames(apiKeyNames, defaults);
54
+ const namedValue = resolveNamedClassifierApiKey(context, names);
55
+ if (namedValue)
56
+ return namedValue;
57
+ if (isDefaultClassifierCredentialNames(names, defaults)) {
58
+ const firstPartyValue = getNonEmptyString(context.settings.classifierProviders?.[providerId]?.apiKey);
59
+ if (firstPartyValue)
60
+ return firstPartyValue;
61
+ // Compatibility only: old applications stored the key under the removed plugin.
62
+ if (providerId === 'jev') {
63
+ const legacyValue = getNonEmptyString(context.settings.pluginSettings?.typesafe?.typesafeApiKey);
64
+ if (legacyValue)
65
+ return legacyValue;
66
+ }
67
+ }
68
+ throw new Error(`${providerId === 'jev' ? 'Jev' : 'Classifier'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Classifier.`);
69
+ }
70
+ function resolveNamedClassifierApiKey(context, names) {
71
+ const programmaticValue = getNonEmptyString(context.settings?.[names.programmaticName]);
72
+ if (programmaticValue)
73
+ return programmaticValue;
74
+ const environmentValue = getNonEmptyString(context.settings?.pluginEnv?.[names.environmentVariableName]);
75
+ if (environmentValue)
76
+ return environmentValue;
77
+ return getNonEmptyString(globalThis.process?.env?.[names.environmentVariableName]);
78
+ }
79
+ function getNonEmptyString(value) {
80
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
81
+ }
@@ -0,0 +1,97 @@
1
+ const legacyTypesafePluginId = 'typesafe';
2
+ function isLegacyTypesafePlugin(spec) {
3
+ return spec.type === 'built-in' && spec.id === legacyTypesafePluginId;
4
+ }
5
+ /**
6
+ * Converts the former TypeSafe plugin node family into the first-party
7
+ * classifier contract. It is intentionally idempotent because project data
8
+ * reaches Core through imports, hosted snapshots, recordings, and copies.
9
+ */
10
+ export function normalizeClassifierProject(project) {
11
+ for (const graph of Object.values(project.graphs))
12
+ normalizeClassifierGraph(graph);
13
+ for (const prefab of Object.values(project.nodePrefabs ?? {}))
14
+ normalizeClassifierNode(prefab.sourceNode);
15
+ if (project.plugins?.some(isLegacyTypesafePlugin)) {
16
+ project.plugins = project.plugins.filter((plugin) => !isLegacyTypesafePlugin(plugin));
17
+ }
18
+ }
19
+ /**
20
+ * Checks whether a project still needs the in-place legacy migration. Hosts
21
+ * which receive a caller-owned project object use this before cloning, so a
22
+ * compatibility repair never mutates the caller's snapshot.
23
+ */
24
+ export function hasLegacyClassifierProjectData(project) {
25
+ return (project.plugins?.some(isLegacyTypesafePlugin) === true ||
26
+ Object.values(project.graphs).some(hasLegacyClassifierGraphData) ||
27
+ Object.values(project.nodePrefabs ?? {}).some((prefab) => hasLegacyClassifierNodeData(prefab.sourceNode)));
28
+ }
29
+ export function normalizeClassifierGraph(graph) {
30
+ for (const node of graph.nodes)
31
+ normalizeClassifierNode(node);
32
+ }
33
+ export function hasLegacyClassifierGraphData(graph) {
34
+ return graph.nodes.some(hasLegacyClassifierNodeData);
35
+ }
36
+ export function normalizeClassifierNode(node) {
37
+ const legacyNode = node;
38
+ switch (legacyNode.type) {
39
+ case 'jevChoiceQuestion':
40
+ normalizeQuestionNode(legacyNode, 'choice', 'Jev Choice Question');
41
+ return;
42
+ case 'jevScoreQuestion':
43
+ normalizeQuestionNode(legacyNode, 'score', 'Jev Score Question');
44
+ return;
45
+ case 'jevNoulQuestion':
46
+ normalizeQuestionNode(legacyNode, 'noul', 'Jev Noul Question');
47
+ return;
48
+ case 'jevEvaluate':
49
+ normalizeEvaluateNode(legacyNode);
50
+ return;
51
+ case 'classifierEvaluate':
52
+ if (hasDeprecatedGlobalCredentialNames(legacyNode))
53
+ normalizeEvaluateNode(legacyNode);
54
+ return;
55
+ default:
56
+ return;
57
+ }
58
+ }
59
+ function hasLegacyClassifierNodeData(node) {
60
+ return (node.type === 'jevChoiceQuestion' ||
61
+ node.type === 'jevScoreQuestion' ||
62
+ node.type === 'jevNoulQuestion' ||
63
+ node.type === 'jevEvaluate' ||
64
+ (node.type === 'classifierEvaluate' && hasDeprecatedGlobalCredentialNames(node)));
65
+ }
66
+ function hasDeprecatedGlobalCredentialNames(node) {
67
+ return Object.prototype.hasOwnProperty.call(asRecord(node.data), 'apiKeyNames');
68
+ }
69
+ function normalizeQuestionNode(node, questionType, legacyTitle) {
70
+ node.type = 'classifierQuestion';
71
+ node.data = {
72
+ ...asRecord(node.data),
73
+ questionType,
74
+ };
75
+ if (node.title === legacyTitle)
76
+ node.title = 'Classifier Question';
77
+ }
78
+ function normalizeEvaluateNode(node) {
79
+ const legacyData = asRecord(node.data);
80
+ const legacyApiKeyNames = legacyData.apiKeyNames;
81
+ const existingNames = asRecord(legacyData.apiKeyNamesByProvider);
82
+ const apiKeyNamesByProvider = legacyApiKeyNames === undefined || Object.prototype.hasOwnProperty.call(existingNames, 'jev')
83
+ ? existingNames
84
+ : { ...existingNames, jev: legacyApiKeyNames };
85
+ const { apiKeyNames: _legacyApiKeyNames, ...dataWithoutLegacyNames } = legacyData;
86
+ node.type = 'classifierEvaluate';
87
+ node.data = {
88
+ ...dataWithoutLegacyNames,
89
+ provider: typeof legacyData.provider === 'string' && legacyData.provider ? legacyData.provider : 'jev',
90
+ ...(Object.keys(apiKeyNamesByProvider).length > 0 ? { apiKeyNamesByProvider } : {}),
91
+ };
92
+ if (node.title === 'Jev Evaluate')
93
+ node.title = 'Classifier Evaluate';
94
+ }
95
+ function asRecord(value) {
96
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
97
+ }