@techis/ai-runtime 0.3.0-rc.16 → 0.4.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/ADAPTER-AUTHORING.md +101 -0
  2. package/ADAPTER-CONFORMANCE.md +50 -0
  3. package/ANTHROPIC-MESSAGES.md +115 -0
  4. package/API.md +275 -0
  5. package/GEMINI-INTERACTIONS.md +49 -0
  6. package/MIGRATION.md +114 -0
  7. package/MOONSHOT-CHAT.md +53 -0
  8. package/OPENAI-RESPONSES.md +62 -0
  9. package/README.md +52 -39
  10. package/THIRD_PARTY_NOTICES +34 -34
  11. package/ZAI-CHAT.md +35 -0
  12. package/dist/adapters/anthropic-capabilities.d.ts +14 -0
  13. package/dist/adapters/anthropic-capabilities.d.ts.map +1 -0
  14. package/dist/adapters/anthropic-capabilities.js +63 -0
  15. package/dist/adapters/anthropic-capabilities.js.map +1 -0
  16. package/dist/adapters/anthropic-mapping.d.ts +7 -0
  17. package/dist/adapters/anthropic-mapping.d.ts.map +1 -0
  18. package/dist/adapters/anthropic-mapping.js +370 -0
  19. package/dist/adapters/anthropic-mapping.js.map +1 -0
  20. package/dist/adapters/anthropic-stream.d.ts +16 -0
  21. package/dist/adapters/anthropic-stream.d.ts.map +1 -0
  22. package/dist/adapters/anthropic-stream.js +271 -0
  23. package/dist/adapters/anthropic-stream.js.map +1 -0
  24. package/dist/adapters/anthropic.d.ts +4 -0
  25. package/dist/adapters/anthropic.d.ts.map +1 -0
  26. package/dist/adapters/anthropic.js +63 -0
  27. package/dist/adapters/anthropic.js.map +1 -0
  28. package/dist/adapters/chat-stream.d.ts +17 -0
  29. package/dist/adapters/chat-stream.d.ts.map +1 -0
  30. package/dist/adapters/chat-stream.js +220 -0
  31. package/dist/adapters/chat-stream.js.map +1 -0
  32. package/dist/adapters/conformance.d.ts +75 -0
  33. package/dist/adapters/conformance.d.ts.map +1 -0
  34. package/dist/adapters/conformance.js +156 -0
  35. package/dist/adapters/conformance.js.map +1 -0
  36. package/dist/adapters/gemini-mapping.d.ts +17 -0
  37. package/dist/adapters/gemini-mapping.d.ts.map +1 -0
  38. package/dist/adapters/gemini-mapping.js +295 -0
  39. package/dist/adapters/gemini-mapping.js.map +1 -0
  40. package/dist/adapters/gemini-stream.d.ts +6 -0
  41. package/dist/adapters/gemini-stream.d.ts.map +1 -0
  42. package/dist/adapters/gemini-stream.js +316 -0
  43. package/dist/adapters/gemini-stream.js.map +1 -0
  44. package/dist/adapters/gemini.d.ts +3 -1
  45. package/dist/adapters/gemini.d.ts.map +1 -1
  46. package/dist/adapters/gemini.js +43 -62
  47. package/dist/adapters/gemini.js.map +1 -1
  48. package/dist/adapters/http.d.ts +22 -6
  49. package/dist/adapters/http.d.ts.map +1 -1
  50. package/dist/adapters/http.js +152 -56
  51. package/dist/adapters/http.js.map +1 -1
  52. package/dist/adapters/moonshot-mapping.d.ts +14 -0
  53. package/dist/adapters/moonshot-mapping.d.ts.map +1 -0
  54. package/dist/adapters/moonshot-mapping.js +242 -0
  55. package/dist/adapters/moonshot-mapping.js.map +1 -0
  56. package/dist/adapters/moonshot.d.ts.map +1 -1
  57. package/dist/adapters/moonshot.js +48 -13
  58. package/dist/adapters/moonshot.js.map +1 -1
  59. package/dist/adapters/openai-mapping.d.ts +13 -0
  60. package/dist/adapters/openai-mapping.d.ts.map +1 -0
  61. package/dist/adapters/openai-mapping.js +242 -0
  62. package/dist/adapters/openai-mapping.js.map +1 -0
  63. package/dist/adapters/openai-stream.d.ts +5 -0
  64. package/dist/adapters/openai-stream.d.ts.map +1 -0
  65. package/dist/adapters/openai-stream.js +288 -0
  66. package/dist/adapters/openai-stream.js.map +1 -0
  67. package/dist/adapters/openai.d.ts +1 -1
  68. package/dist/adapters/openai.d.ts.map +1 -1
  69. package/dist/adapters/openai.js +32 -65
  70. package/dist/adapters/openai.js.map +1 -1
  71. package/dist/adapters/registry.d.ts +12 -1
  72. package/dist/adapters/registry.d.ts.map +1 -1
  73. package/dist/adapters/registry.js +145 -1
  74. package/dist/adapters/registry.js.map +1 -1
  75. package/dist/adapters/request-capabilities.d.ts +4 -0
  76. package/dist/adapters/request-capabilities.d.ts.map +1 -0
  77. package/dist/adapters/request-capabilities.js +53 -0
  78. package/dist/adapters/request-capabilities.js.map +1 -0
  79. package/dist/adapters/sse.d.ts +24 -0
  80. package/dist/adapters/sse.d.ts.map +1 -0
  81. package/dist/adapters/sse.js +209 -0
  82. package/dist/adapters/sse.js.map +1 -0
  83. package/dist/adapters/stream-evidence.d.ts +14 -0
  84. package/dist/adapters/stream-evidence.d.ts.map +1 -0
  85. package/dist/adapters/stream-evidence.js +69 -0
  86. package/dist/adapters/stream-evidence.js.map +1 -0
  87. package/dist/adapters/types.d.ts +99 -1
  88. package/dist/adapters/types.d.ts.map +1 -1
  89. package/dist/adapters/validation.d.ts +8 -0
  90. package/dist/adapters/validation.d.ts.map +1 -0
  91. package/dist/adapters/validation.js +231 -0
  92. package/dist/adapters/validation.js.map +1 -0
  93. package/dist/adapters/zai-mapping.d.ts +12 -0
  94. package/dist/adapters/zai-mapping.d.ts.map +1 -0
  95. package/dist/adapters/zai-mapping.js +246 -0
  96. package/dist/adapters/zai-mapping.js.map +1 -0
  97. package/dist/adapters/zai.d.ts +1 -25
  98. package/dist/adapters/zai.d.ts.map +1 -1
  99. package/dist/adapters/zai.js +37 -67
  100. package/dist/adapters/zai.js.map +1 -1
  101. package/dist/bundle-source.d.ts.map +1 -1
  102. package/dist/bundle-source.js +9 -7
  103. package/dist/bundle-source.js.map +1 -1
  104. package/dist/catalog-delivery.d.ts +7 -0
  105. package/dist/catalog-delivery.d.ts.map +1 -1
  106. package/dist/catalog-delivery.js +87 -39
  107. package/dist/catalog-delivery.js.map +1 -1
  108. package/dist/catalog-publication-source.d.ts +16 -0
  109. package/dist/catalog-publication-source.d.ts.map +1 -0
  110. package/dist/catalog-publication-source.js +99 -0
  111. package/dist/catalog-publication-source.js.map +1 -0
  112. package/dist/catalog-publication.d.ts +50 -0
  113. package/dist/catalog-publication.d.ts.map +1 -0
  114. package/dist/catalog-publication.js +127 -0
  115. package/dist/catalog-publication.js.map +1 -0
  116. package/dist/catalog-reader-configuration.d.ts +6 -0
  117. package/dist/catalog-reader-configuration.d.ts.map +1 -0
  118. package/dist/catalog-reader-configuration.js +2 -0
  119. package/dist/catalog-reader-configuration.js.map +1 -0
  120. package/dist/catalog-transfer.d.ts +11 -0
  121. package/dist/catalog-transfer.d.ts.map +1 -0
  122. package/dist/catalog-transfer.js +55 -0
  123. package/dist/catalog-transfer.js.map +1 -0
  124. package/dist/client.d.ts +9 -1
  125. package/dist/client.d.ts.map +1 -1
  126. package/dist/client.js +14 -6
  127. package/dist/client.js.map +1 -1
  128. package/dist/compatibility-client.d.ts +58 -0
  129. package/dist/compatibility-client.d.ts.map +1 -0
  130. package/dist/compatibility-client.js +116 -0
  131. package/dist/compatibility-client.js.map +1 -0
  132. package/dist/compatibility-execution.d.ts +47 -0
  133. package/dist/compatibility-execution.d.ts.map +1 -0
  134. package/dist/compatibility-execution.js +2 -0
  135. package/dist/compatibility-execution.js.map +1 -0
  136. package/dist/compatibility-stream-projection.d.ts +116 -0
  137. package/dist/compatibility-stream-projection.d.ts.map +1 -0
  138. package/dist/compatibility-stream-projection.js +188 -0
  139. package/dist/compatibility-stream-projection.js.map +1 -0
  140. package/dist/compatibility-types.d.ts +281 -0
  141. package/dist/compatibility-types.d.ts.map +1 -0
  142. package/dist/compatibility-types.js +2 -0
  143. package/dist/compatibility-types.js.map +1 -0
  144. package/dist/continuation.d.ts +49 -0
  145. package/dist/continuation.d.ts.map +1 -0
  146. package/dist/continuation.js +187 -0
  147. package/dist/continuation.js.map +1 -0
  148. package/dist/cost.d.ts +19 -4
  149. package/dist/cost.d.ts.map +1 -1
  150. package/dist/cost.js +109 -38
  151. package/dist/cost.js.map +1 -1
  152. package/dist/direct-model-client.d.ts +4 -0
  153. package/dist/direct-model-client.d.ts.map +1 -0
  154. package/dist/direct-model-client.js +37 -0
  155. package/dist/direct-model-client.js.map +1 -0
  156. package/dist/direct-model-types.d.ts +40 -0
  157. package/dist/direct-model-types.d.ts.map +1 -0
  158. package/dist/direct-model-types.js +2 -0
  159. package/dist/direct-model-types.js.map +1 -0
  160. package/dist/errors.d.ts +27 -1
  161. package/dist/errors.d.ts.map +1 -1
  162. package/dist/errors.js +10 -7
  163. package/dist/errors.js.map +1 -1
  164. package/dist/execution-configuration.d.ts +33 -0
  165. package/dist/execution-configuration.d.ts.map +1 -0
  166. package/dist/execution-configuration.js +16 -0
  167. package/dist/execution-configuration.js.map +1 -0
  168. package/dist/feature-planning.d.ts +23 -0
  169. package/dist/feature-planning.d.ts.map +1 -0
  170. package/dist/feature-planning.js +249 -0
  171. package/dist/feature-planning.js.map +1 -0
  172. package/dist/feature-policy.d.ts +13 -0
  173. package/dist/feature-policy.d.ts.map +1 -0
  174. package/dist/feature-policy.js +60 -0
  175. package/dist/feature-policy.js.map +1 -0
  176. package/dist/generation-input.d.ts +7 -0
  177. package/dist/generation-input.d.ts.map +1 -0
  178. package/dist/generation-input.js +24 -0
  179. package/dist/generation-input.js.map +1 -0
  180. package/dist/generation-stream.d.ts +35 -0
  181. package/dist/generation-stream.d.ts.map +1 -0
  182. package/dist/generation-stream.js +178 -0
  183. package/dist/generation-stream.js.map +1 -0
  184. package/dist/index.d.ts +36 -5
  185. package/dist/index.d.ts.map +1 -1
  186. package/dist/index.js +30 -3
  187. package/dist/index.js.map +1 -1
  188. package/dist/model-client-types.d.ts +99 -0
  189. package/dist/model-client-types.d.ts.map +1 -0
  190. package/dist/model-client-types.js +7 -0
  191. package/dist/model-client-types.js.map +1 -0
  192. package/dist/model-client.d.ts +3 -0
  193. package/dist/model-client.d.ts.map +1 -0
  194. package/dist/model-client.js +96 -0
  195. package/dist/model-client.js.map +1 -0
  196. package/dist/model-configuration.d.ts +40 -0
  197. package/dist/model-configuration.d.ts.map +1 -0
  198. package/dist/model-configuration.js +102 -0
  199. package/dist/model-configuration.js.map +1 -0
  200. package/dist/named-client-types.d.ts +72 -0
  201. package/dist/named-client-types.d.ts.map +1 -0
  202. package/dist/named-client-types.js +4 -0
  203. package/dist/named-client-types.js.map +1 -0
  204. package/dist/named-client.d.ts +4 -0
  205. package/dist/named-client.d.ts.map +1 -0
  206. package/dist/named-client.js +68 -0
  207. package/dist/named-client.js.map +1 -0
  208. package/dist/named-configuration.d.ts +57 -0
  209. package/dist/named-configuration.d.ts.map +1 -0
  210. package/dist/named-configuration.js +119 -0
  211. package/dist/named-configuration.js.map +1 -0
  212. package/dist/native-operation.d.ts +6 -0
  213. package/dist/native-operation.d.ts.map +1 -0
  214. package/dist/native-operation.js +45 -0
  215. package/dist/native-operation.js.map +1 -0
  216. package/dist/package-updates.d.ts +2 -0
  217. package/dist/package-updates.d.ts.map +1 -1
  218. package/dist/package-updates.js +5 -9
  219. package/dist/package-updates.js.map +1 -1
  220. package/dist/profile-client.d.ts +13 -0
  221. package/dist/profile-client.d.ts.map +1 -0
  222. package/dist/profile-client.js +57 -0
  223. package/dist/profile-client.js.map +1 -0
  224. package/dist/published-catalog.d.ts +22 -0
  225. package/dist/published-catalog.d.ts.map +1 -0
  226. package/dist/published-catalog.js +25 -0
  227. package/dist/published-catalog.js.map +1 -0
  228. package/dist/reasoning-resolution.d.ts.map +1 -1
  229. package/dist/reasoning-resolution.js +11 -2
  230. package/dist/reasoning-resolution.js.map +1 -1
  231. package/dist/request-mapping.d.ts +15 -0
  232. package/dist/request-mapping.d.ts.map +1 -0
  233. package/dist/request-mapping.js +479 -0
  234. package/dist/request-mapping.js.map +1 -0
  235. package/dist/resolution.d.ts.map +1 -1
  236. package/dist/resolution.js +7 -10
  237. package/dist/resolution.js.map +1 -1
  238. package/dist/result-mapping.d.ts +17 -0
  239. package/dist/result-mapping.d.ts.map +1 -0
  240. package/dist/result-mapping.js +123 -0
  241. package/dist/result-mapping.js.map +1 -0
  242. package/dist/route-adoption-node.d.ts +22 -0
  243. package/dist/route-adoption-node.d.ts.map +1 -0
  244. package/dist/route-adoption-node.js +134 -0
  245. package/dist/route-adoption-node.js.map +1 -0
  246. package/dist/route-adoption.d.ts +100 -0
  247. package/dist/route-adoption.d.ts.map +1 -0
  248. package/dist/route-adoption.js +176 -0
  249. package/dist/route-adoption.js.map +1 -0
  250. package/dist/route-client.d.ts +78 -0
  251. package/dist/route-client.d.ts.map +1 -0
  252. package/dist/route-client.js +91 -0
  253. package/dist/route-client.js.map +1 -0
  254. package/dist/route-readiness.d.ts +27 -0
  255. package/dist/route-readiness.d.ts.map +1 -0
  256. package/dist/route-readiness.js +78 -0
  257. package/dist/route-readiness.js.map +1 -0
  258. package/dist/route-set-file-source.d.ts +7 -0
  259. package/dist/route-set-file-source.d.ts.map +1 -0
  260. package/dist/route-set-file-source.js +27 -0
  261. package/dist/route-set-file-source.js.map +1 -0
  262. package/dist/route-set-json-source.d.ts +27 -0
  263. package/dist/route-set-json-source.d.ts.map +1 -0
  264. package/dist/route-set-json-source.js +126 -0
  265. package/dist/route-set-json-source.js.map +1 -0
  266. package/dist/route-set.d.ts +30 -0
  267. package/dist/route-set.d.ts.map +1 -0
  268. package/dist/route-set.js +33 -0
  269. package/dist/route-set.js.map +1 -0
  270. package/dist/run.d.ts +42 -4
  271. package/dist/run.d.ts.map +1 -1
  272. package/dist/run.js +925 -474
  273. package/dist/run.js.map +1 -1
  274. package/dist/system-instructions.d.ts +23 -0
  275. package/dist/system-instructions.d.ts.map +1 -0
  276. package/dist/system-instructions.js +57 -0
  277. package/dist/system-instructions.js.map +1 -0
  278. package/dist/types.d.ts +3 -1
  279. package/dist/types.d.ts.map +1 -1
  280. package/dist/types.js.map +1 -1
  281. package/dist/version.d.ts +1 -1
  282. package/dist/version.d.ts.map +1 -1
  283. package/dist/version.js +1 -1
  284. package/dist/version.js.map +1 -1
  285. package/package.json +35 -26
  286. package/third-party-licenses.json +2 -7
  287. /package/third-party-licenses/{fast-uri@3.1.7 → fast-uri@3.1.9}/LICENSE +0 -0
