@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,546 @@
1
+ import { openAIResponsesOutputItem, openAIResponsesOutputItems, openAIResponsesResponseId, openAIResponsesRouting, openAIResponsesTerminal, openAIResponsesUsage, } from "./openai_responses_output.js";
2
+ import { piMessageToInteractionOutput } from "../../providers/pi_output.js";
3
+ import { isProviderFailureMessage, providerFailureFromEvent, providerFailureMessage, } from "../../runtime/provider_stream_outcome.js";
4
+ import { sseStream } from "./sse_stream.js";
5
+ export function openAIResponsesSseStream(args) {
6
+ const encoder = new TextEncoder();
7
+ const responseId = openAIResponsesResponseId(args.id);
8
+ const createdAt = Math.floor(Date.now() / 1000);
9
+ const accumulator = new ResponsesAccumulator(args, responseId);
10
+ return sseStream({
11
+ protocol: "openai_responses",
12
+ lifecycle: args,
13
+ start: ({ controller, snapshot, lifecycle, settle, observeTerminal }) => {
14
+ let sequenceNumber = 0;
15
+ let emitTerminal = null;
16
+ const send = (event, value) => {
17
+ if (!lifecycle.canWrite)
18
+ return;
19
+ const data = { type: event, ...value, sequence_number: sequenceNumber++ };
20
+ snapshot.record({ event, data });
21
+ controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));
22
+ };
23
+ // A Responses failure is a terminal envelope, so it is armed here and
24
+ // emitted with the close frame rather than sent mid-stream.
25
+ const armFailure = (message) => {
26
+ emitTerminal = () => sendFailure(send, args, responseId, createdAt, accumulator, message);
27
+ };
28
+ send("response.created", {
29
+ response: responseEnvelope(args, responseId, createdAt, "in_progress", [], undefined),
30
+ });
31
+ return {
32
+ consume: async () => {
33
+ for await (const event of args.events) {
34
+ if (lifecycle.shouldStopConsuming)
35
+ break;
36
+ if (event.type === "done") {
37
+ if (!isRecord(event.message))
38
+ throw new Error("Provider stream ended without a terminal message.");
39
+ observeTerminal(event.message);
40
+ if (isProviderFailureMessage(event.message)) {
41
+ const message = event.message;
42
+ settle({ status: "provider_error", message });
43
+ armFailure(message);
44
+ break;
45
+ }
46
+ const output = accumulator.complete(event.message, send);
47
+ settle({ status: "completed", message: event.message, output });
48
+ const terminal = openAIResponsesTerminal(output);
49
+ emitTerminal = () => {
50
+ send(`response.${terminal.status}`, {
51
+ response: responseEnvelope(args, responseId, createdAt, terminal.status, openAIResponsesOutputItems(output), output),
52
+ });
53
+ };
54
+ break;
55
+ }
56
+ if (event.type === "error") {
57
+ const message = providerFailureFromEvent(event);
58
+ settle({ status: "provider_error", message });
59
+ armFailure(message);
60
+ break;
61
+ }
62
+ accumulator.consume(event, send);
63
+ }
64
+ },
65
+ emitProviderError: armFailure,
66
+ close: () => {
67
+ emitTerminal?.();
68
+ controller.close();
69
+ },
70
+ };
71
+ },
72
+ });
73
+ }
74
+ class ResponsesAccumulator {
75
+ args;
76
+ responseId;
77
+ items = new Map();
78
+ addedIndexes = new Set();
79
+ completedIndexes = new Set();
80
+ messageIds = new Map();
81
+ reasoningIds = new Map();
82
+ messagePartStarted = new Set();
83
+ reasoningPartStarted = new Set();
84
+ reasoningSummaryCompleted = new Set();
85
+ providerIndexByContentIndex = new Map();
86
+ pendingProviderIndexes = [];
87
+ activeIndex = null;
88
+ finalOutput = null;
89
+ providerResponse = null;
90
+ constructor(args, responseId) {
91
+ this.args = args;
92
+ this.responseId = responseId;
93
+ }
94
+ consume(event, send) {
95
+ const type = event.type;
96
+ if (type === "provider_event" && isRecord(event.event)) {
97
+ this.consumeProviderEvent(event.event, send);
98
+ return;
99
+ }
100
+ if (type === "text_start" || type === "thinking_start" || type === "toolcall_start") {
101
+ const index = this.indexFor(event);
102
+ this.activate(index, send);
103
+ if (type === "thinking_start")
104
+ this.ensureReasoning(index, send);
105
+ return;
106
+ }
107
+ if (type === "text_delta" && typeof event.delta === "string" && event.delta) {
108
+ const index = this.indexFor(event);
109
+ this.activate(index, send);
110
+ const message = this.ensureMessage(index, send);
111
+ const text = message.content[0]?.type === "text" ? message.content[0].text : "";
112
+ message.content = [{ type: "text", text: text + event.delta }];
113
+ send("response.output_text.delta", {
114
+ item_id: message.id,
115
+ output_index: index,
116
+ content_index: 0,
117
+ delta: event.delta,
118
+ });
119
+ return;
120
+ }
121
+ if (type === "thinking_delta" && typeof event.delta === "string" && event.delta) {
122
+ const index = this.indexFor(event);
123
+ this.activate(index, send);
124
+ const reasoning = this.ensureReasoning(index, send);
125
+ if (!this.reasoningPartStarted.has(index)) {
126
+ this.reasoningPartStarted.add(index);
127
+ send("response.reasoning_summary_part.added", {
128
+ item_id: reasoning.id,
129
+ output_index: index,
130
+ summary_index: 0,
131
+ part: { type: "summary_text", text: "" },
132
+ });
133
+ }
134
+ reasoning.summary[0] = (reasoning.summary[0] ?? "") + event.delta;
135
+ send("response.reasoning_summary_text.delta", {
136
+ item_id: reasoning.id,
137
+ output_index: index,
138
+ summary_index: 0,
139
+ delta: event.delta,
140
+ });
141
+ return;
142
+ }
143
+ if (type === "text_end" || type === "thinking_end" || type === "toolcall_end") {
144
+ const index = this.indexFor(event);
145
+ this.activate(index, send);
146
+ const item = this.itemFromEndEvent(event, index);
147
+ if (item) {
148
+ this.items.set(index, this.withStreamedId(item, index));
149
+ this.sendItemDone(index, send);
150
+ }
151
+ this.activeIndex = null;
152
+ }
153
+ }
154
+ complete(message, send) {
155
+ const codexTerminalOmittedOutput = this.args.source.api === "openai-codex-responses"
156
+ && this.providerResponse !== null
157
+ && (!Array.isArray(this.providerResponse.output) || this.providerResponse.output.length === 0)
158
+ && this.items.size > 0;
159
+ const terminal = piMessageToInteractionOutput(this.providerResponse && !codexTerminalOmittedOutput
160
+ ? { ...message, providerResponse: this.providerResponse }
161
+ : message, this.args.source, this.args.request);
162
+ if (codexTerminalOmittedOutput) {
163
+ terminal.items = [...this.items.entries()]
164
+ .sort(([left], [right]) => left - right)
165
+ .map(([, item]) => item);
166
+ }
167
+ for (const index of this.items.keys()) {
168
+ if (index >= terminal.items.length) {
169
+ throw new Error(`Provider terminal output omitted streamed output item ${index}.`);
170
+ }
171
+ }
172
+ const items = terminal.items.map((item, index) => {
173
+ const streamed = this.items.get(index);
174
+ if (streamed && !sameOutputIdentity(streamed, item)) {
175
+ throw new Error(`Provider terminal output changed the identity of output item ${index}.`);
176
+ }
177
+ const reconciled = this.withStreamedId(item, index);
178
+ this.items.set(index, reconciled);
179
+ return reconciled;
180
+ });
181
+ terminal.items = items;
182
+ this.finalOutput = terminal;
183
+ for (const index of [...this.items.keys()].sort((a, b) => a - b))
184
+ this.sendItemDone(index, send);
185
+ return terminal;
186
+ }
187
+ consumeProviderEvent(event, send) {
188
+ const type = typeof event.type === "string" ? event.type : "";
189
+ if ((type === "response.completed" || type === "response.incomplete") &&
190
+ isRecord(event.response)) {
191
+ this.providerResponse = event.response;
192
+ return;
193
+ }
194
+ if (type === "response.output_item.added" && isRecord(event.item)) {
195
+ const index = providerOutputIndex(event);
196
+ if (event.item.type === "web_search_call") {
197
+ const item = providerHostedToolCall(event.item, this.args.source);
198
+ this.items.set(index, item);
199
+ this.addedIndexes.add(index);
200
+ send(type, providerEventPayload(event));
201
+ return;
202
+ }
203
+ if (!this.providerIndexIsMapped(index))
204
+ this.pendingProviderIndexes.push(index);
205
+ if (event.item.type === "message"
206
+ && typeof event.item.id === "string"
207
+ && !this.messageIds.has(index)) {
208
+ this.messageIds.set(index, event.item.id);
209
+ }
210
+ if (event.item.type === "reasoning"
211
+ && typeof event.item.id === "string"
212
+ && !this.reasoningIds.has(index)) {
213
+ this.reasoningIds.set(index, event.item.id);
214
+ }
215
+ return;
216
+ }
217
+ if (type === "response.output_item.done" && isRecord(event.item)) {
218
+ const index = providerOutputIndex(event);
219
+ if (event.item.type === "message") {
220
+ this.applyProviderMessageAnnotations(index, event.item);
221
+ return;
222
+ }
223
+ if (event.item.type !== "web_search_call")
224
+ return;
225
+ this.items.set(index, providerHostedToolCall(event.item, this.args.source));
226
+ if (!this.addedIndexes.has(index)) {
227
+ this.addedIndexes.add(index);
228
+ send("response.output_item.added", { output_index: index, item: event.item });
229
+ }
230
+ this.completedIndexes.add(index);
231
+ send(type, providerEventPayload(event));
232
+ return;
233
+ }
234
+ if (type === "response.output_text.annotation.added") {
235
+ const index = providerOutputIndex(event);
236
+ const item = this.items.get(index);
237
+ const contentIndex = typeof event.content_index === "number" ? event.content_index : 0;
238
+ if (item?.type === "message" && isRecord(event.annotation)) {
239
+ const part = item.content[contentIndex];
240
+ if (part?.type === "text") {
241
+ part.annotations = [...(part.annotations ?? []), { ...event.annotation }];
242
+ }
243
+ }
244
+ send(type, providerEventPayload(event));
245
+ return;
246
+ }
247
+ if (type.startsWith("response.web_search_call.")) {
248
+ send(type, providerEventPayload(event));
249
+ }
250
+ }
251
+ applyProviderMessageAnnotations(index, item) {
252
+ const message = this.items.get(index);
253
+ if (message?.type !== "message" || !Array.isArray(item.content))
254
+ return;
255
+ for (const [contentIndex, providerPart] of item.content.entries()) {
256
+ if (!isRecord(providerPart) || !Array.isArray(providerPart.annotations))
257
+ continue;
258
+ const part = message.content[contentIndex];
259
+ if (part?.type !== "text")
260
+ continue;
261
+ part.annotations = providerPart.annotations.flatMap((annotation) => isRecord(annotation) ? [{ ...annotation }] : []);
262
+ }
263
+ }
264
+ currentOutputItems() {
265
+ if (this.finalOutput)
266
+ return openAIResponsesOutputItems(this.finalOutput);
267
+ const output = this.baseOutput();
268
+ output.items = [...this.items.entries()]
269
+ .sort(([a], [b]) => a - b)
270
+ .map(([, item]) => item);
271
+ return output.items.length ? openAIResponsesOutputItems(output) : [];
272
+ }
273
+ currentUsage() {
274
+ return openAIResponsesUsage(this.finalOutput ?? this.baseOutput());
275
+ }
276
+ ensureMessage(index, send) {
277
+ const existing = this.items.get(index);
278
+ if (existing?.type === "message")
279
+ return existing;
280
+ const id = this.messageIds.get(index) ?? streamedItemId("msg", this.responseId, index);
281
+ this.messageIds.set(index, id);
282
+ const message = {
283
+ type: "message",
284
+ id,
285
+ role: "assistant",
286
+ content: [{ type: "text", text: "" }],
287
+ contentShape: "parts",
288
+ source: this.args.source,
289
+ };
290
+ this.items.set(index, message);
291
+ this.addedIndexes.add(index);
292
+ send("response.output_item.added", {
293
+ output_index: index,
294
+ item: {
295
+ type: "message",
296
+ role: "assistant",
297
+ id,
298
+ status: "in_progress",
299
+ content: [],
300
+ },
301
+ });
302
+ this.sendMessagePartAdded(index, id, send);
303
+ return message;
304
+ }
305
+ ensureReasoning(index, send) {
306
+ const existing = this.items.get(index);
307
+ if (existing?.type === "reasoning")
308
+ return existing;
309
+ const id = this.reasoningIds.get(index) ?? streamedItemId("rs", this.responseId, index);
310
+ this.reasoningIds.set(index, id);
311
+ const reasoning = {
312
+ type: "reasoning",
313
+ id,
314
+ summary: [],
315
+ content: [],
316
+ source: this.args.source,
317
+ };
318
+ this.items.set(index, reasoning);
319
+ this.addedIndexes.add(index);
320
+ send("response.output_item.added", {
321
+ output_index: index,
322
+ item: { type: "reasoning", id, status: "in_progress", summary: [] },
323
+ });
324
+ return reasoning;
325
+ }
326
+ itemFromEndEvent(event, index) {
327
+ if (isRecord(event.partial)) {
328
+ const output = piMessageToInteractionOutput(event.partial, this.args.source, this.args.request);
329
+ const contentIndex = event.contentIndex;
330
+ if (typeof contentIndex === "number" && output.items[contentIndex])
331
+ return output.items[contentIndex];
332
+ }
333
+ if (event.type === "toolcall_end" && isRecord(event.toolCall)) {
334
+ const output = piMessageToInteractionOutput({ content: [{ type: "toolCall", ...event.toolCall }], stopReason: "toolUse" }, this.args.source, this.args.request);
335
+ return output.items[0] ?? null;
336
+ }
337
+ return this.items.get(index) ?? null;
338
+ }
339
+ withStreamedId(item, index) {
340
+ if (item.type === "message" && this.messageIds.has(index))
341
+ return { ...item, id: this.messageIds.get(index) };
342
+ if (item.type === "reasoning" && this.reasoningIds.has(index))
343
+ return { ...item, id: this.reasoningIds.get(index) };
344
+ return item;
345
+ }
346
+ sendItemDone(index, send) {
347
+ if (this.completedIndexes.has(index))
348
+ return;
349
+ const item = this.items.get(index);
350
+ if (!item)
351
+ return;
352
+ if (item.type === "reasoning" && !this.finalOutput)
353
+ return;
354
+ const serialized = openAIResponsesOutputItem(this.finalOutput ?? this.baseOutput(), item, index);
355
+ if (!this.addedIndexes.has(index)) {
356
+ this.addedIndexes.add(index);
357
+ if (item.type === "message") {
358
+ send("response.output_item.added", {
359
+ output_index: index,
360
+ item: {
361
+ type: "message",
362
+ role: "assistant",
363
+ id: serialized.id,
364
+ status: "in_progress",
365
+ content: [],
366
+ },
367
+ });
368
+ }
369
+ else {
370
+ send("response.output_item.added", { output_index: index, item: serialized });
371
+ }
372
+ }
373
+ if (item.type === "message") {
374
+ const id = String(serialized.id);
375
+ const text = item.content.filter((part) => part.type === "text").map((part) => part.text).join("");
376
+ const annotations = item.content.flatMap((part) => part.type === "text" ? part.annotations ?? [] : []);
377
+ const part = { type: "output_text", text, annotations };
378
+ this.sendMessagePartAdded(index, id, send);
379
+ send("response.output_text.done", {
380
+ item_id: id,
381
+ output_index: index,
382
+ content_index: 0,
383
+ text,
384
+ });
385
+ send("response.content_part.done", {
386
+ item_id: id,
387
+ output_index: index,
388
+ content_index: 0,
389
+ part,
390
+ });
391
+ }
392
+ if (item.type === "reasoning" && !this.reasoningSummaryCompleted.has(index) && item.summary[0]) {
393
+ this.reasoningSummaryCompleted.add(index);
394
+ send("response.reasoning_summary_text.done", {
395
+ item_id: serialized.id,
396
+ output_index: index,
397
+ summary_index: 0,
398
+ text: item.summary[0],
399
+ });
400
+ }
401
+ this.completedIndexes.add(index);
402
+ send("response.output_item.done", {
403
+ output_index: index,
404
+ item: serialized,
405
+ });
406
+ }
407
+ sendMessagePartAdded(index, id, send) {
408
+ if (this.messagePartStarted.has(index))
409
+ return;
410
+ this.messagePartStarted.add(index);
411
+ send("response.content_part.added", {
412
+ item_id: id,
413
+ output_index: index,
414
+ content_index: 0,
415
+ part: { type: "output_text", text: "", annotations: [] },
416
+ });
417
+ }
418
+ activate(index, send) {
419
+ if (this.activeIndex !== null && this.activeIndex !== index)
420
+ this.sendItemDone(this.activeIndex, send);
421
+ this.activeIndex = index;
422
+ }
423
+ indexFor(event) {
424
+ const contentIndex = event.contentIndex;
425
+ if (typeof contentIndex !== "number" || !Number.isInteger(contentIndex) || contentIndex < 0) {
426
+ throw new Error("Provider stream event is missing a valid contentIndex.");
427
+ }
428
+ const existing = this.providerIndexByContentIndex.get(contentIndex);
429
+ if (existing !== undefined)
430
+ return existing;
431
+ const providerIndex = this.pendingProviderIndexes.shift() ?? this.nextAvailableOutputIndex(contentIndex);
432
+ this.providerIndexByContentIndex.set(contentIndex, providerIndex);
433
+ return providerIndex;
434
+ }
435
+ providerIndexIsMapped(index) {
436
+ return [...this.providerIndexByContentIndex.values()].includes(index);
437
+ }
438
+ nextAvailableOutputIndex(candidate) {
439
+ const reserved = new Set([
440
+ ...this.items.keys(),
441
+ ...this.pendingProviderIndexes,
442
+ ...this.providerIndexByContentIndex.values(),
443
+ ]);
444
+ while (reserved.has(candidate))
445
+ candidate += 1;
446
+ return candidate;
447
+ }
448
+ baseOutput() {
449
+ return {
450
+ responseId: this.responseId,
451
+ createdAtMs: Date.now(),
452
+ source: this.args.source,
453
+ items: [],
454
+ usage: {
455
+ input: 0,
456
+ output: 0,
457
+ cacheRead: 0,
458
+ cacheWrite: 0,
459
+ totalTokens: 0,
460
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
461
+ },
462
+ stopReason: "stop",
463
+ };
464
+ }
465
+ }
466
+ function providerOutputIndex(event) {
467
+ const index = event.output_index;
468
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0) {
469
+ throw new Error("OpenAI provider event is missing a valid output_index.");
470
+ }
471
+ return index;
472
+ }
473
+ function providerEventPayload(event) {
474
+ const { type: _type, sequence_number: _sequenceNumber, ...payload } = event;
475
+ return payload;
476
+ }
477
+ function providerHostedToolCall(item, source) {
478
+ if (item.type !== "web_search_call" || typeof item.id !== "string" || !item.id) {
479
+ throw new Error("OpenAI provider web search item is malformed.");
480
+ }
481
+ const status = providerHostedStatus(item.status);
482
+ return {
483
+ type: "hosted_tool_call",
484
+ id: item.id,
485
+ tool: "web_search",
486
+ providerType: "web_search_call",
487
+ ...(status ? { status } : {}),
488
+ payload: { ...item },
489
+ source,
490
+ };
491
+ }
492
+ function providerHostedStatus(value) {
493
+ return value === "in_progress" ||
494
+ value === "searching" ||
495
+ value === "completed" ||
496
+ value === "incomplete" ||
497
+ value === "failed"
498
+ ? value
499
+ : undefined;
500
+ }
501
+ function sameOutputIdentity(left, right) {
502
+ if (left.type !== right.type)
503
+ return false;
504
+ if (left.type === "hosted_tool_call" && right.type === "hosted_tool_call") {
505
+ return left.id === right.id
506
+ && left.tool === right.tool
507
+ && left.providerType === right.providerType;
508
+ }
509
+ if (left.type !== "tool_call" || right.type !== "tool_call")
510
+ return true;
511
+ return left.callId === right.callId
512
+ && left.kind === right.kind
513
+ && left.name === right.name
514
+ && left.namespace === right.namespace;
515
+ }
516
+ function responseEnvelope(args, id, createdAt, status, output, interaction) {
517
+ return {
518
+ id,
519
+ object: "response",
520
+ created_at: createdAt,
521
+ status,
522
+ incomplete_details: status === "incomplete" ? { reason: "max_output_tokens" } : null,
523
+ model: args.model,
524
+ output,
525
+ parallel_tool_calls: args.request.parallelToolCalls ?? true,
526
+ ...(interaction ? { usage: openAIResponsesUsage(interaction) } : {}),
527
+ dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId),
528
+ };
529
+ }
530
+ function sendFailure(send, args, responseId, createdAt, accumulator, error) {
531
+ send("response.failed", {
532
+ response: {
533
+ ...responseEnvelope(args, responseId, createdAt, "failed", accumulator.currentOutputItems(), undefined),
534
+ usage: accumulator.currentUsage(),
535
+ error: {
536
+ message: providerFailureMessage(error),
537
+ type: "server_error",
538
+ code: "provider_execution_failed",
539
+ },
540
+ },
541
+ });
542
+ }
543
+ function streamedItemId(prefix, responseId, index) {
544
+ return `${prefix}_${responseId}_${index}`.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
545
+ }
546
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
@@ -0,0 +1,31 @@
1
+ import { ProviderStreamLifecycle } from "../../runtime/provider_stream_lifecycle.js";
2
+ import { type ProviderStreamOutcome } from "../../runtime/provider_stream_outcome.js";
3
+ import { DeliveredStreamSnapshot } from "./delivered_stream_snapshot.js";
4
+ export type SseStreamLifecycleArgs = {
5
+ onFinal?: (outcome: ProviderStreamOutcome) => void;
6
+ beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
7
+ clientSignal?: AbortSignal;
8
+ onAbort?: () => void;
9
+ };
10
+ export type SseStreamContext = {
11
+ controller: ReadableStreamDefaultController<Uint8Array>;
12
+ snapshot: DeliveredStreamSnapshot;
13
+ lifecycle: ProviderStreamLifecycle;
14
+ settle(outcome: ProviderStreamOutcome): void;
15
+ observeTerminal(message: Record<string, unknown>): void;
16
+ };
17
+ export type SseStreamHandlers = {
18
+ consume(): Promise<void>;
19
+ emitProviderError(message: Record<string, unknown>): void;
20
+ close(outcome: ProviderStreamOutcome): void;
21
+ };
22
+ /**
23
+ * The cancel/terminal skeleton every hosted SSE protocol shares. The protocol
24
+ * owns its wire encoding and event translation; this owns the terminal race,
25
+ * the fallback terminals, and the single finish that closes the response.
26
+ */
27
+ export declare function sseStream(args: {
28
+ protocol: string;
29
+ lifecycle: SseStreamLifecycleArgs;
30
+ start: (context: SseStreamContext) => SseStreamHandlers;
31
+ }): ReadableStream<Uint8Array>;
@@ -0,0 +1,67 @@
1
+ import { ProviderStreamLifecycle } from "../../runtime/provider_stream_lifecycle.js";
2
+ import { providerFailure, providerFailureFromCaught, providerFailureFromTerminal, } from "../../runtime/provider_stream_outcome.js";
3
+ import { DeliveredStreamSnapshot } from "./delivered_stream_snapshot.js";
4
+ /**
5
+ * The cancel/terminal skeleton every hosted SSE protocol shares. The protocol
6
+ * owns its wire encoding and event translation; this owns the terminal race,
7
+ * the fallback terminals, and the single finish that closes the response.
8
+ */
9
+ export function sseStream(args) {
10
+ let terminalOutcome = null;
11
+ let terminalMessage = null;
12
+ const snapshot = new DeliveredStreamSnapshot(args.protocol);
13
+ const lifecycle = new ProviderStreamLifecycle({
14
+ partialResponse: () => snapshot.body(),
15
+ onFinal: args.lifecycle.onFinal,
16
+ onAbort: args.lifecycle.onAbort,
17
+ cancelSignal: args.lifecycle.clientSignal,
18
+ terminalOutcome: () => terminalOutcome,
19
+ });
20
+ return new ReadableStream({
21
+ cancel() {
22
+ lifecycle.cancel(terminalOutcome);
23
+ },
24
+ async start(controller) {
25
+ const handlers = args.start({
26
+ controller,
27
+ snapshot,
28
+ lifecycle,
29
+ settle: (outcome) => {
30
+ terminalOutcome = outcome;
31
+ },
32
+ observeTerminal: (message) => {
33
+ terminalMessage = message;
34
+ },
35
+ });
36
+ const failTerminal = (message) => {
37
+ terminalOutcome = { status: "provider_error", message };
38
+ handlers.emitProviderError(message);
39
+ };
40
+ try {
41
+ await handlers.consume();
42
+ if (!terminalOutcome && !lifecycle.shouldStopConsuming) {
43
+ failTerminal(providerFailure("Provider stream ended without a terminal event."));
44
+ }
45
+ }
46
+ catch (error) {
47
+ if (!lifecycle.shouldStopConsuming) {
48
+ failTerminal(terminalMessage
49
+ ? providerFailureFromTerminal(error, terminalMessage)
50
+ : providerFailureFromCaught(error));
51
+ }
52
+ }
53
+ finally {
54
+ const outcome = terminalOutcome ?? {
55
+ status: "aborted",
56
+ message: null,
57
+ responseBody: snapshot.body(),
58
+ };
59
+ await lifecycle.finish({
60
+ outcome,
61
+ beforeClose: args.lifecycle.beforeClose,
62
+ close: () => handlers.close(outcome),
63
+ });
64
+ }
65
+ },
66
+ });
67
+ }
@@ -0,0 +1,11 @@
1
+ import type { AnthropicSafeguards, InteractionRequest } from "../interaction/types.js";
2
+ import type { ProviderFetch } from "./response_capture.js";
3
+ export declare function forwardsAnthropicSafeguards(request: Pick<InteractionRequest, "anthropicSafeguards">, model: Record<string, unknown>): boolean;
4
+ export declare function payloadWithSafeguards(payload: Record<string, unknown>, safeguards: AnthropicSafeguards): Record<string, unknown>;
5
+ export type SafeguardResultsTap = {
6
+ fetch: ProviderFetch;
7
+ results: () => unknown[] | undefined;
8
+ };
9
+ export declare function safeguardResultsTap(fetch?: ProviderFetch): SafeguardResultsTap;
10
+ export declare function messageWithSafeguardResults(message: Record<string, unknown>, results: unknown[] | undefined): Record<string, unknown>;
11
+ export declare function eventsWithSafeguardResults(events: AsyncIterable<Record<string, unknown>>, tap: SafeguardResultsTap): AsyncIterable<Record<string, unknown>>;