@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.
- package/dist/cjs/bundle.cjs +3093 -1440
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/cjs/interpolationRuntime.cjs +40 -4
- package/dist/cjs/interpolationRuntime.cjs.map +2 -2
- package/dist/cjs/serialization.cjs +1880 -0
- package/dist/cjs/serialization.cjs.map +7 -0
- package/dist/cjs/webAppRuntime.cjs +168 -6
- package/dist/cjs/webAppRuntime.cjs.map +3 -3
- package/dist/esm/api/processSettings.js +1 -0
- package/dist/esm/exports.js +2 -0
- package/dist/esm/model/AgentResponseTrace.js +99 -34
- package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
- package/dist/esm/model/DataValue.js +11 -2
- package/dist/esm/model/GlobalVariables.js +2 -1
- package/dist/esm/model/GraphBoundaryEffects.js +38 -1
- package/dist/esm/model/GraphExecutionState.js +81 -0
- package/dist/esm/model/GraphProcessor.js +621 -942
- package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
- package/dist/esm/model/Nodes.js +5 -0
- package/dist/esm/model/ProjectBundle.js +23 -10
- package/dist/esm/model/ProjectBundleRuntime.js +54 -0
- package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
- package/dist/esm/model/SubprocessorBridge.js +125 -87
- package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
- package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
- package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
- package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
- package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
- package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
- package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
- package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
- package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
- package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
- package/dist/esm/model/chat-v2/llmChatV2Body.js +2 -2
- package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
- package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
- package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +18 -8
- package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
- package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
- package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
- package/dist/esm/model/chat-v2/llmProfile.js +2 -1
- package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
- package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
- package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
- package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
- package/dist/esm/model/chat-v2/messageConverter.js +18 -16
- package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
- package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
- package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
- package/dist/esm/model/chat-v2/providerOptions.js +30 -25
- package/dist/esm/model/classifier/credentials.js +13 -3
- package/dist/esm/model/classifier/limits.js +33 -3
- package/dist/esm/model/classifier/perplexity.js +63 -0
- package/dist/esm/model/classifier/profile.js +151 -0
- package/dist/esm/model/classifier/profileExecution.js +294 -0
- package/dist/esm/model/classifier/providers.js +217 -30
- package/dist/esm/model/classifier/state.js +4 -1
- package/dist/esm/model/classifier/types.js +11 -1
- package/dist/esm/model/nodeRunFailure.js +8 -1
- package/dist/esm/model/nodes/CallGraphNode.js +6 -0
- package/dist/esm/model/nodes/ClassifierEvaluateNode.js +250 -59
- package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
- package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
- package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
- package/dist/esm/model/nodes/SubGraphNode.js +3 -0
- package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
- package/dist/esm/model/profileSuspensionHints.js +8 -0
- package/dist/esm/serialization.js +2 -0
- package/dist/esm/utils/coerceType.js +11 -1
- package/dist/esm/webAppRuntime.js +1 -0
- package/dist/types/exports.d.ts +2 -0
- package/dist/types/model/AgentResponseTrace.d.ts +15 -4
- package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
- package/dist/types/model/DataValue.d.ts +12 -8
- package/dist/types/model/ExecutorProtocol.d.ts +7 -0
- package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
- package/dist/types/model/GraphExecutionState.d.ts +68 -0
- package/dist/types/model/GraphProcessor.d.ts +1 -0
- package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
- package/dist/types/model/Nodes.d.ts +7 -4
- package/dist/types/model/ProcessContext.d.ts +12 -3
- package/dist/types/model/ProjectBundle.d.ts +9 -4
- package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
- package/dist/types/model/RivetUIContext.d.ts +1 -1
- package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
- package/dist/types/model/Settings.d.ts +1 -0
- package/dist/types/model/SubprocessorBridge.d.ts +2 -0
- package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
- package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
- package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
- package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
- package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
- package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
- package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
- package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
- package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
- package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
- package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
- package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
- package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
- package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
- package/dist/types/model/classifier/credentials.d.ts +4 -0
- package/dist/types/model/classifier/limits.d.ts +4 -1
- package/dist/types/model/classifier/perplexity.d.ts +7 -0
- package/dist/types/model/classifier/profile.d.ts +46 -0
- package/dist/types/model/classifier/profileExecution.d.ts +32 -0
- package/dist/types/model/classifier/providers.d.ts +32 -1
- package/dist/types/model/classifier/types.d.ts +9 -0
- package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
- package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
- package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
- package/dist/types/model/profileSuspensionHints.d.ts +8 -0
- package/dist/types/serialization.d.ts +2 -0
- package/dist/types/webAppRuntime.d.ts +1 -0
- package/package.json +7 -1
|
@@ -1,15 +1,18 @@
|
|
|
1
|
-
import { JEV_DEFAULT_CREDENTIAL_NAMES, LIQUID_DEFAULT_CREDENTIAL_NAMES, OPENAI_DEFAULT_CREDENTIAL_NAMES, } from './credentials.js';
|
|
1
|
+
import { JEV_DEFAULT_CREDENTIAL_NAMES, LIQUID_DEFAULT_CREDENTIAL_NAMES, OPENAI_DEFAULT_CREDENTIAL_NAMES, OPENROUTER_DEFAULT_CREDENTIAL_NAMES, PERPLEXITY_DEFAULT_CREDENTIAL_NAMES, } from './credentials.js';
|
|
2
2
|
import { assertLiquidImageLimits } from './images.js';
|
|
3
3
|
import { prepareClassifierState, systemOneState, } from './state.js';
|
|
4
4
|
import { validateClassifierEvaluationResponse } from './response.js';
|
|
5
5
|
import { createOpenAIDecisionRequest, validateOpenAIDecisionResponse } from './openai.js';
|
|
6
|
+
import { assertPerplexityDecisionLimits, perplexityDecisionState, PERPLEXITY_DECISION_MODELS } from './perplexity.js';
|
|
6
7
|
import { prepareClassifierQuestion } from './questions.js';
|
|
7
8
|
import { classifierArrayValues } from './json.js';
|
|
8
|
-
import { assertClassifierResourceLimits, ClassifierValueBudget, CLASSIFIER_LIMITS, ClassifierResourceLimitError, readClassifierResponse, } from './limits.js';
|
|
9
|
+
import { assertClassifierResourceLimits, ClassifierValueBudget, CLASSIFIER_LIMITS, ClassifierResourceLimitError, ClassifierResponseReadError, readClassifierResponse, } from './limits.js';
|
|
9
10
|
export { validateApiCompatibleClassifierResponse } from './response.js';
|
|
10
11
|
export const JEV_SYSTEM_ONE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
|
|
11
12
|
export const LIQUID_SYSTEM_ONE_ENDPOINT = 'https://api.liquid.ai/decisions/v1/systemone';
|
|
12
13
|
export const OPENAI_DECISIONS_ENDPOINT = 'https://api.openai.com/v1/decisions';
|
|
14
|
+
export const OPENROUTER_DECISIONS_ENDPOINT = 'https://openrouter.ai/api/alpha/decisions';
|
|
15
|
+
export const PERPLEXITY_DECISIONS_ENDPOINT = 'https://api.perplexity.ai/v1/decisions';
|
|
13
16
|
/** Jev's published USD rates. Keep this Core-owned rather than graph-authored. */
|
|
14
17
|
export const JEV_TOKEN_PRICING = {
|
|
15
18
|
inputPerMillionTokens: 0.042,
|
|
@@ -65,6 +68,22 @@ export const liquidClassifierProvider = createApiCompatibleClassifierProvider({
|
|
|
65
68
|
assertLiquidImageLimits(state.images, check);
|
|
66
69
|
},
|
|
67
70
|
});
|
|
71
|
+
/** Native Decisions API, not chat completions. Microsoft Decision-1 is text-only.
|
|
72
|
+
* https://openrouter.ai/microsoft/microsoft-decision-1
|
|
73
|
+
*/
|
|
74
|
+
export const openrouterClassifierProvider = createApiCompatibleClassifierProvider({
|
|
75
|
+
id: 'openrouter',
|
|
76
|
+
label: 'OpenRouter',
|
|
77
|
+
defaultModel: 'microsoft/microsoft-decision-1',
|
|
78
|
+
credentialNames: OPENROUTER_DEFAULT_CREDENTIAL_NAMES,
|
|
79
|
+
endpoint: OPENROUTER_DECISIONS_ENDPOINT,
|
|
80
|
+
modelPricing: [
|
|
81
|
+
{
|
|
82
|
+
models: ['microsoft/microsoft-decision-1'],
|
|
83
|
+
pricing: { inputPerMillionTokens: 0.042, outputPerMillionTokens: 0 },
|
|
84
|
+
},
|
|
85
|
+
],
|
|
86
|
+
});
|
|
68
87
|
/** Decisions-specific rates, not GPT-6 Luna's Chat/Responses cache/output rates.
|
|
69
88
|
* https://developers.openai.com/api/docs/guides/decisions#pricing-and-availability
|
|
70
89
|
*/
|
|
@@ -89,12 +108,60 @@ export const openaiClassifierProvider = createClassifierProvider({
|
|
|
89
108
|
buildRequest: createOpenAIDecisionRequest,
|
|
90
109
|
validateResponse: validateOpenAIDecisionResponse,
|
|
91
110
|
});
|
|
111
|
+
/** https://docs.perplexity.ai/docs/decisions/quickstart */
|
|
112
|
+
export const perplexityClassifierProvider = createClassifierProvider({
|
|
113
|
+
id: 'perplexity',
|
|
114
|
+
label: 'Perplexity',
|
|
115
|
+
defaultModel: 'pplx-decider-v1.1-27b',
|
|
116
|
+
credentialNames: PERPLEXITY_DEFAULT_CREDENTIAL_NAMES,
|
|
117
|
+
browserExecutionSupported: false,
|
|
118
|
+
endpoint: PERPLEXITY_DECISIONS_ENDPOINT,
|
|
119
|
+
supportsImages: (model) => PERPLEXITY_DECISION_MODELS.includes(model),
|
|
120
|
+
modelPricing: [
|
|
121
|
+
{
|
|
122
|
+
models: PERPLEXITY_DECISION_MODELS,
|
|
123
|
+
pricing: { inputPerMillionTokens: 0.02, outputPerMillionTokens: 0 },
|
|
124
|
+
},
|
|
125
|
+
],
|
|
126
|
+
checkRequest: assertPerplexityDecisionLimits,
|
|
127
|
+
buildRequest: ({ model, state, questions }) => ({
|
|
128
|
+
model,
|
|
129
|
+
state: perplexityDecisionState(state),
|
|
130
|
+
questions: createQuestionMap(questions),
|
|
131
|
+
}),
|
|
132
|
+
validateResponse: validateClassifierEvaluationResponse,
|
|
133
|
+
});
|
|
92
134
|
/** Ordered so adding compatible providers does not alter authored IDs. */
|
|
93
135
|
export const classifierProviders = [
|
|
94
136
|
jevClassifierProvider,
|
|
95
137
|
liquidClassifierProvider,
|
|
96
138
|
openaiClassifierProvider,
|
|
139
|
+
openrouterClassifierProvider,
|
|
140
|
+
perplexityClassifierProvider,
|
|
97
141
|
];
|
|
142
|
+
export class ClassifierProviderError extends Error {
|
|
143
|
+
kind;
|
|
144
|
+
statusCode;
|
|
145
|
+
constructor(message, kind, statusCode, options) {
|
|
146
|
+
super(message, options);
|
|
147
|
+
this.kind = kind;
|
|
148
|
+
this.statusCode = statusCode;
|
|
149
|
+
this.name = 'ClassifierProviderError';
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
export function classifierFailureKind(kind, status) {
|
|
153
|
+
return kind === 'http' && (status === 401 || status === 403) ? 'authentication' : kind;
|
|
154
|
+
}
|
|
155
|
+
/** Bounded preparation/provider explanation, without traversing causes or capturing response bodies. */
|
|
156
|
+
export function classifierErrorMessage(error, apiKey) {
|
|
157
|
+
try {
|
|
158
|
+
const text = error instanceof Error ? error.message : typeof error === 'string' ? error : 'Classifier request failed.';
|
|
159
|
+
return (apiKey ? text.split(apiKey).join('[redacted]') : text).slice(0, 2000);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return 'Classifier request failed with unreadable error metadata.';
|
|
163
|
+
}
|
|
164
|
+
}
|
|
98
165
|
function createOperation(args, label) {
|
|
99
166
|
if (!Number.isFinite(args.timeoutMs) ||
|
|
100
167
|
args.timeoutMs <= 0 ||
|
|
@@ -105,7 +172,7 @@ function createOperation(args, label) {
|
|
|
105
172
|
// Node turns overflowing setTimeout delays into 1 ms, not a long timeout.
|
|
106
173
|
if (deadline - now > MAX_TIMER_DELAY_MS)
|
|
107
174
|
throw new Error(`Classifier effective timeout must not exceed ${MAX_TIMER_DELAY_MS} ms.`);
|
|
108
|
-
const timeoutError = () => new
|
|
175
|
+
const timeoutError = () => new ClassifierProviderError(`${label} request timed out after ${args.timeoutMs} ms.`, 'timeout');
|
|
109
176
|
return {
|
|
110
177
|
signal: args.signal,
|
|
111
178
|
deadline,
|
|
@@ -118,7 +185,7 @@ function createOperation(args, label) {
|
|
|
118
185
|
}
|
|
119
186
|
/** A plain specification and one runner for both graph and direct provider inputs. */
|
|
120
187
|
function createClassifierProvider(spec) {
|
|
121
|
-
const { endpoint, buildRequest, validateResponse, checkState, ...provider } = spec;
|
|
188
|
+
const { endpoint, buildRequest, validateResponse, checkState, checkRequest, ...provider } = spec;
|
|
122
189
|
const evaluate = async (input) => {
|
|
123
190
|
// Reject removed evidence fields before object spread can read a getter or
|
|
124
191
|
// discard non-enumerable/inherited content.
|
|
@@ -150,10 +217,17 @@ function createClassifierProvider(spec) {
|
|
|
150
217
|
questions.push(question);
|
|
151
218
|
}
|
|
152
219
|
if (state.kind === 'messages' && state.images.length && !provider.supportsImages?.(args.model))
|
|
153
|
-
throw new
|
|
154
|
-
|
|
220
|
+
throw new ClassifierProviderError(`${provider.label} model '${args.model}' does not support classifier images.`, 'capability');
|
|
221
|
+
try {
|
|
222
|
+
checkState?.(state, operation.check);
|
|
223
|
+
checkRequest?.({ model: args.model, state, questions }, operation.check);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
operation.check();
|
|
227
|
+
throw new ClassifierProviderError(error instanceof Error ? error.message : `${provider.label} does not support this classifier evidence.`, 'capability', undefined, { cause: error });
|
|
228
|
+
}
|
|
155
229
|
operation.check();
|
|
156
|
-
const result = await callClassifierHttp(args, { endpoint, validateResponse
|
|
230
|
+
const result = await callClassifierHttp(args, { ...provider, endpoint, validateResponse }, { model: args.model, state, questions }, buildRequest, operation);
|
|
157
231
|
operation.check();
|
|
158
232
|
return result;
|
|
159
233
|
};
|
|
@@ -229,11 +303,40 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
|
|
|
229
303
|
assertClassifierResourceLimits(request, operation.check);
|
|
230
304
|
const requestJson = JSON.stringify(request);
|
|
231
305
|
if (maxRequestBytes !== undefined && new TextEncoder().encode(requestJson).byteLength >= maxRequestBytes) {
|
|
232
|
-
throw new
|
|
306
|
+
throw new ClassifierProviderError(`${providerLabel} request must be smaller than ${maxRequestBytes / 1_000_000} MB, including State, images, and questions. Resize images or reduce input content.`, 'capability');
|
|
233
307
|
}
|
|
234
308
|
let requestBody;
|
|
309
|
+
let attemptIndex = -1;
|
|
310
|
+
let attemptStartedAt = 0;
|
|
311
|
+
const report = (outcome, status, kind, classifierUsage, error) => {
|
|
312
|
+
try {
|
|
313
|
+
args.onAttempt?.({
|
|
314
|
+
attemptIndex,
|
|
315
|
+
durationMs: Math.max(0, Date.now() - attemptStartedAt),
|
|
316
|
+
outcome,
|
|
317
|
+
status,
|
|
318
|
+
kind,
|
|
319
|
+
...(classifierUsage ? { classifierUsage } : {}),
|
|
320
|
+
...(error ? { error: classifierErrorMessage(error, apiKey) } : {}),
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
/* Observers cannot alter execution. */
|
|
325
|
+
}
|
|
326
|
+
};
|
|
235
327
|
operation.check();
|
|
236
328
|
for (;;) {
|
|
329
|
+
operation.check();
|
|
330
|
+
attemptIndex++;
|
|
331
|
+
attemptStartedAt = Date.now();
|
|
332
|
+
if (args.onRequestBody) {
|
|
333
|
+
try {
|
|
334
|
+
args.onRequestBody(() => (requestBody ??= JSON.parse(requestJson)));
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
/* Observation only. */
|
|
338
|
+
}
|
|
339
|
+
}
|
|
237
340
|
operation.check();
|
|
238
341
|
const remainingMs = deadline - Date.now();
|
|
239
342
|
const controller = new AbortController();
|
|
@@ -257,9 +360,17 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
|
|
|
257
360
|
}
|
|
258
361
|
catch (error) {
|
|
259
362
|
cleanupAttempt();
|
|
363
|
+
if (signal.aborted) {
|
|
364
|
+
report('aborted', undefined, undefined, undefined, `${providerLabel} request was canceled.`);
|
|
365
|
+
operation.check();
|
|
366
|
+
}
|
|
367
|
+
const kind = controller.signal.aborted && !signal.aborted ? 'timeout' : 'transport';
|
|
368
|
+
report('failure', undefined, kind, undefined, kind === 'timeout'
|
|
369
|
+
? `${providerLabel} request timed out after ${args.timeoutMs} ms.`
|
|
370
|
+
: `${providerLabel} transport request failed.`);
|
|
260
371
|
operation.check(controller.signal);
|
|
261
372
|
if (automaticRetryCount >= MAX_AUTOMATIC_ATTEMPTS - 1) {
|
|
262
|
-
throw new
|
|
373
|
+
throw new ClassifierProviderError(`${providerLabel} request failed after ${MAX_AUTOMATIC_ATTEMPTS} attempts due to a transport error.`, 'transport', undefined, { cause: error });
|
|
263
374
|
}
|
|
264
375
|
automaticRetryCount += 1;
|
|
265
376
|
await waitForRetry(Math.min(250 * 2 ** (automaticRetryCount - 1), deadline - Date.now()), signal, providerLabel);
|
|
@@ -271,56 +382,108 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
|
|
|
271
382
|
catch (error) {
|
|
272
383
|
cleanupAttempt();
|
|
273
384
|
discardResponseBody(response);
|
|
385
|
+
report(signal.aborted ? 'aborted' : 'failure', response.status, signal.aborted ? undefined : 'timeout', undefined, signal.aborted
|
|
386
|
+
? `${providerLabel} request was canceled.`
|
|
387
|
+
: `${providerLabel} request timed out after ${args.timeoutMs} ms.`);
|
|
274
388
|
throw error;
|
|
275
389
|
}
|
|
276
390
|
if (!response.ok) {
|
|
391
|
+
report('failure', response.status, 'http', undefined, response.status === 401 || response.status === 403
|
|
392
|
+
? `${providerLabel} authentication failed (HTTP ${response.status}). Check the ${providerLabel} API key.`
|
|
393
|
+
: `${providerLabel} rejected the request (HTTP ${response.status}).`);
|
|
394
|
+
const retryable = RETRYABLE_STATUSES.has(response.status);
|
|
395
|
+
const permanent = [400, 401, 402, 403, 413, 422].includes(response.status);
|
|
396
|
+
const willRetry = (retryable && automaticRetryCount < MAX_AUTOMATIC_ATTEMPTS - 1) ||
|
|
397
|
+
(!retryable && !permanent && configuredRetryCountUsed < configuredRetryCount);
|
|
398
|
+
if (args.onResponseBody && !willRetry) {
|
|
399
|
+
// Opt-in diagnostics must not hold up fallback on a stalled error body.
|
|
400
|
+
const diagnosticTimer = setTimeout(() => controller.abort(), Math.min(1000, deadline - Date.now()));
|
|
401
|
+
try {
|
|
402
|
+
await waitForAttempt(readClassifierResponse(response, controller.signal, assertAttemptActive, args.onResponseBody), controller.signal);
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
// Missing, malformed, oversized or interrupted diagnostics cannot replace the HTTP rejection.
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
clearTimeout(diagnosticTimer);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
277
411
|
cleanupAttempt();
|
|
278
412
|
// Rejected bodies are not answer outputs. Release every response, not just
|
|
279
413
|
// retries, so caught terminal failures cannot leave connections occupied.
|
|
280
414
|
// Initiate cancellation without awaiting a hostile stream's cleanup;
|
|
281
415
|
// neither the final error nor the next bounded retry may depend on it.
|
|
282
416
|
discardResponseBody(response);
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
417
|
+
// Diagnostic collection introduces an await after receiving the rejection.
|
|
418
|
+
// Caller cancellation and the overall deadline still outrank HTTP suppression.
|
|
419
|
+
// Do not check the diagnostic-only controller: its 1 s cap preserves the HTTP error.
|
|
420
|
+
operation.check();
|
|
421
|
+
if (willRetry) {
|
|
422
|
+
let delayMs;
|
|
423
|
+
if (retryable) {
|
|
424
|
+
automaticRetryCount += 1;
|
|
425
|
+
delayMs = getRetryDelayMs(response.headers.get('retry-after'), automaticRetryCount, deadline);
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
configuredRetryCountUsed += 1;
|
|
429
|
+
delayMs = Math.min(configuredCooldownMs, deadline - Date.now());
|
|
430
|
+
}
|
|
286
431
|
await waitForRetry(delayMs, signal, providerLabel);
|
|
287
432
|
continue;
|
|
288
433
|
}
|
|
289
434
|
if (response.status === 401 || response.status === 403) {
|
|
290
|
-
throw
|
|
291
|
-
statusCode: response.status,
|
|
292
|
-
});
|
|
293
|
-
}
|
|
294
|
-
if (response.status === 422 || response.status === 400) {
|
|
295
|
-
throw Object.assign(new Error(`${providerLabel} rejected the request (HTTP ${response.status}).`), {
|
|
296
|
-
statusCode: response.status,
|
|
297
|
-
});
|
|
435
|
+
throw new ClassifierProviderError(`${providerLabel} authentication failed. Check the ${providerLabel} API key.`, 'http', response.status);
|
|
298
436
|
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
437
|
+
// Repeating an unchanged invalid/oversized request or an unfunded account
|
|
438
|
+
// cannot recover. These remain HTTP failures so profile fallback works.
|
|
439
|
+
if ([400, 402, 413, 422].includes(response.status)) {
|
|
440
|
+
throw new ClassifierProviderError(`${providerLabel} rejected the request (HTTP ${response.status}).`, 'http', response.status);
|
|
303
441
|
}
|
|
304
|
-
throw
|
|
305
|
-
statusCode: response.status,
|
|
306
|
-
});
|
|
442
|
+
throw new ClassifierProviderError(`${providerLabel} request failed (HTTP ${response.status}).`, 'http', response.status);
|
|
307
443
|
}
|
|
308
444
|
let body;
|
|
309
445
|
try {
|
|
310
|
-
body = await waitForAttempt(readClassifierResponse(response, controller.signal, assertAttemptActive), controller.signal);
|
|
446
|
+
body = await waitForAttempt(readClassifierResponse(response, controller.signal, assertAttemptActive, args.onResponseBody), controller.signal);
|
|
311
447
|
assertAttemptActive();
|
|
312
448
|
}
|
|
313
449
|
catch (error) {
|
|
450
|
+
if (signal.aborted) {
|
|
451
|
+
report('aborted', response.status, undefined, undefined, `${providerLabel} request was canceled.`);
|
|
452
|
+
discardResponseBody(response);
|
|
453
|
+
operation.check();
|
|
454
|
+
}
|
|
455
|
+
const kind = controller.signal.aborted && !signal.aborted
|
|
456
|
+
? 'timeout'
|
|
457
|
+
: error instanceof ClassifierResponseReadError
|
|
458
|
+
? 'transport'
|
|
459
|
+
: 'response-parsing';
|
|
460
|
+
report('failure', response.status, kind, undefined, kind === 'timeout'
|
|
461
|
+
? `${providerLabel} request timed out after ${args.timeoutMs} ms.`
|
|
462
|
+
: error instanceof ClassifierResourceLimitError
|
|
463
|
+
? error.message
|
|
464
|
+
: kind === 'transport'
|
|
465
|
+
? `${providerLabel} response body could not be read.`
|
|
466
|
+
: `${providerLabel} returned an invalid JSON response.`);
|
|
314
467
|
discardResponseBody(response);
|
|
315
468
|
operation.check(controller.signal);
|
|
316
469
|
if (error instanceof ClassifierResourceLimitError)
|
|
317
470
|
throw error;
|
|
318
|
-
throw new
|
|
471
|
+
throw new ClassifierProviderError(kind === 'transport'
|
|
472
|
+
? `${providerLabel} response body could not be read.`
|
|
473
|
+
: `${providerLabel} returned an invalid JSON response.`, kind, undefined, { cause: error });
|
|
319
474
|
}
|
|
320
475
|
finally {
|
|
321
476
|
cleanupAttempt();
|
|
322
477
|
}
|
|
323
|
-
|
|
478
|
+
let validatedResponse;
|
|
479
|
+
try {
|
|
480
|
+
validatedResponse = validateResponse(body, prepared.questions, providerLabel);
|
|
481
|
+
}
|
|
482
|
+
catch (error) {
|
|
483
|
+
report('failure', response.status, 'response-validation', classifierAttemptUsage(body, spec, args.model), error instanceof Error ? error.message : `${providerLabel} returned an invalid classifier response.`);
|
|
484
|
+
throw new ClassifierProviderError(error instanceof Error ? error.message : `${providerLabel} returned an invalid classifier response.`, 'response-validation', undefined, { cause: error });
|
|
485
|
+
}
|
|
486
|
+
report('success', response.status, undefined, classifierAttemptUsage(body, spec, args.model));
|
|
324
487
|
return {
|
|
325
488
|
// Preserve the direct-provider result contract, but graph runs with the
|
|
326
489
|
// diagnostic disabled never allocate this second representation.
|
|
@@ -337,6 +500,30 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
|
|
|
337
500
|
};
|
|
338
501
|
}
|
|
339
502
|
}
|
|
503
|
+
/** The bounded reader produced plain JSON; do not require valid answers to retain usable usage. */
|
|
504
|
+
function classifierAttemptUsage(body, provider, requestedModel) {
|
|
505
|
+
if (!body || typeof body !== 'object' || Array.isArray(body) || !Object.hasOwn(body, 'usage'))
|
|
506
|
+
return;
|
|
507
|
+
const { usage, model } = body;
|
|
508
|
+
if (!usage ||
|
|
509
|
+
typeof usage !== 'object' ||
|
|
510
|
+
Array.isArray(usage) ||
|
|
511
|
+
!Object.hasOwn(usage, 'input_tokens') ||
|
|
512
|
+
!Object.hasOwn(usage, 'output_tokens') ||
|
|
513
|
+
!Number.isSafeInteger(usage.input_tokens) ||
|
|
514
|
+
usage.input_tokens < 0 ||
|
|
515
|
+
!Number.isSafeInteger(usage.output_tokens) ||
|
|
516
|
+
usage.output_tokens < 0)
|
|
517
|
+
return;
|
|
518
|
+
const estimatedCostUsd = typeof model === 'string' && Object.hasOwn(body, 'model')
|
|
519
|
+
? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model })
|
|
520
|
+
: undefined;
|
|
521
|
+
return {
|
|
522
|
+
inputTokens: usage.input_tokens,
|
|
523
|
+
outputTokens: usage.output_tokens,
|
|
524
|
+
...(estimatedCostUsd === undefined ? {} : { estimatedCostUsd }),
|
|
525
|
+
};
|
|
526
|
+
}
|
|
340
527
|
/** Bound awaiting even when a custom transport ignores its abort signal. */
|
|
341
528
|
function waitForAttempt(promise, signal, onLateResult) {
|
|
342
529
|
return new Promise((resolve, reject) => {
|
|
@@ -13,8 +13,11 @@ export function prepareClassifierState(input, budget) {
|
|
|
13
13
|
throw new Error('Rivet State input and provider State cannot be supplied together.');
|
|
14
14
|
return prepareRivetState(input.stateInput, budget);
|
|
15
15
|
}
|
|
16
|
-
if (input.stateMessages === undefined)
|
|
16
|
+
if (input.stateMessages === undefined) {
|
|
17
|
+
if (typeof input.state !== 'string' && !record(input.state) && !Array.isArray(input.state))
|
|
18
|
+
throw new Error('State must be text, a JSON object or an array.');
|
|
17
19
|
return { kind: 'json', value: snapshotClassifierJson(input.state, 'State', budget) };
|
|
20
|
+
}
|
|
18
21
|
if (input.state !== '')
|
|
19
22
|
throw new Error('Structured State and multimodal State messages cannot be supplied together.');
|
|
20
23
|
const messages = snapshotClassifierJson(input.stateMessages, 'State', budget);
|
|
@@ -1 +1,11 @@
|
|
|
1
|
-
|
|
1
|
+
/** Secret-free classification used by fallback diagnostics and recording traces. */
|
|
2
|
+
export const classifierFailureKinds = [
|
|
3
|
+
'configuration',
|
|
4
|
+
'capability',
|
|
5
|
+
'authentication',
|
|
6
|
+
'transport',
|
|
7
|
+
'http',
|
|
8
|
+
'timeout',
|
|
9
|
+
'response-parsing',
|
|
10
|
+
'response-validation',
|
|
11
|
+
];
|
|
@@ -36,7 +36,14 @@ export function createCaughtRunFailureOutputs(definitions, error, evidence) {
|
|
|
36
36
|
for (const definition of definitions) {
|
|
37
37
|
outputs[definition.id] = { type: 'control-flow-excluded', value: undefined };
|
|
38
38
|
}
|
|
39
|
-
for (const id of [
|
|
39
|
+
for (const id of [
|
|
40
|
+
'requestBody',
|
|
41
|
+
'responseBody',
|
|
42
|
+
'llmAttempts',
|
|
43
|
+
'llmProfileSummary',
|
|
44
|
+
'classifierAttempts',
|
|
45
|
+
'classifierProfileSummary',
|
|
46
|
+
]) {
|
|
40
47
|
const port = id;
|
|
41
48
|
if (port in outputs && evidence?.[port] != null)
|
|
42
49
|
outputs[port] = evidence[port];
|
|
@@ -102,6 +102,12 @@ export class CallGraphNodeImpl extends NodeImpl {
|
|
|
102
102
|
type: 'object',
|
|
103
103
|
value: graphOutputs,
|
|
104
104
|
};
|
|
105
|
+
// Carry implicit graph metrics outside the wrapped user outputs so the
|
|
106
|
+
// containing processor accounts this invocation just like a Subgraph.
|
|
107
|
+
for (const metric of ['cost', 'costBreakdown']) {
|
|
108
|
+
if (graphOutputs[metric])
|
|
109
|
+
outputs[metric] = graphOutputs[metric];
|
|
110
|
+
}
|
|
105
111
|
if (this.data.useErrorOutput) {
|
|
106
112
|
outputs['error'] = {
|
|
107
113
|
type: 'control-flow-excluded',
|