package/dist/run.js CHANGED
@@ -1,10 +1,23 @@
1
1
  import { withDeadline } from "./deadline.js";
2
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";
3
+ import { compileSchema, deriveReceiptId, deriveNativeReceiptId, deriveModelReceiptId, deriveProfileReceiptId, deriveDirectModelReceiptId, hashInstructions, validateReasoningForModel, reasoningSupportWarnings, isNativeReasoningControl } from "@techis/ai-contracts";
4
+ import { AISubsystemError, attachProviderErrorContext, AttemptsExhaustedError, BudgetExceededError, CancellationError, ConfigurationInvalidError, CredentialInvalidError, CredentialUnavailableError, InputLimitExceededError, ProviderCallError, ProviderOutputTruncatedError, InvalidOutputError, UnsupportedAdapterError, UnsupportedCapabilityError } from "./errors.js";
5
+ import { applyReportedCostContext, costContextForRequest, costFromUsage, estimateInputTokens, mergeCostContexts, mergeReportedUsage, preflightCostCeiling, priceForModel } from "./cost.js";
6
6
  import { resolveEffectiveReasoning } from "./reasoning-resolution.js";
7
+ import { installedAdapterVersions } from "./adapters/registry.js";
7
8
  import { OPERATION_ID_PATTERN, REQUEST_ID_PATTERN } from "./types.js";
