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,191 @@
1
+ "use strict";
2
+ /**
3
+ * Dispatch helpers extracted from run.ts (G-1/G-5 Phase A). The run loop is at
4
+ * its LOC cap, so the tool-passthrough and streaming seams live here — the same
5
+ * move G-2 made when it pulled applyRunRequirements/candidateFilterFromOptions
6
+ * into resolve.ts. Pure/near-pure: request shaping, the stream-vs-buffered
7
+ * dispatch fork, and the tool-call RunResult builder.
8
+ *
9
+ * Tool *execution* is never ours (spec §4.4); these helpers normalize the
10
+ * protocol and surface it — nothing here runs a tool.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.recordSearchCostRow = recordSearchCostRow;
14
+ exports.buildAdapterRequest = buildAdapterRequest;
15
+ exports.buildRepairAdapterRequest = buildRepairAdapterRequest;
16
+ exports.dispatchCandidate = dispatchCandidate;
17
+ exports.emitToolCallResult = emitToolCallResult;
18
+ const node_crypto_1 = require("node:crypto");
19
+ const cache_stamp_1 = require("./cache-stamp");
20
+ const cache_handle_1 = require("./cache-handle");
21
+ /** Record the grounding-inject search's own telemetry row (WS3): a $-only line
22
+ * under the synthetic "search" provider. Extracted from run.ts to keep it under
23
+ * the LOC cap; behaviour is byte-identical to the prior inline recorder. */
24
+ function recordSearchCostRow(telemetry, route, effectiveTags, servedVariant, searchProviderId, costUsd) {
25
+ telemetry.record({
26
+ id: (0, node_crypto_1.randomUUID)(),
27
+ ts: new Date().toISOString(),
28
+ route: route.route,
29
+ routeVersion: route.version,
30
+ provider: "search",
31
+ model: searchProviderId,
32
+ requestedTier: "standard",
33
+ servedTier: "standard",
34
+ tokensIn: 0,
35
+ tokensOut: 0,
36
+ tokensCached: 0,
37
+ tokensCacheWrite: 0,
38
+ tokensCacheWrite1h: 0,
39
+ costEstimateUsd: costUsd,
40
+ latencyMs: 0,
41
+ ttfbMs: null,
42
+ failureClass: null,
43
+ attemptsJson: "{}",
44
+ tagsJson: JSON.stringify(effectiveTags),
45
+ fingerprintCell: route.fingerprintCell,
46
+ servedVariant,
47
+ repairedBy: null,
48
+ pricingMissing: false,
49
+ cacheKey: null,
50
+ prefixFingerprint: null,
51
+ });
52
+ }
53
+ /** Build the primary-attempt AdapterRequest — adds the grounding hint and the
54
+ * unified tools/toolChoice passthrough (spec §4.4). */
55
+ function buildAdapterRequest(parts) {
56
+ const { route, candidate, systemPrompt, userDirective, nativeGrounded, opts } = parts;
57
+ // Request-path caching, two layers with a strict precedence (CE-1 spec §2.2):
58
+ // (1) a CUSTOMER-supplied handle (RunOptions.cache) for the matching
59
+ // provider WINS — it is a real provider-native resource the customer
60
+ // owns. On gemini this is a `cachedContents/<id>`; the gemini adapter
61
+ // then drops systemInstruction+tools by design (they are BAKED INTO the
62
+ // cache at creation, and the API rejects setting both — gemini.ts:145).
63
+ // That is correct API behavior, not a bug; the teaching doc explains it.
64
+ // The WS-C gemini exclusion is untouched — it covers GENERATED keys only.
65
+ // (2) else the WS-C `cache: auto` generated stamp — same pure gate the
66
+ // recorder uses, so wire and telemetry never disagree (gemini excluded
67
+ // here by that gate, not by prose).
68
+ // Absent RunOptions.cache, (1) is null and this is byte-identical to main.
69
+ const customerCache = (0, cache_handle_1.customerCacheHandle)(opts.cache, candidate, parts.suppressCustomerCache === true);
70
+ const cacheStamp = (0, cache_stamp_1.cacheStampForCandidate)(route, candidate);
71
+ const cacheDirective = customerCache ?? cacheStamp.request;
72
+ return {
73
+ candidate,
74
+ systemPrompt,
75
+ userPrompt: userDirective,
76
+ outputSchema: route.outputSchema,
77
+ requestedTier: route.policy.tier,
78
+ timeoutMs: route.policy.timeoutMs,
79
+ ...(cacheDirective !== null ? { cache: cacheDirective } : {}),
80
+ ...(route.require.includes("grounded") && nativeGrounded ? { grounding: true } : {}),
81
+ // CE-6: the route's declared sampling rides every primary attempt. Absent ⇒
82
+ // no `sampling` key ⇒ adapters keep their constants/omissions (byte-identical).
83
+ ...(route.policy.sampling !== undefined ? { sampling: route.policy.sampling } : {}),
84
+ ...(opts.tools !== undefined ? { tools: opts.tools } : {}),
85
+ ...(opts.toolChoice !== undefined ? { toolChoice: opts.toolChoice } : {}),
86
+ };
87
+ }
88
+ /** Build the repair-attempt AdapterRequest (no tools — repair re-asks for the
89
+ * structured object, never a tool call). */
90
+ function buildRepairAdapterRequest(route, candidate, systemPrompt, repairDirective) {
91
+ // No cache stamp (WS-C): a repair re-asks with a DIFFERENT prompt (error
92
+ // feedback / repair-model framing), so it does not share the route's cacheable
93
+ // prefix identity. Sending the primary fingerprint as a routing key here would
94
+ // point dissimilar prompts at the same cache slot (openai explicitly warns
95
+ // against that) and would misfile the row in WS-B's warm-set. The recorder
96
+ // (record-attempt.ts) skips repair rows symmetrically.
97
+ return {
98
+ candidate,
99
+ systemPrompt,
100
+ userPrompt: repairDirective,
101
+ outputSchema: route.outputSchema,
102
+ requestedTier: route.policy.tier,
103
+ timeoutMs: route.policy.timeoutMs,
104
+ // CE-6: repair / JSON-extractor followups inherit the route's sampling — one
105
+ // knob per route, not per rung (spec §3). A repair re-ask at a different
106
+ // temperature than the primary would be a silent behaviour split.
107
+ ...(route.policy.sampling !== undefined ? { sampling: route.policy.sampling } : {}),
108
+ };
109
+ }
110
+ /**
111
+ * Dispatch a candidate. When a delta sink is supplied AND the adapter can
112
+ * stream, drain its stream — forwarding raw text deltas to the sink — and
113
+ * return the terminal `AdapterResult` (identical to what `call()` returns, so
114
+ * the run loop's cost/validation/telemetry logic is unchanged). Otherwise
115
+ * buffered `call()`.
116
+ */
117
+ async function dispatchCandidate(adapter, req, onDelta) {
118
+ if (onDelta === undefined || adapter.stream === undefined) {
119
+ return adapter.call(req);
120
+ }
121
+ let final = null;
122
+ for await (const ev of adapter.stream(req)) {
123
+ if (ev.kind === "delta") {
124
+ if (ev.text !== "")
125
+ onDelta({ text: ev.text });
126
+ }
127
+ else {
128
+ final = ev.result;
129
+ }
130
+ }
131
+ return (final ?? {
132
+ ok: false,
133
+ failure: {
134
+ class: "network",
135
+ message: "adapter stream ended without a terminal result",
136
+ provider: req.candidate.provider,
137
+ model: req.candidate.model,
138
+ },
139
+ });
140
+ }
141
+ /**
142
+ * Record a tool-call turn and build its RunResult (spec §4.4). A tool call is
143
+ * NOT a schema-validated JSON turn: it records a normal (non-failure) telemetry
144
+ * row, then returns a result with `validated: false`, `output: null` (the caller
145
+ * reads `meta.toolCalls`, runs the tool, and continues the exchange), and the
146
+ * normalized calls surfaced on the meta. Recording goes through run.ts's own
147
+ * `recordAttempt` so the ledger/tenancy stamping is identical to every other row.
148
+ */
149
+ function emitToolCallResult(record, parts) {
150
+ const { route, candidate, result, costUsd, latencyMs, attemptsByClass, servedVariant } = parts;
151
+ const inferenceId = record({
152
+ candidate,
153
+ servedTier: result.usage.servedTier,
154
+ tokensIn: result.usage.tokensIn,
155
+ tokensOut: result.usage.tokensOut,
156
+ tokensCached: result.usage.tokensCached,
157
+ ...(result.usage.tokensCacheWrite !== undefined
158
+ ? { tokensCacheWrite: result.usage.tokensCacheWrite }
159
+ : {}),
160
+ ...(result.usage.tokensCacheWrite1h !== undefined
161
+ ? { tokensCacheWrite1h: result.usage.tokensCacheWrite1h }
162
+ : {}),
163
+ costUsd,
164
+ latencyMs,
165
+ ...(result.usage.ttfbMs !== undefined ? { ttfbMs: result.usage.ttfbMs } : {}),
166
+ failure: null,
167
+ pricingMissing: parts.pricingMissing,
168
+ });
169
+ return {
170
+ output: null,
171
+ meta: {
172
+ inferenceId,
173
+ route: route.route,
174
+ routeVersion: route.version,
175
+ provider: candidate.provider,
176
+ model: candidate.model,
177
+ requestedTier: route.policy.tier,
178
+ servedTier: result.usage.servedTier,
179
+ tokensIn: result.usage.tokensIn,
180
+ tokensOut: result.usage.tokensOut,
181
+ tokensCached: result.usage.tokensCached,
182
+ costEstimateUsd: costUsd,
183
+ latencyMs,
184
+ validated: false,
185
+ attemptsByClass,
186
+ servedVariant,
187
+ repairedBy: null,
188
+ toolCalls: result.toolCalls,
189
+ },
190
+ };
191
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The RAW LANE — HTTP gateway Phase C (spec §4.2). A zero-margin BYOK
3
+ * passthrough: the caller names a `provider/model` and supplies (server-side,
4
+ * fail-closed) their own provider key; we dispatch DIRECTLY through the matching
5
+ * adapter and meter the call at the provider's list price. There is NO route, NO
6
+ * capability gate, NO validation, NO repair, NO envelope — and, by contract, NO
7
+ * ModelRig margin on the hop (the never-price-the-hop rule; the cost recorded is
8
+ * exactly `attemptCost`'s list price, which is what the verified lane records
9
+ * too). This module is the SDK half; the server half (BYOK resolution + the
10
+ * `key_ownership` tag) lives in `modelrig-server`.
11
+ *
12
+ * WHY THIS IS AN SDK PRIMITIVE, not server code: `AdapterRequest.candidate` is a
13
+ * branded `CandidateRef` mintable only in `run/resolve.ts`, and adapters are
14
+ * constructed with their key baked in — both live here. The server resolves the
15
+ * BYOK key fail-closed and calls `rig.runRaw`/`rig.runRawStream`; it never
16
+ * touches an adapter or the brand.
17
+ *
18
+ * KNOWN LIMITATIONS (flagged for the architect, not hidden):
19
+ * - The adapter contract is single `systemPrompt` + `userPrompt`, not a
20
+ * `messages[]` array, so a multi-turn transcript is flattened by the caller
21
+ * (see `modelrig-server`'s `deriveRawPrompts`).
22
+ * - CE-6: the raw lane now forwards `temperature`/`topP` (via
23
+ * `AdapterRequest.sampling`) when the caller supplies them; absent, they are
24
+ * still dropped and the dispatch is byte-identical to pre-CE-6. `max_tokens`
25
+ * maps to `maxOutputTokens` (unchanged).
26
+ * - CE-2: the raw lane exposes three more provider knobs — `grounding`
27
+ * (native web grounding), `serviceTier`, and `reasoning` (thinking effort).
28
+ * Each is ADDITIVE: absent ⇒ byte-identical dispatch. A DECLARED directive is
29
+ * never silently dropped — `grounding`/`reasoning` on a provider that cannot
30
+ * honor it are rejected fail-closed PRE-DISPATCH (`assertRawKnobsSupported`),
31
+ * with no meter, no provider call, and no telemetry row. v1 support set for
32
+ * both = { gemini }. `serviceTier` forwards to every adapter's tier path and
33
+ * `meta.requestedTier` now reports the DECLARED tier (an honesty fix — it
34
+ * previously hardcoded `"standard"`).
35
+ */
36
+ import type { AdapterRequest, CandidateRef, ProviderId, ReasoningParams, ServiceTier, ToolChoice, ToolDefinition } from "../types/provider";
37
+ import type { RunResult, RunTags } from "../types/route";
38
+ import type { RunStreamHandle } from "./stream";
39
+ import type { TelemetryStore } from "../types/telemetry";
40
+ /** Raw-lane request. `systemPrompt`/`userPrompt` are already flattened from the
41
+ * OpenAI `messages[]` by the caller; `tags` carries the caller's dimensions
42
+ * (the server stamps `key_ownership` here). `lane: "raw"` is stamped by this
43
+ * module and cannot be overridden. */
44
+ export interface RawRunInput {
45
+ readonly provider: ProviderId;
46
+ readonly model: string;
47
+ /** The caller's BYOK provider secret, resolved fail-closed server-side. Held
48
+ * in memory for this one call, then dropped (never logged, never stored). */
49
+ readonly apiKey: string;
50
+ readonly systemPrompt: string;
51
+ readonly userPrompt: string;
52
+ readonly tags?: RunTags;
53
+ readonly maxOutputTokens?: number;
54
+ /** CE-6 sampling on the raw lane (spec §2). `temperature`/`topP` are the raw
55
+ * lane's exposure of the same knobs `RoutePolicy.sampling` gives the routed
56
+ * lane; `maxOutputTokens` above already existed. Absent ⇒ byte-identical raw
57
+ * dispatch (the params were previously dropped, per the header note). */
58
+ readonly temperature?: number;
59
+ readonly topP?: number;
60
+ readonly timeoutMs?: number;
61
+ readonly tools?: readonly ToolDefinition[];
62
+ readonly toolChoice?: ToolChoice;
63
+ /** CE-1 customer cache-handle pass-through on the Lane-B seam (spec §1.3
64
+ * success metric: "…passes its existing cachedContent handle through
65
+ * rig.run/runRaw"). The raw lane has exactly ONE provider (`provider` above),
66
+ * so the handle is unconditionally for it — no provider matching. Forwarded
67
+ * verbatim to `AdapterRequest.cache`; ModelRig never manages the resource. The
68
+ * stamped row carries the customer key with a null `prefix_fingerprint` (the
69
+ * raw lane runs no WS-C stamping), so provenance reads `customer` by the
70
+ * derivation rule. */
71
+ readonly cache?: {
72
+ readonly key: string;
73
+ readonly ttlSeconds?: number;
74
+ };
75
+ /** CE-2 F1 — native provider grounding on the raw lane (spec §3 F1). Object
76
+ * form so `"inject"` can join later without reshaping; v1 accepts ONLY
77
+ * `"native"`, which maps to `AdapterRequest.grounding = true`. GEMINI-ONLY in
78
+ * v1: declared on any other provider throws `RigFailureError`
79
+ * `invariant_violation` pre-dispatch (`assertRawKnobsSupported`). Interplay
80
+ * with `cache.key`: no code needed here — the gemini adapter's `cachedContent`
81
+ * path excludes tools (the googleSearch tool is expected to be baked into the
82
+ * customer's cache resource at creation). */
83
+ readonly grounding?: {
84
+ readonly mode: "native";
85
+ };
86
+ /** CE-2 F2 — service tier on the raw lane (spec §3 F2). Forwarded to
87
+ * `AdapterRequest.requestedTier` (default `"standard"`). ModelRig does NOT
88
+ * perform flex→standard degrade on the raw lane — a capacity rejection
89
+ * surfaces CLASSIFIED (`capacity_shed`) and the customer's own ladder retries
90
+ * at `"standard"`. `meta.servedTier`/`meta.requestedTier` report the truth. */
91
+ readonly serviceTier?: ServiceTier;
92
+ /** CE-2 F3 — reasoning/thinking effort on the raw lane (spec §3 F3). Absent ⇒
93
+ * byte-identical (gemini keeps its hardcoded `"high"`). GEMINI-ONLY in v1 (and
94
+ * only on a thinking-capable model): declared on any other provider throws
95
+ * pre-dispatch (`assertRawKnobsSupported`); declared on a non-thinking gemini
96
+ * model is rejected classified by the adapter (`geminiReasoningUnsupported`). */
97
+ readonly reasoning?: ReasoningParams;
98
+ }
99
+ export interface RawRunDeps {
100
+ readonly telemetry: TelemetryStore;
101
+ /** Mirrors RunDeps: the conservative per-MTok rate for an unpriced model.
102
+ * Used only to keep `attemptCost` honest — the raw lane has no envelope, so
103
+ * it never charges the unpriced fallback; a missing price records `$0`. */
104
+ readonly unpricedRateUsdPerMTok?: number;
105
+ }
106
+ /**
107
+ * CE-2 fail-closed guard (spec §3 F1/F3). A DECLARED directive is NEVER silently
108
+ * dropped: `grounding`/`reasoning` on a provider that cannot honor it — or a
109
+ * `grounding.mode` other than the v1-supported `"native"` — throws
110
+ * `RigFailureError` `invariant_violation` (the existing TERMINAL class; no new
111
+ * FailureClass member, spec §3 rationale) BEFORE any adapter is built, any
112
+ * provider call is made, or any telemetry row is written. Exported so the guard
113
+ * is unit-testable without a network. Idempotent and side-effect-free.
114
+ */
115
+ export declare function assertRawKnobsSupported(input: RawRunInput): void;
116
+ /** Pure raw-lane request shaping — exported for unit tests (no network). */
117
+ export declare function buildRawRequest(candidate: CandidateRef, input: RawRunInput): AdapterRequest;
118
+ /** Buffered raw dispatch (spec §4.2). Records telemetry, returns the RunResult,
119
+ * or throws `RigFailureError` on an adapter failure. */
120
+ export declare function runRaw(deps: RawRunDeps, input: RawRunInput): Promise<RunResult>;
121
+ /**
122
+ * Streaming raw dispatch (spec §4.3, "raw lane: true streaming, deltas passed
123
+ * through"). Drains the adapter's own stream when it has one, forwarding raw
124
+ * text deltas, and emits a single terminal `final` RunResult; adapters without
125
+ * `stream` (anthropic/gemini) fall back to a buffered `call()` with no deltas.
126
+ * There is NO terminal-validation event — that is a structured-route concept;
127
+ * the raw lane has no schema and the streamed bytes ARE the answer.
128
+ */
129
+ export declare function runRawStream(deps: RawRunDeps, input: RawRunInput): RunStreamHandle;
130
+ //# sourceMappingURL=raw.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"raw.d.ts","sourceRoot":"","sources":["../../src/run/raw.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAYH,OAAO,KAAK,EACV,cAAc,EAGd,YAAY,EAGZ,UAAU,EACV,eAAe,EACf,WAAW,EACX,UAAU,EACV,cAAc,EACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAW,SAAS,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,KAAK,EAAkB,eAAe,EAAE,MAAM,UAAU,CAAC;AAChE,OAAO,KAAK,EAAgB,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEvE;;;sCAGsC;AACtC,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;IAC9B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;iFAC6E;IAC7E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC;;;6EAGyE;IACzE,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,cAAc,EAAE,CAAC;IAC3C,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;IACjC;;;;;;;0BAOsB;IACtB,QAAQ,CAAC,KAAK,CAAC,EAAE;QAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACxE;;;;;;;iDAO6C;IAC7C,QAAQ,CAAC,SAAS,CAAC,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAA;KAAE,CAAC;IACjD;;;;mFAI+E;IAC/E,QAAQ,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC;IACnC;;;;qFAIiF;IACjF,QAAQ,CAAC,SAAS,CAAC,EAAE,eAAe,CAAC;CACtC;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC;IACnC;;+EAE2E;IAC3E,QAAQ,CAAC,sBAAsB,CAAC,EAAE,MAAM,CAAC;CAC1C;AAkDD;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,CAiChE;AAED,4EAA4E;AAC5E,wBAAgB,eAAe,CAAC,SAAS,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,GAAG,cAAc,CAiC3F;AAsJD;wDACwD;AACxD,wBAAsB,MAAM,CAAC,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,CAAC,CASrF;AAcD;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,GAAG,eAAe,CA6ClF"}