@techis/ai-runtime 0.0.0-stage → 0.3.0-rc.16
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/LICENSE +122 -0
- package/README.md +56 -3
- package/THIRD_PARTY_NOTICES +34 -0
- package/dist/adapters/gemini.d.ts +3 -0
- package/dist/adapters/gemini.d.ts.map +1 -0
- package/dist/adapters/gemini.js +85 -0
- package/dist/adapters/gemini.js.map +1 -0
- package/dist/adapters/http.d.ts +21 -0
- package/dist/adapters/http.d.ts.map +1 -0
- package/dist/adapters/http.js +86 -0
- package/dist/adapters/http.js.map +1 -0
- package/dist/adapters/mock.d.ts +40 -0
- package/dist/adapters/mock.d.ts.map +1 -0
- package/dist/adapters/mock.js +48 -0
- package/dist/adapters/mock.js.map +1 -0
- package/dist/adapters/moonshot.d.ts +3 -0
- package/dist/adapters/moonshot.d.ts.map +1 -0
- package/dist/adapters/moonshot.js +46 -0
- package/dist/adapters/moonshot.js.map +1 -0
- package/dist/adapters/openai.d.ts +4 -0
- package/dist/adapters/openai.d.ts.map +1 -0
- package/dist/adapters/openai.js +110 -0
- package/dist/adapters/openai.js.map +1 -0
- package/dist/adapters/registry.d.ts +6 -0
- package/dist/adapters/registry.d.ts.map +1 -0
- package/dist/adapters/registry.js +39 -0
- package/dist/adapters/registry.js.map +1 -0
- package/dist/adapters/types.d.ts +60 -0
- package/dist/adapters/types.d.ts.map +1 -0
- package/dist/adapters/types.js +2 -0
- package/dist/adapters/types.js.map +1 -0
- package/dist/adapters/zai.d.ts +27 -0
- package/dist/adapters/zai.d.ts.map +1 -0
- package/dist/adapters/zai.js +111 -0
- package/dist/adapters/zai.js.map +1 -0
- package/dist/bundle-source-factory.d.ts +4 -0
- package/dist/bundle-source-factory.d.ts.map +1 -0
- package/dist/bundle-source-factory.js +5 -0
- package/dist/bundle-source-factory.js.map +1 -0
- package/dist/bundle-source.d.ts +40 -0
- package/dist/bundle-source.d.ts.map +1 -0
- package/dist/bundle-source.js +167 -0
- package/dist/bundle-source.js.map +1 -0
- package/dist/catalog-delivery.d.ts +53 -0
- package/dist/catalog-delivery.d.ts.map +1 -0
- package/dist/catalog-delivery.js +148 -0
- package/dist/catalog-delivery.js.map +1 -0
- package/dist/client.d.ts +33 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +238 -0
- package/dist/client.js.map +1 -0
- package/dist/cost.d.ts +28 -0
- package/dist/cost.d.ts.map +1 -0
- package/dist/cost.js +92 -0
- package/dist/cost.js.map +1 -0
- package/dist/deadline.d.ts +3 -0
- package/dist/deadline.d.ts.map +1 -0
- package/dist/deadline.js +37 -0
- package/dist/deadline.js.map +1 -0
- package/dist/errors.d.ts +64 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +116 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/package-updates.d.ts +24 -0
- package/dist/package-updates.d.ts.map +1 -0
- package/dist/package-updates.js +56 -0
- package/dist/package-updates.js.map +1 -0
- package/dist/reasoning-resolution.d.ts +33 -0
- package/dist/reasoning-resolution.d.ts.map +1 -0
- package/dist/reasoning-resolution.js +89 -0
- package/dist/reasoning-resolution.js.map +1 -0
- package/dist/resolution.d.ts +17 -0
- package/dist/resolution.d.ts.map +1 -0
- package/dist/resolution.js +94 -0
- package/dist/resolution.js.map +1 -0
- package/dist/run.d.ts +45 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/run.js +803 -0
- package/dist/run.js.map +1 -0
- package/dist/scoped-source.d.ts +20 -0
- package/dist/scoped-source.d.ts.map +1 -0
- package/dist/scoped-source.js +112 -0
- package/dist/scoped-source.js.map +1 -0
- package/dist/snapshot.d.ts +40 -0
- package/dist/snapshot.d.ts.map +1 -0
- package/dist/snapshot.js +234 -0
- package/dist/snapshot.js.map +1 -0
- package/dist/types.d.ts +244 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +15 -0
- package/dist/types.js.map +1 -0
- package/dist/version.d.ts +9 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +9 -0
- package/dist/version.js.map +1 -0
- package/package.json +24 -4
- package/third-party-licenses/ajv-formats@3.0.1/LICENSE +21 -0
- package/third-party-licenses/ajv@8.20.0/LICENSE +22 -0
- package/third-party-licenses/fast-deep-equal@3.1.3/LICENSE +21 -0
- package/third-party-licenses/fast-uri@3.1.7/LICENSE +30 -0
- package/third-party-licenses/json-schema-traverse@1.0.0/LICENSE +21 -0
- package/third-party-licenses/require-from-string@2.0.2/license +21 -0
- package/third-party-licenses/typescript@5.9.3/LICENSE.txt +55 -0
- package/third-party-licenses/typescript@5.9.3/ThirdPartyNoticeText.txt +193 -0
- package/third-party-licenses.json +102 -0
package/dist/run.js
ADDED
|
@@ -0,0 +1,803 @@
|
|
|
1
|
+
import { withDeadline } from "./deadline.js";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { compileSchema, deriveReceiptId, hashInstructions, validateReasoningForModel } from "@techis/ai-contracts";
|
|
4
|
+
import { AISubsystemError, AttemptsExhaustedError, BudgetExceededError, CancellationError, ConfigurationInvalidError, CredentialInvalidError, CredentialUnavailableError, InputLimitExceededError, ProviderCallError, InvalidOutputError, UnsupportedAdapterError, UnsupportedCapabilityError } from "./errors.js";
|
|
5
|
+
import { costFromUsage, estimateInputTokens, preflightCostCeiling, priceForModel } from "./cost.js";
|
|
6
|
+
import { resolveEffectiveReasoning } from "./reasoning-resolution.js";
|
|
7
|
+
import { OPERATION_ID_PATTERN, REQUEST_ID_PATTERN } from "./types.js";
|
|
8
|
+
const RETRYABLE_CODE_TO_CLASS = {
|
|
9
|
+
"provider-rate-limit": "provider-rate-limit",
|
|
10
|
+
"provider-timeout": "provider-timeout",
|
|
11
|
+
"provider-server-error": "provider-server-error",
|
|
12
|
+
"network-error": "network-error"
|
|
13
|
+
};
|
|
14
|
+
/** Error classes that reject an invocation before any provider I/O was attempted. */
|
|
15
|
+
const PREFLIGHT_CODES = new Set([
|
|
16
|
+
"configuration-invalid",
|
|
17
|
+
"unsupported-capability",
|
|
18
|
+
"unsupported-adapter",
|
|
19
|
+
"input-limit-exceeded",
|
|
20
|
+
"budget-exceeded"
|
|
21
|
+
]);
|
|
22
|
+
/**
|
|
23
|
+
* The execution engine for one pinned run. Retries re-issue the generation request only:
|
|
24
|
+
* the runtime performs no host side effects between attempts, so a completed business
|
|
25
|
+
* tool action can never be replayed by retry or provider switching.
|
|
26
|
+
*/
|
|
27
|
+
export function createRun(token, snapshot, deps, resolutionWarnings = []) {
|
|
28
|
+
token = structuredClone(token);
|
|
29
|
+
snapshot = structuredClone(snapshot);
|
|
30
|
+
const systemInstructions = token.instructionProjection?.systemInstructions ?? token.persona.systemInstructions;
|
|
31
|
+
const models = new Map(snapshot.catalog.models.map((model) => [model.catalogId, model]));
|
|
32
|
+
const runId = randomUUID();
|
|
33
|
+
return {
|
|
34
|
+
get resolution() { return structuredClone(token); },
|
|
35
|
+
async generate(options) {
|
|
36
|
+
const startedAt = Date.now();
|
|
37
|
+
const admittedAt = performance.now();
|
|
38
|
+
const requestId = typeof options.requestId === "string" && REQUEST_ID_PATTERN.test(options.requestId)
|
|
39
|
+
? options.requestId
|
|
40
|
+
: options.requestId === undefined
|
|
41
|
+
? randomUUID()
|
|
42
|
+
: "invalid-request-id";
|
|
43
|
+
const attempts = [];
|
|
44
|
+
let resolvedOutputSchema;
|
|
45
|
+
let outputValidator;
|
|
46
|
+
let receiptEmitted = false;
|
|
47
|
+
let lastEvidence;
|
|
48
|
+
const emit = async (receipt) => {
|
|
49
|
+
if (receiptEmitted)
|
|
50
|
+
return receipt;
|
|
51
|
+
receiptEmitted = true;
|
|
52
|
+
try {
|
|
53
|
+
await deps.onExecutionReceipt?.(receipt);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
receipt.warnings = [...(receipt.warnings ?? []), "Execution receipt sink failed; the completed generation was not retried."];
|
|
57
|
+
}
|
|
58
|
+
return receipt;
|
|
59
|
+
};
|
|
60
|
+
try {
|
|
61
|
+
if (typeof options.operationId !== "string" || !OPERATION_ID_PATTERN.test(options.operationId)) {
|
|
62
|
+
throw new ConfigurationInvalidError("GenerateOptions.operationId is required and must be a bounded logical identifier (letters, digits, '.', '_', '-'; max 128 characters)");
|
|
63
|
+
}
|
|
64
|
+
const { signal, ...request } = options;
|
|
65
|
+
options = { ...structuredClone(request), signal };
|
|
66
|
+
const warnings = [...resolutionWarnings];
|
|
67
|
+
const profile = token.profile;
|
|
68
|
+
validateInvocationControls(options);
|
|
69
|
+
if (profile.status !== "published") {
|
|
70
|
+
throw new ConfigurationInvalidError(`Profile ${profile.profileId}@${profile.revision} is ${profile.status}; only published profiles are executable`);
|
|
71
|
+
}
|
|
72
|
+
const search = options.operation?.webSearch === true;
|
|
73
|
+
const operation = { ...options.operation, webSearch: search };
|
|
74
|
+
const nativeLimit = operation.openai?.maxToolCalls;
|
|
75
|
+
const searchCount = operation.zai?.searchResultCount;
|
|
76
|
+
if (nativeLimit !== undefined && (!Number.isSafeInteger(nativeLimit) || nativeLimit < 1)) {
|
|
77
|
+
throw new ConfigurationInvalidError("OpenAI maxToolCalls must be a positive integer");
|
|
78
|
+
}
|
|
79
|
+
if (searchCount !== undefined && (!Number.isSafeInteger(searchCount) || searchCount < 1 || searchCount > 50)) {
|
|
80
|
+
throw new ConfigurationInvalidError("ZAI searchResultCount must be an integer from 1 to 50");
|
|
81
|
+
}
|
|
82
|
+
const maxAttempts = Math.min(profile.execution.maxAttempts ?? 3, options.execution?.maxAttempts ?? Infinity, profile.execution.fallbackPolicy === "forward-only" ? 1 + profile.fallbacks.length : Infinity);
|
|
83
|
+
const callerTiming = options.execution?.timingPolicy === "caller";
|
|
84
|
+
const clock = callerTiming ? () => performance.now() : () => Date.now();
|
|
85
|
+
const deadlineMs = callerTiming ? options.execution?.deadlineMs ?? Infinity
|
|
86
|
+
: Math.min(profile.execution.deadlineMs ?? 120_000, options.execution?.deadlineMs ?? Infinity);
|
|
87
|
+
const deadlineAt = (callerTiming ? admittedAt : startedAt) + deadlineMs;
|
|
88
|
+
const deadlineError = () => new AttemptsExhaustedError(`Deadline of ${deadlineMs}ms exhausted.`, { attempts: attempts.length });
|
|
89
|
+
const outputSchema = options.outputSchema ?? (token.persona.outputRequirements.kind === "structured" ? token.persona.outputRequirements.schema : undefined);
|
|
90
|
+
resolvedOutputSchema = outputSchema;
|
|
91
|
+
const structured = token.persona.outputRequirements.kind === "structured" || options.outputSchema !== undefined;
|
|
92
|
+
if (structured) {
|
|
93
|
+
try {
|
|
94
|
+
outputValidator = compileSchema(outputSchema ?? { type: "object" });
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
throw new ConfigurationInvalidError("The requested output schema is not a valid JSON Schema");
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
// Slot planning: adapter availability, version requirements, and modality support are
|
|
101
|
+
// checked before any execution attempt so unsupported requirements fail fast.
|
|
102
|
+
const plans = [];
|
|
103
|
+
const precheckFailures = [];
|
|
104
|
+
for (const [index, slot] of [profile.primary, ...profile.fallbacks].entries()) {
|
|
105
|
+
const role = index === 0 ? "primary" : "fallback";
|
|
106
|
+
const model = models.get(slot.catalogId);
|
|
107
|
+
if (!model) {
|
|
108
|
+
precheckFailures.push(`${role} ${slot.catalogId}: not present in pinned catalog release`);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (model.lifecycle.status === "retired") {
|
|
112
|
+
precheckFailures.push(`${role} ${slot.catalogId}: retired`);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const adapter = deps.registry.get(model.adapterId);
|
|
116
|
+
if (!adapter) {
|
|
117
|
+
precheckFailures.push(`${role} ${slot.catalogId}: adapter "${model.adapterId}" is not installed`);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (!adapter.providers.includes(model.provider)) {
|
|
121
|
+
precheckFailures.push(`${role} ${slot.catalogId}: adapter "${adapter.id}" does not serve provider "${model.provider}"`);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const minVersion = snapshot.manifest.adapterRequirements[model.adapterId]?.minVersion;
|
|
125
|
+
if (minVersion && !satisfiesMin(adapter.version, minVersion)) {
|
|
126
|
+
precheckFailures.push(`${role} ${slot.catalogId}: adapter ${model.adapterId} ${adapter.version} is older than required ${minVersion}`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const slotWarnings = [];
|
|
130
|
+
const images = typeof options.input !== "string" ? options.input.images ?? [] : [];
|
|
131
|
+
if (images.length > 0 && (!adapter.supportedInputModalities.includes("image") || !model.capabilities.inputModalities.includes("image"))) {
|
|
132
|
+
precheckFailures.push(`${role} ${slot.catalogId}: installed adapter ${adapter.id} cannot carry image input`);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (structured && (!adapter.supportsStructuredOutput || !model.capabilities.structuredOutput)) {
|
|
136
|
+
precheckFailures.push(`${role} ${slot.catalogId}: installed adapter ${adapter.id} cannot produce structured output`);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (images.some(image => image.detail) && adapter.id !== "openai-responses") {
|
|
140
|
+
precheckFailures.push(`${role} ${slot.catalogId}: explicit image detail requires the OpenAI adapter`);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const tools = [...(profile.requiredCapabilities.providerTools ?? []), ...(search ? ["web_search"] : [])];
|
|
144
|
+
const missingTools = tools.filter(tool => !adapter.supportedProviderTools?.includes(tool) || !model.capabilities.providerTools.includes(tool));
|
|
145
|
+
if (missingTools.length) {
|
|
146
|
+
precheckFailures.push(`${role} ${slot.catalogId}: installed adapter cannot carry required provider tools ${missingTools.join(", ")}`);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (slot.settings.providerOptions && Object.keys(slot.settings.providerOptions).length) {
|
|
150
|
+
precheckFailures.push(`${role} ${slot.catalogId}: providerOptions are not supported by this runtime`);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
const inputModalitiesNeeded = profile.requiredCapabilities.inputModalities;
|
|
154
|
+
const missingInAdapter = inputModalitiesNeeded.filter((modality) => !adapter.supportedInputModalities.includes(modality));
|
|
155
|
+
if (missingInAdapter.length > 0) {
|
|
156
|
+
precheckFailures.push(`${role} ${slot.catalogId}: installed adapter ${adapter.id} cannot carry ${missingInAdapter.join(", ")} input required by the profile`);
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (model.lifecycle.status === "deprecated") {
|
|
160
|
+
slotWarnings.push(`${role} model ${slot.catalogId} is deprecated; consider adopting a replacement.`);
|
|
161
|
+
}
|
|
162
|
+
if (model.lifecycle.status === "preview" || model.lifecycle.status === "unknown") {
|
|
163
|
+
slotWarnings.push(`${role} model ${slot.catalogId} lifecycle is ${model.lifecycle.status}; availability does not establish GA.`);
|
|
164
|
+
}
|
|
165
|
+
plans.push({ slot, model, role, adapterId: adapter.id, adapterVersion: adapter.version, warnings: slotWarnings });
|
|
166
|
+
}
|
|
167
|
+
if (precheckFailures.length > 0) {
|
|
168
|
+
throw new UnsupportedAdapterError(`Profile ${profile.profileId} has unusable model slots: ${precheckFailures.join("; ")}`, { profileId: profile.profileId, precheckFailures });
|
|
169
|
+
}
|
|
170
|
+
if (options.requestId !== undefined && (typeof options.requestId !== "string" || !REQUEST_ID_PATTERN.test(options.requestId))) {
|
|
171
|
+
throw new ConfigurationInvalidError("GenerateOptions.requestId must be a bounded storage-safe identifier (letters, digits, '.', '_', '-'; max 128 characters)");
|
|
172
|
+
}
|
|
173
|
+
for (const plan of plans)
|
|
174
|
+
warnings.push(...plan.warnings);
|
|
175
|
+
const estimated = estimateInputTokens(options.input);
|
|
176
|
+
estimated.tokens += estimateInputTokens(systemInstructions).tokens;
|
|
177
|
+
if (outputSchema)
|
|
178
|
+
estimated.tokens += estimateInputTokens(JSON.stringify(outputSchema)).tokens;
|
|
179
|
+
for (const plan of plans) {
|
|
180
|
+
const inputLimit = minDefined(profile.caps?.maxInputTokens, deps.clientCaps?.maxInputTokens, options.caps?.maxInputTokens, plan.model.capabilities.maxInputTokens);
|
|
181
|
+
if (estimated.tokens > inputLimit) {
|
|
182
|
+
throw new InputLimitExceededError(`Estimated input of ~${estimated.tokens} tokens (${estimated.basis}) exceeds the ${plan.role} model limit of ${inputLimit} tokens.`, { catalogId: plan.model.catalogId, estimatedInputTokens: estimated.tokens, limit: inputLimit });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const slotIds = new Set(plans.map(plan => plan.slot.catalogId));
|
|
186
|
+
for (const catalogId of Object.keys(profile.effortPolicy?.byModel ?? {})) {
|
|
187
|
+
if (!slotIds.has(catalogId)) {
|
|
188
|
+
throw new ConfigurationInvalidError(`Effort policy model ${catalogId} is not a primary or fallback slot in profile ${profile.profileId}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
for (const catalogId of Object.keys(options.effortByModel ?? {})) {
|
|
192
|
+
if (!slotIds.has(catalogId)) {
|
|
193
|
+
throw new ConfigurationInvalidError(`Effort request model ${catalogId} is not a primary or fallback slot in profile ${profile.profileId}`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// Resolve and validate every primary/fallback before the first provider request.
|
|
197
|
+
// A fallback that cannot honor this invocation must never be discovered only after
|
|
198
|
+
// a billable primary attempt has already occurred.
|
|
199
|
+
const preparedPlans = plans.map(plan => {
|
|
200
|
+
validateProfileSlotSemantics(profile, plan);
|
|
201
|
+
const output = resolveOutputTokens({
|
|
202
|
+
requested: options.maxOutputTokens,
|
|
203
|
+
slotDefault: plan.slot.settings.defaultMaxOutputTokens,
|
|
204
|
+
profileDefault: profile.defaults?.maxOutputTokens,
|
|
205
|
+
modelCapability: plan.model.capabilities.maxOutputTokens,
|
|
206
|
+
profileCap: profile.caps?.maxOutputTokens,
|
|
207
|
+
clientCap: deps.clientCaps?.maxOutputTokens,
|
|
208
|
+
invocationCap: options.caps?.maxOutputTokens
|
|
209
|
+
});
|
|
210
|
+
const effort = resolveEffectiveReasoning(plan.model, plan.slot.settings, {
|
|
211
|
+
effortHint: options.effortHint,
|
|
212
|
+
exactEffort: options.effortByModel?.[plan.model.catalogId],
|
|
213
|
+
effortPolicy: profile.effortPolicy
|
|
214
|
+
});
|
|
215
|
+
warnings.push(...effort.notes);
|
|
216
|
+
const semanticErrors = validateReasoningForModel(plan.model, effort.effective);
|
|
217
|
+
if (semanticErrors.length > 0) {
|
|
218
|
+
throw new UnsupportedCapabilityError(semanticErrors.join("; "), { catalogId: plan.slot.catalogId });
|
|
219
|
+
}
|
|
220
|
+
let nativeSettings;
|
|
221
|
+
try {
|
|
222
|
+
nativeSettings = deps.registry.get(plan.model.adapterId).translateReasoning(plan.model, effort.effective);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
throw new UnsupportedCapabilityError(`Adapter ${plan.adapterId} cannot translate native reasoning for ${plan.model.catalogId}`, { adapterId: plan.adapterId, catalogId: plan.model.catalogId });
|
|
226
|
+
}
|
|
227
|
+
const ceiling = preflightCostCeiling(priceForModel(snapshot.catalog, snapshot.manifest, plan.slot.catalogId), estimated.tokens, output.effective ?? plan.model.capabilities.maxOutputTokens);
|
|
228
|
+
return { plan, effort, nativeSettings, output, preflightCost: toCostEstimate(ceiling, "preflight-estimate") };
|
|
229
|
+
});
|
|
230
|
+
// The applicable cost-ceiling policy: profile, client, and invocation caps intersect.
|
|
231
|
+
const budget = intersectCostCaps(profile.caps?.maxEstimatedCost, deps.clientCaps?.maxEstimatedCost, options.caps?.maxEstimatedCost);
|
|
232
|
+
let reservedCost = 0;
|
|
233
|
+
const retryableClasses = new Set(profile.execution.retry.retryableErrorClasses);
|
|
234
|
+
let attemptIndex = 0;
|
|
235
|
+
let lastError;
|
|
236
|
+
while (attemptIndex < Math.min(maxAttempts, profile.execution.fallbackPolicy === "forward-only" ? preparedPlans.length : Infinity)) {
|
|
237
|
+
if (options.signal?.aborted)
|
|
238
|
+
throw new CancellationError();
|
|
239
|
+
const remaining = deadlineAt - clock();
|
|
240
|
+
if (remaining <= 0) {
|
|
241
|
+
throw new AttemptsExhaustedError(`Deadline of ${deadlineMs}ms exhausted before attempt ${attemptIndex + 1}.`, { attempts: attempts.length });
|
|
242
|
+
}
|
|
243
|
+
const evidence = preparedPlans[attemptIndex % preparedPlans.length];
|
|
244
|
+
const { plan, nativeSettings, output } = evidence;
|
|
245
|
+
const price = priceForModel(snapshot.catalog, snapshot.manifest, plan.slot.catalogId);
|
|
246
|
+
if (price?.schemaVersion === 2)
|
|
247
|
+
warnings.push(`Price ${price.priceRevisionId} uses rates observed at ${price.observedAt}; ` +
|
|
248
|
+
`provider effective-from ${price.effectiveDate ?? "unknown"}. Cost remains an estimate from the exact pinned observation.`);
|
|
249
|
+
lastEvidence = evidence;
|
|
250
|
+
let reservedForAttempt = 0;
|
|
251
|
+
if (budget) {
|
|
252
|
+
if (search)
|
|
253
|
+
throw new BudgetExceededError("Cannot enforce search cost ceiling without verified tool pricing and metering");
|
|
254
|
+
if (!evidence.preflightCost.priceKnown || budget.currency !== evidence.preflightCost.currency) {
|
|
255
|
+
throw new BudgetExceededError("Cannot enforce configured cost ceiling: missing or incompatible prices");
|
|
256
|
+
}
|
|
257
|
+
if (reservedCost + evidence.preflightCost.amount > budget.amount) {
|
|
258
|
+
throw new BudgetExceededError("Conservative cumulative preflight estimate exceeds configured ceiling");
|
|
259
|
+
}
|
|
260
|
+
// A timed-out request may have consumed the full allowance. Reserve before I/O.
|
|
261
|
+
reservedForAttempt = evidence.preflightCost.amount;
|
|
262
|
+
reservedCost += reservedForAttempt;
|
|
263
|
+
}
|
|
264
|
+
attemptIndex += 1;
|
|
265
|
+
const attemptStartedAt = Date.now();
|
|
266
|
+
const attemptTimeout = callerTiming ? options.execution?.attemptTimeoutMs ?? Infinity
|
|
267
|
+
: Math.min(remaining, profile.execution.attemptTimeoutMs ?? 60_000, options.execution?.attemptTimeoutMs ?? Infinity);
|
|
268
|
+
let providerRequestStarted = false;
|
|
269
|
+
let response;
|
|
270
|
+
try {
|
|
271
|
+
const adapter = deps.registry.get(plan.model.adapterId);
|
|
272
|
+
const connection = token.connections[plan.model.provider];
|
|
273
|
+
if (!connection) {
|
|
274
|
+
throw new CredentialUnavailableError(`No connection configured for provider "${plan.model.provider}" in ${token.applicationId}/${token.environmentId}`, { provider: plan.model.provider });
|
|
275
|
+
}
|
|
276
|
+
const scheduledAttempt = async (queueSignal) => {
|
|
277
|
+
const attemptContext = {
|
|
278
|
+
attemptId: `${requestId}-attempt-${attemptIndex}`,
|
|
279
|
+
catalogId: plan.model.catalogId,
|
|
280
|
+
providerModelId: plan.model.providerModelId,
|
|
281
|
+
provider: plan.model.provider,
|
|
282
|
+
providerTools: plan.model.capabilities.providerTools,
|
|
283
|
+
webSearch: Boolean(search),
|
|
284
|
+
remainingDeadlineMs: deadlineAt - clock(),
|
|
285
|
+
signal: queueSignal
|
|
286
|
+
};
|
|
287
|
+
let admitted = false;
|
|
288
|
+
const startAttempt = async () => {
|
|
289
|
+
if (queueSignal?.aborted)
|
|
290
|
+
throw options.signal?.aborted ? new CancellationError() : deadlineError();
|
|
291
|
+
if (callerTiming && deadlineAt - clock() <= 0)
|
|
292
|
+
throw deadlineError();
|
|
293
|
+
if (admitted)
|
|
294
|
+
throw new ConfigurationInvalidError("An attempt may only be admitted once");
|
|
295
|
+
admitted = true;
|
|
296
|
+
const admittedTimeout = callerTiming ? Math.min(attemptTimeout, deadlineAt - clock()) : attemptTimeout;
|
|
297
|
+
const attemptDeadlineAt = clock() + admittedTimeout;
|
|
298
|
+
return withDeadline(async (signal) => {
|
|
299
|
+
const credential = await deps.credentialResolver.resolve(connection.credentialReference, {
|
|
300
|
+
applicationId: token.applicationId,
|
|
301
|
+
environmentId: token.environmentId,
|
|
302
|
+
provider: plan.model.provider
|
|
303
|
+
}).catch((resolverError) => {
|
|
304
|
+
// A decryptable-failure (corrupt/undecryptable secure store) stops with an
|
|
305
|
+
// actionable status; a missing credential records a skip and moves forward.
|
|
306
|
+
if (resolverError instanceof CredentialInvalidError)
|
|
307
|
+
throw resolverError;
|
|
308
|
+
throw new CredentialUnavailableError(`Credential unavailable for provider ${plan.model.provider}`);
|
|
309
|
+
});
|
|
310
|
+
const assertDispatchAllowed = () => {
|
|
311
|
+
if (options.signal?.aborted)
|
|
312
|
+
throw new CancellationError();
|
|
313
|
+
if (signal.aborted || (callerTiming && clock() >= attemptDeadlineAt)) {
|
|
314
|
+
throw new ProviderCallError("provider-timeout", "Attempt deadline exceeded before dispatch", true);
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
assertDispatchAllowed();
|
|
318
|
+
const dispatchTimeout = callerTiming ? Math.min(attemptDeadlineAt, deadlineAt) - clock() : attemptTimeout;
|
|
319
|
+
const guardedFetch = (input, init) => {
|
|
320
|
+
assertDispatchAllowed();
|
|
321
|
+
return deps.fetchImpl(input, { ...init, signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal });
|
|
322
|
+
};
|
|
323
|
+
providerRequestStarted = true;
|
|
324
|
+
const result = await adapter.execute({
|
|
325
|
+
model: plan.model,
|
|
326
|
+
systemInstructions,
|
|
327
|
+
input: options.input,
|
|
328
|
+
outputSchema,
|
|
329
|
+
operation,
|
|
330
|
+
nativeSettings,
|
|
331
|
+
...(output.effective !== undefined ? { maxOutputTokens: output.effective } : {}),
|
|
332
|
+
temperature: plan.slot.settings.temperature,
|
|
333
|
+
endpoint: connection.endpoint ?? adapter.defaultEndpoint,
|
|
334
|
+
credential,
|
|
335
|
+
timeoutMs: dispatchTimeout,
|
|
336
|
+
signal
|
|
337
|
+
}, guardedFetch);
|
|
338
|
+
assertDispatchAllowed();
|
|
339
|
+
return result;
|
|
340
|
+
}, admittedTimeout, () => new ProviderCallError("provider-timeout", "Attempt deadline exceeded", true), queueSignal);
|
|
341
|
+
};
|
|
342
|
+
return (deps.attemptExecutor ?? ((_context, start) => start()))(attemptContext, startAttempt);
|
|
343
|
+
};
|
|
344
|
+
response = callerTiming
|
|
345
|
+
? await withDeadline(scheduledAttempt, deadlineAt - clock(), deadlineError, options.signal)
|
|
346
|
+
: await scheduledAttempt(options.signal);
|
|
347
|
+
if (options.signal?.aborted)
|
|
348
|
+
throw new CancellationError();
|
|
349
|
+
if (callerTiming && clock() >= deadlineAt)
|
|
350
|
+
throw deadlineError();
|
|
351
|
+
if (response.output.kind === "refusal") {
|
|
352
|
+
throw new InvalidOutputError("Provider returned a refusal");
|
|
353
|
+
}
|
|
354
|
+
let value;
|
|
355
|
+
if (structured) {
|
|
356
|
+
if (response.output.kind === "structured") {
|
|
357
|
+
value = response.output.value;
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
try {
|
|
361
|
+
value = JSON.parse(response.output.text);
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
throw new InvalidOutputError(`Provider returned non-JSON output where structured output was required (persona ${token.personaId}).`);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const result = outputValidator(value);
|
|
368
|
+
if (!result.valid) {
|
|
369
|
+
throw new InvalidOutputError(`Provider output does not conform to the requested output schema: ${result.errors.slice(0, 5).join("; ")}`);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const cost = withUnknownToolCharges(toCostEstimate(costFromUsage(response.usage, price), response.usage ? "reported-usage" : "preflight-estimate"), search);
|
|
373
|
+
// Search is not uniformly metered across providers; token costs alone are not the total.
|
|
374
|
+
if (search) {
|
|
375
|
+
warnings.push("Total cost is unknown because provider-hosted tool charges are not fully metered.");
|
|
376
|
+
}
|
|
377
|
+
if (!cost.priceKnown) {
|
|
378
|
+
warnings.push(`Pricing for model ${plan.slot.catalogId} is unknown for at least one used dimension; cost estimate omitted (unknown is never zero).`);
|
|
379
|
+
}
|
|
380
|
+
if (!response.usage)
|
|
381
|
+
warnings.push("Provider did not report usage; cost basis is a conservative preflight estimate.");
|
|
382
|
+
attempts.push({
|
|
383
|
+
attempt: attemptIndex,
|
|
384
|
+
catalogId: plan.slot.catalogId,
|
|
385
|
+
providerModelId: plan.model.providerModelId,
|
|
386
|
+
role: plan.role,
|
|
387
|
+
latencyMs: Date.now() - attemptStartedAt,
|
|
388
|
+
outcome: "succeeded",
|
|
389
|
+
providerRequestStarted,
|
|
390
|
+
effective: effectiveControls(token.profile, evidence),
|
|
391
|
+
usage: response.usage,
|
|
392
|
+
costEstimate: cost
|
|
393
|
+
});
|
|
394
|
+
const totalCost = summarizeAttemptCosts(attempts);
|
|
395
|
+
if (attempts.length > 1 && totalCost?.basis === "preflight-estimate") {
|
|
396
|
+
warnings.push("Total cost includes conservative preflight estimates for attempts without reported usage.");
|
|
397
|
+
}
|
|
398
|
+
const receipt = await emit(buildReceipt({
|
|
399
|
+
status: "succeeded",
|
|
400
|
+
runId,
|
|
401
|
+
requestId,
|
|
402
|
+
operationId: options.operationId,
|
|
403
|
+
token,
|
|
404
|
+
snapshot,
|
|
405
|
+
attempts,
|
|
406
|
+
requested: requestedBlock(options, resolvedOutputSchema),
|
|
407
|
+
evidence: lastEvidence,
|
|
408
|
+
usage: response.usage,
|
|
409
|
+
cost: totalCost,
|
|
410
|
+
warnings,
|
|
411
|
+
startedAt
|
|
412
|
+
}));
|
|
413
|
+
return {
|
|
414
|
+
output: structured ? { kind: "structured", value } : { kind: "text", text: response.output.text },
|
|
415
|
+
executionReceipt: receipt
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
catch (error) {
|
|
419
|
+
const aiError = error instanceof AISubsystemError ? error : new AISubsystemError("network-error", "Provider adapter failed unexpectedly", true);
|
|
420
|
+
// Queue rejection, missing credentials, and other failures before adapter
|
|
421
|
+
// execution cannot consume provider budget. Release only those reservations;
|
|
422
|
+
// once adapter execution starts, retain the conservative allowance.
|
|
423
|
+
if (!providerRequestStarted && reservedForAttempt > 0) {
|
|
424
|
+
reservedCost -= reservedForAttempt;
|
|
425
|
+
reservedForAttempt = 0;
|
|
426
|
+
}
|
|
427
|
+
if (options.signal?.aborted || aiError.code === "cancelled") {
|
|
428
|
+
attempts.push({
|
|
429
|
+
attempt: attemptIndex,
|
|
430
|
+
catalogId: plan.slot.catalogId,
|
|
431
|
+
providerModelId: plan.model.providerModelId,
|
|
432
|
+
role: plan.role,
|
|
433
|
+
latencyMs: Date.now() - attemptStartedAt,
|
|
434
|
+
outcome: "cancelled",
|
|
435
|
+
providerRequestStarted,
|
|
436
|
+
effective: effectiveControls(token.profile, evidence),
|
|
437
|
+
errorClass: "cancelled",
|
|
438
|
+
usage: response?.usage,
|
|
439
|
+
costEstimate: withUnknownToolCharges(response?.usage ? toCostEstimate(costFromUsage(response.usage, price), "reported-usage") : evidence.preflightCost, search)
|
|
440
|
+
});
|
|
441
|
+
throw new CancellationError();
|
|
442
|
+
}
|
|
443
|
+
const errorClass = RETRYABLE_CODE_TO_CLASS[aiError.code];
|
|
444
|
+
// Explicit model unavailability always moves the chain forward (the slot is
|
|
445
|
+
// recorded as skipped); other classes follow the profile's retry policy.
|
|
446
|
+
const eligible = aiError.code === "model-unavailable" || aiError.code === "credential-unavailable" ||
|
|
447
|
+
(aiError.retryable && errorClass !== undefined && retryableClasses.has(errorClass));
|
|
448
|
+
attempts.push({
|
|
449
|
+
attempt: attemptIndex,
|
|
450
|
+
catalogId: plan.slot.catalogId,
|
|
451
|
+
providerModelId: plan.model.providerModelId,
|
|
452
|
+
role: plan.role,
|
|
453
|
+
latencyMs: Date.now() - attemptStartedAt,
|
|
454
|
+
outcome: "failed",
|
|
455
|
+
providerRequestStarted,
|
|
456
|
+
effective: effectiveControls(token.profile, evidence),
|
|
457
|
+
errorClass: aiError.code,
|
|
458
|
+
errorMessage: receiptErrorMessage(aiError),
|
|
459
|
+
usage: response?.usage,
|
|
460
|
+
costEstimate: withUnknownToolCharges(response?.usage ? toCostEstimate(costFromUsage(response.usage, price), "reported-usage") : evidence.preflightCost, search)
|
|
461
|
+
});
|
|
462
|
+
if (!eligible)
|
|
463
|
+
throw aiError;
|
|
464
|
+
lastError = aiError;
|
|
465
|
+
if (profile.execution.retry.minRetryDelayMs && attemptIndex < maxAttempts &&
|
|
466
|
+
(profile.execution.fallbackPolicy !== "forward-only" || attemptIndex < plans.length)) {
|
|
467
|
+
await new Promise((resolve, reject) => {
|
|
468
|
+
const done = () => { options.signal?.removeEventListener("abort", abort); resolve(); };
|
|
469
|
+
const timer = setTimeout(done, Math.min(profile.execution.retry.minRetryDelayMs, Math.max(0, deadlineAt - clock())));
|
|
470
|
+
const abort = () => { clearTimeout(timer); reject(new CancellationError()); };
|
|
471
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
472
|
+
if (options.signal?.aborted)
|
|
473
|
+
abort();
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
throw new AttemptsExhaustedError(`All ${maxAttempts} attempts exhausted for persona ${token.personaId}: ${attempts.map((a) => `${a.catalogId}: ${a.errorClass}`).join("; ")}`, { attempts: attempts.length, lastError: lastError?.code });
|
|
479
|
+
}
|
|
480
|
+
catch (error) {
|
|
481
|
+
const aiError = error instanceof AISubsystemError
|
|
482
|
+
? error
|
|
483
|
+
: new AISubsystemError("network-error", error instanceof Error ? error.message : "Unexpected execution failure", true);
|
|
484
|
+
const status = aiError.code === "cancelled"
|
|
485
|
+
? "cancelled"
|
|
486
|
+
: PREFLIGHT_CODES.has(aiError.code) && attempts.length === 0
|
|
487
|
+
? "rejected"
|
|
488
|
+
: "failed";
|
|
489
|
+
const receiptOperationId = typeof options.operationId === "string" &&
|
|
490
|
+
OPERATION_ID_PATTERN.test(options.operationId)
|
|
491
|
+
? options.operationId
|
|
492
|
+
: "invalid-operation-id";
|
|
493
|
+
const receipt = await emit(buildReceipt({
|
|
494
|
+
status,
|
|
495
|
+
runId,
|
|
496
|
+
requestId,
|
|
497
|
+
operationId: receiptOperationId,
|
|
498
|
+
token,
|
|
499
|
+
snapshot,
|
|
500
|
+
attempts,
|
|
501
|
+
requested: requestedBlock(options, resolvedOutputSchema),
|
|
502
|
+
evidence: lastEvidence,
|
|
503
|
+
cost: summarizeAttemptCosts(attempts),
|
|
504
|
+
warnings: [...resolutionWarnings],
|
|
505
|
+
startedAt,
|
|
506
|
+
error: { code: aiError.code, message: receiptErrorMessage(aiError) }
|
|
507
|
+
}));
|
|
508
|
+
aiError.executionReceipt = receipt;
|
|
509
|
+
throw aiError;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
function validateInvocationControls(options) {
|
|
515
|
+
if (options.maxOutputTokens !== undefined && (!Number.isSafeInteger(options.maxOutputTokens) || options.maxOutputTokens <= 0)) {
|
|
516
|
+
throw new ConfigurationInvalidError("GenerateOptions.maxOutputTokens must be a positive integer");
|
|
517
|
+
}
|
|
518
|
+
validateExecutionCaps(options.caps, "Invocation");
|
|
519
|
+
for (const [name, value] of Object.entries(options.execution ?? {})) {
|
|
520
|
+
if (name === "timingPolicy") {
|
|
521
|
+
if (value !== undefined && value !== "profile" && value !== "caller") {
|
|
522
|
+
throw new ConfigurationInvalidError("Execution timingPolicy must be profile or caller");
|
|
523
|
+
}
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
if (value !== undefined && (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)) {
|
|
527
|
+
throw new ConfigurationInvalidError(`Execution setting ${name} must be a positive integer`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
if (options.effortHint !== undefined && (typeof options.effortHint !== "string" || options.effortHint.length === 0 || options.effortHint.length > 128)) {
|
|
531
|
+
throw new ConfigurationInvalidError("effortHint must be a non-empty string of at most 128 characters");
|
|
532
|
+
}
|
|
533
|
+
const byModel = options.effortByModel;
|
|
534
|
+
if (byModel !== undefined) {
|
|
535
|
+
const entries = Object.entries(byModel);
|
|
536
|
+
if (entries.length > 32)
|
|
537
|
+
throw new ConfigurationInvalidError("effortByModel supports at most 32 model entries");
|
|
538
|
+
for (const [catalogId, level] of entries) {
|
|
539
|
+
if (!catalogId || catalogId.length > 128 || typeof level !== "string" || level.length === 0 || level.length > 128) {
|
|
540
|
+
throw new ConfigurationInvalidError("effortByModel keys and values must be bounded non-empty strings");
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
export function validateExecutionCaps(caps, label) {
|
|
546
|
+
if (caps !== undefined && (caps === null || typeof caps !== "object" || Array.isArray(caps))) {
|
|
547
|
+
throw new ConfigurationInvalidError(`${label} caps must be an object`);
|
|
548
|
+
}
|
|
549
|
+
const entries = Object.entries(caps ?? {});
|
|
550
|
+
const allowed = new Set(["maxInputTokens", "maxOutputTokens", "maxEstimatedCost"]);
|
|
551
|
+
const unknown = entries.map(([name]) => name).filter(name => !allowed.has(name));
|
|
552
|
+
if (unknown.length > 0)
|
|
553
|
+
throw new ConfigurationInvalidError(`${label} caps contain unknown fields: ${unknown.join(", ")}`);
|
|
554
|
+
for (const [name, value] of entries) {
|
|
555
|
+
if (value === undefined)
|
|
556
|
+
continue;
|
|
557
|
+
if (name === "maxEstimatedCost") {
|
|
558
|
+
const cost = value;
|
|
559
|
+
const costKeys = cost && typeof cost === "object" && !Array.isArray(cost) ? Object.keys(cost) : [];
|
|
560
|
+
if (costKeys.some(key => key !== "currency" && key !== "amount") ||
|
|
561
|
+
typeof cost?.currency !== "string" || cost.currency.length !== 3 ||
|
|
562
|
+
typeof cost?.amount !== "number" || !Number.isFinite(cost.amount) || cost.amount < 0) {
|
|
563
|
+
throw new ConfigurationInvalidError(`${label} cap maxEstimatedCost requires a 3-letter currency and a non-negative amount`);
|
|
564
|
+
}
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
568
|
+
throw new ConfigurationInvalidError(`${label} cap ${name} must be a positive integer`);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
function validateProfileSlotSemantics(profile, plan) {
|
|
572
|
+
const { model, slot, role } = plan;
|
|
573
|
+
const invalid = (message) => {
|
|
574
|
+
throw new ConfigurationInvalidError(`${role} ${slot.catalogId}: ${message}`, { profileId: profile.profileId, catalogId: slot.catalogId });
|
|
575
|
+
};
|
|
576
|
+
if (slot.settings.defaultMaxOutputTokens !== undefined && slot.settings.defaultMaxOutputTokens > model.capabilities.maxOutputTokens) {
|
|
577
|
+
invalid(`slot default max output ${slot.settings.defaultMaxOutputTokens} exceeds model capability ${model.capabilities.maxOutputTokens}`);
|
|
578
|
+
}
|
|
579
|
+
if (profile.defaults?.maxOutputTokens !== undefined && profile.defaults.maxOutputTokens > model.capabilities.maxOutputTokens) {
|
|
580
|
+
invalid(`profile default max output ${profile.defaults.maxOutputTokens} exceeds model capability ${model.capabilities.maxOutputTokens}`);
|
|
581
|
+
}
|
|
582
|
+
if (profile.caps?.maxOutputTokens !== undefined && profile.caps.maxOutputTokens > model.capabilities.maxOutputTokens) {
|
|
583
|
+
invalid(`profile max output cap ${profile.caps.maxOutputTokens} exceeds model capability ${model.capabilities.maxOutputTokens}`);
|
|
584
|
+
}
|
|
585
|
+
if (profile.caps?.maxInputTokens !== undefined && profile.caps.maxInputTokens > model.capabilities.maxInputTokens) {
|
|
586
|
+
invalid(`profile max input cap ${profile.caps.maxInputTokens} exceeds model capability ${model.capabilities.maxInputTokens}`);
|
|
587
|
+
}
|
|
588
|
+
const configured = slot.settings.reasoning;
|
|
589
|
+
if (profile.effortPolicy?.enabled && configured && configured.mode !== "effort" && configured.mode !== "provider-default") {
|
|
590
|
+
invalid(`effort policy cannot preserve effort hints through a ${configured.mode} reasoning control`);
|
|
591
|
+
}
|
|
592
|
+
const policy = profile.effortPolicy?.byModel?.[slot.catalogId];
|
|
593
|
+
if (!policy)
|
|
594
|
+
return;
|
|
595
|
+
const levels = model.nativeReasoning.supportedEffortLevels;
|
|
596
|
+
if (!levels || !model.nativeReasoning.supportedControls.includes("effort")) {
|
|
597
|
+
invalid("effort policy has bounds or translations but the model does not support effort levels");
|
|
598
|
+
}
|
|
599
|
+
const supportedLevels = levels;
|
|
600
|
+
const rank = (level) => supportedLevels.indexOf(level);
|
|
601
|
+
const assertLevel = (kind, level) => {
|
|
602
|
+
if (rank(level) < 0)
|
|
603
|
+
invalid(`effort policy ${kind} "${level}" is not a supported native level`);
|
|
604
|
+
};
|
|
605
|
+
if (policy.minimum !== undefined)
|
|
606
|
+
assertLevel("minimum", policy.minimum);
|
|
607
|
+
if (policy.maximum !== undefined)
|
|
608
|
+
assertLevel("maximum", policy.maximum);
|
|
609
|
+
for (const [hint, native] of Object.entries(policy.translations ?? {}))
|
|
610
|
+
assertLevel(`translation of "${hint}"`, native);
|
|
611
|
+
if (policy.minimum !== undefined && policy.maximum !== undefined && rank(policy.minimum) > rank(policy.maximum)) {
|
|
612
|
+
invalid(`effort policy minimum "${policy.minimum}" ranks above maximum "${policy.maximum}" in catalog-declared ordering`);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Receipt error text crosses a telemetry/storage boundary and therefore never copies an
|
|
617
|
+
* exception message. Provider SDKs and credential stores can include response bodies,
|
|
618
|
+
* endpoints, or credential material in those messages. The stable error code remains the
|
|
619
|
+
* diagnostic key; this allowlist supplies only bounded, non-sensitive context.
|
|
620
|
+
*/
|
|
621
|
+
function receiptErrorMessage(error) {
|
|
622
|
+
const messages = {
|
|
623
|
+
"configuration-invalid": "Execution configuration is invalid.",
|
|
624
|
+
"configuration-unavailable": "Execution configuration is unavailable.",
|
|
625
|
+
"configuration-revoked": "Execution configuration has been revoked.",
|
|
626
|
+
"unsupported-capability": "A requested capability is unsupported.",
|
|
627
|
+
"unsupported-adapter": "A required provider adapter is unavailable.",
|
|
628
|
+
"credential-unavailable": "A required provider credential is unavailable.",
|
|
629
|
+
"credential-invalid": "A required provider credential is invalid.",
|
|
630
|
+
"model-unavailable": "The requested model is unavailable.",
|
|
631
|
+
"provider-rate-limit": "The provider rate limit was reached.",
|
|
632
|
+
"provider-timeout": "The provider request timed out.",
|
|
633
|
+
"provider-server-error": "The provider returned a server error.",
|
|
634
|
+
"provider-invalid-request": "The provider rejected the request.",
|
|
635
|
+
"network-error": "The provider request failed due to a network error.",
|
|
636
|
+
"cancelled": "Execution was cancelled.",
|
|
637
|
+
"invalid-output": "The provider returned invalid output.",
|
|
638
|
+
"provider-output-truncated": "The provider response was truncated by the output token limit.",
|
|
639
|
+
"attempts-exhausted": "Execution attempts were exhausted.",
|
|
640
|
+
"budget-exceeded": "The configured execution budget was exceeded.",
|
|
641
|
+
"input-limit-exceeded": "The configured input limit was exceeded."
|
|
642
|
+
};
|
|
643
|
+
return messages[error.code];
|
|
644
|
+
}
|
|
645
|
+
function minDefined(...values) {
|
|
646
|
+
return Math.min(...values.filter((value) => value !== undefined));
|
|
647
|
+
}
|
|
648
|
+
function requestedBlock(options, outputSchema) {
|
|
649
|
+
return {
|
|
650
|
+
...(options.effortHint !== undefined ? { effortHint: options.effortHint } : {}),
|
|
651
|
+
...(options.effortByModel !== undefined ? { effortByModel: options.effortByModel } : {}),
|
|
652
|
+
...(options.maxOutputTokens !== undefined ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
653
|
+
outputSchemaPresent: outputSchema !== undefined
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
function effectiveControls(profile, evidence) {
|
|
657
|
+
const { plan, effort, output } = evidence;
|
|
658
|
+
return {
|
|
659
|
+
reasoning: effort.effective,
|
|
660
|
+
...(effort.requestedEffort !== undefined ? { requestedEffort: effort.requestedEffort } : {}),
|
|
661
|
+
...(effort.effectiveEffort !== undefined ? { effectiveEffort: effort.effectiveEffort } : {}),
|
|
662
|
+
...(profile.defaults?.maxOutputTokens !== undefined ? { profileDefaultMaxOutputTokens: profile.defaults.maxOutputTokens } : {}),
|
|
663
|
+
...(plan.slot.settings.defaultMaxOutputTokens !== undefined ? { slotDefaultMaxOutputTokens: plan.slot.settings.defaultMaxOutputTokens } : {}),
|
|
664
|
+
...(output.effective !== undefined ? { maxOutputTokens: output.effective } : {}),
|
|
665
|
+
...(output.appliedCaps.length > 0 ? { appliedCaps: output.appliedCaps } : {})
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
function toCostEstimate(cost, basis) {
|
|
669
|
+
return {
|
|
670
|
+
currency: cost.currency,
|
|
671
|
+
...(cost.amount !== undefined ? { amount: cost.amount } : {}),
|
|
672
|
+
...(cost.priceRevisionId !== undefined ? { priceRevisionId: cost.priceRevisionId } : {}),
|
|
673
|
+
priceKnown: cost.priceKnown,
|
|
674
|
+
basis
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
function withUnknownToolCharges(cost, providerToolUsed) {
|
|
678
|
+
if (!providerToolUsed)
|
|
679
|
+
return cost;
|
|
680
|
+
const { amount: _amount, ...withoutAmount } = cost;
|
|
681
|
+
return { ...withoutAmount, priceKnown: false };
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Produces one terminal estimate without combining currencies. Per-attempt estimates retain
|
|
685
|
+
* the complete multi-currency evidence when a fallback crosses providers/currencies.
|
|
686
|
+
*/
|
|
687
|
+
function summarizeAttemptCosts(attempts) {
|
|
688
|
+
const billable = attempts.filter(attempt => attempt.providerRequestStarted && attempt.costEstimate).map(attempt => attempt.costEstimate);
|
|
689
|
+
if (billable.length === 0)
|
|
690
|
+
return undefined;
|
|
691
|
+
const currencies = new Set(billable.map(cost => cost.currency));
|
|
692
|
+
const terminal = billable[billable.length - 1];
|
|
693
|
+
if (currencies.size > 1) {
|
|
694
|
+
return { currency: terminal.currency, priceKnown: false, basis: "preflight-estimate" };
|
|
695
|
+
}
|
|
696
|
+
const revisions = new Set(billable.map(cost => cost.priceRevisionId).filter((revision) => revision !== undefined));
|
|
697
|
+
const known = billable.every(cost => cost.priceKnown && cost.amount !== undefined);
|
|
698
|
+
return {
|
|
699
|
+
currency: terminal.currency,
|
|
700
|
+
...(known ? { amount: billable.reduce((sum, cost) => sum + cost.amount, 0) } : {}),
|
|
701
|
+
...(revisions.size === 1 ? { priceRevisionId: [...revisions][0] } : {}),
|
|
702
|
+
priceKnown: known,
|
|
703
|
+
basis: billable.every(cost => cost.basis === "reported-usage") ? "reported-usage" : "preflight-estimate"
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
/** Cost caps intersect only within one currency; caps in different currencies cannot be combined. */
|
|
707
|
+
function intersectCostCaps(...caps) {
|
|
708
|
+
const present = caps.filter((cap) => cap !== undefined);
|
|
709
|
+
if (present.length === 0)
|
|
710
|
+
return undefined;
|
|
711
|
+
const currencies = new Set(present.map(cap => cap.currency));
|
|
712
|
+
if (currencies.size > 1) {
|
|
713
|
+
throw new BudgetExceededError(`Cannot intersect estimated-cost caps in different currencies (${[...currencies].join(", ")})`);
|
|
714
|
+
}
|
|
715
|
+
return { currency: present[0].currency, amount: Math.min(...present.map(cap => cap.amount)) };
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Output-token resolution for one attempt (implementation plan section 6.4): the explicit
|
|
719
|
+
* request replaces the slot/profile default upward or downward; the effective value is the
|
|
720
|
+
* minimum of the request, the model capability, and every explicit cap. With no explicit
|
|
721
|
+
* request or cap the provider field is omitted rather than manufacturing a number.
|
|
722
|
+
*/
|
|
723
|
+
function resolveOutputTokens(input) {
|
|
724
|
+
const request = input.requested ?? input.slotDefault ?? input.profileDefault;
|
|
725
|
+
const bounds = [
|
|
726
|
+
{ source: "model", value: input.modelCapability },
|
|
727
|
+
...(input.profileCap !== undefined ? [{ source: "profile", value: input.profileCap }] : []),
|
|
728
|
+
...(input.clientCap !== undefined ? [{ source: "client", value: input.clientCap }] : []),
|
|
729
|
+
...(input.invocationCap !== undefined ? [{ source: "invocation", value: input.invocationCap }] : [])
|
|
730
|
+
];
|
|
731
|
+
const explicitPolicy = input.profileCap !== undefined || input.clientCap !== undefined || input.invocationCap !== undefined;
|
|
732
|
+
if (request === undefined && !explicitPolicy) {
|
|
733
|
+
return { appliedCaps: [] };
|
|
734
|
+
}
|
|
735
|
+
const effective = Math.min(request ?? Number.POSITIVE_INFINITY, ...bounds.map(bound => bound.value));
|
|
736
|
+
const ceiling = request ?? input.modelCapability;
|
|
737
|
+
const appliedCaps = bounds
|
|
738
|
+
.filter(bound => bound.value < ceiling)
|
|
739
|
+
.map(bound => ({
|
|
740
|
+
source: bound.source,
|
|
741
|
+
dimension: "maxOutputTokens",
|
|
742
|
+
value: bound.value,
|
|
743
|
+
...(request !== undefined ? { requested: request } : {}),
|
|
744
|
+
effective
|
|
745
|
+
}));
|
|
746
|
+
return { ...(request !== undefined ? { requested: request } : {}), effective, appliedCaps };
|
|
747
|
+
}
|
|
748
|
+
function buildReceipt(input) {
|
|
749
|
+
const { token, evidence } = input;
|
|
750
|
+
const plan = evidence?.plan;
|
|
751
|
+
const effectiveBlock = evidence ? effectiveControls(token.profile, evidence) : undefined;
|
|
752
|
+
return {
|
|
753
|
+
schemaVersion: 1,
|
|
754
|
+
receiptId: deriveReceiptId({
|
|
755
|
+
applicationId: token.applicationId,
|
|
756
|
+
environmentId: token.environmentId,
|
|
757
|
+
runId: input.runId,
|
|
758
|
+
requestId: input.requestId,
|
|
759
|
+
operationId: input.operationId
|
|
760
|
+
}),
|
|
761
|
+
runId: input.runId,
|
|
762
|
+
requestId: input.requestId,
|
|
763
|
+
applicationId: token.applicationId,
|
|
764
|
+
environmentId: token.environmentId,
|
|
765
|
+
...(token.scope ? { desktopConfigurationId: token.scope.desktopConfigurationId, workspaceId: token.scope.workspaceId } : {}),
|
|
766
|
+
personaId: token.personaId,
|
|
767
|
+
operationId: input.operationId,
|
|
768
|
+
status: input.status,
|
|
769
|
+
instructionHash: token.persona.instructionHash,
|
|
770
|
+
...(token.instructionProjection ? { effectiveInstructionHash: hashInstructions(token.instructionProjection.systemInstructions) } : {}),
|
|
771
|
+
manifestRevision: token.manifestRevision,
|
|
772
|
+
profileId: token.profile.profileId,
|
|
773
|
+
profileRevision: token.profile.revision,
|
|
774
|
+
catalogRevision: input.snapshot.catalog.catalogRevision,
|
|
775
|
+
...(plan ? { adapterId: plan.adapterId, adapterVersion: plan.adapterVersion, providerModelId: plan.model.providerModelId, provider: plan.model.provider } : {}),
|
|
776
|
+
requested: input.requested,
|
|
777
|
+
...(effectiveBlock && Object.keys(effectiveBlock).length > 0 ? { effective: effectiveBlock } : {}),
|
|
778
|
+
attempts: structuredClone(input.attempts),
|
|
779
|
+
...(input.usage !== undefined ? { usage: input.usage } : {}),
|
|
780
|
+
...(input.cost ? { costEstimate: input.cost } : {}),
|
|
781
|
+
latencyMs: Date.now() - input.startedAt,
|
|
782
|
+
fallbackUsed: input.status === "succeeded"
|
|
783
|
+
? plan?.role === "fallback"
|
|
784
|
+
: input.attempts.some(attempt => attempt.role === "fallback"),
|
|
785
|
+
...(input.error ? { error: input.error } : {}),
|
|
786
|
+
...(input.warnings.length > 0 ? { warnings: [...new Set(input.warnings)] } : {}),
|
|
787
|
+
completedAt: new Date().toISOString()
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
function satisfiesMin(version, minVersion) {
|
|
791
|
+
const parse = (v) => v.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
|
792
|
+
const [a, b] = [parse(version), parse(minVersion)];
|
|
793
|
+
const length = Math.max(a.length, b.length);
|
|
794
|
+
for (let i = 0; i < length; i++) {
|
|
795
|
+
const av = a[i] ?? 0;
|
|
796
|
+
const bv = b[i] ?? 0;
|
|
797
|
+
if (av !== bv)
|
|
798
|
+
return av > bv;
|
|
799
|
+
}
|
|
800
|
+
return true;
|
|
801
|
+
}
|
|
802
|
+
export { hashInstructions };
|
|
803
|
+
//# sourceMappingURL=run.js.map
|