9
+ import { getExecutionProvenance } from "./execution-configuration.js";
10
+ import { prepareNativeOperation } from "./native-operation.js";
11
+ import { planGenerationFeatures } from "./feature-planning.js";
12
+ import { evaluateFeaturePolicy, validateFeaturePolicy } from "./feature-policy.js";
13
+ import { mergeProviderOptions } from "./request-mapping.js";
14
+ import { createContinuationState, resolveContinuation } from "./continuation.js";
15
+ import { estimateGenerationInput, legacyGenerationInput } from "./generation-input.js";
16
+ import { generationFromAdapterResponse } from "./result-mapping.js";
17
+ import { createCompatibilityInterfaces } from "./compatibility-client.js";
18
+ import { abortable, consumeAdapterStream } from "./generation-stream.js";
19
+ import { validateAdapterResponse, validateGenerationOutput, validateUsage } from "./adapters/validation.js";
20
+ import { createStreamEvidence } from "./adapters/stream-evidence.js";
8
21
  const RETRYABLE_CODE_TO_CLASS = {
9
22
  "provider-rate-limit": "provider-rate-limit",
10
23
  "provider-timeout": "provider-timeout",
@@ -19,237 +32,409 @@ const PREFLIGHT_CODES = new Set([
19
32
  "input-limit-exceeded",
20
33
  "budget-exceeded"
21
34
  ]);
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
- */
35
+ const executionConfiguration = (token) => "directModel" in token ? token.executionConfiguration : token.profile;
27
36
  export function createRun(token, snapshot, deps, resolutionWarnings = []) {
37
+ if (("native" in token) !== ("nativeCredentialResolver" in deps))
38
+ throw new ConfigurationInvalidError("Execution credential protocol differs from token.");
28
39
  token = structuredClone(token);
29
40
  snapshot = structuredClone(snapshot);
30
- const systemInstructions = token.instructionProjection?.systemInstructions ?? token.persona.systemInstructions;
41
+ const provenance = getExecutionProvenance(token);
42
+ if (("model" in token || "directModel" in token) !== ("modelCredentialResolver" in deps))
43
+ throw new ConfigurationInvalidError("Execution credential protocol differs from token.");
44
+ const systemInstructions = "model" in token || "directModel" in token ? token.systemInstructions : token.instructionProjection?.systemInstructions ?? token.persona.systemInstructions;
45
+ const outputRequirements = "model" in token || "directModel" in token ? undefined : token.persona.outputRequirements;
31
46
  const models = new Map(snapshot.catalog.models.map((model) => [model.catalogId, model]));
32
47
  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 {
48
+ async function execute(options, invocation) {
49
+ const startedAt = invocation?.admittedAt ?? performance.now(), admittedAt = startedAt;
50
+ const validOptions = options !== null && typeof options === "object" && !Array.isArray(options);
51
+ if (!validOptions)
52
+ options = { operationId: "", input: "" };
53
+ let richRequest;
54
+ let effectiveInstructions = systemInstructions;
55
+ const requestId = typeof options.requestId === "string" && REQUEST_ID_PATTERN.test(options.requestId)
56
+ ? options.requestId
57
+ : options.requestId === undefined
58
+ ? randomUUID()
59
+ : "invalid-request-id";
60
+ const attempts = [];
61
+ const skippedSlots = [];
62
+ let resolvedOutputSchema;
63
+ let outputValidator;
64
+ let terminalReceipt;
65
+ let lastEvidence;
66
+ const warnings = [...resolutionWarnings];
67
+ const emit = async (receipt) => {
68
+ if (terminalReceipt)
69
+ return terminalReceipt;
70
+ terminalReceipt = receipt;
71
+ if (invocation) {
72
+ if (receipt.status === "succeeded")
73
+ invocation.state.terminalCommitted = true;
74
+ for (const evidence of [receipt.generation, ...receipt.attempts.map(attempt => attempt.generation)])
75
+ if (evidence) {
76
+ evidence.clientStyle = invocation.style;
77
+ evidence.mode = invocation.stream ? "stream" : "final";
78
+ }
79
+ }
80
+ try {
81
+ if ("kind" in receipt && receipt.kind === "direct-model-execution-receipt" && "onDirectModelExecutionReceipt" in deps)
82
+ await deps.onDirectModelExecutionReceipt?.(receipt);
83
+ else if ("kind" in receipt && receipt.kind === "profile-execution-receipt" && "onProfileExecutionReceipt" in deps)
84
+ await deps.onProfileExecutionReceipt?.(receipt);
85
+ else if ("kind" in receipt && receipt.kind === "model-execution-receipt" && "onModelExecutionReceipt" in deps)
86
+ await deps.onModelExecutionReceipt?.(receipt);
87
+ else if ("kind" in receipt && receipt.kind === "native-execution-receipt" && "nativeCredentialResolver" in deps)
88
+ await deps.onNativeExecutionReceipt?.(receipt);
89
+ else if (!("kind" in receipt) && "credentialResolver" in deps)
53
90
  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
- };
91
+ }
92
+ catch {
93
+ receipt.warnings = [...(receipt.warnings ?? []), "Execution receipt sink failed; inference was not retried."];
94
+ }
95
+ return receipt;
96
+ };
97
+ try {
98
+ if (!validOptions)
99
+ throw new ConfigurationInvalidError("Generation options must be an object");
100
+ if (typeof options.operationId !== "string" || !OPERATION_ID_PATTERN.test(options.operationId)) {
101
+ throw new ConfigurationInvalidError("GenerateOptions.operationId is required and must be a bounded logical identifier (letters, digits, '.', '_', '-'; max 128 characters)");
102
+ }
103
+ const { signal, ...request } = options;
60
104
  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
105
  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) {
106
+ }
107
+ catch {
108
+ throw new ConfigurationInvalidError("Generation options must contain serializable data");
109
+ }
110
+ if (signal !== undefined && !(signal instanceof AbortSignal))
111
+ throw new ConfigurationInvalidError("signal must be an AbortSignal");
112
+ if (signal?.aborted)
113
+ throw new CancellationError();
114
+ const profile = executionConfiguration(token);
115
+ if (invocation) {
116
+ richRequest = invocation.map().request;
117
+ const primary = models.get(profile.primary.catalogId);
118
+ if (richRequest.model !== undefined && richRequest.model !== primary?.catalogId && richRequest.model !== primary?.providerModelId)
119
+ throw new ConfigurationInvalidError("Request model differs from the pinned primary model");
120
+ effectiveInstructions = richRequest.instructions === undefined ? systemInstructions : systemInstructions + "\n\n" + richRequest.instructions;
121
+ richRequest.instructions = effectiveInstructions;
122
+ options.input = legacyGenerationInput(richRequest);
123
+ options.maxOutputTokens = richRequest.maxOutputTokens;
124
+ options.effortHint = richRequest.effort;
125
+ options.operation = richRequest.webSearch === undefined ? undefined : { webSearch: richRequest.webSearch };
126
+ options.outputSchema = richRequest.outputFormat?.type === "json_schema" ? richRequest.outputFormat.schema : undefined;
127
+ }
128
+ validateInvocationControls(options);
129
+ validateGenerateInput(options.input);
130
+ const nativeOperation = "native" in token ? prepareNativeOperation(token, options, richRequest) : undefined;
131
+ if (richRequest && nativeOperation) {
132
+ richRequest.webSearch = nativeOperation.webSearch;
133
+ if (options.outputSchema)
134
+ richRequest.outputFormat = { type: "json_schema", schema: options.outputSchema };
135
+ }
136
+ if (!("directModel" in token) && token.profile.status !== "published") {
137
+ throw new ConfigurationInvalidError(`Profile ${token.profile.profileId}@${token.profile.revision} is ${token.profile.status}; only published profiles are executable`);
138
+ }
139
+ const search = options.operation?.webSearch === true;
140
+ const operation = { ...options.operation, webSearch: search };
141
+ const nativeLimit = operation.openai?.maxToolCalls;
142
+ const searchCount = operation.zai?.searchResultCount;
143
+ if (nativeLimit !== undefined && (!Number.isSafeInteger(nativeLimit) || nativeLimit < 1)) {
144
+ throw new ConfigurationInvalidError("OpenAI maxToolCalls must be a positive integer");
145
+ }
146
+ if (searchCount !== undefined && (!Number.isSafeInteger(searchCount) || searchCount < 1 || searchCount > 50)) {
147
+ throw new ConfigurationInvalidError("ZAI searchResultCount must be an integer from 1 to 50");
148
+ }
149
+ const maxAttempts = Math.min(profile.execution.maxAttempts ?? 3, options.execution?.maxAttempts ?? Infinity, profile.execution.fallbackPolicy === "forward-only" ? 1 + profile.fallbacks.length : Infinity);
150
+ const callerTiming = "directModel" in token || options.execution?.timingPolicy === "caller";
151
+ const clock = () => performance.now();
152
+ const deadlineMs = Math.min(nativeOperation?.timeoutMs ?? Infinity, callerTiming ? options.execution?.deadlineMs ?? Infinity
153
+ : Math.min(profile.execution.deadlineMs ?? 120_000, options.execution?.deadlineMs ?? Infinity));
154
+ const deadlineAt = admittedAt + deadlineMs;
155
+ const deadlineError = () => new AttemptsExhaustedError(`Deadline of ${deadlineMs}ms exhausted.`, { attempts: attempts.length });
156
+ if ("directModel" in token && "authorizeDirectModelPayload" in deps && deps.authorizeDirectModelPayload) {
157
+ await withDeadline(signal => deps.authorizeDirectModelPayload({ resolution: structuredClone(token), operationId: options.operationId,
158
+ input: structuredClone(options.input), systemInstructions: effectiveInstructions, outputSchema: options.outputSchema,
159
+ ...(richRequest ? { generation: structuredClone(richRequest) } : {}), signal })
160
+ .catch(() => { throw new ConfigurationInvalidError("Trusted host rejected direct-model payload authorization."); }), deadlineAt - clock(), deadlineError, options.signal);
161
+ }
162
+ if (nativeOperation && "nativeCredentialResolver" in deps) {
163
+ if (options.signal?.aborted)
164
+ throw new CancellationError();
165
+ if (nativeOperation.protectedPayloadPolicy !== "none" && !deps.authorizeNativePayload)
166
+ throw new ConfigurationInvalidError("Pinned protected-payload policy requires an explicit trusted host authorization hook.");
167
+ if (deps.authorizeNativePayload) {
93
168
  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;
169
+ await withDeadline(signal => deps.authorizeNativePayload(structuredClone(nativeOperation), structuredClone({ input: options.input,
170
+ systemInstructions: effectiveInstructions, outputSchema: options.outputSchema, controls: options.operation,
171
+ ...(richRequest ? { generation: richRequest } : {}) }), signal)
172
+ .catch(() => { throw new ConfigurationInvalidError("Trusted host rejected native payload authorization."); }), deadlineAt - clock(), deadlineError, options.signal);
142
173
  }
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.`);
174
+ catch (error) {
175
+ if (options.signal?.aborted)
176
+ throw new CancellationError();
177
+ throw error;
164
178
  }
165
- plans.push({ slot, model, role, adapterId: adapter.id, adapterVersion: adapter.version, warnings: slotWarnings });
166
179
  }
167
- if (precheckFailures.length > 0) {
168
- throw new UnsupportedAdapterError(`Profile ${profile.profileId} has unusable model slots: ${precheckFailures.join("; ")}`, { profileId: profile.profileId, precheckFailures });
180
+ }
181
+ if ("model" in token && "configurationId" in token.model && "authorizeModelPayload" in deps && deps.authorizeModelPayload) {
182
+ await withDeadline(signal => deps.authorizeModelPayload({ resolution: structuredClone(token), operationId: options.operationId,
183
+ input: structuredClone(options.input), systemInstructions: effectiveInstructions, outputSchema: options.outputSchema,
184
+ ...(richRequest ? { generation: structuredClone(richRequest) } : {}), signal })
185
+ .catch(() => { throw new ConfigurationInvalidError("Trusted host rejected payload authorization."); }), deadlineAt - clock(), deadlineError, options.signal);
186
+ }
187
+ if ("model" in token && !("configurationId" in token.model) && "authorizeProfilePayload" in deps && deps.authorizeProfilePayload) {
188
+ await withDeadline(signal => deps.authorizeProfilePayload({ resolution: structuredClone(token),
189
+ operationId: options.operationId, input: structuredClone(options.input), systemInstructions: effectiveInstructions,
190
+ outputSchema: options.outputSchema, ...(richRequest ? { generation: structuredClone(richRequest) } : {}), signal })
191
+ .catch(() => { throw new ConfigurationInvalidError("Trusted host rejected payload authorization."); }), deadlineAt - clock(), deadlineError, options.signal);
192
+ }
193
+ const outputSchema = options.outputSchema ?? (outputRequirements?.kind === "structured" ? outputRequirements.schema : undefined);
194
+ if (richRequest && outputSchema) {
195
+ if (richRequest.outputFormat && richRequest.outputFormat.type !== "json_schema")
196
+ throw new ConfigurationInvalidError("Requested output format conflicts with the pinned structured output requirement");
197
+ richRequest.outputFormat ??= { type: "json_schema", schema: outputSchema };
198
+ }
199
+ resolvedOutputSchema = outputSchema;
200
+ const structured = outputRequirements?.kind === "structured" || options.outputSchema !== undefined ||
201
+ richRequest?.outputFormat?.type === "json_object";
202
+ if (structured) {
203
+ try {
204
+ outputValidator = compileSchema(outputSchema ?? { type: "object" });
169
205
  }
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)");
206
+ catch {
207
+ throw new ConfigurationInvalidError("The requested output schema is not a valid JSON Schema");
172
208
  }
173
- for (const plan of plans)
174
- warnings.push(...plan.warnings);
175
- const estimated = estimateInputTokens(options.input);
209
+ }
210
+ // Validate request/configuration integrity independently of slot availability and feature support.
211
+ if (options.requestId !== undefined && (typeof options.requestId !== "string" || !REQUEST_ID_PATTERN.test(options.requestId))) {
212
+ throw new ConfigurationInvalidError("GenerateOptions.requestId must be a bounded storage-safe identifier");
213
+ }
214
+ const slots = [profile.primary, ...profile.fallbacks], slotIds = new Set(slots.map(slot => slot.catalogId));
215
+ for (const catalogId of [...Object.keys(profile.effortPolicy?.byModel ?? {}), ...Object.keys(options.effortByModel ?? {})]) {
216
+ if (!slotIds.has(catalogId))
217
+ throw new ConfigurationInvalidError(`Effort model ${catalogId} is not a primary or fallback profile slot`);
218
+ }
219
+ const estimated = richRequest ? { tokens: estimateGenerationInput(richRequest) } : estimateInputTokens(options.input);
220
+ if (!richRequest) {
176
221
  estimated.tokens += estimateInputTokens(systemInstructions).tokens;
177
222
  if (outputSchema)
178
223
  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
- }
224
+ }
225
+ const policyInputLimit = minDefined(profile.caps?.maxInputTokens, deps.clientCaps?.maxInputTokens, options.caps?.maxInputTokens);
226
+ if (estimated.tokens > policyInputLimit)
227
+ throw new InputLimitExceededError("Estimated input exceeds an explicit policy bound", { estimatedInputTokens: estimated.tokens, limit: policyInputLimit });
228
+ const plans = [], unavailable = [];
229
+ const installed = installedAdapterVersions(deps.registry);
230
+ const targetFor = (model) => {
231
+ const adapter = deps.registry.get(model.adapterId);
232
+ return { provider: model.provider, providerModelId: model.providerModelId, adapterId: adapter?.id ?? model.adapterId,
233
+ adapterVersion: adapter?.version ?? "unavailable", configurationRevision: provenance.kind === "direct-model" ?
234
+ provenance.modelConfigurationDigest : provenance.revision,
235
+ supportsResponseId: adapter?.supportsResponseId === true };
236
+ };
237
+ const primaryTarget = models.has(profile.primary.catalogId) ? targetFor(models.get(profile.primary.catalogId)) : undefined;
238
+ for (const [index, slot] of slots.entries()) {
239
+ const role = index === 0 ? "primary" : "fallback", model = models.get(slot.catalogId);
240
+ if (!model)
241
+ throw new ConfigurationInvalidError(`${role} ${slot.catalogId}: missing from the pinned catalog`);
242
+ if (profile.catalogCompatibility?.excludedCatalogIds?.includes(slot.catalogId))
243
+ throw new ConfigurationInvalidError(`${role} ${slot.catalogId}: excluded by the pinned profile`);
244
+ // An invalid extension is still invalid even if its slot is never reached.
245
+ mergeProviderOptions(slot.settings.providerOptions, undefined);
246
+ if (slot.settings.reasoning !== undefined && !isNativeReasoningControl(slot.settings.reasoning))
247
+ throw new ConfigurationInvalidError(`${role} ${slot.catalogId}: malformed native reasoning control`);
248
+ const adapter = deps.registry.get(model.adapterId), minVersion = snapshot.manifest.adapterRequirements[model.adapterId]?.minVersion;
249
+ const routeVersion = installed[model.adapterId]?.version ?? adapter?.version;
250
+ const unavailableReason = model.lifecycle.status === "retired" ? "retired"
251
+ : !adapter ? "adapter-missing" : !adapter.providers.includes(model.provider) ? "adapter-provider"
252
+ : minVersion && !satisfiesMin(routeVersion, minVersion) ? "adapter-version"
253
+ : !model.capabilities.outputModalities.includes("text") ? "text-output" : undefined;
254
+ if (unavailableReason) {
255
+ unavailable.push(`${role} ${slot.catalogId} (${model.provider}): ${unavailableReason}; skipped.`);
256
+ skippedSlots.push({ slot: index, catalogId: slot.catalogId, providerModelId: model.providerModelId, role,
257
+ reason: unavailableReason, phase: "preflight", providerRequestStarted: false });
258
+ continue;
184
259
  }
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
- }
260
+ const generation = richRequest ? structuredClone(richRequest) : { items: [{ type: "message", role: "user", content: [
261
+ { type: "text", text: typeof options.input === "string" ? options.input : options.input.text ?? "" },
262
+ ...(typeof options.input === "string" ? [] : (options.input.images ?? []).map(image => ({ type: "image",
263
+ source: { type: "base64", mimeType: image.mimeType, data: image.dataBase64 },
264
+ ...(image.detail !== undefined ? { detail: image.detail } : {}) })))
265
+ ] }], instructions: systemInstructions,
266
+ ...(structured ? { outputFormat: { type: "json_schema", schema: (outputSchema ?? { type: "object" }) } } : {}),
267
+ ...(search ? { webSearch: true } : {}), ...(slot.settings.temperature !== undefined ? { temperature: slot.settings.temperature } : {}) };
268
+ generation.temperature ??= slot.settings.temperature;
269
+ if (options.featurePolicy?.structuredOutputEnforcement === "provider-native" && generation.outputFormat?.type === "json_schema" &&
270
+ generation.outputFormat.strict === undefined)
271
+ generation.outputFormat.strict = true;
272
+ const target = targetFor(model);
273
+ const continuation = richRequest ? resolveContinuation(generation, target, primaryTarget) : undefined;
274
+ if (continuation?.kind === "unavailable") {
275
+ unavailable.push(`${role} ${slot.catalogId}: continuation-not-portable; skipped.`);
276
+ skippedSlots.push({ slot: index, catalogId: slot.catalogId, providerModelId: model.providerModelId, role,
277
+ reason: "continuation-not-portable", phase: "preflight", providerRequestStarted: false });
278
+ continue;
190
279
  }
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
- }
280
+ const features = planGenerationFeatures({ request: continuation?.request ?? generation, model, adapter: adapter, role,
281
+ stream: Boolean(invocation?.stream),
282
+ requiredInputModalities: profile.requiredCapabilities.inputModalities,
283
+ requiredProviderTools: profile.requiredCapabilities.providerTools, slotProviderOptions: slot.settings.providerOptions,
284
+ reasoningControl: slot.settings.reasoning });
285
+ const blocks = features.request.items.flatMap(item => item.type === "message" ? item.content ?? [] : []);
286
+ if (continuation) {
287
+ features.features.push(...continuation.features);
288
+ features.warnings.push(...continuation.warnings);
289
+ }
290
+ const policyErrors = evaluateFeaturePolicy(options.featurePolicy, features, { original: continuation?.request ?? generation,
291
+ model, adapter: adapter, phase: "initial" });
292
+ if (policyErrors.length) {
293
+ if (role === "primary")
294
+ throw new UnsupportedCapabilityError("Primary does not satisfy featurePolicy: " + policyErrors.join("; "));
295
+ warnings.push(`Fallback ${slot.catalogId} excluded by featurePolicy: ${policyErrors.join("; ")}.`);
296
+ continue;
195
297
  }
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 => {
298
+ const input = richRequest ? legacyGenerationInput(features.request) : typeof options.input === "string" ? options.input : {
299
+ text: blocks.filter(block => block.type === "text").map(block => block.text).join("\n"),
300
+ images: blocks.flatMap(block => block.type === "image" && block.source.type === "base64" ? [{ mimeType: block.source.mimeType,
301
+ dataBase64: block.source.data, ...(block.detail !== undefined ? { detail: block.detail } : {}) }] : [])
302
+ };
303
+ const inputLimit = minDefined(model.capabilities.maxInputTokens, model.capabilities.contextWindowTokens);
304
+ const effectiveEstimate = richRequest ? estimateGenerationInput(features.request) : estimateInputTokens(input).tokens + estimateInputTokens(systemInstructions).tokens +
305
+ (features.request.outputFormat?.type === "json_schema"
306
+ ? estimateInputTokens(JSON.stringify(features.request.outputFormat.schema)).tokens : 0);
307
+ if (effectiveEstimate > inputLimit || effectiveEstimate >= (model.capabilities.contextWindowTokens ?? Infinity)) {
308
+ if (role === "primary")
309
+ throw new InputLimitExceededError("Estimated input exceeds the primary model limit", { catalogId: model.catalogId, estimatedInputTokens: effectiveEstimate, limit: inputLimit });
310
+ unavailable.push(`fallback ${slot.catalogId}: input exceeds the model limit; skipped.`);
311
+ skippedSlots.push({ slot: index, catalogId: slot.catalogId, providerModelId: model.providerModelId, role,
312
+ reason: "input-limit", phase: "preflight", providerRequestStarted: false });
313
+ continue;
314
+ }
315
+ const slotWarnings = [...features.warnings];
316
+ if (model.lifecycle.status !== "ga")
317
+ slotWarnings.push(`${role} model ${slot.catalogId} lifecycle is ${model.lifecycle.status}.`);
318
+ plans.push({ originalRequest: structuredClone(continuation?.request ?? generation), policyFeatures: [...features.features],
319
+ slotIndex: index, slot, model, role, adapterId: model.adapterId, adapterVersion: adapter.version, warnings: slotWarnings,
320
+ features, input, structured: structured && features.request.outputFormat?.type !== "text",
321
+ estimatedInputTokens: effectiveEstimate, costContext: costContextForRequest(features.request, model.provider),
322
+ ...(continuation ? { continuationTarget: target, continuationRequest: continuation.mode === "native-id" || continuation.mode === "native-replay" ? { ...features.request,
323
+ continuation: generation.continuation ?? { ...primaryTarget, responseId: generation.previousResponseId },
324
+ previousResponseId: generation.previousResponseId } : features.request } : {}),
325
+ implementation: { id: adapter.id, version: adapter.version, contractVersion: adapter.contractVersion ?? 1 },
326
+ compatibleAdapterVersion: routeVersion, protocol: adapter.protocol });
327
+ }
328
+ warnings.push(...unavailable);
329
+ if (!plans.length)
330
+ throw new UnsupportedAdapterError("No usable configured model slots", { unavailable });
331
+ const preparedPlans = plans.flatMap(plan => {
332
+ const output = resolveOutputTokens({ requested: options.maxOutputTokens, slotDefault: plan.slot.settings.defaultMaxOutputTokens,
333
+ profileDefault: profile.defaults?.maxOutputTokens, modelCapability: knownOutputCeiling(plan.model, plan.estimatedInputTokens),
334
+ profileCap: profile.caps?.maxOutputTokens, clientCap: deps.clientCaps?.maxOutputTokens, invocationCap: options.caps?.maxOutputTokens });
335
+ let effort, nativeSettings;
336
+ try {
200
337
  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);
338
+ effort = resolveEffectiveReasoning(plan.model, plan.slot.settings, { effortHint: richRequest ? plan.features.request.effort : options.effortHint,
339
+ exactEffort: options.effortByModel?.[plan.model.catalogId], effortPolicy: profile.effortPolicy });
216
340
  const semanticErrors = validateReasoningForModel(plan.model, effort.effective);
217
- if (semanticErrors.length > 0) {
341
+ if (semanticErrors.length)
218
342
  throw new UnsupportedCapabilityError(semanticErrors.join("; "), { catalogId: plan.slot.catalogId });
219
- }
220
- let nativeSettings;
343
+ const uncertainty = reasoningSupportWarnings(plan.model, effort.effective);
344
+ effort.notes.push(...uncertainty);
345
+ if (effort.effective.mode !== "provider-default")
346
+ plan.features.features.push({ feature: "reasoning", requested: true,
347
+ effective: uncertainty.length ? "unknown" : "sent", ...(uncertainty.length ? { reason: "unknown-capability" } : {}) });
221
348
  try {
222
349
  nativeSettings = deps.registry.get(plan.model.adapterId).translateReasoning(plan.model, effort.effective);
223
350
  }
224
351
  catch {
225
- throw new UnsupportedCapabilityError(`Adapter ${plan.adapterId} cannot translate native reasoning for ${plan.model.catalogId}`, { adapterId: plan.adapterId, catalogId: plan.model.catalogId });
352
+ throw new UnsupportedCapabilityError(`Adapter ${plan.adapterId} cannot translate reasoning for ${plan.model.catalogId}`);
226
353
  }
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;
354
+ }
355
+ catch (error) {
356
+ if (plan.role === "primary" || !(error instanceof UnsupportedCapabilityError))
357
+ throw error;
358
+ effort = { effective: { mode: "provider-default" }, notes: [
359
+ `Fallback ${plan.model.catalogId}: unsupported reasoning override omitted; provider defaults apply.`
360
+ ] };
361
+ nativeSettings = {};
362
+ plan.features.features = plan.features.features.filter(feature => feature.feature !== "reasoning");
363
+ plan.features.features.push({ feature: "reasoning", requested: true, effective: "omitted", reason: "unsupported" });
364
+ }
365
+ plan.warnings.push(...effort.notes);
366
+ plan.policyFeatures.push(...plan.features.features);
367
+ // A backup's reasoning degradation can invalidate model-specific choices (for example named tools with thinking on).
368
+ if (deps.registry.get(plan.model.adapterId).resolveRequestCapabilities &&
369
+ JSON.stringify(effort.effective) !== JSON.stringify(plan.slot.settings.reasoning ?? { mode: "provider-default" })) {
370
+ const rechecked = planGenerationFeatures({ request: plan.features.request, model: plan.model,
371
+ adapter: deps.registry.get(plan.model.adapterId), role: plan.role, reasoningControl: effort.effective });
372
+ plan.features.request = rechecked.request;
373
+ plan.features.capabilities = rechecked.capabilities;
374
+ plan.policyFeatures.push(...rechecked.features);
375
+ for (const feature of rechecked.features)
376
+ if (feature.feature !== "reasoning" && !plan.features.features.some(existing => JSON.stringify(existing) === JSON.stringify(feature))) {
377
+ plan.features.features = plan.features.features.filter(existing => existing.feature !== feature.feature);
378
+ plan.features.features.push(feature);
379
+ }
380
+ for (const warning of rechecked.warnings)
381
+ if (!plan.warnings.includes(warning))
382
+ plan.warnings.push(warning);
383
+ }
384
+ const policyErrors = evaluateFeaturePolicy(options.featurePolicy, plan.features, { original: plan.originalRequest,
385
+ model: plan.model, adapter: deps.registry.get(plan.model.adapterId), cumulativeFeatures: plan.policyFeatures });
386
+ if (policyErrors.length) {
387
+ if (plan.role === "primary")
388
+ throw new UnsupportedCapabilityError("Primary does not satisfy featurePolicy: " + policyErrors.join("; "));
389
+ warnings.push(`Fallback ${plan.slot.catalogId} excluded by featurePolicy: ${policyErrors.join("; ")}.`);
390
+ return [];
391
+ }
392
+ const effectiveEstimate = plan.estimatedInputTokens;
393
+ const ceiling = preflightCostCeiling(priceForModel(snapshot.catalog, snapshot.manifest, plan.slot.catalogId), effectiveEstimate, output.effective ?? knownOutputCeiling(plan.model, effectiveEstimate), plan.costContext);
394
+ return [{ plan, effort, nativeSettings, output, preflightCost: toCostEstimate(ceiling, "preflight-estimate") }];
395
+ });
396
+ // The applicable cost-ceiling policy: profile, client, and invocation caps intersect.
397
+ const budget = intersectCostCaps(profile.caps?.maxEstimatedCost, deps.clientCaps?.maxEstimatedCost, options.caps?.maxEstimatedCost);
398
+ let reservedCost = 0;
399
+ const retryableClasses = new Set(profile.execution.retry.retryableErrorClasses);
400
+ let attemptIndex = 0;
401
+ let slotCursor = 0, visitIndex = 0;
402
+ const unavailableSlots = new Set();
403
+ const forward = profile.execution.fallbackPolicy === "forward-only";
404
+ const hasNextPlan = () => preparedPlans.some((evidence, index) => (!forward || index >= slotCursor) &&
405
+ !unavailableSlots.has(evidence.plan.slotIndex));
406
+ const nextPlan = () => {
407
+ for (let scanned = 0; scanned < preparedPlans.length; scanned++) {
408
+ if (forward && slotCursor >= preparedPlans.length)
409
+ return undefined;
410
+ const candidate = preparedPlans[slotCursor++ % preparedPlans.length];
411
+ if (!unavailableSlots.has(candidate.plan.slotIndex))
412
+ return candidate;
413
+ }
414
+ return undefined;
415
+ };
416
+ let lastError;
417
+ while (attemptIndex < maxAttempts && hasNextPlan()) {
418
+ if (options.signal?.aborted)
419
+ throw new CancellationError();
420
+ const remaining = deadlineAt - clock();
421
+ if (remaining <= 0) {
422
+ throw new AttemptsExhaustedError(`Deadline of ${deadlineMs}ms exhausted before attempt ${attemptIndex + 1}.`, { attempts: attempts.length });
423
+ }
424
+ const evidence = nextPlan();
425
+ visitIndex++;
426
+ const { plan, nativeSettings, output } = evidence;
427
+ warnings.push(...plan.warnings);
428
+ const effectiveSearch = plan.features.request.webSearch === true;
429
+ const price = priceForModel(snapshot.catalog, snapshot.manifest, plan.slot.catalogId);
430
+ if (price?.schemaVersion === 2)
431
+ warnings.push(`Price ${price.priceRevisionId} uses rates observed at ${price.observedAt}; ` +
432
+ `provider effective-from ${price.effectiveDate ?? "unknown"}. Cost remains an estimate from the exact pinned observation.`);
433
+ lastEvidence = evidence;
434
+ let reservedForAttempt = 0;
435
+ const reserveBudget = () => {
251
436
  if (budget) {
252
- if (search)
437
+ if (effectiveSearch)
253
438
  throw new BudgetExceededError("Cannot enforce search cost ceiling without verified tool pricing and metering");
254
439
  if (!evidence.preflightCost.priceKnown || budget.currency !== evidence.preflightCost.currency) {
255
440
  throw new BudgetExceededError("Cannot enforce configured cost ceiling: missing or incompatible prices");
@@ -261,262 +446,450 @@ export function createRun(token, snapshot, deps, resolutionWarnings = []) {
261
446
  reservedForAttempt = evidence.preflightCost.amount;
262
447
  reservedCost += reservedForAttempt;
263
448
  }
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
- };
449
+ };
450
+ attemptIndex += 1;
451
+ const attemptStartedAt = clock();
452
+ const attemptTimeout = callerTiming ? options.execution?.attemptTimeoutMs ?? Infinity
453
+ : Math.min(remaining, profile.execution.attemptTimeoutMs ?? 60_000, options.execution?.attemptTimeoutMs ?? Infinity);
454
+ let providerRequestStarted = false;
455
+ let response;
456
+ let streamStarted = false, streamResponseId;
457
+ try {
458
+ const adapter = deps.registry.get(plan.model.adapterId);
459
+ const connection = Object.hasOwn(token.connections, plan.model.provider) ? token.connections[plan.model.provider] : undefined;
460
+ if (!connection) {
461
+ throw new CredentialUnavailableError(`No connection configured for provider "${plan.model.provider}" in application ${token.applicationId}`, { provider: plan.model.provider });
462
+ }
463
+ const scheduledAttempt = async (queueSignal) => {
464
+ const attemptContext = {
465
+ attemptId: `${requestId}-visit-${visitIndex}`,
466
+ catalogId: plan.model.catalogId,
467
+ providerModelId: plan.model.providerModelId,
468
+ provider: plan.model.provider,
469
+ providerTools: plan.model.capabilities.providerTools,
470
+ webSearch: effectiveSearch,
471
+ remainingDeadlineMs: deadlineAt - clock(),
472
+ signal: queueSignal
473
+ };
474
+ let admitted = false;
475
+ let completedResult;
476
+ const startAttempt = async () => {
477
+ if (queueSignal?.aborted)
478
+ throw options.signal?.aborted ? new CancellationError() : deadlineError();
479
+ if (deadlineAt - clock() <= 0)
480
+ throw deadlineError();
481
+ if (admitted)
482
+ throw new ConfigurationInvalidError("An attempt may only be admitted once");
483
+ admitted = true;
484
+ const admittedTimeout = Math.min(attemptTimeout, deadlineAt - clock());
485
+ const attemptDeadlineAt = clock() + admittedTimeout;
486
+ const completed = await withDeadline(async (signal) => {
487
+ const credentialRequest = "directModel" in token && "modelCredentialResolver" in deps
488
+ ? deps.modelCredentialResolver.resolve(connection.credentialReference, { applicationId: token.applicationId,
489
+ revision: token.directModel.modelConfigurationDigest, provider: plan.model.provider })
490
+ : "model" in token && "modelCredentialResolver" in deps
491
+ ? deps.modelCredentialResolver.resolve(connection.credentialReference, { applicationId: token.applicationId,
492
+ ...("configurationId" in token.model ? { configurationId: token.model.configurationId } : {}), revision: token.model.revision, provider: plan.model.provider })
493
+ : "native" in token && "nativeCredentialResolver" in deps
494
+ ? deps.nativeCredentialResolver.resolve(connection.credentialReference, { applicationId: token.applicationId,
495
+ configurationId: token.native.configurationId, workspaceId: token.native.workspaceId,
496
+ revision: token.native.revision, provider: plan.model.provider })
497
+ : !("native" in token) && !("model" in token) && !("directModel" in token) && "credentialResolver" in deps
498
+ ? deps.credentialResolver.resolve(connection.credentialReference, { applicationId: token.applicationId,
499
+ environmentId: token.environmentId, provider: plan.model.provider })
500
+ : Promise.reject(new ConfigurationInvalidError("Credential protocol mismatch"));
501
+ const credential = await credentialRequest.catch((resolverError) => {
502
+ // A decryptable-failure (corrupt/undecryptable secure store) stops with an
503
+ // actionable status; a missing credential records a skip and moves forward.
504
+ if (resolverError instanceof CredentialInvalidError)
505
+ throw resolverError;
506
+ throw new CredentialUnavailableError(`Credential unavailable for provider ${plan.model.provider}`);
507
+ });
508
+ const assertDispatchAllowed = () => {
509
+ if (options.signal?.aborted)
510
+ throw new CancellationError();
511
+ if (signal.aborted || clock() >= attemptDeadlineAt) {
512
+ throw new ProviderCallError("provider-timeout", "Attempt deadline exceeded before dispatch", true);
513
+ }
514
+ };
515
+ assertDispatchAllowed();
516
+ const dispatchTimeout = Math.min(attemptDeadlineAt, deadlineAt) - clock();
517
+ const guardedFetch = async (input, init) => {
317
518
  assertDispatchAllowed();
318
- const dispatchTimeout = callerTiming ? Math.min(attemptDeadlineAt, deadlineAt) - clock() : attemptTimeout;
319
- const guardedFetch = (input, init) => {
519
+ const result = await deps.fetchImpl(input, { ...init, signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal });
520
+ try {
320
521
  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();
522
+ }
523
+ catch (error) {
524
+ try {
525
+ void result.body?.cancel().catch(() => { });
526
+ }
527
+ catch { }
528
+ throw error;
529
+ }
339
530
  return result;
340
- }, admittedTimeout, () => new ProviderCallError("provider-timeout", "Attempt deadline exceeded", true), queueSignal);
341
- };
342
- return (deps.attemptExecutor ?? ((_context, start) => start()))(attemptContext, startAttempt);
531
+ };
532
+ reserveBudget();
533
+ providerRequestStarted = true;
534
+ const adapterRequest = {
535
+ model: plan.model,
536
+ systemInstructions: effectiveInstructions,
537
+ input: plan.input,
538
+ outputSchema: plan.structured ? outputSchema : undefined,
539
+ operation: { ...operation, webSearch: effectiveSearch },
540
+ ...(adapter.contractVersion === 2 ? { generation: { ...plan.features.request,
541
+ ...(output.effective !== undefined ? { maxOutputTokens: output.effective } : {}) } } : {}),
542
+ nativeSettings,
543
+ ...(output.effective !== undefined ? { maxOutputTokens: output.effective } : {}),
544
+ temperature: plan.features.request.temperature,
545
+ endpoint: connection.endpoint ?? adapter.defaultEndpoint,
546
+ credential,
547
+ timeoutMs: dispatchTimeout,
548
+ signal
549
+ };
550
+ let result;
551
+ if (invocation?.stream && !plan.features.buffered && adapter.stream) {
552
+ const iterator = consumeAdapterStream(adapter.stream(adapterRequest, guardedFetch));
553
+ const streamEvidence = createStreamEvidence({ provider: plan.model.provider, adapterId: adapter.id, adapterVersion: adapter.version });
554
+ let usage;
555
+ try {
556
+ while (true) {
557
+ const item = await abortable(iterator.next(), signal);
558
+ if (item.done) {
559
+ result = item.value;
560
+ result.usage = mergeReportedUsage(usage, result.generation?.usage, result.usage);
561
+ break;
562
+ }
563
+ if (item.value.type === "usage")
564
+ usage = mergeReportedUsage(usage, item.value.usage);
565
+ let event = item.value;
566
+ let providerDerived = true;
567
+ if (event.type === "start") {
568
+ providerDerived = event.id !== undefined || event.model !== undefined;
569
+ streamResponseId = event.id ?? requestId;
570
+ streamStarted = true;
571
+ event = { ...event, id: streamResponseId, model: event.model ?? plan.model.providerModelId };
572
+ }
573
+ else if (!streamStarted && event.type !== "usage") {
574
+ streamResponseId = requestId;
575
+ streamStarted = true;
576
+ streamEvidence.add({ type: "start", id: requestId, model: plan.model.providerModelId });
577
+ await abortable(invocation.stream.emit({ attempt: attemptIndex,
578
+ providerDerived: false, event: { type: "start", id: requestId, model: plan.model.providerModelId } }), signal);
579
+ }
580
+ streamEvidence.add(event);
581
+ await abortable(invocation.stream.emit({ attempt: attemptIndex, event, providerDerived }), signal);
582
+ }
583
+ }
584
+ catch (error) {
585
+ const partial = error instanceof AISubsystemError && error.partialResult ? error.partialResult : streamEvidence.partial();
586
+ partial.usage = mergeReportedUsage(usage, partial.usage);
587
+ response = { output: { kind: "text", text: partial.text }, generation: partial, usage: partial.usage };
588
+ throw error;
589
+ }
590
+ finally {
591
+ void iterator.return(undefined).catch(() => { });
592
+ }
593
+ }
594
+ else
595
+ result = await adapter.execute(adapterRequest, guardedFetch);
596
+ assertDispatchAllowed();
597
+ return result;
598
+ }, admittedTimeout, () => new ProviderCallError("provider-timeout", "Attempt deadline exceeded", true), queueSignal);
599
+ completedResult = completed;
600
+ return completed;
343
601
  };
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") {
602
+ const guardedStart = () => {
603
+ const pending = startAttempt();
604
+ void pending.catch(() => { }); // A host that abandons its promise cannot leak a late rejection.
605
+ return pending;
606
+ };
607
+ const result = await (deps.attemptExecutor ?? ((_context, start) => start()))(attemptContext, guardedStart);
608
+ if (!admitted || !completedResult || result !== completedResult)
609
+ throw new ConfigurationInvalidError("Attempt executor must return the admitted provider result");
610
+ return result;
611
+ };
612
+ if (invocation?.stream)
613
+ for (const message of plan.warnings)
614
+ await withDeadline(() => invocation.stream.emit({ attempt: attemptIndex, event: { type: "warning", message } }), deadlineAt - clock(), deadlineError, options.signal);
615
+ response = await withDeadline(scheduledAttempt, deadlineAt - clock(), deadlineError, options.signal);
616
+ if (options.signal?.aborted)
617
+ throw new CancellationError();
618
+ if (clock() >= deadlineAt)
619
+ throw deadlineError();
620
+ response = validateAdapterResponse(response);
621
+ response.usage = mergeReportedUsage(response.generation?.usage, response.usage);
622
+ let generation;
623
+ if (invocation) {
624
+ generation = generationFromAdapterResponse(response);
625
+ generation.id ??= response.providerRequestId ?? streamResponseId ?? requestId;
626
+ if (streamStarted && generation.id !== streamResponseId)
627
+ throw new InvalidOutputError("Adapter stream response ID differs from its final result ID");
628
+ generation.providerModelId ??= plan.model.providerModelId;
629
+ generation.usage = response.usage;
630
+ generation.features = [...plan.features.features, ...(generation.features ?? [])];
631
+ if (generation.native) {
632
+ generation.native.provider = plan.model.provider;
633
+ generation.native.adapterId = plan.implementation.id;
634
+ generation.native.adapterVersion = plan.implementation.version;
635
+ }
636
+ if (plan.continuationRequest && plan.continuationTarget)
637
+ generation.continuation = createContinuationState({
638
+ request: plan.continuationRequest, output: generation, target: plan.continuationTarget,
639
+ nativeItems: generation.continuation?.nativeItems
640
+ });
641
+ response.generation = generation;
642
+ if (generation.status === "failed")
643
+ throw new InvalidOutputError("Provider returned a failed generation");
644
+ }
645
+ if (!invocation) {
646
+ if (response.generation?.status === "incomplete")
647
+ throw new ProviderOutputTruncatedError("Provider returned incomplete output");
648
+ if (response.output.kind === "refusal" || response.generation?.status === "refused")
352
649
  throw new InvalidOutputError("Provider returned a refusal");
650
+ if (response.generation && response.generation.status !== "completed")
651
+ throw new InvalidOutputError("Legacy generate requires completed output; use a rich client interface for tool continuation");
652
+ }
653
+ let value;
654
+ const validateStructured = plan.structured && (!generation || generation.status === "completed");
655
+ if (validateStructured) {
656
+ if (response.output.kind === "structured") {
657
+ value = response.output.value;
353
658
  }
354
- let value;
355
- if (structured) {
356
- if (response.output.kind === "structured") {
357
- value = response.output.value;
659
+ else {
660
+ try {
661
+ value = JSON.parse(generation?.text ?? (response.output.kind === "text" ? response.output.text : ""));
358
662
  }
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("; ")}`);
663
+ catch {
664
+ throw new InvalidOutputError("Provider returned non-JSON output where structured output was required.");
370
665
  }
371
666
  }
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.");
667
+ const result = outputValidator(value);
668
+ if (!result.valid) {
669
+ throw new InvalidOutputError(`Provider output does not conform to the requested output schema: ${result.errors.slice(0, 5).join("; ")}`);
376
670
  }
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).`);
671
+ }
672
+ if (invocation?.stream && generation) {
673
+ if (!streamStarted)
674
+ await withDeadline(() => invocation.stream.emit({ attempt: attemptIndex,
675
+ event: { type: "start", id: generation.id, model: generation.providerModelId } }), deadlineAt - clock(), deadlineError, options.signal);
676
+ await withDeadline(() => invocation.stream.emit({ attempt: attemptIndex, event: { type: "output", output: generation } }), deadlineAt - clock(), deadlineError, options.signal);
677
+ if (options.signal?.aborted)
678
+ throw new CancellationError();
679
+ }
680
+ const cost = response.usage ? toCostEstimate(costFromUsage(response.usage, price, mergeCostContexts(plan.costContext, response.generation?.costContext)), "reported-usage")
681
+ : toCostEstimate(applyReportedCostContext(evidence.preflightCost, response.generation?.costContext), "preflight-estimate");
682
+ // Search is not uniformly metered across providers; token costs alone are not the total.
683
+ if (effectiveSearch) {
684
+ warnings.push("Total cost is unknown because provider-hosted tool charges are not fully metered.");
685
+ }
686
+ if (!cost.priceKnown) {
687
+ warnings.push(`Pricing for model ${plan.slot.catalogId} is unknown for at least one used dimension; cost estimate omitted (unknown is never zero).`);
688
+ if (cost.uncertainties?.length)
689
+ warnings.push("Cost estimate is incomplete: " + cost.uncertainties.join(", ") + ".");
690
+ }
691
+ if (!response.usage)
692
+ warnings.push("Provider did not report usage; cost uses available preflight evidence, not measured usage.");
693
+ attempts.push({
694
+ generation: generationEvidence(evidence, response.generation?.status ?? "completed", true),
695
+ attempt: attemptIndex,
696
+ catalogId: plan.slot.catalogId,
697
+ providerModelId: plan.model.providerModelId,
698
+ role: plan.role,
699
+ latencyMs: elapsedSince(attemptStartedAt),
700
+ outcome: "succeeded",
701
+ providerRequestStarted,
702
+ effective: effectiveControls(executionConfiguration(token), evidence),
703
+ usage: response.usage,
704
+ costEstimate: cost
705
+ });
706
+ const totalCost = summarizeAttemptCosts(attempts);
707
+ if (attempts.length > 1 && totalCost?.basis === "preflight-estimate") {
708
+ warnings.push("Total cost includes conservative preflight estimates for attempts without reported usage.");
709
+ }
710
+ const receipt = await emit(buildReceipt({
711
+ status: "succeeded",
712
+ runId,
713
+ requestId,
714
+ operationId: options.operationId,
715
+ token,
716
+ snapshot,
717
+ attempts,
718
+ skippedSlots,
719
+ requested: requestedBlock(options, resolvedOutputSchema),
720
+ evidence: lastEvidence,
721
+ usage: response.usage,
722
+ cost: totalCost,
723
+ warnings,
724
+ startedAt
725
+ }));
726
+ return {
727
+ output: validateStructured ? { kind: "structured", value } : { kind: "text", text: generation?.text ??
728
+ (response.output.kind === "structured" ? JSON.stringify(response.output.value) : response.output.kind === "text" ? response.output.text : "") },
729
+ executionReceipt: receipt, ...(generation ? { generation, requestId, providerModelId: plan.model.providerModelId } : {})
730
+ };
731
+ }
732
+ catch (error) {
733
+ const aiError = error instanceof AISubsystemError ? error : new AISubsystemError("network-error", "Provider adapter failed unexpectedly", true);
734
+ if (!response && aiError.partialResult)
735
+ response = { output: { kind: "text", text: aiError.partialResult.text },
736
+ generation: aiError.partialResult, usage: aiError.partialResult.usage };
737
+ if (response?.usage !== undefined) {
738
+ try {
739
+ response.usage = validateUsage(response.usage);
379
740
  }
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.");
741
+ catch {
742
+ delete response.usage;
397
743
  }
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
744
  }
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;
745
+ if (response?.generation) {
746
+ try {
747
+ response.generation = validateGenerationOutput(response.generation);
748
+ response.generation.features ??= structuredClone(plan.features.features);
749
+ response.generation.id ??= streamResponseId ?? requestId;
750
+ response.generation.providerModelId ??= plan.model.providerModelId;
751
+ response.usage = mergeReportedUsage(response.generation.usage, response.usage);
752
+ response.generation.usage = response.usage;
426
753
  }
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();
754
+ catch {
755
+ delete response.generation;
442
756
  }
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));
757
+ }
758
+ const implementation = deps.registry.get(plan.model.adapterId);
759
+ if (response?.generation)
760
+ attachProviderErrorContext(aiError, {
761
+ native: aiError.native ?? response.generation.native, partialResult: response.generation
762
+ });
763
+ if (!aiError.native && aiError.httpResponse)
764
+ attachProviderErrorContext(aiError, { native: {
765
+ provider: plan.model.provider, adapterId: implementation.id, adapterVersion: implementation.version,
766
+ body: aiError.httpResponse.body, ...(aiError.httpResponse.requestId ? { requestId: aiError.httpResponse.requestId } : {})
767
+ } });
768
+ // Queue rejection, missing credentials, and other failures before adapter
769
+ // execution cannot consume provider budget. Release only those reservations;
770
+ // once adapter execution starts, retain the conservative allowance.
771
+ if (!providerRequestStarted && reservedForAttempt > 0) {
772
+ reservedCost -= reservedForAttempt;
773
+ reservedForAttempt = 0;
774
+ }
775
+ if (options.signal?.aborted || aiError.code === "cancelled") {
448
776
  attempts.push({
777
+ generation: generationEvidence(evidence, response?.generation?.status ?? "failed", invocation?.stream?.context.outputExposed ?? false),
449
778
  attempt: attemptIndex,
450
779
  catalogId: plan.slot.catalogId,
451
780
  providerModelId: plan.model.providerModelId,
452
781
  role: plan.role,
453
- latencyMs: Date.now() - attemptStartedAt,
454
- outcome: "failed",
782
+ latencyMs: elapsedSince(attemptStartedAt),
783
+ outcome: "cancelled",
455
784
  providerRequestStarted,
456
- effective: effectiveControls(token.profile, evidence),
457
- errorClass: aiError.code,
458
- errorMessage: receiptErrorMessage(aiError),
785
+ effective: effectiveControls(executionConfiguration(token), evidence),
786
+ errorClass: "cancelled",
459
787
  usage: response?.usage,
460
- costEstimate: withUnknownToolCharges(response?.usage ? toCostEstimate(costFromUsage(response.usage, price), "reported-usage") : evidence.preflightCost, search)
788
+ costEstimate: response?.usage ? toCostEstimate(costFromUsage(response.usage, price, mergeCostContexts(plan.costContext, response.generation?.costContext)), "reported-usage")
789
+ : toCostEstimate(applyReportedCostContext(evidence.preflightCost, response?.generation?.costContext), "preflight-estimate")
461
790
  });
462
- if (!eligible)
463
- throw aiError;
791
+ throw attachProviderErrorContext(new CancellationError(), aiError);
792
+ }
793
+ const errorClass = RETRYABLE_CODE_TO_CLASS[aiError.code];
794
+ if (aiError.code === "credential-unavailable" || aiError.code === "model-unavailable") {
795
+ unavailableSlots.add(plan.slotIndex);
796
+ skippedSlots.push({ slot: plan.slotIndex, catalogId: plan.slot.catalogId, providerModelId: plan.model.providerModelId,
797
+ role: plan.role, phase: "execution", reason: aiError.code, providerRequestStarted });
798
+ warnings.push(`${plan.role} ${plan.slot.catalogId}: ${aiError.code}; skipped for the remainder of this invocation.`);
464
799
  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
- });
800
+ if (!providerRequestStarted) {
801
+ attemptIndex--;
802
+ continue;
475
803
  }
476
804
  }
805
+ // Explicit model unavailability always moves the chain forward (the slot is
806
+ // recorded as skipped); other classes follow the profile's retry policy.
807
+ const eligible = aiError.code === "model-unavailable" || aiError.code === "credential-unavailable" ||
808
+ (aiError.retryable && errorClass !== undefined && retryableClasses.has(errorClass));
809
+ attempts.push({
810
+ generation: generationEvidence(evidence, response?.generation?.status ?? "failed", invocation?.stream?.context.outputExposed ?? false),
811
+ attempt: attemptIndex,
812
+ catalogId: plan.slot.catalogId,
813
+ providerModelId: plan.model.providerModelId,
814
+ role: plan.role,
815
+ latencyMs: elapsedSince(attemptStartedAt),
816
+ outcome: "failed",
817
+ providerRequestStarted,
818
+ effective: effectiveControls(executionConfiguration(token), evidence),
819
+ errorClass: aiError.code,
820
+ errorMessage: receiptErrorMessage(aiError),
821
+ usage: response?.usage,
822
+ costEstimate: response?.usage ? toCostEstimate(costFromUsage(response.usage, price, mergeCostContexts(plan.costContext, response.generation?.costContext)), "reported-usage")
823
+ : toCostEstimate(applyReportedCostContext(evidence.preflightCost, response?.generation?.costContext), "preflight-estimate")
824
+ });
825
+ if (!eligible || invocation?.stream?.context.outputExposed)
826
+ throw aiError;
827
+ lastError = aiError;
828
+ const hint = aiError.httpResponse?.retryAfterMs;
829
+ const delay = Math.max(profile.execution.retry.minRetryDelayMs ?? 0, typeof hint === "number" && Number.isFinite(hint) && hint >= 0 ? hint : 0);
830
+ if (delay > 0 && attemptIndex < maxAttempts && hasNextPlan())
831
+ await retryDelay(delay, deadlineAt - clock(), deadlineError, options.signal);
477
832
  }
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
833
  }
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
- }));
834
+ throw attachProviderErrorContext(new AttemptsExhaustedError(`Attempts exhausted or all remaining slots unavailable (${attemptIndex}/${maxAttempts} attempts consumed).`, { attempts: attempts.length, lastError: lastError?.code }), lastError ?? {});
835
+ }
836
+ catch (error) {
837
+ const aiError = error instanceof AISubsystemError
838
+ ? error
839
+ : new AISubsystemError("network-error", "Unexpected execution failure", true);
840
+ const status = aiError.code === "cancelled"
841
+ ? "cancelled"
842
+ : PREFLIGHT_CODES.has(aiError.code) && attempts.length === 0
843
+ ? "rejected"
844
+ : "failed";
845
+ const receiptOperationId = typeof options.operationId === "string" &&
846
+ OPERATION_ID_PATTERN.test(options.operationId)
847
+ ? options.operationId
848
+ : "invalid-operation-id";
849
+ const receipt = await emit(buildReceipt({
850
+ status,
851
+ runId,
852
+ requestId,
853
+ operationId: receiptOperationId,
854
+ token,
855
+ snapshot,
856
+ attempts,
857
+ skippedSlots,
858
+ requested: requestedBlock(options, resolvedOutputSchema),
859
+ evidence: lastEvidence,
860
+ cost: summarizeAttemptCosts(attempts),
861
+ warnings,
862
+ startedAt,
863
+ error: { code: aiError.code, message: receiptErrorMessage(aiError) }
864
+ }));
865
+ if ("kind" in receipt && receipt.kind === "direct-model-execution-receipt")
866
+ aiError.directModelExecutionReceipt = receipt;
867
+ else if ("kind" in receipt && receipt.kind === "profile-execution-receipt")
868
+ aiError.profileExecutionReceipt = receipt;
869
+ else if ("kind" in receipt && receipt.kind === "model-execution-receipt")
870
+ aiError.modelExecutionReceipt = receipt;
871
+ else if ("kind" in receipt)
872
+ aiError.nativeExecutionReceipt = receipt;
873
+ else
508
874
  aiError.executionReceipt = receipt;
509
- throw aiError;
510
- }
875
+ throw aiError;
511
876
  }
512
- };
877
+ }
878
+ return { get resolution() { return structuredClone(token); }, generate: options => execute(options),
879
+ ...createCompatibilityInterfaces(execute) };
513
880
  }
514
881
  function validateInvocationControls(options) {
882
+ if (options.featurePolicy !== undefined)
883
+ validateFeaturePolicy(options.featurePolicy);
515
884
  if (options.maxOutputTokens !== undefined && (!Number.isSafeInteger(options.maxOutputTokens) || options.maxOutputTokens <= 0)) {
516
885
  throw new ConfigurationInvalidError("GenerateOptions.maxOutputTokens must be a positive integer");
517
886
  }
518
887
  validateExecutionCaps(options.caps, "Invocation");
888
+ if (options.execution !== undefined && (!options.execution || typeof options.execution !== "object" || Array.isArray(options.execution)))
889
+ throw new ConfigurationInvalidError("Execution settings must be an object");
519
890
  for (const [name, value] of Object.entries(options.execution ?? {})) {
891
+ if (!["timingPolicy", "attemptTimeoutMs", "deadlineMs", "maxAttempts"].includes(name))
892
+ throw new ConfigurationInvalidError("Execution settings contain an unsupported field");
520
893
  if (name === "timingPolicy") {
521
894
  if (value !== undefined && value !== "profile" && value !== "caller") {
522
895
  throw new ConfigurationInvalidError("Execution timingPolicy must be profile or caller");
@@ -532,6 +905,8 @@ function validateInvocationControls(options) {
532
905
  }
533
906
  const byModel = options.effortByModel;
534
907
  if (byModel !== undefined) {
908
+ if (!byModel || typeof byModel !== "object" || Array.isArray(byModel))
909
+ throw new ConfigurationInvalidError("effortByModel must be an object");
535
910
  const entries = Object.entries(byModel);
536
911
  if (entries.length > 32)
537
912
  throw new ConfigurationInvalidError("effortByModel supports at most 32 model entries");
@@ -542,6 +917,20 @@ function validateInvocationControls(options) {
542
917
  }
543
918
  }
544
919
  }
920
+ function validateGenerateInput(input) {
921
+ if (typeof input === "string")
922
+ return;
923
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !["text", "images"].includes(key)) ||
924
+ (input.text !== undefined && typeof input.text !== "string") || (input.images !== undefined && !Array.isArray(input.images)))
925
+ throw new ConfigurationInvalidError("Generation input must be text or a text/images object");
926
+ for (const image of input.images ?? []) {
927
+ if (!image || typeof image !== "object" || Array.isArray(image) ||
928
+ Object.keys(image).some(key => !["mimeType", "dataBase64", "detail"].includes(key)) ||
929
+ typeof image.mimeType !== "string" || !image.mimeType || typeof image.dataBase64 !== "string" ||
930
+ (image.detail !== undefined && !["auto", "low", "high", "original"].includes(image.detail)))
931
+ throw new ConfigurationInvalidError("Generation images must contain MIME type, base64 data and optional valid detail");
932
+ }
933
+ }
545
934
  export function validateExecutionCaps(caps, label) {
546
935
  if (caps !== undefined && (caps === null || typeof caps !== "object" || Array.isArray(caps))) {
547
936
  throw new ConfigurationInvalidError(`${label} caps must be an object`);
@@ -571,36 +960,31 @@ export function validateExecutionCaps(caps, label) {
571
960
  function validateProfileSlotSemantics(profile, plan) {
572
961
  const { model, slot, role } = plan;
573
962
  const invalid = (message) => {
574
- throw new ConfigurationInvalidError(`${role} ${slot.catalogId}: ${message}`, { profileId: profile.profileId, catalogId: slot.catalogId });
963
+ throw new ConfigurationInvalidError(`${role} ${slot.catalogId}: ${message}`, {
964
+ ...("profileId" in profile ? { profileId: profile.profileId } : {}), catalogId: slot.catalogId
965
+ });
575
966
  };
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
967
  const configured = slot.settings.reasoning;
589
968
  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`);
