modelrig 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (310) hide show
  1. package/CHANGELOG.md +158 -0
  2. package/README.md +53 -11
  3. package/data/PROVENANCE.md +19 -0
  4. package/data/pricing-manual.json +22 -0
  5. package/data/pricing-map.json +46362 -0
  6. package/data/pricing-overlay.json +419 -0
  7. package/dist/adapters/anthropic.d.ts +50 -6
  8. package/dist/adapters/anthropic.d.ts.map +1 -1
  9. package/dist/adapters/anthropic.js +123 -29
  10. package/dist/adapters/build-adapters.d.ts +11 -0
  11. package/dist/adapters/build-adapters.d.ts.map +1 -0
  12. package/dist/adapters/build-adapters.js +45 -0
  13. package/dist/adapters/deepseek.d.ts +6 -0
  14. package/dist/adapters/deepseek.d.ts.map +1 -1
  15. package/dist/adapters/deepseek.js +54 -1
  16. package/dist/adapters/gemini.d.ts +10 -0
  17. package/dist/adapters/gemini.d.ts.map +1 -1
  18. package/dist/adapters/gemini.js +78 -7
  19. package/dist/adapters/grok.d.ts +9 -0
  20. package/dist/adapters/grok.d.ts.map +1 -1
  21. package/dist/adapters/grok.js +67 -3
  22. package/dist/adapters/openai-compat.d.ts +6 -0
  23. package/dist/adapters/openai-compat.d.ts.map +1 -1
  24. package/dist/adapters/openai-compat.js +58 -1
  25. package/dist/adapters/openai-stream.d.ts +58 -0
  26. package/dist/adapters/openai-stream.d.ts.map +1 -0
  27. package/dist/adapters/openai-stream.js +120 -0
  28. package/dist/adapters/openai.d.ts +6 -0
  29. package/dist/adapters/openai.d.ts.map +1 -1
  30. package/dist/adapters/openai.js +60 -1
  31. package/dist/adapters/sampling.d.ts +28 -0
  32. package/dist/adapters/sampling.d.ts.map +1 -0
  33. package/dist/adapters/sampling.js +34 -0
  34. package/dist/adapters/tool-mapping.d.ts +92 -0
  35. package/dist/adapters/tool-mapping.d.ts.map +1 -0
  36. package/dist/adapters/tool-mapping.js +143 -0
  37. package/dist/artifacts/artifact.d.ts +137 -0
  38. package/dist/artifacts/artifact.d.ts.map +1 -0
  39. package/dist/artifacts/artifact.js +377 -0
  40. package/dist/artifacts/content-uploader.d.ts +87 -0
  41. package/dist/artifacts/content-uploader.d.ts.map +1 -0
  42. package/dist/artifacts/content-uploader.js +124 -0
  43. package/dist/artifacts/index.d.ts +63 -0
  44. package/dist/artifacts/index.d.ts.map +1 -0
  45. package/dist/artifacts/index.js +80 -0
  46. package/dist/artifacts/run-context.d.ts +129 -0
  47. package/dist/artifacts/run-context.d.ts.map +1 -0
  48. package/dist/artifacts/run-context.js +208 -0
  49. package/dist/artifacts/scrub.d.ts +60 -0
  50. package/dist/artifacts/scrub.d.ts.map +1 -0
  51. package/dist/artifacts/scrub.js +139 -0
  52. package/dist/artifacts/step.d.ts +26 -0
  53. package/dist/artifacts/step.d.ts.map +1 -0
  54. package/dist/artifacts/step.js +37 -0
  55. package/dist/artifacts/taint.d.ts +63 -0
  56. package/dist/artifacts/taint.d.ts.map +1 -0
  57. package/dist/artifacts/taint.js +76 -0
  58. package/dist/bakeoff/cache-sim.d.ts +99 -0
  59. package/dist/bakeoff/cache-sim.d.ts.map +1 -0
  60. package/dist/bakeoff/cache-sim.js +126 -0
  61. package/dist/bakeoff/eval-cases.d.ts +96 -0
  62. package/dist/bakeoff/eval-cases.d.ts.map +1 -0
  63. package/dist/bakeoff/eval-cases.js +105 -0
  64. package/dist/bakeoff/report.d.ts +41 -0
  65. package/dist/bakeoff/report.d.ts.map +1 -0
  66. package/dist/bakeoff/report.js +142 -0
  67. package/dist/bakeoff/samples.d.ts +15 -0
  68. package/dist/bakeoff/samples.d.ts.map +1 -1
  69. package/dist/bakeoff/samples.js +20 -0
  70. package/dist/cli.d.ts +1 -3
  71. package/dist/cli.d.ts.map +1 -1
  72. package/dist/cli.js +134 -116
  73. package/dist/config.d.ts +100 -0
  74. package/dist/config.d.ts.map +1 -1
  75. package/dist/config.js +104 -0
  76. package/dist/deprecations.d.ts +32 -0
  77. package/dist/deprecations.d.ts.map +1 -0
  78. package/dist/deprecations.js +59 -0
  79. package/dist/gateway/http-protocol.d.ts +175 -0
  80. package/dist/gateway/http-protocol.d.ts.map +1 -0
  81. package/dist/gateway/http-protocol.js +105 -0
  82. package/dist/index.d.ts +106 -19
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +266 -138
  85. package/dist/init/finder.d.ts +15 -0
  86. package/dist/init/finder.d.ts.map +1 -1
  87. package/dist/init/finder.js +46 -0
  88. package/dist/init/init-cli.d.ts +10 -0
  89. package/dist/init/init-cli.d.ts.map +1 -0
  90. package/dist/init/init-cli.js +86 -0
  91. package/dist/init/observe-cli.d.ts +19 -0
  92. package/dist/init/observe-cli.d.ts.map +1 -0
  93. package/dist/init/observe-cli.js +73 -0
  94. package/dist/init/observe.d.ts +81 -0
  95. package/dist/init/observe.d.ts.map +1 -0
  96. package/dist/init/observe.js +245 -0
  97. package/dist/registry/build.d.ts +94 -1
  98. package/dist/registry/build.d.ts.map +1 -1
  99. package/dist/registry/build.js +125 -4
  100. package/dist/registry/cache-policy.d.ts +94 -0
  101. package/dist/registry/cache-policy.d.ts.map +1 -0
  102. package/dist/registry/cache-policy.js +238 -0
  103. package/dist/registry/call-notes.d.ts.map +1 -1
  104. package/dist/registry/call-notes.js +40 -2
  105. package/dist/registry/effective-rate.d.ts +151 -0
  106. package/dist/registry/effective-rate.d.ts.map +1 -0
  107. package/dist/registry/effective-rate.js +156 -0
  108. package/dist/registry/facts.d.ts.map +1 -1
  109. package/dist/registry/facts.js +16 -0
  110. package/dist/registry/parity.d.ts +26 -0
  111. package/dist/registry/parity.d.ts.map +1 -1
  112. package/dist/registry/parity.js +43 -2
  113. package/dist/registry/pricing-shape.d.ts +113 -0
  114. package/dist/registry/pricing-shape.d.ts.map +1 -0
  115. package/dist/registry/pricing-shape.js +123 -0
  116. package/dist/registry/pricing.d.ts +25 -1
  117. package/dist/registry/pricing.d.ts.map +1 -1
  118. package/dist/registry/pricing.js +64 -6
  119. package/dist/rigindex/bootstrap.d.ts +36 -0
  120. package/dist/rigindex/bootstrap.d.ts.map +1 -0
  121. package/dist/rigindex/bootstrap.js +97 -0
  122. package/dist/rigindex/fit.d.ts +24 -0
  123. package/dist/rigindex/fit.d.ts.map +1 -0
  124. package/dist/rigindex/fit.js +76 -0
  125. package/dist/rigindex/gates.d.ts +52 -0
  126. package/dist/rigindex/gates.d.ts.map +1 -0
  127. package/dist/rigindex/gates.js +109 -0
  128. package/dist/rigindex/graph.d.ts +31 -0
  129. package/dist/rigindex/graph.d.ts.map +1 -0
  130. package/dist/rigindex/graph.js +120 -0
  131. package/dist/rigindex/index.d.ts +23 -0
  132. package/dist/rigindex/index.d.ts.map +1 -0
  133. package/dist/rigindex/index.js +112 -0
  134. package/dist/rigindex/types.d.ts +76 -0
  135. package/dist/rigindex/types.d.ts.map +1 -0
  136. package/dist/rigindex/types.js +8 -0
  137. package/dist/routes/cache-lint.d.ts +41 -0
  138. package/dist/routes/cache-lint.d.ts.map +1 -0
  139. package/dist/routes/cache-lint.js +81 -0
  140. package/dist/routes/loader.d.ts +48 -0
  141. package/dist/routes/loader.d.ts.map +1 -1
  142. package/dist/routes/loader.js +167 -0
  143. package/dist/routes/resolved-bundle.d.ts +79 -0
  144. package/dist/routes/resolved-bundle.d.ts.map +1 -0
  145. package/dist/routes/resolved-bundle.js +148 -0
  146. package/dist/routes/sampling-config.d.ts +32 -0
  147. package/dist/routes/sampling-config.d.ts.map +1 -0
  148. package/dist/routes/sampling-config.js +91 -0
  149. package/dist/run/ajv.d.ts +22 -0
  150. package/dist/run/ajv.d.ts.map +1 -0
  151. package/dist/run/ajv.js +32 -0
  152. package/dist/run/cache-handle.d.ts +58 -0
  153. package/dist/run/cache-handle.d.ts.map +1 -0
  154. package/dist/run/cache-handle.js +54 -0
  155. package/dist/run/cache-stamp.d.ts +65 -0
  156. package/dist/run/cache-stamp.d.ts.map +1 -0
  157. package/dist/run/cache-stamp.js +0 -0
  158. package/dist/run/capture-write.d.ts +33 -0
  159. package/dist/run/capture-write.d.ts.map +1 -0
  160. package/dist/run/capture-write.js +55 -0
  161. package/dist/run/cost.d.ts.map +1 -1
  162. package/dist/run/cost.js +1 -1
  163. package/dist/run/dispatch.d.ts +99 -0
  164. package/dist/run/dispatch.d.ts.map +1 -0
  165. package/dist/run/dispatch.js +191 -0
  166. package/dist/run/raw.d.ts +130 -0
  167. package/dist/run/raw.d.ts.map +1 -0
  168. package/dist/run/raw.js +363 -0
  169. package/dist/run/record-attempt.d.ts +40 -0
  170. package/dist/run/record-attempt.d.ts.map +1 -0
  171. package/dist/run/record-attempt.js +99 -0
  172. package/dist/run/resolve.d.ts +75 -2
  173. package/dist/run/resolve.d.ts.map +1 -1
  174. package/dist/run/resolve.js +126 -4
  175. package/dist/run/run.d.ts +14 -0
  176. package/dist/run/run.d.ts.map +1 -1
  177. package/dist/run/run.js +0 -0
  178. package/dist/run/stream.d.ts +49 -0
  179. package/dist/run/stream.d.ts.map +1 -0
  180. package/dist/run/stream.js +87 -0
  181. package/dist/run/validate.d.ts.map +1 -1
  182. package/dist/run/validate.js +6 -7
  183. package/dist/savings/cache-ledger.d.ts +108 -0
  184. package/dist/savings/cache-ledger.d.ts.map +1 -0
  185. package/dist/savings/cache-ledger.js +174 -0
  186. package/dist/savings/cache-reconcile.d.ts +64 -0
  187. package/dist/savings/cache-reconcile.d.ts.map +1 -0
  188. package/dist/savings/cache-reconcile.js +59 -0
  189. package/dist/savings/cache-stats.d.ts +63 -0
  190. package/dist/savings/cache-stats.d.ts.map +1 -0
  191. package/dist/savings/cache-stats.js +108 -0
  192. package/dist/savings/emit.d.ts +13 -0
  193. package/dist/savings/emit.d.ts.map +1 -1
  194. package/dist/savings/emit.js +25 -0
  195. package/dist/savings/swap-execute.d.ts +14 -0
  196. package/dist/savings/swap-execute.d.ts.map +1 -1
  197. package/dist/savings/swap-execute.js +44 -1
  198. package/dist/savings/swaps-client.d.ts +14 -0
  199. package/dist/savings/swaps-client.d.ts.map +1 -1
  200. package/dist/savings/swaps-client.js +16 -2
  201. package/dist/settings/api-fetcher.d.ts +39 -0
  202. package/dist/settings/api-fetcher.d.ts.map +1 -0
  203. package/dist/settings/api-fetcher.js +92 -0
  204. package/dist/settings/index.d.ts +10 -0
  205. package/dist/settings/index.d.ts.map +1 -0
  206. package/dist/settings/index.js +15 -0
  207. package/dist/settings/task-settings.d.ts +91 -0
  208. package/dist/settings/task-settings.d.ts.map +1 -0
  209. package/dist/settings/task-settings.js +116 -0
  210. package/dist/status.d.ts +77 -0
  211. package/dist/status.d.ts.map +1 -0
  212. package/dist/status.js +113 -0
  213. package/dist/telemetry/artifact-store.d.ts +48 -0
  214. package/dist/telemetry/artifact-store.d.ts.map +1 -0
  215. package/dist/telemetry/artifact-store.js +189 -0
  216. package/dist/telemetry/cache-miss-streak.d.ts +79 -0
  217. package/dist/telemetry/cache-miss-streak.d.ts.map +1 -0
  218. package/dist/telemetry/cache-miss-streak.js +99 -0
  219. package/dist/telemetry/capture.d.ts +3 -0
  220. package/dist/telemetry/capture.d.ts.map +1 -1
  221. package/dist/telemetry/capture.js +15 -8
  222. package/dist/telemetry/exporter-setup.d.ts +28 -0
  223. package/dist/telemetry/exporter-setup.d.ts.map +1 -0
  224. package/dist/telemetry/exporter-setup.js +34 -0
  225. package/dist/telemetry/exporter.d.ts +75 -0
  226. package/dist/telemetry/exporter.d.ts.map +1 -1
  227. package/dist/telemetry/exporter.js +324 -47
  228. package/dist/telemetry/health.d.ts +76 -0
  229. package/dist/telemetry/health.d.ts.map +1 -0
  230. package/dist/telemetry/health.js +92 -0
  231. package/dist/telemetry/ingest-protocol.d.ts +152 -3
  232. package/dist/telemetry/ingest-protocol.d.ts.map +1 -1
  233. package/dist/telemetry/ingest-protocol.js +204 -4
  234. package/dist/telemetry/load-error-report.d.ts +24 -0
  235. package/dist/telemetry/load-error-report.d.ts.map +1 -0
  236. package/dist/telemetry/load-error-report.js +50 -0
  237. package/dist/telemetry/otel-map.d.ts +121 -0
  238. package/dist/telemetry/otel-map.d.ts.map +1 -0
  239. package/dist/telemetry/otel-map.js +224 -0
  240. package/dist/telemetry/otel-normalize.d.ts +104 -0
  241. package/dist/telemetry/otel-normalize.d.ts.map +1 -0
  242. package/dist/telemetry/otel-normalize.js +530 -0
  243. package/dist/telemetry/otlp-emitter.d.ts +52 -0
  244. package/dist/telemetry/otlp-emitter.d.ts.map +1 -0
  245. package/dist/telemetry/otlp-emitter.js +144 -0
  246. package/dist/telemetry/otlp-proto.d.ts +29 -0
  247. package/dist/telemetry/otlp-proto.d.ts.map +1 -0
  248. package/dist/telemetry/otlp-proto.js +266 -0
  249. package/dist/telemetry/sinks.d.ts +37 -1
  250. package/dist/telemetry/sinks.d.ts.map +1 -1
  251. package/dist/telemetry/sinks.js +121 -30
  252. package/dist/telemetry/store.d.ts +28 -1
  253. package/dist/telemetry/store.d.ts.map +1 -1
  254. package/dist/telemetry/store.js +218 -3
  255. package/dist/tenancy/api-key-format.d.ts +15 -5
  256. package/dist/tenancy/api-key-format.d.ts.map +1 -1
  257. package/dist/tenancy/api-key-format.js +24 -5
  258. package/dist/types/config-teaching.d.ts +62 -0
  259. package/dist/types/config-teaching.d.ts.map +1 -0
  260. package/dist/types/config-teaching.js +183 -0
  261. package/dist/types/provider.d.ts +147 -1
  262. package/dist/types/provider.d.ts.map +1 -1
  263. package/dist/types/provider.js +21 -1
  264. package/dist/types/route.d.ts +79 -1
  265. package/dist/types/route.d.ts.map +1 -1
  266. package/dist/types/telemetry.d.ts +117 -0
  267. package/dist/types/telemetry.d.ts.map +1 -1
  268. package/dist/validate-cli.d.ts +12 -0
  269. package/dist/validate-cli.d.ts.map +1 -0
  270. package/dist/validate-cli.js +57 -0
  271. package/dist/verify/capture.d.ts +66 -0
  272. package/dist/verify/capture.d.ts.map +1 -0
  273. package/dist/verify/capture.js +180 -0
  274. package/dist/verify/cli-run.d.ts +23 -0
  275. package/dist/verify/cli-run.d.ts.map +1 -0
  276. package/dist/verify/cli-run.js +57 -0
  277. package/dist/verify/diff.d.ts +48 -0
  278. package/dist/verify/diff.d.ts.map +1 -0
  279. package/dist/verify/diff.js +157 -0
  280. package/dist/verify/index.d.ts +17 -0
  281. package/dist/verify/index.d.ts.map +1 -0
  282. package/dist/verify/index.js +24 -0
  283. package/dist/verify/report.d.ts +14 -0
  284. package/dist/verify/report.d.ts.map +1 -0
  285. package/dist/verify/report.js +88 -0
  286. package/dist/verify/types.d.ts +101 -0
  287. package/dist/verify/types.d.ts.map +1 -0
  288. package/dist/verify/types.js +17 -0
  289. package/dist/verify/verify.d.ts +29 -0
  290. package/dist/verify/verify.d.ts.map +1 -0
  291. package/dist/verify/verify.js +148 -0
  292. package/dist/watch/evaluate.d.ts +162 -3
  293. package/dist/watch/evaluate.d.ts.map +1 -1
  294. package/dist/watch/evaluate.js +61 -0
  295. package/dist/watch/monitor.d.ts +116 -0
  296. package/dist/watch/monitor.d.ts.map +1 -0
  297. package/dist/watch/monitor.js +199 -0
  298. package/dist/watch/proposals.d.ts +20 -4
  299. package/dist/watch/proposals.d.ts.map +1 -1
  300. package/dist/watch/proposals.js +31 -3
  301. package/dist/watch/run.d.ts +33 -0
  302. package/dist/watch/run.d.ts.map +1 -1
  303. package/dist/watch/run.js +39 -0
  304. package/package.json +7 -1
  305. package/registry/LICENSE +20 -0
  306. package/registry/leaderboard.json +3639 -0
  307. package/registry/registry.json +7263 -0
  308. package/dist/telemetry/supabase-exporter.d.ts +0 -64
  309. package/dist/telemetry/supabase-exporter.d.ts.map +0 -1
  310. package/dist/telemetry/supabase-exporter.js +0 -211
