@puku-ai/sdk 4.0.0 → 4.0.2

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 (583) hide show
  1. package/README.md +29 -10
  2. package/dist/index.d.ts +26 -0
  3. package/dist/index.js +32 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/vendor/_vendor/partial-json-parser/parser.d.ts +2 -0
  6. package/dist/vendor/_vendor/partial-json-parser/parser.js +223 -0
  7. package/dist/vendor/_vendor/partial-json-parser/parser.js.map +1 -0
  8. package/dist/vendor/api-promise.d.ts +2 -0
  9. package/dist/vendor/api-promise.js +3 -0
  10. package/dist/vendor/api-promise.js.map +1 -0
  11. package/dist/vendor/client.d.ts +399 -0
  12. package/dist/vendor/client.js +976 -0
  13. package/dist/vendor/client.js.map +1 -0
  14. package/dist/vendor/core/api-promise.d.ts +49 -0
  15. package/dist/vendor/core/api-promise.js +77 -0
  16. package/dist/vendor/core/api-promise.js.map +1 -0
  17. package/dist/vendor/core/api.d.ts +10 -0
  18. package/dist/vendor/core/api.js +2 -0
  19. package/dist/vendor/core/api.js.map +1 -0
  20. package/dist/vendor/core/credentials.d.ts +130 -0
  21. package/dist/vendor/core/credentials.js +274 -0
  22. package/dist/vendor/core/credentials.js.map +1 -0
  23. package/dist/vendor/core/error.d.ts +82 -0
  24. package/dist/vendor/core/error.js +140 -0
  25. package/dist/vendor/core/error.js.map +1 -0
  26. package/dist/vendor/core/middleware.d.ts +153 -0
  27. package/dist/vendor/core/middleware.js +168 -0
  28. package/dist/vendor/core/middleware.js.map +1 -0
  29. package/dist/vendor/core/pagination.d.ts +121 -0
  30. package/dist/vendor/core/pagination.js +207 -0
  31. package/dist/vendor/core/pagination.js.map +1 -0
  32. package/dist/vendor/core/resource.d.ts +5 -0
  33. package/dist/vendor/core/resource.js +8 -0
  34. package/dist/vendor/core/resource.js.map +1 -0
  35. package/dist/vendor/core/streaming.d.ts +41 -0
  36. package/dist/vendor/core/streaming.js +342 -0
  37. package/dist/vendor/core/streaming.js.map +1 -0
  38. package/dist/vendor/core/uploads.d.ts +2 -0
  39. package/dist/vendor/core/uploads.js +2 -0
  40. package/dist/vendor/core/uploads.js.map +1 -0
  41. package/dist/vendor/error.d.ts +2 -0
  42. package/dist/vendor/error.js +3 -0
  43. package/dist/vendor/error.js.map +1 -0
  44. package/dist/vendor/helpers/beta/environments.d.ts +22 -0
  45. package/dist/vendor/helpers/beta/environments.js +23 -0
  46. package/dist/vendor/helpers/beta/environments.js.map +1 -0
  47. package/dist/vendor/helpers/beta/json-schema.d.ts +36 -0
  48. package/dist/vendor/helpers/beta/json-schema.js +53 -0
  49. package/dist/vendor/helpers/beta/json-schema.js.map +1 -0
  50. package/dist/vendor/helpers/beta/mcp.d.ts +302 -0
  51. package/dist/vendor/helpers/beta/mcp.js +406 -0
  52. package/dist/vendor/helpers/beta/mcp.js.map +1 -0
  53. package/dist/vendor/helpers/beta/memory.d.ts +10 -0
  54. package/dist/vendor/helpers/beta/memory.js +15 -0
  55. package/dist/vendor/helpers/beta/memory.js.map +1 -0
  56. package/dist/vendor/helpers/beta/standard-schema.d.ts +44 -0
  57. package/dist/vendor/helpers/beta/standard-schema.js +54 -0
  58. package/dist/vendor/helpers/beta/standard-schema.js.map +1 -0
  59. package/dist/vendor/helpers/beta/zod.d.ts +32 -0
  60. package/dist/vendor/helpers/beta/zod.js +52 -0
  61. package/dist/vendor/helpers/beta/zod.js.map +1 -0
  62. package/dist/vendor/helpers/index.d.ts +2 -0
  63. package/dist/vendor/helpers/index.js +3 -0
  64. package/dist/vendor/helpers/index.js.map +1 -0
  65. package/dist/vendor/helpers/json-schema.d.ts +17 -0
  66. package/dist/vendor/helpers/json-schema.js +34 -0
  67. package/dist/vendor/helpers/json-schema.js.map +1 -0
  68. package/dist/vendor/helpers/zod.d.ts +12 -0
  69. package/dist/vendor/helpers/zod.js +42 -0
  70. package/dist/vendor/helpers/zod.js.map +1 -0
  71. package/dist/vendor/index.d.ts +16 -0
  72. package/dist/vendor/index.js +23 -0
  73. package/dist/vendor/index.js.map +1 -0
  74. package/dist/vendor/internal/builtin-types.d.ts +72 -0
  75. package/dist/vendor/internal/builtin-types.js +3 -0
  76. package/dist/vendor/internal/builtin-types.js.map +1 -0
  77. package/dist/vendor/internal/constants.d.ts +4 -0
  78. package/dist/vendor/internal/constants.js +10 -0
  79. package/dist/vendor/internal/constants.js.map +1 -0
  80. package/dist/vendor/internal/decoders/jsonl.d.ts +9 -0
  81. package/dist/vendor/internal/decoders/jsonl.js +37 -0
  82. package/dist/vendor/internal/decoders/jsonl.js.map +1 -0
  83. package/dist/vendor/internal/decoders/line.d.ts +16 -0
  84. package/dist/vendor/internal/decoders/line.js +105 -0
  85. package/dist/vendor/internal/decoders/line.js.map +1 -0
  86. package/dist/vendor/internal/detect-platform.d.ts +14 -0
  87. package/dist/vendor/internal/detect-platform.js +155 -0
  88. package/dist/vendor/internal/detect-platform.js.map +1 -0
  89. package/dist/vendor/internal/errors.d.ts +2 -0
  90. package/dist/vendor/internal/errors.js +38 -0
  91. package/dist/vendor/internal/errors.js.map +1 -0
  92. package/dist/vendor/internal/file-store.d.ts +135 -0
  93. package/dist/vendor/internal/file-store.js +529 -0
  94. package/dist/vendor/internal/file-store.js.map +1 -0
  95. package/dist/vendor/internal/headers.d.ts +28 -0
  96. package/dist/vendor/internal/headers.js +114 -0
  97. package/dist/vendor/internal/headers.js.map +1 -0
  98. package/dist/vendor/internal/message-stream-utils.d.ts +9 -0
  99. package/dist/vendor/internal/message-stream-utils.js +30 -0
  100. package/dist/vendor/internal/message-stream-utils.js.map +1 -0
  101. package/dist/vendor/internal/node.browser.d.ts +8 -0
  102. package/dist/vendor/internal/node.browser.js +19 -0
  103. package/dist/vendor/internal/node.browser.js.map +1 -0
  104. package/dist/vendor/internal/node.d.ts +13 -0
  105. package/dist/vendor/internal/node.js +14 -0
  106. package/dist/vendor/internal/node.js.map +1 -0
  107. package/dist/vendor/internal/parse.d.ts +17 -0
  108. package/dist/vendor/internal/parse.js +62 -0
  109. package/dist/vendor/internal/parse.js.map +1 -0
  110. package/dist/vendor/internal/qs/formats.d.ts +6 -0
  111. package/dist/vendor/internal/qs/formats.js +9 -0
  112. package/dist/vendor/internal/qs/formats.js.map +1 -0
  113. package/dist/vendor/internal/qs/index.d.ts +9 -0
  114. package/dist/vendor/internal/qs/index.js +10 -0
  115. package/dist/vendor/internal/qs/index.js.map +1 -0
  116. package/dist/vendor/internal/qs/stringify.d.ts +2 -0
  117. package/dist/vendor/internal/qs/stringify.js +274 -0
  118. package/dist/vendor/internal/qs/stringify.js.map +1 -0
  119. package/dist/vendor/internal/qs/types.d.ts +56 -0
  120. package/dist/vendor/internal/qs/types.js +2 -0
  121. package/dist/vendor/internal/qs/types.js.map +1 -0
  122. package/dist/vendor/internal/qs/utils.d.ts +14 -0
  123. package/dist/vendor/internal/qs/utils.js +217 -0
  124. package/dist/vendor/internal/qs/utils.js.map +1 -0
  125. package/dist/vendor/internal/request-options.d.ts +126 -0
  126. package/dist/vendor/internal/request-options.js +27 -0
  127. package/dist/vendor/internal/request-options.js.map +1 -0
  128. package/dist/vendor/internal/request-signal.d.ts +3 -0
  129. package/dist/vendor/internal/request-signal.js +45 -0
  130. package/dist/vendor/internal/request-signal.js.map +1 -0
  131. package/dist/vendor/internal/shim-types.d.ts +16 -0
  132. package/dist/vendor/internal/shim-types.js +3 -0
  133. package/dist/vendor/internal/shim-types.js.map +1 -0
  134. package/dist/vendor/internal/shims.d.ts +25 -0
  135. package/dist/vendor/internal/shims.js +85 -0
  136. package/dist/vendor/internal/shims.js.map +1 -0
  137. package/dist/vendor/internal/stainless-helper-header.d.ts +59 -0
  138. package/dist/vendor/internal/stainless-helper-header.js +83 -0
  139. package/dist/vendor/internal/stainless-helper-header.js.map +1 -0
  140. package/dist/vendor/internal/stream-utils.d.ts +7 -0
  141. package/dist/vendor/internal/stream-utils.js +35 -0
  142. package/dist/vendor/internal/stream-utils.js.map +1 -0
  143. package/dist/vendor/internal/to-file.d.ts +44 -0
  144. package/dist/vendor/internal/to-file.js +93 -0
  145. package/dist/vendor/internal/to-file.js.map +1 -0
  146. package/dist/vendor/internal/types.d.ts +62 -0
  147. package/dist/vendor/internal/types.js +3 -0
  148. package/dist/vendor/internal/types.js.map +1 -0
  149. package/dist/vendor/internal/uploads.d.ts +41 -0
  150. package/dist/vendor/internal/uploads.js +139 -0
  151. package/dist/vendor/internal/uploads.js.map +1 -0
  152. package/dist/vendor/internal/utils/abort.d.ts +11 -0
  153. package/dist/vendor/internal/utils/abort.js +22 -0
  154. package/dist/vendor/internal/utils/abort.js.map +1 -0
  155. package/dist/vendor/internal/utils/async-queue.d.ts +30 -0
  156. package/dist/vendor/internal/utils/async-queue.js +66 -0
  157. package/dist/vendor/internal/utils/async-queue.js.map +1 -0
  158. package/dist/vendor/internal/utils/backoff.d.ts +22 -0
  159. package/dist/vendor/internal/utils/backoff.js +36 -0
  160. package/dist/vendor/internal/utils/backoff.js.map +1 -0
  161. package/dist/vendor/internal/utils/base64.d.ts +2 -0
  162. package/dist/vendor/internal/utils/base64.js +33 -0
  163. package/dist/vendor/internal/utils/base64.js.map +1 -0
  164. package/dist/vendor/internal/utils/bytes.d.ts +3 -0
  165. package/dist/vendor/internal/utils/bytes.js +26 -0
  166. package/dist/vendor/internal/utils/bytes.js.map +1 -0
  167. package/dist/vendor/internal/utils/env.d.ts +8 -0
  168. package/dist/vendor/internal/utils/env.js +18 -0
  169. package/dist/vendor/internal/utils/env.js.map +1 -0
  170. package/dist/vendor/internal/utils/log.d.ts +46 -0
  171. package/dist/vendor/internal/utils/log.js +105 -0
  172. package/dist/vendor/internal/utils/log.js.map +1 -0
  173. package/dist/vendor/internal/utils/path.d.ts +14 -0
  174. package/dist/vendor/internal/utils/path.js +74 -0
  175. package/dist/vendor/internal/utils/path.js.map +1 -0
  176. package/dist/vendor/internal/utils/promise.d.ts +10 -0
  177. package/dist/vendor/internal/utils/promise.js +15 -0
  178. package/dist/vendor/internal/utils/promise.js.map +1 -0
  179. package/dist/vendor/internal/utils/query.d.ts +1 -0
  180. package/dist/vendor/internal/utils/query.js +6 -0
  181. package/dist/vendor/internal/utils/query.js.map +1 -0
  182. package/dist/vendor/internal/utils/sleep.d.ts +9 -0
  183. package/dist/vendor/internal/utils/sleep.js +24 -0
  184. package/dist/vendor/internal/utils/sleep.js.map +1 -0
  185. package/dist/vendor/internal/utils/time.d.ts +2 -0
  186. package/dist/vendor/internal/utils/time.js +5 -0
  187. package/dist/vendor/internal/utils/time.js.map +1 -0
  188. package/dist/vendor/internal/utils/uuid.d.ts +4 -0
  189. package/dist/vendor/internal/utils/uuid.js +15 -0
  190. package/dist/vendor/internal/utils/uuid.js.map +1 -0
  191. package/dist/vendor/internal/utils/values.d.ts +24 -0
  192. package/dist/vendor/internal/utils/values.js +106 -0
  193. package/dist/vendor/internal/utils/values.js.map +1 -0
  194. package/dist/vendor/internal/utils.d.ts +7 -0
  195. package/dist/vendor/internal/utils.js +9 -0
  196. package/dist/vendor/internal/utils.js.map +1 -0
  197. package/dist/vendor/lib/BetaMessageStream.d.ts +123 -0
  198. package/dist/vendor/lib/BetaMessageStream.js +662 -0
  199. package/dist/vendor/lib/BetaMessageStream.js.map +1 -0
  200. package/dist/vendor/lib/MessageStream.d.ts +122 -0
  201. package/dist/vendor/lib/MessageStream.js +609 -0
  202. package/dist/vendor/lib/MessageStream.js.map +1 -0
  203. package/dist/vendor/lib/beta-parser.d.ts +36 -0
  204. package/dist/vendor/lib/beta-parser.js +75 -0
  205. package/dist/vendor/lib/beta-parser.js.map +1 -0
  206. package/dist/vendor/lib/credentials/credential-chain.d.ts +38 -0
  207. package/dist/vendor/lib/credentials/credential-chain.js +208 -0
  208. package/dist/vendor/lib/credentials/credential-chain.js.map +1 -0
  209. package/dist/vendor/lib/credentials/identity-token.d.ts +10 -0
  210. package/dist/vendor/lib/credentials/identity-token.js +35 -0
  211. package/dist/vendor/lib/credentials/identity-token.js.map +1 -0
  212. package/dist/vendor/lib/credentials/oidc-federation.d.ts +39 -0
  213. package/dist/vendor/lib/credentials/oidc-federation.js +79 -0
  214. package/dist/vendor/lib/credentials/oidc-federation.js.map +1 -0
  215. package/dist/vendor/lib/credentials/token-cache.d.ts +53 -0
  216. package/dist/vendor/lib/credentials/token-cache.js +110 -0
  217. package/dist/vendor/lib/credentials/token-cache.js.map +1 -0
  218. package/dist/vendor/lib/credentials/types.d.ts +95 -0
  219. package/dist/vendor/lib/credentials/types.js +226 -0
  220. package/dist/vendor/lib/credentials/types.js.map +1 -0
  221. package/dist/vendor/lib/credentials/user-oauth.d.ts +20 -0
  222. package/dist/vendor/lib/credentials/user-oauth.js +94 -0
  223. package/dist/vendor/lib/credentials/user-oauth.js.map +1 -0
  224. package/dist/vendor/lib/credentials.d.ts +3 -0
  225. package/dist/vendor/lib/credentials.js +3 -0
  226. package/dist/vendor/lib/credentials.js.map +1 -0
  227. package/dist/vendor/lib/environments/index.d.ts +3 -0
  228. package/dist/vendor/lib/environments/index.js +4 -0
  229. package/dist/vendor/lib/environments/index.js.map +1 -0
  230. package/dist/vendor/lib/environments/poller.d.ts +94 -0
  231. package/dist/vendor/lib/environments/poller.js +218 -0
  232. package/dist/vendor/lib/environments/poller.js.map +1 -0
  233. package/dist/vendor/lib/environments/worker.d.ts +226 -0
  234. package/dist/vendor/lib/environments/worker.js +572 -0
  235. package/dist/vendor/lib/environments/worker.js.map +1 -0
  236. package/dist/vendor/lib/helper-client.d.ts +30 -0
  237. package/dist/vendor/lib/helper-client.js +55 -0
  238. package/dist/vendor/lib/helper-client.js.map +1 -0
  239. package/dist/vendor/lib/middleware.d.ts +97 -0
  240. package/dist/vendor/lib/middleware.js +775 -0
  241. package/dist/vendor/lib/middleware.js.map +1 -0
  242. package/dist/vendor/lib/parser.d.ts +31 -0
  243. package/dist/vendor/lib/parser.js +62 -0
  244. package/dist/vendor/lib/parser.js.map +1 -0
  245. package/dist/vendor/lib/sessions/accumulate.d.ts +22 -0
  246. package/dist/vendor/lib/sessions/accumulate.js +42 -0
  247. package/dist/vendor/lib/sessions/accumulate.js.map +1 -0
  248. package/dist/vendor/lib/standard-schema.d.ts +130 -0
  249. package/dist/vendor/lib/standard-schema.js +41 -0
  250. package/dist/vendor/lib/standard-schema.js.map +1 -0
  251. package/dist/vendor/lib/tools/BetaRunnableTool.d.ts +48 -0
  252. package/dist/vendor/lib/tools/BetaRunnableTool.js +26 -0
  253. package/dist/vendor/lib/tools/BetaRunnableTool.js.map +1 -0
  254. package/dist/vendor/lib/tools/BetaToolRunner.d.ts +160 -0
  255. package/dist/vendor/lib/tools/BetaToolRunner.js +497 -0
  256. package/dist/vendor/lib/tools/BetaToolRunner.js.map +1 -0
  257. package/dist/vendor/lib/tools/CompactionControl.d.ts +29 -0
  258. package/dist/vendor/lib/tools/CompactionControl.js +25 -0
  259. package/dist/vendor/lib/tools/CompactionControl.js.map +1 -0
  260. package/dist/vendor/lib/tools/SessionToolRunner.d.ts +178 -0
  261. package/dist/vendor/lib/tools/SessionToolRunner.js +737 -0
  262. package/dist/vendor/lib/tools/SessionToolRunner.js.map +1 -0
  263. package/dist/vendor/lib/tools/ToolError.d.ts +32 -0
  264. package/dist/vendor/lib/tools/ToolError.js +43 -0
  265. package/dist/vendor/lib/tools/ToolError.js.map +1 -0
  266. package/dist/vendor/lib/transform-json-schema.d.ts +2 -0
  267. package/dist/vendor/lib/transform-json-schema.js +111 -0
  268. package/dist/vendor/lib/transform-json-schema.js.map +1 -0
  269. package/dist/vendor/pagination.d.ts +2 -0
  270. package/dist/vendor/pagination.js +3 -0
  271. package/dist/vendor/pagination.js.map +1 -0
  272. package/dist/vendor/resource.d.ts +2 -0
  273. package/dist/vendor/resource.js +3 -0
  274. package/dist/vendor/resource.js.map +1 -0
  275. package/dist/vendor/resources/beta/agents/agents.d.ts +1128 -0
  276. package/dist/vendor/resources/beta/agents/agents.js +123 -0
  277. package/dist/vendor/resources/beta/agents/agents.js.map +1 -0
  278. package/dist/vendor/resources/beta/agents/index.d.ts +2 -0
  279. package/dist/vendor/resources/beta/agents/index.js +4 -0
  280. package/dist/vendor/resources/beta/agents/index.js.map +1 -0
  281. package/dist/vendor/resources/beta/agents/versions.d.ts +32 -0
  282. package/dist/vendor/resources/beta/agents/versions.js +32 -0
  283. package/dist/vendor/resources/beta/agents/versions.js.map +1 -0
  284. package/dist/vendor/resources/beta/agents.d.ts +1 -0
  285. package/dist/vendor/resources/beta/agents.js +3 -0
  286. package/dist/vendor/resources/beta/agents.js.map +1 -0
  287. package/dist/vendor/resources/beta/beta.d.ts +131 -0
  288. package/dist/vendor/resources/beta/beta.js +69 -0
  289. package/dist/vendor/resources/beta/beta.js.map +1 -0
  290. package/dist/vendor/resources/beta/deployment-runs.d.ts +305 -0
  291. package/dist/vendor/resources/beta/deployment-runs.js +51 -0
  292. package/dist/vendor/resources/beta/deployment-runs.js.map +1 -0
  293. package/dist/vendor/resources/beta/deployments.d.ts +698 -0
  294. package/dist/vendor/resources/beta/deployments.js +192 -0
  295. package/dist/vendor/resources/beta/deployments.js.map +1 -0
  296. package/dist/vendor/resources/beta/dreams.d.ts +335 -0
  297. package/dist/vendor/resources/beta/dreams.js +112 -0
  298. package/dist/vendor/resources/beta/dreams.js.map +1 -0
  299. package/dist/vendor/resources/beta/environments/environments.d.ts +432 -0
  300. package/dist/vendor/resources/beta/environments/environments.js +142 -0
  301. package/dist/vendor/resources/beta/environments/environments.js.map +1 -0
  302. package/dist/vendor/resources/beta/environments/index.d.ts +2 -0
  303. package/dist/vendor/resources/beta/environments/index.js +4 -0
  304. package/dist/vendor/resources/beta/environments/index.js.map +1 -0
  305. package/dist/vendor/resources/beta/environments/work.d.ts +500 -0
  306. package/dist/vendor/resources/beta/environments/work.js +251 -0
  307. package/dist/vendor/resources/beta/environments/work.js.map +1 -0
  308. package/dist/vendor/resources/beta/environments.d.ts +1 -0
  309. package/dist/vendor/resources/beta/environments.js +3 -0
  310. package/dist/vendor/resources/beta/environments.js.map +1 -0
  311. package/dist/vendor/resources/beta/files.d.ts +190 -0
  312. package/dist/vendor/resources/beta/files.js +120 -0
  313. package/dist/vendor/resources/beta/files.js.map +1 -0
  314. package/dist/vendor/resources/beta/index.d.ts +17 -0
  315. package/dist/vendor/resources/beta/index.js +19 -0
  316. package/dist/vendor/resources/beta/index.js.map +1 -0
  317. package/dist/vendor/resources/beta/memory-stores/index.d.ts +3 -0
  318. package/dist/vendor/resources/beta/memory-stores/index.js +5 -0
  319. package/dist/vendor/resources/beta/memory-stores/index.js.map +1 -0
  320. package/dist/vendor/resources/beta/memory-stores/memories.d.ts +346 -0
  321. package/dist/vendor/resources/beta/memory-stores/memories.js +126 -0
  322. package/dist/vendor/resources/beta/memory-stores/memories.js.map +1 -0
  323. package/dist/vendor/resources/beta/memory-stores/memory-stores.d.ts +230 -0
  324. package/dist/vendor/resources/beta/memory-stores/memory-stores.js +137 -0
  325. package/dist/vendor/resources/beta/memory-stores/memory-stores.js.map +1 -0
  326. package/dist/vendor/resources/beta/memory-stores/memory-versions.d.ts +252 -0
  327. package/dist/vendor/resources/beta/memory-stores/memory-versions.js +77 -0
  328. package/dist/vendor/resources/beta/memory-stores/memory-versions.js.map +1 -0
  329. package/dist/vendor/resources/beta/memory-stores.d.ts +1 -0
  330. package/dist/vendor/resources/beta/memory-stores.js +3 -0
  331. package/dist/vendor/resources/beta/memory-stores.js.map +1 -0
  332. package/dist/vendor/resources/beta/messages/batches.d.ts +685 -0
  333. package/dist/vendor/resources/beta/messages/batches.js +203 -0
  334. package/dist/vendor/resources/beta/messages/batches.js.map +1 -0
  335. package/dist/vendor/resources/beta/messages/index.d.ts +3 -0
  336. package/dist/vendor/resources/beta/messages/index.js +5 -0
  337. package/dist/vendor/resources/beta/messages/index.js.map +1 -0
  338. package/dist/vendor/resources/beta/messages/messages.d.ts +5376 -0
  339. package/dist/vendor/resources/beta/messages/messages.js +158 -0
  340. package/dist/vendor/resources/beta/messages/messages.js.map +1 -0
  341. package/dist/vendor/resources/beta/messages.d.ts +1 -0
  342. package/dist/vendor/resources/beta/messages.js +3 -0
  343. package/dist/vendor/resources/beta/messages.js.map +1 -0
  344. package/dist/vendor/resources/beta/models.d.ts +217 -0
  345. package/dist/vendor/resources/beta/models.js +56 -0
  346. package/dist/vendor/resources/beta/models.js.map +1 -0
  347. package/dist/vendor/resources/beta/organization/api-keys.d.ts +176 -0
  348. package/dist/vendor/resources/beta/organization/api-keys.js +52 -0
  349. package/dist/vendor/resources/beta/organization/api-keys.js.map +1 -0
  350. package/dist/vendor/resources/beta/organization/compliance-settings.d.ts +73 -0
  351. package/dist/vendor/resources/beta/organization/compliance-settings.js +48 -0
  352. package/dist/vendor/resources/beta/organization/compliance-settings.js.map +1 -0
  353. package/dist/vendor/resources/beta/organization/external-keys.d.ts +271 -0
  354. package/dist/vendor/resources/beta/organization/external-keys.js +115 -0
  355. package/dist/vendor/resources/beta/organization/external-keys.js.map +1 -0
  356. package/dist/vendor/resources/beta/organization/federation/federation.d.ts +13 -0
  357. package/dist/vendor/resources/beta/organization/federation/federation.js +13 -0
  358. package/dist/vendor/resources/beta/organization/federation/federation.js.map +1 -0
  359. package/dist/vendor/resources/beta/organization/federation/index.d.ts +3 -0
  360. package/dist/vendor/resources/beta/organization/federation/index.js +5 -0
  361. package/dist/vendor/resources/beta/organization/federation/index.js.map +1 -0
  362. package/dist/vendor/resources/beta/organization/federation/issuers.d.ts +352 -0
  363. package/dist/vendor/resources/beta/organization/federation/issuers.js +165 -0
  364. package/dist/vendor/resources/beta/organization/federation/issuers.js.map +1 -0
  365. package/dist/vendor/resources/beta/organization/federation/rules/index.d.ts +2 -0
  366. package/dist/vendor/resources/beta/organization/federation/rules/index.js +4 -0
  367. package/dist/vendor/resources/beta/organization/federation/rules/index.js.map +1 -0
  368. package/dist/vendor/resources/beta/organization/federation/rules/rules.d.ts +467 -0
  369. package/dist/vendor/resources/beta/organization/federation/rules/rules.js +190 -0
  370. package/dist/vendor/resources/beta/organization/federation/rules/rules.js.map +1 -0
  371. package/dist/vendor/resources/beta/organization/federation/rules/workspaces.d.ts +123 -0
  372. package/dist/vendor/resources/beta/organization/federation/rules/workspaces.js +110 -0
  373. package/dist/vendor/resources/beta/organization/federation/rules/workspaces.js.map +1 -0
  374. package/dist/vendor/resources/beta/organization/federation/rules.d.ts +1 -0
  375. package/dist/vendor/resources/beta/organization/federation/rules.js +3 -0
  376. package/dist/vendor/resources/beta/organization/federation/rules.js.map +1 -0
  377. package/dist/vendor/resources/beta/organization/federation.d.ts +1 -0
  378. package/dist/vendor/resources/beta/organization/federation.js +3 -0
  379. package/dist/vendor/resources/beta/organization/federation.js.map +1 -0
  380. package/dist/vendor/resources/beta/organization/index.d.ts +10 -0
  381. package/dist/vendor/resources/beta/organization/index.js +12 -0
  382. package/dist/vendor/resources/beta/organization/index.js.map +1 -0
  383. package/dist/vendor/resources/beta/organization/invites.d.ts +161 -0
  384. package/dist/vendor/resources/beta/organization/invites.js +72 -0
  385. package/dist/vendor/resources/beta/organization/invites.js.map +1 -0
  386. package/dist/vendor/resources/beta/organization/organization.d.ts +72 -0
  387. package/dist/vendor/resources/beta/organization/organization.js +54 -0
  388. package/dist/vendor/resources/beta/organization/organization.js.map +1 -0
  389. package/dist/vendor/resources/beta/organization/rate-limits.d.ts +76 -0
  390. package/dist/vendor/resources/beta/organization/rate-limits.js +27 -0
  391. package/dist/vendor/resources/beta/organization/rate-limits.js.map +1 -0
  392. package/dist/vendor/resources/beta/organization/service-accounts/index.d.ts +2 -0
  393. package/dist/vendor/resources/beta/organization/service-accounts/index.js +4 -0
  394. package/dist/vendor/resources/beta/organization/service-accounts/index.js.map +1 -0
  395. package/dist/vendor/resources/beta/organization/service-accounts/service-accounts.d.ts +257 -0
  396. package/dist/vendor/resources/beta/organization/service-accounts/service-accounts.js +166 -0
  397. package/dist/vendor/resources/beta/organization/service-accounts/service-accounts.js.map +1 -0
  398. package/dist/vendor/resources/beta/organization/service-accounts/workspaces.d.ts +140 -0
  399. package/dist/vendor/resources/beta/organization/service-accounts/workspaces.js +121 -0
  400. package/dist/vendor/resources/beta/organization/service-accounts/workspaces.js.map +1 -0
  401. package/dist/vendor/resources/beta/organization/service-accounts.d.ts +1 -0
  402. package/dist/vendor/resources/beta/organization/service-accounts.js +3 -0
  403. package/dist/vendor/resources/beta/organization/service-accounts.js.map +1 -0
  404. package/dist/vendor/resources/beta/organization/users.d.ts +123 -0
  405. package/dist/vendor/resources/beta/organization/users.js +63 -0
  406. package/dist/vendor/resources/beta/organization/users.js.map +1 -0
  407. package/dist/vendor/resources/beta/organization/workspaces/index.d.ts +4 -0
  408. package/dist/vendor/resources/beta/organization/workspaces/index.js +6 -0
  409. package/dist/vendor/resources/beta/organization/workspaces/index.js.map +1 -0
  410. package/dist/vendor/resources/beta/organization/workspaces/members.d.ts +134 -0
  411. package/dist/vendor/resources/beta/organization/workspaces/members.js +98 -0
  412. package/dist/vendor/resources/beta/organization/workspaces/members.js.map +1 -0
  413. package/dist/vendor/resources/beta/organization/workspaces/rate-limits.d.ts +82 -0
  414. package/dist/vendor/resources/beta/organization/workspaces/rate-limits.js +30 -0
  415. package/dist/vendor/resources/beta/organization/workspaces/rate-limits.js.map +1 -0
  416. package/dist/vendor/resources/beta/organization/workspaces/service-accounts.d.ts +209 -0
  417. package/dist/vendor/resources/beta/organization/workspaces/service-accounts.js +185 -0
  418. package/dist/vendor/resources/beta/organization/workspaces/service-accounts.js.map +1 -0
  419. package/dist/vendor/resources/beta/organization/workspaces/workspaces.d.ts +302 -0
  420. package/dist/vendor/resources/beta/organization/workspaces/workspaces.js +104 -0
  421. package/dist/vendor/resources/beta/organization/workspaces/workspaces.js.map +1 -0
  422. package/dist/vendor/resources/beta/organization/workspaces.d.ts +1 -0
  423. package/dist/vendor/resources/beta/organization/workspaces.js +3 -0
  424. package/dist/vendor/resources/beta/organization/workspaces.js.map +1 -0
  425. package/dist/vendor/resources/beta/organization.d.ts +1 -0
  426. package/dist/vendor/resources/beta/organization.js +3 -0
  427. package/dist/vendor/resources/beta/organization.js.map +1 -0
  428. package/dist/vendor/resources/beta/sessions/events.d.ts +1513 -0
  429. package/dist/vendor/resources/beta/sessions/events.js +115 -0
  430. package/dist/vendor/resources/beta/sessions/events.js.map +1 -0
  431. package/dist/vendor/resources/beta/sessions/index.d.ts +4 -0
  432. package/dist/vendor/resources/beta/sessions/index.js +6 -0
  433. package/dist/vendor/resources/beta/sessions/index.js.map +1 -0
  434. package/dist/vendor/resources/beta/sessions/resources.d.ts +227 -0
  435. package/dist/vendor/resources/beta/sessions/resources.js +128 -0
  436. package/dist/vendor/resources/beta/sessions/resources.js.map +1 -0
  437. package/dist/vendor/resources/beta/sessions/sessions.d.ts +866 -0
  438. package/dist/vendor/resources/beta/sessions/sessions.js +150 -0
  439. package/dist/vendor/resources/beta/sessions/sessions.js.map +1 -0
  440. package/dist/vendor/resources/beta/sessions/threads/events.d.ts +77 -0
  441. package/dist/vendor/resources/beta/sessions/threads/events.js +57 -0
  442. package/dist/vendor/resources/beta/sessions/threads/events.js.map +1 -0
  443. package/dist/vendor/resources/beta/sessions/threads/index.d.ts +2 -0
  444. package/dist/vendor/resources/beta/sessions/threads/index.js +4 -0
  445. package/dist/vendor/resources/beta/sessions/threads/index.js.map +1 -0
  446. package/dist/vendor/resources/beta/sessions/threads/threads.d.ts +195 -0
  447. package/dist/vendor/resources/beta/sessions/threads/threads.js +80 -0
  448. package/dist/vendor/resources/beta/sessions/threads/threads.js.map +1 -0
  449. package/dist/vendor/resources/beta/sessions/threads.d.ts +1 -0
  450. package/dist/vendor/resources/beta/sessions/threads.js +3 -0
  451. package/dist/vendor/resources/beta/sessions/threads.js.map +1 -0
  452. package/dist/vendor/resources/beta/sessions.d.ts +1 -0
  453. package/dist/vendor/resources/beta/sessions.js +3 -0
  454. package/dist/vendor/resources/beta/sessions.js.map +1 -0
  455. package/dist/vendor/resources/beta/skills/index.d.ts +2 -0
  456. package/dist/vendor/resources/beta/skills/index.js +4 -0
  457. package/dist/vendor/resources/beta/skills/index.js.map +1 -0
  458. package/dist/vendor/resources/beta/skills/skills.d.ts +178 -0
  459. package/dist/vendor/resources/beta/skills/skills.js +96 -0
  460. package/dist/vendor/resources/beta/skills/skills.js.map +1 -0
  461. package/dist/vendor/resources/beta/skills/versions.d.ts +181 -0
  462. package/dist/vendor/resources/beta/skills/versions.js +125 -0
  463. package/dist/vendor/resources/beta/skills/versions.js.map +1 -0
  464. package/dist/vendor/resources/beta/skills.d.ts +1 -0
  465. package/dist/vendor/resources/beta/skills.js +3 -0
  466. package/dist/vendor/resources/beta/skills.js.map +1 -0
  467. package/dist/vendor/resources/beta/tunnels/certificates.d.ts +162 -0
  468. package/dist/vendor/resources/beta/tunnels/certificates.js +125 -0
  469. package/dist/vendor/resources/beta/tunnels/certificates.js.map +1 -0
  470. package/dist/vendor/resources/beta/tunnels/index.d.ts +2 -0
  471. package/dist/vendor/resources/beta/tunnels/index.js +4 -0
  472. package/dist/vendor/resources/beta/tunnels/index.js.map +1 -0
  473. package/dist/vendor/resources/beta/tunnels/tunnels.d.ts +211 -0
  474. package/dist/vendor/resources/beta/tunnels/tunnels.js +173 -0
  475. package/dist/vendor/resources/beta/tunnels/tunnels.js.map +1 -0
  476. package/dist/vendor/resources/beta/tunnels.d.ts +1 -0
  477. package/dist/vendor/resources/beta/tunnels.js +3 -0
  478. package/dist/vendor/resources/beta/tunnels.js.map +1 -0
  479. package/dist/vendor/resources/beta/user-profiles.d.ts +244 -0
  480. package/dist/vendor/resources/beta/user-profiles.js +114 -0
  481. package/dist/vendor/resources/beta/user-profiles.js.map +1 -0
  482. package/dist/vendor/resources/beta/vaults/credentials.d.ts +715 -0
  483. package/dist/vendor/resources/beta/vaults/credentials.js +173 -0
  484. package/dist/vendor/resources/beta/vaults/credentials.js.map +1 -0
  485. package/dist/vendor/resources/beta/vaults/index.d.ts +2 -0
  486. package/dist/vendor/resources/beta/vaults/index.js +4 -0
  487. package/dist/vendor/resources/beta/vaults/index.js.map +1 -0
  488. package/dist/vendor/resources/beta/vaults/vaults.d.ts +191 -0
  489. package/dist/vendor/resources/beta/vaults/vaults.js +141 -0
  490. package/dist/vendor/resources/beta/vaults/vaults.js.map +1 -0
  491. package/dist/vendor/resources/beta/vaults.d.ts +1 -0
  492. package/dist/vendor/resources/beta/vaults.js +3 -0
  493. package/dist/vendor/resources/beta/vaults.js.map +1 -0
  494. package/dist/vendor/resources/beta/webhooks.d.ts +464 -0
  495. package/dist/vendor/resources/beta/webhooks.js +29 -0
  496. package/dist/vendor/resources/beta/webhooks.js.map +1 -0
  497. package/dist/vendor/resources/beta.d.ts +1 -0
  498. package/dist/vendor/resources/beta.js +3 -0
  499. package/dist/vendor/resources/beta.js.map +1 -0
  500. package/dist/vendor/resources/completions.d.ts +172 -0
  501. package/dist/vendor/resources/completions.js +19 -0
  502. package/dist/vendor/resources/completions.js.map +1 -0
  503. package/dist/vendor/resources/files.d.ts +104 -0
  504. package/dist/vendor/resources/files.js +48 -0
  505. package/dist/vendor/resources/files.js.map +1 -0
  506. package/dist/vendor/resources/index.d.ts +7 -0
  507. package/dist/vendor/resources/index.js +9 -0
  508. package/dist/vendor/resources/index.js.map +1 -0
  509. package/dist/vendor/resources/messages/batches.d.ts +312 -0
  510. package/dist/vendor/resources/messages/batches.js +157 -0
  511. package/dist/vendor/resources/messages/batches.js.map +1 -0
  512. package/dist/vendor/resources/messages/index.d.ts +2 -0
  513. package/dist/vendor/resources/messages/index.js +4 -0
  514. package/dist/vendor/resources/messages/index.js.map +1 -0
  515. package/dist/vendor/resources/messages/messages.d.ts +3886 -0
  516. package/dist/vendor/resources/messages/messages.js +130 -0
  517. package/dist/vendor/resources/messages/messages.js.map +1 -0
  518. package/dist/vendor/resources/messages.d.ts +1 -0
  519. package/dist/vendor/resources/messages.js +3 -0
  520. package/dist/vendor/resources/messages.js.map +1 -0
  521. package/dist/vendor/resources/models.d.ts +196 -0
  522. package/dist/vendor/resources/models.js +41 -0
  523. package/dist/vendor/resources/models.js.map +1 -0
  524. package/dist/vendor/resources/shared.d.ts +43 -0
  525. package/dist/vendor/resources/shared.js +3 -0
  526. package/dist/vendor/resources/shared.js.map +1 -0
  527. package/dist/vendor/resources/skills/index.d.ts +2 -0
  528. package/dist/vendor/resources/skills/index.js +4 -0
  529. package/dist/vendor/resources/skills/index.js.map +1 -0
  530. package/dist/vendor/resources/skills/skills.d.ts +128 -0
  531. package/dist/vendor/resources/skills/skills.js +36 -0
  532. package/dist/vendor/resources/skills/skills.js.map +1 -0
  533. package/dist/vendor/resources/skills/versions.d.ts +103 -0
  534. package/dist/vendor/resources/skills/versions.js +37 -0
  535. package/dist/vendor/resources/skills/versions.js.map +1 -0
  536. package/dist/vendor/resources/skills.d.ts +1 -0
  537. package/dist/vendor/resources/skills.js +3 -0
  538. package/dist/vendor/resources/skills.js.map +1 -0
  539. package/dist/vendor/resources/top-level.d.ts +1 -0
  540. package/dist/vendor/resources/top-level.js +3 -0
  541. package/dist/vendor/resources/top-level.js.map +1 -0
  542. package/dist/vendor/resources.d.ts +1 -0
  543. package/dist/vendor/resources.js +2 -0
  544. package/dist/vendor/resources.js.map +1 -0
  545. package/dist/vendor/streaming.d.ts +2 -0
  546. package/dist/vendor/streaming.js +3 -0
  547. package/dist/vendor/streaming.js.map +1 -0
  548. package/dist/vendor/tools/agent-toolset/fs-util.d.ts +74 -0
  549. package/dist/vendor/tools/agent-toolset/fs-util.js +184 -0
  550. package/dist/vendor/tools/agent-toolset/fs-util.js.map +1 -0
  551. package/dist/vendor/tools/agent-toolset/memories.d.ts +172 -0
  552. package/dist/vendor/tools/agent-toolset/memories.js +910 -0
  553. package/dist/vendor/tools/agent-toolset/memories.js.map +1 -0
  554. package/dist/vendor/tools/agent-toolset/node.browser.d.ts +80 -0
  555. package/dist/vendor/tools/agent-toolset/node.browser.js +129 -0
  556. package/dist/vendor/tools/agent-toolset/node.browser.js.map +1 -0
  557. package/dist/vendor/tools/agent-toolset/node.d.ts +191 -0
  558. package/dist/vendor/tools/agent-toolset/node.js +886 -0
  559. package/dist/vendor/tools/agent-toolset/node.js.map +1 -0
  560. package/dist/vendor/tools/agent-toolset/skills.d.ts +73 -0
  561. package/dist/vendor/tools/agent-toolset/skills.js +320 -0
  562. package/dist/vendor/tools/agent-toolset/skills.js.map +1 -0
  563. package/dist/vendor/tools/agent-toolset/sync-interval.d.ts +18 -0
  564. package/dist/vendor/tools/agent-toolset/sync-interval.js +25 -0
  565. package/dist/vendor/tools/agent-toolset/sync-interval.js.map +1 -0
  566. package/dist/vendor/tools/memory/node.browser.d.ts +26 -0
  567. package/dist/vendor/tools/memory/node.browser.js +44 -0
  568. package/dist/vendor/tools/memory/node.browser.js.map +1 -0
  569. package/dist/vendor/tools/memory/node.d.ts +17 -0
  570. package/dist/vendor/tools/memory/node.js +327 -0
  571. package/dist/vendor/tools/memory/node.js.map +1 -0
  572. package/dist/vendor/uploads.d.ts +2 -0
  573. package/dist/vendor/uploads.js +3 -0
  574. package/dist/vendor/uploads.js.map +1 -0
  575. package/dist/vendor/version.d.ts +1 -0
  576. package/dist/vendor/version.js +2 -0
  577. package/dist/vendor/version.js.map +1 -0
  578. package/package.json +7 -14
  579. package/sdk.cjs +6 -6
  580. package/sdk.cjs.map +18 -18
  581. package/sdk.d.ts +10 -10
  582. package/sdk.mjs +21 -21
  583. package/sdk.mjs.map +18 -18
