@valerypopoff/rivet2-core 2.22.0 → 2.24.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 (49) hide show
  1. package/dist/cjs/bundle.cjs +1166 -797
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +4 -1
  4. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  5. package/dist/esm/exports.js +0 -1
  6. package/dist/esm/index.js +3 -0
  7. package/dist/esm/integrations/CodeRunner.js +6 -3
  8. package/dist/esm/integrations/CodeRunnerNamespace.js +10 -0
  9. package/dist/esm/model/AgentResponseTracePresentation.js +5 -1
  10. package/dist/esm/model/ChildInvocationOwnership.js +51 -0
  11. package/dist/esm/model/GraphProcessor.js +32 -54
  12. package/dist/esm/model/NodeRegistration.js +2 -6
  13. package/dist/esm/model/classifier/baseten.js +78 -0
  14. package/dist/esm/model/classifier/credentials.js +17 -9
  15. package/dist/esm/model/classifier/images.js +4 -4
  16. package/dist/esm/model/classifier/jev.js +45 -0
  17. package/dist/esm/model/classifier/json.js +1 -1
  18. package/dist/esm/model/classifier/limits.js +13 -13
  19. package/dist/esm/model/classifier/openai.js +20 -2
  20. package/dist/esm/model/classifier/preparation.js +5 -5
  21. package/dist/esm/model/classifier/profile.js +14 -13
  22. package/dist/esm/model/classifier/profileExecution.js +26 -23
  23. package/dist/esm/model/classifier/providers.js +170 -74
  24. package/dist/esm/model/classifier/questionHelpers.js +21 -2
  25. package/dist/esm/model/classifier/questions.js +37 -7
  26. package/dist/esm/model/classifier/response.js +8 -2
  27. package/dist/esm/model/classifier/state.js +2 -2
  28. package/dist/esm/model/classifier/subq.js +51 -0
  29. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +32 -61
  30. package/dist/esm/model/nodes/ClassifierProfileNode.js +9 -9
  31. package/dist/esm/model/nodes/ClassifierQuestionNode.js +53 -34
  32. package/dist/types/index.d.ts +1 -1
  33. package/dist/types/integrations/CodeRunner.d.ts +4 -1
  34. package/dist/types/integrations/CodeRunnerNamespace.d.ts +5 -0
  35. package/dist/types/model/AgentResponseTracePresentation.d.ts +2 -0
  36. package/dist/types/model/ChildInvocationOwnership.d.ts +36 -0
  37. package/dist/types/model/classifier/baseten.d.ts +8 -0
  38. package/dist/types/model/classifier/credentials.d.ts +2 -0
  39. package/dist/types/model/classifier/jev.d.ts +9 -0
  40. package/dist/types/model/classifier/profileExecution.d.ts +1 -1
  41. package/dist/types/model/classifier/providers.d.ts +26 -5
  42. package/dist/types/model/classifier/questionHelpers.d.ts +3 -1
  43. package/dist/types/model/classifier/questions.d.ts +2 -1
  44. package/dist/types/model/classifier/state.d.ts +1 -0
  45. package/dist/types/model/classifier/subq.d.ts +8 -0
  46. package/dist/types/model/classifier/types.d.ts +9 -2
  47. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +2 -4
  48. package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +2 -2
  49. package/package.json +2 -2
@@ -1,5 +1,4 @@
1
1
  export * from './utils/index.js';
2
- // eslint-disable-next-line import/no-cycle -- GraphProcessor depends on CodeRunner, which exposes the top-level Rivet export surface.
3
2
  export * from './model/GraphProcessor.js';
4
3
  export { canConsumeControlFlowExcludedInput } from './model/NodeExclusionPolicy.js';
5
4
  export * from './model/DataValue.js';
package/dist/esm/index.js CHANGED
@@ -1,2 +1,5 @@
1
+ import * as RivetTypes from './exports.js';
2
+ import { installCodeRunnerNamespace } from './integrations/CodeRunnerNamespace.js';
3
+ installCodeRunnerNamespace(RivetTypes);
1
4
  export * from './exports.js';
2
5
  export const Rivet = undefined;
@@ -1,8 +1,11 @@
1
1
  import { resolveCodeInterpolationExpression } from '../utils/interpolation.js';
2
- // eslint-disable-next-line import/no-cycle -- Authored code receives the complete public Rivet namespace at execution time.
3
- import * as Rivet from '../exports.js';
2
+ import { getCodeRunnerNamespace } from './CodeRunnerNamespace.js';
4
3
  export { ALL_CODE_RUNNER_OPTIONS } from './CodeRunnerOptions.js';