969
+ throw new UnsupportedCapabilityError(`Effort policy cannot preserve effort hints through a ${configured.mode} reasoning control`);
591
970
  }
592
971
  const policy = profile.effortPolicy?.byModel?.[slot.catalogId];
593
972
  if (!policy)
594
973
  return;
595
974
  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");
975
+ if (model.nativeReasoning.supportedControls !== undefined && !model.nativeReasoning.supportedControls.includes("effort")) {
976
+ throw new UnsupportedCapabilityError("Effort policy requires native levels this model does not support");
977
+ }
978
+ if (!levels) {
979
+ if (policy.minimum !== undefined || policy.maximum !== undefined)
980
+ throw new UnsupportedCapabilityError("Ordered effort bounds require known native level ordering");
981
+ return;
598
982
  }
599
983
  const supportedLevels = levels;
600
984
  const rank = (level) => supportedLevels.indexOf(level);
601
985
  const assertLevel = (kind, level) => {
602
986
  if (rank(level) < 0)
603
- invalid(`effort policy ${kind} "${level}" is not a supported native level`);
987
+ throw new UnsupportedCapabilityError(`Effort policy ${kind} is not a supported native level`);
604
988
  };
605
989
  if (policy.minimum !== undefined)
606
990
  assertLevel("minimum", policy.minimum);
