zen-code 3.0.5 → 4.0.0

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.
@@ -1,3862 +0,0 @@
1
- import Es from "micromatch";
2
- import { z as l } from "zod";
3
- import "lowdb";
4
- import "lowdb/node";
5
- import "yaml";
6
- var F = /* @__PURE__ */ ((n) => (n.ALLOW = "allow", n.ASK = "ask", n.DENY = "deny", n))(F || {});
7
- l.object({
8
- tool: l.string(),
9
- specifier: l.string().optional(),
10
- action: l.nativeEnum(F)
11
- });
12
- l.object({
13
- allow: l.array(l.string()).optional(),
14
- ask: l.array(l.string()).optional(),
15
- deny: l.array(l.string()).optional(),
16
- defaultMode: l.nativeEnum(F).optional()
17
- });
18
- l.object({
19
- name: l.string(),
20
- args: l.record(l.string(), l.any())
21
- });
22
- class G {
23
- rules;
24
- defaultMode;
25
- patternCache = /* @__PURE__ */ new Map();
26
- constructor(e) {
27
- this.rules = e.rules, this.defaultMode = e.defaultMode || F.ASK, this.rules.sort((t, s) => {
28
- const r = { deny: 0, ask: 1, allow: 2 }, i = r[t.action] - r[s.action];
29
- if (i !== 0)
30
- return i;
31
- const o = t.specifier == null ? 1 : 0, c = s.specifier == null ? 1 : 0;
32
- return o - c;
33
- });
34
- }
35
- /**
36
- * Check if a tool call is permitted
37
- */
38
- checkPermission(e) {
39
- for (const t of this.rules)
40
- if (this.matchRule(t, e))
41
- return {
42
- allowed: t.action === "allow" || t.action === "ask",
43
- requiresApproval: t.action === "ask",
44
- matchedRule: t,
45
- reason: this.getReason(t)
46
- };
47
- return {
48
- allowed: this.defaultMode === "allow" || this.defaultMode === "ask",
49
- requiresApproval: this.defaultMode === "ask",
50
- reason: `No matching rule, using default mode: ${this.defaultMode}`
51
- };
52
- }
53
- /**
54
- * Check if a rule matches a tool call
55
- */
56
- matchRule(e, t) {
57
- if (e.tool !== t.name)
58
- return !1;
59
- if (!e.specifier)
60
- return !0;
61
- const s = this.argsToString(t.args);
62
- return t.name === "Bash" ? this.matchBashCommand(e.specifier, s) : e.specifier.endsWith(" ") && !/[*?[\\]/.test(e.specifier) ? s.startsWith(e.specifier) : this.matchGlob(e.specifier, s);
63
- }
64
- /**
65
- * Match Bash commands with shell operator awareness
66
- */
67
- matchBashCommand(e, t) {
68
- if (/[;&|]/.test(t))
69
- return !1;
70
- const r = /[<>()]/;
71
- if (r.test(t)) {
72
- const i = t.split(r)[0].trim();
73
- return this.matchBashPattern(e, i);
74
- }
75
- return this.matchBashPattern(e, t);
76
- }
77
- /**
78
- * Match Bash command patterns with support for prefix and glob matching
79
- */
80
- matchBashPattern(e, t) {
81
- return e.endsWith(" ") ? t.startsWith(e) : this.matchGlob(e, t);
82
- }
83
- /**
84
- * Glob pattern matching using micromatch with caching
85
- */
86
- matchGlob(e, t) {
87
- try {
88
- const s = e.replace(/^\.\//, ""), r = t.replace(/^\.\//, ""), i = `${e}::${t}`, o = this.patternCache.get(i);
89
- if (o !== void 0)
90
- return o;
91
- const c = Es.isMatch(r, s, {
92
- nocase: !1,
93
- dot: !0
94
- });
95
- return this.cacheResult(i, c), c;
96
- } catch {
97
- return t === e;
98
- }
99
- }
100
- /**
101
- * Cache matching result with LRU-style size limit
102
- */
103
- cacheResult(e, t) {
104
- if (this.patternCache.size > 1e3) {
105
- const s = this.patternCache.keys().next().value;
106
- s && this.patternCache.delete(s);
107
- }
108
- this.patternCache.set(e, t);
109
- }
110
- /**
111
- * Convert tool arguments to string representation
112
- */
113
- argsToString(e) {
114
- return typeof e == "object" && e !== null ? "command" in e && e.command ? String(e.command) : "file_path" in e && e.file_path ? String(e.file_path) : Object.values(e).flat().join(" ") : String(e);
115
- }
116
- /**
117
- * Get human-readable reason for permission decision
118
- */
119
- getReason(e) {
120
- const t = e.action.toUpperCase(), s = e.tool, r = e.specifier ? `(${e.specifier})` : "";
121
- return `${t} rule matched: ${s}${r}`;
122
- }
123
- /**
124
- * Parse permission rule from string format
125
- * Examples:
126
- * - "Bash" -> { tool: "Bash", action: "allow" }
127
- * - "Bash(git commit )" -> { tool: "Bash", specifier: "git commit ", action: "allow" }
128
- */
129
- static parseRule(e, t) {
130
- const s = e.match(/^(\w+)(?:\((.*)\))?$/);
131
- if (!s)
132
- throw new Error(`Invalid permission rule format: ${e}`);
133
- const [, r, i] = s;
134
- return {
135
- tool: r,
136
- specifier: i,
137
- // MODIFIED: Don't trim - preserve trailing spaces which are significant for glob patterns
138
- action: t
139
- };
140
- }
141
- /**
142
- * Create matcher from configuration object
143
- */
144
- static fromConfig(e) {
145
- const t = [];
146
- for (const s of e.allow || [])
147
- t.push(G.parseRule(s, F.ALLOW));
148
- for (const s of e.ask || [])
149
- t.push(G.parseRule(s, F.ASK));
150
- for (const s of e.deny || [])
151
- t.push(G.parseRule(s, F.DENY));
152
- return new G({
153
- rules: t,
154
- defaultMode: e.defaultMode || F.ASK
155
- });
156
- }
157
- /**
158
- * Clear cache (useful for testing or config reload)
159
- */
160
- clearCache() {
161
- this.patternCache.clear();
162
- }
163
- /**
164
- * Get current cache size
165
- */
166
- getCacheSize() {
167
- return this.patternCache.size;
168
- }
169
- }
170
- class J {
171
- configStore;
172
- /** 工具名称映射 */
173
- toolNameMapper = {};
174
- constructor(e) {
175
- this.configStore = e;
176
- }
177
- // ========== 单例模式 ==========
178
- static instance = null;
179
- /**
180
- * 获取单例实例
181
- * @param configStore 配置存储实例(仅首次调用需要)
182
- */
183
- static getInstance(e) {
184
- if (!J.instance) {
185
- if (!e)
186
- throw new Error("PermissionStore not initialized. Provide configStore on first call.");
187
- J.instance = new J(e);
188
- }
189
- return J.instance;
190
- }
191
- /**
192
- * 重置单例(测试用)
193
- */
194
- static resetInstance() {
195
- J.instance = null;
196
- }
197
- // ========== 业务方法 ==========
198
- /**
199
- * 获取权限匹配器实例
200
- */
201
- async getPermissions() {
202
- const e = await this.configStore.getConfig();
203
- if (e.permissions)
204
- return G.fromConfig(e.permissions);
205
- }
206
- /**
207
- * 检查 Bash 命令权限
208
- */
209
- async checkBashPermission(e, t) {
210
- return (await this.getPermissions())?.checkPermission({
211
- name: "Bash",
212
- args: { command: e, cwd: t }
213
- });
214
- }
215
- /**
216
- * 检查读取文件权限
217
- */
218
- async checkReadPermission(e) {
219
- return (await this.getPermissions())?.checkPermission({
220
- name: "Read",
221
- args: { file_path: e }
222
- });
223
- }
224
- /**
225
- * 检查写入文件权限
226
- */
227
- async checkWritePermission(e) {
228
- return (await this.getPermissions())?.checkPermission({
229
- name: "Write",
230
- args: { file_path: e }
231
- });
232
- }
233
- }
234
- class vs {
235
- configStore;
236
- skillStore;
237
- pluginStore;
238
- remoteStore;
239
- permissionStore;
240
- _initialized = !1;
241
- constructor(e, t, s, r) {
242
- this.configStore = e, this.skillStore = t, this.pluginStore = s, this.remoteStore = r, this.permissionStore = J.getInstance(e);
243
- }
244
- /**
245
- * 初始化管理器(延迟初始化)
246
- * 必须在使用其他方法前调用
247
- */
248
- async initialize() {
249
- this._initialized || ("initialize" in this.configStore && typeof this.configStore.initialize == "function" && await this.configStore.initialize(), "initialize" in this.skillStore && typeof this.skillStore.initialize == "function" && await this.skillStore.initialize(), "initialize" in this.pluginStore && typeof this.pluginStore.initialize == "function" && await this.pluginStore.initialize(), this._initialized = !0);
250
- }
251
- /**
252
- * 确保已初始化(内部使用)
253
- */
254
- async ensureInitialized() {
255
- if (!this._initialized)
256
- throw new Error("ConfigManager not initialized. Call await manager.initialize() first.");
257
- }
258
- // 配置相关
259
- async getConfig() {
260
- return await this.ensureInitialized(), await this.configStore.getConfig();
261
- }
262
- async updateConfig(e) {
263
- return await this.ensureInitialized(), await this.configStore.updateConfig(e);
264
- }
265
- // Skills 相关
266
- async listSkills() {
267
- return await this.ensureInitialized(), await this.skillStore.listSkills();
268
- }
269
- async getSkill(e) {
270
- return await this.ensureInitialized(), await this.skillStore.getSkill(e);
271
- }
272
- async saveSkill(e, t) {
273
- return await this.ensureInitialized(), await this.skillStore.saveSkill(e, t);
274
- }
275
- async deleteSkill(e) {
276
- return await this.ensureInitialized(), await this.skillStore.deleteSkill(e);
277
- }
278
- async syncSkillsFromRemote() {
279
- if (await this.ensureInitialized(), !this.remoteStore)
280
- throw new Error("Remote store not configured");
281
- return await this.skillStore.syncFromRemote(this.remoteStore);
282
- }
283
- // Plugins 相关
284
- async listPlugins() {
285
- return await this.ensureInitialized(), await this.pluginStore.listPlugins();
286
- }
287
- async getPluginConfig(e) {
288
- return await this.ensureInitialized(), await this.pluginStore.getPluginConfig(e);
289
- }
290
- async updatePluginConfig(e, t) {
291
- return await this.ensureInitialized(), await this.pluginStore.updatePluginConfig(e, t);
292
- }
293
- async installPlugin(e, t) {
294
- return await this.ensureInitialized(), await this.pluginStore.installPlugin(e, t);
295
- }
296
- async uninstallPlugin(e) {
297
- return await this.ensureInitialized(), await this.pluginStore.uninstallPlugin(e);
298
- }
299
- // Permissions 相关
300
- /**
301
- * 检查 Bash 命令权限
302
- */
303
- async checkBashPermission(e, t) {
304
- return await this.ensureInitialized(), await this.permissionStore.checkBashPermission(e, t);
305
- }
306
- /**
307
- * 检查读取文件权限
308
- */
309
- async checkReadPermission(e) {
310
- return await this.ensureInitialized(), await this.permissionStore.checkReadPermission(e);
311
- }
312
- /**
313
- * 检查写入文件权限
314
- */
315
- async checkWritePermission(e) {
316
- return await this.ensureInitialized(), await this.permissionStore.checkWritePermission(e);
317
- }
318
- /**
319
- * 获取权限匹配器(用于高级操作)
320
- */
321
- async getPermissionMatcher() {
322
- return await this.ensureInitialized(), await this.permissionStore.getPermissions();
323
- }
324
- /** fs 专用 */
325
- getConfigPath() {
326
- return this.configStore?.dbPath;
327
- }
328
- }
329
- async function As() {
330
- const { FileSystemConfigStore: n } = await import("./FileSystemConfigStore-Bog5vylu.mjs"), { FileSystemSkillStore: e } = await import("./FileSystemSkillStore-yvEvcRxB.mjs"), { FileSystemPluginStore: t } = await import("./FileSystemPluginStore-ChortK7z.mjs"), s = new n(), r = new e(), i = new t(), o = new vs(s, r, i);
331
- return await o.initialize(), o;
332
- }
333
- const Is = l.enum(["idea", "bug_report", "feature", "refactor"]), $s = l.enum(["low", "medium", "high", "critical"]), Os = l.enum(["pending", "planned", "archived"]), Bs = l.enum(["user_input", "ai_suggestion", "conversation_derived"]), Cs = l.object({
334
- id: l.string().uuid(),
335
- type: Is,
336
- title: l.string().min(1).max(200),
337
- description: l.string(),
338
- priority: $s.default("medium"),
339
- source: Bs,
340
- status: Os.default("pending"),
341
- createdAt: l.string().datetime(),
342
- tags: l.array(l.string()).default([]),
343
- metadata: l.object({
344
- relatedFiles: l.array(l.string()).optional(),
345
- conversationContext: l.string().optional(),
346
- estimatedComplexity: l.enum(["simple", "medium", "complex"]).optional()
347
- }).optional()
348
- });
349
- l.object({
350
- version: l.literal("1.0"),
351
- sparks: l.array(Cs),
352
- lastUpdated: l.string().datetime()
353
- });
354
- const Jt = l.enum([
355
- "pickup",
356
- // 待领取(新任务,未被 agent 接管)
357
- "running",
358
- // 运行中(agent 正在执行)
359
- "complete",
360
- // 已完成(成功完成)
361
- "error",
362
- // 已失败(失败,暂停中)
363
- "review",
364
- // 待审核(完成,等待人工确认)
365
- "feedback"
366
- // 待反馈(agent 卡住,需要人工输入)
367
- ]), it = l.enum([
368
- "default",
369
- "planner",
370
- "reviewer",
371
- "refactor",
372
- "finder",
373
- "debugger"
374
- ]), js = l.enum(["serial", "parallel"]), Xt = l.lazy(
375
- () => l.object({
376
- // 基本信息
377
- id: l.string(),
378
- title: l.string().min(1).max(200),
379
- description: l.string(),
380
- // 执行控制
381
- execution: js.optional(),
382
- children: l.array(l.lazy(() => Xt)).optional(),
383
- // Agent 分配
384
- agentType: it.optional(),
385
- threadId: l.string().optional(),
386
- // 元数据
387
- estimatedTime: l.string().optional(),
388
- complexity: l.enum(["simple", "medium", "complex"]).optional(),
389
- dependencies: l.array(l.string()).optional(),
390
- acceptanceCriteria: l.array(l.string()).optional(),
391
- // 状态相关(运行时)
392
- status: Jt.optional(),
393
- startedAt: l.string().datetime().optional(),
394
- completedAt: l.string().datetime().optional(),
395
- assignedTo: it.optional(),
396
- error: l.object({
397
- message: l.string(),
398
- stack: l.string().optional(),
399
- retryCount: l.number().optional()
400
- }).optional()
401
- })
402
- ), Ns = l.object({
403
- taskId: l.string(),
404
- planId: l.string(),
405
- threadId: l.string(),
406
- // 关联的 LangGraph thread ID
407
- agentType: it,
408
- // 改为类型安全的 AgentType
409
- status: Jt,
410
- startedAt: l.string().datetime(),
411
- completedAt: l.string().datetime().optional(),
412
- output: l.string().optional(),
413
- error: l.string().optional(),
414
- changedFiles: l.array(l.string()).optional()
415
- });
416
- l.object({
417
- version: l.literal("1.0"),
418
- lastUpdated: l.string().datetime(),
419
- // 活跃的任务树
420
- activePlanId: l.string().optional(),
421
- tasks: l.record(l.string(), Xt),
422
- // 执行历史
423
- history: l.array(Ns),
424
- // 全局配置
425
- config: l.object({
426
- maxConcurrentAgents: l.number().min(1).max(10).default(3),
427
- retryLimit: l.number().min(0).max(10).default(3),
428
- autoResume: l.boolean().default(!1)
429
- })
430
- });
431
- const Ue = await As(), Ls = async () => {
432
- await Ue.initialize();
433
- }, qs = async () => await Ue.getConfig(), Ws = async (n) => {
434
- await Ue.updateConfig(n);
435
- }, Cn = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
436
- __proto__: null,
437
- configStore: Ue,
438
- getConfig: qs,
439
- initDb: Ls,
440
- updateConfig: Ws
441
- }, Symbol.toStringTag, { value: "Module" }));
442
- function u(n, e, t, s, r) {
443
- if (typeof e == "function" ? n !== e || !0 : !e.has(n))
444
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
445
- return e.set(n, t), t;
446
- }
447
- function a(n, e, t, s) {
448
- if (t === "a" && !s)
449
- throw new TypeError("Private accessor was defined without a getter");
450
- if (typeof e == "function" ? n !== e || !s : !e.has(n))
451
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
452
- return t === "m" ? s : t === "a" ? s.call(n) : s ? s.value : e.get(n);
453
- }
454
- let Kt = function() {
455
- const { crypto: n } = globalThis;
456
- if (n?.randomUUID)
457
- return Kt = n.randomUUID.bind(n), n.randomUUID();
458
- const e = new Uint8Array(1), t = n ? () => n.getRandomValues(e)[0] : () => Math.random() * 255 & 255;
459
- return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (s) => (+s ^ t() & 15 >> +s / 4).toString(16));
460
- };
461
- function ye(n) {
462
- return typeof n == "object" && n !== null && // Spec-compliant fetch implementations
463
- ("name" in n && n.name === "AbortError" || // Expo fetch
464
- "message" in n && String(n.message).includes("FetchRequestCanceledException"));
465
- }
466
- const at = (n) => {
467
- if (n instanceof Error)
468
- return n;
469
- if (typeof n == "object" && n !== null) {
470
- try {
471
- if (Object.prototype.toString.call(n) === "[object Error]") {
472
- const e = new Error(n.message, n.cause ? { cause: n.cause } : {});
473
- return n.stack && (e.stack = n.stack), n.cause && !e.cause && (e.cause = n.cause), n.name && (e.name = n.name), e;
474
- }
475
- } catch {
476
- }
477
- try {
478
- return new Error(JSON.stringify(n));
479
- } catch {
480
- }
481
- }
482
- return new Error(n);
483
- };
484
- class d extends Error {
485
- }
486
- class S extends d {
487
- constructor(e, t, s, r) {
488
- super(`${S.makeMessage(e, t, s)}`), this.status = e, this.headers = r, this.requestID = r?.get("request-id"), this.error = t;
489
- }
490
- static makeMessage(e, t, s) {
491
- const r = t?.message ? typeof t.message == "string" ? t.message : JSON.stringify(t.message) : t ? JSON.stringify(t) : s;
492
- return e && r ? `${e} ${r}` : e ? `${e} status code (no body)` : r || "(no status code or body)";
493
- }
494
- static generate(e, t, s, r) {
495
- if (!e || !r)
496
- return new De({ message: s, cause: at(t) });
497
- const i = t;
498
- return e === 400 ? new Qt(e, i, s, r) : e === 401 ? new Gt(e, i, s, r) : e === 403 ? new Yt(e, i, s, r) : e === 404 ? new Zt(e, i, s, r) : e === 409 ? new es(e, i, s, r) : e === 422 ? new ts(e, i, s, r) : e === 429 ? new ss(e, i, s, r) : e >= 500 ? new ns(e, i, s, r) : new S(e, i, s, r);
499
- }
500
- }
501
- class A extends S {
502
- constructor({ message: e } = {}) {
503
- super(void 0, void 0, e || "Request was aborted.", void 0);
504
- }
505
- }
506
- class De extends S {
507
- constructor({ message: e, cause: t }) {
508
- super(void 0, void 0, e || "Connection error.", void 0), t && (this.cause = t);
509
- }
510
- }
511
- class Vt extends De {
512
- constructor({ message: e } = {}) {
513
- super({ message: e ?? "Request timed out." });
514
- }
515
- }
516
- class Qt extends S {
517
- }
518
- class Gt extends S {
519
- }
520
- class Yt extends S {
521
- }
522
- class Zt extends S {
523
- }
524
- class es extends S {
525
- }
526
- class ts extends S {
527
- }
528
- class ss extends S {
529
- }
530
- class ns extends S {
531
- }
532
- const Fs = /^[a-z][a-z0-9+.-]*:/i, Us = (n) => Fs.test(n);
533
- let ot = (n) => (ot = Array.isArray, ot(n)), kt = ot;
534
- function ct(n) {
535
- return typeof n != "object" ? {} : n ?? {};
536
- }
537
- function Ds(n) {
538
- if (!n)
539
- return !0;
540
- for (const e in n)
541
- return !1;
542
- return !0;
543
- }
544
- function zs(n, e) {
545
- return Object.prototype.hasOwnProperty.call(n, e);
546
- }
547
- const Hs = (n, e) => {
548
- if (typeof e != "number" || !Number.isInteger(e))
549
- throw new d(`${n} must be an integer`);
550
- if (e < 0)
551
- throw new d(`${n} must be a positive integer`);
552
- return e;
553
- }, rs = (n) => {
554
- try {
555
- return JSON.parse(n);
556
- } catch {
557
- return;
558
- }
559
- }, jn = (n, e) => {
560
- const t = n[e];
561
- return delete n[e], t;
562
- }, Js = (n) => new Promise((e) => setTimeout(e, n)), V = "0.71.2", Xs = () => (
563
- // @ts-ignore
564
- typeof window < "u" && // @ts-ignore
565
- typeof window.document < "u" && // @ts-ignore
566
- typeof navigator < "u"
567
- );
568
- function Ks() {
569
- return typeof Deno < "u" && Deno.build != null ? "deno" : typeof EdgeRuntime < "u" ? "edge" : Object.prototype.toString.call(typeof globalThis.process < "u" ? globalThis.process : 0) === "[object process]" ? "node" : "unknown";
570
- }
571
- const Vs = () => {
572
- const n = Ks();
573
- if (n === "deno")
574
- return {
575
- "X-Stainless-Lang": "js",
576
- "X-Stainless-Package-Version": V,
577
- "X-Stainless-OS": Mt(Deno.build.os),
578
- "X-Stainless-Arch": xt(Deno.build.arch),
579
- "X-Stainless-Runtime": "deno",
580
- "X-Stainless-Runtime-Version": typeof Deno.version == "string" ? Deno.version : Deno.version?.deno ?? "unknown"
581
- };
582
- if (typeof EdgeRuntime < "u")
583
- return {
584
- "X-Stainless-Lang": "js",
585
- "X-Stainless-Package-Version": V,
586
- "X-Stainless-OS": "Unknown",
587
- "X-Stainless-Arch": `other:${EdgeRuntime}`,
588
- "X-Stainless-Runtime": "edge",
589
- "X-Stainless-Runtime-Version": globalThis.process.version
590
- };
591
- if (n === "node")
592
- return {
593
- "X-Stainless-Lang": "js",
594
- "X-Stainless-Package-Version": V,
595
- "X-Stainless-OS": Mt(globalThis.process.platform ?? "unknown"),
596
- "X-Stainless-Arch": xt(globalThis.process.arch ?? "unknown"),
597
- "X-Stainless-Runtime": "node",
598
- "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
599
- };
600
- const e = Qs();
601
- return e ? {
602
- "X-Stainless-Lang": "js",
603
- "X-Stainless-Package-Version": V,
604
- "X-Stainless-OS": "Unknown",
605
- "X-Stainless-Arch": "unknown",
606
- "X-Stainless-Runtime": `browser:${e.browser}`,
607
- "X-Stainless-Runtime-Version": e.version
608
- } : {
609
- "X-Stainless-Lang": "js",
610
- "X-Stainless-Package-Version": V,
611
- "X-Stainless-OS": "Unknown",
612
- "X-Stainless-Arch": "unknown",
613
- "X-Stainless-Runtime": "unknown",
614
- "X-Stainless-Runtime-Version": "unknown"
615
- };
616
- };
617
- function Qs() {
618
- if (typeof navigator > "u" || !navigator)
619
- return null;
620
- const n = [
621
- { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
622
- { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
623
- { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
624
- { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
625
- { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
626
- { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
627
- ];
628
- for (const { key: e, pattern: t } of n) {
629
- const s = t.exec(navigator.userAgent);
630
- if (s) {
631
- const r = s[1] || 0, i = s[2] || 0, o = s[3] || 0;
632
- return { browser: e, version: `${r}.${i}.${o}` };
633
- }
634
- }
635
- return null;
636
- }
637
- const xt = (n) => n === "x32" ? "x32" : n === "x86_64" || n === "x64" ? "x64" : n === "arm" ? "arm" : n === "aarch64" || n === "arm64" ? "arm64" : n ? `other:${n}` : "unknown", Mt = (n) => (n = n.toLowerCase(), n.includes("ios") ? "iOS" : n === "android" ? "Android" : n === "darwin" ? "MacOS" : n === "win32" ? "Windows" : n === "freebsd" ? "FreeBSD" : n === "openbsd" ? "OpenBSD" : n === "linux" ? "Linux" : n ? `Other:${n}` : "Unknown");
638
- let Rt;
639
- const Gs = () => Rt ?? (Rt = Vs());
640
- function Ys() {
641
- if (typeof fetch < "u")
642
- return fetch;
643
- throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
644
- }
645
- function is(...n) {
646
- const e = globalThis.ReadableStream;
647
- if (typeof e > "u")
648
- throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
649
- return new e(...n);
650
- }
651
- function as(n) {
652
- let e = Symbol.asyncIterator in n ? n[Symbol.asyncIterator]() : n[Symbol.iterator]();
653
- return is({
654
- start() {
655
- },
656
- async pull(t) {
657
- const { done: s, value: r } = await e.next();
658
- s ? t.close() : t.enqueue(r);
659
- },
660
- async cancel() {
661
- await e.return?.();
662
- }
663
- });
664
- }
665
- function ft(n) {
666
- if (n[Symbol.asyncIterator])
667
- return n;
668
- const e = n.getReader();
669
- return {
670
- async next() {
671
- try {
672
- const t = await e.read();
673
- return t?.done && e.releaseLock(), t;
674
- } catch (t) {
675
- throw e.releaseLock(), t;
676
- }
677
- },
678
- async return() {
679
- const t = e.cancel();
680
- return e.releaseLock(), await t, { done: !0, value: void 0 };
681
- },
682
- [Symbol.asyncIterator]() {
683
- return this;
684
- }
685
- };
686
- }
687
- async function Zs(n) {
688
- if (n === null || typeof n != "object")
689
- return;
690
- if (n[Symbol.asyncIterator]) {
691
- await n[Symbol.asyncIterator]().return?.();
692
- return;
693
- }
694
- const e = n.getReader(), t = e.cancel();
695
- e.releaseLock(), await t;
696
- }
697
- const en = ({ headers: n, body: e }) => ({
698
- bodyHeaders: {
699
- "content-type": "application/json"
700
- },
701
- body: JSON.stringify(e)
702
- });
703
- function tn(n) {
704
- let e = 0;
705
- for (const r of n)
706
- e += r.length;
707
- const t = new Uint8Array(e);
708
- let s = 0;
709
- for (const r of n)
710
- t.set(r, s), s += r.length;
711
- return t;
712
- }
713
- let Pt;
714
- function pt(n) {
715
- let e;
716
- return (Pt ?? (e = new globalThis.TextEncoder(), Pt = e.encode.bind(e)))(n);
717
- }
718
- let Tt;
719
- function Et(n) {
720
- let e;
721
- return (Tt ?? (e = new globalThis.TextDecoder(), Tt = e.decode.bind(e)))(n);
722
- }
723
- var M, R;
724
- class we {
725
- constructor() {
726
- M.set(this, void 0), R.set(this, void 0), u(this, M, new Uint8Array()), u(this, R, null);
727
- }
728
- decode(e) {
729
- if (e == null)
730
- return [];
731
- const t = e instanceof ArrayBuffer ? new Uint8Array(e) : typeof e == "string" ? pt(e) : e;
732
- u(this, M, tn([a(this, M, "f"), t]));
733
- const s = [];
734
- let r;
735
- for (; (r = sn(a(this, M, "f"), a(this, R, "f"))) != null; ) {
736
- if (r.carriage && a(this, R, "f") == null) {
737
- u(this, R, r.index);
738
- continue;
739
- }
740
- if (a(this, R, "f") != null && (r.index !== a(this, R, "f") + 1 || r.carriage)) {
741
- s.push(Et(a(this, M, "f").subarray(0, a(this, R, "f") - 1))), u(this, M, a(this, M, "f").subarray(a(this, R, "f"))), u(this, R, null);
742
- continue;
743
- }
744
- const i = a(this, R, "f") !== null ? r.preceding - 1 : r.preceding, o = Et(a(this, M, "f").subarray(0, i));
745
- s.push(o), u(this, M, a(this, M, "f").subarray(r.index)), u(this, R, null);
746
- }
747
- return s;
748
- }
749
- flush() {
750
- return a(this, M, "f").length ? this.decode(`
751
- `) : [];
752
- }
753
- }
754
- M = /* @__PURE__ */ new WeakMap(), R = /* @__PURE__ */ new WeakMap();
755
- we.NEWLINE_CHARS = /* @__PURE__ */ new Set([`
756
- `, "\r"]);
757
- we.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
758
- function sn(n, e) {
759
- for (let r = e ?? 0; r < n.length; r++) {
760
- if (n[r] === 10)
761
- return { preceding: r, index: r + 1, carriage: !1 };
762
- if (n[r] === 13)
763
- return { preceding: r, index: r + 1, carriage: !0 };
764
- }
765
- return null;
766
- }
767
- function nn(n) {
768
- for (let s = 0; s < n.length - 1; s++) {
769
- if (n[s] === 10 && n[s + 1] === 10 || n[s] === 13 && n[s + 1] === 13)
770
- return s + 2;
771
- if (n[s] === 13 && n[s + 1] === 10 && s + 3 < n.length && n[s + 2] === 13 && n[s + 3] === 10)
772
- return s + 4;
773
- }
774
- return -1;
775
- }
776
- const qe = {
777
- off: 0,
778
- error: 200,
779
- warn: 300,
780
- info: 400,
781
- debug: 500
782
- }, vt = (n, e, t) => {
783
- if (n) {
784
- if (zs(qe, n))
785
- return n;
786
- k(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(qe))}`);
787
- }
788
- };
789
- function me() {
790
- }
791
- function Se(n, e, t) {
792
- return !e || qe[n] > qe[t] ? me : e[n].bind(e);
793
- }
794
- const rn = {
795
- error: me,
796
- warn: me,
797
- info: me,
798
- debug: me
799
- };
800
- let At = /* @__PURE__ */ new WeakMap();
801
- function k(n) {
802
- const e = n.logger, t = n.logLevel ?? "off";
803
- if (!e)
804
- return rn;
805
- const s = At.get(e);
806
- if (s && s[0] === t)
807
- return s[1];
808
- const r = {
809
- error: Se("error", e, t),
810
- warn: Se("warn", e, t),
811
- info: Se("info", e, t),
812
- debug: Se("debug", e, t)
813
- };
814
- return At.set(e, [t, r]), r;
815
- }
816
- const H = (n) => (n.options && (n.options = { ...n.options }, delete n.options.headers), n.headers && (n.headers = Object.fromEntries((n.headers instanceof Headers ? [...n.headers] : Object.entries(n.headers)).map(([e, t]) => [
817
- e,
818
- e.toLowerCase() === "x-api-key" || e.toLowerCase() === "authorization" || e.toLowerCase() === "cookie" || e.toLowerCase() === "set-cookie" ? "***" : t
819
- ]))), "retryOfRequestLogID" in n && (n.retryOfRequestLogID && (n.retryOf = n.retryOfRequestLogID), delete n.retryOfRequestLogID), n);
820
- var ee;
821
- class O {
822
- constructor(e, t, s) {
823
- this.iterator = e, ee.set(this, void 0), this.controller = t, u(this, ee, s);
824
- }
825
- static fromSSEResponse(e, t, s) {
826
- let r = !1;
827
- const i = s ? k(s) : console;
828
- async function* o() {
829
- if (r)
830
- throw new d("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
831
- r = !0;
832
- let c = !1;
833
- try {
834
- for await (const h of an(e, t)) {
835
- if (h.event === "completion")
836
- try {
837
- yield JSON.parse(h.data);
838
- } catch (f) {
839
- throw i.error("Could not parse message into JSON:", h.data), i.error("From chunk:", h.raw), f;
840
- }
841
- if (h.event === "message_start" || h.event === "message_delta" || h.event === "message_stop" || h.event === "content_block_start" || h.event === "content_block_delta" || h.event === "content_block_stop")
842
- try {
843
- yield JSON.parse(h.data);
844
- } catch (f) {
845
- throw i.error("Could not parse message into JSON:", h.data), i.error("From chunk:", h.raw), f;
846
- }
847
- if (h.event !== "ping" && h.event === "error")
848
- throw new S(void 0, rs(h.data) ?? h.data, void 0, e.headers);
849
- }
850
- c = !0;
851
- } catch (h) {
852
- if (ye(h))
853
- return;
854
- throw h;
855
- } finally {
856
- c || t.abort();
857
- }
858
- }
859
- return new O(o, t, s);
860
- }
861
- /**
862
- * Generates a Stream from a newline-separated ReadableStream
863
- * where each item is a JSON value.
864
- */
865
- static fromReadableStream(e, t, s) {
866
- let r = !1;
867
- async function* i() {
868
- const c = new we(), h = ft(e);
869
- for await (const f of h)
870
- for (const g of c.decode(f))
871
- yield g;
872
- for (const f of c.flush())
873
- yield f;
874
- }
875
- async function* o() {
876
- if (r)
877
- throw new d("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
878
- r = !0;
879
- let c = !1;
880
- try {
881
- for await (const h of i())
882
- c || h && (yield JSON.parse(h));
883
- c = !0;
884
- } catch (h) {
885
- if (ye(h))
886
- return;
887
- throw h;
888
- } finally {
889
- c || t.abort();
890
- }
891
- }
892
- return new O(o, t, s);
893
- }
894
- [(ee = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
895
- return this.iterator();
896
- }
897
- /**
898
- * Splits the stream into two streams which can be
899
- * independently read from at different speeds.
900
- */
901
- tee() {
902
- const e = [], t = [], s = this.iterator(), r = (i) => ({
903
- next: () => {
904
- if (i.length === 0) {
905
- const o = s.next();
906
- e.push(o), t.push(o);
907
- }
908
- return i.shift();
909
- }
910
- });
911
- return [
912
- new O(() => r(e), this.controller, a(this, ee, "f")),
913
- new O(() => r(t), this.controller, a(this, ee, "f"))
914
- ];
915
- }
916
- /**
917
- * Converts this stream to a newline-separated ReadableStream of
918
- * JSON stringified values in the stream
919
- * which can be turned back into a Stream with `Stream.fromReadableStream()`.
920
- */
921
- toReadableStream() {
922
- const e = this;
923
- let t;
924
- return is({
925
- async start() {
926
- t = e[Symbol.asyncIterator]();
927
- },
928
- async pull(s) {
929
- try {
930
- const { value: r, done: i } = await t.next();
931
- if (i)
932
- return s.close();
933
- const o = pt(JSON.stringify(r) + `
934
- `);
935
- s.enqueue(o);
936
- } catch (r) {
937
- s.error(r);
938
- }
939
- },
940
- async cancel() {
941
- await t.return?.();
942
- }
943
- });
944
- }
945
- }
946
- async function* an(n, e) {
947
- if (!n.body)
948
- throw e.abort(), typeof globalThis.navigator < "u" && globalThis.navigator.product === "ReactNative" ? new d("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api") : new d("Attempted to iterate over a response with no body");
949
- const t = new cn(), s = new we(), r = ft(n.body);
950
- for await (const i of on(r))
951
- for (const o of s.decode(i)) {
952
- const c = t.decode(o);
953
- c && (yield c);
954
- }
955
- for (const i of s.flush()) {
956
- const o = t.decode(i);
957
- o && (yield o);
958
- }
959
- }
960
- async function* on(n) {
961
- let e = new Uint8Array();
962
- for await (const t of n) {
963
- if (t == null)
964
- continue;
965
- const s = t instanceof ArrayBuffer ? new Uint8Array(t) : typeof t == "string" ? pt(t) : t;
966
- let r = new Uint8Array(e.length + s.length);
967
- r.set(e), r.set(s, e.length), e = r;
968
- let i;
969
- for (; (i = nn(e)) !== -1; )
970
- yield e.slice(0, i), e = e.slice(i);
971
- }
972
- e.length > 0 && (yield e);
973
- }
974
- class cn {
975
- constructor() {
976
- this.event = null, this.data = [], this.chunks = [];
977
- }
978
- decode(e) {
979
- if (e.endsWith("\r") && (e = e.substring(0, e.length - 1)), !e) {
980
- if (!this.event && !this.data.length)
981
- return null;
982
- const i = {
983
- event: this.event,
984
- data: this.data.join(`
985
- `),
986
- raw: this.chunks
987
- };
988
- return this.event = null, this.data = [], this.chunks = [], i;
989
- }
990
- if (this.chunks.push(e), e.startsWith(":"))
991
- return null;
992
- let [t, s, r] = ln(e, ":");
993
- return r.startsWith(" ") && (r = r.substring(1)), t === "event" ? this.event = r : t === "data" && this.data.push(r), null;
994
- }
995
- }
996
- function ln(n, e) {
997
- const t = n.indexOf(e);
998
- return t !== -1 ? [n.substring(0, t), e, n.substring(t + e.length)] : [n, "", ""];
999
- }
1000
- async function os(n, e) {
1001
- const { response: t, requestLogID: s, retryOfRequestLogID: r, startTime: i } = e, o = await (async () => {
1002
- if (e.options.stream)
1003
- return k(n).debug("response", t.status, t.url, t.headers, t.body), e.options.__streamClass ? e.options.__streamClass.fromSSEResponse(t, e.controller) : O.fromSSEResponse(t, e.controller);
1004
- if (t.status === 204)
1005
- return null;
1006
- if (e.options.__binaryResponse)
1007
- return t;
1008
- const h = t.headers.get("content-type")?.split(";")[0]?.trim();
1009
- if (h?.includes("application/json") || h?.endsWith("+json")) {
1010
- const y = await t.json();
1011
- return cs(y, t);
1012
- }
1013
- return await t.text();
1014
- })();
1015
- return k(n).debug(`[${s}] response parsed`, H({
1016
- retryOfRequestLogID: r,
1017
- url: t.url,
1018
- status: t.status,
1019
- body: o,
1020
- durationMs: Date.now() - i
1021
- })), o;
1022
- }
1023
- function cs(n, e) {
1024
- return !n || typeof n != "object" || Array.isArray(n) ? n : Object.defineProperty(n, "_request_id", {
1025
- value: e.headers.get("request-id"),
1026
- enumerable: !1
1027
- });
1028
- }
1029
- var ge;
1030
- class ze extends Promise {
1031
- constructor(e, t, s = os) {
1032
- super((r) => {
1033
- r(null);
1034
- }), this.responsePromise = t, this.parseResponse = s, ge.set(this, void 0), u(this, ge, e);
1035
- }
1036
- _thenUnwrap(e) {
1037
- return new ze(a(this, ge, "f"), this.responsePromise, async (t, s) => cs(e(await this.parseResponse(t, s), s), s.response));
1038
- }
1039
- /**
1040
- * Gets the raw `Response` instance instead of parsing the response
1041
- * data.
1042
- *
1043
- * If you want to parse the response body but still get the `Response`
1044
- * instance, you can use {@link withResponse()}.
1045
- *
1046
- * 👋 Getting the wrong TypeScript type for `Response`?
1047
- * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
1048
- * to your `tsconfig.json`.
1049
- */
1050
- asResponse() {
1051
- return this.responsePromise.then((e) => e.response);
1052
- }
1053
- /**
1054
- * Gets the parsed response data, the raw `Response` instance and the ID of the request,
1055
- * returned via the `request-id` header which is useful for debugging requests and resporting
1056
- * issues to Anthropic.
1057
- *
1058
- * If you just want to get the raw `Response` instance without parsing it,
1059
- * you can use {@link asResponse()}.
1060
- *
1061
- * 👋 Getting the wrong TypeScript type for `Response`?
1062
- * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
1063
- * to your `tsconfig.json`.
1064
- */
1065
- async withResponse() {
1066
- const [e, t] = await Promise.all([this.parse(), this.asResponse()]);
1067
- return { data: e, response: t, request_id: t.headers.get("request-id") };
1068
- }
1069
- parse() {
1070
- return this.parsedPromise || (this.parsedPromise = this.responsePromise.then((e) => this.parseResponse(a(this, ge, "f"), e))), this.parsedPromise;
1071
- }
1072
- then(e, t) {
1073
- return this.parse().then(e, t);
1074
- }
1075
- catch(e) {
1076
- return this.parse().catch(e);
1077
- }
1078
- finally(e) {
1079
- return this.parse().finally(e);
1080
- }
1081
- }
1082
- ge = /* @__PURE__ */ new WeakMap();
1083
- var ke;
1084
- class ls {
1085
- constructor(e, t, s, r) {
1086
- ke.set(this, void 0), u(this, ke, e), this.options = r, this.response = t, this.body = s;
1087
- }
1088
- hasNextPage() {
1089
- return this.getPaginatedItems().length ? this.nextPageRequestOptions() != null : !1;
1090
- }
1091
- async getNextPage() {
1092
- const e = this.nextPageRequestOptions();
1093
- if (!e)
1094
- throw new d("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
1095
- return await a(this, ke, "f").requestAPIList(this.constructor, e);
1096
- }
1097
- async *iterPages() {
1098
- let e = this;
1099
- for (yield e; e.hasNextPage(); )
1100
- e = await e.getNextPage(), yield e;
1101
- }
1102
- async *[(ke = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
1103
- for await (const e of this.iterPages())
1104
- for (const t of e.getPaginatedItems())
1105
- yield t;
1106
- }
1107
- }
1108
- class un extends ze {
1109
- constructor(e, t, s) {
1110
- super(e, t, async (r, i) => new s(r, i.response, await os(r, i), i.options));
1111
- }
1112
- /**
1113
- * Allow auto-paginating iteration on an unawaited list call, eg:
1114
- *
1115
- * for await (const item of client.items.list()) {
1116
- * console.log(item)
1117
- * }
1118
- */
1119
- async *[Symbol.asyncIterator]() {
1120
- const e = await this;
1121
- for await (const t of e)
1122
- yield t;
1123
- }
1124
- }
1125
- class _e extends ls {
1126
- constructor(e, t, s, r) {
1127
- super(e, t, s, r), this.data = s.data || [], this.has_more = s.has_more || !1, this.first_id = s.first_id || null, this.last_id = s.last_id || null;
1128
- }
1129
- getPaginatedItems() {
1130
- return this.data ?? [];
1131
- }
1132
- hasNextPage() {
1133
- return this.has_more === !1 ? !1 : super.hasNextPage();
1134
- }
1135
- nextPageRequestOptions() {
1136
- if (this.options.query?.before_id) {
1137
- const t = this.first_id;
1138
- return t ? {
1139
- ...this.options,
1140
- query: {
1141
- ...ct(this.options.query),
1142
- before_id: t
1143
- }
1144
- } : null;
1145
- }
1146
- const e = this.last_id;
1147
- return e ? {
1148
- ...this.options,
1149
- query: {
1150
- ...ct(this.options.query),
1151
- after_id: e
1152
- }
1153
- } : null;
1154
- }
1155
- }
1156
- class us extends ls {
1157
- constructor(e, t, s, r) {
1158
- super(e, t, s, r), this.data = s.data || [], this.has_more = s.has_more || !1, this.next_page = s.next_page || null;
1159
- }
1160
- getPaginatedItems() {
1161
- return this.data ?? [];
1162
- }
1163
- hasNextPage() {
1164
- return this.has_more === !1 ? !1 : super.hasNextPage();
1165
- }
1166
- nextPageRequestOptions() {
1167
- const e = this.next_page;
1168
- return e ? {
1169
- ...this.options,
1170
- query: {
1171
- ...ct(this.options.query),
1172
- page: e
1173
- }
1174
- } : null;
1175
- }
1176
- }
1177
- const hs = () => {
1178
- if (typeof File > "u") {
1179
- const { process: n } = globalThis, e = typeof n?.versions?.node == "string" && parseInt(n.versions.node.split(".")) < 20;
1180
- throw new Error("`File` is not defined as a global, which is required for file uploads." + (e ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
1181
- }
1182
- };
1183
- function Y(n, e, t) {
1184
- return hs(), new File(n, e ?? "unknown_file", t);
1185
- }
1186
- function Ne(n) {
1187
- return (typeof n == "object" && n !== null && ("name" in n && n.name && String(n.name) || "url" in n && n.url && String(n.url) || "filename" in n && n.filename && String(n.filename) || "path" in n && n.path && String(n.path)) || "").split(/[\\/]/).pop() || void 0;
1188
- }
1189
- const ds = (n) => n != null && typeof n == "object" && typeof n[Symbol.asyncIterator] == "function", mt = async (n, e) => ({ ...n, body: await dn(n.body, e) }), It = /* @__PURE__ */ new WeakMap();
1190
- function hn(n) {
1191
- const e = typeof n == "function" ? n : n.fetch, t = It.get(e);
1192
- if (t)
1193
- return t;
1194
- const s = (async () => {
1195
- try {
1196
- const r = "Response" in e ? e.Response : (await e("data:,")).constructor, i = new FormData();
1197
- return i.toString() !== await new r(i).text();
1198
- } catch {
1199
- return !0;
1200
- }
1201
- })();
1202
- return It.set(e, s), s;
1203
- }
1204
- const dn = async (n, e) => {
1205
- if (!await hn(e))
1206
- throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
1207
- const t = new FormData();
1208
- return await Promise.all(Object.entries(n || {}).map(([s, r]) => lt(t, s, r))), t;
1209
- }, fn = (n) => n instanceof Blob && "name" in n, lt = async (n, e, t) => {
1210
- if (t !== void 0) {
1211
- if (t == null)
1212
- throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);
1213
- if (typeof t == "string" || typeof t == "number" || typeof t == "boolean")
1214
- n.append(e, String(t));
1215
- else if (t instanceof Response) {
1216
- let s = {};
1217
- const r = t.headers.get("Content-Type");
1218
- r && (s = { type: r }), n.append(e, Y([await t.blob()], Ne(t), s));
1219
- } else if (ds(t))
1220
- n.append(e, Y([await new Response(as(t)).blob()], Ne(t)));
1221
- else if (fn(t))
1222
- n.append(e, Y([t], Ne(t), { type: t.type }));
1223
- else if (Array.isArray(t))
1224
- await Promise.all(t.map((s) => lt(n, e + "[]", s)));
1225
- else if (typeof t == "object")
1226
- await Promise.all(Object.entries(t).map(([s, r]) => lt(n, `${e}[${s}]`, r)));
1227
- else
1228
- throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`);
1229
- }
1230
- }, fs = (n) => n != null && typeof n == "object" && typeof n.size == "number" && typeof n.type == "string" && typeof n.text == "function" && typeof n.slice == "function" && typeof n.arrayBuffer == "function", pn = (n) => n != null && typeof n == "object" && typeof n.name == "string" && typeof n.lastModified == "number" && fs(n), mn = (n) => n != null && typeof n == "object" && typeof n.url == "string" && typeof n.blob == "function";
1231
- async function gn(n, e, t) {
1232
- if (hs(), n = await n, e || (e = Ne(n)), pn(n))
1233
- return n instanceof File && e == null && t == null ? n : Y([await n.arrayBuffer()], e ?? n.name, {
1234
- type: n.type,
1235
- lastModified: n.lastModified,
1236
- ...t
1237
- });
1238
- if (mn(n)) {
1239
- const r = await n.blob();
1240
- return e || (e = new URL(n.url).pathname.split(/[\\/]/).pop()), Y(await ut(r), e, t);
1241
- }
1242
- const s = await ut(n);
1243
- if (!t?.type) {
1244
- const r = s.find((i) => typeof i == "object" && "type" in i && i.type);
1245
- typeof r == "string" && (t = { ...t, type: r });
1246
- }
1247
- return Y(s, e, t);
1248
- }
1249
- async function ut(n) {
1250
- let e = [];
1251
- if (typeof n == "string" || ArrayBuffer.isView(n) || // includes Uint8Array, Buffer, etc.
1252
- n instanceof ArrayBuffer)
1253
- e.push(n);
1254
- else if (fs(n))
1255
- e.push(n instanceof Blob ? n : await n.arrayBuffer());
1256
- else if (ds(n))
1257
- for await (const t of n)
1258
- e.push(...await ut(t));
1259
- else {
1260
- const t = n?.constructor?.name;
1261
- throw new Error(`Unexpected data type: ${typeof n}${t ? `; constructor: ${t}` : ""}${yn(n)}`);
1262
- }
1263
- return e;
1264
- }
1265
- function yn(n) {
1266
- return typeof n != "object" || n === null ? "" : `; props: [${Object.getOwnPropertyNames(n).map((t) => `"${t}"`).join(", ")}]`;
1267
- }
1268
- class I {
1269
- constructor(e) {
1270
- this._client = e;
1271
- }
1272
- }
1273
- const ps = /* @__PURE__ */ Symbol.for("brand.privateNullableHeaders");
1274
- function* wn(n) {
1275
- if (!n)
1276
- return;
1277
- if (ps in n) {
1278
- const { values: s, nulls: r } = n;
1279
- yield* s.entries();
1280
- for (const i of r)
1281
- yield [i, null];
1282
- return;
1283
- }
1284
- let e = !1, t;
1285
- n instanceof Headers ? t = n.entries() : kt(n) ? t = n : (e = !0, t = Object.entries(n ?? {}));
1286
- for (let s of t) {
1287
- const r = s[0];
1288
- if (typeof r != "string")
1289
- throw new TypeError("expected header name to be a string");
1290
- const i = kt(s[1]) ? s[1] : [s[1]];
1291
- let o = !1;
1292
- for (const c of i)
1293
- c !== void 0 && (e && !o && (o = !0, yield [r, null]), yield [r, c]);
1294
- }
1295
- }
1296
- const m = (n) => {
1297
- const e = new Headers(), t = /* @__PURE__ */ new Set();
1298
- for (const s of n) {
1299
- const r = /* @__PURE__ */ new Set();
1300
- for (const [i, o] of wn(s)) {
1301
- const c = i.toLowerCase();
1302
- r.has(c) || (e.delete(i), r.add(c)), o === null ? (e.delete(i), t.add(c)) : (e.append(i, o), t.delete(c));
1303
- }
1304
- }
1305
- return { [ps]: !0, values: e, nulls: t };
1306
- };
1307
- function ms(n) {
1308
- return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
1309
- }
1310
- const $t = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)), _n = (n = ms) => function(t, ...s) {
1311
- if (t.length === 1)
1312
- return t[0];
1313
- let r = !1;
1314
- const i = [], o = t.reduce((g, y, E) => {
1315
- /[?#]/.test(y) && (r = !0);
1316
- const p = s[E];
1317
- let v = (r ? encodeURIComponent : n)("" + p);
1318
- return E !== s.length && (p == null || typeof p == "object" && // handle values from other realms
1319
- p.toString === Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty ?? $t) ?? $t)?.toString) && (v = p + "", i.push({
1320
- start: g.length + y.length,
1321
- length: v.length,
1322
- error: `Value of type ${Object.prototype.toString.call(p).slice(8, -1)} is not a valid path parameter`
1323
- })), g + y + (E === s.length ? "" : v);
1324
- }, ""), c = o.split(/[?#]/, 1)[0], h = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
1325
- let f;
1326
- for (; (f = h.exec(c)) !== null; )
1327
- i.push({
1328
- start: f.index,
1329
- length: f[0].length,
1330
- error: `Value "${f[0]}" can't be safely passed as a path parameter`
1331
- });
1332
- if (i.sort((g, y) => g.start - y.start), i.length > 0) {
1333
- let g = 0;
1334
- const y = i.reduce((E, p) => {
1335
- const v = " ".repeat(p.start - g), Ke = "^".repeat(p.length);
1336
- return g = p.start + p.length, E + v + Ke;
1337
- }, "");
1338
- throw new d(`Path parameters result in path with invalid segments:
1339
- ${i.map((E) => E.error).join(`
1340
- `)}
1341
- ${o}
1342
- ${y}`);
1343
- }
1344
- return o;
1345
- }, b = /* @__PURE__ */ _n(ms);
1346
- class gs extends I {
1347
- /**
1348
- * List Files
1349
- *
1350
- * @example
1351
- * ```ts
1352
- * // Automatically fetches more pages as needed.
1353
- * for await (const fileMetadata of client.beta.files.list()) {
1354
- * // ...
1355
- * }
1356
- * ```
1357
- */
1358
- list(e = {}, t) {
1359
- const { betas: s, ...r } = e ?? {};
1360
- return this._client.getAPIList("/v1/files", _e, {
1361
- query: r,
1362
- ...t,
1363
- headers: m([
1364
- { "anthropic-beta": [...s ?? [], "files-api-2025-04-14"].toString() },
1365
- t?.headers
1366
- ])
1367
- });
1368
- }
1369
- /**
1370
- * Delete File
1371
- *
1372
- * @example
1373
- * ```ts
1374
- * const deletedFile = await client.beta.files.delete(
1375
- * 'file_id',
1376
- * );
1377
- * ```
1378
- */
1379
- delete(e, t = {}, s) {
1380
- const { betas: r } = t ?? {};
1381
- return this._client.delete(b`/v1/files/${e}`, {
1382
- ...s,
1383
- headers: m([
1384
- { "anthropic-beta": [...r ?? [], "files-api-2025-04-14"].toString() },
1385
- s?.headers
1386
- ])
1387
- });
1388
- }
1389
- /**
1390
- * Download File
1391
- *
1392
- * @example
1393
- * ```ts
1394
- * const response = await client.beta.files.download(
1395
- * 'file_id',
1396
- * );
1397
- *
1398
- * const content = await response.blob();
1399
- * console.log(content);
1400
- * ```
1401
- */
1402
- download(e, t = {}, s) {
1403
- const { betas: r } = t ?? {};
1404
- return this._client.get(b`/v1/files/${e}/content`, {
1405
- ...s,
1406
- headers: m([
1407
- {
1408
- "anthropic-beta": [...r ?? [], "files-api-2025-04-14"].toString(),
1409
- Accept: "application/binary"
1410
- },
1411
- s?.headers
1412
- ]),
1413
- __binaryResponse: !0
1414
- });
1415
- }
1416
- /**
1417
- * Get File Metadata
1418
- *
1419
- * @example
1420
- * ```ts
1421
- * const fileMetadata =
1422
- * await client.beta.files.retrieveMetadata('file_id');
1423
- * ```
1424
- */
1425
- retrieveMetadata(e, t = {}, s) {
1426
- const { betas: r } = t ?? {};
1427
- return this._client.get(b`/v1/files/${e}`, {
1428
- ...s,
1429
- headers: m([
1430
- { "anthropic-beta": [...r ?? [], "files-api-2025-04-14"].toString() },
1431
- s?.headers
1432
- ])
1433
- });
1434
- }
1435
- /**
1436
- * Upload File
1437
- *
1438
- * @example
1439
- * ```ts
1440
- * const fileMetadata = await client.beta.files.upload({
1441
- * file: fs.createReadStream('path/to/file'),
1442
- * });
1443
- * ```
1444
- */
1445
- upload(e, t) {
1446
- const { betas: s, ...r } = e;
1447
- return this._client.post("/v1/files", mt({
1448
- body: r,
1449
- ...t,
1450
- headers: m([
1451
- { "anthropic-beta": [...s ?? [], "files-api-2025-04-14"].toString() },
1452
- t?.headers
1453
- ])
1454
- }, this._client));
1455
- }
1456
- }
1457
- let ys = class extends I {
1458
- /**
1459
- * Get a specific model.
1460
- *
1461
- * The Models API response can be used to determine information about a specific
1462
- * model or resolve a model alias to a model ID.
1463
- *
1464
- * @example
1465
- * ```ts
1466
- * const betaModelInfo = await client.beta.models.retrieve(
1467
- * 'model_id',
1468
- * );
1469
- * ```
1470
- */
1471
- retrieve(e, t = {}, s) {
1472
- const { betas: r } = t ?? {};
1473
- return this._client.get(b`/v1/models/${e}?beta=true`, {
1474
- ...s,
1475
- headers: m([
1476
- { ...r?.toString() != null ? { "anthropic-beta": r?.toString() } : void 0 },
1477
- s?.headers
1478
- ])
1479
- });
1480
- }
1481
- /**
1482
- * List available models.
1483
- *
1484
- * The Models API response can be used to determine which models are available for
1485
- * use in the API. More recently released models are listed first.
1486
- *
1487
- * @example
1488
- * ```ts
1489
- * // Automatically fetches more pages as needed.
1490
- * for await (const betaModelInfo of client.beta.models.list()) {
1491
- * // ...
1492
- * }
1493
- * ```
1494
- */
1495
- list(e = {}, t) {
1496
- const { betas: s, ...r } = e ?? {};
1497
- return this._client.getAPIList("/v1/models?beta=true", _e, {
1498
- query: r,
1499
- ...t,
1500
- headers: m([
1501
- { ...s?.toString() != null ? { "anthropic-beta": s?.toString() } : void 0 },
1502
- t?.headers
1503
- ])
1504
- });
1505
- }
1506
- };
1507
- const ws = {
1508
- "claude-opus-4-20250514": 8192,
1509
- "claude-opus-4-0": 8192,
1510
- "claude-4-opus-20250514": 8192,
1511
- "anthropic.claude-opus-4-20250514-v1:0": 8192,
1512
- "claude-opus-4@20250514": 8192,
1513
- "claude-opus-4-1-20250805": 8192,
1514
- "anthropic.claude-opus-4-1-20250805-v1:0": 8192,
1515
- "claude-opus-4-1@20250805": 8192
1516
- };
1517
- function Ot(n, e, t) {
1518
- return !e || !("parse" in (e.output_format ?? {})) ? {
1519
- ...n,
1520
- content: n.content.map((s) => {
1521
- if (s.type === "text") {
1522
- const r = Object.defineProperty({ ...s }, "parsed_output", {
1523
- value: null,
1524
- enumerable: !1
1525
- });
1526
- return Object.defineProperty(r, "parsed", {
1527
- get() {
1528
- return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."), null;
1529
- },
1530
- enumerable: !1
1531
- });
1532
- }
1533
- return s;
1534
- }),
1535
- parsed_output: null
1536
- } : _s(n, e, t);
1537
- }
1538
- function _s(n, e, t) {
1539
- let s = null;
1540
- const r = n.content.map((i) => {
1541
- if (i.type === "text") {
1542
- const o = bn(e, i.text);
1543
- s === null && (s = o);
1544
- const c = Object.defineProperty({ ...i }, "parsed_output", {
1545
- value: o,
1546
- enumerable: !1
1547
- });
1548
- return Object.defineProperty(c, "parsed", {
1549
- get() {
1550
- return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."), o;
1551
- },
1552
- enumerable: !1
1553
- });
1554
- }
1555
- return i;
1556
- });
1557
- return {
1558
- ...n,
1559
- content: r,
1560
- parsed_output: s
1561
- };
1562
- }
1563
- function bn(n, e) {
1564
- if (n.output_format?.type !== "json_schema")
1565
- return null;
1566
- try {
1567
- return "parse" in n.output_format ? n.output_format.parse(e) : JSON.parse(e);
1568
- } catch (t) {
1569
- throw new d(`Failed to parse structured output: ${t}`);
1570
- }
1571
- }
1572
- const Sn = (n) => {
1573
- let e = 0, t = [];
1574
- for (; e < n.length; ) {
1575
- let s = n[e];
1576
- if (s === "\\") {
1577
- e++;
1578
- continue;
1579
- }
1580
- if (s === "{") {
1581
- t.push({
1582
- type: "brace",
1583
- value: "{"
1584
- }), e++;
1585
- continue;
1586
- }
1587
- if (s === "}") {
1588
- t.push({
1589
- type: "brace",
1590
- value: "}"
1591
- }), e++;
1592
- continue;
1593
- }
1594
- if (s === "[") {
1595
- t.push({
1596
- type: "paren",
1597
- value: "["
1598
- }), e++;
1599
- continue;
1600
- }
1601
- if (s === "]") {
1602
- t.push({
1603
- type: "paren",
1604
- value: "]"
1605
- }), e++;
1606
- continue;
1607
- }
1608
- if (s === ":") {
1609
- t.push({
1610
- type: "separator",
1611
- value: ":"
1612
- }), e++;
1613
- continue;
1614
- }
1615
- if (s === ",") {
1616
- t.push({
1617
- type: "delimiter",
1618
- value: ","
1619
- }), e++;
1620
- continue;
1621
- }
1622
- if (s === '"') {
1623
- let c = "", h = !1;
1624
- for (s = n[++e]; s !== '"'; ) {
1625
- if (e === n.length) {
1626
- h = !0;
1627
- break;
1628
- }
1629
- if (s === "\\") {
1630
- if (e++, e === n.length) {
1631
- h = !0;
1632
- break;
1633
- }
1634
- c += s + n[e], s = n[++e];
1635
- } else
1636
- c += s, s = n[++e];
1637
- }
1638
- s = n[++e], h || t.push({
1639
- type: "string",
1640
- value: c
1641
- });
1642
- continue;
1643
- }
1644
- if (s && /\s/.test(s)) {
1645
- e++;
1646
- continue;
1647
- }
1648
- let i = /[0-9]/;
1649
- if (s && i.test(s) || s === "-" || s === ".") {
1650
- let c = "";
1651
- for (s === "-" && (c += s, s = n[++e]); s && i.test(s) || s === "."; )
1652
- c += s, s = n[++e];
1653
- t.push({
1654
- type: "number",
1655
- value: c
1656
- });
1657
- continue;
1658
- }
1659
- let o = /[a-z]/i;
1660
- if (s && o.test(s)) {
1661
- let c = "";
1662
- for (; s && o.test(s) && e !== n.length; )
1663
- c += s, s = n[++e];
1664
- if (c == "true" || c == "false" || c === "null")
1665
- t.push({
1666
- type: "name",
1667
- value: c
1668
- });
1669
- else {
1670
- e++;
1671
- continue;
1672
- }
1673
- continue;
1674
- }
1675
- e++;
1676
- }
1677
- return t;
1678
- }, Q = (n) => {
1679
- if (n.length === 0)
1680
- return n;
1681
- let e = n[n.length - 1];
1682
- switch (e.type) {
1683
- case "separator":
1684
- return n = n.slice(0, n.length - 1), Q(n);
1685
- case "number":
1686
- let t = e.value[e.value.length - 1];
1687
- if (t === "." || t === "-")
1688
- return n = n.slice(0, n.length - 1), Q(n);
1689
- case "string":
1690
- let s = n[n.length - 2];
1691
- if (s?.type === "delimiter")
1692
- return n = n.slice(0, n.length - 1), Q(n);
1693
- if (s?.type === "brace" && s.value === "{")
1694
- return n = n.slice(0, n.length - 1), Q(n);
1695
- break;
1696
- case "delimiter":
1697
- return n = n.slice(0, n.length - 1), Q(n);
1698
- }
1699
- return n;
1700
- }, kn = (n) => {
1701
- let e = [];
1702
- return n.map((t) => {
1703
- t.type === "brace" && (t.value === "{" ? e.push("}") : e.splice(e.lastIndexOf("}"), 1)), t.type === "paren" && (t.value === "[" ? e.push("]") : e.splice(e.lastIndexOf("]"), 1));
1704
- }), e.length > 0 && e.reverse().map((t) => {
1705
- t === "}" ? n.push({
1706
- type: "brace",
1707
- value: "}"
1708
- }) : t === "]" && n.push({
1709
- type: "paren",
1710
- value: "]"
1711
- });
1712
- }), n;
1713
- }, xn = (n) => {
1714
- let e = "";
1715
- return n.map((t) => {
1716
- t.type === "string" ? e += '"' + t.value + '"' : e += t.value;
1717
- }), e;
1718
- }, bs = (n) => JSON.parse(xn(kn(Q(Sn(n)))));
1719
- var P, L, X, te, xe, se, ne, Me, re, C, ie, Re, Pe, U, Te, Ee, ae, Qe, Bt, ve, Ge, Ye, Ze, Ct;
1720
- const jt = "__json_buf";
1721
- function Nt(n) {
1722
- return n.type === "tool_use" || n.type === "server_tool_use" || n.type === "mcp_tool_use";
1723
- }
1724
- class We {
1725
- constructor(e, t) {
1726
- P.add(this), this.messages = [], this.receivedMessages = [], L.set(this, void 0), X.set(this, null), this.controller = new AbortController(), te.set(this, void 0), xe.set(this, () => {
1727
- }), se.set(this, () => {
1728
- }), ne.set(this, void 0), Me.set(this, () => {
1729
- }), re.set(this, () => {
1730
- }), C.set(this, {}), ie.set(this, !1), Re.set(this, !1), Pe.set(this, !1), U.set(this, !1), Te.set(this, void 0), Ee.set(this, void 0), ae.set(this, void 0), ve.set(this, (s) => {
1731
- if (u(this, Re, !0), ye(s) && (s = new A()), s instanceof A)
1732
- return u(this, Pe, !0), this._emit("abort", s);
1733
- if (s instanceof d)
1734
- return this._emit("error", s);
1735
- if (s instanceof Error) {
1736
- const r = new d(s.message);
1737
- return r.cause = s, this._emit("error", r);
1738
- }
1739
- return this._emit("error", new d(String(s)));
1740
- }), u(this, te, new Promise((s, r) => {
1741
- u(this, xe, s, "f"), u(this, se, r, "f");
1742
- })), u(this, ne, new Promise((s, r) => {
1743
- u(this, Me, s, "f"), u(this, re, r, "f");
1744
- })), a(this, te, "f").catch(() => {
1745
- }), a(this, ne, "f").catch(() => {
1746
- }), u(this, X, e), u(this, ae, t?.logger ?? console);
1747
- }
1748
- get response() {
1749
- return a(this, Te, "f");
1750
- }
1751
- get request_id() {
1752
- return a(this, Ee, "f");
1753
- }
1754
- /**
1755
- * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
1756
- * returned vie the `request-id` header which is useful for debugging requests and resporting
1757
- * issues to Anthropic.
1758
- *
1759
- * This is the same as the `APIPromise.withResponse()` method.
1760
- *
1761
- * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
1762
- * as no `Response` is available.
1763
- */
1764
- async withResponse() {
1765
- u(this, U, !0);
1766
- const e = await a(this, te, "f");
1767
- if (!e)
1768
- throw new Error("Could not resolve a `Response` object");
1769
- return {
1770
- data: this,
1771
- response: e,
1772
- request_id: e.headers.get("request-id")
1773
- };
1774
- }
1775
- /**
1776
- * Intended for use on the frontend, consuming a stream produced with
1777
- * `.toReadableStream()` on the backend.
1778
- *
1779
- * Note that messages sent to the model do not appear in `.on('message')`
1780
- * in this context.
1781
- */
1782
- static fromReadableStream(e) {
1783
- const t = new We(null);
1784
- return t._run(() => t._fromReadableStream(e)), t;
1785
- }
1786
- static createMessage(e, t, s, { logger: r } = {}) {
1787
- const i = new We(t, { logger: r });
1788
- for (const o of t.messages)
1789
- i._addMessageParam(o);
1790
- return u(i, X, { ...t, stream: !0 }), i._run(() => i._createMessage(e, { ...t, stream: !0 }, { ...s, headers: { ...s?.headers, "X-Stainless-Helper-Method": "stream" } })), i;
1791
- }
1792
- _run(e) {
1793
- e().then(() => {
1794
- this._emitFinal(), this._emit("end");
1795
- }, a(this, ve, "f"));
1796
- }
1797
- _addMessageParam(e) {
1798
- this.messages.push(e);
1799
- }
1800
- _addMessage(e, t = !0) {
1801
- this.receivedMessages.push(e), t && this._emit("message", e);
1802
- }
1803
- async _createMessage(e, t, s) {
1804
- const r = s?.signal;
1805
- let i;
1806
- r && (r.aborted && this.controller.abort(), i = this.controller.abort.bind(this.controller), r.addEventListener("abort", i));
1807
- try {
1808
- a(this, P, "m", Ge).call(this);
1809
- const { response: o, data: c } = await e.create({ ...t, stream: !0 }, { ...s, signal: this.controller.signal }).withResponse();
1810
- this._connected(o);
1811
- for await (const h of c)
1812
- a(this, P, "m", Ye).call(this, h);
1813
- if (c.controller.signal?.aborted)
1814
- throw new A();
1815
- a(this, P, "m", Ze).call(this);
1816
- } finally {
1817
- r && i && r.removeEventListener("abort", i);
1818
- }
1819
- }
1820
- _connected(e) {
1821
- this.ended || (u(this, Te, e), u(this, Ee, e?.headers.get("request-id")), a(this, xe, "f").call(this, e), this._emit("connect"));
1822
- }
1823
- get ended() {
1824
- return a(this, ie, "f");
1825
- }
1826
- get errored() {
1827
- return a(this, Re, "f");
1828
- }
1829
- get aborted() {
1830
- return a(this, Pe, "f");
1831
- }
1832
- abort() {
1833
- this.controller.abort();
1834
- }
1835
- /**
1836
- * Adds the listener function to the end of the listeners array for the event.
1837
- * No checks are made to see if the listener has already been added. Multiple calls passing
1838
- * the same combination of event and listener will result in the listener being added, and
1839
- * called, multiple times.
1840
- * @returns this MessageStream, so that calls can be chained
1841
- */
1842
- on(e, t) {
1843
- return (a(this, C, "f")[e] || (a(this, C, "f")[e] = [])).push({ listener: t }), this;
1844
- }
1845
- /**
1846
- * Removes the specified listener from the listener array for the event.
1847
- * off() will remove, at most, one instance of a listener from the listener array. If any single
1848
- * listener has been added multiple times to the listener array for the specified event, then
1849
- * off() must be called multiple times to remove each instance.
1850
- * @returns this MessageStream, so that calls can be chained
1851
- */
1852
- off(e, t) {
1853
- const s = a(this, C, "f")[e];
1854
- if (!s)
1855
- return this;
1856
- const r = s.findIndex((i) => i.listener === t);
1857
- return r >= 0 && s.splice(r, 1), this;
1858
- }
1859
- /**
1860
- * Adds a one-time listener function for the event. The next time the event is triggered,
1861
- * this listener is removed and then invoked.
1862
- * @returns this MessageStream, so that calls can be chained
1863
- */
1864
- once(e, t) {
1865
- return (a(this, C, "f")[e] || (a(this, C, "f")[e] = [])).push({ listener: t, once: !0 }), this;
1866
- }
1867
- /**
1868
- * This is similar to `.once()`, but returns a Promise that resolves the next time
1869
- * the event is triggered, instead of calling a listener callback.
1870
- * @returns a Promise that resolves the next time given event is triggered,
1871
- * or rejects if an error is emitted. (If you request the 'error' event,
1872
- * returns a promise that resolves with the error).
1873
- *
1874
- * Example:
1875
- *
1876
- * const message = await stream.emitted('message') // rejects if the stream errors
1877
- */
1878
- emitted(e) {
1879
- return new Promise((t, s) => {
1880
- u(this, U, !0), e !== "error" && this.once("error", s), this.once(e, t);
1881
- });
1882
- }
1883
- async done() {
1884
- u(this, U, !0), await a(this, ne, "f");
1885
- }
1886
- get currentMessage() {
1887
- return a(this, L, "f");
1888
- }
1889
- /**
1890
- * @returns a promise that resolves with the the final assistant Message response,
1891
- * or rejects if an error occurred or the stream ended prematurely without producing a Message.
1892
- * If structured outputs were used, this will be a ParsedMessage with a `parsed` field.
1893
- */
1894
- async finalMessage() {
1895
- return await this.done(), a(this, P, "m", Qe).call(this);
1896
- }
1897
- /**
1898
- * @returns a promise that resolves with the the final assistant Message's text response, concatenated
1899
- * together if there are more than one text blocks.
1900
- * Rejects if an error occurred or the stream ended prematurely without producing a Message.
1901
- */
1902
- async finalText() {
1903
- return await this.done(), a(this, P, "m", Bt).call(this);
1904
- }
1905
- _emit(e, ...t) {
1906
- if (a(this, ie, "f"))
1907
- return;
1908
- e === "end" && (u(this, ie, !0), a(this, Me, "f").call(this));
1909
- const s = a(this, C, "f")[e];
1910
- if (s && (a(this, C, "f")[e] = s.filter((r) => !r.once), s.forEach(({ listener: r }) => r(...t))), e === "abort") {
1911
- const r = t[0];
1912
- !a(this, U, "f") && !s?.length && Promise.reject(r), a(this, se, "f").call(this, r), a(this, re, "f").call(this, r), this._emit("end");
1913
- return;
1914
- }
1915
- if (e === "error") {
1916
- const r = t[0];
1917
- !a(this, U, "f") && !s?.length && Promise.reject(r), a(this, se, "f").call(this, r), a(this, re, "f").call(this, r), this._emit("end");
1918
- }
1919
- }
1920
- _emitFinal() {
1921
- this.receivedMessages.at(-1) && this._emit("finalMessage", a(this, P, "m", Qe).call(this));
1922
- }
1923
- async _fromReadableStream(e, t) {
1924
- const s = t?.signal;
1925
- let r;
1926
- s && (s.aborted && this.controller.abort(), r = this.controller.abort.bind(this.controller), s.addEventListener("abort", r));
1927
- try {
1928
- a(this, P, "m", Ge).call(this), this._connected(null);
1929
- const i = O.fromReadableStream(e, this.controller);
1930
- for await (const o of i)
1931
- a(this, P, "m", Ye).call(this, o);
1932
- if (i.controller.signal?.aborted)
1933
- throw new A();
1934
- a(this, P, "m", Ze).call(this);
1935
- } finally {
1936
- s && r && s.removeEventListener("abort", r);
1937
- }
1938
- }
1939
- [(L = /* @__PURE__ */ new WeakMap(), X = /* @__PURE__ */ new WeakMap(), te = /* @__PURE__ */ new WeakMap(), xe = /* @__PURE__ */ new WeakMap(), se = /* @__PURE__ */ new WeakMap(), ne = /* @__PURE__ */ new WeakMap(), Me = /* @__PURE__ */ new WeakMap(), re = /* @__PURE__ */ new WeakMap(), C = /* @__PURE__ */ new WeakMap(), ie = /* @__PURE__ */ new WeakMap(), Re = /* @__PURE__ */ new WeakMap(), Pe = /* @__PURE__ */ new WeakMap(), U = /* @__PURE__ */ new WeakMap(), Te = /* @__PURE__ */ new WeakMap(), Ee = /* @__PURE__ */ new WeakMap(), ae = /* @__PURE__ */ new WeakMap(), ve = /* @__PURE__ */ new WeakMap(), P = /* @__PURE__ */ new WeakSet(), Qe = function() {
1940
- if (this.receivedMessages.length === 0)
1941
- throw new d("stream ended without producing a Message with role=assistant");
1942
- return this.receivedMessages.at(-1);
1943
- }, Bt = function() {
1944
- if (this.receivedMessages.length === 0)
1945
- throw new d("stream ended without producing a Message with role=assistant");
1946
- const t = this.receivedMessages.at(-1).content.filter((s) => s.type === "text").map((s) => s.text);
1947
- if (t.length === 0)
1948
- throw new d("stream ended without producing a content block with type=text");
1949
- return t.join(" ");
1950
- }, Ge = function() {
1951
- this.ended || u(this, L, void 0);
1952
- }, Ye = function(t) {
1953
- if (this.ended)
1954
- return;
1955
- const s = a(this, P, "m", Ct).call(this, t);
1956
- switch (this._emit("streamEvent", t, s), t.type) {
1957
- case "content_block_delta": {
1958
- const r = s.content.at(-1);
1959
- switch (t.delta.type) {
1960
- case "text_delta": {
1961
- r.type === "text" && this._emit("text", t.delta.text, r.text || "");
1962
- break;
1963
- }
1964
- case "citations_delta": {
1965
- r.type === "text" && this._emit("citation", t.delta.citation, r.citations ?? []);
1966
- break;
1967
- }
1968
- case "input_json_delta": {
1969
- Nt(r) && r.input && this._emit("inputJson", t.delta.partial_json, r.input);
1970
- break;
1971
- }
1972
- case "thinking_delta": {
1973
- r.type === "thinking" && this._emit("thinking", t.delta.thinking, r.thinking);
1974
- break;
1975
- }
1976
- case "signature_delta": {
1977
- r.type === "thinking" && this._emit("signature", r.signature);
1978
- break;
1979
- }
1980
- default:
1981
- t.delta;
1982
- }
1983
- break;
1984
- }
1985
- case "message_stop": {
1986
- this._addMessageParam(s), this._addMessage(Ot(s, a(this, X, "f"), { logger: a(this, ae, "f") }), !0);
1987
- break;
1988
- }
1989
- case "content_block_stop": {
1990
- this._emit("contentBlock", s.content.at(-1));
1991
- break;
1992
- }
1993
- case "message_start": {
1994
- u(this, L, s);
1995
- break;
1996
- }
1997
- }
1998
- }, Ze = function() {
1999
- if (this.ended)
2000
- throw new d("stream has ended, this shouldn't happen");
2001
- const t = a(this, L, "f");
2002
- if (!t)
2003
- throw new d("request ended without sending any chunks");
2004
- return u(this, L, void 0), Ot(t, a(this, X, "f"), { logger: a(this, ae, "f") });
2005
- }, Ct = function(t) {
2006
- let s = a(this, L, "f");
2007
- if (t.type === "message_start") {
2008
- if (s)
2009
- throw new d(`Unexpected event order, got ${t.type} before receiving "message_stop"`);
2010
- return t.message;
2011
- }
2012
- if (!s)
2013
- throw new d(`Unexpected event order, got ${t.type} before "message_start"`);
2014
- switch (t.type) {
2015
- case "message_stop":
2016
- return s;
2017
- case "message_delta":
2018
- return s.container = t.delta.container, s.stop_reason = t.delta.stop_reason, s.stop_sequence = t.delta.stop_sequence, s.usage.output_tokens = t.usage.output_tokens, s.context_management = t.context_management, t.usage.input_tokens != null && (s.usage.input_tokens = t.usage.input_tokens), t.usage.cache_creation_input_tokens != null && (s.usage.cache_creation_input_tokens = t.usage.cache_creation_input_tokens), t.usage.cache_read_input_tokens != null && (s.usage.cache_read_input_tokens = t.usage.cache_read_input_tokens), t.usage.server_tool_use != null && (s.usage.server_tool_use = t.usage.server_tool_use), s;
2019
- case "content_block_start":
2020
- return s.content.push(t.content_block), s;
2021
- case "content_block_delta": {
2022
- const r = s.content.at(t.index);
2023
- switch (t.delta.type) {
2024
- case "text_delta": {
2025
- r?.type === "text" && (s.content[t.index] = {
2026
- ...r,
2027
- text: (r.text || "") + t.delta.text
2028
- });
2029
- break;
2030
- }
2031
- case "citations_delta": {
2032
- r?.type === "text" && (s.content[t.index] = {
2033
- ...r,
2034
- citations: [...r.citations ?? [], t.delta.citation]
2035
- });
2036
- break;
2037
- }
2038
- case "input_json_delta": {
2039
- if (r && Nt(r)) {
2040
- let i = r[jt] || "";
2041
- i += t.delta.partial_json;
2042
- const o = { ...r };
2043
- if (Object.defineProperty(o, jt, {
2044
- value: i,
2045
- enumerable: !1,
2046
- writable: !0
2047
- }), i)
2048
- try {
2049
- o.input = bs(i);
2050
- } catch (c) {
2051
- const h = new d(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${i}`);
2052
- a(this, ve, "f").call(this, h);
2053
- }
2054
- s.content[t.index] = o;
2055
- }
2056
- break;
2057
- }
2058
- case "thinking_delta": {
2059
- r?.type === "thinking" && (s.content[t.index] = {
2060
- ...r,
2061
- thinking: r.thinking + t.delta.thinking
2062
- });
2063
- break;
2064
- }
2065
- case "signature_delta": {
2066
- r?.type === "thinking" && (s.content[t.index] = {
2067
- ...r,
2068
- signature: t.delta.signature
2069
- });
2070
- break;
2071
- }
2072
- default:
2073
- t.delta;
2074
- }
2075
- return s;
2076
- }
2077
- case "content_block_stop":
2078
- return s;
2079
- }
2080
- }, Symbol.asyncIterator)]() {
2081
- const e = [], t = [];
2082
- let s = !1;
2083
- return this.on("streamEvent", (r) => {
2084
- const i = t.shift();
2085
- i ? i.resolve(r) : e.push(r);
2086
- }), this.on("end", () => {
2087
- s = !0;
2088
- for (const r of t)
2089
- r.resolve(void 0);
2090
- t.length = 0;
2091
- }), this.on("abort", (r) => {
2092
- s = !0;
2093
- for (const i of t)
2094
- i.reject(r);
2095
- t.length = 0;
2096
- }), this.on("error", (r) => {
2097
- s = !0;
2098
- for (const i of t)
2099
- i.reject(r);
2100
- t.length = 0;
2101
- }), {
2102
- next: async () => e.length ? { value: e.shift(), done: !1 } : s ? { value: void 0, done: !0 } : new Promise((i, o) => t.push({ resolve: i, reject: o })).then((i) => i ? { value: i, done: !1 } : { value: void 0, done: !0 }),
2103
- return: async () => (this.abort(), { value: void 0, done: !0 })
2104
- };
2105
- }
2106
- toReadableStream() {
2107
- return new O(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream();
2108
- }
2109
- }
2110
- const Mn = 1e5, Rn = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
2111
- 1. Task Overview
2112
- The user's core request and success criteria
2113
- Any clarifications or constraints they specified
2114
- 2. Current State
2115
- What has been completed so far
2116
- Files created, modified, or analyzed (with paths if relevant)
2117
- Key outputs or artifacts produced
2118
- 3. Important Discoveries
2119
- Technical constraints or requirements uncovered
2120
- Decisions made and their rationale
2121
- Errors encountered and how they were resolved
2122
- What approaches were tried that didn't work (and why)
2123
- 4. Next Steps
2124
- Specific actions needed to complete the task
2125
- Any blockers or open questions to resolve
2126
- Priority order if multiple steps remain
2127
- 5. Context to Preserve
2128
- User preferences or style requirements
2129
- Domain-specific details that aren't obvious
2130
- Any promises made to the user
2131
- Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
2132
- Wrap your summary in <summary></summary> tags.`;
2133
- var oe, K, D, _, ce, x, N, q, le, Lt, ht;
2134
- function qt() {
2135
- let n, e;
2136
- return { promise: new Promise((s, r) => {
2137
- n = s, e = r;
2138
- }), resolve: n, reject: e };
2139
- }
2140
- class Ss {
2141
- constructor(e, t, s) {
2142
- oe.add(this), this.client = e, K.set(this, !1), D.set(this, !1), _.set(this, void 0), ce.set(this, void 0), x.set(this, void 0), N.set(this, void 0), q.set(this, void 0), le.set(this, 0), u(this, _, {
2143
- params: {
2144
- // You can't clone the entire params since there are functions as handlers.
2145
- // You also don't really need to clone params.messages, but it probably will prevent a foot gun
2146
- // somewhere.
2147
- ...t,
2148
- messages: structuredClone(t.messages)
2149
- }
2150
- }), u(this, ce, {
2151
- ...s,
2152
- headers: m([{ "x-stainless-helper": "BetaToolRunner" }, s?.headers])
2153
- }), u(this, q, qt());
2154
- }
2155
- async *[(K = /* @__PURE__ */ new WeakMap(), D = /* @__PURE__ */ new WeakMap(), _ = /* @__PURE__ */ new WeakMap(), ce = /* @__PURE__ */ new WeakMap(), x = /* @__PURE__ */ new WeakMap(), N = /* @__PURE__ */ new WeakMap(), q = /* @__PURE__ */ new WeakMap(), le = /* @__PURE__ */ new WeakMap(), oe = /* @__PURE__ */ new WeakSet(), Lt = async function() {
2156
- const t = a(this, _, "f").params.compactionControl;
2157
- if (!t || !t.enabled)
2158
- return !1;
2159
- let s = 0;
2160
- if (a(this, x, "f") !== void 0)
2161
- try {
2162
- const f = await a(this, x, "f");
2163
- s = f.usage.input_tokens + (f.usage.cache_creation_input_tokens ?? 0) + (f.usage.cache_read_input_tokens ?? 0) + f.usage.output_tokens;
2164
- } catch {
2165
- return !1;
2166
- }
2167
- const r = t.contextTokenThreshold ?? Mn;
2168
- if (s < r)
2169
- return !1;
2170
- const i = t.model ?? a(this, _, "f").params.model, o = t.summaryPrompt ?? Rn, c = a(this, _, "f").params.messages;
2171
- if (c[c.length - 1].role === "assistant") {
2172
- const f = c[c.length - 1];
2173
- if (Array.isArray(f.content)) {
2174
- const g = f.content.filter((y) => y.type !== "tool_use");
2175
- g.length === 0 ? c.pop() : f.content = g;
2176
- }
2177
- }
2178
- const h = await this.client.beta.messages.create({
2179
- model: i,
2180
- messages: [
2181
- ...c,
2182
- {
2183
- role: "user",
2184
- content: [
2185
- {
2186
- type: "text",
2187
- text: o
2188
- }
2189
- ]
2190
- }
2191
- ],
2192
- max_tokens: a(this, _, "f").params.max_tokens
2193
- }, {
2194
- headers: { "x-stainless-helper": "compaction" }
2195
- });
2196
- if (h.content[0]?.type !== "text")
2197
- throw new d("Expected text response for compaction");
2198
- return a(this, _, "f").params.messages = [
2199
- {
2200
- role: "user",
2201
- content: h.content
2202
- }
2203
- ], !0;
2204
- }, Symbol.asyncIterator)]() {
2205
- var e;
2206
- if (a(this, K, "f"))
2207
- throw new d("Cannot iterate over a consumed stream");
2208
- u(this, K, !0), u(this, D, !0), u(this, N, void 0);
2209
- try {
2210
- for (; ; ) {
2211
- let t;
2212
- try {
2213
- if (a(this, _, "f").params.max_iterations && a(this, le, "f") >= a(this, _, "f").params.max_iterations)
2214
- break;
2215
- u(this, D, !1, "f"), u(this, N, void 0, "f"), u(this, le, (e = a(this, le, "f"), e++, e), "f"), u(this, x, void 0, "f");
2216
- const { max_iterations: s, compactionControl: r, ...i } = a(this, _, "f").params;
2217
- if (i.stream ? (t = this.client.beta.messages.stream({ ...i }, a(this, ce, "f")), u(this, x, t.finalMessage(), "f"), a(this, x, "f").catch(() => {
2218
- }), yield t) : (u(this, x, this.client.beta.messages.create({ ...i, stream: !1 }, a(this, ce, "f")), "f"), yield a(this, x, "f")), !await a(this, oe, "m", Lt).call(this)) {
2219
- if (!a(this, D, "f")) {
2220
- const { role: h, content: f } = await a(this, x, "f");
2221
- a(this, _, "f").params.messages.push({ role: h, content: f });
2222
- }
2223
- const c = await a(this, oe, "m", ht).call(this, a(this, _, "f").params.messages.at(-1));
2224
- if (c)
2225
- a(this, _, "f").params.messages.push(c);
2226
- else if (!a(this, D, "f"))
2227
- break;
2228
- }
2229
- } finally {
2230
- t && t.abort();
2231
- }
2232
- }
2233
- if (!a(this, x, "f"))
2234
- throw new d("ToolRunner concluded without a message from the server");
2235
- a(this, q, "f").resolve(await a(this, x, "f"));
2236
- } catch (t) {
2237
- throw u(this, K, !1), a(this, q, "f").promise.catch(() => {
2238
- }), a(this, q, "f").reject(t), u(this, q, qt()), t;
2239
- }
2240
- }
2241
- setMessagesParams(e) {
2242
- typeof e == "function" ? a(this, _, "f").params = e(a(this, _, "f").params) : a(this, _, "f").params = e, u(this, D, !0), u(this, N, void 0);
2243
- }
2244
- /**
2245
- * Get the tool response for the last message from the assistant.
2246
- * Avoids redundant tool executions by caching results.
2247
- *
2248
- * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed
2249
- *
2250
- * @example
2251
- * const toolResponse = await runner.generateToolResponse();
2252
- * if (toolResponse) {
2253
- * console.log('Tool results:', toolResponse.content);
2254
- * }
2255
- */
2256
- async generateToolResponse() {
2257
- const e = await a(this, x, "f") ?? this.params.messages.at(-1);
2258
- return e ? a(this, oe, "m", ht).call(this, e) : null;
2259
- }
2260
- /**
2261
- * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and
2262
- * will wait for an instance to start and go to completion.
2263
- *
2264
- * @returns A promise that resolves to the final BetaMessage when the iterator completes
2265
- *
2266
- * @example
2267
- * // Start consuming the iterator
2268
- * for await (const message of runner) {
2269
- * console.log('Message:', message.content);
2270
- * }
2271
- *
2272
- * // Meanwhile, wait for completion from another part of the code
2273
- * const finalMessage = await runner.done();
2274
- * console.log('Final response:', finalMessage.content);
2275
- */
2276
- done() {
2277
- return a(this, q, "f").promise;
2278
- }
2279
- /**
2280
- * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream:
2281
- * * If the iterator has not been consumed, consume the entire iterator and return the final message from the
2282
- * assistant.
2283
- * * If the iterator has been consumed, waits for it to complete and returns the final message.
2284
- *
2285
- * @returns A promise that resolves to the final BetaMessage from the conversation
2286
- * @throws {AnthropicError} If no messages were processed during the conversation
2287
- *
2288
- * @example
2289
- * const finalMessage = await runner.runUntilDone();
2290
- * console.log('Final response:', finalMessage.content);
2291
- */
2292
- async runUntilDone() {
2293
- if (!a(this, K, "f"))
2294
- for await (const e of this)
2295
- ;
2296
- return this.done();
2297
- }
2298
- /**
2299
- * Get the current parameters being used by the ToolRunner.
2300
- *
2301
- * @returns A readonly view of the current ToolRunnerParams
2302
- *
2303
- * @example
2304
- * const currentParams = runner.params;
2305
- * console.log('Current model:', currentParams.model);
2306
- * console.log('Message count:', currentParams.messages.length);
2307
- */
2308
- get params() {
2309
- return a(this, _, "f").params;
2310
- }
2311
- /**
2312
- * Add one or more messages to the conversation history.
2313
- *
2314
- * @param messages - One or more BetaMessageParam objects to add to the conversation
2315
- *
2316
- * @example
2317
- * runner.pushMessages(
2318
- * { role: 'user', content: 'Also, what about the weather in NYC?' }
2319
- * );
2320
- *
2321
- * @example
2322
- * // Adding multiple messages
2323
- * runner.pushMessages(
2324
- * { role: 'user', content: 'What about NYC?' },
2325
- * { role: 'user', content: 'And Boston?' }
2326
- * );
2327
- */
2328
- pushMessages(...e) {
2329
- this.setMessagesParams((t) => ({
2330
- ...t,
2331
- messages: [...t.messages, ...e]
2332
- }));
2333
- }
2334
- /**
2335
- * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone()
2336
- * This allows using `await runner` instead of `await runner.runUntilDone()`
2337
- */
2338
- then(e, t) {
2339
- return this.runUntilDone().then(e, t);
2340
- }
2341
- }
2342
- ht = async function(e) {
2343
- return a(this, N, "f") !== void 0 ? a(this, N, "f") : (u(this, N, Pn(a(this, _, "f").params, e)), a(this, N, "f"));
2344
- };
2345
- async function Pn(n, e = n.messages.at(-1)) {
2346
- if (!e || e.role !== "assistant" || !e.content || typeof e.content == "string")
2347
- return null;
2348
- const t = e.content.filter((r) => r.type === "tool_use");
2349
- return t.length === 0 ? null : {
2350
- role: "user",
2351
- content: await Promise.all(t.map(async (r) => {
2352
- const i = n.tools.find((o) => ("name" in o ? o.name : o.mcp_server_name) === r.name);
2353
- if (!i || !("run" in i))
2354
- return {
2355
- type: "tool_result",
2356
- tool_use_id: r.id,
2357
- content: `Error: Tool '${r.name}' not found`,
2358
- is_error: !0
2359
- };
2360
- try {
2361
- let o = r.input;
2362
- "parse" in i && i.parse && (o = i.parse(o));
2363
- const c = await i.run(o);
2364
- return {
2365
- type: "tool_result",
2366
- tool_use_id: r.id,
2367
- content: c
2368
- };
2369
- } catch (o) {
2370
- return {
2371
- type: "tool_result",
2372
- tool_use_id: r.id,
2373
- content: `Error: ${o instanceof Error ? o.message : String(o)}`,
2374
- is_error: !0
2375
- };
2376
- }
2377
- }))
2378
- };
2379
- }
2380
- class He {
2381
- constructor(e, t) {
2382
- this.iterator = e, this.controller = t;
2383
- }
2384
- async *decoder() {
2385
- const e = new we();
2386
- for await (const t of this.iterator)
2387
- for (const s of e.decode(t))
2388
- yield JSON.parse(s);
2389
- for (const t of e.flush())
2390
- yield JSON.parse(t);
2391
- }
2392
- [Symbol.asyncIterator]() {
2393
- return this.decoder();
2394
- }
2395
- static fromResponse(e, t) {
2396
- if (!e.body)
2397
- throw t.abort(), typeof globalThis.navigator < "u" && globalThis.navigator.product === "ReactNative" ? new d("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api") : new d("Attempted to iterate over a response with no body");
2398
- return new He(ft(e.body), t);
2399
- }
2400
- }
2401
- let ks = class extends I {
2402
- /**
2403
- * Send a batch of Message creation requests.
2404
- *
2405
- * The Message Batches API can be used to process multiple Messages API requests at
2406
- * once. Once a Message Batch is created, it begins processing immediately. Batches
2407
- * can take up to 24 hours to complete.
2408
- *
2409
- * Learn more about the Message Batches API in our
2410
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
2411
- *
2412
- * @example
2413
- * ```ts
2414
- * const betaMessageBatch =
2415
- * await client.beta.messages.batches.create({
2416
- * requests: [
2417
- * {
2418
- * custom_id: 'my-custom-id-1',
2419
- * params: {
2420
- * max_tokens: 1024,
2421
- * messages: [
2422
- * { content: 'Hello, world', role: 'user' },
2423
- * ],
2424
- * model: 'claude-sonnet-4-5-20250929',
2425
- * },
2426
- * },
2427
- * ],
2428
- * });
2429
- * ```
2430
- */
2431
- create(e, t) {
2432
- const { betas: s, ...r } = e;
2433
- return this._client.post("/v1/messages/batches?beta=true", {
2434
- body: r,
2435
- ...t,
2436
- headers: m([
2437
- { "anthropic-beta": [...s ?? [], "message-batches-2024-09-24"].toString() },
2438
- t?.headers
2439
- ])
2440
- });
2441
- }
2442
- /**
2443
- * This endpoint is idempotent and can be used to poll for Message Batch
2444
- * completion. To access the results of a Message Batch, make a request to the
2445
- * `results_url` field in the response.
2446
- *
2447
- * Learn more about the Message Batches API in our
2448
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
2449
- *
2450
- * @example
2451
- * ```ts
2452
- * const betaMessageBatch =
2453
- * await client.beta.messages.batches.retrieve(
2454
- * 'message_batch_id',
2455
- * );
2456
- * ```
2457
- */
2458
- retrieve(e, t = {}, s) {
2459
- const { betas: r } = t ?? {};
2460
- return this._client.get(b`/v1/messages/batches/${e}?beta=true`, {
2461
- ...s,
2462
- headers: m([
2463
- { "anthropic-beta": [...r ?? [], "message-batches-2024-09-24"].toString() },
2464
- s?.headers
2465
- ])
2466
- });
2467
- }
2468
- /**
2469
- * List all Message Batches within a Workspace. Most recently created batches are
2470
- * returned first.
2471
- *
2472
- * Learn more about the Message Batches API in our
2473
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
2474
- *
2475
- * @example
2476
- * ```ts
2477
- * // Automatically fetches more pages as needed.
2478
- * for await (const betaMessageBatch of client.beta.messages.batches.list()) {
2479
- * // ...
2480
- * }
2481
- * ```
2482
- */
2483
- list(e = {}, t) {
2484
- const { betas: s, ...r } = e ?? {};
2485
- return this._client.getAPIList("/v1/messages/batches?beta=true", _e, {
2486
- query: r,
2487
- ...t,
2488
- headers: m([
2489
- { "anthropic-beta": [...s ?? [], "message-batches-2024-09-24"].toString() },
2490
- t?.headers
2491
- ])
2492
- });
2493
- }
2494
- /**
2495
- * Delete a Message Batch.
2496
- *
2497
- * Message Batches can only be deleted once they've finished processing. If you'd
2498
- * like to delete an in-progress batch, you must first cancel it.
2499
- *
2500
- * Learn more about the Message Batches API in our
2501
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
2502
- *
2503
- * @example
2504
- * ```ts
2505
- * const betaDeletedMessageBatch =
2506
- * await client.beta.messages.batches.delete(
2507
- * 'message_batch_id',
2508
- * );
2509
- * ```
2510
- */
2511
- delete(e, t = {}, s) {
2512
- const { betas: r } = t ?? {};
2513
- return this._client.delete(b`/v1/messages/batches/${e}?beta=true`, {
2514
- ...s,
2515
- headers: m([
2516
- { "anthropic-beta": [...r ?? [], "message-batches-2024-09-24"].toString() },
2517
- s?.headers
2518
- ])
2519
- });
2520
- }
2521
- /**
2522
- * Batches may be canceled any time before processing ends. Once cancellation is
2523
- * initiated, the batch enters a `canceling` state, at which time the system may
2524
- * complete any in-progress, non-interruptible requests before finalizing
2525
- * cancellation.
2526
- *
2527
- * The number of canceled requests is specified in `request_counts`. To determine
2528
- * which requests were canceled, check the individual results within the batch.
2529
- * Note that cancellation may not result in any canceled requests if they were
2530
- * non-interruptible.
2531
- *
2532
- * Learn more about the Message Batches API in our
2533
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
2534
- *
2535
- * @example
2536
- * ```ts
2537
- * const betaMessageBatch =
2538
- * await client.beta.messages.batches.cancel(
2539
- * 'message_batch_id',
2540
- * );
2541
- * ```
2542
- */
2543
- cancel(e, t = {}, s) {
2544
- const { betas: r } = t ?? {};
2545
- return this._client.post(b`/v1/messages/batches/${e}/cancel?beta=true`, {
2546
- ...s,
2547
- headers: m([
2548
- { "anthropic-beta": [...r ?? [], "message-batches-2024-09-24"].toString() },
2549
- s?.headers
2550
- ])
2551
- });
2552
- }
2553
- /**
2554
- * Streams the results of a Message Batch as a `.jsonl` file.
2555
- *
2556
- * Each line in the file is a JSON object containing the result of a single request
2557
- * in the Message Batch. Results are not guaranteed to be in the same order as
2558
- * requests. Use the `custom_id` field to match results to requests.
2559
- *
2560
- * Learn more about the Message Batches API in our
2561
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
2562
- *
2563
- * @example
2564
- * ```ts
2565
- * const betaMessageBatchIndividualResponse =
2566
- * await client.beta.messages.batches.results(
2567
- * 'message_batch_id',
2568
- * );
2569
- * ```
2570
- */
2571
- async results(e, t = {}, s) {
2572
- const r = await this.retrieve(e);
2573
- if (!r.results_url)
2574
- throw new d(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);
2575
- const { betas: i } = t ?? {};
2576
- return this._client.get(r.results_url, {
2577
- ...s,
2578
- headers: m([
2579
- {
2580
- "anthropic-beta": [...i ?? [], "message-batches-2024-09-24"].toString(),
2581
- Accept: "application/binary"
2582
- },
2583
- s?.headers
2584
- ]),
2585
- stream: !0,
2586
- __binaryResponse: !0
2587
- })._thenUnwrap((o, c) => He.fromResponse(c.response, c.controller));
2588
- }
2589
- };
2590
- const Wt = {
2591
- "claude-1.3": "November 6th, 2024",
2592
- "claude-1.3-100k": "November 6th, 2024",
2593
- "claude-instant-1.1": "November 6th, 2024",
2594
- "claude-instant-1.1-100k": "November 6th, 2024",
2595
- "claude-instant-1.2": "November 6th, 2024",
2596
- "claude-3-sonnet-20240229": "July 21st, 2025",
2597
- "claude-3-opus-20240229": "January 5th, 2026",
2598
- "claude-2.1": "July 21st, 2025",
2599
- "claude-2.0": "July 21st, 2025",
2600
- "claude-3-7-sonnet-latest": "February 19th, 2026",
2601
- "claude-3-7-sonnet-20250219": "February 19th, 2026"
2602
- };
2603
- let Je = class extends I {
2604
- constructor() {
2605
- super(...arguments), this.batches = new ks(this._client);
2606
- }
2607
- create(e, t) {
2608
- const { betas: s, ...r } = e;
2609
- r.model in Wt && console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${Wt[r.model]}
2610
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
2611
- let i = this._client._options.timeout;
2612
- if (!r.stream && i == null) {
2613
- const o = ws[r.model] ?? void 0;
2614
- i = this._client.calculateNonstreamingTimeout(r.max_tokens, o);
2615
- }
2616
- return this._client.post("/v1/messages?beta=true", {
2617
- body: r,
2618
- timeout: i ?? 6e5,
2619
- ...t,
2620
- headers: m([
2621
- { ...s?.toString() != null ? { "anthropic-beta": s?.toString() } : void 0 },
2622
- t?.headers
2623
- ]),
2624
- stream: e.stream ?? !1
2625
- });
2626
- }
2627
- /**
2628
- * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and
2629
- * the response will be automatically parsed and available in the `parsed_output` property of the message.
2630
- *
2631
- * @example
2632
- * ```ts
2633
- * const message = await client.beta.messages.parse({
2634
- * model: 'claude-3-5-sonnet-20241022',
2635
- * max_tokens: 1024,
2636
- * messages: [{ role: 'user', content: 'What is 2+2?' }],
2637
- * output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'),
2638
- * });
2639
- *
2640
- * console.log(message.parsed_output?.answer); // 4
2641
- * ```
2642
- */
2643
- parse(e, t) {
2644
- return t = {
2645
- ...t,
2646
- headers: m([
2647
- { "anthropic-beta": [...e.betas ?? [], "structured-outputs-2025-11-13"].toString() },
2648
- t?.headers
2649
- ])
2650
- }, this.create(e, t).then((s) => _s(s, e, { logger: this._client.logger ?? console }));
2651
- }
2652
- /**
2653
- * Create a Message stream
2654
- */
2655
- stream(e, t) {
2656
- return We.createMessage(this, e, t);
2657
- }
2658
- /**
2659
- * Count the number of tokens in a Message.
2660
- *
2661
- * The Token Count API can be used to count the number of tokens in a Message,
2662
- * including tools, images, and documents, without creating it.
2663
- *
2664
- * Learn more about token counting in our
2665
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
2666
- *
2667
- * @example
2668
- * ```ts
2669
- * const betaMessageTokensCount =
2670
- * await client.beta.messages.countTokens({
2671
- * messages: [{ content: 'string', role: 'user' }],
2672
- * model: 'claude-opus-4-5-20251101',
2673
- * });
2674
- * ```
2675
- */
2676
- countTokens(e, t) {
2677
- const { betas: s, ...r } = e;
2678
- return this._client.post("/v1/messages/count_tokens?beta=true", {
2679
- body: r,
2680
- ...t,
2681
- headers: m([
2682
- { "anthropic-beta": [...s ?? [], "token-counting-2024-11-01"].toString() },
2683
- t?.headers
2684
- ])
2685
- });
2686
- }
2687
- toolRunner(e, t) {
2688
- return new Ss(this._client, e, t);
2689
- }
2690
- };
2691
- Je.Batches = ks;
2692
- Je.BetaToolRunner = Ss;
2693
- class xs extends I {
2694
- /**
2695
- * Create Skill Version
2696
- *
2697
- * @example
2698
- * ```ts
2699
- * const version = await client.beta.skills.versions.create(
2700
- * 'skill_id',
2701
- * );
2702
- * ```
2703
- */
2704
- create(e, t = {}, s) {
2705
- const { betas: r, ...i } = t ?? {};
2706
- return this._client.post(b`/v1/skills/${e}/versions?beta=true`, mt({
2707
- body: i,
2708
- ...s,
2709
- headers: m([
2710
- { "anthropic-beta": [...r ?? [], "skills-2025-10-02"].toString() },
2711
- s?.headers
2712
- ])
2713
- }, this._client));
2714
- }
2715
- /**
2716
- * Get Skill Version
2717
- *
2718
- * @example
2719
- * ```ts
2720
- * const version = await client.beta.skills.versions.retrieve(
2721
- * 'version',
2722
- * { skill_id: 'skill_id' },
2723
- * );
2724
- * ```
2725
- */
2726
- retrieve(e, t, s) {
2727
- const { skill_id: r, betas: i } = t;
2728
- return this._client.get(b`/v1/skills/${r}/versions/${e}?beta=true`, {
2729
- ...s,
2730
- headers: m([
2731
- { "anthropic-beta": [...i ?? [], "skills-2025-10-02"].toString() },
2732
- s?.headers
2733
- ])
2734
- });
2735
- }
2736
- /**
2737
- * List Skill Versions
2738
- *
2739
- * @example
2740
- * ```ts
2741
- * // Automatically fetches more pages as needed.
2742
- * for await (const versionListResponse of client.beta.skills.versions.list(
2743
- * 'skill_id',
2744
- * )) {
2745
- * // ...
2746
- * }
2747
- * ```
2748
- */
2749
- list(e, t = {}, s) {
2750
- const { betas: r, ...i } = t ?? {};
2751
- return this._client.getAPIList(b`/v1/skills/${e}/versions?beta=true`, us, {
2752
- query: i,
2753
- ...s,
2754
- headers: m([
2755
- { "anthropic-beta": [...r ?? [], "skills-2025-10-02"].toString() },
2756
- s?.headers
2757
- ])
2758
- });
2759
- }
2760
- /**
2761
- * Delete Skill Version
2762
- *
2763
- * @example
2764
- * ```ts
2765
- * const version = await client.beta.skills.versions.delete(
2766
- * 'version',
2767
- * { skill_id: 'skill_id' },
2768
- * );
2769
- * ```
2770
- */
2771
- delete(e, t, s) {
2772
- const { skill_id: r, betas: i } = t;
2773
- return this._client.delete(b`/v1/skills/${r}/versions/${e}?beta=true`, {
2774
- ...s,
2775
- headers: m([
2776
- { "anthropic-beta": [...i ?? [], "skills-2025-10-02"].toString() },
2777
- s?.headers
2778
- ])
2779
- });
2780
- }
2781
- }
2782
- class gt extends I {
2783
- constructor() {
2784
- super(...arguments), this.versions = new xs(this._client);
2785
- }
2786
- /**
2787
- * Create Skill
2788
- *
2789
- * @example
2790
- * ```ts
2791
- * const skill = await client.beta.skills.create();
2792
- * ```
2793
- */
2794
- create(e = {}, t) {
2795
- const { betas: s, ...r } = e ?? {};
2796
- return this._client.post("/v1/skills?beta=true", mt({
2797
- body: r,
2798
- ...t,
2799
- headers: m([
2800
- { "anthropic-beta": [...s ?? [], "skills-2025-10-02"].toString() },
2801
- t?.headers
2802
- ])
2803
- }, this._client));
2804
- }
2805
- /**
2806
- * Get Skill
2807
- *
2808
- * @example
2809
- * ```ts
2810
- * const skill = await client.beta.skills.retrieve('skill_id');
2811
- * ```
2812
- */
2813
- retrieve(e, t = {}, s) {
2814
- const { betas: r } = t ?? {};
2815
- return this._client.get(b`/v1/skills/${e}?beta=true`, {
2816
- ...s,
2817
- headers: m([
2818
- { "anthropic-beta": [...r ?? [], "skills-2025-10-02"].toString() },
2819
- s?.headers
2820
- ])
2821
- });
2822
- }
2823
- /**
2824
- * List Skills
2825
- *
2826
- * @example
2827
- * ```ts
2828
- * // Automatically fetches more pages as needed.
2829
- * for await (const skillListResponse of client.beta.skills.list()) {
2830
- * // ...
2831
- * }
2832
- * ```
2833
- */
2834
- list(e = {}, t) {
2835
- const { betas: s, ...r } = e ?? {};
2836
- return this._client.getAPIList("/v1/skills?beta=true", us, {
2837
- query: r,
2838
- ...t,
2839
- headers: m([
2840
- { "anthropic-beta": [...s ?? [], "skills-2025-10-02"].toString() },
2841
- t?.headers
2842
- ])
2843
- });
2844
- }
2845
- /**
2846
- * Delete Skill
2847
- *
2848
- * @example
2849
- * ```ts
2850
- * const skill = await client.beta.skills.delete('skill_id');
2851
- * ```
2852
- */
2853
- delete(e, t = {}, s) {
2854
- const { betas: r } = t ?? {};
2855
- return this._client.delete(b`/v1/skills/${e}?beta=true`, {
2856
- ...s,
2857
- headers: m([
2858
- { "anthropic-beta": [...r ?? [], "skills-2025-10-02"].toString() },
2859
- s?.headers
2860
- ])
2861
- });
2862
- }
2863
- }
2864
- gt.Versions = xs;
2865
- class Z extends I {
2866
- constructor() {
2867
- super(...arguments), this.models = new ys(this._client), this.messages = new Je(this._client), this.files = new gs(this._client), this.skills = new gt(this._client);
2868
- }
2869
- }
2870
- Z.Models = ys;
2871
- Z.Messages = Je;
2872
- Z.Files = gs;
2873
- Z.Skills = gt;
2874
- class Ms extends I {
2875
- create(e, t) {
2876
- const { betas: s, ...r } = e;
2877
- return this._client.post("/v1/complete", {
2878
- body: r,
2879
- timeout: this._client._options.timeout ?? 6e5,
2880
- ...t,
2881
- headers: m([
2882
- { ...s?.toString() != null ? { "anthropic-beta": s?.toString() } : void 0 },
2883
- t?.headers
2884
- ]),
2885
- stream: e.stream ?? !1
2886
- });
2887
- }
2888
- }
2889
- var T, W, ue, Ae, he, de, Ie, fe, j, pe, $e, Oe, z, Be, Ce, et, Ft, tt, st, nt, rt, Ut;
2890
- const Dt = "__json_buf";
2891
- function zt(n) {
2892
- return n.type === "tool_use" || n.type === "server_tool_use";
2893
- }
2894
- class Fe {
2895
- constructor() {
2896
- T.add(this), this.messages = [], this.receivedMessages = [], W.set(this, void 0), this.controller = new AbortController(), ue.set(this, void 0), Ae.set(this, () => {
2897
- }), he.set(this, () => {
2898
- }), de.set(this, void 0), Ie.set(this, () => {
2899
- }), fe.set(this, () => {
2900
- }), j.set(this, {}), pe.set(this, !1), $e.set(this, !1), Oe.set(this, !1), z.set(this, !1), Be.set(this, void 0), Ce.set(this, void 0), tt.set(this, (e) => {
2901
- if (u(this, $e, !0), ye(e) && (e = new A()), e instanceof A)
2902
- return u(this, Oe, !0), this._emit("abort", e);
2903
- if (e instanceof d)
2904
- return this._emit("error", e);
2905
- if (e instanceof Error) {
2906
- const t = new d(e.message);
2907
- return t.cause = e, this._emit("error", t);
2908
- }
2909
- return this._emit("error", new d(String(e)));
2910
- }), u(this, ue, new Promise((e, t) => {
2911
- u(this, Ae, e, "f"), u(this, he, t, "f");
2912
- })), u(this, de, new Promise((e, t) => {
2913
- u(this, Ie, e, "f"), u(this, fe, t, "f");
2914
- })), a(this, ue, "f").catch(() => {
2915
- }), a(this, de, "f").catch(() => {
2916
- });
2917
- }
2918
- get response() {
2919
- return a(this, Be, "f");
2920
- }
2921
- get request_id() {
2922
- return a(this, Ce, "f");
2923
- }
2924
- /**
2925
- * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
2926
- * returned vie the `request-id` header which is useful for debugging requests and resporting
2927
- * issues to Anthropic.
2928
- *
2929
- * This is the same as the `APIPromise.withResponse()` method.
2930
- *
2931
- * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
2932
- * as no `Response` is available.
2933
- */
2934
- async withResponse() {
2935
- u(this, z, !0);
2936
- const e = await a(this, ue, "f");
2937
- if (!e)
2938
- throw new Error("Could not resolve a `Response` object");
2939
- return {
2940
- data: this,
2941
- response: e,
2942
- request_id: e.headers.get("request-id")
2943
- };
2944
- }
2945
- /**
2946
- * Intended for use on the frontend, consuming a stream produced with
2947
- * `.toReadableStream()` on the backend.
2948
- *
2949
- * Note that messages sent to the model do not appear in `.on('message')`
2950
- * in this context.
2951
- */
2952
- static fromReadableStream(e) {
2953
- const t = new Fe();
2954
- return t._run(() => t._fromReadableStream(e)), t;
2955
- }
2956
- static createMessage(e, t, s) {
2957
- const r = new Fe();
2958
- for (const i of t.messages)
2959
- r._addMessageParam(i);
2960
- return r._run(() => r._createMessage(e, { ...t, stream: !0 }, { ...s, headers: { ...s?.headers, "X-Stainless-Helper-Method": "stream" } })), r;
2961
- }
2962
- _run(e) {
2963
- e().then(() => {
2964
- this._emitFinal(), this._emit("end");
2965
- }, a(this, tt, "f"));
2966
- }
2967
- _addMessageParam(e) {
2968
- this.messages.push(e);
2969
- }
2970
- _addMessage(e, t = !0) {
2971
- this.receivedMessages.push(e), t && this._emit("message", e);
2972
- }
2973
- async _createMessage(e, t, s) {
2974
- const r = s?.signal;
2975
- let i;
2976
- r && (r.aborted && this.controller.abort(), i = this.controller.abort.bind(this.controller), r.addEventListener("abort", i));
2977
- try {
2978
- a(this, T, "m", st).call(this);
2979
- const { response: o, data: c } = await e.create({ ...t, stream: !0 }, { ...s, signal: this.controller.signal }).withResponse();
2980
- this._connected(o);
2981
- for await (const h of c)
2982
- a(this, T, "m", nt).call(this, h);
2983
- if (c.controller.signal?.aborted)
2984
- throw new A();
2985
- a(this, T, "m", rt).call(this);
2986
- } finally {
2987
- r && i && r.removeEventListener("abort", i);
2988
- }
2989
- }
2990
- _connected(e) {
2991
- this.ended || (u(this, Be, e), u(this, Ce, e?.headers.get("request-id")), a(this, Ae, "f").call(this, e), this._emit("connect"));
2992
- }
2993
- get ended() {
2994
- return a(this, pe, "f");
2995
- }
2996
- get errored() {
2997
- return a(this, $e, "f");
2998
- }
2999
- get aborted() {
3000
- return a(this, Oe, "f");
3001
- }
3002
- abort() {
3003
- this.controller.abort();
3004
- }
3005
- /**
3006
- * Adds the listener function to the end of the listeners array for the event.
3007
- * No checks are made to see if the listener has already been added. Multiple calls passing
3008
- * the same combination of event and listener will result in the listener being added, and
3009
- * called, multiple times.
3010
- * @returns this MessageStream, so that calls can be chained
3011
- */
3012
- on(e, t) {
3013
- return (a(this, j, "f")[e] || (a(this, j, "f")[e] = [])).push({ listener: t }), this;
3014
- }
3015
- /**
3016
- * Removes the specified listener from the listener array for the event.
3017
- * off() will remove, at most, one instance of a listener from the listener array. If any single
3018
- * listener has been added multiple times to the listener array for the specified event, then
3019
- * off() must be called multiple times to remove each instance.
3020
- * @returns this MessageStream, so that calls can be chained
3021
- */
3022
- off(e, t) {
3023
- const s = a(this, j, "f")[e];
3024
- if (!s)
3025
- return this;
3026
- const r = s.findIndex((i) => i.listener === t);
3027
- return r >= 0 && s.splice(r, 1), this;
3028
- }
3029
- /**
3030
- * Adds a one-time listener function for the event. The next time the event is triggered,
3031
- * this listener is removed and then invoked.
3032
- * @returns this MessageStream, so that calls can be chained
3033
- */
3034
- once(e, t) {
3035
- return (a(this, j, "f")[e] || (a(this, j, "f")[e] = [])).push({ listener: t, once: !0 }), this;
3036
- }
3037
- /**
3038
- * This is similar to `.once()`, but returns a Promise that resolves the next time
3039
- * the event is triggered, instead of calling a listener callback.
3040
- * @returns a Promise that resolves the next time given event is triggered,
3041
- * or rejects if an error is emitted. (If you request the 'error' event,
3042
- * returns a promise that resolves with the error).
3043
- *
3044
- * Example:
3045
- *
3046
- * const message = await stream.emitted('message') // rejects if the stream errors
3047
- */
3048
- emitted(e) {
3049
- return new Promise((t, s) => {
3050
- u(this, z, !0), e !== "error" && this.once("error", s), this.once(e, t);
3051
- });
3052
- }
3053
- async done() {
3054
- u(this, z, !0), await a(this, de, "f");
3055
- }
3056
- get currentMessage() {
3057
- return a(this, W, "f");
3058
- }
3059
- /**
3060
- * @returns a promise that resolves with the the final assistant Message response,
3061
- * or rejects if an error occurred or the stream ended prematurely without producing a Message.
3062
- */
3063
- async finalMessage() {
3064
- return await this.done(), a(this, T, "m", et).call(this);
3065
- }
3066
- /**
3067
- * @returns a promise that resolves with the the final assistant Message's text response, concatenated
3068
- * together if there are more than one text blocks.
3069
- * Rejects if an error occurred or the stream ended prematurely without producing a Message.
3070
- */
3071
- async finalText() {
3072
- return await this.done(), a(this, T, "m", Ft).call(this);
3073
- }
3074
- _emit(e, ...t) {
3075
- if (a(this, pe, "f"))
3076
- return;
3077
- e === "end" && (u(this, pe, !0), a(this, Ie, "f").call(this));
3078
- const s = a(this, j, "f")[e];
3079
- if (s && (a(this, j, "f")[e] = s.filter((r) => !r.once), s.forEach(({ listener: r }) => r(...t))), e === "abort") {
3080
- const r = t[0];
3081
- !a(this, z, "f") && !s?.length && Promise.reject(r), a(this, he, "f").call(this, r), a(this, fe, "f").call(this, r), this._emit("end");
3082
- return;
3083
- }
3084
- if (e === "error") {
3085
- const r = t[0];
3086
- !a(this, z, "f") && !s?.length && Promise.reject(r), a(this, he, "f").call(this, r), a(this, fe, "f").call(this, r), this._emit("end");
3087
- }
3088
- }
3089
- _emitFinal() {
3090
- this.receivedMessages.at(-1) && this._emit("finalMessage", a(this, T, "m", et).call(this));
3091
- }
3092
- async _fromReadableStream(e, t) {
3093
- const s = t?.signal;
3094
- let r;
3095
- s && (s.aborted && this.controller.abort(), r = this.controller.abort.bind(this.controller), s.addEventListener("abort", r));
3096
- try {
3097
- a(this, T, "m", st).call(this), this._connected(null);
3098
- const i = O.fromReadableStream(e, this.controller);
3099
- for await (const o of i)
3100
- a(this, T, "m", nt).call(this, o);
3101
- if (i.controller.signal?.aborted)
3102
- throw new A();
3103
- a(this, T, "m", rt).call(this);
3104
- } finally {
3105
- s && r && s.removeEventListener("abort", r);
3106
- }
3107
- }
3108
- [(W = /* @__PURE__ */ new WeakMap(), ue = /* @__PURE__ */ new WeakMap(), Ae = /* @__PURE__ */ new WeakMap(), he = /* @__PURE__ */ new WeakMap(), de = /* @__PURE__ */ new WeakMap(), Ie = /* @__PURE__ */ new WeakMap(), fe = /* @__PURE__ */ new WeakMap(), j = /* @__PURE__ */ new WeakMap(), pe = /* @__PURE__ */ new WeakMap(), $e = /* @__PURE__ */ new WeakMap(), Oe = /* @__PURE__ */ new WeakMap(), z = /* @__PURE__ */ new WeakMap(), Be = /* @__PURE__ */ new WeakMap(), Ce = /* @__PURE__ */ new WeakMap(), tt = /* @__PURE__ */ new WeakMap(), T = /* @__PURE__ */ new WeakSet(), et = function() {
3109
- if (this.receivedMessages.length === 0)
3110
- throw new d("stream ended without producing a Message with role=assistant");
3111
- return this.receivedMessages.at(-1);
3112
- }, Ft = function() {
3113
- if (this.receivedMessages.length === 0)
3114
- throw new d("stream ended without producing a Message with role=assistant");
3115
- const t = this.receivedMessages.at(-1).content.filter((s) => s.type === "text").map((s) => s.text);
3116
- if (t.length === 0)
3117
- throw new d("stream ended without producing a content block with type=text");
3118
- return t.join(" ");
3119
- }, st = function() {
3120
- this.ended || u(this, W, void 0);
3121
- }, nt = function(t) {
3122
- if (this.ended)
3123
- return;
3124
- const s = a(this, T, "m", Ut).call(this, t);
3125
- switch (this._emit("streamEvent", t, s), t.type) {
3126
- case "content_block_delta": {
3127
- const r = s.content.at(-1);
3128
- switch (t.delta.type) {
3129
- case "text_delta": {
3130
- r.type === "text" && this._emit("text", t.delta.text, r.text || "");
3131
- break;
3132
- }
3133
- case "citations_delta": {
3134
- r.type === "text" && this._emit("citation", t.delta.citation, r.citations ?? []);
3135
- break;
3136
- }
3137
- case "input_json_delta": {
3138
- zt(r) && r.input && this._emit("inputJson", t.delta.partial_json, r.input);
3139
- break;
3140
- }
3141
- case "thinking_delta": {
3142
- r.type === "thinking" && this._emit("thinking", t.delta.thinking, r.thinking);
3143
- break;
3144
- }
3145
- case "signature_delta": {
3146
- r.type === "thinking" && this._emit("signature", r.signature);
3147
- break;
3148
- }
3149
- default:
3150
- t.delta;
3151
- }
3152
- break;
3153
- }
3154
- case "message_stop": {
3155
- this._addMessageParam(s), this._addMessage(s, !0);
3156
- break;
3157
- }
3158
- case "content_block_stop": {
3159
- this._emit("contentBlock", s.content.at(-1));
3160
- break;
3161
- }
3162
- case "message_start": {
3163
- u(this, W, s);
3164
- break;
3165
- }
3166
- }
3167
- }, rt = function() {
3168
- if (this.ended)
3169
- throw new d("stream has ended, this shouldn't happen");
3170
- const t = a(this, W, "f");
3171
- if (!t)
3172
- throw new d("request ended without sending any chunks");
3173
- return u(this, W, void 0), t;
3174
- }, Ut = function(t) {
3175
- let s = a(this, W, "f");
3176
- if (t.type === "message_start") {
3177
- if (s)
3178
- throw new d(`Unexpected event order, got ${t.type} before receiving "message_stop"`);
3179
- return t.message;
3180
- }
3181
- if (!s)
3182
- throw new d(`Unexpected event order, got ${t.type} before "message_start"`);
3183
- switch (t.type) {
3184
- case "message_stop":
3185
- return s;
3186
- case "message_delta":
3187
- return s.stop_reason = t.delta.stop_reason, s.stop_sequence = t.delta.stop_sequence, s.usage.output_tokens = t.usage.output_tokens, t.usage.input_tokens != null && (s.usage.input_tokens = t.usage.input_tokens), t.usage.cache_creation_input_tokens != null && (s.usage.cache_creation_input_tokens = t.usage.cache_creation_input_tokens), t.usage.cache_read_input_tokens != null && (s.usage.cache_read_input_tokens = t.usage.cache_read_input_tokens), t.usage.server_tool_use != null && (s.usage.server_tool_use = t.usage.server_tool_use), s;
3188
- case "content_block_start":
3189
- return s.content.push({ ...t.content_block }), s;
3190
- case "content_block_delta": {
3191
- const r = s.content.at(t.index);
3192
- switch (t.delta.type) {
3193
- case "text_delta": {
3194
- r?.type === "text" && (s.content[t.index] = {
3195
- ...r,
3196
- text: (r.text || "") + t.delta.text
3197
- });
3198
- break;
3199
- }
3200
- case "citations_delta": {
3201
- r?.type === "text" && (s.content[t.index] = {
3202
- ...r,
3203
- citations: [...r.citations ?? [], t.delta.citation]
3204
- });
3205
- break;
3206
- }
3207
- case "input_json_delta": {
3208
- if (r && zt(r)) {
3209
- let i = r[Dt] || "";
3210
- i += t.delta.partial_json;
3211
- const o = { ...r };
3212
- Object.defineProperty(o, Dt, {
3213
- value: i,
3214
- enumerable: !1,
3215
- writable: !0
3216
- }), i && (o.input = bs(i)), s.content[t.index] = o;
3217
- }
3218
- break;
3219
- }
3220
- case "thinking_delta": {
3221
- r?.type === "thinking" && (s.content[t.index] = {
3222
- ...r,
3223
- thinking: r.thinking + t.delta.thinking
3224
- });
3225
- break;
3226
- }
3227
- case "signature_delta": {
3228
- r?.type === "thinking" && (s.content[t.index] = {
3229
- ...r,
3230
- signature: t.delta.signature
3231
- });
3232
- break;
3233
- }
3234
- default:
3235
- t.delta;
3236
- }
3237
- return s;
3238
- }
3239
- case "content_block_stop":
3240
- return s;
3241
- }
3242
- }, Symbol.asyncIterator)]() {
3243
- const e = [], t = [];
3244
- let s = !1;
3245
- return this.on("streamEvent", (r) => {
3246
- const i = t.shift();
3247
- i ? i.resolve(r) : e.push(r);
3248
- }), this.on("end", () => {
3249
- s = !0;
3250
- for (const r of t)
3251
- r.resolve(void 0);
3252
- t.length = 0;
3253
- }), this.on("abort", (r) => {
3254
- s = !0;
3255
- for (const i of t)
3256
- i.reject(r);
3257
- t.length = 0;
3258
- }), this.on("error", (r) => {
3259
- s = !0;
3260
- for (const i of t)
3261
- i.reject(r);
3262
- t.length = 0;
3263
- }), {
3264
- next: async () => e.length ? { value: e.shift(), done: !1 } : s ? { value: void 0, done: !0 } : new Promise((i, o) => t.push({ resolve: i, reject: o })).then((i) => i ? { value: i, done: !1 } : { value: void 0, done: !0 }),
3265
- return: async () => (this.abort(), { value: void 0, done: !0 })
3266
- };
3267
- }
3268
- toReadableStream() {
3269
- return new O(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream();
3270
- }
3271
- }
3272
- class Rs extends I {
3273
- /**
3274
- * Send a batch of Message creation requests.
3275
- *
3276
- * The Message Batches API can be used to process multiple Messages API requests at
3277
- * once. Once a Message Batch is created, it begins processing immediately. Batches
3278
- * can take up to 24 hours to complete.
3279
- *
3280
- * Learn more about the Message Batches API in our
3281
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
3282
- *
3283
- * @example
3284
- * ```ts
3285
- * const messageBatch = await client.messages.batches.create({
3286
- * requests: [
3287
- * {
3288
- * custom_id: 'my-custom-id-1',
3289
- * params: {
3290
- * max_tokens: 1024,
3291
- * messages: [
3292
- * { content: 'Hello, world', role: 'user' },
3293
- * ],
3294
- * model: 'claude-sonnet-4-5-20250929',
3295
- * },
3296
- * },
3297
- * ],
3298
- * });
3299
- * ```
3300
- */
3301
- create(e, t) {
3302
- return this._client.post("/v1/messages/batches", { body: e, ...t });
3303
- }
3304
- /**
3305
- * This endpoint is idempotent and can be used to poll for Message Batch
3306
- * completion. To access the results of a Message Batch, make a request to the
3307
- * `results_url` field in the response.
3308
- *
3309
- * Learn more about the Message Batches API in our
3310
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
3311
- *
3312
- * @example
3313
- * ```ts
3314
- * const messageBatch = await client.messages.batches.retrieve(
3315
- * 'message_batch_id',
3316
- * );
3317
- * ```
3318
- */
3319
- retrieve(e, t) {
3320
- return this._client.get(b`/v1/messages/batches/${e}`, t);
3321
- }
3322
- /**
3323
- * List all Message Batches within a Workspace. Most recently created batches are
3324
- * returned first.
3325
- *
3326
- * Learn more about the Message Batches API in our
3327
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
3328
- *
3329
- * @example
3330
- * ```ts
3331
- * // Automatically fetches more pages as needed.
3332
- * for await (const messageBatch of client.messages.batches.list()) {
3333
- * // ...
3334
- * }
3335
- * ```
3336
- */
3337
- list(e = {}, t) {
3338
- return this._client.getAPIList("/v1/messages/batches", _e, { query: e, ...t });
3339
- }
3340
- /**
3341
- * Delete a Message Batch.
3342
- *
3343
- * Message Batches can only be deleted once they've finished processing. If you'd
3344
- * like to delete an in-progress batch, you must first cancel it.
3345
- *
3346
- * Learn more about the Message Batches API in our
3347
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
3348
- *
3349
- * @example
3350
- * ```ts
3351
- * const deletedMessageBatch =
3352
- * await client.messages.batches.delete('message_batch_id');
3353
- * ```
3354
- */
3355
- delete(e, t) {
3356
- return this._client.delete(b`/v1/messages/batches/${e}`, t);
3357
- }
3358
- /**
3359
- * Batches may be canceled any time before processing ends. Once cancellation is
3360
- * initiated, the batch enters a `canceling` state, at which time the system may
3361
- * complete any in-progress, non-interruptible requests before finalizing
3362
- * cancellation.
3363
- *
3364
- * The number of canceled requests is specified in `request_counts`. To determine
3365
- * which requests were canceled, check the individual results within the batch.
3366
- * Note that cancellation may not result in any canceled requests if they were
3367
- * non-interruptible.
3368
- *
3369
- * Learn more about the Message Batches API in our
3370
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
3371
- *
3372
- * @example
3373
- * ```ts
3374
- * const messageBatch = await client.messages.batches.cancel(
3375
- * 'message_batch_id',
3376
- * );
3377
- * ```
3378
- */
3379
- cancel(e, t) {
3380
- return this._client.post(b`/v1/messages/batches/${e}/cancel`, t);
3381
- }
3382
- /**
3383
- * Streams the results of a Message Batch as a `.jsonl` file.
3384
- *
3385
- * Each line in the file is a JSON object containing the result of a single request
3386
- * in the Message Batch. Results are not guaranteed to be in the same order as
3387
- * requests. Use the `custom_id` field to match results to requests.
3388
- *
3389
- * Learn more about the Message Batches API in our
3390
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
3391
- *
3392
- * @example
3393
- * ```ts
3394
- * const messageBatchIndividualResponse =
3395
- * await client.messages.batches.results('message_batch_id');
3396
- * ```
3397
- */
3398
- async results(e, t) {
3399
- const s = await this.retrieve(e);
3400
- if (!s.results_url)
3401
- throw new d(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);
3402
- return this._client.get(s.results_url, {
3403
- ...t,
3404
- headers: m([{ Accept: "application/binary" }, t?.headers]),
3405
- stream: !0,
3406
- __binaryResponse: !0
3407
- })._thenUnwrap((r, i) => He.fromResponse(i.response, i.controller));
3408
- }
3409
- }
3410
- class yt extends I {
3411
- constructor() {
3412
- super(...arguments), this.batches = new Rs(this._client);
3413
- }
3414
- create(e, t) {
3415
- e.model in Ht && console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Ht[e.model]}
3416
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
3417
- let s = this._client._options.timeout;
3418
- if (!e.stream && s == null) {
3419
- const r = ws[e.model] ?? void 0;
3420
- s = this._client.calculateNonstreamingTimeout(e.max_tokens, r);
3421
- }
3422
- return this._client.post("/v1/messages", {
3423
- body: e,
3424
- timeout: s ?? 6e5,
3425
- ...t,
3426
- stream: e.stream ?? !1
3427
- });
3428
- }
3429
- /**
3430
- * Create a Message stream
3431
- */
3432
- stream(e, t) {
3433
- return Fe.createMessage(this, e, t);
3434
- }
3435
- /**
3436
- * Count the number of tokens in a Message.
3437
- *
3438
- * The Token Count API can be used to count the number of tokens in a Message,
3439
- * including tools, images, and documents, without creating it.
3440
- *
3441
- * Learn more about token counting in our
3442
- * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
3443
- *
3444
- * @example
3445
- * ```ts
3446
- * const messageTokensCount =
3447
- * await client.messages.countTokens({
3448
- * messages: [{ content: 'string', role: 'user' }],
3449
- * model: 'claude-opus-4-5-20251101',
3450
- * });
3451
- * ```
3452
- */
3453
- countTokens(e, t) {
3454
- return this._client.post("/v1/messages/count_tokens", { body: e, ...t });
3455
- }
3456
- }
3457
- const Ht = {
3458
- "claude-1.3": "November 6th, 2024",
3459
- "claude-1.3-100k": "November 6th, 2024",
3460
- "claude-instant-1.1": "November 6th, 2024",
3461
- "claude-instant-1.1-100k": "November 6th, 2024",
3462
- "claude-instant-1.2": "November 6th, 2024",
3463
- "claude-3-sonnet-20240229": "July 21st, 2025",
3464
- "claude-3-opus-20240229": "January 5th, 2026",
3465
- "claude-2.1": "July 21st, 2025",
3466
- "claude-2.0": "July 21st, 2025",
3467
- "claude-3-7-sonnet-latest": "February 19th, 2026",
3468
- "claude-3-7-sonnet-20250219": "February 19th, 2026"
3469
- };
3470
- yt.Batches = Rs;
3471
- class Ps extends I {
3472
- /**
3473
- * Get a specific model.
3474
- *
3475
- * The Models API response can be used to determine information about a specific
3476
- * model or resolve a model alias to a model ID.
3477
- */
3478
- retrieve(e, t = {}, s) {
3479
- const { betas: r } = t ?? {};
3480
- return this._client.get(b`/v1/models/${e}`, {
3481
- ...s,
3482
- headers: m([
3483
- { ...r?.toString() != null ? { "anthropic-beta": r?.toString() } : void 0 },
3484
- s?.headers
3485
- ])
3486
- });
3487
- }
3488
- /**
3489
- * List available models.
3490
- *
3491
- * The Models API response can be used to determine which models are available for
3492
- * use in the API. More recently released models are listed first.
3493
- */
3494
- list(e = {}, t) {
3495
- const { betas: s, ...r } = e ?? {};
3496
- return this._client.getAPIList("/v1/models", _e, {
3497
- query: r,
3498
- ...t,
3499
- headers: m([
3500
- { ...s?.toString() != null ? { "anthropic-beta": s?.toString() } : void 0 },
3501
- t?.headers
3502
- ])
3503
- });
3504
- }
3505
- }
3506
- const je = (n) => {
3507
- if (typeof globalThis.process < "u")
3508
- return globalThis.process.env?.[n]?.trim() ?? void 0;
3509
- if (typeof globalThis.Deno < "u")
3510
- return globalThis.Deno.env?.get?.(n)?.trim();
3511
- };
3512
- var dt, wt, Le, Ts;
3513
- const Tn = "\\n\\nHuman:", En = "\\n\\nAssistant:";
3514
- class w {
3515
- /**
3516
- * API Client for interfacing with the Anthropic API.
3517
- *
3518
- * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
3519
- * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
3520
- * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
3521
- * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
3522
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
3523
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
3524
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
3525
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
3526
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
3527
- * @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.
3528
- */
3529
- constructor({ baseURL: e = je("ANTHROPIC_BASE_URL"), apiKey: t = je("ANTHROPIC_API_KEY") ?? null, authToken: s = je("ANTHROPIC_AUTH_TOKEN") ?? null, ...r } = {}) {
3530
- dt.add(this), Le.set(this, void 0);
3531
- const i = {
3532
- apiKey: t,
3533
- authToken: s,
3534
- ...r,
3535
- baseURL: e || "https://api.anthropic.com"
3536
- };
3537
- if (!i.dangerouslyAllowBrowser && Xs())
3538
- throw new d(`It looks like you're running in a browser-like environment.
3539
-
3540
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
3541
- If you understand the risks and have appropriate mitigations in place,
3542
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
3543
-
3544
- new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
3545
- `);
3546
- this.baseURL = i.baseURL, this.timeout = i.timeout ?? wt.DEFAULT_TIMEOUT, this.logger = i.logger ?? console;
3547
- const o = "warn";
3548
- this.logLevel = o, this.logLevel = vt(i.logLevel, "ClientOptions.logLevel", this) ?? vt(je("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this) ?? o, this.fetchOptions = i.fetchOptions, this.maxRetries = i.maxRetries ?? 2, this.fetch = i.fetch ?? Ys(), u(this, Le, en), this._options = i, this.apiKey = typeof t == "string" ? t : null, this.authToken = s;
3549
- }
3550
- /**
3551
- * Create a new client instance re-using the same options given to the current client with optional overriding.
3552
- */
3553
- withOptions(e) {
3554
- return new this.constructor({
3555
- ...this._options,
3556
- baseURL: this.baseURL,
3557
- maxRetries: this.maxRetries,
3558
- timeout: this.timeout,
3559
- logger: this.logger,
3560
- logLevel: this.logLevel,
3561
- fetch: this.fetch,
3562
- fetchOptions: this.fetchOptions,
3563
- apiKey: this.apiKey,
3564
- authToken: this.authToken,
3565
- ...e
3566
- });
3567
- }
3568
- defaultQuery() {
3569
- return this._options.defaultQuery;
3570
- }
3571
- validateHeaders({ values: e, nulls: t }) {
3572
- if (!(e.get("x-api-key") || e.get("authorization")) && !(this.apiKey && e.get("x-api-key")) && !t.has("x-api-key") && !(this.authToken && e.get("authorization")) && !t.has("authorization"))
3573
- throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
3574
- }
3575
- async authHeaders(e) {
3576
- return m([await this.apiKeyAuth(e), await this.bearerAuth(e)]);
3577
- }
3578
- async apiKeyAuth(e) {
3579
- if (this.apiKey != null)
3580
- return m([{ "X-Api-Key": this.apiKey }]);
3581
- }
3582
- async bearerAuth(e) {
3583
- if (this.authToken != null)
3584
- return m([{ Authorization: `Bearer ${this.authToken}` }]);
3585
- }
3586
- /**
3587
- * Basic re-implementation of `qs.stringify` for primitive types.
3588
- */
3589
- stringifyQuery(e) {
3590
- return Object.entries(e).filter(([t, s]) => typeof s < "u").map(([t, s]) => {
3591
- if (typeof s == "string" || typeof s == "number" || typeof s == "boolean")
3592
- return `${encodeURIComponent(t)}=${encodeURIComponent(s)}`;
3593
- if (s === null)
3594
- return `${encodeURIComponent(t)}=`;
3595
- throw new d(`Cannot stringify type ${typeof s}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
3596
- }).join("&");
3597
- }
3598
- getUserAgent() {
3599
- return `${this.constructor.name}/JS ${V}`;
3600
- }
3601
- defaultIdempotencyKey() {
3602
- return `stainless-node-retry-${Kt()}`;
3603
- }
3604
- makeStatusError(e, t, s, r) {
3605
- return S.generate(e, t, s, r);
3606
- }
3607
- buildURL(e, t, s) {
3608
- const r = !a(this, dt, "m", Ts).call(this) && s || this.baseURL, i = Us(e) ? new URL(e) : new URL(r + (r.endsWith("/") && e.startsWith("/") ? e.slice(1) : e)), o = this.defaultQuery();
3609
- return Ds(o) || (t = { ...o, ...t }), typeof t == "object" && t && !Array.isArray(t) && (i.search = this.stringifyQuery(t)), i.toString();
3610
- }
3611
- _calculateNonstreamingTimeout(e) {
3612
- if (3600 * e / 128e3 > 600)
3613
- throw new d("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");
3614
- return 600 * 1e3;
3615
- }
3616
- /**
3617
- * Used as a callback for mutating the given `FinalRequestOptions` object.
3618
- */
3619
- async prepareOptions(e) {
3620
- }
3621
- /**
3622
- * Used as a callback for mutating the given `RequestInit` object.
3623
- *
3624
- * This is useful for cases where you want to add certain headers based off of
3625
- * the request properties, e.g. `method` or `url`.
3626
- */
3627
- async prepareRequest(e, { url: t, options: s }) {
3628
- }
3629
- get(e, t) {
3630
- return this.methodRequest("get", e, t);
3631
- }
3632
- post(e, t) {
3633
- return this.methodRequest("post", e, t);
3634
- }
3635
- patch(e, t) {
3636
- return this.methodRequest("patch", e, t);
3637
- }
3638
- put(e, t) {
3639
- return this.methodRequest("put", e, t);
3640
- }
3641
- delete(e, t) {
3642
- return this.methodRequest("delete", e, t);
3643
- }
3644
- methodRequest(e, t, s) {
3645
- return this.request(Promise.resolve(s).then((r) => ({ method: e, path: t, ...r })));
3646
- }
3647
- request(e, t = null) {
3648
- return new ze(this, this.makeRequest(e, t, void 0));
3649
- }
3650
- async makeRequest(e, t, s) {
3651
- const r = await e, i = r.maxRetries ?? this.maxRetries;
3652
- t == null && (t = i), await this.prepareOptions(r);
3653
- const { req: o, url: c, timeout: h } = await this.buildRequest(r, {
3654
- retryCount: i - t
3655
- });
3656
- await this.prepareRequest(o, { url: c, options: r });
3657
- const f = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"), g = s === void 0 ? "" : `, retryOf: ${s}`, y = Date.now();
3658
- if (k(this).debug(`[${f}] sending request`, H({
3659
- retryOfRequestLogID: s,
3660
- method: r.method,
3661
- url: c,
3662
- options: r,
3663
- headers: o.headers
3664
- })), r.signal?.aborted)
3665
- throw new A();
3666
- const E = new AbortController(), p = await this.fetchWithTimeout(c, o, h, E).catch(at), v = Date.now();
3667
- if (p instanceof globalThis.Error) {
3668
- const B = `retrying, ${t} attempts remaining`;
3669
- if (r.signal?.aborted)
3670
- throw new A();
3671
- const $ = ye(p) || /timed? ?out/i.test(String(p) + ("cause" in p ? String(p.cause) : ""));
3672
- if (t)
3673
- return k(this).info(`[${f}] connection ${$ ? "timed out" : "failed"} - ${B}`), k(this).debug(`[${f}] connection ${$ ? "timed out" : "failed"} (${B})`, H({
3674
- retryOfRequestLogID: s,
3675
- url: c,
3676
- durationMs: v - y,
3677
- message: p.message
3678
- })), this.retryRequest(r, t, s ?? f);
3679
- throw k(this).info(`[${f}] connection ${$ ? "timed out" : "failed"} - error; no more retries left`), k(this).debug(`[${f}] connection ${$ ? "timed out" : "failed"} (error; no more retries left)`, H({
3680
- retryOfRequestLogID: s,
3681
- url: c,
3682
- durationMs: v - y,
3683
- message: p.message
3684
- })), $ ? new Vt() : new De({ cause: p });
3685
- }
3686
- const Ke = [...p.headers.entries()].filter(([B]) => B === "request-id").map(([B, $]) => ", " + B + ": " + JSON.stringify($)).join(""), Ve = `[${f}${g}${Ke}] ${o.method} ${c} ${p.ok ? "succeeded" : "failed"} with status ${p.status} in ${v - y}ms`;
3687
- if (!p.ok) {
3688
- const B = await this.shouldRetry(p);
3689
- if (t && B) {
3690
- const be = `retrying, ${t} attempts remaining`;
3691
- return await Zs(p.body), k(this).info(`${Ve} - ${be}`), k(this).debug(`[${f}] response error (${be})`, H({
3692
- retryOfRequestLogID: s,
3693
- url: p.url,
3694
- status: p.status,
3695
- headers: p.headers,
3696
- durationMs: v - y
3697
- })), this.retryRequest(r, t, s ?? f, p.headers);
3698
- }
3699
- const $ = B ? "error; no more retries left" : "error; not retryable";
3700
- k(this).info(`${Ve} - ${$}`);
3701
- const _t = await p.text().catch((be) => at(be).message), bt = rs(_t), St = bt ? void 0 : _t;
3702
- throw k(this).debug(`[${f}] response error (${$})`, H({
3703
- retryOfRequestLogID: s,
3704
- url: p.url,
3705
- status: p.status,
3706
- headers: p.headers,
3707
- message: St,
3708
- durationMs: Date.now() - y
3709
- })), this.makeStatusError(p.status, bt, St, p.headers);
3710
- }
3711
- return k(this).info(Ve), k(this).debug(`[${f}] response start`, H({
3712
- retryOfRequestLogID: s,
3713
- url: p.url,
3714
- status: p.status,
3715
- headers: p.headers,
3716
- durationMs: v - y
3717
- })), { response: p, options: r, controller: E, requestLogID: f, retryOfRequestLogID: s, startTime: y };
3718
- }
3719
- getAPIList(e, t, s) {
3720
- return this.requestAPIList(t, { method: "get", path: e, ...s });
3721
- }
3722
- requestAPIList(e, t) {
3723
- const s = this.makeRequest(t, null, void 0);
3724
- return new un(this, s, e);
3725
- }
3726
- async fetchWithTimeout(e, t, s, r) {
3727
- const { signal: i, method: o, ...c } = t || {};
3728
- i && i.addEventListener("abort", () => r.abort());
3729
- const h = setTimeout(() => r.abort(), s), f = globalThis.ReadableStream && c.body instanceof globalThis.ReadableStream || typeof c.body == "object" && c.body !== null && Symbol.asyncIterator in c.body, g = {
3730
- signal: r.signal,
3731
- ...f ? { duplex: "half" } : {},
3732
- method: "GET",
3733
- ...c
3734
- };
3735
- o && (g.method = o.toUpperCase());
3736
- try {
3737
- return await this.fetch.call(void 0, e, g);
3738
- } finally {
3739
- clearTimeout(h);
3740
- }
3741
- }
3742
- async shouldRetry(e) {
3743
- const t = e.headers.get("x-should-retry");
3744
- return t === "true" ? !0 : t === "false" ? !1 : e.status === 408 || e.status === 409 || e.status === 429 || e.status >= 500;
3745
- }
3746
- async retryRequest(e, t, s, r) {
3747
- let i;
3748
- const o = r?.get("retry-after-ms");
3749
- if (o) {
3750
- const h = parseFloat(o);
3751
- Number.isNaN(h) || (i = h);
3752
- }
3753
- const c = r?.get("retry-after");
3754
- if (c && !i) {
3755
- const h = parseFloat(c);
3756
- Number.isNaN(h) ? i = Date.parse(c) - Date.now() : i = h * 1e3;
3757
- }
3758
- if (!(i && 0 <= i && i < 60 * 1e3)) {
3759
- const h = e.maxRetries ?? this.maxRetries;
3760
- i = this.calculateDefaultRetryTimeoutMillis(t, h);
3761
- }
3762
- return await Js(i), this.makeRequest(e, t - 1, s);
3763
- }
3764
- calculateDefaultRetryTimeoutMillis(e, t) {
3765
- const i = t - e, o = Math.min(0.5 * Math.pow(2, i), 8), c = 1 - Math.random() * 0.25;
3766
- return o * c * 1e3;
3767
- }
3768
- calculateNonstreamingTimeout(e, t) {
3769
- if (36e5 * e / 128e3 > 6e5 || t != null && e > t)
3770
- throw new d("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");
3771
- return 6e5;
3772
- }
3773
- async buildRequest(e, { retryCount: t = 0 } = {}) {
3774
- const s = { ...e }, { method: r, path: i, query: o, defaultBaseURL: c } = s, h = this.buildURL(i, o, c);
3775
- "timeout" in s && Hs("timeout", s.timeout), s.timeout = s.timeout ?? this.timeout;
3776
- const { bodyHeaders: f, body: g } = this.buildBody({ options: s }), y = await this.buildHeaders({ options: e, method: r, bodyHeaders: f, retryCount: t });
3777
- return { req: {
3778
- method: r,
3779
- headers: y,
3780
- ...s.signal && { signal: s.signal },
3781
- ...globalThis.ReadableStream && g instanceof globalThis.ReadableStream && { duplex: "half" },
3782
- ...g && { body: g },
3783
- ...this.fetchOptions ?? {},
3784
- ...s.fetchOptions ?? {}
3785
- }, url: h, timeout: s.timeout };
3786
- }
3787
- async buildHeaders({ options: e, method: t, bodyHeaders: s, retryCount: r }) {
3788
- let i = {};
3789
- this.idempotencyHeader && t !== "get" && (e.idempotencyKey || (e.idempotencyKey = this.defaultIdempotencyKey()), i[this.idempotencyHeader] = e.idempotencyKey);
3790
- const o = m([
3791
- i,
3792
- {
3793
- Accept: "application/json",
3794
- "User-Agent": this.getUserAgent(),
3795
- "X-Stainless-Retry-Count": String(r),
3796
- ...e.timeout ? { "X-Stainless-Timeout": String(Math.trunc(e.timeout / 1e3)) } : {},
3797
- ...Gs(),
3798
- ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0,
3799
- "anthropic-version": "2023-06-01"
3800
- },
3801
- await this.authHeaders(e),
3802
- this._options.defaultHeaders,
3803
- s,
3804
- e.headers
3805
- ]);
3806
- return this.validateHeaders(o), o.values;
3807
- }
3808
- buildBody({ options: { body: e, headers: t } }) {
3809
- if (!e)
3810
- return { bodyHeaders: void 0, body: void 0 };
3811
- const s = m([t]);
3812
- return (
3813
- // Pass raw type verbatim
3814
- ArrayBuffer.isView(e) || e instanceof ArrayBuffer || e instanceof DataView || typeof e == "string" && // Preserve legacy string encoding behavior for now
3815
- s.values.has("content-type") || // `Blob` is superset of `File`
3816
- globalThis.Blob && e instanceof globalThis.Blob || // `FormData` -> `multipart/form-data`
3817
- e instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
3818
- e instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
3819
- globalThis.ReadableStream && e instanceof globalThis.ReadableStream ? { bodyHeaders: void 0, body: e } : typeof e == "object" && (Symbol.asyncIterator in e || Symbol.iterator in e && "next" in e && typeof e.next == "function") ? { bodyHeaders: void 0, body: as(e) } : a(this, Le, "f").call(this, { body: e, headers: s })
3820
- );
3821
- }
3822
- }
3823
- wt = w, Le = /* @__PURE__ */ new WeakMap(), dt = /* @__PURE__ */ new WeakSet(), Ts = function() {
3824
- return this.baseURL !== "https://api.anthropic.com";
3825
- };
3826
- w.Anthropic = wt;
3827
- w.HUMAN_PROMPT = Tn;
3828
- w.AI_PROMPT = En;
3829
- w.DEFAULT_TIMEOUT = 6e5;
3830
- w.AnthropicError = d;
3831
- w.APIError = S;
3832
- w.APIConnectionError = De;
3833
- w.APIConnectionTimeoutError = Vt;
3834
- w.APIUserAbortError = A;
3835
- w.NotFoundError = Zt;
3836
- w.ConflictError = es;
3837
- w.RateLimitError = ss;
3838
- w.BadRequestError = Qt;
3839
- w.AuthenticationError = Gt;
3840
- w.InternalServerError = ns;
3841
- w.PermissionDeniedError = Yt;
3842
- w.UnprocessableEntityError = ts;
3843
- w.toFile = gn;
3844
- class Xe extends w {
3845
- constructor() {
3846
- super(...arguments), this.completions = new Ms(this), this.messages = new yt(this), this.models = new Ps(this), this.beta = new Z(this);
3847
- }
3848
- }
3849
- Xe.Completions = Ms;
3850
- Xe.Messages = yt;
3851
- Xe.Models = Ps;
3852
- Xe.Beta = Z;
3853
- export {
3854
- Xe as A,
3855
- Xt as T,
3856
- Cn as a,
3857
- Ue as c,
3858
- qs as g,
3859
- Ls as i,
3860
- jn as p,
3861
- Ws as u
3862
- };