@mupt-ai/dari-gateway 0.1.0 → 0.2.1

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 (369) hide show
  1. package/README.md +8 -1
  2. package/dist/bun.d.ts +2 -0
  3. package/dist/bun.js +4 -0
  4. package/dist/context/eval_catalog.d.ts +3 -0
  5. package/dist/context/eval_catalog.js +7 -0
  6. package/dist/context/interaction_fingerprint.d.ts +27 -0
  7. package/dist/context/interaction_fingerprint.js +519 -0
  8. package/dist/context/interaction_fingerprint_format.d.ts +42 -0
  9. package/dist/context/interaction_fingerprint_format.js +113 -0
  10. package/dist/context/interaction_lease_depth.d.ts +2 -0
  11. package/dist/context/interaction_lease_depth.js +110 -0
  12. package/dist/context/lease_history.d.ts +7 -0
  13. package/dist/context/lease_history.js +158 -0
  14. package/dist/context/pricing.d.ts +4 -0
  15. package/dist/context/pricing.js +23 -0
  16. package/dist/context/provider_prompt_accounting.d.ts +14 -0
  17. package/dist/context/provider_prompt_accounting.js +187 -0
  18. package/dist/context/routing_context.d.ts +40 -0
  19. package/dist/context/routing_context.js +211 -0
  20. package/dist/http/auth.d.ts +2 -0
  21. package/dist/http/auth.js +35 -0
  22. package/dist/http/errors.d.ts +19 -0
  23. package/dist/http/errors.js +89 -0
  24. package/dist/http/handler.d.ts +12 -0
  25. package/dist/http/handler.js +81 -0
  26. package/dist/http/http2_server.d.ts +6 -0
  27. package/dist/http/http2_server.js +103 -0
  28. package/dist/http/serve.d.ts +20 -0
  29. package/dist/http/serve.js +78 -0
  30. package/dist/index.d.ts +6 -0
  31. package/dist/index.js +8 -0
  32. package/dist/ingress/anthropic_messages.d.ts +3 -0
  33. package/dist/ingress/anthropic_messages.js +122 -0
  34. package/dist/ingress/anthropic_models.d.ts +1 -0
  35. package/dist/ingress/anthropic_models.js +23 -0
  36. package/dist/ingress/chat_completions.d.ts +2 -0
  37. package/dist/ingress/chat_completions.js +37 -0
  38. package/dist/ingress/claude_code/request_context.d.ts +2 -0
  39. package/dist/ingress/claude_code/request_context.js +31 -0
  40. package/dist/ingress/codex.d.ts +3 -0
  41. package/dist/ingress/codex.js +65 -0
  42. package/dist/ingress/codex_models.d.ts +2 -0
  43. package/dist/ingress/codex_models.js +89 -0
  44. package/dist/ingress/json.d.ts +1 -0
  45. package/dist/ingress/json.js +95 -0
  46. package/dist/ingress/models.d.ts +1 -0
  47. package/dist/ingress/models.js +53 -0
  48. package/dist/interaction/capabilities.d.ts +3 -0
  49. package/dist/interaction/capabilities.js +24 -0
  50. package/dist/interaction/image.d.ts +4 -0
  51. package/dist/interaction/image.js +13 -0
  52. package/dist/interaction/portable_reasoning_state.d.ts +4 -0
  53. package/dist/interaction/portable_reasoning_state.js +18 -0
  54. package/dist/interaction/provider_continuation_state.d.ts +6 -0
  55. package/dist/interaction/provider_continuation_state.js +27 -0
  56. package/dist/interaction/tool_identity.d.ts +10 -0
  57. package/dist/interaction/tool_identity.js +41 -0
  58. package/dist/interaction/types.d.ts +203 -0
  59. package/dist/interaction/types.js +5 -0
  60. package/dist/models/context_limits.d.ts +2 -0
  61. package/dist/models/context_limits.js +7 -0
  62. package/dist/models/execution_provider.d.ts +8 -0
  63. package/dist/models/execution_provider.js +13 -0
  64. package/dist/models/gateways.d.ts +11 -0
  65. package/dist/models/gateways.js +45 -0
  66. package/dist/models/ids.d.ts +1 -0
  67. package/dist/models/ids.js +15 -0
  68. package/dist/models/provider_defaults.d.ts +4 -0
  69. package/dist/models/provider_defaults.js +41 -0
  70. package/dist/models/runtime_overrides.d.ts +4 -0
  71. package/dist/models/runtime_overrides.js +209 -0
  72. package/dist/observability/errors.d.ts +8 -0
  73. package/dist/observability/errors.js +11 -0
  74. package/dist/platform/platform.d.ts +152 -0
  75. package/dist/platform/platform.js +11 -0
  76. package/dist/platform/routing_contract.d.ts +2 -0
  77. package/dist/platform/routing_contract.js +5 -0
  78. package/dist/protocol/input/anthropic_messages.d.ts +2 -0
  79. package/dist/protocol/input/anthropic_messages.js +494 -0
  80. package/dist/protocol/input/chat_completions.d.ts +4 -0
  81. package/dist/protocol/input/chat_completions.js +212 -0
  82. package/dist/protocol/input/chat_completions_validation.d.ts +2 -0
  83. package/dist/protocol/input/chat_completions_validation.js +257 -0
  84. package/dist/protocol/input/openai_responses.d.ts +2 -0
  85. package/dist/protocol/input/openai_responses.js +666 -0
  86. package/dist/protocol/input/router_model.d.ts +7 -0
  87. package/dist/protocol/input/router_model.js +43 -0
  88. package/dist/protocol/output/anthropic_messages.d.ts +10 -0
  89. package/dist/protocol/output/anthropic_messages.js +15 -0
  90. package/dist/protocol/output/anthropic_messages_output.d.ts +10 -0
  91. package/dist/protocol/output/anthropic_messages_output.js +124 -0
  92. package/dist/protocol/output/anthropic_messages_stream.d.ts +16 -0
  93. package/dist/protocol/output/anthropic_messages_stream.js +267 -0
  94. package/dist/protocol/output/chat_completions.d.ts +29 -0
  95. package/dist/protocol/output/chat_completions.js +406 -0
  96. package/dist/protocol/output/chat_reasoning_detail.d.ts +2 -0
  97. package/dist/protocol/output/chat_reasoning_detail.js +13 -0
  98. package/dist/protocol/output/delivered_stream_snapshot.d.ts +10 -0
  99. package/dist/protocol/output/delivered_stream_snapshot.js +31 -0
  100. package/dist/protocol/output/openai_responses.d.ts +10 -0
  101. package/dist/protocol/output/openai_responses.js +14 -0
  102. package/dist/protocol/output/openai_responses_output.d.ts +14 -0
  103. package/dist/protocol/output/openai_responses_output.js +125 -0
  104. package/dist/protocol/output/openai_responses_stream.d.ts +18 -0
  105. package/dist/protocol/output/openai_responses_stream.js +546 -0
  106. package/dist/protocol/output/sse_stream.d.ts +31 -0
  107. package/dist/protocol/output/sse_stream.js +67 -0
  108. package/dist/providers/anthropic_safeguards.d.ts +11 -0
  109. package/dist/providers/anthropic_safeguards.js +81 -0
  110. package/dist/providers/aws_assume_role.d.ts +17 -0
  111. package/dist/providers/aws_assume_role.js +107 -0
  112. package/dist/providers/cancel_estimate.d.ts +43 -0
  113. package/dist/providers/cancel_estimate.js +89 -0
  114. package/dist/providers/execution.d.ts +72 -0
  115. package/dist/providers/execution.js +491 -0
  116. package/dist/providers/model_capabilities.d.ts +11 -0
  117. package/dist/providers/model_capabilities.js +29 -0
  118. package/dist/providers/pi.d.ts +65 -0
  119. package/dist/providers/pi.js +319 -0
  120. package/dist/providers/pi_context.d.ts +7 -0
  121. package/dist/providers/pi_context.js +405 -0
  122. package/dist/providers/pi_options.d.ts +11 -0
  123. package/dist/providers/pi_options.js +398 -0
  124. package/dist/providers/pi_output.d.ts +2 -0
  125. package/dist/providers/pi_output.js +453 -0
  126. package/dist/providers/provider_attempt_runner.d.ts +55 -0
  127. package/dist/providers/provider_attempt_runner.js +90 -0
  128. package/dist/providers/provider_call.d.ts +77 -0
  129. package/dist/providers/provider_call.js +292 -0
  130. package/dist/providers/provider_reported_cost.d.ts +10 -0
  131. package/dist/providers/provider_reported_cost.js +123 -0
  132. package/dist/providers/reasoning.d.ts +12 -0
  133. package/dist/providers/reasoning.js +30 -0
  134. package/dist/providers/response_capture.d.ts +23 -0
  135. package/dist/providers/response_capture.js +47 -0
  136. package/dist/providers/stream_finalization.d.ts +46 -0
  137. package/dist/providers/stream_finalization.js +165 -0
  138. package/dist/providers/subscription_limits.d.ts +31 -0
  139. package/dist/providers/subscription_limits.js +163 -0
  140. package/dist/providers/subscription_usage.d.ts +10 -0
  141. package/dist/providers/subscription_usage.js +79 -0
  142. package/dist/runtime/claude_code/auxiliary_routing.d.ts +3 -0
  143. package/dist/runtime/claude_code/auxiliary_routing.js +60 -0
  144. package/dist/runtime/customer_disconnect.d.ts +20 -0
  145. package/dist/runtime/customer_disconnect.js +49 -0
  146. package/dist/runtime/explicit_model.d.ts +4 -0
  147. package/dist/runtime/explicit_model.js +53 -0
  148. package/dist/runtime/harness_identity/conversation.d.ts +33 -0
  149. package/dist/runtime/harness_identity/conversation.js +39 -0
  150. package/dist/runtime/harness_identity/extract.d.ts +8 -0
  151. package/dist/runtime/harness_identity/extract.js +214 -0
  152. package/dist/runtime/harness_identity/index.d.ts +2 -0
  153. package/dist/runtime/harness_identity/index.js +2 -0
  154. package/dist/runtime/prepare_routed_completion.d.ts +33 -0
  155. package/dist/runtime/prepare_routed_completion.js +167 -0
  156. package/dist/runtime/provider_stream_lifecycle.d.ts +31 -0
  157. package/dist/runtime/provider_stream_lifecycle.js +88 -0
  158. package/dist/runtime/provider_stream_outcome.d.ts +23 -0
  159. package/dist/runtime/provider_stream_outcome.js +55 -0
  160. package/dist/runtime/request_tags.d.ts +7 -0
  161. package/dist/runtime/request_tags.js +33 -0
  162. package/dist/runtime/routed_completion.d.ts +17 -0
  163. package/dist/runtime/routed_completion.js +80 -0
  164. package/dist/runtime/routed_protocol.d.ts +30 -0
  165. package/dist/runtime/routed_protocol.js +1 -0
  166. package/dist/runtime/routed_runtime.d.ts +40 -0
  167. package/dist/runtime/routed_runtime.js +535 -0
  168. package/dist/runtime/routing_lease.d.ts +26 -0
  169. package/dist/runtime/routing_lease.js +210 -0
  170. package/dist/runtime/runtime_reporter.d.ts +71 -0
  171. package/dist/runtime/runtime_reporter.js +35 -0
  172. package/dist/self_host/config.d.ts +46 -0
  173. package/dist/self_host/config.js +105 -0
  174. package/dist/self_host/main.d.ts +16 -0
  175. package/dist/self_host/main.js +95 -0
  176. package/dist/self_host/platform.d.ts +13 -0
  177. package/dist/self_host/platform.js +50 -0
  178. package/dist/self_host/prefix_store.d.ts +46 -0
  179. package/dist/self_host/prefix_store.js +261 -0
  180. package/dist/self_host/resolve.d.ts +28 -0
  181. package/dist/self_host/resolve.js +171 -0
  182. package/dist/self_host/subscriptions/access.d.ts +10 -0
  183. package/dist/self_host/subscriptions/access.js +37 -0
  184. package/dist/self_host/subscriptions/http.d.ts +15 -0
  185. package/dist/self_host/subscriptions/http.js +187 -0
  186. package/dist/self_host/subscriptions/index.d.ts +24 -0
  187. package/dist/self_host/subscriptions/index.js +24 -0
  188. package/dist/self_host/subscriptions/oauth.d.ts +55 -0
  189. package/dist/self_host/subscriptions/oauth.js +281 -0
  190. package/dist/self_host/subscriptions/store.d.ts +78 -0
  191. package/dist/self_host/subscriptions/store.js +235 -0
  192. package/dist/strategies/auto_routing_selector.d.ts +12 -0
  193. package/dist/strategies/auto_routing_selector.js +61 -0
  194. package/dist/strategies/eval_relevance.d.ts +17 -0
  195. package/dist/strategies/eval_relevance.js +32 -0
  196. package/dist/strategies/fallback_decision.d.ts +8 -0
  197. package/dist/strategies/fallback_decision.js +17 -0
  198. package/dist/strategies/priority_selector.d.ts +7 -0
  199. package/dist/strategies/priority_selector.js +37 -0
  200. package/dist/strategies/route_decision.d.ts +22 -0
  201. package/dist/strategies/route_decision.js +65 -0
  202. package/dist/strategies/routing.d.ts +74 -0
  203. package/dist/strategies/routing.js +280 -0
  204. package/dist/strategies/selector_projection.d.ts +15 -0
  205. package/dist/strategies/selector_projection.js +161 -0
  206. package/dist/telemetry/background.d.ts +7 -0
  207. package/dist/telemetry/background.js +33 -0
  208. package/dist/telemetry/benchmark_replay.d.ts +37 -0
  209. package/dist/telemetry/benchmark_replay.js +108 -0
  210. package/dist/telemetry/billing_finalization.d.ts +64 -0
  211. package/dist/telemetry/billing_finalization.js +96 -0
  212. package/dist/telemetry/ingest_values.d.ts +4 -0
  213. package/dist/telemetry/ingest_values.js +12 -0
  214. package/dist/telemetry/model_cost.d.ts +3 -0
  215. package/dist/telemetry/model_cost.js +15 -0
  216. package/dist/telemetry/prefix_state.d.ts +47 -0
  217. package/dist/telemetry/prefix_state.js +116 -0
  218. package/dist/telemetry/report.d.ts +88 -0
  219. package/dist/telemetry/report.js +621 -0
  220. package/dist/telemetry/requests/interaction_observability.d.ts +45 -0
  221. package/dist/telemetry/requests/interaction_observability.js +180 -0
  222. package/dist/telemetry/requests/retained_interaction_request.d.ts +8 -0
  223. package/dist/telemetry/requests/retained_interaction_request.js +10 -0
  224. package/dist/telemetry/scrub.d.ts +2 -0
  225. package/dist/telemetry/scrub.js +31 -0
  226. package/dist/telemetry/skills/claude/catalog.d.ts +6 -0
  227. package/dist/telemetry/skills/claude/catalog.js +99 -0
  228. package/dist/telemetry/skills/claude/file_reads.d.ts +4 -0
  229. package/dist/telemetry/skills/claude/file_reads.js +110 -0
  230. package/dist/telemetry/skills/claude/observations.d.ts +3 -0
  231. package/dist/telemetry/skills/claude/observations.js +366 -0
  232. package/dist/telemetry/skills/codex/catalog.d.ts +11 -0
  233. package/dist/telemetry/skills/codex/catalog.js +138 -0
  234. package/dist/telemetry/skills/codex/exec_file_reads.d.ts +9 -0
  235. package/dist/telemetry/skills/codex/exec_file_reads.js +36 -0
  236. package/dist/telemetry/skills/codex/explicit.d.ts +3 -0
  237. package/dist/telemetry/skills/codex/explicit.js +90 -0
  238. package/dist/telemetry/skills/codex/file_reads.d.ts +4 -0
  239. package/dist/telemetry/skills/codex/file_reads.js +37 -0
  240. package/dist/telemetry/skills/codex/identity.d.ts +2 -0
  241. package/dist/telemetry/skills/codex/identity.js +20 -0
  242. package/dist/telemetry/skills/observations.d.ts +21 -0
  243. package/dist/telemetry/skills/observations.js +41 -0
  244. package/dist/telemetry/skills/paths.d.ts +11 -0
  245. package/dist/telemetry/skills/paths.js +61 -0
  246. package/dist/telemetry/skills/pi.d.ts +6 -0
  247. package/dist/telemetry/skills/pi.js +223 -0
  248. package/dist/telemetry/skills/shell_file_reads.d.ts +7 -0
  249. package/dist/telemetry/skills/shell_file_reads.js +226 -0
  250. package/dist/telemetry/skills/shell_words.d.ts +13 -0
  251. package/dist/telemetry/skills/shell_words.js +189 -0
  252. package/dist/telemetry/tools/input.d.ts +2 -0
  253. package/dist/telemetry/tools/input.js +14 -0
  254. package/dist/telemetry/tools/observations.d.ts +29 -0
  255. package/dist/telemetry/tools/observations.js +247 -0
  256. package/dist/telemetry/usage.d.ts +57 -0
  257. package/dist/telemetry/usage.js +136 -0
  258. package/dist/types.d.ts +94 -0
  259. package/dist/types.js +1 -0
  260. package/package.json +22 -5
  261. package/src/bun.ts +4 -0
  262. package/src/context/eval_catalog.ts +1 -1
  263. package/src/context/interaction_fingerprint.ts +9 -9
  264. package/src/context/interaction_fingerprint_format.ts +1 -1
  265. package/src/context/interaction_lease_depth.ts +1 -1
  266. package/src/context/pricing.ts +1 -1
  267. package/src/context/provider_prompt_accounting.ts +5 -5
  268. package/src/context/routing_context.ts +17 -17
  269. package/src/http/auth.ts +1 -1
  270. package/src/http/handler.ts +8 -8
  271. package/src/http/serve.ts +3 -3
  272. package/src/index.ts +10 -9
  273. package/src/ingress/anthropic_messages.ts +12 -12
  274. package/src/ingress/anthropic_models.ts +1 -1
  275. package/src/ingress/chat_completions.ts +9 -9
  276. package/src/ingress/claude_code/request_context.ts +2 -2
  277. package/src/ingress/codex.ts +10 -10
  278. package/src/ingress/codex_models.ts +4 -4
  279. package/src/ingress/json.ts +1 -1
  280. package/src/ingress/models.ts +10 -10
  281. package/src/interaction/capabilities.ts +1 -1
  282. package/src/interaction/portable_reasoning_state.ts +1 -1
  283. package/src/interaction/provider_continuation_state.ts +1 -1
  284. package/src/interaction/tool_identity.ts +2 -2
  285. package/src/interaction/types.ts +3 -0
  286. package/src/models/context_limits.ts +1 -1
  287. package/src/models/execution_provider.ts +1 -1
  288. package/src/models/ids.ts +1 -1
  289. package/src/models/provider_defaults.ts +1 -1
  290. package/src/models/runtime_overrides.ts +1 -1
  291. package/src/observability/errors.ts +2 -2
  292. package/src/platform/platform.ts +36 -4
  293. package/src/protocol/input/anthropic_messages.ts +7 -7
  294. package/src/protocol/input/chat_completions.ts +5 -5
  295. package/src/protocol/input/chat_completions_validation.ts +4 -4
  296. package/src/protocol/input/openai_responses.ts +6 -6
  297. package/src/protocol/output/anthropic_messages.ts +3 -3
  298. package/src/protocol/output/anthropic_messages_output.ts +6 -4
  299. package/src/protocol/output/anthropic_messages_stream.ts +7 -7
  300. package/src/protocol/output/chat_completions.ts +13 -13
  301. package/src/protocol/output/chat_reasoning_detail.ts +1 -1
  302. package/src/protocol/output/openai_responses.ts +3 -3
  303. package/src/protocol/output/openai_responses_output.ts +4 -2
  304. package/src/protocol/output/openai_responses_stream.ts +6 -6
  305. package/src/protocol/output/sse_stream.ts +3 -3
  306. package/src/providers/anthropic_safeguards.ts +2 -2
  307. package/src/providers/aws_assume_role.ts +2 -2
  308. package/src/providers/cancel_estimate.ts +1 -1
  309. package/src/providers/execution.ts +17 -17
  310. package/src/providers/pi.ts +115 -41
  311. package/src/providers/pi_context.ts +6 -6
  312. package/src/providers/pi_options.ts +283 -453
  313. package/src/providers/pi_output.ts +6 -5
  314. package/src/providers/provider_attempt_runner.ts +1 -1
  315. package/src/providers/provider_call.ts +37 -18
  316. package/src/providers/provider_reported_cost.ts +138 -0
  317. package/src/providers/reasoning.ts +2 -2
  318. package/src/providers/stream_finalization.ts +10 -10
  319. package/src/providers/subscription_limits.ts +3 -3
  320. package/src/runtime/claude_code/auxiliary_routing.ts +5 -5
  321. package/src/runtime/customer_disconnect.ts +1 -1
  322. package/src/runtime/explicit_model.ts +31 -4
  323. package/src/runtime/harness_identity/conversation.ts +1 -1
  324. package/src/runtime/harness_identity/extract.ts +3 -3
  325. package/src/runtime/harness_identity/index.ts +2 -2
  326. package/src/runtime/prepare_routed_completion.ts +46 -10
  327. package/src/runtime/provider_stream_lifecycle.ts +1 -1
  328. package/src/runtime/provider_stream_outcome.ts +2 -2
  329. package/src/runtime/request_tags.ts +34 -0
  330. package/src/runtime/routed_completion.ts +13 -11
  331. package/src/runtime/routed_protocol.ts +2 -2
  332. package/src/runtime/routed_runtime.ts +38 -20
  333. package/src/runtime/routing_lease.ts +7 -7
  334. package/src/runtime/runtime_reporter.ts +3 -3
  335. package/src/self_host/main.ts +19 -14
  336. package/src/self_host/platform.ts +5 -5
  337. package/src/self_host/prefix_store.ts +2 -2
  338. package/src/self_host/resolve.ts +11 -11
  339. package/src/self_host/subscriptions/access.ts +2 -2
  340. package/src/self_host/subscriptions/http.ts +2 -2
  341. package/src/self_host/subscriptions/index.ts +4 -4
  342. package/src/self_host/subscriptions/store.ts +1 -1
  343. package/src/strategies/auto_routing_selector.ts +2 -2
  344. package/src/strategies/eval_relevance.ts +3 -3
  345. package/src/strategies/priority_selector.ts +1 -1
  346. package/src/strategies/route_decision.ts +7 -7
  347. package/src/strategies/routing.ts +11 -11
  348. package/src/strategies/selector_projection.ts +2 -2
  349. package/src/telemetry/billing_finalization.ts +3 -3
  350. package/src/telemetry/model_cost.ts +1 -1
  351. package/src/telemetry/prefix_state.ts +4 -4
  352. package/src/telemetry/report.ts +30 -25
  353. package/src/telemetry/requests/interaction_observability.ts +1 -1
  354. package/src/telemetry/requests/retained_interaction_request.ts +1 -1
  355. package/src/telemetry/skills/claude/catalog.ts +1 -1
  356. package/src/telemetry/skills/claude/file_reads.ts +6 -6
  357. package/src/telemetry/skills/claude/observations.ts +3 -3
  358. package/src/telemetry/skills/codex/catalog.ts +3 -3
  359. package/src/telemetry/skills/codex/exec_file_reads.ts +4 -4
  360. package/src/telemetry/skills/codex/explicit.ts +3 -3
  361. package/src/telemetry/skills/codex/file_reads.ts +5 -5
  362. package/src/telemetry/skills/observations.ts +7 -7
  363. package/src/telemetry/skills/pi.ts +3 -3
  364. package/src/telemetry/skills/shell_file_reads.ts +2 -2
  365. package/src/telemetry/skills/shell_words.ts +1 -1
  366. package/src/telemetry/tools/input.ts +1 -1
  367. package/src/telemetry/tools/observations.ts +9 -9
  368. package/src/telemetry/usage.ts +9 -5
  369. package/src/types.ts +15 -0