@@ -645,11 +1029,20 @@ function receiptErrorMessage(error) {
645
1029
  function minDefined(...values) {
646
1030
  return Math.min(...values.filter((value) => value !== undefined));
647
1031
  }
1032
+ function knownOutputCeiling(model, inputTokens = 0) {
1033
+ const ceiling = minDefined(model.capabilities.maxOutputTokens, model.capabilities.contextWindowTokens === undefined ? undefined : Math.max(0, model.capabilities.contextWindowTokens - inputTokens));
1034
+ return Number.isFinite(ceiling) ? ceiling : undefined;
1035
+ }
648
1036
  function requestedBlock(options, outputSchema) {
1037
+ // Rejected calls can contain malformed controls: evidence must still satisfy its schema.
1038
+ const bounded = (value) => typeof value === "string" && value.length > 0 && value.length <= 128;
1039
+ const byModel = options.effortByModel && typeof options.effortByModel === "object" && !Array.isArray(options.effortByModel)
1040
+ ? Object.entries(options.effortByModel) : undefined;
1041
+ const validByModel = byModel && byModel.length <= 32 && byModel.every(([key, value]) => bounded(key) && bounded(value));
649
1042
  return {
650
- ...(options.effortHint !== undefined ? { effortHint: options.effortHint } : {}),
651
- ...(options.effortByModel !== undefined ? { effortByModel: options.effortByModel } : {}),
652
- ...(options.maxOutputTokens !== undefined ? { maxOutputTokens: options.maxOutputTokens } : {}),
1043
+ ...(bounded(options.effortHint) ? { effortHint: options.effortHint } : {}),
1044
+ ...(validByModel ? { effortByModel: Object.fromEntries(byModel) } : {}),
1045
+ ...(Number.isSafeInteger(options.maxOutputTokens) && options.maxOutputTokens > 0 ? { maxOutputTokens: options.maxOutputTokens } : {}),
653
1046
  outputSchemaPresent: outputSchema !== undefined
654
1047
  };
655
1048
  }
@@ -671,15 +1064,10 @@ function toCostEstimate(cost, basis) {
671
1064
  ...(cost.amount !== undefined ? { amount: cost.amount } : {}),
672
1065
  ...(cost.priceRevisionId !== undefined ? { priceRevisionId: cost.priceRevisionId } : {}),
673
1066
  priceKnown: cost.priceKnown,
1067
+ ...(cost.uncertainties?.length ? { uncertainties: [...cost.uncertainties] } : {}),
674
1068
  basis
675
1069
  };
676
1070
  }
