openclaw-amem 1.1.0 → 1.1.1

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.
package/dist/index.js CHANGED
@@ -30,4231 +30,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/tslib.mjs
34
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
35
- if (kind === "m")
36
- throw new TypeError("Private method is not writable");
37
- if (kind === "a" && !f)
38
- throw new TypeError("Private accessor was defined without a setter");
39
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
40
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
41
- return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
42
- }
43
- function __classPrivateFieldGet(receiver, state, kind, f) {
44
- if (kind === "a" && !f)
45
- throw new TypeError("Private accessor was defined without a getter");
46
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
47
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
48
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
49
- }
50
- var init_tslib = __esm({
51
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"() {
52
- "use strict";
53
- }
54
- });
55
-
56
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs
57
- var uuid4;
58
- var init_uuid = __esm({
59
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"() {
60
- "use strict";
61
- uuid4 = function() {
62
- const { crypto: crypto2 } = globalThis;
63
- if (crypto2?.randomUUID) {
64
- uuid4 = crypto2.randomUUID.bind(crypto2);
65
- return crypto2.randomUUID();
66
- }
67
- const u8 = new Uint8Array(1);
68
- const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
69
- return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));
70
- };
71
- }
72
- });
73
-
74
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/errors.mjs
75
- function isAbortError(err) {
76
- return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
77
- ("name" in err && err.name === "AbortError" || // Expo fetch
78
- "message" in err && String(err.message).includes("FetchRequestCanceledException"));
79
- }
80
- var castToError;
81
- var init_errors = __esm({
82
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/errors.mjs"() {
83
- "use strict";
84
- castToError = (err) => {
85
- if (err instanceof Error)
86
- return err;
87
- if (typeof err === "object" && err !== null) {
88
- try {
89
- if (Object.prototype.toString.call(err) === "[object Error]") {
90
- const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
91
- if (err.stack)
92
- error.stack = err.stack;
93
- if (err.cause && !error.cause)
94
- error.cause = err.cause;
95
- if (err.name)
96
- error.name = err.name;
97
- return error;
98
- }
99
- } catch {
100
- }
101
- try {
102
- return new Error(JSON.stringify(err));
103
- } catch {
104
- }
105
- }
106
- return new Error(err);
107
- };
108
- }
109
- });
110
-
111
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/error.mjs
112
- var AnthropicError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError;
113
- var init_error = __esm({
114
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/error.mjs"() {
115
- "use strict";
116
- init_errors();
117
- AnthropicError = class extends Error {
118
- };
119
- APIError = class _APIError extends AnthropicError {
120
- constructor(status, error, message, headers) {
121
- super(`${_APIError.makeMessage(status, error, message)}`);
122
- this.status = status;
123
- this.headers = headers;
124
- this.requestID = headers?.get("request-id");
125
- this.error = error;
126
- }
127
- static makeMessage(status, error, message) {
128
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
129
- if (status && msg) {
130
- return `${status} ${msg}`;
131
- }
132
- if (status) {
133
- return `${status} status code (no body)`;
134
- }
135
- if (msg) {
136
- return msg;
137
- }
138
- return "(no status code or body)";
139
- }
140
- static generate(status, errorResponse, message, headers) {
141
- if (!status || !headers) {
142
- return new APIConnectionError({ message, cause: castToError(errorResponse) });
143
- }
144
- const error = errorResponse;
145
- if (status === 400) {
146
- return new BadRequestError(status, error, message, headers);
147
- }
148
- if (status === 401) {
149
- return new AuthenticationError(status, error, message, headers);
150
- }
151
- if (status === 403) {
152
- return new PermissionDeniedError(status, error, message, headers);
153
- }
154
- if (status === 404) {
155
- return new NotFoundError(status, error, message, headers);
156
- }
157
- if (status === 409) {
158
- return new ConflictError(status, error, message, headers);
159
- }
160
- if (status === 422) {
161
- return new UnprocessableEntityError(status, error, message, headers);
162
- }
163
- if (status === 429) {
164
- return new RateLimitError(status, error, message, headers);
165
- }
166
- if (status >= 500) {
167
- return new InternalServerError(status, error, message, headers);
168
- }
169
- return new _APIError(status, error, message, headers);
170
- }
171
- };
172
- APIUserAbortError = class extends APIError {
173
- constructor({ message } = {}) {
174
- super(void 0, void 0, message || "Request was aborted.", void 0);
175
- }
176
- };
177
- APIConnectionError = class extends APIError {
178
- constructor({ message, cause }) {
179
- super(void 0, void 0, message || "Connection error.", void 0);
180
- if (cause)
181
- this.cause = cause;
182
- }
183
- };
184
- APIConnectionTimeoutError = class extends APIConnectionError {
185
- constructor({ message } = {}) {
186
- super({ message: message ?? "Request timed out." });
187
- }
188
- };
189
- BadRequestError = class extends APIError {
190
- };
191
- AuthenticationError = class extends APIError {
192
- };
193
- PermissionDeniedError = class extends APIError {
194
- };
195
- NotFoundError = class extends APIError {
196
- };
197
- ConflictError = class extends APIError {
198
- };
199
- UnprocessableEntityError = class extends APIError {
200
- };
201
- RateLimitError = class extends APIError {
202
- };
203
- InternalServerError = class extends APIError {
204
- };
205
- }
206
- });
207
-
208
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs
209
- function maybeObj(x) {
210
- if (typeof x !== "object") {
211
- return {};
212
- }
213
- return x ?? {};
214
- }
215
- function isEmptyObj(obj) {
216
- if (!obj)
217
- return true;
218
- for (const _k in obj)
219
- return false;
220
- return true;
221
- }
222
- function hasOwn(obj, key) {
223
- return Object.prototype.hasOwnProperty.call(obj, key);
224
- }
225
- var startsWithSchemeRegexp, isAbsoluteURL, validatePositiveInteger, safeJSON;
226
- var init_values = __esm({
227
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"() {
228
- "use strict";
229
- init_error();
230
- startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
231
- isAbsoluteURL = (url) => {
232
- return startsWithSchemeRegexp.test(url);
233
- };
234
- validatePositiveInteger = (name, n) => {
235
- if (typeof n !== "number" || !Number.isInteger(n)) {
236
- throw new AnthropicError(`${name} must be an integer`);
237
- }
238
- if (n < 0) {
239
- throw new AnthropicError(`${name} must be a positive integer`);
240
- }
241
- return n;
242
- };
243
- safeJSON = (text) => {
244
- try {
245
- return JSON.parse(text);
246
- } catch (err) {
247
- return void 0;
248
- }
249
- };
250
- }
251
- });
252
-
253
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs
254
- var sleep;
255
- var init_sleep = __esm({
256
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"() {
257
- "use strict";
258
- sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
259
- }
260
- });
261
-
262
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs
263
- function noop() {
264
- }
265
- function makeLogFn(fnLevel, logger, logLevel) {
266
- if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
267
- return noop;
268
- } else {
269
- return logger[fnLevel].bind(logger);
270
- }
271
- }
272
- function loggerFor(client2) {
273
- const logger = client2.logger;
274
- const logLevel = client2.logLevel ?? "off";
275
- if (!logger) {
276
- return noopLogger;
277
- }
278
- const cachedLogger = cachedLoggers.get(logger);
279
- if (cachedLogger && cachedLogger[0] === logLevel) {
280
- return cachedLogger[1];
281
- }
282
- const levelLogger = {
283
- error: makeLogFn("error", logger, logLevel),
284
- warn: makeLogFn("warn", logger, logLevel),
285
- info: makeLogFn("info", logger, logLevel),
286
- debug: makeLogFn("debug", logger, logLevel)
287
- };
288
- cachedLoggers.set(logger, [logLevel, levelLogger]);
289
- return levelLogger;
290
- }
291
- var levelNumbers, parseLogLevel, noopLogger, cachedLoggers, formatRequestDetails;
292
- var init_log = __esm({
293
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"() {
294
- "use strict";
295
- init_values();
296
- levelNumbers = {
297
- off: 0,
298
- error: 200,
299
- warn: 300,
300
- info: 400,
301
- debug: 500
302
- };
303
- parseLogLevel = (maybeLevel, sourceName, client2) => {
304
- if (!maybeLevel) {
305
- return void 0;
306
- }
307
- if (hasOwn(levelNumbers, maybeLevel)) {
308
- return maybeLevel;
309
- }
310
- loggerFor(client2).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
311
- return void 0;
312
- };
313
- noopLogger = {
314
- error: noop,
315
- warn: noop,
316
- info: noop,
317
- debug: noop
318
- };
319
- cachedLoggers = /* @__PURE__ */ new WeakMap();
320
- formatRequestDetails = (details) => {
321
- if (details.options) {
322
- details.options = { ...details.options };
323
- delete details.options["headers"];
324
- }
325
- if (details.headers) {
326
- details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
327
- name,
328
- name.toLowerCase() === "x-api-key" || name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
329
- ]));
330
- }
331
- if ("retryOfRequestLogID" in details) {
332
- if (details.retryOfRequestLogID) {
333
- details.retryOf = details.retryOfRequestLogID;
334
- }
335
- delete details.retryOfRequestLogID;
336
- }
337
- return details;
338
- };
339
- }
340
- });
341
-
342
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/version.mjs
343
- var VERSION;
344
- var init_version = __esm({
345
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/version.mjs"() {
346
- "use strict";
347
- VERSION = "0.52.0";
348
- }
349
- });
350
-
351
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs
352
- function getDetectedPlatform() {
353
- if (typeof Deno !== "undefined" && Deno.build != null) {
354
- return "deno";
355
- }
356
- if (typeof EdgeRuntime !== "undefined") {
357
- return "edge";
358
- }
359
- if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
360
- return "node";
361
- }
362
- return "unknown";
363
- }
364
- function getBrowserInfo() {
365
- if (typeof navigator === "undefined" || !navigator) {
366
- return null;
367
- }
368
- const browserPatterns = [
369
- { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
370
- { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
371
- { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
372
- { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
373
- { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
374
- { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
375
- ];
376
- for (const { key, pattern } of browserPatterns) {
377
- const match = pattern.exec(navigator.userAgent);
378
- if (match) {
379
- const major = match[1] || 0;
380
- const minor = match[2] || 0;
381
- const patch = match[3] || 0;
382
- return { browser: key, version: `${major}.${minor}.${patch}` };
383
- }
384
- }
385
- return null;
386
- }
387
- var isRunningInBrowser, getPlatformProperties, normalizeArch, normalizePlatform, _platformHeaders, getPlatformHeaders;
388
- var init_detect_platform = __esm({
389
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"() {
390
- "use strict";
391
- init_version();
392
- isRunningInBrowser = () => {
393
- return (
394
- // @ts-ignore
395
- typeof window !== "undefined" && // @ts-ignore
396
- typeof window.document !== "undefined" && // @ts-ignore
397
- typeof navigator !== "undefined"
398
- );
399
- };
400
- getPlatformProperties = () => {
401
- const detectedPlatform = getDetectedPlatform();
402
- if (detectedPlatform === "deno") {
403
- return {
404
- "X-Stainless-Lang": "js",
405
- "X-Stainless-Package-Version": VERSION,
406
- "X-Stainless-OS": normalizePlatform(Deno.build.os),
407
- "X-Stainless-Arch": normalizeArch(Deno.build.arch),
408
- "X-Stainless-Runtime": "deno",
409
- "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
410
- };
411
- }
412
- if (typeof EdgeRuntime !== "undefined") {
413
- return {
414
- "X-Stainless-Lang": "js",
415
- "X-Stainless-Package-Version": VERSION,
416
- "X-Stainless-OS": "Unknown",
417
- "X-Stainless-Arch": `other:${EdgeRuntime}`,
418
- "X-Stainless-Runtime": "edge",
419
- "X-Stainless-Runtime-Version": globalThis.process.version
420
- };
421
- }
422
- if (detectedPlatform === "node") {
423
- return {
424
- "X-Stainless-Lang": "js",
425
- "X-Stainless-Package-Version": VERSION,
426
- "X-Stainless-OS": normalizePlatform(globalThis.process.platform),
427
- "X-Stainless-Arch": normalizeArch(globalThis.process.arch),
428
- "X-Stainless-Runtime": "node",
429
- "X-Stainless-Runtime-Version": globalThis.process.version
430
- };
431
- }
432
- const browserInfo = getBrowserInfo();
433
- if (browserInfo) {
434
- return {
435
- "X-Stainless-Lang": "js",
436
- "X-Stainless-Package-Version": VERSION,
437
- "X-Stainless-OS": "Unknown",
438
- "X-Stainless-Arch": "unknown",
439
- "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
440
- "X-Stainless-Runtime-Version": browserInfo.version
441
- };
442
- }
443
- return {
444
- "X-Stainless-Lang": "js",
445
- "X-Stainless-Package-Version": VERSION,
446
- "X-Stainless-OS": "Unknown",
447
- "X-Stainless-Arch": "unknown",
448
- "X-Stainless-Runtime": "unknown",
449
- "X-Stainless-Runtime-Version": "unknown"
450
- };
451
- };
452
- normalizeArch = (arch) => {
453
- if (arch === "x32")
454
- return "x32";
455
- if (arch === "x86_64" || arch === "x64")
456
- return "x64";
457
- if (arch === "arm")
458
- return "arm";
459
- if (arch === "aarch64" || arch === "arm64")
460
- return "arm64";
461
- if (arch)
462
- return `other:${arch}`;
463
- return "unknown";
464
- };
465
- normalizePlatform = (platform) => {
466
- platform = platform.toLowerCase();
467
- if (platform.includes("ios"))
468
- return "iOS";
469
- if (platform === "android")
470
- return "Android";
471
- if (platform === "darwin")
472
- return "MacOS";
473
- if (platform === "win32")
474
- return "Windows";
475
- if (platform === "freebsd")
476
- return "FreeBSD";
477
- if (platform === "openbsd")
478
- return "OpenBSD";
479
- if (platform === "linux")
480
- return "Linux";
481
- if (platform)
482
- return `Other:${platform}`;
483
- return "Unknown";
484
- };
485
- getPlatformHeaders = () => {
486
- return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
487
- };
488
- }
489
- });
490
-
491
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/shims.mjs
492
- function getDefaultFetch() {
493
- if (typeof fetch !== "undefined") {
494
- return fetch;
495
- }
496
- 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`");
497
- }
498
- function makeReadableStream(...args) {
499
- const ReadableStream = globalThis.ReadableStream;
500
- if (typeof ReadableStream === "undefined") {
501
- throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
502
- }
503
- return new ReadableStream(...args);
504
- }
505
- function ReadableStreamFrom(iterable) {
506
- let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
507
- return makeReadableStream({
508
- start() {
509
- },
510
- async pull(controller) {
511
- const { done, value } = await iter.next();
512
- if (done) {
513
- controller.close();
514
- } else {
515
- controller.enqueue(value);
516
- }
517
- },
518
- async cancel() {
519
- await iter.return?.();
520
- }
521
- });
522
- }
523
- function ReadableStreamToAsyncIterable(stream) {
524
- if (stream[Symbol.asyncIterator])
525
- return stream;
526
- const reader = stream.getReader();
527
- return {
528
- async next() {
529
- try {
530
- const result = await reader.read();
531
- if (result?.done)
532
- reader.releaseLock();
533
- return result;
534
- } catch (e) {
535
- reader.releaseLock();
536
- throw e;
537
- }
538
- },
539
- async return() {
540
- const cancelPromise = reader.cancel();
541
- reader.releaseLock();
542
- await cancelPromise;
543
- return { done: true, value: void 0 };
544
- },
545
- [Symbol.asyncIterator]() {
546
- return this;
547
- }
548
- };
549
- }
550
- async function CancelReadableStream(stream) {
551
- if (stream === null || typeof stream !== "object")
552
- return;
553
- if (stream[Symbol.asyncIterator]) {
554
- await stream[Symbol.asyncIterator]().return?.();
555
- return;
556
- }
557
- const reader = stream.getReader();
558
- const cancelPromise = reader.cancel();
559
- reader.releaseLock();
560
- await cancelPromise;
561
- }
562
- var init_shims = __esm({
563
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/shims.mjs"() {
564
- "use strict";
565
- }
566
- });
567
-
568
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/request-options.mjs
569
- var FallbackEncoder;
570
- var init_request_options = __esm({
571
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"() {
572
- "use strict";
573
- FallbackEncoder = ({ headers, body }) => {
574
- return {
575
- bodyHeaders: {
576
- "content-type": "application/json"
577
- },
578
- body: JSON.stringify(body)
579
- };
580
- };
581
- }
582
- });
583
-
584
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs
585
- function concatBytes(buffers) {
586
- let length = 0;
587
- for (const buffer of buffers) {
588
- length += buffer.length;
589
- }
590
- const output = new Uint8Array(length);
591
- let index = 0;
592
- for (const buffer of buffers) {
593
- output.set(buffer, index);
594
- index += buffer.length;
595
- }
596
- return output;
597
- }
598
- function encodeUTF8(str) {
599
- let encoder;
600
- return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str);
601
- }
602
- function decodeUTF8(bytes) {
603
- let decoder;
604
- return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes);
605
- }
606
- var encodeUTF8_, decodeUTF8_;
607
- var init_bytes = __esm({
608
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"() {
609
- "use strict";
610
- }
611
- });
612
-
613
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs
614
- function findNewlineIndex(buffer, startIndex) {
615
- const newline = 10;
616
- const carriage = 13;
617
- for (let i = startIndex ?? 0; i < buffer.length; i++) {
618
- if (buffer[i] === newline) {
619
- return { preceding: i, index: i + 1, carriage: false };
620
- }
621
- if (buffer[i] === carriage) {
622
- return { preceding: i, index: i + 1, carriage: true };
623
- }
624
- }
625
- return null;
626
- }
627
- function findDoubleNewlineIndex(buffer) {
628
- const newline = 10;
629
- const carriage = 13;
630
- for (let i = 0; i < buffer.length - 1; i++) {
631
- if (buffer[i] === newline && buffer[i + 1] === newline) {
632
- return i + 2;
633
- }
634
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
635
- return i + 2;
636
- }
637
- if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
638
- return i + 4;
639
- }
640
- }
641
- return -1;
642
- }
643
- var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex, LineDecoder;
644
- var init_line = __esm({
645
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"() {
646
- "use strict";
647
- init_tslib();
648
- init_bytes();
649
- LineDecoder = class {
650
- constructor() {
651
- _LineDecoder_buffer.set(this, void 0);
652
- _LineDecoder_carriageReturnIndex.set(this, void 0);
653
- __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
654
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
655
- }
656
- decode(chunk) {
657
- if (chunk == null) {
658
- return [];
659
- }
660
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
661
- __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f");
662
- const lines = [];
663
- let patternIndex;
664
- while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
665
- if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) {
666
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
667
- continue;
668
- }
669
- if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
670
- lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
671
- __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f");
672
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
673
- continue;
674
- }
675
- const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
676
- const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
677
- lines.push(line);
678
- __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f");
679
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
680
- }
681
- return lines;
682
- }
683
- flush() {
684
- if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
685
- return [];
686
- }
687
- return this.decode("\n");
688
- }
689
- };
690
- _LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex = /* @__PURE__ */ new WeakMap();
691
- LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
692
- LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
693
- }
694
- });
695
-
696
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/streaming.mjs
697
- async function* _iterSSEMessages(response, controller) {
698
- if (!response.body) {
699
- controller.abort();
700
- if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
701
- throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
702
- }
703
- throw new AnthropicError(`Attempted to iterate over a response with no body`);
704
- }
705
- const sseDecoder = new SSEDecoder();
706
- const lineDecoder = new LineDecoder();
707
- const iter = ReadableStreamToAsyncIterable(response.body);
708
- for await (const sseChunk of iterSSEChunks(iter)) {
709
- for (const line of lineDecoder.decode(sseChunk)) {
710
- const sse = sseDecoder.decode(line);
711
- if (sse)
712
- yield sse;
713
- }
714
- }
715
- for (const line of lineDecoder.flush()) {
716
- const sse = sseDecoder.decode(line);
717
- if (sse)
718
- yield sse;
719
- }
720
- }
721
- async function* iterSSEChunks(iterator) {
722
- let data = new Uint8Array();
723
- for await (const chunk of iterator) {
724
- if (chunk == null) {
725
- continue;
726
- }
727
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
728
- let newData = new Uint8Array(data.length + binaryChunk.length);
729
- newData.set(data);
730
- newData.set(binaryChunk, data.length);
731
- data = newData;
732
- let patternIndex;
733
- while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
734
- yield data.slice(0, patternIndex);
735
- data = data.slice(patternIndex);
736
- }
737
- }
738
- if (data.length > 0) {
739
- yield data;
740
- }
741
- }
742
- function partition(str, delimiter) {
743
- const index = str.indexOf(delimiter);
744
- if (index !== -1) {
745
- return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
746
- }
747
- return [str, "", ""];
748
- }
749
- var Stream, SSEDecoder;
750
- var init_streaming = __esm({
751
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/streaming.mjs"() {
752
- "use strict";
753
- init_error();
754
- init_shims();
755
- init_line();
756
- init_shims();
757
- init_errors();
758
- init_values();
759
- init_bytes();
760
- init_error();
761
- Stream = class _Stream {
762
- constructor(iterator, controller) {
763
- this.iterator = iterator;
764
- this.controller = controller;
765
- }
766
- static fromSSEResponse(response, controller) {
767
- let consumed = false;
768
- async function* iterator() {
769
- if (consumed) {
770
- throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
771
- }
772
- consumed = true;
773
- let done = false;
774
- try {
775
- for await (const sse of _iterSSEMessages(response, controller)) {
776
- if (sse.event === "completion") {
777
- try {
778
- yield JSON.parse(sse.data);
779
- } catch (e) {
780
- console.error(`Could not parse message into JSON:`, sse.data);
781
- console.error(`From chunk:`, sse.raw);
782
- throw e;
783
- }
784
- }
785
- if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
786
- try {
787
- yield JSON.parse(sse.data);
788
- } catch (e) {
789
- console.error(`Could not parse message into JSON:`, sse.data);
790
- console.error(`From chunk:`, sse.raw);
791
- throw e;
792
- }
793
- }
794
- if (sse.event === "ping") {
795
- continue;
796
- }
797
- if (sse.event === "error") {
798
- throw new APIError(void 0, safeJSON(sse.data) ?? sse.data, void 0, response.headers);
799
- }
800
- }
801
- done = true;
802
- } catch (e) {
803
- if (isAbortError(e))
804
- return;
805
- throw e;
806
- } finally {
807
- if (!done)
808
- controller.abort();
809
- }
810
- }
811
- return new _Stream(iterator, controller);
812
- }
813
- /**
814
- * Generates a Stream from a newline-separated ReadableStream
815
- * where each item is a JSON value.
816
- */
817
- static fromReadableStream(readableStream, controller) {
818
- let consumed = false;
819
- async function* iterLines() {
820
- const lineDecoder = new LineDecoder();
821
- const iter = ReadableStreamToAsyncIterable(readableStream);
822
- for await (const chunk of iter) {
823
- for (const line of lineDecoder.decode(chunk)) {
824
- yield line;
825
- }
826
- }
827
- for (const line of lineDecoder.flush()) {
828
- yield line;
829
- }
830
- }
831
- async function* iterator() {
832
- if (consumed) {
833
- throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
834
- }
835
- consumed = true;
836
- let done = false;
837
- try {
838
- for await (const line of iterLines()) {
839
- if (done)
840
- continue;
841
- if (line)
842
- yield JSON.parse(line);
843
- }
844
- done = true;
845
- } catch (e) {
846
- if (isAbortError(e))
847
- return;
848
- throw e;
849
- } finally {
850
- if (!done)
851
- controller.abort();
852
- }
853
- }
854
- return new _Stream(iterator, controller);
855
- }
856
- [Symbol.asyncIterator]() {
857
- return this.iterator();
858
- }
859
- /**
860
- * Splits the stream into two streams which can be
861
- * independently read from at different speeds.
862
- */
863
- tee() {
864
- const left = [];
865
- const right = [];
866
- const iterator = this.iterator();
867
- const teeIterator = (queue) => {
868
- return {
869
- next: () => {
870
- if (queue.length === 0) {
871
- const result = iterator.next();
872
- left.push(result);
873
- right.push(result);
874
- }
875
- return queue.shift();
876
- }
877
- };
878
- };
879
- return [
880
- new _Stream(() => teeIterator(left), this.controller),
881
- new _Stream(() => teeIterator(right), this.controller)
882
- ];
883
- }
884
- /**
885
- * Converts this stream to a newline-separated ReadableStream of
886
- * JSON stringified values in the stream
887
- * which can be turned back into a Stream with `Stream.fromReadableStream()`.
888
- */
889
- toReadableStream() {
890
- const self = this;
891
- let iter;
892
- return makeReadableStream({
893
- async start() {
894
- iter = self[Symbol.asyncIterator]();
895
- },
896
- async pull(ctrl) {
897
- try {
898
- const { value, done } = await iter.next();
899
- if (done)
900
- return ctrl.close();
901
- const bytes = encodeUTF8(JSON.stringify(value) + "\n");
902
- ctrl.enqueue(bytes);
903
- } catch (err) {
904
- ctrl.error(err);
905
- }
906
- },
907
- async cancel() {
908
- await iter.return?.();
909
- }
910
- });
911
- }
912
- };
913
- SSEDecoder = class {
914
- constructor() {
915
- this.event = null;
916
- this.data = [];
917
- this.chunks = [];
918
- }
919
- decode(line) {
920
- if (line.endsWith("\r")) {
921
- line = line.substring(0, line.length - 1);
922
- }
923
- if (!line) {
924
- if (!this.event && !this.data.length)
925
- return null;
926
- const sse = {
927
- event: this.event,
928
- data: this.data.join("\n"),
929
- raw: this.chunks
930
- };
931
- this.event = null;
932
- this.data = [];
933
- this.chunks = [];
934
- return sse;
935
- }
936
- this.chunks.push(line);
937
- if (line.startsWith(":")) {
938
- return null;
939
- }
940
- let [fieldname, _, value] = partition(line, ":");
941
- if (value.startsWith(" ")) {
942
- value = value.substring(1);
943
- }
944
- if (fieldname === "event") {
945
- this.event = value;
946
- } else if (fieldname === "data") {
947
- this.data.push(value);
948
- }
949
- return null;
950
- }
951
- };
952
- }
953
- });
954
-
955
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/parse.mjs
956
- async function defaultParseResponse(client2, props) {
957
- const { response, requestLogID, retryOfRequestLogID, startTime } = props;
958
- const body = await (async () => {
959
- if (props.options.stream) {
960
- loggerFor(client2).debug("response", response.status, response.url, response.headers, response.body);
961
- if (props.options.__streamClass) {
962
- return props.options.__streamClass.fromSSEResponse(response, props.controller);
963
- }
964
- return Stream.fromSSEResponse(response, props.controller);
965
- }
966
- if (response.status === 204) {
967
- return null;
968
- }
969
- if (props.options.__binaryResponse) {
970
- return response;
971
- }
972
- const contentType = response.headers.get("content-type");
973
- const mediaType = contentType?.split(";")[0]?.trim();
974
- const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
975
- if (isJSON) {
976
- const json = await response.json();
977
- return addRequestID(json, response);
978
- }
979
- const text = await response.text();
980
- return text;
981
- })();
982
- loggerFor(client2).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
983
- retryOfRequestLogID,
984
- url: response.url,
985
- status: response.status,
986
- body,
987
- durationMs: Date.now() - startTime
988
- }));
989
- return body;
990
- }
991
- function addRequestID(value, response) {
992
- if (!value || typeof value !== "object" || Array.isArray(value)) {
993
- return value;
994
- }
995
- return Object.defineProperty(value, "_request_id", {
996
- value: response.headers.get("request-id"),
997
- enumerable: false
998
- });
999
- }
1000
- var init_parse = __esm({
1001
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/parse.mjs"() {
1002
- "use strict";
1003
- init_streaming();
1004
- init_log();
1005
- }
1006
- });
1007
-
1008
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/api-promise.mjs
1009
- var _APIPromise_client, APIPromise;
1010
- var init_api_promise = __esm({
1011
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/api-promise.mjs"() {
1012
- "use strict";
1013
- init_tslib();
1014
- init_parse();
1015
- APIPromise = class _APIPromise extends Promise {
1016
- constructor(client2, responsePromise, parseResponse = defaultParseResponse) {
1017
- super((resolve) => {
1018
- resolve(null);
1019
- });
1020
- this.responsePromise = responsePromise;
1021
- this.parseResponse = parseResponse;
1022
- _APIPromise_client.set(this, void 0);
1023
- __classPrivateFieldSet(this, _APIPromise_client, client2, "f");
1024
- }
1025
- _thenUnwrap(transform) {
1026
- return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client2, props) => addRequestID(transform(await this.parseResponse(client2, props), props), props.response));
1027
- }
1028
- /**
1029
- * Gets the raw `Response` instance instead of parsing the response
1030
- * data.
1031
- *
1032
- * If you want to parse the response body but still get the `Response`
1033
- * instance, you can use {@link withResponse()}.
1034
- *
1035
- * 👋 Getting the wrong TypeScript type for `Response`?
1036
- * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
1037
- * to your `tsconfig.json`.
1038
- */
1039
- asResponse() {
1040
- return this.responsePromise.then((p) => p.response);
1041
- }
1042
- /**
1043
- * Gets the parsed response data, the raw `Response` instance and the ID of the request,
1044
- * returned via the `request-id` header which is useful for debugging requests and resporting
1045
- * issues to Anthropic.
1046
- *
1047
- * If you just want to get the raw `Response` instance without parsing it,
1048
- * you can use {@link asResponse()}.
1049
- *
1050
- * 👋 Getting the wrong TypeScript type for `Response`?
1051
- * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
1052
- * to your `tsconfig.json`.
1053
- */
1054
- async withResponse() {
1055
- const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
1056
- return { data, response, request_id: response.headers.get("request-id") };
1057
- }
1058
- parse() {
1059
- if (!this.parsedPromise) {
1060
- this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
1061
- }
1062
- return this.parsedPromise;
1063
- }
1064
- then(onfulfilled, onrejected) {
1065
- return this.parse().then(onfulfilled, onrejected);
1066
- }
1067
- catch(onrejected) {
1068
- return this.parse().catch(onrejected);
1069
- }
1070
- finally(onfinally) {
1071
- return this.parse().finally(onfinally);
1072
- }
1073
- };
1074
- _APIPromise_client = /* @__PURE__ */ new WeakMap();
1075
- }
1076
- });
1077
-
1078
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/pagination.mjs
1079
- var _AbstractPage_client, AbstractPage, PagePromise, Page;
1080
- var init_pagination = __esm({
1081
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/pagination.mjs"() {
1082
- "use strict";
1083
- init_tslib();
1084
- init_error();
1085
- init_parse();
1086
- init_api_promise();
1087
- init_values();
1088
- AbstractPage = class {
1089
- constructor(client2, response, body, options) {
1090
- _AbstractPage_client.set(this, void 0);
1091
- __classPrivateFieldSet(this, _AbstractPage_client, client2, "f");
1092
- this.options = options;
1093
- this.response = response;
1094
- this.body = body;
1095
- }
1096
- hasNextPage() {
1097
- const items = this.getPaginatedItems();
1098
- if (!items.length)
1099
- return false;
1100
- return this.nextPageRequestOptions() != null;
1101
- }
1102
- async getNextPage() {
1103
- const nextOptions = this.nextPageRequestOptions();
1104
- if (!nextOptions) {
1105
- throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
1106
- }
1107
- return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
1108
- }
1109
- async *iterPages() {
1110
- let page = this;
1111
- yield page;
1112
- while (page.hasNextPage()) {
1113
- page = await page.getNextPage();
1114
- yield page;
1115
- }
1116
- }
1117
- async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
1118
- for await (const page of this.iterPages()) {
1119
- for (const item of page.getPaginatedItems()) {
1120
- yield item;
1121
- }
1122
- }
1123
- }
1124
- };
1125
- PagePromise = class extends APIPromise {
1126
- constructor(client2, request, Page2) {
1127
- super(client2, request, async (client3, props) => new Page2(client3, props.response, await defaultParseResponse(client3, props), props.options));
1128
- }
1129
- /**
1130
- * Allow auto-paginating iteration on an unawaited list call, eg:
1131
- *
1132
- * for await (const item of client.items.list()) {
1133
- * console.log(item)
1134
- * }
1135
- */
1136
- async *[Symbol.asyncIterator]() {
1137
- const page = await this;
1138
- for await (const item of page) {
1139
- yield item;
1140
- }
1141
- }
1142
- };
1143
- Page = class extends AbstractPage {
1144
- constructor(client2, response, body, options) {
1145
- super(client2, response, body, options);
1146
- this.data = body.data || [];
1147
- this.has_more = body.has_more || false;
1148
- this.first_id = body.first_id || null;
1149
- this.last_id = body.last_id || null;
1150
- }
1151
- getPaginatedItems() {
1152
- return this.data ?? [];
1153
- }
1154
- hasNextPage() {
1155
- if (this.has_more === false) {
1156
- return false;
1157
- }
1158
- return super.hasNextPage();
1159
- }
1160
- nextPageRequestOptions() {
1161
- if (this.options.query?.["before_id"]) {
1162
- const first_id = this.first_id;
1163
- if (!first_id) {
1164
- return null;
1165
- }
1166
- return {
1167
- ...this.options,
1168
- query: {
1169
- ...maybeObj(this.options.query),
1170
- before_id: first_id
1171
- }
1172
- };
1173
- }
1174
- const cursor = this.last_id;
1175
- if (!cursor) {
1176
- return null;
1177
- }
1178
- return {
1179
- ...this.options,
1180
- query: {
1181
- ...maybeObj(this.options.query),
1182
- after_id: cursor
1183
- }
1184
- };
1185
- }
1186
- };
1187
- }
1188
- });
1189
-
1190
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/uploads.mjs
1191
- function makeFile(fileBits, fileName, options) {
1192
- checkFileSupport();
1193
- return new File(fileBits, fileName ?? "unknown_file", options);
1194
- }
1195
- function getName(value) {
1196
- return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0;
1197
- }
1198
- function supportsFormData(fetchObject) {
1199
- const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
1200
- const cached = supportsFormDataMap.get(fetch2);
1201
- if (cached)
1202
- return cached;
1203
- const promise = (async () => {
1204
- try {
1205
- const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor;
1206
- const data = new FormData();
1207
- if (data.toString() === await new FetchResponse(data).text()) {
1208
- return false;
1209
- }
1210
- return true;
1211
- } catch {
1212
- return true;
1213
- }
1214
- })();
1215
- supportsFormDataMap.set(fetch2, promise);
1216
- return promise;
1217
- }
1218
- var checkFileSupport, isAsyncIterable, multipartFormRequestOptions, supportsFormDataMap, createForm, isNamedBlob, addFormValue;
1219
- var init_uploads = __esm({
1220
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/uploads.mjs"() {
1221
- "use strict";
1222
- init_shims();
1223
- checkFileSupport = () => {
1224
- if (typeof File === "undefined") {
1225
- const { process: process2 } = globalThis;
1226
- const isOldNode = typeof process2?.versions?.node === "string" && parseInt(process2.versions.node.split(".")) < 20;
1227
- throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
1228
- }
1229
- };
1230
- isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
1231
- multipartFormRequestOptions = async (opts, fetch2) => {
1232
- return { ...opts, body: await createForm(opts.body, fetch2) };
1233
- };
1234
- supportsFormDataMap = /* @__PURE__ */ new WeakMap();
1235
- createForm = async (body, fetch2) => {
1236
- if (!await supportsFormData(fetch2)) {
1237
- throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
1238
- }
1239
- const form = new FormData();
1240
- await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
1241
- return form;
1242
- };
1243
- isNamedBlob = (value) => value instanceof Blob && "name" in value;
1244
- addFormValue = async (form, key, value) => {
1245
- if (value === void 0)
1246
- return;
1247
- if (value == null) {
1248
- throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
1249
- }
1250
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1251
- form.append(key, String(value));
1252
- } else if (value instanceof Response) {
1253
- let options = {};
1254
- const contentType = value.headers.get("Content-Type");
1255
- if (contentType) {
1256
- options = { type: contentType };
1257
- }
1258
- form.append(key, makeFile([await value.blob()], getName(value), options));
1259
- } else if (isAsyncIterable(value)) {
1260
- form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value)));
1261
- } else if (isNamedBlob(value)) {
1262
- form.append(key, makeFile([value], getName(value), { type: value.type }));
1263
- } else if (Array.isArray(value)) {
1264
- await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
1265
- } else if (typeof value === "object") {
1266
- await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
1267
- } else {
1268
- throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
1269
- }
1270
- };
1271
- }
1272
- });
1273
-
1274
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/to-file.mjs
1275
- async function toFile(value, name, options) {
1276
- checkFileSupport();
1277
- value = await value;
1278
- name || (name = getName(value));
1279
- if (isFileLike(value)) {
1280
- if (value instanceof File && name == null && options == null) {
1281
- return value;
1282
- }
1283
- return makeFile([await value.arrayBuffer()], name ?? value.name, {
1284
- type: value.type,
1285
- lastModified: value.lastModified,
1286
- ...options
1287
- });
1288
- }
1289
- if (isResponseLike(value)) {
1290
- const blob = await value.blob();
1291
- name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
1292
- return makeFile(await getBytes(blob), name, options);
1293
- }
1294
- const parts = await getBytes(value);
1295
- if (!options?.type) {
1296
- const type = parts.find((part) => typeof part === "object" && "type" in part && part.type);
1297
- if (typeof type === "string") {
1298
- options = { ...options, type };
1299
- }
1300
- }
1301
- return makeFile(parts, name, options);
1302
- }
1303
- async function getBytes(value) {
1304
- let parts = [];
1305
- if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
1306
- value instanceof ArrayBuffer) {
1307
- parts.push(value);
1308
- } else if (isBlobLike(value)) {
1309
- parts.push(value instanceof Blob ? value : await value.arrayBuffer());
1310
- } else if (isAsyncIterable(value)) {
1311
- for await (const chunk of value) {
1312
- parts.push(...await getBytes(chunk));
1313
- }
1314
- } else {
1315
- const constructor = value?.constructor?.name;
1316
- throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`);
1317
- }
1318
- return parts;
1319
- }
1320
- function propsForError(value) {
1321
- if (typeof value !== "object" || value === null)
1322
- return "";
1323
- const props = Object.getOwnPropertyNames(value);
1324
- return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`;
1325
- }
1326
- var isBlobLike, isFileLike, isResponseLike;
1327
- var init_to_file = __esm({
1328
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/to-file.mjs"() {
1329
- "use strict";
1330
- init_uploads();
1331
- init_uploads();
1332
- isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
1333
- isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value);
1334
- isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
1335
- }
1336
- });
1337
-
1338
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/uploads.mjs
1339
- var init_uploads2 = __esm({
1340
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/uploads.mjs"() {
1341
- "use strict";
1342
- init_to_file();
1343
- }
1344
- });
1345
-
1346
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/shared.mjs
1347
- var init_shared = __esm({
1348
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/shared.mjs"() {
1349
- "use strict";
1350
- }
1351
- });
1352
-
1353
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/resource.mjs
1354
- var APIResource;
1355
- var init_resource = __esm({
1356
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/core/resource.mjs"() {
1357
- "use strict";
1358
- APIResource = class {
1359
- constructor(client2) {
1360
- this._client = client2;
1361
- }
1362
- };
1363
- }
1364
- });
1365
-
1366
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/headers.mjs
1367
- function* iterateHeaders(headers) {
1368
- if (!headers)
1369
- return;
1370
- if (brand_privateNullableHeaders in headers) {
1371
- const { values, nulls } = headers;
1372
- yield* values.entries();
1373
- for (const name of nulls) {
1374
- yield [name, null];
1375
- }
1376
- return;
1377
- }
1378
- let shouldClear = false;
1379
- let iter;
1380
- if (headers instanceof Headers) {
1381
- iter = headers.entries();
1382
- } else if (isArray(headers)) {
1383
- iter = headers;
1384
- } else {
1385
- shouldClear = true;
1386
- iter = Object.entries(headers ?? {});
1387
- }
1388
- for (let row of iter) {
1389
- const name = row[0];
1390
- if (typeof name !== "string")
1391
- throw new TypeError("expected header name to be a string");
1392
- const values = isArray(row[1]) ? row[1] : [row[1]];
1393
- let didClear = false;
1394
- for (const value of values) {
1395
- if (value === void 0)
1396
- continue;
1397
- if (shouldClear && !didClear) {
1398
- didClear = true;
1399
- yield [name, null];
1400
- }
1401
- yield [name, value];
1402
- }
1403
- }
1404
- }
1405
- var brand_privateNullableHeaders, isArray, buildHeaders;
1406
- var init_headers = __esm({
1407
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/headers.mjs"() {
1408
- "use strict";
1409
- brand_privateNullableHeaders = /* @__PURE__ */ Symbol.for("brand.privateNullableHeaders");
1410
- isArray = Array.isArray;
1411
- buildHeaders = (newHeaders) => {
1412
- const targetHeaders = new Headers();
1413
- const nullHeaders = /* @__PURE__ */ new Set();
1414
- for (const headers of newHeaders) {
1415
- const seenHeaders = /* @__PURE__ */ new Set();
1416
- for (const [name, value] of iterateHeaders(headers)) {
1417
- const lowerName = name.toLowerCase();
1418
- if (!seenHeaders.has(lowerName)) {
1419
- targetHeaders.delete(name);
1420
- seenHeaders.add(lowerName);
1421
- }
1422
- if (value === null) {
1423
- targetHeaders.delete(name);
1424
- nullHeaders.add(lowerName);
1425
- } else {
1426
- targetHeaders.append(name, value);
1427
- nullHeaders.delete(lowerName);
1428
- }
1429
- }
1430
- }
1431
- return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
1432
- };
1433
- }
1434
- });
1435
-
1436
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs
1437
- function encodeURIPath(str) {
1438
- return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
1439
- }
1440
- var createPathTagFunction, path;
1441
- var init_path = __esm({
1442
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs"() {
1443
- "use strict";
1444
- init_error();
1445
- createPathTagFunction = (pathEncoder = encodeURIPath) => function path6(statics, ...params) {
1446
- if (statics.length === 1)
1447
- return statics[0];
1448
- let postPath = false;
1449
- const path7 = statics.reduce((previousValue, currentValue, index) => {
1450
- if (/[?#]/.test(currentValue)) {
1451
- postPath = true;
1452
- }
1453
- return previousValue + currentValue + (index === params.length ? "" : (postPath ? encodeURIComponent : pathEncoder)(String(params[index])));
1454
- }, "");
1455
- const pathOnly = path7.split(/[?#]/, 1)[0];
1456
- const invalidSegments = [];
1457
- const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
1458
- let match;
1459
- while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
1460
- invalidSegments.push({
1461
- start: match.index,
1462
- length: match[0].length
1463
- });
1464
- }
1465
- if (invalidSegments.length > 0) {
1466
- let lastEnd = 0;
1467
- const underline = invalidSegments.reduce((acc, segment) => {
1468
- const spaces = " ".repeat(segment.start - lastEnd);
1469
- const arrows = "^".repeat(segment.length);
1470
- lastEnd = segment.start + segment.length;
1471
- return acc + spaces + arrows;
1472
- }, "");
1473
- throw new AnthropicError(`Path parameters result in path with invalid segments:
1474
- ${path7}
1475
- ${underline}`);
1476
- }
1477
- return path7;
1478
- };
1479
- path = createPathTagFunction(encodeURIPath);
1480
- }
1481
- });
1482
-
1483
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs
1484
- var Files;
1485
- var init_files = __esm({
1486
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs"() {
1487
- "use strict";
1488
- init_resource();
1489
- init_pagination();
1490
- init_headers();
1491
- init_uploads();
1492
- init_path();
1493
- Files = class extends APIResource {
1494
- /**
1495
- * List Files
1496
- *
1497
- * @example
1498
- * ```ts
1499
- * // Automatically fetches more pages as needed.
1500
- * for await (const fileMetadata of client.beta.files.list()) {
1501
- * // ...
1502
- * }
1503
- * ```
1504
- */
1505
- list(params = {}, options) {
1506
- const { betas, ...query } = params ?? {};
1507
- return this._client.getAPIList("/v1/files", Page, {
1508
- query,
1509
- ...options,
1510
- headers: buildHeaders([
1511
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
1512
- options?.headers
1513
- ])
1514
- });
1515
- }
1516
- /**
1517
- * Delete File
1518
- *
1519
- * @example
1520
- * ```ts
1521
- * const deletedFile = await client.beta.files.delete(
1522
- * 'file_id',
1523
- * );
1524
- * ```
1525
- */
1526
- delete(fileID, params = {}, options) {
1527
- const { betas } = params ?? {};
1528
- return this._client.delete(path`/v1/files/${fileID}`, {
1529
- ...options,
1530
- headers: buildHeaders([
1531
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
1532
- options?.headers
1533
- ])
1534
- });
1535
- }
1536
- /**
1537
- * Download File
1538
- *
1539
- * @example
1540
- * ```ts
1541
- * const response = await client.beta.files.download(
1542
- * 'file_id',
1543
- * );
1544
- *
1545
- * const content = await response.blob();
1546
- * console.log(content);
1547
- * ```
1548
- */
1549
- download(fileID, params = {}, options) {
1550
- const { betas } = params ?? {};
1551
- return this._client.get(path`/v1/files/${fileID}/content`, {
1552
- ...options,
1553
- headers: buildHeaders([
1554
- {
1555
- "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(),
1556
- Accept: "application/binary"
1557
- },
1558
- options?.headers
1559
- ]),
1560
- __binaryResponse: true
1561
- });
1562
- }
1563
- /**
1564
- * Get File Metadata
1565
- *
1566
- * @example
1567
- * ```ts
1568
- * const fileMetadata =
1569
- * await client.beta.files.retrieveMetadata('file_id');
1570
- * ```
1571
- */
1572
- retrieveMetadata(fileID, params = {}, options) {
1573
- const { betas } = params ?? {};
1574
- return this._client.get(path`/v1/files/${fileID}`, {
1575
- ...options,
1576
- headers: buildHeaders([
1577
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
1578
- options?.headers
1579
- ])
1580
- });
1581
- }
1582
- /**
1583
- * Upload File
1584
- *
1585
- * @example
1586
- * ```ts
1587
- * const fileMetadata = await client.beta.files.upload({
1588
- * file: fs.createReadStream('path/to/file'),
1589
- * });
1590
- * ```
1591
- */
1592
- upload(params, options) {
1593
- const { betas, ...body } = params;
1594
- return this._client.post("/v1/files", multipartFormRequestOptions({
1595
- body,
1596
- ...options,
1597
- headers: buildHeaders([
1598
- { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() },
1599
- options?.headers
1600
- ])
1601
- }, this._client));
1602
- }
1603
- };
1604
- }
1605
- });
1606
-
1607
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs
1608
- var Models;
1609
- var init_models = __esm({
1610
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs"() {
1611
- "use strict";
1612
- init_resource();
1613
- init_pagination();
1614
- init_headers();
1615
- init_path();
1616
- Models = class extends APIResource {
1617
- /**
1618
- * Get a specific model.
1619
- *
1620
- * The Models API response can be used to determine information about a specific
1621
- * model or resolve a model alias to a model ID.
1622
- *
1623
- * @example
1624
- * ```ts
1625
- * const betaModelInfo = await client.beta.models.retrieve(
1626
- * 'model_id',
1627
- * );
1628
- * ```
1629
- */
1630
- retrieve(modelID, params = {}, options) {
1631
- const { betas } = params ?? {};
1632
- return this._client.get(path`/v1/models/${modelID}?beta=true`, {
1633
- ...options,
1634
- headers: buildHeaders([
1635
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
1636
- options?.headers
1637
- ])
1638
- });
1639
- }
1640
- /**
1641
- * List available models.
1642
- *
1643
- * The Models API response can be used to determine which models are available for
1644
- * use in the API. More recently released models are listed first.
1645
- *
1646
- * @example
1647
- * ```ts
1648
- * // Automatically fetches more pages as needed.
1649
- * for await (const betaModelInfo of client.beta.models.list()) {
1650
- * // ...
1651
- * }
1652
- * ```
1653
- */
1654
- list(params = {}, options) {
1655
- const { betas, ...query } = params ?? {};
1656
- return this._client.getAPIList("/v1/models?beta=true", Page, {
1657
- query,
1658
- ...options,
1659
- headers: buildHeaders([
1660
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
1661
- options?.headers
1662
- ])
1663
- });
1664
- }
1665
- };
1666
- }
1667
- });
1668
-
1669
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs
1670
- var JSONLDecoder;
1671
- var init_jsonl = __esm({
1672
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs"() {
1673
- "use strict";
1674
- init_error();
1675
- init_shims();
1676
- init_line();
1677
- JSONLDecoder = class _JSONLDecoder {
1678
- constructor(iterator, controller) {
1679
- this.iterator = iterator;
1680
- this.controller = controller;
1681
- }
1682
- async *decoder() {
1683
- const lineDecoder = new LineDecoder();
1684
- for await (const chunk of this.iterator) {
1685
- for (const line of lineDecoder.decode(chunk)) {
1686
- yield JSON.parse(line);
1687
- }
1688
- }
1689
- for (const line of lineDecoder.flush()) {
1690
- yield JSON.parse(line);
1691
- }
1692
- }
1693
- [Symbol.asyncIterator]() {
1694
- return this.decoder();
1695
- }
1696
- static fromResponse(response, controller) {
1697
- if (!response.body) {
1698
- controller.abort();
1699
- if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
1700
- throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
1701
- }
1702
- throw new AnthropicError(`Attempted to iterate over a response with no body`);
1703
- }
1704
- return new _JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller);
1705
- }
1706
- };
1707
- }
1708
- });
1709
-
1710
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/error.mjs
1711
- var init_error2 = __esm({
1712
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/error.mjs"() {
1713
- "use strict";
1714
- init_error();
1715
- }
1716
- });
1717
-
1718
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs
1719
- var Batches;
1720
- var init_batches = __esm({
1721
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs"() {
1722
- "use strict";
1723
- init_resource();
1724
- init_pagination();
1725
- init_headers();
1726
- init_jsonl();
1727
- init_error2();
1728
- init_path();
1729
- Batches = class extends APIResource {
1730
- /**
1731
- * Send a batch of Message creation requests.
1732
- *
1733
- * The Message Batches API can be used to process multiple Messages API requests at
1734
- * once. Once a Message Batch is created, it begins processing immediately. Batches
1735
- * can take up to 24 hours to complete.
1736
- *
1737
- * Learn more about the Message Batches API in our
1738
- * [user guide](/en/docs/build-with-claude/batch-processing)
1739
- *
1740
- * @example
1741
- * ```ts
1742
- * const betaMessageBatch =
1743
- * await client.beta.messages.batches.create({
1744
- * requests: [
1745
- * {
1746
- * custom_id: 'my-custom-id-1',
1747
- * params: {
1748
- * max_tokens: 1024,
1749
- * messages: [
1750
- * { content: 'Hello, world', role: 'user' },
1751
- * ],
1752
- * model: 'claude-3-7-sonnet-20250219',
1753
- * },
1754
- * },
1755
- * ],
1756
- * });
1757
- * ```
1758
- */
1759
- create(params, options) {
1760
- const { betas, ...body } = params;
1761
- return this._client.post("/v1/messages/batches?beta=true", {
1762
- body,
1763
- ...options,
1764
- headers: buildHeaders([
1765
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
1766
- options?.headers
1767
- ])
1768
- });
1769
- }
1770
- /**
1771
- * This endpoint is idempotent and can be used to poll for Message Batch
1772
- * completion. To access the results of a Message Batch, make a request to the
1773
- * `results_url` field in the response.
1774
- *
1775
- * Learn more about the Message Batches API in our
1776
- * [user guide](/en/docs/build-with-claude/batch-processing)
1777
- *
1778
- * @example
1779
- * ```ts
1780
- * const betaMessageBatch =
1781
- * await client.beta.messages.batches.retrieve(
1782
- * 'message_batch_id',
1783
- * );
1784
- * ```
1785
- */
1786
- retrieve(messageBatchID, params = {}, options) {
1787
- const { betas } = params ?? {};
1788
- return this._client.get(path`/v1/messages/batches/${messageBatchID}?beta=true`, {
1789
- ...options,
1790
- headers: buildHeaders([
1791
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
1792
- options?.headers
1793
- ])
1794
- });
1795
- }
1796
- /**
1797
- * List all Message Batches within a Workspace. Most recently created batches are
1798
- * returned first.
1799
- *
1800
- * Learn more about the Message Batches API in our
1801
- * [user guide](/en/docs/build-with-claude/batch-processing)
1802
- *
1803
- * @example
1804
- * ```ts
1805
- * // Automatically fetches more pages as needed.
1806
- * for await (const betaMessageBatch of client.beta.messages.batches.list()) {
1807
- * // ...
1808
- * }
1809
- * ```
1810
- */
1811
- list(params = {}, options) {
1812
- const { betas, ...query } = params ?? {};
1813
- return this._client.getAPIList("/v1/messages/batches?beta=true", Page, {
1814
- query,
1815
- ...options,
1816
- headers: buildHeaders([
1817
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
1818
- options?.headers
1819
- ])
1820
- });
1821
- }
1822
- /**
1823
- * Delete a Message Batch.
1824
- *
1825
- * Message Batches can only be deleted once they've finished processing. If you'd
1826
- * like to delete an in-progress batch, you must first cancel it.
1827
- *
1828
- * Learn more about the Message Batches API in our
1829
- * [user guide](/en/docs/build-with-claude/batch-processing)
1830
- *
1831
- * @example
1832
- * ```ts
1833
- * const betaDeletedMessageBatch =
1834
- * await client.beta.messages.batches.delete(
1835
- * 'message_batch_id',
1836
- * );
1837
- * ```
1838
- */
1839
- delete(messageBatchID, params = {}, options) {
1840
- const { betas } = params ?? {};
1841
- return this._client.delete(path`/v1/messages/batches/${messageBatchID}?beta=true`, {
1842
- ...options,
1843
- headers: buildHeaders([
1844
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
1845
- options?.headers
1846
- ])
1847
- });
1848
- }
1849
- /**
1850
- * Batches may be canceled any time before processing ends. Once cancellation is
1851
- * initiated, the batch enters a `canceling` state, at which time the system may
1852
- * complete any in-progress, non-interruptible requests before finalizing
1853
- * cancellation.
1854
- *
1855
- * The number of canceled requests is specified in `request_counts`. To determine
1856
- * which requests were canceled, check the individual results within the batch.
1857
- * Note that cancellation may not result in any canceled requests if they were
1858
- * non-interruptible.
1859
- *
1860
- * Learn more about the Message Batches API in our
1861
- * [user guide](/en/docs/build-with-claude/batch-processing)
1862
- *
1863
- * @example
1864
- * ```ts
1865
- * const betaMessageBatch =
1866
- * await client.beta.messages.batches.cancel(
1867
- * 'message_batch_id',
1868
- * );
1869
- * ```
1870
- */
1871
- cancel(messageBatchID, params = {}, options) {
1872
- const { betas } = params ?? {};
1873
- return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
1874
- ...options,
1875
- headers: buildHeaders([
1876
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
1877
- options?.headers
1878
- ])
1879
- });
1880
- }
1881
- /**
1882
- * Streams the results of a Message Batch as a `.jsonl` file.
1883
- *
1884
- * Each line in the file is a JSON object containing the result of a single request
1885
- * in the Message Batch. Results are not guaranteed to be in the same order as
1886
- * requests. Use the `custom_id` field to match results to requests.
1887
- *
1888
- * Learn more about the Message Batches API in our
1889
- * [user guide](/en/docs/build-with-claude/batch-processing)
1890
- *
1891
- * @example
1892
- * ```ts
1893
- * const betaMessageBatchIndividualResponse =
1894
- * await client.beta.messages.batches.results(
1895
- * 'message_batch_id',
1896
- * );
1897
- * ```
1898
- */
1899
- async results(messageBatchID, params = {}, options) {
1900
- const batch = await this.retrieve(messageBatchID);
1901
- if (!batch.results_url) {
1902
- throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
1903
- }
1904
- const { betas } = params ?? {};
1905
- return this._client.get(batch.results_url, {
1906
- ...options,
1907
- headers: buildHeaders([
1908
- {
1909
- "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
1910
- Accept: "application/binary"
1911
- },
1912
- options?.headers
1913
- ]),
1914
- stream: true,
1915
- __binaryResponse: true
1916
- })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
1917
- }
1918
- };
1919
- }
1920
- });
1921
-
1922
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/streaming.mjs
1923
- var init_streaming2 = __esm({
1924
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/streaming.mjs"() {
1925
- "use strict";
1926
- init_streaming();
1927
- }
1928
- });
1929
-
1930
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
1931
- var tokenize, strip, unstrip, generate, partialParse;
1932
- var init_parser = __esm({
1933
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs"() {
1934
- "use strict";
1935
- tokenize = (input) => {
1936
- let current = 0;
1937
- let tokens = [];
1938
- while (current < input.length) {
1939
- let char = input[current];
1940
- if (char === "\\") {
1941
- current++;
1942
- continue;
1943
- }
1944
- if (char === "{") {
1945
- tokens.push({
1946
- type: "brace",
1947
- value: "{"
1948
- });
1949
- current++;
1950
- continue;
1951
- }
1952
- if (char === "}") {
1953
- tokens.push({
1954
- type: "brace",
1955
- value: "}"
1956
- });
1957
- current++;
1958
- continue;
1959
- }
1960
- if (char === "[") {
1961
- tokens.push({
1962
- type: "paren",
1963
- value: "["
1964
- });
1965
- current++;
1966
- continue;
1967
- }
1968
- if (char === "]") {
1969
- tokens.push({
1970
- type: "paren",
1971
- value: "]"
1972
- });
1973
- current++;
1974
- continue;
1975
- }
1976
- if (char === ":") {
1977
- tokens.push({
1978
- type: "separator",
1979
- value: ":"
1980
- });
1981
- current++;
1982
- continue;
1983
- }
1984
- if (char === ",") {
1985
- tokens.push({
1986
- type: "delimiter",
1987
- value: ","
1988
- });
1989
- current++;
1990
- continue;
1991
- }
1992
- if (char === '"') {
1993
- let value = "";
1994
- let danglingQuote = false;
1995
- char = input[++current];
1996
- while (char !== '"') {
1997
- if (current === input.length) {
1998
- danglingQuote = true;
1999
- break;
2000
- }
2001
- if (char === "\\") {
2002
- current++;
2003
- if (current === input.length) {
2004
- danglingQuote = true;
2005
- break;
2006
- }
2007
- value += char + input[current];
2008
- char = input[++current];
2009
- } else {
2010
- value += char;
2011
- char = input[++current];
2012
- }
2013
- }
2014
- char = input[++current];
2015
- if (!danglingQuote) {
2016
- tokens.push({
2017
- type: "string",
2018
- value
2019
- });
2020
- }
2021
- continue;
2022
- }
2023
- let WHITESPACE = /\s/;
2024
- if (char && WHITESPACE.test(char)) {
2025
- current++;
2026
- continue;
2027
- }
2028
- let NUMBERS = /[0-9]/;
2029
- if (char && NUMBERS.test(char) || char === "-" || char === ".") {
2030
- let value = "";
2031
- if (char === "-") {
2032
- value += char;
2033
- char = input[++current];
2034
- }
2035
- while (char && NUMBERS.test(char) || char === ".") {
2036
- value += char;
2037
- char = input[++current];
2038
- }
2039
- tokens.push({
2040
- type: "number",
2041
- value
2042
- });
2043
- continue;
2044
- }
2045
- let LETTERS = /[a-z]/i;
2046
- if (char && LETTERS.test(char)) {
2047
- let value = "";
2048
- while (char && LETTERS.test(char)) {
2049
- if (current === input.length) {
2050
- break;
2051
- }
2052
- value += char;
2053
- char = input[++current];
2054
- }
2055
- if (value == "true" || value == "false" || value === "null") {
2056
- tokens.push({
2057
- type: "name",
2058
- value
2059
- });
2060
- } else {
2061
- current++;
2062
- continue;
2063
- }
2064
- continue;
2065
- }
2066
- current++;
2067
- }
2068
- return tokens;
2069
- };
2070
- strip = (tokens) => {
2071
- if (tokens.length === 0) {
2072
- return tokens;
2073
- }
2074
- let lastToken = tokens[tokens.length - 1];
2075
- switch (lastToken.type) {
2076
- case "separator":
2077
- tokens = tokens.slice(0, tokens.length - 1);
2078
- return strip(tokens);
2079
- break;
2080
- case "number":
2081
- let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
2082
- if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") {
2083
- tokens = tokens.slice(0, tokens.length - 1);
2084
- return strip(tokens);
2085
- }
2086
- case "string":
2087
- let tokenBeforeTheLastToken = tokens[tokens.length - 2];
2088
- if (tokenBeforeTheLastToken?.type === "delimiter") {
2089
- tokens = tokens.slice(0, tokens.length - 1);
2090
- return strip(tokens);
2091
- } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") {
2092
- tokens = tokens.slice(0, tokens.length - 1);
2093
- return strip(tokens);
2094
- }
2095
- break;
2096
- case "delimiter":
2097
- tokens = tokens.slice(0, tokens.length - 1);
2098
- return strip(tokens);
2099
- break;
2100
- }
2101
- return tokens;
2102
- };
2103
- unstrip = (tokens) => {
2104
- let tail = [];
2105
- tokens.map((token) => {
2106
- if (token.type === "brace") {
2107
- if (token.value === "{") {
2108
- tail.push("}");
2109
- } else {
2110
- tail.splice(tail.lastIndexOf("}"), 1);
2111
- }
2112
- }
2113
- if (token.type === "paren") {
2114
- if (token.value === "[") {
2115
- tail.push("]");
2116
- } else {
2117
- tail.splice(tail.lastIndexOf("]"), 1);
2118
- }
2119
- }
2120
- });
2121
- if (tail.length > 0) {
2122
- tail.reverse().map((item) => {
2123
- if (item === "}") {
2124
- tokens.push({
2125
- type: "brace",
2126
- value: "}"
2127
- });
2128
- } else if (item === "]") {
2129
- tokens.push({
2130
- type: "paren",
2131
- value: "]"
2132
- });
2133
- }
2134
- });
2135
- }
2136
- return tokens;
2137
- };
2138
- generate = (tokens) => {
2139
- let output = "";
2140
- tokens.map((token) => {
2141
- switch (token.type) {
2142
- case "string":
2143
- output += '"' + token.value + '"';
2144
- break;
2145
- default:
2146
- output += token.value;
2147
- break;
2148
- }
2149
- });
2150
- return output;
2151
- };
2152
- partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
2153
- }
2154
- });
2155
-
2156
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs
2157
- function checkNever(x) {
2158
- }
2159
- var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage, JSON_BUF_PROPERTY, BetaMessageStream;
2160
- var init_BetaMessageStream = __esm({
2161
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs"() {
2162
- "use strict";
2163
- init_tslib();
2164
- init_errors();
2165
- init_error2();
2166
- init_streaming2();
2167
- init_parser();
2168
- JSON_BUF_PROPERTY = "__json_buf";
2169
- BetaMessageStream = class _BetaMessageStream {
2170
- constructor() {
2171
- _BetaMessageStream_instances.add(this);
2172
- this.messages = [];
2173
- this.receivedMessages = [];
2174
- _BetaMessageStream_currentMessageSnapshot.set(this, void 0);
2175
- this.controller = new AbortController();
2176
- _BetaMessageStream_connectedPromise.set(this, void 0);
2177
- _BetaMessageStream_resolveConnectedPromise.set(this, () => {
2178
- });
2179
- _BetaMessageStream_rejectConnectedPromise.set(this, () => {
2180
- });
2181
- _BetaMessageStream_endPromise.set(this, void 0);
2182
- _BetaMessageStream_resolveEndPromise.set(this, () => {
2183
- });
2184
- _BetaMessageStream_rejectEndPromise.set(this, () => {
2185
- });
2186
- _BetaMessageStream_listeners.set(this, {});
2187
- _BetaMessageStream_ended.set(this, false);
2188
- _BetaMessageStream_errored.set(this, false);
2189
- _BetaMessageStream_aborted.set(this, false);
2190
- _BetaMessageStream_catchingPromiseCreated.set(this, false);
2191
- _BetaMessageStream_response.set(this, void 0);
2192
- _BetaMessageStream_request_id.set(this, void 0);
2193
- _BetaMessageStream_handleError.set(this, (error) => {
2194
- __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f");
2195
- if (isAbortError(error)) {
2196
- error = new APIUserAbortError();
2197
- }
2198
- if (error instanceof APIUserAbortError) {
2199
- __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f");
2200
- return this._emit("abort", error);
2201
- }
2202
- if (error instanceof AnthropicError) {
2203
- return this._emit("error", error);
2204
- }
2205
- if (error instanceof Error) {
2206
- const anthropicError = new AnthropicError(error.message);
2207
- anthropicError.cause = error;
2208
- return this._emit("error", anthropicError);
2209
- }
2210
- return this._emit("error", new AnthropicError(String(error)));
2211
- });
2212
- __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => {
2213
- __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f");
2214
- __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
2215
- }), "f");
2216
- __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => {
2217
- __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f");
2218
- __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f");
2219
- }), "f");
2220
- __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => {
2221
- });
2222
- __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => {
2223
- });
2224
- }
2225
- get response() {
2226
- return __classPrivateFieldGet(this, _BetaMessageStream_response, "f");
2227
- }
2228
- get request_id() {
2229
- return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f");
2230
- }
2231
- /**
2232
- * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
2233
- * returned vie the `request-id` header which is useful for debugging requests and resporting
2234
- * issues to Anthropic.
2235
- *
2236
- * This is the same as the `APIPromise.withResponse()` method.
2237
- *
2238
- * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
2239
- * as no `Response` is available.
2240
- */
2241
- async withResponse() {
2242
- const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f");
2243
- if (!response) {
2244
- throw new Error("Could not resolve a `Response` object");
2245
- }
2246
- return {
2247
- data: this,
2248
- response,
2249
- request_id: response.headers.get("request-id")
2250
- };
2251
- }
2252
- /**
2253
- * Intended for use on the frontend, consuming a stream produced with
2254
- * `.toReadableStream()` on the backend.
2255
- *
2256
- * Note that messages sent to the model do not appear in `.on('message')`
2257
- * in this context.
2258
- */
2259
- static fromReadableStream(stream) {
2260
- const runner = new _BetaMessageStream();
2261
- runner._run(() => runner._fromReadableStream(stream));
2262
- return runner;
2263
- }
2264
- static createMessage(messages, params, options) {
2265
- const runner = new _BetaMessageStream();
2266
- for (const message of params.messages) {
2267
- runner._addMessageParam(message);
2268
- }
2269
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
2270
- return runner;
2271
- }
2272
- _run(executor) {
2273
- executor().then(() => {
2274
- this._emitFinal();
2275
- this._emit("end");
2276
- }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f"));
2277
- }
2278
- _addMessageParam(message) {
2279
- this.messages.push(message);
2280
- }
2281
- _addMessage(message, emit = true) {
2282
- this.receivedMessages.push(message);
2283
- if (emit) {
2284
- this._emit("message", message);
2285
- }
2286
- }
2287
- async _createMessage(messages, params, options) {
2288
- const signal = options?.signal;
2289
- if (signal) {
2290
- if (signal.aborted)
2291
- this.controller.abort();
2292
- signal.addEventListener("abort", () => this.controller.abort());
2293
- }
2294
- __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
2295
- const { response, data: stream } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse();
2296
- this._connected(response);
2297
- for await (const event of stream) {
2298
- __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
2299
- }
2300
- if (stream.controller.signal?.aborted) {
2301
- throw new APIUserAbortError();
2302
- }
2303
- __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
2304
- }
2305
- _connected(response) {
2306
- if (this.ended)
2307
- return;
2308
- __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f");
2309
- __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f");
2310
- __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response);
2311
- this._emit("connect");
2312
- }
2313
- get ended() {
2314
- return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f");
2315
- }
2316
- get errored() {
2317
- return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f");
2318
- }
2319
- get aborted() {
2320
- return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f");
2321
- }
2322
- abort() {
2323
- this.controller.abort();
2324
- }
2325
- /**
2326
- * Adds the listener function to the end of the listeners array for the event.
2327
- * No checks are made to see if the listener has already been added. Multiple calls passing
2328
- * the same combination of event and listener will result in the listener being added, and
2329
- * called, multiple times.
2330
- * @returns this MessageStream, so that calls can be chained
2331
- */
2332
- on(event, listener) {
2333
- const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []);
2334
- listeners.push({ listener });
2335
- return this;
2336
- }
2337
- /**
2338
- * Removes the specified listener from the listener array for the event.
2339
- * off() will remove, at most, one instance of a listener from the listener array. If any single
2340
- * listener has been added multiple times to the listener array for the specified event, then
2341
- * off() must be called multiple times to remove each instance.
2342
- * @returns this MessageStream, so that calls can be chained
2343
- */
2344
- off(event, listener) {
2345
- const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event];
2346
- if (!listeners)
2347
- return this;
2348
- const index = listeners.findIndex((l) => l.listener === listener);
2349
- if (index >= 0)
2350
- listeners.splice(index, 1);
2351
- return this;
2352
- }
2353
- /**
2354
- * Adds a one-time listener function for the event. The next time the event is triggered,
2355
- * this listener is removed and then invoked.
2356
- * @returns this MessageStream, so that calls can be chained
2357
- */
2358
- once(event, listener) {
2359
- const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []);
2360
- listeners.push({ listener, once: true });
2361
- return this;
2362
- }
2363
- /**
2364
- * This is similar to `.once()`, but returns a Promise that resolves the next time
2365
- * the event is triggered, instead of calling a listener callback.
2366
- * @returns a Promise that resolves the next time given event is triggered,
2367
- * or rejects if an error is emitted. (If you request the 'error' event,
2368
- * returns a promise that resolves with the error).
2369
- *
2370
- * Example:
2371
- *
2372
- * const message = await stream.emitted('message') // rejects if the stream errors
2373
- */
2374
- emitted(event) {
2375
- return new Promise((resolve, reject) => {
2376
- __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
2377
- if (event !== "error")
2378
- this.once("error", reject);
2379
- this.once(event, resolve);
2380
- });
2381
- }
2382
- async done() {
2383
- __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
2384
- await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f");
2385
- }
2386
- get currentMessage() {
2387
- return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
2388
- }
2389
- /**
2390
- * @returns a promise that resolves with the the final assistant Message response,
2391
- * or rejects if an error occurred or the stream ended prematurely without producing a Message.
2392
- */
2393
- async finalMessage() {
2394
- await this.done();
2395
- return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this);
2396
- }
2397
- /**
2398
- * @returns a promise that resolves with the the final assistant Message's text response, concatenated
2399
- * together if there are more than one text blocks.
2400
- * Rejects if an error occurred or the stream ended prematurely without producing a Message.
2401
- */
2402
- async finalText() {
2403
- await this.done();
2404
- return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this);
2405
- }
2406
- _emit(event, ...args) {
2407
- if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f"))
2408
- return;
2409
- if (event === "end") {
2410
- __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f");
2411
- __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this);
2412
- }
2413
- const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event];
2414
- if (listeners) {
2415
- __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
2416
- listeners.forEach(({ listener }) => listener(...args));
2417
- }
2418
- if (event === "abort") {
2419
- const error = args[0];
2420
- if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2421
- Promise.reject(error);
2422
- }
2423
- __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
2424
- __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
2425
- this._emit("end");
2426
- return;
2427
- }
2428
- if (event === "error") {
2429
- const error = args[0];
2430
- if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2431
- Promise.reject(error);
2432
- }
2433
- __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
2434
- __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
2435
- this._emit("end");
2436
- }
2437
- }
2438
- _emitFinal() {
2439
- const finalMessage = this.receivedMessages.at(-1);
2440
- if (finalMessage) {
2441
- this._emit("finalMessage", __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this));
2442
- }
2443
- }
2444
- async _fromReadableStream(readableStream, options) {
2445
- const signal = options?.signal;
2446
- if (signal) {
2447
- if (signal.aborted)
2448
- this.controller.abort();
2449
- signal.addEventListener("abort", () => this.controller.abort());
2450
- }
2451
- __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
2452
- this._connected(null);
2453
- const stream = Stream.fromReadableStream(readableStream, this.controller);
2454
- for await (const event of stream) {
2455
- __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
2456
- }
2457
- if (stream.controller.signal?.aborted) {
2458
- throw new APIUserAbortError();
2459
- }
2460
- __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
2461
- }
2462
- [(_BetaMessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_listeners = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_ended = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_errored = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_aborted = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_response = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_request_id = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_handleError = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_instances = /* @__PURE__ */ new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage2() {
2463
- if (this.receivedMessages.length === 0) {
2464
- throw new AnthropicError("stream ended without producing a Message with role=assistant");
2465
- }
2466
- return this.receivedMessages.at(-1);
2467
- }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText2() {
2468
- if (this.receivedMessages.length === 0) {
2469
- throw new AnthropicError("stream ended without producing a Message with role=assistant");
2470
- }
2471
- const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
2472
- if (textBlocks.length === 0) {
2473
- throw new AnthropicError("stream ended without producing a content block with type=text");
2474
- }
2475
- return textBlocks.join(" ");
2476
- }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest2() {
2477
- if (this.ended)
2478
- return;
2479
- __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f");
2480
- }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent2(event) {
2481
- if (this.ended)
2482
- return;
2483
- const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event);
2484
- this._emit("streamEvent", event, messageSnapshot);
2485
- switch (event.type) {
2486
- case "content_block_delta": {
2487
- const content = messageSnapshot.content.at(-1);
2488
- switch (event.delta.type) {
2489
- case "text_delta": {
2490
- if (content.type === "text") {
2491
- this._emit("text", event.delta.text, content.text || "");
2492
- }
2493
- break;
2494
- }
2495
- case "citations_delta": {
2496
- if (content.type === "text") {
2497
- this._emit("citation", event.delta.citation, content.citations ?? []);
2498
- }
2499
- break;
2500
- }
2501
- case "input_json_delta": {
2502
- if ((content.type === "tool_use" || content.type === "mcp_tool_use") && content.input) {
2503
- this._emit("inputJson", event.delta.partial_json, content.input);
2504
- }
2505
- break;
2506
- }
2507
- case "thinking_delta": {
2508
- if (content.type === "thinking") {
2509
- this._emit("thinking", event.delta.thinking, content.thinking);
2510
- }
2511
- break;
2512
- }
2513
- case "signature_delta": {
2514
- if (content.type === "thinking") {
2515
- this._emit("signature", content.signature);
2516
- }
2517
- break;
2518
- }
2519
- default:
2520
- checkNever(event.delta);
2521
- }
2522
- break;
2523
- }
2524
- case "message_stop": {
2525
- this._addMessageParam(messageSnapshot);
2526
- this._addMessage(messageSnapshot, true);
2527
- break;
2528
- }
2529
- case "content_block_stop": {
2530
- this._emit("contentBlock", messageSnapshot.content.at(-1));
2531
- break;
2532
- }
2533
- case "message_start": {
2534
- __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f");
2535
- break;
2536
- }
2537
- case "content_block_start":
2538
- case "message_delta":
2539
- break;
2540
- }
2541
- }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest2() {
2542
- if (this.ended) {
2543
- throw new AnthropicError(`stream has ended, this shouldn't happen`);
2544
- }
2545
- const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
2546
- if (!snapshot) {
2547
- throw new AnthropicError(`request ended without sending any chunks`);
2548
- }
2549
- __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f");
2550
- return snapshot;
2551
- }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage2(event) {
2552
- let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
2553
- if (event.type === "message_start") {
2554
- if (snapshot) {
2555
- throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
2556
- }
2557
- return event.message;
2558
- }
2559
- if (!snapshot) {
2560
- throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
2561
- }
2562
- switch (event.type) {
2563
- case "message_stop":
2564
- return snapshot;
2565
- case "message_delta":
2566
- snapshot.container = event.delta.container;
2567
- snapshot.stop_reason = event.delta.stop_reason;
2568
- snapshot.stop_sequence = event.delta.stop_sequence;
2569
- snapshot.usage.output_tokens = event.usage.output_tokens;
2570
- if (event.usage.input_tokens != null) {
2571
- snapshot.usage.input_tokens = event.usage.input_tokens;
2572
- }
2573
- if (event.usage.cache_creation_input_tokens != null) {
2574
- snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
2575
- }
2576
- if (event.usage.cache_read_input_tokens != null) {
2577
- snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
2578
- }
2579
- if (event.usage.server_tool_use != null) {
2580
- snapshot.usage.server_tool_use = event.usage.server_tool_use;
2581
- }
2582
- return snapshot;
2583
- case "content_block_start":
2584
- snapshot.content.push(event.content_block);
2585
- return snapshot;
2586
- case "content_block_delta": {
2587
- const snapshotContent = snapshot.content.at(event.index);
2588
- switch (event.delta.type) {
2589
- case "text_delta": {
2590
- if (snapshotContent?.type === "text") {
2591
- snapshotContent.text += event.delta.text;
2592
- }
2593
- break;
2594
- }
2595
- case "citations_delta": {
2596
- if (snapshotContent?.type === "text") {
2597
- snapshotContent.citations ?? (snapshotContent.citations = []);
2598
- snapshotContent.citations.push(event.delta.citation);
2599
- }
2600
- break;
2601
- }
2602
- case "input_json_delta": {
2603
- if (snapshotContent?.type === "tool_use" || snapshotContent?.type === "mcp_tool_use") {
2604
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || "";
2605
- jsonBuf += event.delta.partial_json;
2606
- Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, {
2607
- value: jsonBuf,
2608
- enumerable: false,
2609
- writable: true
2610
- });
2611
- if (jsonBuf) {
2612
- snapshotContent.input = partialParse(jsonBuf);
2613
- }
2614
- }
2615
- break;
2616
- }
2617
- case "thinking_delta": {
2618
- if (snapshotContent?.type === "thinking") {
2619
- snapshotContent.thinking += event.delta.thinking;
2620
- }
2621
- break;
2622
- }
2623
- case "signature_delta": {
2624
- if (snapshotContent?.type === "thinking") {
2625
- snapshotContent.signature = event.delta.signature;
2626
- }
2627
- break;
2628
- }
2629
- default:
2630
- checkNever(event.delta);
2631
- }
2632
- return snapshot;
2633
- }
2634
- case "content_block_stop":
2635
- return snapshot;
2636
- }
2637
- }, Symbol.asyncIterator)]() {
2638
- const pushQueue = [];
2639
- const readQueue = [];
2640
- let done = false;
2641
- this.on("streamEvent", (event) => {
2642
- const reader = readQueue.shift();
2643
- if (reader) {
2644
- reader.resolve(event);
2645
- } else {
2646
- pushQueue.push(event);
2647
- }
2648
- });
2649
- this.on("end", () => {
2650
- done = true;
2651
- for (const reader of readQueue) {
2652
- reader.resolve(void 0);
2653
- }
2654
- readQueue.length = 0;
2655
- });
2656
- this.on("abort", (err) => {
2657
- done = true;
2658
- for (const reader of readQueue) {
2659
- reader.reject(err);
2660
- }
2661
- readQueue.length = 0;
2662
- });
2663
- this.on("error", (err) => {
2664
- done = true;
2665
- for (const reader of readQueue) {
2666
- reader.reject(err);
2667
- }
2668
- readQueue.length = 0;
2669
- });
2670
- return {
2671
- next: async () => {
2672
- if (!pushQueue.length) {
2673
- if (done) {
2674
- return { value: void 0, done: true };
2675
- }
2676
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
2677
- }
2678
- const chunk = pushQueue.shift();
2679
- return { value: chunk, done: false };
2680
- },
2681
- return: async () => {
2682
- this.abort();
2683
- return { value: void 0, done: true };
2684
- }
2685
- };
2686
- }
2687
- toReadableStream() {
2688
- const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
2689
- return stream.toReadableStream();
2690
- }
2691
- };
2692
- }
2693
- });
2694
-
2695
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/constants.mjs
2696
- var MODEL_NONSTREAMING_TOKENS;
2697
- var init_constants = __esm({
2698
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/constants.mjs"() {
2699
- "use strict";
2700
- MODEL_NONSTREAMING_TOKENS = {
2701
- "claude-opus-4-20250514": 8192,
2702
- "claude-opus-4-0": 8192,
2703
- "claude-4-opus-20250514": 8192,
2704
- "anthropic.claude-opus-4-20250514-v1:0": 8192,
2705
- "claude-opus-4@20250514": 8192
2706
- };
2707
- }
2708
- });
2709
-
2710
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs
2711
- var DEPRECATED_MODELS, Messages;
2712
- var init_messages = __esm({
2713
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs"() {
2714
- "use strict";
2715
- init_resource();
2716
- init_batches();
2717
- init_batches();
2718
- init_headers();
2719
- init_BetaMessageStream();
2720
- init_constants();
2721
- DEPRECATED_MODELS = {
2722
- "claude-1.3": "November 6th, 2024",
2723
- "claude-1.3-100k": "November 6th, 2024",
2724
- "claude-instant-1.1": "November 6th, 2024",
2725
- "claude-instant-1.1-100k": "November 6th, 2024",
2726
- "claude-instant-1.2": "November 6th, 2024",
2727
- "claude-3-sonnet-20240229": "July 21st, 2025",
2728
- "claude-2.1": "July 21st, 2025",
2729
- "claude-2.0": "July 21st, 2025"
2730
- };
2731
- Messages = class extends APIResource {
2732
- constructor() {
2733
- super(...arguments);
2734
- this.batches = new Batches(this._client);
2735
- }
2736
- create(params, options) {
2737
- const { betas, ...body } = params;
2738
- if (body.model in DEPRECATED_MODELS) {
2739
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}
2740
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
2741
- }
2742
- let timeout = this._client._options.timeout;
2743
- if (!body.stream && timeout == null) {
2744
- const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0;
2745
- timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
2746
- }
2747
- return this._client.post("/v1/messages?beta=true", {
2748
- body,
2749
- timeout: timeout ?? 6e5,
2750
- ...options,
2751
- headers: buildHeaders([
2752
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
2753
- options?.headers
2754
- ]),
2755
- stream: params.stream ?? false
2756
- });
2757
- }
2758
- /**
2759
- * Create a Message stream
2760
- */
2761
- stream(body, options) {
2762
- return BetaMessageStream.createMessage(this, body, options);
2763
- }
2764
- /**
2765
- * Count the number of tokens in a Message.
2766
- *
2767
- * The Token Count API can be used to count the number of tokens in a Message,
2768
- * including tools, images, and documents, without creating it.
2769
- *
2770
- * Learn more about token counting in our
2771
- * [user guide](/en/docs/build-with-claude/token-counting)
2772
- *
2773
- * @example
2774
- * ```ts
2775
- * const betaMessageTokensCount =
2776
- * await client.beta.messages.countTokens({
2777
- * messages: [{ content: 'string', role: 'user' }],
2778
- * model: 'claude-3-7-sonnet-latest',
2779
- * });
2780
- * ```
2781
- */
2782
- countTokens(params, options) {
2783
- const { betas, ...body } = params;
2784
- return this._client.post("/v1/messages/count_tokens?beta=true", {
2785
- body,
2786
- ...options,
2787
- headers: buildHeaders([
2788
- { "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString() },
2789
- options?.headers
2790
- ])
2791
- });
2792
- }
2793
- };
2794
- Messages.Batches = Batches;
2795
- }
2796
- });
2797
-
2798
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
2799
- var Beta;
2800
- var init_beta = __esm({
2801
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs"() {
2802
- "use strict";
2803
- init_resource();
2804
- init_files();
2805
- init_files();
2806
- init_models();
2807
- init_models();
2808
- init_messages();
2809
- init_messages();
2810
- Beta = class extends APIResource {
2811
- constructor() {
2812
- super(...arguments);
2813
- this.models = new Models(this._client);
2814
- this.messages = new Messages(this._client);
2815
- this.files = new Files(this._client);
2816
- }
2817
- };
2818
- Beta.Models = Models;
2819
- Beta.Messages = Messages;
2820
- Beta.Files = Files;
2821
- }
2822
- });
2823
-
2824
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/completions.mjs
2825
- var Completions;
2826
- var init_completions = __esm({
2827
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/completions.mjs"() {
2828
- "use strict";
2829
- init_resource();
2830
- init_headers();
2831
- Completions = class extends APIResource {
2832
- create(params, options) {
2833
- const { betas, ...body } = params;
2834
- return this._client.post("/v1/complete", {
2835
- body,
2836
- timeout: this._client._options.timeout ?? 6e5,
2837
- ...options,
2838
- headers: buildHeaders([
2839
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
2840
- options?.headers
2841
- ]),
2842
- stream: params.stream ?? false
2843
- });
2844
- }
2845
- };
2846
- }
2847
- });
2848
-
2849
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
2850
- function checkNever2(x) {
2851
- }
2852
- var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage, JSON_BUF_PROPERTY2, MessageStream;
2853
- var init_MessageStream = __esm({
2854
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs"() {
2855
- "use strict";
2856
- init_tslib();
2857
- init_errors();
2858
- init_error2();
2859
- init_streaming2();
2860
- init_parser();
2861
- JSON_BUF_PROPERTY2 = "__json_buf";
2862
- MessageStream = class _MessageStream {
2863
- constructor() {
2864
- _MessageStream_instances.add(this);
2865
- this.messages = [];
2866
- this.receivedMessages = [];
2867
- _MessageStream_currentMessageSnapshot.set(this, void 0);
2868
- this.controller = new AbortController();
2869
- _MessageStream_connectedPromise.set(this, void 0);
2870
- _MessageStream_resolveConnectedPromise.set(this, () => {
2871
- });
2872
- _MessageStream_rejectConnectedPromise.set(this, () => {
2873
- });
2874
- _MessageStream_endPromise.set(this, void 0);
2875
- _MessageStream_resolveEndPromise.set(this, () => {
2876
- });
2877
- _MessageStream_rejectEndPromise.set(this, () => {
2878
- });
2879
- _MessageStream_listeners.set(this, {});
2880
- _MessageStream_ended.set(this, false);
2881
- _MessageStream_errored.set(this, false);
2882
- _MessageStream_aborted.set(this, false);
2883
- _MessageStream_catchingPromiseCreated.set(this, false);
2884
- _MessageStream_response.set(this, void 0);
2885
- _MessageStream_request_id.set(this, void 0);
2886
- _MessageStream_handleError.set(this, (error) => {
2887
- __classPrivateFieldSet(this, _MessageStream_errored, true, "f");
2888
- if (isAbortError(error)) {
2889
- error = new APIUserAbortError();
2890
- }
2891
- if (error instanceof APIUserAbortError) {
2892
- __classPrivateFieldSet(this, _MessageStream_aborted, true, "f");
2893
- return this._emit("abort", error);
2894
- }
2895
- if (error instanceof AnthropicError) {
2896
- return this._emit("error", error);
2897
- }
2898
- if (error instanceof Error) {
2899
- const anthropicError = new AnthropicError(error.message);
2900
- anthropicError.cause = error;
2901
- return this._emit("error", anthropicError);
2902
- }
2903
- return this._emit("error", new AnthropicError(String(error)));
2904
- });
2905
- __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
2906
- __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f");
2907
- __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f");
2908
- }), "f");
2909
- __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
2910
- __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f");
2911
- __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f");
2912
- }), "f");
2913
- __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => {
2914
- });
2915
- __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => {
2916
- });
2917
- }
2918
- get response() {
2919
- return __classPrivateFieldGet(this, _MessageStream_response, "f");
2920
- }
2921
- get request_id() {
2922
- return __classPrivateFieldGet(this, _MessageStream_request_id, "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
- const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f");
2936
- if (!response) {
2937
- throw new Error("Could not resolve a `Response` object");
2938
- }
2939
- return {
2940
- data: this,
2941
- response,
2942
- request_id: response.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(stream) {
2953
- const runner = new _MessageStream();
2954
- runner._run(() => runner._fromReadableStream(stream));
2955
- return runner;
2956
- }
2957
- static createMessage(messages, params, options) {
2958
- const runner = new _MessageStream();
2959
- for (const message of params.messages) {
2960
- runner._addMessageParam(message);
2961
- }
2962
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
2963
- return runner;
2964
- }
2965
- _run(executor) {
2966
- executor().then(() => {
2967
- this._emitFinal();
2968
- this._emit("end");
2969
- }, __classPrivateFieldGet(this, _MessageStream_handleError, "f"));
2970
- }
2971
- _addMessageParam(message) {
2972
- this.messages.push(message);
2973
- }
2974
- _addMessage(message, emit = true) {
2975
- this.receivedMessages.push(message);
2976
- if (emit) {
2977
- this._emit("message", message);
2978
- }
2979
- }
2980
- async _createMessage(messages, params, options) {
2981
- const signal = options?.signal;
2982
- if (signal) {
2983
- if (signal.aborted)
2984
- this.controller.abort();
2985
- signal.addEventListener("abort", () => this.controller.abort());
2986
- }
2987
- __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
2988
- const { response, data: stream } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse();
2989
- this._connected(response);
2990
- for await (const event of stream) {
2991
- __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
2992
- }
2993
- if (stream.controller.signal?.aborted) {
2994
- throw new APIUserAbortError();
2995
- }
2996
- __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
2997
- }
2998
- _connected(response) {
2999
- if (this.ended)
3000
- return;
3001
- __classPrivateFieldSet(this, _MessageStream_response, response, "f");
3002
- __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get("request-id"), "f");
3003
- __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response);
3004
- this._emit("connect");
3005
- }
3006
- get ended() {
3007
- return __classPrivateFieldGet(this, _MessageStream_ended, "f");
3008
- }
3009
- get errored() {
3010
- return __classPrivateFieldGet(this, _MessageStream_errored, "f");
3011
- }
3012
- get aborted() {
3013
- return __classPrivateFieldGet(this, _MessageStream_aborted, "f");
3014
- }
3015
- abort() {
3016
- this.controller.abort();
3017
- }
3018
- /**
3019
- * Adds the listener function to the end of the listeners array for the event.
3020
- * No checks are made to see if the listener has already been added. Multiple calls passing
3021
- * the same combination of event and listener will result in the listener being added, and
3022
- * called, multiple times.
3023
- * @returns this MessageStream, so that calls can be chained
3024
- */
3025
- on(event, listener) {
3026
- const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []);
3027
- listeners.push({ listener });
3028
- return this;
3029
- }
3030
- /**
3031
- * Removes the specified listener from the listener array for the event.
3032
- * off() will remove, at most, one instance of a listener from the listener array. If any single
3033
- * listener has been added multiple times to the listener array for the specified event, then
3034
- * off() must be called multiple times to remove each instance.
3035
- * @returns this MessageStream, so that calls can be chained
3036
- */
3037
- off(event, listener) {
3038
- const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event];
3039
- if (!listeners)
3040
- return this;
3041
- const index = listeners.findIndex((l) => l.listener === listener);
3042
- if (index >= 0)
3043
- listeners.splice(index, 1);
3044
- return this;
3045
- }
3046
- /**
3047
- * Adds a one-time listener function for the event. The next time the event is triggered,
3048
- * this listener is removed and then invoked.
3049
- * @returns this MessageStream, so that calls can be chained
3050
- */
3051
- once(event, listener) {
3052
- const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []);
3053
- listeners.push({ listener, once: true });
3054
- return this;
3055
- }
3056
- /**
3057
- * This is similar to `.once()`, but returns a Promise that resolves the next time
3058
- * the event is triggered, instead of calling a listener callback.
3059
- * @returns a Promise that resolves the next time given event is triggered,
3060
- * or rejects if an error is emitted. (If you request the 'error' event,
3061
- * returns a promise that resolves with the error).
3062
- *
3063
- * Example:
3064
- *
3065
- * const message = await stream.emitted('message') // rejects if the stream errors
3066
- */
3067
- emitted(event) {
3068
- return new Promise((resolve, reject) => {
3069
- __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
3070
- if (event !== "error")
3071
- this.once("error", reject);
3072
- this.once(event, resolve);
3073
- });
3074
- }
3075
- async done() {
3076
- __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
3077
- await __classPrivateFieldGet(this, _MessageStream_endPromise, "f");
3078
- }
3079
- get currentMessage() {
3080
- return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
3081
- }
3082
- /**
3083
- * @returns a promise that resolves with the the final assistant Message response,
3084
- * or rejects if an error occurred or the stream ended prematurely without producing a Message.
3085
- */
3086
- async finalMessage() {
3087
- await this.done();
3088
- return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
3089
- }
3090
- /**
3091
- * @returns a promise that resolves with the the final assistant Message's text response, concatenated
3092
- * together if there are more than one text blocks.
3093
- * Rejects if an error occurred or the stream ended prematurely without producing a Message.
3094
- */
3095
- async finalText() {
3096
- await this.done();
3097
- return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
3098
- }
3099
- _emit(event, ...args) {
3100
- if (__classPrivateFieldGet(this, _MessageStream_ended, "f"))
3101
- return;
3102
- if (event === "end") {
3103
- __classPrivateFieldSet(this, _MessageStream_ended, true, "f");
3104
- __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this);
3105
- }
3106
- const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event];
3107
- if (listeners) {
3108
- __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
3109
- listeners.forEach(({ listener }) => listener(...args));
3110
- }
3111
- if (event === "abort") {
3112
- const error = args[0];
3113
- if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
3114
- Promise.reject(error);
3115
- }
3116
- __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
3117
- __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error);
3118
- this._emit("end");
3119
- return;
3120
- }
3121
- if (event === "error") {
3122
- const error = args[0];
3123
- if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
3124
- Promise.reject(error);
3125
- }
3126
- __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
3127
- __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error);
3128
- this._emit("end");
3129
- }
3130
- }
3131
- _emitFinal() {
3132
- const finalMessage = this.receivedMessages.at(-1);
3133
- if (finalMessage) {
3134
- this._emit("finalMessage", __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
3135
- }
3136
- }
3137
- async _fromReadableStream(readableStream, options) {
3138
- const signal = options?.signal;
3139
- if (signal) {
3140
- if (signal.aborted)
3141
- this.controller.abort();
3142
- signal.addEventListener("abort", () => this.controller.abort());
3143
- }
3144
- __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
3145
- this._connected(null);
3146
- const stream = Stream.fromReadableStream(readableStream, this.controller);
3147
- for await (const event of stream) {
3148
- __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
3149
- }
3150
- if (stream.controller.signal?.aborted) {
3151
- throw new APIUserAbortError();
3152
- }
3153
- __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
3154
- }
3155
- [(_MessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _MessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_listeners = /* @__PURE__ */ new WeakMap(), _MessageStream_ended = /* @__PURE__ */ new WeakMap(), _MessageStream_errored = /* @__PURE__ */ new WeakMap(), _MessageStream_aborted = /* @__PURE__ */ new WeakMap(), _MessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _MessageStream_response = /* @__PURE__ */ new WeakMap(), _MessageStream_request_id = /* @__PURE__ */ new WeakMap(), _MessageStream_handleError = /* @__PURE__ */ new WeakMap(), _MessageStream_instances = /* @__PURE__ */ new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage2() {
3156
- if (this.receivedMessages.length === 0) {
3157
- throw new AnthropicError("stream ended without producing a Message with role=assistant");
3158
- }
3159
- return this.receivedMessages.at(-1);
3160
- }, _MessageStream_getFinalText = function _MessageStream_getFinalText2() {
3161
- if (this.receivedMessages.length === 0) {
3162
- throw new AnthropicError("stream ended without producing a Message with role=assistant");
3163
- }
3164
- const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
3165
- if (textBlocks.length === 0) {
3166
- throw new AnthropicError("stream ended without producing a content block with type=text");
3167
- }
3168
- return textBlocks.join(" ");
3169
- }, _MessageStream_beginRequest = function _MessageStream_beginRequest2() {
3170
- if (this.ended)
3171
- return;
3172
- __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f");
3173
- }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent2(event) {
3174
- if (this.ended)
3175
- return;
3176
- const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
3177
- this._emit("streamEvent", event, messageSnapshot);
3178
- switch (event.type) {
3179
- case "content_block_delta": {
3180
- const content = messageSnapshot.content.at(-1);
3181
- switch (event.delta.type) {
3182
- case "text_delta": {
3183
- if (content.type === "text") {
3184
- this._emit("text", event.delta.text, content.text || "");
3185
- }
3186
- break;
3187
- }
3188
- case "citations_delta": {
3189
- if (content.type === "text") {
3190
- this._emit("citation", event.delta.citation, content.citations ?? []);
3191
- }
3192
- break;
3193
- }
3194
- case "input_json_delta": {
3195
- if (content.type === "tool_use" && content.input) {
3196
- this._emit("inputJson", event.delta.partial_json, content.input);
3197
- }
3198
- break;
3199
- }
3200
- case "thinking_delta": {
3201
- if (content.type === "thinking") {
3202
- this._emit("thinking", event.delta.thinking, content.thinking);
3203
- }
3204
- break;
3205
- }
3206
- case "signature_delta": {
3207
- if (content.type === "thinking") {
3208
- this._emit("signature", content.signature);
3209
- }
3210
- break;
3211
- }
3212
- default:
3213
- checkNever2(event.delta);
3214
- }
3215
- break;
3216
- }
3217
- case "message_stop": {
3218
- this._addMessageParam(messageSnapshot);
3219
- this._addMessage(messageSnapshot, true);
3220
- break;
3221
- }
3222
- case "content_block_stop": {
3223
- this._emit("contentBlock", messageSnapshot.content.at(-1));
3224
- break;
3225
- }
3226
- case "message_start": {
3227
- __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
3228
- break;
3229
- }
3230
- case "content_block_start":
3231
- case "message_delta":
3232
- break;
3233
- }
3234
- }, _MessageStream_endRequest = function _MessageStream_endRequest2() {
3235
- if (this.ended) {
3236
- throw new AnthropicError(`stream has ended, this shouldn't happen`);
3237
- }
3238
- const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
3239
- if (!snapshot) {
3240
- throw new AnthropicError(`request ended without sending any chunks`);
3241
- }
3242
- __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f");
3243
- return snapshot;
3244
- }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage2(event) {
3245
- let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
3246
- if (event.type === "message_start") {
3247
- if (snapshot) {
3248
- throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
3249
- }
3250
- return event.message;
3251
- }
3252
- if (!snapshot) {
3253
- throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
3254
- }
3255
- switch (event.type) {
3256
- case "message_stop":
3257
- return snapshot;
3258
- case "message_delta":
3259
- snapshot.stop_reason = event.delta.stop_reason;
3260
- snapshot.stop_sequence = event.delta.stop_sequence;
3261
- snapshot.usage.output_tokens = event.usage.output_tokens;
3262
- if (event.usage.input_tokens != null) {
3263
- snapshot.usage.input_tokens = event.usage.input_tokens;
3264
- }
3265
- if (event.usage.cache_creation_input_tokens != null) {
3266
- snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
3267
- }
3268
- if (event.usage.cache_read_input_tokens != null) {
3269
- snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
3270
- }
3271
- if (event.usage.server_tool_use != null) {
3272
- snapshot.usage.server_tool_use = event.usage.server_tool_use;
3273
- }
3274
- return snapshot;
3275
- case "content_block_start":
3276
- snapshot.content.push(event.content_block);
3277
- return snapshot;
3278
- case "content_block_delta": {
3279
- const snapshotContent = snapshot.content.at(event.index);
3280
- switch (event.delta.type) {
3281
- case "text_delta": {
3282
- if (snapshotContent?.type === "text") {
3283
- snapshotContent.text += event.delta.text;
3284
- }
3285
- break;
3286
- }
3287
- case "citations_delta": {
3288
- if (snapshotContent?.type === "text") {
3289
- snapshotContent.citations ?? (snapshotContent.citations = []);
3290
- snapshotContent.citations.push(event.delta.citation);
3291
- }
3292
- break;
3293
- }
3294
- case "input_json_delta": {
3295
- if (snapshotContent?.type === "tool_use") {
3296
- let jsonBuf = snapshotContent[JSON_BUF_PROPERTY2] || "";
3297
- jsonBuf += event.delta.partial_json;
3298
- Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY2, {
3299
- value: jsonBuf,
3300
- enumerable: false,
3301
- writable: true
3302
- });
3303
- if (jsonBuf) {
3304
- snapshotContent.input = partialParse(jsonBuf);
3305
- }
3306
- }
3307
- break;
3308
- }
3309
- case "thinking_delta": {
3310
- if (snapshotContent?.type === "thinking") {
3311
- snapshotContent.thinking += event.delta.thinking;
3312
- }
3313
- break;
3314
- }
3315
- case "signature_delta": {
3316
- if (snapshotContent?.type === "thinking") {
3317
- snapshotContent.signature = event.delta.signature;
3318
- }
3319
- break;
3320
- }
3321
- default:
3322
- checkNever2(event.delta);
3323
- }
3324
- return snapshot;
3325
- }
3326
- case "content_block_stop":
3327
- return snapshot;
3328
- }
3329
- }, Symbol.asyncIterator)]() {
3330
- const pushQueue = [];
3331
- const readQueue = [];
3332
- let done = false;
3333
- this.on("streamEvent", (event) => {
3334
- const reader = readQueue.shift();
3335
- if (reader) {
3336
- reader.resolve(event);
3337
- } else {
3338
- pushQueue.push(event);
3339
- }
3340
- });
3341
- this.on("end", () => {
3342
- done = true;
3343
- for (const reader of readQueue) {
3344
- reader.resolve(void 0);
3345
- }
3346
- readQueue.length = 0;
3347
- });
3348
- this.on("abort", (err) => {
3349
- done = true;
3350
- for (const reader of readQueue) {
3351
- reader.reject(err);
3352
- }
3353
- readQueue.length = 0;
3354
- });
3355
- this.on("error", (err) => {
3356
- done = true;
3357
- for (const reader of readQueue) {
3358
- reader.reject(err);
3359
- }
3360
- readQueue.length = 0;
3361
- });
3362
- return {
3363
- next: async () => {
3364
- if (!pushQueue.length) {
3365
- if (done) {
3366
- return { value: void 0, done: true };
3367
- }
3368
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
3369
- }
3370
- const chunk = pushQueue.shift();
3371
- return { value: chunk, done: false };
3372
- },
3373
- return: async () => {
3374
- this.abort();
3375
- return { value: void 0, done: true };
3376
- }
3377
- };
3378
- }
3379
- toReadableStream() {
3380
- const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
3381
- return stream.toReadableStream();
3382
- }
3383
- };
3384
- }
3385
- });
3386
-
3387
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs
3388
- var Batches2;
3389
- var init_batches2 = __esm({
3390
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs"() {
3391
- "use strict";
3392
- init_resource();
3393
- init_pagination();
3394
- init_headers();
3395
- init_jsonl();
3396
- init_error2();
3397
- init_path();
3398
- Batches2 = class extends APIResource {
3399
- /**
3400
- * Send a batch of Message creation requests.
3401
- *
3402
- * The Message Batches API can be used to process multiple Messages API requests at
3403
- * once. Once a Message Batch is created, it begins processing immediately. Batches
3404
- * can take up to 24 hours to complete.
3405
- *
3406
- * Learn more about the Message Batches API in our
3407
- * [user guide](/en/docs/build-with-claude/batch-processing)
3408
- *
3409
- * @example
3410
- * ```ts
3411
- * const messageBatch = await client.messages.batches.create({
3412
- * requests: [
3413
- * {
3414
- * custom_id: 'my-custom-id-1',
3415
- * params: {
3416
- * max_tokens: 1024,
3417
- * messages: [
3418
- * { content: 'Hello, world', role: 'user' },
3419
- * ],
3420
- * model: 'claude-3-7-sonnet-20250219',
3421
- * },
3422
- * },
3423
- * ],
3424
- * });
3425
- * ```
3426
- */
3427
- create(body, options) {
3428
- return this._client.post("/v1/messages/batches", { body, ...options });
3429
- }
3430
- /**
3431
- * This endpoint is idempotent and can be used to poll for Message Batch
3432
- * completion. To access the results of a Message Batch, make a request to the
3433
- * `results_url` field in the response.
3434
- *
3435
- * Learn more about the Message Batches API in our
3436
- * [user guide](/en/docs/build-with-claude/batch-processing)
3437
- *
3438
- * @example
3439
- * ```ts
3440
- * const messageBatch = await client.messages.batches.retrieve(
3441
- * 'message_batch_id',
3442
- * );
3443
- * ```
3444
- */
3445
- retrieve(messageBatchID, options) {
3446
- return this._client.get(path`/v1/messages/batches/${messageBatchID}`, options);
3447
- }
3448
- /**
3449
- * List all Message Batches within a Workspace. Most recently created batches are
3450
- * returned first.
3451
- *
3452
- * Learn more about the Message Batches API in our
3453
- * [user guide](/en/docs/build-with-claude/batch-processing)
3454
- *
3455
- * @example
3456
- * ```ts
3457
- * // Automatically fetches more pages as needed.
3458
- * for await (const messageBatch of client.messages.batches.list()) {
3459
- * // ...
3460
- * }
3461
- * ```
3462
- */
3463
- list(query = {}, options) {
3464
- return this._client.getAPIList("/v1/messages/batches", Page, { query, ...options });
3465
- }
3466
- /**
3467
- * Delete a Message Batch.
3468
- *
3469
- * Message Batches can only be deleted once they've finished processing. If you'd
3470
- * like to delete an in-progress batch, you must first cancel it.
3471
- *
3472
- * Learn more about the Message Batches API in our
3473
- * [user guide](/en/docs/build-with-claude/batch-processing)
3474
- *
3475
- * @example
3476
- * ```ts
3477
- * const deletedMessageBatch =
3478
- * await client.messages.batches.delete('message_batch_id');
3479
- * ```
3480
- */
3481
- delete(messageBatchID, options) {
3482
- return this._client.delete(path`/v1/messages/batches/${messageBatchID}`, options);
3483
- }
3484
- /**
3485
- * Batches may be canceled any time before processing ends. Once cancellation is
3486
- * initiated, the batch enters a `canceling` state, at which time the system may
3487
- * complete any in-progress, non-interruptible requests before finalizing
3488
- * cancellation.
3489
- *
3490
- * The number of canceled requests is specified in `request_counts`. To determine
3491
- * which requests were canceled, check the individual results within the batch.
3492
- * Note that cancellation may not result in any canceled requests if they were
3493
- * non-interruptible.
3494
- *
3495
- * Learn more about the Message Batches API in our
3496
- * [user guide](/en/docs/build-with-claude/batch-processing)
3497
- *
3498
- * @example
3499
- * ```ts
3500
- * const messageBatch = await client.messages.batches.cancel(
3501
- * 'message_batch_id',
3502
- * );
3503
- * ```
3504
- */
3505
- cancel(messageBatchID, options) {
3506
- return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel`, options);
3507
- }
3508
- /**
3509
- * Streams the results of a Message Batch as a `.jsonl` file.
3510
- *
3511
- * Each line in the file is a JSON object containing the result of a single request
3512
- * in the Message Batch. Results are not guaranteed to be in the same order as
3513
- * requests. Use the `custom_id` field to match results to requests.
3514
- *
3515
- * Learn more about the Message Batches API in our
3516
- * [user guide](/en/docs/build-with-claude/batch-processing)
3517
- *
3518
- * @example
3519
- * ```ts
3520
- * const messageBatchIndividualResponse =
3521
- * await client.messages.batches.results('message_batch_id');
3522
- * ```
3523
- */
3524
- async results(messageBatchID, options) {
3525
- const batch = await this.retrieve(messageBatchID);
3526
- if (!batch.results_url) {
3527
- throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
3528
- }
3529
- return this._client.get(batch.results_url, {
3530
- ...options,
3531
- headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
3532
- stream: true,
3533
- __binaryResponse: true
3534
- })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
3535
- }
3536
- };
3537
- }
3538
- });
3539
-
3540
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs
3541
- var Messages2, DEPRECATED_MODELS2;
3542
- var init_messages2 = __esm({
3543
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs"() {
3544
- "use strict";
3545
- init_resource();
3546
- init_MessageStream();
3547
- init_batches2();
3548
- init_batches2();
3549
- init_constants();
3550
- Messages2 = class extends APIResource {
3551
- constructor() {
3552
- super(...arguments);
3553
- this.batches = new Batches2(this._client);
3554
- }
3555
- create(body, options) {
3556
- if (body.model in DEPRECATED_MODELS2) {
3557
- console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body.model]}
3558
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
3559
- }
3560
- let timeout = this._client._options.timeout;
3561
- if (!body.stream && timeout == null) {
3562
- const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0;
3563
- timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
3564
- }
3565
- return this._client.post("/v1/messages", {
3566
- body,
3567
- timeout: timeout ?? 6e5,
3568
- ...options,
3569
- stream: body.stream ?? false
3570
- });
3571
- }
3572
- /**
3573
- * Create a Message stream
3574
- */
3575
- stream(body, options) {
3576
- return MessageStream.createMessage(this, body, options);
3577
- }
3578
- /**
3579
- * Count the number of tokens in a Message.
3580
- *
3581
- * The Token Count API can be used to count the number of tokens in a Message,
3582
- * including tools, images, and documents, without creating it.
3583
- *
3584
- * Learn more about token counting in our
3585
- * [user guide](/en/docs/build-with-claude/token-counting)
3586
- *
3587
- * @example
3588
- * ```ts
3589
- * const messageTokensCount =
3590
- * await client.messages.countTokens({
3591
- * messages: [{ content: 'string', role: 'user' }],
3592
- * model: 'claude-3-7-sonnet-latest',
3593
- * });
3594
- * ```
3595
- */
3596
- countTokens(body, options) {
3597
- return this._client.post("/v1/messages/count_tokens", { body, ...options });
3598
- }
3599
- };
3600
- DEPRECATED_MODELS2 = {
3601
- "claude-1.3": "November 6th, 2024",
3602
- "claude-1.3-100k": "November 6th, 2024",
3603
- "claude-instant-1.1": "November 6th, 2024",
3604
- "claude-instant-1.1-100k": "November 6th, 2024",
3605
- "claude-instant-1.2": "November 6th, 2024",
3606
- "claude-3-sonnet-20240229": "July 21st, 2025",
3607
- "claude-2.1": "July 21st, 2025",
3608
- "claude-2.0": "July 21st, 2025"
3609
- };
3610
- Messages2.Batches = Batches2;
3611
- }
3612
- });
3613
-
3614
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/models.mjs
3615
- var Models2;
3616
- var init_models2 = __esm({
3617
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/models.mjs"() {
3618
- "use strict";
3619
- init_resource();
3620
- init_pagination();
3621
- init_headers();
3622
- init_path();
3623
- Models2 = class extends APIResource {
3624
- /**
3625
- * Get a specific model.
3626
- *
3627
- * The Models API response can be used to determine information about a specific
3628
- * model or resolve a model alias to a model ID.
3629
- */
3630
- retrieve(modelID, params = {}, options) {
3631
- const { betas } = params ?? {};
3632
- return this._client.get(path`/v1/models/${modelID}`, {
3633
- ...options,
3634
- headers: buildHeaders([
3635
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
3636
- options?.headers
3637
- ])
3638
- });
3639
- }
3640
- /**
3641
- * List available models.
3642
- *
3643
- * The Models API response can be used to determine which models are available for
3644
- * use in the API. More recently released models are listed first.
3645
- */
3646
- list(params = {}, options) {
3647
- const { betas, ...query } = params ?? {};
3648
- return this._client.getAPIList("/v1/models", Page, {
3649
- query,
3650
- ...options,
3651
- headers: buildHeaders([
3652
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
3653
- options?.headers
3654
- ])
3655
- });
3656
- }
3657
- };
3658
- }
3659
- });
3660
-
3661
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/index.mjs
3662
- var init_resources = __esm({
3663
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/resources/index.mjs"() {
3664
- "use strict";
3665
- init_shared();
3666
- init_beta();
3667
- init_completions();
3668
- init_messages2();
3669
- init_models2();
3670
- }
3671
- });
3672
-
3673
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs
3674
- var readEnv;
3675
- var init_env = __esm({
3676
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"() {
3677
- "use strict";
3678
- readEnv = (env) => {
3679
- if (typeof globalThis.process !== "undefined") {
3680
- return globalThis.process.env?.[env]?.trim() ?? void 0;
3681
- }
3682
- if (typeof globalThis.Deno !== "undefined") {
3683
- return globalThis.Deno.env?.get?.(env)?.trim();
3684
- }
3685
- return void 0;
3686
- };
3687
- }
3688
- });
3689
-
3690
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/client.mjs
3691
- var _a, _BaseAnthropic_encoder, BaseAnthropic, Anthropic, HUMAN_PROMPT, AI_PROMPT;
3692
- var init_client = __esm({
3693
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/client.mjs"() {
3694
- "use strict";
3695
- init_tslib();
3696
- init_uuid();
3697
- init_values();
3698
- init_sleep();
3699
- init_log();
3700
- init_errors();
3701
- init_detect_platform();
3702
- init_shims();
3703
- init_request_options();
3704
- init_version();
3705
- init_error();
3706
- init_pagination();
3707
- init_uploads2();
3708
- init_resources();
3709
- init_api_promise();
3710
- init_detect_platform();
3711
- init_headers();
3712
- init_completions();
3713
- init_models2();
3714
- init_env();
3715
- init_log();
3716
- init_values();
3717
- init_beta();
3718
- init_messages2();
3719
- BaseAnthropic = class {
3720
- /**
3721
- * API Client for interfacing with the Anthropic API.
3722
- *
3723
- * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
3724
- * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
3725
- * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
3726
- * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
3727
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
3728
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
3729
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
3730
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
3731
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
3732
- * @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.
3733
- */
3734
- constructor({ baseURL = readEnv("ANTHROPIC_BASE_URL"), apiKey = readEnv("ANTHROPIC_API_KEY") ?? null, authToken = readEnv("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) {
3735
- _BaseAnthropic_encoder.set(this, void 0);
3736
- const options = {
3737
- apiKey,
3738
- authToken,
3739
- ...opts,
3740
- baseURL: baseURL || `https://api.anthropic.com`
3741
- };
3742
- if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
3743
- throw new AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
3744
- }
3745
- this.baseURL = options.baseURL;
3746
- this.timeout = options.timeout ?? Anthropic.DEFAULT_TIMEOUT;
3747
- this.logger = options.logger ?? console;
3748
- const defaultLogLevel = "warn";
3749
- this.logLevel = defaultLogLevel;
3750
- this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this) ?? defaultLogLevel;
3751
- this.fetchOptions = options.fetchOptions;
3752
- this.maxRetries = options.maxRetries ?? 2;
3753
- this.fetch = options.fetch ?? getDefaultFetch();
3754
- __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f");
3755
- this._options = options;
3756
- this.apiKey = apiKey;
3757
- this.authToken = authToken;
3758
- }
3759
- /**
3760
- * Create a new client instance re-using the same options given to the current client with optional overriding.
3761
- */
3762
- withOptions(options) {
3763
- return new this.constructor({
3764
- ...this._options,
3765
- baseURL: this.baseURL,
3766
- maxRetries: this.maxRetries,
3767
- timeout: this.timeout,
3768
- logger: this.logger,
3769
- logLevel: this.logLevel,
3770
- fetchOptions: this.fetchOptions,
3771
- apiKey: this.apiKey,
3772
- authToken: this.authToken,
3773
- ...options
3774
- });
3775
- }
3776
- defaultQuery() {
3777
- return this._options.defaultQuery;
3778
- }
3779
- validateHeaders({ values, nulls }) {
3780
- if (this.apiKey && values.get("x-api-key")) {
3781
- return;
3782
- }
3783
- if (nulls.has("x-api-key")) {
3784
- return;
3785
- }
3786
- if (this.authToken && values.get("authorization")) {
3787
- return;
3788
- }
3789
- if (nulls.has("authorization")) {
3790
- return;
3791
- }
3792
- 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');
3793
- }
3794
- authHeaders(opts) {
3795
- return buildHeaders([this.apiKeyAuth(opts), this.bearerAuth(opts)]);
3796
- }
3797
- apiKeyAuth(opts) {
3798
- if (this.apiKey == null) {
3799
- return void 0;
3800
- }
3801
- return buildHeaders([{ "X-Api-Key": this.apiKey }]);
3802
- }
3803
- bearerAuth(opts) {
3804
- if (this.authToken == null) {
3805
- return void 0;
3806
- }
3807
- return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]);
3808
- }
3809
- /**
3810
- * Basic re-implementation of `qs.stringify` for primitive types.
3811
- */
3812
- stringifyQuery(query) {
3813
- return Object.entries(query).filter(([_, value]) => typeof value !== "undefined").map(([key, value]) => {
3814
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
3815
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
3816
- }
3817
- if (value === null) {
3818
- return `${encodeURIComponent(key)}=`;
3819
- }
3820
- throw new AnthropicError(`Cannot stringify type ${typeof value}; 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.`);
3821
- }).join("&");
3822
- }
3823
- getUserAgent() {
3824
- return `${this.constructor.name}/JS ${VERSION}`;
3825
- }
3826
- defaultIdempotencyKey() {
3827
- return `stainless-node-retry-${uuid4()}`;
3828
- }
3829
- makeStatusError(status, error, message, headers) {
3830
- return APIError.generate(status, error, message, headers);
3831
- }
3832
- buildURL(path6, query) {
3833
- const url = isAbsoluteURL(path6) ? new URL(path6) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path6.startsWith("/") ? path6.slice(1) : path6));
3834
- const defaultQuery = this.defaultQuery();
3835
- if (!isEmptyObj(defaultQuery)) {
3836
- query = { ...defaultQuery, ...query };
3837
- }
3838
- if (typeof query === "object" && query && !Array.isArray(query)) {
3839
- url.search = this.stringifyQuery(query);
3840
- }
3841
- return url.toString();
3842
- }
3843
- _calculateNonstreamingTimeout(maxTokens) {
3844
- const defaultTimeout = 10 * 60;
3845
- const expectedTimeout = 60 * 60 * maxTokens / 128e3;
3846
- if (expectedTimeout > defaultTimeout) {
3847
- throw new AnthropicError("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");
3848
- }
3849
- return defaultTimeout * 1e3;
3850
- }
3851
- /**
3852
- * Used as a callback for mutating the given `FinalRequestOptions` object.
3853
- */
3854
- async prepareOptions(options) {
3855
- }
3856
- /**
3857
- * Used as a callback for mutating the given `RequestInit` object.
3858
- *
3859
- * This is useful for cases where you want to add certain headers based off of
3860
- * the request properties, e.g. `method` or `url`.
3861
- */
3862
- async prepareRequest(request, { url, options }) {
3863
- }
3864
- get(path6, opts) {
3865
- return this.methodRequest("get", path6, opts);
3866
- }
3867
- post(path6, opts) {
3868
- return this.methodRequest("post", path6, opts);
3869
- }
3870
- patch(path6, opts) {
3871
- return this.methodRequest("patch", path6, opts);
3872
- }
3873
- put(path6, opts) {
3874
- return this.methodRequest("put", path6, opts);
3875
- }
3876
- delete(path6, opts) {
3877
- return this.methodRequest("delete", path6, opts);
3878
- }
3879
- methodRequest(method, path6, opts) {
3880
- return this.request(Promise.resolve(opts).then((opts2) => {
3881
- return { method, path: path6, ...opts2 };
3882
- }));
3883
- }
3884
- request(options, remainingRetries = null) {
3885
- return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0));
3886
- }
3887
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
3888
- const options = await optionsInput;
3889
- const maxRetries = options.maxRetries ?? this.maxRetries;
3890
- if (retriesRemaining == null) {
3891
- retriesRemaining = maxRetries;
3892
- }
3893
- await this.prepareOptions(options);
3894
- const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
3895
- await this.prepareRequest(req, { url, options });
3896
- const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
3897
- const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`;
3898
- const startTime = Date.now();
3899
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
3900
- retryOfRequestLogID,
3901
- method: options.method,
3902
- url,
3903
- options,
3904
- headers: req.headers
3905
- }));
3906
- if (options.signal?.aborted) {
3907
- throw new APIUserAbortError();
3908
- }
3909
- const controller = new AbortController();
3910
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
3911
- const headersTime = Date.now();
3912
- if (response instanceof Error) {
3913
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
3914
- if (options.signal?.aborted) {
3915
- throw new APIUserAbortError();
3916
- }
3917
- const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
3918
- if (retriesRemaining) {
3919
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
3920
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
3921
- retryOfRequestLogID,
3922
- url,
3923
- durationMs: headersTime - startTime,
3924
- message: response.message
3925
- }));
3926
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
3927
- }
3928
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
3929
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({
3930
- retryOfRequestLogID,
3931
- url,
3932
- durationMs: headersTime - startTime,
3933
- message: response.message
3934
- }));
3935
- if (isTimeout) {
3936
- throw new APIConnectionTimeoutError();
3937
- }
3938
- throw new APIConnectionError({ cause: response });
3939
- }
3940
- const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
3941
- const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
3942
- if (!response.ok) {
3943
- const shouldRetry = this.shouldRetry(response);
3944
- if (retriesRemaining && shouldRetry) {
3945
- const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
3946
- await CancelReadableStream(response.body);
3947
- loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);
3948
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({
3949
- retryOfRequestLogID,
3950
- url: response.url,
3951
- status: response.status,
3952
- headers: response.headers,
3953
- durationMs: headersTime - startTime
3954
- }));
3955
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
3956
- }
3957
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
3958
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
3959
- const errText = await response.text().catch((err2) => castToError(err2).message);
3960
- const errJSON = safeJSON(errText);
3961
- const errMessage = errJSON ? void 0 : errText;
3962
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
3963
- retryOfRequestLogID,
3964
- url: response.url,
3965
- status: response.status,
3966
- headers: response.headers,
3967
- message: errMessage,
3968
- durationMs: Date.now() - startTime
3969
- }));
3970
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
3971
- throw err;
3972
- }
3973
- loggerFor(this).info(responseInfo);
3974
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
3975
- retryOfRequestLogID,
3976
- url: response.url,
3977
- status: response.status,
3978
- headers: response.headers,
3979
- durationMs: headersTime - startTime
3980
- }));
3981
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
3982
- }
3983
- getAPIList(path6, Page2, opts) {
3984
- return this.requestAPIList(Page2, { method: "get", path: path6, ...opts });
3985
- }
3986
- requestAPIList(Page2, options) {
3987
- const request = this.makeRequest(options, null, void 0);
3988
- return new PagePromise(this, request, Page2);
3989
- }
3990
- async fetchWithTimeout(url, init, ms, controller) {
3991
- const { signal, method, ...options } = init || {};
3992
- if (signal)
3993
- signal.addEventListener("abort", () => controller.abort());
3994
- const timeout = setTimeout(() => controller.abort(), ms);
3995
- const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body;
3996
- const fetchOptions = {
3997
- signal: controller.signal,
3998
- ...isReadableBody ? { duplex: "half" } : {},
3999
- method: "GET",
4000
- ...options
4001
- };
4002
- if (method) {
4003
- fetchOptions.method = method.toUpperCase();
4004
- }
4005
- try {
4006
- return await this.fetch.call(void 0, url, fetchOptions);
4007
- } finally {
4008
- clearTimeout(timeout);
4009
- }
4010
- }
4011
- shouldRetry(response) {
4012
- const shouldRetryHeader = response.headers.get("x-should-retry");
4013
- if (shouldRetryHeader === "true")
4014
- return true;
4015
- if (shouldRetryHeader === "false")
4016
- return false;
4017
- if (response.status === 408)
4018
- return true;
4019
- if (response.status === 409)
4020
- return true;
4021
- if (response.status === 429)
4022
- return true;
4023
- if (response.status >= 500)
4024
- return true;
4025
- return false;
4026
- }
4027
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
4028
- let timeoutMillis;
4029
- const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
4030
- if (retryAfterMillisHeader) {
4031
- const timeoutMs = parseFloat(retryAfterMillisHeader);
4032
- if (!Number.isNaN(timeoutMs)) {
4033
- timeoutMillis = timeoutMs;
4034
- }
4035
- }
4036
- const retryAfterHeader = responseHeaders?.get("retry-after");
4037
- if (retryAfterHeader && !timeoutMillis) {
4038
- const timeoutSeconds = parseFloat(retryAfterHeader);
4039
- if (!Number.isNaN(timeoutSeconds)) {
4040
- timeoutMillis = timeoutSeconds * 1e3;
4041
- } else {
4042
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
4043
- }
4044
- }
4045
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) {
4046
- const maxRetries = options.maxRetries ?? this.maxRetries;
4047
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
4048
- }
4049
- await sleep(timeoutMillis);
4050
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
4051
- }
4052
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
4053
- const initialRetryDelay = 0.5;
4054
- const maxRetryDelay = 8;
4055
- const numRetries = maxRetries - retriesRemaining;
4056
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
4057
- const jitter = 1 - Math.random() * 0.25;
4058
- return sleepSeconds * jitter * 1e3;
4059
- }
4060
- calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
4061
- const maxTime = 60 * 60 * 1e3;
4062
- const defaultTime = 60 * 10 * 1e3;
4063
- const expectedTime = maxTime * maxTokens / 128e3;
4064
- if (expectedTime > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) {
4065
- throw new AnthropicError("Streaming is strongly recommended for operations that may token longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");
4066
- }
4067
- return defaultTime;
4068
- }
4069
- buildRequest(inputOptions, { retryCount = 0 } = {}) {
4070
- const options = { ...inputOptions };
4071
- const { method, path: path6, query } = options;
4072
- const url = this.buildURL(path6, query);
4073
- if ("timeout" in options)
4074
- validatePositiveInteger("timeout", options.timeout);
4075
- options.timeout = options.timeout ?? this.timeout;
4076
- const { bodyHeaders, body } = this.buildBody({ options });
4077
- const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
4078
- const req = {
4079
- method,
4080
- headers: reqHeaders,
4081
- ...options.signal && { signal: options.signal },
4082
- ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
4083
- ...body && { body },
4084
- ...this.fetchOptions ?? {},
4085
- ...options.fetchOptions ?? {}
4086
- };
4087
- return { req, url, timeout: options.timeout };
4088
- }
4089
- buildHeaders({ options, method, bodyHeaders, retryCount }) {
4090
- let idempotencyHeaders = {};
4091
- if (this.idempotencyHeader && method !== "get") {
4092
- if (!options.idempotencyKey)
4093
- options.idempotencyKey = this.defaultIdempotencyKey();
4094
- idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
4095
- }
4096
- const headers = buildHeaders([
4097
- idempotencyHeaders,
4098
- {
4099
- Accept: "application/json",
4100
- "User-Agent": this.getUserAgent(),
4101
- "X-Stainless-Retry-Count": String(retryCount),
4102
- ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {},
4103
- ...getPlatformHeaders(),
4104
- ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0,
4105
- "anthropic-version": "2023-06-01"
4106
- },
4107
- this.authHeaders(options),
4108
- this._options.defaultHeaders,
4109
- bodyHeaders,
4110
- options.headers
4111
- ]);
4112
- this.validateHeaders(headers);
4113
- return headers.values;
4114
- }
4115
- buildBody({ options: { body, headers: rawHeaders } }) {
4116
- if (!body) {
4117
- return { bodyHeaders: void 0, body: void 0 };
4118
- }
4119
- const headers = buildHeaders([rawHeaders]);
4120
- if (
4121
- // Pass raw type verbatim
4122
- ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now
4123
- headers.values.has("content-type") || // `Blob` is superset of `File`
4124
- body instanceof Blob || // `FormData` -> `multipart/form-data`
4125
- body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
4126
- body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
4127
- globalThis.ReadableStream && body instanceof globalThis.ReadableStream
4128
- ) {
4129
- return { bodyHeaders: void 0, body };
4130
- } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) {
4131
- return { bodyHeaders: void 0, body: ReadableStreamFrom(body) };
4132
- } else {
4133
- return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
4134
- }
4135
- }
4136
- };
4137
- _a = BaseAnthropic, _BaseAnthropic_encoder = /* @__PURE__ */ new WeakMap();
4138
- BaseAnthropic.Anthropic = _a;
4139
- BaseAnthropic.HUMAN_PROMPT = "\n\nHuman:";
4140
- BaseAnthropic.AI_PROMPT = "\n\nAssistant:";
4141
- BaseAnthropic.DEFAULT_TIMEOUT = 6e5;
4142
- BaseAnthropic.AnthropicError = AnthropicError;
4143
- BaseAnthropic.APIError = APIError;
4144
- BaseAnthropic.APIConnectionError = APIConnectionError;
4145
- BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError;
4146
- BaseAnthropic.APIUserAbortError = APIUserAbortError;
4147
- BaseAnthropic.NotFoundError = NotFoundError;
4148
- BaseAnthropic.ConflictError = ConflictError;
4149
- BaseAnthropic.RateLimitError = RateLimitError;
4150
- BaseAnthropic.BadRequestError = BadRequestError;
4151
- BaseAnthropic.AuthenticationError = AuthenticationError;
4152
- BaseAnthropic.InternalServerError = InternalServerError;
4153
- BaseAnthropic.PermissionDeniedError = PermissionDeniedError;
4154
- BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError;
4155
- BaseAnthropic.toFile = toFile;
4156
- Anthropic = class extends BaseAnthropic {
4157
- constructor() {
4158
- super(...arguments);
4159
- this.completions = new Completions(this);
4160
- this.messages = new Messages2(this);
4161
- this.models = new Models2(this);
4162
- this.beta = new Beta(this);
4163
- }
4164
- };
4165
- Anthropic.Completions = Completions;
4166
- Anthropic.Messages = Messages2;
4167
- Anthropic.Models = Models2;
4168
- Anthropic.Beta = Beta;
4169
- ({ HUMAN_PROMPT, AI_PROMPT } = Anthropic);
4170
- }
4171
- });
4172
-
4173
- // ../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/index.mjs
4174
- var init_sdk = __esm({
4175
- "../../node_modules/.pnpm/@anthropic-ai+sdk@0.52.0/node_modules/@anthropic-ai/sdk/index.mjs"() {
4176
- "use strict";
4177
- init_client();
4178
- init_uploads2();
4179
- init_api_promise();
4180
- init_client();
4181
- init_pagination();
4182
- init_error();
4183
- }
4184
- });
4185
-
4186
- // ../../node_modules/.pnpm/uuid@14.0.1/node_modules/uuid/dist-node/stringify.js
4187
- function unsafeStringify(arr, offset = 0) {
4188
- return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
4189
- }
4190
- var byteToHex;
4191
- var init_stringify = __esm({
4192
- "../../node_modules/.pnpm/uuid@14.0.1/node_modules/uuid/dist-node/stringify.js"() {
4193
- "use strict";
4194
- byteToHex = [];
4195
- for (let i = 0; i < 256; ++i) {
4196
- byteToHex.push((i + 256).toString(16).slice(1));
4197
- }
4198
- }
4199
- });
4200
-
4201
- // ../../node_modules/.pnpm/uuid@14.0.1/node_modules/uuid/dist-node/rng.js
4202
- function rng() {
4203
- return crypto.getRandomValues(rnds8);
4204
- }
4205
- var rnds8;
4206
- var init_rng = __esm({
4207
- "../../node_modules/.pnpm/uuid@14.0.1/node_modules/uuid/dist-node/rng.js"() {
4208
- "use strict";
4209
- rnds8 = new Uint8Array(16);
4210
- }
4211
- });
4212
-
4213
- // ../../node_modules/.pnpm/uuid@14.0.1/node_modules/uuid/dist-node/v4.js
4214
- function v4(options, buf, offset) {
4215
- if (!buf && !options && crypto.randomUUID) {
4216
- return crypto.randomUUID();
4217
- }
4218
- return _v4(options, buf, offset);
4219
- }
4220
- function _v4(options, buf, offset) {
4221
- options = options || {};
4222
- const rnds = options.random ?? options.rng?.() ?? rng();
4223
- if (rnds.length < 16) {
4224
- throw new Error("Random bytes length must be >= 16");
4225
- }
4226
- rnds[6] = rnds[6] & 15 | 64;
4227
- rnds[8] = rnds[8] & 63 | 128;
4228
- if (buf) {
4229
- offset = offset || 0;
4230
- if (offset < 0 || offset + 16 > buf.length) {
4231
- throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
4232
- }
4233
- for (let i = 0; i < 16; ++i) {
4234
- buf[offset + i] = rnds[i];
4235
- }
4236
- return buf;
4237
- }
4238
- return unsafeStringify(rnds);
4239
- }
4240
- var v4_default;
4241
- var init_v4 = __esm({
4242
- "../../node_modules/.pnpm/uuid@14.0.1/node_modules/uuid/dist-node/v4.js"() {
4243
- "use strict";
4244
- init_rng();
4245
- init_stringify();
4246
- v4_default = v4;
4247
- }
4248
- });
4249
-
4250
- // ../../node_modules/.pnpm/uuid@14.0.1/node_modules/uuid/dist-node/index.js
4251
- var init_dist_node = __esm({
4252
- "../../node_modules/.pnpm/uuid@14.0.1/node_modules/uuid/dist-node/index.js"() {
4253
- "use strict";
4254
- init_v4();
4255
- }
4256
- });
4257
-
4258
33
  // ../amem-core/dist/index.js
4259
34
  var dist_exports = {};
4260
35
  __export(dist_exports, {
@@ -4364,7 +139,7 @@ function cosineSimilarity(a, b) {
4364
139
  return dot;
4365
140
  }
4366
141
  function counterFile() {
4367
- return process.env.AMEM_EVO_COUNTER_PATH || path22.join(getDataDir(), "amem_evo_cnt.json");
142
+ return process.env.AMEM_EVO_COUNTER_PATH || path2.join(getDataDir(), "amem_evo_cnt.json");
4368
143
  }
4369
144
  function getEvoCount() {
4370
145
  try {
@@ -5108,7 +883,7 @@ async function addMemory(content, agentId = "main", opts) {
5108
883
  const readers = scope === "shared" ? ["*"] : [agentId];
5109
884
  const writers = [agentId];
5110
885
  const note = {
5111
- id: v4_default(),
886
+ id: (0, import_uuid.v4)(),
5112
887
  content,
5113
888
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5114
889
  keywords,
@@ -5354,7 +1129,7 @@ async function listMemories(agentId = "main", storageCtx) {
5354
1129
  const count = await ctx.countNotes(agentId);
5355
1130
  return { count };
5356
1131
  }
5357
- function sleep2(ms) {
1132
+ function sleep(ms) {
5358
1133
  return new Promise((resolve) => setTimeout(resolve, ms));
5359
1134
  }
5360
1135
  async function mergeSimilarNotes(agentId, storageCtx) {
@@ -5433,7 +1208,7 @@ async function mergeSimilarNotes(agentId, storageCtx) {
5433
1208
  } else {
5434
1209
  await ctx.patchNotePayload(pendingNote.id, { pending_merge: false, evolution_type: "NEW" });
5435
1210
  }
5436
- await sleep2(200);
1211
+ await sleep(200);
5437
1212
  }
5438
1213
  if (notes.length < 5) return evolvedCount;
5439
1214
  const pendingIds = new Set(pendingNotes.map((n) => n.id));
@@ -5468,7 +1243,7 @@ async function mergeSimilarNotes(agentId, storageCtx) {
5468
1243
  deletedIds.add(dropNote.id);
5469
1244
  mergedCount++;
5470
1245
  }
5471
- await sleep2(200);
1246
+ await sleep(200);
5472
1247
  }
5473
1248
  return evolvedCount + mergedCount;
5474
1249
  }
@@ -5581,7 +1356,7 @@ async function consolidateMemories(agentId, logger, storageCtx) {
5581
1356
  } else {
5582
1357
  log.info(` -> LLM decision: DO NOT MERGE.`);
5583
1358
  }
5584
- await sleep2(200);
1359
+ await sleep(200);
5585
1360
  }
5586
1361
  log.info(`[Consolidation] Completed consolidation run. Merged ${mergedCount} pairs.`);
5587
1362
  return mergedCount;
@@ -5708,23 +1483,23 @@ async function generateReviewBatch(agentId, outputPath) {
5708
1483
  fs3.writeFileSync(filePath, lines.join("\n"), "utf8");
5709
1484
  return filePath;
5710
1485
  }
5711
- var os, path2, fs, path22, import_crypto, fs2, path3, import_jieba, fs3, path4, _dataDir, pipeline, extractor, MODEL_NAME, EVO_THRESHOLD, LOCALE, en, zh, templates, t, client, MODEL, VALID_CONFIDENCE, VALID_CATEGORIES, VALID_EVOLUTION_TYPES, QDRANT_URL, getCollection, VECTOR_DIM, _collectionReady, _collectionReadyMap, _jieba, EPHEMERAL_SIGNALS, LOCALE2, DEFAULT_OUTPUT_DIR;
1486
+ var os, path, fs, path2, import_sdk, import_uuid, import_crypto, fs2, path3, import_jieba, fs3, path4, _dataDir, pipeline, extractor, MODEL_NAME, EVO_THRESHOLD, LOCALE, en, zh, templates, t, client, MODEL, VALID_CONFIDENCE, VALID_CATEGORIES, VALID_EVOLUTION_TYPES, QDRANT_URL, getCollection, VECTOR_DIM, _collectionReady, _collectionReadyMap, _jieba, EPHEMERAL_SIGNALS, LOCALE2, DEFAULT_OUTPUT_DIR;
5712
1487
  var init_dist = __esm({
5713
1488
  "../amem-core/dist/index.js"() {
5714
1489
  "use strict";
5715
1490
  os = __toESM(require("os"), 1);
5716
- path2 = __toESM(require("path"), 1);
1491
+ path = __toESM(require("path"), 1);
5717
1492
  fs = __toESM(require("fs"), 1);
5718
- path22 = __toESM(require("path"), 1);
5719
- init_sdk();
5720
- init_dist_node();
1493
+ path2 = __toESM(require("path"), 1);
1494
+ import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
1495
+ import_uuid = require("uuid");
5721
1496
  import_crypto = require("crypto");
5722
1497
  fs2 = __toESM(require("fs"), 1);
5723
1498
  path3 = __toESM(require("path"), 1);
5724
1499
  import_jieba = require("@node-rs/jieba");
5725
1500
  fs3 = __toESM(require("fs"), 1);
5726
1501
  path4 = __toESM(require("path"), 1);
5727
- _dataDir = process.env.AMEM_DATA_DIR || path2.join(os.homedir(), ".amem");
1502
+ _dataDir = process.env.AMEM_DATA_DIR || path.join(os.homedir(), ".amem");
5728
1503
  pipeline = null;
5729
1504
  extractor = null;
5730
1505
  MODEL_NAME = "Xenova/paraphrase-multilingual-MiniLM-L12-v2";
@@ -5902,7 +1677,7 @@ B: "\u7528\u6237\u7684 VS Code \u4F7F\u7528 One Dark Pro \u4E3B\u9898"
5902
1677
  };
5903
1678
  templates = { en, zh };
5904
1679
  t = templates[LOCALE];
5905
- client = new Anthropic({
1680
+ client = new import_sdk.default({
5906
1681
  ...process.env.AMEM_LLM_API_KEY && { apiKey: process.env.AMEM_LLM_API_KEY },
5907
1682
  ...process.env.AMEM_LLM_BASE_URL && { baseURL: process.env.AMEM_LLM_BASE_URL }
5908
1683
  });