@puku-ai/sdk 4.0.0 → 4.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (583) hide show
  1. package/README.md +29 -10
  2. package/dist/index.d.ts +26 -0
  3. package/dist/index.js +32 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/vendor/_vendor/partial-json-parser/parser.d.ts +2 -0
  6. package/dist/vendor/_vendor/partial-json-parser/parser.js +223 -0
  7. package/dist/vendor/_vendor/partial-json-parser/parser.js.map +1 -0
  8. package/dist/vendor/api-promise.d.ts +2 -0
  9. package/dist/vendor/api-promise.js +3 -0
  10. package/dist/vendor/api-promise.js.map +1 -0
  11. package/dist/vendor/client.d.ts +399 -0
  12. package/dist/vendor/client.js +976 -0
  13. package/dist/vendor/client.js.map +1 -0
  14. package/dist/vendor/core/api-promise.d.ts +49 -0
  15. package/dist/vendor/core/api-promise.js +77 -0
  16. package/dist/vendor/core/api-promise.js.map +1 -0
  17. package/dist/vendor/core/api.d.ts +10 -0
  18. package/dist/vendor/core/api.js +2 -0
  19. package/dist/vendor/core/api.js.map +1 -0
  20. package/dist/vendor/core/credentials.d.ts +130 -0
  21. package/dist/vendor/core/credentials.js +274 -0
  22. package/dist/vendor/core/credentials.js.map +1 -0
  23. package/dist/vendor/core/error.d.ts +82 -0
  24. package/dist/vendor/core/error.js +140 -0
  25. package/dist/vendor/core/error.js.map +1 -0
  26. package/dist/vendor/core/middleware.d.ts +153 -0
  27. package/dist/vendor/core/middleware.js +168 -0
  28. package/dist/vendor/core/middleware.js.map +1 -0
  29. package/dist/vendor/core/pagination.d.ts +121 -0
  30. package/dist/vendor/core/pagination.js +207 -0
  31. package/dist/vendor/core/pagination.js.map +1 -0
  32. package/dist/vendor/core/resource.d.ts +5 -0
  33. package/dist/vendor/core/resource.js +8 -0
  34. package/dist/vendor/core/resource.js.map +1 -0
  35. package/dist/vendor/core/streaming.d.ts +41 -0
  36. package/dist/vendor/core/streaming.js +342 -0
  37. package/dist/vendor/core/streaming.js.map +1 -0
  38. package/dist/vendor/core/uploads.d.ts +2 -0
  39. package/dist/vendor/core/uploads.js +2 -0
  40. package/dist/vendor/core/uploads.js.map +1 -0
  41. package/dist/vendor/error.d.ts +2 -0
  42. package/dist/vendor/error.js +3 -0
  43. package/dist/vendor/error.js.map +1 -0
  44. package/dist/vendor/helpers/beta/environments.d.ts +22 -0
  45. package/dist/vendor/helpers/beta/environments.js +23 -0
  46. package/dist/vendor/helpers/beta/environments.js.map +1 -0
  47. package/dist/vendor/helpers/beta/json-schema.d.ts +36 -0
  48. package/dist/vendor/helpers/beta/json-schema.js +53 -0
  49. package/dist/vendor/helpers/beta/json-schema.js.map +1 -0
  50. package/dist/vendor/helpers/beta/mcp.d.ts +302 -0
  51. package/dist/vendor/helpers/beta/mcp.js +406 -0
  52. package/dist/vendor/helpers/beta/mcp.js.map +1 -0
  53. package/dist/vendor/helpers/beta/memory.d.ts +10 -0
  54. package/dist/vendor/helpers/beta/memory.js +15 -0
  55. package/dist/vendor/helpers/beta/memory.js.map +1 -0
  56. package/dist/vendor/helpers/beta/standard-schema.d.ts +44 -0
  57. package/dist/vendor/helpers/beta/standard-schema.js +54 -0
  58. package/dist/vendor/helpers/beta/standard-schema.js.map +1 -0
  59. package/dist/vendor/helpers/beta/zod.d.ts +32 -0
  60. package/dist/vendor/helpers/beta/zod.js +52 -0
  61. package/dist/vendor/helpers/beta/zod.js.map +1 -0
  62. package/dist/vendor/helpers/index.d.ts +2 -0
  63. package/dist/vendor/helpers/index.js +3 -0
  64. package/dist/vendor/helpers/index.js.map +1 -0
  65. package/dist/vendor/helpers/json-schema.d.ts +17 -0
  66. package/dist/vendor/helpers/json-schema.js +34 -0
  67. package/dist/vendor/helpers/json-schema.js.map +1 -0
  68. package/dist/vendor/helpers/zod.d.ts +12 -0
  69. package/dist/vendor/helpers/zod.js +42 -0
  70. package/dist/vendor/helpers/zod.js.map +1 -0
  71. package/dist/vendor/index.d.ts +16 -0
  72. package/dist/vendor/index.js +23 -0
  73. package/dist/vendor/index.js.map +1 -0
  74. package/dist/vendor/internal/builtin-types.d.ts +72 -0
  75. package/dist/vendor/internal/builtin-types.js +3 -0
  76. package/dist/vendor/internal/builtin-types.js.map +1 -0
  77. package/dist/vendor/internal/constants.d.ts +4 -0
  78. package/dist/vendor/internal/constants.js +10 -0
  79. package/dist/vendor/internal/constants.js.map +1 -0
  80. package/dist/vendor/internal/decoders/jsonl.d.ts +9 -0
  81. package/dist/vendor/internal/decoders/jsonl.js +37 -0
  82. package/dist/vendor/internal/decoders/jsonl.js.map +1 -0
  83. package/dist/vendor/internal/decoders/line.d.ts +16 -0
  84. package/dist/vendor/internal/decoders/line.js +105 -0
  85. package/dist/vendor/internal/decoders/line.js.map +1 -0
  86. package/dist/vendor/internal/detect-platform.d.ts +14 -0
  87. package/dist/vendor/internal/detect-platform.js +155 -0
  88. package/dist/vendor/internal/detect-platform.js.map +1 -0
  89. package/dist/vendor/internal/errors.d.ts +2 -0
  90. package/dist/vendor/internal/errors.js +38 -0
  91. package/dist/vendor/internal/errors.js.map +1 -0
  92. package/dist/vendor/internal/file-store.d.ts +135 -0
  93. package/dist/vendor/internal/file-store.js +529 -0
  94. package/dist/vendor/internal/file-store.js.map +1 -0
  95. package/dist/vendor/internal/headers.d.ts +28 -0
  96. package/dist/vendor/internal/headers.js +114 -0
  97. package/dist/vendor/internal/headers.js.map +1 -0
  98. package/dist/vendor/internal/message-stream-utils.d.ts +9 -0
  99. package/dist/vendor/internal/message-stream-utils.js +30 -0
  100. package/dist/vendor/internal/message-stream-utils.js.map +1 -0
  101. package/dist/vendor/internal/node.browser.d.ts +8 -0
  102. package/dist/vendor/internal/node.browser.js +19 -0
  103. package/dist/vendor/internal/node.browser.js.map +1 -0
  104. package/dist/vendor/internal/node.d.ts +13 -0
  105. package/dist/vendor/internal/node.js +14 -0
  106. package/dist/vendor/internal/node.js.map +1 -0
  107. package/dist/vendor/internal/parse.d.ts +17 -0
  108. package/dist/vendor/internal/parse.js +62 -0
  109. package/dist/vendor/internal/parse.js.map +1 -0
  110. package/dist/vendor/internal/qs/formats.d.ts +6 -0
  111. package/dist/vendor/internal/qs/formats.js +9 -0
  112. package/dist/vendor/internal/qs/formats.js.map +1 -0
  113. package/dist/vendor/internal/qs/index.d.ts +9 -0
  114. package/dist/vendor/internal/qs/index.js +10 -0
  115. package/dist/vendor/internal/qs/index.js.map +1 -0
  116. package/dist/vendor/internal/qs/stringify.d.ts +2 -0
  117. package/dist/vendor/internal/qs/stringify.js +274 -0
  118. package/dist/vendor/internal/qs/stringify.js.map +1 -0
  119. package/dist/vendor/internal/qs/types.d.ts +56 -0
  120. package/dist/vendor/internal/qs/types.js +2 -0
  121. package/dist/vendor/internal/qs/types.js.map +1 -0
  122. package/dist/vendor/internal/qs/utils.d.ts +14 -0
  123. package/dist/vendor/internal/qs/utils.js +217 -0
  124. package/dist/vendor/internal/qs/utils.js.map +1 -0
  125. package/dist/vendor/internal/request-options.d.ts +126 -0
  126. package/dist/vendor/internal/request-options.js +27 -0
  127. package/dist/vendor/internal/request-options.js.map +1 -0
  128. package/dist/vendor/internal/request-signal.d.ts +3 -0
  129. package/dist/vendor/internal/request-signal.js +45 -0
  130. package/dist/vendor/internal/request-signal.js.map +1 -0
  131. package/dist/vendor/internal/shim-types.d.ts +16 -0
  132. package/dist/vendor/internal/shim-types.js +3 -0
  133. package/dist/vendor/internal/shim-types.js.map +1 -0
  134. package/dist/vendor/internal/shims.d.ts +25 -0
  135. package/dist/vendor/internal/shims.js +85 -0
  136. package/dist/vendor/internal/shims.js.map +1 -0
  137. package/dist/vendor/internal/stainless-helper-header.d.ts +59 -0
  138. package/dist/vendor/internal/stainless-helper-header.js +83 -0
  139. package/dist/vendor/internal/stainless-helper-header.js.map +1 -0
  140. package/dist/vendor/internal/stream-utils.d.ts +7 -0
  141. package/dist/vendor/internal/stream-utils.js +35 -0
  142. package/dist/vendor/internal/stream-utils.js.map +1 -0
  143. package/dist/vendor/internal/to-file.d.ts +44 -0
  144. package/dist/vendor/internal/to-file.js +93 -0
  145. package/dist/vendor/internal/to-file.js.map +1 -0
  146. package/dist/vendor/internal/types.d.ts +62 -0
  147. package/dist/vendor/internal/types.js +3 -0
  148. package/dist/vendor/internal/types.js.map +1 -0
  149. package/dist/vendor/internal/uploads.d.ts +41 -0
  150. package/dist/vendor/internal/uploads.js +139 -0
  151. package/dist/vendor/internal/uploads.js.map +1 -0
  152. package/dist/vendor/internal/utils/abort.d.ts +11 -0
  153. package/dist/vendor/internal/utils/abort.js +22 -0
  154. package/dist/vendor/internal/utils/abort.js.map +1 -0
  155. package/dist/vendor/internal/utils/async-queue.d.ts +30 -0
  156. package/dist/vendor/internal/utils/async-queue.js +66 -0
  157. package/dist/vendor/internal/utils/async-queue.js.map +1 -0
  158. package/dist/vendor/internal/utils/backoff.d.ts +22 -0
  159. package/dist/vendor/internal/utils/backoff.js +36 -0
  160. package/dist/vendor/internal/utils/backoff.js.map +1 -0
  161. package/dist/vendor/internal/utils/base64.d.ts +2 -0
  162. package/dist/vendor/internal/utils/base64.js +33 -0
  163. package/dist/vendor/internal/utils/base64.js.map +1 -0
  164. package/dist/vendor/internal/utils/bytes.d.ts +3 -0
  165. package/dist/vendor/internal/utils/bytes.js +26 -0
  166. package/dist/vendor/internal/utils/bytes.js.map +1 -0
  167. package/dist/vendor/internal/utils/env.d.ts +8 -0
  168. package/dist/vendor/internal/utils/env.js +18 -0
  169. package/dist/vendor/internal/utils/env.js.map +1 -0
  170. package/dist/vendor/internal/utils/log.d.ts +46 -0
  171. package/dist/vendor/internal/utils/log.js +105 -0
  172. package/dist/vendor/internal/utils/log.js.map +1 -0
  173. package/dist/vendor/internal/utils/path.d.ts +14 -0
  174. package/dist/vendor/internal/utils/path.js +74 -0
  175. package/dist/vendor/internal/utils/path.js.map +1 -0
  176. package/dist/vendor/internal/utils/promise.d.ts +10 -0
  177. package/dist/vendor/internal/utils/promise.js +15 -0
  178. package/dist/vendor/internal/utils/promise.js.map +1 -0
  179. package/dist/vendor/internal/utils/query.d.ts +1 -0
  180. package/dist/vendor/internal/utils/query.js +6 -0
  181. package/dist/vendor/internal/utils/query.js.map +1 -0
  182. package/dist/vendor/internal/utils/sleep.d.ts +9 -0
  183. package/dist/vendor/internal/utils/sleep.js +24 -0
  184. package/dist/vendor/internal/utils/sleep.js.map +1 -0
  185. package/dist/vendor/internal/utils/time.d.ts +2 -0
  186. package/dist/vendor/internal/utils/time.js +5 -0
  187. package/dist/vendor/internal/utils/time.js.map +1 -0
  188. package/dist/vendor/internal/utils/uuid.d.ts +4 -0
  189. package/dist/vendor/internal/utils/uuid.js +15 -0
  190. package/dist/vendor/internal/utils/uuid.js.map +1 -0
  191. package/dist/vendor/internal/utils/values.d.ts +24 -0
  192. package/dist/vendor/internal/utils/values.js +106 -0
  193. package/dist/vendor/internal/utils/values.js.map +1 -0
  194. package/dist/vendor/internal/utils.d.ts +7 -0
  195. package/dist/vendor/internal/utils.js +9 -0
  196. package/dist/vendor/internal/utils.js.map +1 -0
  197. package/dist/vendor/lib/BetaMessageStream.d.ts +123 -0
  198. package/dist/vendor/lib/BetaMessageStream.js +662 -0
  199. package/dist/vendor/lib/BetaMessageStream.js.map +1 -0
  200. package/dist/vendor/lib/MessageStream.d.ts +122 -0
  201. package/dist/vendor/lib/MessageStream.js +609 -0
  202. package/dist/vendor/lib/MessageStream.js.map +1 -0
  203. package/dist/vendor/lib/beta-parser.d.ts +36 -0
  204. package/dist/vendor/lib/beta-parser.js +75 -0
  205. package/dist/vendor/lib/beta-parser.js.map +1 -0
  206. package/dist/vendor/lib/credentials/credential-chain.d.ts +38 -0
  207. package/dist/vendor/lib/credentials/credential-chain.js +208 -0
  208. package/dist/vendor/lib/credentials/credential-chain.js.map +1 -0
  209. package/dist/vendor/lib/credentials/identity-token.d.ts +10 -0
  210. package/dist/vendor/lib/credentials/identity-token.js +35 -0
  211. package/dist/vendor/lib/credentials/identity-token.js.map +1 -0
  212. package/dist/vendor/lib/credentials/oidc-federation.d.ts +39 -0
  213. package/dist/vendor/lib/credentials/oidc-federation.js +79 -0
  214. package/dist/vendor/lib/credentials/oidc-federation.js.map +1 -0
  215. package/dist/vendor/lib/credentials/token-cache.d.ts +53 -0
  216. package/dist/vendor/lib/credentials/token-cache.js +110 -0
  217. package/dist/vendor/lib/credentials/token-cache.js.map +1 -0
  218. package/dist/vendor/lib/credentials/types.d.ts +95 -0
  219. package/dist/vendor/lib/credentials/types.js +226 -0
  220. package/dist/vendor/lib/credentials/types.js.map +1 -0
  221. package/dist/vendor/lib/credentials/user-oauth.d.ts +20 -0
  222. package/dist/vendor/lib/credentials/user-oauth.js +94 -0
  223. package/dist/vendor/lib/credentials/user-oauth.js.map +1 -0
  224. package/dist/vendor/lib/credentials.d.ts +3 -0
  225. package/dist/vendor/lib/credentials.js +3 -0
  226. package/dist/vendor/lib/credentials.js.map +1 -0
  227. package/dist/vendor/lib/environments/index.d.ts +3 -0
  228. package/dist/vendor/lib/environments/index.js +4 -0
  229. package/dist/vendor/lib/environments/index.js.map +1 -0
  230. package/dist/vendor/lib/environments/poller.d.ts +94 -0
  231. package/dist/vendor/lib/environments/poller.js +218 -0
  232. package/dist/vendor/lib/environments/poller.js.map +1 -0
  233. package/dist/vendor/lib/environments/worker.d.ts +226 -0
  234. package/dist/vendor/lib/environments/worker.js +572 -0
  235. package/dist/vendor/lib/environments/worker.js.map +1 -0
  236. package/dist/vendor/lib/helper-client.d.ts +30 -0
  237. package/dist/vendor/lib/helper-client.js +55 -0
  238. package/dist/vendor/lib/helper-client.js.map +1 -0
  239. package/dist/vendor/lib/middleware.d.ts +97 -0
  240. package/dist/vendor/lib/middleware.js +775 -0
  241. package/dist/vendor/lib/middleware.js.map +1 -0
  242. package/dist/vendor/lib/parser.d.ts +31 -0
  243. package/dist/vendor/lib/parser.js +62 -0
  244. package/dist/vendor/lib/parser.js.map +1 -0
  245. package/dist/vendor/lib/sessions/accumulate.d.ts +22 -0
  246. package/dist/vendor/lib/sessions/accumulate.js +42 -0
  247. package/dist/vendor/lib/sessions/accumulate.js.map +1 -0
  248. package/dist/vendor/lib/standard-schema.d.ts +130 -0
  249. package/dist/vendor/lib/standard-schema.js +41 -0
  250. package/dist/vendor/lib/standard-schema.js.map +1 -0
  251. package/dist/vendor/lib/tools/BetaRunnableTool.d.ts +48 -0
  252. package/dist/vendor/lib/tools/BetaRunnableTool.js +26 -0
  253. package/dist/vendor/lib/tools/BetaRunnableTool.js.map +1 -0
  254. package/dist/vendor/lib/tools/BetaToolRunner.d.ts +160 -0
  255. package/dist/vendor/lib/tools/BetaToolRunner.js +497 -0
  256. package/dist/vendor/lib/tools/BetaToolRunner.js.map +1 -0
  257. package/dist/vendor/lib/tools/CompactionControl.d.ts +29 -0
  258. package/dist/vendor/lib/tools/CompactionControl.js +25 -0
  259. package/dist/vendor/lib/tools/CompactionControl.js.map +1 -0
  260. package/dist/vendor/lib/tools/SessionToolRunner.d.ts +178 -0
  261. package/dist/vendor/lib/tools/SessionToolRunner.js +737 -0
  262. package/dist/vendor/lib/tools/SessionToolRunner.js.map +1 -0
  263. package/dist/vendor/lib/tools/ToolError.d.ts +32 -0
  264. package/dist/vendor/lib/tools/ToolError.js +43 -0
  265. package/dist/vendor/lib/tools/ToolError.js.map +1 -0
  266. package/dist/vendor/lib/transform-json-schema.d.ts +2 -0
  267. package/dist/vendor/lib/transform-json-schema.js +111 -0
  268. package/dist/vendor/lib/transform-json-schema.js.map +1 -0
  269. package/dist/vendor/pagination.d.ts +2 -0
  270. package/dist/vendor/pagination.js +3 -0
  271. package/dist/vendor/pagination.js.map +1 -0
  272. package/dist/vendor/resource.d.ts +2 -0
  273. package/dist/vendor/resource.js +3 -0
  274. package/dist/vendor/resource.js.map +1 -0
  275. package/dist/vendor/resources/beta/agents/agents.d.ts +1128 -0
  276. package/dist/vendor/resources/beta/agents/agents.js +123 -0
  277. package/dist/vendor/resources/beta/agents/agents.js.map +1 -0
  278. package/dist/vendor/resources/beta/agents/index.d.ts +2 -0
  279. package/dist/vendor/resources/beta/agents/index.js +4 -0
  280. package/dist/vendor/resources/beta/agents/index.js.map +1 -0
  281. package/dist/vendor/resources/beta/agents/versions.d.ts +32 -0
  282. package/dist/vendor/resources/beta/agents/versions.js +32 -0
  283. package/dist/vendor/resources/beta/agents/versions.js.map +1 -0
  284. package/dist/vendor/resources/beta/agents.d.ts +1 -0
  285. package/dist/vendor/resources/beta/agents.js +3 -0
  286. package/dist/vendor/resources/beta/agents.js.map +1 -0
  287. package/dist/vendor/resources/beta/beta.d.ts +131 -0
  288. package/dist/vendor/resources/beta/beta.js +69 -0
  289. package/dist/vendor/resources/beta/beta.js.map +1 -0
  290. package/dist/vendor/resources/beta/deployment-runs.d.ts +305 -0
  291. package/dist/vendor/resources/beta/deployment-runs.js +51 -0
  292. package/dist/vendor/resources/beta/deployment-runs.js.map +1 -0
  293. package/dist/vendor/resources/beta/deployments.d.ts +698 -0
  294. package/dist/vendor/resources/beta/deployments.js +192 -0
  295. package/dist/vendor/resources/beta/deployments.js.map +1 -0
  296. package/dist/vendor/resources/beta/dreams.d.ts +335 -0
  297. package/dist/vendor/resources/beta/dreams.js +112 -0
  298. package/dist/vendor/resources/beta/dreams.js.map +1 -0
  299. package/dist/vendor/resources/beta/environments/environments.d.ts +432 -0
  300. package/dist/vendor/resources/beta/environments/environments.js +142 -0
  301. package/dist/vendor/resources/beta/environments/environments.js.map +1 -0
  302. package/dist/vendor/resources/beta/environments/index.d.ts +2 -0
  303. package/dist/vendor/resources/beta/environments/index.js +4 -0
  304. package/dist/vendor/resources/beta/environments/index.js.map +1 -0
  305. package/dist/vendor/resources/beta/environments/work.d.ts +500 -0
  306. package/dist/vendor/resources/beta/environments/work.js +251 -0
  307. package/dist/vendor/resources/beta/environments/work.js.map +1 -0
  308. package/dist/vendor/resources/beta/environments.d.ts +1 -0
  309. package/dist/vendor/resources/beta/environments.js +3 -0
  310. package/dist/vendor/resources/beta/environments.js.map +1 -0
  311. package/dist/vendor/resources/beta/files.d.ts +190 -0
  312. package/dist/vendor/resources/beta/files.js +120 -0
  313. package/dist/vendor/resources/beta/files.js.map +1 -0
  314. package/dist/vendor/resources/beta/index.d.ts +17 -0
  315. package/dist/vendor/resources/beta/index.js +19 -0
  316. package/dist/vendor/resources/beta/index.js.map +1 -0
  317. package/dist/vendor/resources/beta/memory-stores/index.d.ts +3 -0
  318. package/dist/vendor/resources/beta/memory-stores/index.js +5 -0
  319. package/dist/vendor/resources/beta/memory-stores/index.js.map +1 -0
  320. package/dist/vendor/resources/beta/memory-stores/memories.d.ts +346 -0
  321. package/dist/vendor/resources/beta/memory-stores/memories.js +126 -0
  322. package/dist/vendor/resources/beta/memory-stores/memories.js.map +1 -0
  323. package/dist/vendor/resources/beta/memory-stores/memory-stores.d.ts +230 -0
  324. package/dist/vendor/resources/beta/memory-stores/memory-stores.js +137 -0
  325. package/dist/vendor/resources/beta/memory-stores/memory-stores.js.map +1 -0
  326. package/dist/vendor/resources/beta/memory-stores/memory-versions.d.ts +252 -0
  327. package/dist/vendor/resources/beta/memory-stores/memory-versions.js +77 -0
  328. package/dist/vendor/resources/beta/memory-stores/memory-versions.js.map +1 -0
  329. package/dist/vendor/resources/beta/memory-stores.d.ts +1 -0
  330. package/dist/vendor/resources/beta/memory-stores.js +3 -0
  331. package/dist/vendor/resources/beta/memory-stores.js.map +1 -0
  332. package/dist/vendor/resources/beta/messages/batches.d.ts +685 -0
  333. package/dist/vendor/resources/beta/messages/batches.js +203 -0
  334. package/dist/vendor/resources/beta/messages/batches.js.map +1 -0
  335. package/dist/vendor/resources/beta/messages/index.d.ts +3 -0
  336. package/dist/vendor/resources/beta/messages/index.js +5 -0
  337. package/dist/vendor/resources/beta/messages/index.js.map +1 -0
  338. package/dist/vendor/resources/beta/messages/messages.d.ts +5376 -0
  339. package/dist/vendor/resources/beta/messages/messages.js +158 -0
  340. package/dist/vendor/resources/beta/messages/messages.js.map +1 -0
  341. package/dist/vendor/resources/beta/messages.d.ts +1 -0
  342. package/dist/vendor/resources/beta/messages.js +3 -0
  343. package/dist/vendor/resources/beta/messages.js.map +1 -0
  344. package/dist/vendor/resources/beta/models.d.ts +217 -0
  345. package/dist/vendor/resources/beta/models.js +56 -0
  346. package/dist/vendor/resources/beta/models.js.map +1 -0
  347. package/dist/vendor/resources/beta/organization/api-keys.d.ts +176 -0
  348. package/dist/vendor/resources/beta/organization/api-keys.js +52 -0
  349. package/dist/vendor/resources/beta/organization/api-keys.js.map +1 -0
  350. package/dist/vendor/resources/beta/organization/compliance-settings.d.ts +73 -0
  351. package/dist/vendor/resources/beta/organization/compliance-settings.js +48 -0
  352. package/dist/vendor/resources/beta/organization/compliance-settings.js.map +1 -0
  353. package/dist/vendor/resources/beta/organization/external-keys.d.ts +271 -0
  354. package/dist/vendor/resources/beta/organization/external-keys.js +115 -0
  355. package/dist/vendor/resources/beta/organization/external-keys.js.map +1 -0
  356. package/dist/vendor/resources/beta/organization/federation/federation.d.ts +13 -0
  357. package/dist/vendor/resources/beta/organization/federation/federation.js +13 -0
  358. package/dist/vendor/resources/beta/organization/federation/federation.js.map +1 -0
  359. package/dist/vendor/resources/beta/organization/federation/index.d.ts +3 -0
  360. package/dist/vendor/resources/beta/organization/federation/index.js +5 -0
  361. package/dist/vendor/resources/beta/organization/federation/index.js.map +1 -0
  362. package/dist/vendor/resources/beta/organization/federation/issuers.d.ts +352 -0
  363. package/dist/vendor/resources/beta/organization/federation/issuers.js +165 -0
  364. package/dist/vendor/resources/beta/organization/federation/issuers.js.map +1 -0
  365. package/dist/vendor/resources/beta/organization/federation/rules/index.d.ts +2 -0
  366. package/dist/vendor/resources/beta/organization/federation/rules/index.js +4 -0
  367. package/dist/vendor/resources/beta/organization/federation/rules/index.js.map +1 -0
  368. package/dist/vendor/resources/beta/organization/federation/rules/rules.d.ts +467 -0
  369. package/dist/vendor/resources/beta/organization/federation/rules/rules.js +190 -0
  370. package/dist/vendor/resources/beta/organization/federation/rules/rules.js.map +1 -0
  371. package/dist/vendor/resources/beta/organization/federation/rules/workspaces.d.ts +123 -0
  372. package/dist/vendor/resources/beta/organization/federation/rules/workspaces.js +110 -0
  373. package/dist/vendor/resources/beta/organization/federation/rules/workspaces.js.map +1 -0
  374. package/dist/vendor/resources/beta/organization/federation/rules.d.ts +1 -0
  375. package/dist/vendor/resources/beta/organization/federation/rules.js +3 -0
  376. package/dist/vendor/resources/beta/organization/federation/rules.js.map +1 -0
  377. package/dist/vendor/resources/beta/organization/federation.d.ts +1 -0
  378. package/dist/vendor/resources/beta/organization/federation.js +3 -0
  379. package/dist/vendor/resources/beta/organization/federation.js.map +1 -0
  380. package/dist/vendor/resources/beta/organization/index.d.ts +10 -0
  381. package/dist/vendor/resources/beta/organization/index.js +12 -0
  382. package/dist/vendor/resources/beta/organization/index.js.map +1 -0
  383. package/dist/vendor/resources/beta/organization/invites.d.ts +161 -0
  384. package/dist/vendor/resources/beta/organization/invites.js +72 -0
  385. package/dist/vendor/resources/beta/organization/invites.js.map +1 -0
  386. package/dist/vendor/resources/beta/organization/organization.d.ts +72 -0
  387. package/dist/vendor/resources/beta/organization/organization.js +54 -0
  388. package/dist/vendor/resources/beta/organization/organization.js.map +1 -0
  389. package/dist/vendor/resources/beta/organization/rate-limits.d.ts +76 -0
  390. package/dist/vendor/resources/beta/organization/rate-limits.js +27 -0
  391. package/dist/vendor/resources/beta/organization/rate-limits.js.map +1 -0
  392. package/dist/vendor/resources/beta/organization/service-accounts/index.d.ts +2 -0
  393. package/dist/vendor/resources/beta/organization/service-accounts/index.js +4 -0
  394. package/dist/vendor/resources/beta/organization/service-accounts/index.js.map +1 -0
  395. package/dist/vendor/resources/beta/organization/service-accounts/service-accounts.d.ts +257 -0
  396. package/dist/vendor/resources/beta/organization/service-accounts/service-accounts.js +166 -0
  397. package/dist/vendor/resources/beta/organization/service-accounts/service-accounts.js.map +1 -0
  398. package/dist/vendor/resources/beta/organization/service-accounts/workspaces.d.ts +140 -0
  399. package/dist/vendor/resources/beta/organization/service-accounts/workspaces.js +121 -0
  400. package/dist/vendor/resources/beta/organization/service-accounts/workspaces.js.map +1 -0
  401. package/dist/vendor/resources/beta/organization/service-accounts.d.ts +1 -0
  402. package/dist/vendor/resources/beta/organization/service-accounts.js +3 -0
  403. package/dist/vendor/resources/beta/organization/service-accounts.js.map +1 -0
  404. package/dist/vendor/resources/beta/organization/users.d.ts +123 -0
  405. package/dist/vendor/resources/beta/organization/users.js +63 -0
  406. package/dist/vendor/resources/beta/organization/users.js.map +1 -0
  407. package/dist/vendor/resources/beta/organization/workspaces/index.d.ts +4 -0
  408. package/dist/vendor/resources/beta/organization/workspaces/index.js +6 -0
  409. package/dist/vendor/resources/beta/organization/workspaces/index.js.map +1 -0
  410. package/dist/vendor/resources/beta/organization/workspaces/members.d.ts +134 -0
  411. package/dist/vendor/resources/beta/organization/workspaces/members.js +98 -0
  412. package/dist/vendor/resources/beta/organization/workspaces/members.js.map +1 -0
  413. package/dist/vendor/resources/beta/organization/workspaces/rate-limits.d.ts +82 -0
  414. package/dist/vendor/resources/beta/organization/workspaces/rate-limits.js +30 -0
  415. package/dist/vendor/resources/beta/organization/workspaces/rate-limits.js.map +1 -0
  416. package/dist/vendor/resources/beta/organization/workspaces/service-accounts.d.ts +209 -0
  417. package/dist/vendor/resources/beta/organization/workspaces/service-accounts.js +185 -0
  418. package/dist/vendor/resources/beta/organization/workspaces/service-accounts.js.map +1 -0
  419. package/dist/vendor/resources/beta/organization/workspaces/workspaces.d.ts +302 -0
  420. package/dist/vendor/resources/beta/organization/workspaces/workspaces.js +104 -0
  421. package/dist/vendor/resources/beta/organization/workspaces/workspaces.js.map +1 -0
  422. package/dist/vendor/resources/beta/organization/workspaces.d.ts +1 -0
  423. package/dist/vendor/resources/beta/organization/workspaces.js +3 -0
  424. package/dist/vendor/resources/beta/organization/workspaces.js.map +1 -0
  425. package/dist/vendor/resources/beta/organization.d.ts +1 -0
  426. package/dist/vendor/resources/beta/organization.js +3 -0
  427. package/dist/vendor/resources/beta/organization.js.map +1 -0
  428. package/dist/vendor/resources/beta/sessions/events.d.ts +1513 -0
  429. package/dist/vendor/resources/beta/sessions/events.js +115 -0
  430. package/dist/vendor/resources/beta/sessions/events.js.map +1 -0
  431. package/dist/vendor/resources/beta/sessions/index.d.ts +4 -0
  432. package/dist/vendor/resources/beta/sessions/index.js +6 -0
  433. package/dist/vendor/resources/beta/sessions/index.js.map +1 -0
  434. package/dist/vendor/resources/beta/sessions/resources.d.ts +227 -0
  435. package/dist/vendor/resources/beta/sessions/resources.js +128 -0
  436. package/dist/vendor/resources/beta/sessions/resources.js.map +1 -0
  437. package/dist/vendor/resources/beta/sessions/sessions.d.ts +866 -0
  438. package/dist/vendor/resources/beta/sessions/sessions.js +150 -0
  439. package/dist/vendor/resources/beta/sessions/sessions.js.map +1 -0
  440. package/dist/vendor/resources/beta/sessions/threads/events.d.ts +77 -0
  441. package/dist/vendor/resources/beta/sessions/threads/events.js +57 -0
  442. package/dist/vendor/resources/beta/sessions/threads/events.js.map +1 -0
  443. package/dist/vendor/resources/beta/sessions/threads/index.d.ts +2 -0
  444. package/dist/vendor/resources/beta/sessions/threads/index.js +4 -0
  445. package/dist/vendor/resources/beta/sessions/threads/index.js.map +1 -0
  446. package/dist/vendor/resources/beta/sessions/threads/threads.d.ts +195 -0
  447. package/dist/vendor/resources/beta/sessions/threads/threads.js +80 -0
  448. package/dist/vendor/resources/beta/sessions/threads/threads.js.map +1 -0
  449. package/dist/vendor/resources/beta/sessions/threads.d.ts +1 -0
  450. package/dist/vendor/resources/beta/sessions/threads.js +3 -0
  451. package/dist/vendor/resources/beta/sessions/threads.js.map +1 -0
  452. package/dist/vendor/resources/beta/sessions.d.ts +1 -0
  453. package/dist/vendor/resources/beta/sessions.js +3 -0
  454. package/dist/vendor/resources/beta/sessions.js.map +1 -0
  455. package/dist/vendor/resources/beta/skills/index.d.ts +2 -0
  456. package/dist/vendor/resources/beta/skills/index.js +4 -0
  457. package/dist/vendor/resources/beta/skills/index.js.map +1 -0
  458. package/dist/vendor/resources/beta/skills/skills.d.ts +178 -0
  459. package/dist/vendor/resources/beta/skills/skills.js +96 -0
  460. package/dist/vendor/resources/beta/skills/skills.js.map +1 -0
  461. package/dist/vendor/resources/beta/skills/versions.d.ts +181 -0
  462. package/dist/vendor/resources/beta/skills/versions.js +125 -0
  463. package/dist/vendor/resources/beta/skills/versions.js.map +1 -0
  464. package/dist/vendor/resources/beta/skills.d.ts +1 -0
  465. package/dist/vendor/resources/beta/skills.js +3 -0
  466. package/dist/vendor/resources/beta/skills.js.map +1 -0
  467. package/dist/vendor/resources/beta/tunnels/certificates.d.ts +162 -0
  468. package/dist/vendor/resources/beta/tunnels/certificates.js +125 -0
  469. package/dist/vendor/resources/beta/tunnels/certificates.js.map +1 -0
  470. package/dist/vendor/resources/beta/tunnels/index.d.ts +2 -0
  471. package/dist/vendor/resources/beta/tunnels/index.js +4 -0
  472. package/dist/vendor/resources/beta/tunnels/index.js.map +1 -0
  473. package/dist/vendor/resources/beta/tunnels/tunnels.d.ts +211 -0
  474. package/dist/vendor/resources/beta/tunnels/tunnels.js +173 -0
  475. package/dist/vendor/resources/beta/tunnels/tunnels.js.map +1 -0
  476. package/dist/vendor/resources/beta/tunnels.d.ts +1 -0
  477. package/dist/vendor/resources/beta/tunnels.js +3 -0
  478. package/dist/vendor/resources/beta/tunnels.js.map +1 -0
  479. package/dist/vendor/resources/beta/user-profiles.d.ts +244 -0
  480. package/dist/vendor/resources/beta/user-profiles.js +114 -0
  481. package/dist/vendor/resources/beta/user-profiles.js.map +1 -0
  482. package/dist/vendor/resources/beta/vaults/credentials.d.ts +715 -0
  483. package/dist/vendor/resources/beta/vaults/credentials.js +173 -0
  484. package/dist/vendor/resources/beta/vaults/credentials.js.map +1 -0
  485. package/dist/vendor/resources/beta/vaults/index.d.ts +2 -0
  486. package/dist/vendor/resources/beta/vaults/index.js +4 -0
  487. package/dist/vendor/resources/beta/vaults/index.js.map +1 -0
  488. package/dist/vendor/resources/beta/vaults/vaults.d.ts +191 -0
  489. package/dist/vendor/resources/beta/vaults/vaults.js +141 -0
  490. package/dist/vendor/resources/beta/vaults/vaults.js.map +1 -0
  491. package/dist/vendor/resources/beta/vaults.d.ts +1 -0
  492. package/dist/vendor/resources/beta/vaults.js +3 -0
  493. package/dist/vendor/resources/beta/vaults.js.map +1 -0
  494. package/dist/vendor/resources/beta/webhooks.d.ts +464 -0
  495. package/dist/vendor/resources/beta/webhooks.js +29 -0
  496. package/dist/vendor/resources/beta/webhooks.js.map +1 -0
  497. package/dist/vendor/resources/beta.d.ts +1 -0
  498. package/dist/vendor/resources/beta.js +3 -0
  499. package/dist/vendor/resources/beta.js.map +1 -0
  500. package/dist/vendor/resources/completions.d.ts +172 -0
  501. package/dist/vendor/resources/completions.js +19 -0
  502. package/dist/vendor/resources/completions.js.map +1 -0
  503. package/dist/vendor/resources/files.d.ts +104 -0
  504. package/dist/vendor/resources/files.js +48 -0
  505. package/dist/vendor/resources/files.js.map +1 -0
  506. package/dist/vendor/resources/index.d.ts +7 -0
  507. package/dist/vendor/resources/index.js +9 -0
  508. package/dist/vendor/resources/index.js.map +1 -0
  509. package/dist/vendor/resources/messages/batches.d.ts +312 -0
  510. package/dist/vendor/resources/messages/batches.js +157 -0
  511. package/dist/vendor/resources/messages/batches.js.map +1 -0
  512. package/dist/vendor/resources/messages/index.d.ts +2 -0
  513. package/dist/vendor/resources/messages/index.js +4 -0
  514. package/dist/vendor/resources/messages/index.js.map +1 -0
  515. package/dist/vendor/resources/messages/messages.d.ts +3886 -0
  516. package/dist/vendor/resources/messages/messages.js +130 -0
  517. package/dist/vendor/resources/messages/messages.js.map +1 -0
  518. package/dist/vendor/resources/messages.d.ts +1 -0
  519. package/dist/vendor/resources/messages.js +3 -0
  520. package/dist/vendor/resources/messages.js.map +1 -0
  521. package/dist/vendor/resources/models.d.ts +196 -0
  522. package/dist/vendor/resources/models.js +41 -0
  523. package/dist/vendor/resources/models.js.map +1 -0
  524. package/dist/vendor/resources/shared.d.ts +43 -0
  525. package/dist/vendor/resources/shared.js +3 -0
  526. package/dist/vendor/resources/shared.js.map +1 -0
  527. package/dist/vendor/resources/skills/index.d.ts +2 -0
  528. package/dist/vendor/resources/skills/index.js +4 -0
  529. package/dist/vendor/resources/skills/index.js.map +1 -0
  530. package/dist/vendor/resources/skills/skills.d.ts +128 -0
  531. package/dist/vendor/resources/skills/skills.js +36 -0
  532. package/dist/vendor/resources/skills/skills.js.map +1 -0
  533. package/dist/vendor/resources/skills/versions.d.ts +103 -0
  534. package/dist/vendor/resources/skills/versions.js +37 -0
  535. package/dist/vendor/resources/skills/versions.js.map +1 -0
  536. package/dist/vendor/resources/skills.d.ts +1 -0
  537. package/dist/vendor/resources/skills.js +3 -0
  538. package/dist/vendor/resources/skills.js.map +1 -0
  539. package/dist/vendor/resources/top-level.d.ts +1 -0
  540. package/dist/vendor/resources/top-level.js +3 -0
  541. package/dist/vendor/resources/top-level.js.map +1 -0
  542. package/dist/vendor/resources.d.ts +1 -0
  543. package/dist/vendor/resources.js +2 -0
  544. package/dist/vendor/resources.js.map +1 -0
  545. package/dist/vendor/streaming.d.ts +2 -0
  546. package/dist/vendor/streaming.js +3 -0
  547. package/dist/vendor/streaming.js.map +1 -0
  548. package/dist/vendor/tools/agent-toolset/fs-util.d.ts +74 -0
  549. package/dist/vendor/tools/agent-toolset/fs-util.js +184 -0
  550. package/dist/vendor/tools/agent-toolset/fs-util.js.map +1 -0
  551. package/dist/vendor/tools/agent-toolset/memories.d.ts +172 -0
  552. package/dist/vendor/tools/agent-toolset/memories.js +910 -0
  553. package/dist/vendor/tools/agent-toolset/memories.js.map +1 -0
  554. package/dist/vendor/tools/agent-toolset/node.browser.d.ts +80 -0
  555. package/dist/vendor/tools/agent-toolset/node.browser.js +129 -0
  556. package/dist/vendor/tools/agent-toolset/node.browser.js.map +1 -0
  557. package/dist/vendor/tools/agent-toolset/node.d.ts +191 -0
  558. package/dist/vendor/tools/agent-toolset/node.js +886 -0
  559. package/dist/vendor/tools/agent-toolset/node.js.map +1 -0
  560. package/dist/vendor/tools/agent-toolset/skills.d.ts +73 -0
  561. package/dist/vendor/tools/agent-toolset/skills.js +320 -0
  562. package/dist/vendor/tools/agent-toolset/skills.js.map +1 -0
  563. package/dist/vendor/tools/agent-toolset/sync-interval.d.ts +18 -0
  564. package/dist/vendor/tools/agent-toolset/sync-interval.js +25 -0
  565. package/dist/vendor/tools/agent-toolset/sync-interval.js.map +1 -0
  566. package/dist/vendor/tools/memory/node.browser.d.ts +26 -0
  567. package/dist/vendor/tools/memory/node.browser.js +44 -0
  568. package/dist/vendor/tools/memory/node.browser.js.map +1 -0
  569. package/dist/vendor/tools/memory/node.d.ts +17 -0
  570. package/dist/vendor/tools/memory/node.js +327 -0
  571. package/dist/vendor/tools/memory/node.js.map +1 -0
  572. package/dist/vendor/uploads.d.ts +2 -0
  573. package/dist/vendor/uploads.js +3 -0
  574. package/dist/vendor/uploads.js.map +1 -0
  575. package/dist/vendor/version.d.ts +1 -0
  576. package/dist/vendor/version.js +2 -0
  577. package/dist/vendor/version.js.map +1 -0
  578. package/package.json +7 -14
  579. package/sdk.cjs +6 -6
  580. package/sdk.cjs.map +18 -18
  581. package/sdk.d.ts +10 -10
  582. package/sdk.mjs +21 -21
  583. package/sdk.mjs.map +18 -18
