@valerypopoff/rivet2-core 2.17.0 → 2.19.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 (115) hide show
  1. package/dist/cjs/bundle.cjs +3093 -1440
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +40 -4
  4. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  5. package/dist/cjs/serialization.cjs +1880 -0
  6. package/dist/cjs/serialization.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs +168 -6
  8. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  9. package/dist/esm/api/processSettings.js +1 -0
  10. package/dist/esm/exports.js +2 -0
  11. package/dist/esm/model/AgentResponseTrace.js +99 -34
  12. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  13. package/dist/esm/model/DataValue.js +11 -2
  14. package/dist/esm/model/GlobalVariables.js +2 -1
  15. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  16. package/dist/esm/model/GraphExecutionState.js +81 -0
  17. package/dist/esm/model/GraphProcessor.js +621 -942
  18. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  19. package/dist/esm/model/Nodes.js +5 -0
  20. package/dist/esm/model/ProjectBundle.js +23 -10
  21. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  22. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  23. package/dist/esm/model/SubprocessorBridge.js +125 -87
  24. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  25. package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
  26. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  27. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  28. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  29. package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
  30. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  31. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  32. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
  33. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  34. package/dist/esm/model/chat-v2/llmChatV2Body.js +2 -2
  35. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  36. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  37. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +18 -8
  38. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  39. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  40. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  41. package/dist/esm/model/chat-v2/llmProfile.js +2 -1
  42. package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
  43. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  44. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  45. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  46. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  47. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  48. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  49. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  50. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  51. package/dist/esm/model/classifier/credentials.js +13 -3
  52. package/dist/esm/model/classifier/limits.js +33 -3
  53. package/dist/esm/model/classifier/perplexity.js +63 -0
  54. package/dist/esm/model/classifier/profile.js +151 -0
  55. package/dist/esm/model/classifier/profileExecution.js +294 -0
  56. package/dist/esm/model/classifier/providers.js +217 -30
  57. package/dist/esm/model/classifier/state.js +4 -1
  58. package/dist/esm/model/classifier/types.js +11 -1
  59. package/dist/esm/model/nodeRunFailure.js +8 -1
  60. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  61. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +250 -59
  62. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  63. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  64. package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
  65. package/dist/esm/model/nodes/SubGraphNode.js +3 -0
  66. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  67. package/dist/esm/model/profileSuspensionHints.js +8 -0
  68. package/dist/esm/serialization.js +2 -0
  69. package/dist/esm/utils/coerceType.js +11 -1
  70. package/dist/esm/webAppRuntime.js +1 -0
  71. package/dist/types/exports.d.ts +2 -0
  72. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  73. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  74. package/dist/types/model/DataValue.d.ts +12 -8
  75. package/dist/types/model/ExecutorProtocol.d.ts +7 -0
  76. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  77. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  78. package/dist/types/model/GraphProcessor.d.ts +1 -0
  79. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  80. package/dist/types/model/Nodes.d.ts +7 -4
  81. package/dist/types/model/ProcessContext.d.ts +12 -3
  82. package/dist/types/model/ProjectBundle.d.ts +9 -4
  83. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  84. package/dist/types/model/RivetUIContext.d.ts +1 -1
  85. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  86. package/dist/types/model/Settings.d.ts +1 -0
  87. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  88. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  89. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  90. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  91. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  92. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  93. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
  94. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  95. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  96. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  97. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
  98. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  99. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  100. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  101. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  102. package/dist/types/model/classifier/credentials.d.ts +4 -0
  103. package/dist/types/model/classifier/limits.d.ts +4 -1
  104. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  105. package/dist/types/model/classifier/profile.d.ts +46 -0
  106. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  107. package/dist/types/model/classifier/providers.d.ts +32 -1
  108. package/dist/types/model/classifier/types.d.ts +9 -0
  109. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
  110. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  111. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  112. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  113. package/dist/types/serialization.d.ts +2 -0
  114. package/dist/types/webAppRuntime.d.ts +1 -0
  115. package/package.json +7 -1
