@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
package/sdk.mjs CHANGED
@@ -1,5 +1,5 @@
1
- var C9=Object.create;var{getPrototypeOf:U9,defineProperty:a1,getOwnPropertyNames:N9}=Object;var F9=Object.prototype.hasOwnProperty;function q9(J){return this[J]}var M9,T9,w9=(J,$,Z)=>{var X=J!=null&&typeof J==="object";if(X){var G=$?M9??=new WeakMap:T9??=new WeakMap,Q=G.get(J);if(Q)return Q}Z=J!=null?C9(U9(J)):{};let Y=$||!J||!J.__esModule?a1(Z,"default",{value:J,enumerable:!0}):Z;for(let z of N9(J))if(!F9.call(Y,z))a1(Y,z,{get:q9.bind(J,z),enumerable:!0});if(X)G.set(J,Y);return Y};var r8=(J,$)=>()=>($||J(($={exports:{}}).exports,$),$.exports);var O9=(J)=>J;function R9(J,$){this[J]=O9.bind(null,$)}var RJ=(J,$)=>{for(var Z in $)a1(J,Z,{get:$[Z],enumerable:!0,configurable:!0,set:R9.bind($,Z)})};var M=(J,$)=>()=>(J&&($=J(J=0)),$);var U2=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return U2=J.randomUUID.bind(J),J.randomUUID();let $=new Uint8Array(1),Z=J?()=>J.getRandomValues($)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(X)=>(+X^Z()&15>>+X/4).toString(16))};function U0(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var a0=(J)=>{if(J instanceof Error)return J;if(typeof J==="object"&&J!==null){try{let $=Object.prototype.toString.call(J);if($==="[object Error]"||$==="[object DOMException]"){let Z=Error(J.message,J.cause?{cause:J.cause}:{});if(J.stack)Z.stack=J.stack;if(J.cause&&!Z.cause)Z.cause=J.cause;if(J.name)Z.name=J.name;return Z}}catch{}try{return Error(JSON.stringify(J))}catch{}}return Error(J)};var T,l,Z0,S0,g2,t8,h2,m2,u2,d2,c2,p2,l2,i2;var c=M(()=>{T=class T extends Error{name="PukuError";constructor(J){super(J);this.name="PukuError"}};l=class l extends T{status;headers;error;requestID;workspaceID;type;constructor(J,$,Z,X,G){super(`${l.makeMessage(J,$,Z)}`);this.status=J,this.headers=X,this.requestID=X?.get("request-id"),this.workspaceID=X?.get("puku-workspace-id"),this.error=$,this.type=G??null}static makeMessage(J,$,Z){let X=$?.message?typeof $.message==="string"?$.message:JSON.stringify($.message):$?JSON.stringify($):Z;if(J&&X)return`${J} ${X}`;if(J)return`${J} status code (no body)`;if(X)return X;return"(no status code or body)"}static generate(J,$,Z,X){if(!J||!X)return new S0({message:Z,cause:a0($)});let G=$,Q=G?.error?.type;if(J===400)return new h2(J,G,Z,X,Q);if(J===401)return new m2(J,G,Z,X,Q);if(J===403)return new u2(J,G,Z,X,Q);if(J===404)return new d2(J,G,Z,X,Q);if(J===409)return new c2(J,G,Z,X,Q);if(J===422)return new p2(J,G,Z,X,Q);if(J===429)return new l2(J,G,Z,X,Q);if(J>=500)return new i2(J,G,Z,X,Q);return new l(J,G,Z,X,Q)}};Z0=class Z0 extends l{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};S0=class S0 extends l{constructor({message:J,cause:$}){super(void 0,void 0,J||"Connection error.",void 0);if($)this.cause=$}};g2=class g2 extends S0{constructor({message:J}={}){super({message:J??"Request timed out."})}};t8=class t8 extends T{constructor(J,{cause:$}={}){super(J??"Retryable error.");if($!==void 0)this.cause=$}};h2=class h2 extends l{};m2=class m2 extends l{};u2=class u2 extends l{};d2=class d2 extends l{};c2=class c2 extends l{};p2=class p2 extends l{};l2=class l2 extends l{};i2=class i2 extends l{}});function n2(J){if(typeof J!=="object")return{};return J??{}}function r1(J){if(!J)return!0;for(let $ in J)return!1;return!0}function HJ(J,$){return Object.prototype.hasOwnProperty.call(J,$)}function t1(J){return J!=null&&typeof J==="object"&&!Array.isArray(J)}function x0(J){}var H9,AJ=(J)=>{return H9.test(J)},X0=(J)=>(X0=Array.isArray,X0(J)),o1,LJ=(J,$)=>{if(typeof $!=="number"||!Number.isInteger($))throw new T(`${J} must be an integer`);if($<0)throw new T(`${J} must be a positive integer`);return $},o0=(J)=>{try{return JSON.parse(J)}catch($){return}},G0=(J,$)=>{let Z=J[$];return delete J[$],Z};var Q0=M(()=>{c();H9=/^[a-z][a-z0-9+.-]*:/i,o1=X0});var T0=(J,$)=>new Promise((Z)=>{if($?.aborted)return Z();let X=()=>{clearTimeout(G),Z()},G=setTimeout(()=>{$?.removeEventListener("abort",X),Z()},J);$?.addEventListener("abort",X,{once:!0})});var B0="0.123.0";function L9(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}function j9(){if(typeof navigator>"u"||!navigator)return null;let J=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:$,pattern:Z}of J){let X=Z.exec(navigator.userAgent);if(X){let G=X[1]||0,Q=X[2]||0,Y=X[3]||0;return{browser:$,version:`${G}.${Q}.${Y}`}}}return null}var PJ=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},D9=()=>{let J=L9();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":jJ(Deno.build.os),"X-Stainless-Arch":DJ(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(J==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":jJ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":DJ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let $=j9();if($)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${$.browser}`,"X-Stainless-Runtime-Version":$.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},DJ=(J)=>{if(J==="x32")return"x32";if(J==="x86_64"||J==="x64")return"x64";if(J==="arm")return"arm";if(J==="aarch64"||J==="arm64")return"arm64";if(J)return`other:${J}`;return"unknown"},jJ=(J)=>{if(J=J.toLowerCase(),J.includes("ios"))return"iOS";if(J==="android")return"Android";if(J==="darwin")return"MacOS";if(J==="win32")return"Windows";if(J==="freebsd")return"FreeBSD";if(J==="openbsd")return"OpenBSD";if(J==="linux")return"Linux";if(J)return`Other:${J}`;return"Unknown"},P9,a2=()=>{return P9??=D9()};var s8=()=>{};function S9(J,$){return()=>J.removeEventListener("abort",$)}function _J(J,$,Z){e8.set(J,S9($,Z))}function EJ(J,$){if(e8.has($))SJ?.register(J,$,$)}function H0(J){let $=e8.get(J);if($)e8.delete(J),SJ?.unregister(J),$()}var e8,SJ;var J1=M(()=>{e8=new WeakMap,SJ=typeof globalThis.FinalizationRegistry==="function"?new globalThis.FinalizationRegistry((J)=>H0(J)):null});function IJ(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new PukuAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function s1(...J){let $=globalThis.ReadableStream;if(typeof $>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new $(...J)}function $1(J){let $=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return s1({start(){},async pull(Z){let{done:X,value:G}=await $.next();if(X)Z.close();else Z.enqueue(G)},async cancel(){await $.return?.()}})}function o2(J){if(J[Symbol.asyncIterator])return J;let $=J.getReader();return{async next(){try{let Z=await $.read();if(Z?.done)$.releaseLock();return Z}catch(Z){throw $.releaseLock(),Z}},async return(){let Z=$.cancel();return $.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function yJ(J){if(J===null||typeof J!=="object")return;if(J[Symbol.asyncIterator]){await J[Symbol.asyncIterator]().return?.();return}let $=J.getReader(),Z=$.cancel();$.releaseLock(),await Z}class e1{index}var xJ=({headers:J,body:$})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify($)}};var J6="RFC3986",$6=(J)=>String(J),Z6,kJ="RFC1738";var X6=M(()=>{Z6={RFC1738:(J)=>String(J).replace(/%20/g,"+"),RFC3986:$6}});function vJ(J){if(!J||typeof J!=="object")return!1;return!!(J.constructor&&J.constructor.isBuffer&&J.constructor.isBuffer(J))}function Q6(J,$){if(X0(J)){let Z=[];for(let X=0;X<J.length;X+=1)Z.push($(J[X]));return Z}return $(J)}var Z1=(J,$)=>(Z1=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Z1(J,$)),L0,G6=1024,fJ=(J,$,Z,X,G)=>{if(J.length===0)return J;let Q=J;if(typeof J==="symbol")Q=Symbol.prototype.toString.call(J);else if(typeof J!=="string")Q=String(J);if(Z==="iso-8859-1")return escape(Q).replace(/%u[0-9a-f]{4}/gi,function(z){return"%26%23"+parseInt(z.slice(2),16)+"%3B"});let Y="";for(let z=0;z<Q.length;z+=G6){let B=Q.length>=G6?Q.slice(z,z+G6):Q,K=[];for(let W=0;W<B.length;++W){let C=B.charCodeAt(W);if(C===45||C===46||C===95||C===126||C>=48&&C<=57||C>=65&&C<=90||C>=97&&C<=122||G===kJ&&(C===40||C===41)){K[K.length]=B.charAt(W);continue}if(C<128){K[K.length]=L0[C];continue}if(C<2048){K[K.length]=L0[192|C>>6]+L0[128|C&63];continue}if(C<55296||C>=57344){K[K.length]=L0[224|C>>12]+L0[128|C>>6&63]+L0[128|C&63];continue}W+=1,C=65536+((C&1023)<<10|B.charCodeAt(W)&1023),K[K.length]=L0[240|C>>18]+L0[128|C>>12&63]+L0[128|C>>6&63]+L0[128|C&63]}Y+=K.join("")}return Y};var bJ=M(()=>{X6();Q0();L0=(()=>{let J=[];for(let $=0;$<256;++$)J.push("%"+(($<16?"0":"")+$.toString(16)).toUpperCase());return J})()});function y9(J){return typeof J==="string"||typeof J==="number"||typeof J==="boolean"||typeof J==="symbol"||typeof J==="bigint"}function mJ(J,$,Z,X,G,Q,Y,z,B,K,W,C,V,F,q,A,R,H){let O=J,D=H,S=0,y=!1;while((D=D.get(Y6))!==void 0&&!y){let b=D.get(J);if(S+=1,typeof b<"u")if(b===S)throw RangeError("Cyclic object value");else y=!0;if(typeof D.get(Y6)>"u")S=0}if(typeof K==="function")O=K($,O);else if(O instanceof Date)O=V?.(O);else if(Z==="comma"&&X0(O))O=Q6(O,function(b){if(b instanceof Date)return V?.(b);return b});if(O===null){if(Q)return B&&!A?B($,a.encoder,R,"key",F):$;O=""}if(y9(O)||vJ(O)){if(B){let b=A?$:B($,a.encoder,R,"key",F);return[q?.(b)+"="+q?.(B(O,a.encoder,R,"value",F))]}return[q?.($)+"="+q?.(String(O))]}let f=[];if(typeof O>"u")return f;let v;if(Z==="comma"&&X0(O)){if(A&&B)O=Q6(O,B);v=[{value:O.length>0?O.join(",")||null:void 0}]}else if(X0(K))v=K;else{let b=Object.keys(O);v=W?b.sort(W):b}let g=z?String($).replace(/\./g,"%2E"):String($),d=X&&X0(O)&&O.length===1?g+"[]":g;if(G&&X0(O)&&O.length===0)return d+"[]";for(let b=0;b<v.length;++b){let t=v[b],A0=typeof t==="object"&&typeof t.value<"u"?t.value:O[t];if(Y&&A0===null)continue;let n0=C&&z?t.replace(/\./g,"%2E"):t,C2=X0(O)?typeof Z==="function"?Z(d,n0):d:d+(C?"."+n0:"["+n0+"]");H.set(J,S);let OJ=new WeakMap;OJ.set(Y6,H),hJ(f,mJ(A0,C2,Z,X,G,Q,Y,z,Z==="comma"&&A&&X0(O)?null:B,K,W,C,V,F,q,A,R,OJ))}return f}function x9(J=a){if(typeof J.allowEmptyArrays<"u"&&typeof J.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof J.encodeDotInKeys<"u"&&typeof J.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(J.encoder!==null&&typeof J.encoder<"u"&&typeof J.encoder!=="function")throw TypeError("Encoder has to be a function.");let $=J.charset||a.charset;if(typeof J.charset<"u"&&J.charset!=="utf-8"&&J.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let Z=J6;if(typeof J.format<"u"){if(!Z1(Z6,J.format))throw TypeError("Unknown format option provided.");Z=J.format}let X=Z6[Z],G=a.filter;if(typeof J.filter==="function"||X0(J.filter))G=J.filter;let Q;if(J.arrayFormat&&J.arrayFormat in gJ)Q=J.arrayFormat;else if("indices"in J)Q=J.indices?"indices":"repeat";else Q=a.arrayFormat;if("commaRoundTrip"in J&&typeof J.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let Y=typeof J.allowDots>"u"?!!J.encodeDotInKeys===!0?!0:a.allowDots:!!J.allowDots;return{addQueryPrefix:typeof J.addQueryPrefix==="boolean"?J.addQueryPrefix:a.addQueryPrefix,allowDots:Y,allowEmptyArrays:typeof J.allowEmptyArrays==="boolean"?!!J.allowEmptyArrays:a.allowEmptyArrays,arrayFormat:Q,charset:$,charsetSentinel:typeof J.charsetSentinel==="boolean"?J.charsetSentinel:a.charsetSentinel,commaRoundTrip:!!J.commaRoundTrip,delimiter:typeof J.delimiter>"u"?a.delimiter:J.delimiter,encode:typeof J.encode==="boolean"?J.encode:a.encode,encodeDotInKeys:typeof J.encodeDotInKeys==="boolean"?J.encodeDotInKeys:a.encodeDotInKeys,encoder:typeof J.encoder==="function"?J.encoder:a.encoder,encodeValuesOnly:typeof J.encodeValuesOnly==="boolean"?J.encodeValuesOnly:a.encodeValuesOnly,filter:G,format:Z,formatter:X,serializeDate:typeof J.serializeDate==="function"?J.serializeDate:a.serializeDate,skipNulls:typeof J.skipNulls==="boolean"?J.skipNulls:a.skipNulls,sort:typeof J.sort==="function"?J.sort:null,strictNullHandling:typeof J.strictNullHandling==="boolean"?J.strictNullHandling:a.strictNullHandling}}function uJ(J,$={}){let Z=J,X=x9($),G,Q;if(typeof X.filter==="function")Q=X.filter,Z=Q("",Z);else if(X0(X.filter))Q=X.filter,G=Q;let Y=[];if(typeof Z!=="object"||Z===null)return"";let z=gJ[X.arrayFormat],B=z==="comma"&&X.commaRoundTrip;if(!G)G=Object.keys(Z);if(X.sort)G.sort(X.sort);let K=new WeakMap;for(let V=0;V<G.length;++V){let F=G[V];if(X.skipNulls&&Z[F]===null)continue;hJ(Y,mJ(Z[F],F,z,B,X.allowEmptyArrays,X.strictNullHandling,X.skipNulls,X.encodeDotInKeys,X.encode?X.encoder:null,X.filter,X.sort,X.allowDots,X.serializeDate,X.format,X.formatter,X.encodeValuesOnly,X.charset,K))}let W=Y.join(X.delimiter),C=X.addQueryPrefix===!0?"?":"";if(X.charsetSentinel)if(X.charset==="iso-8859-1")C+="utf8=%26%2310003%3B&";else C+="utf8=%E2%9C%93&";return W.length>0?C+W:""}var gJ,hJ=function(J,$){Array.prototype.push.apply(J,X0($)?$:[$])},I9,a,Y6;var dJ=M(()=>{bJ();X6();Q0();gJ={brackets(J){return String(J)+"[]"},comma:"comma",indices(J,$){return String(J)+"["+$+"]"},repeat(J){return String(J)}},a={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fJ,encodeValuesOnly:!1,format:J6,formatter:$6,indices:!1,serializeDate(J){return(I9??=Function.prototype.call.bind(Date.prototype.toISOString))(J)},skipNulls:!1,strictNullHandling:!1};Y6={}});function cJ(J){return uJ(J,{arrayFormat:"brackets"})}var z6=M(()=>{dJ()});var D0={};RJ(D0,{util:()=>K6,stream:()=>X1,path:()=>j,os:()=>f9,fs:()=>_0,crypto:()=>k0,child_process:()=>B6});import*as B6 from"node:child_process";import*as k0 from"node:crypto";import*as _0 from"node:fs";import*as f9 from"node:os";import*as j from"node:path";import*as X1 from"node:stream";import*as K6 from"node:util";var K0=()=>{};function Q1(J){if(!J)return;let $;try{$=new URL(J)}catch(X){throw new m(`Invalid token endpoint base URL "${J}": ${X}`)}if($.protocol==="https:")return;let Z=$.hostname.toLowerCase().replace(/^\[|\]$/g,"");if($.protocol==="http:"&&(Z==="localhost"||Z==="127.0.0.1"||Z==="::1"))return;throw new m(`Refusing to send credential over non-https token endpoint "${J}"`)}async function Y1(J,$){let Z=await b9(J),X;try{X=JSON.parse(Z)}catch{throw new m(`Token endpoint returned non-JSON response (status ${J.status})`,J.status,W0(Z),$)}if(!X.access_token)throw new m(`Token endpoint response missing access_token: ${JSON.stringify(W0(X))}`,J.status,W0(X),$);if(X.token_type&&X.token_type.toLowerCase()!=="bearer")throw new m(`Token endpoint response: unsupported token_type "${X.token_type}" (want Bearer)`,J.status,W0(X),$);return X}function W0(J){if(J==null)return J;if(typeof J==="string"){let $;try{$=JSON.parse(J)}catch{if(J.length<=W6)return J;return J.slice(0,W6)+`... <${J.length-W6} more chars>`}return JSON.stringify(W0($))}if(typeof J==="object"&&!Array.isArray(J)){let $={};for(let[Z,X]of Object.entries(J))if(v9.has(Z))$[Z]=X;return $}return null}async function z1(J,$=(Z)=>console.warn(`puku-ai/sdk: ${Z}`)){if(typeof process>"u"||process.platform==="win32")return;let{fs:Z}=await Promise.resolve().then(() => (K0(),D0)),X=J,G;try{X=await Z.promises.realpath(J),G=await Z.promises.stat(X)}catch{return}let Q=G.mode&511;if(Q&18)throw new m(`Credentials file at ${X} is group/world-writable (mode 0o${Q.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${X}\`.`);if(Q&36)throw new m(`Credentials file at ${X} is group/world-readable (mode 0o${Q.toString(8)}); run \`chmod 600 ${X}\` before retrying.`);if(typeof process.getuid==="function"&&G.uid!==process.getuid())$(`credentials file at ${X} is owned by uid ${G.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function B1(J,$){let{fs:Z,path:X}=await Promise.resolve().then(() => (K0(),D0)),G=X.dirname(J);await Z.promises.mkdir(G,{recursive:!0,mode:448});let Q=`${J}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let Y=await Z.promises.open(Q,"w",384);try{await Y.writeFile(JSON.stringify($,null,2)),await Y.sync()}finally{await Y.close()}await Z.promises.rename(Q,J)}catch(Y){throw await Z.promises.unlink(Q).catch(()=>{}),Y}try{let Y=await Z.promises.open(G,"r");try{await Y.sync()}finally{await Y.close()}}catch{}}async function b9(J){if(!J.body)return"";let $=J.body.getReader(),Z=[],X=0;for(;;){let{done:Q,value:Y}=await $.read();if(Q)break;if(X+Y.length>pJ){let z=pJ-X;if(z>0)Z.push(Y.subarray(0,z));await $.cancel();break}Z.push(Y),X+=Y.length}let G;if(Z.length===1)G=Z[0];else{G=new Uint8Array(Z.reduce((Y,z)=>Y+z.length,0));let Q=0;for(let Y of Z)G.set(Y,Q),Q+=Y.length}return new TextDecoder("utf-8").decode(G)}var lJ="urn:ietf:params:oauth:grant-type:jwt-bearer",iJ="refresh_token",G1="/v1/oauth/token",f0="oauth-2025-04-20",V6="oidc-federation-2026-04-01",nJ=120,N2=30,aJ=5,pJ=1048576,W6=2000,v9,m;var r0=M(()=>{c();v9=new Set(["error","error_description","error_uri"]);m=class m extends T{statusCode;body;requestId;constructor(J,$=null,Z=null,X=null){super(J);this.statusCode=$,this.body=Z,this.requestId=X}}});function w0(){return Math.floor(Date.now()/1000)}class C6{provider;cached=null;pendingRefresh=null;nextForce=!1;lastAdvisoryError=0;onAdvisoryRefreshError;constructor(J,$){this.provider=J,this.onAdvisoryRefreshError=$}async getToken(){let J=this.nextForce;this.nextForce=!1;let $=this.cached;if(J||$==null)return(await this.refresh(J)).token;if($.expiresAt==null)return $.token;let Z=$.expiresAt-w0();if(Z>nJ)return $.token;if(Z>N2)return this.backgroundRefresh(),$.token;return(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(J=!1){if(this.pendingRefresh&&!J)return this.pendingRefresh;return this.doRefresh(J)}backgroundRefresh(){if(this.pendingRefresh)return;if(w0()-this.lastAdvisoryError<aJ)return;this.doRefresh().catch((J)=>{this.lastAdvisoryError=w0(),this.onAdvisoryRefreshError?.(J)})}doRefresh(J=!1){return this.pendingRefresh=this.provider(J?{forceRefresh:!0}:void 0).then(($)=>{return this.cached=$,this.pendingRefresh=null,$},($)=>{throw this.pendingRefresh=null,$}),this.pendingRefresh}}var oJ=M(()=>{r0()});var x=(J)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[J]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(J)?.trim()||void 0;return};function sJ(J){let $=0;for(let G of J)$+=G.length;let Z=new Uint8Array($),X=0;for(let G of J)Z.set(G,X),X+=G.length;return Z}function v0(J){let $;return(rJ??($=new globalThis.TextEncoder,rJ=$.encode.bind($)))(J)}function t0(J){let $;return(tJ??($=new globalThis.TextDecoder,tJ=$.decode.bind($)))(J)}var rJ,tJ;var r2=(J)=>{if(typeof globalThis.Buffer<"u"){let $=globalThis.Buffer.from(J,"base64");return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}if(typeof atob<"u"){let $=atob(J),Z=new Uint8Array($.length);for(let X=0;X<$.length;X++)Z[X]=$.charCodeAt(X);return Z}throw new T("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")};var K1=M(()=>{c()});function t2(){}function W1(J,$,Z){if(!$||V1[J]>V1[Z])return t2;else return $[J].bind($)}function N6(J,$){let Z=eJ.get(J);if(Z&&Z[0]===$)return Z[1];let X={error:W1("error",J,$),warn:W1("warn",J,$),info:W1("info",J,$),debug:W1("debug",J,$)};return eJ.set(J,[$,X]),X}function k(J){let $=J.logger,Z=J.logLevel??"off";if(!$)return g9;return N6($,Z)}function $$(){let J=x("PUKU_LOG");if(!U6||J!==J$)J$=J,U6=N6(console,C1(J,"process.env['PUKU_LOG']",N6(console,s2))??s2);return U6}var s2="warn",V1,C1=(J,$,Z)=>{if(!J)return;if(HJ(V1,J))return J;Z.warn(`${$} was set to ${JSON.stringify(J)}, expected one of ${JSON.stringify(Object.keys(V1))}`);return},g9,eJ,J$,U6,j0=(J)=>{if(J.options)J.options={...J.options},delete J.options.headers;if(J.headers)J.headers=Object.fromEntries((J.headers instanceof Headers?[...J.headers]:Object.entries(J.headers)).map(([$,Z])=>[$,$.toLowerCase()==="authorization"||$.toLowerCase()==="api-key"||$.toLowerCase()==="x-api-key"||$.toLowerCase()==="cookie"||$.toLowerCase()==="set-cookie"?"***":Z]));if("retryOfRequestLogID"in J){if(J.retryOfRequestLogID)J.retryOf=J.retryOfRequestLogID;delete J.retryOfRequestLogID}return J};var O0=M(()=>{Q0();V1={off:0,error:200,warn:300,info:400,debug:500};g9={error:t2,warn:t2,info:t2,debug:t2},eJ=new WeakMap});var F6=M(()=>{Q0();K1();O0();z6()});function Z$(J){if(!J)throw Error("profile name is empty");if(J==="."||J==="..")throw Error(`profile name "${J}" is not allowed`);if(J.includes("/")||J.includes("\\"))throw Error(`profile name "${J}" must not contain path separators`);if(!h9.test(J))throw Error(`profile name "${J}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var U1="1.0",h9,X$=async(J)=>{let $=await q6();if($===null)return null;let Z=J??await Q$();if(Z===null)return null;Z$(Z);let{fs:X,path:G}=await Promise.resolve().then(() => (K0(),D0)),Q=G.join($,"configs",`${Z}.json`),Y;try{Y=await X.promises.readFile(Q,"utf-8")}catch(K){if(K?.code!=="ENOENT")throw Error(`failed to read config file ${Q}: ${K}`);Y=null}if(Y===null){let K=x("PUKU_ORGANIZATION_ID"),W=x("PUKU_IDENTITY_TOKEN_FILE"),C=x("PUKU_FEDERATION_RULE_ID");if(C&&K)return{fromFile:!1,config:{organization_id:K,workspace_id:x("PUKU_WORKSPACE_ID"),base_url:x("PUKU_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:C,service_account_id:x("PUKU_SERVICE_ACCOUNT_ID"),identity_token:W?{source:"file",path:W}:void 0,scope:x("PUKU_SCOPE")}}};return null}let z;try{z=JSON.parse(Y)}catch(K){throw Error(`failed to parse config file ${Q}: ${K}`)}if(!z.authentication)throw Error(`config file ${Q} is missing "authentication"`);let B=z.authentication.type;if(B!=="oidc_federation"&&B!=="user_oauth")throw Error(`authentication.type "${B}" is not a known authentication type`);if(z.organization_id??=x("PUKU_ORGANIZATION_ID"),z.workspace_id??=x("PUKU_WORKSPACE_ID"),z.base_url??=x("PUKU_BASE_URL"),z.authentication.scope??=x("PUKU_SCOPE"),z.authentication.type==="oidc_federation"){if(!z.authentication.identity_token){let K=x("PUKU_IDENTITY_TOKEN_FILE");if(K)z.authentication.identity_token={source:"file",path:K}}if(!z.authentication.federation_rule_id)z.authentication.federation_rule_id=x("PUKU_FEDERATION_RULE_ID")??"";z.authentication.service_account_id??=x("PUKU_SERVICE_ACCOUNT_ID")}return{config:z,fromFile:!0}},G$=async(J,$)=>{if(J?.authentication.credentials_path)return J.authentication.credentials_path;let Z=await q6();if(!Z)return null;let X=$??await Q$();if(!X)return null;Z$(X);let{path:G}=await Promise.resolve().then(() => (K0(),D0));return G.join(Z,"credentials",`${X}.json`)},q6=async()=>{if(!m9())return null;let{path:J}=await Promise.resolve().then(() => (K0(),D0)),$=x("PUKU_CONFIG_DIR");if($)return $;if(a2()["X-Stainless-OS"]==="Windows"){let Q=x("APPDATA");if(Q)return J.join(Q,"PukuAI");let Y=x("USERPROFILE");if(Y)return J.join(Y,"AppData","Roaming","PukuAI");return null}let X=x("XDG_CONFIG_HOME");if(X)return J.join(X,"puku");let G=x("HOME");if(G)return J.join(G,".config","puku");return null},m9=()=>{let J=a2()["X-Stainless-Runtime"];return J==="node"||J==="deno"},Q$=async()=>{let J=await q6();if(!J)return null;let $=x("PUKU_PROFILE");if($)return $;let{fs:Z,path:X}=await Promise.resolve().then(() => (K0(),D0)),G=X.join(J,"active_config");try{return(await Z.promises.readFile(G,"utf-8")).trim()||"default"}catch(Q){if(Q?.code!=="ENOENT")throw Error(`failed to read ${G}: ${Q}`);return"default"}};var M6=M(()=>{s8();F6();h9=/^[A-Za-z0-9_.-]+$/});function T6(J){if(!J)throw new T("Identity token file path is empty");return async()=>{let{fs:$}=await Promise.resolve().then(() => (K0(),D0)),Z;try{Z=await $.promises.readFile(J,"utf-8")}catch(G){throw new T(`Failed to read identity token file at ${J}: ${G}`)}let X=Z.trim();if(!X)throw new T(`Identity token file at ${J} is empty`);return X}}function Y$(J){if(!J)throw new T("Identity token value is empty");return()=>J}var z$=M(()=>{c()});function B$(J){return async()=>{Q1(J.baseURL);let $=await J.identityTokenProvider();if($.length>16384)throw new m(`Identity token is ${Math.ceil($.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let Z={grant_type:lJ,assertion:$,federation_rule_id:J.federationRuleId,organization_id:J.organizationId};if(J.serviceAccountId)Z.service_account_id=J.serviceAccountId;if(J.workspaceId)Z.workspace_id=J.workspaceId;let X=`${J.baseURL}${G1}`,G;try{G=await J.fetch(X,{method:"POST",headers:{"Content-Type":"application/json","puku-beta":`${f0},${V6}`,"User-Agent":J.userAgent||`puku-ai-sdk-typescript/${B0} oidcFederationProvider`},body:JSON.stringify(Z)})}catch(B){throw new m(`Failed to reach token endpoint ${X}: ${B}`)}let Q=G.headers.get("Request-Id");if(!G.ok){let B=await G.text().catch(()=>""),K=W0(B),W="";if(G.status===401)W=` Ensure your federation rule matches your identity token. ${J.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the PUKU_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Puku Console for more details.`;throw new m(`Token exchange failed with status ${G.status}${Q?` (request-id ${Q})`:""}: ${K}${W}`,G.status,K,Q)}let Y=await Y1(G,Q),z=Number(Y.expires_in);if(!Number.isFinite(z))throw new m(`Token endpoint response missing required fields: ${JSON.stringify(W0(Y))}`,G.status,W0(Y),Q);return{token:Y.access_token,expiresAt:w0()+z}}}var K$=M(()=>{r0()});function W$(J){return async($)=>{let{fs:Z}=await Promise.resolve().then(() => (K0(),D0));await z1(J.credentialsPath,J.onSafetyWarning);let X;try{X=await Z.promises.readFile(J.credentialsPath,"utf-8")}catch(R){throw new m(`Credentials file not found at ${J.credentialsPath}: ${R}`)}let G;try{G=JSON.parse(X)}catch(R){throw new m(`Credentials file at ${J.credentialsPath} is not valid JSON: ${R}`)}let Q=G.access_token;if(!Q)throw new m(`Credentials file at ${J.credentialsPath} must include 'access_token'`);let Y=G.expires_at;if(!$?.forceRefresh&&(Y==null||w0()<Y-N2))return{token:Q,expiresAt:Y??null};let z=G.refresh_token;if(!J.clientId||!z)throw new m(`Access token at ${J.credentialsPath} has expired and no refresh is available (client_id ${J.clientId?"set":"empty"}, refresh_token ${z?"set":"empty"})`);Q1(J.baseURL);let B={grant_type:iJ,refresh_token:z,client_id:J.clientId},K=`${J.baseURL}${G1}`,W;try{W=await J.fetch(K,{method:"POST",headers:{"Content-Type":"application/json","puku-beta":f0,"User-Agent":J.userAgent||`puku-ai-sdk-typescript/${B0} userOAuthProvider`},body:JSON.stringify(B)})}catch(R){throw new m(`User OAuth refresh failed to reach token endpoint: ${R}`)}let C=W.headers.get("Request-Id");if(!W.ok){let R=await W.text().catch(()=>"");throw new m(`User OAuth refresh failed (HTTP ${W.status}): ${W0(R)}`,W.status,W0(R),C)}let V=await Y1(W,C),F=Number(V.expires_in);if(!Number.isFinite(F))throw new m(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(W0(V))}`,W.status,W0(V),C);let q=w0()+F,A=V.refresh_token||z;return await B1(J.credentialsPath,{...G,version:U1,type:"oauth_token",access_token:V.access_token,expires_at:q,refresh_token:A}),{token:V.access_token,expiresAt:q}}}var V$=M(()=>{M6();r0()});function w6(J,$){let Z=J.authentication.credentials_path??null,X=(J.base_url||$.baseURL).replace(/\/+$/,""),G=u9(J,Z,X,$),Q={};if(J.workspace_id&&J.authentication.type==="user_oauth")Q["puku-workspace-id"]=J.workspace_id;return{provider:G,extraHeaders:Q,baseURL:J.base_url||void 0}}async function C$(J,$){let Z=await X$($);if(!Z)return null;let{config:X,fromFile:G}=Z,Q=X.authentication.credentials_path||!G?X:{...X,authentication:{...X.authentication,credentials_path:await G$(X,$)??void 0}};return w6(Q,J)}function u9(J,$,Z,X){switch(J.authentication.type){case"oidc_federation":{let G=J.authentication,Q=d9(G);if(!Q)throw new m("oidc_federation config requires an identity token (set authentication.identity_token, PUKU_IDENTITY_TOKEN_FILE, or PUKU_IDENTITY_TOKEN)");if(!G.federation_rule_id)throw new m("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via PUKU_FEDERATION_RULE_ID (profile takes precedence).");if(!J.organization_id)throw new m("oidc_federation config requires organization_id (set PUKU_ORGANIZATION_ID or config.organization_id)");let Y=B$({identityTokenProvider:Q,federationRuleId:G.federation_rule_id,organizationId:J.organization_id,serviceAccountId:G.service_account_id,workspaceId:J.workspace_id,baseURL:Z,fetch:X.fetch,userAgent:X.userAgent});if($)return c9(Y,$,X.onCacheWriteError,X.onSafetyWarning);return Y}case"user_oauth":{if(!$)throw new m("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return W$({credentialsPath:$,clientId:J.authentication.client_id,baseURL:Z,fetch:X.fetch,userAgent:X.userAgent,onSafetyWarning:X.onSafetyWarning})}default:{let G=J.authentication.type;throw new m(`authentication.type "${G}" is not a known authentication type`)}}}function d9(J){if(J.identity_token){let X=J.identity_token.source;if(X!=="file")throw new m(`identity_token.source "${X}" is not supported by this SDK version (only "file")`);if(!J.identity_token.path)throw new m('identity_token.source "file" requires a non-empty path');return T6(J.identity_token.path)}let $=x("PUKU_IDENTITY_TOKEN_FILE");if($)return T6($);let Z=x("PUKU_IDENTITY_TOKEN");if(Z)return Y$(Z);return null}function c9(J,$,Z,X){return async(G)=>{let{fs:Q}=await Promise.resolve().then(() => (K0(),D0));await z1($,X);let Y;try{let B=await Q.promises.readFile($,"utf-8");Y=JSON.parse(B);let K=Y?.access_token;if(K&&!G?.forceRefresh){let W=Y?.expires_at;if(W==null||w0()<W-N2)return{token:K,expiresAt:W??null}}}catch(B){if(B?.code!=="ENOENT"&&!(B instanceof SyntaxError))Z?.(B)}let z=await J(G);try{await B1($,{...Y??{},version:U1,type:"oauth_token",access_token:z.token,expires_at:z.expiresAt})}catch(B){Z?.(B)}return z}}var U$=M(()=>{M6();r0();z$();K$();V$()});function p9(J,$){for(let G=$??0;G<J.length;G++){if(J[G]===10)return{preceding:G,index:G+1,carriage:!1};if(J[G]===13)return{preceding:G,index:G+1,carriage:!0}}return null}function N$(J){for(let X=0;X<J.length-1;X++){if(J[X]===10&&J[X+1]===10)return X+2;if(J[X]===13&&J[X+1]===13)return X+2;if(J[X]===13&&J[X+1]===10&&X+3<J.length&&J[X+2]===13&&J[X+3]===10)return X+4}return-1}var F2;var O6=M(()=>{F2=class F2{static NEWLINE_CHARS=new Set([`
2
- `,"\r"]);static NEWLINE_REGEXP=/\r\n|[\n\r]/g;#J;#$;constructor(){this.#J=new Uint8Array,this.#$=null}decode(J){if(J==null)return[];let $=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?v0(J):J;this.#J=sJ([this.#J,$]);let Z=[],X;while((X=p9(this.#J,this.#$))!=null){if(X.carriage&&this.#$==null){this.#$=X.index;continue}if(this.#$!=null&&(X.index!==this.#$+1||X.carriage)){Z.push(t0(this.#J.subarray(0,this.#$-1))),this.#J=this.#J.subarray(this.#$),this.#$=null;continue}let G=this.#$!==null?X.preceding-1:X.preceding,Q=t0(this.#J.subarray(0,G));Z.push(Q),this.#J=this.#J.subarray(X.index),this.#$=null}return Z}flush(){if(!this.#J.length)return[];return this.decode(`
1
+ var C9=Object.create;var{getPrototypeOf:U9,defineProperty:a1,getOwnPropertyNames:N9}=Object;var F9=Object.prototype.hasOwnProperty;function q9(J){return this[J]}var M9,T9,w9=(J,$,Z)=>{var X=J!=null&&typeof J==="object";if(X){var G=$?M9??=new WeakMap:T9??=new WeakMap,Q=G.get(J);if(Q)return Q}Z=J!=null?C9(U9(J)):{};let Y=$||!J||!J.__esModule?a1(Z,"default",{value:J,enumerable:!0}):Z;for(let z of N9(J))if(!F9.call(Y,z))a1(Y,z,{get:q9.bind(J,z),enumerable:!0});if(X)G.set(J,Y);return Y};var r8=(J,$)=>()=>($||J(($={exports:{}}).exports,$),$.exports);var O9=(J)=>J;function R9(J,$){this[J]=O9.bind(null,$)}var R4=(J,$)=>{for(var Z in $)a1(J,Z,{get:$[Z],enumerable:!0,configurable:!0,set:R9.bind($,Z)})};var M=(J,$)=>()=>(J&&($=J(J=0)),$);var U2=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return U2=J.randomUUID.bind(J),J.randomUUID();let $=new Uint8Array(1),Z=J?()=>J.getRandomValues($)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(X)=>(+X^Z()&15>>+X/4).toString(16))};function U0(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var a0=(J)=>{if(J instanceof Error)return J;if(typeof J==="object"&&J!==null){try{let $=Object.prototype.toString.call(J);if($==="[object Error]"||$==="[object DOMException]"){let Z=Error(J.message,J.cause?{cause:J.cause}:{});if(J.stack)Z.stack=J.stack;if(J.cause&&!Z.cause)Z.cause=J.cause;if(J.name)Z.name=J.name;return Z}}catch{}try{return Error(JSON.stringify(J))}catch{}}return Error(J)};var T,l,Z0,S0,g2,t8,h2,m2,u2,d2,c2,p2,l2,i2;var c=M(()=>{T=class T extends Error{name="PukuError";constructor(J){super(J);this.name="PukuError"}};l=class l extends T{status;headers;error;requestID;workspaceID;type;constructor(J,$,Z,X,G){super(`${l.makeMessage(J,$,Z)}`);this.status=J,this.headers=X,this.requestID=X?.get("request-id"),this.workspaceID=X?.get("puku-workspace-id"),this.error=$,this.type=G??null}static makeMessage(J,$,Z){let X=$?.message?typeof $.message==="string"?$.message:JSON.stringify($.message):$?JSON.stringify($):Z;if(J&&X)return`${J} ${X}`;if(J)return`${J} status code (no body)`;if(X)return X;return"(no status code or body)"}static generate(J,$,Z,X){if(!J||!X)return new S0({message:Z,cause:a0($)});let G=$,Q=G?.error?.type;if(J===400)return new h2(J,G,Z,X,Q);if(J===401)return new m2(J,G,Z,X,Q);if(J===403)return new u2(J,G,Z,X,Q);if(J===404)return new d2(J,G,Z,X,Q);if(J===409)return new c2(J,G,Z,X,Q);if(J===422)return new p2(J,G,Z,X,Q);if(J===429)return new l2(J,G,Z,X,Q);if(J>=500)return new i2(J,G,Z,X,Q);return new l(J,G,Z,X,Q)}};Z0=class Z0 extends l{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};S0=class S0 extends l{constructor({message:J,cause:$}){super(void 0,void 0,J||"Connection error.",void 0);if($)this.cause=$}};g2=class g2 extends S0{constructor({message:J}={}){super({message:J??"Request timed out."})}};t8=class t8 extends T{constructor(J,{cause:$}={}){super(J??"Retryable error.");if($!==void 0)this.cause=$}};h2=class h2 extends l{};m2=class m2 extends l{};u2=class u2 extends l{};d2=class d2 extends l{};c2=class c2 extends l{};p2=class p2 extends l{};l2=class l2 extends l{};i2=class i2 extends l{}});function n2(J){if(typeof J!=="object")return{};return J??{}}function r1(J){if(!J)return!0;for(let $ in J)return!1;return!0}function H4(J,$){return Object.prototype.hasOwnProperty.call(J,$)}function t1(J){return J!=null&&typeof J==="object"&&!Array.isArray(J)}function x0(J){}var H9,A4=(J)=>{return H9.test(J)},X0=(J)=>(X0=Array.isArray,X0(J)),o1,L4=(J,$)=>{if(typeof $!=="number"||!Number.isInteger($))throw new T(`${J} must be an integer`);if($<0)throw new T(`${J} must be a positive integer`);return $},o0=(J)=>{try{return JSON.parse(J)}catch($){return}},G0=(J,$)=>{let Z=J[$];return delete J[$],Z};var Q0=M(()=>{c();H9=/^[a-z][a-z0-9+.-]*:/i,o1=X0});var T0=(J,$)=>new Promise((Z)=>{if($?.aborted)return Z();let X=()=>{clearTimeout(G),Z()},G=setTimeout(()=>{$?.removeEventListener("abort",X),Z()},J);$?.addEventListener("abort",X,{once:!0})});var B0="4.0.2";function L9(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}function j9(){if(typeof navigator>"u"||!navigator)return null;let J=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:$,pattern:Z}of J){let X=Z.exec(navigator.userAgent);if(X){let G=X[1]||0,Q=X[2]||0,Y=X[3]||0;return{browser:$,version:`${G}.${Q}.${Y}`}}}return null}var P4=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},D9=()=>{let J=L9();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":j4(Deno.build.os),"X-Stainless-Arch":D4(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(J==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":j4(globalThis.process.platform??"unknown"),"X-Stainless-Arch":D4(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let $=j9();if($)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${$.browser}`,"X-Stainless-Runtime-Version":$.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},D4=(J)=>{if(J==="x32")return"x32";if(J==="x86_64"||J==="x64")return"x64";if(J==="arm")return"arm";if(J==="aarch64"||J==="arm64")return"arm64";if(J)return`other:${J}`;return"unknown"},j4=(J)=>{if(J=J.toLowerCase(),J.includes("ios"))return"iOS";if(J==="android")return"Android";if(J==="darwin")return"MacOS";if(J==="win32")return"Windows";if(J==="freebsd")return"FreeBSD";if(J==="openbsd")return"OpenBSD";if(J==="linux")return"Linux";if(J)return`Other:${J}`;return"Unknown"},P9,a2=()=>{return P9??=D9()};var s8=()=>{};function S9(J,$){return()=>J.removeEventListener("abort",$)}function _4(J,$,Z){e8.set(J,S9($,Z))}function E4(J,$){if(e8.has($))S4?.register(J,$,$)}function H0(J){let $=e8.get(J);if($)e8.delete(J),S4?.unregister(J),$()}var e8,S4;var J1=M(()=>{e8=new WeakMap,S4=typeof globalThis.FinalizationRegistry==="function"?new globalThis.FinalizationRegistry((J)=>H0(J)):null});function I4(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new PukuAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function s1(...J){let $=globalThis.ReadableStream;if(typeof $>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new $(...J)}function $1(J){let $=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return s1({start(){},async pull(Z){let{done:X,value:G}=await $.next();if(X)Z.close();else Z.enqueue(G)},async cancel(){await $.return?.()}})}function o2(J){if(J[Symbol.asyncIterator])return J;let $=J.getReader();return{async next(){try{let Z=await $.read();if(Z?.done)$.releaseLock();return Z}catch(Z){throw $.releaseLock(),Z}},async return(){let Z=$.cancel();return $.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function y4(J){if(J===null||typeof J!=="object")return;if(J[Symbol.asyncIterator]){await J[Symbol.asyncIterator]().return?.();return}let $=J.getReader(),Z=$.cancel();$.releaseLock(),await Z}class e1{index}var x4=({headers:J,body:$})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify($)}};var J6="RFC3986",$6=(J)=>String(J),Z6,k4="RFC1738";var X6=M(()=>{Z6={RFC1738:(J)=>String(J).replace(/%20/g,"+"),RFC3986:$6}});function v4(J){if(!J||typeof J!=="object")return!1;return!!(J.constructor&&J.constructor.isBuffer&&J.constructor.isBuffer(J))}function Q6(J,$){if(X0(J)){let Z=[];for(let X=0;X<J.length;X+=1)Z.push($(J[X]));return Z}return $(J)}var Z1=(J,$)=>(Z1=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Z1(J,$)),L0,G6=1024,f4=(J,$,Z,X,G)=>{if(J.length===0)return J;let Q=J;if(typeof J==="symbol")Q=Symbol.prototype.toString.call(J);else if(typeof J!=="string")Q=String(J);if(Z==="iso-8859-1")return escape(Q).replace(/%u[0-9a-f]{4}/gi,function(z){return"%26%23"+parseInt(z.slice(2),16)+"%3B"});let Y="";for(let z=0;z<Q.length;z+=G6){let B=Q.length>=G6?Q.slice(z,z+G6):Q,K=[];for(let W=0;W<B.length;++W){let C=B.charCodeAt(W);if(C===45||C===46||C===95||C===126||C>=48&&C<=57||C>=65&&C<=90||C>=97&&C<=122||G===k4&&(C===40||C===41)){K[K.length]=B.charAt(W);continue}if(C<128){K[K.length]=L0[C];continue}if(C<2048){K[K.length]=L0[192|C>>6]+L0[128|C&63];continue}if(C<55296||C>=57344){K[K.length]=L0[224|C>>12]+L0[128|C>>6&63]+L0[128|C&63];continue}W+=1,C=65536+((C&1023)<<10|B.charCodeAt(W)&1023),K[K.length]=L0[240|C>>18]+L0[128|C>>12&63]+L0[128|C>>6&63]+L0[128|C&63]}Y+=K.join("")}return Y};var b4=M(()=>{X6();Q0();L0=(()=>{let J=[];for(let $=0;$<256;++$)J.push("%"+(($<16?"0":"")+$.toString(16)).toUpperCase());return J})()});function y9(J){return typeof J==="string"||typeof J==="number"||typeof J==="boolean"||typeof J==="symbol"||typeof J==="bigint"}function m4(J,$,Z,X,G,Q,Y,z,B,K,W,C,V,F,q,A,R,H){let O=J,D=H,S=0,y=!1;while((D=D.get(Y6))!==void 0&&!y){let b=D.get(J);if(S+=1,typeof b<"u")if(b===S)throw RangeError("Cyclic object value");else y=!0;if(typeof D.get(Y6)>"u")S=0}if(typeof K==="function")O=K($,O);else if(O instanceof Date)O=V?.(O);else if(Z==="comma"&&X0(O))O=Q6(O,function(b){if(b instanceof Date)return V?.(b);return b});if(O===null){if(Q)return B&&!A?B($,a.encoder,R,"key",F):$;O=""}if(y9(O)||v4(O)){if(B){let b=A?$:B($,a.encoder,R,"key",F);return[q?.(b)+"="+q?.(B(O,a.encoder,R,"value",F))]}return[q?.($)+"="+q?.(String(O))]}let f=[];if(typeof O>"u")return f;let v;if(Z==="comma"&&X0(O)){if(A&&B)O=Q6(O,B);v=[{value:O.length>0?O.join(",")||null:void 0}]}else if(X0(K))v=K;else{let b=Object.keys(O);v=W?b.sort(W):b}let g=z?String($).replace(/\./g,"%2E"):String($),d=X&&X0(O)&&O.length===1?g+"[]":g;if(G&&X0(O)&&O.length===0)return d+"[]";for(let b=0;b<v.length;++b){let t=v[b],A0=typeof t==="object"&&typeof t.value<"u"?t.value:O[t];if(Y&&A0===null)continue;let n0=C&&z?t.replace(/\./g,"%2E"):t,C2=X0(O)?typeof Z==="function"?Z(d,n0):d:d+(C?"."+n0:"["+n0+"]");H.set(J,S);let O4=new WeakMap;O4.set(Y6,H),h4(f,m4(A0,C2,Z,X,G,Q,Y,z,Z==="comma"&&A&&X0(O)?null:B,K,W,C,V,F,q,A,R,O4))}return f}function x9(J=a){if(typeof J.allowEmptyArrays<"u"&&typeof J.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof J.encodeDotInKeys<"u"&&typeof J.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(J.encoder!==null&&typeof J.encoder<"u"&&typeof J.encoder!=="function")throw TypeError("Encoder has to be a function.");let $=J.charset||a.charset;if(typeof J.charset<"u"&&J.charset!=="utf-8"&&J.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let Z=J6;if(typeof J.format<"u"){if(!Z1(Z6,J.format))throw TypeError("Unknown format option provided.");Z=J.format}let X=Z6[Z],G=a.filter;if(typeof J.filter==="function"||X0(J.filter))G=J.filter;let Q;if(J.arrayFormat&&J.arrayFormat in g4)Q=J.arrayFormat;else if("indices"in J)Q=J.indices?"indices":"repeat";else Q=a.arrayFormat;if("commaRoundTrip"in J&&typeof J.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let Y=typeof J.allowDots>"u"?!!J.encodeDotInKeys===!0?!0:a.allowDots:!!J.allowDots;return{addQueryPrefix:typeof J.addQueryPrefix==="boolean"?J.addQueryPrefix:a.addQueryPrefix,allowDots:Y,allowEmptyArrays:typeof J.allowEmptyArrays==="boolean"?!!J.allowEmptyArrays:a.allowEmptyArrays,arrayFormat:Q,charset:$,charsetSentinel:typeof J.charsetSentinel==="boolean"?J.charsetSentinel:a.charsetSentinel,commaRoundTrip:!!J.commaRoundTrip,delimiter:typeof J.delimiter>"u"?a.delimiter:J.delimiter,encode:typeof J.encode==="boolean"?J.encode:a.encode,encodeDotInKeys:typeof J.encodeDotInKeys==="boolean"?J.encodeDotInKeys:a.encodeDotInKeys,encoder:typeof J.encoder==="function"?J.encoder:a.encoder,encodeValuesOnly:typeof J.encodeValuesOnly==="boolean"?J.encodeValuesOnly:a.encodeValuesOnly,filter:G,format:Z,formatter:X,serializeDate:typeof J.serializeDate==="function"?J.serializeDate:a.serializeDate,skipNulls:typeof J.skipNulls==="boolean"?J.skipNulls:a.skipNulls,sort:typeof J.sort==="function"?J.sort:null,strictNullHandling:typeof J.strictNullHandling==="boolean"?J.strictNullHandling:a.strictNullHandling}}function u4(J,$={}){let Z=J,X=x9($),G,Q;if(typeof X.filter==="function")Q=X.filter,Z=Q("",Z);else if(X0(X.filter))Q=X.filter,G=Q;let Y=[];if(typeof Z!=="object"||Z===null)return"";let z=g4[X.arrayFormat],B=z==="comma"&&X.commaRoundTrip;if(!G)G=Object.keys(Z);if(X.sort)G.sort(X.sort);let K=new WeakMap;for(let V=0;V<G.length;++V){let F=G[V];if(X.skipNulls&&Z[F]===null)continue;h4(Y,m4(Z[F],F,z,B,X.allowEmptyArrays,X.strictNullHandling,X.skipNulls,X.encodeDotInKeys,X.encode?X.encoder:null,X.filter,X.sort,X.allowDots,X.serializeDate,X.format,X.formatter,X.encodeValuesOnly,X.charset,K))}let W=Y.join(X.delimiter),C=X.addQueryPrefix===!0?"?":"";if(X.charsetSentinel)if(X.charset==="iso-8859-1")C+="utf8=%26%2310003%3B&";else C+="utf8=%E2%9C%93&";return W.length>0?C+W:""}var g4,h4=function(J,$){Array.prototype.push.apply(J,X0($)?$:[$])},I9,a,Y6;var d4=M(()=>{b4();X6();Q0();g4={brackets(J){return String(J)+"[]"},comma:"comma",indices(J,$){return String(J)+"["+$+"]"},repeat(J){return String(J)}},a={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:f4,encodeValuesOnly:!1,format:J6,formatter:$6,indices:!1,serializeDate(J){return(I9??=Function.prototype.call.bind(Date.prototype.toISOString))(J)},skipNulls:!1,strictNullHandling:!1};Y6={}});function c4(J){return u4(J,{arrayFormat:"brackets"})}var z6=M(()=>{d4()});var D0={};R4(D0,{util:()=>K6,stream:()=>X1,path:()=>j,os:()=>f9,fs:()=>_0,crypto:()=>k0,child_process:()=>B6});import*as B6 from"node:child_process";import*as k0 from"node:crypto";import*as _0 from"node:fs";import*as f9 from"node:os";import*as j from"node:path";import*as X1 from"node:stream";import*as K6 from"node:util";var K0=()=>{};function Q1(J){if(!J)return;let $;try{$=new URL(J)}catch(X){throw new m(`Invalid token endpoint base URL "${J}": ${X}`)}if($.protocol==="https:")return;let Z=$.hostname.toLowerCase().replace(/^\[|\]$/g,"");if($.protocol==="http:"&&(Z==="localhost"||Z==="127.0.0.1"||Z==="::1"))return;throw new m(`Refusing to send credential over non-https token endpoint "${J}"`)}async function Y1(J,$){let Z=await b9(J),X;try{X=JSON.parse(Z)}catch{throw new m(`Token endpoint returned non-JSON response (status ${J.status})`,J.status,W0(Z),$)}if(!X.access_token)throw new m(`Token endpoint response missing access_token: ${JSON.stringify(W0(X))}`,J.status,W0(X),$);if(X.token_type&&X.token_type.toLowerCase()!=="bearer")throw new m(`Token endpoint response: unsupported token_type "${X.token_type}" (want Bearer)`,J.status,W0(X),$);return X}function W0(J){if(J==null)return J;if(typeof J==="string"){let $;try{$=JSON.parse(J)}catch{if(J.length<=W6)return J;return J.slice(0,W6)+`... <${J.length-W6} more chars>`}return JSON.stringify(W0($))}if(typeof J==="object"&&!Array.isArray(J)){let $={};for(let[Z,X]of Object.entries(J))if(v9.has(Z))$[Z]=X;return $}return null}async function z1(J,$=(Z)=>console.warn(`puku-ai/sdk: ${Z}`)){if(typeof process>"u"||process.platform==="win32")return;let{fs:Z}=await Promise.resolve().then(() => (K0(),D0)),X=J,G;try{X=await Z.promises.realpath(J),G=await Z.promises.stat(X)}catch{return}let Q=G.mode&511;if(Q&18)throw new m(`Credentials file at ${X} is group/world-writable (mode 0o${Q.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${X}\`.`);if(Q&36)throw new m(`Credentials file at ${X} is group/world-readable (mode 0o${Q.toString(8)}); run \`chmod 600 ${X}\` before retrying.`);if(typeof process.getuid==="function"&&G.uid!==process.getuid())$(`credentials file at ${X} is owned by uid ${G.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function B1(J,$){let{fs:Z,path:X}=await Promise.resolve().then(() => (K0(),D0)),G=X.dirname(J);await Z.promises.mkdir(G,{recursive:!0,mode:448});let Q=`${J}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let Y=await Z.promises.open(Q,"w",384);try{await Y.writeFile(JSON.stringify($,null,2)),await Y.sync()}finally{await Y.close()}await Z.promises.rename(Q,J)}catch(Y){throw await Z.promises.unlink(Q).catch(()=>{}),Y}try{let Y=await Z.promises.open(G,"r");try{await Y.sync()}finally{await Y.close()}}catch{}}async function b9(J){if(!J.body)return"";let $=J.body.getReader(),Z=[],X=0;for(;;){let{done:Q,value:Y}=await $.read();if(Q)break;if(X+Y.length>p4){let z=p4-X;if(z>0)Z.push(Y.subarray(0,z));await $.cancel();break}Z.push(Y),X+=Y.length}let G;if(Z.length===1)G=Z[0];else{G=new Uint8Array(Z.reduce((Y,z)=>Y+z.length,0));let Q=0;for(let Y of Z)G.set(Y,Q),Q+=Y.length}return new TextDecoder("utf-8").decode(G)}var l4="urn:ietf:params:oauth:grant-type:jwt-bearer",i4="refresh_token",G1="/v1/oauth/token",f0="oauth-2025-04-20",V6="oidc-federation-2026-04-01",n4=120,N2=30,a4=5,p4=1048576,W6=2000,v9,m;var r0=M(()=>{c();v9=new Set(["error","error_description","error_uri"]);m=class m extends T{statusCode;body;requestId;constructor(J,$=null,Z=null,X=null){super(J);this.statusCode=$,this.body=Z,this.requestId=X}}});function w0(){return Math.floor(Date.now()/1000)}class C6{provider;cached=null;pendingRefresh=null;nextForce=!1;lastAdvisoryError=0;onAdvisoryRefreshError;constructor(J,$){this.provider=J,this.onAdvisoryRefreshError=$}async getToken(){let J=this.nextForce;this.nextForce=!1;let $=this.cached;if(J||$==null)return(await this.refresh(J)).token;if($.expiresAt==null)return $.token;let Z=$.expiresAt-w0();if(Z>n4)return $.token;if(Z>N2)return this.backgroundRefresh(),$.token;return(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(J=!1){if(this.pendingRefresh&&!J)return this.pendingRefresh;return this.doRefresh(J)}backgroundRefresh(){if(this.pendingRefresh)return;if(w0()-this.lastAdvisoryError<a4)return;this.doRefresh().catch((J)=>{this.lastAdvisoryError=w0(),this.onAdvisoryRefreshError?.(J)})}doRefresh(J=!1){return this.pendingRefresh=this.provider(J?{forceRefresh:!0}:void 0).then(($)=>{return this.cached=$,this.pendingRefresh=null,$},($)=>{throw this.pendingRefresh=null,$}),this.pendingRefresh}}var o4=M(()=>{r0()});var x=(J)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[J]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(J)?.trim()||void 0;return};function s4(J){let $=0;for(let G of J)$+=G.length;let Z=new Uint8Array($),X=0;for(let G of J)Z.set(G,X),X+=G.length;return Z}function v0(J){let $;return(r4??($=new globalThis.TextEncoder,r4=$.encode.bind($)))(J)}function t0(J){let $;return(t4??($=new globalThis.TextDecoder,t4=$.decode.bind($)))(J)}var r4,t4;var r2=(J)=>{if(typeof globalThis.Buffer<"u"){let $=globalThis.Buffer.from(J,"base64");return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}if(typeof atob<"u"){let $=atob(J),Z=new Uint8Array($.length);for(let X=0;X<$.length;X++)Z[X]=$.charCodeAt(X);return Z}throw new T("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")};var K1=M(()=>{c()});function t2(){}function W1(J,$,Z){if(!$||V1[J]>V1[Z])return t2;else return $[J].bind($)}function N6(J,$){let Z=e4.get(J);if(Z&&Z[0]===$)return Z[1];let X={error:W1("error",J,$),warn:W1("warn",J,$),info:W1("info",J,$),debug:W1("debug",J,$)};return e4.set(J,[$,X]),X}function k(J){let $=J.logger,Z=J.logLevel??"off";if(!$)return g9;return N6($,Z)}function $$(){let J=x("PUKU_LOG");if(!U6||J!==J$)J$=J,U6=N6(console,C1(J,"process.env['PUKU_LOG']",N6(console,s2))??s2);return U6}var s2="warn",V1,C1=(J,$,Z)=>{if(!J)return;if(H4(V1,J))return J;Z.warn(`${$} was set to ${JSON.stringify(J)}, expected one of ${JSON.stringify(Object.keys(V1))}`);return},g9,e4,J$,U6,j0=(J)=>{if(J.options)J.options={...J.options},delete J.options.headers;if(J.headers)J.headers=Object.fromEntries((J.headers instanceof Headers?[...J.headers]:Object.entries(J.headers)).map(([$,Z])=>[$,$.toLowerCase()==="authorization"||$.toLowerCase()==="api-key"||$.toLowerCase()==="x-api-key"||$.toLowerCase()==="cookie"||$.toLowerCase()==="set-cookie"?"***":Z]));if("retryOfRequestLogID"in J){if(J.retryOfRequestLogID)J.retryOf=J.retryOfRequestLogID;delete J.retryOfRequestLogID}return J};var O0=M(()=>{Q0();V1={off:0,error:200,warn:300,info:400,debug:500};g9={error:t2,warn:t2,info:t2,debug:t2},e4=new WeakMap});var F6=M(()=>{Q0();K1();O0();z6()});function Z$(J){if(!J)throw Error("profile name is empty");if(J==="."||J==="..")throw Error(`profile name "${J}" is not allowed`);if(J.includes("/")||J.includes("\\"))throw Error(`profile name "${J}" must not contain path separators`);if(!h9.test(J))throw Error(`profile name "${J}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var U1="1.0",h9,X$=async(J)=>{let $=await q6();if($===null)return null;let Z=J??await Q$();if(Z===null)return null;Z$(Z);let{fs:X,path:G}=await Promise.resolve().then(() => (K0(),D0)),Q=G.join($,"configs",`${Z}.json`),Y;try{Y=await X.promises.readFile(Q,"utf-8")}catch(K){if(K?.code!=="ENOENT")throw Error(`failed to read config file ${Q}: ${K}`);Y=null}if(Y===null){let K=x("PUKU_ORGANIZATION_ID"),W=x("PUKU_IDENTITY_TOKEN_FILE"),C=x("PUKU_FEDERATION_RULE_ID");if(C&&K)return{fromFile:!1,config:{organization_id:K,workspace_id:x("PUKU_WORKSPACE_ID"),base_url:x("PUKU_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:C,service_account_id:x("PUKU_SERVICE_ACCOUNT_ID"),identity_token:W?{source:"file",path:W}:void 0,scope:x("PUKU_SCOPE")}}};return null}let z;try{z=JSON.parse(Y)}catch(K){throw Error(`failed to parse config file ${Q}: ${K}`)}if(!z.authentication)throw Error(`config file ${Q} is missing "authentication"`);let B=z.authentication.type;if(B!=="oidc_federation"&&B!=="user_oauth")throw Error(`authentication.type "${B}" is not a known authentication type`);if(z.organization_id??=x("PUKU_ORGANIZATION_ID"),z.workspace_id??=x("PUKU_WORKSPACE_ID"),z.base_url??=x("PUKU_BASE_URL"),z.authentication.scope??=x("PUKU_SCOPE"),z.authentication.type==="oidc_federation"){if(!z.authentication.identity_token){let K=x("PUKU_IDENTITY_TOKEN_FILE");if(K)z.authentication.identity_token={source:"file",path:K}}if(!z.authentication.federation_rule_id)z.authentication.federation_rule_id=x("PUKU_FEDERATION_RULE_ID")??"";z.authentication.service_account_id??=x("PUKU_SERVICE_ACCOUNT_ID")}return{config:z,fromFile:!0}},G$=async(J,$)=>{if(J?.authentication.credentials_path)return J.authentication.credentials_path;let Z=await q6();if(!Z)return null;let X=$??await Q$();if(!X)return null;Z$(X);let{path:G}=await Promise.resolve().then(() => (K0(),D0));return G.join(Z,"credentials",`${X}.json`)},q6=async()=>{if(!m9())return null;let{path:J}=await Promise.resolve().then(() => (K0(),D0)),$=x("PUKU_CONFIG_DIR");if($)return $;if(a2()["X-Stainless-OS"]==="Windows"){let Q=x("APPDATA");if(Q)return J.join(Q,"PukuAI");let Y=x("USERPROFILE");if(Y)return J.join(Y,"AppData","Roaming","PukuAI");return null}let X=x("XDG_CONFIG_HOME");if(X)return J.join(X,"puku");let G=x("HOME");if(G)return J.join(G,".config","puku");return null},m9=()=>{let J=a2()["X-Stainless-Runtime"];return J==="node"||J==="deno"},Q$=async()=>{let J=await q6();if(!J)return null;let $=x("PUKU_PROFILE");if($)return $;let{fs:Z,path:X}=await Promise.resolve().then(() => (K0(),D0)),G=X.join(J,"active_config");try{return(await Z.promises.readFile(G,"utf-8")).trim()||"default"}catch(Q){if(Q?.code!=="ENOENT")throw Error(`failed to read ${G}: ${Q}`);return"default"}};var M6=M(()=>{s8();F6();h9=/^[A-Za-z0-9_.-]+$/});function T6(J){if(!J)throw new T("Identity token file path is empty");return async()=>{let{fs:$}=await Promise.resolve().then(() => (K0(),D0)),Z;try{Z=await $.promises.readFile(J,"utf-8")}catch(G){throw new T(`Failed to read identity token file at ${J}: ${G}`)}let X=Z.trim();if(!X)throw new T(`Identity token file at ${J} is empty`);return X}}function Y$(J){if(!J)throw new T("Identity token value is empty");return()=>J}var z$=M(()=>{c()});function B$(J){return async()=>{Q1(J.baseURL);let $=await J.identityTokenProvider();if($.length>16384)throw new m(`Identity token is ${Math.ceil($.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let Z={grant_type:l4,assertion:$,federation_rule_id:J.federationRuleId,organization_id:J.organizationId};if(J.serviceAccountId)Z.service_account_id=J.serviceAccountId;if(J.workspaceId)Z.workspace_id=J.workspaceId;let X=`${J.baseURL}${G1}`,G;try{G=await J.fetch(X,{method:"POST",headers:{"Content-Type":"application/json","puku-beta":`${f0},${V6}`,"User-Agent":J.userAgent||`puku-ai-sdk-typescript/${B0} oidcFederationProvider`},body:JSON.stringify(Z)})}catch(B){throw new m(`Failed to reach token endpoint ${X}: ${B}`)}let Q=G.headers.get("Request-Id");if(!G.ok){let B=await G.text().catch(()=>""),K=W0(B),W="";if(G.status===401)W=` Ensure your federation rule matches your identity token. ${J.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the PUKU_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Puku Console for more details.`;throw new m(`Token exchange failed with status ${G.status}${Q?` (request-id ${Q})`:""}: ${K}${W}`,G.status,K,Q)}let Y=await Y1(G,Q),z=Number(Y.expires_in);if(!Number.isFinite(z))throw new m(`Token endpoint response missing required fields: ${JSON.stringify(W0(Y))}`,G.status,W0(Y),Q);return{token:Y.access_token,expiresAt:w0()+z}}}var K$=M(()=>{r0()});function W$(J){return async($)=>{let{fs:Z}=await Promise.resolve().then(() => (K0(),D0));await z1(J.credentialsPath,J.onSafetyWarning);let X;try{X=await Z.promises.readFile(J.credentialsPath,"utf-8")}catch(R){throw new m(`Credentials file not found at ${J.credentialsPath}: ${R}`)}let G;try{G=JSON.parse(X)}catch(R){throw new m(`Credentials file at ${J.credentialsPath} is not valid JSON: ${R}`)}let Q=G.access_token;if(!Q)throw new m(`Credentials file at ${J.credentialsPath} must include 'access_token'`);let Y=G.expires_at;if(!$?.forceRefresh&&(Y==null||w0()<Y-N2))return{token:Q,expiresAt:Y??null};let z=G.refresh_token;if(!J.clientId||!z)throw new m(`Access token at ${J.credentialsPath} has expired and no refresh is available (client_id ${J.clientId?"set":"empty"}, refresh_token ${z?"set":"empty"})`);Q1(J.baseURL);let B={grant_type:i4,refresh_token:z,client_id:J.clientId},K=`${J.baseURL}${G1}`,W;try{W=await J.fetch(K,{method:"POST",headers:{"Content-Type":"application/json","puku-beta":f0,"User-Agent":J.userAgent||`puku-ai-sdk-typescript/${B0} userOAuthProvider`},body:JSON.stringify(B)})}catch(R){throw new m(`User OAuth refresh failed to reach token endpoint: ${R}`)}let C=W.headers.get("Request-Id");if(!W.ok){let R=await W.text().catch(()=>"");throw new m(`User OAuth refresh failed (HTTP ${W.status}): ${W0(R)}`,W.status,W0(R),C)}let V=await Y1(W,C),F=Number(V.expires_in);if(!Number.isFinite(F))throw new m(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(W0(V))}`,W.status,W0(V),C);let q=w0()+F,A=V.refresh_token||z;return await B1(J.credentialsPath,{...G,version:U1,type:"oauth_token",access_token:V.access_token,expires_at:q,refresh_token:A}),{token:V.access_token,expiresAt:q}}}var V$=M(()=>{M6();r0()});function w6(J,$){let Z=J.authentication.credentials_path??null,X=(J.base_url||$.baseURL).replace(/\/+$/,""),G=u9(J,Z,X,$),Q={};if(J.workspace_id&&J.authentication.type==="user_oauth")Q["puku-workspace-id"]=J.workspace_id;return{provider:G,extraHeaders:Q,baseURL:J.base_url||void 0}}async function C$(J,$){let Z=await X$($);if(!Z)return null;let{config:X,fromFile:G}=Z,Q=X.authentication.credentials_path||!G?X:{...X,authentication:{...X.authentication,credentials_path:await G$(X,$)??void 0}};return w6(Q,J)}function u9(J,$,Z,X){switch(J.authentication.type){case"oidc_federation":{let G=J.authentication,Q=d9(G);if(!Q)throw new m("oidc_federation config requires an identity token (set authentication.identity_token, PUKU_IDENTITY_TOKEN_FILE, or PUKU_IDENTITY_TOKEN)");if(!G.federation_rule_id)throw new m("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via PUKU_FEDERATION_RULE_ID (profile takes precedence).");if(!J.organization_id)throw new m("oidc_federation config requires organization_id (set PUKU_ORGANIZATION_ID or config.organization_id)");let Y=B$({identityTokenProvider:Q,federationRuleId:G.federation_rule_id,organizationId:J.organization_id,serviceAccountId:G.service_account_id,workspaceId:J.workspace_id,baseURL:Z,fetch:X.fetch,userAgent:X.userAgent});if($)return c9(Y,$,X.onCacheWriteError,X.onSafetyWarning);return Y}case"user_oauth":{if(!$)throw new m("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return W$({credentialsPath:$,clientId:J.authentication.client_id,baseURL:Z,fetch:X.fetch,userAgent:X.userAgent,onSafetyWarning:X.onSafetyWarning})}default:{let G=J.authentication.type;throw new m(`authentication.type "${G}" is not a known authentication type`)}}}function d9(J){if(J.identity_token){let X=J.identity_token.source;if(X!=="file")throw new m(`identity_token.source "${X}" is not supported by this SDK version (only "file")`);if(!J.identity_token.path)throw new m('identity_token.source "file" requires a non-empty path');return T6(J.identity_token.path)}let $=x("PUKU_IDENTITY_TOKEN_FILE");if($)return T6($);let Z=x("PUKU_IDENTITY_TOKEN");if(Z)return Y$(Z);return null}function c9(J,$,Z,X){return async(G)=>{let{fs:Q}=await Promise.resolve().then(() => (K0(),D0));await z1($,X);let Y;try{let B=await Q.promises.readFile($,"utf-8");Y=JSON.parse(B);let K=Y?.access_token;if(K&&!G?.forceRefresh){let W=Y?.expires_at;if(W==null||w0()<W-N2)return{token:K,expiresAt:W??null}}}catch(B){if(B?.code!=="ENOENT"&&!(B instanceof SyntaxError))Z?.(B)}let z=await J(G);try{await B1($,{...Y??{},version:U1,type:"oauth_token",access_token:z.token,expires_at:z.expiresAt})}catch(B){Z?.(B)}return z}}var U$=M(()=>{M6();r0();z$();K$();V$()});function p9(J,$){for(let G=$??0;G<J.length;G++){if(J[G]===10)return{preceding:G,index:G+1,carriage:!1};if(J[G]===13)return{preceding:G,index:G+1,carriage:!0}}return null}function N$(J){for(let X=0;X<J.length-1;X++){if(J[X]===10&&J[X+1]===10)return X+2;if(J[X]===13&&J[X+1]===13)return X+2;if(J[X]===13&&J[X+1]===10&&X+3<J.length&&J[X+2]===13&&J[X+3]===10)return X+4}return-1}var F2;var O6=M(()=>{F2=class F2{static NEWLINE_CHARS=new Set([`
2
+ `,"\r"]);static NEWLINE_REGEXP=/\r\n|[\n\r]/g;#J;#$;constructor(){this.#J=new Uint8Array,this.#$=null}decode(J){if(J==null)return[];let $=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?v0(J):J;this.#J=s4([this.#J,$]);let Z=[],X;while((X=p9(this.#J,this.#$))!=null){if(X.carriage&&this.#$==null){this.#$=X.index;continue}if(this.#$!=null&&(X.index!==this.#$+1||X.carriage)){Z.push(t0(this.#J.subarray(0,this.#$-1))),this.#J=this.#J.subarray(this.#$),this.#$=null;continue}let G=this.#$!==null?X.preceding-1:X.preceding,Q=t0(this.#J.subarray(0,G));Z.push(Q),this.#J=this.#J.subarray(X.index),this.#$=null}return Z}flush(){if(!this.#J.length)return[];return this.decode(`
3
3
  `)}}});async function*F$(J,$){if(!J.body){if($.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new T("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new T("Attempted to iterate over a response with no body")}let Z=new q$,X=new F2,G=o2(J.body);for await(let Q of l9(G))for(let Y of X.decode(Q)){let z=Z.decode(Y);if(z)yield z}for(let Q of X.flush()){let Y=Z.decode(Q);if(Y)yield Y}}async function*l9(J){let $=new Uint8Array;for await(let Z of J){if(Z==null)continue;let X=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?v0(Z):Z,G=new Uint8Array($.length+X.length);G.set($),G.set(X,$.length),$=G;let Q;while((Q=N$($))!==-1)yield $.slice(0,Q),$=$.slice(Q)}if($.length>0)yield $}class q${data;event;chunks;constructor(){this.event=null,this.data=[],this.chunks=[]}decode(J){if(J.endsWith("\r"))J=J.substring(0,J.length-1);if(!J){if(!this.event&&!this.data.length)return null;let G={event:this.event,data:this.data.join(`
4
4
  `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push(J),J.startsWith(":"))return null;let[$,Z,X]=i9(J,":");if(X.startsWith(" "))X=X.substring(1);if($==="event")this.event=X;else if($==="data")this.data.push(X);return null}}function i9(J,$){let Z=J.indexOf($);if(Z!==-1)return[J.substring(0,Z),$,J.substring(Z+$.length)];return[J,"",""]}var s;var q2=M(()=>{c();O6();Q0();O0();c();J1();s=class s{iterator;controller;#J;constructor(J,$,Z){this.iterator=J;this.controller=$,this.#J=Z}static rawEvents(J,$=new AbortController){return F$(J,$)}static fromSSEResponse(J,$,Z){let X=!1,G=Z?k(Z):console;async function*Q(){if(X)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let Y=!1;try{for await(let z of F$(J,$)){if(z.event==="completion")try{yield JSON.parse(z.data)}catch(B){throw G.error("Could not parse message into JSON:",z.data),G.error("From chunk:",z.raw),B}if(z.event==="message_start"||z.event==="message_delta"||z.event==="message_stop"||z.event==="content_block_start"||z.event==="content_block_delta"||z.event==="content_block_stop"||z.event==="message"||z.event==="user.message"||z.event==="user.interrupt"||z.event==="user.tool_confirmation"||z.event==="user.custom_tool_result"||z.event==="user.tool_result"||z.event==="agent.message"||z.event==="agent.thinking"||z.event==="agent.tool_use"||z.event==="agent.tool_result"||z.event==="agent.mcp_tool_use"||z.event==="agent.mcp_tool_result"||z.event==="agent.custom_tool_use"||z.event==="agent.thread_context_compacted"||z.event==="session.status_running"||z.event==="session.status_idle"||z.event==="session.status_rescheduled"||z.event==="session.status_terminated"||z.event==="session.error"||z.event==="session.deleted"||z.event==="session.updated"||z.event==="span.model_request_start"||z.event==="span.model_request_end"||z.event==="span.outcome_evaluation_start"||z.event==="span.outcome_evaluation_ongoing"||z.event==="span.outcome_evaluation_end"||z.event==="user.define_outcome"||z.event==="agent.thread_message_received"||z.event==="agent.thread_message_sent"||z.event==="agent.session_thread_message_received"||z.event==="agent.session_thread_message_sent"||z.event==="session.thread_created"||z.event==="session.thread_status_created"||z.event==="session.thread_status_running"||z.event==="session.thread_status_idle"||z.event==="session.thread_status_rescheduled"||z.event==="session.thread_status_terminated"||z.event==="event_start"||z.event==="event_delta"||z.event==="system.message")try{yield JSON.parse(z.data)}catch(B){throw G.error("Could not parse message into JSON:",z.data),G.error("From chunk:",z.raw),B}if(z.event==="ping")continue;if(z.event==="error"){let B=o0(z.data)??z.data,K=B?.error?.type;throw new l(void 0,B,void 0,J.headers,K)}}Y=!0}catch(z){if(U0(z))return;throw z}finally{if(!Y)$.abort();H0($)}}return new s(Q,$,Z)}static fromReadableStream(J,$,Z){let X=!1;async function*G(){let Y=new F2,z=o2(J);for await(let B of z)for(let K of Y.decode(B))yield K;for(let B of Y.flush())yield B}async function*Q(){if(X)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let Y=!1;try{for await(let z of G()){if(Y)continue;if(z)yield JSON.parse(z)}Y=!0}catch(z){if(U0(z))return;throw z}finally{if(!Y)$.abort();H0($)}}return new s(Q,$,Z)}[Symbol.asyncIterator](){return this.iterator()}tee(){let J=[],$=[],Z=this.iterator(),X=(G)=>{return{next:()=>{if(G.length===0){let Q=Z.next();J.push(Q),$.push(Q)}return G.shift()}}};return[new s(()=>X(J),this.controller,this.#J),new s(()=>X($),this.controller,this.#J)]}toReadableStream(){let J=this,$;return s1({async start(){$=J[Symbol.asyncIterator]()},async pull(Z){try{let{value:X,done:G}=await $.next();if(G)return Z.close();let Q=v0(JSON.stringify(X)+`
5
5
  `);Z.enqueue(Q)}catch(X){Z.error(X)}},async cancel(){await $.return?.()}})}}});async function N1(J,$){let{response:Z,requestLogID:X,retryOfRequestLogID:G,startTime:Q}=$,Y=await(async()=>{if($.options.stream)return k(J).debug("response",Z.status,Z.url,Z.headers,Z.body),s.fromSSEResponse(Z,$.controller,J);if(Z.status===204)return null;if($.options.__binaryResponse)return Z;let B=Z.headers.get("content-type")?.split(";")[0]?.trim();if(B?.includes("application/json")||B?.endsWith("+json")){if(Z.headers.get("content-length")==="0")return;let V=await Z.json();return e2(V,Z)}return await Z.text()})().finally(()=>{if(!$.options.stream&&!$.options.__binaryResponse)H0($.controller)});return k(J).debug(`[${X}] response parsed`,j0({retryOfRequestLogID:G,url:Z.url,status:Z.status,body:Y,durationMs:Date.now()-Q})),Y}function e2(J,$){if(!J||typeof J!=="object"||Array.isArray(J))return J;return Object.defineProperties(J,{_request_id:{value:$.headers.get("request-id"),enumerable:!1},_workspace_id:{value:$.headers.get("puku-workspace-id"),enumerable:!1}})}var F1=M(()=>{q2();O0();J1()});function R6(J){return typeof J==="object"&&J!==null&&T$.has(J)}function w$(J){let $=new Set;while(typeof J==="object"&&J!==null&&!$.has(J)){if($.add(J),R6(J)||U0(J)||J instanceof S0||J instanceof t8)return!0;J=J.cause}return!1}function A6(J,$,Z,X){return async(G,Q={})=>{if($.length===0)return J.call(void 0,G,Q);let Y=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers),z=await a9(J,$,Z,X)({...Q,headers:Y,url:typeof G==="string"?G:G instanceof URL?G.href:G.url});if(z.bodyUsed||z.body?.locked)throw new T("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return z}}function n9(J,$){let Z=new WeakMap;return{options:J,logger:$?k($):$$(),parse(X){if(J?.stream&&X.ok)return M$(X,J,$);let G=Z.get(X);if(!G)G=M$(X,J,$),Z.set(X,G);return G}}}async function M$(J,$,Z){if(J.bodyUsed||J.body?.locked)throw new T("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if($?.stream&&J.ok)return s.fromSSEResponse(J.clone(),new AbortController,Z);if(J.status===204)return null;if($?.__binaryResponse)return J;let G=J.headers.get("content-type")?.split(";")[0]?.trim();if(G?.includes("application/json")||G?.endsWith("+json")){if(J.headers.get("content-length")==="0")return;return e2(await J.clone().json(),J)}return await J.clone().text()}function a9(J,$,Z,X){let G=async({url:Y,...z})=>{try{return await J.call(void 0,Y,z)}catch(B){let K=a0(B);throw T$.add(K),K}},Q=n9(Z,X);for(let Y=$.length-1;Y>=0;Y--){let z=$[Y],B=G;G=async(K)=>z(K,B,Q)}return G}var T$;var O$=M(()=>{F1();O0();c();q2();T$=new WeakSet});var s0;var q1=M(()=>{F1();s0=class s0 extends Promise{responsePromise;parseResponse;parsedPromise;#J;constructor(J,$,Z=N1){super((X)=>{X(null)});this.responsePromise=$;this.parseResponse=Z;this.#J=J}_thenUnwrap(J){return new s0(this.#J,this.responsePromise,async($,Z)=>e2(J(await this.parseResponse($,Z),Z),Z.response))}asResponse(){return this.responsePromise.then((J)=>J.response)}async withResponse(){let[J,$]=await Promise.all([this.parse(),this.asResponse()]);return{data:J,response:$,request_id:$.headers.get("request-id"),workspace_id:$.headers.get("puku-workspace-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((J)=>this.parseResponse(this.#J,J));return this.parsedPromise}then(J,$){return this.parse().then(J,$)}catch(J){return this.parse().catch(J)}finally(J){return this.parse().finally(J)}}});var M1,T1,o,L,H6;var _=M(()=>{c();F1();q1();Q0();M1=class M1{#J;options;response;body;constructor(J,$,Z,X){this.#J=J,this.options=X,this.response=$,this.body=Z}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let J=this.nextPageRequestOptions();if(!J)throw new T("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await this.#J.requestAPIList(this.constructor,J)}async*iterPages(){let J=this;yield J;while(J.hasNextPage())J=await J.getNextPage(),yield J}async*[Symbol.asyncIterator](){for await(let J of this.iterPages())for(let $ of J.getPaginatedItems())yield $}};T1=class T1 extends s0{constructor(J,$,Z){super(J,$,async(X,G)=>new Z(X,G.response,await N1(X,G),G.options))}async*[Symbol.asyncIterator](){let J=await this;for await(let $ of J)yield $}};o=class o extends M1{data;has_more;first_id;last_id;constructor(J,$,Z,X){super(J,$,Z,X);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.first_id=Z.first_id||null,this.last_id=Z.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let $=this.first_id;if(!$)return null;return{...this.options,query:{...n2(this.options.query),before_id:$}}}let J=this.last_id;if(!J)return null;return{...this.options,query:{...n2(this.options.query),after_id:J}}}};L=class L extends M1{data;next_page;constructor(J,$,Z,X){super(J,$,Z,X);this.data=Z.data||[],this.next_page=Z.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let J=this.next_page;if(!J)return null;return{...this.options,query:{...n2(this.options.query),page:J}}}};H6=class H6 extends M1{data;next_page;prev_page;constructor(J,$,Z,X){super(J,$,Z,X);this.data=Z.data||[],this.next_page=Z.next_page||null,this.prev_page=Z.prev_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let J=this.next_page;if(!J)return null;return{...this.options,query:{...n2(this.options.query),page:J}}}}});function e0(J,$,Z){return D6(),new File(J,$??"unknown_file",Z)}function J8(J,$){let Z=typeof J==="object"&&J!==null&&(("name"in J)&&J.name&&String(J.name)||("url"in J)&&J.url&&String(J.url)||("filename"in J)&&J.filename&&String(J.filename)||("path"in J)&&J.path&&String(J.path))||"";return $?Z.split(/[\\/]/).pop()||void 0:Z}function r9(J){let $=typeof J==="function"?J:J.fetch,Z=R$.get($);if(Z)return Z;let X=(async()=>{try{let G="Response"in $?$.Response:(await $("data:,")).constructor,Q=new FormData;if(Q.toString()===await new G(Q).text())return!1;return!0}catch{return!0}})();return R$.set($,X),X}var D6=()=>{if(typeof File>"u"){let{process:J}=globalThis,$=typeof J?.versions?.node==="string"&&parseInt(J.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+($?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},j6=(J)=>J!=null&&typeof J==="object"&&typeof J[Symbol.asyncIterator]==="function",F0=async(J,$,Z=!0)=>{return{...J,body:await t9(J.body,$,Z)}},R$,t9=async(J,$,Z=!0)=>{if(!await r9($))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let X=new FormData;return await Promise.all(Object.entries(J||{}).map(([G,Q])=>L6(X,G,Q,Z))),X},L6=async(J,$,Z,X)=>{if(Z===void 0)return;if(Z==null)throw TypeError(`Received null for "${$}"; to pass null in FormData, you must use the string 'null'`);if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")J.append($,String(Z));else if(Z instanceof Response){let G={},Q=Z.headers.get("Content-Type");if(Q)G={type:Q};J.append($,e0([await Z.blob()],J8(Z,X),G))}else if(j6(Z))J.append($,e0([await new Response($1(Z)).blob()],J8(Z,X)));else if(Z instanceof Blob)J.append($,e0([Z],J8(Z,X)||void 0,{type:Z.type}));else if(Array.isArray(Z))await Promise.all(Z.map((G)=>L6(J,$+"[]",G,X)));else if(typeof Z.then==="function")throw TypeError(`Received a Promise for "${$}"; await it first, e.g. \`await toFile(...)\``);else if(Z instanceof ArrayBuffer||ArrayBuffer.isView(Z))throw TypeError(`Received ${Z.constructor.name} for "${$}"; to upload raw bytes, wrap them with \`await toFile(bytes, 'filename')\``);else if(typeof Z==="object")await Promise.all(Object.entries(Z).map(([G,Q])=>L6(J,`${$}[${G}]`,Q,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Z} instead`)};var E0=M(()=>{R$=new WeakMap});async function w1(J,$,Z){if(D6(),J=await J,$||=J8(J,!0),s9(J)){if(J instanceof File&&$==null&&Z==null)return J;return e0([await J.arrayBuffer()],$??J.name,{type:J.type,lastModified:J.lastModified,...Z})}if(e9(J)){let G=await J.blob();return $||=new URL(J.url).pathname.split(/[\\/]/).pop(),e0(await P6(G),$,Z)}let X=await P6(J);if(!Z?.type){let G=X.find((Q)=>typeof Q==="object"&&("type"in Q)&&Q.type);if(typeof G==="string")Z={...Z,type:G}}return e0(X,$,Z)}async function P6(J){let $=[];if(typeof J==="string"||ArrayBuffer.isView(J)||J instanceof ArrayBuffer)$.push(J);else if(A$(J))$.push(J instanceof Blob?J:await J.arrayBuffer());else if(j6(J))for await(let Z of J)$.push(...await P6(Z));else{let Z=J?.constructor?.name;throw Error(`Unexpected data type: ${typeof J}${Z?`; constructor: ${Z}`:""}${J3(J)}`)}return $}function J3(J){if(typeof J!=="object"||J===null)return"";return`; props: [${Object.getOwnPropertyNames(J).map((Z)=>`"${Z}"`).join(", ")}]`}var A$=(J)=>J!=null&&typeof J==="object"&&typeof J.size==="number"&&typeof J.type==="string"&&typeof J.text==="function"&&typeof J.slice==="function"&&typeof J.arrayBuffer==="function",s9=(J)=>J!=null&&typeof J==="object"&&typeof J.name==="string"&&typeof J.lastModified==="number"&&A$(J),e9=(J)=>J!=null&&typeof J==="object"&&typeof J.url==="string"&&typeof J.blob==="function";var H$=M(()=>{E0();E0()});var S6=M(()=>{H$()});class w{_client;constructor(J){this._client=J}}function*Z3(J){if(!J)return;if(L$ in J){let{values:X,nulls:G}=J;yield*X.entries();for(let Q of G)yield[Q,null];return}let $=!1,Z;if(J instanceof Headers)Z=J.entries();else if(o1(J))Z=J;else $=!0,Z=Object.entries(J??{});for(let X of Z){let G=X[0];if(typeof G!=="string")throw TypeError("expected header name to be a string");let Q=o1(X[1])?X[1]:[X[1]],Y=!1;for(let z of Q){if(z===void 0)continue;if($&&!Y)Y=!0,yield[G,O1];yield[G,z]}}}var L$,O1,X3,_6=(J,$)=>{let Z=J?J.split(",").map((X)=>X.trim()).filter(Boolean):[];for(let X of $.split(",").map((G)=>G.trim()))if(X&&!Z.includes(X))Z.push(X);return Z.join(", ")},U=(J)=>{let $=new Headers,Z=new Set;for(let X of J){let G=new Set;for(let[Q,Y]of Z3(X)){let z=Q.toLowerCase();if(X3.has(z)){if(Y===O1)continue;if(Y===null)$.delete(Q),Z.add(z);else $.set(Q,_6($.get(Q),Y)),Z.delete(z);continue}if(Y===O1||!G.has(z)){if($.delete(Q),G.add(z),Y===O1)continue}if(Y===null)$.delete(Q),Z.add(z);else $.append(Q,Y),Z.delete(z)}}return{[L$]:!0,values:$,nulls:Z}};var E=M(()=>{Q0();L$=Symbol.for("brand.privateNullableHeaders");O1=Symbol("clear"),X3=new Set(["x-stainless-helper"])});function j$(J){return J.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var D$,G3=(J=j$)=>function(Z,...X){if(Z.length===1)return Z[0];let G=!1,Q=[],Y=Z.reduce((W,C,V)=>{if(/[?#]/.test(C))G=!0;let F=X[V],q=(G?encodeURIComponent:J)(""+F);if(V!==X.length&&(F==null||typeof F==="object"&&F.toString===Object.getPrototypeOf(Object.getPrototypeOf(F.hasOwnProperty??D$)??D$)?.toString))q=F+"",Q.push({start:W.length+C.length,length:q.length,error:`Value of type ${Object.prototype.toString.call(F).slice(8,-1)} is not a valid path parameter`});return W+C+(V===X.length?"":q)},""),z=Y.split(/[?#]/,1)[0],B=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,K;while((K=B.exec(z))!==null)Q.push({start:K.index,length:K[0].length,error:`Value "${K[0]}" can't be safely passed as a path parameter`});if(Q.sort((W,C)=>W.start-C.start),Q.length>0){let W=0,C=Q.reduce((V,F)=>{let q=" ".repeat(F.start-W),A="^".repeat(F.length);return W=F.start+F.length,V+q+A},"");throw new T(`Path parameters result in path with invalid segments:
@@ -11,18 +11,18 @@ ${C}`)}return Y},N;var I=M(()=>{c();D$=Object.freeze(Object.create(null)),N=G3(j
11
11
  `:"")+"{"+Object.entries(J).map(([C,V])=>`${C}: ${JSON.stringify(V)}`).join(", ")+"}"}return $}var m3;var l6=M(()=>{F6();m3=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"])});function m0(J){if(J.inputSchema.type!=="object")throw Error(`JSON schema for tool "${J.name}" must be an object, but got ${J.inputSchema.type}`);return{type:"custom",name:J.name,input_schema:J.inputSchema,description:J.description,run:J.run,parse:($)=>$,...J.close?{close:J.close}:{}}}function d3(J,$){if(J.type!=="object")throw Error(`JSON schema for tool must be an object, but got ${J.type}`);if($?.transform??!0)J=x1(J);return{type:"json_schema",schema:{...J},parse:(X)=>{try{return JSON.parse(X)}catch(G){throw new T(`Failed to parse structured output: ${G}`)}}}}var i6=M(()=>{k1();l6()});function w2(){let J,$;return{promise:new Promise((X,G)=>{J=X,$=G}),resolve:J,reject:$}}function f1(J,$){let Z=j.relative(J,$);return Z===""||!Z.startsWith(".."+j.sep)&&Z!==".."&&!j.isAbsolute(Z)}async function n6(J,$){for(let Z of J)if(f1(await F8(j.resolve(Z)),$))return Z;return}function M8(J){let $=J?.code;return typeof $==="string"?$:void 0}async function F8(J){let $=[],Z=J,X=0;for(;;){let G;try{G=await O2.realpath(Z)}catch(Q){let Y;try{Y=(await O2.lstat(Z)).isSymbolicLink()}catch(z){let B=M8(z);if(B!=="ENOENT"&&B!=="ENOTDIR")throw z;let K=j.dirname(Z);if(K===Z)throw z;$.push(j.basename(Z)),Z=K;continue}if(!Y)throw Q;if(++X>p3)throw Object.assign(Error("too many levels of symbolic links"),{code:"ELOOP"});Z=j.resolve(j.dirname(Z),await O2.readlink(Z));continue}return $.length?j.join(G,...$.reverse()):G}}async function a$(J,$,Z){let X=Z?.allowedRoots??[],G=await F8(j.resolve(J)),Q;try{Q=await F8(j.resolve(G,$))}catch(z){throw new P(R2(z,`path ${JSON.stringify($)}`))}if(f1(G,Q)||await n6(X,Q)!==void 0)return Q;let Y=X.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new P(`path ${JSON.stringify($)} is outside ${Y}`)}async function a6(J,$){let Z=j.dirname(J),X=j.join(Z,`.tmp-${process.pid}-${k0.randomUUID()}`),G;try{G=await O2.open(X,"wx",c3),await G.writeFile($,"utf-8"),await G.sync(),await G.close(),G=void 0,await O2.rename(X,J)}catch(Q){if(G)await G.close().catch(()=>{});throw await O2.unlink(X).catch(()=>{}),Q}}function R2(J,$){let Z=M8(J);switch(Z){case"ENOENT":return`${$}: no such file or directory`;case"EACCES":case"EPERM":return`${$}: permission denied`;case"ENOTDIR":return`${$}: not a directory`;case"EISDIR":return`${$}: is a directory`;case"ELOOP":return`${$}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${$}: file name too long`;case"ENOSPC":return`${$}: no space left on device`;case"EMFILE":case"ENFILE":return`${$}: too many open files`;default:return`${$}: ${Z!==void 0?`i/o error (${Z})`:"i/o error"}`}}var O2,q8=493,c3=420,p3=40;var o6=M(()=>{K0();I0();O2=_0.promises});async function t6(J){let{client:$,sessionId:Z}=J;if(!$)return async()=>{};let X=k($),G=J.session;if(!G){if(Z===void 0)return async()=>{};X.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),G=await $.beta.sessions.retrieve(Z)}let Q=j.resolve(J.workdir,"skills"),Y=[];for(let z of G.agent.skills)try{let B=await $.beta.skills.versions.retrieve(z.version,{skill_id:z.skill_id}),K=j.basename(B.name.trim());if(K===""||K==="."||K==="..")K=z.skill_id;let W=j.resolve(Q,K);if(W!==Q&&!W.startsWith(Q+j.sep)){X.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:B.name});continue}let C=await $.beta.skills.versions.download(B.id,{skill_id:z.skill_id});await M0.rm(W,{recursive:!0,force:!0}),await M0.mkdir(W,{recursive:!0,mode:q8}),Y.push(W),await v1(C,W),X.info("downloaded skill",{component:"agent-tool-context",skill_id:z.skill_id,version:B.id,dest:W})}catch(B){X.warn("failed to download skill",{component:"agent-tool-context",skill_id:z.skill_id,error:String(B)})}return async()=>{for(let z of Y)await M0.rm(z,{recursive:!0,force:!0}).catch((B)=>{X.warn("failed to clean up skill",{component:"agent-tool-context",dest:z,error:String(B)})})}}function i3(J){for(let $ of J){let Z=$.trim();if(!Z)continue;if(j.isAbsolute(Z)||Z.split(/[\\/]/).includes(".."))throw new T(`refusing to extract unsafe archive member: ${Z}`)}}function o$(J){let $=J.split(`
12
12
  `);if($[$.length-1]==="")$.pop();return $}function a3(J,$){return/^[\x20-\x7E]+$/.test($)&&!/[\\^#]/.test($)&&!(J==="unzip"&&$.startsWith("-"))}function o3(J,$,Z){let X=o$($),G=o$(Z);if(X.length!==G.length)throw new T(s6);let Q=[],Y=[];return X.forEach((z,B)=>{if(n3[J].has(G[B].charAt(0))){Q.push(z);return}if(!a3(J,z))throw new T(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(z)}`);Y.push(z)}),{plain:Q,special:Y}}async function r$(J){for(let $ of await M0.readdir(J,{withFileTypes:!0}))if($.isDirectory())await r$(j.join(J,$.name));else if(!$.isFile())throw new T(s6)}async function r6(J,$){try{let{stdout:Z}=await l3(J,$);return Z}catch(Z){if(M8(Z)==="ENOENT")throw new T(`skill extraction requires the \`${J}\` command, but it was not found on PATH`);throw Z}}function r3(J){let $,Z=!1;for(let X of J){let G=X.trim().split("/").filter((Y)=>Y!==""&&Y!==".");if(G.length===0)continue;let Q=G[0];if($===void 0)$=Q;else if(Q!==$)return"";if(G.length>1)Z=!0}return $!==void 0&&Z?$:""}async function v1(J,$){let Z=j.join($,`.skill-archive-${process.pid}-${Date.now()}`);if(!J.body)throw new T("skill download response had no body");await X1.promises.pipeline(X1.Readable.fromWeb(J.body),_0.createWriteStream(Z));let X=j.join(j.dirname($),`.skill-stage-${process.pid}-${Date.now()}`),G=j.join(j.dirname($),`.skill-exclude-${process.pid}-${Date.now()}`);try{let Q=await s3(Z,4),Y=Q.length>=4&&Q[0]===80&&Q[1]===75&&Q[2]===3&&Q[3]===4,z=Y?"unzip":"tar",B=await r6(z,Y?["-Z1",Z]:["-tf",Z]),K=await r6(z,Y?["-Z","--h","--t",Z]:["-tvf",Z]),{plain:W,special:C}=o3(z,B,K);i3([...W,...C]);let V=r3(W);if(await M0.mkdir(X,{recursive:!0,mode:q8}),W.length>0)await r6(z,await t3(z,Z,X,C,G));await r$(X);let F=V?j.join(X,V):X,q=await M0.readdir(F).catch((A)=>{throw M8(A)==="ENOENT"?new T(s6):A});for(let A of q)await M0.rename(j.join(F,A),j.join($,A))}finally{await M0.rm(Z,{force:!0}),await M0.rm(G,{force:!0}),await M0.rm(X,{recursive:!0,force:!0})}}async function t3(J,$,Z,X,G){let Q=X.map((Y)=>Y.replace(/[*?[\\]/g,"\\$&"));if(J==="unzip")return["-oq",$,"-d",Z,...Q.length>0?["-x",...Q]:[]];if(Q.length===0)return["-xf",$,"-C",Z];return await M0.writeFile(G,Q.join(`
13
13
  `)+`
14
- `,{flag:"wx",mode:384}),["-xf",$,"-C",Z,"-X",G]}async function s3(J,$){let Z=await M0.open(J,"r");try{let X=Buffer.alloc($),{bytesRead:G}=await Z.read(X,0,$,0);return X.subarray(0,G)}finally{await Z.close()}}var M0,l3,s6="skill archive listing is inconsistent; refusing to extract",n3;var t$=M(()=>{K0();c();O0();o6();M0=_0.promises,l3=K6.promisify(B6.execFile);n3={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])}});function J4(J){return J.startsWith("/")&&!J.split("/").includes("..")}function Z5(){return e6!==0}async function X5(J){let $=[],Z=J;for(;;){try{await r.stat(Z);break}catch(G){let Q=G.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR"&&Q!=="ELOOP")throw G}$.push(Z);let X=j.dirname(Z);if(X===Z)break;Z=X}for(let X of $.reverse())try{await r.mkdir(X,{mode:$Z})}catch(G){if(G.code!=="EEXIST")throw G}}async function s$(J,$){let Z=j.relative(J,$);if(Z==="")return;let X=J;for(let G of Z.split(j.sep)){X=j.join(X,G);try{await r.mkdir(X,{mode:$Z})}catch(Q){if(Q.code!=="EEXIST")throw Q}}}async function G5(J,$,Z){let X=Z?J5:e3,G=j.join(j.dirname(J),`.fs-${k0.randomBytes(8).toString("hex")}.tmp`),Q;try{Q=await r.open(G,A2.O_WRONLY|A2.O_CREAT|A2.O_EXCL|e6,X),await Q.writeFile($),await Q.close(),Q=void 0,await r.rename(G,J)}catch(Y){if(Q)await Q.close().catch(()=>{});throw await r.unlink(G).catch(()=>{}),Y}}async function ZZ(J,$){let Z;try{Z=await r.open($,A2.O_RDONLY|e6|$5)}catch(X){let G=X.code;if(G==="ELOOP"||G==="EMLINK")throw new u(u.IS_A_SYMLINK,J);throw X}try{if(!(await Z.stat()).isFile())throw new u(u.NOT_A_FILE,J)}catch(X){throw await Z.close().catch(()=>{}),X}return Z}async function Q5(J){let $=k0.createHash("sha256"),Z=await ZZ(j.basename(J),J),X=new Uint8Array(1048576);try{for(;;){let{bytesRead:G}=await Z.read(X,0,X.length);if(G===0)break;$.update(X.subarray(0,G))}}finally{await Z.close()}return $.digest("hex")}async function e$(J,$,Z){if(!await z5($,Z))return[];let X=[];return await XZ(Z,(G,Q)=>{if(Q.isFile())X.push([j.relative(J,G).split(j.sep).join("/"),G])}),X.sort(),X}async function Y5(J,$,Z){let X=(Y)=>j.relative(J,Y).split(j.sep).join("/"),G;try{G=await r.lstat(Z,{bigint:!0})}catch(Y){let z=Y.code;if(z==="ENOENT"||z==="ENOTDIR")return new Set;throw Y}if(G.isSymbolicLink())return new Set([X(Z)]);if(!G.isDirectory())throw new u(u.NOT_A_DIRECTORY,$);let Q=new Set;return await XZ(Z,(Y,z)=>{if(z.isSymbolicLink())Q.add(X(Y))}),Q}async function z5(J,$){let Z;try{Z=await r.lstat($,{bigint:!0})}catch(X){let G=X.code;if(G==="ENOENT"||G==="ENOTDIR")return!1;throw X}if(!Z.isDirectory())throw new u(u.NOT_A_DIRECTORY,J);return!0}async function XZ(J,$){let Z=[J];while(Z.length){let X=Z.pop(),G;try{G=await r.readdir(X,{withFileTypes:!0})}catch(Q){if(Q.code==="ENOENT")continue;throw Q}for(let Q of G){let Y=j.join(X,Q.name);if($(Y,Q),Q.isDirectory()&&!Q.isSymbolicLink())Z.push(Y)}}}function B5(J,$){return $.mtimeNs===J.mtimeNs&&$.ctimeNs===J.ctimeNs&&$.size===J.size}function K5(J,$){return(J.mtimeNs>J.ctimeNs?J.mtimeNs:J.ctimeNs)<$-b1.timestampTrustMarginNs}var r,A2,$Z=448,e3=384,J5=448,e6,$5,u,T8,W5=2000000000n,b1,GZ,JZ;var QZ=M(()=>{K0();r=_0.promises,A2=_0.constants,e6=A2.O_NOFOLLOW??0,$5=A2.O_NONBLOCK??0;u=class u extends Error{static ESCAPES_ROOT="escapes the store root";static IS_A_SYMLINK="is a symlink";static NOT_A_FILE="is not a regular file";static NOT_A_DIRECTORY="is not a directory";static NOT_UTF8="is not valid utf-8";static MOVE_DESTINATION_EXISTS="already exists";reason;relPath;constructor(J,$){super(`path ${JSON.stringify($)} ${J}`);this.name="FileStoreError",this.reason=J,this.relPath=$}};T8=class T8{rootPath;removedOnDispose;decoder;hashes=new Map;static isPathLegal=J4;constructor(J,$,Z=!1){this.rootPath=J,this.removedOnDispose=$,this.decoder=Z?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(J,$){if(!Z5())throw Error("FileStore requires O_NOFOLLOW support on this platform");let Z=!1;try{await r.lstat(J)}catch(X){if(X.code!=="ENOENT")throw X;Z=!0}return new T8(j.resolve(J),Z,$?.utf8??!1)}async createRoot(){await X5(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){if(!this.removedOnDispose)return;await r.rm(this.rootPath,{recursive:!0,force:!0})}async put(J,$,Z){let X=J.replace(/\\/g,"/");if(X.endsWith("/")||X.endsWith("/.")||X===""||X===".")throw new u(u.NOT_A_FILE,J);let G=this.resolveUnderRoot(J),Q=typeof $==="string"?v0($):$;this.requireUtf8(J,Q),await s$(this.rootPath,j.dirname(G)),await G5(G,Q,Z?.executable??!1)}async get(J){let $=this.resolveUnderRoot(J),Z;try{Z=await ZZ(J,$)}catch(G){if(G.code==="ENOENT")return null;throw G}let X;try{let G=await Z.readFile();X=new Uint8Array(G.buffer,G.byteOffset,G.byteLength)}finally{await Z.close()}return this.requireUtf8(J,X),X}async ls(J="/"){let $=this.resolveUnderRoot(J);return new Set((await e$(this.rootPath,J,$)).map(([Z])=>Z))}async findSymlinks(J="/"){let $=this.resolveUnderRoot(J);return Y5(this.rootPath,J,$)}async hashtree(J="/"){let $=this.resolveUnderRoot(J),Z=b1.nowNs(),X=Object.create(null);for(let[G,Q]of await e$(this.rootPath,J,$)){let Y=await this.hashViaCache(G,Q,Z);if(Y!==null)X[G]=Y}return X}async hashFile(J){let $=this.resolveUnderRoot(J),Z;try{Z=await r.lstat($,{bigint:!0})}catch(G){if(G.code==="ENOENT")return null;throw G}if(Z.isSymbolicLink())throw new u(u.IS_A_SYMLINK,J);if(!Z.isFile())throw new u(u.NOT_A_FILE,J);let X=j.relative(this.rootPath,$).split(j.sep).join("/");return this.hashViaCache(X,$,b1.nowNs())}async move(J,$){let Z=this.resolveUnderRoot(J),X=this.resolveUnderRoot($);if(Z===this.rootPath||X===this.rootPath)return;if(await r.stat(X).then(()=>!0,()=>!1))throw new u(u.MOVE_DESTINATION_EXISTS,$);await s$(this.rootPath,j.dirname(X)),await r.rename(Z,X)}async remove(J){let $=this.resolveUnderRoot(J);if($===this.rootPath)return;let Z;try{Z=await r.lstat($,{bigint:!0})}catch(X){if(X.code==="ENOENT")return;throw X}if(Z.isDirectory())await r.rm($,{recursive:!0,force:!0});else try{await r.unlink($)}catch(X){if(X.code!=="ENOENT")throw X}}resolveUnderRoot(J){let $=J.replace(/\\/g,"/").replace(/^\/+/,""),Z=$.split("/").filter((X)=>X!==""&&X!==".");if(j.posix.isAbsolute($)||Z.includes(".."))throw new u(u.ESCAPES_ROOT,J);return Z.length===0?this.rootPath:j.join(this.rootPath,...Z)}requireUtf8(J,$){if(!this.decoder)return;try{this.decoder.decode($)}catch{throw new u(u.NOT_UTF8,J)}}async hashViaCache(J,$,Z){let X;try{X=await r.lstat($,{bigint:!0})}catch(Y){if(Y.code==="ENOENT")return null;throw Y}if(!X.isFile())return null;let G=this.hashes.get(J),Q;if(G!==void 0&&B5(G,X))Q=G.sha;else try{Q=await b1.hashFile($)}catch(Y){let z=Y.code;if(z==="ENOENT"||Y instanceof u)return null;if(z==="ELOOP"||z==="EMLINK")return null;throw Y}if(K5(X,Z))this.hashes.set(J,{mtimeNs:X.mtimeNs,ctimeNs:X.ctimeNs,size:X.size,sha:Q});return Q}};b1={hashFile:Q5,timestampTrustMarginNs:W5,nowNs:()=>BigInt(Date.now())*1000000n},GZ=T8,JZ=Symbol.asyncDispose;if(JZ)Object.defineProperty(T8.prototype,JZ,{value:T8.prototype.dispose,configurable:!0,writable:!0})});function YZ(J){return k0.createHash("sha256").update(`version ${BZ}
15
- ${J}`,"utf-8").digest("hex")}class KZ{mode;cap;waiveWindow;attempted=0;capped=0;suppressed=0;constructor(J,$,Z){this.mode=J;this.cap=$;this.waiveWindow=Z}takeSlot(){if(this.attempted>=this.cap)return this.capped++,!1;return this.attempted++,!0}}class $4{#J;#$;#X;#G;#Z;#Q;#B=!1;#Y=[];constructor(J,$){this.#J=J,this.#$=$.workdir,this.#X=$.syncIntervalMs??N8,I1(this.#X,"syncIntervalMs"),this.#G=$.syncDeletions??"enabled",this.#Z=k(J),this.#Q=Date.now()}get roots(){return this.#Y.map((J)=>J.files.root().path)}get readOnlyRoots(){return this.#Y.filter((J)=>J.readOnly).map((J)=>J.files.root().path)}#z(J){if(J.mount_path){if(!J4(J.mount_path))throw new u0(`memory store mount_path is not a clean absolute path: ${JSON.stringify(J.mount_path)} (memory_store_id=${J.memory_store_id})`);return J.mount_path}return j.join(this.#$,"memory",J.name||J.memory_store_id)}async download(J){for(let $ of J.resources){if($.type!=="memory_store")continue;let Z=this.#z($),X;try{if(X={memoryStoreId:$.memory_store_id,files:await GZ.open(Z,{utf8:!0}),readOnly:$.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!X.files.root().removedOnDispose)throw new u0(`something already exists at the memory store's path: ${Z} (memory_store_id=${$.memory_store_id}); it must not exist when the session starts`);try{await X.files.createRoot()}catch(G){if(!H2(G))throw G;throw new u0(`cannot create the memory store's folder: ${Z} (memory_store_id=${$.memory_store_id}): ${G}; the worker host must make this mount path writable`,G)}await this.#F(X),this.#Z.info("downloaded memories",{count:X.baseline.size,memory_store_id:X.memoryStoreId,dest:X.files.root().path}),this.#Y.push(X)}catch(G){if(X)await X.files.dispose().catch(()=>{});if(G instanceof u0)throw G;throw new u0(`failed to download memory store memory_store_id=${$.memory_store_id}: ${G}`,G)}}this.#Q=Date.now()}async finish(){if(this.#B)throw new T("finish() was already called: it is the session's last sync and runs once");this.#B=!0,await this.syncAll(!0)}async syncAll(J){await Promise.all(this.#Y.map(($)=>this.#C($,J))),this.#Q=Date.now()}async#K(J){let $=await J.files.hashtree(),Z=$[G2];if(delete $[G2],Z===YZ(J.memoryStoreId))return{files:$,markerOk:!0,distrustReason:null};return{files:$,markerOk:!1,distrustReason:Z!==void 0?"the marker file does not match this store":"the marker file is gone"}}async#C(J,$){try{let Z=await this.#K(J),X=Z.files;if(!Z.markerOk){if(Object.keys(X).length>0){this.#Z.warn(`${Z.distrustReason}; leaving the memory store folder as found and not syncing`,{root:J.files.root().path,memory_store_id:J.memoryStoreId});return}await this.#V(J,"the folder or its marker is gone");return}if(Object.keys(X).length===0&&J.baseline.size>1){await this.#V(J,"every memory file is gone at once");return}let G=new Map;for await(let[K,W]of this.#T(J.memoryStoreId))G.set(K,W);let Q=new KZ(this.#G,Math.max(q5,Math.min(M5,Math.floor(J.baseline.size/4))),$),Y=[],z=new Map,B=[...new Set([...G.keys(),...Object.keys(X),...J.baseline.keys()])].sort();for(let K of B){let W=G.get(K),C=X[K],V=J.baseline.get(K),F;if(C===void 0&&V!==void 0&&W!==void 0&&W.content_sha256===V&&!J.readOnly)F=await this.#R(J,K,W,V,Q);else F=await this.#W(J,K,W,C,Y);if(F!==void 0)z.set(K,F)}if(J.baseline=z,await this.#O(J,Y),Q.suppressed>0)this.#Z.debug("remote deletes are disabled; locally deleted memories stay on the server",{count:Q.suppressed,memory_store_id:J.memoryStoreId});if(Q.capped>0)this.#Z.warn(`delete cap reached: ${Q.mode==="log_only"?"would send":"sent"} ${Q.attempted} deletes, held ${Q.capped} for later syncs`,{memory_store_id:J.memoryStoreId})}catch(Z){this.#Z.warn("memory sync failed",{memory_store_id:J.memoryStoreId,error:String(Z)})}}async syncIfDue(){if(Date.now()-this.#Q<this.#X)return;await this.syncAll(!1)}async flushWrites(J){await Promise.all(this.#Y.map(($)=>this.#U($,J)))}async#U(J,$){let Z=new Map,X=new Set,G=async()=>{if(J.readOnly)return;let Q=await this.#K(J);if(!Q.markerOk){this.#Z.warn(`${Q.distrustReason}; not uploading anything from the memory store folder`,{root:J.files.root().path,memory_store_id:J.memoryStoreId});return}for(let[B,K]of Object.entries(Q.files))if(K!==J.baseline.get(B)&&J.refusedShas.get(B)!==K)Z.set(B,K),X.add(B);if(Z.size===0||$?.aborted)return;let Y=new Map;for await(let[B,K]of this.#T(J.memoryStoreId)){if($?.aborted)return;Y.set(B,K)}let z=[];for(let B of[...Z.keys()].sort()){let K=Z.get(B),W=J.baseline.get(B),C=Y.get(B);if(C!==void 0&&C.content_sha256===K){J.baseline.set(B,C.content_sha256),X.delete(B);continue}if(C!==void 0&&C.content_sha256!==W){this.#Z.warn("memory changed both locally and remotely; the flush leaves the remote version",{path:B,memory_store_id:J.memoryStoreId}),X.delete(B);continue}z.push([B,K,C])}await this.#A(J,z,X,$)};try{if(await T5(G(),$),$?.aborted&&X.size>0)this.#Z.warn(`memory flush cut off part-way; ${X.size} of ${Z.size} changed files had not finished uploading`,{memory_store_id:J.memoryStoreId})}catch(Q){this.#Z.warn("memory flush failed",{memory_store_id:J.memoryStoreId,error:String(Q)})}}async dispose(){for(let J of this.#Y){let $=J.files.root();try{let Z=await this.#K(J);if(!Z.markerOk&&Object.keys(Z.files).length>0){this.#Z.warn(`${Z.distrustReason}; leaving the memory store folder on disk`,{root:$.path,memory_store_id:J.memoryStoreId});continue}await J.files.dispose()}catch(Z){if(!(Z instanceof u)&&!H2(Z))throw Z;this.#Z.warn("failed to remove the memory store folder",{root:J.files.root().path,memory_store_id:J.memoryStoreId,error:String(Z)});continue}if($.removedOnDispose)this.#Z.info("removed memory store dir",{dest:$.path,memory_store_id:J.memoryStoreId})}}async#V(J,$){this.#Z.warn(`${$}; re-downloading the memory store folder instead of syncing`,{root:J.files.root().path,memory_store_id:J.memoryStoreId}),await J.files.createRoot(),await this.#F(J)}async#F(J){J.baseline=new Map,J.pendingDeletes.clear(),await J.files.put(G2,`version ${BZ}
16
- ${J.memoryStoreId}`);for await(let[$,Z]of this.#T(J.memoryStoreId,"full"))if(await this.#q(J,$,Z.content??""))J.baseline.set($,Z.content_sha256)}async#W(J,$,Z,X,G){let Q=J.baseline.get($);if(X!==void 0)J.pendingDeletes.delete($);if(!Z){if(X===void 0){J.pendingDeletes.delete($);return}if(Q!==void 0){if(X===Q){let W=await this.#M(J,$,Q);if(W===void 0)return;if(W===Q)return Q;X=W}if(J.readOnly)this.#Z.warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:$,memory_store_id:J.memoryStoreId});else if(J.refusedShas.get($)!==X)this.#Z.info("memory deleted remotely but edited locally; re-creating it from the file",{path:$,memory_store_id:J.memoryStoreId})}if(J.readOnly)return;if(J.refusedShas.get($)===X)return;return await this.#N(J,$,X,void 0)}let Y=Z.content_sha256,z=Y!==Q,B=X!==void 0&&X!==Q&&X!==Y,K=!J.readOnly&&B;if(X===void 0&&Q!==void 0){if(z)this.#Z.warn("memory deleted locally but changed remotely; restoring the remote version",{path:$,memory_store_id:J.memoryStoreId}),J.pendingDeletes.delete($),G.push([$,Z]);return Q}if(z){if(X===Y)return Y;if(B)this.#Z.warn("memory changed both locally and remotely; keeping the remote version",{path:$,memory_store_id:J.memoryStoreId});return G.push([$,Z]),Q}if(K){if(J.refusedShas.get($)===X)return Y;return await this.#N(J,$,X,Z)??Y}return Y}async#M(J,$,Z){let X;try{X=await J.files.hashFile($)}catch(G){if(!(G instanceof u)&&!H2(G))throw G;return Z}if(X===null)return;if(X!==Z)return X;try{await J.files.remove($)}catch(G){if(!(G instanceof u)&&!H2(G))throw G;return this.#Z.warn("failed to remove memory deleted remotely",{path:$,memory_store_id:J.memoryStoreId,error:String(G)}),Z}return}async#q(J,$,Z){try{await J.files.put($,Z)}catch(X){if(!(X instanceof u)&&!H2(X))throw X;return this.#Z.warn("failed to write memory",{path:$,memory_store_id:J.memoryStoreId,error:String(X)}),!1}return!0}async#O(J,$){if($.length===0)return;let Z=async(Q,Y)=>{let z;try{z=await this.#J.beta.memoryStores.memories.retrieve(Y.id,{memory_store_id:J.memoryStoreId,view:"full"})}catch(B){if(e(B,404))return;this.#Z.warn("failed to fetch memory content",{path:Q,memory_store_id:J.memoryStoreId,error:String(B)});return}if(await this.#q(J,Q,z.content??""))J.baseline.set(Q,z.content_sha256)},X=$[Symbol.iterator](),G=async()=>{for(let[Q,Y]of X)await Z(Q,Y)};await Promise.all(Array.from({length:Math.min(N5,$.length)},G))}async#A(J,$,Z,X){let G=$[Symbol.iterator](),Q=async()=>{for(let[Y,z,B]of G){if(X?.aborted)return;let K=await this.#N(J,Y,z,B);if(Z.delete(Y),K!==void 0)J.baseline.set(Y,K)}};await Promise.all(Array.from({length:Math.min(F5,$.length)},Q))}async*#T(J,$="basic"){let Z=$==="basic"?C5:U5;for await(let X of this.#J.beta.memoryStores.memories.list(J,{view:$,limit:Z})){if(X.type!=="memory")continue;let G=X.path.replace(/^\/+/,"");if(G===G2){this.#Z.warn("the server listed the reserved marker path; skipping",{path:X.path,memory_store_id:J});continue}yield[G,X]}}async#N(J,$,Z,X){try{let G=await J.files.get($);if(G===null)return;let Q=t0(G),Y=X?await this.#J.beta.memoryStores.memories.update(X.id,{memory_store_id:J.memoryStoreId,content:Q,precondition:{type:"content_sha256",content_sha256:X.content_sha256}}):await this.#J.beta.memoryStores.memories.create(J.memoryStoreId,{path:"/"+$,content:Q});return J.refusedShas.delete($),Y.content_sha256}catch(G){if(X&&e(G,404))return await this.#N(J,$,Z,void 0);let Q=G instanceof u||e(G,400)||e(G,413);if(X&&e(G,409))this.#Z.warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:$,memory_store_id:J.memoryStoreId});else if(Q&&Z!==void 0)J.refusedShas.set($,Z),this.#Z.warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:$,memory_store_id:J.memoryStoreId,rejection:String(G)});else this.#Z.warn("failed to upload memory",{path:$,memory_store_id:J.memoryStoreId,error:String(G)});return}}async#R(J,$,Z,X,G){if(G.mode==="disabled")return G.suppressed++,X;let Q=J.pendingDeletes.get($);if(Q===void 0)Q=Date.now(),J.pendingDeletes.set($,Q);if(!G.waiveWindow&&Date.now()-Q<V5)return X;let Y,z;try{Y=await J.files.hashFile(G2)===YZ(J.memoryStoreId),z=await J.files.hashFile($)===null}catch(K){if(!(K instanceof u)&&!H2(K))throw K;Y=z=!1}if(!Y)return X;if(!z)return J.pendingDeletes.delete($),X;if(!G.takeSlot())return X;if(G.mode==="log_only")return this.#Z.info("log-only: sync would delete this memory on the server",{path:$,memory_store_id:J.memoryStoreId}),X;let B=await this.#w(J,$,Z,X);if(B===void 0)J.pendingDeletes.delete($);return B}async#w(J,$,Z,X){try{await this.#J.beta.memoryStores.memories.delete(Z.id,{memory_store_id:J.memoryStoreId,expected_content_sha256:X})}catch(G){if(e(G,404))return;if(e(G,409)||e(G,412))this.#Z.warn("memory deleted locally but changed remotely; keeping the remote version",{path:$,memory_store_id:J.memoryStoreId});else this.#Z.warn("failed to delete memory",{path:$,memory_store_id:J.memoryStoreId,error:String(G)});return X}this.#Z.info("propagated local deletion",{path:$,memory_store_id:J.memoryStoreId});return}}function H2(J){return typeof J==="object"&&J!==null&&typeof J.code==="string"}async function T5(J,$){if(!$){await J;return}let Z,X=new Promise((G)=>{if(Z=G,$.aborted)G()});$.addEventListener("abort",Z,{once:!0});try{await Promise.race([J,X])}finally{$.removeEventListener("abort",Z)}}var zZ=30000,G2=".puku-memory-store",BZ=1,V5=30000,C5=100,U5=20,N5=16,F5=32,q5=8,M5=50,u0;var WZ=M(()=>{K0();c();O0();T2();QZ();y1();y1();u0=class u0 extends T{constructor(J,$){super(J);if(this.name="SessionMemoryError",$!==void 0)this.cause=$}}});var AZ={};RJ(AZ,{setupSkills:()=>t6,resolvePath:()=>Y2,extractSkillArchive:()=>v1,betaWriteTool:()=>Q4,betaReadTool:()=>G4,betaGrepTool:()=>B4,betaGlobTool:()=>z4,betaEditTool:()=>Y4,betaBashTool:()=>X4,betaAgentToolset20260401:()=>TZ,SessionMemoryStores:()=>$4,SessionMemoryError:()=>u0,MIN_MEMORY_SYNC_INTERVAL_MS:()=>U8,MEMORY_FLUSH_TIMEOUT_MS:()=>zZ,MARKER_PATH:()=>G2,DEFAULT_MEMORY_SYNC_INTERVAL_MS:()=>N8,BashTimeoutError:()=>g1,BashSession:()=>h1});import*as J0 from"node:fs/promises";import*as O8 from"node:fs";import*as Y0 from"node:path";import*as Z4 from"node:child_process";import*as NZ from"node:crypto";import*as FZ from"node:readline";function MZ(J){return J===void 0?w5:J}function Q2(J){if(J===void 0)return;throw new T("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function TZ(J){return[X4(J),G4(J),Q4(J),Y4(J),z4(J),B4(J)]}async function Y2(J,$){return Q2(J.unrestrictedPaths),a$(J.workdir,$,{allowedRoots:J.allowedRoots??[]})}function wZ(J,$){return n6(J.readOnlyRoots??[],$)}function D5(){let J={};for(let[$,Z]of Object.entries(process.env)){if($.startsWith("PUKU_"))continue;J[$]=Z}return J}class h1{#J;#$="";#X=!1;#G=!1;#Z=null;constructor(J,$=D5()){this.#J=Z4.spawn("/bin/bash",["--noprofile","--norc"],{cwd:J,env:{...$,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),this.#J.stdout.setEncoding("utf8"),this.#J.stderr.setEncoding("utf8"),this.#J.stdout.on("data",(Z)=>this.#Q(Z)),this.#J.stderr.on("data",(Z)=>this.#Q(Z)),this.#J.once("close",()=>{this.#G=!0;let Z=this.#Z;this.#Z=null,Z?.resolve()})}get closed(){return this.#G}#Q(J){if(this.#$+=J,this.#$.length>VZ)this.#$=this.#$.slice(this.#$.length-VZ),this.#X=!0;if(this.#Z&&this.#$.indexOf(this.#Z.sentinel)>=0){let $=this.#Z;this.#Z=null,$.resolve()}}async exec(J,$={}){if(this.#G)throw new T("bash session terminated");let Z=$.timeoutMs??qZ,X=$.signal;X?.throwIfAborted(),this.#$="",this.#X=!1;let G=`__ANT_CMD_${NZ.randomUUID()}_DONE__`,Q=`${G.slice(0,8)}''${G.slice(8)}`,Y=`{ ${J}
14
+ `,{flag:"wx",mode:384}),["-xf",$,"-C",Z,"-X",G]}async function s3(J,$){let Z=await M0.open(J,"r");try{let X=Buffer.alloc($),{bytesRead:G}=await Z.read(X,0,$,0);return X.subarray(0,G)}finally{await Z.close()}}var M0,l3,s6="skill archive listing is inconsistent; refusing to extract",n3;var t$=M(()=>{K0();c();O0();o6();M0=_0.promises,l3=K6.promisify(B6.execFile);n3={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])}});function JJ(J){return J.startsWith("/")&&!J.split("/").includes("..")}function ZX(){return e6!==0}async function XX(J){let $=[],Z=J;for(;;){try{await r.stat(Z);break}catch(G){let Q=G.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR"&&Q!=="ELOOP")throw G}$.push(Z);let X=j.dirname(Z);if(X===Z)break;Z=X}for(let X of $.reverse())try{await r.mkdir(X,{mode:$Z})}catch(G){if(G.code!=="EEXIST")throw G}}async function s$(J,$){let Z=j.relative(J,$);if(Z==="")return;let X=J;for(let G of Z.split(j.sep)){X=j.join(X,G);try{await r.mkdir(X,{mode:$Z})}catch(Q){if(Q.code!=="EEXIST")throw Q}}}async function GX(J,$,Z){let X=Z?JX:e3,G=j.join(j.dirname(J),`.fs-${k0.randomBytes(8).toString("hex")}.tmp`),Q;try{Q=await r.open(G,A2.O_WRONLY|A2.O_CREAT|A2.O_EXCL|e6,X),await Q.writeFile($),await Q.close(),Q=void 0,await r.rename(G,J)}catch(Y){if(Q)await Q.close().catch(()=>{});throw await r.unlink(G).catch(()=>{}),Y}}async function ZZ(J,$){let Z;try{Z=await r.open($,A2.O_RDONLY|e6|$X)}catch(X){let G=X.code;if(G==="ELOOP"||G==="EMLINK")throw new u(u.IS_A_SYMLINK,J);throw X}try{if(!(await Z.stat()).isFile())throw new u(u.NOT_A_FILE,J)}catch(X){throw await Z.close().catch(()=>{}),X}return Z}async function QX(J){let $=k0.createHash("sha256"),Z=await ZZ(j.basename(J),J),X=new Uint8Array(1048576);try{for(;;){let{bytesRead:G}=await Z.read(X,0,X.length);if(G===0)break;$.update(X.subarray(0,G))}}finally{await Z.close()}return $.digest("hex")}async function e$(J,$,Z){if(!await zX($,Z))return[];let X=[];return await XZ(Z,(G,Q)=>{if(Q.isFile())X.push([j.relative(J,G).split(j.sep).join("/"),G])}),X.sort(),X}async function YX(J,$,Z){let X=(Y)=>j.relative(J,Y).split(j.sep).join("/"),G;try{G=await r.lstat(Z,{bigint:!0})}catch(Y){let z=Y.code;if(z==="ENOENT"||z==="ENOTDIR")return new Set;throw Y}if(G.isSymbolicLink())return new Set([X(Z)]);if(!G.isDirectory())throw new u(u.NOT_A_DIRECTORY,$);let Q=new Set;return await XZ(Z,(Y,z)=>{if(z.isSymbolicLink())Q.add(X(Y))}),Q}async function zX(J,$){let Z;try{Z=await r.lstat($,{bigint:!0})}catch(X){let G=X.code;if(G==="ENOENT"||G==="ENOTDIR")return!1;throw X}if(!Z.isDirectory())throw new u(u.NOT_A_DIRECTORY,J);return!0}async function XZ(J,$){let Z=[J];while(Z.length){let X=Z.pop(),G;try{G=await r.readdir(X,{withFileTypes:!0})}catch(Q){if(Q.code==="ENOENT")continue;throw Q}for(let Q of G){let Y=j.join(X,Q.name);if($(Y,Q),Q.isDirectory()&&!Q.isSymbolicLink())Z.push(Y)}}}function BX(J,$){return $.mtimeNs===J.mtimeNs&&$.ctimeNs===J.ctimeNs&&$.size===J.size}function KX(J,$){return(J.mtimeNs>J.ctimeNs?J.mtimeNs:J.ctimeNs)<$-b1.timestampTrustMarginNs}var r,A2,$Z=448,e3=384,JX=448,e6,$X,u,T8,WX=2000000000n,b1,GZ,JZ;var QZ=M(()=>{K0();r=_0.promises,A2=_0.constants,e6=A2.O_NOFOLLOW??0,$X=A2.O_NONBLOCK??0;u=class u extends Error{static ESCAPES_ROOT="escapes the store root";static IS_A_SYMLINK="is a symlink";static NOT_A_FILE="is not a regular file";static NOT_A_DIRECTORY="is not a directory";static NOT_UTF8="is not valid utf-8";static MOVE_DESTINATION_EXISTS="already exists";reason;relPath;constructor(J,$){super(`path ${JSON.stringify($)} ${J}`);this.name="FileStoreError",this.reason=J,this.relPath=$}};T8=class T8{rootPath;removedOnDispose;decoder;hashes=new Map;static isPathLegal=JJ;constructor(J,$,Z=!1){this.rootPath=J,this.removedOnDispose=$,this.decoder=Z?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(J,$){if(!ZX())throw Error("FileStore requires O_NOFOLLOW support on this platform");let Z=!1;try{await r.lstat(J)}catch(X){if(X.code!=="ENOENT")throw X;Z=!0}return new T8(j.resolve(J),Z,$?.utf8??!1)}async createRoot(){await XX(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){if(!this.removedOnDispose)return;await r.rm(this.rootPath,{recursive:!0,force:!0})}async put(J,$,Z){let X=J.replace(/\\/g,"/");if(X.endsWith("/")||X.endsWith("/.")||X===""||X===".")throw new u(u.NOT_A_FILE,J);let G=this.resolveUnderRoot(J),Q=typeof $==="string"?v0($):$;this.requireUtf8(J,Q),await s$(this.rootPath,j.dirname(G)),await GX(G,Q,Z?.executable??!1)}async get(J){let $=this.resolveUnderRoot(J),Z;try{Z=await ZZ(J,$)}catch(G){if(G.code==="ENOENT")return null;throw G}let X;try{let G=await Z.readFile();X=new Uint8Array(G.buffer,G.byteOffset,G.byteLength)}finally{await Z.close()}return this.requireUtf8(J,X),X}async ls(J="/"){let $=this.resolveUnderRoot(J);return new Set((await e$(this.rootPath,J,$)).map(([Z])=>Z))}async findSymlinks(J="/"){let $=this.resolveUnderRoot(J);return YX(this.rootPath,J,$)}async hashtree(J="/"){let $=this.resolveUnderRoot(J),Z=b1.nowNs(),X=Object.create(null);for(let[G,Q]of await e$(this.rootPath,J,$)){let Y=await this.hashViaCache(G,Q,Z);if(Y!==null)X[G]=Y}return X}async hashFile(J){let $=this.resolveUnderRoot(J),Z;try{Z=await r.lstat($,{bigint:!0})}catch(G){if(G.code==="ENOENT")return null;throw G}if(Z.isSymbolicLink())throw new u(u.IS_A_SYMLINK,J);if(!Z.isFile())throw new u(u.NOT_A_FILE,J);let X=j.relative(this.rootPath,$).split(j.sep).join("/");return this.hashViaCache(X,$,b1.nowNs())}async move(J,$){let Z=this.resolveUnderRoot(J),X=this.resolveUnderRoot($);if(Z===this.rootPath||X===this.rootPath)return;if(await r.stat(X).then(()=>!0,()=>!1))throw new u(u.MOVE_DESTINATION_EXISTS,$);await s$(this.rootPath,j.dirname(X)),await r.rename(Z,X)}async remove(J){let $=this.resolveUnderRoot(J);if($===this.rootPath)return;let Z;try{Z=await r.lstat($,{bigint:!0})}catch(X){if(X.code==="ENOENT")return;throw X}if(Z.isDirectory())await r.rm($,{recursive:!0,force:!0});else try{await r.unlink($)}catch(X){if(X.code!=="ENOENT")throw X}}resolveUnderRoot(J){let $=J.replace(/\\/g,"/").replace(/^\/+/,""),Z=$.split("/").filter((X)=>X!==""&&X!==".");if(j.posix.isAbsolute($)||Z.includes(".."))throw new u(u.ESCAPES_ROOT,J);return Z.length===0?this.rootPath:j.join(this.rootPath,...Z)}requireUtf8(J,$){if(!this.decoder)return;try{this.decoder.decode($)}catch{throw new u(u.NOT_UTF8,J)}}async hashViaCache(J,$,Z){let X;try{X=await r.lstat($,{bigint:!0})}catch(Y){if(Y.code==="ENOENT")return null;throw Y}if(!X.isFile())return null;let G=this.hashes.get(J),Q;if(G!==void 0&&BX(G,X))Q=G.sha;else try{Q=await b1.hashFile($)}catch(Y){let z=Y.code;if(z==="ENOENT"||Y instanceof u)return null;if(z==="ELOOP"||z==="EMLINK")return null;throw Y}if(KX(X,Z))this.hashes.set(J,{mtimeNs:X.mtimeNs,ctimeNs:X.ctimeNs,size:X.size,sha:Q});return Q}};b1={hashFile:QX,timestampTrustMarginNs:WX,nowNs:()=>BigInt(Date.now())*1000000n},GZ=T8,JZ=Symbol.asyncDispose;if(JZ)Object.defineProperty(T8.prototype,JZ,{value:T8.prototype.dispose,configurable:!0,writable:!0})});function YZ(J){return k0.createHash("sha256").update(`version ${BZ}
15
+ ${J}`,"utf-8").digest("hex")}class KZ{mode;cap;waiveWindow;attempted=0;capped=0;suppressed=0;constructor(J,$,Z){this.mode=J;this.cap=$;this.waiveWindow=Z}takeSlot(){if(this.attempted>=this.cap)return this.capped++,!1;return this.attempted++,!0}}class $J{#J;#$;#X;#G;#Z;#Q;#B=!1;#Y=[];constructor(J,$){this.#J=J,this.#$=$.workdir,this.#X=$.syncIntervalMs??N8,I1(this.#X,"syncIntervalMs"),this.#G=$.syncDeletions??"enabled",this.#Z=k(J),this.#Q=Date.now()}get roots(){return this.#Y.map((J)=>J.files.root().path)}get readOnlyRoots(){return this.#Y.filter((J)=>J.readOnly).map((J)=>J.files.root().path)}#z(J){if(J.mount_path){if(!JJ(J.mount_path))throw new u0(`memory store mount_path is not a clean absolute path: ${JSON.stringify(J.mount_path)} (memory_store_id=${J.memory_store_id})`);return J.mount_path}return j.join(this.#$,"memory",J.name||J.memory_store_id)}async download(J){for(let $ of J.resources){if($.type!=="memory_store")continue;let Z=this.#z($),X;try{if(X={memoryStoreId:$.memory_store_id,files:await GZ.open(Z,{utf8:!0}),readOnly:$.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!X.files.root().removedOnDispose)throw new u0(`something already exists at the memory store's path: ${Z} (memory_store_id=${$.memory_store_id}); it must not exist when the session starts`);try{await X.files.createRoot()}catch(G){if(!H2(G))throw G;throw new u0(`cannot create the memory store's folder: ${Z} (memory_store_id=${$.memory_store_id}): ${G}; the worker host must make this mount path writable`,G)}await this.#F(X),this.#Z.info("downloaded memories",{count:X.baseline.size,memory_store_id:X.memoryStoreId,dest:X.files.root().path}),this.#Y.push(X)}catch(G){if(X)await X.files.dispose().catch(()=>{});if(G instanceof u0)throw G;throw new u0(`failed to download memory store memory_store_id=${$.memory_store_id}: ${G}`,G)}}this.#Q=Date.now()}async finish(){if(this.#B)throw new T("finish() was already called: it is the session's last sync and runs once");this.#B=!0,await this.syncAll(!0)}async syncAll(J){await Promise.all(this.#Y.map(($)=>this.#C($,J))),this.#Q=Date.now()}async#K(J){let $=await J.files.hashtree(),Z=$[G2];if(delete $[G2],Z===YZ(J.memoryStoreId))return{files:$,markerOk:!0,distrustReason:null};return{files:$,markerOk:!1,distrustReason:Z!==void 0?"the marker file does not match this store":"the marker file is gone"}}async#C(J,$){try{let Z=await this.#K(J),X=Z.files;if(!Z.markerOk){if(Object.keys(X).length>0){this.#Z.warn(`${Z.distrustReason}; leaving the memory store folder as found and not syncing`,{root:J.files.root().path,memory_store_id:J.memoryStoreId});return}await this.#V(J,"the folder or its marker is gone");return}if(Object.keys(X).length===0&&J.baseline.size>1){await this.#V(J,"every memory file is gone at once");return}let G=new Map;for await(let[K,W]of this.#T(J.memoryStoreId))G.set(K,W);let Q=new KZ(this.#G,Math.max(qX,Math.min(MX,Math.floor(J.baseline.size/4))),$),Y=[],z=new Map,B=[...new Set([...G.keys(),...Object.keys(X),...J.baseline.keys()])].sort();for(let K of B){let W=G.get(K),C=X[K],V=J.baseline.get(K),F;if(C===void 0&&V!==void 0&&W!==void 0&&W.content_sha256===V&&!J.readOnly)F=await this.#R(J,K,W,V,Q);else F=await this.#W(J,K,W,C,Y);if(F!==void 0)z.set(K,F)}if(J.baseline=z,await this.#O(J,Y),Q.suppressed>0)this.#Z.debug("remote deletes are disabled; locally deleted memories stay on the server",{count:Q.suppressed,memory_store_id:J.memoryStoreId});if(Q.capped>0)this.#Z.warn(`delete cap reached: ${Q.mode==="log_only"?"would send":"sent"} ${Q.attempted} deletes, held ${Q.capped} for later syncs`,{memory_store_id:J.memoryStoreId})}catch(Z){this.#Z.warn("memory sync failed",{memory_store_id:J.memoryStoreId,error:String(Z)})}}async syncIfDue(){if(Date.now()-this.#Q<this.#X)return;await this.syncAll(!1)}async flushWrites(J){await Promise.all(this.#Y.map(($)=>this.#U($,J)))}async#U(J,$){let Z=new Map,X=new Set,G=async()=>{if(J.readOnly)return;let Q=await this.#K(J);if(!Q.markerOk){this.#Z.warn(`${Q.distrustReason}; not uploading anything from the memory store folder`,{root:J.files.root().path,memory_store_id:J.memoryStoreId});return}for(let[B,K]of Object.entries(Q.files))if(K!==J.baseline.get(B)&&J.refusedShas.get(B)!==K)Z.set(B,K),X.add(B);if(Z.size===0||$?.aborted)return;let Y=new Map;for await(let[B,K]of this.#T(J.memoryStoreId)){if($?.aborted)return;Y.set(B,K)}let z=[];for(let B of[...Z.keys()].sort()){let K=Z.get(B),W=J.baseline.get(B),C=Y.get(B);if(C!==void 0&&C.content_sha256===K){J.baseline.set(B,C.content_sha256),X.delete(B);continue}if(C!==void 0&&C.content_sha256!==W){this.#Z.warn("memory changed both locally and remotely; the flush leaves the remote version",{path:B,memory_store_id:J.memoryStoreId}),X.delete(B);continue}z.push([B,K,C])}await this.#A(J,z,X,$)};try{if(await TX(G(),$),$?.aborted&&X.size>0)this.#Z.warn(`memory flush cut off part-way; ${X.size} of ${Z.size} changed files had not finished uploading`,{memory_store_id:J.memoryStoreId})}catch(Q){this.#Z.warn("memory flush failed",{memory_store_id:J.memoryStoreId,error:String(Q)})}}async dispose(){for(let J of this.#Y){let $=J.files.root();try{let Z=await this.#K(J);if(!Z.markerOk&&Object.keys(Z.files).length>0){this.#Z.warn(`${Z.distrustReason}; leaving the memory store folder on disk`,{root:$.path,memory_store_id:J.memoryStoreId});continue}await J.files.dispose()}catch(Z){if(!(Z instanceof u)&&!H2(Z))throw Z;this.#Z.warn("failed to remove the memory store folder",{root:J.files.root().path,memory_store_id:J.memoryStoreId,error:String(Z)});continue}if($.removedOnDispose)this.#Z.info("removed memory store dir",{dest:$.path,memory_store_id:J.memoryStoreId})}}async#V(J,$){this.#Z.warn(`${$}; re-downloading the memory store folder instead of syncing`,{root:J.files.root().path,memory_store_id:J.memoryStoreId}),await J.files.createRoot(),await this.#F(J)}async#F(J){J.baseline=new Map,J.pendingDeletes.clear(),await J.files.put(G2,`version ${BZ}
16
+ ${J.memoryStoreId}`);for await(let[$,Z]of this.#T(J.memoryStoreId,"full"))if(await this.#q(J,$,Z.content??""))J.baseline.set($,Z.content_sha256)}async#W(J,$,Z,X,G){let Q=J.baseline.get($);if(X!==void 0)J.pendingDeletes.delete($);if(!Z){if(X===void 0){J.pendingDeletes.delete($);return}if(Q!==void 0){if(X===Q){let W=await this.#M(J,$,Q);if(W===void 0)return;if(W===Q)return Q;X=W}if(J.readOnly)this.#Z.warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:$,memory_store_id:J.memoryStoreId});else if(J.refusedShas.get($)!==X)this.#Z.info("memory deleted remotely but edited locally; re-creating it from the file",{path:$,memory_store_id:J.memoryStoreId})}if(J.readOnly)return;if(J.refusedShas.get($)===X)return;return await this.#N(J,$,X,void 0)}let Y=Z.content_sha256,z=Y!==Q,B=X!==void 0&&X!==Q&&X!==Y,K=!J.readOnly&&B;if(X===void 0&&Q!==void 0){if(z)this.#Z.warn("memory deleted locally but changed remotely; restoring the remote version",{path:$,memory_store_id:J.memoryStoreId}),J.pendingDeletes.delete($),G.push([$,Z]);return Q}if(z){if(X===Y)return Y;if(B)this.#Z.warn("memory changed both locally and remotely; keeping the remote version",{path:$,memory_store_id:J.memoryStoreId});return G.push([$,Z]),Q}if(K){if(J.refusedShas.get($)===X)return Y;return await this.#N(J,$,X,Z)??Y}return Y}async#M(J,$,Z){let X;try{X=await J.files.hashFile($)}catch(G){if(!(G instanceof u)&&!H2(G))throw G;return Z}if(X===null)return;if(X!==Z)return X;try{await J.files.remove($)}catch(G){if(!(G instanceof u)&&!H2(G))throw G;return this.#Z.warn("failed to remove memory deleted remotely",{path:$,memory_store_id:J.memoryStoreId,error:String(G)}),Z}return}async#q(J,$,Z){try{await J.files.put($,Z)}catch(X){if(!(X instanceof u)&&!H2(X))throw X;return this.#Z.warn("failed to write memory",{path:$,memory_store_id:J.memoryStoreId,error:String(X)}),!1}return!0}async#O(J,$){if($.length===0)return;let Z=async(Q,Y)=>{let z;try{z=await this.#J.beta.memoryStores.memories.retrieve(Y.id,{memory_store_id:J.memoryStoreId,view:"full"})}catch(B){if(e(B,404))return;this.#Z.warn("failed to fetch memory content",{path:Q,memory_store_id:J.memoryStoreId,error:String(B)});return}if(await this.#q(J,Q,z.content??""))J.baseline.set(Q,z.content_sha256)},X=$[Symbol.iterator](),G=async()=>{for(let[Q,Y]of X)await Z(Q,Y)};await Promise.all(Array.from({length:Math.min(NX,$.length)},G))}async#A(J,$,Z,X){let G=$[Symbol.iterator](),Q=async()=>{for(let[Y,z,B]of G){if(X?.aborted)return;let K=await this.#N(J,Y,z,B);if(Z.delete(Y),K!==void 0)J.baseline.set(Y,K)}};await Promise.all(Array.from({length:Math.min(FX,$.length)},Q))}async*#T(J,$="basic"){let Z=$==="basic"?CX:UX;for await(let X of this.#J.beta.memoryStores.memories.list(J,{view:$,limit:Z})){if(X.type!=="memory")continue;let G=X.path.replace(/^\/+/,"");if(G===G2){this.#Z.warn("the server listed the reserved marker path; skipping",{path:X.path,memory_store_id:J});continue}yield[G,X]}}async#N(J,$,Z,X){try{let G=await J.files.get($);if(G===null)return;let Q=t0(G),Y=X?await this.#J.beta.memoryStores.memories.update(X.id,{memory_store_id:J.memoryStoreId,content:Q,precondition:{type:"content_sha256",content_sha256:X.content_sha256}}):await this.#J.beta.memoryStores.memories.create(J.memoryStoreId,{path:"/"+$,content:Q});return J.refusedShas.delete($),Y.content_sha256}catch(G){if(X&&e(G,404))return await this.#N(J,$,Z,void 0);let Q=G instanceof u||e(G,400)||e(G,413);if(X&&e(G,409))this.#Z.warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:$,memory_store_id:J.memoryStoreId});else if(Q&&Z!==void 0)J.refusedShas.set($,Z),this.#Z.warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:$,memory_store_id:J.memoryStoreId,rejection:String(G)});else this.#Z.warn("failed to upload memory",{path:$,memory_store_id:J.memoryStoreId,error:String(G)});return}}async#R(J,$,Z,X,G){if(G.mode==="disabled")return G.suppressed++,X;let Q=J.pendingDeletes.get($);if(Q===void 0)Q=Date.now(),J.pendingDeletes.set($,Q);if(!G.waiveWindow&&Date.now()-Q<VX)return X;let Y,z;try{Y=await J.files.hashFile(G2)===YZ(J.memoryStoreId),z=await J.files.hashFile($)===null}catch(K){if(!(K instanceof u)&&!H2(K))throw K;Y=z=!1}if(!Y)return X;if(!z)return J.pendingDeletes.delete($),X;if(!G.takeSlot())return X;if(G.mode==="log_only")return this.#Z.info("log-only: sync would delete this memory on the server",{path:$,memory_store_id:J.memoryStoreId}),X;let B=await this.#w(J,$,Z,X);if(B===void 0)J.pendingDeletes.delete($);return B}async#w(J,$,Z,X){try{await this.#J.beta.memoryStores.memories.delete(Z.id,{memory_store_id:J.memoryStoreId,expected_content_sha256:X})}catch(G){if(e(G,404))return;if(e(G,409)||e(G,412))this.#Z.warn("memory deleted locally but changed remotely; keeping the remote version",{path:$,memory_store_id:J.memoryStoreId});else this.#Z.warn("failed to delete memory",{path:$,memory_store_id:J.memoryStoreId,error:String(G)});return X}this.#Z.info("propagated local deletion",{path:$,memory_store_id:J.memoryStoreId});return}}function H2(J){return typeof J==="object"&&J!==null&&typeof J.code==="string"}async function TX(J,$){if(!$){await J;return}let Z,X=new Promise((G)=>{if(Z=G,$.aborted)G()});$.addEventListener("abort",Z,{once:!0});try{await Promise.race([J,X])}finally{$.removeEventListener("abort",Z)}}var zZ=30000,G2=".puku-memory-store",BZ=1,VX=30000,CX=100,UX=20,NX=16,FX=32,qX=8,MX=50,u0;var WZ=M(()=>{K0();c();O0();T2();QZ();y1();y1();u0=class u0 extends T{constructor(J,$){super(J);if(this.name="SessionMemoryError",$!==void 0)this.cause=$}}});var AZ={};R4(AZ,{setupSkills:()=>t6,resolvePath:()=>Y2,extractSkillArchive:()=>v1,betaWriteTool:()=>QJ,betaReadTool:()=>GJ,betaGrepTool:()=>BJ,betaGlobTool:()=>zJ,betaEditTool:()=>YJ,betaBashTool:()=>XJ,betaAgentToolset20260401:()=>TZ,SessionMemoryStores:()=>$J,SessionMemoryError:()=>u0,MIN_MEMORY_SYNC_INTERVAL_MS:()=>U8,MEMORY_FLUSH_TIMEOUT_MS:()=>zZ,MARKER_PATH:()=>G2,DEFAULT_MEMORY_SYNC_INTERVAL_MS:()=>N8,BashTimeoutError:()=>g1,BashSession:()=>h1});import*as J0 from"node:fs/promises";import*as O8 from"node:fs";import*as Y0 from"node:path";import*as ZJ from"node:child_process";import*as NZ from"node:crypto";import*as FZ from"node:readline";function MZ(J){return J===void 0?wX:J}function Q2(J){if(J===void 0)return;throw new T("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function TZ(J){return[XJ(J),GJ(J),QJ(J),YJ(J),zJ(J),BJ(J)]}async function Y2(J,$){return Q2(J.unrestrictedPaths),a$(J.workdir,$,{allowedRoots:J.allowedRoots??[]})}function wZ(J,$){return n6(J.readOnlyRoots??[],$)}function DX(){let J={};for(let[$,Z]of Object.entries(process.env)){if($.startsWith("PUKU_"))continue;J[$]=Z}return J}class h1{#J;#$="";#X=!1;#G=!1;#Z=null;constructor(J,$=DX()){this.#J=ZJ.spawn("/bin/bash",["--noprofile","--norc"],{cwd:J,env:{...$,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),this.#J.stdout.setEncoding("utf8"),this.#J.stderr.setEncoding("utf8"),this.#J.stdout.on("data",(Z)=>this.#Q(Z)),this.#J.stderr.on("data",(Z)=>this.#Q(Z)),this.#J.once("close",()=>{this.#G=!0;let Z=this.#Z;this.#Z=null,Z?.resolve()})}get closed(){return this.#G}#Q(J){if(this.#$+=J,this.#$.length>VZ)this.#$=this.#$.slice(this.#$.length-VZ),this.#X=!0;if(this.#Z&&this.#$.indexOf(this.#Z.sentinel)>=0){let $=this.#Z;this.#Z=null,$.resolve()}}async exec(J,$={}){if(this.#G)throw new T("bash session terminated");let Z=$.timeoutMs??qZ,X=$.signal;X?.throwIfAborted(),this.#$="",this.#X=!1;let G=`__ANT_CMD_${NZ.randomUUID()}_DONE__`,Q=`${G.slice(0,8)}''${G.slice(8)}`,Y=`{ ${J}
17
17
  } </dev/null 2>&1; printf '\\n${Q}%d\\n' $?
18
- `;if(this.#J.stdin.write(Y),this.#$.indexOf(G)<0){let{promise:V,resolve:F}=w2();this.#Z={sentinel:G,resolve:F};let q,A;try{await Promise.race([V,new Promise((R,H)=>{q=setTimeout(()=>H(new g1(Z)),Z)}),new Promise((R,H)=>{if(!X)return;A=()=>H(X.reason),X.addEventListener("abort",A,{once:!0})})])}finally{if(q)clearTimeout(q);if(A&&X)X.removeEventListener("abort",A);this.#Z=null}}let z=this.#$.indexOf(G);if(z<0)throw new T("bash session terminated");let K=this.#$.slice(z+G.length).match(/^(-?\d+)/),W=K?parseInt(K[1],10):-1,C=this.#$.slice(0,z).replace(H5,"").replace(/\n+$/,"");if(this.#X)C=`[output truncated]
19
- ${C}`;return{output:C,exitCode:W}}close(){if(this.#G)return;this.#G=!0;let J=this.#Z;this.#Z=null,J?.resolve(),this.#J.stdout.destroy(),this.#J.stderr.destroy(),this.#J.stdin.destroy();try{process.kill(-this.#J.pid,"SIGKILL")}catch{this.#J.kill("SIGKILL")}this.#J.unref()}}function X4(J){Q2(J.unrestrictedPaths);let $,Z=Promise.resolve();return m0({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command:X,restart:G,timeout_ms:Q},Y)=>{let z=Z,B=w2();Z=B.promise;try{await z}catch{}try{if(G)$?.close(),$=void 0;if(!X){if(G)return"bash session restarted";throw new P("bash: command is required")}$??=new h1(J.workdir,J.env);try{let{output:K,exitCode:W}=await $.exec(X,{timeoutMs:Q??qZ,signal:Y?.signal});if(W!==0)throw new P(K||`exit ${W}`);return K}catch(K){if(K instanceof P)throw K;throw $.close(),$=void 0,new P(`bash: ${K instanceof Error?K.message:String(K)}`)}}finally{B.resolve()}},close:()=>{$?.close(),$=void 0}})}function G4(J){return Q2(J.unrestrictedPaths),m0({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path:$,view_range:Z})=>{if(!$)throw new P("read: file_path is required");let X=await Y2(J,$);if(Z?.length&&Z.length!==2)throw new P("read: view_range must be [start_line, end_line]");let G;try{let W=await J0.stat(X);if(!W.isFile())throw new P(`read: ${$} is not a regular file`);let C=MZ(J.maxFileBytes);if(C!==null&&W.size>C){if(!Z?.length)throw new P(`read: ${$} is ${W.size} bytes, exceeds ${C}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[V,F]=Z;return await j5(X,$,V,F,C)}G=await J0.readFile(X,"utf8")}catch(W){if(W instanceof P)throw W;throw new P(`read: ${R2(W,$)}`)}if(!Z?.length)return G;let[Q,Y]=Z,z=G.split(`
18
+ `;if(this.#J.stdin.write(Y),this.#$.indexOf(G)<0){let{promise:V,resolve:F}=w2();this.#Z={sentinel:G,resolve:F};let q,A;try{await Promise.race([V,new Promise((R,H)=>{q=setTimeout(()=>H(new g1(Z)),Z)}),new Promise((R,H)=>{if(!X)return;A=()=>H(X.reason),X.addEventListener("abort",A,{once:!0})})])}finally{if(q)clearTimeout(q);if(A&&X)X.removeEventListener("abort",A);this.#Z=null}}let z=this.#$.indexOf(G);if(z<0)throw new T("bash session terminated");let K=this.#$.slice(z+G.length).match(/^(-?\d+)/),W=K?parseInt(K[1],10):-1,C=this.#$.slice(0,z).replace(HX,"").replace(/\n+$/,"");if(this.#X)C=`[output truncated]
19
+ ${C}`;return{output:C,exitCode:W}}close(){if(this.#G)return;this.#G=!0;let J=this.#Z;this.#Z=null,J?.resolve(),this.#J.stdout.destroy(),this.#J.stderr.destroy(),this.#J.stdin.destroy();try{process.kill(-this.#J.pid,"SIGKILL")}catch{this.#J.kill("SIGKILL")}this.#J.unref()}}function XJ(J){Q2(J.unrestrictedPaths);let $,Z=Promise.resolve();return m0({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command:X,restart:G,timeout_ms:Q},Y)=>{let z=Z,B=w2();Z=B.promise;try{await z}catch{}try{if(G)$?.close(),$=void 0;if(!X){if(G)return"bash session restarted";throw new P("bash: command is required")}$??=new h1(J.workdir,J.env);try{let{output:K,exitCode:W}=await $.exec(X,{timeoutMs:Q??qZ,signal:Y?.signal});if(W!==0)throw new P(K||`exit ${W}`);return K}catch(K){if(K instanceof P)throw K;throw $.close(),$=void 0,new P(`bash: ${K instanceof Error?K.message:String(K)}`)}}finally{B.resolve()}},close:()=>{$?.close(),$=void 0}})}function GJ(J){return Q2(J.unrestrictedPaths),m0({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path:$,view_range:Z})=>{if(!$)throw new P("read: file_path is required");let X=await Y2(J,$);if(Z?.length&&Z.length!==2)throw new P("read: view_range must be [start_line, end_line]");let G;try{let W=await J0.stat(X);if(!W.isFile())throw new P(`read: ${$} is not a regular file`);let C=MZ(J.maxFileBytes);if(C!==null&&W.size>C){if(!Z?.length)throw new P(`read: ${$} is ${W.size} bytes, exceeds ${C}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[V,F]=Z;return await jX(X,$,V,F,C)}G=await J0.readFile(X,"utf8")}catch(W){if(W instanceof P)throw W;throw new P(`read: ${R2(W,$)}`)}if(!Z?.length)return G;let[Q,Y]=Z,z=G.split(`
20
20
  `),B=Math.max(0,Q-1),K=Y>0?Y:z.length;return z.slice(B,K).join(`
21
- `)}})}async function j5(J,$,Z,X,G){let Q=new OZ($,Z,X,G);if(Q.rangeIsEmpty())return"";let Y=O8.createReadStream(J,{highWaterMark:O5});try{for await(let z of Y)if(Q.collectFrom(z),Q.rangeIsCollected())break}finally{Y.destroy()}return Q.text()}class OZ{#J;#$;#X;#G;#Z;#Q;#B=0;#Y=[];#z=0;constructor(J,$,Z,X){this.#J=J,this.#$=$,this.#X=Z,this.#G=Math.max(0,$-1),this.#Z=Z>0?Z:1/0,this.#Q=X}rangeIsEmpty(){return this.#Z<=this.#G}rangeIsCollected(){return this.#B>=this.#Z}collectFrom(J){let $=0;while($<J.length&&!this.rangeIsCollected()){let Z=J.indexOf(10,$),X=Z<0?J.length:Z;if(this.#B>=this.#G)this.#K(J.subarray($,X),Z>=0);if(Z<0)break;this.#B++,$=Z+1}}#K(J,$){if(this.#Y.push(J),this.#z+=J.length,$&&this.#B+1<this.#Z)this.#Y.push(CZ),this.#z+=CZ.length;if(this.#z>this.#Q)throw this.#C()}#C(){if(this.#Z-this.#G===1)return new P(`read: line ${this.#G+1} of ${this.#J} alone exceeds ${this.#Q}-byte limit. The read tool cannot return part of a line, so view_range cannot narrow this further.`);return new P(`read: view_range [${this.#$}, ${this.#X}] of ${this.#J} exceeds ${this.#Q}-byte limit. Narrow the view_range to read a smaller portion.`)}text(){return Buffer.concat(this.#Y,this.#z).toString("utf8")}}function Q4(J){return Q2(J.unrestrictedPaths),m0({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path:$,content:Z})=>{if(!$)throw new P("write: file_path is required");let X=await Y2(J,$),G=await wZ(J,X);if(G!==void 0)throw new P(`write: ${$} is inside read-only directory ${G}`);try{await J0.mkdir(Y0.dirname(X),{recursive:!0,mode:q8}),await a6(X,Z??"")}catch(Q){throw new P(`write: ${R2(Q,$)}`)}return`wrote ${Buffer.byteLength(Z??"")} bytes to ${$}`}})}function Y4(J){return Q2(J.unrestrictedPaths),m0({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path:$,old_string:Z,new_string:X,replace_all:G})=>{if(!$)throw new P("edit: file_path is required");if(!Z)throw new P("edit: old_string is required");let Q=await Y2(J,$),Y=await wZ(J,Q);if(Y!==void 0)throw new P(`edit: ${$} is inside read-only directory ${Y}`);let z;try{let W=await J0.stat(Q);if(!W.isFile())throw new P(`edit: ${$} is not a regular file`);let C=MZ(J.maxFileBytes);if(C!==null&&W.size>C)throw new P(`edit: ${$} is ${W.size} bytes, exceeds ${C}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);z=await J0.readFile(Q,"utf8")}catch(W){if(W instanceof P)throw W;throw new P(`edit: ${R2(W,$)}`)}let B=z.split(Z).length-1;if(B===0)throw new P(`edit: old_string not found in ${$}`);let K;if(G)K=z.split(Z).join(X);else{if(B>1)throw new P(`edit: old_string appears ${B} times in ${$} (must be unique)`);K=z.replace(Z,()=>X)}try{await a6(Q,K)}catch(W){throw new P(`edit: write: ${R2(W,$)}`)}return`edited ${$} (${G?B:1} replacement(s))`}})}function P5(J){return J.split(/[\\/{},]/).includes("..")}function z4(J){return Q2(J.unrestrictedPaths),m0({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern:$,path:Z})=>{if(!$)throw new P("glob: pattern is required");if(Y0.isAbsolute($))throw new P("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(P5($))throw new P('glob: ".." is not permitted in the pattern');let X=Z?await Y2(J,Z):Y0.resolve(J.workdir),G=Z?X:await F8(X),Q=[],Y=RZ;try{for await(let z of L5($,{cwd:X,withFileTypes:!0,exclude:(B)=>B.name===".git"||B.name==="node_modules"})){if(Y--<=0)break;if(!z.isFile())continue;let B=Y0.join(z.parentPath,z.name),K;try{K=await J0.realpath(B)}catch{continue}if(!f1(G,K))continue;let W=0;try{W=(await J0.stat(B)).mtimeMs}catch{}Q.push({path:B,mtime:W})}}catch(z){throw new P(`glob: ${z instanceof Error?z.message:String(z)}`)}if(Q.length===0)return"no matches";return Q.sort((z,B)=>B.mtime-z.mtime),Q.slice(0,A5).map((z)=>z.path).join(`
22
- `)}})}function B4(J){return Q2(J.unrestrictedPaths),m0({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern:$,path:Z},X)=>{if(!$)throw new P("grep: pattern is required");let G=Y0.resolve(J.workdir);if(Z)G=await Y2(J,Z);let Q=await y5();return Q?S5(Q,$,G,X?.signal):_5($,G,X?.signal)}})}function S5(J,$,Z,X){return new Promise((G,Q)=>{let Y=Z4.spawn(J,["-n","--no-heading","-e",$,"--",Z],{...X?{signal:X}:{}}),z="",B="",K=!1;Y.stdout.on("data",(W)=>{if(K)return;if(z+=W,z.length>w8)K=!0,z=z.slice(0,w8),Y.kill("SIGKILL")}),Y.stderr.on("data",(W)=>B+=W),Y.on("close",(W)=>{if(X?.aborted)return Q(new P("grep: aborted"));if(K)return G(z+`
23
- [output truncated at ${w8} bytes]`);if(W===0)return G(z);if(W===1)return G("no matches");Q(new P(`grep: rg failed: ${B||`exit ${W}`}`))}),Y.on("error",(W)=>{if(X?.aborted)return Q(new P("grep: aborted"));Q(new P(`grep: rg failed: ${W.message}`))})})}async function _5(J,$,Z){let X;try{X=new RegExp(J)}catch(B){throw new P(`grep: invalid regex: ${B instanceof Error?B.message:String(B)}`)}let G=[],Q=w8,Y=(B)=>{if(Q-=B.length+1,Q<0)return G.push(`[output truncated at ${w8} bytes]`),!1;return G.push(B),!0};if((await J0.stat($).catch(()=>null))?.isFile())await UZ($,X,Y);else await I5($,"",(B)=>UZ(Y0.join($,B),X,Y),Z);if(Z?.aborted)throw new P("grep: aborted");if(G.length===0)return"no matches";return G.join(`
24
- `)}async function UZ(J,$,Z){let X=O8.createReadStream(J,{encoding:"utf8"}),G=FZ.createInterface({input:X,crlfDelay:1/0}),Q=0;try{for await(let Y of G){if(Q++,Y.length>R5)continue;if($.test(Y)&&!Z(`${J}:${Q}:${Y}`))return!1}}catch{}finally{X.destroy()}return!0}async function I5(J,$,Z,X){let G=RZ;async function Q(Y,z){if(z>E5)return!0;if(X?.aborted)return!1;let B;try{B=await J0.readdir(Y0.join(J,Y),{withFileTypes:!0})}catch{return!0}for(let K of B){if(K.name===".git"||K.name==="node_modules")continue;if(G--<=0)return!1;if(X?.aborted)return!1;let W=Y?Y0.join(Y,K.name):K.name;if(K.isDirectory()){if(!await Q(W,z+1))return!1}else if(K.isFile()){if(await Z(W)===!1)return!1}}return!0}await Q($,0)}async function y5(){let J=(process.env.PATH??"").split(Y0.delimiter);for(let $ of J){let Z=Y0.join($,"rg");try{return await J0.access(Z,O8.constants.X_OK),Z}catch{}}return null}var VZ=102400,qZ=120000,w5=262144,O5=65536,CZ,w8=102400,R5=2000,A5=200,g1,H5,L5,E5=40,RZ=50000;var K4=M(()=>{c();I0();i6();o6();t$();WZ();CZ=Buffer.from(`
25
- `);g1=class g1 extends T{timeoutMs;constructor(J){super(`bash command timed out after ${J}ms`);this.name="BashTimeoutError",this.timeoutMs=J}};H5=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,L5=J0.glob});function f5(J){return J.resources.some(($)=>$.type==="memory_store")}function v5(J){if(!J)return null;let $;try{let X=J.replace(/-/g,"+").replace(/_/g,"/"),G=X.padEnd(Math.ceil(X.length/4)*4,"=");$=JSON.parse(t0(r2(G)))}catch{return null}if($===null||typeof $!=="object"||Array.isArray($))return null;let Z=$.sessions_token;return typeof Z==="string"&&Z!==""?Z:null}class R8{client;environmentId;environmentKey;tools;workdir;unrestrictedPaths;maxFileBytes;maxIdleMs;memorySyncIntervalMs;memorySyncDeletions;workerId;requestOptions;#J;constructor(J){if(J.unrestrictedPaths!==void 0)throw new T("The `unrestrictedPaths` option you passed to EnvironmentWorker (or client.beta.environments.work.worker()) is no longer supported. The worker's file tools (read, write, edit, glob, grep) are now always confined to `workdir` plus the session's memory folders. Remove `unrestrictedPaths` from your options; to let the file tools reach any other directory, add it to `AgentToolContext.allowedRoots` from a `tools` factory.");if(this.client=J.client,this.environmentId=J.environmentId,this.environmentKey=J.environmentKey,this.tools=J.tools,this.workdir=J.workdir??process.cwd(),this.maxFileBytes=J.maxFileBytes,this.maxIdleMs=J.maxIdleMs,J.memorySyncIntervalMs!=null)I1(J.memorySyncIntervalMs,"memorySyncIntervalMs");this.memorySyncIntervalMs=J.memorySyncIntervalMs,this.memorySyncDeletions=J.memorySyncDeletions??"enabled",this.workerId=J.workerId,this.requestOptions=J.requestOptions,this.#J=J.signal}async run(J){let{environmentId:$,environmentKey:Z}=this;if($===void 0||Z===void 0)throw new T("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");let X=J??this.#J,G=new $2({client:this.client,environmentId:$,environmentKey:Z,...this.workerId!==void 0?{workerId:this.workerId}:{},...X?{signal:X}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(let Q of G)try{await this.#$(Q,Z,G.signal)}catch(Y){if(G.signal?.aborted)throw Y;k(this.client).error("work item failed",{work_id:Q.id,error:String(Y)})}}async handleItem(J){let $=J?.workId??x("PUKU_WORK_ID"),Z=J?.environmentId??x("PUKU_ENVIRONMENT_ID"),X=J?.sessionId??x("PUKU_SESSION_ID"),G=J?.environmentKey??this.environmentKey??x("PUKU_ENVIRONMENT_KEY"),Q=J?.workSecret||x("PUKU_WORK_SECRET")||null;if(!$)throw new T("handleItem: workId is required — pass it or set PUKU_WORK_ID");if(!Z)throw new T("handleItem: environmentId is required — pass it or set PUKU_ENVIRONMENT_ID");if(!X)throw new T("handleItem: sessionId is required — pass it or set PUKU_SESSION_ID");if(!G)throw new T("handleItem: environmentKey is required — pass it, construct the worker with it, or set PUKU_ENVIRONMENT_KEY");let Y={id:$,environment_id:Z,secret:Q,data:{type:"session",id:X}};await this.#$(Y,G,J?.signal??this.#J)}async#$(J,$,Z){let X=k(this.client),G=v5(J.secret);if(J.secret&&G===null)X.warn("work item carried a secret payload but no sessions token could be extracted; falling back to the environment key",{work_id:J.id});let Q=G??$,Y=S1(this.client,{authToken:Q,helper:"environments-worker"}),z=J.data.id,B=new AbortController,K=g0(Z,B),W=new DZ(B),C=await Promise.resolve().then(() => (K4(),AZ)),V,F,q=h5(Y,J,W,X,this.requestOptions,(O)=>{V=O,F?._setSendRetryWindow(O)}).catch((O)=>{if(!B.signal.aborted)X.error("heartbeat loop failed",{work_id:J.id,error:String(O)});B.abort()}),A=async()=>{},R,H=!1;try{if(J.data.type!=="session"){X.debug("skipping non-session work item",{work_id:J.id,type:J.data.type});return}let O=await Y.beta.sessions.retrieve(z);if(G===null&&this.memorySyncIntervalMs!==null&&f5(O))throw new C.SessionMemoryError(`cannot mount the session's memories: the work item carried no sessions token (work_id=${J.id}, session_id=${z}); the memory endpoints reject the environment key, so the poller must issue a per-item \`secret\` carrying \`sessions_token\`, or set \`memorySyncIntervalMs: null\` to run without memory`);let D={workdir:this.workdir,client:Y,session:O,...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}};try{A=await C.setupSkills(D)}catch(y){X.warn("skill setup failed",{session_id:z,work_id:J.id,error:String(y)})}if(G!==null&&this.memorySyncIntervalMs!==null)R=new C.SessionMemoryStores(Y,{workdir:this.workdir,...this.memorySyncIntervalMs!==void 0?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await R.download(O),D.allowedRoots=R.roots,D.readOnlyRoots=R.readOnlyRoots;else X.debug("memory stores disabled for this item",{work_id:J.id});let S=typeof this.tools==="function"?this.tools(D):this.tools??C.betaAgentToolset20260401(D);if(F=new Z2(z,{client:Y,tools:S,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:B.signal}),V!==void 0)F._setSendRetryWindow(V);for await(let y of F)if(R)await R.syncIfDue();H=!B.signal.aborted}finally{try{await A().catch((O)=>{X.warn("skill cleanup failed",{session_id:z,work_id:J.id,error:String(O)})})}finally{if(R){let O=C.MEMORY_FLUSH_TIMEOUT_MS;if(H){if(await LZ(R.finish(),O))X.warn(`final memory sync cut off after ${O}ms; the flush that follows still uploads changed files`,{session_id:z,work_id:J.id})}let D=new AbortController;if(await LZ(R.flushWrites(D.signal),O))D.abort(),X.warn(`memory flush cut off after ${O}ms; changed files it had not uploaded yet are not saved`,{session_id:z,work_id:J.id});await R.dispose().catch((y)=>{X.warn("memory store cleanup failed",{session_id:z,work_id:J.id,error:String(y)})})}}if(W.finish("runner_done"),K(),await q,W.lost)X.info("lease lost; released without stopping it",{session_id:z,work_id:J.id});else await b5(Y,J,X,this.requestOptions)}}}async function LZ(J,$){let Z;try{return await Promise.race([J.then(()=>!1,()=>!1),new Promise((X)=>{Z=setTimeout(()=>X(!0),$)})])}finally{if(Z!==void 0)clearTimeout(Z)}}async function b5(J,$,Z,X){try{await J.beta.environments.work.stop($.id,{environment_id:$.environment_id,force:!0},{...X,headers:U([X?.headers])})}catch(G){if(!e(G,409))Z.error("force-stop on exit failed",{work_id:$.id,error:String(G)})}}class DZ{#J;#$;constructor(J){this.#J=J}get signal(){return this.#J.signal}finish(J){this.#$??=J,this.#J.abort()}get lost(){return this.#$==="lease_lost"||this.#$==="assumed_lost"}}function g5(J){let $=J instanceof l?J.error:void 0;for(let Z of["error","details","current_state"]){if(!t1($))return{};$=$[Z]}return t1($)?$:{}}async function h5(J,$,Z,X,G,Q){let Y=HZ,z=x5,B=Date.now(),K=k5,W=async()=>{let C=new AbortController,V=g0(Z.signal,C),F=setTimeout(()=>C.abort(),Y);try{let q=await J.beta.environments.work.heartbeat($.id,{environment_id:$.environment_id,expected_last_heartbeat:K},{...G,headers:U([G?.headers]),signal:C.signal});if(B=Date.now(),K=q.last_heartbeat,q.ttl_seconds>0)z=q.ttl_seconds*1000,Y=Math.max(1000,Math.min(z/2,HZ)),Q?.(z);if(q.state==="stopping"||q.state==="stopped")X.info("heartbeat signals shutdown",{work_id:$.id,state:q.state}),Z.finish("control_plane_stop");if(!q.lease_extended)X.warn("lease not extended, shutting down",{work_id:$.id}),Z.finish("control_plane_stop")}catch(q){if(Z.signal.throwIfAborted(),e(q,412)){let A=g5(q);X.error("lease lost: heartbeat precondition failed",{work_id:$.id,server_state:A.state,server_ttl_seconds:A.ttl_seconds,server_last_heartbeat:A.last_heartbeat}),Z.finish("lease_lost");return}if(h0(q))throw X.error("permanent heartbeat failure",{work_id:$.id,error:String(q)}),Z.finish("heartbeat_rejected"),q;if(Date.now()-B>z){X.error("lease assumed lost: no successful heartbeat in ttl",{work_id:$.id,ttl_ms:z,error:String(q)}),Z.finish("assumed_lost");return}X.warn("transient heartbeat failure",{work_id:$.id,error:String(q)})}finally{clearTimeout(F),V()}};await W();while(!Z.signal.aborted)await T0(Y,Z.signal),Z.signal.throwIfAborted(),await W()}var HZ=30000,x5=90000,k5="NO_HEARTBEAT";var W4=M(()=>{c();O0();K1();T2();Q0();E();E1();_1();d6();y1()});var z2;var V4=M(()=>{_();E();I();_1();W4();_1();W4();z2=class z2 extends w{retrieve(J,$,Z){let{environment_id:X,betas:G}=$;return this._client.get(N`/v1/environments/${X}/work/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{environment_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/environments/${X}/work/${J}?beta=true`,{body:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/environments/${J}/work?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}ack(J,$,Z){let{environment_id:X,betas:G}=$;return this._client.post(N`/v1/environments/${X}/work/${J}/ack?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}heartbeat(J,$,Z){let{environment_id:X,desired_ttl_seconds:G,expected_last_heartbeat:Q,betas:Y}=$;return this._client.post(N`/v1/environments/${X}/work/${J}/heartbeat?beta=true`,{query:{desired_ttl_seconds:G,expected_last_heartbeat:Q},...Z,headers:U([{"puku-beta":[...Y??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}poll(J,$={},Z){let{betas:X,"PukuAI-Worker-ID":G,...Q}=$??{};return this._client.get(N`/v1/environments/${J}/work/poll?beta=true`,{query:Q,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString(),...G!=null?{"PukuAI-Worker-ID":G}:void 0},Z?.headers])})}stats(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/environments/${J}/work/stats?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}stop(J,$,Z){let{environment_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/environments/${X}/work/${J}/stop?beta=true`,{body:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}poller(J){return new $2({...J,client:this._client})}worker(J){return new R8({...J,client:this._client})}};z2.WorkPoller=$2;z2.EnvironmentWorker=R8});var L2;var C4=M(()=>{V4();V4();_();E();I();L2=class L2 extends w{work=new z2(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/environments?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/environments/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/environments/${J}?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/environments?beta=true",L,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/environments/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/environments/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}};L2.Work=z2});var A8;var U4=M(()=>{_();E();I();A8=class A8 extends w{create(J,$,Z){let{view:X,betas:G,...Q}=$;return this._client.post(N`/v1/memory_stores/${J}/memories?beta=true`,{query:{view:X},body:Q,...Z,headers:U([{"puku-beta":[...G??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}retrieve(J,$,Z){let{memory_store_id:X,betas:G,...Q}=$;return this._client.get(N`/v1/memory_stores/${X}/memories/${J}?beta=true`,{query:Q,...Z,headers:U([{"puku-beta":[...G??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}update(J,$,Z){let{memory_store_id:X,view:G,betas:Q,...Y}=$;return this._client.post(N`/v1/memory_stores/${X}/memories/${J}?beta=true`,{query:{view:G},body:Y,...Z,headers:U([{"puku-beta":[...Q??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/memory_stores/${J}/memories?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}delete(J,$,Z){let{memory_store_id:X,expected_content_sha256:G,betas:Q}=$;return this._client.delete(N`/v1/memory_stores/${X}/memories/${J}?beta=true`,{query:{expected_content_sha256:G},...Z,headers:U([{"puku-beta":[...Q??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}}});var H8;var N4=M(()=>{_();E();I();H8=class H8 extends w{retrieve(J,$,Z){let{memory_store_id:X,betas:G,...Q}=$;return this._client.get(N`/v1/memory_stores/${X}/memory_versions/${J}?beta=true`,{query:Q,...Z,headers:U([{"puku-beta":[...G??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/memory_stores/${J}/memory_versions?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}redact(J,$,Z){let{memory_store_id:X,betas:G}=$;return this._client.post(N`/v1/memory_stores/${X}/memory_versions/${J}/redact?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}}});var B2;var F4=M(()=>{U4();U4();N4();N4();_();E();I();B2=class B2 extends w{memories=new A8(this._client);memoryVersions=new H8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/memory_stores?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"agent-memory-2026-07-22"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/memory_stores/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/memory_stores/${J}?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/memory_stores?beta=true",L,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"agent-memory-2026-07-22"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/memory_stores/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/memory_stores/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}};B2.Memories=A8;B2.MemoryVersions=H8});var D2=M(()=>{c()});var j2;var q4=M(()=>{c();O6();j2=class j2{iterator;controller;constructor(J,$){this.iterator=J;this.controller=$}async*decoder(){let J=new F2;for await(let $ of this.iterator)for(let Z of J.decode($))yield JSON.parse(Z);for(let $ of J.flush())yield JSON.parse($)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(J,$){if(!J.body){if($.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new T("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new T("Attempted to iterate over a response with no body")}return new j2(o2(J.body),$)}}});var L8;var M4=M(()=>{_();E();q4();D2();I();L8=class L8 extends w{create(J,$){let{betas:Z,user_profile_id:X,...G}=J;return this._client.post("/v1/messages/batches?beta=true",{body:G,...$,headers:U([{"puku-beta":[...Z??[],"message-batches-2024-09-24"].toString(),...X!=null?{"puku-user-profile-id":X}:void 0},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/messages/batches/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/messages/batches?beta=true",o,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"message-batches-2024-09-24"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/messages/batches/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}cancel(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/messages/batches/${J}/cancel?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}async results(J,$={},Z){let X=await this.retrieve(J);if(!X.results_url)throw new T(`No batch \`results_url\`; Has it finished processing? ${X.processing_status} - ${X.id}`);let{betas:G}=$??{};return this._client.get(X.results_url,{...Z,headers:U([{"puku-beta":[...G??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,Y)=>j2.fromResponse(Y.response,Y.controller))}}});var D8;var m1=M(()=>{D8={"puku-opus-4@20250514":8192,"puku.puku-opus-4-1-20250805-v1:0":8192,"puku-opus-4-1@20250805":8192}});function jZ(J){return J?.output_format??J?.output_config?.format}function T4(J,$,Z){let X=jZ($);if(!$||!("parse"in(X??{})))return{...J,content:J.content.map((G)=>{if(G.type==="text"){let Q=Object.defineProperty({...G},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(Q,"parsed",{get(){return Z.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return G}),parsed_output:null};return w4(J,$,Z)}function w4(J,$,Z){let X=null,G=J.content.map((Q)=>{if(Q.type==="text"){let Y=i5($,Q.text);if(X===null)X=Y;let z=Object.defineProperty({...Q},"parsed_output",{value:Y,enumerable:!1});return Object.defineProperty(z,"parsed",{get(){return Z.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),Y},enumerable:!1})}return Q});return{...J,content:G,parsed_output:X}}function i5(J,$){let Z=jZ(J);if(Z?.type!=="json_schema")return null;try{if("parse"in Z)return Z.parse($);return JSON.parse($)}catch(X){throw new T(`Failed to parse structured output: ${X}`)}}var O4=M(()=>{c()});var R4=M(()=>{q2()});var n5=(J)=>{let $=0,Z=[];while($<J.length){let X=J[$];if(X==="\\"){$++;continue}if(X==="{"){Z.push({type:"brace",value:"{"}),$++;continue}if(X==="}"){Z.push({type:"brace",value:"}"}),$++;continue}if(X==="["){Z.push({type:"paren",value:"["}),$++;continue}if(X==="]"){Z.push({type:"paren",value:"]"}),$++;continue}if(X===":"){Z.push({type:"separator",value:":"}),$++;continue}if(X===","){Z.push({type:"delimiter",value:","}),$++;continue}if(X==='"'){let z="",B=!1;X=J[++$];while(X!=='"'){if($===J.length){B=!0;break}if(X==="\\"){if($++,$===J.length){B=!0;break}z+=X+J[$],X=J[++$]}else z+=X,X=J[++$]}if(X=J[++$],!B)Z.push({type:"string",value:z});continue}if(X&&/\s/.test(X)){$++;continue}let Q=/[0-9]/;if(X&&Q.test(X)||X==="-"||X==="."){let z="";if(X==="-")z+=X,X=J[++$];while(X&&Q.test(X)||X===".")z+=X,X=J[++$];Z.push({type:"number",value:z});continue}let Y=/[a-z]/i;if(X&&Y.test(X)){let z="";while(X&&Y.test(X)){if($===J.length)break;z+=X,X=J[++$]}if(z=="true"||z=="false"||z==="null")Z.push({type:"name",value:z});else{$++;continue}continue}$++}return Z},P2=(J)=>{if(J.length===0)return J;let $=J[J.length-1];switch($.type){case"separator":return J=J.slice(0,J.length-1),P2(J);break;case"number":let Z=$.value[$.value.length-1];if(Z==="."||Z==="-")return J=J.slice(0,J.length-1),P2(J);case"string":let X=J[J.length-2];if(X?.type==="delimiter")return J=J.slice(0,J.length-1),P2(J);else if(X?.type==="brace"&&X.value==="{")return J=J.slice(0,J.length-1),P2(J);break;case"delimiter":return J=J.slice(0,J.length-1),P2(J);break}return J},a5=(J)=>{let $=[];if(J.map((Z)=>{if(Z.type==="brace")if(Z.value==="{")$.push("}");else $.splice($.lastIndexOf("}"),1);if(Z.type==="paren")if(Z.value==="[")$.push("]");else $.splice($.lastIndexOf("]"),1)}),$.length>0)$.reverse().map((Z)=>{if(Z==="}")J.push({type:"brace",value:"}"});else if(Z==="]")J.push({type:"paren",value:"]"})});return J},o5=(J)=>{let $="";return J.map((Z)=>{switch(Z.type){case"string":$+='"'+Z.value+'"';break;default:$+=Z.value;break}}),$},PZ=(J)=>JSON.parse(o5(a5(P2(n5(J)))));var SZ=()=>{};function u1(J,$){let Z={};for(let Q of Object.keys(J))if(Q!=="input")Z[Q]=J[Q];Object.defineProperty(Z,d0,{value:$,enumerable:!1,writable:!0});let X,G=!1;return Object.defineProperty(Z,"input",{enumerable:!0,configurable:!0,get(){if(!G)X=$?PZ($):{},G=!0;return X}}),Z}var d0="__json_buf";var A4=M(()=>{SZ()});function H4(J){return J.type==="tool_use"||J.type==="server_tool_use"||J.type==="mcp_tool_use"}var j8;var _Z=M(()=>{q0();D2();Q0();R4();O4();A4();j8=class j8{messages=[];receivedMessages=[];#J;#$=null;controller=new AbortController;#X;#G=()=>{};#Z=()=>{};#Q;#B=()=>{};#Y=()=>{};#z={};#K=!1;#C=!1;#U=!1;#V=!1;#F;#W;#M;#q;constructor(J,$){this.#X=new Promise((Z,X)=>{this.#G=Z,this.#Z=X}),this.#Q=new Promise((Z,X)=>{this.#B=Z,this.#Y=X}),this.#X.catch(()=>{}),this.#Q.catch(()=>{}),this.#$=J,this.#q=$?.logger??console}get response(){return this.#F}get request_id(){return this.#W}get workspace_id(){return this.#M}async withResponse(){this.#V=!0;let J=await this.#X;if(!J)throw Error("Could not resolve a `Response` object");return{data:this,response:J,request_id:J.headers.get("request-id"),workspace_id:J.headers.get("puku-workspace-id")}}static fromReadableStream(J){let $=new j8(null);return $._run(()=>$._fromReadableStream(J)),$}static createMessage(J,$,Z,{logger:X}={}){let G=new j8($,{logger:X});for(let Q of $.messages)G._addMessageParam(Q);return G.#$={...$,stream:!0},G._run(()=>G._createMessage(J,{...$,stream:!0},{...Z,headers:{...Z?.headers,[A1]:"stream"}})),G}_run(J){J().then(()=>{this._emitFinal(),this._emit("end")},this.#T)}_addMessageParam(J){this.messages.push(J)}_addMessage(J,$=!0){if(this.receivedMessages.push(J),$)this._emit("message",J)}async _createMessage(J,$,Z){let X=Z?.signal,G;if(X){if(X.aborted)this.controller.abort();G=this.controller.abort.bind(this.controller),X.addEventListener("abort",G)}try{this.#N();let{response:Q,data:Y}=await J.create({...$,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(Q);for await(let z of Y)this.#R(z);if(Y.controller.signal?.aborted)throw new Z0;this.#w()}finally{if(X&&G)X.removeEventListener("abort",G)}}_connected(J){if(this.ended)return;this.#F=J,this.#W=J?.headers.get("request-id"),this.#M=J?.headers.get("puku-workspace-id"),this.#G(J),this._emit("connect")}get ended(){return this.#K}get errored(){return this.#C}get aborted(){return this.#U}abort(){this.controller.abort()}on(J,$){return(this.#z[J]||(this.#z[J]=[])).push({listener:$}),this}off(J,$){let Z=this.#z[J];if(!Z)return this;let X=Z.findIndex((G)=>G.listener===$);if(X>=0)Z.splice(X,1);return this}once(J,$){return(this.#z[J]||(this.#z[J]=[])).push({listener:$,once:!0}),this}emitted(J){return new Promise(($,Z)=>{if(this.#V=!0,J!=="error")this.once("error",Z);this.once(J,$)})}async done(){this.#V=!0,await this.#Q}get currentMessage(){return this.#J}#O(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)}async finalMessage(){return await this.done(),this.#O()}#A(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");let J=this.receivedMessages.at(-1).content.filter(($)=>$.type==="text").map(($)=>$.text);if(J.length===0)throw new T("stream ended without producing a content block with type=text");return J.join(" ")}async finalText(){return await this.done(),this.#A()}#T=(J)=>{if(this.#C=!0,U0(J))J=new Z0;if(J instanceof Z0)return this.#U=!0,this._emit("abort",J);if(J instanceof T)return this._emit("error",J);if(J instanceof Error){let $=new T(J.message);return $.cause=J,this._emit("error",$)}return this._emit("error",new T(String(J)))};_emit(J,...$){if(this.#K)return;if(J==="end")this.#K=!0,this.#B();let Z=this.#z[J];if(Z)this.#z[J]=Z.filter((X)=>!X.once),Z.forEach(({listener:X})=>X(...$));if(J==="abort"){let X=$[0];if(!this.#V&&!Z?.length)Promise.reject(X);this.#Z(X),this.#Y(X),this._emit("end");return}if(J==="error"){let X=$[0];if(!this.#V&&!Z?.length)Promise.reject(X);this.#Z(X),this.#Y(X),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",this.#O())}#N(){if(this.ended)return;this.#J=void 0}#R(J){if(this.ended)return;let $=this.#H(J);switch(this._emit("streamEvent",J,$),J.type){case"content_block_delta":{let Z=$.content.at(-1);switch(J.delta.type){case"text_delta":{if(Z.type==="text")this._emit("text",J.delta.text,Z.text||"");break}case"citations_delta":{if(Z.type==="text")this._emit("citation",J.delta.citation,Z.citations??[]);break}case"input_json_delta":{if(H4(Z)&&this.#z.inputJson?.length){let X;try{X=Z.input}catch(G){this.#T(this.#L(Z,G));break}this._emit("inputJson",J.delta.partial_json,X)}break}case"thinking_delta":{if(Z.type==="thinking")this._emit("thinking",J.delta.thinking,Z.thinking);break}case"signature_delta":{if(Z.type==="thinking")this._emit("signature",Z.signature);break}case"compaction_delta":{if(Z.type==="compaction"&&Z.content)this._emit("compaction",Z.content);break}default:x0(J.delta)}break}case"message_stop":{this._addMessageParam($),this._addMessage(T4($,this.#$,{logger:this.#q}),!0);break}case"content_block_stop":{this._emit("contentBlock",$.content.at(-1));break}case"message_start":{this.#J=$;break}case"content_block_start":case"message_delta":break}}#w(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let J=this.#J;if(!J)throw new T("request ended without sending any chunks");return this.#J=void 0,T4(J,this.#$,{logger:this.#q})}async _fromReadableStream(J,$){let Z=$?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{this.#N(),this._connected(null);let G=s.fromReadableStream(J,this.controller);for await(let Q of G)this.#R(Q);if(G.controller.signal?.aborted)throw new Z0;this.#w()}finally{if(Z&&X)Z.removeEventListener("abort",X)}}#H(J){let $=this.#J;if(J.type==="message_start"){if($)throw new T(`Unexpected event order, got ${J.type} before receiving "message_stop"`);return J.message}if(!$)throw new T(`Unexpected event order, got ${J.type} before "message_start"`);switch(J.type){case"message_stop":return $;case"message_delta":if($.stop_reason=J.delta.stop_reason,$.stop_sequence=J.delta.stop_sequence,$.stop_details=J.delta.stop_details,$.usage.output_tokens=J.usage.output_tokens,J.delta.container!=null)$.container=J.delta.container;if(J.context_management!=null)$.context_management=J.context_management;if(J.input_transformations!=null)$.input_transformations=J.input_transformations;if(J.usage.input_tokens!=null)$.usage.input_tokens=J.usage.input_tokens;if(J.usage.cache_creation_input_tokens!=null)$.usage.cache_creation_input_tokens=J.usage.cache_creation_input_tokens;if(J.usage.cache_read_input_tokens!=null)$.usage.cache_read_input_tokens=J.usage.cache_read_input_tokens;if(J.usage.server_tool_use!=null)$.usage.server_tool_use=J.usage.server_tool_use;if(J.usage.iterations!=null)$.usage.iterations=J.usage.iterations;if(J.usage.fallback_credit!=null)$.usage.fallback_credit=J.usage.fallback_credit;if(J.usage.output_tokens_details!=null)$.usage.output_tokens_details=J.usage.output_tokens_details;return $;case"content_block_start":if($.content.push(J.content_block),J.content_block.type==="fallback")$.model=J.content_block.to.model;return $;case"content_block_delta":{let Z=$.content.at(J.index);switch(J.delta.type){case"text_delta":{if(Z?.type==="text")$.content[J.index]={...Z,text:(Z.text||"")+J.delta.text};break}case"citations_delta":{if(Z?.type==="text")$.content[J.index]={...Z,citations:[...Z.citations??[],J.delta.citation]};break}case"input_json_delta":{if(Z&&H4(Z)){let X=(Z[d0]||"")+J.delta.partial_json;$.content[J.index]=u1(Z,X)}break}case"thinking_delta":{if(Z?.type==="thinking")$.content[J.index]={...Z,thinking:Z.thinking+J.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")$.content[J.index]={...Z,signature:J.delta.signature};break}case"compaction_delta":{if(Z?.type==="compaction")$.content[J.index]={...Z,content:(Z.content||"")+J.delta.content,encrypted_content:J.delta.encrypted_content};break}default:x0(J.delta)}return $}case"content_block_stop":{let Z=$.content.at(J.index);if(Z&&H4(Z)&&d0 in Z){let X;try{X=Z.input}catch(G){X={},this.#T(this.#L(Z,G))}Object.defineProperty(Z,"input",{value:X,enumerable:!0,configurable:!0,writable:!0})}return $}}}#L(J,$){let Z=J[d0];return new T(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${$}. JSON: ${Z}`)}[Symbol.asyncIterator](){let J=[],$=[],Z=!1;return this.on("streamEvent",(X)=>{let G=$.shift();if(G)G.resolve(X);else J.push(X)}),this.on("end",()=>{Z=!0;for(let X of $)X.resolve(void 0);$.length=0}),this.on("abort",(X)=>{Z=!0;for(let G of $)G.reject(X);$.length=0}),this.on("error",(X)=>{Z=!0;for(let G of $)G.reject(X);$.length=0}),{next:async()=>{if(!J.length){if(Z)return{value:void 0,done:!0};return new Promise((G,Q)=>$.push({resolve:G,reject:Q})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:J.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var EZ=1e5,IZ=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
21
+ `)}})}async function jX(J,$,Z,X,G){let Q=new OZ($,Z,X,G);if(Q.rangeIsEmpty())return"";let Y=O8.createReadStream(J,{highWaterMark:OX});try{for await(let z of Y)if(Q.collectFrom(z),Q.rangeIsCollected())break}finally{Y.destroy()}return Q.text()}class OZ{#J;#$;#X;#G;#Z;#Q;#B=0;#Y=[];#z=0;constructor(J,$,Z,X){this.#J=J,this.#$=$,this.#X=Z,this.#G=Math.max(0,$-1),this.#Z=Z>0?Z:1/0,this.#Q=X}rangeIsEmpty(){return this.#Z<=this.#G}rangeIsCollected(){return this.#B>=this.#Z}collectFrom(J){let $=0;while($<J.length&&!this.rangeIsCollected()){let Z=J.indexOf(10,$),X=Z<0?J.length:Z;if(this.#B>=this.#G)this.#K(J.subarray($,X),Z>=0);if(Z<0)break;this.#B++,$=Z+1}}#K(J,$){if(this.#Y.push(J),this.#z+=J.length,$&&this.#B+1<this.#Z)this.#Y.push(CZ),this.#z+=CZ.length;if(this.#z>this.#Q)throw this.#C()}#C(){if(this.#Z-this.#G===1)return new P(`read: line ${this.#G+1} of ${this.#J} alone exceeds ${this.#Q}-byte limit. The read tool cannot return part of a line, so view_range cannot narrow this further.`);return new P(`read: view_range [${this.#$}, ${this.#X}] of ${this.#J} exceeds ${this.#Q}-byte limit. Narrow the view_range to read a smaller portion.`)}text(){return Buffer.concat(this.#Y,this.#z).toString("utf8")}}function QJ(J){return Q2(J.unrestrictedPaths),m0({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path:$,content:Z})=>{if(!$)throw new P("write: file_path is required");let X=await Y2(J,$),G=await wZ(J,X);if(G!==void 0)throw new P(`write: ${$} is inside read-only directory ${G}`);try{await J0.mkdir(Y0.dirname(X),{recursive:!0,mode:q8}),await a6(X,Z??"")}catch(Q){throw new P(`write: ${R2(Q,$)}`)}return`wrote ${Buffer.byteLength(Z??"")} bytes to ${$}`}})}function YJ(J){return Q2(J.unrestrictedPaths),m0({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path:$,old_string:Z,new_string:X,replace_all:G})=>{if(!$)throw new P("edit: file_path is required");if(!Z)throw new P("edit: old_string is required");let Q=await Y2(J,$),Y=await wZ(J,Q);if(Y!==void 0)throw new P(`edit: ${$} is inside read-only directory ${Y}`);let z;try{let W=await J0.stat(Q);if(!W.isFile())throw new P(`edit: ${$} is not a regular file`);let C=MZ(J.maxFileBytes);if(C!==null&&W.size>C)throw new P(`edit: ${$} is ${W.size} bytes, exceeds ${C}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);z=await J0.readFile(Q,"utf8")}catch(W){if(W instanceof P)throw W;throw new P(`edit: ${R2(W,$)}`)}let B=z.split(Z).length-1;if(B===0)throw new P(`edit: old_string not found in ${$}`);let K;if(G)K=z.split(Z).join(X);else{if(B>1)throw new P(`edit: old_string appears ${B} times in ${$} (must be unique)`);K=z.replace(Z,()=>X)}try{await a6(Q,K)}catch(W){throw new P(`edit: write: ${R2(W,$)}`)}return`edited ${$} (${G?B:1} replacement(s))`}})}function PX(J){return J.split(/[\\/{},]/).includes("..")}function zJ(J){return Q2(J.unrestrictedPaths),m0({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern:$,path:Z})=>{if(!$)throw new P("glob: pattern is required");if(Y0.isAbsolute($))throw new P("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(PX($))throw new P('glob: ".." is not permitted in the pattern');let X=Z?await Y2(J,Z):Y0.resolve(J.workdir),G=Z?X:await F8(X),Q=[],Y=RZ;try{for await(let z of LX($,{cwd:X,withFileTypes:!0,exclude:(B)=>B.name===".git"||B.name==="node_modules"})){if(Y--<=0)break;if(!z.isFile())continue;let B=Y0.join(z.parentPath,z.name),K;try{K=await J0.realpath(B)}catch{continue}if(!f1(G,K))continue;let W=0;try{W=(await J0.stat(B)).mtimeMs}catch{}Q.push({path:B,mtime:W})}}catch(z){throw new P(`glob: ${z instanceof Error?z.message:String(z)}`)}if(Q.length===0)return"no matches";return Q.sort((z,B)=>B.mtime-z.mtime),Q.slice(0,AX).map((z)=>z.path).join(`
22
+ `)}})}function BJ(J){return Q2(J.unrestrictedPaths),m0({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern:$,path:Z},X)=>{if(!$)throw new P("grep: pattern is required");let G=Y0.resolve(J.workdir);if(Z)G=await Y2(J,Z);let Q=await yX();return Q?SX(Q,$,G,X?.signal):_X($,G,X?.signal)}})}function SX(J,$,Z,X){return new Promise((G,Q)=>{let Y=ZJ.spawn(J,["-n","--no-heading","-e",$,"--",Z],{...X?{signal:X}:{}}),z="",B="",K=!1;Y.stdout.on("data",(W)=>{if(K)return;if(z+=W,z.length>w8)K=!0,z=z.slice(0,w8),Y.kill("SIGKILL")}),Y.stderr.on("data",(W)=>B+=W),Y.on("close",(W)=>{if(X?.aborted)return Q(new P("grep: aborted"));if(K)return G(z+`
23
+ [output truncated at ${w8} bytes]`);if(W===0)return G(z);if(W===1)return G("no matches");Q(new P(`grep: rg failed: ${B||`exit ${W}`}`))}),Y.on("error",(W)=>{if(X?.aborted)return Q(new P("grep: aborted"));Q(new P(`grep: rg failed: ${W.message}`))})})}async function _X(J,$,Z){let X;try{X=new RegExp(J)}catch(B){throw new P(`grep: invalid regex: ${B instanceof Error?B.message:String(B)}`)}let G=[],Q=w8,Y=(B)=>{if(Q-=B.length+1,Q<0)return G.push(`[output truncated at ${w8} bytes]`),!1;return G.push(B),!0};if((await J0.stat($).catch(()=>null))?.isFile())await UZ($,X,Y);else await IX($,"",(B)=>UZ(Y0.join($,B),X,Y),Z);if(Z?.aborted)throw new P("grep: aborted");if(G.length===0)return"no matches";return G.join(`
24
+ `)}async function UZ(J,$,Z){let X=O8.createReadStream(J,{encoding:"utf8"}),G=FZ.createInterface({input:X,crlfDelay:1/0}),Q=0;try{for await(let Y of G){if(Q++,Y.length>RX)continue;if($.test(Y)&&!Z(`${J}:${Q}:${Y}`))return!1}}catch{}finally{X.destroy()}return!0}async function IX(J,$,Z,X){let G=RZ;async function Q(Y,z){if(z>EX)return!0;if(X?.aborted)return!1;let B;try{B=await J0.readdir(Y0.join(J,Y),{withFileTypes:!0})}catch{return!0}for(let K of B){if(K.name===".git"||K.name==="node_modules")continue;if(G--<=0)return!1;if(X?.aborted)return!1;let W=Y?Y0.join(Y,K.name):K.name;if(K.isDirectory()){if(!await Q(W,z+1))return!1}else if(K.isFile()){if(await Z(W)===!1)return!1}}return!0}await Q($,0)}async function yX(){let J=(process.env.PATH??"").split(Y0.delimiter);for(let $ of J){let Z=Y0.join($,"rg");try{return await J0.access(Z,O8.constants.X_OK),Z}catch{}}return null}var VZ=102400,qZ=120000,wX=262144,OX=65536,CZ,w8=102400,RX=2000,AX=200,g1,HX,LX,EX=40,RZ=50000;var KJ=M(()=>{c();I0();i6();o6();t$();WZ();CZ=Buffer.from(`
25
+ `);g1=class g1 extends T{timeoutMs;constructor(J){super(`bash command timed out after ${J}ms`);this.name="BashTimeoutError",this.timeoutMs=J}};HX=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,LX=J0.glob});function fX(J){return J.resources.some(($)=>$.type==="memory_store")}function vX(J){if(!J)return null;let $;try{let X=J.replace(/-/g,"+").replace(/_/g,"/"),G=X.padEnd(Math.ceil(X.length/4)*4,"=");$=JSON.parse(t0(r2(G)))}catch{return null}if($===null||typeof $!=="object"||Array.isArray($))return null;let Z=$.sessions_token;return typeof Z==="string"&&Z!==""?Z:null}class R8{client;environmentId;environmentKey;tools;workdir;unrestrictedPaths;maxFileBytes;maxIdleMs;memorySyncIntervalMs;memorySyncDeletions;workerId;requestOptions;#J;constructor(J){if(J.unrestrictedPaths!==void 0)throw new T("The `unrestrictedPaths` option you passed to EnvironmentWorker (or client.beta.environments.work.worker()) is no longer supported. The worker's file tools (read, write, edit, glob, grep) are now always confined to `workdir` plus the session's memory folders. Remove `unrestrictedPaths` from your options; to let the file tools reach any other directory, add it to `AgentToolContext.allowedRoots` from a `tools` factory.");if(this.client=J.client,this.environmentId=J.environmentId,this.environmentKey=J.environmentKey,this.tools=J.tools,this.workdir=J.workdir??process.cwd(),this.maxFileBytes=J.maxFileBytes,this.maxIdleMs=J.maxIdleMs,J.memorySyncIntervalMs!=null)I1(J.memorySyncIntervalMs,"memorySyncIntervalMs");this.memorySyncIntervalMs=J.memorySyncIntervalMs,this.memorySyncDeletions=J.memorySyncDeletions??"enabled",this.workerId=J.workerId,this.requestOptions=J.requestOptions,this.#J=J.signal}async run(J){let{environmentId:$,environmentKey:Z}=this;if($===void 0||Z===void 0)throw new T("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");let X=J??this.#J,G=new $2({client:this.client,environmentId:$,environmentKey:Z,...this.workerId!==void 0?{workerId:this.workerId}:{},...X?{signal:X}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(let Q of G)try{await this.#$(Q,Z,G.signal)}catch(Y){if(G.signal?.aborted)throw Y;k(this.client).error("work item failed",{work_id:Q.id,error:String(Y)})}}async handleItem(J){let $=J?.workId??x("PUKU_WORK_ID"),Z=J?.environmentId??x("PUKU_ENVIRONMENT_ID"),X=J?.sessionId??x("PUKU_SESSION_ID"),G=J?.environmentKey??this.environmentKey??x("PUKU_ENVIRONMENT_KEY"),Q=J?.workSecret||x("PUKU_WORK_SECRET")||null;if(!$)throw new T("handleItem: workId is required — pass it or set PUKU_WORK_ID");if(!Z)throw new T("handleItem: environmentId is required — pass it or set PUKU_ENVIRONMENT_ID");if(!X)throw new T("handleItem: sessionId is required — pass it or set PUKU_SESSION_ID");if(!G)throw new T("handleItem: environmentKey is required — pass it, construct the worker with it, or set PUKU_ENVIRONMENT_KEY");let Y={id:$,environment_id:Z,secret:Q,data:{type:"session",id:X}};await this.#$(Y,G,J?.signal??this.#J)}async#$(J,$,Z){let X=k(this.client),G=vX(J.secret);if(J.secret&&G===null)X.warn("work item carried a secret payload but no sessions token could be extracted; falling back to the environment key",{work_id:J.id});let Q=G??$,Y=S1(this.client,{authToken:Q,helper:"environments-worker"}),z=J.data.id,B=new AbortController,K=g0(Z,B),W=new DZ(B),C=await Promise.resolve().then(() => (KJ(),AZ)),V,F,q=hX(Y,J,W,X,this.requestOptions,(O)=>{V=O,F?._setSendRetryWindow(O)}).catch((O)=>{if(!B.signal.aborted)X.error("heartbeat loop failed",{work_id:J.id,error:String(O)});B.abort()}),A=async()=>{},R,H=!1;try{if(J.data.type!=="session"){X.debug("skipping non-session work item",{work_id:J.id,type:J.data.type});return}let O=await Y.beta.sessions.retrieve(z);if(G===null&&this.memorySyncIntervalMs!==null&&fX(O))throw new C.SessionMemoryError(`cannot mount the session's memories: the work item carried no sessions token (work_id=${J.id}, session_id=${z}); the memory endpoints reject the environment key, so the poller must issue a per-item \`secret\` carrying \`sessions_token\`, or set \`memorySyncIntervalMs: null\` to run without memory`);let D={workdir:this.workdir,client:Y,session:O,...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}};try{A=await C.setupSkills(D)}catch(y){X.warn("skill setup failed",{session_id:z,work_id:J.id,error:String(y)})}if(G!==null&&this.memorySyncIntervalMs!==null)R=new C.SessionMemoryStores(Y,{workdir:this.workdir,...this.memorySyncIntervalMs!==void 0?{syncIntervalMs:this.memorySyncIntervalMs}:{},syncDeletions:this.memorySyncDeletions}),await R.download(O),D.allowedRoots=R.roots,D.readOnlyRoots=R.readOnlyRoots;else X.debug("memory stores disabled for this item",{work_id:J.id});let S=typeof this.tools==="function"?this.tools(D):this.tools??C.betaAgentToolset20260401(D);if(F=new Z2(z,{client:Y,tools:S,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:B.signal}),V!==void 0)F._setSendRetryWindow(V);for await(let y of F)if(R)await R.syncIfDue();H=!B.signal.aborted}finally{try{await A().catch((O)=>{X.warn("skill cleanup failed",{session_id:z,work_id:J.id,error:String(O)})})}finally{if(R){let O=C.MEMORY_FLUSH_TIMEOUT_MS;if(H){if(await LZ(R.finish(),O))X.warn(`final memory sync cut off after ${O}ms; the flush that follows still uploads changed files`,{session_id:z,work_id:J.id})}let D=new AbortController;if(await LZ(R.flushWrites(D.signal),O))D.abort(),X.warn(`memory flush cut off after ${O}ms; changed files it had not uploaded yet are not saved`,{session_id:z,work_id:J.id});await R.dispose().catch((y)=>{X.warn("memory store cleanup failed",{session_id:z,work_id:J.id,error:String(y)})})}}if(W.finish("runner_done"),K(),await q,W.lost)X.info("lease lost; released without stopping it",{session_id:z,work_id:J.id});else await bX(Y,J,X,this.requestOptions)}}}async function LZ(J,$){let Z;try{return await Promise.race([J.then(()=>!1,()=>!1),new Promise((X)=>{Z=setTimeout(()=>X(!0),$)})])}finally{if(Z!==void 0)clearTimeout(Z)}}async function bX(J,$,Z,X){try{await J.beta.environments.work.stop($.id,{environment_id:$.environment_id,force:!0},{...X,headers:U([X?.headers])})}catch(G){if(!e(G,409))Z.error("force-stop on exit failed",{work_id:$.id,error:String(G)})}}class DZ{#J;#$;constructor(J){this.#J=J}get signal(){return this.#J.signal}finish(J){this.#$??=J,this.#J.abort()}get lost(){return this.#$==="lease_lost"||this.#$==="assumed_lost"}}function gX(J){let $=J instanceof l?J.error:void 0;for(let Z of["error","details","current_state"]){if(!t1($))return{};$=$[Z]}return t1($)?$:{}}async function hX(J,$,Z,X,G,Q){let Y=HZ,z=xX,B=Date.now(),K=kX,W=async()=>{let C=new AbortController,V=g0(Z.signal,C),F=setTimeout(()=>C.abort(),Y);try{let q=await J.beta.environments.work.heartbeat($.id,{environment_id:$.environment_id,expected_last_heartbeat:K},{...G,headers:U([G?.headers]),signal:C.signal});if(B=Date.now(),K=q.last_heartbeat,q.ttl_seconds>0)z=q.ttl_seconds*1000,Y=Math.max(1000,Math.min(z/2,HZ)),Q?.(z);if(q.state==="stopping"||q.state==="stopped")X.info("heartbeat signals shutdown",{work_id:$.id,state:q.state}),Z.finish("control_plane_stop");if(!q.lease_extended)X.warn("lease not extended, shutting down",{work_id:$.id}),Z.finish("control_plane_stop")}catch(q){if(Z.signal.throwIfAborted(),e(q,412)){let A=gX(q);X.error("lease lost: heartbeat precondition failed",{work_id:$.id,server_state:A.state,server_ttl_seconds:A.ttl_seconds,server_last_heartbeat:A.last_heartbeat}),Z.finish("lease_lost");return}if(h0(q))throw X.error("permanent heartbeat failure",{work_id:$.id,error:String(q)}),Z.finish("heartbeat_rejected"),q;if(Date.now()-B>z){X.error("lease assumed lost: no successful heartbeat in ttl",{work_id:$.id,ttl_ms:z,error:String(q)}),Z.finish("assumed_lost");return}X.warn("transient heartbeat failure",{work_id:$.id,error:String(q)})}finally{clearTimeout(F),V()}};await W();while(!Z.signal.aborted)await T0(Y,Z.signal),Z.signal.throwIfAborted(),await W()}var HZ=30000,xX=90000,kX="NO_HEARTBEAT";var WJ=M(()=>{c();O0();K1();T2();Q0();E();E1();_1();d6();y1()});var z2;var VJ=M(()=>{_();E();I();_1();WJ();_1();WJ();z2=class z2 extends w{retrieve(J,$,Z){let{environment_id:X,betas:G}=$;return this._client.get(N`/v1/environments/${X}/work/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{environment_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/environments/${X}/work/${J}?beta=true`,{body:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/environments/${J}/work?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}ack(J,$,Z){let{environment_id:X,betas:G}=$;return this._client.post(N`/v1/environments/${X}/work/${J}/ack?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}heartbeat(J,$,Z){let{environment_id:X,desired_ttl_seconds:G,expected_last_heartbeat:Q,betas:Y}=$;return this._client.post(N`/v1/environments/${X}/work/${J}/heartbeat?beta=true`,{query:{desired_ttl_seconds:G,expected_last_heartbeat:Q},...Z,headers:U([{"puku-beta":[...Y??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}poll(J,$={},Z){let{betas:X,"PukuAI-Worker-ID":G,...Q}=$??{};return this._client.get(N`/v1/environments/${J}/work/poll?beta=true`,{query:Q,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString(),...G!=null?{"PukuAI-Worker-ID":G}:void 0},Z?.headers])})}stats(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/environments/${J}/work/stats?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}stop(J,$,Z){let{environment_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/environments/${X}/work/${J}/stop?beta=true`,{body:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}poller(J){return new $2({...J,client:this._client})}worker(J){return new R8({...J,client:this._client})}};z2.WorkPoller=$2;z2.EnvironmentWorker=R8});var L2;var CJ=M(()=>{VJ();VJ();_();E();I();L2=class L2 extends w{work=new z2(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/environments?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/environments/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/environments/${J}?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/environments?beta=true",L,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/environments/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/environments/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}};L2.Work=z2});var A8;var UJ=M(()=>{_();E();I();A8=class A8 extends w{create(J,$,Z){let{view:X,betas:G,...Q}=$;return this._client.post(N`/v1/memory_stores/${J}/memories?beta=true`,{query:{view:X},body:Q,...Z,headers:U([{"puku-beta":[...G??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}retrieve(J,$,Z){let{memory_store_id:X,betas:G,...Q}=$;return this._client.get(N`/v1/memory_stores/${X}/memories/${J}?beta=true`,{query:Q,...Z,headers:U([{"puku-beta":[...G??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}update(J,$,Z){let{memory_store_id:X,view:G,betas:Q,...Y}=$;return this._client.post(N`/v1/memory_stores/${X}/memories/${J}?beta=true`,{query:{view:G},body:Y,...Z,headers:U([{"puku-beta":[...Q??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/memory_stores/${J}/memories?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}delete(J,$,Z){let{memory_store_id:X,expected_content_sha256:G,betas:Q}=$;return this._client.delete(N`/v1/memory_stores/${X}/memories/${J}?beta=true`,{query:{expected_content_sha256:G},...Z,headers:U([{"puku-beta":[...Q??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}}});var H8;var NJ=M(()=>{_();E();I();H8=class H8 extends w{retrieve(J,$,Z){let{memory_store_id:X,betas:G,...Q}=$;return this._client.get(N`/v1/memory_stores/${X}/memory_versions/${J}?beta=true`,{query:Q,...Z,headers:U([{"puku-beta":[...G??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/memory_stores/${J}/memory_versions?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}redact(J,$,Z){let{memory_store_id:X,betas:G}=$;return this._client.post(N`/v1/memory_stores/${X}/memory_versions/${J}/redact?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}}});var B2;var FJ=M(()=>{UJ();UJ();NJ();NJ();_();E();I();B2=class B2 extends w{memories=new A8(this._client);memoryVersions=new H8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/memory_stores?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"agent-memory-2026-07-22"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/memory_stores/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/memory_stores/${J}?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/memory_stores?beta=true",L,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"agent-memory-2026-07-22"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/memory_stores/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/memory_stores/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"agent-memory-2026-07-22"].toString()},Z?.headers])})}};B2.Memories=A8;B2.MemoryVersions=H8});var D2=M(()=>{c()});var j2;var qJ=M(()=>{c();O6();j2=class j2{iterator;controller;constructor(J,$){this.iterator=J;this.controller=$}async*decoder(){let J=new F2;for await(let $ of this.iterator)for(let Z of J.decode($))yield JSON.parse(Z);for(let $ of J.flush())yield JSON.parse($)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(J,$){if(!J.body){if($.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new T("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new T("Attempted to iterate over a response with no body")}return new j2(o2(J.body),$)}}});var L8;var MJ=M(()=>{_();E();qJ();D2();I();L8=class L8 extends w{create(J,$){let{betas:Z,user_profile_id:X,...G}=J;return this._client.post("/v1/messages/batches?beta=true",{body:G,...$,headers:U([{"puku-beta":[...Z??[],"message-batches-2024-09-24"].toString(),...X!=null?{"puku-user-profile-id":X}:void 0},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/messages/batches/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/messages/batches?beta=true",o,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"message-batches-2024-09-24"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/messages/batches/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}cancel(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/messages/batches/${J}/cancel?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}async results(J,$={},Z){let X=await this.retrieve(J);if(!X.results_url)throw new T(`No batch \`results_url\`; Has it finished processing? ${X.processing_status} - ${X.id}`);let{betas:G}=$??{};return this._client.get(X.results_url,{...Z,headers:U([{"puku-beta":[...G??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,Y)=>j2.fromResponse(Y.response,Y.controller))}}});var D8;var m1=M(()=>{D8={"puku-ai-2.7":8192,"puku-ai-2.8":8192,"opus-4.8":8192}});function jZ(J){return J?.output_format??J?.output_config?.format}function TJ(J,$,Z){let X=jZ($);if(!$||!("parse"in(X??{})))return{...J,content:J.content.map((G)=>{if(G.type==="text"){let Q=Object.defineProperty({...G},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(Q,"parsed",{get(){return Z.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return G}),parsed_output:null};return wJ(J,$,Z)}function wJ(J,$,Z){let X=null,G=J.content.map((Q)=>{if(Q.type==="text"){let Y=iX($,Q.text);if(X===null)X=Y;let z=Object.defineProperty({...Q},"parsed_output",{value:Y,enumerable:!1});return Object.defineProperty(z,"parsed",{get(){return Z.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),Y},enumerable:!1})}return Q});return{...J,content:G,parsed_output:X}}function iX(J,$){let Z=jZ(J);if(Z?.type!=="json_schema")return null;try{if("parse"in Z)return Z.parse($);return JSON.parse($)}catch(X){throw new T(`Failed to parse structured output: ${X}`)}}var OJ=M(()=>{c()});var RJ=M(()=>{q2()});var nX=(J)=>{let $=0,Z=[];while($<J.length){let X=J[$];if(X==="\\"){$++;continue}if(X==="{"){Z.push({type:"brace",value:"{"}),$++;continue}if(X==="}"){Z.push({type:"brace",value:"}"}),$++;continue}if(X==="["){Z.push({type:"paren",value:"["}),$++;continue}if(X==="]"){Z.push({type:"paren",value:"]"}),$++;continue}if(X===":"){Z.push({type:"separator",value:":"}),$++;continue}if(X===","){Z.push({type:"delimiter",value:","}),$++;continue}if(X==='"'){let z="",B=!1;X=J[++$];while(X!=='"'){if($===J.length){B=!0;break}if(X==="\\"){if($++,$===J.length){B=!0;break}z+=X+J[$],X=J[++$]}else z+=X,X=J[++$]}if(X=J[++$],!B)Z.push({type:"string",value:z});continue}if(X&&/\s/.test(X)){$++;continue}let Q=/[0-9]/;if(X&&Q.test(X)||X==="-"||X==="."){let z="";if(X==="-")z+=X,X=J[++$];while(X&&Q.test(X)||X===".")z+=X,X=J[++$];Z.push({type:"number",value:z});continue}let Y=/[a-z]/i;if(X&&Y.test(X)){let z="";while(X&&Y.test(X)){if($===J.length)break;z+=X,X=J[++$]}if(z=="true"||z=="false"||z==="null")Z.push({type:"name",value:z});else{$++;continue}continue}$++}return Z},P2=(J)=>{if(J.length===0)return J;let $=J[J.length-1];switch($.type){case"separator":return J=J.slice(0,J.length-1),P2(J);break;case"number":let Z=$.value[$.value.length-1];if(Z==="."||Z==="-")return J=J.slice(0,J.length-1),P2(J);case"string":let X=J[J.length-2];if(X?.type==="delimiter")return J=J.slice(0,J.length-1),P2(J);else if(X?.type==="brace"&&X.value==="{")return J=J.slice(0,J.length-1),P2(J);break;case"delimiter":return J=J.slice(0,J.length-1),P2(J);break}return J},aX=(J)=>{let $=[];if(J.map((Z)=>{if(Z.type==="brace")if(Z.value==="{")$.push("}");else $.splice($.lastIndexOf("}"),1);if(Z.type==="paren")if(Z.value==="[")$.push("]");else $.splice($.lastIndexOf("]"),1)}),$.length>0)$.reverse().map((Z)=>{if(Z==="}")J.push({type:"brace",value:"}"});else if(Z==="]")J.push({type:"paren",value:"]"})});return J},oX=(J)=>{let $="";return J.map((Z)=>{switch(Z.type){case"string":$+='"'+Z.value+'"';break;default:$+=Z.value;break}}),$},PZ=(J)=>JSON.parse(oX(aX(P2(nX(J)))));var SZ=()=>{};function u1(J,$){let Z={};for(let Q of Object.keys(J))if(Q!=="input")Z[Q]=J[Q];Object.defineProperty(Z,d0,{value:$,enumerable:!1,writable:!0});let X,G=!1;return Object.defineProperty(Z,"input",{enumerable:!0,configurable:!0,get(){if(!G)X=$?PZ($):{},G=!0;return X}}),Z}var d0="__json_buf";var AJ=M(()=>{SZ()});function HJ(J){return J.type==="tool_use"||J.type==="server_tool_use"||J.type==="mcp_tool_use"}var j8;var _Z=M(()=>{q0();D2();Q0();RJ();OJ();AJ();j8=class j8{messages=[];receivedMessages=[];#J;#$=null;controller=new AbortController;#X;#G=()=>{};#Z=()=>{};#Q;#B=()=>{};#Y=()=>{};#z={};#K=!1;#C=!1;#U=!1;#V=!1;#F;#W;#M;#q;constructor(J,$){this.#X=new Promise((Z,X)=>{this.#G=Z,this.#Z=X}),this.#Q=new Promise((Z,X)=>{this.#B=Z,this.#Y=X}),this.#X.catch(()=>{}),this.#Q.catch(()=>{}),this.#$=J,this.#q=$?.logger??console}get response(){return this.#F}get request_id(){return this.#W}get workspace_id(){return this.#M}async withResponse(){this.#V=!0;let J=await this.#X;if(!J)throw Error("Could not resolve a `Response` object");return{data:this,response:J,request_id:J.headers.get("request-id"),workspace_id:J.headers.get("puku-workspace-id")}}static fromReadableStream(J){let $=new j8(null);return $._run(()=>$._fromReadableStream(J)),$}static createMessage(J,$,Z,{logger:X}={}){let G=new j8($,{logger:X});for(let Q of $.messages)G._addMessageParam(Q);return G.#$={...$,stream:!0},G._run(()=>G._createMessage(J,{...$,stream:!0},{...Z,headers:{...Z?.headers,[A1]:"stream"}})),G}_run(J){J().then(()=>{this._emitFinal(),this._emit("end")},this.#T)}_addMessageParam(J){this.messages.push(J)}_addMessage(J,$=!0){if(this.receivedMessages.push(J),$)this._emit("message",J)}async _createMessage(J,$,Z){let X=Z?.signal,G;if(X){if(X.aborted)this.controller.abort();G=this.controller.abort.bind(this.controller),X.addEventListener("abort",G)}try{this.#N();let{response:Q,data:Y}=await J.create({...$,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(Q);for await(let z of Y)this.#R(z);if(Y.controller.signal?.aborted)throw new Z0;this.#w()}finally{if(X&&G)X.removeEventListener("abort",G)}}_connected(J){if(this.ended)return;this.#F=J,this.#W=J?.headers.get("request-id"),this.#M=J?.headers.get("puku-workspace-id"),this.#G(J),this._emit("connect")}get ended(){return this.#K}get errored(){return this.#C}get aborted(){return this.#U}abort(){this.controller.abort()}on(J,$){return(this.#z[J]||(this.#z[J]=[])).push({listener:$}),this}off(J,$){let Z=this.#z[J];if(!Z)return this;let X=Z.findIndex((G)=>G.listener===$);if(X>=0)Z.splice(X,1);return this}once(J,$){return(this.#z[J]||(this.#z[J]=[])).push({listener:$,once:!0}),this}emitted(J){return new Promise(($,Z)=>{if(this.#V=!0,J!=="error")this.once("error",Z);this.once(J,$)})}async done(){this.#V=!0,await this.#Q}get currentMessage(){return this.#J}#O(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)}async finalMessage(){return await this.done(),this.#O()}#A(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");let J=this.receivedMessages.at(-1).content.filter(($)=>$.type==="text").map(($)=>$.text);if(J.length===0)throw new T("stream ended without producing a content block with type=text");return J.join(" ")}async finalText(){return await this.done(),this.#A()}#T=(J)=>{if(this.#C=!0,U0(J))J=new Z0;if(J instanceof Z0)return this.#U=!0,this._emit("abort",J);if(J instanceof T)return this._emit("error",J);if(J instanceof Error){let $=new T(J.message);return $.cause=J,this._emit("error",$)}return this._emit("error",new T(String(J)))};_emit(J,...$){if(this.#K)return;if(J==="end")this.#K=!0,this.#B();let Z=this.#z[J];if(Z)this.#z[J]=Z.filter((X)=>!X.once),Z.forEach(({listener:X})=>X(...$));if(J==="abort"){let X=$[0];if(!this.#V&&!Z?.length)Promise.reject(X);this.#Z(X),this.#Y(X),this._emit("end");return}if(J==="error"){let X=$[0];if(!this.#V&&!Z?.length)Promise.reject(X);this.#Z(X),this.#Y(X),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",this.#O())}#N(){if(this.ended)return;this.#J=void 0}#R(J){if(this.ended)return;let $=this.#H(J);switch(this._emit("streamEvent",J,$),J.type){case"content_block_delta":{let Z=$.content.at(-1);switch(J.delta.type){case"text_delta":{if(Z.type==="text")this._emit("text",J.delta.text,Z.text||"");break}case"citations_delta":{if(Z.type==="text")this._emit("citation",J.delta.citation,Z.citations??[]);break}case"input_json_delta":{if(HJ(Z)&&this.#z.inputJson?.length){let X;try{X=Z.input}catch(G){this.#T(this.#L(Z,G));break}this._emit("inputJson",J.delta.partial_json,X)}break}case"thinking_delta":{if(Z.type==="thinking")this._emit("thinking",J.delta.thinking,Z.thinking);break}case"signature_delta":{if(Z.type==="thinking")this._emit("signature",Z.signature);break}case"compaction_delta":{if(Z.type==="compaction"&&Z.content)this._emit("compaction",Z.content);break}default:x0(J.delta)}break}case"message_stop":{this._addMessageParam($),this._addMessage(TJ($,this.#$,{logger:this.#q}),!0);break}case"content_block_stop":{this._emit("contentBlock",$.content.at(-1));break}case"message_start":{this.#J=$;break}case"content_block_start":case"message_delta":break}}#w(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let J=this.#J;if(!J)throw new T("request ended without sending any chunks");return this.#J=void 0,TJ(J,this.#$,{logger:this.#q})}async _fromReadableStream(J,$){let Z=$?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{this.#N(),this._connected(null);let G=s.fromReadableStream(J,this.controller);for await(let Q of G)this.#R(Q);if(G.controller.signal?.aborted)throw new Z0;this.#w()}finally{if(Z&&X)Z.removeEventListener("abort",X)}}#H(J){let $=this.#J;if(J.type==="message_start"){if($)throw new T(`Unexpected event order, got ${J.type} before receiving "message_stop"`);return J.message}if(!$)throw new T(`Unexpected event order, got ${J.type} before "message_start"`);switch(J.type){case"message_stop":return $;case"message_delta":if($.stop_reason=J.delta.stop_reason,$.stop_sequence=J.delta.stop_sequence,$.stop_details=J.delta.stop_details,$.usage.output_tokens=J.usage.output_tokens,J.delta.container!=null)$.container=J.delta.container;if(J.context_management!=null)$.context_management=J.context_management;if(J.input_transformations!=null)$.input_transformations=J.input_transformations;if(J.usage.input_tokens!=null)$.usage.input_tokens=J.usage.input_tokens;if(J.usage.cache_creation_input_tokens!=null)$.usage.cache_creation_input_tokens=J.usage.cache_creation_input_tokens;if(J.usage.cache_read_input_tokens!=null)$.usage.cache_read_input_tokens=J.usage.cache_read_input_tokens;if(J.usage.server_tool_use!=null)$.usage.server_tool_use=J.usage.server_tool_use;if(J.usage.iterations!=null)$.usage.iterations=J.usage.iterations;if(J.usage.fallback_credit!=null)$.usage.fallback_credit=J.usage.fallback_credit;if(J.usage.output_tokens_details!=null)$.usage.output_tokens_details=J.usage.output_tokens_details;return $;case"content_block_start":if($.content.push(J.content_block),J.content_block.type==="fallback")$.model=J.content_block.to.model;return $;case"content_block_delta":{let Z=$.content.at(J.index);switch(J.delta.type){case"text_delta":{if(Z?.type==="text")$.content[J.index]={...Z,text:(Z.text||"")+J.delta.text};break}case"citations_delta":{if(Z?.type==="text")$.content[J.index]={...Z,citations:[...Z.citations??[],J.delta.citation]};break}case"input_json_delta":{if(Z&&HJ(Z)){let X=(Z[d0]||"")+J.delta.partial_json;$.content[J.index]=u1(Z,X)}break}case"thinking_delta":{if(Z?.type==="thinking")$.content[J.index]={...Z,thinking:Z.thinking+J.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")$.content[J.index]={...Z,signature:J.delta.signature};break}case"compaction_delta":{if(Z?.type==="compaction")$.content[J.index]={...Z,content:(Z.content||"")+J.delta.content,encrypted_content:J.delta.encrypted_content};break}default:x0(J.delta)}return $}case"content_block_stop":{let Z=$.content.at(J.index);if(Z&&HJ(Z)&&d0 in Z){let X;try{X=Z.input}catch(G){X={},this.#T(this.#L(Z,G))}Object.defineProperty(Z,"input",{value:X,enumerable:!0,configurable:!0,writable:!0})}return $}}}#L(J,$){let Z=J[d0];return new T(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${$}. JSON: ${Z}`)}[Symbol.asyncIterator](){let J=[],$=[],Z=!1;return this.on("streamEvent",(X)=>{let G=$.shift();if(G)G.resolve(X);else J.push(X)}),this.on("end",()=>{Z=!0;for(let X of $)X.resolve(void 0);$.length=0}),this.on("abort",(X)=>{Z=!0;for(let G of $)G.reject(X);$.length=0}),this.on("error",(X)=>{Z=!0;for(let G of $)G.reject(X);$.length=0}),{next:async()=>{if(!J.length){if(Z)return{value:void 0,done:!0};return new Promise((G,Q)=>$.push({resolve:G,reject:Q})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:J.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var EZ=1e5,IZ=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
26
26
  1. Task Overview
27
27
  The user's core request and success criteria
28
28
  Any clarifications or constraints they specified
@@ -44,25 +44,25 @@ User preferences or style requirements
44
44
  Domain-specific details that aren't obvious
45
45
  Any promises made to the user
46
46
  Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
47
- Wrap your summary in <summary></summary> tags.`;async function r5(J,$=J.messages.at(-1),Z){if(!$||$.role!=="assistant"||!$.content||typeof $.content==="string")return null;let X=$.content.filter((Y)=>Y.type==="tool_use");if(X.length===0)return null;let G=s5(J);return{role:"user",content:await Promise.all(X.map(async(Y)=>{let z=J.tools.find((B)=>("name"in B?B.name:("mcp_server_name"in B)?B.mcp_server_name:B.type)===Y.name);if(!z||!("run"in z)||!G.has(Y.name))return t5(Y);try{let B=Y.input;if("parse"in z&&z.parse)B=z.parse(B);let K=await z.run(B,{toolUse:Y,toolUseBlock:Y,signal:Z?.signal});return{type:"tool_result",tool_use_id:Y.id,content:K}}catch(B){return{type:"tool_result",tool_use_id:Y.id,content:B instanceof P?B.content:`Error: ${B instanceof Error?B.message:String(B)}`,is_error:!0}}}))}}function t5(J){return{type:"tool_result",tool_use_id:J.id,content:`Error: Tool '${J.name}' not found`,is_error:!0}}function s5(J){let $=new Set;for(let Z of J.tools)if("run"in Z)$.add(Z.name);for(let Z of J.messages){if(Z.role!=="system"||typeof Z.content==="string")continue;for(let X of Z.content)e5(X,$)}return $}function e5(J,$){switch(J.type){case"tool_removal":case"tool_addition":JX(J,$);break}}function JX(J,$){let Z=$X(J.tool);if(Z===void 0)return;if(J.type==="tool_removal")$.delete(Z);else $.add(Z)}function $X(J){switch(J.type){case"tool_reference":return J.name;default:return}}function ZX(J){if(J===null)return"stop";switch(J){case"tool_use":return"run_tools";case"pause_turn":case"compaction":return"resume";case"end_turn":case"stop_sequence":case"max_tokens":case"model_context_window_exceeded":case"refusal":return"stop";default:return x0(J),"stop"}}var P8;var L4=M(()=>{I0();c();E();Q0();q0();P8=class P8{client;#J=!1;#$=!1;#X;#G;#Z;#Q;#B;#Y=0;constructor(J,$,Z){this.client=J;this.#X={params:{...$,messages:structuredClone($.messages)}};let X=H1($.tools,$.messages);if(this.#G={...Z,headers:U([G8("BetaToolRunner"),X.length?{[J2]:X.join(", ")}:void 0,Z?.headers])},this.#B=w2(),$.compactionControl?.enabled)console.warn('Puku: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://puku.ai/docs/en/build-with-puku/compaction')}async#z(){let J=this.#X.params.compactionControl;if(!J||!J.enabled)return!1;let $=0;if(this.#Z!==void 0)try{let z=await this.#Z;$=z.usage.input_tokens+(z.usage.cache_creation_input_tokens??0)+(z.usage.cache_read_input_tokens??0)+z.usage.output_tokens}catch{return!1}let Z=J.contextTokenThreshold??EZ;if($<Z)return!1;let X=J.model??this.#X.params.model,G=J.summaryPrompt??IZ,Q=this.#X.params.messages;if(Q[Q.length-1].role==="assistant"){let z=Q[Q.length-1];if(Array.isArray(z.content)){let B=z.content.filter((K)=>K.type!=="tool_use");if(B.length===0)Q.pop();else z.content=B}}let Y=await this.client.beta.messages.create({model:X,messages:[...Q,{role:"user",content:[{type:"text",text:G}]}],max_tokens:this.#X.params.max_tokens},{signal:this.#G.signal,headers:U([this.#G.headers,G8("compaction")])});if(Y.content[0]?.type!=="text")throw new T("Expected text response for compaction");return this.#X.params.messages=[{role:"user",content:Y.content}],!0}async*[Symbol.asyncIterator](){if(this.#J)throw new T("Cannot iterate over a consumed stream");this.#J=!0,this.#$=!0,this.#Q=void 0;try{while(!0){let J;try{if(this.#X.params.max_iterations&&this.#Y>=this.#X.params.max_iterations)break;this.#$=!1,this.#Q=void 0,this.#Y++,this.#Z=void 0;let{max_iterations:$,compactionControl:Z,...X}=this.#X.params;if(X.stream)J=this.client.beta.messages.stream({...X},this.#G),this.#Z=J.finalMessage(),this.#Z.catch(()=>{}),yield J;else this.#Z=this.client.beta.messages.create({...X,stream:!1},this.#G),yield this.#Z;if(!await this.#z()){if(!this.#$){let Y=await this.#Z,z=ZX(Y.stop_reason);this.#X.params.messages.push({role:Y.role,content:Y.content});let{container:B}=this.#X.params;if(Y.container){if(B==null)this.#X.params.container=Y.container.id;else if(typeof B==="object"&&B.id==null)this.#X.params.container={...B,id:Y.container.id}}if(z==="stop")break;if(z==="resume")continue}let Q=await this.#K(this.#X.params.messages.at(-1));if(Q)this.#X.params.messages.push(Q);else if(!this.#$)break}}finally{if(J)J.abort()}}if(!this.#Z)throw new T("ToolRunner concluded without a message from the server");this.#B.resolve(await this.#Z)}catch(J){throw this.#J=!1,this.#B.promise.catch(()=>{}),this.#B.reject(J),this.#B=w2(),J}}setMessagesParams(J){if(typeof J==="function")this.#X.params=J(this.#X.params);else this.#X.params=J;this.#$=!0,this.#Q=void 0}setRequestOptions(J){if(typeof J==="function")this.#G=J(this.#G);else this.#G={...this.#G,...J}}async generateToolResponse(J=this.#G.signal){let $=await this.#Z??this.params.messages.at(-1);if(!$)return null;return this.#K($,J)}async#K(J,$=this.#G.signal){if(this.#Q!==void 0)return this.#Q;return this.#Q=r5(this.#X.params,J,{...this.#G,signal:$}),this.#Q}done(){return this.#B.promise}async runUntilDone(){if(!this.#J)for await(let J of this);return this.done()}get params(){return this.#X.params}pushMessages(...J){this.setMessagesParams(($)=>({...$,messages:[...$.messages,...J]}))}then(J,$){return this.runUntilDone().then(J,$)}}});function xZ(J){if(!J.output_format)return J;if(J.output_config?.format)throw new T("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:$,...Z}=J;return{...Z,output_config:{...J.output_config,format:$}}}var yZ,XX,c0;var D4=M(()=>{D2();M4();m1();E();q0();O4();_Z();L4();I0();M4();L4();I0();yZ={"puku-1.3":"November 6th, 2024","puku-1.3-100k":"November 6th, 2024","puku-instant-1.1":"November 6th, 2024","puku-instant-1.1-100k":"November 6th, 2024","puku-instant-1.2":"November 6th, 2024","puku-3-sonnet-20240229":"July 21st, 2025","puku-3-opus-20240229":"January 5th, 2026","puku-2.1":"July 21st, 2025","puku-2.0":"July 21st, 2025","puku-3-7-sonnet-latest":"February 19th, 2026"},XX=[];c0=class c0 extends w{batches=new L8(this._client);create(J,$){let Z=xZ(J),{betas:X,user_profile_id:G,...Q}=Z;if(Q.model in yZ)console.warn(`The Puku SDK model '${Q.model}' is deprecated and will reach end-of-life on ${yZ[Q.model]}
48
- Please migrate to a newer model. Visit https://puku.ai/docs/resources/model-deprecations for more information.`);if(XX.includes(Q.model)&&Q.thinking&&Q.thinking.type==="enabled")console.warn(`Using Puku with ${Q.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://puku.ai/docs/en/build-with-puku/adaptive-thinking`);let Y=$?.timeout??this._client._options.timeout;if(!Q.stream&&Y==null){let B=D8[Q.model]??void 0;Y=this._client.calculateNonstreamingTimeout(Q.max_tokens,B)}let z=Q8(Q.tools,Q.messages);return this._client.post("/v1/messages?beta=true",{body:Q,timeout:Y??600000,...$,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0,...G!=null?{"puku-user-profile-id":G}:void 0},z,$?.headers]),stream:Z.stream??!1})}parse(J,$){return $={...$,headers:U([{"puku-beta":[...J.betas??[],"structured-outputs-2025-12-15"].toString()},$?.headers])},this.create(J,$).then((Z)=>w4(Z,J,{logger:this._client.logger??console}))}stream(J,$){return j8.createMessage(this,J,$)}countTokens(J,$){let Z=xZ(J),{betas:X,user_profile_id:G,...Q}=Z;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Q,...$,headers:U([{"puku-beta":[...X??[],"token-counting-2024-11-01"].toString(),...G!=null?{"puku-user-profile-id":G}:void 0},$?.headers])})}toolRunner(J,$){return new P8(this._client,J,$)}};c0.Batches=L8;c0.BetaToolRunner=P8;c0.ToolError=P});var S8;var j4=M(()=>{_();I();S8=class S8 extends w{retrieve(J,$){return this._client.get(N`/v1/organizations/api_keys/${J}?beta=true`,$)}update(J,$,Z){return this._client.post(N`/v1/organizations/api_keys/${J}?beta=true`,{body:$,...Z})}list(J={},$){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",o,{query:J,...$})}}});var _8;var P4=M(()=>{_8=class _8 extends w{retrieve(J){return this._client.get("/v1/organizations/compliance_settings?beta=true",J)}update(J,$){return this._client.post("/v1/organizations/compliance_settings?beta=true",{body:J,...$})}}});var E8;var S4=M(()=>{_();I();E8=class E8 extends w{create(J,$){return this._client.post("/v1/organizations/external_keys?beta=true",{body:J,...$})}retrieve(J,$){return this._client.get(N`/v1/organizations/external_keys/${J}?beta=true`,$)}update(J,$,Z){return this._client.post(N`/v1/organizations/external_keys/${J}?beta=true`,{body:$,...Z})}list(J={},$){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",L,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/organizations/external_keys/${J}?beta=true`,$)}validate(J,$){return this._client.post(N`/v1/organizations/external_keys/${J}/validate?beta=true`,$)}}});var I8;var _4=M(()=>{_();I();I8=class I8 extends w{create(J,$){return this._client.post("/v1/organizations/invites?beta=true",{body:J,...$})}retrieve(J,$){return this._client.get(N`/v1/organizations/invites/${J}?beta=true`,$)}list(J={},$){return this._client.getAPIList("/v1/organizations/invites?beta=true",o,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/organizations/invites/${J}?beta=true`,$)}}});var y8;var E4=M(()=>{_();y8=class y8 extends w{list(J={},$){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",L,{query:J,...$})}}});var x8;var I4=M(()=>{_();I();x8=class x8 extends w{retrieve(J,$){return this._client.get(N`/v1/organizations/users/${J}?beta=true`,$)}update(J,$,Z){return this._client.post(N`/v1/organizations/users/${J}?beta=true`,{body:$,...Z})}list(J={},$){return this._client.getAPIList("/v1/organizations/users?beta=true",o,{query:J,...$})}remove(J,$){return this._client.delete(N`/v1/organizations/users/${J}?beta=true`,$)}}});var k8;var y4=M(()=>{_();E();I();k8=class k8 extends w{create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/organizations/federation_issuers/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/federation_issuers/${J}?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/organizations/federation_issuers?beta=true",L,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/organizations/federation_issuers/${J}/archive?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}}});var f8;var x4=M(()=>{_();E();I();f8=class f8 extends w{list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/organizations/federation_rules/${J}/workspaces?beta=true`,L,{query:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}add(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/federation_rules/${J}/workspaces?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}remove(J,$,Z){let{federation_rule_id:X,betas:G}=$;return this._client.delete(N`/v1/organizations/federation_rules/${X}/workspaces/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}}});var S2;var k4=M(()=>{x4();x4();_();E();I();S2=class S2 extends w{workspaces=new f8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/organizations/federation_rules/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/federation_rules/${J}?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/organizations/federation_rules?beta=true",L,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/organizations/federation_rules/${J}/archive?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}};S2.Workspaces=f8});var K2;var f4=M(()=>{y4();y4();k4();k4();K2=class K2 extends w{issuers=new k8(this._client);rules=new S2(this._client)};K2.Issuers=k8;K2.Rules=S2});var v8;var v4=M(()=>{_();E();I();v8=class v8 extends w{list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/organizations/service_accounts/${J}/workspaces?beta=true`,L,{query:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}add(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/service_accounts/${J}/workspaces?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}remove(J,$,Z){let{service_account_id:X,betas:G}=$;return this._client.delete(N`/v1/organizations/service_accounts/${X}/workspaces/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}}});var _2;var b4=M(()=>{v4();v4();_();E();I();_2=class _2 extends w{workspaces=new v8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/organizations/service_accounts/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/service_accounts/${J}?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/organizations/service_accounts?beta=true",L,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/organizations/service_accounts/${J}/archive?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}};_2.Workspaces=v8});var b8;var g4=M(()=>{_();I();b8=class b8 extends w{retrieve(J,$,Z){let{workspace_id:X}=$;return this._client.get(N`/v1/organizations/workspaces/${X}/members/${J}?beta=true`,Z)}update(J,$,Z){let{workspace_id:X,...G}=$;return this._client.post(N`/v1/organizations/workspaces/${X}/members/${J}?beta=true`,{body:G,...Z})}list(J,$={},Z){return this._client.getAPIList(N`/v1/organizations/workspaces/${J}/members?beta=true`,o,{query:$,...Z})}add(J,$,Z){return this._client.post(N`/v1/organizations/workspaces/${J}/members?beta=true`,{body:$,...Z})}remove(J,$,Z){let{workspace_id:X}=$;return this._client.delete(N`/v1/organizations/workspaces/${X}/members/${J}?beta=true`,Z)}}});var g8;var h4=M(()=>{_();I();g8=class g8 extends w{list(J,$={},Z){return this._client.getAPIList(N`/v1/organizations/workspaces/${J}/rate_limits?beta=true`,L,{query:$,...Z})}}});var h8;var m4=M(()=>{_();E();I();h8=class h8 extends w{retrieve(J,$,Z){let{workspace_id:X,betas:G}=$;return this._client.get(N`/v1/organizations/workspaces/${X}/service_accounts/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}update(J,$,Z){let{workspace_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/organizations/workspaces/${X}/service_accounts/${J}?beta=true`,{body:Q,...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/organizations/workspaces/${J}/service_accounts?beta=true`,L,{query:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}add(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/workspaces/${J}/service_accounts?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}remove(J,$,Z){let{workspace_id:X,betas:G}=$;return this._client.delete(N`/v1/organizations/workspaces/${X}/service_accounts/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}}});var p0;var u4=M(()=>{g4();g4();h4();h4();m4();m4();_();E();I();p0=class p0 extends w{rateLimits=new g8(this._client);members=new b8(this._client);serviceAccounts=new h8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/organizations/workspaces?beta=true",{body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}retrieve(J,$){return this._client.get(N`/v1/organizations/workspaces/${J}?beta=true`,$)}update(J,$,Z){return this._client.post(N`/v1/organizations/workspaces/${J}?beta=true`,{body:$,...Z})}list(J={},$){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",o,{query:J,...$})}archive(J,$){return this._client.post(N`/v1/organizations/workspaces/${J}/archive?beta=true`,$)}};p0.RateLimits=g8;p0.Members=b8;p0.ServiceAccounts=h8});var C0;var d4=M(()=>{j4();j4();P4();P4();S4();S4();_4();_4();E4();E4();I4();I4();f4();f4();b4();b4();u4();u4();C0=class C0 extends w{apiKeys=new S8(this._client);externalKeys=new E8(this._client);federation=new K2(this._client);invites=new I8(this._client);serviceAccounts=new _2(this._client);users=new x8(this._client);workspaces=new p0(this._client);rateLimits=new y8(this._client);complianceSettings=new _8(this._client);retrieve(J){return this._client.get("/v1/organizations/me?beta=true",J)}};C0.APIKeys=S8;C0.ExternalKeys=E8;C0.Federation=K2;C0.Invites=I8;C0.ServiceAccounts=_2;C0.Users=x8;C0.Workspaces=p0;C0.RateLimits=y8;C0.ComplianceSettings=_8});var E2;var c4=M(()=>{_();E();I();E1();E1();E2=class E2 extends w{list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/sessions/${J}/events?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}send(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/sessions/${J}/events?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}stream(J,$={},Z){let{betas:X,...G}=$??{};return this._client.get(N`/v1/sessions/${J}/events/stream?beta=true`,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers]),stream:!0})}toolRunner(J,$){return new Z2(J,{...$,client:this._client})}};E2.SessionToolRunner=Z2});var m8;var p4=M(()=>{_();E();I();m8=class m8 extends w{retrieve(J,$,Z){let{session_id:X,betas:G}=$;return this._client.get(N`/v1/sessions/${X}/resources/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{session_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/sessions/${X}/resources/${J}?beta=true`,{body:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/sessions/${J}/resources?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}delete(J,$,Z){let{session_id:X,betas:G}=$;return this._client.delete(N`/v1/sessions/${X}/resources/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}add(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/sessions/${J}/resources?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}}});var u8;var l4=M(()=>{_();E();I();u8=class u8 extends w{list(J,$,Z){let{session_id:X,betas:G,...Q}=$;return this._client.getAPIList(N`/v1/sessions/${X}/threads/${J}/events?beta=true`,L,{query:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}stream(J,$,Z){let{session_id:X,betas:G,...Q}=$;return this._client.get(N`/v1/sessions/${X}/threads/${J}/stream?beta=true`,{query:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers]),stream:!0})}}});var I2;var i4=M(()=>{l4();l4();_();E();I();I2=class I2 extends w{events=new u8(this._client);retrieve(J,$,Z){let{session_id:X,betas:G}=$;return this._client.get(N`/v1/sessions/${X}/threads/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/sessions/${J}/threads?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$,Z){let{session_id:X,betas:G}=$;return this._client.post(N`/v1/sessions/${X}/threads/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}};I2.Events=u8});var l0;var n4=M(()=>{c4();c4();p4();p4();i4();i4();_();E();I();l0=class l0 extends w{events=new E2(this._client);resources=new m8(this._client);threads=new I2(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/sessions?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/sessions/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/sessions/${J}?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/sessions?beta=true",H6,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/sessions/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/sessions/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}};l0.Events=E2;l0.Resources=m8;l0.Threads=I2});var d8;var a4=M(()=>{_();E();E0();I();d8=class d8 extends w{create(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/skills/${J}/versions?beta=true`,F0({body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])},this._client,!1))}retrieve(J,$,Z){let{skill_id:X,betas:G}=$;return this._client.get(N`/v1/skills/${X}/versions/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/skills/${J}/versions?beta=true`,L,{query:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}delete(J,$,Z){let{skill_id:X,betas:G}=$;return this._client.delete(N`/v1/skills/${X}/versions/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}download(J,$,Z){let{skill_id:X,betas:G}=$;return this._client.get(N`/v1/skills/${X}/versions/${J}/content?beta=true`,{...Z,headers:U([{Accept:"application/binary",...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers]),__binaryResponse:!0})}}});var y2;var o4=M(()=>{a4();a4();_();E();E0();I();y2=class y2 extends w{versions=new d8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/skills?beta=true",F0({body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])},this._client,!1))}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/skills/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/skills?beta=true",L,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/skills/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}};y2.Versions=d8});var c8;var r4=M(()=>{_();E();I();c8=class c8 extends w{create(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/tunnels/${J}/certificates?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}retrieve(J,$,Z){let{tunnel_id:X,betas:G}=$;return this._client.get(N`/v1/tunnels/${X}/certificates/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/tunnels/${J}/certificates?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}archive(J,$,Z){let{tunnel_id:X,betas:G}=$;return this._client.post(N`/v1/tunnels/${X}/certificates/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}}});var x2;var t4=M(()=>{r4();r4();_();E();I();x2=class x2 extends w{certificates=new c8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/tunnels?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"mcp-tunnels-2026-06-22"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/tunnels/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/tunnels?beta=true",L,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"mcp-tunnels-2026-06-22"].toString()},$?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/tunnels/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}revealToken(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/tunnels/${J}/reveal_token?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}rotateToken(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/tunnels/${J}/rotate_token?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}};x2.Certificates=c8});var p8;var s4=M(()=>{_();E();I();p8=class p8 extends w{create(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/vaults/${J}/credentials?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}retrieve(J,$,Z){let{vault_id:X,betas:G}=$;return this._client.get(N`/v1/vaults/${X}/credentials/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{vault_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/vaults/${X}/credentials/${J}?beta=true`,{body:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/vaults/${J}/credentials?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}delete(J,$,Z){let{vault_id:X,betas:G}=$;return this._client.delete(N`/v1/vaults/${X}/credentials/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$,Z){let{vault_id:X,betas:G}=$;return this._client.post(N`/v1/vaults/${X}/credentials/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}mcpOAuthValidate(J,$,Z){let{vault_id:X,betas:G}=$;return this._client.post(N`/v1/vaults/${X}/credentials/${J}/mcp_oauth_validate?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}}});var k2;var e4=M(()=>{s4();s4();_();E();I();k2=class k2 extends w{credentials=new p8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/vaults?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/vaults/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/vaults/${J}?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/vaults?beta=true",L,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/vaults/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/vaults/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}};k2.Credentials=p8});var i;var JJ=M(()=>{E6();E6();I6();I6();y6();y6();x6();x6();k6();k6();f6();f6();g6();g6();m6();m6();C4();C4();F4();F4();D4();D4();d4();d4();n4();n4();o4();o4();t4();t4();e4();e4();i=class i extends w{models=new z8(this._client);messages=new c0(this._client);agents=new M2(this._client);environments=new L2(this._client);sessions=new l0(this._client);deployments=new Z8(this._client);deploymentRuns=new $8(this._client);vaults=new k2(this._client);memoryStores=new B2(this._client);files=new Y8(this._client);skills=new y2(this._client);webhooks=new V8(this._client);userProfiles=new B8(this._client);dreams=new X8(this._client);tunnels=new x2(this._client);organization=new C0(this._client)};i.Models=z8;i.Messages=c0;i.Agents=M2;i.Environments=L2;i.Sessions=l0;i.Deployments=Z8;i.DeploymentRuns=$8;i.Vaults=k2;i.MemoryStores=B2;i.Files=Y8;i.Skills=y2;i.Webhooks=V8;i.UserProfiles=B8;i.Dreams=X8;i.Tunnels=x2;i.Organization=C0});var f2;var $J=M(()=>{E();f2=class f2 extends w{create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/complete",{body:X,timeout:this._client._options.timeout??600000,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers]),stream:J.stream??!1})}}});var v2;var ZJ=M(()=>{_();E();q0();E0();I();v2=class v2 extends w{list(J={},$){return this._client.getAPIList("/v1/files",L,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/files/${J}`,$)}download(J,$){return this._client.get(N`/v1/files/${J}/content`,{...$,headers:U([{Accept:"application/binary"},$?.headers]),__binaryResponse:!0})}retrieveMetadata(J,$){return this._client.get(N`/v1/files/${J}`,$)}upload(J,$){return this._client.post("/v1/files",F0({body:J,...$,headers:U([L1(J.file),$?.headers])},this._client))}}});function kZ(J){return J?.output_config?.format}function XJ(J,$,Z){let X=kZ($);if(!$||!("parse"in(X??{})))return{...J,content:J.content.map((G)=>{if(G.type==="text")return Object.defineProperty({...G},"parsed_output",{value:null,enumerable:!1});return G}),parsed_output:null};return GJ(J,$,Z)}function GJ(J,$,Z){let X=null,G=J.content.map((Q)=>{if(Q.type==="text"){let Y=xX($,Q.text);if(X===null)X=Y;return Object.defineProperty({...Q},"parsed_output",{value:Y,enumerable:!1})}return Q});return{...J,content:G,parsed_output:X}}function xX(J,$){let Z=kZ(J);if(Z?.type!=="json_schema")return null;try{if("parse"in Z)return Z.parse($);return JSON.parse($)}catch(X){throw new T(`Failed to parse structured output: ${X}`)}}var QJ=M(()=>{c()});function YJ(J){return J.type==="tool_use"||J.type==="server_tool_use"}var l8;var fZ=M(()=>{q0();Q0();D2();R4();QJ();A4();l8=class l8{messages=[];receivedMessages=[];#J;#$=null;controller=new AbortController;#X;#G=()=>{};#Z=()=>{};#Q;#B=()=>{};#Y=()=>{};#z={};#K=!1;#C=!1;#U=!1;#V=!1;#F;#W;#M;#q;constructor(J,$){this.#X=new Promise((Z,X)=>{this.#G=Z,this.#Z=X}),this.#Q=new Promise((Z,X)=>{this.#B=Z,this.#Y=X}),this.#X.catch(()=>{}),this.#Q.catch(()=>{}),this.#$=J,this.#q=$?.logger??console}get response(){return this.#F}get request_id(){return this.#W}get workspace_id(){return this.#M}async withResponse(){this.#V=!0;let J=await this.#X;if(!J)throw Error("Could not resolve a `Response` object");return{data:this,response:J,request_id:J.headers.get("request-id"),workspace_id:J.headers.get("puku-workspace-id")}}static fromReadableStream(J){let $=new l8(null);return $._run(()=>$._fromReadableStream(J)),$}static createMessage(J,$,Z,{logger:X}={}){let G=new l8($,{logger:X});for(let Q of $.messages)G._addMessageParam(Q);return G.#$={...$,stream:!0},G._run(()=>G._createMessage(J,{...$,stream:!0},{...Z,headers:{...Z?.headers,[A1]:"stream"}})),G}_run(J){J().then(()=>{this._emitFinal(),this._emit("end")},this.#T)}_addMessageParam(J){this.messages.push(J)}_addMessage(J,$=!0){if(this.receivedMessages.push(J),$)this._emit("message",J)}async _createMessage(J,$,Z){let X=Z?.signal,G;if(X){if(X.aborted)this.controller.abort();G=this.controller.abort.bind(this.controller),X.addEventListener("abort",G)}try{this.#N();let{response:Q,data:Y}=await J.create({...$,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(Q);for await(let z of Y)this.#R(z);if(Y.controller.signal?.aborted)throw new Z0;this.#w()}finally{if(X&&G)X.removeEventListener("abort",G)}}_connected(J){if(this.ended)return;this.#F=J,this.#W=J?.headers.get("request-id"),this.#M=J?.headers.get("puku-workspace-id"),this.#G(J),this._emit("connect")}get ended(){return this.#K}get errored(){return this.#C}get aborted(){return this.#U}abort(){this.controller.abort()}on(J,$){return(this.#z[J]||(this.#z[J]=[])).push({listener:$}),this}off(J,$){let Z=this.#z[J];if(!Z)return this;let X=Z.findIndex((G)=>G.listener===$);if(X>=0)Z.splice(X,1);return this}once(J,$){return(this.#z[J]||(this.#z[J]=[])).push({listener:$,once:!0}),this}emitted(J){return new Promise(($,Z)=>{if(this.#V=!0,J!=="error")this.once("error",Z);this.once(J,$)})}async done(){this.#V=!0,await this.#Q}get currentMessage(){return this.#J}#O(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)}async finalMessage(){return await this.done(),this.#O()}#A(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");let J=this.receivedMessages.at(-1).content.filter(($)=>$.type==="text").map(($)=>$.text);if(J.length===0)throw new T("stream ended without producing a content block with type=text");return J.join(" ")}async finalText(){return await this.done(),this.#A()}#T=(J)=>{if(this.#C=!0,U0(J))J=new Z0;if(J instanceof Z0)return this.#U=!0,this._emit("abort",J);if(J instanceof T)return this._emit("error",J);if(J instanceof Error){let $=new T(J.message);return $.cause=J,this._emit("error",$)}return this._emit("error",new T(String(J)))};_emit(J,...$){if(this.#K)return;if(J==="end")this.#K=!0,this.#B();let Z=this.#z[J];if(Z)this.#z[J]=Z.filter((X)=>!X.once),Z.forEach(({listener:X})=>X(...$));if(J==="abort"){let X=$[0];if(!this.#V&&!Z?.length)Promise.reject(X);this.#Z(X),this.#Y(X),this._emit("end");return}if(J==="error"){let X=$[0];if(!this.#V&&!Z?.length)Promise.reject(X);this.#Z(X),this.#Y(X),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",this.#O())}#N(){if(this.ended)return;this.#J=void 0}#R(J){if(this.ended)return;let $=this.#H(J);switch(this._emit("streamEvent",J,$),J.type){case"content_block_delta":{let Z=$.content.at(-1);switch(J.delta.type){case"text_delta":{if(Z.type==="text")this._emit("text",J.delta.text,Z.text||"");break}case"citations_delta":{if(Z.type==="text")this._emit("citation",J.delta.citation,Z.citations??[]);break}case"input_json_delta":{if(YJ(Z)&&this.#z.inputJson?.length)this._emit("inputJson",J.delta.partial_json,Z.input);break}case"thinking_delta":{if(Z.type==="thinking")this._emit("thinking",J.delta.thinking,Z.thinking);break}case"signature_delta":{if(Z.type==="thinking")this._emit("signature",Z.signature);break}default:x0(J.delta)}break}case"message_stop":{this._addMessageParam($),this._addMessage(XJ($,this.#$,{logger:this.#q}),!0);break}case"content_block_stop":{this._emit("contentBlock",$.content.at(-1));break}case"message_start":{this.#J=$;break}case"content_block_start":case"message_delta":break}}#w(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let J=this.#J;if(!J)throw new T("request ended without sending any chunks");return this.#J=void 0,XJ(J,this.#$,{logger:this.#q})}async _fromReadableStream(J,$){let Z=$?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{this.#N(),this._connected(null);let G=s.fromReadableStream(J,this.controller);for await(let Q of G)this.#R(Q);if(G.controller.signal?.aborted)throw new Z0;this.#w()}finally{if(Z&&X)Z.removeEventListener("abort",X)}}#H(J){let $=this.#J;if(J.type==="message_start"){if($)throw new T(`Unexpected event order, got ${J.type} before receiving "message_stop"`);return J.message}if(!$)throw new T(`Unexpected event order, got ${J.type} before "message_start"`);switch(J.type){case"message_stop":return $;case"message_delta":if($.stop_reason=J.delta.stop_reason,$.stop_sequence=J.delta.stop_sequence,$.stop_details=J.delta.stop_details,$.usage.output_tokens=J.usage.output_tokens,J.delta.container!=null)$.container=J.delta.container;if(J.usage.input_tokens!=null)$.usage.input_tokens=J.usage.input_tokens;if(J.usage.cache_creation_input_tokens!=null)$.usage.cache_creation_input_tokens=J.usage.cache_creation_input_tokens;if(J.usage.cache_read_input_tokens!=null)$.usage.cache_read_input_tokens=J.usage.cache_read_input_tokens;if(J.usage.server_tool_use!=null)$.usage.server_tool_use=J.usage.server_tool_use;if(J.usage.output_tokens_details!=null)$.usage.output_tokens_details=J.usage.output_tokens_details;return $;case"content_block_start":return $.content.push({...J.content_block}),$;case"content_block_delta":{let Z=$.content.at(J.index);switch(J.delta.type){case"text_delta":{if(Z?.type==="text")$.content[J.index]={...Z,text:(Z.text||"")+J.delta.text};break}case"citations_delta":{if(Z?.type==="text")$.content[J.index]={...Z,citations:[...Z.citations??[],J.delta.citation]};break}case"input_json_delta":{if(Z&&YJ(Z)){let X=(Z[d0]||"")+J.delta.partial_json;$.content[J.index]=u1(Z,X)}break}case"thinking_delta":{if(Z?.type==="thinking")$.content[J.index]={...Z,thinking:Z.thinking+J.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")$.content[J.index]={...Z,signature:J.delta.signature};break}default:x0(J.delta)}return $}case"content_block_stop":{let Z=$.content.at(J.index);if(Z&&YJ(Z)&&d0 in Z)Object.defineProperty(Z,"input",{value:Z.input,enumerable:!0,configurable:!0,writable:!0});return $}}}[Symbol.asyncIterator](){let J=[],$=[],Z=!1;return this.on("streamEvent",(X)=>{let G=$.shift();if(G)G.resolve(X);else J.push(X)}),this.on("end",()=>{Z=!0;for(let X of $)X.resolve(void 0);$.length=0}),this.on("abort",(X)=>{Z=!0;for(let G of $)G.reject(X);$.length=0}),this.on("error",(X)=>{Z=!0;for(let G of $)G.reject(X);$.length=0}),{next:async()=>{if(!J.length){if(Z)return{value:void 0,done:!0};return new Promise((G,Q)=>$.push({resolve:G,reject:Q})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:J.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var i8;var zJ=M(()=>{_();E();q4();D2();I();i8=class i8 extends w{create(J,$){let{user_profile_id:Z,...X}=J;return this._client.post("/v1/messages/batches",{body:X,...$,headers:U([{...Z!=null?{"puku-user-profile-id":Z}:void 0},$?.headers])})}retrieve(J,$){return this._client.get(N`/v1/messages/batches/${J}`,$)}list(J={},$){return this._client.getAPIList("/v1/messages/batches",o,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/messages/batches/${J}`,$)}cancel(J,$){return this._client.post(N`/v1/messages/batches/${J}/cancel`,$)}async results(J,$){let Z=await this.retrieve(J);if(!Z.results_url)throw new T(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);return this._client.get(Z.results_url,{...$,headers:U([{Accept:"application/binary"},$?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((X,G)=>j2.fromResponse(G.response,G.controller))}}});var W2,vZ,fX;var BJ=M(()=>{E();q0();fZ();QJ();zJ();zJ();m1();W2=class W2 extends w{batches=new i8(this._client);create(J,$){let{user_profile_id:Z,...X}=J;if(X.model in vZ)console.warn(`The Puku SDK model '${X.model}' is deprecated and will reach end-of-life on ${vZ[X.model]}
49
- Please migrate to a newer model. Visit https://puku.ai/docs/resources/model-deprecations for more information.`);if(fX.includes(X.model)&&X.thinking&&X.thinking.type==="enabled")console.warn(`Using Puku with ${X.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://puku.ai/docs/en/build-with-puku/adaptive-thinking`);let G=$?.timeout??this._client._options.timeout;if(!X.stream&&G==null){let Y=D8[X.model]??void 0;G=this._client.calculateNonstreamingTimeout(X.max_tokens,Y)}let Q=Q8(X.tools,X.messages);return this._client.post("/v1/messages",{body:X,timeout:G??600000,...$,headers:U([{...Z!=null?{"puku-user-profile-id":Z}:void 0},Q,$?.headers]),stream:J.stream??!1})}parse(J,$){return this.create(J,$).then((Z)=>GJ(Z,J,{logger:this._client.logger??console}))}stream(J,$){return l8.createMessage(this,J,$,{logger:this._client.logger??console})}countTokens(J,$){let{user_profile_id:Z,...X}=J;return this._client.post("/v1/messages/count_tokens",{body:X,...$,headers:U([{...Z!=null?{"puku-user-profile-id":Z}:void 0},$?.headers])})}};vZ={"puku-1.3":"November 6th, 2024","puku-1.3-100k":"November 6th, 2024","puku-instant-1.1":"November 6th, 2024","puku-instant-1.1-100k":"November 6th, 2024","puku-instant-1.2":"November 6th, 2024","puku-3-sonnet-20240229":"July 21st, 2025","puku-3-opus-20240229":"January 5th, 2026","puku-2.1":"July 21st, 2025","puku-2.0":"July 21st, 2025","puku-3-7-sonnet-latest":"February 19th, 2026"},fX=[];W2.Batches=i8});var b2;var KJ=M(()=>{_();E();I();b2=class b2 extends w{retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/models/${J}`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/models",o,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}}});var n8;var WJ=M(()=>{_();E0();I();n8=class n8 extends w{create(J,$,Z){return this._client.post(N`/v1/skills/${J}/versions`,F0({body:$,...Z},this._client,!1))}retrieve(J,$,Z){let{skill_id:X}=$;return this._client.get(N`/v1/skills/${X}/versions/${J}`,Z)}list(J,$={},Z){return this._client.getAPIList(N`/v1/skills/${J}/versions`,L,{query:$,...Z})}delete(J,$,Z){let{skill_id:X}=$;return this._client.delete(N`/v1/skills/${X}/versions/${J}`,Z)}}});var V2;var VJ=M(()=>{WJ();WJ();_();E0();I();V2=class V2 extends w{versions=new n8(this._client);create(J,$){return this._client.post("/v1/skills",F0({body:J,...$},this._client,!1))}retrieve(J,$){return this._client.get(N`/v1/skills/${J}`,$)}list(J={},$){return this._client.getAPIList("/v1/skills",L,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/skills/${J}`,$)}};V2.Versions=n8});var bZ=M(()=>{JJ();$J();ZJ();BJ();KJ();VJ()});var gZ="\\n\\nHuman:",hZ="\\n\\nAssistant:",d1,P0;var CJ=M(()=>{Q0();s8();J1();z6();c();r0();oJ();U$();O$();_();S6();bZ();q1();$J();ZJ();KJ();JJ();BJ();VJ();s8();E();O0();Q0();d1=class d1{apiKey;authToken;webhookKey;get credentials(){return this._authState.provider}_authState;_baseURLIsExplicit;_requestAuthFlags=new WeakMap;baseURL;maxRetries;timeout;logger;logLevel;fetchOptions;middleware;fetch;#J;idempotencyHeader;_options;constructor({baseURL:J=x("PUKU_BASE_URL"),apiKey:$,authToken:Z,webhookKey:X=x("PUKU_WEBHOOK_SIGNING_KEY")??null,...G}={}){if($===void 0)$=G.profile!=null?null:x("PUKU_API_KEY")??null;if(Z===void 0)Z=G.profile!=null?null:x("PUKU_AUTH_TOKEN")??null;if(G.profile!=null&&(G.credentials!=null||G.config!=null))throw TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let Q={apiKey:$,authToken:Z,webhookKey:X,...G,baseURL:J||""};if(!Q.baseURL)throw new T("Missing baseURL: pass `baseURL` to the constructor or set the PUKU_BASE_URL environment variable.");if(!Q.dangerouslyAllowBrowser&&PJ())throw new T(`It looks like you're running in a browser-like environment.
47
+ Wrap your summary in <summary></summary> tags.`;async function rX(J,$=J.messages.at(-1),Z){if(!$||$.role!=="assistant"||!$.content||typeof $.content==="string")return null;let X=$.content.filter((Y)=>Y.type==="tool_use");if(X.length===0)return null;let G=sX(J);return{role:"user",content:await Promise.all(X.map(async(Y)=>{let z=J.tools.find((B)=>("name"in B?B.name:("mcp_server_name"in B)?B.mcp_server_name:B.type)===Y.name);if(!z||!("run"in z)||!G.has(Y.name))return tX(Y);try{let B=Y.input;if("parse"in z&&z.parse)B=z.parse(B);let K=await z.run(B,{toolUse:Y,toolUseBlock:Y,signal:Z?.signal});return{type:"tool_result",tool_use_id:Y.id,content:K}}catch(B){return{type:"tool_result",tool_use_id:Y.id,content:B instanceof P?B.content:`Error: ${B instanceof Error?B.message:String(B)}`,is_error:!0}}}))}}function tX(J){return{type:"tool_result",tool_use_id:J.id,content:`Error: Tool '${J.name}' not found`,is_error:!0}}function sX(J){let $=new Set;for(let Z of J.tools)if("run"in Z)$.add(Z.name);for(let Z of J.messages){if(Z.role!=="system"||typeof Z.content==="string")continue;for(let X of Z.content)eX(X,$)}return $}function eX(J,$){switch(J.type){case"tool_removal":case"tool_addition":JG(J,$);break}}function JG(J,$){let Z=$G(J.tool);if(Z===void 0)return;if(J.type==="tool_removal")$.delete(Z);else $.add(Z)}function $G(J){switch(J.type){case"tool_reference":return J.name;default:return}}function ZG(J){if(J===null)return"stop";switch(J){case"tool_use":return"run_tools";case"pause_turn":case"compaction":return"resume";case"end_turn":case"stop_sequence":case"max_tokens":case"model_context_window_exceeded":case"refusal":return"stop";default:return x0(J),"stop"}}var P8;var LJ=M(()=>{I0();c();E();Q0();q0();P8=class P8{client;#J=!1;#$=!1;#X;#G;#Z;#Q;#B;#Y=0;constructor(J,$,Z){this.client=J;this.#X={params:{...$,messages:structuredClone($.messages)}};let X=H1($.tools,$.messages);if(this.#G={...Z,headers:U([G8("BetaToolRunner"),X.length?{[J2]:X.join(", ")}:void 0,Z?.headers])},this.#B=w2(),$.compactionControl?.enabled)console.warn('Puku: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://puku.sh/docs/')}async#z(){let J=this.#X.params.compactionControl;if(!J||!J.enabled)return!1;let $=0;if(this.#Z!==void 0)try{let z=await this.#Z;$=z.usage.input_tokens+(z.usage.cache_creation_input_tokens??0)+(z.usage.cache_read_input_tokens??0)+z.usage.output_tokens}catch{return!1}let Z=J.contextTokenThreshold??EZ;if($<Z)return!1;let X=J.model??this.#X.params.model,G=J.summaryPrompt??IZ,Q=this.#X.params.messages;if(Q[Q.length-1].role==="assistant"){let z=Q[Q.length-1];if(Array.isArray(z.content)){let B=z.content.filter((K)=>K.type!=="tool_use");if(B.length===0)Q.pop();else z.content=B}}let Y=await this.client.beta.messages.create({model:X,messages:[...Q,{role:"user",content:[{type:"text",text:G}]}],max_tokens:this.#X.params.max_tokens},{signal:this.#G.signal,headers:U([this.#G.headers,G8("compaction")])});if(Y.content[0]?.type!=="text")throw new T("Expected text response for compaction");return this.#X.params.messages=[{role:"user",content:Y.content}],!0}async*[Symbol.asyncIterator](){if(this.#J)throw new T("Cannot iterate over a consumed stream");this.#J=!0,this.#$=!0,this.#Q=void 0;try{while(!0){let J;try{if(this.#X.params.max_iterations&&this.#Y>=this.#X.params.max_iterations)break;this.#$=!1,this.#Q=void 0,this.#Y++,this.#Z=void 0;let{max_iterations:$,compactionControl:Z,...X}=this.#X.params;if(X.stream)J=this.client.beta.messages.stream({...X},this.#G),this.#Z=J.finalMessage(),this.#Z.catch(()=>{}),yield J;else this.#Z=this.client.beta.messages.create({...X,stream:!1},this.#G),yield this.#Z;if(!await this.#z()){if(!this.#$){let Y=await this.#Z,z=ZG(Y.stop_reason);this.#X.params.messages.push({role:Y.role,content:Y.content});let{container:B}=this.#X.params;if(Y.container){if(B==null)this.#X.params.container=Y.container.id;else if(typeof B==="object"&&B.id==null)this.#X.params.container={...B,id:Y.container.id}}if(z==="stop")break;if(z==="resume")continue}let Q=await this.#K(this.#X.params.messages.at(-1));if(Q)this.#X.params.messages.push(Q);else if(!this.#$)break}}finally{if(J)J.abort()}}if(!this.#Z)throw new T("ToolRunner concluded without a message from the server");this.#B.resolve(await this.#Z)}catch(J){throw this.#J=!1,this.#B.promise.catch(()=>{}),this.#B.reject(J),this.#B=w2(),J}}setMessagesParams(J){if(typeof J==="function")this.#X.params=J(this.#X.params);else this.#X.params=J;this.#$=!0,this.#Q=void 0}setRequestOptions(J){if(typeof J==="function")this.#G=J(this.#G);else this.#G={...this.#G,...J}}async generateToolResponse(J=this.#G.signal){let $=await this.#Z??this.params.messages.at(-1);if(!$)return null;return this.#K($,J)}async#K(J,$=this.#G.signal){if(this.#Q!==void 0)return this.#Q;return this.#Q=rX(this.#X.params,J,{...this.#G,signal:$}),this.#Q}done(){return this.#B.promise}async runUntilDone(){if(!this.#J)for await(let J of this);return this.done()}get params(){return this.#X.params}pushMessages(...J){this.setMessagesParams(($)=>({...$,messages:[...$.messages,...J]}))}then(J,$){return this.runUntilDone().then(J,$)}}});function xZ(J){if(!J.output_format)return J;if(J.output_config?.format)throw new T("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:$,...Z}=J;return{...Z,output_config:{...J.output_config,format:$}}}var yZ,XG,c0;var DJ=M(()=>{D2();MJ();m1();E();q0();OJ();_Z();LJ();I0();MJ();LJ();I0();yZ={"puku-1.3":"November 6th, 2024","puku-1.3-100k":"November 6th, 2024","puku-instant-1.1":"November 6th, 2024","puku-instant-1.1-100k":"November 6th, 2024","puku-instant-1.2":"November 6th, 2024","puku-3-sonnet-20240229":"July 21st, 2025","puku-3-opus-20240229":"January 5th, 2026","puku-2.1":"July 21st, 2025","puku-2.0":"July 21st, 2025","puku-3-7-sonnet-latest":"February 19th, 2026"},XG=[];c0=class c0 extends w{batches=new L8(this._client);create(J,$){let Z=xZ(J),{betas:X,user_profile_id:G,...Q}=Z;if(Q.model in yZ)console.warn(`The Puku SDK model '${Q.model}' is deprecated and will reach end-of-life on ${yZ[Q.model]}
48
+ Please migrate to a newer model. Visit https://puku.ai/docs/resources/model-deprecations for more information.`);if(XG.includes(Q.model)&&Q.thinking&&Q.thinking.type==="enabled")console.warn(`Using Puku with ${Q.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://puku.ai/docs/en/build-with-puku/adaptive-thinking`);let Y=$?.timeout??this._client._options.timeout;if(!Q.stream&&Y==null){let B=D8[Q.model]??void 0;Y=this._client.calculateNonstreamingTimeout(Q.max_tokens,B)}let z=Q8(Q.tools,Q.messages);return this._client.post("/v1/messages?beta=true",{body:Q,timeout:Y??600000,...$,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0,...G!=null?{"puku-user-profile-id":G}:void 0},z,$?.headers]),stream:Z.stream??!1})}parse(J,$){return $={...$,headers:U([{"puku-beta":[...J.betas??[],"structured-outputs-2025-12-15"].toString()},$?.headers])},this.create(J,$).then((Z)=>wJ(Z,J,{logger:this._client.logger??console}))}stream(J,$){return j8.createMessage(this,J,$)}countTokens(J,$){let Z=xZ(J),{betas:X,user_profile_id:G,...Q}=Z;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Q,...$,headers:U([{"puku-beta":[...X??[],"token-counting-2024-11-01"].toString(),...G!=null?{"puku-user-profile-id":G}:void 0},$?.headers])})}toolRunner(J,$){return new P8(this._client,J,$)}};c0.Batches=L8;c0.BetaToolRunner=P8;c0.ToolError=P});var S8;var jJ=M(()=>{_();I();S8=class S8 extends w{retrieve(J,$){return this._client.get(N`/v1/organizations/api_keys/${J}?beta=true`,$)}update(J,$,Z){return this._client.post(N`/v1/organizations/api_keys/${J}?beta=true`,{body:$,...Z})}list(J={},$){return this._client.getAPIList("/v1/organizations/api_keys?beta=true",o,{query:J,...$})}}});var _8;var PJ=M(()=>{_8=class _8 extends w{retrieve(J){return this._client.get("/v1/organizations/compliance_settings?beta=true",J)}update(J,$){return this._client.post("/v1/organizations/compliance_settings?beta=true",{body:J,...$})}}});var E8;var SJ=M(()=>{_();I();E8=class E8 extends w{create(J,$){return this._client.post("/v1/organizations/external_keys?beta=true",{body:J,...$})}retrieve(J,$){return this._client.get(N`/v1/organizations/external_keys/${J}?beta=true`,$)}update(J,$,Z){return this._client.post(N`/v1/organizations/external_keys/${J}?beta=true`,{body:$,...Z})}list(J={},$){return this._client.getAPIList("/v1/organizations/external_keys?beta=true",L,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/organizations/external_keys/${J}?beta=true`,$)}validate(J,$){return this._client.post(N`/v1/organizations/external_keys/${J}/validate?beta=true`,$)}}});var I8;var _J=M(()=>{_();I();I8=class I8 extends w{create(J,$){return this._client.post("/v1/organizations/invites?beta=true",{body:J,...$})}retrieve(J,$){return this._client.get(N`/v1/organizations/invites/${J}?beta=true`,$)}list(J={},$){return this._client.getAPIList("/v1/organizations/invites?beta=true",o,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/organizations/invites/${J}?beta=true`,$)}}});var y8;var EJ=M(()=>{_();y8=class y8 extends w{list(J={},$){return this._client.getAPIList("/v1/organizations/rate_limits?beta=true",L,{query:J,...$})}}});var x8;var IJ=M(()=>{_();I();x8=class x8 extends w{retrieve(J,$){return this._client.get(N`/v1/organizations/users/${J}?beta=true`,$)}update(J,$,Z){return this._client.post(N`/v1/organizations/users/${J}?beta=true`,{body:$,...Z})}list(J={},$){return this._client.getAPIList("/v1/organizations/users?beta=true",o,{query:J,...$})}remove(J,$){return this._client.delete(N`/v1/organizations/users/${J}?beta=true`,$)}}});var k8;var yJ=M(()=>{_();E();I();k8=class k8 extends w{create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/organizations/federation_issuers?beta=true",{body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/organizations/federation_issuers/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/federation_issuers/${J}?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/organizations/federation_issuers?beta=true",L,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/organizations/federation_issuers/${J}/archive?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}}});var f8;var xJ=M(()=>{_();E();I();f8=class f8 extends w{list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/organizations/federation_rules/${J}/workspaces?beta=true`,L,{query:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}add(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/federation_rules/${J}/workspaces?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}remove(J,$,Z){let{federation_rule_id:X,betas:G}=$;return this._client.delete(N`/v1/organizations/federation_rules/${X}/workspaces/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}}});var S2;var kJ=M(()=>{xJ();xJ();_();E();I();S2=class S2 extends w{workspaces=new f8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/organizations/federation_rules?beta=true",{body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/organizations/federation_rules/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/federation_rules/${J}?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/organizations/federation_rules?beta=true",L,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/organizations/federation_rules/${J}/archive?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}};S2.Workspaces=f8});var K2;var fJ=M(()=>{yJ();yJ();kJ();kJ();K2=class K2 extends w{issuers=new k8(this._client);rules=new S2(this._client)};K2.Issuers=k8;K2.Rules=S2});var v8;var vJ=M(()=>{_();E();I();v8=class v8 extends w{list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/organizations/service_accounts/${J}/workspaces?beta=true`,L,{query:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}add(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/service_accounts/${J}/workspaces?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}remove(J,$,Z){let{service_account_id:X,betas:G}=$;return this._client.delete(N`/v1/organizations/service_accounts/${X}/workspaces/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}}});var _2;var bJ=M(()=>{vJ();vJ();_();E();I();_2=class _2 extends w{workspaces=new v8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/organizations/service_accounts?beta=true",{body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/organizations/service_accounts/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/service_accounts/${J}?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/organizations/service_accounts?beta=true",L,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/organizations/service_accounts/${J}/archive?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}};_2.Workspaces=v8});var b8;var gJ=M(()=>{_();I();b8=class b8 extends w{retrieve(J,$,Z){let{workspace_id:X}=$;return this._client.get(N`/v1/organizations/workspaces/${X}/members/${J}?beta=true`,Z)}update(J,$,Z){let{workspace_id:X,...G}=$;return this._client.post(N`/v1/organizations/workspaces/${X}/members/${J}?beta=true`,{body:G,...Z})}list(J,$={},Z){return this._client.getAPIList(N`/v1/organizations/workspaces/${J}/members?beta=true`,o,{query:$,...Z})}add(J,$,Z){return this._client.post(N`/v1/organizations/workspaces/${J}/members?beta=true`,{body:$,...Z})}remove(J,$,Z){let{workspace_id:X}=$;return this._client.delete(N`/v1/organizations/workspaces/${X}/members/${J}?beta=true`,Z)}}});var g8;var hJ=M(()=>{_();I();g8=class g8 extends w{list(J,$={},Z){return this._client.getAPIList(N`/v1/organizations/workspaces/${J}/rate_limits?beta=true`,L,{query:$,...Z})}}});var h8;var mJ=M(()=>{_();E();I();h8=class h8 extends w{retrieve(J,$,Z){let{workspace_id:X,betas:G}=$;return this._client.get(N`/v1/organizations/workspaces/${X}/service_accounts/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}update(J,$,Z){let{workspace_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/organizations/workspaces/${X}/service_accounts/${J}?beta=true`,{body:Q,...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/organizations/workspaces/${J}/service_accounts?beta=true`,L,{query:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}add(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/organizations/workspaces/${J}/service_accounts?beta=true`,{body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}remove(J,$,Z){let{workspace_id:X,betas:G}=$;return this._client.delete(N`/v1/organizations/workspaces/${X}/service_accounts/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}}});var p0;var uJ=M(()=>{gJ();gJ();hJ();hJ();mJ();mJ();_();E();I();p0=class p0 extends w{rateLimits=new g8(this._client);members=new b8(this._client);serviceAccounts=new h8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/organizations/workspaces?beta=true",{body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}retrieve(J,$){return this._client.get(N`/v1/organizations/workspaces/${J}?beta=true`,$)}update(J,$,Z){return this._client.post(N`/v1/organizations/workspaces/${J}?beta=true`,{body:$,...Z})}list(J={},$){return this._client.getAPIList("/v1/organizations/workspaces?beta=true",o,{query:J,...$})}archive(J,$){return this._client.post(N`/v1/organizations/workspaces/${J}/archive?beta=true`,$)}};p0.RateLimits=g8;p0.Members=b8;p0.ServiceAccounts=h8});var C0;var dJ=M(()=>{jJ();jJ();PJ();PJ();SJ();SJ();_J();_J();EJ();EJ();IJ();IJ();fJ();fJ();bJ();bJ();uJ();uJ();C0=class C0 extends w{apiKeys=new S8(this._client);externalKeys=new E8(this._client);federation=new K2(this._client);invites=new I8(this._client);serviceAccounts=new _2(this._client);users=new x8(this._client);workspaces=new p0(this._client);rateLimits=new y8(this._client);complianceSettings=new _8(this._client);retrieve(J){return this._client.get("/v1/organizations/me?beta=true",J)}};C0.APIKeys=S8;C0.ExternalKeys=E8;C0.Federation=K2;C0.Invites=I8;C0.ServiceAccounts=_2;C0.Users=x8;C0.Workspaces=p0;C0.RateLimits=y8;C0.ComplianceSettings=_8});var E2;var cJ=M(()=>{_();E();I();E1();E1();E2=class E2 extends w{list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/sessions/${J}/events?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}send(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/sessions/${J}/events?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}stream(J,$={},Z){let{betas:X,...G}=$??{};return this._client.get(N`/v1/sessions/${J}/events/stream?beta=true`,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers]),stream:!0})}toolRunner(J,$){return new Z2(J,{...$,client:this._client})}};E2.SessionToolRunner=Z2});var m8;var pJ=M(()=>{_();E();I();m8=class m8 extends w{retrieve(J,$,Z){let{session_id:X,betas:G}=$;return this._client.get(N`/v1/sessions/${X}/resources/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{session_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/sessions/${X}/resources/${J}?beta=true`,{body:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/sessions/${J}/resources?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}delete(J,$,Z){let{session_id:X,betas:G}=$;return this._client.delete(N`/v1/sessions/${X}/resources/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}add(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/sessions/${J}/resources?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}}});var u8;var lJ=M(()=>{_();E();I();u8=class u8 extends w{list(J,$,Z){let{session_id:X,betas:G,...Q}=$;return this._client.getAPIList(N`/v1/sessions/${X}/threads/${J}/events?beta=true`,L,{query:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}stream(J,$,Z){let{session_id:X,betas:G,...Q}=$;return this._client.get(N`/v1/sessions/${X}/threads/${J}/stream?beta=true`,{query:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers]),stream:!0})}}});var I2;var iJ=M(()=>{lJ();lJ();_();E();I();I2=class I2 extends w{events=new u8(this._client);retrieve(J,$,Z){let{session_id:X,betas:G}=$;return this._client.get(N`/v1/sessions/${X}/threads/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/sessions/${J}/threads?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$,Z){let{session_id:X,betas:G}=$;return this._client.post(N`/v1/sessions/${X}/threads/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}};I2.Events=u8});var l0;var nJ=M(()=>{cJ();cJ();pJ();pJ();iJ();iJ();_();E();I();l0=class l0 extends w{events=new E2(this._client);resources=new m8(this._client);threads=new I2(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/sessions?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/sessions/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/sessions/${J}?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/sessions?beta=true",H6,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/sessions/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/sessions/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}};l0.Events=E2;l0.Resources=m8;l0.Threads=I2});var d8;var aJ=M(()=>{_();E();E0();I();d8=class d8 extends w{create(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/skills/${J}/versions?beta=true`,F0({body:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])},this._client,!1))}retrieve(J,$,Z){let{skill_id:X,betas:G}=$;return this._client.get(N`/v1/skills/${X}/versions/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/skills/${J}/versions?beta=true`,L,{query:G,...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}delete(J,$,Z){let{skill_id:X,betas:G}=$;return this._client.delete(N`/v1/skills/${X}/versions/${J}?beta=true`,{...Z,headers:U([{...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers])})}download(J,$,Z){let{skill_id:X,betas:G}=$;return this._client.get(N`/v1/skills/${X}/versions/${J}/content?beta=true`,{...Z,headers:U([{Accept:"application/binary",...G?.toString()!=null?{"puku-beta":G?.toString()}:void 0},Z?.headers]),__binaryResponse:!0})}}});var y2;var oJ=M(()=>{aJ();aJ();_();E();E0();I();y2=class y2 extends w{versions=new d8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/skills?beta=true",F0({body:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])},this._client,!1))}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/skills/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/skills?beta=true",L,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/skills/${J}?beta=true`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}};y2.Versions=d8});var c8;var rJ=M(()=>{_();E();I();c8=class c8 extends w{create(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/tunnels/${J}/certificates?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}retrieve(J,$,Z){let{tunnel_id:X,betas:G}=$;return this._client.get(N`/v1/tunnels/${X}/certificates/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/tunnels/${J}/certificates?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}archive(J,$,Z){let{tunnel_id:X,betas:G}=$;return this._client.post(N`/v1/tunnels/${X}/certificates/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}}});var x2;var tJ=M(()=>{rJ();rJ();_();E();I();x2=class x2 extends w{certificates=new c8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/tunnels?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"mcp-tunnels-2026-06-22"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/tunnels/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/tunnels?beta=true",L,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"mcp-tunnels-2026-06-22"].toString()},$?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/tunnels/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}revealToken(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/tunnels/${J}/reveal_token?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}rotateToken(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/tunnels/${J}/rotate_token?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"mcp-tunnels-2026-06-22"].toString()},Z?.headers])})}};x2.Certificates=c8});var p8;var sJ=M(()=>{_();E();I();p8=class p8 extends w{create(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/vaults/${J}/credentials?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}retrieve(J,$,Z){let{vault_id:X,betas:G}=$;return this._client.get(N`/v1/vaults/${X}/credentials/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{vault_id:X,betas:G,...Q}=$;return this._client.post(N`/v1/vaults/${X}/credentials/${J}?beta=true`,{body:Q,...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J,$={},Z){let{betas:X,...G}=$??{};return this._client.getAPIList(N`/v1/vaults/${J}/credentials?beta=true`,L,{query:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}delete(J,$,Z){let{vault_id:X,betas:G}=$;return this._client.delete(N`/v1/vaults/${X}/credentials/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$,Z){let{vault_id:X,betas:G}=$;return this._client.post(N`/v1/vaults/${X}/credentials/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}mcpOAuthValidate(J,$,Z){let{vault_id:X,betas:G}=$;return this._client.post(N`/v1/vaults/${X}/credentials/${J}/mcp_oauth_validate?beta=true`,{...Z,headers:U([{"puku-beta":[...G??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}}});var k2;var eJ=M(()=>{sJ();sJ();_();E();I();k2=class k2 extends w{credentials=new p8(this._client);create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/vaults?beta=true",{body:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/vaults/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}update(J,$,Z){let{betas:X,...G}=$;return this._client.post(N`/v1/vaults/${J}?beta=true`,{body:G,...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/vaults?beta=true",L,{query:X,...$,headers:U([{"puku-beta":[...Z??[],"managed-agents-2026-04-01"].toString()},$?.headers])})}delete(J,$={},Z){let{betas:X}=$??{};return this._client.delete(N`/v1/vaults/${J}?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}archive(J,$={},Z){let{betas:X}=$??{};return this._client.post(N`/v1/vaults/${J}/archive?beta=true`,{...Z,headers:U([{"puku-beta":[...X??[],"managed-agents-2026-04-01"].toString()},Z?.headers])})}};k2.Credentials=p8});var i;var J4=M(()=>{E6();E6();I6();I6();y6();y6();x6();x6();k6();k6();f6();f6();g6();g6();m6();m6();CJ();CJ();FJ();FJ();DJ();DJ();dJ();dJ();nJ();nJ();oJ();oJ();tJ();tJ();eJ();eJ();i=class i extends w{models=new z8(this._client);messages=new c0(this._client);agents=new M2(this._client);environments=new L2(this._client);sessions=new l0(this._client);deployments=new Z8(this._client);deploymentRuns=new $8(this._client);vaults=new k2(this._client);memoryStores=new B2(this._client);files=new Y8(this._client);skills=new y2(this._client);webhooks=new V8(this._client);userProfiles=new B8(this._client);dreams=new X8(this._client);tunnels=new x2(this._client);organization=new C0(this._client)};i.Models=z8;i.Messages=c0;i.Agents=M2;i.Environments=L2;i.Sessions=l0;i.Deployments=Z8;i.DeploymentRuns=$8;i.Vaults=k2;i.MemoryStores=B2;i.Files=Y8;i.Skills=y2;i.Webhooks=V8;i.UserProfiles=B8;i.Dreams=X8;i.Tunnels=x2;i.Organization=C0});var f2;var $4=M(()=>{E();f2=class f2 extends w{create(J,$){let{betas:Z,...X}=J;return this._client.post("/v1/complete",{body:X,timeout:this._client._options.timeout??600000,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers]),stream:J.stream??!1})}}});var v2;var Z4=M(()=>{_();E();q0();E0();I();v2=class v2 extends w{list(J={},$){return this._client.getAPIList("/v1/files",L,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/files/${J}`,$)}download(J,$){return this._client.get(N`/v1/files/${J}/content`,{...$,headers:U([{Accept:"application/binary"},$?.headers]),__binaryResponse:!0})}retrieveMetadata(J,$){return this._client.get(N`/v1/files/${J}`,$)}upload(J,$){return this._client.post("/v1/files",F0({body:J,...$,headers:U([L1(J.file),$?.headers])},this._client))}}});function kZ(J){return J?.output_config?.format}function X4(J,$,Z){let X=kZ($);if(!$||!("parse"in(X??{})))return{...J,content:J.content.map((G)=>{if(G.type==="text")return Object.defineProperty({...G},"parsed_output",{value:null,enumerable:!1});return G}),parsed_output:null};return G4(J,$,Z)}function G4(J,$,Z){let X=null,G=J.content.map((Q)=>{if(Q.type==="text"){let Y=xG($,Q.text);if(X===null)X=Y;return Object.defineProperty({...Q},"parsed_output",{value:Y,enumerable:!1})}return Q});return{...J,content:G,parsed_output:X}}function xG(J,$){let Z=kZ(J);if(Z?.type!=="json_schema")return null;try{if("parse"in Z)return Z.parse($);return JSON.parse($)}catch(X){throw new T(`Failed to parse structured output: ${X}`)}}var Q4=M(()=>{c()});function Y4(J){return J.type==="tool_use"||J.type==="server_tool_use"}var l8;var fZ=M(()=>{q0();Q0();D2();RJ();Q4();AJ();l8=class l8{messages=[];receivedMessages=[];#J;#$=null;controller=new AbortController;#X;#G=()=>{};#Z=()=>{};#Q;#B=()=>{};#Y=()=>{};#z={};#K=!1;#C=!1;#U=!1;#V=!1;#F;#W;#M;#q;constructor(J,$){this.#X=new Promise((Z,X)=>{this.#G=Z,this.#Z=X}),this.#Q=new Promise((Z,X)=>{this.#B=Z,this.#Y=X}),this.#X.catch(()=>{}),this.#Q.catch(()=>{}),this.#$=J,this.#q=$?.logger??console}get response(){return this.#F}get request_id(){return this.#W}get workspace_id(){return this.#M}async withResponse(){this.#V=!0;let J=await this.#X;if(!J)throw Error("Could not resolve a `Response` object");return{data:this,response:J,request_id:J.headers.get("request-id"),workspace_id:J.headers.get("puku-workspace-id")}}static fromReadableStream(J){let $=new l8(null);return $._run(()=>$._fromReadableStream(J)),$}static createMessage(J,$,Z,{logger:X}={}){let G=new l8($,{logger:X});for(let Q of $.messages)G._addMessageParam(Q);return G.#$={...$,stream:!0},G._run(()=>G._createMessage(J,{...$,stream:!0},{...Z,headers:{...Z?.headers,[A1]:"stream"}})),G}_run(J){J().then(()=>{this._emitFinal(),this._emit("end")},this.#T)}_addMessageParam(J){this.messages.push(J)}_addMessage(J,$=!0){if(this.receivedMessages.push(J),$)this._emit("message",J)}async _createMessage(J,$,Z){let X=Z?.signal,G;if(X){if(X.aborted)this.controller.abort();G=this.controller.abort.bind(this.controller),X.addEventListener("abort",G)}try{this.#N();let{response:Q,data:Y}=await J.create({...$,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(Q);for await(let z of Y)this.#R(z);if(Y.controller.signal?.aborted)throw new Z0;this.#w()}finally{if(X&&G)X.removeEventListener("abort",G)}}_connected(J){if(this.ended)return;this.#F=J,this.#W=J?.headers.get("request-id"),this.#M=J?.headers.get("puku-workspace-id"),this.#G(J),this._emit("connect")}get ended(){return this.#K}get errored(){return this.#C}get aborted(){return this.#U}abort(){this.controller.abort()}on(J,$){return(this.#z[J]||(this.#z[J]=[])).push({listener:$}),this}off(J,$){let Z=this.#z[J];if(!Z)return this;let X=Z.findIndex((G)=>G.listener===$);if(X>=0)Z.splice(X,1);return this}once(J,$){return(this.#z[J]||(this.#z[J]=[])).push({listener:$,once:!0}),this}emitted(J){return new Promise(($,Z)=>{if(this.#V=!0,J!=="error")this.once("error",Z);this.once(J,$)})}async done(){this.#V=!0,await this.#Q}get currentMessage(){return this.#J}#O(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)}async finalMessage(){return await this.done(),this.#O()}#A(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");let J=this.receivedMessages.at(-1).content.filter(($)=>$.type==="text").map(($)=>$.text);if(J.length===0)throw new T("stream ended without producing a content block with type=text");return J.join(" ")}async finalText(){return await this.done(),this.#A()}#T=(J)=>{if(this.#C=!0,U0(J))J=new Z0;if(J instanceof Z0)return this.#U=!0,this._emit("abort",J);if(J instanceof T)return this._emit("error",J);if(J instanceof Error){let $=new T(J.message);return $.cause=J,this._emit("error",$)}return this._emit("error",new T(String(J)))};_emit(J,...$){if(this.#K)return;if(J==="end")this.#K=!0,this.#B();let Z=this.#z[J];if(Z)this.#z[J]=Z.filter((X)=>!X.once),Z.forEach(({listener:X})=>X(...$));if(J==="abort"){let X=$[0];if(!this.#V&&!Z?.length)Promise.reject(X);this.#Z(X),this.#Y(X),this._emit("end");return}if(J==="error"){let X=$[0];if(!this.#V&&!Z?.length)Promise.reject(X);this.#Z(X),this.#Y(X),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",this.#O())}#N(){if(this.ended)return;this.#J=void 0}#R(J){if(this.ended)return;let $=this.#H(J);switch(this._emit("streamEvent",J,$),J.type){case"content_block_delta":{let Z=$.content.at(-1);switch(J.delta.type){case"text_delta":{if(Z.type==="text")this._emit("text",J.delta.text,Z.text||"");break}case"citations_delta":{if(Z.type==="text")this._emit("citation",J.delta.citation,Z.citations??[]);break}case"input_json_delta":{if(Y4(Z)&&this.#z.inputJson?.length)this._emit("inputJson",J.delta.partial_json,Z.input);break}case"thinking_delta":{if(Z.type==="thinking")this._emit("thinking",J.delta.thinking,Z.thinking);break}case"signature_delta":{if(Z.type==="thinking")this._emit("signature",Z.signature);break}default:x0(J.delta)}break}case"message_stop":{this._addMessageParam($),this._addMessage(X4($,this.#$,{logger:this.#q}),!0);break}case"content_block_stop":{this._emit("contentBlock",$.content.at(-1));break}case"message_start":{this.#J=$;break}case"content_block_start":case"message_delta":break}}#w(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let J=this.#J;if(!J)throw new T("request ended without sending any chunks");return this.#J=void 0,X4(J,this.#$,{logger:this.#q})}async _fromReadableStream(J,$){let Z=$?.signal,X;if(Z){if(Z.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),Z.addEventListener("abort",X)}try{this.#N(),this._connected(null);let G=s.fromReadableStream(J,this.controller);for await(let Q of G)this.#R(Q);if(G.controller.signal?.aborted)throw new Z0;this.#w()}finally{if(Z&&X)Z.removeEventListener("abort",X)}}#H(J){let $=this.#J;if(J.type==="message_start"){if($)throw new T(`Unexpected event order, got ${J.type} before receiving "message_stop"`);return J.message}if(!$)throw new T(`Unexpected event order, got ${J.type} before "message_start"`);switch(J.type){case"message_stop":return $;case"message_delta":if($.stop_reason=J.delta.stop_reason,$.stop_sequence=J.delta.stop_sequence,$.stop_details=J.delta.stop_details,$.usage.output_tokens=J.usage.output_tokens,J.delta.container!=null)$.container=J.delta.container;if(J.usage.input_tokens!=null)$.usage.input_tokens=J.usage.input_tokens;if(J.usage.cache_creation_input_tokens!=null)$.usage.cache_creation_input_tokens=J.usage.cache_creation_input_tokens;if(J.usage.cache_read_input_tokens!=null)$.usage.cache_read_input_tokens=J.usage.cache_read_input_tokens;if(J.usage.server_tool_use!=null)$.usage.server_tool_use=J.usage.server_tool_use;if(J.usage.output_tokens_details!=null)$.usage.output_tokens_details=J.usage.output_tokens_details;return $;case"content_block_start":return $.content.push({...J.content_block}),$;case"content_block_delta":{let Z=$.content.at(J.index);switch(J.delta.type){case"text_delta":{if(Z?.type==="text")$.content[J.index]={...Z,text:(Z.text||"")+J.delta.text};break}case"citations_delta":{if(Z?.type==="text")$.content[J.index]={...Z,citations:[...Z.citations??[],J.delta.citation]};break}case"input_json_delta":{if(Z&&Y4(Z)){let X=(Z[d0]||"")+J.delta.partial_json;$.content[J.index]=u1(Z,X)}break}case"thinking_delta":{if(Z?.type==="thinking")$.content[J.index]={...Z,thinking:Z.thinking+J.delta.thinking};break}case"signature_delta":{if(Z?.type==="thinking")$.content[J.index]={...Z,signature:J.delta.signature};break}default:x0(J.delta)}return $}case"content_block_stop":{let Z=$.content.at(J.index);if(Z&&Y4(Z)&&d0 in Z)Object.defineProperty(Z,"input",{value:Z.input,enumerable:!0,configurable:!0,writable:!0});return $}}}[Symbol.asyncIterator](){let J=[],$=[],Z=!1;return this.on("streamEvent",(X)=>{let G=$.shift();if(G)G.resolve(X);else J.push(X)}),this.on("end",()=>{Z=!0;for(let X of $)X.resolve(void 0);$.length=0}),this.on("abort",(X)=>{Z=!0;for(let G of $)G.reject(X);$.length=0}),this.on("error",(X)=>{Z=!0;for(let G of $)G.reject(X);$.length=0}),{next:async()=>{if(!J.length){if(Z)return{value:void 0,done:!0};return new Promise((G,Q)=>$.push({resolve:G,reject:Q})).then((G)=>G?{value:G,done:!1}:{value:void 0,done:!0})}return{value:J.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var i8;var z4=M(()=>{_();E();qJ();D2();I();i8=class i8 extends w{create(J,$){let{user_profile_id:Z,...X}=J;return this._client.post("/v1/messages/batches",{body:X,...$,headers:U([{...Z!=null?{"puku-user-profile-id":Z}:void 0},$?.headers])})}retrieve(J,$){return this._client.get(N`/v1/messages/batches/${J}`,$)}list(J={},$){return this._client.getAPIList("/v1/messages/batches",o,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/messages/batches/${J}`,$)}cancel(J,$){return this._client.post(N`/v1/messages/batches/${J}/cancel`,$)}async results(J,$){let Z=await this.retrieve(J);if(!Z.results_url)throw new T(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);return this._client.get(Z.results_url,{...$,headers:U([{Accept:"application/binary"},$?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((X,G)=>j2.fromResponse(G.response,G.controller))}}});var W2,vZ,fG;var B4=M(()=>{E();q0();fZ();Q4();z4();z4();m1();W2=class W2 extends w{batches=new i8(this._client);create(J,$){let{user_profile_id:Z,...X}=J;if(X.model in vZ)console.warn(`The Puku SDK model '${X.model}' is deprecated and will reach end-of-life on ${vZ[X.model]}
49
+ Please migrate to a newer model. Visit https://puku.ai/docs/resources/model-deprecations for more information.`);if(fG.includes(X.model)&&X.thinking&&X.thinking.type==="enabled")console.warn(`Using Puku with ${X.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://puku.ai/docs/en/build-with-puku/adaptive-thinking`);let G=$?.timeout??this._client._options.timeout;if(!X.stream&&G==null){let Y=D8[X.model]??void 0;G=this._client.calculateNonstreamingTimeout(X.max_tokens,Y)}let Q=Q8(X.tools,X.messages);return this._client.post("/v1/messages",{body:X,timeout:G??600000,...$,headers:U([{...Z!=null?{"puku-user-profile-id":Z}:void 0},Q,$?.headers]),stream:J.stream??!1})}parse(J,$){return this.create(J,$).then((Z)=>G4(Z,J,{logger:this._client.logger??console}))}stream(J,$){return l8.createMessage(this,J,$,{logger:this._client.logger??console})}countTokens(J,$){let{user_profile_id:Z,...X}=J;return this._client.post("/v1/messages/count_tokens",{body:X,...$,headers:U([{...Z!=null?{"puku-user-profile-id":Z}:void 0},$?.headers])})}};vZ={"puku-1.3":"November 6th, 2024","puku-1.3-100k":"November 6th, 2024","puku-instant-1.1":"November 6th, 2024","puku-instant-1.1-100k":"November 6th, 2024","puku-instant-1.2":"November 6th, 2024","puku-3-sonnet-20240229":"July 21st, 2025","puku-3-opus-20240229":"January 5th, 2026","puku-2.1":"July 21st, 2025","puku-2.0":"July 21st, 2025","puku-3-7-sonnet-latest":"February 19th, 2026"},fG=[];W2.Batches=i8});var b2;var K4=M(()=>{_();E();I();b2=class b2 extends w{retrieve(J,$={},Z){let{betas:X}=$??{};return this._client.get(N`/v1/models/${J}`,{...Z,headers:U([{...X?.toString()!=null?{"puku-beta":X?.toString()}:void 0},Z?.headers])})}list(J={},$){let{betas:Z,...X}=J??{};return this._client.getAPIList("/v1/models",o,{query:X,...$,headers:U([{...Z?.toString()!=null?{"puku-beta":Z?.toString()}:void 0},$?.headers])})}}});var n8;var W4=M(()=>{_();E0();I();n8=class n8 extends w{create(J,$,Z){return this._client.post(N`/v1/skills/${J}/versions`,F0({body:$,...Z},this._client,!1))}retrieve(J,$,Z){let{skill_id:X}=$;return this._client.get(N`/v1/skills/${X}/versions/${J}`,Z)}list(J,$={},Z){return this._client.getAPIList(N`/v1/skills/${J}/versions`,L,{query:$,...Z})}delete(J,$,Z){let{skill_id:X}=$;return this._client.delete(N`/v1/skills/${X}/versions/${J}`,Z)}}});var V2;var V4=M(()=>{W4();W4();_();E0();I();V2=class V2 extends w{versions=new n8(this._client);create(J,$){return this._client.post("/v1/skills",F0({body:J,...$},this._client,!1))}retrieve(J,$){return this._client.get(N`/v1/skills/${J}`,$)}list(J={},$){return this._client.getAPIList("/v1/skills",L,{query:J,...$})}delete(J,$){return this._client.delete(N`/v1/skills/${J}`,$)}};V2.Versions=n8});var bZ=M(()=>{J4();$4();Z4();B4();K4();V4()});var gZ="\\n\\nHuman:",hZ="\\n\\nAssistant:",d1,P0;var C4=M(()=>{Q0();s8();J1();z6();c();r0();o4();U$();O$();_();S6();bZ();q1();$4();Z4();K4();J4();B4();V4();s8();E();O0();Q0();d1=class d1{apiKey;authToken;webhookKey;get credentials(){return this._authState.provider}_authState;_baseURLIsExplicit;_requestAuthFlags=new WeakMap;baseURL;maxRetries;timeout;logger;logLevel;fetchOptions;middleware;fetch;#J;idempotencyHeader;_options;constructor({baseURL:J=x("PUKU_BASE_URL"),apiKey:$,authToken:Z,webhookKey:X=x("PUKU_WEBHOOK_SIGNING_KEY")??null,...G}={}){if($===void 0)$=G.profile!=null?null:x("PUKU_API_KEY")??null;if(Z===void 0)Z=G.profile!=null?null:x("PUKU_AUTH_TOKEN")??null;if(G.profile!=null&&(G.credentials!=null||G.config!=null))throw TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let Q={apiKey:$,authToken:Z,webhookKey:X,...G,baseURL:J||""};if(!Q.baseURL)throw new T("Missing baseURL: pass `baseURL` to the constructor or set the PUKU_BASE_URL environment variable.");if(!Q.dangerouslyAllowBrowser&&P4())throw new T(`It looks like you're running in a browser-like environment.
50
50
 
51
51
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
52
52
  If you understand the risks and have appropriate mitigations in place,
53
53
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
54
54
 
55
55
  new PukuAI({ apiKey, dangerouslyAllowBrowser: true });
56
- `);if(this.baseURL=Q.baseURL,this.baseURL.endsWith("/v1"))this.baseURL=this.baseURL.slice(0,-3);this._baseURLIsExplicit=G.__baseURLIsExplicit??!!J,this.timeout=Q.timeout??d1.DEFAULT_TIMEOUT,this.logger=Q.logger??console,this.logLevel=s2,this.logLevel=C1(Q.logLevel,"ClientOptions.logLevel",k(this))??C1(x("PUKU_LOG"),"process.env['PUKU_LOG']",k(this))??s2,this.fetchOptions=Q.fetchOptions,this.maxRetries=Q.maxRetries??2,this.fetch=Q.fetch??IJ(),this.#J=xJ,this.middleware=[...Q.middleware??[]];let Y=x("PUKU_CUSTOM_HEADERS");if(Y){let B={};for(let K of Y.split(`
57
- `)){let W=K.indexOf(":");if(W>=0)B[K.substring(0,W).trim()]=K.substring(W+1).trim()}Q.defaultHeaders={...B,...Q.defaultHeaders}}let z=G.__auth;if(delete Q.__auth,delete Q.__baseURLIsExplicit,this._options=Q,this.apiKey=typeof $==="string"?$:null,this.authToken=Z,this.webhookKey=X,z){if(this._authState=z,!this._baseURLIsExplicit&&z.baseURL)this.baseURL=z.baseURL}else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let B=Q.credentials??null;if(B)this._authState.provider=B,this._authState.tokenCache=this._makeTokenCache(B);else if(Q.config!=null){let K=w6(Q.config,this._credentialResolverOptions());this._authState.provider=K.provider,this._authState.tokenCache=this._makeTokenCache(K.provider),this._authState.extraHeaders=K.extraHeaders,this._applyCredentialBaseURL(K.baseURL)}else if(Q.profile!=null)this._authState.resolution=this._resolveDefaultCredentials(Q.profile);else if(this._shouldResolveDefaultCredentials())this._authState.resolution=this._resolveDefaultCredentials()}}_shouldResolveDefaultCredentials(){return!0}_applyCredentialBaseURL(J){if(!J)return;let $=J.replace(/\/+$/,"");if(this._authState.baseURL=$,!this._baseURLIsExplicit)this.baseURL=$}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:(J)=>{k(this).debug("credential cache write failed (best-effort)",J)},onSafetyWarning:(J)=>{k(this).warn(J)}}}_credentialsFetch(){return A6(this.fetch,this.middleware,void 0,this)}_makeTokenCache(J){return new C6(J,($)=>{k(this).debug("advisory token refresh failed; serving cached token",$)})}withOptions(J){let $="credentials"in J||"config"in J||"profile"in J,Z="apiKey"in J||"authToken"in J||$,X={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...$?{credentials:void 0,config:void 0,profile:void 0}:{},...J,__auth:Z?void 0:this._authState,__baseURLIsExplicit:"baseURL"in J?!0:this._baseURLIsExplicit};return new this.constructor(X)}async _resolveDefaultCredentials(J){try{let $=await C$(this._credentialResolverOptions(),J);if($)this._authState.provider=$.provider,this._authState.tokenCache=this._makeTokenCache($.provider),this._authState.extraHeaders=$.extraHeaders,this._applyCredentialBaseURL($.baseURL);else if(J!=null)throw new T(`Profile "${J}" could not be resolved (no <config_dir>/configs/${J}.json found).`)}catch($){this._authState.error=$}finally{this._authState.resolution=null}}#$(){return this.baseURL!==""}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:J,nulls:$}){if(J.get("x-api-key")||J.get("authorization"))return;if(this._authState.error)throw this._authState.error;if(this._authState.tokenCache||this._authState.resolution)return;if(this.apiKey&&J.get("x-api-key"))return;if($.has("x-api-key"))return;if(this.authToken&&J.get("authorization"))return;if($.has("authorization"))return;throw Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}_authFlags(J){let $=this._requestAuthFlags.get(J);if(!$)$={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(J,$);return $}async authHeaders(J){if(this._authState.resolution)await this._authState.resolution;if(this._authState.error)return;if(this._authState.tokenCache&&this.apiKey==null){let $=await this._authState.tokenCache.getToken();return this._authFlags(J).usedTokenCache=!0,U([{Authorization:`Bearer ${$}`}])}return U([await this.apiKeyAuth(J),await this.bearerAuth(J)])}async apiKeyAuth(J){if(this.apiKey==null)return;return U([{"X-Api-Key":this.apiKey}])}async bearerAuth(J){if(this.authToken==null)return;return U([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(J){return cJ(J)}getUserAgent(){return`Puku/JS ${B0}`}defaultIdempotencyKey(){return`stainless-node-retry-${U2()}`}makeStatusError(J,$,Z,X){return l.generate(J,$,Z,X)}buildURL(J,$,Z){let X=!this.#$()&&Z||this.baseURL,G=AJ(J)?new URL(J):new URL(X+(X.endsWith("/")&&J.startsWith("/")?J.slice(1):J)),Q=this.defaultQuery(),Y=Object.fromEntries(G.searchParams);if(!r1(Q)||!r1(Y))$={...Y,...Q,...$};if(typeof $==="object"&&$&&!Array.isArray($))G.search=this.stringifyQuery($);return G.toString()}_calculateNonstreamingTimeout(J){if(3600*J/128000>600)throw new T("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/puku-ai/sdk#streaming-responses for more details");return 600000}async prepareOptions(J){}async prepareRequest(J,{url:$,options:Z}){if(this._authState.tokenCache&&this.apiKey==null){let X=J.headers instanceof Headers?J.headers:new Headers(J.headers);for(let[Q,Y]of Object.entries(this._authState.extraHeaders))if(!X.has(Q))X.set(Q,Y);if(!X.get("puku-beta")?.split(",").map((Q)=>Q.trim())?.includes(f0))X.append("puku-beta",f0);J.headers=X}}backendMiddleware(){return[]}get(J,$){return this.methodRequest("get",J,$)}post(J,$){return this.methodRequest("post",J,$)}patch(J,$){return this.methodRequest("patch",J,$)}put(J,$){return this.methodRequest("put",J,$)}delete(J,$){return this.methodRequest("delete",J,$)}methodRequest(J,$,Z){return this.request(Promise.resolve(Z).then((X)=>{return{method:J,path:$,...X}}))}request(J,$=null){return new s0(this,this.makeRequest(J,$,void 0))}async makeRequest(J,$,Z){let X=await J,G=X.maxRetries??this.maxRetries;if($==null)$=G,this._requestAuthFlags.delete(X);await this.prepareOptions(X);let{req:Q,url:Y,timeout:z}=await this.buildRequest(X,{retryCount:G-$}),B="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),K=Z===void 0?"":`, retryOf: ${Z}`,W=Date.now();if(X.signal?.aborted)throw new Z0;let C=new AbortController,V=await this.fetchWithTimeout(Y,Q,z,C,X,{requestLogID:B,retryOfRequestLogID:Z}).catch(a0),F=Date.now();if(V instanceof globalThis.Error){H0(C);let R=`retrying, ${$} attempts remaining`;if(X.signal?.aborted)throw new Z0;let H=U0(V)||/timed? ?out/i.test(String(V)+("cause"in V?String(V.cause):"")),O=this.middleware.length>0||!!X.middleware?.length||this.backendMiddleware().length>0;if(O&&!H&&!w$(V))throw k(this).info(`[${B}] middleware error (not retryable)`),k(this).debug(`[${B}] middleware error (not retryable)`,j0({retryOfRequestLogID:Z,url:Y,durationMs:F-W,message:V.message})),V;if($)return k(this).info(`[${B}] connection ${H?"timed out":"failed"} - ${R}`),k(this).debug(`[${B}] connection ${H?"timed out":"failed"} (${R})`,j0({retryOfRequestLogID:Z,url:Y,durationMs:F-W,message:V.message})),this.retryRequest(X,$,Z??B);if(k(this).info(`[${B}] connection ${H?"timed out":"failed"} - error; no more retries left`),k(this).debug(`[${B}] connection ${H?"timed out":"failed"} (error; no more retries left)`,j0({retryOfRequestLogID:Z,url:Y,durationMs:F-W,message:V.message})),H)throw new g2;if(O&&!R6(V))throw V;throw new S0({cause:V})}let q=[...V.headers.entries()].filter(([R])=>R==="request-id"||R==="puku-workspace-id").map(([R,H])=>", "+R+": "+JSON.stringify(H)).join(""),A=`[${B}${K}${q}] ${Q.method} ${Y} ${V.ok?"succeeded":"failed"} with status ${V.status} in ${F-W}ms`;if(!V.ok){let R=await this.shouldRetry(V,X);if($&&R){let f=`retrying, ${$} attempts remaining`;return await yJ(V.body),H0(C),k(this).info(`${A} - ${f}`),k(this).debug(`[${B}] response error (${f})`,j0({retryOfRequestLogID:Z,url:V.url,status:V.status,headers:V.headers,durationMs:F-W})),this.retryRequest(X,$,Z??B,V.headers)}let H=R?"error; no more retries left":"error; not retryable";k(this).info(`${A} - ${H}`);let O=await V.text().catch((f)=>a0(f).message),D=o0(O),S=D?void 0:O;throw k(this).debug(`[${B}] response error (${H})`,j0({retryOfRequestLogID:Z,url:V.url,status:V.status,headers:V.headers,message:S,durationMs:Date.now()-W})),H0(C),this.makeStatusError(V.status,D,S,V.headers)}return k(this).info(A),k(this).debug(`[${B}] response start`,j0({retryOfRequestLogID:Z,url:V.url,status:V.status,headers:V.headers,durationMs:F-W})),EJ(V.body??V,C),{response:V,options:X,controller:C,requestLogID:B,retryOfRequestLogID:Z,startTime:W}}getAPIList(J,$,Z){return this.requestAPIList($,Z&&"then"in Z?Z.then((X)=>({method:"get",path:J,...X})):{method:"get",path:J,...Z})}requestAPIList(J,$){let Z=this.makeRequest($,null,void 0);return new T1(this,Z,J)}async fetchWithTimeout(J,$,Z,X,G,Q){let{signal:Y,method:z,...B}=$||{},K=this._makeAbort(X);if(Y)Y.addEventListener("abort",K,{once:!0}),_J(X,Y,K);let W=globalThis.ReadableStream&&B.body instanceof globalThis.ReadableStream||typeof B.body==="object"&&B.body!==null&&Symbol.asyncIterator in B.body,C={signal:X.signal,...W?{duplex:"half"}:{},method:"GET",...B};if(z)C.method=z.toUpperCase();let V=this.fetch,F=async(O,D)=>{let S=setTimeout(K,Z);try{return await V.call(void 0,O,D)}finally{clearTimeout(S)}},q=G===void 0?F:async(O,D={})=>{let S=typeof O==="string"?O:O instanceof URL?O.href:O.url;if(D.headers=D.headers instanceof Headers?D.headers:new Headers(D.headers),await this.prepareRequest(D,{url:S,options:G}),Q)k(this).debug(`[${Q.requestLogID}] sending request`,j0({retryOfRequestLogID:Q.retryOfRequestLogID,method:D.method,url:S,options:G,headers:D.headers}));return F(O,D)},A=G?.middleware,R=this.backendMiddleware(),H=A?.length||R.length?[...this.middleware,...A??[],...R]:this.middleware;return await A6(q,H,G,this)(J,C)}async shouldRetry(J,$){let Z=this._authFlags($);if(J.status===401&&this._authState.tokenCache&&Z.usedTokenCache&&!Z.didRefreshFor401)return Z.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let X=J.headers.get("x-should-retry");if(X==="true")return!0;if(X==="false")return!1;if(J.status===408)return!0;if(J.status===409)return!0;if(J.status===429)return!0;if(J.status>=500)return!0;return!1}async retryRequest(J,$,Z,X){let G,Q=X?.get("retry-after-ms");if(Q){let z=parseFloat(Q);if(!Number.isNaN(z))G=z}let Y=X?.get("retry-after");if(Y&&!G){let z=parseFloat(Y);if(!Number.isNaN(z))G=z*1000;else G=Date.parse(Y)-Date.now()}if(G===void 0){let z=J.maxRetries??this.maxRetries;G=this.calculateDefaultRetryTimeoutMillis($,z)}return await T0(G),this.makeRequest(J,$-1,Z)}calculateDefaultRetryTimeoutMillis(J,$){let G=$-J,Q=Math.min(0.5*Math.pow(2,G),8),Y=1-Math.random()*0.25;return Q*Y*1000}calculateNonstreamingTimeout(J,$){if(3600000*J/128000>600000||$!=null&&J>$)throw new T("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/puku-ai/sdk#long-requests for more details");return 600000}async buildRequest(J,{retryCount:$=0}={}){let Z={...J},{method:X,path:G,query:Q,defaultBaseURL:Y}=Z;if(this._authState.resolution)await this._authState.resolution;if(!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL)this.baseURL=this._authState.baseURL;let z=this.buildURL(G,Q,Y);if("timeout"in Z)LJ("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:B,body:K}=this.buildBody({options:Z}),W=await this.buildHeaders({options:J,method:X,bodyHeaders:B,retryCount:$});return{req:{method:X,headers:W,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&K instanceof globalThis.ReadableStream&&{duplex:"half"},...K&&{body:K},...this.fetchOptions??{},...Z.fetchOptions??{}},url:z,timeout:Z.timeout}}async buildHeaders({options:J,method:$,bodyHeaders:Z,retryCount:X}){let G={};if(this.idempotencyHeader&&$!=="get"){if(!J.idempotencyKey)J.idempotencyKey=this.defaultIdempotencyKey();G[this.idempotencyHeader]=J.idempotencyKey}let Q=U([G,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(X),...J.timeout?{"X-Stainless-Timeout":String(Math.trunc(J.timeout/1000))}:{},...a2(),...this._options.dangerouslyAllowBrowser?{"puku-dangerous-direct-browser-access":"true"}:void 0,"puku-version":"2023-06-01"},await this.authHeaders(J),this._options.defaultHeaders,Z,J.headers]);return this.validateHeaders(Q),Q.values}_makeAbort(J){return()=>J.abort()}buildBody({options:{body:J,headers:$}}){if(!J)return{bodyHeaders:void 0,body:void 0};let Z=U([$]);if(ArrayBuffer.isView(J)||J instanceof ArrayBuffer||J instanceof DataView||typeof J==="string"&&Z.values.has("content-type")||globalThis.Blob&&J instanceof globalThis.Blob||J instanceof FormData||J instanceof URLSearchParams||globalThis.ReadableStream&&J instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:J};else if(typeof J==="object"&&((Symbol.asyncIterator in J)||(Symbol.iterator in J)&&("next"in J)&&typeof J.next==="function"))return{bodyHeaders:void 0,body:$1(J)};else if(typeof J==="object"&&Z.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(J)};else return this.#J({body:J,headers:Z})}static HUMAN_PROMPT=gZ;static AI_PROMPT=hZ;static DEFAULT_TIMEOUT=600000;static PukuError=T;static APIError=l;static APIConnectionError=S0;static APIConnectionTimeoutError=g2;static APIUserAbortError=Z0;static NotFoundError=d2;static ConflictError=c2;static RateLimitError=l2;static BadRequestError=h2;static AuthenticationError=m2;static InternalServerError=i2;static PermissionDeniedError=u2;static UnprocessableEntityError=p2;static toFile=w1};P0=class P0 extends d1{completions=new f2(this);messages=new W2(this);models=new b2(this);files=new v2(this);skills=new V2(this);beta=new i(this)};P0.Completions=f2;P0.Messages=W2;P0.Models=b2;P0.Files=v2;P0.Skills=V2;P0.Beta=i});function hX(J){let $=J.messages.flatMap((Z)=>{if(!Array.isArray(Z.content))return[Z];let X=Z.content.filter((G)=>G.type!=="fallback");if(X.length===Z.content.length)return[Z];return X.length>0?[{...Z,content:X}]:[]});return{...J,messages:$}}function mZ(J,$){let Z={...J};for(let[X,G]of Object.entries($))if(X==="output_config"&&G!=null){let Q={...Z[X]??{}};for(let[Y,z]of Object.entries(G))UJ(Q,Y,z);UJ(Z,X,Object.keys(Q).length?Q:null)}else UJ(Z,X,G);return Z}function UJ(J,$,Z){if(Z===void 0)return;if(Z===null)delete J[$];else J[$]=Z}function mX(J,$={}){let Z=!1;return async(X,G,Q)=>{let[Y,z]=(Q.options?.path??"").split("?");if(J.length===0||Q.options?.method!=="post"||Y!=="/v1/messages"||new URLSearchParams(z).get("beta")!=="true"||typeof Q.options.body!=="object"||Q.options.body==null)return G(X);if(Q.options.body.fallbacks!=null)throw new T("Sending the `fallbacks:` request param is not supported when using the `betaRefusalFallbackMiddleware`. 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, or omit the `fallbacks:` param if you'd like `betaRefusalFallbackMiddleware` to handle fallbacks on the client side.");let B=$.onError??((f)=>Q.logger.error(`puku-ai/sdk: betaRefusalFallbackMiddleware: ${f.message}`));X=lX(X,$.betas??gX);let K=hX(Q.options.body),W=Q.options.fallbackState,C=W?.index??-1;if(!Number.isInteger(C)||C<-1||C>=J.length)throw new T(`fallbackState.index ${C} is out of bounds for a chain of ${J.length} fallback(s); was the state shared with a different middleware?`);let V=(f)=>{if(W)W.index=f;else if(!Z)Z=!0,Q.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.")},F=C===-1?K:mZ(K,J[C]),q=typeof X.body!=="string"?X:{...X,body:JSON.stringify(F)},A=await G(q);if(!A.ok)return A;if(Q.options.stream===!0){let f=C+1;if(f>=J.length||typeof q.body!=="string")return A;return uX({request:q,response:A,next:G,ctx:Q,fallbacks:J,firstHop:f,onError:B,pin:V})}let R=C,H=A,O=F.model,D=[];while(R<J.length-1){let f=await Q.parse(H);if(f?.type!=="message"||f.stop_reason!=="refusal")break;R+=1,V(R);let v=J[R];D.push({type:"fallback",from:{model:O??f.model},to:{model:v.model},trigger:{type:"refusal",category:f.stop_details?.category??null}}),O=v.model,H=await G({...X,body:JSON.stringify({...mZ(K,v),...f.stop_details?.fallback_credit_token?{fallback_credit_token:iZ(f.stop_details.fallback_credit_token)}:void 0})})}if(D.length===0)return H;let S=await Q.parse(H);if(S?.type!=="message"||S.stop_reason==="refusal"||!Array.isArray(S.content))return H;let y=new Headers(H.headers);return y.delete("content-length"),new Response(JSON.stringify({...S,content:[...D,...S.content]}),{status:H.status,statusText:H.statusText,headers:y})}}function uX(J){let $=new AbortController,Z=J.request.signal;if(Z?.aborted)$.abort(Z.reason);else Z?.addEventListener("abort",nX($,Z),{once:!0});let X=dX(J,$),G=new ReadableStream({async pull(Q){try{let{value:Y,done:z}=await X.next();if(z)return Q.close();Q.enqueue(Y)}catch(Y){Q.error(Y)}},async cancel(){$.abort(),await X.return?.(void 0)}});return new Response(G,J.response)}async function*dX({request:J,response:$,next:Z,ctx:X,fallbacks:G,firstHop:Q,onError:Y,pin:z},B){let K=yield*uZ({response:$,controller:B,indexBase:0,hasNext:!0,onError:Y,splice:null});if(!K.refused)return;let W=K.nextIndex,C=K.refused.token,V=[],F=K.refused.hasPrefillClaim?dZ(K.blocks):[],q=K.model??"",A=K.refused.usage,R=K.refused.stopDetails,H=K.refused.inputTransformations,O=[NJ("message",K.model??"",K.refused.usage)];for(let D=Q;D<G.length;D++){let S=G[D].model,y=D+1<G.length;z(D);let f=W++;yield y0("content_block_start",{type:"content_block_start",index:f,content_block:{type:"fallback",from:{model:q},to:{model:S},trigger:{type:"refusal",category:R?.category??null}}}),yield y0("content_block_stop",{type:"content_block_stop",index:f});let v=[...V,...F],g=null,d=null;for(let t=0;t<2;t++){let A0=cX(J,{model:S,creditToken:C,continuation:v});A0.signal=B.signal;try{g=await Z(A0)}catch(C2){if(U0(C2))throw C2;d={kind:"request_failed",message:`fallback request failed: ${C2}`,model:S,status:null,detail:C2};break}if(g.ok)break;let n0=await X.parse(g).catch(()=>null);if(t===0&&g.status===400&&F.length){X.logger.warn(`puku-ai/sdk: betaRefusalFallbackMiddleware: fallback request with the partial output appended was rejected (HTTP 400: ${JSON.stringify(n0)}); retrying without it`),v=V,g=null;continue}d={kind:"request_failed",message:`fallback request failed: HTTP ${g.status}: ${JSON.stringify(n0)}`,model:S,status:g.status,detail:n0};break}if(d){if(Y(d),y)continue;let t={...R,recommended_model:S};yield y0("message_delta",{type:"message_delta",context_management:null,delta:{stop_reason:"refusal",stop_sequence:null,container:null,stop_details:t},usage:A??{},...H!==void 0&&{input_transformations:H}}),yield y0("message_stop",{type:"message_stop"});return}let b=yield*uZ({response:g,controller:B,indexBase:W,hasNext:y,onError:Y,splice:{iterations:O,model:S}});if(!b.refused)return;C=b.refused.token,R=b.refused.stopDetails,H=b.refused.inputTransformations,V=v,F=b.refused.hasPrefillClaim?dZ(b.blocks):[],O.push(NJ("message",S,b.refused.usage)),A=b.refused.usage,q=S,W=b.nextIndex}}async function*uZ(J){let{response:$,controller:Z,indexBase:X,hasNext:G,onError:Q,splice:Y}=J,z=new lZ(X),B,K=null,W;for await(let C of s.rawEvents($,Z)){let V=o0(C.data);switch(V?.type){case"message_start":{if(B=V.message.model,K=V.message.usage,"input_transformations"in V.message)W=V.message.input_transformations;if(Y)continue;break}case"content_block_start":{if(z.start(V),Y){yield y0(V.type,V);continue}break}case"content_block_delta":{if(z.delta(V),Y){yield y0(V.type,V);continue}break}case"content_block_stop":{if(z.stop(V),Y){yield y0(V.type,V);continue}break}case"message_delta":{if(V.delta.stop_reason==="refusal"){let F=V.delta.stop_details?.type==="refusal"?V.delta.stop_details:null;if(F?.fallback_credit_token&&G){let q=cZ(V.usage,K);return yield*z.closeOpenBlocks(),{refused:{token:F.fallback_credit_token,hasPrefillClaim:F.fallback_has_prefill_claim===!0,usage:q,stopDetails:F,inputTransformations:Y?W:void 0},model:B,blocks:z.contentBlocks(),nextIndex:z.nextIndex}}if(!F?.fallback_credit_token)Q({kind:"no_credit_token",message:"refusal stop_details has no fallback_credit_token",event:V});else Q({kind:"chain_exhausted",message:"refusal but no fallback entries remain",event:V})}if(Y){let F=cZ(V.usage,K);if(F.iterations=[...Y.iterations,NJ("fallback_message",Y.model,F)],V.usage=F,!("input_transformations"in V)&&W!==void 0)V.input_transformations=W;yield y0("message_delta",V);continue}break}}yield iX(C)}return{refused:null,model:B,blocks:z.contentBlocks(),nextIndex:z.nextIndex}}class lZ{indexBase;blocks=[];nextIndex;open=[];constructor(J=0){this.indexBase=J;this.nextIndex=J}contentBlocks(){return this.blocks.map((J)=>J.block)}start(J){this.blocks.push({index:J.index,block:{...J.content_block}}),J.index+=this.indexBase,this.open.push(J.index),this.nextIndex=Math.max(this.nextIndex,J.index+1)}delta(J){pX(this.blocks,J.index,J.delta),J.index+=this.indexBase}stop(J){J.index+=this.indexBase;let $=this.open.indexOf(J.index);if($!==-1)this.open.splice($,1);this.nextIndex=Math.max(this.nextIndex,J.index+1)}*closeOpenBlocks(){for(let J of this.open)yield y0("content_block_stop",{type:"content_block_stop",index:J});this.open.length=0}}function iZ(J){return{token:J,mode:"best_effort"}}function cX(J,{model:$,creditToken:Z,continuation:X}){let G=JSON.parse(J.body);if(G.model=$,G.fallback_credit_token=iZ(Z),X.length)G.messages=[...G.messages,{role:"assistant",content:X}];return{...J,headers:new Headers(J.headers),body:JSON.stringify(G)}}function pX(J,$,Z){let X=J.find((G)=>G.index===$)?.block;if(!X)return;switch(Z.type){case"text_delta":{X.text=(X.text??"")+Z.text;break}case"input_json_delta":{X._partial_json=(X._partial_json??"")+Z.partial_json;break}case"citations_delta":(X.citations??=[]).push(Z.citation);break;case"thinking_delta":{X.thinking=(X.thinking??"")+Z.thinking;break}case"signature_delta":{X.signature=Z.signature;break}case"compaction_delta":break;default:((G)=>{})(Z)}}function dZ(J){return J.map(($)=>{if(typeof $?._partial_json!=="string")return $;let{_partial_json:Z,...X}=$;return{...X,input:o0(Z)??X.input}})}function lX(J,$){let Z=new Headers(J.headers),X=new Set(Z.get("puku-beta")?.split(",").map((G)=>G.trim()));for(let G of $)if(!X.has(G))Z.append("puku-beta",G),X.add(G);return Z.set(J2,_6(Z.get(J2),"fallback-refusal-middleware")),{...J,headers:Z}}function y0(J,$){let Z={event:J,data:JSON.stringify($),raw:[]};return pZ.encode(nZ(Z))}function iX(J){return pZ.encode(J.raw.length?J.raw.join(`
56
+ `);if(this.baseURL=Q.baseURL,this.baseURL.endsWith("/v1"))this.baseURL=this.baseURL.slice(0,-3);this._baseURLIsExplicit=G.__baseURLIsExplicit??!!J,this.timeout=Q.timeout??d1.DEFAULT_TIMEOUT,this.logger=Q.logger??console,this.logLevel=s2,this.logLevel=C1(Q.logLevel,"ClientOptions.logLevel",k(this))??C1(x("PUKU_LOG"),"process.env['PUKU_LOG']",k(this))??s2,this.fetchOptions=Q.fetchOptions,this.maxRetries=Q.maxRetries??2,this.fetch=Q.fetch??I4(),this.#J=x4,this.middleware=[...Q.middleware??[]];let Y=x("PUKU_CUSTOM_HEADERS");if(Y){let B={};for(let K of Y.split(`
57
+ `)){let W=K.indexOf(":");if(W>=0)B[K.substring(0,W).trim()]=K.substring(W+1).trim()}Q.defaultHeaders={...B,...Q.defaultHeaders}}let z=G.__auth;if(delete Q.__auth,delete Q.__baseURLIsExplicit,this._options=Q,this.apiKey=typeof $==="string"?$:null,this.authToken=Z,this.webhookKey=X,z){if(this._authState=z,!this._baseURLIsExplicit&&z.baseURL)this.baseURL=z.baseURL}else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let B=Q.credentials??null;if(B)this._authState.provider=B,this._authState.tokenCache=this._makeTokenCache(B);else if(Q.config!=null){let K=w6(Q.config,this._credentialResolverOptions());this._authState.provider=K.provider,this._authState.tokenCache=this._makeTokenCache(K.provider),this._authState.extraHeaders=K.extraHeaders,this._applyCredentialBaseURL(K.baseURL)}else if(Q.profile!=null)this._authState.resolution=this._resolveDefaultCredentials(Q.profile);else if(this._shouldResolveDefaultCredentials())this._authState.resolution=this._resolveDefaultCredentials()}}_shouldResolveDefaultCredentials(){return!0}_applyCredentialBaseURL(J){if(!J)return;let $=J.replace(/\/+$/,"");if(this._authState.baseURL=$,!this._baseURLIsExplicit)this.baseURL=$}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:(J)=>{k(this).debug("credential cache write failed (best-effort)",J)},onSafetyWarning:(J)=>{k(this).warn(J)}}}_credentialsFetch(){return A6(this.fetch,this.middleware,void 0,this)}_makeTokenCache(J){return new C6(J,($)=>{k(this).debug("advisory token refresh failed; serving cached token",$)})}withOptions(J){let $="credentials"in J||"config"in J||"profile"in J,Z="apiKey"in J||"authToken"in J||$,X={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...$?{credentials:void 0,config:void 0,profile:void 0}:{},...J,__auth:Z?void 0:this._authState,__baseURLIsExplicit:"baseURL"in J?!0:this._baseURLIsExplicit};return new this.constructor(X)}async _resolveDefaultCredentials(J){try{let $=await C$(this._credentialResolverOptions(),J);if($)this._authState.provider=$.provider,this._authState.tokenCache=this._makeTokenCache($.provider),this._authState.extraHeaders=$.extraHeaders,this._applyCredentialBaseURL($.baseURL);else if(J!=null)throw new T(`Profile "${J}" could not be resolved (no <config_dir>/configs/${J}.json found).`)}catch($){this._authState.error=$}finally{this._authState.resolution=null}}#$(){return this.baseURL!==""}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:J,nulls:$}){if(J.get("x-api-key")||J.get("authorization"))return;if(this._authState.error)throw this._authState.error;if(this._authState.tokenCache||this._authState.resolution)return;if(this.apiKey&&J.get("x-api-key"))return;if($.has("x-api-key"))return;if(this.authToken&&J.get("authorization"))return;if($.has("authorization"))return;throw Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}_authFlags(J){let $=this._requestAuthFlags.get(J);if(!$)$={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(J,$);return $}async authHeaders(J){if(this._authState.resolution)await this._authState.resolution;if(this._authState.error)return;if(this._authState.tokenCache&&this.apiKey==null){let $=await this._authState.tokenCache.getToken();return this._authFlags(J).usedTokenCache=!0,U([{Authorization:`Bearer ${$}`}])}return U([await this.apiKeyAuth(J),await this.bearerAuth(J)])}async apiKeyAuth(J){if(this.apiKey==null)return;return U([{"X-Api-Key":this.apiKey}])}async bearerAuth(J){if(this.authToken==null)return;return U([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(J){return c4(J)}getUserAgent(){return`Puku/JS ${B0}`}defaultIdempotencyKey(){return`stainless-node-retry-${U2()}`}makeStatusError(J,$,Z,X){return l.generate(J,$,Z,X)}buildURL(J,$,Z){let X=!this.#$()&&Z||this.baseURL,G=A4(J)?new URL(J):new URL(X+(X.endsWith("/")&&J.startsWith("/")?J.slice(1):J)),Q=this.defaultQuery(),Y=Object.fromEntries(G.searchParams);if(!r1(Q)||!r1(Y))$={...Y,...Q,...$};if(typeof $==="object"&&$&&!Array.isArray($))G.search=this.stringifyQuery($);return G.toString()}_calculateNonstreamingTimeout(J){if(3600*J/128000>600)throw new T("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/puku-ai/sdk#streaming-responses for more details");return 600000}async prepareOptions(J){}async prepareRequest(J,{url:$,options:Z}){if(this._authState.tokenCache&&this.apiKey==null){let X=J.headers instanceof Headers?J.headers:new Headers(J.headers);for(let[Q,Y]of Object.entries(this._authState.extraHeaders))if(!X.has(Q))X.set(Q,Y);if(!X.get("puku-beta")?.split(",").map((Q)=>Q.trim())?.includes(f0))X.append("puku-beta",f0);J.headers=X}}backendMiddleware(){return[]}get(J,$){return this.methodRequest("get",J,$)}post(J,$){return this.methodRequest("post",J,$)}patch(J,$){return this.methodRequest("patch",J,$)}put(J,$){return this.methodRequest("put",J,$)}delete(J,$){return this.methodRequest("delete",J,$)}methodRequest(J,$,Z){return this.request(Promise.resolve(Z).then((X)=>{return{method:J,path:$,...X}}))}request(J,$=null){return new s0(this,this.makeRequest(J,$,void 0))}async makeRequest(J,$,Z){let X=await J,G=X.maxRetries??this.maxRetries;if($==null)$=G,this._requestAuthFlags.delete(X);await this.prepareOptions(X);let{req:Q,url:Y,timeout:z}=await this.buildRequest(X,{retryCount:G-$}),B="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),K=Z===void 0?"":`, retryOf: ${Z}`,W=Date.now();if(X.signal?.aborted)throw new Z0;let C=new AbortController,V=await this.fetchWithTimeout(Y,Q,z,C,X,{requestLogID:B,retryOfRequestLogID:Z}).catch(a0),F=Date.now();if(V instanceof globalThis.Error){H0(C);let R=`retrying, ${$} attempts remaining`;if(X.signal?.aborted)throw new Z0;let H=U0(V)||/timed? ?out/i.test(String(V)+("cause"in V?String(V.cause):"")),O=this.middleware.length>0||!!X.middleware?.length||this.backendMiddleware().length>0;if(O&&!H&&!w$(V))throw k(this).info(`[${B}] middleware error (not retryable)`),k(this).debug(`[${B}] middleware error (not retryable)`,j0({retryOfRequestLogID:Z,url:Y,durationMs:F-W,message:V.message})),V;if($)return k(this).info(`[${B}] connection ${H?"timed out":"failed"} - ${R}`),k(this).debug(`[${B}] connection ${H?"timed out":"failed"} (${R})`,j0({retryOfRequestLogID:Z,url:Y,durationMs:F-W,message:V.message})),this.retryRequest(X,$,Z??B);if(k(this).info(`[${B}] connection ${H?"timed out":"failed"} - error; no more retries left`),k(this).debug(`[${B}] connection ${H?"timed out":"failed"} (error; no more retries left)`,j0({retryOfRequestLogID:Z,url:Y,durationMs:F-W,message:V.message})),H)throw new g2;if(O&&!R6(V))throw V;throw new S0({cause:V})}let q=[...V.headers.entries()].filter(([R])=>R==="request-id"||R==="puku-workspace-id").map(([R,H])=>", "+R+": "+JSON.stringify(H)).join(""),A=`[${B}${K}${q}] ${Q.method} ${Y} ${V.ok?"succeeded":"failed"} with status ${V.status} in ${F-W}ms`;if(!V.ok){let R=await this.shouldRetry(V,X);if($&&R){let f=`retrying, ${$} attempts remaining`;return await y4(V.body),H0(C),k(this).info(`${A} - ${f}`),k(this).debug(`[${B}] response error (${f})`,j0({retryOfRequestLogID:Z,url:V.url,status:V.status,headers:V.headers,durationMs:F-W})),this.retryRequest(X,$,Z??B,V.headers)}let H=R?"error; no more retries left":"error; not retryable";k(this).info(`${A} - ${H}`);let O=await V.text().catch((f)=>a0(f).message),D=o0(O),S=D?void 0:O;throw k(this).debug(`[${B}] response error (${H})`,j0({retryOfRequestLogID:Z,url:V.url,status:V.status,headers:V.headers,message:S,durationMs:Date.now()-W})),H0(C),this.makeStatusError(V.status,D,S,V.headers)}return k(this).info(A),k(this).debug(`[${B}] response start`,j0({retryOfRequestLogID:Z,url:V.url,status:V.status,headers:V.headers,durationMs:F-W})),E4(V.body??V,C),{response:V,options:X,controller:C,requestLogID:B,retryOfRequestLogID:Z,startTime:W}}getAPIList(J,$,Z){return this.requestAPIList($,Z&&"then"in Z?Z.then((X)=>({method:"get",path:J,...X})):{method:"get",path:J,...Z})}requestAPIList(J,$){let Z=this.makeRequest($,null,void 0);return new T1(this,Z,J)}async fetchWithTimeout(J,$,Z,X,G,Q){let{signal:Y,method:z,...B}=$||{},K=this._makeAbort(X);if(Y)Y.addEventListener("abort",K,{once:!0}),_4(X,Y,K);let W=globalThis.ReadableStream&&B.body instanceof globalThis.ReadableStream||typeof B.body==="object"&&B.body!==null&&Symbol.asyncIterator in B.body,C={signal:X.signal,...W?{duplex:"half"}:{},method:"GET",...B};if(z)C.method=z.toUpperCase();let V=this.fetch,F=async(O,D)=>{let S=setTimeout(K,Z);try{return await V.call(void 0,O,D)}finally{clearTimeout(S)}},q=G===void 0?F:async(O,D={})=>{let S=typeof O==="string"?O:O instanceof URL?O.href:O.url;if(D.headers=D.headers instanceof Headers?D.headers:new Headers(D.headers),await this.prepareRequest(D,{url:S,options:G}),Q)k(this).debug(`[${Q.requestLogID}] sending request`,j0({retryOfRequestLogID:Q.retryOfRequestLogID,method:D.method,url:S,options:G,headers:D.headers}));return F(O,D)},A=G?.middleware,R=this.backendMiddleware(),H=A?.length||R.length?[...this.middleware,...A??[],...R]:this.middleware;return await A6(q,H,G,this)(J,C)}async shouldRetry(J,$){let Z=this._authFlags($);if(J.status===401&&this._authState.tokenCache&&Z.usedTokenCache&&!Z.didRefreshFor401)return Z.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let X=J.headers.get("x-should-retry");if(X==="true")return!0;if(X==="false")return!1;if(J.status===408)return!0;if(J.status===409)return!0;if(J.status===429)return!0;if(J.status>=500)return!0;return!1}async retryRequest(J,$,Z,X){let G,Q=X?.get("retry-after-ms");if(Q){let z=parseFloat(Q);if(!Number.isNaN(z))G=z}let Y=X?.get("retry-after");if(Y&&!G){let z=parseFloat(Y);if(!Number.isNaN(z))G=z*1000;else G=Date.parse(Y)-Date.now()}if(G===void 0){let z=J.maxRetries??this.maxRetries;G=this.calculateDefaultRetryTimeoutMillis($,z)}return await T0(G),this.makeRequest(J,$-1,Z)}calculateDefaultRetryTimeoutMillis(J,$){let G=$-J,Q=Math.min(0.5*Math.pow(2,G),8),Y=1-Math.random()*0.25;return Q*Y*1000}calculateNonstreamingTimeout(J,$){if(3600000*J/128000>600000||$!=null&&J>$)throw new T("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/puku-ai/sdk#long-requests for more details");return 600000}async buildRequest(J,{retryCount:$=0}={}){let Z={...J},{method:X,path:G,query:Q,defaultBaseURL:Y}=Z;if(this._authState.resolution)await this._authState.resolution;if(!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL)this.baseURL=this._authState.baseURL;let z=this.buildURL(G,Q,Y);if("timeout"in Z)L4("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:B,body:K}=this.buildBody({options:Z}),W=await this.buildHeaders({options:J,method:X,bodyHeaders:B,retryCount:$});return{req:{method:X,headers:W,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&K instanceof globalThis.ReadableStream&&{duplex:"half"},...K&&{body:K},...this.fetchOptions??{},...Z.fetchOptions??{}},url:z,timeout:Z.timeout}}async buildHeaders({options:J,method:$,bodyHeaders:Z,retryCount:X}){let G={};if(this.idempotencyHeader&&$!=="get"){if(!J.idempotencyKey)J.idempotencyKey=this.defaultIdempotencyKey();G[this.idempotencyHeader]=J.idempotencyKey}let Q=U([G,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(X),...J.timeout?{"X-Stainless-Timeout":String(Math.trunc(J.timeout/1000))}:{},...a2(),...this._options.dangerouslyAllowBrowser?{"puku-dangerous-direct-browser-access":"true"}:void 0,"puku-version":"2023-06-01"},await this.authHeaders(J),this._options.defaultHeaders,Z,J.headers]);return this.validateHeaders(Q),Q.values}_makeAbort(J){return()=>J.abort()}buildBody({options:{body:J,headers:$}}){if(!J)return{bodyHeaders:void 0,body:void 0};let Z=U([$]);if(ArrayBuffer.isView(J)||J instanceof ArrayBuffer||J instanceof DataView||typeof J==="string"&&Z.values.has("content-type")||globalThis.Blob&&J instanceof globalThis.Blob||J instanceof FormData||J instanceof URLSearchParams||globalThis.ReadableStream&&J instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:J};else if(typeof J==="object"&&((Symbol.asyncIterator in J)||(Symbol.iterator in J)&&("next"in J)&&typeof J.next==="function"))return{bodyHeaders:void 0,body:$1(J)};else if(typeof J==="object"&&Z.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(J)};else return this.#J({body:J,headers:Z})}static HUMAN_PROMPT=gZ;static AI_PROMPT=hZ;static DEFAULT_TIMEOUT=600000;static PukuError=T;static APIError=l;static APIConnectionError=S0;static APIConnectionTimeoutError=g2;static APIUserAbortError=Z0;static NotFoundError=d2;static ConflictError=c2;static RateLimitError=l2;static BadRequestError=h2;static AuthenticationError=m2;static InternalServerError=i2;static PermissionDeniedError=u2;static UnprocessableEntityError=p2;static toFile=w1};P0=class P0 extends d1{completions=new f2(this);messages=new W2(this);models=new b2(this);files=new v2(this);skills=new V2(this);beta=new i(this)};P0.Completions=f2;P0.Messages=W2;P0.Models=b2;P0.Files=v2;P0.Skills=V2;P0.Beta=i});function hG(J){let $=J.messages.flatMap((Z)=>{if(!Array.isArray(Z.content))return[Z];let X=Z.content.filter((G)=>G.type!=="fallback");if(X.length===Z.content.length)return[Z];return X.length>0?[{...Z,content:X}]:[]});return{...J,messages:$}}function mZ(J,$){let Z={...J};for(let[X,G]of Object.entries($))if(X==="output_config"&&G!=null){let Q={...Z[X]??{}};for(let[Y,z]of Object.entries(G))U4(Q,Y,z);U4(Z,X,Object.keys(Q).length?Q:null)}else U4(Z,X,G);return Z}function U4(J,$,Z){if(Z===void 0)return;if(Z===null)delete J[$];else J[$]=Z}function mG(J,$={}){let Z=!1;return async(X,G,Q)=>{let[Y,z]=(Q.options?.path??"").split("?");if(J.length===0||Q.options?.method!=="post"||Y!=="/v1/messages"||new URLSearchParams(z).get("beta")!=="true"||typeof Q.options.body!=="object"||Q.options.body==null)return G(X);if(Q.options.body.fallbacks!=null)throw new T("Sending the `fallbacks:` request param is not supported when using the `betaRefusalFallbackMiddleware`. 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, or omit the `fallbacks:` param if you'd like `betaRefusalFallbackMiddleware` to handle fallbacks on the client side.");let B=$.onError??((f)=>Q.logger.error(`puku-ai/sdk: betaRefusalFallbackMiddleware: ${f.message}`));X=lG(X,$.betas??gG);let K=hG(Q.options.body),W=Q.options.fallbackState,C=W?.index??-1;if(!Number.isInteger(C)||C<-1||C>=J.length)throw new T(`fallbackState.index ${C} is out of bounds for a chain of ${J.length} fallback(s); was the state shared with a different middleware?`);let V=(f)=>{if(W)W.index=f;else if(!Z)Z=!0,Q.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.")},F=C===-1?K:mZ(K,J[C]),q=typeof X.body!=="string"?X:{...X,body:JSON.stringify(F)},A=await G(q);if(!A.ok)return A;if(Q.options.stream===!0){let f=C+1;if(f>=J.length||typeof q.body!=="string")return A;return uG({request:q,response:A,next:G,ctx:Q,fallbacks:J,firstHop:f,onError:B,pin:V})}let R=C,H=A,O=F.model,D=[];while(R<J.length-1){let f=await Q.parse(H);if(f?.type!=="message"||f.stop_reason!=="refusal")break;R+=1,V(R);let v=J[R];D.push({type:"fallback",from:{model:O??f.model},to:{model:v.model},trigger:{type:"refusal",category:f.stop_details?.category??null}}),O=v.model,H=await G({...X,body:JSON.stringify({...mZ(K,v),...f.stop_details?.fallback_credit_token?{fallback_credit_token:iZ(f.stop_details.fallback_credit_token)}:void 0})})}if(D.length===0)return H;let S=await Q.parse(H);if(S?.type!=="message"||S.stop_reason==="refusal"||!Array.isArray(S.content))return H;let y=new Headers(H.headers);return y.delete("content-length"),new Response(JSON.stringify({...S,content:[...D,...S.content]}),{status:H.status,statusText:H.statusText,headers:y})}}function uG(J){let $=new AbortController,Z=J.request.signal;if(Z?.aborted)$.abort(Z.reason);else Z?.addEventListener("abort",nG($,Z),{once:!0});let X=dG(J,$),G=new ReadableStream({async pull(Q){try{let{value:Y,done:z}=await X.next();if(z)return Q.close();Q.enqueue(Y)}catch(Y){Q.error(Y)}},async cancel(){$.abort(),await X.return?.(void 0)}});return new Response(G,J.response)}async function*dG({request:J,response:$,next:Z,ctx:X,fallbacks:G,firstHop:Q,onError:Y,pin:z},B){let K=yield*uZ({response:$,controller:B,indexBase:0,hasNext:!0,onError:Y,splice:null});if(!K.refused)return;let W=K.nextIndex,C=K.refused.token,V=[],F=K.refused.hasPrefillClaim?dZ(K.blocks):[],q=K.model??"",A=K.refused.usage,R=K.refused.stopDetails,H=K.refused.inputTransformations,O=[N4("message",K.model??"",K.refused.usage)];for(let D=Q;D<G.length;D++){let S=G[D].model,y=D+1<G.length;z(D);let f=W++;yield y0("content_block_start",{type:"content_block_start",index:f,content_block:{type:"fallback",from:{model:q},to:{model:S},trigger:{type:"refusal",category:R?.category??null}}}),yield y0("content_block_stop",{type:"content_block_stop",index:f});let v=[...V,...F],g=null,d=null;for(let t=0;t<2;t++){let A0=cG(J,{model:S,creditToken:C,continuation:v});A0.signal=B.signal;try{g=await Z(A0)}catch(C2){if(U0(C2))throw C2;d={kind:"request_failed",message:`fallback request failed: ${C2}`,model:S,status:null,detail:C2};break}if(g.ok)break;let n0=await X.parse(g).catch(()=>null);if(t===0&&g.status===400&&F.length){X.logger.warn(`puku-ai/sdk: betaRefusalFallbackMiddleware: fallback request with the partial output appended was rejected (HTTP 400: ${JSON.stringify(n0)}); retrying without it`),v=V,g=null;continue}d={kind:"request_failed",message:`fallback request failed: HTTP ${g.status}: ${JSON.stringify(n0)}`,model:S,status:g.status,detail:n0};break}if(d){if(Y(d),y)continue;let t={...R,recommended_model:S};yield y0("message_delta",{type:"message_delta",context_management:null,delta:{stop_reason:"refusal",stop_sequence:null,container:null,stop_details:t},usage:A??{},...H!==void 0&&{input_transformations:H}}),yield y0("message_stop",{type:"message_stop"});return}let b=yield*uZ({response:g,controller:B,indexBase:W,hasNext:y,onError:Y,splice:{iterations:O,model:S}});if(!b.refused)return;C=b.refused.token,R=b.refused.stopDetails,H=b.refused.inputTransformations,V=v,F=b.refused.hasPrefillClaim?dZ(b.blocks):[],O.push(N4("message",S,b.refused.usage)),A=b.refused.usage,q=S,W=b.nextIndex}}async function*uZ(J){let{response:$,controller:Z,indexBase:X,hasNext:G,onError:Q,splice:Y}=J,z=new lZ(X),B,K=null,W;for await(let C of s.rawEvents($,Z)){let V=o0(C.data);switch(V?.type){case"message_start":{if(B=V.message.model,K=V.message.usage,"input_transformations"in V.message)W=V.message.input_transformations;if(Y)continue;break}case"content_block_start":{if(z.start(V),Y){yield y0(V.type,V);continue}break}case"content_block_delta":{if(z.delta(V),Y){yield y0(V.type,V);continue}break}case"content_block_stop":{if(z.stop(V),Y){yield y0(V.type,V);continue}break}case"message_delta":{if(V.delta.stop_reason==="refusal"){let F=V.delta.stop_details?.type==="refusal"?V.delta.stop_details:null;if(F?.fallback_credit_token&&G){let q=cZ(V.usage,K);return yield*z.closeOpenBlocks(),{refused:{token:F.fallback_credit_token,hasPrefillClaim:F.fallback_has_prefill_claim===!0,usage:q,stopDetails:F,inputTransformations:Y?W:void 0},model:B,blocks:z.contentBlocks(),nextIndex:z.nextIndex}}if(!F?.fallback_credit_token)Q({kind:"no_credit_token",message:"refusal stop_details has no fallback_credit_token",event:V});else Q({kind:"chain_exhausted",message:"refusal but no fallback entries remain",event:V})}if(Y){let F=cZ(V.usage,K);if(F.iterations=[...Y.iterations,N4("fallback_message",Y.model,F)],V.usage=F,!("input_transformations"in V)&&W!==void 0)V.input_transformations=W;yield y0("message_delta",V);continue}break}}yield iG(C)}return{refused:null,model:B,blocks:z.contentBlocks(),nextIndex:z.nextIndex}}class lZ{indexBase;blocks=[];nextIndex;open=[];constructor(J=0){this.indexBase=J;this.nextIndex=J}contentBlocks(){return this.blocks.map((J)=>J.block)}start(J){this.blocks.push({index:J.index,block:{...J.content_block}}),J.index+=this.indexBase,this.open.push(J.index),this.nextIndex=Math.max(this.nextIndex,J.index+1)}delta(J){pG(this.blocks,J.index,J.delta),J.index+=this.indexBase}stop(J){J.index+=this.indexBase;let $=this.open.indexOf(J.index);if($!==-1)this.open.splice($,1);this.nextIndex=Math.max(this.nextIndex,J.index+1)}*closeOpenBlocks(){for(let J of this.open)yield y0("content_block_stop",{type:"content_block_stop",index:J});this.open.length=0}}function iZ(J){return{token:J,mode:"best_effort"}}function cG(J,{model:$,creditToken:Z,continuation:X}){let G=JSON.parse(J.body);if(G.model=$,G.fallback_credit_token=iZ(Z),X.length)G.messages=[...G.messages,{role:"assistant",content:X}];return{...J,headers:new Headers(J.headers),body:JSON.stringify(G)}}function pG(J,$,Z){let X=J.find((G)=>G.index===$)?.block;if(!X)return;switch(Z.type){case"text_delta":{X.text=(X.text??"")+Z.text;break}case"input_json_delta":{X._partial_json=(X._partial_json??"")+Z.partial_json;break}case"citations_delta":(X.citations??=[]).push(Z.citation);break;case"thinking_delta":{X.thinking=(X.thinking??"")+Z.thinking;break}case"signature_delta":{X.signature=Z.signature;break}case"compaction_delta":break;default:((G)=>{})(Z)}}function dZ(J){return J.map(($)=>{if(typeof $?._partial_json!=="string")return $;let{_partial_json:Z,...X}=$;return{...X,input:o0(Z)??X.input}})}function lG(J,$){let Z=new Headers(J.headers),X=new Set(Z.get("puku-beta")?.split(",").map((G)=>G.trim()));for(let G of $)if(!X.has(G))Z.append("puku-beta",G),X.add(G);return Z.set(J2,_6(Z.get(J2),"fallback-refusal-middleware")),{...J,headers:Z}}function y0(J,$){let Z={event:J,data:JSON.stringify($),raw:[]};return pZ.encode(nZ(Z))}function iG(J){return pZ.encode(J.raw.length?J.raw.join(`
58
58
  `)+`
59
59
 
60
- `:nZ(J))}function NJ(J,$,Z){return{type:J,model:$,input_tokens:Z?.input_tokens??0,output_tokens:Z?.output_tokens??0,cache_read_input_tokens:Z?.cache_read_input_tokens??0,cache_creation_input_tokens:Z?.cache_creation_input_tokens??0,cache_creation:Z?.cache_creation??null}}function cZ(J,$){let Z={...$??{},...J??{}};for(let X of Object.keys(Z))if(Z[X]==null&&$?.[X]!=null)Z[X]=$[X];return Z}function nZ(J){let $="";if(J.event!==null)$+=`event: ${J.event}
60
+ `:nZ(J))}function N4(J,$,Z){return{type:J,model:$,input_tokens:Z?.input_tokens??0,output_tokens:Z?.output_tokens??0,cache_read_input_tokens:Z?.cache_read_input_tokens??0,cache_creation_input_tokens:Z?.cache_creation_input_tokens??0,cache_creation:Z?.cache_creation??null}}function cZ(J,$){let Z={...$??{},...J??{}};for(let X of Object.keys(Z))if(Z[X]==null&&$?.[X]!=null)Z[X]=$[X];return Z}function nZ(J){let $="";if(J.event!==null)$+=`event: ${J.event}
61
61
  `;for(let Z of J.data.split(`
62
62
  `))$+=`data: ${Z}
63
63
  `;return $+`
64
- `}function nX(J,$){return()=>J.abort($.reason)}var pZ,gX;var aZ=M(()=>{c();q2();E();q0();Q0();pZ=new TextEncoder,gX=["fallback-credit-2026-07-01"]});var k1=M(()=>{CJ();S6();q1();aZ();CJ();_();r0();m1();c();q2()});k1();i6();k1();l6();function oZ(J){let $=Object.values(J).filter((X)=>typeof X==="number");return Object.entries(J).filter(([X,G])=>$.indexOf(+X)===-1).map(([X,G])=>G)}function i0(J,$,Z){Object.defineProperty(J,$,{value:Z,writable:!0,enumerable:!0,configurable:!0})}var Gg="captureStackTrace"in Error?Error.captureStackTrace:(...J)=>{};var rZ=/^-?\d+$/,tZ=/^-?\d+(?:\.\d+)?$/;var sZ;class eZ{constructor(){this._map=new WeakMap,this._idmap=new Map}add(J,...$){let Z=$[0];if(this._map.set(J,Z),Z&&typeof Z==="object"&&"id"in Z)this._idmap.set(Z.id,J);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(J){let $=this._map.get(J);if($&&typeof $==="object"&&"id"in $)this._idmap.delete($.id);return this._map.delete(J),this}get(J){let $=J._zod.parent;if($){let Z={...this.get($)??{}};delete Z.id;let X={...Z,...this._map.get(J)};return Object.keys(X).length?X:void 0}return this._map.get(J)}has(J){return this._map.has(J)}}function oX(){return new eZ}(sZ=globalThis).__zod_globalRegistry??(sZ.__zod_globalRegistry=oX());var J9=globalThis.__zod_globalRegistry;function a8(J,...$){for(let Z of $)for(let X of Reflect.ownKeys(Z))if(Object.prototype.propertyIsEnumerable.call(Z,X))i0(J,X,Z[X]);return J}function c1(J){let $=J?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";return{processors:J.processors??{},metadataRegistry:J?.metadata??J9,target:$,unrepresentable:J?.unrepresentable??"throw",override:J?.override??(()=>{}),io:J?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:J?.cycles??"ref",reused:J?.reused??"inline",intersections:[],deferred:[],external:J?.external??void 0}}function $0(J,$,Z,X,G){let Q=typeof $.unrepresentable==="function"?$.unrepresentable({zodSchema:J,path:X.path,message:G}):$.unrepresentable;if(Q==="any")return!1;if(Q===void 0||Q==="throw")throw Error(G);return Object.assign(Z,Q),!0}function p(J,$,Z={path:[],schemaPath:[]}){var X;let G=J._zod.def,Q=$.seen.get(J);if(Q){if(Q.count++,Z.schemaPath.includes(J))Q.cycle=Z.path;return Q.schema}let Y={schema:{},count:1,cycle:void 0,path:Z.path};$.seen.set(J,Y),$.sharedDefsExtractedFor=void 0,$.sharedEmitDoneFor=void 0;let z=J._zod.toJSONSchema?.();if(z)Y.schema=z;else{let W={...Z,schemaPath:[...Z.schemaPath,J],path:Z.path};if(J._zod.processJSONSchema)J._zod.processJSONSchema($,Y.schema,W);else{let V=Y.schema,F=$.processors[G.type];if(!F)throw Error(`[toJSONSchema]: Non-representable type encountered: ${G.type}`);F(J,$,V,W)}let C=J._zod.parent;if(C){if(!Y.ref)Y.ref=C;p(C,$,W),$.seen.get(C).isParent=!0}}let B=$.metadataRegistry.get(J);if(B)a8(Y.schema,B);if($.io==="input"&&z0(J))delete Y.schema.examples,delete Y.schema.default;if($.io==="input"&&"_prefault"in Y.schema)(X=Y.schema).default??(X.default=Y.schema._prefault);return delete Y.schema._prefault,$.seen.get(J).schema}function $9(J){return J.replace(/~/g,"~0").replace(/\//g,"~1")}function p1(J,$){let Z=J.seen.get($);if(!Z)throw Error("Unprocessed schema. This is a bug in Zod.");if(J.external&&J.sharedDefsExtractedFor===J.external)return;let X=new Map;for(let Y of J.seen.entries()){let z=J.metadataRegistry.get(Y[0])?.id;if(z){let B=X.get(z);if(B&&B!==Y[0])throw Error(`Duplicate schema id "${z}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);X.set(z,Y[0])}}let G=(Y)=>{let z=J.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let C=J.external.registry.get(Y[0])?.id,V=J.external.uri??((q)=>q);if(C)return{ref:V(C)};let F=Y[1].defId??Y[1].schema.id??`schema${J.counter++}`;return Y[1].defId=F,{defId:F,ref:`${V("__shared")}#/${z}/${$9(F)}`}}let B="#",K=`${B}/${z}/`;if(Y[1]===Z&&!Y[1].schema.id)return{ref:B};let W=Y[1].schema.id??`__schema${J.counter++}`;return{defId:W,ref:K+$9(W)}},Q=(Y)=>{if(Y[1].schema.$ref)return;let z=Y[1],{ref:B,defId:K}=G(Y);if(z.def={...z.schema},K)z.defId=K;let W=z.schema;for(let C in W)delete W[C];W.$ref=B};if(J.cycles==="throw")for(let Y of J.seen.entries()){let z=Y[1];if(z.cycle)throw Error(`Cycle detected: #/${z.cycle?.join("/")}/<root>
64
+ `}function nG(J,$){return()=>J.abort($.reason)}var pZ,gG;var aZ=M(()=>{c();q2();E();q0();Q0();pZ=new TextEncoder,gG=["fallback-credit-2026-07-01"]});var k1=M(()=>{C4();S6();q1();aZ();C4();_();r0();m1();c();q2()});k1();i6();k1();l6();function oZ(J){let $=Object.values(J).filter((X)=>typeof X==="number");return Object.entries(J).filter(([X,G])=>$.indexOf(+X)===-1).map(([X,G])=>G)}function i0(J,$,Z){Object.defineProperty(J,$,{value:Z,writable:!0,enumerable:!0,configurable:!0})}var Gg="captureStackTrace"in Error?Error.captureStackTrace:(...J)=>{};var rZ=/^-?\d+$/,tZ=/^-?\d+(?:\.\d+)?$/;var sZ;class eZ{constructor(){this._map=new WeakMap,this._idmap=new Map}add(J,...$){let Z=$[0];if(this._map.set(J,Z),Z&&typeof Z==="object"&&"id"in Z)this._idmap.set(Z.id,J);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(J){let $=this._map.get(J);if($&&typeof $==="object"&&"id"in $)this._idmap.delete($.id);return this._map.delete(J),this}get(J){let $=J._zod.parent;if($){let Z={...this.get($)??{}};delete Z.id;let X={...Z,...this._map.get(J)};return Object.keys(X).length?X:void 0}return this._map.get(J)}has(J){return this._map.has(J)}}function oG(){return new eZ}(sZ=globalThis).__zod_globalRegistry??(sZ.__zod_globalRegistry=oG());var J9=globalThis.__zod_globalRegistry;function a8(J,...$){for(let Z of $)for(let X of Reflect.ownKeys(Z))if(Object.prototype.propertyIsEnumerable.call(Z,X))i0(J,X,Z[X]);return J}function c1(J){let $=J?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";return{processors:J.processors??{},metadataRegistry:J?.metadata??J9,target:$,unrepresentable:J?.unrepresentable??"throw",override:J?.override??(()=>{}),io:J?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:J?.cycles??"ref",reused:J?.reused??"inline",intersections:[],deferred:[],external:J?.external??void 0}}function $0(J,$,Z,X,G){let Q=typeof $.unrepresentable==="function"?$.unrepresentable({zodSchema:J,path:X.path,message:G}):$.unrepresentable;if(Q==="any")return!1;if(Q===void 0||Q==="throw")throw Error(G);return Object.assign(Z,Q),!0}function p(J,$,Z={path:[],schemaPath:[]}){var X;let G=J._zod.def,Q=$.seen.get(J);if(Q){if(Q.count++,Z.schemaPath.includes(J))Q.cycle=Z.path;return Q.schema}let Y={schema:{},count:1,cycle:void 0,path:Z.path};$.seen.set(J,Y),$.sharedDefsExtractedFor=void 0,$.sharedEmitDoneFor=void 0;let z=J._zod.toJSONSchema?.();if(z)Y.schema=z;else{let W={...Z,schemaPath:[...Z.schemaPath,J],path:Z.path};if(J._zod.processJSONSchema)J._zod.processJSONSchema($,Y.schema,W);else{let V=Y.schema,F=$.processors[G.type];if(!F)throw Error(`[toJSONSchema]: Non-representable type encountered: ${G.type}`);F(J,$,V,W)}let C=J._zod.parent;if(C){if(!Y.ref)Y.ref=C;p(C,$,W),$.seen.get(C).isParent=!0}}let B=$.metadataRegistry.get(J);if(B)a8(Y.schema,B);if($.io==="input"&&z0(J))delete Y.schema.examples,delete Y.schema.default;if($.io==="input"&&"_prefault"in Y.schema)(X=Y.schema).default??(X.default=Y.schema._prefault);return delete Y.schema._prefault,$.seen.get(J).schema}function $9(J){return J.replace(/~/g,"~0").replace(/\//g,"~1")}function p1(J,$){let Z=J.seen.get($);if(!Z)throw Error("Unprocessed schema. This is a bug in Zod.");if(J.external&&J.sharedDefsExtractedFor===J.external)return;let X=new Map;for(let Y of J.seen.entries()){let z=J.metadataRegistry.get(Y[0])?.id;if(z){let B=X.get(z);if(B&&B!==Y[0])throw Error(`Duplicate schema id "${z}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);X.set(z,Y[0])}}let G=(Y)=>{let z=J.target==="draft-2020-12"?"$defs":"definitions";if(J.external){let C=J.external.registry.get(Y[0])?.id,V=J.external.uri??((q)=>q);if(C)return{ref:V(C)};let F=Y[1].defId??Y[1].schema.id??`schema${J.counter++}`;return Y[1].defId=F,{defId:F,ref:`${V("__shared")}#/${z}/${$9(F)}`}}let B="#",K=`${B}/${z}/`;if(Y[1]===Z&&!Y[1].schema.id)return{ref:B};let W=Y[1].schema.id??`__schema${J.counter++}`;return{defId:W,ref:K+$9(W)}},Q=(Y)=>{if(Y[1].schema.$ref)return;let z=Y[1],{ref:B,defId:K}=G(Y);if(z.def={...z.schema},K)z.defId=K;let W=z.schema;for(let C in W)delete W[C];W.$ref=B};if(J.cycles==="throw")for(let Y of J.seen.entries()){let z=Y[1];if(z.cycle)throw Error(`Cycle detected: #/${z.cycle?.join("/")}/<root>
65
65
 
66
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let Y of J.seen.entries()){let z=Y[1];if($===Y[0]){Q(Y);continue}if(J.external){let K=J.external.registry.get(Y[0])?.id;if($!==Y[0]&&K){Q(Y);continue}}if(J.metadataRegistry.get(Y[0])?.id){Q(Y);continue}if(z.cycle){Q(Y);continue}if(z.count>1){if(J.reused==="ref"){Q(Y);continue}}}if(J.external)J.sharedDefsExtractedFor=J.external}function Q9(J){let $=J.anyOf;if(!Array.isArray($)||$.length===0||J.type!==void 0)return;let Z=[];for(let X of $){if(!X||typeof X!=="object")return;Q9(X);let G=Object.keys(X);if(G.length!==1||G[0]!=="type")return;let Q=X.type;for(let Y of Array.isArray(Q)?Q:[Q]){if(typeof Y!=="string")return;if(!Z.includes(Y))Z.push(Y)}}delete J.anyOf,J.type=Z.length===1?Z[0]:Z}var Y9=new Set(["type","properties","required","additionalProperties"]),Z9=["oneOf","anyOf"];function X9(J){let $=J.additionalProperties;if($===void 0||$===!1||typeof $!=="object"||$===null)return null;return Object.keys($).length?$:null}function FJ(J){let $=[];for(let Q of J){if(typeof Q!=="object"||Q.type!=="object")return null;for(let Y in Q)if(!Y9.has(Y))return null;$.push(Q)}let Z={},X=new Set;for(let Q of $){for(let Y in Q.properties){if(Object.prototype.hasOwnProperty.call(Z,Y))continue;let z=[];for(let K of $){let W=K.properties?.[Y]??X9(K);if(W===null||W===void 0)continue;if(!z.some((C)=>JSON.stringify(C)===JSON.stringify(W)))z.push(W)}let B=z.length===1?z[0]:FJ(z)??{allOf:z};i0(Z,Y,B)}for(let Y of Q.required??[])X.add(Y)}let G={type:"object",properties:Z};if(X.size)G.required=[...X];if($.every((Q)=>Q.additionalProperties===!1))G.additionalProperties=!1;else{let Q=[];for(let Y of $){let z=X9(Y);if(z&&!Q.some((B)=>JSON.stringify(B)===JSON.stringify(z)))Q.push(z)}if(Q.length===1)G.additionalProperties=Q[0];else if(Q.length>1)G.additionalProperties={allOf:Q}}return G}function rX(J){let $=J.allOf;if(!Array.isArray($)||$.length<2)return;for(let G of Y9)if(G in J)return;let Z=$.filter((G)=>Z9.some((Q)=>Array.isArray(G[Q]))),X=null;if(!Z.length)X=FJ($);else{let G=Z[0],Q=Z9.find((B)=>Array.isArray(G[B]));if(Object.keys(G).length!==1)return;let Y=$.filter((B)=>B!==G),z=G[Q].map((B)=>FJ([...Y,B]));if(z.some((B)=>!B))return;X={[Q]:z}}if(!X)return;delete J.allOf,a8(J,X)}function l1(J,$){let Z=J.seen.get($);if(!Z)throw Error("Unprocessed schema. This is a bug in Zod.");let X=(z)=>{let B=J.seen.get(z);if(B.ref===null)return;let K=B.def??B.schema,W={...K},C=B.ref;if(B.ref=null,C){X(C);let F=J.seen.get(C),q=F.schema;if(q.$ref&&(J.target==="draft-07"||J.target==="draft-04"||J.target==="openapi-3.0"))K.allOf=K.allOf??[],K.allOf.push(q);else a8(K,q);if(a8(K,W),z._zod.parent===C)for(let R in K){if(R==="$ref"||R==="allOf")continue;if(!(R in W))delete K[R]}if(q.$ref&&F.def)for(let R in K){if(R==="$ref"||R==="allOf")continue;if(R in F.def&&JSON.stringify(K[R])===JSON.stringify(F.def[R]))delete K[R]}}let V=z._zod.parent;if(V&&V!==C){X(V);let F=J.seen.get(V);if(F?.schema.$ref){if(K.$ref=F.schema.$ref,F.def)for(let q in K){if(q==="$ref"||q==="allOf")continue;if(q in F.def&&JSON.stringify(K[q])===JSON.stringify(F.def[q]))delete K[q]}}}J.override({zodSchema:z,jsonSchema:K,path:B.path??[]})};if(!J.external||J.sharedEmitDoneFor!==J.external){for(let z of[...J.seen.entries()].reverse())X(z[0]);if(J.target!=="openapi-3.0")for(let z of J.seen.entries())Q9(z[1].def??z[1].schema);for(let z of J.deferred)z();if(J.intersections.length){let z=new Map;for(let B of J.seen.values())for(let K of[B.schema,B.def]){let W=K?.allOf;if(!Array.isArray(W))continue;let C=z.get(W);if(C)C.push(K);else z.set(W,[K])}for(let B of J.intersections)for(let K of z.get(B)??[])rX(K)}}let G={};if(J.target==="draft-2020-12")G.$schema="https://json-schema.org/draft/2020-12/schema";else if(J.target==="draft-07")G.$schema="http://json-schema.org/draft-07/schema#";else if(J.target==="draft-04")G.$schema="http://json-schema.org/draft-04/schema#";else if(J.target==="openapi-3.0");if(J.external?.uri){let z=J.external.registry.get($)?.id;if(!z)throw Error("Schema is missing an `id` property");G.$id=J.external.uri(z)}a8(G,Z.defId?Z.schema:Z.def??Z.schema);let Q=J.metadataRegistry.get($)?.id;if(Q!==void 0&&G.id===Q)delete G.id;let Y=J.external?.defs??{};if(!J.external||J.sharedEmitDoneFor!==J.external)for(let z of J.seen.entries()){let B=z[1];if(B.def&&B.defId){if(B.def.id===B.defId)delete B.def.id;i0(Y,B.defId,B.def)}}if(J.external)J.sharedEmitDoneFor=J.external;if(J.external);else if(Object.keys(Y).length>0)if(J.target==="draft-2020-12")G.$defs=Y;else G.definitions=Y;try{let z=JSON.parse(JSON.stringify(G));return Object.defineProperty(z,"~standard",{value:{...$["~standard"],jsonSchema:{input:G9($,"input",J.processors),output:G9($,"output",J.processors)}},enumerable:!1,writable:!1}),z}catch(z){throw Error("Error converting schema to JSON.")}}function z0(J,$){let Z=$??{seen:new Set};if(Z.seen.has(J))return!1;Z.seen.add(J);let X=J._zod.def;if(X.type==="transform")return!0;if(X.type==="array")return z0(X.element,Z);if(X.type==="set")return z0(X.valueType,Z);if(X.type==="lazy")return z0(X.getter(),Z);if(X.type==="promise"||X.type==="optional"||X.type==="nonoptional"||X.type==="nullable"||X.type==="readonly"||X.type==="default"||X.type==="prefault"||X.type==="catch")return z0(X.innerType,Z);if(X.type==="intersection")return z0(X.left,Z)||z0(X.right,Z);if(X.type==="record"||X.type==="map")return z0(X.keyType,Z)||z0(X.valueType,Z);if(X.type==="pipe"){if(J._zod.traits.has("$ZodCodec"))return!0;return z0(X.in,Z)||z0(X.out,Z)}if(X.type==="object"){for(let G in X.shape)if(z0(X.shape[G],Z))return!0;return!1}if(X.type==="union"){for(let G of X.options)if(z0(G,Z))return!0;return!1}if(X.type==="tuple"){for(let G of X.items)if(z0(G,Z))return!0;if(X.rest&&z0(X.rest,Z))return!0;return!1}return!1}var G9=(J,$,Z={})=>(X)=>{let{libraryOptions:G,target:Q}=X??{},Y=c1({...G??{},target:Q,io:$,processors:Z});return p(J,Y),p1(Y,J),l1(Y,J)};var tX={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sX=(J,$,Z,X)=>{let G=Z;G.type="string";let{minimum:Q,maximum:Y,format:z,patterns:B,contentEncoding:K,laxFormat:W}=J._zod.bag;if(typeof Q==="number")G.minLength=Q;if(typeof Y==="number")G.maxLength=Y;if(z){if(G.format=tX[z]??z,G.format==="")delete G.format;if(z==="time"||W)delete G.format}if(K)G.contentEncoding=K;if(B&&B.size>0){let C=[...B];if(C.length===1)G.pattern=C[0].source;else if(C.length>1)G.allOf=[...C.map((V)=>({...$.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"?{type:"string"}:{},pattern:V.source}))]}},eX=(J,$,Z,X)=>{let G=Z,{minimum:Q,maximum:Y,format:z,multipleOf:B,exclusiveMaximum:K,exclusiveMinimum:W}=J._zod.bag;if(typeof z==="string"&&z.includes("int"))G.type="integer";else G.type="number";let C=typeof W==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),V=typeof K==="number"&&K<=(Y??Number.POSITIVE_INFINITY),F=$.target==="draft-04"||$.target==="openapi-3.0";if(C)if(F)G.minimum=W,G.exclusiveMinimum=!0;else G.exclusiveMinimum=W;else if(typeof Q==="number")G.minimum=Q;if(V)if(F)G.maximum=K,G.exclusiveMaximum=!0;else G.exclusiveMaximum=K;else if(typeof Y==="number")G.maximum=Y;if(typeof B==="number")if(Number.isFinite(B)&&B!==0)G.multipleOf=Math.abs(B);else $0(J,$,G,X,`A multipleOf divisor of ${B} cannot be represented in JSON Schema`)},JG=(J,$,Z,X)=>{Z.type="boolean"},$G=(J,$,Z,X)=>{$0(J,$,Z,X,"BigInt cannot be represented in JSON Schema")},ZG=(J,$,Z,X)=>{$0(J,$,Z,X,"Symbols cannot be represented in JSON Schema")},XG=(J,$,Z,X)=>{if($.target==="openapi-3.0")Z.type="string",Z.nullable=!0,Z.enum=[null];else Z.type="null"},GG=(J,$,Z,X)=>{$0(J,$,Z,X,"Undefined cannot be represented in JSON Schema")},QG=(J,$,Z,X)=>{$0(J,$,Z,X,"Void cannot be represented in JSON Schema")},YG=(J,$,Z,X)=>{Z.not={}},zG=(J,$,Z,X)=>{},BG=(J,$,Z,X)=>{},KG=(J,$,Z,X)=>{$0(J,$,Z,X,"Date cannot be represented in JSON Schema")},WG=(J,$,Z,X)=>{let G=J._zod.def,Q=oZ(G.entries);if(Q.length===0){Z.not={};return}if(Q.every((Y)=>typeof Y==="number"))Z.type="number";if(Q.every((Y)=>typeof Y==="string"))Z.type="string";Z.enum=Q},VG=(J,$,Z,X)=>{let G=J._zod.def;if(G.values.length===0){Z.not={};return}let Q=[];for(let Y of G.values)if(Y===void 0){if($0(J,$,Z,X,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof Y==="bigint"){if($0(J,$,Z,X,"BigInt literals cannot be represented in JSON Schema"))return;Q.push(Number(Y))}else Q.push(Y);if(Q.length===0);else if(Q.length===1){let Y=Q[0];if(Z.type=Y===null?"null":typeof Y,$.target==="draft-04"||$.target==="openapi-3.0")Z.enum=[Y];else Z.const=Y}else{if(Q.every((Y)=>typeof Y==="number"))Z.type="number";if(Q.every((Y)=>typeof Y==="string"))Z.type="string";if(Q.every((Y)=>typeof Y==="boolean"))Z.type="boolean";if(Q.every((Y)=>Y===null))Z.type="null";Z.enum=Q}},CG=(J,$,Z,X)=>{$0(J,$,Z,X,"NaN cannot be represented in JSON Schema")},UG=(J,$,Z,X)=>{let G=Z,Q=J._zod.pattern;if(!Q)throw Error("Pattern not found in template literal");G.type="string",G.pattern=Q.source},NG=(J,$,Z,X)=>{let G=Z,Q={type:"string",format:"binary",contentEncoding:"binary"},{minimum:Y,maximum:z,mime:B}=J._zod.bag;if(Y!==void 0)Q.minLength=Y;if(z!==void 0)Q.maxLength=z;if(B)if(B.length===1)Q.contentMediaType=B[0],Object.assign(G,Q);else Object.assign(G,Q),G.anyOf=B.map((K)=>({contentMediaType:K}));else Object.assign(G,Q)},FG=(J,$,Z,X)=>{Z.type="boolean"},qG=(J,$,Z,X)=>{$0(J,$,Z,X,"Custom types cannot be represented in JSON Schema")},MG=(J,$,Z,X)=>{$0(J,$,Z,X,"Function types cannot be represented in JSON Schema")},TG=(J,$,Z,X)=>{$0(J,$,Z,X,"Transforms cannot be represented in JSON Schema")},wG=(J,$,Z,X)=>{$0(J,$,Z,X,"Map cannot be represented in JSON Schema")},OG=(J,$,Z,X)=>{$0(J,$,Z,X,"Set cannot be represented in JSON Schema")},RG=(J,$,Z,X)=>{let G=Z,Q=J._zod.def,{minimum:Y,maximum:z}=J._zod.bag;if(typeof Y==="number")G.minItems=Y;if(typeof z==="number")G.maxItems=z;G.type="array",G.items=p(Q.element,$,{...X,path:[...X.path,"items"]})};function o8(J){let $=J._zod.def;if($.type==="pipe"&&$.in._zod.traits.has("$ZodTransform"))return o8($.out);if($.type==="catch")return o8($.innerType);return J._zod.optin}var AG=(J,$,Z,X)=>{let G=Z,Q=J._zod.def,Y=Q.shape;if(Object.getOwnPropertySymbols(Y).length&&$0(J,$,G,X,"Symbol keys cannot be represented in JSON Schema"))return;G.type="object",G.properties={};for(let W in Y)i0(G.properties,W,p(Y[W],$,{...X,path:[...X.path,"properties",W]}));let B=new Set(Object.keys(Y)),K=new Set([...B].filter((W)=>{let C=Q.shape[W];if($.io==="input")return o8(C)===void 0;else return C._zod.optout===void 0}));if(K.size>0)G.required=Array.from(K);if(Q.catchall?._zod.def.type==="never")G.additionalProperties=!1;else if(!Q.catchall){if($.io==="output")G.additionalProperties=!1}else if(Q.catchall)G.additionalProperties=p(Q.catchall,$,{...X,path:[...X.path,"additionalProperties"]})},HG=(J,$,Z,X)=>{let G=J._zod.def,Q=G.inclusive===!1,Y=G.options.map((z,B)=>p(z,$,{...X,path:[...X.path,Q?"oneOf":"anyOf",B]}));if(Q)Z.oneOf=Y;else Z.anyOf=Y},LG=(J,$,Z,X)=>{let G=J._zod.def,Q=p(G.left,$,{...X,path:[...X.path,"allOf",0]}),Y=p(G.right,$,{...X,path:[...X.path,"allOf",1]}),z=(K)=>("allOf"in K)&&Object.keys(K).length===1,B=[...z(Q)?Q.allOf:[Q],...z(Y)?Y.allOf:[Y]];Z.allOf=B,$.intersections.push(B)},DG=(J,$,Z,X)=>{let G=Z,Q=J._zod.def;G.type="array";let Y=$.target==="draft-2020-12"?"prefixItems":"items",z=$.target==="draft-2020-12"?"items":$.target==="openapi-3.0"?"items":"additionalItems",B=Q.items.map((A,R)=>p(A,$,{...X,path:[...X.path,Y,R]})),K=Q.rest?p(Q.rest,$,{...X,path:[...X.path,z,...$.target==="openapi-3.0"?[Q.items.length]:[]]}):null,W=Q.items.length;while(W>0){let A=Q.items[W-1];if(!($.io==="input"?o8(A)!==void 0:A._zod.optout==="optional"))break;W--}let C=Q.items.length,V=!Q.rest;if($.target==="draft-2020-12"){if(G.prefixItems=B,V)G.items=!1;else if(K)G.items=K;if(W>0)G.minItems=W;if(V)G.maxItems=C}else if($.target==="openapi-3.0"){if(G.items={anyOf:B},K)G.items.anyOf.push(K);if(W>0)G.minItems=W;if(V)G.maxItems=C}else{if(G.items=B,V)G.additionalItems=!1;else if(K)G.additionalItems=K;if(W>0)G.minItems=W;if(V)G.maxItems=C}let{minimum:F,maximum:q}=J._zod.bag;if(typeof F==="number")G.minItems=F;if(typeof q==="number")G.maxItems=q};function qJ(J,$,Z){if($.$ref){if(Z.has($))return $;Z.add($);let q=J.get($)?.def;if(!q)return $;let A=qJ(J,q,Z);return A===q?$:A}for(let q of["anyOf","oneOf"]){let A=$[q];if(!Array.isArray(A))continue;let R=A.map((H)=>qJ(J,H,Z));if(R.some((H,O)=>H!==A[O]))$={...$,[q]:R}}let X=Array.isArray($.type)?$.type:[$.type],G=!X.includes("string")&&X.some((q)=>q==="number"||q==="integer"),Q=$.enum??($.const!==void 0?[$.const]:void 0);if(!G&&!Q?.some((q)=>typeof q==="number"))return $;let{minimum:Y,maximum:z,exclusiveMinimum:B,exclusiveMaximum:K,multipleOf:W,format:C,id:V,...F}=$;if(F.enum)F.enum=F.enum.map((q)=>typeof q==="number"?String(q):q);else if(typeof F.const==="number")F.const=String(F.const);if(!G)return F;if(F.type="string",!Q)F.pattern=(X.includes("number")?tZ:rZ).source;return F}var MJ=new WeakMap;function jG(J){let $=new Map;for(let X of J.seen.values())if(X.def&&!$.has(X.schema))$.set(X.schema,X);let Z=new Map;for(let X of MJ.get(J)??[]){let G=J.seen.get(X),Q=(G?.def??G?.schema)?.propertyNames;if(!Q||Q===!0||Z.has(Q))continue;let Y=qJ($,Q,new Set);if(Y!==Q)Z.set(Q,Y)}if(!Z.size)return;for(let X of J.seen.values())for(let G of[X.schema,X.def]){let Q=G&&Z.get(G.propertyNames);if(Q)G.propertyNames=Q}}var PG=(J,$,Z,X)=>{let G=Z,Q=J._zod.def;G.type="object";let Y=Q.keyType,B=Y._zod.bag?.patterns;if(Q.mode==="loose"&&B&&B.size>0){let C=p(Q.valueType,$,{...X,path:[...X.path,"patternProperties","*"]});G.patternProperties={};for(let V of B)i0(G.patternProperties,V.source,C)}else{if($.target==="draft-07"||$.target==="draft-2020-12"){G.propertyNames=p(Q.keyType,$,{...X,path:[...X.path,"propertyNames"]});let C=MJ.get($);if(!C)C=[],MJ.set($,C),$.deferred.push(()=>jG($));C.push(J)}G.additionalProperties=p(Q.valueType,$,{...X,path:[...X.path,"additionalProperties"]})}let K=Y._zod.values,W=$.io==="input"&&o8(Q.valueType)!==void 0;if(K&&!Q.partial&&!W){let C=[...K].filter((V)=>typeof V==="string"||typeof V==="number");if(C.length>0)G.required=C.map(String)}},SG=(J,$,Z,X)=>{let G=J._zod.def,Q=p(G.innerType,$,X),Y=$.seen.get(J);if($.target==="openapi-3.0")Y.ref=G.innerType,Z.nullable=!0;else Z.anyOf=[Q,{type:"null"}]},_G=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType},TJ=Symbol();function B9(J,$,Z,X,G){let Q=!1,Y=JSON.stringify(J,(z,B)=>{if(typeof B!=="bigint")return B;return Q=!0,null});if(!Q)return JSON.parse(Y);return $0($,Z,X,G,"BigInt defaults cannot be represented in JSON Schema"),TJ}var EG=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType;let Y=B9(G.defaultValue,J,$,Z,X);if(Y!==TJ)Z.default=Y},IG=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);if(Q.ref=G.innerType,$.io!=="input")return;let Y=B9(G.defaultValue,J,$,Z,X);if(Y!==TJ)Z._prefault=Y},yG=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType;let Y;try{Y=G.catchValue(void 0)}catch{$0(J,$,Z,X,"Dynamic catch values are not supported in JSON Schema");return}Z.default=Y},xG=(J,$,Z,X)=>{let G=J._zod.def,Q=G.in._zod.traits.has("$ZodTransform"),Y=$.io==="input"?Q?G.out:G.in:G.out;p(Y,$,X);let z=$.seen.get(J);z.ref=Y},kG=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType,Z.readOnly=!0},fG=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType},vG=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType},bG=(J,$,Z,X)=>{let G=J._zod.innerType;p(G,$,X);let Q=$.seen.get(J);Q.ref=G},z9={string:sX,number:eX,boolean:JG,bigint:$G,symbol:ZG,null:XG,undefined:GG,void:QG,never:YG,any:zG,unknown:BG,date:KG,enum:WG,literal:VG,nan:CG,template_literal:UG,file:NG,success:FG,custom:qG,function:MG,transform:TG,map:wG,set:OG,array:RG,object:AG,union:HG,intersection:LG,tuple:DG,record:PG,nullable:SG,nonoptional:_G,default:EG,prefault:IG,catch:yG,pipe:xG,readonly:kG,promise:fG,optional:vG,lazy:bG};function i1(J,$){if("_idmap"in J){let X=J,G=c1({...$,processors:z9}),Q={};for(let B of X._idmap.entries()){let[K,W]=B;p(W,G)}let Y={},z={registry:X,uri:$?.uri,defs:Q};G.external=z;for(let B of X._idmap.entries()){let[K,W]=B;p1(G,W),i0(Y,K,l1(G,W))}if(Object.keys(Q).length>0){let B=G.target==="draft-2020-12"?"$defs":"definitions";Y.__shared={[B]:Q}}return{schemas:Y}}let Z=c1({...$,processors:z9});return p(J,Z),p1(Z,J),l1(Z,J)}c();function gG(J){return{type:"json_schema",schema:{...x1(i1(J,{reused:"ref"}))},parse:(Z)=>{let X=J.safeParse(JSON.parse(Z));if(!X.success)throw new T(`Failed to parse structured output: ${X.error.message} cause: ${X.error.issues}`);return X.data}}}function hG(J){let $=i1(J.inputSchema,{reused:"ref"});if($.type!=="object")throw Error(`Zod schema for tool "${J.name}" must be an object, but got ${$.type}`);let Z=$;return{type:"custom",name:J.name,input_schema:Z,description:J.description,run:J.run,parse:(X)=>J.inputSchema.parse(X),...J.close?{close:J.close}:{}}}function mG(J){return{type:"memory_20250818",name:"memory",parse:($)=>$,run:($)=>{let Z=J[$.command];if(!Z)throw Error(`${$.command} not implemented`);return Z.bind(J)($)}}}I0();q0();K1();var uG=["image/jpeg","image/png","image/gif","image/webp"];function wJ(J){return uG.includes(J)}function dG(J){return!J||J.startsWith("text/")||J==="application/pdf"||wJ(J)}class R0 extends Error{constructor(J){super(J);this.name="UnsupportedMCPValueError"}}function K9(J,$,Z){let X={...J.inputSchema,type:"object",properties:J.inputSchema.properties??null,required:J.inputSchema.required??null};return{...{name:J.name,input_schema:X,...J.description!==void 0?{description:J.description}:{},...Z},run:async(Y)=>{let z=await $.callTool({name:J.name,arguments:Y});if(z.isError){let B=z.content.map((K)=>n1(K));throw new P(B)}if(z.content.length===0&&typeof z.structuredContent==="object"&&z.structuredContent!==null)return JSON.stringify(z.structuredContent);return z.content.map((B)=>n1(B))},parse:(Y)=>Y,[V0]:"mcpTool"}}function cG(J,$,Z){return J.map((X)=>K9(X,$,Z))}function W9(J,$){return{role:J.role,content:[n1(J.content,$)],[V0]:"mcpMessage"}}function pG(J,$){return J.map((Z)=>W9(Z,$))}function n1(J,$){switch(J.type){case"text":return{type:"text",text:J.text,...$,[V0]:"mcpContent"};case"image":{if(!wJ(J.mimeType))throw new R0(`Unsupported image MIME type: ${J.mimeType}`);return{type:"image",source:{type:"base64",data:J.data,media_type:J.mimeType},...$,[V0]:"mcpContent"}}case"resource":return V9(J.resource,$,"mcpContent");case"resource_link":case"audio":throw new R0(`Unsupported MCP content type: ${J.type}`);default:throw new R0(`Unsupported MCP content type: ${J.type}`)}}function V9(J,$,Z="mcpResourceToContent"){let X=J.mimeType;if(X&&wJ(X)){if(!("blob"in J))throw new R0(`Image resource must have blob data, not text. URI: ${J.uri}`);return{type:"image",source:{type:"base64",data:J.blob,media_type:X},...$,[V0]:Z}}if(X==="application/pdf"){if(!("blob"in J))throw new R0(`PDF resource must have blob data, not text. URI: ${J.uri}`);return{type:"document",source:{type:"base64",data:J.blob,media_type:"application/pdf"},...$,[V0]:Z}}if(!X||X.startsWith("text/"))return{type:"document",source:nG(J),...$,[V0]:Z};throw new R0(`Unsupported MIME type "${X}" for resource: ${J.uri}`)}function lG(J,$){if(J.contents.length===0)throw new R0("Resource contents array must contain at least one item");let Z=J.contents.find((X)=>dG(X.mimeType));if(!Z){let X=J.contents.map((G)=>G.mimeType).filter((G)=>G!==void 0);throw new R0(`No supported MIME type found in resource contents. Available: ${X.join(", ")}`)}return V9(Z,$)}function iG(J){if("blob"in J)return r2(J.blob);return new TextEncoder().encode(J.text)}function nG(J){return{type:"text",data:"text"in J?J.text:new TextDecoder().decode(r2(J.blob)),media_type:"text/plain"}}function aG(J){if(J.contents.length===0)throw new R0("Resource contents array must contain at least one item");let $=J.contents[0],Z=new URL($.uri).pathname.split("/").at(-1)||"file",X=$.mimeType,G=iG($),Q=new File([G],Z,X?{type:X}:void 0);return Q[V0]="mcpResourceToFile",Q}I0();K4();export{w1 as toFile,t6 as setupSkills,Y2 as resolvePath,cG as mcpTools,K9 as mcpTool,aG as mcpResourceToFile,lG as mcpResourceToContent,pG as mcpMessages,W9 as mcpMessage,n1 as mcpContent,v1 as extractSkillArchive,P0 as default,hG as betaZodTool,gG as betaZodOutputFormat,Q4 as betaWriteTool,m0 as betaTool,mX as betaRefusalFallbackMiddleware,G4 as betaReadTool,mG as betaMemoryTool,d3 as betaJSONSchemaOutputFormat,B4 as betaGrepTool,z4 as betaGlobTool,Y4 as betaEditTool,X4 as betaBashTool,TZ as betaAgentToolset20260401,B0 as VERSION,R0 as UnsupportedMCPValueError,p2 as UnprocessableEntityError,P as ToolError,s as Stream,t8 as RetryableError,l2 as RateLimitError,T as PukuError,P0 as PukuAI,u2 as PermissionDeniedError,T1 as PagePromise,f0 as OAUTH_API_BETA_HEADER,d2 as NotFoundError,D8 as MODEL_NONSTREAMING_TOKENS,i2 as InternalServerError,gZ as HUMAN_PROMPT,V6 as FEDERATION_BETA_HEADER,c2 as ConflictError,e1 as BetaFallbackState,g1 as BashTimeoutError,h1 as BashSession,d1 as BasePuku,h2 as BadRequestError,m2 as AuthenticationError,Z0 as APIUserAbortError,s0 as APIPromise,l as APIError,g2 as APIConnectionTimeoutError,S0 as APIConnectionError,hZ as AI_PROMPT};
66
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let Y of J.seen.entries()){let z=Y[1];if($===Y[0]){Q(Y);continue}if(J.external){let K=J.external.registry.get(Y[0])?.id;if($!==Y[0]&&K){Q(Y);continue}}if(J.metadataRegistry.get(Y[0])?.id){Q(Y);continue}if(z.cycle){Q(Y);continue}if(z.count>1){if(J.reused==="ref"){Q(Y);continue}}}if(J.external)J.sharedDefsExtractedFor=J.external}function Q9(J){let $=J.anyOf;if(!Array.isArray($)||$.length===0||J.type!==void 0)return;let Z=[];for(let X of $){if(!X||typeof X!=="object")return;Q9(X);let G=Object.keys(X);if(G.length!==1||G[0]!=="type")return;let Q=X.type;for(let Y of Array.isArray(Q)?Q:[Q]){if(typeof Y!=="string")return;if(!Z.includes(Y))Z.push(Y)}}delete J.anyOf,J.type=Z.length===1?Z[0]:Z}var Y9=new Set(["type","properties","required","additionalProperties"]),Z9=["oneOf","anyOf"];function X9(J){let $=J.additionalProperties;if($===void 0||$===!1||typeof $!=="object"||$===null)return null;return Object.keys($).length?$:null}function F4(J){let $=[];for(let Q of J){if(typeof Q!=="object"||Q.type!=="object")return null;for(let Y in Q)if(!Y9.has(Y))return null;$.push(Q)}let Z={},X=new Set;for(let Q of $){for(let Y in Q.properties){if(Object.prototype.hasOwnProperty.call(Z,Y))continue;let z=[];for(let K of $){let W=K.properties?.[Y]??X9(K);if(W===null||W===void 0)continue;if(!z.some((C)=>JSON.stringify(C)===JSON.stringify(W)))z.push(W)}let B=z.length===1?z[0]:F4(z)??{allOf:z};i0(Z,Y,B)}for(let Y of Q.required??[])X.add(Y)}let G={type:"object",properties:Z};if(X.size)G.required=[...X];if($.every((Q)=>Q.additionalProperties===!1))G.additionalProperties=!1;else{let Q=[];for(let Y of $){let z=X9(Y);if(z&&!Q.some((B)=>JSON.stringify(B)===JSON.stringify(z)))Q.push(z)}if(Q.length===1)G.additionalProperties=Q[0];else if(Q.length>1)G.additionalProperties={allOf:Q}}return G}function rG(J){let $=J.allOf;if(!Array.isArray($)||$.length<2)return;for(let G of Y9)if(G in J)return;let Z=$.filter((G)=>Z9.some((Q)=>Array.isArray(G[Q]))),X=null;if(!Z.length)X=F4($);else{let G=Z[0],Q=Z9.find((B)=>Array.isArray(G[B]));if(Object.keys(G).length!==1)return;let Y=$.filter((B)=>B!==G),z=G[Q].map((B)=>F4([...Y,B]));if(z.some((B)=>!B))return;X={[Q]:z}}if(!X)return;delete J.allOf,a8(J,X)}function l1(J,$){let Z=J.seen.get($);if(!Z)throw Error("Unprocessed schema. This is a bug in Zod.");let X=(z)=>{let B=J.seen.get(z);if(B.ref===null)return;let K=B.def??B.schema,W={...K},C=B.ref;if(B.ref=null,C){X(C);let F=J.seen.get(C),q=F.schema;if(q.$ref&&(J.target==="draft-07"||J.target==="draft-04"||J.target==="openapi-3.0"))K.allOf=K.allOf??[],K.allOf.push(q);else a8(K,q);if(a8(K,W),z._zod.parent===C)for(let R in K){if(R==="$ref"||R==="allOf")continue;if(!(R in W))delete K[R]}if(q.$ref&&F.def)for(let R in K){if(R==="$ref"||R==="allOf")continue;if(R in F.def&&JSON.stringify(K[R])===JSON.stringify(F.def[R]))delete K[R]}}let V=z._zod.parent;if(V&&V!==C){X(V);let F=J.seen.get(V);if(F?.schema.$ref){if(K.$ref=F.schema.$ref,F.def)for(let q in K){if(q==="$ref"||q==="allOf")continue;if(q in F.def&&JSON.stringify(K[q])===JSON.stringify(F.def[q]))delete K[q]}}}J.override({zodSchema:z,jsonSchema:K,path:B.path??[]})};if(!J.external||J.sharedEmitDoneFor!==J.external){for(let z of[...J.seen.entries()].reverse())X(z[0]);if(J.target!=="openapi-3.0")for(let z of J.seen.entries())Q9(z[1].def??z[1].schema);for(let z of J.deferred)z();if(J.intersections.length){let z=new Map;for(let B of J.seen.values())for(let K of[B.schema,B.def]){let W=K?.allOf;if(!Array.isArray(W))continue;let C=z.get(W);if(C)C.push(K);else z.set(W,[K])}for(let B of J.intersections)for(let K of z.get(B)??[])rG(K)}}let G={};if(J.target==="draft-2020-12")G.$schema="https://json-schema.org/draft/2020-12/schema";else if(J.target==="draft-07")G.$schema="http://json-schema.org/draft-07/schema#";else if(J.target==="draft-04")G.$schema="http://json-schema.org/draft-04/schema#";else if(J.target==="openapi-3.0");if(J.external?.uri){let z=J.external.registry.get($)?.id;if(!z)throw Error("Schema is missing an `id` property");G.$id=J.external.uri(z)}a8(G,Z.defId?Z.schema:Z.def??Z.schema);let Q=J.metadataRegistry.get($)?.id;if(Q!==void 0&&G.id===Q)delete G.id;let Y=J.external?.defs??{};if(!J.external||J.sharedEmitDoneFor!==J.external)for(let z of J.seen.entries()){let B=z[1];if(B.def&&B.defId){if(B.def.id===B.defId)delete B.def.id;i0(Y,B.defId,B.def)}}if(J.external)J.sharedEmitDoneFor=J.external;if(J.external);else if(Object.keys(Y).length>0)if(J.target==="draft-2020-12")G.$defs=Y;else G.definitions=Y;try{let z=JSON.parse(JSON.stringify(G));return Object.defineProperty(z,"~standard",{value:{...$["~standard"],jsonSchema:{input:G9($,"input",J.processors),output:G9($,"output",J.processors)}},enumerable:!1,writable:!1}),z}catch(z){throw Error("Error converting schema to JSON.")}}function z0(J,$){let Z=$??{seen:new Set};if(Z.seen.has(J))return!1;Z.seen.add(J);let X=J._zod.def;if(X.type==="transform")return!0;if(X.type==="array")return z0(X.element,Z);if(X.type==="set")return z0(X.valueType,Z);if(X.type==="lazy")return z0(X.getter(),Z);if(X.type==="promise"||X.type==="optional"||X.type==="nonoptional"||X.type==="nullable"||X.type==="readonly"||X.type==="default"||X.type==="prefault"||X.type==="catch")return z0(X.innerType,Z);if(X.type==="intersection")return z0(X.left,Z)||z0(X.right,Z);if(X.type==="record"||X.type==="map")return z0(X.keyType,Z)||z0(X.valueType,Z);if(X.type==="pipe"){if(J._zod.traits.has("$ZodCodec"))return!0;return z0(X.in,Z)||z0(X.out,Z)}if(X.type==="object"){for(let G in X.shape)if(z0(X.shape[G],Z))return!0;return!1}if(X.type==="union"){for(let G of X.options)if(z0(G,Z))return!0;return!1}if(X.type==="tuple"){for(let G of X.items)if(z0(G,Z))return!0;if(X.rest&&z0(X.rest,Z))return!0;return!1}return!1}var G9=(J,$,Z={})=>(X)=>{let{libraryOptions:G,target:Q}=X??{},Y=c1({...G??{},target:Q,io:$,processors:Z});return p(J,Y),p1(Y,J),l1(Y,J)};var tG={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sG=(J,$,Z,X)=>{let G=Z;G.type="string";let{minimum:Q,maximum:Y,format:z,patterns:B,contentEncoding:K,laxFormat:W}=J._zod.bag;if(typeof Q==="number")G.minLength=Q;if(typeof Y==="number")G.maxLength=Y;if(z){if(G.format=tG[z]??z,G.format==="")delete G.format;if(z==="time"||W)delete G.format}if(K)G.contentEncoding=K;if(B&&B.size>0){let C=[...B];if(C.length===1)G.pattern=C[0].source;else if(C.length>1)G.allOf=[...C.map((V)=>({...$.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"?{type:"string"}:{},pattern:V.source}))]}},eG=(J,$,Z,X)=>{let G=Z,{minimum:Q,maximum:Y,format:z,multipleOf:B,exclusiveMaximum:K,exclusiveMinimum:W}=J._zod.bag;if(typeof z==="string"&&z.includes("int"))G.type="integer";else G.type="number";let C=typeof W==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),V=typeof K==="number"&&K<=(Y??Number.POSITIVE_INFINITY),F=$.target==="draft-04"||$.target==="openapi-3.0";if(C)if(F)G.minimum=W,G.exclusiveMinimum=!0;else G.exclusiveMinimum=W;else if(typeof Q==="number")G.minimum=Q;if(V)if(F)G.maximum=K,G.exclusiveMaximum=!0;else G.exclusiveMaximum=K;else if(typeof Y==="number")G.maximum=Y;if(typeof B==="number")if(Number.isFinite(B)&&B!==0)G.multipleOf=Math.abs(B);else $0(J,$,G,X,`A multipleOf divisor of ${B} cannot be represented in JSON Schema`)},J5=(J,$,Z,X)=>{Z.type="boolean"},$5=(J,$,Z,X)=>{$0(J,$,Z,X,"BigInt cannot be represented in JSON Schema")},Z5=(J,$,Z,X)=>{$0(J,$,Z,X,"Symbols cannot be represented in JSON Schema")},X5=(J,$,Z,X)=>{if($.target==="openapi-3.0")Z.type="string",Z.nullable=!0,Z.enum=[null];else Z.type="null"},G5=(J,$,Z,X)=>{$0(J,$,Z,X,"Undefined cannot be represented in JSON Schema")},Q5=(J,$,Z,X)=>{$0(J,$,Z,X,"Void cannot be represented in JSON Schema")},Y5=(J,$,Z,X)=>{Z.not={}},z5=(J,$,Z,X)=>{},B5=(J,$,Z,X)=>{},K5=(J,$,Z,X)=>{$0(J,$,Z,X,"Date cannot be represented in JSON Schema")},W5=(J,$,Z,X)=>{let G=J._zod.def,Q=oZ(G.entries);if(Q.length===0){Z.not={};return}if(Q.every((Y)=>typeof Y==="number"))Z.type="number";if(Q.every((Y)=>typeof Y==="string"))Z.type="string";Z.enum=Q},V5=(J,$,Z,X)=>{let G=J._zod.def;if(G.values.length===0){Z.not={};return}let Q=[];for(let Y of G.values)if(Y===void 0){if($0(J,$,Z,X,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof Y==="bigint"){if($0(J,$,Z,X,"BigInt literals cannot be represented in JSON Schema"))return;Q.push(Number(Y))}else Q.push(Y);if(Q.length===0);else if(Q.length===1){let Y=Q[0];if(Z.type=Y===null?"null":typeof Y,$.target==="draft-04"||$.target==="openapi-3.0")Z.enum=[Y];else Z.const=Y}else{if(Q.every((Y)=>typeof Y==="number"))Z.type="number";if(Q.every((Y)=>typeof Y==="string"))Z.type="string";if(Q.every((Y)=>typeof Y==="boolean"))Z.type="boolean";if(Q.every((Y)=>Y===null))Z.type="null";Z.enum=Q}},C5=(J,$,Z,X)=>{$0(J,$,Z,X,"NaN cannot be represented in JSON Schema")},U5=(J,$,Z,X)=>{let G=Z,Q=J._zod.pattern;if(!Q)throw Error("Pattern not found in template literal");G.type="string",G.pattern=Q.source},N5=(J,$,Z,X)=>{let G=Z,Q={type:"string",format:"binary",contentEncoding:"binary"},{minimum:Y,maximum:z,mime:B}=J._zod.bag;if(Y!==void 0)Q.minLength=Y;if(z!==void 0)Q.maxLength=z;if(B)if(B.length===1)Q.contentMediaType=B[0],Object.assign(G,Q);else Object.assign(G,Q),G.anyOf=B.map((K)=>({contentMediaType:K}));else Object.assign(G,Q)},F5=(J,$,Z,X)=>{Z.type="boolean"},q5=(J,$,Z,X)=>{$0(J,$,Z,X,"Custom types cannot be represented in JSON Schema")},M5=(J,$,Z,X)=>{$0(J,$,Z,X,"Function types cannot be represented in JSON Schema")},T5=(J,$,Z,X)=>{$0(J,$,Z,X,"Transforms cannot be represented in JSON Schema")},w5=(J,$,Z,X)=>{$0(J,$,Z,X,"Map cannot be represented in JSON Schema")},O5=(J,$,Z,X)=>{$0(J,$,Z,X,"Set cannot be represented in JSON Schema")},R5=(J,$,Z,X)=>{let G=Z,Q=J._zod.def,{minimum:Y,maximum:z}=J._zod.bag;if(typeof Y==="number")G.minItems=Y;if(typeof z==="number")G.maxItems=z;G.type="array",G.items=p(Q.element,$,{...X,path:[...X.path,"items"]})};function o8(J){let $=J._zod.def;if($.type==="pipe"&&$.in._zod.traits.has("$ZodTransform"))return o8($.out);if($.type==="catch")return o8($.innerType);return J._zod.optin}var A5=(J,$,Z,X)=>{let G=Z,Q=J._zod.def,Y=Q.shape;if(Object.getOwnPropertySymbols(Y).length&&$0(J,$,G,X,"Symbol keys cannot be represented in JSON Schema"))return;G.type="object",G.properties={};for(let W in Y)i0(G.properties,W,p(Y[W],$,{...X,path:[...X.path,"properties",W]}));let B=new Set(Object.keys(Y)),K=new Set([...B].filter((W)=>{let C=Q.shape[W];if($.io==="input")return o8(C)===void 0;else return C._zod.optout===void 0}));if(K.size>0)G.required=Array.from(K);if(Q.catchall?._zod.def.type==="never")G.additionalProperties=!1;else if(!Q.catchall){if($.io==="output")G.additionalProperties=!1}else if(Q.catchall)G.additionalProperties=p(Q.catchall,$,{...X,path:[...X.path,"additionalProperties"]})},H5=(J,$,Z,X)=>{let G=J._zod.def,Q=G.inclusive===!1,Y=G.options.map((z,B)=>p(z,$,{...X,path:[...X.path,Q?"oneOf":"anyOf",B]}));if(Q)Z.oneOf=Y;else Z.anyOf=Y},L5=(J,$,Z,X)=>{let G=J._zod.def,Q=p(G.left,$,{...X,path:[...X.path,"allOf",0]}),Y=p(G.right,$,{...X,path:[...X.path,"allOf",1]}),z=(K)=>("allOf"in K)&&Object.keys(K).length===1,B=[...z(Q)?Q.allOf:[Q],...z(Y)?Y.allOf:[Y]];Z.allOf=B,$.intersections.push(B)},D5=(J,$,Z,X)=>{let G=Z,Q=J._zod.def;G.type="array";let Y=$.target==="draft-2020-12"?"prefixItems":"items",z=$.target==="draft-2020-12"?"items":$.target==="openapi-3.0"?"items":"additionalItems",B=Q.items.map((A,R)=>p(A,$,{...X,path:[...X.path,Y,R]})),K=Q.rest?p(Q.rest,$,{...X,path:[...X.path,z,...$.target==="openapi-3.0"?[Q.items.length]:[]]}):null,W=Q.items.length;while(W>0){let A=Q.items[W-1];if(!($.io==="input"?o8(A)!==void 0:A._zod.optout==="optional"))break;W--}let C=Q.items.length,V=!Q.rest;if($.target==="draft-2020-12"){if(G.prefixItems=B,V)G.items=!1;else if(K)G.items=K;if(W>0)G.minItems=W;if(V)G.maxItems=C}else if($.target==="openapi-3.0"){if(G.items={anyOf:B},K)G.items.anyOf.push(K);if(W>0)G.minItems=W;if(V)G.maxItems=C}else{if(G.items=B,V)G.additionalItems=!1;else if(K)G.additionalItems=K;if(W>0)G.minItems=W;if(V)G.maxItems=C}let{minimum:F,maximum:q}=J._zod.bag;if(typeof F==="number")G.minItems=F;if(typeof q==="number")G.maxItems=q};function q4(J,$,Z){if($.$ref){if(Z.has($))return $;Z.add($);let q=J.get($)?.def;if(!q)return $;let A=q4(J,q,Z);return A===q?$:A}for(let q of["anyOf","oneOf"]){let A=$[q];if(!Array.isArray(A))continue;let R=A.map((H)=>q4(J,H,Z));if(R.some((H,O)=>H!==A[O]))$={...$,[q]:R}}let X=Array.isArray($.type)?$.type:[$.type],G=!X.includes("string")&&X.some((q)=>q==="number"||q==="integer"),Q=$.enum??($.const!==void 0?[$.const]:void 0);if(!G&&!Q?.some((q)=>typeof q==="number"))return $;let{minimum:Y,maximum:z,exclusiveMinimum:B,exclusiveMaximum:K,multipleOf:W,format:C,id:V,...F}=$;if(F.enum)F.enum=F.enum.map((q)=>typeof q==="number"?String(q):q);else if(typeof F.const==="number")F.const=String(F.const);if(!G)return F;if(F.type="string",!Q)F.pattern=(X.includes("number")?tZ:rZ).source;return F}var M4=new WeakMap;function j5(J){let $=new Map;for(let X of J.seen.values())if(X.def&&!$.has(X.schema))$.set(X.schema,X);let Z=new Map;for(let X of M4.get(J)??[]){let G=J.seen.get(X),Q=(G?.def??G?.schema)?.propertyNames;if(!Q||Q===!0||Z.has(Q))continue;let Y=q4($,Q,new Set);if(Y!==Q)Z.set(Q,Y)}if(!Z.size)return;for(let X of J.seen.values())for(let G of[X.schema,X.def]){let Q=G&&Z.get(G.propertyNames);if(Q)G.propertyNames=Q}}var P5=(J,$,Z,X)=>{let G=Z,Q=J._zod.def;G.type="object";let Y=Q.keyType,B=Y._zod.bag?.patterns;if(Q.mode==="loose"&&B&&B.size>0){let C=p(Q.valueType,$,{...X,path:[...X.path,"patternProperties","*"]});G.patternProperties={};for(let V of B)i0(G.patternProperties,V.source,C)}else{if($.target==="draft-07"||$.target==="draft-2020-12"){G.propertyNames=p(Q.keyType,$,{...X,path:[...X.path,"propertyNames"]});let C=M4.get($);if(!C)C=[],M4.set($,C),$.deferred.push(()=>j5($));C.push(J)}G.additionalProperties=p(Q.valueType,$,{...X,path:[...X.path,"additionalProperties"]})}let K=Y._zod.values,W=$.io==="input"&&o8(Q.valueType)!==void 0;if(K&&!Q.partial&&!W){let C=[...K].filter((V)=>typeof V==="string"||typeof V==="number");if(C.length>0)G.required=C.map(String)}},S5=(J,$,Z,X)=>{let G=J._zod.def,Q=p(G.innerType,$,X),Y=$.seen.get(J);if($.target==="openapi-3.0")Y.ref=G.innerType,Z.nullable=!0;else Z.anyOf=[Q,{type:"null"}]},_5=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType},T4=Symbol();function B9(J,$,Z,X,G){let Q=!1,Y=JSON.stringify(J,(z,B)=>{if(typeof B!=="bigint")return B;return Q=!0,null});if(!Q)return JSON.parse(Y);return $0($,Z,X,G,"BigInt defaults cannot be represented in JSON Schema"),T4}var E5=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType;let Y=B9(G.defaultValue,J,$,Z,X);if(Y!==T4)Z.default=Y},I5=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);if(Q.ref=G.innerType,$.io!=="input")return;let Y=B9(G.defaultValue,J,$,Z,X);if(Y!==T4)Z._prefault=Y},y5=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType;let Y;try{Y=G.catchValue(void 0)}catch{$0(J,$,Z,X,"Dynamic catch values are not supported in JSON Schema");return}Z.default=Y},x5=(J,$,Z,X)=>{let G=J._zod.def,Q=G.in._zod.traits.has("$ZodTransform"),Y=$.io==="input"?Q?G.out:G.in:G.out;p(Y,$,X);let z=$.seen.get(J);z.ref=Y},k5=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType,Z.readOnly=!0},f5=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType},v5=(J,$,Z,X)=>{let G=J._zod.def;p(G.innerType,$,X);let Q=$.seen.get(J);Q.ref=G.innerType},b5=(J,$,Z,X)=>{let G=J._zod.innerType;p(G,$,X);let Q=$.seen.get(J);Q.ref=G},z9={string:sG,number:eG,boolean:J5,bigint:$5,symbol:Z5,null:X5,undefined:G5,void:Q5,never:Y5,any:z5,unknown:B5,date:K5,enum:W5,literal:V5,nan:C5,template_literal:U5,file:N5,success:F5,custom:q5,function:M5,transform:T5,map:w5,set:O5,array:R5,object:A5,union:H5,intersection:L5,tuple:D5,record:P5,nullable:S5,nonoptional:_5,default:E5,prefault:I5,catch:y5,pipe:x5,readonly:k5,promise:f5,optional:v5,lazy:b5};function i1(J,$){if("_idmap"in J){let X=J,G=c1({...$,processors:z9}),Q={};for(let B of X._idmap.entries()){let[K,W]=B;p(W,G)}let Y={},z={registry:X,uri:$?.uri,defs:Q};G.external=z;for(let B of X._idmap.entries()){let[K,W]=B;p1(G,W),i0(Y,K,l1(G,W))}if(Object.keys(Q).length>0){let B=G.target==="draft-2020-12"?"$defs":"definitions";Y.__shared={[B]:Q}}return{schemas:Y}}let Z=c1({...$,processors:z9});return p(J,Z),p1(Z,J),l1(Z,J)}c();function g5(J){return{type:"json_schema",schema:{...x1(i1(J,{reused:"ref"}))},parse:(Z)=>{let X=J.safeParse(JSON.parse(Z));if(!X.success)throw new T(`Failed to parse structured output: ${X.error.message} cause: ${X.error.issues}`);return X.data}}}function h5(J){let $=i1(J.inputSchema,{reused:"ref"});if($.type!=="object")throw Error(`Zod schema for tool "${J.name}" must be an object, but got ${$.type}`);let Z=$;return{type:"custom",name:J.name,input_schema:Z,description:J.description,run:J.run,parse:(X)=>J.inputSchema.parse(X),...J.close?{close:J.close}:{}}}function m5(J){return{type:"memory_20250818",name:"memory",parse:($)=>$,run:($)=>{let Z=J[$.command];if(!Z)throw Error(`${$.command} not implemented`);return Z.bind(J)($)}}}I0();q0();K1();var u5=["image/jpeg","image/png","image/gif","image/webp"];function w4(J){return u5.includes(J)}function d5(J){return!J||J.startsWith("text/")||J==="application/pdf"||w4(J)}class R0 extends Error{constructor(J){super(J);this.name="UnsupportedMCPValueError"}}function K9(J,$,Z){let X={...J.inputSchema,type:"object",properties:J.inputSchema.properties??null,required:J.inputSchema.required??null};return{...{name:J.name,input_schema:X,...J.description!==void 0?{description:J.description}:{},...Z},run:async(Y)=>{let z=await $.callTool({name:J.name,arguments:Y});if(z.isError){let B=z.content.map((K)=>n1(K));throw new P(B)}if(z.content.length===0&&typeof z.structuredContent==="object"&&z.structuredContent!==null)return JSON.stringify(z.structuredContent);return z.content.map((B)=>n1(B))},parse:(Y)=>Y,[V0]:"mcpTool"}}function c5(J,$,Z){return J.map((X)=>K9(X,$,Z))}function W9(J,$){return{role:J.role,content:[n1(J.content,$)],[V0]:"mcpMessage"}}function p5(J,$){return J.map((Z)=>W9(Z,$))}function n1(J,$){switch(J.type){case"text":return{type:"text",text:J.text,...$,[V0]:"mcpContent"};case"image":{if(!w4(J.mimeType))throw new R0(`Unsupported image MIME type: ${J.mimeType}`);return{type:"image",source:{type:"base64",data:J.data,media_type:J.mimeType},...$,[V0]:"mcpContent"}}case"resource":return V9(J.resource,$,"mcpContent");case"resource_link":case"audio":throw new R0(`Unsupported MCP content type: ${J.type}`);default:throw new R0(`Unsupported MCP content type: ${J.type}`)}}function V9(J,$,Z="mcpResourceToContent"){let X=J.mimeType;if(X&&w4(X)){if(!("blob"in J))throw new R0(`Image resource must have blob data, not text. URI: ${J.uri}`);return{type:"image",source:{type:"base64",data:J.blob,media_type:X},...$,[V0]:Z}}if(X==="application/pdf"){if(!("blob"in J))throw new R0(`PDF resource must have blob data, not text. URI: ${J.uri}`);return{type:"document",source:{type:"base64",data:J.blob,media_type:"application/pdf"},...$,[V0]:Z}}if(!X||X.startsWith("text/"))return{type:"document",source:n5(J),...$,[V0]:Z};throw new R0(`Unsupported MIME type "${X}" for resource: ${J.uri}`)}function l5(J,$){if(J.contents.length===0)throw new R0("Resource contents array must contain at least one item");let Z=J.contents.find((X)=>d5(X.mimeType));if(!Z){let X=J.contents.map((G)=>G.mimeType).filter((G)=>G!==void 0);throw new R0(`No supported MIME type found in resource contents. Available: ${X.join(", ")}`)}return V9(Z,$)}function i5(J){if("blob"in J)return r2(J.blob);return new TextEncoder().encode(J.text)}function n5(J){return{type:"text",data:"text"in J?J.text:new TextDecoder().decode(r2(J.blob)),media_type:"text/plain"}}function a5(J){if(J.contents.length===0)throw new R0("Resource contents array must contain at least one item");let $=J.contents[0],Z=new URL($.uri).pathname.split("/").at(-1)||"file",X=$.mimeType,G=i5($),Q=new File([G],Z,X?{type:X}:void 0);return Q[V0]="mcpResourceToFile",Q}I0();KJ();export{w1 as toFile,t6 as setupSkills,Y2 as resolvePath,c5 as mcpTools,K9 as mcpTool,a5 as mcpResourceToFile,l5 as mcpResourceToContent,p5 as mcpMessages,W9 as mcpMessage,n1 as mcpContent,v1 as extractSkillArchive,P0 as default,h5 as betaZodTool,g5 as betaZodOutputFormat,QJ as betaWriteTool,m0 as betaTool,mG as betaRefusalFallbackMiddleware,GJ as betaReadTool,m5 as betaMemoryTool,d3 as betaJSONSchemaOutputFormat,BJ as betaGrepTool,zJ as betaGlobTool,YJ as betaEditTool,XJ as betaBashTool,TZ as betaAgentToolset20260401,B0 as VERSION,R0 as UnsupportedMCPValueError,p2 as UnprocessableEntityError,P as ToolError,s as Stream,t8 as RetryableError,l2 as RateLimitError,T as PukuError,P0 as PukuAI,u2 as PermissionDeniedError,T1 as PagePromise,f0 as OAUTH_API_BETA_HEADER,d2 as NotFoundError,D8 as MODEL_NONSTREAMING_TOKENS,i2 as InternalServerError,gZ as HUMAN_PROMPT,V6 as FEDERATION_BETA_HEADER,c2 as ConflictError,e1 as BetaFallbackState,g1 as BashTimeoutError,h1 as BashSession,d1 as BasePuku,h2 as BadRequestError,m2 as AuthenticationError,Z0 as APIUserAbortError,s0 as APIPromise,l as APIError,g2 as APIConnectionTimeoutError,S0 as APIConnectionError,hZ as AI_PROMPT};
67
67
 
68
- //# debugId=6019958B710F562364756E2164756E21
68
+ //# debugId=B92593A0D518752564756E2164756E21