677
- function withUnknownToolCharges(cost, providerToolUsed) {
678
- if (!providerToolUsed)
679
- return cost;
680
- const { amount: _amount, ...withoutAmount } = cost;
681
- return { ...withoutAmount, priceKnown: false };
682
- }
683
1071
  /**
684
1072
  * Produces one terminal estimate without combining currencies. Per-attempt estimates retain
685
1073
  * the complete multi-currency evidence when a fallback crosses providers/currencies.
@@ -690,8 +1078,10 @@ function summarizeAttemptCosts(attempts) {
690
1078
  return undefined;
691
1079
  const currencies = new Set(billable.map(cost => cost.currency));
692
1080
  const terminal = billable[billable.length - 1];
1081
+ const uncertainties = [...new Set(billable.flatMap(cost => cost.uncertainties ?? []))];
1082
+ const basis = billable.every(cost => cost.basis === "reported-usage") ? "reported-usage" : "preflight-estimate";
693
1083
  if (currencies.size > 1) {
694
- return { currency: terminal.currency, priceKnown: false, basis: "preflight-estimate" };
1084
+ return { currency: terminal.currency, priceKnown: false, basis, uncertainties: [...uncertainties, "currency"] };
695
1085
  }
696
1086
  const revisions = new Set(billable.map(cost => cost.priceRevisionId).filter((revision) => revision !== undefined));
697
1087
  const known = billable.every(cost => cost.priceKnown && cost.amount !== undefined);
@@ -700,7 +1090,8 @@ function summarizeAttemptCosts(attempts) {
700
1090
  ...(known ? { amount: billable.reduce((sum, cost) => sum + cost.amount, 0) } : {}),
701
1091
  ...(revisions.size === 1 ? { priceRevisionId: [...revisions][0] } : {}),
702
1092
  priceKnown: known,
703
- basis: billable.every(cost => cost.basis === "reported-usage") ? "reported-usage" : "preflight-estimate"
1093
+ ...(uncertainties.length ? { uncertainties } : {}),
1094
+ basis
704
1095
  };
705
1096
  }
706
1097
  /** Cost caps intersect only within one currency; caps in different currencies cannot be combined. */