@@ -0,0 +1,405 @@
1
+ import { encodeOpenAIReasoningSignature } from "@mupt-ai/dari-router/protocols";
2
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
3
+ import { HttpError } from "../http/errors.js";
4
+ import { parseDataImageUrl } from "../interaction/image.js";
5
+ import { providerToolCallId, toolWireName } from "../interaction/tool_identity.js";
6
+ import { compatibleProviderContinuation, sameProviderIdentity, } from "../interaction/provider_continuation_state.js";
7
+ import { isOpenAIResponsesApi } from "./model_capabilities.js";
8
+ const UNKNOWN_SOURCE = {
9
+ provider: "dari",
10
+ api: "interaction-history",
11
+ model: "unknown",
12
+ };
13
+ export function buildContext(request, target) {
14
+ const systemParts = request.instructions ? [request.instructions] : [];
15
+ const messages = [];
16
+ const toolCalls = new Map();
17
+ const timestamp = Date.now();
18
+ let pending = null;
19
+ let sawConversationItem = false;
20
+ const flushAssistant = () => {
21
+ if (!pending)
22
+ return;
23
+ if (pending.content.length === 0)
24
+ pending.content.push({ type: "text", text: "" });
25
+ pending.stopReason = pending.content.some((part) => part.type === "toolCall") ? "toolUse" : "stop";
26
+ messages.push(pending);
27
+ pending = null;
28
+ };
29
+ const assistantFor = (source) => {
30
+ if (pending && !sameProviderIdentity(pending, source))
31
+ flushAssistant();
32
+ pending ??= {
33
+ role: "assistant",
34
+ content: [],
35
+ ...source,
36
+ usage: zeroUsage(),
37
+ stopReason: "stop",
38
+ timestamp,
39
+ };
40
+ return pending;
41
+ };
42
+ const assistantForReasoning = (source) => {
43
+ // Codex can persist a streamed tool call before reasoning recovered from
44
+ // the terminal response. Both items still belong to one assistant turn.
45
+ if (pending && sameProviderIdentity(pending, UNKNOWN_SOURCE)) {
46
+ pending.provider = source.provider;
47
+ pending.api = source.api;
48
+ pending.model = source.model;
49
+ }
50
+ return assistantFor(source);
51
+ };
52
+ for (const [itemIndex, item] of request.items.entries()) {
53
+ if (item.type === "message" && (item.role === "system" || item.role === "developer")) {
54
+ flushAssistant();
55
+ const text = readableContent(item.content);
56
+ if (!text)
57
+ continue;
58
+ if (!sawConversationItem) {
59
+ // Leading preamble is identical on every request, so folding it into
60
+ // the system prompt keeps the provider payload prefix stable.
61
+ systemParts.push(text);
62
+ continue;
63
+ }
64
+ // Mid-conversation system/developer notes arrive between turns (Claude
65
+ // Code appends a `<total_tokens>` reminder after every tool result).
66
+ // Folding them into the system prompt mutates the front of the provider
67
+ // payload, so prefix-matching prompt caches miss and re-write the whole
68
+ // conversation at cache-write prices. Keep them positional instead.
69
+ appendPositionalNote(messages, text, timestamp);
70
+ continue;
71
+ }
72
+ sawConversationItem = true;
73
+ if (item.type === "message" && item.role === "user") {
74
+ flushAssistant();
75
+ appendUserMessage(messages, userContent(item.content, item.contentShape), timestamp);
76
+ continue;
77
+ }
78
+ if (item.type === "tool_result") {
79
+ flushAssistant();
80
+ const call = toolCalls.get(item.callId);
81
+ messages.push({
82
+ role: "toolResult",
83
+ toolCallId: call?.id ?? item.callId,
84
+ toolName: call?.name ?? item.name ?? "tool",
85
+ content: toolResultContent(item.output, target),
86
+ isError: item.isError ?? false,
87
+ timestamp,
88
+ ...(item.loadedTools?.length ? { addedToolNames: [...item.loadedTools] } : {}),
89
+ });
90
+ continue;
91
+ }
92
+ if (item.type === "reasoning_configuration") {
93
+ if (!isOpenAIResponsesApi(target.api)) {
94
+ throw new HttpError(400, "Reasoning configuration updates require a GPT-6 Responses model.", "unsupported_reasoning_configuration", "input");
95
+ }
96
+ const assistant = assistantFor(target);
97
+ assistant.content.push({
98
+ type: "providerItem",
99
+ item: {
100
+ type: "configuration_update",
101
+ reasoning: { effort: item.effort === "off" ? "none" : item.effort },
102
+ },
103
+ name: "providerItem",
104
+ arguments: {},
105
+ });
106
+ continue;
107
+ }
108
+ if (item.type === "reasoning") {
109
+ const continuation = compatibleProviderContinuation(item.continuation, target);
110
+ if (continuation) {
111
+ const assistant = assistantForReasoning(continuation.source);
112
+ const firstNonReasoning = assistant.content.findIndex((content) => content.type !== "thinking");
113
+ assistant.content.splice(firstNonReasoning === -1 ? assistant.content.length : firstNonReasoning, 0, thinkingContent(item, continuation));
114
+ // Managed-effort Claude models bind each thinking block to the prefix
115
+ // it was generated under, which ended in an effort marker. Pi only
116
+ // re-inserts that marker before turns that carry their level; without
117
+ // it the API silently drops the replayed block.
118
+ if (continuation.kind !== "openai_reasoning" && continuation.effort !== undefined) {
119
+ assistant.providerThinkingLevel = continuation.effort;
120
+ }
121
+ }
122
+ else {
123
+ const readable = [...item.summary, ...item.content].join("\n");
124
+ if (readable) {
125
+ const assistant = assistantForReasoning(item.source ?? item.continuation?.source ?? UNKNOWN_SOURCE);
126
+ const firstToolCall = assistant.content.findIndex((content) => content.type === "toolCall");
127
+ assistant.content.splice(firstToolCall === -1 ? assistant.content.length : firstToolCall, 0, {
128
+ type: "text",
129
+ text: portableReasoningText(request.items, itemIndex, readable, target),
130
+ });
131
+ }
132
+ }
133
+ continue;
134
+ }
135
+ if (item.type === "tool_call") {
136
+ const assistant = assistantFor(pending ? identityOf(pending) : UNKNOWN_SOURCE);
137
+ const id = providerToolCallId(item.callId, item.id, target.api);
138
+ const name = toolWireName(item.namespace, item.name);
139
+ assistant.content.push({
140
+ type: "toolCall",
141
+ id,
142
+ name,
143
+ arguments: toolArguments(item.kind, item.input),
144
+ });
145
+ toolCalls.set(item.callId, { id, name });
146
+ continue;
147
+ }
148
+ if (item.type === "hosted_tool_call") {
149
+ if (item.tool === "server_tool_use" || item.tool === "tool_search") {
150
+ // Server tool use and tool search results are Anthropic-specific.
151
+ // Handle them before the generic OpenAI Responses branch to avoid
152
+ // emitting Anthropic-shaped payloads as Responses provider items.
153
+ if (target.api === "anthropic-messages") {
154
+ // Round-trip preservation when routing to Anthropic.
155
+ if (item.tool === "server_tool_use") {
156
+ const assistant = assistantFor(item.source ?? target);
157
+ assistant.content.push({
158
+ type: "serverToolCall",
159
+ id: item.serverToolUseId ?? item.id,
160
+ name: item.serverToolName ?? "tool",
161
+ arguments: item.serverToolInput ?? {},
162
+ });
163
+ }
164
+ else {
165
+ const assistant = assistantFor(item.source ?? target);
166
+ assistant.content.push({
167
+ type: "toolSearchResult",
168
+ toolUseId: item.serverToolUseId ?? item.id,
169
+ content: (item.serverToolResult ?? []).map((ref) => ({
170
+ type: "tool_reference",
171
+ tool_name: ref.toolName,
172
+ })),
173
+ });
174
+ }
175
+ }
176
+ else {
177
+ // Emit as text for non-Anthropic providers at reduced fidelity.
178
+ // Append to the current assistant turn to avoid splitting it with a
179
+ // fabricated user message.
180
+ const assistant = assistantFor(item.source ?? target);
181
+ assistant.content.push({
182
+ type: "text",
183
+ text: `[Server tool ${item.serverToolName ?? item.tool}: ${JSON.stringify(item.payload)}]`,
184
+ });
185
+ }
186
+ }
187
+ else if (isOpenAIResponsesApi(target.api)) {
188
+ const assistant = assistantFor(item.source ?? target);
189
+ assistant.content.push({
190
+ type: "providerItem",
191
+ item: item.payload,
192
+ // Pi's generic estimator treats non-text assistant blocks like tool calls.
193
+ // These compatibility fields stay in process; the Responses adapter emits only `item`.
194
+ name: "providerItem",
195
+ arguments: item.payload,
196
+ });
197
+ }
198
+ continue;
199
+ }
200
+ if (item.role === "assistant") {
201
+ const assistant = assistantFor(item.source ?? (pending ? identityOf(pending) : UNKNOWN_SOURCE));
202
+ for (const [contentIndex, content] of item.content.entries()) {
203
+ if (content.type === "text") {
204
+ const signatureId = item.id ?? (item.phase ? `msg_dari_${itemIndex}_${contentIndex}` : undefined);
205
+ assistant.content.push({
206
+ type: "text",
207
+ text: content.text,
208
+ ...(content.annotations?.length ? { annotations: content.annotations } : {}),
209
+ ...(signatureId ? { textSignature: textSignature(signatureId, item.phase) } : {}),
210
+ });
211
+ }
212
+ else {
213
+ assistant.content.push({ type: "text", text: "(assistant image omitted)" });
214
+ }
215
+ }
216
+ }
217
+ }
218
+ flushAssistant();
219
+ const context = { messages };
220
+ if (systemParts.length > 0)
221
+ context.systemPrompt = systemParts.join("\n\n");
222
+ const clientTools = request.tools.filter((tool) => tool.kind !== "hosted" && (tool.kind !== "server_tool" || target.api === "anthropic-messages"));
223
+ if (clientTools.length > 0)
224
+ context.tools = clientTools.map((tool) => toolToPi(tool, target.api));
225
+ return context;
226
+ }
227
+ function thinkingContent(item, continuation) {
228
+ if (continuation.kind === "openai_reasoning") {
229
+ const providerItemId = continuation.providerItemId ?? item.id;
230
+ return {
231
+ type: "thinking",
232
+ thinking: [...item.summary, ...item.content].join("\n"),
233
+ thinkingSignature: encodeOpenAIReasoningSignature({
234
+ ...(providerItemId ? { id: providerItemId } : {}),
235
+ summary: item.summary,
236
+ content: item.content,
237
+ encryptedContent: continuation.encryptedContent,
238
+ }),
239
+ };
240
+ }
241
+ if (continuation.kind === "anthropic_thinking") {
242
+ return {
243
+ type: "thinking",
244
+ thinking: continuation.thinking,
245
+ thinkingSignature: continuation.signature,
246
+ };
247
+ }
248
+ return {
249
+ type: "thinking",
250
+ thinking: "",
251
+ thinkingSignature: continuation.data,
252
+ redacted: true,
253
+ };
254
+ }
255
+ function userContent(content, shape) {
256
+ if (shape !== "parts")
257
+ return content.filter((part) => part.type === "text").map((part) => part.text).join("");
258
+ return content.map(contentToPi);
259
+ }
260
+ function appendPositionalNote(messages, text, timestamp) {
261
+ const previous = messages.at(-1);
262
+ if (previous?.role === "toolResult") {
263
+ previous.content = [...contentBlocks(previous.content), { type: "text", text }];
264
+ return;
265
+ }
266
+ appendUserMessage(messages, [{ type: "text", text }], timestamp);
267
+ }
268
+ function appendUserMessage(messages, content, timestamp) {
269
+ const previous = messages.at(-1);
270
+ if (previous?.role === "user") {
271
+ previous.content = [...contentBlocks(previous.content), ...contentBlocks(content)];
272
+ return;
273
+ }
274
+ messages.push({ role: "user", content, timestamp });
275
+ }
276
+ function contentBlocks(content) {
277
+ if (typeof content === "string")
278
+ return [{ type: "text", text: content }];
279
+ return Array.isArray(content) ? content : [];
280
+ }
281
+ function toolResultContent(content, target) {
282
+ if (content === null)
283
+ return [];
284
+ if (typeof content === "string")
285
+ return [{ type: "text", text: content }];
286
+ // Anthropic emits tool_reference parts natively via addedToolNames, so
287
+ // flattening them to synthetic text here would duplicate the names. Other
288
+ // providers have no native tool_reference representation, so keep the text
289
+ // fallback for them.
290
+ const filtered = target.api === "anthropic-messages"
291
+ ? content.filter((part) => part.type !== "tool_reference")
292
+ : content;
293
+ return filtered.map(contentToPi);
294
+ }
295
+ function contentToPi(content) {
296
+ if (content.type === "text")
297
+ return { type: "text", text: content.text };
298
+ if (content.type === "tool_reference")
299
+ return { type: "text", text: `Referenced tool: ${content.toolName}` };
300
+ const image = parseDataImageUrl(content.url);
301
+ if (!image) {
302
+ throw new HttpError(400, "Only base64 data URLs are supported for routed image input.", "invalid_request_error", "input.image_url");
303
+ }
304
+ return {
305
+ type: "image",
306
+ mimeType: image.mimeType,
307
+ data: image.data,
308
+ ...(content.detail !== undefined ? { detail: content.detail } : {}),
309
+ };
310
+ }
311
+ function portableReasoningText(items, itemIndex, readable, target) {
312
+ if (target.api !== "openai-completions")
313
+ return readable;
314
+ for (let index = itemIndex + 1; index < items.length; index += 1) {
315
+ const next = items[index];
316
+ if (next.type === "reasoning" || next.type === "tool_call")
317
+ continue;
318
+ if (next.type === "message" && next.role === "assistant") {
319
+ return next.content.some((part) => part.type === "text" && part.text.length > 0)
320
+ ? `${readable}\n\n`
321
+ : readable;
322
+ }
323
+ break;
324
+ }
325
+ return readable;
326
+ }
327
+ function readableContent(content) {
328
+ return content.map((part) => (part.type === "text" ? part.text : "(image omitted)")).join("\n");
329
+ }
330
+ function toolToPi(tool, targetApi) {
331
+ if (tool.kind === "client_tool" && targetApi === "anthropic-messages") {
332
+ return {
333
+ name: tool.name,
334
+ type: tool.type,
335
+ serverTool: true,
336
+ };
337
+ }
338
+ const result = {
339
+ name: (tool.kind === "server_tool" || tool.kind === "client_tool"
340
+ ? tool.name
341
+ : toolWireName(tool.namespace, tool.name)),
342
+ // Anthropic rejects description on server tool definitions as an extra input.
343
+ ...(tool.kind === "server_tool" ? {} : { description: tool.description ?? "" }),
344
+ };
345
+ if (tool.kind === "function") {
346
+ result.parameters = tool.parameters ?? { type: "object", properties: {} };
347
+ if (tool.deferLoading !== undefined)
348
+ result.deferLoading = tool.deferLoading;
349
+ }
350
+ else if (tool.kind === "server_tool") {
351
+ // Server tools are Anthropic-specific; Pi doesn't handle them. We pass
352
+ // the type through so the Pi adapter can preserve it for Anthropic.
353
+ result.type = tool.type;
354
+ // Server tools don't have input_schema; but Pi's convertTools would add one
355
+ // if we set parameters. Mark it to skip the schema.
356
+ result.serverTool = true;
357
+ }
358
+ else if (tool.kind === "client_tool") {
359
+ result.parameters = { type: "object", properties: {}, additionalProperties: true };
360
+ }
361
+ else {
362
+ result.parameters = {
363
+ type: "object",
364
+ properties: { input: { type: "string" } },
365
+ required: ["input"],
366
+ additionalProperties: false,
367
+ };
368
+ }
369
+ return result;
370
+ }
371
+ function toolArguments(kind, input) {
372
+ if (kind === "custom")
373
+ return { input: typeof input === "string" ? input : "" };
374
+ if (input && typeof input === "object")
375
+ return input;
376
+ if (typeof input !== "string" || input.trim() === "")
377
+ return {};
378
+ let parsed;
379
+ try {
380
+ parsed = JSON.parse(input);
381
+ }
382
+ catch {
383
+ throw new HttpError(400, "Function tool arguments must contain a JSON object.", "invalid_request_error", "input.arguments");
384
+ }
385
+ if (!isRecord(parsed)) {
386
+ throw new HttpError(400, "Function tool arguments must contain a JSON object.", "invalid_request_error", "input.arguments");
387
+ }
388
+ return parsed;
389
+ }
390
+ function textSignature(id, phase) {
391
+ return JSON.stringify({ v: 1, id, ...(phase ? { phase } : {}) });
392
+ }
393
+ function identityOf(value) {
394
+ return { provider: value.provider, api: value.api, model: value.model };
395
+ }
396
+ function zeroUsage() {
397
+ return {
398
+ input: 0,
399
+ output: 0,
400
+ cacheRead: 0,
401
+ cacheWrite: 0,
402
+ totalTokens: 0,
403
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
404
+ };
405
+ }
@@ -0,0 +1,11 @@
1
+ import { type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
2
+ import type { InteractionRequest } from "../interaction/types.js";
3
+ import type { ResolvedProviderAuth } from "../types.js";
4
+ import type { ProviderFetch } from "./response_capture.js";
5
+ type PiOptionsSupport = {
6
+ getSupportedThinkingLevels?: (model: Record<string, unknown>) => string[];
7
+ };
8
+ type Model = Record<string, unknown>;
9
+ export declare function buildOptions(request: InteractionRequest, auth: ResolvedProviderAuth | string, selectedModel: string, model: Model, pi: PiOptionsSupport, sessionId?: string, selectedReasoningEffort?: ReasoningEffort, timeoutMs?: number, signal?: AbortSignal, fetch?: ProviderFetch): Record<string, unknown>;
10
+ export declare function supportedThinkingLevels(model: Model, pi: PiOptionsSupport): string[];
11
+ export {};