@@ -0,0 +1,976 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+ import { uuid4 } from './internal/utils/uuid.js';
3
+ import { validatePositiveInteger, isAbsoluteURL, safeJSON } from './internal/utils/values.js';
4
+ import { sleep } from './internal/utils/sleep.js';
5
+ import { castToError, isAbortError } from './internal/errors.js';
6
+ import { getPlatformHeaders } from './internal/detect-platform.js';
7
+ import { armAbandonmentBackstop, registerRequestSignalCleanup, releaseRequestSignal, } from './internal/request-signal.js';
8
+ import * as Shims from './internal/shims.js';
9
+ import * as Opts from './internal/request-options.js';
10
+ import { stringifyQuery } from './internal/utils/query.js';
11
+ import { VERSION } from './version.js';
12
+ import * as Errors from './core/error.js';
13
+ import { OAUTH_API_BETA_HEADER } from './lib/credentials/types.js';
14
+ import { TokenCache } from './lib/credentials/token-cache.js';
15
+ import { defaultCredentials, resolveCredentialsFromConfig } from './lib/credentials/credential-chain.js';
16
+ import { isFetchOriginError, isRetryableError, wrapFetchWithMiddleware, } from './core/middleware.js';
17
+ import * as Pagination from './core/pagination.js';
18
+ import * as Uploads from './core/uploads.js';
19
+ import * as API from './resources/index.js';
20
+ import { APIPromise } from './core/api-promise.js';
21
+ import { Completions, } from './resources/completions.js';
22
+ import { Files, } from './resources/files.js';
23
+ import { Models, } from './resources/models.js';
24
+ import { Beta, } from './resources/beta/beta.js';
25
+ import { Messages, } from './resources/messages/messages.js';
26
+ import { Skills, } from './resources/skills/skills.js';
27
+ import { isRunningInBrowser } from './internal/detect-platform.js';
28
+ import { buildHeaders } from './internal/headers.js';
29
+ import { readEnv } from './internal/utils/env.js';
30
+ import { defaultLogLevel, formatRequestDetails, loggerFor, parseLogLevel, } from './internal/utils/log.js';
31
+ import { isEmptyObj } from './internal/utils/values.js';
32
+ export const HUMAN_PROMPT = '\\n\\nHuman:';
33
+ export const AI_PROMPT = '\\n\\nAssistant:';
34
+ /**
35
+ * Base class for Puku API clients.
36
+ */
37
+ export class BasePuku {
38
+ apiKey;
39
+ authToken;
40
+ webhookKey;
41
+ /**
42
+ * The active credential provider. Default credential resolution runs once
43
+ * at construction time. If it fails, the error is surfaced on every
44
+ * request and the client must be reconstructed — there is no retry path.
45
+ *
46
+ * Clones returned by {@link withOptions} share the parent's auth state
47
+ * (provider, token cache, pending resolution, and any resolution error)
48
+ * unless the caller passes an explicit `apiKey`, `authToken`,
49
+ * `credentials`, `config`, or `profile` override.
50
+ */
51
+ get credentials() {
52
+ return this._authState.provider;
53
+ }
54
+ _authState;
55
+ /**
56
+ * Whether `baseURL` was chosen by the caller (constructor arg or env var)
57
+ * rather than derived. Non-explicit base URLs may be replaced — by a
58
+ * profile-supplied host, or by re-derivation in `withOptions()` clones.
59
+ * Subclasses that derive their own base URL should correct this after
60
+ * `super()`, since the base constructor can't tell a derived value apart.
61
+ */
62
+ _baseURLIsExplicit;
63
+ _requestAuthFlags = new WeakMap();
64
+ baseURL;
65
+ maxRetries;
66
+ timeout;
67
+ logger;
68
+ logLevel;
69
+ fetchOptions;
70
+ middleware;
71
+ fetch;
72
+ #encoder;
73
+ idempotencyHeader;
74
+ _options;
75
+ /**
76
+ * API Client for interfacing with the Puku API.
77
+ *
78
+ * @param {string | null | undefined} [opts.apiKey=process.env['PUKU_API_KEY'] ?? null]
79
+ * @param {string | null | undefined} [opts.authToken=process.env['PUKU_AUTH_TOKEN'] ?? null]
80
+ * @param {string | null | undefined} [opts.webhookKey=process.env['PUKU_WEBHOOK_SIGNING_KEY'] ?? null]
81
+ * @param {string} [opts.baseURL=process.env['PUKU_BASE_URL']] - Override the default base URL for the API. Required.
82
+ * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
83
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
84
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
85
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
86
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
87
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
88
+ * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
89
+ */
90
+ constructor({ baseURL = readEnv('PUKU_BASE_URL'), apiKey, authToken, webhookKey = readEnv('PUKU_WEBHOOK_SIGNING_KEY') ?? null, ...opts } = {}) {
91
+ // An explicit `profile` is a constructor-level credential choice; when set,
92
+ // do not let env PUKU_API_KEY / PUKU_AUTH_TOKEN shadow it.
93
+ if (apiKey === undefined) {
94
+ apiKey = opts.profile != null ? null : readEnv('PUKU_API_KEY') ?? null;
95
+ }
96
+ if (authToken === undefined) {
97
+ authToken = opts.profile != null ? null : readEnv('PUKU_AUTH_TOKEN') ?? null;
98
+ }
99
+ if (opts.profile != null && (opts.credentials != null || opts.config != null)) {
100
+ throw new TypeError('Pass at most one of `profile`, `credentials`, or `config`.');
101
+ }
102
+ const options = {
103
+ apiKey,
104
+ authToken,
105
+ webhookKey,
106
+ ...opts,
107
+ baseURL: baseURL || '',
108
+ };
109
+ if (!options.baseURL) {
110
+ throw new Errors.PukuError("Missing baseURL: pass `baseURL` to the constructor or set the PUKU_BASE_URL environment variable.");
111
+ }
112
+ if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
113
+ throw new Errors.PukuError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew PukuAI({ apiKey, dangerouslyAllowBrowser: true });\n");
114
+ }
115
+ this.baseURL = options.baseURL;
116
+ // Normalize a trailing `/v1` so the SDK can append paths
117
+ // (`/v1/messages`, `/v1/models`, etc.) without doubling the prefix. Puku
118
+ // gateways are also commonly deployed at the bare host (e.g.
119
+ // `https://api.sdk.puku.sh`); both forms must work.
120
+ if (this.baseURL.endsWith('/v1')) {
121
+ this.baseURL = this.baseURL.slice(0, -3);
122
+ }
123
+ // After destructuring, `baseURL` is the constructor arg or
124
+ // PUKU_BASE_URL — both count as an explicit choice that a profile
125
+ // base_url must not override. A falsy value means we fell through to the
126
+ // hardcoded default above and a profile may supply the host. withOptions()
127
+ // propagates the parent's flag via __baseURLIsExplicit so a non-overriding
128
+ // clone doesn't mistake the inherited baseURL for a caller-supplied one.
129
+ this._baseURLIsExplicit = opts.__baseURLIsExplicit ?? !!baseURL;
130
+ this.timeout = options.timeout ?? BasePuku.DEFAULT_TIMEOUT /* 10 minutes */;
131
+ this.logger = options.logger ?? console;
132
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
133
+ this.logLevel = defaultLogLevel;
134
+ this.logLevel =
135
+ parseLogLevel(options.logLevel, 'ClientOptions.logLevel', loggerFor(this)) ??
136
+ parseLogLevel(readEnv('PUKU_LOG'), "process.env['PUKU_LOG']", loggerFor(this)) ??
137
+ defaultLogLevel;
138
+ this.fetchOptions = options.fetchOptions;
139
+ this.maxRetries = options.maxRetries ?? 2;
140
+ this.fetch = options.fetch ?? Shims.getDefaultFetch();
141
+ this.#encoder = Opts.FallbackEncoder;
142
+ this.middleware = [...(options.middleware ?? [])];
143
+ const customHeadersEnv = readEnv('PUKU_CUSTOM_HEADERS');
144
+ if (customHeadersEnv) {
145
+ const parsed = {};
146
+ for (const line of customHeadersEnv.split('\n')) {
147
+ const colon = line.indexOf(':');
148
+ if (colon >= 0) {
149
+ parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
150
+ }
151
+ }
152
+ options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
153
+ }
154
+ const inherited = opts.__auth;
155
+ // Never persist the internal __auth handle on _options — it's a
156
+ // one-shot constructor signal, and leaking it through _options would
157
+ // cause withOptions() to spread a stale value into clones.
158
+ delete options.__auth;
159
+ delete options.__baseURLIsExplicit;
160
+ this._options = options;
161
+ this.apiKey = typeof apiKey === 'string' ? apiKey : null;
162
+ this.authToken = authToken;
163
+ this.webhookKey = webhookKey;
164
+ if (inherited) {
165
+ this._authState = inherited;
166
+ if (!this._baseURLIsExplicit && inherited.baseURL) {
167
+ this.baseURL = inherited.baseURL;
168
+ }
169
+ }
170
+ else {
171
+ this._authState = { provider: null, tokenCache: null, resolution: null, error: null, extraHeaders: {} };
172
+ // apiKey/authToken win over credentials/config/profile; don't build a
173
+ // token cache or resolve a config that the request path will then ignore.
174
+ if (this.apiKey == null && this.authToken == null) {
175
+ const credentials = options.credentials ?? null;
176
+ if (credentials) {
177
+ this._authState.provider = credentials;
178
+ this._authState.tokenCache = this._makeTokenCache(credentials);
179
+ }
180
+ else if (options.config != null) {
181
+ const result = resolveCredentialsFromConfig(options.config, this._credentialResolverOptions());
182
+ this._authState.provider = result.provider;
183
+ this._authState.tokenCache = this._makeTokenCache(result.provider);
184
+ this._authState.extraHeaders = result.extraHeaders;
185
+ this._applyCredentialBaseURL(result.baseURL);
186
+ }
187
+ else if (options.profile != null) {
188
+ this._authState.resolution = this._resolveDefaultCredentials(options.profile);
189
+ }
190
+ else if (this._shouldResolveDefaultCredentials()) {
191
+ // No explicit auth provided — lazily resolve from the credential
192
+ // chain on first request. Errors are captured into _auth.error and
193
+ // surfaced on first use rather than as an unhandled rejection.
194
+ this._authState.resolution = this._resolveDefaultCredentials();
195
+ }
196
+ }
197
+ }
198
+ }
199
+ /**
200
+ * Whether to lazily resolve auth from the default credential chain when no
201
+ * explicit auth is configured. Called once from the constructor, so
202
+ * overrides must not depend on subclass instance state. Subclasses that
203
+ * bring their own auth scheme return false so unrelated local credentials
204
+ * are never resolved or allowed to supply a base URL.
205
+ */
206
+ _shouldResolveDefaultCredentials() {
207
+ return true;
208
+ }
209
+ /**
210
+ * Stores a profile/config-supplied base URL on the shared auth state and, if
211
+ * the caller did not pin `baseURL` via constructor option or env, adopts it
212
+ * as this client's outbound API host. Precedence: ctor opt > env > profile >
213
+ * hardcoded default.
214
+ */
215
+ _applyCredentialBaseURL(baseURL) {
216
+ if (!baseURL)
217
+ return;
218
+ const normalized = baseURL.replace(/\/+$/, '');
219
+ this._authState.baseURL = normalized;
220
+ if (!this._baseURLIsExplicit) {
221
+ this.baseURL = normalized;
222
+ }
223
+ }
224
+ /**
225
+ * Options bag passed into the credential chain. `baseURL` here is only the
226
+ * fallback host for the token-exchange POST when the config itself omits
227
+ * `base_url`; the chain returns the config's own `base_url` (if any) on
228
+ * {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL}
229
+ * then adopts for outbound API requests. The two are deliberately decoupled
230
+ * so this fallback never round-trips into precedence.
231
+ */
232
+ _credentialResolverOptions() {
233
+ return {
234
+ baseURL: this.baseURL,
235
+ fetch: this._credentialsFetch(),
236
+ userAgent: this.getUserAgent(),
237
+ onCacheWriteError: (err) => {
238
+ loggerFor(this).debug('credential cache write failed (best-effort)', err);
239
+ },
240
+ onSafetyWarning: (msg) => {
241
+ loggerFor(this).warn(msg);
242
+ },
243
+ };
244
+ }
245
+ /**
246
+ * A `Fetch` for first-party credential token-exchange requests (OIDC
247
+ * federation jwt-bearer grants, user-OAuth refresh grants) that routes
248
+ * through this client's middleware chain, so middleware observes token
249
+ * traffic like any other request. Only client-level middleware applies:
250
+ * a minted token is shared across requests, so attributing the exchange
251
+ * to any one request's per-request middleware would be arbitrary. For the
252
+ * same reason, `ctx.options` is undefined for these requests.
253
+ */
254
+ _credentialsFetch() {
255
+ return wrapFetchWithMiddleware(this.fetch, this.middleware, undefined, this);
256
+ }
257
+ _makeTokenCache(provider) {
258
+ return new TokenCache(provider, (err) => {
259
+ loggerFor(this).debug('advisory token refresh failed; serving cached token', err);
260
+ });
261
+ }
262
+ /**
263
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
264
+ */
265
+ withOptions(options) {
266
+ // Share the auth state object unless the caller passes any auth-related
267
+ // key. The `in` check is intentional: even `apiKey: undefined` opts the
268
+ // clone out of sharing (it gets its own _auth and TokenCache, though it
269
+ // may still wrap the parent's provider via the credentials spread below).
270
+ const overridesStructuredAuth = 'credentials' in options || 'config' in options || 'profile' in options;
271
+ const overridesAuth = 'apiKey' in options || 'authToken' in options || overridesStructuredAuth;
272
+ const internal = {
273
+ ...this._options,
274
+ // Only forward baseURL when the caller (or env) explicitly chose it.
275
+ // For a non-explicit parent, this.baseURL may have been mutated to the
276
+ // profile-resolved host; pinning that as the clone's options.baseURL
277
+ // would make _options on the clone misreport caller intent and would
278
+ // leave the clone stuck on the parent's host across an auth override.
279
+ // The clone instead receives the construction-time value via
280
+ // ...this._options above and re-adopts the profile host through the
281
+ // shared _authState.baseURL + __baseURLIsExplicit=false path.
282
+ ...(this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}),
283
+ maxRetries: this.maxRetries,
284
+ timeout: this.timeout,
285
+ logger: this.logger,
286
+ logLevel: this.logLevel,
287
+ fetch: this.fetch,
288
+ fetchOptions: this.fetchOptions,
289
+ middleware: this.middleware,
290
+ apiKey: this.apiKey,
291
+ authToken: this.authToken,
292
+ webhookKey: this.webhookKey,
293
+ // credentials: this.credentials is a no-op when __auth is shared (the
294
+ // ctor takes the inherited path and ignores options.credentials); when
295
+ // overridesAuth is true via apiKey/authToken only, it lets the clone
296
+ // build a fresh TokenCache around the parent's provider.
297
+ credentials: this.credentials,
298
+ // When the caller passes a structured-credential override, drop inherited
299
+ // structured-credential options so only `...options` supplies them —
300
+ // otherwise an inherited `credentials`/`config`/`profile` would trip the
301
+ // mutual-exclusion check or precedence over the override.
302
+ ...(overridesStructuredAuth ? { credentials: undefined, config: undefined, profile: undefined } : {}),
303
+ ...options,
304
+ // Always set __auth so any stale value from ...this._options is
305
+ // overwritten. undefined means "build fresh auth from these options".
306
+ __auth: overridesAuth ? undefined : this._authState,
307
+ __baseURLIsExplicit: 'baseURL' in options ? true : this._baseURLIsExplicit,
308
+ };
309
+ return new this.constructor(internal);
310
+ }
311
+ /**
312
+ * Lazily resolves credentials from config files or environment variables.
313
+ * Called once from the constructor when no explicit auth is provided, or
314
+ * when an explicit `profile` was passed (in which case a missing/unresolved
315
+ * profile is surfaced as an error instead of falling through to "no auth").
316
+ * The returned promise is stored and awaited on the first request.
317
+ */
318
+ async _resolveDefaultCredentials(profile) {
319
+ try {
320
+ const result = await defaultCredentials(this._credentialResolverOptions(), profile);
321
+ if (result) {
322
+ this._authState.provider = result.provider;
323
+ this._authState.tokenCache = this._makeTokenCache(result.provider);
324
+ this._authState.extraHeaders = result.extraHeaders;
325
+ this._applyCredentialBaseURL(result.baseURL);
326
+ }
327
+ else if (profile != null) {
328
+ throw new Errors.PukuError(`Profile "${profile}" could not be resolved (no <config_dir>/configs/${profile}.json found).`);
329
+ }
330
+ }
331
+ catch (err) {
332
+ this._authState.error = err;
333
+ }
334
+ finally {
335
+ this._authState.resolution = null;
336
+ }
337
+ }
338
+ /**
339
+ * Check whether the base URL is set to its default.
340
+ *
341
+ * A profile-supplied `base_url` counts as an override here: a profile that
342
+ * pins a non-default host is declaring "this whole client targets deployment
343
+ * X", so per-endpoint {@link RequestOptions.defaultBaseURL} hints must not
344
+ * silently route individual calls back to production. No generated resource
345
+ * currently sets `defaultBaseURL`, so this is documenting intent for when
346
+ * one does.
347
+ */
348
+ #baseURLOverridden() {
349
+ return this.baseURL !== '';
350
+ }
351
+ defaultQuery() {
352
+ return this._options.defaultQuery;
353
+ }
354
+ validateHeaders({ values, nulls }) {
355
+ if (values.get('x-api-key') || values.get('authorization')) {
356
+ return;
357
+ }
358
+ if (this._authState.error) {
359
+ throw this._authState.error;
360
+ }
361
+ if (this._authState.tokenCache || this._authState.resolution) {
362
+ return; // auth will be injected per-request via authHeaders
363
+ }
364
+ if (this.apiKey && values.get('x-api-key')) {
365
+ return;
366
+ }
367
+ if (nulls.has('x-api-key')) {
368
+ return;
369
+ }
370
+ if (this.authToken && values.get('authorization')) {
371
+ return;
372
+ }
373
+ if (nulls.has('authorization')) {
374
+ return;
375
+ }
376
+ throw new 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');
377
+ }
378
+ _authFlags(opts) {
379
+ let flags = this._requestAuthFlags.get(opts);
380
+ if (!flags) {
381
+ flags = { usedTokenCache: false, didRefreshFor401: false };
382
+ this._requestAuthFlags.set(opts, flags);
383
+ }
384
+ return flags;
385
+ }
386
+ async authHeaders(opts) {
387
+ // Wait for lazy credential resolution if it's in progress. If it failed,
388
+ // return no auth headers — validateHeaders surfaces the stored error
389
+ // after the explicit-header escape hatch has had a chance to apply.
390
+ if (this._authState.resolution) {
391
+ await this._authState.resolution;
392
+ }
393
+ if (this._authState.error) {
394
+ return undefined;
395
+ }
396
+ // If we have a token cache and no API key is set, use token auth
397
+ if (this._authState.tokenCache && this.apiKey == null) {
398
+ const token = await this._authState.tokenCache.getToken();
399
+ this._authFlags(opts).usedTokenCache = true;
400
+ return buildHeaders([{ Authorization: `Bearer ${token}` }]);
401
+ }
402
+ return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
403
+ }
404
+ async apiKeyAuth(opts) {
405
+ if (this.apiKey == null) {
406
+ return undefined;
407
+ }
408
+ return buildHeaders([{ 'X-Api-Key': this.apiKey }]);
409
+ }
410
+ async bearerAuth(opts) {
411
+ if (this.authToken == null) {
412
+ return undefined;
413
+ }
414
+ return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]);
415
+ }
416
+ stringifyQuery(query) {
417
+ return stringifyQuery(query);
418
+ }
419
+ getUserAgent() {
420
+ return `Puku/JS ${VERSION}`;
421
+ }
422
+ defaultIdempotencyKey() {
423
+ return `stainless-node-retry-${uuid4()}`;
424
+ }
425
+ makeStatusError(status, error, message, headers) {
426
+ return Errors.APIError.generate(status, error, message, headers);
427
+ }
428
+ buildURL(path, query, defaultBaseURL) {
429
+ const baseURL = (!this.#baseURLOverridden() && defaultBaseURL) || this.baseURL;
430
+ const url = isAbsoluteURL(path) ?
431
+ new URL(path)
432
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
433
+ const defaultQuery = this.defaultQuery();
434
+ const pathQuery = Object.fromEntries(url.searchParams);
435
+ if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
436
+ query = { ...pathQuery, ...defaultQuery, ...query };
437
+ }
438
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
439
+ url.search = this.stringifyQuery(query);
440
+ }
441
+ return url.toString();
442
+ }
443
+ _calculateNonstreamingTimeout(maxTokens) {
444
+ const defaultTimeout = 10 * 60;
445
+ const expectedTimeout = (60 * 60 * maxTokens) / 128_000;
446
+ if (expectedTimeout > defaultTimeout) {
447
+ throw new Errors.PukuError('Streaming is required for operations that may take longer than 10 minutes. ' +
448
+ 'See https://github.com/puku-ai/sdk#streaming-responses for more details');
449
+ }
450
+ return defaultTimeout * 1000;
451
+ }
452
+ /**
453
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
454
+ */
455
+ async prepareOptions(options) { }
456
+ /**
457
+ * Used as a callback for mutating the given `RequestInit` object.
458
+ *
459
+ * This is useful for cases where you want to add certain headers based off of
460
+ * the request properties, e.g. `method` or `url`.
461
+ *
462
+ * Runs after all middleware (including {@link backendMiddleware}),
463
+ * immediately before each underlying fetch call, so it sees exactly what
464
+ * goes over the wire. Middleware may replay a request by calling `next()`
465
+ * more than once, so this hook can run multiple times per attempt:
466
+ * overrides must be idempotent and overwrite headers from a previous
467
+ * invocation rather than append to them.
468
+ */
469
+ async prepareRequest(request, { url, options }) {
470
+ // Append auth-derived headers when using token auth. Done here (after all
471
+ // header merging) rather than in authHeaders() so we append to any existing
472
+ // puku-beta values instead of being overwritten by later header sources.
473
+ if (this._authState.tokenCache && this.apiKey == null) {
474
+ // Normalize to a Headers instance — custom fetch impls or polyfills can
475
+ // hand back arrays / plain objects, and silently dropping the beta
476
+ // header in that case would surface as a confusing server-side 4xx.
477
+ const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers);
478
+ for (const [k, v] of Object.entries(this._authState.extraHeaders)) {
479
+ if (!headers.has(k))
480
+ headers.set(k, v);
481
+ }
482
+ const existing = headers
483
+ .get('puku-beta')
484
+ ?.split(',')
485
+ .map((s) => s.trim());
486
+ if (!existing?.includes(OAUTH_API_BETA_HEADER)) {
487
+ headers.append('puku-beta', OAUTH_API_BETA_HEADER);
488
+ }
489
+ request.headers = headers;
490
+ }
491
+ }
492
+ /**
493
+ * Internal {@link Middleware} composed innermost in the chain — inside both
494
+ * client-level and per-request middleware, immediately around the underlying
495
+ * `fetch`. Subclasses for third-party backends override this to adapt the
496
+ * canonical PukuAI-shaped request to the backend's wire shape (URL/body
497
+ * rewriting, request signing) and to normalize the wire response back to the
498
+ * canonical shape (e.g. AWS EventStream to SSE).
499
+ *
500
+ * Running inside the user's middleware means user middleware always observes
501
+ * canonical PukuAI-shaped traffic, and the adaptation re-runs (e.g.
502
+ * re-signs) on every `next()` invocation, covering whatever the middleware
503
+ * mutated.
504
+ *
505
+ * Errors thrown here follow the middleware error policy: they propagate to
506
+ * the caller as-is — no retries, no `APIConnectionError` wrapping — unless
507
+ * retryable (see {@link Middleware}); throw a `RetryableError` to opt into
508
+ * the retry path.
509
+ */
510
+ backendMiddleware() {
511
+ return [];
512
+ }
513
+ get(path, opts) {
514
+ return this.methodRequest('get', path, opts);
515
+ }
516
+ post(path, opts) {
517
+ return this.methodRequest('post', path, opts);
518
+ }
519
+ patch(path, opts) {
520
+ return this.methodRequest('patch', path, opts);
521
+ }
522
+ put(path, opts) {
523
+ return this.methodRequest('put', path, opts);
524
+ }
525
+ delete(path, opts) {
526
+ return this.methodRequest('delete', path, opts);
527
+ }
528
+ methodRequest(method, path, opts) {
529
+ return this.request(Promise.resolve(opts).then((opts) => {
530
+ return { method, path, ...opts };
531
+ }));
532
+ }
533
+ request(options, remainingRetries = null) {
534
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
535
+ }
536
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
537
+ const options = await optionsInput;
538
+ const maxRetries = options.maxRetries ?? this.maxRetries;
539
+ if (retriesRemaining == null) {
540
+ retriesRemaining = maxRetries;
541
+ // Top-level call: reset per-request auth flags so a reused options object
542
+ // (via client.request(opts)) doesn't carry stale 401-refresh state.
543
+ this._requestAuthFlags.delete(options);
544
+ }
545
+ await this.prepareOptions(options);
546
+ const { req, url, timeout } = await this.buildRequest(options, {
547
+ retryCount: maxRetries - retriesRemaining,
548
+ });
549
+ /** Not an API request ID, just for correlating local log entries. */
550
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
551
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
552
+ const startTime = Date.now();
553
+ if (options.signal?.aborted) {
554
+ throw new Errors.APIUserAbortError();
555
+ }
556
+ const controller = new AbortController();
557
+ const response = await this.fetchWithTimeout(url, req, timeout, controller, options, {
558
+ requestLogID,
559
+ retryOfRequestLogID,
560
+ }).catch(castToError);
561
+ const headersTime = Date.now();
562
+ if (response instanceof globalThis.Error) {
563
+ releaseRequestSignal(controller);
564
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
565
+ if (options.signal?.aborted) {
566
+ throw new Errors.APIUserAbortError();
567
+ }
568
+ // detect native connection timeout errors
569
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
570
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
571
+ // others do not provide enough information to distinguish timeouts from other connection errors
572
+ const isTimeout = isAbortError(response) ||
573
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
574
+ // Errors thrown by middleware (user middleware and the backend adaptation
575
+ // alike) propagate to the caller as-is — no retries, no APIConnectionError
576
+ // wrapping — except retryable errors (timeouts/aborts, APIConnectionErrors,
577
+ // and RetryableErrors, directly or in the `cause` chain), which stay on the
578
+ // retry path.
579
+ const hasMiddleware = this.middleware.length > 0 || !!options.middleware?.length || this.backendMiddleware().length > 0;
580
+ if (hasMiddleware && !isTimeout && !isRetryableError(response)) {
581
+ loggerFor(this).info(`[${requestLogID}] middleware error (not retryable)`);
582
+ loggerFor(this).debug(`[${requestLogID}] middleware error (not retryable)`, formatRequestDetails({
583
+ retryOfRequestLogID,
584
+ url,
585
+ durationMs: headersTime - startTime,
586
+ message: response.message,
587
+ }));
588
+ throw response;
589
+ }
590
+ if (retriesRemaining) {
591
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
592
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
593
+ retryOfRequestLogID,
594
+ url,
595
+ durationMs: headersTime - startTime,
596
+ message: response.message,
597
+ }));
598
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
599
+ }
600
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
601
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
602
+ retryOfRequestLogID,
603
+ url,
604
+ durationMs: headersTime - startTime,
605
+ message: response.message,
606
+ }));
607
+ if (isTimeout) {
608
+ throw new Errors.APIConnectionTimeoutError();
609
+ }
610
+ // a retryable middleware-origin error is still the caller's error: once retries are
611
+ // exhausted it propagates as-is rather than wrapped in APIConnectionError
612
+ if (hasMiddleware && !isFetchOriginError(response)) {
613
+ throw response;
614
+ }
615
+ throw new Errors.APIConnectionError({ cause: response });
616
+ }
617
+ const specialHeaders = [...response.headers.entries()]
618
+ .filter(([name]) => name === 'request-id' || name === 'puku-workspace-id')
619
+ .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
620
+ .join('');
621
+ const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
622
+ if (!response.ok) {
623
+ const shouldRetry = await this.shouldRetry(response, options);
624
+ if (retriesRemaining && shouldRetry) {
625
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
626
+ // We don't need the body of this response.
627
+ await Shims.CancelReadableStream(response.body);
628
+ releaseRequestSignal(controller);
629
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
630
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
631
+ retryOfRequestLogID,
632
+ url: response.url,
633
+ status: response.status,
634
+ headers: response.headers,
635
+ durationMs: headersTime - startTime,
636
+ }));
637
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
638
+ }
639
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
640
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
641
+ const errText = await response.text().catch((err) => castToError(err).message);
642
+ const errJSON = safeJSON(errText);
643
+ const errMessage = errJSON ? undefined : errText;
644
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
645
+ retryOfRequestLogID,
646
+ url: response.url,
647
+ status: response.status,
648
+ headers: response.headers,
649
+ message: errMessage,
650
+ durationMs: Date.now() - startTime,
651
+ }));
652
+ releaseRequestSignal(controller);
653
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
654
+ throw err;
655
+ }
656
+ loggerFor(this).info(responseInfo);
657
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
658
+ retryOfRequestLogID,
659
+ url: response.url,
660
+ status: response.status,
661
+ headers: response.headers,
662
+ durationMs: headersTime - startTime,
663
+ }));
664
+ armAbandonmentBackstop(response.body ?? response, controller);
665
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
666
+ }
667
+ getAPIList(path, Page, opts) {
668
+ return this.requestAPIList(Page, opts && 'then' in opts ?
669
+ opts.then((opts) => ({ method: 'get', path, ...opts }))
670
+ : { method: 'get', path, ...opts });
671
+ }
672
+ requestAPIList(Page, options) {
673
+ const request = this.makeRequest(options, null, undefined);
674
+ return new Pagination.PagePromise(this, request, Page);
675
+ }
676
+ async fetchWithTimeout(url, init, ms, controller, requestOptions, logCtx) {
677
+ const { signal, method, ...options } = init || {};
678
+ // Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks.
679
+ // An arrow function like `() => controller.abort()` captures the surrounding scope,
680
+ // which includes the request body and other large objects. When the user passes a
681
+ // long-lived AbortSignal, the listener prevents those objects from being GC'd for
682
+ // the lifetime of the signal. Using `.bind()` only retains a reference to the
683
+ // controller itself.
684
+ const abort = this._makeAbort(controller);
685
+ if (signal) {
686
+ signal.addEventListener('abort', abort, { once: true });
687
+ registerRequestSignalCleanup(controller, signal, abort);
688
+ }
689
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
690
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
691
+ const fetchOptions = {
692
+ signal: controller.signal,
693
+ ...(isReadableBody ? { duplex: 'half' } : {}),
694
+ method: 'GET',
695
+ ...options,
696
+ };
697
+ if (method) {
698
+ // Custom methods like 'patch' need to be uppercased
699
+ // See https://github.com/nodejs/undici/issues/2294
700
+ fetchOptions.method = method.toUpperCase();
701
+ }
702
+ // Arm the timeout around the underlying fetch only, not the middleware
703
+ // chain — middleware can take arbitrarily long (or call `next` more than
704
+ // once), and each inner-fetch invocation gets its own `ms` timer.
705
+ const baseFetch = this.fetch;
706
+ const timedFetch = async (innerUrl, innerInit) => {
707
+ const timeout = setTimeout(abort, ms);
708
+ try {
709
+ return await baseFetch.call(undefined, innerUrl, innerInit);
710
+ }
711
+ finally {
712
+ clearTimeout(timeout);
713
+ }
714
+ };
715
+ // Prepare the request (auth signing and other `prepareRequest` hooks) as
716
+ // the innermost step, after any middleware — including the backend
717
+ // middleware, so it sees exactly what goes over the wire. Runs per
718
+ // inner-fetch invocation, so a request middleware rewrote — or replayed
719
+ // via a second `next()` call — is prepared fresh each time. Preparation is
720
+ // outside the timeout timer, matching its pre-middleware behavior.
721
+ const innerFetch = requestOptions === undefined ? timedFetch : (async (innerUrl, innerInit = {}) => {
722
+ const innerUrlStr = typeof innerUrl === 'string' ? innerUrl
723
+ : innerUrl instanceof URL ? innerUrl.href
724
+ : innerUrl.url;
725
+ innerInit.headers =
726
+ innerInit.headers instanceof Headers ? innerInit.headers : new Headers(innerInit.headers);
727
+ await this.prepareRequest(innerInit, { url: innerUrlStr, options: requestOptions });
728
+ if (logCtx) {
729
+ loggerFor(this).debug(`[${logCtx.requestLogID}] sending request`, formatRequestDetails({
730
+ retryOfRequestLogID: logCtx.retryOfRequestLogID,
731
+ method: innerInit.method,
732
+ url: innerUrlStr,
733
+ options: requestOptions,
734
+ headers: innerInit.headers,
735
+ }));
736
+ }
737
+ return timedFetch(innerUrl, innerInit);
738
+ });
739
+ const requestMiddleware = requestOptions?.middleware;
740
+ const backendMiddleware = this.backendMiddleware();
741
+ const allMiddleware = requestMiddleware?.length || backendMiddleware.length ?
742
+ [...this.middleware, ...(requestMiddleware ?? []), ...backendMiddleware]
743
+ : this.middleware;
744
+ return await wrapFetchWithMiddleware(innerFetch, allMiddleware, requestOptions, this)(url, fetchOptions);
745
+ }
746
+ async shouldRetry(response, options) {
747
+ // Reactive refresh: on a 401 from a request that used the token cache,
748
+ // invalidate and retry once. Only fires when this specific request was
749
+ // bearer-authenticated (not when an apiKey was used) and only once per
750
+ // request — a second 401 after refresh falls through to the normal
751
+ // retry policy below (which treats 4xx as non-retryable).
752
+ const flags = this._authFlags(options);
753
+ if (response.status === 401 &&
754
+ this._authState.tokenCache &&
755
+ flags.usedTokenCache &&
756
+ !flags.didRefreshFor401) {
757
+ flags.didRefreshFor401 = true;
758
+ this._authState.tokenCache.invalidate();
759
+ return true;
760
+ }
761
+ // Note this is not a standard header.
762
+ const shouldRetryHeader = response.headers.get('x-should-retry');
763
+ // If the server explicitly says whether or not to retry, obey.
764
+ if (shouldRetryHeader === 'true')
765
+ return true;
766
+ if (shouldRetryHeader === 'false')
767
+ return false;
768
+ // Retry on request timeouts.
769
+ if (response.status === 408)
770
+ return true;
771
+ // Retry on lock timeouts.
772
+ if (response.status === 409)
773
+ return true;
774
+ // Retry on rate limits.
775
+ if (response.status === 429)
776
+ return true;
777
+ // Retry internal errors.
778
+ if (response.status >= 500)
779
+ return true;
780
+ return false;
781
+ }
782
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
783
+ let timeoutMillis;
784
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
785
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
786
+ if (retryAfterMillisHeader) {
787
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
788
+ if (!Number.isNaN(timeoutMs)) {
789
+ timeoutMillis = timeoutMs;
790
+ }
791
+ }
792
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
793
+ const retryAfterHeader = responseHeaders?.get('retry-after');
794
+ if (retryAfterHeader && !timeoutMillis) {
795
+ const timeoutSeconds = parseFloat(retryAfterHeader);
796
+ if (!Number.isNaN(timeoutSeconds)) {
797
+ timeoutMillis = timeoutSeconds * 1000;
798
+ }
799
+ else {
800
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
801
+ }
802
+ }
803
+ // If the API asks us to wait a certain amount of time, just do what it
804
+ // says, but otherwise calculate a default
805
+ if (timeoutMillis === undefined) {
806
+ const maxRetries = options.maxRetries ?? this.maxRetries;
807
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
808
+ }
809
+ await sleep(timeoutMillis);
810
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
811
+ }
812
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
813
+ const initialRetryDelay = 0.5;
814
+ const maxRetryDelay = 8.0;
815
+ const numRetries = maxRetries - retriesRemaining;
816
+ // Apply exponential backoff, but not more than the max.
817
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
818
+ // Apply some jitter, take up to at most 25 percent of the retry time.
819
+ const jitter = 1 - Math.random() * 0.25;
820
+ return sleepSeconds * jitter * 1000;
821
+ }
822
+ calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
823
+ const maxTime = 60 * 60 * 1000; // 60 minutes
824
+ const defaultTime = 60 * 10 * 1000; // 10 minutes
825
+ const expectedTime = (maxTime * maxTokens) / 128000;
826
+ if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {
827
+ throw new Errors.PukuError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/puku-ai/sdk#long-requests for more details');
828
+ }
829
+ return defaultTime;
830
+ }
831
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
832
+ const options = { ...inputOptions };
833
+ const { method, path, query, defaultBaseURL } = options;
834
+ // Lazy credential resolution may carry a profile-supplied baseURL. Await
835
+ // it before building the request URL so the very first request — and
836
+ // requests on withOptions() clones created before resolution settled —
837
+ // hit the profile's host rather than the hardcoded default.
838
+ if (this._authState.resolution) {
839
+ await this._authState.resolution;
840
+ }
841
+ if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) {
842
+ this.baseURL = this._authState.baseURL;
843
+ }
844
+ const url = this.buildURL(path, query, defaultBaseURL);
845
+ if ('timeout' in options)
846
+ validatePositiveInteger('timeout', options.timeout);
847
+ options.timeout = options.timeout ?? this.timeout;
848
+ const { bodyHeaders, body } = this.buildBody({ options });
849
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
850
+ const req = {
851
+ method,
852
+ headers: reqHeaders,
853
+ ...(options.signal && { signal: options.signal }),
854
+ ...(globalThis.ReadableStream &&
855
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
856
+ ...(body && { body }),
857
+ ...(this.fetchOptions ?? {}),
858
+ ...(options.fetchOptions ?? {}),
859
+ };
860
+ return { req, url, timeout: options.timeout };
861
+ }
862
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
863
+ let idempotencyHeaders = {};
864
+ if (this.idempotencyHeader && method !== 'get') {
865
+ if (!options.idempotencyKey)
866
+ options.idempotencyKey = this.defaultIdempotencyKey();
867
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
868
+ }
869
+ const headers = buildHeaders([
870
+ idempotencyHeaders,
871
+ {
872
+ Accept: 'application/json',
873
+ 'User-Agent': this.getUserAgent(),
874
+ 'X-Stainless-Retry-Count': String(retryCount),
875
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
876
+ ...getPlatformHeaders(),
877
+ ...(this._options.dangerouslyAllowBrowser ?
878
+ { 'puku-dangerous-direct-browser-access': 'true' }
879
+ : undefined),
880
+ 'puku-version': '2023-06-01',
881
+ },
882
+ await this.authHeaders(options),
883
+ this._options.defaultHeaders,
884
+ bodyHeaders,
885
+ options.headers,
886
+ ]);
887
+ this.validateHeaders(headers);
888
+ return headers.values;
889
+ }
890
+ _makeAbort(controller) {
891
+ // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure
892
+ // would capture all request options, and cause a memory leak.
893
+ return () => controller.abort();
894
+ }
895
+ buildBody({ options: { body, headers: rawHeaders } }) {
896
+ if (!body) {
897
+ return { bodyHeaders: undefined, body: undefined };
898
+ }
899
+ const headers = buildHeaders([rawHeaders]);
900
+ if (
901
+ // Pass raw type verbatim
902
+ ArrayBuffer.isView(body) ||
903
+ body instanceof ArrayBuffer ||
904
+ body instanceof DataView ||
905
+ (typeof body === 'string' &&
906
+ // Preserve legacy string encoding behavior for now
907
+ headers.values.has('content-type')) ||
908
+ // `Blob` is superset of `File`
909
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
910
+ // `FormData` -> `multipart/form-data`
911
+ body instanceof FormData ||
912
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
913
+ body instanceof URLSearchParams ||
914
+ // Send chunked stream (each chunk has own `length`)
915
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
916
+ return { bodyHeaders: undefined, body: body };
917
+ }
918
+ else if (typeof body === 'object' &&
919
+ (Symbol.asyncIterator in body ||
920
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
921
+ return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
922
+ }
923
+ else if (typeof body === 'object' &&
924
+ headers.values.get('content-type') === 'application/x-www-form-urlencoded') {
925
+ return {
926
+ bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },
927
+ body: this.stringifyQuery(body),
928
+ };
929
+ }
930
+ else {
931
+ return this.#encoder({ body, headers });
932
+ }
933
+ }
934
+ static HUMAN_PROMPT = HUMAN_PROMPT;
935
+ static AI_PROMPT = AI_PROMPT;
936
+ static DEFAULT_TIMEOUT = 600000; // 10 minutes
937
+ static PukuError = Errors.PukuError;
938
+ static APIError = Errors.APIError;
939
+ static APIConnectionError = Errors.APIConnectionError;
940
+ static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
941
+ static APIUserAbortError = Errors.APIUserAbortError;
942
+ static NotFoundError = Errors.NotFoundError;
943
+ static ConflictError = Errors.ConflictError;
944
+ static RateLimitError = Errors.RateLimitError;
945
+ static BadRequestError = Errors.BadRequestError;
946
+ static AuthenticationError = Errors.AuthenticationError;
947
+ static InternalServerError = Errors.InternalServerError;
948
+ static PermissionDeniedError = Errors.PermissionDeniedError;
949
+ static UnprocessableEntityError = Errors.UnprocessableEntityError;
950
+ static toFile = Uploads.toFile;
951
+ }
952
+ /**
953
+ * API Client for interfacing with the Puku API.
954
+ */
955
+ export class PukuAI extends BasePuku {
956
+ completions = new API.Completions(this);
957
+ messages = new API.Messages(this);
958
+ models = new API.Models(this);
959
+ files = new API.Files(this);
960
+ skills = new API.Skills(this);
961
+ beta = new API.Beta(this);
962
+ }
963
+ PukuAI.Completions = Completions;
964
+ PukuAI.Messages = Messages;
965
+ PukuAI.Models = Models;
966
+ PukuAI.Files = Files;
967
+ PukuAI.Skills = Skills;
968
+ PukuAI.Beta = Beta;
969
+ // ── Puku branding ──────────────────────────────────────────────────────────
970
+ // `@puku-ai/sdk` is published under the Puku brand on npm. The client class
971
+ // `PukuAI` (above) and its base class `BasePuku` (above) ARE the public API;
972
+ // no separate aliases are exposed. Earlier versions of this SDK exposed
973
+ // `PukuAI` / `BasePuku` / `PukuError` as compatibility aliases
974
+ // — those have been removed; consumers should use `PukuAI` / `BasePuku` /
975
+ // `PukuError` directly.
976
+ //# sourceMappingURL=client.js.map