@valerypopoff/rivet2-core 2.6.0 → 2.8.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.
- package/dist/cjs/bundle.cjs +2779 -780
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/interpolationRuntime.cjs +7 -3
- package/dist/cjs/interpolationRuntime.cjs.map +2 -2
- package/dist/esm/api/createProcessor.js +3 -0
- package/dist/esm/exports.js +2 -1
- package/dist/esm/integrations/CodeRunner.js +6 -2
- package/dist/esm/integrations/mcp/MCPBase.js +2 -1
- package/dist/esm/model/ExecutionOutputClone.js +46 -0
- package/dist/esm/model/GlobalVariables.js +452 -0
- package/dist/esm/model/GraphBoundaryEffects.js +12 -4
- package/dist/esm/model/GraphProcessor.js +838 -41
- package/dist/esm/model/Nodes.js +6 -0
- package/dist/esm/model/ProcessContextBuilder.js +3 -1
- package/dist/esm/model/ProjectReferenceLoader.js +36 -1
- package/dist/esm/model/RecordingPlayer.js +39 -4
- package/dist/esm/model/StreamingOutputWatch.js +262 -0
- package/dist/esm/model/StreamingOutputWatchHistory.js +162 -0
- package/dist/esm/model/SubprocessorBridge.js +29 -19
- package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +3 -42
- package/dist/esm/model/nodes/ChatLoopNode.js +8 -4
- package/dist/esm/model/nodes/CodeNewNode.js +5 -2
- package/dist/esm/model/nodes/ExpressionNode.js +5 -2
- package/dist/esm/model/nodes/ExtractObjectPathNode.js +4 -4
- package/dist/esm/model/nodes/GraphOutputNode.js +13 -8
- package/dist/esm/model/nodes/LoopControllerNode.js +6 -4
- package/dist/esm/model/nodes/MCPGetPromptNode.js +2 -1
- package/dist/esm/model/nodes/MCPToolCallNode.js +2 -1
- package/dist/esm/model/nodes/ObjectNode.js +5 -3
- package/dist/esm/model/nodes/PromptNode.js +5 -2
- package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +9 -1
- package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +48 -0
- package/dist/esm/model/nodes/SubGraphNode.js +11 -1
- package/dist/esm/model/nodes/TextNode.js +5 -2
- package/dist/esm/model/nodes/ToTreeNode.js +10 -3
- package/dist/esm/model/nodes/ToolNode.js +5 -2
- package/dist/esm/model/nodes/WatchStreamingOutputNode.js +126 -0
- package/dist/esm/model/nodes/jsListCallbackHelpers.js +7 -1
- package/dist/esm/model/nodes/jsValueInterpolation.js +21 -4
- package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +2 -1
- package/dist/esm/recording/ExecutionRecorder.js +18 -8
- package/dist/esm/utils/interpolation.js +35 -2
- package/dist/esm/utils/serialization/serializationUtils.js +9 -0
- package/dist/esm/utils/serialization/serialization_v4.js +7 -0
- package/dist/types/exports.d.ts +2 -1
- package/dist/types/integrations/CodeRunner.d.ts +3 -3
- package/dist/types/integrations/CodeRunnerOptions.d.ts +5 -0
- package/dist/types/integrations/mcp/MCPBase.d.ts +1 -1
- package/dist/types/model/ExecutionOutputClone.d.ts +11 -0
- package/dist/types/model/ExecutorProtocol.d.ts +9 -2
- package/dist/types/model/GlobalVariables.d.ts +29 -0
- package/dist/types/model/GraphBoundaryEffects.d.ts +7 -1
- package/dist/types/model/GraphProcessor.d.ts +49 -3
- package/dist/types/model/Nodes.d.ts +4 -2
- package/dist/types/model/ProcessContext.d.ts +14 -0
- package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
- package/dist/types/model/Project.d.ts +7 -1
- package/dist/types/model/ProjectReferenceLoader.d.ts +15 -1
- package/dist/types/model/StreamingOutputWatch.d.ts +74 -0
- package/dist/types/model/StreamingOutputWatchHistory.d.ts +60 -0
- package/dist/types/model/SubprocessorBridge.d.ts +2 -0
- package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -3
- package/dist/types/model/nodes/ChatLoopNode.d.ts +2 -0
- package/dist/types/model/nodes/ExtractObjectPathNode.d.ts +1 -1
- package/dist/types/model/nodes/GraphOutputNode.d.ts +8 -1
- package/dist/types/model/nodes/LoopControllerNode.d.ts +2 -0
- package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
- package/dist/types/model/nodes/StopWatchingStreamingOutputNode.d.ts +14 -0
- package/dist/types/model/nodes/ToTreeNode.d.ts +5 -1
- package/dist/types/model/nodes/WatchStreamingOutputNode.d.ts +17 -0
- package/dist/types/model/nodes/jsValueInterpolation.d.ts +10 -1
- package/dist/types/recording/RecordedEvents.d.ts +8 -0
- package/dist/types/utils/interpolation.d.ts +14 -5
- package/package.json +1 -1
package/dist/esm/model/Nodes.js
CHANGED
|
@@ -71,6 +71,10 @@ export * from './nodes/DataBusNode.js';
|
|
|
71
71
|
export * from './DataBusTopology.js';
|
|
72
72
|
import { startBackgroundBranchNode } from './nodes/StartBackgroundBranchNode.js';
|
|
73
73
|
export * from './nodes/StartBackgroundBranchNode.js';
|
|
74
|
+
import { watchStreamingOutputNode } from './nodes/WatchStreamingOutputNode.js';
|
|
75
|
+
export * from './nodes/WatchStreamingOutputNode.js';
|
|
76
|
+
import { stopWatchingStreamingOutputNode } from './nodes/StopWatchingStreamingOutputNode.js';
|
|
77
|
+
export * from './nodes/StopWatchingStreamingOutputNode.js';
|
|
74
78
|
import { popNode } from './nodes/PopNode.js';
|
|
75
79
|
export * from './nodes/PopNode.js';
|
|
76
80
|
import { setGlobalNode } from './nodes/SetGlobalNode.js';
|
|
@@ -243,6 +247,8 @@ export const registerBuiltInNodes = (registry) => {
|
|
|
243
247
|
.register(passthroughNode)
|
|
244
248
|
.register(dataBusNode)
|
|
245
249
|
.register(startBackgroundBranchNode)
|
|
250
|
+
.register(watchStreamingOutputNode)
|
|
251
|
+
.register(stopWatchingStreamingOutputNode)
|
|
246
252
|
.register(popNode)
|
|
247
253
|
.register(setGlobalNode)
|
|
248
254
|
.register(getGlobalNode)
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
export function buildNodeProcessContext(options) {
|
|
2
|
-
const { attachedData, activeOutputPortIds, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, markResultAsEditorCacheHit, node, nodeAbortController, onPartialOutputs, setFailureOutputs, processId, requestUserInput, reportProgress, setGlobal, splitIndex, toolCallContinuation, toolCallTraceSource, waitEvent, } = options;
|
|
2
|
+
const { attachedData, activeOutputPortIds, acceptStreamingWatchStop, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, markResultAsEditorCacheHit, node, nodeAbortController, onGraphOutputPartial, onPartialOutputs, setFailureOutputs, processId, requestUserInput, reportProgress, setGlobal, splitIndex, toolCallContinuation, toolCallTraceSource, waitEvent, } = options;
|
|
3
3
|
return {
|
|
4
4
|
...base,
|
|
5
5
|
node,
|
|
6
6
|
attachedData,
|
|
7
7
|
activeOutputPortIds,
|
|
8
|
+
acceptStreamingWatchStop,
|
|
8
9
|
isDirectRunTarget,
|
|
9
10
|
markResultAsEditorCacheHit,
|
|
10
11
|
waitEvent,
|
|
11
12
|
waitForGlobal: (id, signal = nodeAbortController.signal) => base.waitForGlobal(id, signal),
|
|
12
13
|
waitForStoredValue: (key, signal = nodeAbortController.signal) => base.waitForStoredValue(key, signal),
|
|
13
14
|
externalFunctions: { ...externalFunctions },
|
|
15
|
+
onGraphOutputPartial,
|
|
14
16
|
onPartialOutputs,
|
|
15
17
|
setFailureOutputs,
|
|
16
18
|
signal: nodeAbortController.signal,
|
|
@@ -1 +1,36 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Loads referenced projects depth-first in declared order.
|
|
3
|
+
*
|
|
4
|
+
* The active root is already in memory, so it is visited before traversing
|
|
5
|
+
* references. This keeps legacy cycles compatible without asking a loader to
|
|
6
|
+
* resolve the active project again. The returned record intentionally omits
|
|
7
|
+
* that root; callers already own the authoritative root snapshot.
|
|
8
|
+
*/
|
|
9
|
+
export async function loadProjectReferenceTree(rootProject, rootProjectPath, loader) {
|
|
10
|
+
const collected = Object.create(null);
|
|
11
|
+
const seenProjectIds = new Set([rootProject.metadata.id]);
|
|
12
|
+
const loadReference = async (reference) => {
|
|
13
|
+
if (seenProjectIds.has(reference.id))
|
|
14
|
+
return;
|
|
15
|
+
seenProjectIds.add(reference.id);
|
|
16
|
+
const project = await loader.loadProject(rootProjectPath, reference);
|
|
17
|
+
if (project.metadata.id !== reference.id) {
|
|
18
|
+
throw new Error(`Referenced project "${reference.id}" loaded a project with ID "${project.metadata.id}" instead.`);
|
|
19
|
+
}
|
|
20
|
+
// Project IDs are user-controlled strings. Define an own property so IDs
|
|
21
|
+
// such as __proto__ cannot mutate the lookup object's prototype.
|
|
22
|
+
Object.defineProperty(collected, project.metadata.id, {
|
|
23
|
+
configurable: true,
|
|
24
|
+
enumerable: true,
|
|
25
|
+
value: project,
|
|
26
|
+
writable: true,
|
|
27
|
+
});
|
|
28
|
+
for (const childReference of project.references ?? []) {
|
|
29
|
+
await loadReference(childReference);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
for (const reference of rootProject.references ?? []) {
|
|
33
|
+
await loadReference(reference);
|
|
34
|
+
}
|
|
35
|
+
return collected;
|
|
36
|
+
}
|
|
@@ -17,6 +17,10 @@ function withReplayRecordedAt(data, replayRecordedAt) {
|
|
|
17
17
|
}
|
|
18
18
|
return { ...data, replayRecordedAt };
|
|
19
19
|
}
|
|
20
|
+
function getRecordedEventOccurrenceAt(event) {
|
|
21
|
+
const { occurredAt, ts } = event;
|
|
22
|
+
return typeof occurredAt === 'number' && Number.isFinite(occurredAt) && occurredAt >= 0 ? occurredAt : ts;
|
|
23
|
+
}
|
|
20
24
|
const REPLAY_TIMED_EVENTS = new Set([
|
|
21
25
|
'start',
|
|
22
26
|
'graphStart',
|
|
@@ -32,6 +36,7 @@ const REPLAY_TIMED_EVENTS = new Set([
|
|
|
32
36
|
'nodeError',
|
|
33
37
|
'nodeExcluded',
|
|
34
38
|
'nodeOutputsCleared',
|
|
39
|
+
'streamingOutputWatchSummary',
|
|
35
40
|
// These records retain their own physical call timestamps, but the replay
|
|
36
41
|
// timestamp lets observers keep them on the same historical recording
|
|
37
42
|
// timeline without borrowing a provider timestamp as a node lifecycle time.
|
|
@@ -210,7 +215,10 @@ export async function replayExecutionRecording(options) {
|
|
|
210
215
|
break;
|
|
211
216
|
}
|
|
212
217
|
await waitUntilUnpaused();
|
|
213
|
-
|
|
218
|
+
// Watch history can defer selected evidence until the scheduler settles.
|
|
219
|
+
// Keep recording order on `ts`, but present and derive timing from when
|
|
220
|
+
// the original event actually occurred.
|
|
221
|
+
currentReplayRecordedAt = getRecordedEventOccurrenceAt(event);
|
|
214
222
|
switch (event.type) {
|
|
215
223
|
case 'start': {
|
|
216
224
|
const { data } = event;
|
|
@@ -325,7 +333,7 @@ export async function replayExecutionRecording(options) {
|
|
|
325
333
|
const { data } = event;
|
|
326
334
|
const node = getNode(data.nodeId);
|
|
327
335
|
const execution = getExecution(data.execution?.graphId ?? getGraphIdForNode(data.nodeId), data.execution);
|
|
328
|
-
nodeStartTimestamps.set(getNodeRunKey(execution, data.nodeId, data.processId), event
|
|
336
|
+
nodeStartTimestamps.set(getNodeRunKey(execution, data.nodeId, data.processId), getRecordedEventOccurrenceAt(event));
|
|
329
337
|
emitReplayExecutionEvent('nodeStart', {
|
|
330
338
|
node,
|
|
331
339
|
inputs: data.inputs,
|
|
@@ -348,8 +356,9 @@ export async function replayExecutionRecording(options) {
|
|
|
348
356
|
outputs: data.outputs,
|
|
349
357
|
processId: data.processId,
|
|
350
358
|
...(data.resultOrigin === undefined ? {} : { resultOrigin: data.resultOrigin }),
|
|
359
|
+
...(data.streamingWatchTerminal ? { streamingWatchTerminal: true } : {}),
|
|
351
360
|
execution,
|
|
352
|
-
}, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event
|
|
361
|
+
}, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, getRecordedEventOccurrenceAt(event)), data.splitRunDurationMs));
|
|
353
362
|
nodeResults.set(data.nodeId, data.outputs);
|
|
354
363
|
visitedNodes.add(data.nodeId);
|
|
355
364
|
break;
|
|
@@ -366,7 +375,7 @@ export async function replayExecutionRecording(options) {
|
|
|
366
375
|
...(data.splitOutputs === undefined ? {} : { splitOutputs: data.splitOutputs }),
|
|
367
376
|
...(data.resultOrigin === undefined ? {} : { resultOrigin: data.resultOrigin }),
|
|
368
377
|
execution,
|
|
369
|
-
}, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, event
|
|
378
|
+
}, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, getRecordedEventOccurrenceAt(event)), data.splitRunDurationMs));
|
|
370
379
|
erroredNodes.set(data.nodeId, data.error);
|
|
371
380
|
visitedNodes.add(data.nodeId);
|
|
372
381
|
break;
|
|
@@ -399,6 +408,32 @@ export async function replayExecutionRecording(options) {
|
|
|
399
408
|
});
|
|
400
409
|
break;
|
|
401
410
|
}
|
|
411
|
+
case 'streamingOutputWatchSummary': {
|
|
412
|
+
const { data } = event;
|
|
413
|
+
const execution = getExecution(data.execution?.graphId ?? getGraphIdForNode(data.watchNodeId), data.execution);
|
|
414
|
+
// Watch summaries identify one retained child branch as terminal.
|
|
415
|
+
// A replay creates fresh graph-run IDs, so remap that child identity
|
|
416
|
+
// with the same root-scoped map used for its retained node events.
|
|
417
|
+
const selectedIteration = data.summary.selectedIteration;
|
|
418
|
+
const summary = selectedIteration?.graphRunId != null && data.execution != null
|
|
419
|
+
? {
|
|
420
|
+
...data.summary,
|
|
421
|
+
selectedIteration: {
|
|
422
|
+
...selectedIteration,
|
|
423
|
+
graphRunId: getReplayExecution({
|
|
424
|
+
...data.execution,
|
|
425
|
+
graphRunId: selectedIteration.graphRunId,
|
|
426
|
+
}).graphRunId,
|
|
427
|
+
},
|
|
428
|
+
}
|
|
429
|
+
: data.summary;
|
|
430
|
+
emitReplayExecutionEvent('streamingOutputWatchSummary', {
|
|
431
|
+
watchNode: getNode(data.watchNodeId),
|
|
432
|
+
summary,
|
|
433
|
+
execution,
|
|
434
|
+
});
|
|
435
|
+
break;
|
|
436
|
+
}
|
|
402
437
|
case 'partialOutput': {
|
|
403
438
|
const { data } = event;
|
|
404
439
|
const node = getNode(data.nodeId);
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/** Defaults shared by the persisted node definition and the runtime boundary. */
|
|
2
|
+
export const streamingOutputWatchDefaults = {
|
|
3
|
+
intervalMs: 1_000,
|
|
4
|
+
maxParallelRuns: 4,
|
|
5
|
+
maxQueuedUpdates: 32,
|
|
6
|
+
// Preserve the original fail-closed behavior unless a project explicitly
|
|
7
|
+
// opts into skipping updates that cannot be scheduled.
|
|
8
|
+
queueOverflowBehavior: 'fail',
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Hard safety bounds for persisted settings. The node editor exposes the same
|
|
12
|
+
* limits, but the runtime must also defend against manually edited project data.
|
|
13
|
+
*/
|
|
14
|
+
export const streamingOutputWatchLimits = {
|
|
15
|
+
intervalMs: 3_600_000,
|
|
16
|
+
maxParallelRuns: 32,
|
|
17
|
+
maxQueuedUpdates: 1_024,
|
|
18
|
+
};
|
|
19
|
+
function normalizePositiveInteger(value, fallback, maximum) {
|
|
20
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
21
|
+
return fallback;
|
|
22
|
+
}
|
|
23
|
+
return Math.min(maximum, Math.max(1, Math.floor(value)));
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Owns bounded, cancellable delivery of a streaming node's immutable output
|
|
27
|
+
* snapshots. It deliberately knows nothing about graph topology: the owning
|
|
28
|
+
* GraphProcessor decides how a snapshot runs and whether accepting Stop is
|
|
29
|
+
* required to complete the watch.
|
|
30
|
+
*/
|
|
31
|
+
export class StreamingOutputWatch {
|
|
32
|
+
#options;
|
|
33
|
+
#run;
|
|
34
|
+
#onFailure;
|
|
35
|
+
#requiresAcceptedStop;
|
|
36
|
+
#queue = [];
|
|
37
|
+
#activeRuns = new Set();
|
|
38
|
+
#timer;
|
|
39
|
+
#latestIntervalSnapshot;
|
|
40
|
+
#producerFinished = false;
|
|
41
|
+
#finalSnapshotSettled = false;
|
|
42
|
+
#stopped = false;
|
|
43
|
+
#failure;
|
|
44
|
+
#failureKind;
|
|
45
|
+
#receivedUpdates = 0;
|
|
46
|
+
#coalescedUpdates = 0;
|
|
47
|
+
#droppedUpdates = 0;
|
|
48
|
+
#maximumQueuedUpdates = 0;
|
|
49
|
+
constructor(options, run, onFailure, { requiresAcceptedStop = true } = {}) {
|
|
50
|
+
this.#options = {
|
|
51
|
+
triggerMode: options.triggerMode === 'interval' ? 'interval' : 'every-update',
|
|
52
|
+
executionMode: options.executionMode === 'parallel' ? 'parallel' : 'sequential',
|
|
53
|
+
intervalMs: normalizePositiveInteger(options.intervalMs, streamingOutputWatchDefaults.intervalMs, streamingOutputWatchLimits.intervalMs),
|
|
54
|
+
maxParallelRuns: normalizePositiveInteger(options.maxParallelRuns, streamingOutputWatchDefaults.maxParallelRuns, streamingOutputWatchLimits.maxParallelRuns),
|
|
55
|
+
maxQueuedUpdates: normalizePositiveInteger(options.maxQueuedUpdates, streamingOutputWatchDefaults.maxQueuedUpdates, streamingOutputWatchLimits.maxQueuedUpdates),
|
|
56
|
+
queueOverflowBehavior: options.queueOverflowBehavior === 'drop' ? 'drop' : streamingOutputWatchDefaults.queueOverflowBehavior,
|
|
57
|
+
};
|
|
58
|
+
this.#run = run;
|
|
59
|
+
this.#onFailure = onFailure;
|
|
60
|
+
this.#requiresAcceptedStop = requiresAcceptedStop;
|
|
61
|
+
}
|
|
62
|
+
get hasPending() {
|
|
63
|
+
// Stop prevents new delivery, but accepted and failing invocations still
|
|
64
|
+
// belong to the root lifecycle until they settle. Hiding those active runs
|
|
65
|
+
// here lets finalization report a later missing-Stop error instead of the
|
|
66
|
+
// actual child failure.
|
|
67
|
+
return this.#activeRuns.size > 0 || (!this.#stopped && (this.#queue.length > 0 || this.#timer != null));
|
|
68
|
+
}
|
|
69
|
+
get isAwaitingProducer() {
|
|
70
|
+
return (!this.#stopped &&
|
|
71
|
+
!this.#producerFinished &&
|
|
72
|
+
this.#timer != null &&
|
|
73
|
+
this.#queue.length === 0 &&
|
|
74
|
+
this.#activeRuns.size === 0);
|
|
75
|
+
}
|
|
76
|
+
get stopped() {
|
|
77
|
+
return this.#stopped;
|
|
78
|
+
}
|
|
79
|
+
/** True only after this Watch can no longer receive or run a snapshot. */
|
|
80
|
+
get isSettled() {
|
|
81
|
+
return !this.hasPending && (this.#stopped || this.#failure != null || this.#producerFinished);
|
|
82
|
+
}
|
|
83
|
+
get runtimeSummary() {
|
|
84
|
+
return {
|
|
85
|
+
receivedUpdates: this.#receivedUpdates,
|
|
86
|
+
coalescedUpdates: this.#coalescedUpdates,
|
|
87
|
+
droppedUpdates: this.#droppedUpdates,
|
|
88
|
+
maximumQueuedUpdates: this.#maximumQueuedUpdates,
|
|
89
|
+
...(this.#failureKind === undefined ? {} : { failureKind: this.#failureKind }),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* A Stop boundary can enqueue ordinary parent-graph work when its node
|
|
94
|
+
* completes. Until it settles, its result is not safe to expose
|
|
95
|
+
* through the foreground-output boundary.
|
|
96
|
+
*/
|
|
97
|
+
get canAffectForegroundOutputs() {
|
|
98
|
+
return this.#requiresAcceptedStop;
|
|
99
|
+
}
|
|
100
|
+
publish(snapshot) {
|
|
101
|
+
// A producer's terminal snapshot closes its partial stream. Ignore a
|
|
102
|
+
// misbehaving late callback rather than scheduling work after a final
|
|
103
|
+
// result has already been offered to Stop and ordinary downstream nodes.
|
|
104
|
+
if (this.#stopped || this.#failure || this.#producerFinished) {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
this.#receivedUpdates += 1;
|
|
108
|
+
if (this.#options.triggerMode === 'interval' && !snapshot.isFinal) {
|
|
109
|
+
if (this.#latestIntervalSnapshot) {
|
|
110
|
+
this.#coalescedUpdates += 1;
|
|
111
|
+
}
|
|
112
|
+
this.#latestIntervalSnapshot = snapshot;
|
|
113
|
+
this.#scheduleInterval();
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
this.#enqueue(snapshot);
|
|
117
|
+
}
|
|
118
|
+
finish(finalSnapshot) {
|
|
119
|
+
if (this.#stopped || this.#failure || this.#producerFinished) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
this.#receivedUpdates += 1;
|
|
123
|
+
this.#producerFinished = true;
|
|
124
|
+
if (this.#timer != null) {
|
|
125
|
+
clearTimeout(this.#timer);
|
|
126
|
+
this.#timer = undefined;
|
|
127
|
+
}
|
|
128
|
+
// The final output supersedes a partial snapshot that was still waiting
|
|
129
|
+
// for its interval. Account for that intentionally omitted update just as
|
|
130
|
+
// we account for a newer partial replacing one before the timer fires.
|
|
131
|
+
if (this.#latestIntervalSnapshot) {
|
|
132
|
+
this.#coalescedUpdates += 1;
|
|
133
|
+
}
|
|
134
|
+
this.#latestIntervalSnapshot = undefined;
|
|
135
|
+
this.#enqueue(finalSnapshot);
|
|
136
|
+
}
|
|
137
|
+
/** Preserve the winning invocation's siblings; later owner cancellation cancels all. */
|
|
138
|
+
stop(acceptedUpdateIndex) {
|
|
139
|
+
this.#stopped = true;
|
|
140
|
+
this.#queue.length = 0;
|
|
141
|
+
this.#latestIntervalSnapshot = undefined;
|
|
142
|
+
if (this.#timer != null) {
|
|
143
|
+
clearTimeout(this.#timer);
|
|
144
|
+
this.#timer = undefined;
|
|
145
|
+
}
|
|
146
|
+
for (const activeRun of this.#activeRuns) {
|
|
147
|
+
if (activeRun.updateIndex !== acceptedUpdateIndex)
|
|
148
|
+
activeRun.cancel();
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async drain() {
|
|
152
|
+
while (this.#queue.length > 0 || this.#activeRuns.size > 0 || this.#timer != null) {
|
|
153
|
+
if (this.#timer != null && this.#activeRuns.size === 0 && this.#queue.length === 0) {
|
|
154
|
+
// A producer that is still running owns the next interval. Do not turn
|
|
155
|
+
// an ordinary wait between updates into a busy loop.
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
await Promise.all([...this.#activeRuns].map((run) => run.promise));
|
|
159
|
+
}
|
|
160
|
+
if (this.#producerFinished && this.#finalSnapshotSettled && !this.#stopped && this.#requiresAcceptedStop) {
|
|
161
|
+
this.#fail(new Error('The watched streaming output completed before Stop Watching Streaming Output accepted a value.'), 'missing-stop');
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
#scheduleInterval() {
|
|
165
|
+
if (this.#timer != null) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
this.#timer = setTimeout(() => {
|
|
169
|
+
this.#timer = undefined;
|
|
170
|
+
if (this.#stopped || this.#failure) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const snapshot = this.#latestIntervalSnapshot;
|
|
174
|
+
this.#latestIntervalSnapshot = undefined;
|
|
175
|
+
if (snapshot) {
|
|
176
|
+
this.#enqueue(snapshot);
|
|
177
|
+
}
|
|
178
|
+
}, this.#options.intervalMs);
|
|
179
|
+
}
|
|
180
|
+
#enqueue(snapshot) {
|
|
181
|
+
if (this.#queue.length >= this.#options.maxQueuedUpdates) {
|
|
182
|
+
if (this.#options.queueOverflowBehavior === 'drop') {
|
|
183
|
+
if (snapshot.isFinal) {
|
|
184
|
+
// A final snapshot is the only chance for a Stop branch to accept a
|
|
185
|
+
// value after its producer has completed. Keep that contract without
|
|
186
|
+
// relaxing the configured queue bound: discard the stalest waiting
|
|
187
|
+
// partial and retain the final snapshot instead.
|
|
188
|
+
this.#queue.shift();
|
|
189
|
+
this.#droppedUpdates += 1;
|
|
190
|
+
this.#queue.push(snapshot);
|
|
191
|
+
this.#maximumQueuedUpdates = Math.max(this.#maximumQueuedUpdates, this.#queue.length);
|
|
192
|
+
this.#pump();
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
this.#droppedUpdates += 1;
|
|
196
|
+
}
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
this.#fail(new Error(`Watch Streaming Output exceeded its ${this.#options.maxQueuedUpdates}-update queue limit. ` +
|
|
200
|
+
'Increase the limit, use an interval trigger, or stop the watch sooner.'), 'queue-overflow');
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
this.#queue.push(snapshot);
|
|
204
|
+
this.#maximumQueuedUpdates = Math.max(this.#maximumQueuedUpdates, this.#queue.length);
|
|
205
|
+
this.#pump();
|
|
206
|
+
}
|
|
207
|
+
#pump() {
|
|
208
|
+
const concurrency = this.#options.executionMode === 'parallel' ? this.#options.maxParallelRuns : 1;
|
|
209
|
+
while (!this.#stopped && !this.#failure && this.#queue.length > 0 && this.#activeRuns.size < concurrency) {
|
|
210
|
+
const snapshot = this.#queue.shift();
|
|
211
|
+
let cancel = () => undefined;
|
|
212
|
+
let cancelled = false;
|
|
213
|
+
const activeRun = {
|
|
214
|
+
isFinal: snapshot.isFinal,
|
|
215
|
+
updateIndex: snapshot.updateIndex,
|
|
216
|
+
cancel: () => {
|
|
217
|
+
if (cancelled)
|
|
218
|
+
return;
|
|
219
|
+
cancelled = true;
|
|
220
|
+
cancel();
|
|
221
|
+
},
|
|
222
|
+
promise: Promise.resolve(),
|
|
223
|
+
};
|
|
224
|
+
// Start through a promise boundary so a malformed branch that throws
|
|
225
|
+
// synchronously is still tracked, drained, and reported like an async
|
|
226
|
+
// branch failure.
|
|
227
|
+
activeRun.promise = Promise.resolve()
|
|
228
|
+
.then(() => {
|
|
229
|
+
// stop() may run after this slot is reserved but before its microtask.
|
|
230
|
+
if (this.#stopped)
|
|
231
|
+
return;
|
|
232
|
+
return this.#run(snapshot, (nextCancel) => {
|
|
233
|
+
cancel = nextCancel;
|
|
234
|
+
if (cancelled)
|
|
235
|
+
cancel();
|
|
236
|
+
});
|
|
237
|
+
})
|
|
238
|
+
.catch((error) => {
|
|
239
|
+
if (!this.#stopped) {
|
|
240
|
+
this.#fail(error instanceof Error ? error : new Error(String(error)), 'branch-failure');
|
|
241
|
+
}
|
|
242
|
+
})
|
|
243
|
+
.finally(() => {
|
|
244
|
+
if (activeRun.isFinal) {
|
|
245
|
+
this.#finalSnapshotSettled = true;
|
|
246
|
+
}
|
|
247
|
+
this.#activeRuns.delete(activeRun);
|
|
248
|
+
this.#pump();
|
|
249
|
+
});
|
|
250
|
+
this.#activeRuns.add(activeRun);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
#fail(error, failureKind) {
|
|
254
|
+
if (this.#failure) {
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
this.#failure = error;
|
|
258
|
+
this.#failureKind = failureKind;
|
|
259
|
+
this.#onFailure(error);
|
|
260
|
+
this.stop();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { cloneExecutionValue } from './ExecutionOutputClone.js';
|
|
2
|
+
/** The number of early Watch iterations retained as representative evidence. */
|
|
3
|
+
export const streamingOutputWatchRetainedInitialIterations = 3;
|
|
4
|
+
/**
|
|
5
|
+
* Retains only useful Watch branch evidence before it reaches the outer event
|
|
6
|
+
* emitter. The first three started iterations are delivered live. Later
|
|
7
|
+
* iterations are held only while they can still become the first failure, a
|
|
8
|
+
* Stop winner, or the final/latest iteration. This bounds editor history and
|
|
9
|
+
* recordings without changing the branch's actual execution.
|
|
10
|
+
*/
|
|
11
|
+
export class StreamingOutputWatchHistory {
|
|
12
|
+
// This is deliberately not a complete run history. It contains only active
|
|
13
|
+
// iterations and the few candidates that can still affect retained
|
|
14
|
+
// evidence. Keeping a Map entry for every streamed increment would leave
|
|
15
|
+
// an unbounded metadata leak after we had bounded the event payloads.
|
|
16
|
+
#iterationsByRunId = new Map();
|
|
17
|
+
#latestStarted;
|
|
18
|
+
#firstFailure;
|
|
19
|
+
#stopWinner;
|
|
20
|
+
#startedIterations = 0;
|
|
21
|
+
#retainedInitialUpdateIndexes = [];
|
|
22
|
+
#completedIterations = 0;
|
|
23
|
+
#failedIterations = 0;
|
|
24
|
+
#cancelledIterations = 0;
|
|
25
|
+
#finalized = false;
|
|
26
|
+
#finalizedSelected;
|
|
27
|
+
#now;
|
|
28
|
+
constructor({ now = Date.now } = {}) {
|
|
29
|
+
this.#now = now;
|
|
30
|
+
}
|
|
31
|
+
start(graphRunId, updateIndex) {
|
|
32
|
+
if (this.#finalized) {
|
|
33
|
+
throw new Error('Cannot start a Watch Streaming Output history iteration after finalization.');
|
|
34
|
+
}
|
|
35
|
+
const previousLatest = this.#latestStarted;
|
|
36
|
+
const ordinal = this.#startedIterations + 1;
|
|
37
|
+
const iteration = {
|
|
38
|
+
graphRunId,
|
|
39
|
+
ordinal,
|
|
40
|
+
updateIndex,
|
|
41
|
+
events: [],
|
|
42
|
+
completed: false,
|
|
43
|
+
failed: false,
|
|
44
|
+
cancelled: false,
|
|
45
|
+
retainedImmediately: ordinal <= streamingOutputWatchRetainedInitialIterations,
|
|
46
|
+
};
|
|
47
|
+
this.#startedIterations = ordinal;
|
|
48
|
+
if (iteration.retainedImmediately) {
|
|
49
|
+
this.#retainedInitialUpdateIndexes.push(updateIndex);
|
|
50
|
+
}
|
|
51
|
+
this.#iterationsByRunId.set(graphRunId, iteration);
|
|
52
|
+
this.#latestStarted = iteration;
|
|
53
|
+
this.#releaseIfNoLongerNeeded(previousLatest);
|
|
54
|
+
return iteration;
|
|
55
|
+
}
|
|
56
|
+
forward(iteration, event, data, forward) {
|
|
57
|
+
const owned = this.#getIteration(iteration);
|
|
58
|
+
if (owned.retainedImmediately) {
|
|
59
|
+
return forward(event, data);
|
|
60
|
+
}
|
|
61
|
+
// Later selected evidence is emitted only after the Watch has settled.
|
|
62
|
+
// Capture both the value and its original clock now: retaining a mutable
|
|
63
|
+
// output reference or using the later flush time would make recordings
|
|
64
|
+
// disagree with the execution that actually occurred.
|
|
65
|
+
owned.events.push({ event, data: cloneExecutionValue(data), occurredAt: this.#now() });
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
complete(iteration) {
|
|
69
|
+
const owned = this.#getIteration(iteration);
|
|
70
|
+
if (owned.completed)
|
|
71
|
+
return;
|
|
72
|
+
owned.completed = true;
|
|
73
|
+
// Keep terminal outcomes disjoint. A failure/cancellation still settles an
|
|
74
|
+
// iteration, but callers should not have to subtract it from the completed
|
|
75
|
+
// count to understand the compact summary.
|
|
76
|
+
if (!owned.failed && !owned.cancelled) {
|
|
77
|
+
this.#completedIterations += 1;
|
|
78
|
+
}
|
|
79
|
+
this.#releaseIfNoLongerNeeded(owned);
|
|
80
|
+
}
|
|
81
|
+
fail(iteration) {
|
|
82
|
+
const owned = this.#getIteration(iteration);
|
|
83
|
+
if (!owned.failed) {
|
|
84
|
+
owned.failed = true;
|
|
85
|
+
this.#failedIterations += 1;
|
|
86
|
+
}
|
|
87
|
+
this.#firstFailure ??= owned;
|
|
88
|
+
this.#releaseIfNoLongerNeeded(owned);
|
|
89
|
+
}
|
|
90
|
+
cancel(iteration) {
|
|
91
|
+
const owned = this.#getIteration(iteration);
|
|
92
|
+
if (!owned.cancelled) {
|
|
93
|
+
owned.cancelled = true;
|
|
94
|
+
this.#cancelledIterations += 1;
|
|
95
|
+
}
|
|
96
|
+
this.#releaseIfNoLongerNeeded(owned);
|
|
97
|
+
}
|
|
98
|
+
acceptStop(iteration) {
|
|
99
|
+
this.#stopWinner ??= this.#getIteration(iteration);
|
|
100
|
+
}
|
|
101
|
+
get hasAcceptedStop() {
|
|
102
|
+
return this.#stopWinner != null;
|
|
103
|
+
}
|
|
104
|
+
async finalize(runtime, forward) {
|
|
105
|
+
if (this.#finalized) {
|
|
106
|
+
return this.#buildSummary(runtime, this.#finalizedSelected);
|
|
107
|
+
}
|
|
108
|
+
this.#finalized = true;
|
|
109
|
+
const selected = this.#firstFailure ?? this.#stopWinner ?? this.#latestStarted;
|
|
110
|
+
this.#finalizedSelected = selected;
|
|
111
|
+
if (selected && !selected.retainedImmediately) {
|
|
112
|
+
for (const { event, data, occurredAt } of selected.events) {
|
|
113
|
+
await forward(event, withEventOccurredAt(data, occurredAt));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return this.#buildSummary(runtime, selected);
|
|
117
|
+
}
|
|
118
|
+
#getIteration(iteration) {
|
|
119
|
+
const owned = this.#iterationsByRunId.get(iteration.graphRunId);
|
|
120
|
+
if (!owned) {
|
|
121
|
+
throw new Error('Watch Streaming Output history iteration does not belong to this watcher.');
|
|
122
|
+
}
|
|
123
|
+
return owned;
|
|
124
|
+
}
|
|
125
|
+
#releaseIfNoLongerNeeded(iteration) {
|
|
126
|
+
if (!iteration?.completed ||
|
|
127
|
+
iteration === this.#latestStarted ||
|
|
128
|
+
iteration === this.#firstFailure ||
|
|
129
|
+
iteration === this.#stopWinner) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
iteration.events.length = 0;
|
|
133
|
+
this.#iterationsByRunId.delete(iteration.graphRunId);
|
|
134
|
+
}
|
|
135
|
+
#buildSummary(runtime, selected) {
|
|
136
|
+
const retainedIterationUpdateIndexes = [
|
|
137
|
+
...this.#retainedInitialUpdateIndexes,
|
|
138
|
+
...(selected && !selected.retainedImmediately ? [selected.updateIndex] : []),
|
|
139
|
+
];
|
|
140
|
+
return {
|
|
141
|
+
...runtime,
|
|
142
|
+
completedIterations: this.#completedIterations,
|
|
143
|
+
failedIterations: this.#failedIterations,
|
|
144
|
+
cancelledIterations: this.#cancelledIterations,
|
|
145
|
+
omittedIterations: this.#startedIterations - retainedIterationUpdateIndexes.length,
|
|
146
|
+
retainedIterationUpdateIndexes,
|
|
147
|
+
selectedIteration: selected == null
|
|
148
|
+
? undefined
|
|
149
|
+
: {
|
|
150
|
+
graphRunId: selected.graphRunId,
|
|
151
|
+
updateIndex: selected.updateIndex,
|
|
152
|
+
reason: selected === this.#firstFailure ? 'failure' : selected === this.#stopWinner ? 'stop' : 'latest',
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function withEventOccurredAt(data, eventOccurredAt) {
|
|
158
|
+
if (data == null || typeof data !== 'object') {
|
|
159
|
+
return data;
|
|
160
|
+
}
|
|
161
|
+
return { ...data, eventOccurredAt };
|
|
162
|
+
}
|
|
@@ -20,29 +20,39 @@ function subscribeOwnGraphRunLifecycle(processor, onLifecycleEvent) {
|
|
|
20
20
|
};
|
|
21
21
|
}
|
|
22
22
|
export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
|
|
23
|
+
const forward = (event, data) => {
|
|
24
|
+
// `undefined` is a deliberate interceptor result: the Watch history
|
|
25
|
+
// boundary uses it to retain an event without forwarding it yet. Do not
|
|
26
|
+
// fall through to the parent emitter in that case.
|
|
27
|
+
if (parentState.forwardEvent) {
|
|
28
|
+
return parentState.forwardEvent(event, data);
|
|
29
|
+
}
|
|
30
|
+
return parentEmitter.emit(event, data);
|
|
31
|
+
};
|
|
23
32
|
// Some successful graph-abort paths can emit node terminals just after their
|
|
24
33
|
// graph-level terminal event. Keep passive forwarding alive for the
|
|
25
34
|
// subprocessor object lifetime so remote-debugger/recorder consumers do not
|
|
26
35
|
// miss those node terminals.
|
|
27
36
|
const passiveUnsubscribers = [
|
|
28
|
-
processor.on('nodeError', (event) =>
|
|
29
|
-
processor.on('nodeFinish', (event) =>
|
|
30
|
-
processor.on('partialOutput', (event) =>
|
|
31
|
-
processor.on('progress', (event) =>
|
|
32
|
-
processor.on('llmCallFinished', (event) =>
|
|
33
|
-
processor.on('llmChatOutputSnapshot', (event) =>
|
|
34
|
-
processor.on('llmProfileAttempt', (event) =>
|
|
35
|
-
processor.on('toolCallFinished', (event) =>
|
|
36
|
-
processor.on('nodeExcluded', (event) =>
|
|
37
|
-
processor.on('nodeStart', (event) =>
|
|
38
|
-
processor.on('graphAbort', (event) =>
|
|
39
|
-
processor.on('graphError', (event) =>
|
|
40
|
-
processor.on('userInput', (event) =>
|
|
41
|
-
processor.on('graphStart', (event) =>
|
|
42
|
-
processor.on('graphFinish', (event) =>
|
|
43
|
-
processor.on('nodeOutputsCleared', (event) =>
|
|
44
|
-
processor.on('
|
|
45
|
-
processor.on('
|
|
37
|
+
processor.on('nodeError', (event) => forward('nodeError', event)),
|
|
38
|
+
processor.on('nodeFinish', (event) => forward('nodeFinish', event)),
|
|
39
|
+
processor.on('partialOutput', (event) => forward('partialOutput', event)),
|
|
40
|
+
processor.on('progress', (event) => forward('progress', event)),
|
|
41
|
+
processor.on('llmCallFinished', (event) => forward('llmCallFinished', event)),
|
|
42
|
+
processor.on('llmChatOutputSnapshot', (event) => forward('llmChatOutputSnapshot', event)),
|
|
43
|
+
processor.on('llmProfileAttempt', (event) => forward('llmProfileAttempt', event)),
|
|
44
|
+
processor.on('toolCallFinished', (event) => forward('toolCallFinished', event)),
|
|
45
|
+
processor.on('nodeExcluded', (event) => forward('nodeExcluded', event)),
|
|
46
|
+
processor.on('nodeStart', (event) => forward('nodeStart', event)),
|
|
47
|
+
processor.on('graphAbort', (event) => forward('graphAbort', event)),
|
|
48
|
+
processor.on('graphError', (event) => forward('graphError', event)),
|
|
49
|
+
processor.on('userInput', (event) => forward('userInput', event)),
|
|
50
|
+
processor.on('graphStart', (event) => forward('graphStart', event)),
|
|
51
|
+
processor.on('graphFinish', (event) => forward('graphFinish', event)),
|
|
52
|
+
processor.on('nodeOutputsCleared', (event) => forward('nodeOutputsCleared', event)),
|
|
53
|
+
processor.on('streamingOutputWatchSummary', (event) => forward('streamingOutputWatchSummary', event)),
|
|
54
|
+
processor.on('globalSet', (event) => forward('globalSet', event)),
|
|
55
|
+
processor.on('newAbortController', (event) => forward('newAbortController', event)),
|
|
46
56
|
];
|
|
47
57
|
const controlUnsubscribers = [
|
|
48
58
|
processor.on('pause', () => {
|
|
@@ -58,7 +68,7 @@ export function wireSubprocessorEvents(processor, parentEmitter, parentState) {
|
|
|
58
68
|
];
|
|
59
69
|
const unsubscribeAny = processor.onAny((event, data) => {
|
|
60
70
|
if (event.startsWith('globalSet:')) {
|
|
61
|
-
void
|
|
71
|
+
void forward(event, data);
|
|
62
72
|
}
|
|
63
73
|
});
|
|
64
74
|
let controlsCleanedUp = false;
|