@techis/ai-runtime 0.3.0-rc.17 → 0.4.0-rc.5

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 +50 -35
  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 +6 -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 +12 -3
  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
@@ -0,0 +1,17 @@
1
+ import type { GenerationOutput } from "@techis/ai-contracts";
2
+ import type { AdapterResponse } from "./adapters/types.js";
3
+ import type { ChatCompletionResult, ChatFinishReason, CompatibilityReceipt, ResponsesOutputItem, ResponsesResult } from "./compatibility-types.js";
4
+ export interface ResultProjectionContext<R extends CompatibilityReceipt> {
5
+ /** Runtime identity used only when the provider supplies no response ID. */
6
+ id: string;
7
+ createdAt: number;
8
+ providerModelId: string;
9
+ executionReceipt: R;
10
+ }
11
+ export declare function projectResponsesItems(output: GenerationOutput, id: string): ResponsesOutputItem[];
12
+ export declare function projectResponsesResult<R extends CompatibilityReceipt>(output: GenerationOutput, context: ResultProjectionContext<R>): ResponsesResult<R>;
13
+ export declare function chatFinishReason(output: Pick<GenerationOutput, "status" | "incompleteReason">): ChatFinishReason;
14
+ export declare function projectChatResult<R extends CompatibilityReceipt>(output: GenerationOutput, context: ResultProjectionContext<R>): ChatCompletionResult<R>;
15
+ /** Bridge old execute-only adapters without claiming a provider-native payload they never supplied. */
16
+ export declare function generationFromAdapterResponse(response: AdapterResponse): GenerationOutput;
17
+ //# sourceMappingURL=result-mapping.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-mapping.d.ts","sourceRoot":"","sources":["../src/result-mapping.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAuB,gBAAgB,EAA8B,MAAM,sBAAsB,CAAC;AAC9G,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,KAAK,EAAE,oBAAoB,EAAE,gBAAgB,EAAgC,oBAAoB,EACtG,mBAAmB,EAAE,eAAe,EAAkB,MAAM,0BAA0B,CAAC;AAGzF,MAAM,WAAW,uBAAuB,CAAC,CAAC,SAAS,oBAAoB;IACrE,4EAA4E;IAC5E,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,EAAE,MAAM,CAAC;IACxB,gBAAgB,EAAE,CAAC,CAAC;CACrB;AA+BD,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,gBAAgB,EAAE,EAAE,EAAE,MAAM,GAAG,mBAAmB,EAAE,CAajG;AACD,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,oBAAoB,EAAE,MAAM,EAAE,gBAAgB,EAC7F,OAAO,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,CAMzD;AACD,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,IAAI,CAAC,gBAAgB,EAAE,QAAQ,GAAG,kBAAkB,CAAC,GAAG,gBAAgB,CAShH;AACD,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,oBAAoB,EAAE,MAAM,EAAE,gBAAgB,EACxF,OAAO,EAAE,uBAAuB,CAAC,CAAC,CAAC,GAAG,oBAAoB,CAAC,CAAC,CAAC,CAqB9D;AACD,uGAAuG;AACvG,wBAAgB,6BAA6B,CAAC,QAAQ,EAAE,eAAe,GAAG,gBAAgB,CAUzF"}
@@ -0,0 +1,123 @@
1
+ import { InvalidOutputError } from "./errors.js";
2
+ function defined(value) {
3
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
4
+ }
5
+ function argumentString(value) { return typeof value === "string" ? value : JSON.stringify(value); }
6
+ function responsesUsage(usage) {
7
+ if (!usage)
8
+ return undefined;
9
+ return defined({ input_tokens: usage.inputTokens, output_tokens: usage.outputTokens,
10
+ total_tokens: usage.inputTokens !== undefined && usage.outputTokens !== undefined ? usage.inputTokens + usage.outputTokens : undefined,
11
+ input_tokens_details: usage.cachedInputTokens === undefined && usage.cacheWriteInputTokens === undefined ? undefined
12
+ : defined({ cached_tokens: usage.cachedInputTokens, cache_write_tokens: usage.cacheWriteInputTokens }),
13
+ output_tokens_details: usage.reasoningTokens === undefined ? undefined : { reasoning_tokens: usage.reasoningTokens } });
14
+ }
15
+ function chatUsage(usage) {
16
+ const mapped = responsesUsage(usage);
17
+ return mapped ? defined({ prompt_tokens: mapped.input_tokens, completion_tokens: mapped.output_tokens, total_tokens: mapped.total_tokens,
18
+ prompt_tokens_details: mapped.input_tokens_details, completion_tokens_details: mapped.output_tokens_details }) : undefined;
19
+ }
20
+ function common(output, context) {
21
+ return defined({ outcome: output.status, items: structuredClone(output.items), native: structuredClone(output.native),
22
+ continuation: structuredClone(output.continuation), diagnostics: structuredClone(output.features ?? []),
23
+ runtime_usage: structuredClone(output.usage), incomplete_details: structuredClone(output.incompleteDetails ??
24
+ (output.incompleteReason === undefined ? undefined : { reason: output.incompleteReason })),
25
+ error: structuredClone(output.error), executionReceipt: structuredClone(context.executionReceipt) });
26
+ }
27
+ function outputContent(block) {
28
+ if (block.type === "text")
29
+ return { type: "output_text", text: block.text, annotations: structuredClone(block.annotations ?? []) };
30
+ if (block.type === "refusal")
31
+ return { type: "refusal", refusal: block.refusal };
32
+ // Images/opaque provider blocks remain ordered and available without pretending they are generated text.
33
+ return { type: "runtime.native", value: structuredClone(block) };
34
+ }
35
+ export function projectResponsesItems(output, id) {
36
+ const status = output.status === "incomplete" ? "incomplete" : "completed";
37
+ return output.items.map((item, index) => {
38
+ if (item.type === "native")
39
+ return { type: "runtime.native", provider: item.provider, value: structuredClone(item.value) };
40
+ if (item.type === "function_call")
41
+ return defined({ type: "function_call", id: item.id ?? id + "_item_" + index,
42
+ call_id: item.callId, name: item.name, arguments: argumentString(item.arguments), status: item.status ?? status,
43
+ native: structuredClone(item.native) });
44
+ if (item.type === "function_result")
45
+ return { type: "function_call_output", call_id: item.callId, output: structuredClone(item.output) };
46
+ const content = (item.content ?? []).map(outputContent);
47
+ if (item.refusal !== undefined && item.refusal !== null)
48
+ content.push({ type: "refusal", refusal: item.refusal });
49
+ return defined({ type: "message", id: item.id ?? id + "_item_" + index, role: "assistant", status: item.status ?? status, content,
50
+ annotations: structuredClone(item.annotations), native: structuredClone(item.native) });
51
+ });
52
+ }
53
+ export function projectResponsesResult(output, context) {
54
+ const id = output.id ?? context.id, status = output.status === "incomplete" ? "incomplete" : "completed";
55
+ const items = projectResponsesItems(output, id);
56
+ return defined({ ...common(output, context), id, object: "response", created_at: output.createdAt ?? context.createdAt,
57
+ model: output.providerModelId ?? context.providerModelId,
58
+ status: output.status === "failed" ? "failed" : status, output: items, output_text: output.text, usage: responsesUsage(output.usage) });
59
+ }
60
+ export function chatFinishReason(output) {
61
+ if (output.status === "failed")
62
+ return null;
63
+ if (output.status === "requires_action")
64
+ return "tool_calls";
65
+ if (output.status === "incomplete") {
66
+ if (["max_output_tokens", "max_tokens", "length"].includes(output.incompleteReason ?? ""))
67
+ return "length";
68
+ if (output.incompleteReason === "content_filter")
69
+ return "content_filter";
70
+ return null;
71
+ }
72
+ return "stop";
73
+ }
74
+ export function projectChatResult(output, context) {
75
+ const toolCalls = [], annotations = [], refusals = [];
76
+ let nullableRefusal = false, hasText = false;
77
+ for (const item of output.items) {
78
+ if (item.type === "function_call")
79
+ toolCalls.push({ type: "function", id: item.callId,
80
+ function: { name: item.name, arguments: argumentString(item.arguments) } });
81
+ if (item.type !== "message")
82
+ continue;
83
+ annotations.push(...structuredClone(item.annotations ?? []));
84
+ if (item.refusal === null)
85
+ nullableRefusal = true;
86
+ else if (item.refusal !== undefined)
87
+ refusals.push(item.refusal);
88
+ for (const block of item.content ?? []) {
89
+ if (block.type === "text") {
90
+ hasText = true;
91
+ annotations.push(...structuredClone(block.annotations ?? []));
92
+ }
93
+ else if (block.type === "refusal")
94
+ refusals.push(block.refusal);
95
+ }
96
+ }
97
+ const message = defined({ role: "assistant", content: hasText || output.text !== "" ? output.text : null,
98
+ refusal: refusals.length ? refusals.join("\n") : nullableRefusal ? null : undefined,
99
+ annotations: annotations.length ? annotations : undefined, tool_calls: toolCalls.length ? toolCalls : undefined });
100
+ return defined({ ...common(output, context), id: output.id ?? context.id, object: "chat.completion",
101
+ created: output.createdAt ?? context.createdAt, model: output.providerModelId ?? context.providerModelId,
102
+ choices: [{ index: 0, message, finish_reason: chatFinishReason(output) }], usage: chatUsage(output.usage) });
103
+ }
104
+ /** Bridge old execute-only adapters without claiming a provider-native payload they never supplied. */
105
+ export function generationFromAdapterResponse(response) {
106
+ if (response.generation)
107
+ return structuredClone(response.generation);
108
+ if (response.output.kind === "refusal")
109
+ return { status: "refused", text: "", usage: structuredClone(response.usage),
110
+ items: [{ type: "message", role: "assistant", content: [{ type: "refusal", refusal: response.output.message }] }] };
111
+ let text;
112
+ try {
113
+ text = response.output.kind === "text" ? response.output.text : JSON.stringify(response.output.value);
114
+ }
115
+ catch {
116
+ throw new InvalidOutputError("Legacy adapter returned non-JSON structured output");
117
+ }
118
+ if (typeof text !== "string")
119
+ throw new InvalidOutputError("Legacy adapter returned no serializable output");
120
+ return { status: "completed", text, usage: structuredClone(response.usage),
121
+ items: [{ type: "message", role: "assistant", content: [{ type: "text", text }] }] };
122
+ }
123
+ //# sourceMappingURL=result-mapping.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-mapping.js","sourceRoot":"","sources":["../src/result-mapping.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AASjD,SAAS,OAAO,CAAmB,KAAQ;IACzC,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,KAAK,SAAS,CAAC,CAAM,CAAC;AACjG,CAAC;AACD,SAAS,cAAc,CAAC,KAAsB,IAAY,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC7H,SAAS,cAAc,CAAC,KAAkC;IACxD,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,CAAC,WAAW,EAAE,aAAa,EAAE,KAAK,CAA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zF,CAAC"}
@@ -0,0 +1,22 @@
1
+ import { type ApplicationRouteAdoption } from "@techis/ai-contracts";
2
+ import { ApplicationRouteAdoptionRepository, type RouteAdoptionState, type RouteAdoptionStorage } from "./route-adoption.js";
3
+ /** Atomic immutable selection commits provide CAS without orphaned process locks or partially visible pointer files. */
4
+ export declare class NodeFileRouteAdoptionStorage implements RouteAdoptionStorage {
5
+ readonly directory: string;
6
+ constructor(directory: string);
7
+ private prepare;
8
+ private path;
9
+ private read;
10
+ private create;
11
+ private selection;
12
+ readState(): Promise<RouteAdoptionState | null>;
13
+ commitState(state: RouteAdoptionState, expectedVersion: number): Promise<void>;
14
+ readContent(digest: string): Promise<any>;
15
+ writeContent(digest: string, content: ApplicationRouteAdoption): Promise<void>;
16
+ }
17
+ export declare function createFileRouteAdoptionRepository(options: {
18
+ directory: string;
19
+ applicationId: string;
20
+ now?: () => Date;
21
+ }): ApplicationRouteAdoptionRepository;
22
+ //# sourceMappingURL=route-adoption-node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-adoption-node.d.ts","sourceRoot":"","sources":["../src/route-adoption-node.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,KAAK,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,kCAAkC,EAAE,KAAK,kBAAkB,EAAE,KAAK,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAc7H,wHAAwH;AACxH,qBAAa,4BAA6B,YAAW,oBAAoB;IACvE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;gBACf,SAAS,EAAE,MAAM;YACf,OAAO;IAYrB,OAAO,CAAC,IAAI;YAKE,IAAI;YAaJ,MAAM;YAaN,SAAS;IAgBjB,SAAS,IAAI,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAC/C,WAAW,CAAC,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM;IAS9D,WAAW,CAAC,MAAM,EAAE,MAAM;IAC1B,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,wBAAwB;CAKrE;AACD,wBAAgB,iCAAiC,CAAC,OAAO,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,IAAI,CAAA;CAAE,sCAExH"}
@@ -0,0 +1,134 @@
1
+ import { lstat, mkdir, readdir, open, link, unlink } from "node:fs/promises";
2
+ import { dirname, join, resolve, parse } from "node:path";
3
+ import { constants } from "node:fs";
4
+ import { randomUUID } from "node:crypto";
5
+ import { hashDocumentV2, adoptionRecordDigest, assertAdoptionDigest, validateApplicationRouteAdoption, RouteAdoptionError } from "@techis/ai-contracts";
6
+ import { ApplicationRouteAdoptionRepository } from "./route-adoption.js";
7
+ function assertState(value) {
8
+ const state = value;
9
+ if (!state || Object.keys(state).some(key => !["version", "activeGeneration", "imports"].includes(key)) ||
10
+ !Number.isSafeInteger(state.version) || state.version < 1 || !Array.isArray(state.imports) || state.imports.length > 1000 ||
11
+ new Set(state.imports.map(item => item.generation)).size !== state.imports.length || state.imports.some(item => !Number.isSafeInteger(item.generation) || item.generation < 1 || !/^[a-f0-9]{64}$/.test(item.contentDigest) ||
12
+ !/^[a-f0-9]{64}$/.test(item.identityDigest) || item.qualification && (!/^[a-f0-9]{64}$/.test(item.qualification.reportDigest) ||
13
+ !Number.isFinite(Date.parse(item.qualification.qualifiedAt)))) ||
14
+ state.activeGeneration !== null && !state.imports.some(item => item.generation === state.activeGeneration && item.qualification))
15
+ throw new RouteAdoptionError("dependency-invalid", "Invalid application selection history.");
16
+ }
17
+ /** Atomic immutable selection commits provide CAS without orphaned process locks or partially visible pointer files. */
18
+ export class NodeFileRouteAdoptionStorage {
19
+ directory;
20
+ constructor(directory) { this.directory = resolve(directory); }
21
+ async prepare(create = true) {
22
+ const check = async () => {
23
+ let path = this.directory;
24
+ for (;;) {
25
+ const stat = await lstat(path).catch(error => { if (error.code === "ENOENT")
26
+ return null; throw error; });
27
+ if (stat?.isSymbolicLink() || stat && !stat.isDirectory())
28
+ throw new RouteAdoptionError("dependency-invalid", "Application import directories cannot contain links or non-directories.");
29
+ if (path === parse(path).root)
30
+ break;
31
+ path = dirname(path);
32
+ }
33
+ };
34
+ await check();
35
+ if (create)
36
+ await mkdir(this.directory, { recursive: true });
37
+ await check();
38
+ }
39
+ path(name) {
40
+ if (!/^(?:content-[a-f0-9]{64}|selection-\d{10})\.json$/.test(name))
41
+ throw new RouteAdoptionError("dependency-invalid", "Invalid application import filename.");
42
+ return join(this.directory, name);
43
+ }
44
+ async read(name) {
45
+ await this.prepare(false);
46
+ const path = this.path(name), before = await lstat(path);
47
+ if (before.isSymbolicLink() || !before.isFile())
48
+ throw new RouteAdoptionError("dependency-invalid", "Application import files cannot be links.");
49
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
50
+ try {
51
+ const stat = await handle.stat();
52
+ if (!stat.isFile() || stat.size > 16_000_000 || stat.ino !== before.ino)
53
+ throw new RouteAdoptionError("dependency-invalid", "Application import file changed or exceeds its size limit.");
54
+ const content = await handle.readFile("utf8");
55
+ if (Buffer.byteLength(content) > 16_000_000)
56
+ throw new RouteAdoptionError("dependency-invalid", "Application import exceeds its size limit.");
57
+ return JSON.parse(content);
58
+ }
59
+ finally {
60
+ await handle.close();
61
+ }
62
+ }
63
+ async create(name, value) {
64
+ await this.prepare();
65
+ const target = this.path(name), temporary = join(this.directory, ".adoption-" + randomUUID() + ".tmp");
66
+ const bytes = JSON.stringify(value) + "\n";
67
+ if (Buffer.byteLength(bytes) > 16_000_000)
68
+ throw new RouteAdoptionError("dependency-invalid", "Application import exceeds its size limit.");
69
+ const handle = await open(temporary, "wx", 0o600);
70
+ try {
71
+ await handle.writeFile(bytes);
72
+ await handle.sync();
73
+ }
74
+ finally {
75
+ await handle.close();
76
+ }
77
+ try {
78
+ await link(temporary, target);
79
+ }
80
+ catch (error) {
81
+ if (error.code !== "EEXIST")
82
+ throw error;
83
+ if (hashDocumentV2(await this.read(name)) !== hashDocumentV2(value))
84
+ throw new RouteAdoptionError("adoption-conflict", "Another process committed different application state.");
85
+ }
86
+ finally {
87
+ await unlink(temporary).catch(() => undefined);
88
+ }
89
+ }
90
+ async selection() {
91
+ await this.prepare(false);
92
+ const entries = await readdir(this.directory).catch(error => { if (error.code === "ENOENT")
93
+ return []; throw error; });
94
+ const names = entries.filter(name => /^selection-\d{10}\.json$/.test(name)).sort();
95
+ if (names.length > 100_000)
96
+ throw new RouteAdoptionError("dependency-invalid", "Application selection history exceeds its limit.");
97
+ let last = null;
98
+ for (const [index, name] of names.entries()) {
99
+ if (name !== `selection-${String(index + 1).padStart(10, "0")}.json`)
100
+ throw new RouteAdoptionError("dependency-invalid", "Application selection history has a gap.");
101
+ const commit = await this.read(name);
102
+ assertAdoptionDigest(commit);
103
+ assertState(commit.state);
104
+ if (commit.version !== index + 1 || commit.state.version !== commit.version || commit.previousDigest !== (last?.contentDigest ?? null))
105
+ throw new RouteAdoptionError("dependency-invalid", "Application selection chain integrity failed.");
106
+ last = commit;
107
+ }
108
+ return last;
109
+ }
110
+ async readState() { return structuredClone((await this.selection())?.state ?? null); }
111
+ async commitState(state, expectedVersion) {
112
+ assertState(state);
113
+ const current = await this.selection();
114
+ if (current?.version === state.version && hashDocumentV2(current.state) === hashDocumentV2(state))
115
+ return;
116
+ if ((current?.version ?? 0) !== expectedVersion || state.version !== expectedVersion + 1)
117
+ throw new RouteAdoptionError("adoption-conflict", "Application selection changed concurrently.");
118
+ const commit = { version: state.version, previousDigest: current?.contentDigest ?? null,
119
+ state, contentDigest: "" };
120
+ commit.contentDigest = adoptionRecordDigest(commit);
121
+ await this.create(`selection-${String(state.version).padStart(10, "0")}.json`, commit);
122
+ }
123
+ async readContent(digest) { return this.read("content-" + digest + ".json"); }
124
+ async writeContent(digest, content) {
125
+ validateApplicationRouteAdoption(content);
126
+ if (content.contentDigest !== digest)
127
+ throw new RouteAdoptionError("dependency-invalid", "Application content filename digest mismatch.");
128
+ await this.create("content-" + digest + ".json", content);
129
+ }
130
+ }
131
+ export function createFileRouteAdoptionRepository(options) {
132
+ return new ApplicationRouteAdoptionRepository(new NodeFileRouteAdoptionStorage(options.directory), options);
133
+ }
134
+ //# sourceMappingURL=route-adoption-node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-adoption-node.js","sourceRoot":"","sources":["../src/route-adoption-node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,gCAAgC,EAAE,kBAAkB,EACxF,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,kCAAkC,EAAsD,MAAM,qBAAqB,CAAC;AAE7H,SAAS,WAAW,CAAC,KAAc;IACjC,MAAM,KAAK,GAAG,KAA2B,CAAC;IAC1C,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,kBAAkB,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QACnG,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,CAAC,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,IAAI;QACzH,IAAI,GAAG,CAA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AAC;AAC9G,CAAC"}
@@ -0,0 +1,100 @@
1
+ import { type ApplicationRouteAdoption, type RouteImportResult, type RouteImportProposal, type RouteSourceDescriptor, type ExecutionRequirements } from "@techis/ai-contracts";
2
+ export interface RouteAdoptionEntry {
3
+ generation: number;
4
+ contentDigest: string;
5
+ identityDigest: string;
6
+ qualification?: {
7
+ reportDigest: string;
8
+ qualifiedAt: string;
9
+ };
10
+ }
11
+ export interface RouteAdoptionState {
12
+ version: number;
13
+ activeGeneration: number | null;
14
+ imports: RouteAdoptionEntry[];
15
+ }
16
+ /** Host-owned persistence port. commitState is a single atomic CAS; content is immutable and never activates itself. */
17
+ export interface RouteAdoptionStorage {
18
+ readState(): Promise<RouteAdoptionState | null>;
19
+ commitState(state: RouteAdoptionState, expectedVersion: number): Promise<void>;
20
+ readContent(digest: string): Promise<unknown>;
21
+ writeContent(digest: string, content: ApplicationRouteAdoption): Promise<void>;
22
+ }
23
+ export interface RouteAdoptionImport {
24
+ result: RouteImportResult;
25
+ expectedSource: RouteSourceDescriptor;
26
+ expectedResultDigest: string;
27
+ assignments: Record<string, string>;
28
+ requirements: Record<string, ExecutionRequirements>;
29
+ updatePolicy?: ApplicationRouteAdoption["updatePolicy"];
30
+ offlinePolicy?: ApplicationRouteAdoption["offlinePolicy"];
31
+ instructionReferences?: ApplicationRouteAdoption["instructionReferences"];
32
+ }
33
+ export declare function resolveRouteImportAssignments(proposalValue: RouteImportProposal, resultValue: RouteImportResult, acceptedProposalHash: string): {
34
+ assignments: {
35
+ [k: string]: string;
36
+ };
37
+ requirements: {
38
+ [k: string]: import("@techis/ai-contracts").GenerationFeaturePolicy;
39
+ };
40
+ };
41
+ export declare function compareRouteAdoptions(previous: ApplicationRouteAdoption | null, next: ApplicationRouteAdoption): {
42
+ sourceChanged: boolean;
43
+ routeSetChanged: boolean;
44
+ routes: {
45
+ routeId: string;
46
+ previousRevision: string | null;
47
+ revision: string | null;
48
+ change: string;
49
+ }[];
50
+ assignmentsChanged: boolean;
51
+ };
52
+ export declare class ApplicationRouteAdoptionRepository {
53
+ private storage;
54
+ private options;
55
+ constructor(storage: RouteAdoptionStorage, options: {
56
+ applicationId: string;
57
+ now?: () => Date;
58
+ });
59
+ private state;
60
+ private record;
61
+ readActive(): Promise<ApplicationRouteAdoption | null>;
62
+ listHistory(): Promise<{
63
+ adoption: ApplicationRouteAdoption;
64
+ qualification: {
65
+ reportDigest: string;
66
+ qualifiedAt: string;
67
+ } | undefined;
68
+ state: "enabled" | "qualified" | "imported";
69
+ }[]>;
70
+ private candidate;
71
+ private assertImmutableIdentity;
72
+ previewImport(input: RouteAdoptionImport): Promise<{
73
+ candidate: ApplicationRouteAdoption;
74
+ expectedActiveGeneration: number | null;
75
+ comparison: {
76
+ sourceChanged: boolean;
77
+ routeSetChanged: boolean;
78
+ routes: {
79
+ routeId: string;
80
+ previousRevision: string | null;
81
+ revision: string | null;
82
+ change: string;
83
+ }[];
84
+ assignmentsChanged: boolean;
85
+ };
86
+ }>;
87
+ storeImport(input: RouteAdoptionImport): Promise<ApplicationRouteAdoption>;
88
+ recordQualification(generation: number, reportDigest: string): Promise<void>;
89
+ activateImport(generation: number, expectedActiveGeneration: number | null, options?: {
90
+ allowSourceChange?: boolean;
91
+ }): Promise<ApplicationRouteAdoption>;
92
+ rollback(generation: number, expectedActiveGeneration: number, options?: {
93
+ allowSourceChange?: boolean;
94
+ }): Promise<ApplicationRouteAdoption>;
95
+ readForWorkflow(input: {
96
+ source: RouteSourceDescriptor;
97
+ retrievalError?: "source-unavailable" | "access-denied";
98
+ }): Promise<ApplicationRouteAdoption>;
99
+ }
100
+ //# sourceMappingURL=route-adoption.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-adoption.d.ts","sourceRoot":"","sources":["../src/route-adoption.ts"],"names":[],"mappings":"AAAA,OAAO,EAC2D,KAAK,wBAAwB,EAAE,KAAK,iBAAiB,EACrH,KAAK,mBAAmB,EAAE,KAAK,qBAAqB,EAAE,KAAK,qBAAqB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outeImportProposal, toLegacyRouteSetSnapshot, modelProfileRefs, RouteAdoptionError } from "@techis/ai-contracts";
2
+ export function resolveRouteImportAssignments(proposalValue, resultValue, acceptedProposalHash) {
3
+ const proposal = validateRouteImportProposal(proposalValue), result = validateRouteImportResult(resultValue, { source: proposal.authoring.source, authoring: proposal.authoring });
4
+ if (proposal.proposalHash !== acceptedProposalHash || proposal.authoring.authoringHash !== result.authoringHash ||
5
+ proposal.authoring.importId !== result.importId)
6
+ throw new RouteAdoptionError("proposal-mismatch", "Return data does not belong to the accepted local proposal.");
7
+ return { assignments: Object.fromEntries(Object.entries(proposal.assignments).map(([key, candidate]) => {
8
+ if (!Object.hasOwn(result.candidateRouteIds, candidate))
9
+ throw new RouteAdoptionError("identity-conflict", "Missing authoritative candidate identity.");
10
+ return [key, result.candidateRouteIds[candidate]];
11
+ })), requirements: Object.fromEntries(Object.entries(proposal.assignments).map(([key, candidate]) => [key, proposal.candidates.find(item => item.candidateKey === candidate).requirements])) };
12
+ }
13
+ export function compareRouteAdoptions(previous, next) {
14
+ const before = previous ? modelProfileRefs(toLegacyRouteSetSnapshot(previous.configuration).revision.content) : [];
15
+ const after = modelProfileRefs(toLegacyRouteSetSnapshot(next.configuration).revision.content);
16
+ return { sourceChanged: !!previous && hashDocumentV2(previous.source) !== hashDocumentV2(next.source),
17
+ routeSetChanged: !!previous && previous.routeSetId !== next.routeSetId,
18
+ routes: [...new Set([...before.map(ref => ref.id), ...after.map(ref => ref.id)])].sort().map(routeId => {
19
+ const old = before.find(ref => ref.id === routeId), current = after.find(ref => ref.id === routeId);
20
+ return { routeId, previousRevision: old?.revision ?? null, revision: current?.revision ?? null,
21
+ change: !old ? "added" : !current ? "removed" : hashDocumentV2(old) === hashDocumentV2(current) ? "unchanged" : "changed" };
22
+ }), assignmentsChanged: hashDocumentV2(previous?.assignments ?? {}) !== hashDocumentV2(next.assignments) };
23
+ }
24
+ export class ApplicationRouteAdoptionRepository {
25
+ storage;
26
+ options;
27
+ constructor(storage, options) {
28
+ this.storage = storage;
29
+ this.options = options;
30
+ if (!/^[a-z0-9][a-z0-9._-]{0,99}$/.test(options.applicationId))
31
+ throw Error("Valid application identity required.");
32
+ }
33
+ async state() { return await this.storage.readState() ?? { version: 0, activeGeneration: null, imports: [] }; }
34
+ async record(entry) {
35
+ const record = validateApplicationRouteAdoption(await this.storage.readContent(entry.contentDigest));
36
+ if (record.applicationId !== this.options.applicationId || record.contentDigest !== entry.contentDigest || record.generation !== entry.generation)
37
+ throw new RouteAdoptionError("identity-conflict", "Application adoption identity does not match committed history.");
38
+ return record;
39
+ }
40
+ async readActive() {
41
+ const state = await this.state();
42
+ if (state.activeGeneration === null)
43
+ return null;
44
+ const entry = state.imports.find(entry => entry.generation === state.activeGeneration);
45
+ if (!entry)
46
+ throw new RouteAdoptionError("import-incomplete", "Active selection has no complete import.");
47
+ return this.record(entry);
48
+ }
49
+ async listHistory() {
50
+ const state = await this.state();
51
+ return Promise.all(state.imports.map(async (entry) => ({ adoption: await this.record(entry), qualification: entry.qualification,
52
+ state: state.activeGeneration === entry.generation ? "enabled" : entry.qualification ? "qualified" : "imported" })));
53
+ }
54
+ candidate(input, generation, priorGeneration) {
55
+ const result = validateRouteImportResult(input.result, { source: input.expectedSource, contentDigest: input.expectedResultDigest });
56
+ const candidate = { schemaVersion: 1, kind: "application-route-adoption", applicationId: this.options.applicationId,
57
+ generation, priorGeneration, source: result.source, importResultDigest: result.contentDigest, routeSetId: result.routeSet.routeSetId,
58
+ configuration: result.snapshot, assignments: structuredClone(input.assignments), requirements: structuredClone(input.requirements),
59
+ updatePolicy: input.updatePolicy ?? "explicit", offlinePolicy: input.offlinePolicy ?? { mode: "deny", maxAgeMs: 0, allowProtectedDenial: false },
60
+ ...(input.instructionReferences ? { instructionReferences: structuredClone(input.instructionReferences) } : {}),
61
+ importedAt: (this.options.now ?? (() => new Date()))().toISOString(), contentDigest: "" };
62
+ candidate.contentDigest = adoptionRecordDigest(candidate);
63
+ return validateApplicationRouteAdoption(candidate);
64
+ }
65
+ async assertImmutableIdentity(candidate, state) {
66
+ const snapshot = toLegacyRouteSetSnapshot(candidate.configuration), refs = modelProfileRefs(snapshot.revision.content);
67
+ for (const entry of state.imports) {
68
+ const previous = await this.record(entry);
69
+ if (hashDocumentV2(previous.source) !== hashDocumentV2(candidate.source))
70
+ continue;
71
+ const old = toLegacyRouteSetSnapshot(previous.configuration);
72
+ const beforeCatalog = old.documents[old.revision.content.catalog.sha256];
73
+ const afterCatalog = snapshot.documents[snapshot.revision.content.catalog.sha256];
74
+ if (beforeCatalog.catalogRevision === afterCatalog.catalogRevision) {
75
+ for (const model of beforeCatalog.models) {
76
+ const current = afterCatalog.models.find(item => item.catalogId === model.catalogId);
77
+ if (current && hashDocumentV2(current) !== hashDocumentV2(model))
78
+ throw new RouteAdoptionError("identity-conflict", "A model in an exact catalog revision has conflicting imported bytes.");
79
+ }
80
+ for (const price of beforeCatalog.prices) {
81
+ const current = afterCatalog.prices.find(item => item.priceRevisionId === price.priceRevisionId);
82
+ if (current && hashDocumentV2(current) !== hashDocumentV2(price))
83
+ throw new RouteAdoptionError("identity-conflict", "A price in an exact catalog revision has conflicting imported bytes.");
84
+ }
85
+ for (const [provider, mapping] of Object.entries(beforeCatalog.runtimeMappings ?? {})) {
86
+ const current = afterCatalog.runtimeMappings?.[provider];
87
+ if (current && hashDocumentV2(current) !== hashDocumentV2(mapping))
88
+ throw new RouteAdoptionError("identity-conflict", "An exact catalog runtime mapping has conflicting imported bytes.");
89
+ }
90
+ }
91
+ for (const ref of modelProfileRefs(old.revision.content)) {
92
+ if (refs.some(current => current.id === ref.id && current.revision === ref.revision && current.sha256 !== ref.sha256))
93
+ throw new RouteAdoptionError("identity-conflict", "An exact Route identity has conflicting imported bytes.");
94
+ }
95
+ if (previous.routeSetId === candidate.routeSetId && (old.sourceRevision ?? old.revision).revision ===
96
+ (snapshot.sourceRevision ?? snapshot.revision).revision &&
97
+ hashDocumentV2(old.sourceRevision ?? old.revision) !== hashDocumentV2(snapshot.sourceRevision ?? snapshot.revision))
98
+ throw new RouteAdoptionError("identity-conflict", "An exact Route-set save has conflicting imported content.");
99
+ }
100
+ }
101
+ async previewImport(input) {
102
+ const state = await this.state(), generation = Math.max(0, ...state.imports.map(entry => entry.generation)) + 1;
103
+ const candidate = this.candidate(input, generation, state.activeGeneration);
104
+ await this.assertImmutableIdentity(candidate, state);
105
+ return { candidate, expectedActiveGeneration: state.activeGeneration, comparison: compareRouteAdoptions(await this.readActive(), candidate) };
106
+ }
107
+ async storeImport(input) {
108
+ const identityDigest = hashDocumentV2({ result: input.expectedResultDigest, source: input.expectedSource, assignments: input.assignments,
109
+ requirements: input.requirements, updatePolicy: input.updatePolicy ?? "explicit", offlinePolicy: input.offlinePolicy ??
110
+ { mode: "deny", maxAgeMs: 0, allowProtectedDenial: false }, instructionReferences: input.instructionReferences });
111
+ for (let attempt = 0; attempt < 32; attempt++) {
112
+ const state = await this.state();
113
+ // Validate even a repeated import before returning a stored generation.
114
+ const candidate = this.candidate(input, Math.max(0, ...state.imports.map(entry => entry.generation)) + 1, state.activeGeneration);
115
+ const prior = state.imports.find(entry => entry.identityDigest === identityDigest);
116
+ if (prior)
117
+ return this.record(prior);
118
+ await this.assertImmutableIdentity(candidate, state);
119
+ await this.storage.writeContent(candidate.contentDigest, candidate);
120
+ try {
121
+ await this.storage.commitState({ ...state, version: state.version + 1, imports: [...state.imports,
122
+ { generation: candidate.generation, contentDigest: candidate.contentDigest, identityDigest }] }, state.version);
123
+ return candidate;
124
+ }
125
+ catch (error) {
126
+ if (!(error instanceof RouteAdoptionError) || error.code !== "adoption-conflict")
127
+ throw error;
128
+ }
129
+ }
130
+ throw new RouteAdoptionError("adoption-conflict", "Concurrent imports remain busy; compare and retry.");
131
+ }
132
+ async recordQualification(generation, reportDigest) {
133
+ if (!/^[a-f0-9]{64}$/.test(reportDigest))
134
+ throw Error("Pinned qualification report digest required.");
135
+ const state = await this.state(), entry = state.imports.find(item => item.generation === generation);
136
+ if (!entry)
137
+ throw new RouteAdoptionError("import-incomplete", "Import generation not found.");
138
+ await this.record(entry);
139
+ if (entry.qualification?.reportDigest === reportDigest)
140
+ return;
141
+ const imports = state.imports.map(item => item === entry ? { ...item, qualification: { reportDigest,
142
+ qualifiedAt: (this.options.now ?? (() => new Date()))().toISOString() } } : item);
143
+ await this.storage.commitState({ ...state, version: state.version + 1, imports }, state.version);
144
+ }
145
+ async activateImport(generation, expectedActiveGeneration, options = {}) {
146
+ const state = await this.state(), entry = state.imports.find(item => item.generation === generation);
147
+ if (!entry?.qualification)
148
+ throw new RouteAdoptionError("import-incomplete", "Record host qualification before enabling this import.");
149
+ const record = await this.record(entry);
150
+ if (state.activeGeneration === generation)
151
+ return record;
152
+ if (state.activeGeneration !== expectedActiveGeneration)
153
+ throw new RouteAdoptionError("adoption-conflict", "Active generation changed; compare before enabling.");
154
+ const active = await this.readActive();
155
+ if (active && !options.allowSourceChange && hashDocumentV2(active.source) !== hashDocumentV2(record.source))
156
+ throw new RouteAdoptionError("adoption-conflict", "Enabling a different source requires an explicit source change.");
157
+ await this.storage.commitState({ ...state, version: state.version + 1, activeGeneration: generation }, state.version);
158
+ return record;
159
+ }
160
+ rollback(generation, expectedActiveGeneration, options = {}) {
161
+ return this.activateImport(generation, expectedActiveGeneration, options);
162
+ }
163
+ async readForWorkflow(input) {
164
+ const active = await this.readActive();
165
+ if (!active || hashDocumentV2(active.source) !== hashDocumentV2(input.source))
166
+ throw new RouteAdoptionError("source-unavailable", "No adoption is active for the selected source.");
167
+ if (input.retrievalError) {
168
+ const policy = active.offlinePolicy, age = (this.options.now ?? (() => new Date()))().getTime() - Date.parse(active.importedAt);
169
+ if (policy.mode !== "last-adopted" || age < 0 || age > policy.maxAgeMs ||
170
+ input.retrievalError === "access-denied" && (active.source.kind === "protected" || !policy.allowProtectedDenial))
171
+ throw new RouteAdoptionError(input.retrievalError, "Selected source policy blocks a new offline workflow.");
172
+ }
173
+ return active;
174
+ }
175
+ }
176
+ //# sourceMappingURL=route-adoption.js.map