@@ -723,7 +1114,7 @@ function intersectCostCaps(...caps) {
723
1114
  function resolveOutputTokens(input) {
724
1115
  const request = input.requested ?? input.slotDefault ?? input.profileDefault;
725
1116
  const bounds = [
726
- { source: "model", value: input.modelCapability },
1117
+ ...(input.modelCapability !== undefined ? [{ source: "model", value: input.modelCapability }] : []),
727
1118
  ...(input.profileCap !== undefined ? [{ source: "profile", value: input.profileCap }] : []),
728
1119
  ...(input.clientCap !== undefined ? [{ source: "client", value: input.clientCap }] : []),
729
1120
  ...(input.invocationCap !== undefined ? [{ source: "invocation", value: input.invocationCap }] : [])
@@ -733,7 +1124,7 @@ function resolveOutputTokens(input) {
733
1124
  return { appliedCaps: [] };
734
1125
  }
735
1126
  const effective = Math.min(request ?? Number.POSITIVE_INFINITY, ...bounds.map(bound => bound.value));
736
- const ceiling = request ?? input.modelCapability;
1127
+ const ceiling = request ?? input.modelCapability ?? Number.POSITIVE_INFINITY;
737
1128
  const appliedCaps = bounds
738
1129
  .filter(bound => bound.value < ceiling)
739
1130
  .map(bound => ({
@@ -745,41 +1136,101 @@ function resolveOutputTokens(input) {
745
1136
  }));
746
1137
  return { ...(request !== undefined ? { requested: request } : {}), effective, appliedCaps };
747
1138
  }
1139
+ function elapsedSince(start) { return Math.max(0, Math.round(performance.now() - start)); }
1140
+ async function retryDelay(milliseconds, remaining, timeoutError, parent) {
1141
+ try {
1142
+ await withDeadline(signal => new Promise((resolve, reject) => {
1143
+ const expires = performance.now() + milliseconds;
1144
+ let timer;
1145
+ const cleanup = () => { if (timer)
1146
+ clearTimeout(timer); signal.removeEventListener("abort", abort); };
1147
+ const abort = () => { cleanup(); reject(parent?.aborted ? new CancellationError() : timeoutError()); };
1148
+ const schedule = () => {
1149
+ const left = expires - performance.now();
1150
+ if (left <= 0) {
1151
+ cleanup();
1152
+ resolve();
1153
+ }
1154
+ else
1155
+ timer = setTimeout(schedule, Math.min(Math.ceil(left), 2_147_483_647));
1156
+ };
1157
+ signal.addEventListener("abort", abort, { once: true });
1158
+ if (signal.aborted)
1159
+ abort();
1160
+ else
1161
+ schedule();
1162
+ }), remaining, timeoutError, parent);
1163
+ }
1164
+ catch (error) {
1165
+ if (parent?.aborted)
1166
+ throw new CancellationError();
1167
+ throw error;
1168
+ }
1169
+ }
1170
+ function generationEvidence(evidence, outcome, outputExposed) {
1171
+ const plan = evidence?.plan;
1172
+ return { clientStyle: "generate", mode: "final", outcome, outputExposed,
1173
+ features: structuredClone(plan?.features.features ?? []), ...(plan ? { adapterRoute: plan.adapterId,
1174
+ compatibleAdapterVersion: plan.compatibleAdapterVersion, implementation: { ...plan.implementation },
1175
+ ...(plan.protocol ? { protocol: plan.protocol } : {}) } : {}) };
1176
+ }
748
1177
  function buildReceipt(input) {
749
1178
  const { token, evidence } = input;
750
1179
  const plan = evidence?.plan;
751
- const effectiveBlock = evidence ? effectiveControls(token.profile, evidence) : undefined;
1180
+ const effectiveBlock = evidence ? effectiveControls(executionConfiguration(token), evidence) : undefined;
1181
+ const configuredModel = "directModel" in token ? input.snapshot.catalog.models.find(model => model.catalogId === token.directModel.catalogId) : undefined;
1182
+ const identity = "directModel" in token ? { schemaVersion: 1, kind: "direct-model-execution-receipt",
1183
+ receiptId: deriveDirectModelReceiptId({ applicationId: token.applicationId, catalogDigest: token.directModel.catalogDigest,
1184
+ modelConfigurationDigest: token.directModel.modelConfigurationDigest, runId: input.runId, requestId: input.requestId, operationId: input.operationId }),
1185
+ catalogId: token.directModel.catalogId, catalogDigest: token.directModel.catalogDigest, settingsDigest: token.directModel.settingsDigest,
1186
+ modelConfigurationDigest: token.directModel.modelConfigurationDigest,
1187
+ ...(token.directModel.priceRevisionId ? { priceRevisionId: token.directModel.priceRevisionId, priceDigest: token.directModel.priceDigest } : {}),
1188
+ provider: configuredModel.provider, providerModelId: configuredModel.providerModelId, adapterId: configuredModel.adapterId }
1189
+ : "model" in token && !("configurationId" in token.model) ? { schemaVersion: 5, kind: "profile-execution-receipt",
1190
+ receiptId: deriveProfileReceiptId({ applicationId: token.applicationId, profileSnapshotRevision: token.model.revision,
1191
+ bindingId: token.bindingId, runId: input.runId, requestId: input.requestId, operationId: input.operationId }),
1192
+ profileSnapshotRevision: token.model.revision, bindingId: token.bindingId }
1193
+ : "model" in token && "configurationId" in token.model ? { schemaVersion: 5, kind: "model-execution-receipt",
1194
+ receiptId: deriveModelReceiptId({ applicationId: token.applicationId, configurationId: token.model.configurationId,
1195
+ configurationRevision: token.model.revision, sourceConfigurationRevision: token.model.sourceRevision,
1196
+ ...(token.profileName === undefined ? { bindingId: token.bindingId } : { profileName: token.profileName }),
1197
+ runId: input.runId, requestId: input.requestId, operationId: input.operationId }),
1198
+ configurationId: token.model.configurationId, configurationRevision: token.model.revision,
1199
+ sourceConfigurationRevision: token.model.sourceRevision,
1200
+ ...(token.profileName === undefined ? { bindingId: token.bindingId } : { profileName: token.profileName }) }
1201
+ : "native" in token ? { schemaVersion: 4, kind: "native-execution-receipt",
1202
+ receiptId: deriveNativeReceiptId({ applicationId: token.applicationId, configurationId: token.native.configurationId,
1203
+ workspaceId: token.native.workspaceId, configurationRevision: token.native.revision, bindingId: token.personaId,
1204
+ runId: input.runId, requestId: input.requestId, operationId: input.operationId }),
1205
+ configurationId: token.native.configurationId, workspaceId: token.native.workspaceId,
1206
+ configurationRevision: token.native.revision, bindingId: token.personaId }
1207
+ : !("model" in token) && !("directModel" in token) ? { schemaVersion: 2, receiptId: deriveReceiptId({ applicationId: token.applicationId,
1208
+ environmentId: token.environmentId, runId: input.runId, requestId: input.requestId, operationId: input.operationId }),
1209
+ environmentId: token.environmentId, personaId: token.personaId, manifestRevision: token.manifestRevision,
1210
+ ...(token.scope ? { desktopConfigurationId: token.scope.desktopConfigurationId, workspaceId: token.scope.workspaceId } : {}) }
1211
+ : (() => { throw new ConfigurationInvalidError("Invalid execution identity."); })();
752
1212
  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
- }),
1213
+ ...identity,
1214
+ generation: structuredClone(input.attempts.at(-1)?.generation ?? generationEvidence(evidence, input.status === "succeeded" ? "completed" : "failed", input.status === "succeeded")),
761
1215
  runId: input.runId,
762
1216
  requestId: input.requestId,
763
1217
  applicationId: token.applicationId,
764
- environmentId: token.environmentId,
765
- ...(token.scope ? { desktopConfigurationId: token.scope.desktopConfigurationId, workspaceId: token.scope.workspaceId } : {}),
766
- personaId: token.personaId,
767
1218
  operationId: input.operationId,
768
1219
  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,
1220
+ instructionHash: "model" in token || "directModel" in token ? token.instructionHash : token.persona.instructionHash,
1221
+ ...(!("model" in token) && !("directModel" in token) && token.instructionProjection ?
1222
+ { effectiveInstructionHash: hashInstructions(token.instructionProjection.systemInstructions) } : {}),
1223
+ ...("directModel" in token ? {} : { profileId: token.profile.profileId, profileRevision: token.profile.revision }),
774
1224
  catalogRevision: input.snapshot.catalog.catalogRevision,
775
1225
  ...(plan ? { adapterId: plan.adapterId, adapterVersion: plan.adapterVersion, providerModelId: plan.model.providerModelId, provider: plan.model.provider } : {}),
776
1226
  requested: input.requested,
777
1227
  ...(effectiveBlock && Object.keys(effectiveBlock).length > 0 ? { effective: effectiveBlock } : {}),
778
1228
  attempts: structuredClone(input.attempts),
779
- ...(input.usage !== undefined ? { usage: input.usage } : {}),
1229
+ ...(input.skippedSlots.length ? { skippedSlots: structuredClone(input.skippedSlots) } : {}),
1230
+ ...((input.usage ?? input.attempts.at(-1)?.usage) !== undefined ? { usage: input.usage ?? input.attempts.at(-1).usage } : {}),
780
1231
  ...(input.cost ? { costEstimate: input.cost } : {}),
781
- latencyMs: Date.now() - input.startedAt,
782
- fallbackUsed: input.status === "succeeded"
1232
+ latencyMs: elapsedSince(input.startedAt),
1233
+ fallbackUsed: "directModel" in token ? false : input.status === "succeeded"
783
1234
  ? plan?.role === "fallback"
784
1235
  : input.attempts.some(attempt => attempt.role === "fallback"),
785
1236
  ...(input.error ? { error: input.error } : {}),