@valerypopoff/rivet2-core 2.5.0 → 2.7.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 +3104 -850
- 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/cjs/webAppRuntime.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/AgentResponseTrace.js +8 -3
- 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 +865 -46
- package/dist/esm/model/Nodes.js +6 -0
- package/dist/esm/model/ProcessContextBuilder.js +4 -1
- package/dist/esm/model/ProjectReferenceLoader.js +36 -1
- package/dist/esm/model/RecordingPlayer.js +58 -14
- package/dist/esm/model/SplitRunProcessor.js +37 -16
- package/dist/esm/model/StreamingOutputWatch.js +262 -0
- package/dist/esm/model/StreamingOutputWatchHistory.js +161 -0
- package/dist/esm/model/SubprocessorBridge.js +29 -19
- package/dist/esm/model/UiGraphRendererStyles.js +20 -0
- package/dist/esm/model/chat/aiSdkStreaming.js +3 -2
- package/dist/esm/model/chat-v2/aiSdkBridge.js +63 -5
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +66 -3
- package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +3 -42
- package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +20 -7
- package/dist/esm/model/chat-v2/llmProfileFallback.js +12 -4
- package/dist/esm/model/nodes/CodeNewNode.js +4 -1
- package/dist/esm/model/nodes/ExpressionNode.js +4 -1
- package/dist/esm/model/nodes/ExtractObjectPathNode.js +4 -4
- package/dist/esm/model/nodes/GraphOutputNode.js +13 -8
- package/dist/esm/model/nodes/LLMChatV2Node.js +30 -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 +71 -30
- 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/AgentResponseTrace.d.ts +2 -0
- package/dist/types/model/ExecutionOutputClone.d.ts +11 -0
- package/dist/types/model/ExecutorProtocol.d.ts +12 -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 +55 -3
- package/dist/types/model/Nodes.d.ts +4 -2
- package/dist/types/model/ProcessContext.d.ts +20 -0
- package/dist/types/model/ProcessContextBuilder.d.ts +4 -1
- package/dist/types/model/Project.d.ts +7 -1
- package/dist/types/model/ProjectReferenceLoader.d.ts +15 -1
- package/dist/types/model/SplitRunProcessor.d.ts +2 -1
- package/dist/types/model/StreamingOutputWatch.d.ts +74 -0
- package/dist/types/model/StreamingOutputWatchHistory.d.ts +58 -0
- package/dist/types/model/SubprocessorBridge.d.ts +2 -0
- package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
- package/dist/types/model/chat/aiSdkStreaming.d.ts +1 -1
- package/dist/types/model/chat-v2/chatV2RequestPlan.d.ts +1 -1
- package/dist/types/model/chat-v2/chatV2Types.d.ts +29 -0
- package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -3
- package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +5 -1
- 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/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/ExecutionRecorder.d.ts +6 -1
- package/dist/types/recording/RecordedEvents.d.ts +9 -0
- package/dist/types/utils/interpolation.d.ts +14 -5
- package/package.json +1 -1
|
@@ -0,0 +1,161 @@
|
|
|
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
|
+
updateIndex: selected.updateIndex,
|
|
151
|
+
reason: selected === this.#firstFailure ? 'failure' : selected === this.#stopWinner ? 'stop' : 'latest',
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function withEventOccurredAt(data, eventOccurredAt) {
|
|
157
|
+
if (data == null || typeof data !== 'object') {
|
|
158
|
+
return data;
|
|
159
|
+
}
|
|
160
|
+
return { ...data, eventOccurredAt };
|
|
161
|
+
}
|
|
@@ -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;
|
|
@@ -474,6 +474,7 @@ export const RIVET_WEB_APP_RENDERER_CSS = `
|
|
|
474
474
|
|
|
475
475
|
.rivet-web-app-chat-pins-button,
|
|
476
476
|
.rivet-web-app-chat-search-button,
|
|
477
|
+
.rivet-web-app-chat-new-button,
|
|
477
478
|
.rivet-web-app-chat-menu-button,
|
|
478
479
|
.rivet-web-app-chat-search-close-button,
|
|
479
480
|
.rivet-web-app-chat-search-navigation-button {
|
|
@@ -499,6 +500,18 @@ export const RIVET_WEB_APP_RENDERER_CSS = `
|
|
|
499
500
|
border-radius: 10px;
|
|
500
501
|
}
|
|
501
502
|
|
|
503
|
+
.rivet-web-app-chat-new-button {
|
|
504
|
+
min-height: 30px;
|
|
505
|
+
padding: 0 9px;
|
|
506
|
+
border: 1px solid var(--rivet-web-app-control-border);
|
|
507
|
+
border-radius: 7px;
|
|
508
|
+
background: var(--rivet-web-app-control-background);
|
|
509
|
+
color: var(--rivet-web-app-foreground);
|
|
510
|
+
font-size: 0.875em;
|
|
511
|
+
line-height: 1;
|
|
512
|
+
white-space: nowrap;
|
|
513
|
+
}
|
|
514
|
+
|
|
502
515
|
.rivet-web-app-chat-pins-button {
|
|
503
516
|
display: inline-flex;
|
|
504
517
|
align-items: center;
|
|
@@ -544,6 +557,13 @@ export const RIVET_WEB_APP_RENDERER_CSS = `
|
|
|
544
557
|
outline: none;
|
|
545
558
|
}
|
|
546
559
|
|
|
560
|
+
.rivet-web-app-chat-new-button:hover,
|
|
561
|
+
.rivet-web-app-chat-new-button:focus-visible {
|
|
562
|
+
background: var(--rivet-web-app-control-hover-background);
|
|
563
|
+
color: var(--rivet-web-app-foreground);
|
|
564
|
+
outline: none;
|
|
565
|
+
}
|
|
566
|
+
|
|
547
567
|
.rivet-web-app-chat-menu {
|
|
548
568
|
position: absolute;
|
|
549
569
|
top: calc(100% + 4px);
|
|
@@ -28,11 +28,12 @@ export async function consumeAiSdkStream(fullStream, onPartialOutputs, options =
|
|
|
28
28
|
case 'text-delta': {
|
|
29
29
|
textBlocks.set(part.id, `${textBlocks.get(part.id) ?? ''}${part.text}`);
|
|
30
30
|
responseText = buildResponseText(textBlocks, !!options.dedupeDuplicateTextBlocks);
|
|
31
|
-
onPartialOutputs(responseText, functionCalls);
|
|
31
|
+
onPartialOutputs(responseText, functionCalls, reasoning);
|
|
32
32
|
break;
|
|
33
33
|
}
|
|
34
34
|
case 'reasoning-delta': {
|
|
35
35
|
reasoning += part.text;
|
|
36
|
+
onPartialOutputs(responseText, functionCalls, reasoning);
|
|
36
37
|
break;
|
|
37
38
|
}
|
|
38
39
|
case 'tool-call': {
|
|
@@ -43,7 +44,7 @@ export async function consumeAiSdkStream(fullStream, onPartialOutputs, options =
|
|
|
43
44
|
arguments: JSON.stringify(part.input),
|
|
44
45
|
lastParsedArguments: part.input,
|
|
45
46
|
});
|
|
46
|
-
onPartialOutputs(responseText, functionCalls);
|
|
47
|
+
onPartialOutputs(responseText, functionCalls, reasoning);
|
|
47
48
|
break;
|
|
48
49
|
}
|
|
49
50
|
case 'finish': {
|
|
@@ -273,8 +273,25 @@ async function resolveGenerateReasoning(result) {
|
|
|
273
273
|
}
|
|
274
274
|
return (await resolveOptionalValue(result.reasoning))?.map((part) => part.text).join('') ?? '';
|
|
275
275
|
}
|
|
276
|
+
async function resolveGenerateUsage(result) {
|
|
277
|
+
return (await resolveOptionalValue(result.totalUsage)) ?? (await resolveOptionalValue(result.usage));
|
|
278
|
+
}
|
|
279
|
+
function notifyResponseReceived(options, response) {
|
|
280
|
+
try {
|
|
281
|
+
options.onResponseReceived?.(response);
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
// Failure evidence is observational and must never block provider cleanup.
|
|
285
|
+
}
|
|
286
|
+
}
|
|
276
287
|
async function executeStream(options, executor) {
|
|
277
288
|
const args = buildTextArgs(options);
|
|
289
|
+
try {
|
|
290
|
+
options.onRequestStarted?.();
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
// Failure evidence is observational and must never block a provider call.
|
|
294
|
+
}
|
|
278
295
|
const firstOutputStartedAt = Date.now();
|
|
279
296
|
const handlePromise = Promise.resolve(executor(args));
|
|
280
297
|
const handleTimeout = options.firstOutputTimeoutMs == null
|
|
@@ -293,10 +310,11 @@ async function executeStream(options, executor) {
|
|
|
293
310
|
markOptionalPromiseHandled(handle.requestStatus);
|
|
294
311
|
markOptionalPromiseHandled(handle.usage);
|
|
295
312
|
const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
|
|
296
|
-
const streamed = await consumeAiSdkStream(streamWithDeadlines(handle.fullStream, options, firstOutputStartedAt), (text, functionCalls) => {
|
|
313
|
+
const streamed = await consumeAiSdkStream(streamWithDeadlines(handle.fullStream, options, firstOutputStartedAt), (text, functionCalls, reasoning) => {
|
|
297
314
|
options.onPartialOutput?.({
|
|
298
315
|
text: isStructuredOutput ? collapseRepeatedStructuredJsonText(text) : text,
|
|
299
316
|
functionCalls,
|
|
317
|
+
reasoning,
|
|
300
318
|
});
|
|
301
319
|
}, {
|
|
302
320
|
dedupeDuplicateTextBlocks: isStructuredOutput,
|
|
@@ -304,9 +322,25 @@ async function executeStream(options, executor) {
|
|
|
304
322
|
const responseText = isStructuredOutput
|
|
305
323
|
? collapseRepeatedStructuredJsonText(streamed.responseText)
|
|
306
324
|
: streamed.responseText;
|
|
325
|
+
const usagePromise = streamed.usage != null ? Promise.resolve(streamed.usage) : resolveOptionalValue(handle.usage);
|
|
326
|
+
let evidence = {
|
|
327
|
+
text: responseText,
|
|
328
|
+
functionCalls: streamed.functionCalls,
|
|
329
|
+
reasoning: streamed.reasoning,
|
|
330
|
+
usage: streamed.usage,
|
|
331
|
+
};
|
|
332
|
+
const notifyCurrentResponseEvidence = () => notifyResponseReceived(options, evidence);
|
|
333
|
+
// The stream has completed, so its response, tool calls, and reasoning are
|
|
334
|
+
// real evidence even if a later usage/metadata/structured-output accessor
|
|
335
|
+
// rejects during finalization.
|
|
336
|
+
notifyCurrentResponseEvidence();
|
|
337
|
+
void usagePromise.then((usage) => {
|
|
338
|
+
evidence = { ...evidence, usage };
|
|
339
|
+
notifyCurrentResponseEvidence();
|
|
340
|
+
}, () => undefined);
|
|
307
341
|
const [structuredOutput, usage, finishReason, providerMetadata, requestStatus] = await waitForPostResponseFinalization(Promise.all([
|
|
308
342
|
options.responseOutput != null ? resolveOptionalStructuredOutput(handle.output) : undefined,
|
|
309
|
-
|
|
343
|
+
usagePromise,
|
|
310
344
|
resolveOptionalValue(handle.finishReason),
|
|
311
345
|
resolveOptionalValue(handle.providerMetadata),
|
|
312
346
|
resolveOptionalValue(handle.requestStatus),
|
|
@@ -328,6 +362,12 @@ export async function streamChatV2(options) {
|
|
|
328
362
|
export async function generateChatV2(options) {
|
|
329
363
|
const args = buildTextArgs(options);
|
|
330
364
|
const stepToolCalls = attachGenerateStepToolCallCollector(args);
|
|
365
|
+
try {
|
|
366
|
+
options.onRequestStarted?.();
|
|
367
|
+
}
|
|
368
|
+
catch {
|
|
369
|
+
// Failure evidence is observational and must never block a provider call.
|
|
370
|
+
}
|
|
331
371
|
let result;
|
|
332
372
|
try {
|
|
333
373
|
result = await waitForGeneratedResponse(Promise.resolve((options.executeGenerate ?? defaultGenerateExecutor)(args)), options);
|
|
@@ -341,12 +381,30 @@ export async function generateChatV2(options) {
|
|
|
341
381
|
}
|
|
342
382
|
const isStructuredOutput = isChatV2StructuredResponseFormat(options.responseFormat);
|
|
343
383
|
const responseText = isStructuredOutput ? collapseRepeatedStructuredJsonText(result.text) : result.text;
|
|
384
|
+
const functionCalls = toStreamedFunctionCalls(result.toolCalls != null && result.toolCalls.length > 0 ? result.toolCalls : stepToolCalls);
|
|
385
|
+
const reasoningPromise = resolveGenerateReasoning(result);
|
|
386
|
+
const usagePromise = resolveGenerateUsage(result);
|
|
387
|
+
let evidence = { text: responseText, functionCalls, reasoning: '' };
|
|
388
|
+
const notifyCurrentResponseEvidence = () => notifyResponseReceived(options, evidence);
|
|
389
|
+
// generateText has already returned its complete text/tool response here.
|
|
390
|
+
// Snapshot it before optional metadata, schema output, or usage access can
|
|
391
|
+
// fail. Independently resolved diagnostic fields refresh that snapshot so a
|
|
392
|
+
// different finalization error cannot hide them.
|
|
393
|
+
notifyCurrentResponseEvidence();
|
|
394
|
+
void reasoningPromise.then((reasoning) => {
|
|
395
|
+
evidence = { ...evidence, reasoning };
|
|
396
|
+
notifyCurrentResponseEvidence();
|
|
397
|
+
}, () => undefined);
|
|
398
|
+
void usagePromise.then((usage) => {
|
|
399
|
+
evidence = { ...evidence, usage };
|
|
400
|
+
notifyCurrentResponseEvidence();
|
|
401
|
+
}, () => undefined);
|
|
344
402
|
const [finishReason, structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await waitForPostResponseFinalization((async () => {
|
|
345
403
|
const finishReason = await resolveOptionalValue(result.finishReason);
|
|
346
404
|
const [structuredOutput, usage, reasoning, providerMetadata, requestStatus] = await Promise.all([
|
|
347
405
|
resolveGenerateStructuredOutput(result, options.responseOutput, finishReason),
|
|
348
|
-
|
|
349
|
-
|
|
406
|
+
usagePromise,
|
|
407
|
+
reasoningPromise,
|
|
350
408
|
resolveOptionalValue(result.providerMetadata),
|
|
351
409
|
resolveOptionalValue(result.requestStatus),
|
|
352
410
|
]);
|
|
@@ -355,7 +413,7 @@ export async function generateChatV2(options) {
|
|
|
355
413
|
return {
|
|
356
414
|
responseText,
|
|
357
415
|
structuredOutput,
|
|
358
|
-
functionCalls
|
|
416
|
+
functionCalls,
|
|
359
417
|
usage,
|
|
360
418
|
reasoning,
|
|
361
419
|
finishReason,
|
|
@@ -67,6 +67,33 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
67
67
|
const callId = createObservedChatV2CallId(options);
|
|
68
68
|
const callStartedAt = Date.now();
|
|
69
69
|
let callWasObserved = false;
|
|
70
|
+
// AI SDK accessors such as usage and reasoning may settle after a request
|
|
71
|
+
// has otherwise failed. Their diagnostic callbacks belong only to this
|
|
72
|
+
// physical request: never let a retired retry/fallback candidate overwrite
|
|
73
|
+
// evidence collected by the current one.
|
|
74
|
+
let acceptsResponseEvidence = true;
|
|
75
|
+
const retireResponseEvidence = () => {
|
|
76
|
+
acceptsResponseEvidence = false;
|
|
77
|
+
};
|
|
78
|
+
let latestResponseEvidence;
|
|
79
|
+
const reportResponseEvidence = (response) => {
|
|
80
|
+
if (!acceptsResponseEvidence) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
latestResponseEvidence = response;
|
|
84
|
+
try {
|
|
85
|
+
chatOptions.onResponseReceived?.(response);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// Diagnostic evidence must not alter a retry/fallback decision.
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const publishAndRetireResponseEvidence = () => {
|
|
92
|
+
if (latestResponseEvidence != null) {
|
|
93
|
+
reportResponseEvidence(latestResponseEvidence);
|
|
94
|
+
}
|
|
95
|
+
retireResponseEvidence();
|
|
96
|
+
};
|
|
70
97
|
const attemptController = new AbortController();
|
|
71
98
|
const abortAttemptFromCaller = () => attemptController.abort(signal.reason);
|
|
72
99
|
if (signal.aborted) {
|
|
@@ -83,11 +110,13 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
83
110
|
streamInactivityTimeoutMs: options.streamInactivityTimeoutMs,
|
|
84
111
|
onStreamActivity: options.onStreamActivity,
|
|
85
112
|
onTimeout: (error) => attemptController.abort(error),
|
|
113
|
+
onResponseReceived: reportResponseEvidence,
|
|
86
114
|
};
|
|
87
115
|
const result = transportMode === 'generate'
|
|
88
116
|
? await generateChatV2(attemptChatOptions)
|
|
89
117
|
: await streamChatV2(attemptChatOptions);
|
|
90
118
|
await options.responseBodyCapture?.flush();
|
|
119
|
+
publishAndRetireResponseEvidence();
|
|
91
120
|
const statusCode = result.requestStatus ?? 200;
|
|
92
121
|
notifyChatV2CallFinished(options, {
|
|
93
122
|
callId,
|
|
@@ -121,6 +150,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
121
150
|
await options.responseBodyCapture?.flush({
|
|
122
151
|
waitForPending: !signal.aborted && !isChatV2ProviderTimeoutError(error),
|
|
123
152
|
});
|
|
153
|
+
publishAndRetireResponseEvidence();
|
|
124
154
|
if (!callWasObserved) {
|
|
125
155
|
notifyChatV2CallFinished(options, {
|
|
126
156
|
callId,
|
|
@@ -154,6 +184,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
|
|
|
154
184
|
await waitForLLMChatV2RetryCooldown(retryPlan.cooldownMs, signal);
|
|
155
185
|
}
|
|
156
186
|
finally {
|
|
187
|
+
retireResponseEvidence();
|
|
157
188
|
signal.removeEventListener('abort', abortAttemptFromCaller);
|
|
158
189
|
}
|
|
159
190
|
}
|
|
@@ -181,6 +212,35 @@ export async function runChatV2PipelineExecution(options) {
|
|
|
181
212
|
tools,
|
|
182
213
|
});
|
|
183
214
|
const shouldStreamResponse = plan.transportMode === 'stream';
|
|
215
|
+
const emitFailureCheckpoint = (partial) => {
|
|
216
|
+
if (options.onFailureCheckpoint == null) {
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
options.onFailureCheckpoint(createChatV2CommonOutputs({
|
|
221
|
+
requestMessages,
|
|
222
|
+
response: partial.text,
|
|
223
|
+
structuredOutput: undefined,
|
|
224
|
+
functionCalls: partial.functionCalls,
|
|
225
|
+
usage: normalizeChatV2Usage(partial.usage, options),
|
|
226
|
+
reasoning: partial.reasoning,
|
|
227
|
+
requestBodies: options.requestBodies,
|
|
228
|
+
responseBodies: options.responseBodies,
|
|
229
|
+
outputUsage: plan.output.outputUsage,
|
|
230
|
+
outputReasoning: plan.output.outputReasoning,
|
|
231
|
+
outputRequestBody: plan.output.outputRequestBody,
|
|
232
|
+
outputResponseBody: plan.output.outputResponseBody,
|
|
233
|
+
includeFunctionCalls: plan.output.includeFunctionCalls,
|
|
234
|
+
functionCallMode: plan.output.functionCallMode,
|
|
235
|
+
// An incomplete structured reply is still useful diagnostic text,
|
|
236
|
+
// not a schema-valid graph result.
|
|
237
|
+
responseFormat: undefined,
|
|
238
|
+
}));
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
// Diagnostic capture must not replace the original provider failure.
|
|
242
|
+
}
|
|
243
|
+
};
|
|
184
244
|
let chatResponse;
|
|
185
245
|
try {
|
|
186
246
|
chatResponse = await runChatV2WithRetry(options, {
|
|
@@ -188,20 +248,23 @@ export async function runChatV2PipelineExecution(options) {
|
|
|
188
248
|
abortSignal: options.context.signal,
|
|
189
249
|
executeStream: options.executeStream,
|
|
190
250
|
executeGenerate: options.executeGenerate,
|
|
251
|
+
onRequestStarted: () => emitFailureCheckpoint({ text: '', functionCalls: [], reasoning: '' }),
|
|
252
|
+
onResponseReceived: emitFailureCheckpoint,
|
|
191
253
|
onPartialOutput: !shouldStreamResponse
|
|
192
254
|
? undefined
|
|
193
|
-
: ({ text, functionCalls }) => {
|
|
255
|
+
: ({ text, functionCalls, reasoning }) => {
|
|
256
|
+
emitFailureCheckpoint({ text, functionCalls, reasoning });
|
|
194
257
|
options.context.onPartialOutputs?.(createChatV2CommonOutputs({
|
|
195
258
|
requestMessages,
|
|
196
259
|
response: text,
|
|
197
260
|
structuredOutput: undefined,
|
|
198
261
|
functionCalls,
|
|
199
262
|
usage: undefined,
|
|
200
|
-
reasoning
|
|
263
|
+
reasoning,
|
|
201
264
|
requestBodies: undefined,
|
|
202
265
|
responseBodies: undefined,
|
|
203
266
|
outputUsage: false,
|
|
204
|
-
outputReasoning:
|
|
267
|
+
outputReasoning: plan.output.outputReasoning,
|
|
205
268
|
outputRequestBody: false,
|
|
206
269
|
outputResponseBody: false,
|
|
207
270
|
includeFunctionCalls: plan.output.includeFunctionCalls,
|
|
@@ -1,42 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* reasoning, and direct results after intermediate rounds complete; historical
|
|
5
|
-
* pages must therefore never retain those mutable references.
|
|
6
|
-
*/
|
|
7
|
-
function cloneOutputValue(value, seen = new WeakMap()) {
|
|
8
|
-
if (value == null || typeof value !== 'object') {
|
|
9
|
-
return value;
|
|
10
|
-
}
|
|
11
|
-
if (value instanceof Uint8Array) {
|
|
12
|
-
return new Uint8Array(value);
|
|
13
|
-
}
|
|
14
|
-
const existing = seen.get(value);
|
|
15
|
-
if (existing != null) {
|
|
16
|
-
return existing;
|
|
17
|
-
}
|
|
18
|
-
if (Array.isArray(value)) {
|
|
19
|
-
const clone = [];
|
|
20
|
-
seen.set(value, clone);
|
|
21
|
-
clone.push(...value.map((item) => cloneOutputValue(item, seen)));
|
|
22
|
-
return clone;
|
|
23
|
-
}
|
|
24
|
-
const clone = {};
|
|
25
|
-
seen.set(value, clone);
|
|
26
|
-
for (const [key, item] of Object.entries(value)) {
|
|
27
|
-
clone[key] = cloneOutputValue(item, seen);
|
|
28
|
-
}
|
|
29
|
-
return clone;
|
|
30
|
-
}
|
|
31
|
-
/** Cycle-safe clone shared by the editor cache and LLM logical-round snapshots. */
|
|
32
|
-
export function cloneLLMChatV2Outputs(outputs) {
|
|
33
|
-
if (typeof structuredClone === 'function') {
|
|
34
|
-
try {
|
|
35
|
-
return structuredClone(outputs);
|
|
36
|
-
}
|
|
37
|
-
catch {
|
|
38
|
-
// Fall through for values structuredClone cannot copy.
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
return cloneOutputValue(outputs);
|
|
42
|
-
}
|
|
1
|
+
export { cloneExecutionOutputs } from '../ExecutionOutputClone.js';
|
|
2
|
+
/** @deprecated Prefer cloneExecutionOutputs for new non-Chat call sites. */
|
|
3
|
+
export { cloneExecutionOutputs as cloneLLMChatV2Outputs } from '../ExecutionOutputClone.js';
|
|
@@ -5,13 +5,18 @@ import { createChatV2CapturedBodyOutputs } from './chatV2Outputs.js';
|
|
|
5
5
|
* Captured HTTP bodies are emitted only through their opt-in ports, while
|
|
6
6
|
* attempts and profile summaries retain the same public shapes as a success.
|
|
7
7
|
*/
|
|
8
|
-
export function projectLLMInvocationDiagnostics({ runOptions, outputLLMAttempts, llmAttempts, profileSummary, }) {
|
|
8
|
+
export function projectLLMInvocationDiagnostics({ runOptions, outputLLMAttempts, modelCalls, outputUsage, llmAttempts, profileSummary, }) {
|
|
9
9
|
const capturedBodies = createChatV2CapturedBodyOutputs(runOptions);
|
|
10
10
|
return {
|
|
11
11
|
...Object.fromEntries(Object.entries(capturedBodies).filter(([, output]) => output?.type !== 'control-flow-excluded')),
|
|
12
|
+
...projectLLMInvocationUsageOutput({ modelCalls, outputUsage }),
|
|
12
13
|
...projectLLMInvocationMetadata({ outputLLMAttempts, llmAttempts, profileSummary }),
|
|
13
14
|
};
|
|
14
15
|
}
|
|
16
|
+
/** Combines streamed response state with terminal diagnostics without hiding either. */
|
|
17
|
+
export function mergeLLMInvocationFailureOutputs(partialOutputs, diagnostics) {
|
|
18
|
+
return { ...partialOutputs, ...diagnostics };
|
|
19
|
+
}
|
|
15
20
|
function projectLLMInvocationMetadata(params) {
|
|
16
21
|
const { outputLLMAttempts, llmAttempts, profileSummary } = params;
|
|
17
22
|
const outputs = {};
|
|
@@ -32,12 +37,10 @@ function projectLLMInvocationMetadata(params) {
|
|
|
32
37
|
/** Applies existing public LLM Chat output shapes from invocation facts. */
|
|
33
38
|
export function projectLLMInvocationResult(params) {
|
|
34
39
|
const { result, modelCalls, outputUsage, outputLLMAttempts, llmAttempts, profileSummary } = params;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
result.commonOutputs['usage'] = { type: 'object', value: physicalUsage };
|
|
40
|
-
}
|
|
40
|
+
const usage = getLLMInvocationUsage({ modelCalls, outputUsage });
|
|
41
|
+
if (usage != null) {
|
|
42
|
+
result.usage = usage;
|
|
43
|
+
result.commonOutputs['usage'] = { type: 'object', value: usage };
|
|
41
44
|
}
|
|
42
45
|
Object.assign(result.commonOutputs, projectLLMInvocationMetadata({
|
|
43
46
|
outputLLMAttempts,
|
|
@@ -46,3 +49,13 @@ export function projectLLMInvocationResult(params) {
|
|
|
46
49
|
}));
|
|
47
50
|
return result.commonOutputs;
|
|
48
51
|
}
|
|
52
|
+
function projectLLMInvocationUsageOutput({ modelCalls, outputUsage, }) {
|
|
53
|
+
const usage = getLLMInvocationUsage({ modelCalls, outputUsage });
|
|
54
|
+
return usage == null ? {} : { ['usage']: { type: 'object', value: usage } };
|
|
55
|
+
}
|
|
56
|
+
function getLLMInvocationUsage({ modelCalls, outputUsage, }) {
|
|
57
|
+
if (!outputUsage || modelCalls.length === 0) {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
return projectLLMInvocationUsage(modelCalls) ?? undefined;
|
|
61
|
+
}
|