@@ -0,0 +1,775 @@
1
+ import { PukuError } from '../core/error.js';
2
+ import { Stream } from '../core/streaming.js';
3
+ import { isAbortError } from '../internal/errors.js';
4
+ import { appendHeaderValue } from '../internal/headers.js';
5
+ import { STAINLESS_HELPER_HEADER } from '../internal/stainless-helper-header.js';
6
+ import { safeJSON } from '../internal/utils/values.js';
7
+ export { BetaFallbackState } from '../internal/request-options.js';
8
+ const encoder = new TextEncoder();
9
+ /** Betas sent by default; override with {@link BetaRefusalFallbackOptions.betas}. */
10
+ const DEFAULT_BETAS = ['fallback-credit-2026-07-01'];
11
+ /**
12
+ * Remove `fallback` blocks replayed in history. They only parse under the
13
+ * server-side fallback beta, which belongs to the caller-owned server-side
14
+ * `fallbacks` feature — this middleware never sends it, so a request
15
+ * replaying them would 400. A turn the strip leaves empty is dropped whole;
16
+ * a turn that was already empty is kept — it may carry other payload (e.g. a
17
+ * directive-only system message's `output_config`).
18
+ */
19
+ function stripFallbackBlocks(body) {
20
+ const messages = body.messages.flatMap((message) => {
21
+ if (!Array.isArray(message.content))
22
+ return [message];
23
+ const content = message.content.filter((block) => block.type !== 'fallback');
24
+ if (content.length === message.content.length)
25
+ return [message];
26
+ return content.length > 0 ? [{ ...message, content }] : [];
27
+ });
28
+ return { ...body, messages };
29
+ }
30
+ /**
31
+ * Apply one chain entry to the original request params as a patch: a field
32
+ * set to a value overrides the original, a field explicitly `null` removes
33
+ * the field from the retried request, and an absent (or `undefined`) field
34
+ * keeps the original value. `output_config` patches one level deep — its
35
+ * subfields follow the same set/`null`/absent rules against the original
36
+ * `output_config` (created if the entry sets any subfield). Every hop patches
37
+ * the original params — never a previous hop's patched body — and `body` is
38
+ * never mutated.
39
+ */
40
+ function applyFallbackPatch(body, entry) {
41
+ const patched = { ...body };
42
+ for (const [key, value] of Object.entries(entry)) {
43
+ if (key === 'output_config' && value != null) {
44
+ const merged = { ...(patched[key] ?? {}) };
45
+ for (const [subKey, subValue] of Object.entries(value)) {
46
+ patchField(merged, subKey, subValue);
47
+ }
48
+ patchField(patched, key, Object.keys(merged).length ? merged : null);
49
+ }
50
+ else {
51
+ patchField(patched, key, value);
52
+ }
53
+ }
54
+ return patched;
55
+ }
56
+ /** Set/`null`-unset/absent-keep one field on `target` (mutated). */
57
+ function patchField(target, key, value) {
58
+ if (value === undefined)
59
+ return;
60
+ if (value === null) {
61
+ delete target[key];
62
+ }
63
+ else {
64
+ target[key] = value;
65
+ }
66
+ }
67
+ /**
68
+ * Middleware that retries refused `/v1/messages` requests down a fallback chain.
69
+ *
70
+ * Non-streaming: when a response comes back with `stop_reason: 'refusal'`, the
71
+ * request is retried with each entry of `fallbacks` applied as a patch to the
72
+ * original params (a set field overrides, an explicit `null` unsets, an absent
73
+ * field keeps the original value; entries never patch each other's requests)
74
+ * — passing along the refusal's `fallback_credit_token` — until a model
75
+ * accepts or the chain is exhausted. A message served by a fallback carries a
76
+ * `fallback` content block prepended at each model boundary — the same seam
77
+ * block shape the server-side `fallbacks` param places in `content`, though
78
+ * the rest of the envelope is the serving hop's as returned (see the
79
+ * known-divergences note below); an exhausted chain surfaces the final
80
+ * refusal verbatim.
81
+ *
82
+ * Streaming: when the stream ends in `stop_reason: 'refusal'`, a second
83
+ * request is issued to the fallback model — carrying the refused model's
84
+ * partial output as a trailing assistant prefill when the refusal grants one
85
+ * (`fallback_has_prefill_claim`), plus the refusal's `fallback_credit_token`
86
+ * — and the fallback's events are spliced onto the
87
+ * still-open stream, so the client sees one continuous message in the
88
+ * server-side `fallbacks` wire shape: a `fallback` content block at each model
89
+ * boundary, monotonic block indices, and per-hop `usage.iterations` on the
90
+ * final `message_delta`. Only `model` is honored from each entry on this path:
91
+ * the credit token is redeemable only against the refused request's body, so
92
+ * the other per-entry overrides (`max_tokens`, `thinking`, ...) would be
93
+ * rejected.
94
+ *
95
+ * The fallback-credit beta the credit tokens require is sent by default on
96
+ * every request the middleware handles; the `betas` option controls this.
97
+ *
98
+ * In both modes a fallback that itself refuses with a fresh credit token
99
+ * continues down the chain. A streaming fallback whose prefill the server
100
+ * rejects (HTTP 400) is retried once without it; a fallback whose request
101
+ * fails outright is skipped — its token was never redeemed, so it carries to
102
+ * the next entry.
103
+ *
104
+ * To keep later requests on the model that accepted, pass a
105
+ * {@link BetaFallbackState} via the `fallbackState` request option; requests
106
+ * sharing that state start directly at the pinned fallback. Reuse one state
107
+ * across whatever scope the pin should apply to — typically a conversation.
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * const client = new PukuAI({
112
+ * middleware: [betaRefusalFallbackMiddleware([{ model: 'opus-4.8' }])],
113
+ * });
114
+ *
115
+ * const fallbackState = new BetaFallbackState();
116
+ * const message = await client.beta.messages.create(params, { fallbackState });
117
+ * ```
118
+ */
119
+ export function betaRefusalFallbackMiddleware(fallbacks, options = {}) {
120
+ let warnedMissingState = false;
121
+ return async (request, next, ctx) => {
122
+ // This middleware only applies to the beta messages API
123
+ // (`client.beta.messages`, which posts to `/v1/messages?beta=true`).
124
+ // An empty chain also disables this middleware.
125
+ const [path, query] = (ctx.options?.path ?? '').split('?');
126
+ if (fallbacks.length === 0 ||
127
+ ctx.options?.method !== 'post' ||
128
+ path !== '/v1/messages' ||
129
+ new URLSearchParams(query).get('beta') !== 'true' ||
130
+ typeof ctx.options.body !== 'object' ||
131
+ ctx.options.body == null) {
132
+ return next(request);
133
+ }
134
+ if (ctx.options.body.fallbacks != null) {
135
+ throw new PukuError('Sending the `fallbacks:` request param is not supported when using the `betaRefusalFallbackMiddleware`. ' +
136
+ 'You should either remove the middleware and send `fallbacks:` with the `server-side-fallback-2026-07-01` beta header to let the API handle refusal fallbacks, ' +
137
+ "or omit the `fallbacks:` param if you'd like `betaRefusalFallbackMiddleware` to handle fallbacks on the client side.");
138
+ }
139
+ const onError = options.onError ??
140
+ ((error) => ctx.logger.error(`puku-ai/sdk: betaRefusalFallbackMiddleware: ${error.message}`));
141
+ // Send the configured betas on this and every hop request derived from it,
142
+ // and tag this and every hop with the middleware's helper telemetry.
143
+ request = withMiddlewareHeaders(request, options.betas ?? DEFAULT_BETAS);
144
+ const body = stripFallbackBlocks(ctx.options.body);
145
+ const state = ctx.options.fallbackState;
146
+ // start from the pinned fallback (-1 = the original params)
147
+ const startIndex = state?.index ?? -1;
148
+ if (!Number.isInteger(startIndex) || startIndex < -1 || startIndex >= fallbacks.length) {
149
+ throw new PukuError(`fallbackState.index ${startIndex} is out of bounds for a chain of ${fallbacks.length} fallback(s); was the state shared with a different middleware?`);
150
+ }
151
+ // pin requests sharing the state to the entry being tried
152
+ const pin = (index) => {
153
+ if (state) {
154
+ state.index = index;
155
+ }
156
+ else if (!warnedMissingState) {
157
+ warnedMissingState = true;
158
+ ctx.logger.warn('puku-ai/sdk: betaRefusalFallbackMiddleware fell back without a `fallbackState` request option; follow-up requests will retry models that already refused. Pass a shared `{ fallbackState: new BetaFallbackState() }` to pin them to the accepted model.');
159
+ }
160
+ };
161
+ const initialBody = startIndex === -1 ? body : applyFallbackPatch(body, fallbacks[startIndex]);
162
+ // a non-string body can't be respliced or redeemed against — leave the
163
+ // request untouched (the streaming path stands down on it below too)
164
+ const initialRequest = typeof request.body !== 'string' ? request : { ...request, body: JSON.stringify(initialBody) };
165
+ const response = await next(initialRequest);
166
+ if (!response.ok) {
167
+ return response;
168
+ }
169
+ if (ctx.options.stream === true) {
170
+ const firstHop = startIndex + 1;
171
+ // Splicing needs at least one entry left to hop to and the JSON request
172
+ // body the credit token is redeemable against (an earlier middleware
173
+ // may have rewritten it to another BodyInit); otherwise the stream
174
+ // passes through untouched.
175
+ if (firstHop >= fallbacks.length || typeof initialRequest.body !== 'string') {
176
+ return response;
177
+ }
178
+ return spliceFallbackStream({
179
+ request: initialRequest,
180
+ response,
181
+ next,
182
+ ctx,
183
+ fallbacks,
184
+ firstHop,
185
+ onError,
186
+ pin,
187
+ });
188
+ }
189
+ let index = startIndex;
190
+ let res = response;
191
+ // The model the current hop was requested as — the caller's spelling, not
192
+ // the server's `message.model` echo; the seam block's `from` carries it.
193
+ let requestedModel = initialBody.model;
194
+ const fallbackBlocks = [];
195
+ while (index < fallbacks.length - 1) {
196
+ const message = await ctx.parse(res);
197
+ if (message?.type !== 'message' || message.stop_reason !== 'refusal') {
198
+ break;
199
+ }
200
+ index += 1;
201
+ pin(index);
202
+ const entry = fallbacks[index];
203
+ // One `fallback` seam block per model boundary, prepended to the serving
204
+ // hop's content below — the same block shape the server places in
205
+ // `content`, not a claim of full envelope parity.
206
+ fallbackBlocks.push({
207
+ type: 'fallback',
208
+ // `requestedModel` is always set for a typed body; the `??` defends
209
+ // against an untyped body that carried no `model` field.
210
+ from: { model: requestedModel ?? message.model },
211
+ to: { model: entry.model },
212
+ trigger: { type: 'refusal', category: message.stop_details?.category ?? null },
213
+ });
214
+ requestedModel = entry.model;
215
+ res = await next({
216
+ ...request,
217
+ body: JSON.stringify({
218
+ ...applyFallbackPatch(body, entry),
219
+ ...(message.stop_details?.fallback_credit_token ?
220
+ { fallback_credit_token: creditTokenParam(message.stop_details.fallback_credit_token) }
221
+ : undefined),
222
+ }),
223
+ });
224
+ }
225
+ if (fallbackBlocks.length === 0) {
226
+ return res;
227
+ }
228
+ const served = await ctx.parse(res);
229
+ // Chain exhausted on a refusal (or an error/malformed body): surface it
230
+ // verbatim. The array guard keeps a message-shaped body with non-array
231
+ // `content` from throwing at the spread below.
232
+ if (served?.type !== 'message' || served.stop_reason === 'refusal' || !Array.isArray(served.content)) {
233
+ return res;
234
+ }
235
+ // A fallback hop served (or exhausted the chain with output): prepend the
236
+ // seam blocks so the app-visible `content` opens with one `fallback` block
237
+ // per model boundary. Response init is preserved (same `_request_id`);
238
+ // `content-length` is dropped since the body grew.
239
+ const headers = new Headers(res.headers);
240
+ headers.delete('content-length');
241
+ return new Response(JSON.stringify({ ...served, content: [...fallbackBlocks, ...served.content] }), {
242
+ status: res.status,
243
+ statusText: res.statusText,
244
+ headers,
245
+ });
246
+ };
247
+ }
248
+ /**
249
+ * Wrap stream A in a response whose body passes events through until a
250
+ * retryable refusal, then splices the fallback chain's events on (see
251
+ * {@link splicedEvents}). Cancelling the returned body tears down whichever
252
+ * stream is being read and aborts any in-flight fallback request or retry
253
+ * backoff: hop requests run under `controller`'s signal, which fires on
254
+ * cancel and mirrors the original request's signal — a user abort has no
255
+ * other way to reach a hop, since this synthetic body isn't fetch-backed.
256
+ */
257
+ function spliceFallbackStream(args) {
258
+ const controller = new AbortController();
259
+ const signal = args.request.signal;
260
+ if (signal?.aborted) {
261
+ controller.abort(signal.reason);
262
+ }
263
+ else {
264
+ signal?.addEventListener('abort', makeAbort(controller, signal), { once: true });
265
+ }
266
+ const iter = splicedEvents(args, controller);
267
+ const body = new ReadableStream({
268
+ async pull(ctrl) {
269
+ try {
270
+ const { value, done } = await iter.next();
271
+ if (done)
272
+ return ctrl.close();
273
+ ctrl.enqueue(value);
274
+ }
275
+ catch (err) {
276
+ ctrl.error(err);
277
+ }
278
+ },
279
+ async cancel() {
280
+ controller.abort();
281
+ await iter.return?.(undefined);
282
+ },
283
+ });
284
+ return new Response(body, args.response);
285
+ }
286
+ async function* splicedEvents({ request, response, next, ctx, fallbacks, firstHop, onError, pin }, controller) {
287
+ // --- stream A: pass through until a chainable refusal ---
288
+ const a = yield* consumeHop({
289
+ response,
290
+ controller,
291
+ indexBase: 0,
292
+ hasNext: true, // the caller guarantees firstHop < fallbacks.length
293
+ onError,
294
+ splice: null,
295
+ });
296
+ if (!a.refused)
297
+ return; // non-refusal or not-retryable: pure pass-through.
298
+ // --- fallback chain: try each entry in order ---
299
+ // `base` is the assistant-turn content the current token's request already
300
+ // carried — the token is redeemable only with it resent verbatim. `partial`
301
+ // is the newest refused hop's output, included only when its refusal
302
+ // granted a prefill claim (any other change to the body is a 400).
303
+ let nextIndex = a.nextIndex; // monotonic block index across all spliced streams
304
+ let token = a.refused.token;
305
+ let base = [];
306
+ let partial = a.refused.hasPrefillClaim ? toPrefillBlocks(a.blocks) : [];
307
+ let fromModel = a.model ?? '';
308
+ let lastUsage = a.refused.usage;
309
+ // The refusal whose token is currently in flight — surfaced verbatim (with a
310
+ // recommended_model added) if every fallback request fails and we degrade.
311
+ let refusalDetails = a.refused.stopDetails;
312
+ // That refused hop's suppressed message_start `input_transformations`, which
313
+ // ride on the surfaced refusal delta (none for A: its start reached the client).
314
+ let refusalInputTransformations = a.refused.inputTransformations;
315
+ // One `message` entry per refused hop, in order — A first. Failed hops are
316
+ // skipped (no usage came back); the serving hop is appended as
317
+ // `fallback_message` when its message_delta arrives.
318
+ const iterations = [
319
+ toIterationUsage('message', a.model ?? '', a.refused.usage),
320
+ ];
321
+ for (let hop = firstHop; hop < fallbacks.length; hop++) {
322
+ const model = fallbacks[hop].model;
323
+ const hasNext = hop + 1 < fallbacks.length;
324
+ pin(hop);
325
+ // --- boundary: a `fallback` content block at the next monotonic index ---
326
+ // Emitted before the request, so a hop that fails leaves its boundary in
327
+ // place and the next attempt emits its own (still `from: fromModel` — the
328
+ // last model that contributed output).
329
+ const fbIndex = nextIndex++;
330
+ yield emit('content_block_start', {
331
+ type: 'content_block_start',
332
+ index: fbIndex,
333
+ content_block: {
334
+ type: 'fallback',
335
+ from: { model: fromModel },
336
+ to: { model },
337
+ trigger: { type: 'refusal', category: refusalDetails?.category ?? null },
338
+ },
339
+ });
340
+ yield emit('content_block_stop', {
341
+ type: 'content_block_stop',
342
+ index: fbIndex,
343
+ });
344
+ // --- build the request: appended-assistant continuation ---
345
+ // First attempt carries the newest partial appended (when its refusal
346
+ // granted a prefill claim); a 400 on that form means the server rejected
347
+ // the prefill, so the hop is retried once without it — the same-body
348
+ // form the token always supports.
349
+ let continuation = [...base, ...partial];
350
+ let resB = null;
351
+ let failure = null;
352
+ for (let attempt = 0; attempt < 2; attempt++) {
353
+ const reqB = buildFallbackRequest(request, { model, creditToken: token, continuation });
354
+ // controller mirrors the original signal and additionally fires when the
355
+ // spliced body is cancelled — either must abort an in-flight hop request.
356
+ reqB.signal = controller.signal;
357
+ try {
358
+ resB = await next(reqB);
359
+ }
360
+ catch (err) {
361
+ // the consumer cancelled (or the original request was aborted): unwind
362
+ if (isAbortError(err))
363
+ throw err;
364
+ failure = {
365
+ kind: 'request_failed',
366
+ message: `fallback request failed: ${err}`,
367
+ model,
368
+ status: null,
369
+ detail: err,
370
+ };
371
+ break;
372
+ }
373
+ if (resB.ok)
374
+ break;
375
+ // ctx.parse reads through an internal clone, so it works even though
376
+ // the client will also read this body; resB.text() would conflict.
377
+ const errBody = await ctx.parse(resB).catch(() => null);
378
+ if (attempt === 0 && resB.status === 400 && partial.length) {
379
+ ctx.logger.warn(`puku-ai/sdk: betaRefusalFallbackMiddleware: fallback request with the partial output appended was rejected (HTTP 400: ${JSON.stringify(errBody)}); retrying without it`);
380
+ continuation = base;
381
+ resB = null;
382
+ continue;
383
+ }
384
+ failure = {
385
+ kind: 'request_failed',
386
+ message: `fallback request failed: HTTP ${resB.status}: ${JSON.stringify(errBody)}`,
387
+ model,
388
+ status: resB.status,
389
+ detail: errBody,
390
+ };
391
+ break;
392
+ }
393
+ if (failure) {
394
+ onError(failure);
395
+ // The token was never redeemed — retry it against the next entry.
396
+ if (hasNext)
397
+ continue;
398
+ // Surface the held refusal verbatim — its category/explanation and the
399
+ // still-unredeemed credit token — and point recommended_model at the hop
400
+ // we last tried.
401
+ const stopDetails = {
402
+ ...refusalDetails,
403
+ recommended_model: model,
404
+ };
405
+ yield emit('message_delta', {
406
+ type: 'message_delta',
407
+ context_management: null,
408
+ delta: {
409
+ stop_reason: 'refusal',
410
+ stop_sequence: null,
411
+ container: null,
412
+ stop_details: stopDetails,
413
+ },
414
+ usage: (lastUsage ?? {}),
415
+ ...(refusalInputTransformations !== undefined && {
416
+ input_transformations: refusalInputTransformations,
417
+ }),
418
+ });
419
+ yield emit('message_stop', { type: 'message_stop' });
420
+ return;
421
+ }
422
+ // --- splice: monotonic indices, suppressed message_start, usage.iterations ---
423
+ const b = yield* consumeHop({
424
+ response: resB,
425
+ controller,
426
+ indexBase: nextIndex,
427
+ hasNext,
428
+ onError,
429
+ splice: { iterations, model },
430
+ });
431
+ if (!b.refused)
432
+ return;
433
+ // This hop refused too, with a fresh token: its emitted partial stays in
434
+ // the client's message, becomes the next partial segment, and the chain
435
+ // continues.
436
+ token = b.refused.token;
437
+ refusalDetails = b.refused.stopDetails;
438
+ refusalInputTransformations = b.refused.inputTransformations;
439
+ base = continuation;
440
+ partial = b.refused.hasPrefillClaim ? toPrefillBlocks(b.blocks) : [];
441
+ iterations.push(toIterationUsage('message', model, b.refused.usage));
442
+ lastUsage = b.refused.usage;
443
+ fromModel = model;
444
+ nextIndex = b.nextIndex;
445
+ }
446
+ }
447
+ /**
448
+ * Consume one hop's SSE events, forwarding them to the client while
449
+ * accumulating its content blocks (returned in the outcome).
450
+ *
451
+ * Stream A (`splice: null`) is forwarded in its original wire bytes; a
452
+ * spliced hop (`splice` set) has its message_start suppressed (the client
453
+ * already saw A's), its block indices shifted by `indexBase`, and its
454
+ * terminal message_delta's usage rewritten to the `usage.iterations`
455
+ * chain shape, with the suppressed message_start's `input_transformations`
456
+ * forwarded onto it.
457
+ *
458
+ * A refusal that can be chained — it carries a `fallback_credit_token` and a
459
+ * fallback entry remains — ends the hop early: open blocks are closed, the
460
+ * terminal message_delta + message_stop are suppressed, and the token+usage
461
+ * are returned so the caller can issue the next hop. Any other refusal is
462
+ * reported through `onError` and passes through to the client.
463
+ */
464
+ async function* consumeHop(args) {
465
+ const { response, controller, indexBase, hasNext, onError, splice } = args;
466
+ const tracker = new BlockTracker(indexBase);
467
+ let model;
468
+ let startUsage = null;
469
+ // A spliced hop's message_start is suppressed, so its `input_transformations`
470
+ // must ride on the re-emitted terminal message_delta — the way a server-side
471
+ // fallback reports the serving model's list.
472
+ let startInputTransformations;
473
+ for await (const sse of Stream.rawEvents(response, controller)) {
474
+ const p = safeJSON(sse.data);
475
+ switch (p?.type) {
476
+ case 'message_start': {
477
+ model = p.message.model;
478
+ startUsage = p.message.usage;
479
+ if ('input_transformations' in p.message)
480
+ startInputTransformations = p.message.input_transformations;
481
+ if (splice)
482
+ continue;
483
+ break;
484
+ }
485
+ case 'content_block_start': {
486
+ tracker.start(p);
487
+ if (splice) {
488
+ yield emit(p.type, p);
489
+ continue;
490
+ }
491
+ break;
492
+ }
493
+ case 'content_block_delta': {
494
+ tracker.delta(p);
495
+ if (splice) {
496
+ yield emit(p.type, p);
497
+ continue;
498
+ }
499
+ break;
500
+ }
501
+ case 'content_block_stop': {
502
+ tracker.stop(p);
503
+ if (splice) {
504
+ yield emit(p.type, p);
505
+ continue;
506
+ }
507
+ break;
508
+ }
509
+ case 'message_delta': {
510
+ if (p.delta.stop_reason === 'refusal') {
511
+ // `fallback_credit_token` is null when the refusal isn't eligible
512
+ // for a fallback credit; without one we don't retry.
513
+ const details = p.delta.stop_details?.type === 'refusal' ? p.delta.stop_details : null;
514
+ if (details?.fallback_credit_token && hasNext) {
515
+ const usage = backfill(p.usage, startUsage);
516
+ yield* tracker.closeOpenBlocks();
517
+ // suppress this hop's message_delta + message_stop
518
+ return {
519
+ refused: {
520
+ token: details.fallback_credit_token,
521
+ hasPrefillClaim: details.fallback_has_prefill_claim === true,
522
+ usage,
523
+ stopDetails: details,
524
+ inputTransformations: splice ? startInputTransformations : undefined,
525
+ },
526
+ model,
527
+ blocks: tracker.contentBlocks(),
528
+ nextIndex: tracker.nextIndex,
529
+ };
530
+ }
531
+ if (!details?.fallback_credit_token) {
532
+ onError({
533
+ kind: 'no_credit_token',
534
+ message: 'refusal stop_details has no fallback_credit_token',
535
+ event: p,
536
+ });
537
+ }
538
+ else {
539
+ onError({
540
+ kind: 'chain_exhausted',
541
+ message: 'refusal but no fallback entries remain',
542
+ event: p,
543
+ });
544
+ }
545
+ }
546
+ if (splice) {
547
+ // Terminal hop. Replace iterations, don't append: this hop's own
548
+ // message_delta self-reports a single `{type:"message",
549
+ // model:undefined}` iteration (a fresh non-fallback request counts
550
+ // itself as one message hop). Server-side `fallbacks` relabels the
551
+ // whole chain instead — refused hops as `message`, the serving hop
552
+ // as `fallback_message` — so spreading the self-report would
553
+ // prepend a spurious `message:undefined` entry.
554
+ const usage = backfill(p.usage, startUsage);
555
+ usage.iterations = [
556
+ ...splice.iterations,
557
+ toIterationUsage('fallback_message', splice.model, usage),
558
+ ];
559
+ p.usage = usage;
560
+ if (!('input_transformations' in p) && startInputTransformations !== undefined) {
561
+ p.input_transformations = startInputTransformations;
562
+ }
563
+ yield emit('message_delta', p);
564
+ continue;
565
+ }
566
+ break;
567
+ }
568
+ }
569
+ // message_stop, ping, error, unrecognised — and for stream A every
570
+ // event — pass through in their original wire bytes.
571
+ yield passthroughSSE(sse);
572
+ }
573
+ return { refused: null, model, blocks: tracker.contentBlocks(), nextIndex: tracker.nextIndex };
574
+ }
575
+ /**
576
+ * Block bookkeeping for one stream of the splice: accumulates each content
577
+ * block from its deltas (for the continuation prefill), shifts wire indices
578
+ * by `indexBase` so they stay monotonic across hops, and tracks which blocks
579
+ * are still open so a refusal that cuts mid-block can close them.
580
+ */
581
+ class BlockTracker {
582
+ indexBase;
583
+ /** The stream's accumulated blocks keyed by their original wire index. */
584
+ blocks = [];
585
+ /** One past the highest shifted block index seen. */
586
+ nextIndex;
587
+ /** Shifted indices of blocks started but not yet stopped. */
588
+ open = [];
589
+ constructor(indexBase = 0) {
590
+ this.indexBase = indexBase;
591
+ this.nextIndex = indexBase;
592
+ }
593
+ /** The accumulated content blocks, in start order. */
594
+ contentBlocks() {
595
+ return this.blocks.map((b) => b.block);
596
+ }
597
+ /** Track a content_block_start, shifting `event.index`. */
598
+ start(event) {
599
+ this.blocks.push({ index: event.index, block: { ...event.content_block } });
600
+ event.index += this.indexBase;
601
+ this.open.push(event.index);
602
+ this.nextIndex = Math.max(this.nextIndex, event.index + 1);
603
+ }
604
+ /** Apply a content_block_delta to its accumulating block, shifting `event.index`. */
605
+ delta(event) {
606
+ applyDelta(this.blocks, event.index, event.delta);
607
+ event.index += this.indexBase;
608
+ }
609
+ /** Track a content_block_stop, shifting `event.index`. */
610
+ stop(event) {
611
+ event.index += this.indexBase;
612
+ const i = this.open.indexOf(event.index);
613
+ if (i !== -1)
614
+ this.open.splice(i, 1);
615
+ this.nextIndex = Math.max(this.nextIndex, event.index + 1);
616
+ }
617
+ /** content_block_stop events for any blocks still open. */
618
+ *closeOpenBlocks() {
619
+ for (const index of this.open) {
620
+ yield emit('content_block_stop', {
621
+ type: 'content_block_stop',
622
+ index,
623
+ });
624
+ }
625
+ this.open.length = 0;
626
+ }
627
+ }
628
+ // --- fallback request construction (appended-assistant continuation) -------
629
+ /**
630
+ * Object form of the redeemed credit token. `best_effort` keeps the retry
631
+ * served if the token layer rejects it — the retry then proceeds at normal
632
+ * price and the outcome lands on `usage.fallback_credit` — where the
633
+ * bare-string (`strict`) form would 400 the whole request.
634
+ */
635
+ function creditTokenParam(token) {
636
+ return { token, mode: 'best_effort' };
637
+ }
638
+ function buildFallbackRequest(orig, { model, creditToken, continuation, }) {
639
+ // the caller guarantees a JSON string body (checked before stream A is read)
640
+ const body = JSON.parse(orig.body);
641
+ body.model = model;
642
+ body.fallback_credit_token = creditTokenParam(creditToken);
643
+ // Append the continuation (decided by the chain loop) as a trailing
644
+ // assistant turn; everything else must stay identical to the refused
645
+ // request. When the refusal granted no prefill claim, omit the turn
646
+ // entirely and send the same-body form.
647
+ if (continuation.length) {
648
+ body.messages = [...body.messages, { role: 'assistant', content: continuation }];
649
+ }
650
+ // Do NOT touch max_tokens (or any other render-shaping field): the token is
651
+ // only redeemable against the same request body as the refused request —
652
+ // model, fallback_credit_token, and the one appended assistant turn are the
653
+ // only permitted deltas; anything else is a 400 ("request body ... does not
654
+ // match the original refused request"). This is also why the per-entry
655
+ // BetaFallbackParam overrides are ignored on the streaming path.
656
+ return { ...orig, headers: new Headers(orig.headers), body: JSON.stringify(body) };
657
+ }
658
+ // --- block accumulation & prefill conversion -------------------------------
659
+ /** Apply a content_block_delta to the accumulating block at `index`. */
660
+ function applyDelta(blocks, index, delta) {
661
+ const block = blocks.find((x) => x.index === index)?.block;
662
+ if (!block)
663
+ return;
664
+ switch (delta.type) {
665
+ case 'text_delta': {
666
+ block.text = (block.text ?? '') + delta.text;
667
+ break;
668
+ }
669
+ case 'input_json_delta': {
670
+ block._partial_json = (block._partial_json ?? '') + delta.partial_json;
671
+ break;
672
+ }
673
+ case 'citations_delta':
674
+ (block.citations ??= []).push(delta.citation);
675
+ break;
676
+ case 'thinking_delta': {
677
+ block.thinking = (block.thinking ?? '') + delta.thinking;
678
+ break;
679
+ }
680
+ case 'signature_delta': {
681
+ block.signature = delta.signature;
682
+ break;
683
+ }
684
+ case 'compaction_delta': {
685
+ break;
686
+ }
687
+ default:
688
+ ((_) => { })(delta);
689
+ }
690
+ }
691
+ /**
692
+ * Convert a hop's accumulated response blocks to the appended assistant turn,
693
+ * as-is: a `fallback_has_prefill_claim` refusal guarantees the partial output
694
+ * is resendable verbatim, so no client-side filtering is applied. The only
695
+ * rewrite is reassembling tool inputs from their accumulated
696
+ * `input_json_delta` JSON (content_block_start carries `input: {}`).
697
+ */
698
+ function toPrefillBlocks(responseBlocks) {
699
+ return responseBlocks.map((b) => {
700
+ if (typeof b?._partial_json !== 'string')
701
+ return b;
702
+ const { _partial_json, ...block } = b;
703
+ return { ...block, input: safeJSON(_partial_json) ?? block.input };
704
+ });
705
+ }
706
+ // --- helpers --------------------------------------------------------------
707
+ /**
708
+ * A copy of `request` with `betas` appended to its `puku-beta` header,
709
+ * skipping values already present (set by the caller or another middleware).
710
+ */
711
+ function withMiddlewareHeaders(request, betas) {
712
+ const headers = new Headers(request.headers);
713
+ const existing = new Set(headers
714
+ .get('puku-beta')
715
+ ?.split(',')
716
+ .map((s) => s.trim()));
717
+ for (const beta of betas) {
718
+ if (!existing.has(beta)) {
719
+ headers.append('puku-beta', beta);
720
+ existing.add(beta);
721
+ }
722
+ }
723
+ headers.set(STAINLESS_HELPER_HEADER, appendHeaderValue(headers.get(STAINLESS_HELPER_HEADER), 'fallback-refusal-middleware'));
724
+ return { ...request, headers };
725
+ }
726
+ function emit(event, payload) {
727
+ const sse = { event, data: JSON.stringify(payload), raw: [] };
728
+ return encoder.encode(serializeSSE(sse));
729
+ }
730
+ /**
731
+ * Forward a decoded event in its original wire bytes, preserving SSE fields
732
+ * the decoder doesn't model (`id:`, `retry:`, comment lines). Falls back to
733
+ * re-serializing for events with no raw lines.
734
+ */
735
+ function passthroughSSE(sse) {
736
+ return encoder.encode(sse.raw.length ? sse.raw.join('\n') + '\n\n' : serializeSSE(sse));
737
+ }
738
+ function toIterationUsage(type, model, u) {
739
+ return {
740
+ type,
741
+ model,
742
+ input_tokens: u?.input_tokens ?? 0,
743
+ output_tokens: u?.output_tokens ?? 0,
744
+ cache_read_input_tokens: u?.cache_read_input_tokens ?? 0,
745
+ cache_creation_input_tokens: u?.cache_creation_input_tokens ?? 0,
746
+ cache_creation: u?.cache_creation ?? null,
747
+ };
748
+ }
749
+ /** Fill null/undefined fields on `primary` from `fallback`. */
750
+ function backfill(primary, fallback) {
751
+ const out = { ...(fallback ?? {}), ...(primary ?? {}) };
752
+ for (const k of Object.keys(out)) {
753
+ if (out[k] == null && fallback?.[k] != null)
754
+ out[k] = fallback[k];
755
+ }
756
+ return out;
757
+ }
758
+ /**
759
+ * Serialize a {@link ServerSentEvent} back to its SSE wire form
760
+ * (`event: ...\ndata: ...\n\n`). Multi-line `data` is emitted as one
761
+ * `data:` line per line, matching the spec. The inverse of the decoder
762
+ * behind {@link Stream.rawEvents}.
763
+ */
764
+ function serializeSSE(sse) {
765
+ let out = '';
766
+ if (sse.event !== null)
767
+ out += `event: ${sse.event}\n`;
768
+ for (const line of sse.data.split('\n'))
769
+ out += `data: ${line}\n`;
770
+ return out + '\n';
771
+ }
772
+ function makeAbort(controller, signal) {
773
+ return () => controller.abort(signal.reason);
774
+ }
775
+ //# sourceMappingURL=middleware.js.map