@@ -0,0 +1,64 @@
1
+ /** Invocation-owned boundary resources; no scheduling or event-emission policy. */
2
+ export class GraphSchedulerBoundaryState {
3
+ streamingWatchPlansBySourceNodeId = new Map();
4
+ streamingWatchPlansByWatchNodeId = new Map();
5
+ streamingOutputWatches = new Map();
6
+ streamingCatchPlansBySourceNodeId = new Map();
7
+ streamingCatchTasks = new Set();
8
+ graphOutputPartialBindingsBySourceNodeId = new Map();
9
+ graphInputStreams = {};
10
+ callerInputStreams = new Map();
11
+ inputStreamRoutes = new Map();
12
+ streamCallerTasks = new Set();
13
+ inputStreamDisposers = [];
14
+ pendingGraphInputFinals = new Map();
15
+ streamingWatchFailures = [];
16
+ resetTopology() {
17
+ this.streamingWatchPlansBySourceNodeId = new Map();
18
+ this.streamingWatchPlansByWatchNodeId = new Map();
19
+ this.streamingOutputWatches = new Map();
20
+ this.streamingCatchPlansBySourceNodeId = new Map();
21
+ this.streamingCatchTasks = new Set();
22
+ this.graphOutputPartialBindingsBySourceNodeId = new Map();
23
+ this.streamingWatchFailures = [];
24
+ }
25
+ /** Called after invocation initialization, before subscriptions can be admitted. */
26
+ initializeInputStreams(streams = {}) {
27
+ this.graphInputStreams = streams;
28
+ this.callerInputStreams = new Map();
29
+ this.inputStreamRoutes = new Map();
30
+ this.streamCallerTasks = new Set();
31
+ this.inputStreamDisposers = [];
32
+ this.pendingGraphInputFinals = new Map();
33
+ }
34
+ /** Release every subscription/relay, even if one host-provided disposer fails. */
35
+ releaseInputStreams() {
36
+ const failures = [];
37
+ const release = (operation) => {
38
+ try {
39
+ operation();
40
+ }
41
+ catch (error) {
42
+ failures.push(error);
43
+ }
44
+ };
45
+ for (const dispose of this.inputStreamDisposers.splice(0))
46
+ release(dispose);
47
+ this.pendingGraphInputFinals.clear();
48
+ for (const streams of this.callerInputStreams.values()) {
49
+ for (const relay of Object.values(streams))
50
+ release(() => relay.finish({ error: new Error('Graph input stream owner finished') }));
51
+ }
52
+ this.callerInputStreams.clear();
53
+ this.inputStreamRoutes.clear();
54
+ this.graphInputStreams = {};
55
+ if (failures.length)
56
+ throw new AggregateError(failures, 'Graph input stream cleanup failed');
57
+ }
58
+ async drainCatchTasks(waitForQueue) {
59
+ while (this.streamingCatchTasks.size > 0) {
60
+ await Promise.all([...this.streamingCatchTasks]);
61
+ await waitForQueue();
62
+ }
63
+ }
64
+ }
@@ -227,6 +227,10 @@ export * from './nodes/NodePrefabInstanceNode.js';
227
227
  import { classifierQuestionNode } from './nodes/ClassifierQuestionNode.js';
228
228
  export * from './nodes/ClassifierQuestionNode.js';
229
229
  import { classifierEvaluateNode } from './nodes/ClassifierEvaluateNode.js';
230
+ import { classifierProfileNode } from './nodes/ClassifierProfileNode.js';
231
+ export * from './nodes/ClassifierProfileNode.js';
232
+ export * from './classifier/profile.js';
233
+ export { classifierFailureKinds } from './classifier/types.js';
230
234
  export * from './nodes/ClassifierEvaluateNode.js';
231
235
  export const registerBuiltInNodes = (registry) => {
232
236
  return registry
@@ -342,6 +346,7 @@ export const registerBuiltInNodes = (registry) => {
342
346
  .register(referencedGraphAliasNode)
343
347
  .register(classifierQuestionNode)
344
348
  .register(classifierEvaluateNode)
349
+ .register(classifierProfileNode)
345
350
  .register(nodePrefabInstanceNode);
346
351
  };
347
352
  let globalRivetNodeRegistry = registerBuiltInNodes(new NodeRegistration());
@@ -11,6 +11,7 @@ export class ProjectBundleError extends Error {
11
11
  }
12
12
  export const PROJECT_BUNDLE_MANIFEST = 'rivet-bundle.json';
13
13
  export const PROJECT_BUNDLE_MAX_ARTIFACTS = 256;
14
+ export const PROJECT_BUNDLE_MAX_MANIFEST_BYTES = 1024 * 1024;
14
15
  export function projectBundleTargetKey(projectId, version) {
15
16
  return JSON.stringify([projectId, version]);
16
17
  }
@@ -145,7 +146,7 @@ export function validateProjectBundleManifest(value) {
145
146
  };
146
147
  const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) ? v : fail('expected object');