5
4
  export class IsomorphicCodeRunner {
5
+ resolveNamespace;
6
+ constructor(resolveNamespace = getCodeRunnerNamespace) {
7
+ this.resolveNamespace = resolveNamespace;
8
+ }
6
9
  async runCode(code, inputs, options, graphInputs, contextValues, globalValues) {
7
10
  const argNames = ['inputs'];
8
11
  const args = [inputs];
@@ -16,7 +19,7 @@ export class IsomorphicCodeRunner {
16
19
  }
17
20
  if (options.includeRivet) {
18
21
  argNames.push('Rivet');
19
- args.push(Rivet);
22
+ args.push(this.resolveNamespace());
20
23
  }
21
24
  if (graphInputs) {
22
25
  argNames.push('graphInputs');
@@ -0,0 +1,10 @@
1
+ let namespace;
2
+ export function installCodeRunnerNamespace(value) {
3
+ namespace = value;
4
+ }
5
+ export function getCodeRunnerNamespace() {
6
+ if (!namespace) {
7
+ throw new Error('The Rivet code namespace is unavailable. Import the public core entrypoint or supply a code runner.');
8
+ }
9
+ return namespace;
10
+ }
@@ -1,11 +1,15 @@
1
1
  import { getCustomProviderApiContract } from './chat-v2/customProviderApi.js';
2
+ /** Presentation only: family-scoped exact default alias, never a rewrite of authored/recorded names. */
3
+ export function getProfileDisplayName(name, family) {
4
+ return family === 'classifier' && name === 'Classifier Profile' ? 'Decision AI Profile' : name;
5
+ }
2
6
  export function buildAgentProfileAttemptInspectorRows(attempts) {
3
7
  return attempts.map((attempt) => ({
4
8
  eventId: attempt.eventId,
5
9
  providerAndModel: [
6
10
  ...(attempt.profileName == null || attempt.profileName.trim() === ''
7
11
  ? []
8
- : [`Profile: ${attempt.profileName.trim()}`]),
12
+ : [`Profile: ${getProfileDisplayName(attempt.profileName, attempt.family).trim()}`]),
9
13
  `${formatProvider(attempt)} / ${attempt.model}`,
10
14
  ].join(' · '),
11
15
  context: [
@@ -0,0 +1,51 @@
1
+ export function resolveChildInvocationOwnership(mode, context) {
2
+ const { run } = context;
3
+ switch (mode.kind) {
4
+ case 'continuation':
5
+ return {
6
+ parent: context.parent,
7
+ abortOwner: context.abortOwner,
8
+ sameGraphOwner: context.sameGraphOwner,
9
+ suppressPartialOutputs: false,
10
+ suppressLifecycle: true,
11
+ state: {
12
+ attachedNodeData: run.attachedNodeData,
13
+ graphInputNodeValues: run.graphInputNodeValues,
14
+ graphOutputs: mode.graphOutputs,
15
+ },
16
+ identity: { rootRunId: run.rootRunId, graphRunId: run.graphRunId, parentGraphRunId: run.parentGraphRunId },
17
+ };
18
+ case 'async':
19
+ return {
20
+ parent: context.sameGraphOwner,
21
+ abortOwner: context.root,
22
+ suppressPartialOutputs: true,
23
+ suppressLifecycle: context.rootGraphOrigin,
24
+ state: {
25
+ attachedNodeData: run.attachedNodeData,
26
+ graphInputNodeValues: run.graphInputNodeValues,
27
+ graphOutputs: {},
28
+ },
29
+ identity: context.rootGraphOrigin
30
+ ? { rootRunId: run.rootRunId, graphRunId: run.graphRunId, parentGraphRunId: run.parentGraphRunId }
31
+ : {
32
+ rootRunId: context.rootIdentity.rootRunId,
33
+ graphRunId: context.newGraphRunId(),
34
+ parentGraphRunId: context.sameGraphIdentity.graphRunId,
35
+ },
36
+ };
37
+ case 'watch':
38
+ return {
39
+ parent: context.parent,
40
+ abortOwner: context.root,
41
+ suppressPartialOutputs: true,
42
+ suppressLifecycle: true,
43
+ state: { attachedNodeData: new Map(), graphInputNodeValues: { ...run.graphInputNodeValues }, graphOutputs: {} },
44
+ identity: {
45
+ rootRunId: context.rootIdentity.rootRunId,
46
+ graphRunId: mode.graphRunId,
47
+ parentGraphRunId: run.graphRunId,
48
+ },
49
+ };
50
+ }
51
+ }
@@ -1,4 +1,5 @@
1
1
  import { GraphInvocationState, GraphSharedExecutionState } from './GraphExecutionState.js';
2
+ import { resolveChildInvocationOwnership } from './ChildInvocationOwnership.js';
2
3
  import { planStreamingWatchTopology, planAsyncBranchTopology, getAsyncBranchWatchViolation, } from './SchedulerBoundaryPlanner.js';
3
4
  import { GraphSchedulerBoundaryState, } from './GraphSchedulerBoundaryState.js';
4
5
  import {} from './DataValue.js';
@@ -48,7 +49,6 @@ import { loadProjectReferenceTree } from './ProjectReferenceLoader.js';
48
49
  import { getSubgraphProjectKey, isSubgraphProjectKey } from './SubgraphProjectTarget.js';
49
50
  import { MAX_CAUGHT_STREAMING_CHUNKS } from './nodes/CatchStreamingChunksNode.js';
50
51
  import { isEqual } from 'lodash-es';
51
- // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
52
52
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
53
53
  const graphProcessorGraphOverride = Symbol('graphProcessorGraphOverride');
54
54
  const consumedAsyncBranchTriggerOverride = Symbol('consumedAsyncBranchTriggerOverride');
@@ -1324,6 +1324,9 @@ export class GraphProcessor {
1324
1324
  };
1325
1325
  const key = getSubgraphProjectKey(target);
1326
1326
  let resolved = this.#shared.subgraphTargetCache.get(key);
1327
+ // Snapshot reuse is not permission reuse. A descendant can move
1328
+ // bundles after the parent's discovery but before this child starts;
1329
+ // keep this preflight ahead of any child-node side effects.
1327
1330
  if (resolved)
1328
1331
  await this.#run.context.subgraphProjectLoader?.validateTarget?.(target);
1329
1332
  if (!resolved) {
@@ -1809,7 +1812,6 @@ export class GraphProcessor {
1809
1812
  async #runManagedAsyncBranch(triggerNode, triggerOutputs, plan, onProcessorCreated) {
1810
1813
  const root = this.getRootProcessor();
1811
1814
  const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
1812
- const isRootGraphOrigin = !sameGraphOwner.#isSubProcessor;
1813
1815
  if (root.#run.abortController.signal.aborted) {
1814
1816
  throw createGraphAbortErrorFromSignal(root.#run.abortController.signal, 'Async branch aborted before it started');
1815
1817
  }
@@ -1826,31 +1828,8 @@ export class GraphProcessor {
1826
1828
  .map((connection) => [connection.outputNodeId, this.#definitions[connection.outputNodeId]])),
1827
1829
  onCreated: onProcessorCreated,
1828
1830
  });
1829
- processor.#parent = sameGraphOwner;
1830
- processor.#abortOwnerOverride = root;
1831
- processor.#suppressGraphPartialOutputs = true;
1832
- processor.#suppressGraphLifecycleEvents = isRootGraphOrigin;
1833
- processor.#sharedRunStateOverride = {
1834
- attachedNodeData: this.#run.attachedNodeData,
1835
- graphInputNodeValues: this.#run.graphInputNodeValues,
1836
- // Async branches cannot contain Graph Output nodes. Keep their synthetic
1837
- // boundary outputs private so branch finalization cannot seed the root's
1838
- // derived cost output before the root has accumulated every path.
1839
- graphOutputs: {},
1840
- };
1841
1831
  const branchRunToNodeIds = this.runToNodeIds?.filter((nodeId) => plan.nodeIds.has(nodeId));
1842
1832
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
1843
- processor.#executionIdentityOverride = isRootGraphOrigin
1844
- ? {
1845
- rootRunId: this.#run.rootRunId,
1846
- graphRunId: this.#run.graphRunId,
1847
- parentGraphRunId: this.#run.parentGraphRunId,
1848
- }
1849
- : {
1850
- rootRunId: root.#run.rootRunId,
1851
- graphRunId: nanoid(),
1852
- parentGraphRunId: sameGraphOwner.#run.graphRunId,
1853
- };
1854
1833
  processor.preloadNodeData(triggerNode.id, triggerOutputs);
1855
1834
  processor.#suppressedPreloadedNodeIds.add(triggerNode.id);
1856
1835
  const unwireEvents = this.#wireChildEvents(processor, root, {
@@ -2502,23 +2481,14 @@ export class GraphProcessor {
2502
2481
  throw new Error('Cannot execute a tool continuation branch because the current graph has no ID.');
2503
2482
  }
2504
2483
  const branchGraphOutputs = createGraphOutputsOverlay(this.#run.graphOutputs);
2505
- const processor = this.#constructChildInvocation({ kind: 'continuation', graph: branchPlan.graph });
2506
- processor.#abortOwnerOverride = this.#abortOwnerOverride ?? this;
2507
- processor.#sameGraphRunOwnerOverride = this.#sameGraphRunOwnerOverride ?? this;
2508
- processor.#suppressGraphLifecycleEvents = true;
2509
- processor.#sharedRunStateOverride = {
2510
- attachedNodeData: this.#run.attachedNodeData,
2511
- graphInputNodeValues: this.#run.graphInputNodeValues,
2484
+ const processor = this.#constructChildInvocation({
2485
+ kind: 'continuation',
2486
+ graph: branchPlan.graph,
2512
2487
  graphOutputs: branchGraphOutputs.view,
2513
- };
2488
+ });
2514
2489
  const branchNodeIds = new Set(branchPlan.graph.nodes.map((node) => node.id));
2515
2490
  const branchRunToNodeIds = this.runToNodeIds?.filter((nodeId) => branchNodeIds.has(nodeId));
2516
2491
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
2517
- processor.#executionIdentityOverride = {
2518
- rootRunId: this.#run.rootRunId,
2519
- graphRunId: this.#run.graphRunId,
2520
- parentGraphRunId: this.#run.parentGraphRunId,
2521
- };
2522
2492
  for (const [nodeId, outputs] of branchPlan.preloadedOutputs) {
2523
2493
  processor.preloadNodeData(nodeId, outputs);
2524
2494
  processor.#suppressedPreloadedNodeIds.add(nodeId);
@@ -3176,21 +3146,8 @@ export class GraphProcessor {
3176
3146
  kind: 'watch',
3177
3147
  graph: plan.graph,
3178
3148
  watchNodeId: plan.watchNode.id,
3179
- });
3180
- processor.#abortOwnerOverride = root;
3181
- processor.#suppressGraphPartialOutputs = true;
3182
- processor.#suppressGraphLifecycleEvents = true;
3183
- processor.#sharedRunStateOverride = {
3184
- // Repeated node IDs do not imply shared race/loop state between snapshots.
3185
- attachedNodeData: new Map(),
3186
- graphInputNodeValues: { ...this.#run.graphInputNodeValues },
3187
- graphOutputs: {},
3188
- };
3189
- processor.#executionIdentityOverride = {
3190
- rootRunId: root.#run.rootRunId,
3191
3149
  graphRunId: historyIteration.graphRunId,
3192
- parentGraphRunId: this.#run.graphRunId,
3193
- };
3150
+ });
3194
3151
  processor.#streamingWatchInvocation = {
3195
3152
  plan,
3196
3153
  historyIteration,
@@ -3538,8 +3495,8 @@ export class GraphProcessor {
3538
3495
  execution: parentExecution,
3539
3496
  });
3540
3497
  }
3541
- /** Common construction only. Aliases, execution identity and terminal commits
3542
- * remain explicit in each invocation path rather than a matrix of flags. */
3498
+ /** One construction boundary applies the discriminated ownership contract;
3499
+ * scheduling and terminal commits remain with their respective branch owner. */
3543
3500
  #constructChildInvocation(invocation) {
3544
3501
  const ordinary = invocation.kind === 'subgraph';
3545
3502
  const processor = new GraphProcessor(ordinary ? invocation.project : this.#project, ordinary ? invocation.graphId : invocation.graph.metadata.id, this.#registry, this.#includeTrace, {
@@ -3579,6 +3536,27 @@ export class GraphProcessor {
3579
3536
  processor.#graphCallPath = this.#graphCallPath;
3580
3537
  processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3581
3538
  processor.#executor = this.#executor;
3539
+ if (!ordinary) {
3540
+ const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
3541
+ const ownership = resolveChildInvocationOwnership(invocation, {
3542
+ parent: this,
3543
+ root: this.getRootProcessor(),
3544
+ abortOwner: this.#abortOwnerOverride ?? this,
3545
+ sameGraphOwner,
3546
+ rootGraphOrigin: !sameGraphOwner.#isSubProcessor,
3547
+ run: this.#run,
3548
+ rootIdentity: this.getRootProcessor().#run,
3549
+ sameGraphIdentity: sameGraphOwner.#run,
3550
+ newGraphRunId: () => nanoid(),
3551
+ });
3552
+ processor.#parent = ownership.parent;
3553
+ processor.#abortOwnerOverride = ownership.abortOwner;
3554
+ processor.#sameGraphRunOwnerOverride = ownership.sameGraphOwner;
3555
+ processor.#suppressGraphPartialOutputs = ownership.suppressPartialOutputs;
3556
+ processor.#suppressGraphLifecycleEvents = ownership.suppressLifecycle;
3557
+ processor.#sharedRunStateOverride = ownership.state;
3558
+ processor.#executionIdentityOverride = ownership.identity;
3559
+ }
3582
3560
  return processor;
3583
3561
  }
3584
3562
  #wireChildEvents(processor, owner, options = {}) {
@@ -1,6 +1,6 @@
1
1
  import {} from './NodeBase.js';
2
2
  import { PluginNodeImplClass } from './NodeImpl.js';
3
- import { mapValues, values } from '../utils/typeSafety.js';
3
+ import { values } from '../utils/typeSafety.js';
4
4
  import {} from './RivetPlugin.js';
5
5
  import {} from './RivetUIContext.js';
6
6
  export class NodeRegistration {
@@ -77,10 +77,6 @@ export class NodeRegistration {
77
77
  get #dynamicImpls() {
78
78
  return this.#implsMap;
79
79
  }
80
- get #dynamicDisplayNames() {
81
- const displayNameMap = mapValues(this.#infos, (info) => info.displayName);
82
- return displayNameMap;
83
- }
84
80
  registerPlugin(plugin) {
85
81
  if (plugin.register) {
86
82
  plugin.register((definition) => this.registerPluginNode(definition, plugin));
@@ -118,7 +114,7 @@ export class NodeRegistration {
118
114
  return this.#getInfo(type).displayName;
119
115
  }
120
116
  getDynamicDisplayName(type) {
121
- const displayName = this.#dynamicDisplayNames[type];
117
+ const displayName = Object.hasOwn(this.#infos, type) ? this.#infos[type].displayName : undefined;
122
118
  if (!displayName) {
123
119
  throw new Error(`Unknown node type: ${type}`);
124
120
  }
@@ -0,0 +1,78 @@
1
+ import { inspectClassifierImage } from './images.js';
2
+ /** Native Model API slugs, not Hugging Face or gateway IDs. Verified 2026-10-26. */
3
+ export const BASETEN_DECISION_MODELS = [
4
+ 'decision-models/baseten-elephant-9b-latest',
5
+ 'decision-models/baseten-mammoth-27b-latest',
6
+ ];
7
+ /** Baseten uses inline user-message image parts, never top-level images/placeholders. */
8
+ export function basetenDecisionState(state) {
9
+ if (state.kind === 'json')
10
+ return state.value;
11
+ return {
12
+ messages: state.messages.map(({ parts }) => ({
13
+ role: 'user',
14
+ content: parts.map((part) => part.type === 'text'
15
+ ? { type: 'text', text: part.text }
16
+ : { type: 'image_url', image_url: { url: part.dataUrl } }),
17
+ })),
18
+ };
19
+ }
20
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
21
+ /** https://docs.baseten.co/reference/inference-api/system-one */
22
+ export function assertBasetenDecisionLimits({ model, state, questions }, check) {
23
+ let options = 0;
24
+ for (const question of questions) {
25
+ check();
26
+ options += question.type === 'noul' ? 2 : Object.keys(question.criteria ?? {}).length;
27
+ }
28
+ if (options > 512)
29
+ throw new Error('Baseten supports at most 512 options across all questions; Noul counts as two.');
30
+ const wire = basetenDecisionState(state);
31
+ let characters = 0, images = 0;
32
+ const text = (value) => {
33
+ for (const _character of value) {
34
+ check();
35
+ if (++characters > 50000)
36
+ throw new Error('Baseten rendered State must fit within 50,000 characters.');
37
+ }
38
+ };
39
+ if (!record(wire) || !Array.isArray(wire.messages)) {
40
+ text(typeof wire === 'string' ? wire : JSON.stringify(wire));
41
+ return;
42
+ }
43
+ // Explicit JSON conversation State is interpreted natively by Baseten too.
44
+ // Inspect it as well, so JSON cannot bypass the same model/image limits.
45
+ for (const message of wire.messages) {
46
+ check();
47
+ if (!record(message) || (message.role !== 'user' && message.role !== 'assistant'))
48
+ throw new Error('Baseten State messages must have user or assistant roles.');
49
+ if (typeof message.content === 'string') {
50
+ text(message.content);
51
+ continue;
52
+ }
53
+ if (!Array.isArray(message.content))
54
+ throw new Error('Baseten message content must be text or content parts.');
55
+ for (const part of message.content) {
56
+ check();
57
+ if (!record(part))
58
+ throw new Error('Invalid Baseten State content part.');
59
+ if (part.type === 'text' && typeof part.text === 'string') {
60
+ text(part.text);
61
+ continue;
62
+ }
63
+ if (part.type !== 'image_url' || !record(part.image_url))
64
+ throw new Error('Baseten State supports text and image_url parts only.');
65
+ if (message.role !== 'user')
66
+ throw new Error('Baseten accepts images in user messages only.');
67
+ if (!BASETEN_DECISION_MODELS.some((id) => id === model))
68
+ throw new Error('Image support is not known for this Baseten model.');
69
+ if (++images > 4)
70
+ throw new Error('Baseten supports at most four images per request.');
71
+ if (part.image_url.detail !== undefined && part.image_url.detail !== 'auto')
72
+ throw new Error('Baseten image detail must be auto or omitted.');
73
+ const image = inspectClassifierImage(part.image_url.url, check);
74
+ if (!['image/png', 'image/jpeg', 'image/webp'].includes(image.mediaType))
75
+ throw new Error('Baseten accepts PNG, JPEG and WebP images, not GIF.');
76
+ }
77
+ }
78
+ }
@@ -22,6 +22,14 @@ export const PERPLEXITY_DEFAULT_CREDENTIAL_NAMES = {
22
22
  programmaticName: 'perplexityApiKey',
23
23
  environmentVariableName: 'PERPLEXITY_API_KEY',
24
24
  };
25
+ export const SUBQ_DEFAULT_CREDENTIAL_NAMES = {
26
+ programmaticName: 'subqApiKey',
27
+ environmentVariableName: 'SUBQ_API_KEY',
28
+ };
29
+ export const BASETEN_DEFAULT_CREDENTIAL_NAMES = {
30
+ programmaticName: 'basetenApiKey',
31
+ environmentVariableName: 'BASETEN_API_KEY',
32
+ };
25
33
  const programmaticNamePattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
26
34
  const environmentVariableNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
27
35
  export function isValidClassifierProgrammaticCredentialName(name) {
@@ -32,22 +40,22 @@ export function isValidClassifierEnvironmentCredentialName(name) {
32
40
  }
33
41
  export function normalizeClassifierCredentialNames(value, defaults = JEV_DEFAULT_CREDENTIAL_NAMES) {
34
42
  if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
35
- throw new Error('Classifier API key names must be an object.');
43
+ throw new Error('Decision AI API key names must be an object.');
36
44
  }
37
45
  const raw = value;
38
46
  if (raw?.programmaticName != null && typeof raw.programmaticName !== 'string') {
39
- throw new Error('Classifier programmatic API key name must be a string.');
47
+ throw new Error('Decision AI programmatic API key name must be a string.');
40
48
  }
41
49
  if (raw?.environmentVariableName != null && typeof raw.environmentVariableName !== 'string') {
42
- throw new Error('Classifier API key environment variable must be a string.');
50
+ throw new Error('Decision AI API key environment variable must be a string.');
43
51
  }
44
52
  const programmaticName = raw?.programmaticName?.trim() || defaults.programmaticName;
45
53
  const environmentVariableName = raw?.environmentVariableName?.trim() || defaults.environmentVariableName;
46
54
  if (!isValidClassifierProgrammaticCredentialName(programmaticName)) {
47
- throw new Error('Classifier programmatic API key name must be a JavaScript-style identifier without a leading digit.');
55
+ throw new Error('Decision AI programmatic API key name must be a JavaScript-style identifier without a leading digit.');
48
56
  }
49
57
  if (!isValidClassifierEnvironmentCredentialName(environmentVariableName)) {
50
- throw new Error('Classifier API key environment variable must contain letters, digits, and _ without a leading digit.');
58
+ throw new Error('Decision AI API key environment variable must contain letters, digits, and _ without a leading digit.');
51
59
  }
52
60
  return { programmaticName, environmentVariableName };
53
61
  }
@@ -66,11 +74,11 @@ export function isDefaultClassifierCredentialNames(names, defaults = JEV_DEFAULT
66
74
  export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, defaults, inputs, providerId, }) {
67
75
  if (apiKeySource === 'classifier-settings') {
68
76
  const read = (value, key) => value !== null && typeof value === 'object'
69
- ? classifierDataProperty(value, key, 'Classifier settings credentials')
77
+ ? classifierDataProperty(value, key, 'Decision AI settings credentials')
70
78
  : undefined;
71
79
  const saved = getNonEmptyString(read(read(read(context.settings, 'classifierProviders'), providerId), 'apiKey'));
72
80
  if (!saved)
73
- throw new ClassifierCredentialMissingError(`Classifier settings API key for ${providerId} is not set. No automatic fallback is used.`);
81
+ throw new ClassifierCredentialMissingError(`Decision AI settings API key for ${providerId} is not set. No automatic fallback is used.`);
74
82
  return saved;
75
83
  }
76
84
  if (apiKeySource === 'input') {
@@ -80,7 +88,7 @@ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, de
80
88
  return value;
81
89
  }
82
90
  if (apiKeySource !== undefined && apiKeySource !== 'configured')
83
- throw new Error('Unknown classifier API key source.');
91
+ throw new Error('Unknown Decision AI API key source.');
84
92
  const names = normalizeClassifierCredentialNames(apiKeyNames, defaults);
85
93
  const namedValue = resolveNamedClassifierApiKey(context, names, providerId === 'openai' && isDefaultClassifierCredentialNames(names, defaults));
86
94
  if (namedValue)
@@ -96,7 +104,7 @@ export function resolveClassifierApiKey({ apiKeyNames, apiKeySource, context, de
96
104
  return legacyValue;
97
105
  }
98
106
  }
99
- throw new ClassifierCredentialMissingError(`${providerId === 'jev' ? 'Jev' : 'Classifier'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Classifier.`);
107
+ throw new ClassifierCredentialMissingError(`${providerId === 'jev' ? 'Jev' : 'Decision AI'} API key is not set. Pass ${names.programmaticName}, configure ${names.environmentVariableName}, or set the configured key in Settings > Decision AI.`);
100
108
  }
101
109
  function resolveNamedClassifierApiKey(context, names, useLegacyOpenAIKey = false) {
102
110
  const programmaticValue = getNonEmptyString(context.settings?.[names.programmaticName]);
@@ -139,7 +139,7 @@ export function classifierImageFromText(value, check) {
139
139
  export function prepareClassifierImageText(value, check) {
140
140
  check?.();
141
141
  if (value.length > CLASSIFIER_LIMITS.requestBytes)
142
- throw new Error('Classifier image/text exceeds the 32 MiB input limit.');
142
+ throw new Error('Decision AI image/text exceeds the 32 MiB input limit.');
143
143
  if (value.startsWith('data:image/')) {
144
144
  return { ...inspectClassifierImage(value, check), dataUrl: value };
145
145
  }
@@ -163,14 +163,14 @@ export function assertClassifierImages(value, check) {
163
163
  }
164
164
  export function assertLiquidImageLimits(images, check) {
165
165
  if (images.length > 8)
166
- throw new Error('Liquid d1 State must contain at most 8 images.');
166
+ throw new Error('Liquid Decision AI State must contain at most 8 images.');
167
167
  let patches = 0;
168
168
  for (const { width, height } of images) {
169
169
  check?.();
170
170
  if (Math.max(width, height) / Math.min(width, height) > 100)
171
- throw new Error('Liquid d1 images must have an aspect ratio at most 100:1.');
171
+ throw new Error('Liquid Decision AI images must have an aspect ratio at most 100:1.');
172
172
  patches += Math.ceil(width / 32) * Math.ceil(height / 32);
173
173
  }
174
174
  if (patches > 10_000)
175
- throw new Error('Liquid d1 images must contain at most 10,000 patches of 32 by 32 pixels in total.');
175
+ throw new Error('Liquid Decision AI images must contain at most 10,000 patches of 32 by 32 pixels in total.');
176
176
  }
@@ -0,0 +1,45 @@
1
+ import { createQuestionMap } from './questions.js';
2
+ /** Experimental image contract, verified 2026-10-24: https://docs.typesafe.ai/images */
3
+ export const JEV_IMAGE_MODELS = ['jev-latest', 'jev-preview', 'jev-1.13.0', 'jev-1.14.0'];
4
+ /** https://docs.typesafe.ai/primitives/box — Box requires Jev 1.14, not 1.13. */
5
+ export const JEV_BOX_MODELS = ['jev-latest', 'jev-preview', 'jev-1.14.0'];
6
+ export function assertJevImageLimits(images, check) {
7
+ for (const { dataUrl, mediaType, width, height } of images) {
8
+ check();
9
+ if (mediaType !== 'image/png' && mediaType !== 'image/jpeg')
10
+ throw new Error('Jev images must be still PNG or JPEG. Convert other formats upstream.');
11
+ if (Math.min(width, height) < 280 || Math.max(width, height) > 1568)
12
+ throw new Error('Jev image width and height must each be between 280 and 1568 pixels. Resize upstream.');
13
+ const payload = dataUrl.slice(dataUrl.indexOf(',') + 1);
14
+ const bytes = (payload.length / 4) * 3 - (payload.endsWith('==') ? 2 : payload.endsWith('=') ? 1 : 0);
15
+ if (bytes > 16 * 1024 * 1024)
16
+ throw new Error('Jev image files must not exceed 16 MiB decoded.');
17
+ }
18
+ }
19
+ /** Jev substitutes opaque asset references, not Liquid's numbered image placeholders. */
20
+ export function createJevDecisionRequest({ model, state, questions, }) {
21
+ const references = new Map();
22
+ const assets = {};
23
+ const messagesText = (messages) => messages
24
+ .map(({ parts }) => parts
25
+ .map((part) => {
26
+ if (part.type === 'text')
27
+ return part.text;
28
+ let reference = references.get(part.dataUrl);
29
+ if (!reference) {
30
+ reference = globalThis.crypto.randomUUID();
31
+ references.set(part.dataUrl, reference);
32
+ assets[reference] = {
33
+ type: 'image',
34
+ format: part.dataUrl.startsWith('data:image/png;') ? 'png' : 'jpg',
35
+ data_base64: part.dataUrl.slice(part.dataUrl.indexOf(',') + 1),
36
+ };
37
+ }
38
+ return reference;
39
+ })
40
+ .join('\n'))
41
+ .join('\n\n');
42
+ const value = state.kind === 'json' ? state.value : messagesText(state.messages);
43
+ const questionMap = createQuestionMap(questions, (question) => question.instructionsMessages ? messagesText(question.instructionsMessages) : question.instructions);
44
+ return { model, state: value, questions: questionMap, ...(references.size ? { assets } : {}) };
45
+ }
@@ -8,7 +8,7 @@ export function classifierDataProperty(value, key, label = 'State') {
8
8
  }
9
9
  /** Snapshot only the selected port's wrapper; never read unrelated input getters. */
10
10
  export function classifierInputDataValue(inputs, port) {
11
- const label = `Classifier ${port} input`;
11
+ const label = `Decision AI ${port} input`;
12
12
  const input = classifierDataProperty(inputs, port, label);
13
13
  if (input === undefined)
14
14
  return undefined;
@@ -25,7 +25,7 @@ export function classifierPreparationCheck(signal, deadline, timeoutMs) {
25
25
  return () => {
26
26
  signal.throwIfAborted();
27
27
  if (Date.now() >= deadline)
28
- throw new Error(`Classifier preparation/request timed out${timeoutMs === undefined ? '' : ` after ${timeoutMs} ms`}.`);
28
+ throw new Error(`Decision AI preparation/request timed out${timeoutMs === undefined ? '' : ` after ${timeoutMs} ms`}.`);
29
29
  };
30
30
  }
31
31
  /** Bound expanded work before JSON serialization or image encoding, without reading getters. */
@@ -41,7 +41,7 @@ export class ClassifierValueBudget {
41
41
  constructor(check = () => { }, maxBytes = CLASSIFIER_LIMITS.requestBytes) {
42
42
  this.check = check;
43
43
  if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
44
- throw new ClassifierResourceLimitError('Classifier byte limit must be a positive safe integer.');
44
+ throw new ClassifierResourceLimitError('Decision AI byte limit must be a positive safe integer.');
45
45
  this.maxBytes = Math.min(maxBytes, CLASSIFIER_LIMITS.requestBytes);
46
46
  }
47
47
  get remainingBytes() {
@@ -56,7 +56,7 @@ export class ClassifierValueBudget {
56
56
  ? `${maxBytes / (1024 * 1024)} MiB`
57
57
  : `${maxBytes / 1_000_000} MB`
58
58
  : `${maxBytes}-byte`;
59
- throw new ClassifierResourceLimitError(`Classifier input exceeds the ${size} resource limit. Reduce input content or image size.`);
59
+ throw new ClassifierResourceLimitError(`Decision AI input exceeds the ${size} resource limit. Reduce input content or image size.`);
60
60
  }
61
61
  }
62
62
  string(text) {
@@ -90,9 +90,9 @@ export class ClassifierValueBudget {
90
90
  value(depth) {
91
91
  this.check();
92
92
  if (++this.values > CLASSIFIER_LIMITS.values)
93
- throw new ClassifierResourceLimitError('Classifier input has too many expanded values.');
93
+ throw new ClassifierResourceLimitError('Decision AI input has too many expanded values.');
94
94
  if (depth > CLASSIFIER_LIMITS.depth)
95
- throw new ClassifierResourceLimitError('Classifier input exceeds the maximum nesting depth of 64.');
95
+ throw new ClassifierResourceLimitError('Decision AI input exceeds the maximum nesting depth of 64.');
96
96
  }
97
97
  inspect(value, json) {
98
98
  const startBytes = this.bytes;
@@ -124,13 +124,13 @@ export class ClassifierValueBudget {
124
124
  throw new Error(`${json.label} must not contain JSON serialization hooks.`);
125
125
  }
126
126
  if (path.has(item))
127
- throw new Error('Classifier input contains a circular reference.');
127
+ throw new Error('Decision AI input contains a circular reference.');
128
128
  path.add(item);
129
129
  this.add(2);
130
130
  const copy = json?.copy ? (Array.isArray(item) ? [] : {}) : undefined;
131
131
  if (Array.isArray(item)) {
132
132
  if (item.length > CLASSIFIER_LIMITS.values)
133
- throw new ClassifierResourceLimitError('Classifier input has too many expanded values.');
133
+ throw new ClassifierResourceLimitError('Decision AI input has too many expanded values.');
134
134
  for (let i = 0; i < item.length; i++) {
135
135
  if (i > 0)
136
136
  this.add(1);
@@ -149,7 +149,7 @@ export class ClassifierValueBudget {
149
149
  else {
150
150
  const keys = Object.keys(item);
151
151
  if (keys.length > CLASSIFIER_LIMITS.values)
152
- throw new ClassifierResourceLimitError('Classifier input has too many expanded values.');
152
+ throw new ClassifierResourceLimitError('Decision AI input has too many expanded values.');
153
153
  let index = 0;
154
154
  for (const key of keys) {
155
155
  // Omitted wire fields still cost preparation work and snapshot memory.
@@ -208,7 +208,7 @@ export function checkClassifierJsonWork(text, check, label = 'response') {
208
208
  quoted = true;
209
209
  else if (character === '{' || character === '[') {
210
210
  if (++depth > CLASSIFIER_LIMITS.depth)
211
- throw new ClassifierResourceLimitError(`Classifier ${label} exceeds the maximum nesting depth of 64.`);
211
+ throw new ClassifierResourceLimitError(`Decision AI ${label} exceeds the maximum nesting depth of 64.`);
212
212
  separators++;
213
213
  }
214
214
  else if (character === '}' || character === ']')
@@ -218,14 +218,14 @@ export function checkClassifierJsonWork(text, check, label = 'response') {
218
218
  // A conservative token guard bounds JSON.parse allocation. The exact
219
219
  // expanded-value guard runs on the parsed object afterward.
220
220
  if (separators > CLASSIFIER_LIMITS.values * 2)
221
- throw new ClassifierResourceLimitError(`Classifier ${label} has too many values.`);
221
+ throw new ClassifierResourceLimitError(`Decision AI ${label} has too many values.`);
222
222
  }
223
223
  }
224
224
  /** Consume decoded response bytes incrementally; Content-Length is not trusted. */
225
225
  export async function readClassifierResponse(response, signal, check = () => signal.throwIfAborted(), onBody) {
226
226
  const length = response.headers.get('content-length');
227
227
  if (length && Number(length) > CLASSIFIER_LIMITS.responseBytes)
228
- throw new ClassifierResourceLimitError('Classifier response exceeds the 8 MiB response limit.');
228
+ throw new ClassifierResourceLimitError('Decision AI response exceeds the 8 MiB response limit.');
229
229
  if (!response.body)
230
230
  return JSON.parse('');
231
231
  const reader = response.body.getReader();
@@ -241,7 +241,7 @@ export async function readClassifierResponse(response, signal, check = () => sig
241
241
  for (;;) {
242
242
  check();
243
243
  const { done, value } = await reader.read().catch((cause) => {
244
- throw new ClassifierResponseReadError('Classifier response body could not be read.', { cause });
244
+ throw new ClassifierResponseReadError('Decision AI response body could not be read.', { cause });
245
245
  });
246
246
  check();
247
247
  if (done)
@@ -249,7 +249,7 @@ export async function readClassifierResponse(response, signal, check = () => sig
249
249
  const chunk = classifierByteView(value);
250
250
  bytes += chunk.byteLength;
251
251
  if (bytes > CLASSIFIER_LIMITS.responseBytes)
252
- throw new ClassifierResourceLimitError('Classifier response exceeds the 8 MiB response limit.');
252
+ throw new ClassifierResourceLimitError('Decision AI response exceeds the 8 MiB response limit.');
253
253
  pending += decoder.decode(chunk, { stream: true });
254
254
  if (pending.length >= 64 * 1024) {
255
255
  text.push(pending);