@@ -0,0 +1,363 @@
1
+ "use strict";
2
+ /**
3
+ * The RAW LANE — HTTP gateway Phase C (spec §4.2). A zero-margin BYOK
4
+ * passthrough: the caller names a `provider/model` and supplies (server-side,
5
+ * fail-closed) their own provider key; we dispatch DIRECTLY through the matching
6
+ * adapter and meter the call at the provider's list price. There is NO route, NO
7
+ * capability gate, NO validation, NO repair, NO envelope — and, by contract, NO
8
+ * ModelRig margin on the hop (the never-price-the-hop rule; the cost recorded is
9
+ * exactly `attemptCost`'s list price, which is what the verified lane records
10
+ * too). This module is the SDK half; the server half (BYOK resolution + the
11
+ * `key_ownership` tag) lives in `modelrig-server`.
12
+ *
13
+ * WHY THIS IS AN SDK PRIMITIVE, not server code: `AdapterRequest.candidate` is a
14
+ * branded `CandidateRef` mintable only in `run/resolve.ts`, and adapters are
15
+ * constructed with their key baked in — both live here. The server resolves the
16
+ * BYOK key fail-closed and calls `rig.runRaw`/`rig.runRawStream`; it never
17
+ * touches an adapter or the brand.
18
+ *
19
+ * KNOWN LIMITATIONS (flagged for the architect, not hidden):
20
+ * - The adapter contract is single `systemPrompt` + `userPrompt`, not a
21
+ * `messages[]` array, so a multi-turn transcript is flattened by the caller
22
+ * (see `modelrig-server`'s `deriveRawPrompts`).
23
+ * - CE-6: the raw lane now forwards `temperature`/`topP` (via
24
+ * `AdapterRequest.sampling`) when the caller supplies them; absent, they are
25
+ * still dropped and the dispatch is byte-identical to pre-CE-6. `max_tokens`
26
+ * maps to `maxOutputTokens` (unchanged).
27
+ * - CE-2: the raw lane exposes three more provider knobs — `grounding`
28
+ * (native web grounding), `serviceTier`, and `reasoning` (thinking effort).
29
+ * Each is ADDITIVE: absent ⇒ byte-identical dispatch. A DECLARED directive is
30
+ * never silently dropped — `grounding`/`reasoning` on a provider that cannot
31
+ * honor it are rejected fail-closed PRE-DISPATCH (`assertRawKnobsSupported`),
32
+ * with no meter, no provider call, and no telemetry row. v1 support set for
33
+ * both = { gemini }. `serviceTier` forwards to every adapter's tier path and
34
+ * `meta.requestedTier` now reports the DECLARED tier (an honesty fix — it
35
+ * previously hardcoded `"standard"`).
36
+ */
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.assertRawKnobsSupported = assertRawKnobsSupported;
39
+ exports.buildRawRequest = buildRawRequest;
40
+ exports.runRaw = runRaw;
41
+ exports.runRawStream = runRawStream;
42
+ const node_crypto_1 = require("node:crypto");
43
+ const anthropic_1 = require("../adapters/anthropic");
44
+ const deepseek_1 = require("../adapters/deepseek");
45
+ const gemini_1 = require("../adapters/gemini");
46
+ const grok_1 = require("../adapters/grok");
47
+ const openai_1 = require("../adapters/openai");
48
+ const openai_compat_1 = require("../adapters/openai-compat");
49
+ const cost_1 = require("./cost");
50
+ const resolve_1 = require("./resolve");
51
+ const failures_1 = require("../types/failures");
52
+ /** Absent a route timeout, the raw lane uses a generous default — a passthrough
53
+ * should not be shorter-fused than the underlying provider SDK. */
54
+ const DEFAULT_RAW_TIMEOUT_MS = 120000;
55
+ /** Conservative compat-host capability baseline — parity with createRig's
56
+ * COMPAT_STATIC. Inconsequential for raw calls (outputSchema is always null, so
57
+ * no JSON shaping fires), kept aligned so a raw and a routed compat call shape
58
+ * identically if a schema is ever added. */
59
+ const RAW_COMPAT_PROFILE = new Set(["json_mode"]);
60
+ /** Construct a THROWAWAY adapter bound to the caller's BYOK key for one call.
61
+ * Each adapter builds its provider client fresh inside `call()`/`stream()`, so
62
+ * a per-call instance carries no shared state and leaks no key. Exhaustive over
63
+ * ProviderId — a new provider forces a compile error here. */
64
+ function buildRawAdapter(provider, apiKey) {
65
+ switch (provider) {
66
+ case "openai":
67
+ return (0, openai_1.createOpenAIAdapter)({ apiKey });
68
+ case "anthropic":
69
+ return (0, anthropic_1.createAnthropicAdapter)({ apiKey });
70
+ case "gemini":
71
+ return (0, gemini_1.createGeminiAdapter)({ apiKey });
72
+ case "grok":
73
+ return (0, grok_1.createGrokAdapter)({ apiKey });
74
+ case "deepseek":
75
+ return (0, deepseek_1.createDeepSeekAdapter)({ apiKey });
76
+ case "deepinfra":
77
+ case "fireworks": {
78
+ const host = openai_compat_1.OPENAI_COMPAT_HOSTS[provider];
79
+ return (0, openai_compat_1.createOpenAICompatAdapter)({
80
+ providerId: provider,
81
+ baseUrl: host.baseUrl,
82
+ apiKey,
83
+ ...(host.shapeModelId !== undefined ? { shapeModelId: host.shapeModelId } : {}),
84
+ capabilityProfile: () => RAW_COMPAT_PROFILE,
85
+ });
86
+ }
87
+ }
88
+ }
89
+ /** Providers that can honor a DECLARED raw-lane directive in v1 (spec §3
90
+ * fail-closed matrix). Native grounding and reasoning are both gemini-only
91
+ * today; the other adapters would silently ignore the field — exactly the bug
92
+ * class CE-2 makes impossible. A new-provider entry here is a deliberate,
93
+ * spec-gated widening, never an accident. */
94
+ const NATIVE_GROUNDING_PROVIDERS = new Set(["gemini"]);
95
+ const REASONING_PROVIDERS = new Set(["gemini"]);
96
+ /**
97
+ * CE-2 fail-closed guard (spec §3 F1/F3). A DECLARED directive is NEVER silently
98
+ * dropped: `grounding`/`reasoning` on a provider that cannot honor it — or a
99
+ * `grounding.mode` other than the v1-supported `"native"` — throws
100
+ * `RigFailureError` `invariant_violation` (the existing TERMINAL class; no new
101
+ * FailureClass member, spec §3 rationale) BEFORE any adapter is built, any
102
+ * provider call is made, or any telemetry row is written. Exported so the guard
103
+ * is unit-testable without a network. Idempotent and side-effect-free.
104
+ */
105
+ function assertRawKnobsSupported(input) {
106
+ const groundingMode = input.grounding?.mode;
107
+ if (groundingMode !== undefined) {
108
+ if (groundingMode !== "native") {
109
+ throw new failures_1.RigFailureError({
110
+ class: "invariant_violation",
111
+ message: `unsupported raw-lane grounding mode "${groundingMode}"`,
112
+ provider: input.provider,
113
+ model: input.model,
114
+ fixHint: 'only { mode: "native" } grounding is supported on the raw lane in v1',
115
+ });
116
+ }
117
+ if (!NATIVE_GROUNDING_PROVIDERS.has(input.provider)) {
118
+ throw new failures_1.RigFailureError({
119
+ class: "invariant_violation",
120
+ message: `native grounding on the raw lane is not supported for provider "${input.provider}"`,
121
+ provider: input.provider,
122
+ model: input.model,
123
+ fixHint: "native grounding on the raw lane is gemini-only in v1; remove grounding or switch provider",
124
+ });
125
+ }
126
+ }
127
+ if (input.reasoning !== undefined && !REASONING_PROVIDERS.has(input.provider)) {
128
+ throw new failures_1.RigFailureError({
129
+ class: "invariant_violation",
130
+ message: `reasoning control on the raw lane is not supported for provider "${input.provider}"`,
131
+ provider: input.provider,
132
+ model: input.model,
133
+ fixHint: "reasoning control on the raw lane is gemini-only in v1; remove reasoning or switch provider",
134
+ });
135
+ }
136
+ }
137
+ /** Pure raw-lane request shaping — exported for unit tests (no network). */
138
+ function buildRawRequest(candidate, input) {
139
+ // CE-6: forward temperature/topP through AdapterRequest.sampling ONLY when the
140
+ // caller declared at least one — absent, no `sampling` key is added and the
141
+ // request is byte-identical to pre-CE-6. maxOutputTokens keeps its top-level
142
+ // channel (the adapter resolves sampling.maxOutputTokens ?? maxOutputTokens).
143
+ const sampling = input.temperature !== undefined || input.topP !== undefined
144
+ ? {
145
+ ...(input.temperature !== undefined ? { temperature: input.temperature } : {}),
146
+ ...(input.topP !== undefined ? { topP: input.topP } : {}),
147
+ }
148
+ : undefined;
149
+ return {
150
+ candidate,
151
+ systemPrompt: input.systemPrompt,
152
+ userPrompt: input.userPrompt,
153
+ outputSchema: null, // raw lane never validates — the product distinction
154
+ // CE-2 F2: forward the DECLARED tier (default "standard"); the meta/row
155
+ // honesty fix in finalizeRaw reports this same value, never a hardcode.
156
+ requestedTier: input.serviceTier ?? "standard",
157
+ timeoutMs: input.timeoutMs ?? DEFAULT_RAW_TIMEOUT_MS,
158
+ ...(input.maxOutputTokens !== undefined ? { maxOutputTokens: input.maxOutputTokens } : {}),
159
+ ...(sampling !== undefined ? { sampling } : {}),
160
+ // CE-2 F1: `{ mode: "native" }` → the adapter's native-grounding directive.
161
+ // Any other mode / unsupported provider never reaches here — the guard
162
+ // (assertRawKnobsSupported) rejects it pre-dispatch. Absent ⇒ no key added.
163
+ ...(input.grounding?.mode === "native" ? { grounding: true } : {}),
164
+ // CE-2 F3: forward reasoning verbatim; absent ⇒ no key added (byte-identical).
165
+ ...(input.reasoning !== undefined ? { reasoning: input.reasoning } : {}),
166
+ ...(input.tools !== undefined ? { tools: input.tools } : {}),
167
+ ...(input.toolChoice !== undefined ? { toolChoice: input.toolChoice } : {}),
168
+ ...(input.cache !== undefined ? { cache: input.cache } : {}),
169
+ };
170
+ }
171
+ /** Write the metered raw-lane telemetry row. Mirrors the run loop's minimal
172
+ * `recordSearchCostRow` shape: only load-bearing fields set, route = the
173
+ * `provider/model` handle the caller used, lane + key_ownership riding in
174
+ * `tags_json`. The exporter mirrors it on its normal cadence — no lane column,
175
+ * no schema change (telemetry map, 2026-08-10). */
176
+ function recordRawRow(telemetry, p) {
177
+ const row = {
178
+ id: p.id,
179
+ ts: new Date().toISOString(),
180
+ route: p.rawModelId,
181
+ routeVersion: 0,
182
+ provider: p.provider,
183
+ model: p.model,
184
+ requestedTier: p.requestedTier,
185
+ servedTier: p.usage?.servedTier ?? "standard",
186
+ tokensIn: p.usage?.tokensIn ?? 0,
187
+ tokensOut: p.usage?.tokensOut ?? 0,
188
+ tokensCached: p.usage?.tokensCached ?? 0,
189
+ tokensCacheWrite: p.usage?.tokensCacheWrite ?? 0,
190
+ tokensCacheWrite1h: p.usage?.tokensCacheWrite1h ?? 0,
191
+ costEstimateUsd: p.costUsd,
192
+ latencyMs: p.latencyMs,
193
+ ttfbMs: p.usage?.ttfbMs ?? null,
194
+ failureClass: p.failureClass,
195
+ attemptsJson: "{}",
196
+ tagsJson: JSON.stringify(p.tags),
197
+ fingerprintCell: null,
198
+ servedVariant: null,
199
+ repairedBy: null,
200
+ pricingMissing: p.pricingMissing,
201
+ // CE-1: a customer cache handle (if supplied) stamps `cache_key`; the raw
202
+ // lane runs no WS-C stamping, so `prefix_fingerprint` is always null and the
203
+ // provenance rule reads any non-null key here as `customer`.
204
+ cacheKey: p.cacheKey ?? null,
205
+ prefixFingerprint: null,
206
+ };
207
+ telemetry.record(row);
208
+ }
209
+ /**
210
+ * Turn an `AdapterResult` into a RunResult, recording exactly one telemetry row.
211
+ * Shared by the buffered and streaming paths so cost/telemetry are byte-identical.
212
+ * On a failure result: record the (possibly billed) row, then throw
213
+ * `RigFailureError` — the server maps it to a status exactly like the slug lane.
214
+ */
215
+ function finalizeRaw(deps, input, result, latencyMs) {
216
+ const unpricedRatePerTok = (deps.unpricedRateUsdPerMTok ?? cost_1.DEFAULT_UNPRICED_RATE_USD_PER_MTOK) / 1000000;
217
+ const rawModelId = `${input.provider}/${input.model}`;
218
+ // CE-2 F2: the declared tier is reported truthfully on the row AND the meta.
219
+ const requestedTier = input.serviceTier ?? "standard";
220
+ // lane is SDK-owned and cannot be overridden by a caller-supplied tag.
221
+ const tags = { ...(input.tags ?? {}), lane: "raw" };
222
+ if (!result.ok) {
223
+ let costUsd = 0;
224
+ let pricingMissing = false;
225
+ if (result.usage !== undefined) {
226
+ const settled = (0, cost_1.attemptCost)(input.provider, input.model, result.usage, unpricedRatePerTok);
227
+ costUsd = settled.costUsd;
228
+ pricingMissing = settled.pricingMissing;
229
+ }
230
+ recordRawRow(deps.telemetry, {
231
+ id: (0, node_crypto_1.randomUUID)(),
232
+ rawModelId,
233
+ provider: input.provider,
234
+ model: input.model,
235
+ ...(result.usage !== undefined ? { usage: result.usage } : {}),
236
+ costUsd,
237
+ latencyMs,
238
+ requestedTier,
239
+ failureClass: result.failure.class,
240
+ tags,
241
+ pricingMissing,
242
+ ...(input.cache !== undefined ? { cacheKey: input.cache.key } : {}),
243
+ });
244
+ throw new failures_1.RigFailureError(result.failure);
245
+ }
246
+ const { costUsd, pricingMissing } = (0, cost_1.attemptCost)(input.provider, input.model, result.usage, unpricedRatePerTok);
247
+ const id = (0, node_crypto_1.randomUUID)();
248
+ recordRawRow(deps.telemetry, {
249
+ id,
250
+ rawModelId,
251
+ provider: input.provider,
252
+ model: input.model,
253
+ usage: result.usage,
254
+ costUsd,
255
+ latencyMs,
256
+ requestedTier,
257
+ failureClass: null,
258
+ tags,
259
+ pricingMissing,
260
+ ...(input.cache !== undefined ? { cacheKey: input.cache.key } : {}),
261
+ });
262
+ const toolCalls = result.toolCalls;
263
+ const isToolTurn = toolCalls !== undefined && toolCalls.length > 0;
264
+ const meta = {
265
+ inferenceId: id,
266
+ route: rawModelId,
267
+ routeVersion: 0,
268
+ provider: input.provider,
269
+ model: input.model,
270
+ requestedTier,
271
+ servedTier: result.usage.servedTier,
272
+ tokensIn: result.usage.tokensIn,
273
+ tokensOut: result.usage.tokensOut,
274
+ tokensCached: result.usage.tokensCached,
275
+ costEstimateUsd: costUsd,
276
+ latencyMs,
277
+ validated: false, // raw is NEVER validated — the central product claim
278
+ attemptsByClass: {},
279
+ servedVariant: null,
280
+ repairedBy: null,
281
+ ...(isToolTurn ? { toolCalls } : {}),
282
+ };
283
+ return { output: isToolTurn ? null : result.text, meta };
284
+ }
285
+ /** Buffered raw dispatch (spec §4.2). Records telemetry, returns the RunResult,
286
+ * or throws `RigFailureError` on an adapter failure. */
287
+ async function runRaw(deps, input) {
288
+ // CE-2 F1/F3: fail closed on an unsupported declared directive BEFORE building
289
+ // an adapter — no meter, no provider call, no telemetry row.
290
+ assertRawKnobsSupported(input);
291
+ const adapter = buildRawAdapter(input.provider, input.apiKey);
292
+ const candidate = (0, resolve_1.mintRawCandidate)(input.provider, input.model);
293
+ const started = Date.now();
294
+ const result = await adapter.call(buildRawRequest(candidate, input));
295
+ return finalizeRaw(deps, input, result, Date.now() - started);
296
+ }
297
+ function streamEndedFailure(input) {
298
+ return {
299
+ ok: false,
300
+ failure: {
301
+ class: "network",
302
+ message: "adapter stream ended without a terminal result",
303
+ provider: input.provider,
304
+ model: input.model,
305
+ },
306
+ };
307
+ }
308
+ /**
309
+ * Streaming raw dispatch (spec §4.3, "raw lane: true streaming, deltas passed
310
+ * through"). Drains the adapter's own stream when it has one, forwarding raw
311
+ * text deltas, and emits a single terminal `final` RunResult; adapters without
312
+ * `stream` (anthropic/gemini) fall back to a buffered `call()` with no deltas.
313
+ * There is NO terminal-validation event — that is a structured-route concept;
314
+ * the raw lane has no schema and the streamed bytes ARE the answer.
315
+ */
316
+ function runRawStream(deps, input) {
317
+ let settle;
318
+ let fail;
319
+ const result = new Promise((res, rej) => {
320
+ settle = res;
321
+ fail = rej;
322
+ });
323
+ // Mark handled so an unconsumed rejection never becomes an unhandledRejection;
324
+ // the events iterator surfaces the same error to whoever drains it.
325
+ result.catch(() => { });
326
+ async function* events() {
327
+ try {
328
+ // CE-2 F1/F3: fail closed on an unsupported declared directive BEFORE any
329
+ // adapter/dispatch — surfaced through the handle (result rejects, the
330
+ // events iterator throws), so no meter, no provider call, no telemetry row.
331
+ assertRawKnobsSupported(input);
332
+ const adapter = buildRawAdapter(input.provider, input.apiKey);
333
+ const candidate = (0, resolve_1.mintRawCandidate)(input.provider, input.model);
334
+ const req = buildRawRequest(candidate, input);
335
+ const started = Date.now();
336
+ let adapterResult;
337
+ if (adapter.stream !== undefined) {
338
+ let final = null;
339
+ for await (const ev of adapter.stream(req)) {
340
+ if (ev.kind === "delta") {
341
+ if (ev.text !== "")
342
+ yield { type: "delta", text: ev.text };
343
+ }
344
+ else {
345
+ final = ev.result;
346
+ }
347
+ }
348
+ adapterResult = final ?? streamEndedFailure(input);
349
+ }
350
+ else {
351
+ adapterResult = await adapter.call(req);
352
+ }
353
+ const runResult = finalizeRaw(deps, input, adapterResult, Date.now() - started);
354
+ settle(runResult);
355
+ yield { type: "final", result: runResult };
356
+ }
357
+ catch (err) {
358
+ fail(err);
359
+ throw err;
360
+ }
361
+ }
362
+ return { events: events(), result };
363
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The run loop's per-attempt telemetry recorder, extracted from run.ts (WS-A).
3
+ *
4
+ * run.ts sits at the 700-LOC cap; threading cache-write accounting through the
5
+ * row builder pushed it over, so the recorder — a self-contained mapping from
6
+ * an `AttemptTelemetry` to a persisted `TelemetryRow` plus the ground-truth
7
+ * step mirror — moves here as a factory over the loop's per-run state. Behavior
8
+ * is byte-identical to the former inline closure, save the additive cache
9
+ * fields. Keeping it separate also shrinks the run-loop conflict surface for the
10
+ * in-flight E4 / capture-write work (plan coordination note).
11
+ */
12
+ import type { AttemptTelemetry } from "./dispatch";
13
+ import type { ActiveRunContext } from "../artifacts/run-context";
14
+ import type { RetryLedger } from "./retry";
15
+ import type { RouteBundle, RunOptions, RunTags } from "../types/route";
16
+ import type { TelemetryStore } from "../types/telemetry";
17
+ export interface RecordAttemptDeps {
18
+ readonly telemetry: TelemetryStore;
19
+ readonly route: RouteBundle;
20
+ readonly ledger: RetryLedger;
21
+ readonly effectiveTags: RunTags;
22
+ readonly servedVariant: string | null;
23
+ /** Active run context (E2 chunk A) or null when the artifact namespace is off. */
24
+ readonly runCtx: ActiveRunContext | null;
25
+ readonly autoStepKey: string | null;
26
+ /** CE-1: the run's customer cache handle (RunOptions.cache), or undefined.
27
+ * The recorder derives the customer key from the SAME pure gate the request
28
+ * builder uses ({@link customerCacheHandle}), so wire and row never disagree. */
29
+ readonly cache?: RunOptions["cache"];
30
+ /** CE-1 retry-drop: candidate keys whose handle was dropped after a
31
+ * `cache_invalid` (live reference — the run loop mutates it between calls). A
32
+ * dropped candidate's later rows carry no customer key (they dispatched
33
+ * uncached), exactly matching the request builder's suppression. */
34
+ readonly droppedCacheHandle: ReadonlySet<string>;
35
+ }
36
+ /** Build the run loop's `recordAttempt(attempt) => inferenceId` over this run's
37
+ * state. Records one inference row and, with an active run context, mirrors it
38
+ * as a ground-truth step (fail-open). */
39
+ export declare function createRecordAttempt(deps: RecordAttemptDeps): (attempt: AttemptTelemetry) => string;
40
+ //# sourceMappingURL=record-attempt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"record-attempt.d.ts","sourceRoot":"","sources":["../../src/run/record-attempt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAE3C,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACvE,OAAO,KAAK,EAAgB,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAIvE,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC;IACnC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;IAChC,QAAQ,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC,kFAAkF;IAClF,QAAQ,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,CAAC;IACzC,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC;;qFAEiF;IACjF,QAAQ,CAAC,KAAK,CAAC,EAAE,UAAU,CAAC,OAAO,CAAC,CAAC;IACrC;;;wEAGoE;IACpE,QAAQ,CAAC,kBAAkB,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CAClD;AAED;;yCAEyC;AACzC,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,iBAAiB,GAAG,CAAC,OAAO,EAAE,gBAAgB,KAAK,MAAM,CA6ElG"}
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ /**
3
+ * The run loop's per-attempt telemetry recorder, extracted from run.ts (WS-A).
4
+ *
5
+ * run.ts sits at the 700-LOC cap; threading cache-write accounting through the
6
+ * row builder pushed it over, so the recorder — a self-contained mapping from
7
+ * an `AttemptTelemetry` to a persisted `TelemetryRow` plus the ground-truth
8
+ * step mirror — moves here as a factory over the loop's per-run state. Behavior
9
+ * is byte-identical to the former inline closure, save the additive cache
10
+ * fields. Keeping it separate also shrinks the run-loop conflict surface for the
11
+ * in-flight E4 / capture-write work (plan coordination note).
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.createRecordAttempt = createRecordAttempt;
15
+ const node_crypto_1 = require("node:crypto");
16
+ const failures_1 = require("../types/failures");
17
+ const cache_stamp_1 = require("./cache-stamp");
18
+ const cache_handle_1 = require("./cache-handle");
19
+ /** Build the run loop's `recordAttempt(attempt) => inferenceId` over this run's
20
+ * state. Records one inference row and, with an active run context, mirrors it
21
+ * as a ground-truth step (fail-open). */
22
+ function createRecordAttempt(deps) {
23
+ const { telemetry, route, ledger, effectiveTags, servedVariant, runCtx, autoStepKey } = deps;
24
+ const { cache, droppedCacheHandle } = deps;
25
+ return function recordAttempt(attempt) {
26
+ // Request-path cache substrate (WS-C): derived from the SAME pure gate the
27
+ // dispatcher stamps the request with, so `cache_key`/`prefix_fingerprint` on
28
+ // the row match what was sent for this candidate. No-op (both null) unless
29
+ // the route opted into `cache: auto` — pre-WS-C rows are byte-identical.
30
+ // PRIMARY-attempt only: a repair call (repairedBy set) re-asks with a
31
+ // different prompt (error feedback / repair-model framing), so its prefix
32
+ // does not share the route's cacheable identity — stamping it would file a
33
+ // cold, different-prefix call under the primary fingerprint and pollute
34
+ // WS-B's warm-set derivation and the §5.6 streak alert. Repair rows carry
35
+ // neither key nor fingerprint (matching buildRepairAdapterRequest, which
36
+ // sends no cache directive).
37
+ // CE-1 (spec §2.3): derive the customer key from the SAME gate as the request
38
+ // builder — a matching-provider, non-suppressed handle WINS over the WS-C
39
+ // generated stamp. `prefix_fingerprint` is unchanged, so origin stays
40
+ // derivable with NO new column (customer key != fingerprint ⇒ customer;
41
+ // key == fingerprint ⇒ generated — cacheKeyProvenance). Both derivations
42
+ // skip repair rows symmetrically (their prefix differs from the route's).
43
+ const isPrimary = attempt.repairedBy === undefined;
44
+ const cacheStamp = isPrimary ? (0, cache_stamp_1.cacheStampForCandidate)(route, attempt.candidate) : null;
45
+ // The customer key marks rows whose REQUEST carried the handle. A terminal
46
+ // failure (budget_exhausted / invariant_violation) is recorded by failRun
47
+ // BEFORE any dispatch — the wire never carried the handle — so those rows
48
+ // must not claim a customer key. Terminal classes come only from failRun;
49
+ // adapters never return them. (A grounding-search failure is the one
50
+ // non-terminal pre-dispatch path, but a customer cachedContents handle and
51
+ // the inject rung are mutually exclusive, so it is unreachable in practice.)
52
+ const preDispatch = attempt.failure !== null && failures_1.TERMINAL_CLASSES.has(attempt.failure.class);
53
+ const dropped = droppedCacheHandle.has(`${attempt.candidate.provider} ${attempt.candidate.model}`);
54
+ const customer = isPrimary && !preDispatch ? (0, cache_handle_1.customerCacheHandle)(cache, attempt.candidate, dropped) : null;
55
+ const cacheKey = customer?.key ?? cacheStamp?.cacheKey ?? null;
56
+ const row = {
57
+ id: (0, node_crypto_1.randomUUID)(),
58
+ ts: new Date().toISOString(),
59
+ route: route.route,
60
+ routeVersion: route.version,
61
+ provider: attempt.candidate.provider,
62
+ model: attempt.candidate.model,
63
+ requestedTier: route.policy.tier,
64
+ servedTier: attempt.servedTier,
65
+ tokensIn: attempt.tokensIn,
66
+ tokensOut: attempt.tokensOut,
67
+ tokensCached: attempt.tokensCached,
68
+ // Cache-write accounting (WS-A) + request-path substrate (WS-C).
69
+ tokensCacheWrite: attempt.tokensCacheWrite ?? 0,
70
+ tokensCacheWrite1h: attempt.tokensCacheWrite1h ?? 0,
71
+ cacheKey,
72
+ prefixFingerprint: cacheStamp?.prefixFingerprint ?? null,
73
+ costEstimateUsd: attempt.costUsd,
74
+ latencyMs: attempt.latencyMs,
75
+ ttfbMs: attempt.ttfbMs ?? null,
76
+ failureClass: attempt.failure?.class ?? null,
77
+ attemptsJson: JSON.stringify(ledger.snapshot()),
78
+ tagsJson: JSON.stringify(effectiveTags),
79
+ fingerprintCell: route.fingerprintCell,
80
+ servedVariant,
81
+ repairedBy: attempt.repairedBy ?? null,
82
+ pricingMissing: attempt.pricingMissing ?? false,
83
+ };
84
+ telemetry.record(row);
85
+ // Mirror this inference into a ground-truth step attempt (fail-open — the
86
+ // context swallows buffer errors; the run loop is never affected).
87
+ if (runCtx !== null && autoStepKey !== null) {
88
+ runCtx.emitGroundTruthStep({
89
+ stepKey: autoStepKey,
90
+ task: route.route,
91
+ inferenceId: row.id,
92
+ startedAt: row.ts,
93
+ endedAt: new Date().toISOString(),
94
+ failureClass: row.failureClass,
95
+ });
96
+ }
97
+ return row.id;
98
+ };
99
+ }
@@ -5,7 +5,7 @@
5
5
  * route.require, ordered by prefer:[cost] via the pricing snapshot; on a
6
6
  * retryable failure the run loop asks for the next candidate.
7
7
  */
8
- import type { RouteBundle } from "../types/route";
8
+ import type { RouteBundle, RunOptions } from "../types/route";
9
9
  import type { CandidateRef, CapabilityFlag, ProviderId } from "../types/provider";
10
10
  /** Static capability stub — replaced by the probed registry in Phase 2. */
11
11
  export type CapabilityLookup = (provider: ProviderId, model: string) => ReadonlySet<CapabilityFlag>;
@@ -13,7 +13,80 @@ export interface CandidateIterator {
13
13
  /** Next eligible candidate, or null when the set is exhausted. */
14
14
  next(): CandidateRef | null;
15
15
  }
16
- export declare function resolveCandidates(route: RouteBundle, capabilities: CapabilityLookup, costUsdPerMTok: (provider: ProviderId, model: string) => number | null, searchAvailable?: boolean): CandidateIterator;
16
+ /**
17
+ * Request-time candidate filters (G-2) — optional, applied by resolveCandidates
18
+ * BEFORE the prefer:[cost] sort. Distinct from route.require (capability + ZDR):
19
+ * these are per-run narrowings a caller passes on RunOptions. `maxPriceUsdPerMTok`
20
+ * reuses the same rate prefer:[cost] sorts on, so filter and sort agree.
21
+ */
22
+ export interface CandidateFilter {
23
+ readonly maxPriceUsdPerMTok?: number;
24
+ readonly only?: readonly ProviderId[];
25
+ readonly ignore?: readonly ProviderId[];
26
+ }
27
+ /**
28
+ * SHADOW-MODE warmth-aware ordering (cache-aware-routing spec §5.5, WS-B step 8;
29
+ * [Briefing] "auto only after validation"). Opt-in and NON-ACTUATING: when
30
+ * supplied, `resolveCandidates` computes the ordering that ranking by
31
+ * cache-ADJUSTED effective cost WOULD produce, hands the chosen-vs-recommended
32
+ * comparison to `log`, and then returns the UNCHANGED list-cost order. Absent ⇒
33
+ * the resolver is byte-for-byte its pre-WS-B self. No behavior flip ships this
34
+ * mission — the shadow log is reviewed before any warmth ordering activates
35
+ * (post-deploy gate ledger).
36
+ */
37
+ export interface WarmthShadowOptions {
38
+ /** Cache-adjusted effective cost for a candidate (USD/MTok), or null when
39
+ * unknown — computed by the caller from the derived ledger + effective-rate
40
+ * (kept out of the resolver so this file stays free of pricing/cache logic). */
41
+ readonly effectiveCostUsdPerMTok: (provider: ProviderId, model: string) => number | null;
42
+ /** Sink for the shadow comparison — a logger/telemetry hook. */
43
+ readonly log: (shadow: WarmthShadowLog) => void;
44
+ }
45
+ /** One shadow observation: the order the resolver ACTUALLY returned (list-cost)
46
+ * vs the order warmth-aware ranking would recommend, and whether they diverge. */
47
+ export interface WarmthShadowLog {
48
+ readonly route: string;
49
+ readonly chosen: readonly {
50
+ readonly provider: ProviderId;
51
+ readonly model: string;
52
+ }[];
53
+ readonly recommended: readonly {
54
+ readonly provider: ProviderId;
55
+ readonly model: string;
56
+ }[];
57
+ readonly diverged: boolean;
58
+ }
59
+ export declare function resolveCandidates(route: RouteBundle, capabilities: CapabilityLookup, costUsdPerMTok: (provider: ProviderId, model: string) => number | null, searchAvailable?: boolean, filter?: CandidateFilter, shadowWarmth?: WarmthShadowOptions): CandidateIterator;
60
+ /**
61
+ * Per-run requirement opt-ins (G-3). A caller can demand zero-retention routing
62
+ * for a single run without editing the route bundle: `zero_retention` is unioned
63
+ * into the effective `require`, so the existing satisfiesRequirements filter, the
64
+ * no-eligible-candidate message, and the fail-closed empty-set path all apply
65
+ * unchanged. Additive only — a run opts INTO a stricter requirement, never OUT of
66
+ * a route's declared one (opting out would be a governance downgrade).
67
+ */
68
+ export declare function applyRunRequirements(route: RouteBundle, zeroRetention: boolean): RouteBundle;
69
+ /** Map a run's RunOptions to a CandidateFilter (G-2), or undefined when no knob
70
+ * is set — so the resolver takes the byte-identical pre-G-2 path (back-compat). */
71
+ export declare function candidateFilterFromOptions(opts: RunOptions): CandidateFilter | undefined;
72
+ /** A human-readable suffix naming the binding request-time filters, for the
73
+ * existing no-eligible-candidate error (spec §4.3 — explainability, not a new
74
+ * error class). Empty when no filter is set. */
75
+ export declare function filterSummary(opts: RunOptions): string;
76
+ /**
77
+ * Mint a CandidateRef for the RAW LANE (http-gateway spec §4.2) — a
78
+ * `provider/model` the caller named explicitly, dispatched at zero margin on
79
+ * the caller's own BYOK key with NO route and NO verified pipeline.
80
+ *
81
+ * The candidate-set invariant guards against substituting a model outside a
82
+ * ROUTE's declared list; a route-free, explicitly-named passthrough is outside
83
+ * that invariant's scope by construction (there is no list to escape). This is
84
+ * the ONE sanctioned brand site for it, so the "no `as CandidateRef`" grep stays
85
+ * clean and the brand stays centralized here. The authorization that replaces
86
+ * route membership lives server-side: the raw lane dispatches only after
87
+ * `resolveProviderKeyForCall` returns a BYOK key fail-closed (spec §4.2).
88
+ */
89
+ export declare function mintRawCandidate(provider: ProviderId, model: string): CandidateRef;
17
90
  /**
18
91
  * Mint a CandidateRef for a SPECIFIC declared candidate (the repair rung's
19
92
  * designated repair model — loader-validated to be in the route's candidate
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/run/resolve.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAElF,2EAA2E;AAC3E,MAAM,MAAM,gBAAgB,GAAG,CAC7B,QAAQ,EAAE,UAAU,EACpB,KAAK,EAAE,MAAM,KACV,WAAW,CAAC,cAAc,CAAC,CAAC;AAEjC,MAAM,WAAW,iBAAiB;IAChC,kEAAkE;IAClE,IAAI,IAAI,YAAY,GAAG,IAAI,CAAC;CAC7B;AAuCD,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,WAAW,EAClB,YAAY,EAAE,gBAAgB,EAC9B,cAAc,EAAE,CAAC,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,EACtE,eAAe,UAAQ,GACtB,iBAAiB,CA6BnB;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,WAAW,EAClB,IAAI,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC9D,YAAY,GAAG,IAAI,CAMrB"}
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/run/resolve.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAElF,2EAA2E;AAC3E,MAAM,MAAM,gBAAgB,GAAG,CAC7B,QAAQ,EAAE,UAAU,EACpB,KAAK,EAAE,MAAM,KACV,WAAW,CAAC,cAAc,CAAC,CAAC;AAEjC,MAAM,WAAW,iBAAiB;IAChC,kEAAkE;IAClE,IAAI,IAAI,YAAY,GAAG,IAAI,CAAC;CAC7B;AA6CD;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,UAAU,EAAE,CAAC;IACtC,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,UAAU,EAAE,CAAC;CACzC;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,mBAAmB;IAClC;;oFAEgF;IAChF,QAAQ,CAAC,uBAAuB,EAAE,CAAC,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,CAAC;IACzF,gEAAgE;IAChE,QAAQ,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAC;CACjD;AAED;kFACkF;AAClF,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,SAAS;QAAE,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;QAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACtF,QAAQ,CAAC,WAAW,EAAE,SAAS;QAAE,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;QAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC3F,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC5B;AAED,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,WAAW,EAClB,YAAY,EAAE,gBAAgB,EAC9B,cAAc,EAAE,CAAC,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,EACtE,eAAe,UAAQ,EACvB,MAAM,CAAC,EAAE,eAAe,EACxB,YAAY,CAAC,EAAE,mBAAmB,GACjC,iBAAiB,CAkFnB;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,OAAO,GAAG,WAAW,CAM5F;AAED;mFACmF;AACnF,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,UAAU,GAAG,eAAe,GAAG,SAAS,CAUxF;AAED;;gDAEgD;AAChD,wBAAgB,aAAa,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,CAMtD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,GAAG,YAAY,CAElF;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,WAAW,EAClB,IAAI,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC9D,YAAY,GAAG,IAAI,CAMrB"}