147
148
  const string = (v) => typeof v === 'string' && v.length > 0 && v.length <= 4096 ? v : fail('expected nonempty string');
148
- const array = (v) => Array.isArray(v) && v.length <= PROJECT_BUNDLE_MAX_ARTIFACTS ? v : fail('invalid or oversized list');
149
+ const array = (v, limit = PROJECT_BUNDLE_MAX_ARTIFACTS) => Array.isArray(v) && v.length <= limit ? v : fail('invalid or oversized list');
149
150
  const version = (v) => v === 'latest' || v === 'published' ? v : fail('unknown project version');
150
151
  const paths = new Set();
151
152
  const file = (v) => {
@@ -158,15 +159,20 @@ export function validateProjectBundleManifest(value) {
158
159
  paths.has(path.toLowerCase()))
159
160
  fail('unsafe or duplicate artifact path');
160
161
  paths.add(path.toLowerCase());
161
- if (!Number.isSafeInteger(obj.bytes) || obj.bytes < 0 || obj.bytes > 64 * 1024 * 1024)
162
- fail('invalid artifact size (maximum 64 MiB per file)');
163
- if (typeof obj.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(obj.sha256))
164
- fail('invalid checksum');
165
- return { path, bytes: obj.bytes, sha256: obj.sha256 };
162
+ // Old bundles carry export-time sizes/hashes. Ignore them: edited files are
163
+ // supported, and the loader enforces resource limits against actual bytes.
164
+ return { path };
166
165
  };
167
166
  const obj = object(value);
168
- if (obj.format !== 'rivet-project-bundle' || obj.schemaVersion !== 1 || obj.requiredLoaderVersion !== 1)
167
+ if (obj.format !== 'rivet-project-bundle' ||
168
+ obj.schemaVersion !== 1 ||
169
+ (obj.requiredLoaderVersion !== 1 && obj.requiredLoaderVersion !== 2 && obj.requiredLoaderVersion !== 3))
169
170
  fail('unsupported format or loader version; update @valerypopoff/rivet2-node');
