@puku-ai/sdk 4.0.2 → 4.0.4

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