171
+ const versionPolicy = obj.versionPolicy === undefined ? undefined : version(obj.versionPolicy);
172
+ if (versionPolicy && obj.requiredLoaderVersion !== 3)
173
+ fail('version selection requires loader version 3');
174
+ if (obj.requiredLoaderVersion === 3 && !versionPolicy)
175
+ fail('loader version 3 requires a version selection');
170
176
  const artifacts = array(obj.artifacts).map((v) => {
171
177
  const a = object(v);
172
178
  return {
@@ -184,14 +190,20 @@ export function validateProjectBundleManifest(value) {
184
190
  fail('empty or duplicate artifacts');
185
191
  if (new Set(artifacts.map((a) => projectBundleTargetKey(a.projectId, a.version))).size !== artifacts.length)
186
192
  fail('duplicate project/version artifacts');
193
+ if (versionPolicy && new Set(artifacts.map((a) => a.projectId)).size !== artifacts.length)
194
+ fail('version-selected bundles must contain one artifact per project');
195
+ if (versionPolicy === 'latest' && artifacts.some((a) => a.version !== 'latest'))
196
+ fail('latest version policy contains a published artifact');
187
197
  const rootArtifact = string(obj.rootArtifact);
188
198
  if (!byId.has(rootArtifact))
189
199
  fail('missing root artifact');
190
200
  const targetKeys = new Set(), referenceIds = new Set();
191
- const targets = array(obj.targets).map((v) => {
201
+ // A version-selected artifact has both latest and published bindings. The
202
+ // project limit must not accidentally halve when those aliases are emitted.
203
+ const targets = array(obj.targets, PROJECT_BUNDLE_MAX_ARTIFACTS * 2).map((v) => {
192
204
  const t = object(v), projectId = string(t.projectId), selectedVersion = version(t.version), artifact = string(t.artifact);
193
205
  const key = projectBundleTargetKey(projectId, selectedVersion), a = byId.get(artifact);
194
- if (targetKeys.has(key) || !a || a.projectId !== projectId || a.version !== selectedVersion)
206
+ if (targetKeys.has(key) || !a || a.projectId !== projectId || (!versionPolicy && a.version !== selectedVersion))
195
207
  fail('invalid or duplicate target binding');
196
208
  targetKeys.add(key);
197
209
  return { projectId, version: selectedVersion, artifact };
@@ -224,7 +236,8 @@ export function validateProjectBundleManifest(value) {
224
236
  return {
225
237
  format: 'rivet-project-bundle',
226
238
  schemaVersion: 1,
227
- requiredLoaderVersion: 1,
239
+ requiredLoaderVersion: obj.requiredLoaderVersion,
240
+ ...(versionPolicy ? { versionPolicy } : {}),
228
241
  exportingRuntimeVersion: string(obj.exportingRuntimeVersion),
229
242
  rootArtifact,
230
243
  artifacts,
@@ -0,0 +1,54 @@
1
+ import { InMemoryDatasetProvider } from '../integrations/DatasetProvider.js';
2
+ import { ProjectBundleError, projectBundleTargetKey, validateProjectBundleProjects, } from './ProjectBundle.js';
3
+ /** One isolated dependency/data universe per run. The visible entry project may override its disk copy. */
4
+ export function createProjectBundleRuntime(manifest, snapshots, options = {}) {
5
+ const entryId = options.artifactId ?? manifest.rootArtifact;
6
+ const entry = manifest.artifacts.find((artifact) => artifact.id === entryId);
7
+ if (!entry)
8
+ throw new ProjectBundleError('The selected project is not a member of this bundle.');
9
+ if (options.project && options.project.metadata.id !== entry.projectId)
10
+ throw new ProjectBundleError('The open project identity no longer matches its bundle entry.');
11
+ const runtime = new Map(manifest.artifacts.map((artifact) => {
12
+ const snapshot = snapshots.get(artifact.id);
13
+ if (!snapshot)
14
+ throw new ProjectBundleError(`Bundle is missing artifact ${artifact.id}.`);
15
+ const project = structuredClone(artifact.id === entryId && options.project ? options.project : snapshot.project);
16
+ return [
17
+ artifact.id,
18
+ {
19
+ project,
20
+ sourceProjectPath: snapshot.sourceProjectPath,
21
+ datasetProvider: artifact.id === entryId && options.datasetProvider
22
+ ? options.datasetProvider
23
+ : new InMemoryDatasetProvider(structuredClone(snapshot.datasets)),
24
+ },
25
+ ];
26
+ }));
27
+ validateProjectBundleProjects(manifest, new Map([...runtime].map(([id, snapshot]) => [id, snapshot.project])));
28
+ const targets = new Map(manifest.targets.map((target) => [projectBundleTargetKey(target.projectId, target.version), target.artifact]));
29
+ const references = new Map(manifest.references.map((reference) => [reference.projectId, reference.artifact]));
30
+ const providers = new Map([...runtime.values()].map((snapshot) => [snapshot.project, snapshot.datasetProvider]));
31
+ const root = runtime.get(entryId);
32
+ return {
33
+ project: root.project,
34
+ projectPath: root.sourceProjectPath,
35
+ datasetProvider: root.datasetProvider,
36
+ projectReferenceLoader: {
37
+ getDatasetProvider: (project) => providers.get(project),
38
+ async loadProject(_path, reference) {
39
+ const id = references.get(reference.id);
40
+ if (!id)
41
+ throw new ProjectBundleError(`Bundle has no reference binding for ${reference.id}.`);
42
+ return runtime.get(id).project;
43
+ },
44
+ },
45
+ subgraphProjectLoader: {
46
+ async loadTarget(target) {
47
+ const id = targets.get(projectBundleTargetKey(target.projectId, target.version));
48
+ if (!id)
49
+ throw new ProjectBundleError(`Bundle has no target binding for ${target.projectId}:${target.version}.`);
50
+ return runtime.get(id);
51
+ },
52
+ },
53
+ };
54
+ }
@@ -0,0 +1,233 @@
1
+ function indexConnections(connections) {
2
+ const outgoingByNodeId = new Map();
3
+ const incomingByNodeId = new Map();
4
+ for (const connection of connections) {
5
+ const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
6
+ outgoing.push(connection);
7
+ outgoingByNodeId.set(connection.outputNodeId, outgoing);
8
+ const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
9
+ incoming.push(connection);
10
+ incomingByNodeId.set(connection.inputNodeId, incoming);
11
+ }
12
+ return { outgoingByNodeId, incomingByNodeId };
13
+ }
14
+ export function getAsyncBranchWatchViolation(triggerNode, enclosingWatchNode) {
15
+ if (!enclosingWatchNode)
16
+ return undefined;
17
+ return new Error(`Start Async Branch "${triggerNode.title}" cannot run inside Watch Streaming Output "${enclosingWatchNode.title}". ` +
18
+ 'A Watch invocation must keep all work within the Watch scheduler. Move Start Async Branch after Stop Watching Streaming Output, or run the work directly inside the watched branch.');
19
+ }
20
+ export function* planStreamingWatchTopology(options) {
21
+ const connections = options.connections;
22
+ const { outgoingByNodeId, incomingByNodeId } = indexConnections(connections);
23
+ const relevantNodeIds = options.relevantNodeIds;
24
+ const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
25
+ for (const watchNode of Object.values(options.nodesById)) {
26
+ if (watchNode.type !== 'watchStreamingOutput' || watchNode.disabled || !isRelevant(watchNode.id)) {
27
+ continue;
28
+ }
29
+ if (watchNode.id === options.consumedWatchNodeId) {
30
+ continue;
31
+ }
32
+ const enclosingWatchInvocation = options.enclosingWatchNode;
33
+ if (enclosingWatchInvocation) {
34
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run inside Watch Streaming Output ` +
35
+ `"${enclosingWatchInvocation.title}". A Watch branch cannot contain another Watch, including through Subgraph.`);
36
+ }
37
+ if (options.preloadedNodes.has(watchNode.id)) {
38
+ throw new Error(`Cannot preload ${watchNode.title} because a streaming boundary must be scheduled. ` +
39
+ "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
40
+ }
41
+ const incoming = incomingByNodeId.get(watchNode.id) ?? [];
42
+ if (incoming.length === 0) {
43
+ // An unattached Watch is an ordinary in-progress authoring state. Keep
44
+ // it dormant rather than making an incomplete canvas fail to run.
45
+ yield { kind: 'dormant', watchNode };
46
+ continue;
47
+ }
48
+ if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
49
+ throw new Error(`Watch Streaming Output "${watchNode.title}" must have exactly one Streaming Output input connection.`);
50
+ }
51
+ const sourceConnection = incoming[0];
52
+ const sourceNode = options.nodesById[sourceConnection.outputNodeId];
53
+ if (!sourceNode || sourceNode.disabled || !isRelevant(sourceNode.id)) {
54
+ throw new Error(`Watch Streaming Output "${watchNode.title}" has no runnable streaming source.`);
55
+ }
56
+ if (sourceNode.isSplitRun) {
57
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot watch split-run node "${sourceNode.title}". ` +
58
+ 'Assemble a single streaming value before the watch boundary.');
59
+ }
60
+ const branchNodeIds = new Set();
61
+ const pendingNodeIds = (outgoingByNodeId.get(watchNode.id) ?? [])
62
+ .map((connection) => connection.inputNodeId)
63
+ .filter(isRelevant);
64
+ let stopNodeId;
65
+ while (pendingNodeIds.length > 0) {
66
+ const nodeId = pendingNodeIds.pop();
67
+ if (nodeId === watchNode.id) {
68
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot reconnect to itself.`);
69
+ }
70
+ if (branchNodeIds.has(nodeId)) {
71
+ continue;
72
+ }
73
+ const node = options.nodesById[nodeId];
74
+ if (!node || !isRelevant(nodeId)) {
75
+ continue;
76
+ }
77
+ if (node.disabled) {
78
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot include disabled node "${node.title}".`);
79
+ }
80
+ if (node.type === 'watchStreamingOutput') {
81
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain another Watch Streaming Output node.`);
82
+ }
83
+ if (node.type === 'catchStreamingChunks') {
84
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Catch streaming chunks "${node.title}". ` +
85
+ 'Put Catch streaming chunks outside the repeated Watch branch.');
86
+ }
87
+ if (node.type === 'graphOutput') {
88
+ throw new Error(`Watch Streaming Output "${watchNode.title}" must reach Stop Watching Streaming Output before Graph Output "${node.title}".`);
89
+ }
90
+ if (node.type === 'startBackgroundBranch') {
91
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Start Async Branch. ` +
92
+ 'Keep watched work in the bounded watch branch instead.');
93
+ }
94
+ branchNodeIds.add(nodeId);
95
+ if (node.type === 'stopWatchingStreamingOutput') {
96
+ if (stopNodeId && stopNodeId !== nodeId) {
97
+ throw new Error(`Watch Streaming Output "${watchNode.title}" must have one Stop Watching Streaming Output boundary.`);
98
+ }
99
+ stopNodeId = nodeId;
100
+ continue;
101
+ }
102
+ for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
103
+ if (isRelevant(connection.inputNodeId)) {
104
+ pendingNodeIds.push(connection.inputNodeId);
105
+ }
106
+ }
107
+ }
108
+ if (branchNodeIds.size === 0) {
109
+ // Source -> Watch is also a useful intermediate authoring state. There
110
+ // is no downstream work to schedule yet, so do not create a coordinator.
111
+ yield { kind: 'dormant', watchNode };
112
+ continue;
113
+ }
114
+ if (stopNodeId) {
115
+ const reentry = (outgoingByNodeId.get(stopNodeId) ?? []).find((connection) => connection.inputNodeId === watchNode.id || branchNodeIds.has(connection.inputNodeId));
116
+ if (reentry) {
117
+ const stopNode = options.nodesById[stopNodeId];
118
+ throw new Error(`Stop Watching Streaming Output "${stopNode.title}" cannot reconnect to its own Watch Streaming Output branch. ` +
119
+ 'Connect it only to ordinary downstream execution.');
120
+ }
121
+ }
122
+ for (const nodeId of branchNodeIds) {
123
+ const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== watchNode.id && !branchNodeIds.has(connection.outputNodeId));
124
+ if (externalInput) {
125
+ const node = options.nodesById[nodeId];
126
+ const externalNode = options.nodesById[externalInput.outputNodeId];
127
+ throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run "${node.title}" because it also depends on ` +
128
+ `"${externalNode?.title ?? externalInput.outputNodeId}" outside the watch branch. ` +
129
+ 'Assemble every required value inside the watch boundary.');
130
+ }
131
+ }
132
+ const graph = {
133
+ metadata: options.graph.metadata ? { ...options.graph.metadata } : undefined,
134
+ nodes: options.executionNodes.filter((node) => node.id === watchNode.id || branchNodeIds.has(node.id)),
135
+ connections: connections.filter((connection) => connection.inputNodeId === watchNode.id ||
136
+ (branchNodeIds.has(connection.inputNodeId) &&
137
+ (connection.outputNodeId === watchNode.id || branchNodeIds.has(connection.outputNodeId)))),
138
+ };
139
+ yield {
140
+ kind: 'watch',
141
+ graph,
142
+ watchNode,
143
+ branchNodeIds,
144
+ sourceNodeId: sourceNode.id,
145
+ sourceOutputId: sourceConnection.outputId,
146
+ stopNodeId,
147
+ includeAllStreamedOutput: connections.some((connection) => connection.outputNodeId === watchNode.id &&
148
+ connection.outputId === 'allStreamedOutput' &&
149
+ branchNodeIds.has(connection.inputNodeId)),
150
+ };
151
+ }
152
+ }
153
+ export function* planAsyncBranchTopology(options) {
154
+ const connections = options.connections;
155
+ const { outgoingByNodeId, incomingByNodeId } = indexConnections(connections);
156
+ const relevantNodeIds = options.relevantNodeIds;
157
+ const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
158
+ for (const triggerNode of Object.values(options.nodesById)) {
159
+ // Input anchors describe the consumed trigger's ports, not executable work.
160
+ // A variadic anchor may itself be an outer async trigger.
161
+ if (options.inputAnchorNodeIds?.has(triggerNode.id))
162
+ continue;
163
+ if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRelevant(triggerNode.id)) {
164
+ continue;
165
+ }
166
+ if (triggerNode.id !== options.consumedTriggerNodeId && options.preloadedNodes.has(triggerNode.id)) {
167
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot use preloaded outputs because replaying it could repeat async side effects.`);
168
+ }
169
+ const nodeIds = new Set();
170
+ const pendingNodeIds = (outgoingByNodeId.get(triggerNode.id) ?? [])
171
+ .map((connection) => connection.inputNodeId)
172
+ .filter(isRelevant);
173
+ while (pendingNodeIds.length > 0) {
174
+ const nodeId = pendingNodeIds.pop();
175
+ if (nodeId === triggerNode.id) {
176
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot be part of a cycle or reconnect to its own inputs.`);
177
+ }
178
+ if (nodeIds.has(nodeId)) {
179
+ continue;
180
+ }
181
+ const node = options.nodesById[nodeId];
182
+ if (!node) {
183
+ continue;
184
+ }
185
+ if (node.disabled) {
186
+ continue;
187
+ }
188
+ if (node.type === 'graphOutput') {
189
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain Graph Output node "${node.title}". Async branches are side-effect-only.`);
190
+ }
191
+ nodeIds.add(nodeId);
192
+ for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
193
+ if (isRelevant(connection.inputNodeId)) {
194
+ pendingNodeIds.push(connection.inputNodeId);
195
+ }
196
+ }
197
+ }
198
+ for (const nodeId of nodeIds) {
199
+ const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== triggerNode.id && !nodeIds.has(connection.outputNodeId));
200
+ if (externalInput) {
201
+ const node = options.nodesById[nodeId];
202
+ const externalNode = options.nodesById[externalInput.outputNodeId];
203
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot run "${node.title}" because it also depends on ` +
204
+ `"${externalNode?.title ?? externalInput.outputNodeId}" outside the async branch. Assemble all required values before the async trigger.`);
205
+ }
206
+ }
207
+ if (nodeIds.size === 0) {
208
+ continue;
209
+ }
210
+ const managedAsyncBranchWatchViolation = getAsyncBranchWatchViolation(triggerNode, options.enclosingWatchNode);
211
+ if (managedAsyncBranchWatchViolation) {
212
+ throw managedAsyncBranchWatchViolation;
213
+ }
214
+ const preloadedNodeId = [...nodeIds].find((nodeId) => options.preloadedNodes.has(nodeId));
215
+ if (preloadedNodeId) {
216
+ const preloadedNode = options.nodesById[preloadedNodeId];
217
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain preloaded node "${preloadedNode.title}". Preloading an async descendant would bypass the trigger boundary.`);
218
+ }
219
+ // The node derives its variadic output definitions from connected inputs.
220
+ // Retain shallow input anchors in the slice even though the trigger itself is preloaded.
221
+ const triggerInputConnections = connections.filter((connection) => connection.inputNodeId === triggerNode.id);
222
+ const inputAnchorNodeIds = new Set(triggerInputConnections.map((connection) => connection.outputNodeId));
223
+ const includedNodeIds = new Set([triggerNode.id, ...nodeIds, ...inputAnchorNodeIds]);
224
+ const graph = {
225
+ metadata: options.graph.metadata ? { ...options.graph.metadata } : undefined,
226
+ nodes: options.executionNodes.filter((node) => includedNodeIds.has(node.id)),
227
+ connections: connections.filter((connection) => connection.inputNodeId === triggerNode.id ||
228
+ (nodeIds.has(connection.inputNodeId) &&
229
+ (connection.outputNodeId === triggerNode.id || nodeIds.has(connection.outputNodeId)))),
230
+ };
231
+ yield { triggerNode, graph, nodeIds };
232
+ }
233
+ }