@zhanngning/hecode 0.6.1 → 0.6.3

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/standardwebhooks/src/timing_safe_equal.ts","../node_modules/@stablelib/base64/base64.ts","../node_modules/fast-sha256/sha256.js","../node_modules/standardwebhooks/src/index.ts","../node_modules/@anthropic-ai/sdk/internal/tslib.mjs","../node_modules/@anthropic-ai/sdk/src/internal/errors.ts","../node_modules/@anthropic-ai/sdk/src/core/error.ts","../node_modules/@anthropic-ai/sdk/src/lib/tools/ToolError.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/promise.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/values.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/env.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/log.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/uuid.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/sleep.ts","../node_modules/@anthropic-ai/sdk/src/version.ts","../node_modules/@anthropic-ai/sdk/src/internal/detect-platform.ts","../node_modules/@anthropic-ai/sdk/src/internal/shims.ts","../node_modules/@anthropic-ai/sdk/src/internal/request-options.ts","../node_modules/@anthropic-ai/sdk/src/internal/qs/formats.ts","../node_modules/@anthropic-ai/sdk/src/internal/qs/utils.ts","../node_modules/@anthropic-ai/sdk/src/internal/qs/stringify.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/query.ts","../node_modules/@anthropic-ai/sdk/src/lib/credentials/types.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/time.ts","../node_modules/@anthropic-ai/sdk/src/lib/credentials/token-cache.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/bytes.ts","../node_modules/@anthropic-ai/sdk/src/core/credentials.ts","../node_modules/@anthropic-ai/sdk/src/lib/credentials/identity-token.ts","../node_modules/@anthropic-ai/sdk/src/lib/credentials/oidc-federation.ts","../node_modules/@anthropic-ai/sdk/src/lib/credentials/user-oauth.ts","../node_modules/@anthropic-ai/sdk/src/lib/credentials/credential-chain.ts","../node_modules/@anthropic-ai/sdk/src/internal/decoders/line.ts","../node_modules/@anthropic-ai/sdk/src/core/streaming.ts","../node_modules/@anthropic-ai/sdk/src/internal/parse.ts","../node_modules/@anthropic-ai/sdk/src/core/middleware.ts","../node_modules/@anthropic-ai/sdk/src/core/api-promise.ts","../node_modules/@anthropic-ai/sdk/src/core/pagination.ts","../node_modules/@anthropic-ai/sdk/src/internal/uploads.ts","../node_modules/@anthropic-ai/sdk/src/internal/to-file.ts","../node_modules/@anthropic-ai/sdk/src/core/resource.ts","../node_modules/@anthropic-ai/sdk/src/internal/headers.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/path.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/deployment-runs.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/deployments.ts","../node_modules/@anthropic-ai/sdk/src/internal/stainless-helper-header.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/files.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/models.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/user-profiles.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/webhooks.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/agents/versions.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/agents/agents.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/abort.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/backoff.ts","../node_modules/@anthropic-ai/sdk/src/lib/helper-client.ts","../node_modules/@anthropic-ai/sdk/src/lib/environments/poller.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/async-queue.ts","../node_modules/@anthropic-ai/sdk/src/lib/tools/BetaRunnableTool.ts","../node_modules/@anthropic-ai/sdk/src/lib/tools/SessionToolRunner.ts","../node_modules/@anthropic-ai/sdk/src/lib/environments/worker.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/environments/work.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/environments/environments.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/memory-stores/memories.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/memory-stores/memory-versions.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/memory-stores/memory-stores.ts","../node_modules/@anthropic-ai/sdk/src/internal/decoders/jsonl.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/messages/batches.ts","../node_modules/@anthropic-ai/sdk/src/internal/constants.ts","../node_modules/@anthropic-ai/sdk/src/lib/beta-parser.ts","../node_modules/@anthropic-ai/sdk/src/_vendor/partial-json-parser/parser.ts","../node_modules/@anthropic-ai/sdk/src/internal/message-stream-utils.ts","../node_modules/@anthropic-ai/sdk/src/lib/BetaMessageStream.ts","../node_modules/@anthropic-ai/sdk/src/lib/tools/CompactionControl.ts","../node_modules/@anthropic-ai/sdk/src/lib/tools/BetaToolRunner.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/messages/messages.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/sessions/events.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/sessions/resources.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/sessions/threads/events.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/sessions/threads/threads.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/sessions/sessions.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/skills/versions.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/skills/skills.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/vaults/credentials.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/vaults/vaults.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/beta.ts","../node_modules/@anthropic-ai/sdk/src/resources/completions.ts","../node_modules/@anthropic-ai/sdk/src/lib/parser.ts","../node_modules/@anthropic-ai/sdk/src/lib/MessageStream.ts","../node_modules/@anthropic-ai/sdk/src/resources/messages/batches.ts","../node_modules/@anthropic-ai/sdk/src/resources/messages/messages.ts","../node_modules/@anthropic-ai/sdk/src/resources/models.ts","../node_modules/@anthropic-ai/sdk/src/client.ts","../node_modules/@anthropic-ai/sdk/src/lib/middleware.ts"],"sourcesContent":[null,"// Copyright (C) 2016 Dmitry Chestnykh\n// MIT License. See LICENSE file for details.\n\n/**\n * Package base64 implements Base64 encoding and decoding.\n */\n\n// Invalid character used in decoding to indicate\n// that the character to decode is out of range of\n// alphabet and cannot be decoded.\nconst INVALID_BYTE = 256;\n\n/**\n * Implements standard Base64 encoding.\n *\n * Operates in constant time.\n */\nexport class Coder {\n // TODO(dchest): methods to encode chunk-by-chunk.\n\n constructor(private _paddingCharacter = \"=\") { }\n\n encodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 8 + 5) / 6 | 0;\n }\n return (length + 2) / 3 * 4 | 0;\n }\n\n encode(data: Uint8Array): string {\n let out = \"\";\n\n let i = 0;\n for (; i < data.length - 2; i += 3) {\n let c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n out += this._encodeByte((c >>> 1 * 6) & 63);\n out += this._encodeByte((c >>> 0 * 6) & 63);\n }\n\n const left = data.length - i;\n if (left > 0) {\n let c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);\n out += this._encodeByte((c >>> 3 * 6) & 63);\n out += this._encodeByte((c >>> 2 * 6) & 63);\n if (left === 2) {\n out += this._encodeByte((c >>> 1 * 6) & 63);\n } else {\n out += this._paddingCharacter || \"\";\n }\n out += this._paddingCharacter || \"\";\n }\n\n return out;\n }\n\n maxDecodedLength(length: number): number {\n if (!this._paddingCharacter) {\n return (length * 6 + 7) / 8 | 0;\n }\n return length / 4 * 3 | 0;\n }\n\n decodedLength(s: string): number {\n return this.maxDecodedLength(s.length - this._getPaddingLength(s));\n }\n\n decode(s: string): Uint8Array {\n if (s.length === 0) {\n return new Uint8Array(0);\n }\n const paddingLength = this._getPaddingLength(s);\n const length = s.length - paddingLength;\n const out = new Uint8Array(this.maxDecodedLength(length));\n let op = 0;\n let i = 0;\n let haveBad = 0;\n let v0 = 0, v1 = 0, v2 = 0, v3 = 0;\n for (; i < length - 4; i += 4) {\n v0 = this._decodeChar(s.charCodeAt(i + 0));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n out[op++] = (v1 << 4) | (v2 >>> 2);\n out[op++] = (v2 << 6) | v3;\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n haveBad |= v2 & INVALID_BYTE;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (i < length - 1) {\n v0 = this._decodeChar(s.charCodeAt(i));\n v1 = this._decodeChar(s.charCodeAt(i + 1));\n out[op++] = (v0 << 2) | (v1 >>> 4);\n haveBad |= v0 & INVALID_BYTE;\n haveBad |= v1 & INVALID_BYTE;\n }\n if (i < length - 2) {\n v2 = this._decodeChar(s.charCodeAt(i + 2));\n out[op++] = (v1 << 4) | (v2 >>> 2);\n haveBad |= v2 & INVALID_BYTE;\n }\n if (i < length - 3) {\n v3 = this._decodeChar(s.charCodeAt(i + 3));\n out[op++] = (v2 << 6) | v3;\n haveBad |= v3 & INVALID_BYTE;\n }\n if (haveBad !== 0) {\n throw new Error(\"Base64Coder: incorrect characters for decoding\");\n }\n return out;\n }\n\n // Standard encoding have the following encoded/decoded ranges,\n // which we need to convert between.\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 43 47\n //\n\n // Encode 6 bits in b into a new character.\n protected _encodeByte(b: number): string {\n // Encoding uses constant time operations as follows:\n //\n // 1. Define comparison of A with B using (A - B) >>> 8:\n // if A > B, then result is positive integer\n // if A <= B, then result is 0\n //\n // 2. Define selection of C or 0 using bitwise AND: X & C:\n // if X == 0, then result is 0\n // if X != 0, then result is C\n //\n // 3. Start with the smallest comparison (b >= 0), which is always\n // true, so set the result to the starting ASCII value (65).\n //\n // 4. Continue comparing b to higher ASCII values, and selecting\n // zero if comparison isn't true, otherwise selecting a value\n // to add to result, which:\n //\n // a) undoes the previous addition\n // b) provides new value to add\n //\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);\n\n return String.fromCharCode(result);\n }\n\n // Decode a character code into a byte.\n // Must return 256 if character is out of alphabet range.\n protected _decodeChar(c: number): number {\n // Decoding works similar to encoding: using the same comparison\n // function, but now it works on ranges: result is always incremented\n // by value, but this value becomes zero if the range is not\n // satisfied.\n //\n // Decoding starts with invalid value, 256, which is then\n // subtracted when the range is satisfied. If none of the ranges\n // apply, the function returns 256, which is then checked by\n // the caller to throw error.\n let result = INVALID_BYTE; // start with invalid character\n\n // c == 43 (c > 42 and c < 44)\n result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);\n // c == 47 (c > 46 and c < 48)\n result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n\n private _getPaddingLength(s: string): number {\n let paddingLength = 0;\n if (this._paddingCharacter) {\n for (let i = s.length - 1; i >= 0; i--) {\n if (s[i] !== this._paddingCharacter) {\n break;\n }\n paddingLength++;\n }\n if (s.length < 4 || paddingLength > 2) {\n throw new Error(\"Base64Coder: incorrect padding\");\n }\n }\n return paddingLength;\n }\n\n}\n\nconst stdCoder = new Coder();\n\nexport function encode(data: Uint8Array): string {\n return stdCoder.encode(data);\n}\n\nexport function decode(s: string): Uint8Array {\n return stdCoder.decode(s);\n}\n\n/**\n * Implements URL-safe Base64 encoding.\n * (Same as Base64, but '+' is replaced with '-', and '/' with '_').\n *\n * Operates in constant time.\n */\nexport class URLSafeCoder extends Coder {\n // URL-safe encoding have the following encoded/decoded ranges:\n //\n // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _\n // Index: 0 - 25 26 - 51 52 - 61 62 63\n // ASCII: 65 - 90 97 - 122 48 - 57 45 95\n //\n\n protected _encodeByte(b: number): string {\n let result = b;\n // b >= 0\n result += 65;\n // b > 25\n result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);\n // b > 51\n result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);\n // b > 61\n result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);\n // b > 62\n result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);\n\n return String.fromCharCode(result);\n }\n\n protected _decodeChar(c: number): number {\n let result = INVALID_BYTE;\n\n // c == 45 (c > 44 and c < 46)\n result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);\n // c == 95 (c > 94 and c < 96)\n result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);\n // c > 47 and c < 58\n result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);\n // c > 64 and c < 91\n result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);\n // c > 96 and c < 123\n result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);\n\n return result;\n }\n}\n\nconst urlSafeCoder = new URLSafeCoder();\n\nexport function encodeURLSafe(data: Uint8Array): string {\n return urlSafeCoder.encode(data);\n}\n\nexport function decodeURLSafe(s: string): Uint8Array {\n return urlSafeCoder.decode(s);\n}\n\n\nexport const encodedLength = (length: number) =>\n stdCoder.encodedLength(length);\n\nexport const maxDecodedLength = (length: number) =>\n stdCoder.maxDecodedLength(length);\n\nexport const decodedLength = (s: string) =>\n stdCoder.decodedLength(s);\n","(function (root, factory) {\n // Hack to make all exports of this module sha256 function object properties.\n var exports = {};\n factory(exports);\n var sha256 = exports[\"default\"];\n for (var k in exports) {\n sha256[k] = exports[k];\n }\n \n if (typeof module === 'object' && typeof module.exports === 'object') {\n module.exports = sha256;\n } else if (typeof define === 'function' && define.amd) {\n define(function() { return sha256; }); \n } else {\n root.sha256 = sha256;\n }\n})(this, function(exports) {\n\"use strict\";\nexports.__esModule = true;\n// SHA-256 (+ HMAC and PBKDF2) for JavaScript.\n//\n// Written in 2014-2016 by Dmitry Chestnykh.\n// Public domain, no warranty.\n//\n// Functions (accept and return Uint8Arrays):\n//\n// sha256(message) -> hash\n// sha256.hmac(key, message) -> mac\n// sha256.pbkdf2(password, salt, rounds, dkLen) -> dk\n//\n// Classes:\n//\n// new sha256.Hash()\n// new sha256.HMAC(key)\n//\nexports.digestLength = 32;\nexports.blockSize = 64;\n// SHA-256 constants\nvar K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,\n 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,\n 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,\n 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,\n 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,\n 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,\n 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,\n 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\nfunction hashBlocks(w, v, p, pos, len) {\n var a, b, c, d, e, f, g, h, u, i, j, t1, t2;\n while (len >= 64) {\n a = v[0];\n b = v[1];\n c = v[2];\n d = v[3];\n e = v[4];\n f = v[5];\n g = v[6];\n h = v[7];\n for (i = 0; i < 16; i++) {\n j = pos + i * 4;\n w[i] = (((p[j] & 0xff) << 24) | ((p[j + 1] & 0xff) << 16) |\n ((p[j + 2] & 0xff) << 8) | (p[j + 3] & 0xff));\n }\n for (i = 16; i < 64; i++) {\n u = w[i - 2];\n t1 = (u >>> 17 | u << (32 - 17)) ^ (u >>> 19 | u << (32 - 19)) ^ (u >>> 10);\n u = w[i - 15];\n t2 = (u >>> 7 | u << (32 - 7)) ^ (u >>> 18 | u << (32 - 18)) ^ (u >>> 3);\n w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);\n }\n for (i = 0; i < 64; i++) {\n t1 = (((((e >>> 6 | e << (32 - 6)) ^ (e >>> 11 | e << (32 - 11)) ^\n (e >>> 25 | e << (32 - 25))) + ((e & f) ^ (~e & g))) | 0) +\n ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;\n t2 = (((a >>> 2 | a << (32 - 2)) ^ (a >>> 13 | a << (32 - 13)) ^\n (a >>> 22 | a << (32 - 22))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n h = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n v[0] += a;\n v[1] += b;\n v[2] += c;\n v[3] += d;\n v[4] += e;\n v[5] += f;\n v[6] += g;\n v[7] += h;\n pos += 64;\n len -= 64;\n }\n return pos;\n}\n// Hash implements SHA256 hash algorithm.\nvar Hash = /** @class */ (function () {\n function Hash() {\n this.digestLength = exports.digestLength;\n this.blockSize = exports.blockSize;\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n this.state = new Int32Array(8); // hash state\n this.temp = new Int32Array(64); // temporary state\n this.buffer = new Uint8Array(128); // buffer for data to hash\n this.bufferLength = 0; // number of bytes in buffer\n this.bytesHashed = 0; // number of total bytes hashed\n this.finished = false; // indicates whether the hash was finalized\n this.reset();\n }\n // Resets hash state making it possible\n // to re-use this instance to hash other data.\n Hash.prototype.reset = function () {\n this.state[0] = 0x6a09e667;\n this.state[1] = 0xbb67ae85;\n this.state[2] = 0x3c6ef372;\n this.state[3] = 0xa54ff53a;\n this.state[4] = 0x510e527f;\n this.state[5] = 0x9b05688c;\n this.state[6] = 0x1f83d9ab;\n this.state[7] = 0x5be0cd19;\n this.bufferLength = 0;\n this.bytesHashed = 0;\n this.finished = false;\n return this;\n };\n // Cleans internal buffers and re-initializes hash state.\n Hash.prototype.clean = function () {\n for (var i = 0; i < this.buffer.length; i++) {\n this.buffer[i] = 0;\n }\n for (var i = 0; i < this.temp.length; i++) {\n this.temp[i] = 0;\n }\n this.reset();\n };\n // Updates hash state with the given data.\n //\n // Optionally, length of the data can be specified to hash\n // fewer bytes than data.length.\n //\n // Throws error when trying to update already finalized hash:\n // instance must be reset to use it again.\n Hash.prototype.update = function (data, dataLength) {\n if (dataLength === void 0) { dataLength = data.length; }\n if (this.finished) {\n throw new Error(\"SHA256: can't update because hash was finished.\");\n }\n var dataPos = 0;\n this.bytesHashed += dataLength;\n if (this.bufferLength > 0) {\n while (this.bufferLength < 64 && dataLength > 0) {\n this.buffer[this.bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this.bufferLength === 64) {\n hashBlocks(this.temp, this.state, this.buffer, 0, 64);\n this.bufferLength = 0;\n }\n }\n if (dataLength >= 64) {\n dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);\n dataLength %= 64;\n }\n while (dataLength > 0) {\n this.buffer[this.bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n };\n // Finalizes hash state and puts hash into out.\n //\n // If hash was already finalized, puts the same value.\n Hash.prototype.finish = function (out) {\n if (!this.finished) {\n var bytesHashed = this.bytesHashed;\n var left = this.bufferLength;\n var bitLenHi = (bytesHashed / 0x20000000) | 0;\n var bitLenLo = bytesHashed << 3;\n var padLength = (bytesHashed % 64 < 56) ? 64 : 128;\n this.buffer[left] = 0x80;\n for (var i = left + 1; i < padLength - 8; i++) {\n this.buffer[i] = 0;\n }\n this.buffer[padLength - 8] = (bitLenHi >>> 24) & 0xff;\n this.buffer[padLength - 7] = (bitLenHi >>> 16) & 0xff;\n this.buffer[padLength - 6] = (bitLenHi >>> 8) & 0xff;\n this.buffer[padLength - 5] = (bitLenHi >>> 0) & 0xff;\n this.buffer[padLength - 4] = (bitLenLo >>> 24) & 0xff;\n this.buffer[padLength - 3] = (bitLenLo >>> 16) & 0xff;\n this.buffer[padLength - 2] = (bitLenLo >>> 8) & 0xff;\n this.buffer[padLength - 1] = (bitLenLo >>> 0) & 0xff;\n hashBlocks(this.temp, this.state, this.buffer, 0, padLength);\n this.finished = true;\n }\n for (var i = 0; i < 8; i++) {\n out[i * 4 + 0] = (this.state[i] >>> 24) & 0xff;\n out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff;\n out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff;\n out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff;\n }\n return this;\n };\n // Returns the final hash digest.\n Hash.prototype.digest = function () {\n var out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n };\n // Internal function for use in HMAC for optimization.\n Hash.prototype._saveState = function (out) {\n for (var i = 0; i < this.state.length; i++) {\n out[i] = this.state[i];\n }\n };\n // Internal function for use in HMAC for optimization.\n Hash.prototype._restoreState = function (from, bytesHashed) {\n for (var i = 0; i < this.state.length; i++) {\n this.state[i] = from[i];\n }\n this.bytesHashed = bytesHashed;\n this.finished = false;\n this.bufferLength = 0;\n };\n return Hash;\n}());\nexports.Hash = Hash;\n// HMAC implements HMAC-SHA256 message authentication algorithm.\nvar HMAC = /** @class */ (function () {\n function HMAC(key) {\n this.inner = new Hash();\n this.outer = new Hash();\n this.blockSize = this.inner.blockSize;\n this.digestLength = this.inner.digestLength;\n var pad = new Uint8Array(this.blockSize);\n if (key.length > this.blockSize) {\n (new Hash()).update(key).finish(pad).clean();\n }\n else {\n for (var i = 0; i < key.length; i++) {\n pad[i] = key[i];\n }\n }\n for (var i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36;\n }\n this.inner.update(pad);\n for (var i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36 ^ 0x5c;\n }\n this.outer.update(pad);\n this.istate = new Uint32Array(8);\n this.ostate = new Uint32Array(8);\n this.inner._saveState(this.istate);\n this.outer._saveState(this.ostate);\n for (var i = 0; i < pad.length; i++) {\n pad[i] = 0;\n }\n }\n // Returns HMAC state to the state initialized with key\n // to make it possible to run HMAC over the other data with the same\n // key without creating a new instance.\n HMAC.prototype.reset = function () {\n this.inner._restoreState(this.istate, this.inner.blockSize);\n this.outer._restoreState(this.ostate, this.outer.blockSize);\n return this;\n };\n // Cleans HMAC state.\n HMAC.prototype.clean = function () {\n for (var i = 0; i < this.istate.length; i++) {\n this.ostate[i] = this.istate[i] = 0;\n }\n this.inner.clean();\n this.outer.clean();\n };\n // Updates state with provided data.\n HMAC.prototype.update = function (data) {\n this.inner.update(data);\n return this;\n };\n // Finalizes HMAC and puts the result in out.\n HMAC.prototype.finish = function (out) {\n if (this.outer.finished) {\n this.outer.finish(out);\n }\n else {\n this.inner.finish(out);\n this.outer.update(out, this.digestLength).finish(out);\n }\n return this;\n };\n // Returns message authentication code.\n HMAC.prototype.digest = function () {\n var out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n };\n return HMAC;\n}());\nexports.HMAC = HMAC;\n// Returns SHA256 hash of data.\nfunction hash(data) {\n var h = (new Hash()).update(data);\n var digest = h.digest();\n h.clean();\n return digest;\n}\nexports.hash = hash;\n// Function hash is both available as module.hash and as default export.\nexports[\"default\"] = hash;\n// Returns HMAC-SHA256 of data under the key.\nfunction hmac(key, data) {\n var h = (new HMAC(key)).update(data);\n var digest = h.digest();\n h.clean();\n return digest;\n}\nexports.hmac = hmac;\n// Fills hkdf buffer like this:\n// T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)\nfunction fillBuffer(buffer, hmac, info, counter) {\n // Counter is a byte value: check if it overflowed.\n var num = counter[0];\n if (num === 0) {\n throw new Error(\"hkdf: cannot expand more\");\n }\n // Prepare HMAC instance for new data with old key.\n hmac.reset();\n // Hash in previous output if it was generated\n // (i.e. counter is greater than 1).\n if (num > 1) {\n hmac.update(buffer);\n }\n // Hash in info if it exists.\n if (info) {\n hmac.update(info);\n }\n // Hash in the counter.\n hmac.update(counter);\n // Output result to buffer and clean HMAC instance.\n hmac.finish(buffer);\n // Increment counter inside typed array, this works properly.\n counter[0]++;\n}\nvar hkdfSalt = new Uint8Array(exports.digestLength); // Filled with zeroes.\nfunction hkdf(key, salt, info, length) {\n if (salt === void 0) { salt = hkdfSalt; }\n if (length === void 0) { length = 32; }\n var counter = new Uint8Array([1]);\n // HKDF-Extract uses salt as HMAC key, and key as data.\n var okm = hmac(salt, key);\n // Initialize HMAC for expanding with extracted key.\n // Ensure no collisions with `hmac` function.\n var hmac_ = new HMAC(okm);\n // Allocate buffer.\n var buffer = new Uint8Array(hmac_.digestLength);\n var bufpos = buffer.length;\n var out = new Uint8Array(length);\n for (var i = 0; i < length; i++) {\n if (bufpos === buffer.length) {\n fillBuffer(buffer, hmac_, info, counter);\n bufpos = 0;\n }\n out[i] = buffer[bufpos++];\n }\n hmac_.clean();\n buffer.fill(0);\n counter.fill(0);\n return out;\n}\nexports.hkdf = hkdf;\n// Derives a key from password and salt using PBKDF2-HMAC-SHA256\n// with the given number of iterations.\n//\n// The number of bytes returned is equal to dkLen.\n//\n// (For better security, avoid dkLen greater than hash length - 32 bytes).\nfunction pbkdf2(password, salt, iterations, dkLen) {\n var prf = new HMAC(password);\n var len = prf.digestLength;\n var ctr = new Uint8Array(4);\n var t = new Uint8Array(len);\n var u = new Uint8Array(len);\n var dk = new Uint8Array(dkLen);\n for (var i = 0; i * len < dkLen; i++) {\n var c = i + 1;\n ctr[0] = (c >>> 24) & 0xff;\n ctr[1] = (c >>> 16) & 0xff;\n ctr[2] = (c >>> 8) & 0xff;\n ctr[3] = (c >>> 0) & 0xff;\n prf.reset();\n prf.update(salt);\n prf.update(ctr);\n prf.finish(u);\n for (var j = 0; j < len; j++) {\n t[j] = u[j];\n }\n for (var j = 2; j <= iterations; j++) {\n prf.reset();\n prf.update(u).finish(u);\n for (var k = 0; k < len; k++) {\n t[k] ^= u[k];\n }\n }\n for (var j = 0; j < len && i * len + j < dkLen; j++) {\n dk[i * len + j] = t[j];\n }\n }\n for (var i = 0; i < len; i++) {\n t[i] = u[i] = 0;\n }\n for (var i = 0; i < 4; i++) {\n ctr[i] = 0;\n }\n prf.clean();\n return dk;\n}\nexports.pbkdf2 = pbkdf2;\n});\n",null,"function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\")\n throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f)\n throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver))\n throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return kind === \"a\" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value;\n}\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f)\n throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver))\n throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\nexport { __classPrivateFieldSet, __classPrivateFieldGet };\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nexport function isAbortError(err: unknown) {\n return (\n typeof err === 'object' &&\n err !== null &&\n // Spec-compliant fetch implementations\n (('name' in err && (err as any).name === 'AbortError') ||\n // Expo fetch\n ('message' in err && String((err as any).message).includes('FetchRequestCanceledException')))\n );\n}\n\nexport const castToError = (err: any): Error => {\n if (err instanceof Error) return err;\n if (typeof err === 'object' && err !== null) {\n try {\n if (Object.prototype.toString.call(err) === '[object Error]') {\n // @ts-ignore - not all envs have native support for cause yet\n const error = new Error(err.message, err.cause ? { cause: err.cause } : {});\n if (err.stack) error.stack = err.stack;\n // @ts-ignore - not all envs have native support for cause yet\n if (err.cause && !error.cause) error.cause = err.cause;\n if (err.name) error.name = err.name;\n return error;\n }\n } catch {}\n try {\n return new Error(JSON.stringify(err));\n } catch {}\n }\n return new Error(err);\n};\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { castToError } from '../internal/errors';\nimport type { ErrorType } from '../resources/shared';\n\nexport class AnthropicError extends Error {}\n\nexport class APIError<\n TStatus extends number | undefined = number | undefined,\n THeaders extends Headers | undefined = Headers | undefined,\n TError extends Object | undefined = Object | undefined,\n> extends AnthropicError {\n /** HTTP status for the response that caused the error */\n readonly status: TStatus;\n /** HTTP headers for the response that caused the error */\n readonly headers: THeaders;\n /** JSON body of the response that caused the error */\n readonly error: TError;\n\n readonly requestID: string | null | undefined;\n\n /** The `error.type` from the API response body, e.g. `\"rate_limit_error\"` */\n readonly type: ErrorType | null;\n\n constructor(\n status: TStatus,\n error: TError,\n message: string | undefined,\n headers: THeaders,\n type?: ErrorType | null,\n ) {\n super(`${APIError.makeMessage(status, error, message)}`);\n this.status = status;\n this.headers = headers;\n this.requestID = headers?.get('request-id');\n this.error = error;\n this.type = type ?? null;\n }\n\n private static makeMessage(status: number | undefined, error: any, message: string | undefined) {\n const msg =\n error?.message ?\n typeof error.message === 'string' ?\n error.message\n : JSON.stringify(error.message)\n : error ? JSON.stringify(error)\n : message;\n\n if (status && msg) {\n return `${status} ${msg}`;\n }\n if (status) {\n return `${status} status code (no body)`;\n }\n if (msg) {\n return msg;\n }\n return '(no status code or body)';\n }\n\n static generate(\n status: number | undefined,\n errorResponse: Object | undefined,\n message: string | undefined,\n headers: Headers | undefined,\n ): APIError {\n if (!status || !headers) {\n return new APIConnectionError({ message, cause: castToError(errorResponse) });\n }\n\n const error = errorResponse as Record<string, any>;\n const type = error?.['error']?.['type'] as ErrorType | undefined;\n\n if (status === 400) {\n return new BadRequestError(status, error, message, headers, type);\n }\n\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers, type);\n }\n\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers, type);\n }\n\n if (status === 404) {\n return new NotFoundError(status, error, message, headers, type);\n }\n\n if (status === 409) {\n return new ConflictError(status, error, message, headers, type);\n }\n\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers, type);\n }\n\n if (status === 429) {\n return new RateLimitError(status, error, message, headers, type);\n }\n\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers, type);\n }\n\n return new APIError(status, error, message, headers, type);\n }\n}\n\nexport class APIUserAbortError extends APIError<undefined, undefined, undefined> {\n constructor({ message }: { message?: string } = {}) {\n super(undefined, undefined, message || 'Request was aborted.', undefined);\n }\n}\n\nexport class APIConnectionError extends APIError<undefined, undefined, undefined> {\n constructor({ message, cause }: { message?: string | undefined; cause?: Error | undefined }) {\n super(undefined, undefined, message || 'Connection error.', undefined);\n // in some environments the 'cause' property is already declared\n // @ts-ignore\n if (cause) this.cause = cause;\n }\n}\n\nexport class APIConnectionTimeoutError extends APIConnectionError {\n constructor({ message }: { message?: string } = {}) {\n super({ message: message ?? 'Request timed out.' });\n }\n}\n\n/**\n * An error that opts into the SDK's retry policy: throw it (e.g. from\n * middleware) to have the attempt retried.\n *\n * Note that the request will only be retried when `maxRetries` has not been exhausted.\n */\nexport class RetryableError extends AnthropicError {\n constructor(message?: string, { cause }: { cause?: unknown } = {}) {\n super(message ?? 'Retryable error.');\n // in some environments the 'cause' property is already declared\n // @ts-ignore\n if (cause !== undefined) this.cause = cause;\n }\n}\n\nexport class BadRequestError extends APIError<400, Headers> {}\n\nexport class AuthenticationError extends APIError<401, Headers> {}\n\nexport class PermissionDeniedError extends APIError<403, Headers> {}\n\nexport class NotFoundError extends APIError<404, Headers> {}\n\nexport class ConflictError extends APIError<409, Headers> {}\n\nexport class UnprocessableEntityError extends APIError<422, Headers> {}\n\nexport class RateLimitError extends APIError<429, Headers> {}\n\nexport class InternalServerError extends APIError<number, Headers> {}\n","import { BetaToolResultContentBlockParam } from '../../resources/beta';\n\n/**\n * An error that can be thrown from a tool's `run` method to return structured\n * content blocks as the error result, rather than just a string message.\n *\n * When the ToolRunner catches this error, it will use the `content` property\n * as the tool result with `is_error: true`.\n *\n * @example\n * ```ts\n * const tool = {\n * name: 'my_tool',\n * run: async (input) => {\n * if (somethingWentWrong) {\n * throw new ToolError([\n * { type: 'text', text: 'Error details here' },\n * { type: 'image', source: { type: 'base64', data: '...', media_type: 'image/png' } },\n * ]);\n * }\n * return 'success';\n * },\n * };\n * ```\n */\nexport class ToolError extends Error {\n /**\n * The content to return as the tool result. This will be sent back to the model\n * with `is_error: true`.\n */\n readonly content: string | Array<BetaToolResultContentBlockParam>;\n\n constructor(content: string | Array<BetaToolResultContentBlockParam>) {\n const message =\n typeof content === 'string' ? content : (\n content\n .map((block) => {\n if (block.type === 'text') return block.text;\n return `[${block.type}]`;\n })\n .join(' ')\n );\n super(message);\n this.name = 'ToolError';\n this.content = content;\n }\n}\n","/**\n * A deferred: a `Promise` together with its `resolve` / `reject` functions.\n * This is `Promise.withResolvers()`, which is not available in all supported\n * runtimes.\n */\nexport function promiseWithResolvers<T>(): {\n promise: Promise<T>;\n resolve: (value: T | PromiseLike<T>) => void;\n reject: (reason?: unknown) => void;\n} {\n let resolve!: (value: T | PromiseLike<T>) => void;\n let reject!: (reason?: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { AnthropicError } from '../../core/error';\n\n// https://url.spec.whatwg.org/#url-scheme-string\nconst startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\n\nexport const isAbsoluteURL = (url: string): boolean => {\n return startsWithSchemeRegexp.test(url);\n};\n\nexport let isArray = (val: unknown): val is unknown[] => ((isArray = Array.isArray), isArray(val));\nexport let isReadonlyArray = isArray as (val: unknown) => val is readonly unknown[];\n\n/** Returns an object if the given value isn't an object, otherwise returns as-is */\nexport function maybeObj(x: unknown): object {\n if (typeof x !== 'object') {\n return {};\n }\n\n return x ?? {};\n}\n\n// https://stackoverflow.com/a/34491287\nexport function isEmptyObj(obj: Object | null | undefined): boolean {\n if (!obj) return true;\n for (const _k in obj) return false;\n return true;\n}\n\n// https://eslint.org/docs/latest/rules/no-prototype-builtins\nexport function hasOwn<T extends object = object>(obj: T, key: PropertyKey): key is keyof T {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function isObj(obj: unknown): obj is Record<string, unknown> {\n return obj != null && typeof obj === 'object' && !Array.isArray(obj);\n}\n\nexport const ensurePresent = <T>(value: T | null | undefined): T => {\n if (value == null) {\n throw new AnthropicError(`Expected a value to be given but received ${value} instead.`);\n }\n\n return value;\n};\n\nexport const validatePositiveInteger = (name: string, n: unknown): number => {\n if (typeof n !== 'number' || !Number.isInteger(n)) {\n throw new AnthropicError(`${name} must be an integer`);\n }\n if (n < 0) {\n throw new AnthropicError(`${name} must be a positive integer`);\n }\n return n;\n};\n\nexport const coerceInteger = (value: unknown): number => {\n if (typeof value === 'number') return Math.round(value);\n if (typeof value === 'string') return parseInt(value, 10);\n\n throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceFloat = (value: unknown): number => {\n if (typeof value === 'number') return value;\n if (typeof value === 'string') return parseFloat(value);\n\n throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceBoolean = (value: unknown): boolean => {\n if (typeof value === 'boolean') return value;\n if (typeof value === 'string') return value === 'true';\n return Boolean(value);\n};\n\nexport const maybeCoerceInteger = (value: unknown): number | undefined => {\n if (value == null) {\n return undefined;\n }\n return coerceInteger(value);\n};\n\nexport const maybeCoerceFloat = (value: unknown): number | undefined => {\n if (value == null) {\n return undefined;\n }\n return coerceFloat(value);\n};\n\nexport const maybeCoerceBoolean = (value: unknown): boolean | undefined => {\n if (value == null) {\n return undefined;\n }\n return coerceBoolean(value);\n};\n\nexport const safeJSON = (text: string) => {\n try {\n return JSON.parse(text);\n } catch (err) {\n return undefined;\n }\n};\n\n// Gets a value from an object, deletes the key, and returns the value (or undefined if not found)\nexport const pop = <T extends Record<string, any>, K extends string>(obj: T, key: K): T[K] => {\n const value = obj[key];\n delete obj[key];\n return value;\n};\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\n/**\n * Read an environment variable.\n *\n * Trims beginning and trailing whitespace.\n *\n * Will return undefined if the environment variable doesn't exist or cannot be accessed.\n */\nexport const readEnv = (env: string): string | undefined => {\n if (typeof (globalThis as any).process !== 'undefined') {\n return (globalThis as any).process.env?.[env]?.trim() || undefined;\n }\n if (typeof (globalThis as any).Deno !== 'undefined') {\n return (globalThis as any).Deno.env?.get?.(env)?.trim() || undefined;\n }\n return undefined;\n};\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { hasOwn } from './values';\nimport { readEnv } from './env';\nimport { type BaseAnthropic } from '../../client';\nimport { RequestOptions } from '../request-options';\n\ntype LogFn = (message: string, ...rest: unknown[]) => void;\nexport type Logger = {\n error: LogFn;\n warn: LogFn;\n info: LogFn;\n debug: LogFn;\n};\nexport type LogLevel = 'off' | 'error' | 'warn' | 'info' | 'debug';\n\nexport const defaultLogLevel: LogLevel = 'warn';\n\nconst levelNumbers = {\n off: 0,\n error: 200,\n warn: 300,\n info: 400,\n debug: 500,\n};\n\nexport const parseLogLevel = (\n maybeLevel: string | undefined,\n sourceName: string,\n logger: Logger,\n): LogLevel | undefined => {\n if (!maybeLevel) {\n return undefined;\n }\n if (hasOwn(levelNumbers, maybeLevel)) {\n return maybeLevel;\n }\n logger.warn(\n `${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(\n Object.keys(levelNumbers),\n )}`,\n );\n return undefined;\n};\n\nfunction noop() {}\n\nfunction makeLogFn(fnLevel: keyof Logger, logger: Logger | undefined, logLevel: LogLevel) {\n if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {\n return noop;\n } else {\n // Don't wrap logger functions, we want the stacktrace intact!\n return logger[fnLevel].bind(logger);\n }\n}\n\nconst noopLogger = {\n error: noop,\n warn: noop,\n info: noop,\n debug: noop,\n};\n\nlet cachedLoggers = /* @__PURE__ */ new WeakMap<Logger, [LogLevel, Logger]>();\n\nfunction filterLogger(logger: Logger, logLevel: LogLevel): Logger {\n const cachedLogger = cachedLoggers.get(logger);\n if (cachedLogger && cachedLogger[0] === logLevel) {\n return cachedLogger[1];\n }\n\n const levelLogger = {\n error: makeLogFn('error', logger, logLevel),\n warn: makeLogFn('warn', logger, logLevel),\n info: makeLogFn('info', logger, logLevel),\n debug: makeLogFn('debug', logger, logLevel),\n };\n\n cachedLoggers.set(logger, [logLevel, levelLogger]);\n\n return levelLogger;\n}\n\nexport function loggerFor(client: BaseAnthropic): Logger {\n const logger = client.logger;\n const logLevel = client.logLevel ?? 'off';\n if (!logger) {\n return noopLogger;\n }\n return filterLogger(logger, logLevel);\n}\n\nlet lastEnvLevel: string | undefined;\nlet cachedDefaultLogger: Logger | undefined;\n\n/**\n * A logger matching the client defaults — `console`, filtered to\n * `ANTHROPIC_LOG` or {@link defaultLogLevel} — for contexts with no client to\n * read the configured `logger`/`logLevel` from.\n *\n * Cached per `ANTHROPIC_LOG` value so an invalid value warns once, like a\n * client construction does, rather than on every request.\n */\nexport function defaultLogger(): Logger {\n const envLevel = readEnv('ANTHROPIC_LOG');\n if (!cachedDefaultLogger || envLevel !== lastEnvLevel) {\n lastEnvLevel = envLevel;\n cachedDefaultLogger = filterLogger(\n console,\n parseLogLevel(envLevel, \"process.env['ANTHROPIC_LOG']\", filterLogger(console, defaultLogLevel)) ??\n defaultLogLevel,\n );\n }\n return cachedDefaultLogger;\n}\n\nexport const formatRequestDetails = (details: {\n options?: RequestOptions | undefined;\n headers?: Headers | Record<string, string> | undefined;\n retryOfRequestLogID?: string | undefined;\n retryOf?: string | undefined;\n url?: string | undefined;\n status?: number | undefined;\n method?: string | undefined;\n durationMs?: number | undefined;\n message?: unknown;\n body?: unknown;\n}) => {\n if (details.options) {\n details.options = { ...details.options };\n delete details.options['headers']; // redundant + leaks internals\n }\n if (details.headers) {\n details.headers = Object.fromEntries(\n (details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(\n ([name, value]) => [\n name,\n (\n name.toLowerCase() === 'authorization' ||\n name.toLowerCase() === 'api-key' ||\n name.toLowerCase() === 'x-api-key' ||\n name.toLowerCase() === 'cookie' ||\n name.toLowerCase() === 'set-cookie'\n ) ?\n '***'\n : value,\n ],\n ),\n );\n }\n if ('retryOfRequestLogID' in details) {\n if (details.retryOfRequestLogID) {\n details.retryOf = details.retryOfRequestLogID;\n }\n delete details.retryOfRequestLogID;\n }\n return details;\n};\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\n/**\n * https://stackoverflow.com/a/2117523\n */\nexport let uuid4 = function () {\n const { crypto } = globalThis as any;\n if (crypto?.randomUUID) {\n uuid4 = crypto.randomUUID.bind(crypto);\n return crypto.randomUUID();\n }\n const u8 = new Uint8Array(1);\n const randomByte = crypto ? () => crypto.getRandomValues(u8)[0]! : () => (Math.random() * 0xff) & 0xff;\n return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) =>\n (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16),\n );\n};\n","/**\n * Resolve after `ms`, or immediately when `signal` aborts.\n *\n * When a `signal` is passed the abort listener is always removed so repeated\n * calls do not accumulate listeners on a long-lived signal. Resolves (rather\n * than rejects) on abort — callers treat abort as \"wake up early,\" not as a\n * failure; callers that want to unwind should check the signal themselves.\n */\nexport const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve) => {\n if (signal?.aborted) return resolve();\n\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n\n // `{ once: true }` auto-removes the listener if abort fires first,\n // so we only need an explicit remove on the timer-wins path above.\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n","export const VERSION = '0.106.0'; // x-release-please-version\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { VERSION } from '../version';\n\nexport const isRunningInBrowser = () => {\n return (\n // @ts-ignore\n typeof window !== 'undefined' &&\n // @ts-ignore\n typeof window.document !== 'undefined' &&\n // @ts-ignore\n typeof navigator !== 'undefined'\n );\n};\n\ntype DetectedPlatform = 'deno' | 'node' | 'edge' | 'unknown';\n\n/**\n * Note this does not detect 'browser'; for that, use getBrowserInfo().\n */\nfunction getDetectedPlatform(): DetectedPlatform {\n if (typeof Deno !== 'undefined' && Deno.build != null) {\n return 'deno';\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return 'edge';\n }\n if (\n Object.prototype.toString.call(\n typeof (globalThis as any).process !== 'undefined' ? (globalThis as any).process : 0,\n ) === '[object process]'\n ) {\n return 'node';\n }\n return 'unknown';\n}\n\ndeclare const Deno: any;\ndeclare const EdgeRuntime: any;\ntype Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown';\ntype PlatformName =\n | 'MacOS'\n | 'Linux'\n | 'Windows'\n | 'FreeBSD'\n | 'OpenBSD'\n | 'iOS'\n | 'Android'\n | `Other:${string}`\n | 'Unknown';\ntype Browser = 'ie' | 'edge' | 'chrome' | 'firefox' | 'safari';\ntype PlatformProperties = {\n 'X-Stainless-Lang': 'js';\n 'X-Stainless-Package-Version': string;\n 'X-Stainless-OS': PlatformName;\n 'X-Stainless-Arch': Arch;\n 'X-Stainless-Runtime': 'node' | 'deno' | 'edge' | `browser:${Browser}` | 'unknown';\n 'X-Stainless-Runtime-Version': string;\n};\nconst getPlatformProperties = (): PlatformProperties => {\n const detectedPlatform = getDetectedPlatform();\n if (detectedPlatform === 'deno') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(Deno.build.os),\n 'X-Stainless-Arch': normalizeArch(Deno.build.arch),\n 'X-Stainless-Runtime': 'deno',\n 'X-Stainless-Runtime-Version':\n typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',\n };\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': `other:${EdgeRuntime}`,\n 'X-Stainless-Runtime': 'edge',\n 'X-Stainless-Runtime-Version': (globalThis as any).process.version,\n };\n }\n // Check if Node.js\n if (detectedPlatform === 'node') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform((globalThis as any).process.platform ?? 'unknown'),\n 'X-Stainless-Arch': normalizeArch((globalThis as any).process.arch ?? 'unknown'),\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': (globalThis as any).process.version ?? 'unknown',\n };\n }\n\n const browserInfo = getBrowserInfo();\n if (browserInfo) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,\n 'X-Stainless-Runtime-Version': browserInfo.version,\n };\n }\n\n // TODO add support for Cloudflare workers, etc.\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': 'unknown',\n 'X-Stainless-Runtime-Version': 'unknown',\n };\n};\n\ntype BrowserInfo = {\n browser: Browser;\n version: string;\n};\n\ndeclare const navigator: { userAgent: string } | undefined;\n\n// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts\nfunction getBrowserInfo(): BrowserInfo | null {\n if (typeof navigator === 'undefined' || !navigator) {\n return null;\n }\n\n // NOTE: The order matters here!\n const browserPatterns = [\n { key: 'edge' as const, pattern: /Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie' as const, pattern: /MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie' as const, pattern: /Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'chrome' as const, pattern: /Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'firefox' as const, pattern: /Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'safari' as const, pattern: /(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/ },\n ];\n\n // Find the FIRST matching browser\n for (const { key, pattern } of browserPatterns) {\n const match = pattern.exec(navigator.userAgent);\n if (match) {\n const major = match[1] || 0;\n const minor = match[2] || 0;\n const patch = match[3] || 0;\n\n return { browser: key, version: `${major}.${minor}.${patch}` };\n }\n }\n\n return null;\n}\n\nconst normalizeArch = (arch: string): Arch => {\n // Node docs:\n // - https://nodejs.org/api/process.html#processarch\n // Deno docs:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n if (arch === 'x32') return 'x32';\n if (arch === 'x86_64' || arch === 'x64') return 'x64';\n if (arch === 'arm') return 'arm';\n if (arch === 'aarch64' || arch === 'arm64') return 'arm64';\n if (arch) return `other:${arch}`;\n return 'unknown';\n};\n\nconst normalizePlatform = (platform: string): PlatformName => {\n // Node platforms:\n // - https://nodejs.org/api/process.html#processplatform\n // Deno platforms:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n // - https://github.com/denoland/deno/issues/14799\n\n platform = platform.toLowerCase();\n\n // NOTE: this iOS check is untested and may not work\n // Node does not work natively on IOS, there is a fork at\n // https://github.com/nodejs-mobile/nodejs-mobile\n // however it is unknown at the time of writing how to detect if it is running\n if (platform.includes('ios')) return 'iOS';\n if (platform === 'android') return 'Android';\n if (platform === 'darwin') return 'MacOS';\n if (platform === 'win32') return 'Windows';\n if (platform === 'freebsd') return 'FreeBSD';\n if (platform === 'openbsd') return 'OpenBSD';\n if (platform === 'linux') return 'Linux';\n if (platform) return `Other:${platform}`;\n return 'Unknown';\n};\n\nlet _platformHeaders: PlatformProperties;\nexport const getPlatformHeaders = () => {\n return (_platformHeaders ??= getPlatformProperties());\n};\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\n/**\n * This module provides internal shims and utility functions for environments where certain Node.js or global types may not be available.\n *\n * These are used to ensure we can provide a consistent behaviour between different JavaScript environments and good error\n * messages in cases where an environment isn't fully supported.\n */\n\nimport type { Fetch } from './builtin-types';\nimport type { ReadableStream } from './shim-types';\n\nexport function getDefaultFetch(): Fetch {\n if (typeof fetch !== 'undefined') {\n return fetch as any;\n }\n\n throw new Error(\n '`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`',\n );\n}\n\ntype ReadableStreamArgs = ConstructorParameters<typeof ReadableStream>;\n\nexport function makeReadableStream(...args: ReadableStreamArgs): ReadableStream {\n const ReadableStream = (globalThis as any).ReadableStream;\n if (typeof ReadableStream === 'undefined') {\n // Note: All of the platforms / runtimes we officially support already define\n // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.\n throw new Error(\n '`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`',\n );\n }\n\n return new ReadableStream(...args);\n}\n\nexport function ReadableStreamFrom<T>(iterable: Iterable<T> | AsyncIterable<T>): ReadableStream<T> {\n let iter: AsyncIterator<T> | Iterator<T> =\n Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();\n\n return makeReadableStream({\n start() {},\n async pull(controller: any) {\n const { done, value } = await iter.next();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n}\n\n/**\n * Most browsers don't yet have async iterable support for ReadableStream,\n * and Node has a very different way of reading bytes from its \"ReadableStream\".\n *\n * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nexport function ReadableStreamToAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {\n if (stream[Symbol.asyncIterator]) return stream;\n\n const reader = stream.getReader();\n return {\n async next() {\n try {\n const result = await reader.read();\n if (result?.done) reader.releaseLock(); // release lock when stream becomes closed\n return result;\n } catch (e) {\n reader.releaseLock(); // release lock when stream becomes errored\n throw e;\n }\n },\n async return() {\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n return { done: true, value: undefined };\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n\n/**\n * Cancels a ReadableStream we don't need to consume.\n * See https://undici.nodejs.org/#/?id=garbage-collection\n */\nexport async function CancelReadableStream(stream: any): Promise<void> {\n if (stream === null || typeof stream !== 'object') return;\n\n if (stream[Symbol.asyncIterator]) {\n await stream[Symbol.asyncIterator]().return?.();\n return;\n }\n\n const reader = stream.getReader();\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { NullableHeaders } from './headers';\n\nimport type { BodyInit } from './builtin-types';\nimport { Stream } from '../core/streaming';\nimport type { Middleware } from '../core/middleware';\nimport type { HTTPMethod, MergedRequestInit } from './types';\nimport { type HeadersLike } from './headers';\n\nexport type FinalRequestOptions = RequestOptions & { method: HTTPMethod; path: string };\n\n/**\n * Tracks which fallback a sequence of requests is pinned to.\n *\n * Create one (`new BetaFallbackState()`) and pass it via the `fallbackState`\n * request option on every request that should share the pin — the turns of one\n * conversation, or any wider scope the stickiness should apply to;\n * `betaRefusalFallbackMiddleware` mutates it in place when a model refuses.\n */\nexport class BetaFallbackState {\n /**\n * Index into the fallback chain the requests are pinned to.\n *\n * `undefined` (or -1) targets the original request params; the middleware\n * sets it to the index of the fallback that accepted the request.\n */\n index?: number;\n}\n\n/**\n * Options for an individual API request.\n *\n * Declared as an interface so it can be extended via declaration merging, e.g.\n * to thread custom per-request context through to {@link Middleware}:\n *\n * ```ts\n * declare module '@anthropic-ai/sdk/internal/request-options' {\n * interface RequestOptions {\n * myContext?: string;\n * }\n * }\n * ```\n *\n * The SDK ignores properties it doesn't know about; they are visible to\n * middleware on `ctx.options`.\n */\nexport interface RequestOptions {\n /**\n * The HTTP method for the request (e.g., 'get', 'post', 'put', 'delete').\n */\n method?: HTTPMethod;\n\n /**\n * The URL path for the request.\n *\n * @example \"/v1/foo\"\n */\n path?: string;\n\n /**\n * Query parameters to include in the request URL.\n */\n query?: object | undefined | null;\n\n /**\n * The request body. Can be a string, JSON object, FormData, or other supported types.\n */\n body?: unknown;\n\n /**\n * HTTP headers to include with the request. Can be a Headers object, plain object, or array of tuples.\n */\n headers?: HeadersLike;\n\n /**\n * The maximum number of times that the client will retry a request in case of a\n * temporary failure, like a network error or a 5XX error from the server.\n *\n * @default 2\n */\n maxRetries?: number;\n\n stream?: boolean | undefined;\n\n /**\n * The maximum amount of time (in milliseconds) that the client should wait for a response\n * from the server before timing out a single request.\n *\n * @unit milliseconds\n */\n timeout?: number;\n\n /**\n * Additional `RequestInit` options to be passed to the underlying `fetch` call.\n * These options will be merged with the client's default fetch options.\n */\n fetchOptions?: MergedRequestInit;\n\n /**\n * An AbortSignal that can be used to cancel the request.\n */\n signal?: AbortSignal | undefined | null;\n\n /**\n * Additional {@link Middleware} to wrap this request's HTTP attempts.\n *\n * These run after any client-level middleware (but still outside any backend\n * adaptation) and apply to every attempt of this request, including retries.\n */\n middleware?: ReadonlyArray<Middleware> | undefined;\n\n /**\n * Sticky state for `betaRefusalFallbackMiddleware`.\n *\n * The middleware records which fallback it settled on, so requests sharing\n * the state skip models that already refused. Pass the same object across\n * whatever scope the pin should apply to — typically a conversation.\n */\n fallbackState?: BetaFallbackState;\n\n /**\n * A unique key for this request to enable idempotency.\n */\n idempotencyKey?: string;\n\n /**\n * Override the default base URL for this specific request.\n */\n defaultBaseURL?: string | undefined;\n\n __binaryResponse?: boolean | undefined;\n __streamClass?: typeof Stream;\n}\n\nexport type EncodedContent = { bodyHeaders: HeadersLike; body: BodyInit };\nexport type RequestEncoder = (request: { headers: NullableHeaders; body: unknown }) => EncodedContent;\n\nexport const FallbackEncoder: RequestEncoder = ({ headers, body }) => {\n return {\n bodyHeaders: {\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n };\n};\n","import type { Format } from './types';\n\nexport const default_format: Format = 'RFC3986';\nexport const default_formatter = (v: PropertyKey) => String(v);\nexport const formatters: Record<Format, (str: PropertyKey) => string> = {\n RFC1738: (v: PropertyKey) => String(v).replace(/%20/g, '+'),\n RFC3986: default_formatter,\n};\nexport const RFC1738 = 'RFC1738';\nexport const RFC3986 = 'RFC3986';\n","import { RFC1738 } from './formats';\nimport type { DefaultEncoder, Format } from './types';\nimport { isArray } from '../utils/values';\n\nexport let has = (obj: object, key: PropertyKey): boolean => (\n (has = (Object as any).hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty)),\n has(obj, key)\n);\n\nconst hex_table = /* @__PURE__ */ (() => {\n const array = [];\n for (let i = 0; i < 256; ++i) {\n array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());\n }\n\n return array;\n})();\n\nfunction compact_queue<T extends Record<string, any>>(queue: Array<{ obj: T; prop: string }>) {\n while (queue.length > 1) {\n const item = queue.pop();\n if (!item) continue;\n\n const obj = item.obj[item.prop];\n\n if (isArray(obj)) {\n const compacted: unknown[] = [];\n\n for (let j = 0; j < obj.length; ++j) {\n if (typeof obj[j] !== 'undefined') {\n compacted.push(obj[j]);\n }\n }\n\n // @ts-ignore\n item.obj[item.prop] = compacted;\n }\n }\n}\n\nfunction array_to_object(source: any[], options: { plainObjects: boolean }) {\n const obj = options && options.plainObjects ? Object.create(null) : {};\n for (let i = 0; i < source.length; ++i) {\n if (typeof source[i] !== 'undefined') {\n obj[i] = source[i];\n }\n }\n\n return obj;\n}\n\nexport function merge(\n target: any,\n source: any,\n options: { plainObjects?: boolean; allowPrototypes?: boolean } = {},\n) {\n if (!source) {\n return target;\n }\n\n if (typeof source !== 'object') {\n if (isArray(target)) {\n target.push(source);\n } else if (target && typeof target === 'object') {\n if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) {\n target[source] = true;\n }\n } else {\n return [target, source];\n }\n\n return target;\n }\n\n if (!target || typeof target !== 'object') {\n return [target].concat(source);\n }\n\n let mergeTarget = target;\n if (isArray(target) && !isArray(source)) {\n // @ts-ignore\n mergeTarget = array_to_object(target, options);\n }\n\n if (isArray(target) && isArray(source)) {\n source.forEach(function (item, i) {\n if (has(target, i)) {\n const targetItem = target[i];\n if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {\n target[i] = merge(targetItem, item, options);\n } else {\n target.push(item);\n }\n } else {\n target[i] = item;\n }\n });\n return target;\n }\n\n return Object.keys(source).reduce(function (acc, key) {\n const value = source[key];\n\n if (has(acc, key)) {\n acc[key] = merge(acc[key], value, options);\n } else {\n acc[key] = value;\n }\n return acc;\n }, mergeTarget);\n}\n\nexport function assign_single_source(target: any, source: any) {\n return Object.keys(source).reduce(function (acc, key) {\n acc[key] = source[key];\n return acc;\n }, target);\n}\n\nexport function decode(str: string, _: any, charset: string) {\n const strWithoutPlus = str.replace(/\\+/g, ' ');\n if (charset === 'iso-8859-1') {\n // unescape never throws, no try...catch needed:\n return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);\n }\n // utf-8\n try {\n return decodeURIComponent(strWithoutPlus);\n } catch (e) {\n return strWithoutPlus;\n }\n}\n\nconst limit = 1024;\n\nexport const encode: (\n str: any,\n defaultEncoder: DefaultEncoder,\n charset: string,\n type: 'key' | 'value',\n format: Format,\n) => string = (str, _defaultEncoder, charset, _kind, format: Format) => {\n // This code was originally written by Brian White for the io.js core querystring library.\n // It has been adapted here for stricter adherence to RFC 3986\n if (str.length === 0) {\n return str;\n }\n\n let string = str;\n if (typeof str === 'symbol') {\n string = Symbol.prototype.toString.call(str);\n } else if (typeof str !== 'string') {\n string = String(str);\n }\n\n if (charset === 'iso-8859-1') {\n return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {\n return '%26%23' + parseInt($0.slice(2), 16) + '%3B';\n });\n }\n\n let out = '';\n for (let j = 0; j < string.length; j += limit) {\n const segment = string.length >= limit ? string.slice(j, j + limit) : string;\n const arr = [];\n\n for (let i = 0; i < segment.length; ++i) {\n let c = segment.charCodeAt(i);\n if (\n c === 0x2d || // -\n c === 0x2e || // .\n c === 0x5f || // _\n c === 0x7e || // ~\n (c >= 0x30 && c <= 0x39) || // 0-9\n (c >= 0x41 && c <= 0x5a) || // a-z\n (c >= 0x61 && c <= 0x7a) || // A-Z\n (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( )\n ) {\n arr[arr.length] = segment.charAt(i);\n continue;\n }\n\n if (c < 0x80) {\n arr[arr.length] = hex_table[c];\n continue;\n }\n\n if (c < 0x800) {\n arr[arr.length] = hex_table[0xc0 | (c >> 6)]! + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n\n if (c < 0xd800 || c >= 0xe000) {\n arr[arr.length] =\n hex_table[0xe0 | (c >> 12)]! + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n\n i += 1;\n c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff));\n\n arr[arr.length] =\n hex_table[0xf0 | (c >> 18)]! +\n hex_table[0x80 | ((c >> 12) & 0x3f)] +\n hex_table[0x80 | ((c >> 6) & 0x3f)] +\n hex_table[0x80 | (c & 0x3f)];\n }\n\n out += arr.join('');\n }\n\n return out;\n};\n\nexport function compact(value: any) {\n const queue = [{ obj: { o: value }, prop: 'o' }];\n const refs = [];\n\n for (let i = 0; i < queue.length; ++i) {\n const item = queue[i];\n // @ts-ignore\n const obj = item.obj[item.prop];\n\n const keys = Object.keys(obj);\n for (let j = 0; j < keys.length; ++j) {\n const key = keys[j]!;\n const val = obj[key];\n if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {\n queue.push({ obj: obj, prop: key });\n refs.push(val);\n }\n }\n }\n\n compact_queue(queue);\n\n return value;\n}\n\nexport function is_regexp(obj: any) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n}\n\nexport function is_buffer(obj: any) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));\n}\n\nexport function combine(a: any, b: any) {\n return [].concat(a, b);\n}\n\nexport function maybe_map<T>(val: T[], fn: (v: T) => T) {\n if (isArray(val)) {\n const mapped = [];\n for (let i = 0; i < val.length; i += 1) {\n mapped.push(fn(val[i]!));\n }\n return mapped;\n }\n return fn(val);\n}\n","import { encode, is_buffer, maybe_map, has } from './utils';\nimport { default_format, default_formatter, formatters } from './formats';\nimport type { NonNullableProperties, StringifyOptions } from './types';\nimport { isArray } from '../utils/values';\n\nconst array_prefix_generators = {\n brackets(prefix: PropertyKey) {\n return String(prefix) + '[]';\n },\n comma: 'comma',\n indices(prefix: PropertyKey, key: string) {\n return String(prefix) + '[' + key + ']';\n },\n repeat(prefix: PropertyKey) {\n return String(prefix);\n },\n};\n\nconst push_to_array = function (arr: any[], value_or_array: any) {\n Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]);\n};\n\nlet toISOString;\n\nconst defaults = {\n addQueryPrefix: false,\n allowDots: false,\n allowEmptyArrays: false,\n arrayFormat: 'indices',\n charset: 'utf-8',\n charsetSentinel: false,\n delimiter: '&',\n encode: true,\n encodeDotInKeys: false,\n encoder: encode,\n encodeValuesOnly: false,\n format: default_format,\n formatter: default_formatter,\n /** @deprecated */\n indices: false,\n serializeDate(date) {\n return (toISOString ??= Function.prototype.call.bind(Date.prototype.toISOString))(date);\n },\n skipNulls: false,\n strictNullHandling: false,\n} as NonNullableProperties<StringifyOptions & { formatter: (typeof formatters)['RFC1738'] }>;\n\nfunction is_non_nullish_primitive(v: unknown): v is string | number | boolean | symbol | bigint {\n return (\n typeof v === 'string' ||\n typeof v === 'number' ||\n typeof v === 'boolean' ||\n typeof v === 'symbol' ||\n typeof v === 'bigint'\n );\n}\n\nconst sentinel = {};\n\nfunction inner_stringify(\n object: any,\n prefix: PropertyKey,\n generateArrayPrefix: StringifyOptions['arrayFormat'] | ((prefix: string, key: string) => string),\n commaRoundTrip: boolean,\n allowEmptyArrays: boolean,\n strictNullHandling: boolean,\n skipNulls: boolean,\n encodeDotInKeys: boolean,\n encoder: StringifyOptions['encoder'],\n filter: StringifyOptions['filter'],\n sort: StringifyOptions['sort'],\n allowDots: StringifyOptions['allowDots'],\n serializeDate: StringifyOptions['serializeDate'],\n format: StringifyOptions['format'],\n formatter: StringifyOptions['formatter'],\n encodeValuesOnly: boolean,\n charset: StringifyOptions['charset'],\n sideChannel: WeakMap<any, any>,\n) {\n let obj = object;\n\n let tmp_sc = sideChannel;\n let step = 0;\n let find_flag = false;\n while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) {\n // Where object last appeared in the ref tree\n const pos = tmp_sc.get(object);\n step += 1;\n if (typeof pos !== 'undefined') {\n if (pos === step) {\n throw new RangeError('Cyclic object value');\n } else {\n find_flag = true; // Break while\n }\n }\n if (typeof tmp_sc.get(sentinel) === 'undefined') {\n step = 0;\n }\n }\n\n if (typeof filter === 'function') {\n obj = filter(prefix, obj);\n } else if (obj instanceof Date) {\n obj = serializeDate?.(obj);\n } else if (generateArrayPrefix === 'comma' && isArray(obj)) {\n obj = maybe_map(obj, function (value) {\n if (value instanceof Date) {\n return serializeDate?.(value);\n }\n return value;\n });\n }\n\n if (obj === null) {\n if (strictNullHandling) {\n return encoder && !encodeValuesOnly ?\n // @ts-expect-error\n encoder(prefix, defaults.encoder, charset, 'key', format)\n : prefix;\n }\n\n obj = '';\n }\n\n if (is_non_nullish_primitive(obj) || is_buffer(obj)) {\n if (encoder) {\n const key_value =\n encodeValuesOnly ? prefix\n // @ts-expect-error\n : encoder(prefix, defaults.encoder, charset, 'key', format);\n return [\n formatter?.(key_value) +\n '=' +\n // @ts-expect-error\n formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)),\n ];\n }\n return [formatter?.(prefix) + '=' + formatter?.(String(obj))];\n }\n\n const values: string[] = [];\n\n if (typeof obj === 'undefined') {\n return values;\n }\n\n let obj_keys;\n if (generateArrayPrefix === 'comma' && isArray(obj)) {\n // we need to join elements in\n if (encodeValuesOnly && encoder) {\n // @ts-expect-error values only\n obj = maybe_map(obj, encoder);\n }\n obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];\n } else if (isArray(filter)) {\n obj_keys = filter;\n } else {\n const keys = Object.keys(obj);\n obj_keys = sort ? keys.sort(sort) : keys;\n }\n\n const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\\./g, '%2E') : String(prefix);\n\n const adjusted_prefix =\n commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix;\n\n if (allowEmptyArrays && isArray(obj) && obj.length === 0) {\n return adjusted_prefix + '[]';\n }\n\n for (let j = 0; j < obj_keys.length; ++j) {\n const key = obj_keys[j];\n const value =\n // @ts-ignore\n typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key as any];\n\n if (skipNulls && value === null) {\n continue;\n }\n\n // @ts-ignore\n const encoded_key = allowDots && encodeDotInKeys ? (key as any).replace(/\\./g, '%2E') : key;\n const key_prefix =\n isArray(obj) ?\n typeof generateArrayPrefix === 'function' ?\n generateArrayPrefix(adjusted_prefix, encoded_key)\n : adjusted_prefix\n : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']');\n\n sideChannel.set(object, step);\n const valueSideChannel = new WeakMap();\n valueSideChannel.set(sentinel, sideChannel);\n push_to_array(\n values,\n inner_stringify(\n value,\n key_prefix,\n generateArrayPrefix,\n commaRoundTrip,\n allowEmptyArrays,\n strictNullHandling,\n skipNulls,\n encodeDotInKeys,\n // @ts-ignore\n generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n format,\n formatter,\n encodeValuesOnly,\n charset,\n valueSideChannel,\n ),\n );\n }\n\n return values;\n}\n\nfunction normalize_stringify_options(\n opts: StringifyOptions = defaults,\n): NonNullableProperties<Omit<StringifyOptions, 'indices'>> & { indices?: boolean } {\n if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {\n throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');\n }\n\n if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') {\n throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided');\n }\n\n if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {\n throw new TypeError('Encoder has to be a function.');\n }\n\n const charset = opts.charset || defaults.charset;\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n\n let format = default_format;\n if (typeof opts.format !== 'undefined') {\n if (!has(formatters, opts.format)) {\n throw new TypeError('Unknown format option provided.');\n }\n format = opts.format;\n }\n const formatter = formatters[format];\n\n let filter = defaults.filter;\n if (typeof opts.filter === 'function' || isArray(opts.filter)) {\n filter = opts.filter;\n }\n\n let arrayFormat: StringifyOptions['arrayFormat'];\n if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {\n arrayFormat = opts.arrayFormat;\n } else if ('indices' in opts) {\n arrayFormat = opts.indices ? 'indices' : 'repeat';\n } else {\n arrayFormat = defaults.arrayFormat;\n }\n\n if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {\n throw new TypeError('`commaRoundTrip` must be a boolean, or absent');\n }\n\n const allowDots =\n typeof opts.allowDots === 'undefined' ?\n !!opts.encodeDotInKeys === true ?\n true\n : defaults.allowDots\n : !!opts.allowDots;\n\n return {\n addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,\n // @ts-ignore\n allowDots: allowDots,\n allowEmptyArrays:\n typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,\n arrayFormat: arrayFormat,\n charset: charset,\n charsetSentinel:\n typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n commaRoundTrip: !!opts.commaRoundTrip,\n delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,\n encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,\n encodeDotInKeys:\n typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys,\n encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,\n encodeValuesOnly:\n typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,\n filter: filter,\n format: format,\n formatter: formatter,\n serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,\n skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,\n // @ts-ignore\n sort: typeof opts.sort === 'function' ? opts.sort : null,\n strictNullHandling:\n typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling,\n };\n}\n\nexport function stringify(object: any, opts: StringifyOptions = {}) {\n let obj = object;\n const options = normalize_stringify_options(opts);\n\n let obj_keys: PropertyKey[] | undefined;\n let filter;\n\n if (typeof options.filter === 'function') {\n filter = options.filter;\n obj = filter('', obj);\n } else if (isArray(options.filter)) {\n filter = options.filter;\n obj_keys = filter;\n }\n\n const keys: string[] = [];\n\n if (typeof obj !== 'object' || obj === null) {\n return '';\n }\n\n const generateArrayPrefix = array_prefix_generators[options.arrayFormat];\n const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip;\n\n if (!obj_keys) {\n obj_keys = Object.keys(obj);\n }\n\n if (options.sort) {\n obj_keys.sort(options.sort);\n }\n\n const sideChannel = new WeakMap();\n for (let i = 0; i < obj_keys.length; ++i) {\n const key = obj_keys[i]!;\n\n if (options.skipNulls && obj[key] === null) {\n continue;\n }\n push_to_array(\n keys,\n inner_stringify(\n obj[key],\n key,\n // @ts-expect-error\n generateArrayPrefix,\n commaRoundTrip,\n options.allowEmptyArrays,\n options.strictNullHandling,\n options.skipNulls,\n options.encodeDotInKeys,\n options.encode ? options.encoder : null,\n options.filter,\n options.sort,\n options.allowDots,\n options.serializeDate,\n options.format,\n options.formatter,\n options.encodeValuesOnly,\n options.charset,\n sideChannel,\n ),\n );\n }\n\n const joined = keys.join(options.delimiter);\n let prefix = options.addQueryPrefix === true ? '?' : '';\n\n if (options.charsetSentinel) {\n if (options.charset === 'iso-8859-1') {\n // encodeURIComponent('&#10003;'), the \"numeric entity\" representation of a checkmark\n prefix += 'utf8=%26%2310003%3B&';\n } else {\n // encodeURIComponent('✓')\n prefix += 'utf8=%E2%9C%93&';\n }\n }\n\n return joined.length > 0 ? prefix + joined : '';\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport * as qs from '../qs/stringify';\n\nexport function stringifyQuery(query: object | Record<string, unknown>) {\n return qs.stringify(query, { arrayFormat: 'brackets' });\n}\n","import { AnthropicError } from '../../core/error';\n\nexport type AccessToken = {\n token: string;\n /** Unix epoch seconds. `null` means no expiry (cache forever). */\n expiresAt: number | null;\n};\n\n/**\n * Mints or returns a cached access token.\n *\n * The optional `opts.forceRefresh` flag, set by {@link TokenCache.invalidate}\n * after a 401, tells providers with on-disk caches (user_oauth, cachedExchange)\n * to bypass their freshness short-circuit and always fetch fresh. Providers\n * without a cache can ignore it.\n */\nexport type AccessTokenProvider = (opts?: { forceRefresh?: boolean }) => Promise<AccessToken>;\n\nexport type IdentityTokenProvider = () => string | Promise<string>;\n\nexport type CredentialResult = {\n provider: AccessTokenProvider;\n extraHeaders: Record<string, string>;\n /**\n * The `base_url` from the resolved config/profile, if any. The client\n * applies this to outbound API requests when no explicit `baseURL` (constructor\n * option or `ANTHROPIC_BASE_URL` env) was given, so a profile pointing at a\n * non-default API host both mints its token against that host AND sends\n * subsequent API requests there.\n */\n baseURL?: string | undefined;\n};\n\n/** Response body from `POST /v1/oauth/token`. */\nexport type TokenEndpointResponse = {\n access_token?: string;\n expires_in?: number;\n refresh_token?: string;\n};\n\nexport const GRANT_TYPE_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer';\nexport const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';\nexport const TOKEN_ENDPOINT = '/v1/oauth/token';\n\n/**\n * `anthropic-beta` value required on authenticated API requests using an\n * OAuth bearer token, and on `refresh_token` grants against the token endpoint.\n */\nexport const OAUTH_API_BETA_HEADER = 'oauth-2025-04-20';\n\n/**\n * `anthropic-beta` value required on jwt-bearer exchanges against the token\n * endpoint. It routes the request to the federation service; it must NOT be\n * sent on `refresh_token` grants, which are handled by a different backend.\n */\nexport const FEDERATION_BETA_HEADER = 'oidc-federation-2026-04-01';\n\nexport const ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120;\nexport const MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30;\nexport const ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5;\n\nconst MAX_TOKEN_RESPONSE_BYTES = 1 << 20;\n\n/**\n * Rejects base URLs that would cause a JWT assertion or refresh token to be\n * sent over cleartext HTTP. Loopback hosts are allowed for local development.\n */\nexport function requireSecureTokenEndpoint(baseURL: string): void {\n if (!baseURL) return;\n let u: URL;\n try {\n u = new URL(baseURL);\n } catch (err) {\n throw new WorkloadIdentityError(`Invalid token endpoint base URL \"${baseURL}\": ${err}`);\n }\n if (u.protocol === 'https:') return;\n // WHATWG URL.hostname returns bracketed IPv6 (\"[::1]\"); Go's net/url strips them.\n const host = u.hostname.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (u.protocol === 'http:' && (host === 'localhost' || host === '127.0.0.1' || host === '::1')) {\n return;\n }\n throw new WorkloadIdentityError(`Refusing to send credential over non-https token endpoint \"${baseURL}\"`);\n}\n\n/**\n * Reads the response body as text, parses it as a token-endpoint JSON\n * response, validates `access_token` is present, and rejects a non-Bearer\n * `token_type` when one is provided. Reads at most\n * {@link MAX_TOKEN_RESPONSE_BYTES} from the body stream.\n */\nexport async function parseTokenResponse(\n resp: Response,\n requestId: string | null,\n): Promise<TokenEndpointResponse & { access_token: string }> {\n const text = await readLimitedText(resp);\n let data: TokenEndpointResponse & { token_type?: string };\n try {\n data = JSON.parse(text);\n } catch {\n throw new WorkloadIdentityError(\n `Token endpoint returned non-JSON response (status ${resp.status})`,\n resp.status,\n redactSensitive(text),\n requestId,\n );\n }\n if (!data.access_token) {\n throw new WorkloadIdentityError(\n `Token endpoint response missing access_token: ${JSON.stringify(redactSensitive(data))}`,\n resp.status,\n redactSensitive(data),\n requestId,\n );\n }\n if (data.token_type && data.token_type.toLowerCase() !== 'bearer') {\n throw new WorkloadIdentityError(\n `Token endpoint response: unsupported token_type \"${data.token_type}\" (want Bearer)`,\n resp.status,\n redactSensitive(data),\n requestId,\n );\n }\n return data as TokenEndpointResponse & { access_token: string };\n}\n\nconst MAX_ERROR_BODY_CHARS = 2000;\n// RFC 6749 §5.2 standard error-response fields. Anything else in a token\n// endpoint error body is potentially echoed input (assertion, refresh_token,\n// access_token, …) and is dropped rather than allowlisted-with-exceptions.\nconst SAFE_ERROR_KEYS = new Set(['error', 'error_description', 'error_uri']);\n\n/**\n * Returns a redacted copy of a token-endpoint error body for safe inclusion\n * in an exception. Strings are truncated; objects keep only the RFC 6749\n * §5.2 error fields.\n */\nexport function redactSensitive(body: unknown): unknown {\n if (body == null) return body;\n if (typeof body === 'string') {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n if (body.length <= MAX_ERROR_BODY_CHARS) return body;\n return body.slice(0, MAX_ERROR_BODY_CHARS) + `... <${body.length - MAX_ERROR_BODY_CHARS} more chars>`;\n }\n return JSON.stringify(redactSensitive(parsed));\n }\n if (typeof body === 'object' && !Array.isArray(body)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(body)) {\n if (SAFE_ERROR_KEYS.has(k)) out[k] = v;\n }\n return out;\n }\n return null;\n}\n\n/**\n * Best-effort safety check on a credentials file before reading it.\n *\n * On POSIX: resolves symlinks (so containerized deployments that mount the\n * credential as a symlink to a tmpfs-backed file keep working), then rejects\n * the resolved target if it is group- or world- readable or writable. A uid\n * mismatch on the resolved target is surfaced via `onWarn` since\n * root-written/app-read is common in init-container setups. No-op on Windows.\n */\nexport async function checkCredentialsFileSafety(\n path: string,\n onWarn: (msg: string) => void = (m) => console.warn(`anthropic-sdk: ${m}`),\n): Promise<void> {\n if (typeof process === 'undefined' || process.platform === 'win32') return;\n const fs = await import('node:fs');\n let resolved = path;\n let st;\n try {\n resolved = await fs.promises.realpath(path);\n st = await fs.promises.stat(resolved);\n } catch {\n return; // ENOENT etc — let the subsequent read surface a precise error\n }\n const mode = st.mode & 0o777;\n // 0o022 = group/world write; 0o044 = group/world read.\n if (mode & 0o022) {\n throw new WorkloadIdentityError(\n `Credentials file at ${resolved} is group/world-writable (mode 0o${mode.toString(8)}); ` +\n `this allows other local users to plant tokens. Run \\`chmod 600 ${resolved}\\`.`,\n );\n }\n if (mode & 0o044) {\n throw new WorkloadIdentityError(\n `Credentials file at ${resolved} is group/world-readable (mode 0o${mode.toString(8)}); ` +\n `run \\`chmod 600 ${resolved}\\` before retrying.`,\n );\n }\n if (typeof process.getuid === 'function' && st.uid !== process.getuid()) {\n onWarn(\n `credentials file at ${resolved} is owned by uid ${\n st.uid\n } (current process uid ${process.getuid()}); ` + `verify this is intentional.`,\n );\n }\n}\n\n/**\n * Atomically writes JSON to `targetPath` via a `.tmp` sibling + rename,\n * with fsync on the file and (best-effort) on the parent directory.\n * Creates the parent directory with mode 0700 and the file with mode 0600.\n */\nexport async function writeCredentialsFileAtomic(targetPath: string, data: unknown): Promise<void> {\n const fs = await import('node:fs');\n const path = await import('node:path');\n const dir = path.dirname(targetPath);\n await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });\n // Unique temp name avoids two concurrent writers (different processes or\n // SDK instances) racing on the same '.tmp' sibling and corrupting each\n // other's bytes mid-write before the rename.\n const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;\n try {\n const fh = await fs.promises.open(tmpPath, 'w', 0o600);\n try {\n await fh.writeFile(JSON.stringify(data, null, 2));\n await fh.sync();\n } finally {\n await fh.close();\n }\n await fs.promises.rename(tmpPath, targetPath);\n } catch (err) {\n // Don't leak the temp file if anything between create and rename failed.\n await fs.promises.unlink(tmpPath).catch(() => {});\n throw err;\n }\n // fsync the parent directory so the rename survives a crash.\n try {\n const dirFh = await fs.promises.open(dir, 'r');\n try {\n await dirFh.sync();\n } finally {\n await dirFh.close();\n }\n } catch {\n // Directory fsync is best-effort (unsupported on some platforms, e.g. Windows).\n }\n}\n\nasync function readLimitedText(resp: Response): Promise<string> {\n if (!resp.body) {\n return '';\n }\n const reader = resp.body.getReader();\n const chunks: Uint8Array[] = [];\n let received = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (received + value.length > MAX_TOKEN_RESPONSE_BYTES) {\n const remaining = MAX_TOKEN_RESPONSE_BYTES - received;\n if (remaining > 0) chunks.push(value.subarray(0, remaining));\n await reader.cancel();\n break;\n }\n chunks.push(value);\n received += value.length;\n }\n let merged: Uint8Array;\n if (chunks.length === 1) {\n merged = chunks[0]!;\n } else {\n merged = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));\n let offset = 0;\n for (const c of chunks) {\n merged.set(c, offset);\n offset += c.length;\n }\n }\n return new TextDecoder('utf-8').decode(merged);\n}\n\nexport class WorkloadIdentityError extends AnthropicError {\n readonly statusCode: number | null;\n readonly body: unknown;\n readonly requestId: string | null;\n\n constructor(\n message: string,\n statusCode: number | null = null,\n body: unknown = null,\n requestId: string | null = null,\n ) {\n super(message);\n this.statusCode = statusCode;\n this.body = body;\n this.requestId = requestId;\n }\n}\n","/** Current time as unix epoch seconds. */\nexport function nowAsSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n","import type { AccessToken, AccessTokenProvider } from './types';\nimport {\n ADVISORY_REFRESH_BACKOFF_IN_SECONDS,\n ADVISORY_REFRESH_THRESHOLD_IN_SECONDS,\n MANDATORY_REFRESH_THRESHOLD_IN_SECONDS,\n} from './types';\nimport { nowAsSeconds } from '../../internal/utils/time';\n\n/**\n * Wraps an {@link AccessTokenProvider} with two-tier proactive refresh\n * and concurrent deduplication.\n *\n * Refresh policy on each {@link getToken} call:\n *\n * - No cached token → call provider (blocking), cache, return.\n * - Cached with `expiresAt == null` → return cached forever.\n * - More than 120s remaining → return cached.\n * - 30–120s remaining (advisory window) → return stale token immediately,\n * kick off background refresh. On failure, log and keep stale.\n * - Less than 30s remaining or expired (mandatory) → block and refresh.\n * On failure, throw.\n *\n * Concurrent mandatory callers coalesce into a single provider call.\n */\nexport class TokenCache {\n private provider: AccessTokenProvider;\n private cached: AccessToken | null = null;\n private pendingRefresh: Promise<AccessToken> | null = null;\n private nextForce = false;\n private lastAdvisoryError = 0;\n private onAdvisoryRefreshError: ((err: unknown) => void) | undefined;\n\n constructor(provider: AccessTokenProvider, onAdvisoryRefreshError?: (err: unknown) => void) {\n this.provider = provider;\n this.onAdvisoryRefreshError = onAdvisoryRefreshError;\n }\n\n async getToken(): Promise<string> {\n const force = this.nextForce;\n this.nextForce = false;\n const cached = this.cached;\n\n if (force || cached == null) {\n const token = await this.refresh(force);\n return token.token;\n }\n\n if (cached.expiresAt == null) {\n return cached.token;\n }\n\n const remaining = cached.expiresAt - nowAsSeconds();\n\n if (remaining > ADVISORY_REFRESH_THRESHOLD_IN_SECONDS) {\n return cached.token;\n }\n\n if (remaining > MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {\n this.backgroundRefresh();\n return cached.token;\n }\n\n const token = await this.refresh();\n return token.token;\n }\n\n /**\n * Clears the cached token and marks the next {@link getToken} as a forced\n * refresh, so the underlying provider bypasses any on-disk freshness check.\n * Called after a 401 — the server has just told us the token is bad even\n * if its `expires_at` still looks fresh.\n */\n invalidate(): void {\n this.cached = null;\n this.nextForce = true;\n }\n\n /**\n * Mandatory refresh. Joins any in-flight refresh unless forced — a forced\n * refresh must not coalesce into a non-forced one that may re-serve the\n * same stale disk token.\n */\n private refresh(force = false): Promise<AccessToken> {\n if (this.pendingRefresh && !force) {\n return this.pendingRefresh;\n }\n return this.doRefresh(force);\n }\n\n /**\n * Advisory background refresh. Shares the same in-flight promise as\n * mandatory refreshes for deduplication, but swallows errors so the\n * stale cached token keeps being served. Backs off for\n * {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure so an\n * outage during the advisory window doesn't hammer the token endpoint.\n */\n private backgroundRefresh(): void {\n if (this.pendingRefresh) {\n return;\n }\n if (nowAsSeconds() - this.lastAdvisoryError < ADVISORY_REFRESH_BACKOFF_IN_SECONDS) {\n return;\n }\n this.doRefresh().catch((err) => {\n this.lastAdvisoryError = nowAsSeconds();\n // Advisory failure: keep serving the stale cached token, but surface\n // the error to the caller-provided hook so it can be logged.\n this.onAdvisoryRefreshError?.(err);\n });\n }\n\n /**\n * Core refresh. Sets {@link pendingRefresh} so concurrent callers\n * (both advisory and mandatory) coalesce into a single provider call.\n */\n private doRefresh(force = false): Promise<AccessToken> {\n this.pendingRefresh = this.provider(force ? { forceRefresh: true } : undefined).then(\n (token) => {\n this.cached = token;\n this.pendingRefresh = null;\n return token;\n },\n (err) => {\n this.pendingRefresh = null;\n throw err;\n },\n );\n return this.pendingRefresh;\n }\n}\n","export function concatBytes(buffers: Uint8Array[]): Uint8Array {\n let length = 0;\n for (const buffer of buffers) {\n length += buffer.length;\n }\n const output = new Uint8Array(length);\n let index = 0;\n for (const buffer of buffers) {\n output.set(buffer, index);\n index += buffer.length;\n }\n\n return output;\n}\n\nlet encodeUTF8_: (str: string) => Uint8Array;\nexport function encodeUTF8(str: string) {\n let encoder;\n return (\n encodeUTF8_ ??\n ((encoder = new (globalThis as any).TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder)))\n )(str);\n}\n\nlet decodeUTF8_: (bytes: Uint8Array) => string;\nexport function decodeUTF8(bytes: Uint8Array) {\n let decoder;\n return (\n decodeUTF8_ ??\n ((decoder = new (globalThis as any).TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder)))\n )(bytes);\n}\n","import { getPlatformHeaders } from '../internal/detect-platform';\nimport { readEnv } from '../internal/utils';\n\n/** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ \"1.0\". */\nexport const CONFIG_FILE_VERSION = '1.0';\n/** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ \"1.0\". */\nexport const CREDENTIALS_FILE_VERSION = '1.0';\n\n/**\n * Authentication-mode-specific configuration. On the wire (configs/<profile>.json)\n * this is a flat JSON object under the top-level `authentication` key — `type`,\n * `credentials_path`, and the variant-specific fields all sit at the same level.\n *\n * Unknown fields are silently ignored for forward compatibility. Unknown\n * authentication types are rejected because the SDK has no way to resolve\n * credentials for them.\n */\nexport type AuthenticationInfo = {\n /**\n * Filesystem path to the credentials JSON that stores access/refresh tokens.\n * Defaults to `<config_dir>/credentials/<profile>.json` when omitted.\n */\n credentials_path?: string | undefined;\n} & (\n | {\n type: 'oidc_federation';\n /** Tagged ID (`fdrl_...`) of the federation rule. Required. */\n federation_rule_id: string;\n /** Optional `svac_...` expected-target check. */\n service_account_id?: string | undefined;\n identity_token?:\n | {\n source: 'file';\n path: string;\n }\n | undefined;\n /** Display-only; the SDK does not send this on the jwt-bearer exchange. */\n scope?: string | undefined;\n }\n | {\n type: 'user_oauth';\n /** OAuth client ID for refresh. Empty → access token is treated as static. */\n client_id?: string | undefined;\n /** Display-only; the SDK does not send this on refresh. */\n scope?: string | undefined;\n /** Console URL the profile was created against. Display-only. */\n console_url?: string | undefined;\n }\n);\n\nexport type AnthropicConfig = {\n version?: string;\n authentication: AuthenticationInfo;\n base_url?: string | undefined;\n organization_id?: string | undefined;\n workspace_id?: string | undefined;\n};\n\nexport type AnthropicCredentials = {\n version?: string;\n type: 'oauth_token';\n access_token: string;\n expires_at?: number;\n refresh_token?: string;\n scope?: string;\n organization_uuid?: string;\n organization_name?: string;\n account_email?: string;\n};\n\nconst PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;\n\nfunction validateProfileName(name: string): void {\n if (!name) {\n throw new Error('profile name is empty');\n }\n if (name === '.' || name === '..') {\n throw new Error(`profile name \"${name}\" is not allowed`);\n }\n if (name.includes('/') || name.includes('\\\\')) {\n throw new Error(`profile name \"${name}\" must not contain path separators`);\n }\n if (!PROFILE_NAME_PATTERN.test(name)) {\n throw new Error(\n `profile name \"${name}\" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`,\n );\n }\n}\n\n/**\n * Loads the Anthropic configuration for the given (or active) profile.\n *\n * Returns `null` when running in a browser or no configuration can be resolved.\n * Otherwise, returns the configuration based on the config file and environment variables.\n *\n * **Profile resolution** (first match wins):\n * 1. Explicit `profile` argument\n * 2. `ANTHROPIC_PROFILE` environment variable\n * 3. Contents of `<config_dir>/active_config` file\n * 4. `\"default\"`\n *\n * **Config resolution:**\n * - If `<config_dir>/configs/<profile>.json` exists, it is loaded and\n * missing fields are filled from environment variables. Values present\n * in the file take precedence — env vars only fill gaps:\n * - `ANTHROPIC_BASE_URL` → `base_url`\n * - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`\n * - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`\n * - `ANTHROPIC_SCOPE` → `authentication.scope`\n * - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)\n * - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)\n * - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)\n * - If no config file exists, an `oidc_federation` config is synthesized\n * entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`\n * and `ANTHROPIC_ORGANIZATION_ID` are set.\n */\nexport const loadConfig = async (profile?: string): Promise<AnthropicConfig | null> => {\n return (await loadConfigWithSource(profile))?.config ?? null;\n};\n\n/**\n * Source-tagged result of {@link loadConfigWithSource}. `fromFile` is `true`\n * when `<config_dir>/configs/<profile>.json` exists on disk; `false` when the\n * config was synthesized purely from environment variables.\n *\n * The credential chain uses this distinction to decide whether to back the\n * federation exchange with a disk cache: file-backed profiles get a cache at\n * `<config_dir>/credentials/<profile>.json`, env-only configs do not.\n */\nexport type LoadedConfig = { config: AnthropicConfig; fromFile: boolean };\n\n/**\n * Same as {@link loadConfig}, but also reports whether the config was loaded\n * from a profile file on disk (`fromFile: true`) or synthesized entirely from\n * environment variables (`fromFile: false`).\n */\nexport const loadConfigWithSource = async (profile?: string): Promise<LoadedConfig | null> => {\n const rootConfigPath = await getRootConfigPath();\n if (rootConfigPath === null) {\n return null;\n }\n\n const profileName = profile ?? (await getActiveProfileName());\n if (profileName === null) {\n return null;\n }\n validateProfileName(profileName);\n\n const fs = await import('node:fs');\n const path = await import('node:path');\n const configPath = path.join(rootConfigPath, 'configs', `${profileName}.json`);\n let configRaw: string | null;\n try {\n configRaw = await fs.promises.readFile(configPath, 'utf-8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw new Error(`failed to read config file ${configPath}: ${err}`);\n }\n configRaw = null;\n }\n if (configRaw === null) {\n const organizationId = readEnv('ANTHROPIC_ORGANIZATION_ID');\n const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');\n const federationRuleId = readEnv('ANTHROPIC_FEDERATION_RULE_ID');\n if (federationRuleId && organizationId) {\n return {\n fromFile: false,\n config: {\n organization_id: organizationId,\n // A defaulted-but-empty CI variable (`ANTHROPIC_WORKSPACE_ID=\"\"`) is\n // treated as unset — readEnv coerces empty to undefined, and the body\n // builder's truthy check skips it — so `\"workspace_id\": \"\"` never goes\n // on the wire.\n workspace_id: readEnv('ANTHROPIC_WORKSPACE_ID'),\n base_url: readEnv('ANTHROPIC_BASE_URL'),\n authentication: {\n type: 'oidc_federation',\n federation_rule_id: federationRuleId,\n service_account_id: readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID'),\n identity_token: identityTokenFile ? { source: 'file', path: identityTokenFile } : undefined,\n scope: readEnv('ANTHROPIC_SCOPE'),\n },\n },\n };\n }\n return null;\n }\n\n let config: AnthropicConfig;\n try {\n config = JSON.parse(configRaw);\n } catch (err) {\n throw new Error(`failed to parse config file ${configPath}: ${err}`);\n }\n if (!config.authentication) {\n throw new Error(`config file ${configPath} is missing \"authentication\"`);\n }\n const authType = config.authentication.type;\n if (authType !== 'oidc_federation' && authType !== 'user_oauth') {\n throw new Error(`authentication.type \"${authType}\" is not a known authentication type`);\n }\n\n // File values are authoritative; env vars only fill fields the file left unset.\n config.organization_id ??= readEnv('ANTHROPIC_ORGANIZATION_ID');\n config.workspace_id ??= readEnv('ANTHROPIC_WORKSPACE_ID');\n config.base_url ??= readEnv('ANTHROPIC_BASE_URL');\n config.authentication.scope ??= readEnv('ANTHROPIC_SCOPE');\n\n if (config.authentication.type === 'oidc_federation') {\n if (!config.authentication.identity_token) {\n const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');\n if (identityTokenFile) {\n config.authentication.identity_token = {\n source: 'file',\n path: identityTokenFile,\n };\n }\n }\n\n // Unlike siblings using `??= readEnv()` (which leaves `undefined`), coerce\n // to '' so the type stays `string` (always set). The downstream required\n // check in credential-chain rejects empty, so semantics match but types are\n // cleaner.\n if (!config.authentication.federation_rule_id) {\n config.authentication.federation_rule_id = readEnv('ANTHROPIC_FEDERATION_RULE_ID') ?? '';\n }\n config.authentication.service_account_id ??= readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID');\n }\n\n return { config, fromFile: true };\n};\n\n/**\n * Loads the credential material for the active profile.\n *\n * Returns the parsed credentials or `null` when running in a browser or\n * no credentials file can be found.\n *\n * **Profile resolution** (first match wins):\n * 1. `ANTHROPIC_PROFILE` environment variable\n * 2. Contents of `<config_dir>/active_config` file\n * 3. `\"default\"`\n *\n * **Credentials path resolution** (first match wins):\n * 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})\n * 2. `<config_dir>/credentials/<profile>.json`\n */\nexport const loadCredentials = async (): Promise<AnthropicCredentials | null> => {\n const config = await loadConfig();\n const credentialsPath = await getCredentialsPath(config);\n if (!credentialsPath) {\n return null;\n }\n\n const fs = await import('node:fs');\n let raw: string;\n try {\n raw = await fs.promises.readFile(credentialsPath, 'utf-8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw new Error(`failed to read credentials file ${credentialsPath}: ${err}`);\n }\n return null;\n }\n\n let creds: AnthropicCredentials;\n try {\n creds = JSON.parse(raw);\n } catch (err) {\n throw new Error(`failed to parse credentials file ${credentialsPath}: ${err}`);\n }\n if (creds.type && creds.type !== 'oauth_token') {\n throw new Error(\n `credentials file ${credentialsPath} has unsupported type \"${creds.type}\" (want \"oauth_token\")`,\n );\n }\n return creds;\n};\n\n/**\n * Resolves the credentials file path for the given config.\n *\n * Uses `authentication.credentials_path` from the config if set, otherwise\n * falls back to `<config_dir>/credentials/<profile>.json`.\n *\n * Returns `null` when running in a browser or the path cannot be resolved.\n */\nexport const getCredentialsPath = async (\n config: AnthropicConfig | null,\n profile?: string,\n): Promise<string | null> => {\n if (config?.authentication.credentials_path) {\n return config.authentication.credentials_path;\n }\n\n const rootConfigPath = await getRootConfigPath();\n if (!rootConfigPath) {\n return null;\n }\n\n const profileName = profile ?? (await getActiveProfileName());\n if (!profileName) {\n return null;\n }\n validateProfileName(profileName);\n\n const path = await import('node:path');\n return path.join(rootConfigPath, 'credentials', `${profileName}.json`);\n};\n\nconst getRootConfigPath = async (): Promise<string | null> => {\n if (!supportsLocalConfigFiles()) {\n return null;\n }\n\n const path = await import('node:path');\n\n // ANTHROPIC_CONFIG_DIR is treated as a trusted path: it is set by the\n // process operator, not by remote input, so it is not validated.\n const configDir = readEnv('ANTHROPIC_CONFIG_DIR');\n if (configDir) {\n return configDir;\n }\n\n const os = getPlatformHeaders()['X-Stainless-OS'];\n if (os === 'Windows') {\n const appData = readEnv('APPDATA');\n if (appData) {\n return path.join(appData, 'Anthropic');\n }\n const userProfile = readEnv('USERPROFILE');\n if (userProfile) {\n return path.join(userProfile, 'AppData', 'Roaming', 'Anthropic');\n }\n // No usable Windows config root — return null so callers fall through to\n // \"no config available\" rather than silently writing under C:\\.\n return null;\n }\n\n const xdgConfigHome = readEnv('XDG_CONFIG_HOME');\n if (xdgConfigHome) {\n return path.join(xdgConfigHome, 'anthropic');\n }\n\n const home = readEnv('HOME');\n if (home) {\n return path.join(home, '.config', 'anthropic');\n }\n return null;\n};\n\nconst supportsLocalConfigFiles = (): boolean => {\n const runtime = getPlatformHeaders()['X-Stainless-Runtime'];\n return runtime === 'node' || runtime === 'deno';\n};\n\nconst getActiveProfileName = async (): Promise<string | null> => {\n const rootConfigPath = await getRootConfigPath();\n if (!rootConfigPath) {\n return null;\n }\n\n const profileName = readEnv('ANTHROPIC_PROFILE');\n if (profileName) {\n return profileName;\n }\n\n const fs = await import('node:fs');\n const path = await import('node:path');\n const filePath = path.join(rootConfigPath, 'active_config');\n try {\n return (await fs.promises.readFile(filePath, 'utf-8')).trim() || 'default';\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw new Error(`failed to read ${filePath}: ${err}`);\n }\n return 'default';\n }\n};\n","import { AnthropicError } from '../../core/error';\nimport type { IdentityTokenProvider } from './types';\n\n/**\n * Reads a JWT from a file on every call. Supports automatic rotation\n * (e.g. Kubernetes projected service-account tokens).\n */\nexport function identityTokenFromFile(path: string): IdentityTokenProvider {\n if (!path) {\n throw new AnthropicError('Identity token file path is empty');\n }\n\n return async () => {\n const fs = await import('node:fs');\n let content: string;\n try {\n content = await fs.promises.readFile(path, 'utf-8');\n } catch (err) {\n throw new AnthropicError(`Failed to read identity token file at ${path}: ${err}`);\n }\n const token = content.trim();\n if (!token) {\n throw new AnthropicError(`Identity token file at ${path} is empty`);\n }\n return token;\n };\n}\n\n/**\n * Wraps a static JWT string as an {@link IdentityTokenProvider}.\n */\nexport function identityTokenFromValue(token: string): IdentityTokenProvider {\n if (!token) {\n throw new AnthropicError('Identity token value is empty');\n }\n return () => token;\n}\n","import type { Fetch } from '../../internal/builtin-types';\nimport type { AccessTokenProvider, IdentityTokenProvider } from './types';\nimport {\n FEDERATION_BETA_HEADER,\n GRANT_TYPE_JWT_BEARER,\n OAUTH_API_BETA_HEADER,\n TOKEN_ENDPOINT,\n WorkloadIdentityError,\n parseTokenResponse,\n redactSensitive,\n requireSecureTokenEndpoint,\n} from './types';\nimport { nowAsSeconds } from '../../internal/utils/time';\nimport { VERSION } from '../../version';\n\nexport type OIDCFederationConfig = {\n identityTokenProvider: IdentityTokenProvider;\n federationRuleId: string;\n organizationId: string;\n serviceAccountId?: string | undefined;\n /**\n * Optional `wrkspc_*` tagged ID, or the literal `\"default\"` to scope the\n * token to the organization's default workspace. When omitted the server\n * picks the rule's sole enabled workspace, else the org default if the rule\n * covers it. Required when the rule enables more than one non-default\n * workspace, or to target a specific workspace other than the one the\n * server would pick. The minted token is workspace-scoped: per-request\n * workspace selection (the `anthropic-workspace-id` header) is not supported\n * for federation tokens — switching workspaces requires a new token exchange\n * with a different `workspaceId`.\n */\n workspaceId?: string | undefined;\n baseURL: string;\n fetch: Fetch;\n /**\n * Overrides the outgoing User-Agent header on the token exchange. When\n * empty, sends an SDK-identified UA so the token endpoint's access logs\n * identify the caller.\n */\n userAgent?: string | undefined;\n};\n\n/**\n * Exchanges an external OIDC JWT for an Anthropic access token via the\n * RFC 7523 jwt-bearer grant.\n *\n * Each invocation performs a fresh token exchange. Wrap in a\n * {@link TokenCache} to avoid exchanging on every request.\n *\n * Federation grants do not return a refresh token — callers re-exchange\n * their assertion on expiry.\n */\nexport function oidcFederationProvider(config: OIDCFederationConfig): AccessTokenProvider {\n return async () => {\n requireSecureTokenEndpoint(config.baseURL);\n\n const jwt = await config.identityTokenProvider();\n // The token endpoint enforces a 16 KiB assertion limit; surface a clear\n // client-side error so misconfigured projected-token sources are\n // diagnosable without a server round-trip.\n if (jwt.length > 16 * 1024) {\n throw new WorkloadIdentityError(\n `Identity token is ${Math.ceil(jwt.length / 1024)} KiB, exceeds the 16 KiB assertion limit`,\n );\n }\n\n const body: Record<string, string> = {\n grant_type: GRANT_TYPE_JWT_BEARER,\n assertion: jwt,\n federation_rule_id: config.federationRuleId,\n organization_id: config.organizationId,\n };\n if (config.serviceAccountId) {\n body['service_account_id'] = config.serviceAccountId;\n }\n if (config.workspaceId) {\n body['workspace_id'] = config.workspaceId;\n }\n\n const url = `${config.baseURL}${TOKEN_ENDPOINT}`;\n let resp: Response;\n try {\n resp = await config.fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'anthropic-beta': `${OAUTH_API_BETA_HEADER},${FEDERATION_BETA_HEADER}`,\n 'User-Agent': config.userAgent || `anthropic-sdk-typescript/${VERSION} oidcFederationProvider`,\n },\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${err}`);\n }\n\n const requestId = resp.headers.get('Request-Id');\n\n if (!resp.ok) {\n const text = await resp.text().catch(() => '');\n const redacted = redactSensitive(text);\n // A 401 is hard to debug from the status code alone, so surface\n // guidance: check the federation rule, optionally set a workspace ID\n // (the most common fix when no workspaceId is configured), and point at\n // the Workload identity page in Claude Console for the server-side\n // authentication event log. Other statuses (5xx, 400, ...) get no hint.\n let hint = '';\n if (resp.status === 401) {\n const hintMiddle =\n config.workspaceId ? '' : (\n \"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. \"\n );\n hint = ` Ensure your federation rule matches your identity token. ${hintMiddle}View your authentication events in the Workload identity page of Claude Console for more details.`;\n }\n throw new WorkloadIdentityError(\n `Token exchange failed with status ${resp.status}${\n requestId ? ` (request-id ${requestId})` : ''\n }: ${redacted}${hint}`,\n resp.status,\n redacted,\n requestId,\n );\n }\n\n const data = await parseTokenResponse(resp, requestId);\n const expiresIn = Number(data.expires_in);\n if (!Number.isFinite(expiresIn)) {\n throw new WorkloadIdentityError(\n `Token endpoint response missing required fields: ${JSON.stringify(redactSensitive(data))}`,\n resp.status,\n redactSensitive(data),\n requestId,\n );\n }\n\n return {\n token: data.access_token,\n expiresAt: nowAsSeconds() + expiresIn,\n };\n };\n}\n","import type { Fetch } from '../../internal/builtin-types';\nimport { CREDENTIALS_FILE_VERSION, type AnthropicCredentials } from '../../core/credentials';\nimport type { AccessTokenProvider } from './types';\nimport {\n GRANT_TYPE_REFRESH_TOKEN,\n MANDATORY_REFRESH_THRESHOLD_IN_SECONDS,\n OAUTH_API_BETA_HEADER,\n TOKEN_ENDPOINT,\n WorkloadIdentityError,\n checkCredentialsFileSafety,\n parseTokenResponse,\n redactSensitive,\n requireSecureTokenEndpoint,\n writeCredentialsFileAtomic,\n} from './types';\nimport { nowAsSeconds } from '../../internal/utils/time';\nimport { VERSION } from '../../version';\n\nexport type UserOAuthConfig = {\n credentialsPath: string;\n clientId?: string | undefined;\n baseURL: string;\n fetch: Fetch;\n userAgent?: string | undefined;\n onSafetyWarning?: ((msg: string) => void) | undefined;\n};\n\n/**\n * Reads a user-oauth credential file. Returns the cached access token while\n * fresh; on expiry performs a `refresh_token` grant and writes the new\n * tokens back to the credentials file (atomic replace, fsync'd).\n *\n * If `clientId` is empty, the access token is treated as static — the\n * credentials file is read on every call but no refresh is attempted, and\n * an expired token without a `refresh_token` raises.\n */\nexport function userOAuthProvider(config: UserOAuthConfig): AccessTokenProvider {\n return async (opts) => {\n const fs = await import('node:fs');\n\n await checkCredentialsFileSafety(config.credentialsPath, config.onSafetyWarning);\n\n let raw: string;\n try {\n raw = await fs.promises.readFile(config.credentialsPath, 'utf-8');\n } catch (err) {\n throw new WorkloadIdentityError(`Credentials file not found at ${config.credentialsPath}: ${err}`);\n }\n let creds: AnthropicCredentials;\n try {\n creds = JSON.parse(raw);\n } catch (err) {\n throw new WorkloadIdentityError(\n `Credentials file at ${config.credentialsPath} is not valid JSON: ${err}`,\n );\n }\n\n const accessToken = creds.access_token;\n if (!accessToken) {\n throw new WorkloadIdentityError(\n `Credentials file at ${config.credentialsPath} must include 'access_token'`,\n );\n }\n\n // Return cached token if still fresh (or no expiry info), unless the\n // caller is forcing a refresh after a 401 — then go straight to refresh\n // even if the file's expires_at still looks valid.\n const expiresAt = creds.expires_at;\n if (\n !opts?.forceRefresh &&\n (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS)\n ) {\n return { token: accessToken, expiresAt: expiresAt ?? null };\n }\n\n const refreshToken = creds.refresh_token;\n if (!config.clientId || !refreshToken) {\n throw new WorkloadIdentityError(\n `Access token at ${config.credentialsPath} has expired and no refresh is available ` +\n `(client_id ${config.clientId ? 'set' : 'empty'}, refresh_token ${refreshToken ? 'set' : 'empty'})`,\n );\n }\n\n requireSecureTokenEndpoint(config.baseURL);\n\n const body: Record<string, string> = {\n grant_type: GRANT_TYPE_REFRESH_TOKEN,\n refresh_token: refreshToken,\n client_id: config.clientId,\n };\n\n const url = `${config.baseURL}${TOKEN_ENDPOINT}`;\n let resp: Response;\n try {\n resp = await config.fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'anthropic-beta': OAUTH_API_BETA_HEADER,\n 'User-Agent': config.userAgent || `anthropic-sdk-typescript/${VERSION} userOAuthProvider`,\n },\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new WorkloadIdentityError(`User OAuth refresh failed to reach token endpoint: ${err}`);\n }\n\n const requestId = resp.headers.get('Request-Id');\n\n if (!resp.ok) {\n const text = await resp.text().catch(() => '');\n throw new WorkloadIdentityError(\n `User OAuth refresh failed (HTTP ${resp.status}): ${redactSensitive(text)}`,\n resp.status,\n redactSensitive(text),\n requestId,\n );\n }\n\n const data = await parseTokenResponse(resp, requestId);\n const expiresIn = Number(data.expires_in);\n if (!Number.isFinite(expiresIn)) {\n throw new WorkloadIdentityError(\n `User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(redactSensitive(data))}`,\n resp.status,\n redactSensitive(data),\n requestId,\n );\n }\n const newExpiresAt = nowAsSeconds() + expiresIn;\n const newRefreshToken = data.refresh_token || refreshToken;\n\n await writeCredentialsFileAtomic(config.credentialsPath, {\n ...creds,\n version: CREDENTIALS_FILE_VERSION,\n type: 'oauth_token',\n access_token: data.access_token,\n expires_at: newExpiresAt,\n refresh_token: newRefreshToken,\n });\n\n return { token: data.access_token, expiresAt: newExpiresAt };\n };\n}\n","import type { Fetch } from '../../internal/builtin-types';\nimport { readEnv } from '../../internal/utils/env';\nimport {\n CREDENTIALS_FILE_VERSION,\n loadConfigWithSource,\n getCredentialsPath,\n type AnthropicConfig,\n} from '../../core/credentials';\nimport type { AccessTokenProvider, CredentialResult, IdentityTokenProvider } from './types';\nimport {\n MANDATORY_REFRESH_THRESHOLD_IN_SECONDS,\n WorkloadIdentityError,\n checkCredentialsFileSafety,\n writeCredentialsFileAtomic,\n} from './types';\nimport { nowAsSeconds } from '../../internal/utils/time';\nimport { identityTokenFromFile, identityTokenFromValue } from './identity-token';\nimport { oidcFederationProvider } from './oidc-federation';\nimport { userOAuthProvider } from './user-oauth';\n\n/**\n * Builds a {@link CredentialResult} from an explicit {@link AnthropicConfig}.\n *\n * Use this when constructing a client from an in-memory config object rather\n * than from profile files or environment variables.\n *\n * For `oidc_federation`, `authentication.credentials_path` is optional —\n * if omitted, every call performs a fresh exchange with no on-disk cache.\n * For `user_oauth`, `authentication.credentials_path` is required (it is\n * where the access/refresh tokens live).\n */\nexport type ResolverOptions = {\n baseURL: string;\n fetch: Fetch;\n userAgent?: string | undefined;\n onCacheWriteError?: ((err: unknown) => void) | undefined;\n onSafetyWarning?: ((msg: string) => void) | undefined;\n};\n\nexport function resolveCredentialsFromConfig(\n config: AnthropicConfig,\n options: ResolverOptions,\n): CredentialResult {\n const credentialsPath = config.authentication.credentials_path ?? null;\n const effectiveBaseURL = (config.base_url || options.baseURL).replace(/\\/+$/, '');\n\n const provider = buildProvider(config, credentialsPath, effectiveBaseURL, options);\n\n const extraHeaders: Record<string, string> = {};\n // For federation profiles workspace_id is sent in the jwt-bearer exchange\n // body, not as a request header (the minted token is already\n // workspace-scoped, so the header would be ignored).\n if (config.workspace_id && config.authentication.type === 'user_oauth') {\n extraHeaders['anthropic-workspace-id'] = config.workspace_id;\n }\n\n // Surface the profile's own base_url (not the options.baseURL fallback) so\n // the client can adopt it for outbound API requests when the caller didn't\n // pin one explicitly. Echoing options.baseURL back would defeat precedence.\n return { provider, extraHeaders, baseURL: config.base_url || undefined };\n}\n\n/**\n * Resolves a {@link CredentialResult} from the environment. Returns `null`\n * when no credentials can be resolved.\n *\n * Resolution order:\n *\n * 1. Config file for the active profile (or the explicit `profile` argument)\n * → dispatch on `authentication.type` (`oidc_federation`, `user_oauth`)\n * 2. Environment variables `ANTHROPIC_FEDERATION_RULE_ID` +\n * `ANTHROPIC_ORGANIZATION_ID` (+ identity token) → OIDC federation\n * 3. Nothing matches → `null`\n *\n * Passing `profile` selects `<config_dir>/configs/<profile>.json` directly,\n * skipping `ANTHROPIC_PROFILE` / `active_config` resolution.\n */\nexport async function defaultCredentials(\n options: ResolverOptions,\n profile?: string,\n): Promise<CredentialResult | null> {\n const loaded = await loadConfigWithSource(profile);\n if (!loaded) {\n return null;\n }\n const { config, fromFile } = loaded;\n\n // For file-loaded configs, default credentials_path to the per-profile\n // location so user_oauth and federation caching work. Shallow-clone first\n // so callers that retain a reference to the loaded config don't observe the\n // patched-in default.\n //\n // Env-only credentials (no profile file on disk) skip the disk cache —\n // matching the other SDKs. A disk cache keyed by profile path would\n // re-serve a stale token after a change to ANTHROPIC_WORKSPACE_ID (or\n // ANTHROPIC_ORGANIZATION_ID / ANTHROPIC_FEDERATION_RULE_ID) until the\n // cached token expired, so the env-only chain stays in-memory only.\n const withPath: AnthropicConfig =\n config.authentication.credentials_path || !fromFile ?\n config\n : {\n ...config,\n authentication: {\n ...config.authentication,\n credentials_path: (await getCredentialsPath(config, profile)) ?? undefined,\n },\n };\n\n return resolveCredentialsFromConfig(withPath, options);\n}\n\nfunction buildProvider(\n config: AnthropicConfig,\n credentialsPath: string | null,\n baseURL: string,\n options: ResolverOptions,\n): AccessTokenProvider {\n switch (config.authentication.type) {\n case 'oidc_federation': {\n const auth = config.authentication;\n const identityProvider = resolveIdentityTokenProvider(auth);\n if (!identityProvider) {\n throw new WorkloadIdentityError(\n 'oidc_federation config requires an identity token (set authentication.identity_token, ' +\n 'ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)',\n );\n }\n if (!auth.federation_rule_id) {\n throw new WorkloadIdentityError(\n \"oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).\",\n );\n }\n if (!config.organization_id) {\n throw new WorkloadIdentityError(\n 'oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)',\n );\n }\n\n const exchange = oidcFederationProvider({\n identityTokenProvider: identityProvider,\n federationRuleId: auth.federation_rule_id,\n organizationId: config.organization_id,\n serviceAccountId: auth.service_account_id,\n workspaceId: config.workspace_id,\n baseURL,\n fetch: options.fetch,\n userAgent: options.userAgent,\n });\n\n // If there's a credentials file path, wrap the exchange with file caching\n // (check file for fresh token before exchanging, write back after).\n if (credentialsPath) {\n return cachedExchangeProvider(\n exchange,\n credentialsPath,\n options.onCacheWriteError,\n options.onSafetyWarning,\n );\n }\n return exchange;\n }\n\n case 'user_oauth': {\n if (!credentialsPath) {\n throw new WorkloadIdentityError(\n 'user_oauth config requires authentication.credentials_path ' +\n '(or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)',\n );\n }\n return userOAuthProvider({\n credentialsPath,\n clientId: config.authentication.client_id,\n baseURL,\n fetch: options.fetch,\n userAgent: options.userAgent,\n onSafetyWarning: options.onSafetyWarning,\n });\n }\n\n default: {\n const t = (config.authentication as { type: string }).type;\n throw new WorkloadIdentityError(`authentication.type \"${t}\" is not a known authentication type`);\n }\n }\n}\n\n/**\n * Resolves the identity token provider from config fields or environment variables.\n *\n * Resolution order:\n * 1. `identity_token.path` from the config (source: \"file\")\n * 2. `ANTHROPIC_IDENTITY_TOKEN_FILE` env var\n * 3. `ANTHROPIC_IDENTITY_TOKEN` env var (static value)\n */\nfunction resolveIdentityTokenProvider(\n auth: Extract<AnthropicConfig['authentication'], { type: 'oidc_federation' }>,\n): IdentityTokenProvider | null {\n if (auth.identity_token) {\n // Cast needed to stringify an unknown source value for the error message:\n // the on-disk JSON may contain a source this SDK version doesn't know about.\n const source = (auth.identity_token as { source: string }).source;\n if (source !== 'file') {\n throw new WorkloadIdentityError(\n `identity_token.source \"${source}\" is not supported by this SDK version (only \"file\")`,\n );\n }\n if (!auth.identity_token.path) {\n throw new WorkloadIdentityError(`identity_token.source \"file\" requires a non-empty path`);\n }\n return identityTokenFromFile(auth.identity_token.path);\n }\n\n const tokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');\n if (tokenFile) {\n return identityTokenFromFile(tokenFile);\n }\n\n const tokenValue = readEnv('ANTHROPIC_IDENTITY_TOKEN');\n if (tokenValue) {\n return identityTokenFromValue(tokenValue);\n }\n\n return null;\n}\n\n/**\n * Wraps a federation exchange provider with credential file caching.\n * Checks the file for a fresh token before exchanging, and writes the\n * result back after a successful exchange (best-effort, atomic replace).\n *\n * Note: this is not cross-process serialized — two SDK instances that\n * miss the cache simultaneously will both perform a full exchange and\n * the last writer wins. That is acceptable: federation exchanges are\n * idempotent and the cache is an optimization, not a correctness gate.\n */\nfunction cachedExchangeProvider(\n exchange: AccessTokenProvider,\n credentialsPath: string,\n onCacheWriteError: ((err: unknown) => void) | undefined,\n onSafetyWarning: ((msg: string) => void) | undefined,\n): AccessTokenProvider {\n return async (opts) => {\n const fs = await import('node:fs');\n\n await checkCredentialsFileSafety(credentialsPath, onSafetyWarning);\n\n // Try cached credentials file\n let existing: Record<string, unknown> | undefined;\n try {\n const raw = await fs.promises.readFile(credentialsPath, 'utf-8');\n existing = JSON.parse(raw);\n const token = existing?.['access_token'] as string | undefined;\n if (token && !opts?.forceRefresh) {\n const expiresAt = existing?.['expires_at'] as number | undefined;\n if (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {\n return { token, expiresAt: expiresAt ?? null };\n }\n }\n } catch (err) {\n // ENOENT or invalid-JSON → no usable cache, exchange fresh. Other\n // errors (EACCES, EISDIR, …) indicate a broken cache path; surface to\n // the optional hook so they're at least debuggable, then proceed.\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code !== 'ENOENT' && !(err instanceof SyntaxError)) {\n onCacheWriteError?.(err);\n }\n }\n\n // Exchange for a new token\n const result = await exchange(opts);\n\n // Write cache back (best-effort). Preserve any unknown keys from the\n // existing file (notably refresh_token, in the unlikely case this path\n // is shared with a user_oauth profile) so the federation cache writer\n // doesn't clobber material it didn't own.\n try {\n await writeCredentialsFileAtomic(credentialsPath, {\n ...(existing ?? {}),\n version: CREDENTIALS_FILE_VERSION,\n type: 'oauth_token',\n access_token: result.token,\n expires_at: result.expiresAt,\n });\n } catch (err) {\n // Best-effort caching: surface to the optional hook but never fail\n // the exchange itself.\n onCacheWriteError?.(err);\n }\n\n return result;\n };\n}\n","import { concatBytes, decodeUTF8, encodeUTF8 } from '../utils/bytes';\n\nexport type Bytes = string | ArrayBuffer | Uint8Array | null | undefined;\n\n/**\n * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally\n * reading lines from text.\n *\n * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258\n */\nexport class LineDecoder {\n // prettier-ignore\n static NEWLINE_CHARS = new Set(['\\n', '\\r']);\n static NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\n\n #buffer: Uint8Array;\n #carriageReturnIndex: number | null;\n\n constructor() {\n this.#buffer = new Uint8Array();\n this.#carriageReturnIndex = null;\n }\n\n decode(chunk: Bytes): string[] {\n if (chunk == null) {\n return [];\n }\n\n const binaryChunk =\n chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? encodeUTF8(chunk)\n : chunk;\n\n this.#buffer = concatBytes([this.#buffer, binaryChunk]);\n\n const lines: string[] = [];\n let patternIndex;\n while ((patternIndex = findNewlineIndex(this.#buffer, this.#carriageReturnIndex)) != null) {\n if (patternIndex.carriage && this.#carriageReturnIndex == null) {\n // skip until we either get a corresponding `\\n`, a new `\\r` or nothing\n this.#carriageReturnIndex = patternIndex.index;\n continue;\n }\n\n // we got double \\r or \\rtext\\n\n if (\n this.#carriageReturnIndex != null &&\n (patternIndex.index !== this.#carriageReturnIndex + 1 || patternIndex.carriage)\n ) {\n lines.push(decodeUTF8(this.#buffer.subarray(0, this.#carriageReturnIndex - 1)));\n this.#buffer = this.#buffer.subarray(this.#carriageReturnIndex);\n this.#carriageReturnIndex = null;\n continue;\n }\n\n const endIndex =\n this.#carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;\n\n const line = decodeUTF8(this.#buffer.subarray(0, endIndex));\n lines.push(line);\n\n this.#buffer = this.#buffer.subarray(patternIndex.index);\n this.#carriageReturnIndex = null;\n }\n\n return lines;\n }\n\n flush(): string[] {\n if (!this.#buffer.length) {\n return [];\n }\n return this.decode('\\n');\n }\n}\n\n/**\n * This function searches the buffer for the end patterns, (\\r or \\n)\n * and returns an object with the index preceding the matched newline and the\n * index after the newline char. `null` is returned if no new line is found.\n *\n * ```ts\n * findNewLineIndex('abc\\ndef') -> { preceding: 2, index: 3 }\n * ```\n */\nfunction findNewlineIndex(\n buffer: Uint8Array,\n startIndex: number | null,\n): { preceding: number; index: number; carriage: boolean } | null {\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n\n for (let i = startIndex ?? 0; i < buffer.length; i++) {\n if (buffer[i] === newline) {\n return { preceding: i, index: i + 1, carriage: false };\n }\n\n if (buffer[i] === carriage) {\n return { preceding: i, index: i + 1, carriage: true };\n }\n }\n\n return null;\n}\n\nexport function findDoubleNewlineIndex(buffer: Uint8Array): number {\n // This function searches the buffer for the end patterns (\\r\\r, \\n\\n, \\r\\n\\r\\n)\n // and returns the index right after the first occurrence of any pattern,\n // or -1 if none of the patterns are found.\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n\n for (let i = 0; i < buffer.length - 1; i++) {\n if (buffer[i] === newline && buffer[i + 1] === newline) {\n // \\n\\n\n return i + 2;\n }\n if (buffer[i] === carriage && buffer[i + 1] === carriage) {\n // \\r\\r\n return i + 2;\n }\n if (\n buffer[i] === carriage &&\n buffer[i + 1] === newline &&\n i + 3 < buffer.length &&\n buffer[i + 2] === carriage &&\n buffer[i + 3] === newline\n ) {\n // \\r\\n\\r\\n\n return i + 4;\n }\n }\n\n return -1;\n}\n","import { AnthropicError } from './error';\nimport { type ReadableStream } from '../internal/shim-types';\nimport { makeReadableStream } from '../internal/shims';\nimport { findDoubleNewlineIndex, LineDecoder } from '../internal/decoders/line';\nimport { ReadableStreamToAsyncIterable } from '../internal/shims';\nimport { isAbortError } from '../internal/errors';\nimport { safeJSON } from '../internal/utils/values';\nimport { encodeUTF8 } from '../internal/utils/bytes';\nimport { loggerFor } from '../internal/utils/log';\nimport type { BaseAnthropic } from '../client';\n\nimport { APIError } from './error';\nimport type { ErrorType } from '../resources/shared';\n\ntype Bytes = string | ArrayBuffer | Uint8Array | null | undefined;\n\nexport type ServerSentEvent = {\n event: string | null;\n data: string;\n raw: string[];\n};\n\nexport class Stream<Item> implements AsyncIterable<Item> {\n controller: AbortController;\n #client: BaseAnthropic | undefined;\n\n constructor(\n private iterator: () => AsyncIterator<Item>,\n controller: AbortController,\n client?: BaseAnthropic,\n ) {\n this.controller = controller;\n this.#client = client;\n }\n\n /**\n * Iterate the raw Server-Sent Events from `response` — `{event, data, raw}`\n * objects, before any JSON parsing or event-name filtering.\n *\n * This reads `response.body` directly (not a clone), so the response is\n * consumed. Use this in middleware that fully replaces the stream body; for\n * read-only observation of parsed events, use `ctx.parse()` instead.\n */\n static rawEvents(\n response: Response,\n controller: AbortController = new AbortController(),\n ): AsyncGenerator<ServerSentEvent, void, unknown> {\n return _iterSSEMessages(response, controller);\n }\n\n static fromSSEResponse<Item>(\n response: Response,\n controller: AbortController,\n client?: BaseAnthropic,\n ): Stream<Item> {\n let consumed = false;\n const logger = client ? loggerFor(client) : console;\n\n async function* iterator(): AsyncIterator<Item, any, undefined> {\n if (consumed) {\n throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const sse of _iterSSEMessages(response, controller)) {\n if (sse.event === 'completion') {\n try {\n yield JSON.parse(sse.data) as Item;\n } catch (e) {\n logger.error(`Could not parse message into JSON:`, sse.data);\n logger.error(`From chunk:`, sse.raw);\n throw e;\n }\n }\n\n if (\n sse.event === 'message_start' ||\n sse.event === 'message_delta' ||\n sse.event === 'message_stop' ||\n sse.event === 'content_block_start' ||\n sse.event === 'content_block_delta' ||\n sse.event === 'content_block_stop' ||\n sse.event === 'message' ||\n sse.event === 'user.message' ||\n sse.event === 'user.interrupt' ||\n sse.event === 'user.tool_confirmation' ||\n sse.event === 'user.custom_tool_result' ||\n sse.event === 'user.tool_result' ||\n sse.event === 'agent.message' ||\n sse.event === 'agent.thinking' ||\n sse.event === 'agent.tool_use' ||\n sse.event === 'agent.tool_result' ||\n sse.event === 'agent.mcp_tool_use' ||\n sse.event === 'agent.mcp_tool_result' ||\n sse.event === 'agent.custom_tool_use' ||\n sse.event === 'agent.thread_context_compacted' ||\n sse.event === 'session.status_running' ||\n sse.event === 'session.status_idle' ||\n sse.event === 'session.status_rescheduled' ||\n sse.event === 'session.status_terminated' ||\n sse.event === 'session.error' ||\n sse.event === 'session.deleted' ||\n sse.event === 'session.updated' ||\n sse.event === 'span.model_request_start' ||\n sse.event === 'span.model_request_end' ||\n sse.event === 'span.outcome_evaluation_start' ||\n sse.event === 'span.outcome_evaluation_ongoing' ||\n sse.event === 'span.outcome_evaluation_end' ||\n sse.event === 'user.define_outcome' ||\n sse.event === 'agent.thread_message_received' ||\n sse.event === 'agent.thread_message_sent' ||\n sse.event === 'agent.session_thread_message_received' ||\n sse.event === 'agent.session_thread_message_sent' ||\n sse.event === 'session.thread_created' ||\n sse.event === 'session.thread_status_created' ||\n sse.event === 'session.thread_status_running' ||\n sse.event === 'session.thread_status_idle' ||\n sse.event === 'session.thread_status_rescheduled' ||\n sse.event === 'session.thread_status_terminated' ||\n sse.event === 'system.message'\n ) {\n try {\n yield JSON.parse(sse.data) as Item;\n } catch (e) {\n logger.error(`Could not parse message into JSON:`, sse.data);\n logger.error(`From chunk:`, sse.raw);\n throw e;\n }\n }\n\n if (sse.event === 'ping') {\n continue;\n }\n\n if (sse.event === 'error') {\n const body = safeJSON(sse.data) ?? sse.data;\n const type = body?.error?.type as ErrorType | undefined;\n throw new APIError(undefined, body, undefined, response.headers, type);\n }\n }\n done = true;\n } catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (isAbortError(e)) return;\n throw e;\n } finally {\n // If the user `break`s, abort the ongoing request.\n if (!done) controller.abort();\n }\n }\n\n return new Stream(iterator, controller, client);\n }\n\n /**\n * Generates a Stream from a newline-separated ReadableStream\n * where each item is a JSON value.\n */\n static fromReadableStream<Item>(\n readableStream: ReadableStream,\n controller: AbortController,\n client?: BaseAnthropic,\n ): Stream<Item> {\n let consumed = false;\n\n async function* iterLines(): AsyncGenerator<string, void, unknown> {\n const lineDecoder = new LineDecoder();\n\n const iter = ReadableStreamToAsyncIterable<Bytes>(readableStream);\n for await (const chunk of iter) {\n for (const line of lineDecoder.decode(chunk)) {\n yield line;\n }\n }\n\n for (const line of lineDecoder.flush()) {\n yield line;\n }\n }\n\n async function* iterator(): AsyncIterator<Item, any, undefined> {\n if (consumed) {\n throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const line of iterLines()) {\n if (done) continue;\n if (line) yield JSON.parse(line) as Item;\n }\n done = true;\n } catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (isAbortError(e)) return;\n throw e;\n } finally {\n // If the user `break`s, abort the ongoing request.\n if (!done) controller.abort();\n }\n }\n\n return new Stream(iterator, controller, client);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Item> {\n return this.iterator();\n }\n\n /**\n * Splits the stream into two streams which can be\n * independently read from at different speeds.\n */\n tee(): [Stream<Item>, Stream<Item>] {\n const left: Array<Promise<IteratorResult<Item>>> = [];\n const right: Array<Promise<IteratorResult<Item>>> = [];\n const iterator = this.iterator();\n\n const teeIterator = (queue: Array<Promise<IteratorResult<Item>>>): AsyncIterator<Item> => {\n return {\n next: () => {\n if (queue.length === 0) {\n const result = iterator.next();\n left.push(result);\n right.push(result);\n }\n return queue.shift()!;\n },\n };\n };\n\n return [\n new Stream(() => teeIterator(left), this.controller, this.#client),\n new Stream(() => teeIterator(right), this.controller, this.#client),\n ];\n }\n\n /**\n * Converts this stream to a newline-separated ReadableStream of\n * JSON stringified values in the stream\n * which can be turned back into a Stream with `Stream.fromReadableStream()`.\n */\n toReadableStream(): ReadableStream {\n const self = this;\n let iter: AsyncIterator<Item>;\n\n return makeReadableStream({\n async start() {\n iter = self[Symbol.asyncIterator]();\n },\n async pull(ctrl: any) {\n try {\n const { value, done } = await iter.next();\n if (done) return ctrl.close();\n\n const bytes = encodeUTF8(JSON.stringify(value) + '\\n');\n\n ctrl.enqueue(bytes);\n } catch (err) {\n ctrl.error(err);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n }\n}\n\nexport async function* _iterSSEMessages(\n response: Response,\n controller: AbortController,\n): AsyncGenerator<ServerSentEvent, void, unknown> {\n if (!response.body) {\n controller.abort();\n if (\n typeof (globalThis as any).navigator !== 'undefined' &&\n (globalThis as any).navigator.product === 'ReactNative'\n ) {\n throw new AnthropicError(\n `The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`,\n );\n }\n throw new AnthropicError(`Attempted to iterate over a response with no body`);\n }\n\n const sseDecoder = new SSEDecoder();\n const lineDecoder = new LineDecoder();\n\n const iter = ReadableStreamToAsyncIterable<Bytes>(response.body);\n for await (const sseChunk of iterSSEChunks(iter)) {\n for (const line of lineDecoder.decode(sseChunk)) {\n const sse = sseDecoder.decode(line);\n if (sse) yield sse;\n }\n }\n\n for (const line of lineDecoder.flush()) {\n const sse = sseDecoder.decode(line);\n if (sse) yield sse;\n }\n}\n\n/**\n * Given an async iterable iterator, iterates over it and yields full\n * SSE chunks, i.e. yields when a double new-line is encountered.\n */\nasync function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> {\n let data = new Uint8Array();\n\n for await (const chunk of iterator) {\n if (chunk == null) {\n continue;\n }\n\n const binaryChunk =\n chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? encodeUTF8(chunk)\n : chunk;\n\n let newData = new Uint8Array(data.length + binaryChunk.length);\n newData.set(data);\n newData.set(binaryChunk, data.length);\n data = newData;\n\n let patternIndex;\n while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {\n yield data.slice(0, patternIndex);\n data = data.slice(patternIndex);\n }\n }\n\n if (data.length > 0) {\n yield data;\n }\n}\n\nclass SSEDecoder {\n private data: string[];\n private event: string | null;\n private chunks: string[];\n\n constructor() {\n this.event = null;\n this.data = [];\n this.chunks = [];\n }\n\n decode(line: string) {\n if (line.endsWith('\\r')) {\n line = line.substring(0, line.length - 1);\n }\n\n if (!line) {\n // empty line and we didn't previously encounter any messages\n if (!this.event && !this.data.length) return null;\n\n const sse: ServerSentEvent = {\n event: this.event,\n data: this.data.join('\\n'),\n raw: this.chunks,\n };\n\n this.event = null;\n this.data = [];\n this.chunks = [];\n\n return sse;\n }\n\n this.chunks.push(line);\n\n if (line.startsWith(':')) {\n return null;\n }\n\n let [fieldname, _, value] = partition(line, ':');\n\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n\n if (fieldname === 'event') {\n this.event = value;\n } else if (fieldname === 'data') {\n this.data.push(value);\n }\n\n return null;\n }\n}\n\nfunction partition(str: string, delimiter: string): [string, string, string] {\n const index = str.indexOf(delimiter);\n if (index !== -1) {\n return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\n }\n\n return [str, '', ''];\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport type { FinalRequestOptions } from './request-options';\nimport { Stream } from '../core/streaming';\nimport { type BaseAnthropic } from '../client';\nimport { formatRequestDetails, loggerFor } from './utils/log';\nimport type { AbstractPage } from '../core/pagination';\n\nexport type APIResponseProps = {\n response: Response;\n options: FinalRequestOptions;\n controller: AbortController;\n requestLogID: string;\n retryOfRequestLogID: string | undefined;\n startTime: number;\n};\n\nexport async function defaultParseResponse<T>(\n client: BaseAnthropic,\n props: APIResponseProps,\n): Promise<WithRequestID<T>> {\n const { response, requestLogID, retryOfRequestLogID, startTime } = props;\n const body = await (async () => {\n if (props.options.stream) {\n loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);\n\n // Note: there is an invariant here that isn't represented in the type system\n // that if you set `stream: true` the response type must also be `Stream<T>`\n\n return Stream.fromSSEResponse(response, props.controller) as any;\n }\n\n // fetch refuses to read the body when the status code is 204.\n if (response.status === 204) {\n return null as T;\n }\n\n if (props.options.__binaryResponse) {\n return response as unknown as T;\n }\n\n const contentType = response.headers.get('content-type');\n const mediaType = contentType?.split(';')[0]?.trim();\n const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');\n if (isJSON) {\n const contentLength = response.headers.get('content-length');\n if (contentLength === '0') {\n // if there is no content we can't do anything\n return undefined as T;\n }\n\n const json = await response.json();\n return addRequestID(json as T, response);\n }\n\n const text = await response.text();\n return text as unknown as T;\n })();\n loggerFor(client).debug(\n `[${requestLogID}] response parsed`,\n formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n body,\n durationMs: Date.now() - startTime,\n }),\n );\n return body;\n}\n\nexport type WithRequestID<T> =\n T extends Array<any> | Response | AbstractPage<any> ? T\n : T extends Record<string, any> ? T & { _request_id?: string | null }\n : T;\n\nexport function addRequestID<T>(value: T, response: Response): WithRequestID<T> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value as WithRequestID<T>;\n }\n\n return Object.defineProperty(value, '_request_id', {\n value: response.headers.get('request-id'),\n enumerable: false,\n }) as WithRequestID<T>;\n}\n","import type { BaseAnthropic } from '../client';\nimport type { Fetch } from '../internal/builtin-types';\nimport { castToError, isAbortError } from '../internal/errors';\nimport { addRequestID } from '../internal/parse';\nimport type { FinalRequestOptions } from '../internal/request-options';\nimport { defaultLogger, loggerFor, type Logger } from '../internal/utils/log';\nimport type { APIRequest } from './api';\nimport { AnthropicError, APIConnectionError, RetryableError } from './error';\nimport { Stream } from './streaming';\n\n/**\n * Invokes the rest of the middleware chain, ending with the underlying `fetch`.\n *\n * This function can be invoked multiple times.\n */\nexport type MiddlewareNext = (request: APIRequest) => Promise<Response>;\n\n/**\n * Helpers passed to each middleware alongside `next`, scoped to the request\n * in flight (one context is shared by every middleware in the chain).\n */\nexport interface MiddlewareContext {\n /**\n * The SDK request options the API call in flight was made with: `method`,\n * `path`, the pre-encoded `body`, `stream`, etc.\n *\n * `undefined` when the chain isn't running for an SDK API request, i.e.\n * for credential token-exchange requests.\n */\n readonly options?: FinalRequestOptions | undefined;\n\n /**\n * The client's logger, pre-filtered to the client's configured log level\n * (the `logLevel` client option or the `ANTHROPIC_LOG` environment\n * variable). Calls below the active level are no-ops, so it's always safe\n * to call; with no logger configured it writes to the global `console`.\n *\n * Values are logged as-is — when logging request or response headers,\n * redact credentials (`authorization`, `x-api-key`, `cookie`) the way the\n * SDK's own logs do.\n *\n * @example\n * ```ts\n * const mw: Middleware = async (request, next, ctx) => {\n * ctx.logger.debug('->', request.method, request.url);\n * return next(request);\n * };\n * ```\n */\n readonly logger: Logger;\n\n /**\n * Parse a response body the way the SDK would for the request in flight:\n *\n * - JSON responses are decoded, with the non-enumerable `_request_id`\n * property attached like SDK return values, and anything else resolves\n * to the body text.\n * - For streaming requests ({@link options}`.stream`), resolves immediately\n * with a {@link Stream} reading an independent copy of the response body —\n * iterating it doesn't consume the client's events, and aborting or\n * `break`ing out of it doesn't cancel the underlying request. Each call\n * returns a fresh `Stream` (streams are single-consumer, so they aren't\n * cached). Error (non-2xx) responses parse as JSON/text rather than as a\n * stream, mirroring the SDK's own handling.\n * - For binary requests, resolves with the `Response` itself, unconsumed.\n *\n * Reads through an internal `response.clone()`, so the response stays\n * readable: the client (and any other middleware) can still consume the\n * body afterwards. Non-stream results are cached per `Response` and shared\n * across the middleware chain, so repeated calls cost a single read.\n *\n * @example\n * ```ts\n * const mw: Middleware = async (request, next, ctx) => {\n * const response = await next(request);\n * const data = await ctx.parse<Message>(response);\n * if (data.type === 'message') console.log(data.usage);\n * return response;\n * };\n * ```\n */\n parse<T = unknown>(response: Response): Promise<T>;\n}\n\n/**\n * A function that wraps each HTTP request made by the client.\n *\n * Middleware may observe or modify the request before calling `next`, observe\n * or replace the response, short-circuit by returning a `Response` without\n * calling `next`, or call `next` multiple times to implement custom retries.\n *\n * Middleware always observes the canonical Anthropic-shaped request — e.g.\n * `POST .../v1/messages` with `model` and `stream` in the JSON body and\n * `anthropic-beta` as a header — with the client's logical credentials\n * (`x-api-key` / `Authorization`) applied. On clients for third-party\n * backends (Bedrock, Vertex, Foundry), the backend adaptation — URL and body\n * rewriting, request signing (e.g. AWS SigV4), and response normalization\n * (e.g. AWS EventStream to SSE) — runs *inside* `next`, so middleware behaves\n * identically on every backend: mutating the request is safe (signing covers\n * the final body), and streaming responses are observed as SSE. Each `next()`\n * call re-runs the adaptation, so custom retries re-sign from scratch. To\n * observe the literal wire traffic instead, provide a custom `fetch`.\n *\n * Middleware must not consume the body of the `Response` it returns - the\n * client still needs to read it. To inspect the body, use\n * `await ctx.parse(response)` (cached, leaves the body readable) or read a\n * clone (`await response.clone().text()`); to transform it, return a\n * replacement, e.g. `new Response(body, response)`.\n *\n * Middleware runs per HTTP attempt, inside the SDK's retry loop; the attempt\n * number is available via the `X-Stainless-Retry-Count` request header. An\n * error thrown from middleware propagates to the caller as-is.\n *\n * Middleware errors are **not** retried apart from connection-level errors:\n * timeout/abort errors, errors thrown by `fetch()`, and `APIConnectionError`s\n * or `RetryableError`s — thrown directly or present anywhere in an error's\n * `cause` chain. Retryable middleware errors still propagate to the caller\n * as-is once retries are exhausted.\n *\n * @example\n * ```ts\n * const logger: Middleware = async (request, next, ctx) => {\n * ctx.logger.debug('->', request.method, request.url);\n * const response = await next(request);\n * ctx.logger.debug('<-', response.status, request.url);\n * return response;\n * };\n *\n * const client = new Anthropic({ middleware: [logger] });\n * ```\n */\nexport type Middleware = (\n request: APIRequest,\n next: MiddlewareNext,\n ctx: MiddlewareContext,\n) => Promise<Response>;\n\n/**\n * Errors thrown by the underlying `fetch`, as opposed to by a middleware.\n *\n * Tracked so the client can apply its connection-error retry policy to\n * transport failures while letting errors thrown by middleware propagate to\n * the caller untouched.\n */\nconst fetchOriginErrors = new WeakSet<object>();\n\n/** Whether `err` was thrown by the underlying `fetch` rather than by a middleware. */\nexport function isFetchOriginError(err: unknown): boolean {\n return typeof err === 'object' && err !== null && fetchOriginErrors.has(err);\n}\n\n/**\n * Whether an error thrown by middleware should stay on the SDK's\n * connection-error retry policy: fetch-origin, abort, `APIConnectionError`, or\n * `RetryableError` — checked through the error's `cause` chain.\n */\nexport function isRetryableError(err: unknown): boolean {\n const seen = new Set<unknown>(); // guard against `cause` cycles\n while (typeof err === 'object' && err !== null && !seen.has(err)) {\n seen.add(err);\n if (\n isFetchOriginError(err) ||\n isAbortError(err) ||\n err instanceof APIConnectionError ||\n err instanceof RetryableError\n ) {\n return true;\n }\n err = (err as { cause?: unknown }).cause;\n }\n return false;\n}\n\n/**\n * Wraps `fetchFn` so each call runs through `middleware`, keeping the same\n * call signature as `fetch` itself.\n *\n * With no middleware, calls are passed straight through to `fetchFn`.\n * Otherwise the arguments are normalized into an {@link APIRequest} (headers\n * coerced to a `Headers` instance, URL stringified) before entering the\n * chain. The chain is composed per call, so mutations of a `middleware`\n * array are picked up by later requests.\n *\n * `options` — the SDK request options behind this call, when there are any —\n * is surfaced to middleware as `ctx.options` and drives `ctx.parse`.\n *\n * `client` supplies `ctx.logger` (the client's level-filtered logger);\n * without it, `ctx.logger` falls back to the client defaults: `console`,\n * filtered to `ANTHROPIC_LOG` or `'warn'`.\n */\nexport function wrapFetchWithMiddleware(\n fetchFn: Fetch,\n middleware: readonly Middleware[],\n options?: FinalRequestOptions | undefined,\n client?: BaseAnthropic | undefined,\n): Fetch {\n return async (url, init = {}) => {\n if (middleware.length === 0) {\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n return fetchFn.call(undefined, url, init);\n }\n const headers = init.headers instanceof Headers ? init.headers : new Headers(init.headers);\n const response = await applyMiddleware(\n fetchFn,\n middleware,\n options,\n client,\n )({\n ...init,\n headers,\n url:\n typeof url === 'string' ? url\n : url instanceof URL ? url.href\n : url.url,\n });\n // Catch a footgun before the client tries to read the body itself and\n // fails with a confusing low-level stream error.\n if (response.bodyUsed || response.body?.locked) {\n throw new AnthropicError(\n 'middleware consumed the response body; use response.clone() to inspect it, ' +\n 'or return new Response(body, response) to consume and replace it',\n );\n }\n return response;\n };\n}\n\n/**\n * Creates the {@link MiddlewareContext} shared by every middleware in one chain.\n */\nfunction createMiddlewareContext(\n options: FinalRequestOptions | undefined,\n client: BaseAnthropic | undefined,\n): MiddlewareContext {\n // Keyed on the Response so each `next()` call's response (e.g. with custom\n // retries, or a middleware swapping in a replacement) parses independently,\n // while several middleware parsing the same response share a single read.\n const cache = new WeakMap<Response, Promise<unknown>>();\n return {\n options,\n // Resolved per chain, so changes to the client's `logLevel`/`logger`\n // apply to subsequent requests.\n logger: client ? loggerFor(client) : defaultLogger(),\n parse<T>(response: Response): Promise<T> {\n // Streams are single-consumer, so caching one would hand later callers\n // an already-consumed stream; every call gets a fresh clone-backed one.\n if (options?.stream && response.ok) {\n return parseMiddlewareResponse(response, options) as Promise<T>;\n }\n let parsed = cache.get(response);\n if (!parsed) {\n parsed = parseMiddlewareResponse(response, options);\n cache.set(response, parsed);\n }\n return parsed as Promise<T>;\n },\n };\n}\n\n/**\n * Mirrors the client's own response parsing (`defaultParseResponse` in\n * `internal/parse.ts`), reading through a clone so the body stays available\n * to the rest of the chain and the client itself.\n */\nasync function parseMiddlewareResponse(\n response: Response,\n options: FinalRequestOptions | undefined,\n): Promise<unknown> {\n if (response.bodyUsed || response.body?.locked) {\n throw new AnthropicError(\n 'cannot ctx.parse() a response whose body was already consumed; ' +\n 'call ctx.parse() instead of reading the body, or read via response.clone()',\n );\n }\n\n // Error responses parse as JSON/text below — the SDK only stream-parses\n // successful responses, and middleware typically wants the error body.\n if (options?.stream && response.ok) {\n // A fresh controller rather than the request's own: aborting (or\n // `break`ing out of) the middleware's stream must not cancel the\n // in-flight request the client is still reading.\n return Stream.fromSSEResponse(response.clone(), new AbortController());\n }\n\n // fetch refuses to read the body when the status code is 204.\n if (response.status === 204) {\n return null;\n }\n\n if (options?.__binaryResponse) {\n return response;\n }\n\n const contentType = response.headers.get('content-type');\n const mediaType = contentType?.split(';')[0]?.trim();\n const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');\n if (isJSON) {\n if (response.headers.get('content-length') === '0') {\n // if there is no content we can't do anything\n return undefined;\n }\n return addRequestID(await response.clone().json(), response);\n }\n\n return await response.clone().text();\n}\n\n/**\n * Composes `middleware` around `fetchFn` and returns the entry point of the chain.\n */\nexport function applyMiddleware(\n fetchFn: Fetch,\n middleware: readonly Middleware[],\n options?: FinalRequestOptions | undefined,\n client?: BaseAnthropic | undefined,\n): MiddlewareNext {\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n let next: MiddlewareNext = async ({ url, ...init }) => {\n try {\n return await fetchFn.call(undefined, url, init);\n } catch (err) {\n // Brand the error as fetch-origin, normalizing with `castToError` first since a\n // WeakSet can't hold primitives and the brand must be on the same object the\n // client's own `castToError` will later pass through.\n const error = castToError(err);\n fetchOriginErrors.add(error);\n throw error;\n }\n };\n\n const ctx = createMiddlewareContext(options, client);\n for (let i = middleware.length - 1; i >= 0; i--) {\n const mw = middleware[i]!;\n const nextInner = next;\n next = async (request) => mw(request, nextInner, ctx);\n }\n\n return next;\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { type BaseAnthropic } from '../client';\n\nimport { type PromiseOrValue } from '../internal/types';\nimport {\n type APIResponseProps,\n type WithRequestID,\n defaultParseResponse,\n addRequestID,\n} from '../internal/parse';\n\n/**\n * A subclass of `Promise` providing additional helper methods\n * for interacting with the SDK.\n */\nexport class APIPromise<T> extends Promise<WithRequestID<T>> {\n private parsedPromise: Promise<WithRequestID<T>> | undefined;\n #client: BaseAnthropic;\n\n constructor(\n client: BaseAnthropic,\n private responsePromise: Promise<APIResponseProps>,\n private parseResponse: (\n client: BaseAnthropic,\n props: APIResponseProps,\n ) => PromiseOrValue<WithRequestID<T>> = defaultParseResponse,\n ) {\n super((resolve) => {\n // this is maybe a bit weird but this has to be a no-op to not implicitly\n // parse the response body; instead .then, .catch, .finally are overridden\n // to parse the response\n resolve(null as any);\n });\n this.#client = client;\n }\n\n _thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U> {\n return new APIPromise(this.#client, this.responsePromise, async (client, props) =>\n addRequestID(transform(await this.parseResponse(client, props), props), props.response),\n );\n }\n\n /**\n * Gets the raw `Response` instance instead of parsing the response\n * data.\n *\n * If you want to parse the response body but still get the `Response`\n * instance, you can use {@link withResponse()}.\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\n * to your `tsconfig.json`.\n */\n asResponse(): Promise<Response> {\n return this.responsePromise.then((p) => p.response);\n }\n\n /**\n * Gets the parsed response data, the raw `Response` instance and the ID of the request,\n * returned via the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * If you just want to get the raw `Response` instance without parsing it,\n * you can use {@link asResponse()}.\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\n * to your `tsconfig.json`.\n */\n async withResponse(): Promise<{ data: T; response: Response; request_id: string | null | undefined }> {\n const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\n return { data, response, request_id: response.headers.get('request-id') };\n }\n\n private parse(): Promise<WithRequestID<T>> {\n if (!this.parsedPromise) {\n this.parsedPromise = this.responsePromise.then(\n (data) => this.parseResponse(this.#client, data) as any as Promise<WithRequestID<T>>,\n );\n }\n return this.parsedPromise;\n }\n\n override then<TResult1 = WithRequestID<T>, TResult2 = never>(\n onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): Promise<TResult1 | TResult2> {\n return this.parse().then(onfulfilled, onrejected);\n }\n\n override catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,\n ): Promise<WithRequestID<T> | TResult> {\n return this.parse().catch(onrejected);\n }\n\n override finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<T>> {\n return this.parse().finally(onfinally);\n }\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { AnthropicError } from './error';\nimport { FinalRequestOptions } from '../internal/request-options';\nimport { defaultParseResponse, WithRequestID } from '../internal/parse';\nimport { type BaseAnthropic } from '../client';\nimport { APIPromise } from './api-promise';\nimport { type APIResponseProps } from '../internal/parse';\nimport { maybeObj } from '../internal/utils/values';\n\nexport type PageRequestOptions = Pick<FinalRequestOptions, 'query' | 'headers' | 'body' | 'path' | 'method'>;\n\nexport abstract class AbstractPage<Item> implements AsyncIterable<Item> {\n #client: BaseAnthropic;\n protected options: FinalRequestOptions;\n\n protected response: Response;\n protected body: unknown;\n\n constructor(client: BaseAnthropic, response: Response, body: unknown, options: FinalRequestOptions) {\n this.#client = client;\n this.options = options;\n this.response = response;\n this.body = body;\n }\n\n abstract nextPageRequestOptions(): PageRequestOptions | null;\n\n abstract getPaginatedItems(): Item[];\n\n hasNextPage(): boolean {\n const items = this.getPaginatedItems();\n if (!items.length) return false;\n return this.nextPageRequestOptions() != null;\n }\n\n async getNextPage(): Promise<this> {\n const nextOptions = this.nextPageRequestOptions();\n if (!nextOptions) {\n throw new AnthropicError(\n 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',\n );\n }\n\n return await this.#client.requestAPIList(this.constructor as any, nextOptions);\n }\n\n async *iterPages(): AsyncGenerator<this> {\n let page: this = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<Item> {\n for await (const page of this.iterPages()) {\n for (const item of page.getPaginatedItems()) {\n yield item;\n }\n }\n }\n}\n\n/**\n * This subclass of Promise will resolve to an instantiated Page once the request completes.\n *\n * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\nexport class PagePromise<\n PageClass extends AbstractPage<Item>,\n Item = ReturnType<PageClass['getPaginatedItems']>[number],\n >\n extends APIPromise<PageClass>\n implements AsyncIterable<Item>\n{\n constructor(\n client: BaseAnthropic,\n request: Promise<APIResponseProps>,\n Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,\n ) {\n super(\n client,\n request,\n async (client, props) =>\n new Page(\n client,\n props.response,\n await defaultParseResponse(client, props),\n props.options,\n ) as WithRequestID<PageClass>,\n );\n }\n\n /**\n * Allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<Item> {\n const page = await this;\n for await (const item of page) {\n yield item;\n }\n }\n}\n\nexport interface PageResponse<Item> {\n data: Array<Item>;\n\n has_more: boolean;\n\n first_id: string | null;\n\n last_id: string | null;\n}\n\nexport interface PageParams {\n /**\n * Number of items per page.\n */\n limit?: number;\n\n before_id?: string;\n\n after_id?: string;\n}\n\nexport class Page<Item> extends AbstractPage<Item> implements PageResponse<Item> {\n data: Array<Item>;\n\n has_more: boolean;\n\n first_id: string | null;\n\n last_id: string | null;\n\n constructor(\n client: BaseAnthropic,\n response: Response,\n body: PageResponse<Item>,\n options: FinalRequestOptions,\n ) {\n super(client, response, body, options);\n\n this.data = body.data || [];\n this.has_more = body.has_more || false;\n this.first_id = body.first_id || null;\n this.last_id = body.last_id || null;\n }\n\n getPaginatedItems(): Item[] {\n return this.data ?? [];\n }\n\n override hasNextPage(): boolean {\n if (this.has_more === false) {\n return false;\n }\n\n return super.hasNextPage();\n }\n\n nextPageRequestOptions(): PageRequestOptions | null {\n if ((this.options.query as Record<string, unknown>)?.['before_id']) {\n // in reverse\n const first_id = this.first_id;\n if (!first_id) {\n return null;\n }\n\n return {\n ...this.options,\n query: {\n ...maybeObj(this.options.query),\n before_id: first_id,\n },\n };\n }\n\n const cursor = this.last_id;\n if (!cursor) {\n return null;\n }\n\n return {\n ...this.options,\n query: {\n ...maybeObj(this.options.query),\n after_id: cursor,\n },\n };\n }\n}\n\nexport interface TokenPageResponse<Item> {\n data: Array<Item>;\n\n has_more: boolean;\n\n next_page: string | null;\n}\n\nexport interface TokenPageParams {\n /**\n * Number of items per page.\n */\n limit?: number;\n\n page_token?: string;\n}\n\nexport class TokenPage<Item> extends AbstractPage<Item> implements TokenPageResponse<Item> {\n data: Array<Item>;\n\n has_more: boolean;\n\n next_page: string | null;\n\n constructor(\n client: BaseAnthropic,\n response: Response,\n body: TokenPageResponse<Item>,\n options: FinalRequestOptions,\n ) {\n super(client, response, body, options);\n\n this.data = body.data || [];\n this.has_more = body.has_more || false;\n this.next_page = body.next_page || null;\n }\n\n getPaginatedItems(): Item[] {\n return this.data ?? [];\n }\n\n override hasNextPage(): boolean {\n if (this.has_more === false) {\n return false;\n }\n\n return super.hasNextPage();\n }\n\n nextPageRequestOptions(): PageRequestOptions | null {\n const cursor = this.next_page;\n if (!cursor) {\n return null;\n }\n\n return {\n ...this.options,\n query: {\n ...maybeObj(this.options.query),\n page_token: cursor,\n },\n };\n }\n}\n\nexport interface PageCursorResponse<Item> {\n data: Array<Item>;\n\n next_page: string | null;\n}\n\nexport interface PageCursorParams {\n /**\n * Number of items per page.\n */\n limit?: number;\n\n page?: string | null;\n}\n\nexport class PageCursor<Item> extends AbstractPage<Item> implements PageCursorResponse<Item> {\n data: Array<Item>;\n\n next_page: string | null;\n\n constructor(\n client: BaseAnthropic,\n response: Response,\n body: PageCursorResponse<Item>,\n options: FinalRequestOptions,\n ) {\n super(client, response, body, options);\n\n this.data = body.data || [];\n this.next_page = body.next_page || null;\n }\n\n getPaginatedItems(): Item[] {\n return this.data ?? [];\n }\n\n nextPageRequestOptions(): PageRequestOptions | null {\n const cursor = this.next_page;\n if (!cursor) {\n return null;\n }\n\n return {\n ...this.options,\n query: {\n ...maybeObj(this.options.query),\n page: cursor,\n },\n };\n }\n}\n","import { type RequestOptions } from './request-options';\nimport type { FilePropertyBag, Fetch } from './builtin-types';\nimport type { BaseAnthropic } from '../client';\nimport { ReadableStreamFrom } from './shims';\n\nexport type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | DataView;\ntype FsReadStream = AsyncIterable<Uint8Array> & { path: string | { toString(): string } };\n\n// https://github.com/oven-sh/bun/issues/5980\ninterface BunFile extends Blob {\n readonly name?: string | undefined;\n}\n\nexport const checkFileSupport = () => {\n if (typeof File === 'undefined') {\n const { process } = globalThis as any;\n const isOldNode =\n typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20;\n throw new Error(\n '`File` is not defined as a global, which is required for file uploads.' +\n (isOldNode ?\n \" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.\"\n : ''),\n );\n }\n};\n\n/**\n * Typically, this is a native \"File\" class.\n *\n * We provide the {@link toFile} utility to convert a variety of objects\n * into the File class.\n *\n * For convenience, you can also pass a fetch Response, or in Node,\n * the result of fs.createReadStream().\n */\nexport type Uploadable = File | Response | FsReadStream | BunFile;\n\n/**\n * Construct a `File` instance. This is used to ensure a helpful error is thrown\n * for environments that don't define a global `File` yet.\n */\nexport function makeFile(\n fileBits: BlobPart[],\n fileName: string | undefined,\n options?: FilePropertyBag,\n): File {\n checkFileSupport();\n return new File(fileBits as any, fileName ?? 'unknown_file', options);\n}\n\nexport function getName(value: any, stripPath: boolean): string | undefined {\n const val =\n (typeof value === 'object' &&\n value !== null &&\n (('name' in value && value.name && String(value.name)) ||\n ('url' in value && value.url && String(value.url)) ||\n ('filename' in value && value.filename && String(value.filename)) ||\n ('path' in value && value.path && String(value.path)))) ||\n '';\n\n return stripPath ? val.split(/[\\\\/]/).pop() || undefined : val;\n}\n\nexport const isAsyncIterable = (value: any): value is AsyncIterable<any> =>\n value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';\n\n/**\n * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.\n * Otherwise returns the request as is.\n */\nexport const maybeMultipartFormRequestOptions = async (\n opts: RequestOptions,\n fetch: BaseAnthropic | Fetch,\n): Promise<RequestOptions> => {\n if (!hasUploadableValue(opts.body)) return opts;\n\n return { ...opts, body: await createForm(opts.body, fetch) };\n};\n\ntype MultipartFormRequestOptions = Omit<RequestOptions, 'body'> & { body: unknown };\n\nexport const multipartFormRequestOptions = async (\n opts: MultipartFormRequestOptions,\n fetch: BaseAnthropic | Fetch,\n stripFilenames: boolean = true,\n): Promise<RequestOptions> => {\n return { ...opts, body: await createForm(opts.body, fetch, stripFilenames) };\n};\n\nconst supportsFormDataMap = /* @__PURE__ */ new WeakMap<Fetch, Promise<boolean>>();\n\n/**\n * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending\n * properly-encoded form data, it just stringifies the object, resulting in a request body of \"[object FormData]\".\n * This function detects if the fetch function provided supports the global FormData object to avoid\n * confusing error messages later on.\n */\nfunction supportsFormData(fetchObject: BaseAnthropic | Fetch): Promise<boolean> {\n const fetch: Fetch = typeof fetchObject === 'function' ? fetchObject : (fetchObject as any).fetch;\n const cached = supportsFormDataMap.get(fetch);\n if (cached) return cached;\n const promise = (async () => {\n try {\n const FetchResponse = (\n 'Response' in fetch ?\n fetch.Response\n : (await fetch('data:,')).constructor) as typeof Response;\n const data = new FormData();\n if (data.toString() === (await new FetchResponse(data).text())) {\n return false;\n }\n return true;\n } catch {\n // avoid false negatives\n return true;\n }\n })();\n supportsFormDataMap.set(fetch, promise);\n return promise;\n}\n\nexport const createForm = async <T = Record<string, unknown>>(\n body: T | undefined,\n fetch: BaseAnthropic | Fetch,\n stripFilenames: boolean = true,\n): Promise<FormData> => {\n if (!(await supportsFormData(fetch))) {\n throw new TypeError(\n 'The provided fetch function does not support file uploads with the current global FormData class.',\n );\n }\n const form = new FormData();\n await Promise.all(\n Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, stripFilenames)),\n );\n return form;\n};\n\n// We check for Blob not File because Bun.File doesn't inherit from File,\n// but they both inherit from Blob and have a `name` property at runtime.\nconst isNamedBlob = (value: unknown): value is Blob => value instanceof Blob && 'name' in value;\n\nconst isUploadable = (value: unknown) =>\n typeof value === 'object' &&\n value !== null &&\n (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value));\n\nconst hasUploadableValue = (value: unknown): boolean => {\n if (isUploadable(value)) return true;\n if (Array.isArray(value)) return value.some(hasUploadableValue);\n if (value && typeof value === 'object') {\n for (const k in value) {\n if (hasUploadableValue((value as any)[k])) return true;\n }\n }\n return false;\n};\n\nconst addFormValue = async (\n form: FormData,\n key: string,\n value: unknown,\n stripFilenames: boolean,\n): Promise<void> => {\n if (value === undefined) return;\n if (value == null) {\n throw new TypeError(\n `Received null for \"${key}\"; to pass null in FormData, you must use the string 'null'`,\n );\n }\n\n // TODO: make nested formats configurable\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n form.append(key, String(value));\n } else if (value instanceof Response) {\n let options = {} as FilePropertyBag;\n const contentType = value.headers.get('Content-Type');\n if (contentType) {\n options = { type: contentType };\n }\n\n form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options));\n } else if (isAsyncIterable(value)) {\n form.append(\n key,\n makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, stripFilenames)),\n );\n } else if (isNamedBlob(value)) {\n form.append(key, makeFile([value], getName(value, stripFilenames), { type: value.type }));\n } else if (Array.isArray(value)) {\n await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry, stripFilenames)));\n } else if (typeof value === 'object') {\n await Promise.all(\n Object.entries(value).map(([name, prop]) =>\n addFormValue(form, `${key}[${name}]`, prop, stripFilenames),\n ),\n );\n } else {\n throw new TypeError(\n `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`,\n );\n }\n};\n","import { BlobPart, getName, makeFile, isAsyncIterable } from './uploads';\nimport type { FilePropertyBag } from './builtin-types';\nimport { checkFileSupport } from './uploads';\n\ntype BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | DataView;\n\n/**\n * Intended to match DOM Blob, node-fetch Blob, node:buffer Blob, etc.\n * Don't add arrayBuffer here, node-fetch doesn't have it\n */\ninterface BlobLike {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */\n readonly size: number;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */\n readonly type: string;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */\n text(): Promise<string>;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */\n slice(start?: number, end?: number): BlobLike;\n}\n\n/**\n * This check adds the arrayBuffer() method type because it is available and used at runtime\n */\nconst isBlobLike = (value: any): value is BlobLike & { arrayBuffer(): Promise<ArrayBuffer> } =>\n value != null &&\n typeof value === 'object' &&\n typeof value.size === 'number' &&\n typeof value.type === 'string' &&\n typeof value.text === 'function' &&\n typeof value.slice === 'function' &&\n typeof value.arrayBuffer === 'function';\n\n/**\n * Intended to match DOM File, node:buffer File, undici File, etc.\n */\ninterface FileLike extends BlobLike {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */\n readonly lastModified: number;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */\n readonly name?: string | undefined;\n}\n\n/**\n * This check adds the arrayBuffer() method type because it is available and used at runtime\n */\nconst isFileLike = (value: any): value is FileLike & { arrayBuffer(): Promise<ArrayBuffer> } =>\n value != null &&\n typeof value === 'object' &&\n typeof value.name === 'string' &&\n typeof value.lastModified === 'number' &&\n isBlobLike(value);\n\n/**\n * Intended to match DOM Response, node-fetch Response, undici Response, etc.\n */\nexport interface ResponseLike {\n url: string;\n blob(): Promise<BlobLike>;\n}\n\nconst isResponseLike = (value: any): value is ResponseLike =>\n value != null &&\n typeof value === 'object' &&\n typeof value.url === 'string' &&\n typeof value.blob === 'function';\n\nexport type ToFileInput =\n | FileLike\n | ResponseLike\n | Exclude<BlobLikePart, string>\n | AsyncIterable<BlobLikePart>;\n\n/**\n * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats\n * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts\n * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible\n * @param {Object=} options additional properties\n * @param {string=} options.type the MIME type of the content\n * @param {number=} options.lastModified the last modified timestamp\n * @returns a {@link File} with the given properties\n */\nexport async function toFile(\n value: ToFileInput | PromiseLike<ToFileInput>,\n name?: string | null | undefined,\n options?: FilePropertyBag | undefined,\n): Promise<File> {\n checkFileSupport();\n\n // If it's a promise, resolve it.\n value = await value;\n\n name ||= getName(value, true);\n\n // If we've been given a `File` we don't need to do anything if the name / options\n // have not been customised.\n if (isFileLike(value)) {\n if (value instanceof File && name == null && options == null) {\n return value;\n }\n return makeFile([await value.arrayBuffer()], name ?? value.name, {\n type: value.type,\n lastModified: value.lastModified,\n ...options,\n });\n }\n\n if (isResponseLike(value)) {\n const blob = await value.blob();\n name ||= new URL(value.url).pathname.split(/[\\\\/]/).pop();\n\n return makeFile(await getBytes(blob), name, options);\n }\n\n const parts = await getBytes(value);\n\n if (!options?.type) {\n const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);\n if (typeof type === 'string') {\n options = { ...options, type };\n }\n }\n\n return makeFile(parts, name, options);\n}\n\nasync function getBytes(value: BlobLikePart | AsyncIterable<BlobLikePart>): Promise<Array<BlobPart>> {\n let parts: Array<BlobPart> = [];\n if (\n typeof value === 'string' ||\n ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\n value instanceof ArrayBuffer\n ) {\n parts.push(value);\n } else if (isBlobLike(value)) {\n parts.push(value instanceof Blob ? value : await value.arrayBuffer());\n } else if (\n isAsyncIterable(value) // includes Readable, ReadableStream, etc.\n ) {\n for await (const chunk of value) {\n parts.push(...(await getBytes(chunk as BlobLikePart))); // TODO, consider validating?\n }\n } else {\n const constructor = value?.constructor?.name;\n throw new Error(\n `Unexpected data type: ${typeof value}${\n constructor ? `; constructor: ${constructor}` : ''\n }${propsForError(value)}`,\n );\n }\n\n return parts;\n}\n\nfunction propsForError(value: unknown): string {\n if (typeof value !== 'object' || value === null) return '';\n const props = Object.getOwnPropertyNames(value);\n return `; props: [${props.map((p) => `\"${p}\"`).join(', ')}]`;\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { BaseAnthropic } from '../client';\n\nexport abstract class APIResource {\n protected _client: BaseAnthropic;\n\n constructor(client: BaseAnthropic) {\n this._client = client;\n }\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { isReadonlyArray } from './utils/values';\n\ntype HeaderValue = string | undefined | null;\nexport type HeadersLike =\n | Headers\n | readonly HeaderValue[][]\n | Record<string, HeaderValue | readonly HeaderValue[]>\n | undefined\n | null\n | NullableHeaders;\n\nconst brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders') as symbol & {\n description: 'brand.privateNullableHeaders';\n};\n\n/**\n * @internal\n * Users can pass explicit nulls to unset default headers. When we parse them\n * into a standard headers type we need to preserve that information.\n */\nexport type NullableHeaders = {\n /** Brand check, prevent users from creating a NullableHeaders. */\n [_: typeof brand_privateNullableHeaders]: true;\n /** Parsed headers. */\n values: Headers;\n /** Set of lowercase header names explicitly set to null. */\n nulls: Set<string>;\n};\n\nfunction* iterateHeaders(\n headers: HeadersLike,\n): IterableIterator<readonly [string, string | null | ClearSentinel]> {\n if (!headers) return;\n\n if (brand_privateNullableHeaders in headers) {\n const { values, nulls } = headers as NullableHeaders;\n yield* values.entries();\n for (const name of nulls) {\n yield [name, null];\n }\n return;\n }\n\n let shouldClear = false;\n let iter: Iterable<readonly (HeaderValue | readonly HeaderValue[])[]>;\n if (headers instanceof Headers) {\n iter = headers.entries();\n } else if (isReadonlyArray(headers)) {\n iter = headers;\n } else {\n shouldClear = true;\n iter = Object.entries(headers ?? {});\n }\n for (let row of iter) {\n const name = row[0];\n if (typeof name !== 'string') throw new TypeError('expected header name to be a string');\n const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];\n let didClear = false;\n for (const value of values) {\n if (value === undefined) continue;\n\n // Objects keys always overwrite older headers, they never append.\n // Yield the clear sentinel before adding the new values, so the\n // consumer can tell this synthetic \"clear-before-set\" apart from a\n // user's explicit `null` (= remove).\n if (shouldClear && !didClear) {\n didClear = true;\n yield [name, clearSentinel];\n }\n yield [name, value];\n }\n }\n}\n\n/** Distinguishes iterateHeaders' synthetic clear-before-set from a user `null`. */\nconst clearSentinel = Symbol('clear');\ntype ClearSentinel = typeof clearSentinel;\n\n/**\n * Headers whose values accumulate across {@link buildHeaders} sources instead\n * of the later source's value replacing the earlier one. Values are\n * comma-appended (deduplicated, order-preserving) into a single header line.\n */\nexport const APPEND_HEADERS: ReadonlySet<string> = new Set(['x-stainless-helper']);\n\nexport const appendHeaderValue = (existing: string | null, addition: string): string => {\n const tokens =\n existing ?\n existing\n .split(',')\n .map((t) => t.trim())\n .filter(Boolean)\n : [];\n for (const tok of addition.split(',').map((t) => t.trim())) {\n if (tok && !tokens.includes(tok)) tokens.push(tok);\n }\n return tokens.join(', ');\n};\n\nexport const buildHeaders = (newHeaders: HeadersLike[]): NullableHeaders => {\n const targetHeaders = new Headers();\n const nullHeaders = new Set<string>();\n for (const headers of newHeaders) {\n const seenHeaders = new Set<string>();\n for (const [name, value] of iterateHeaders(headers)) {\n const lowerName = name.toLowerCase();\n if (APPEND_HEADERS.has(lowerName)) {\n // Accumulating headers ignore the synthetic clear-before-set; an\n // explicit `null` (any source shape) is honored as removal.\n if (value === clearSentinel) continue;\n if (value === null) {\n targetHeaders.delete(name);\n nullHeaders.add(lowerName);\n } else {\n targetHeaders.set(name, appendHeaderValue(targetHeaders.get(name), value));\n nullHeaders.delete(lowerName);\n }\n continue;\n }\n if (value === clearSentinel || !seenHeaders.has(lowerName)) {\n targetHeaders.delete(name);\n seenHeaders.add(lowerName);\n if (value === clearSentinel) continue;\n }\n if (value === null) {\n targetHeaders.delete(name);\n nullHeaders.add(lowerName);\n } else {\n targetHeaders.append(name, value);\n nullHeaders.delete(lowerName);\n }\n }\n }\n return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };\n};\n\nexport const isEmptyHeaders = (headers: HeadersLike) => {\n for (const _ of iterateHeaders(headers)) return false;\n return true;\n};\n","import { AnthropicError } from '../../core/error';\n\n/**\n * Percent-encode everything that isn't safe to have in a path without encoding safe chars.\n *\n * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:\n * > unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n * > sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\" / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n * > pchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n */\nexport function encodeURIPath(str: string) {\n return str.replace(/[^A-Za-z0-9\\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);\n}\n\nconst EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));\n\nexport const createPathTagFunction = (pathEncoder = encodeURIPath) =>\n function path(statics: readonly string[], ...params: readonly unknown[]): string {\n // If there are no params, no processing is needed.\n if (statics.length === 1) return statics[0]!;\n\n let postPath = false;\n const invalidSegments = [];\n const path = statics.reduce((previousValue, currentValue, index) => {\n if (/[?#]/.test(currentValue)) {\n postPath = true;\n }\n const value = params[index];\n let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);\n if (\n index !== params.length &&\n (value == null ||\n (typeof value === 'object' &&\n // handle values from other realms\n value.toString ===\n Object.getPrototypeOf(Object.getPrototypeOf((value as any).hasOwnProperty ?? EMPTY) ?? EMPTY)\n ?.toString))\n ) {\n encoded = value + '';\n invalidSegments.push({\n start: previousValue.length + currentValue.length,\n length: encoded.length,\n error: `Value of type ${Object.prototype.toString\n .call(value)\n .slice(8, -1)} is not a valid path parameter`,\n });\n }\n return previousValue + currentValue + (index === params.length ? '' : encoded);\n }, '');\n\n const pathOnly = path.split(/[?#]/, 1)[0]!;\n const invalidSegmentPattern = /(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/gi;\n let match;\n\n // Find all invalid segments\n while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {\n invalidSegments.push({\n start: match.index,\n length: match[0].length,\n error: `Value \"${match[0]}\" can\\'t be safely passed as a path parameter`,\n });\n }\n\n invalidSegments.sort((a, b) => a.start - b.start);\n\n if (invalidSegments.length > 0) {\n let lastEnd = 0;\n const underline = invalidSegments.reduce((acc, segment) => {\n const spaces = ' '.repeat(segment.start - lastEnd);\n const arrows = '^'.repeat(segment.length);\n lastEnd = segment.start + segment.length;\n return acc + spaces + arrows;\n }, '');\n\n throw new AnthropicError(\n `Path parameters result in path with invalid segments:\\n${invalidSegments\n .map((e) => e.error)\n .join('\\n')}\\n${path}\\n${underline}`,\n );\n }\n\n return path;\n };\n\n/**\n * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.\n */\nexport const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport * as BetaAPI from './beta';\nimport * as AgentsAPI from './agents/agents';\nimport { APIPromise } from '../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../core/pagination';\nimport { buildHeaders } from '../../internal/headers';\nimport { RequestOptions } from '../../internal/request-options';\nimport { path } from '../../internal/utils/path';\n\nexport class DeploymentRuns extends APIResource {\n /**\n * Get Deployment Run\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeploymentRun =\n * await client.beta.deploymentRuns.retrieve(\n * 'deployment_run_id',\n * );\n * ```\n */\n retrieve(\n deploymentRunID: string,\n params: DeploymentRunRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeploymentRun> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/deployment_runs/${deploymentRunID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Deployment Runs\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsDeploymentRun of client.beta.deploymentRuns.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: DeploymentRunListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsDeploymentRunsPageCursor, BetaManagedAgentsDeploymentRun> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n '/v1/deployment_runs?beta=true',\n PageCursor<BetaManagedAgentsDeploymentRun>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n}\n\nexport type BetaManagedAgentsDeploymentRunsPageCursor = PageCursor<BetaManagedAgentsDeploymentRun>;\n\n/**\n * The deployment's agent was archived.\n */\nexport interface BetaManagedAgentsAgentArchivedRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'agent_archived_error';\n}\n\n/**\n * A persistent, append-only record of a single deployment execution. Records\n * session creation success or failure — no session lifecycle tracking.\n */\nexport interface BetaManagedAgentsDeploymentRun {\n /**\n * Unique identifier for this run (`drun_...`).\n */\n id: string;\n\n /**\n * A resolved agent reference with a concrete version.\n */\n agent: AgentsAPI.BetaManagedAgentsAgentReference;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n /**\n * ID of the deployment that produced this run.\n */\n deployment_id: string;\n\n /**\n * Why the run failed to create a session. The type identifies the failure; message\n * is human-readable detail.\n */\n error:\n | BetaManagedAgentsEnvironmentArchivedRunError\n | BetaManagedAgentsAgentArchivedRunError\n | BetaManagedAgentsEnvironmentNotFoundRunError\n | BetaManagedAgentsVaultNotFoundRunError\n | BetaManagedAgentsVaultArchivedRunError\n | BetaManagedAgentsFileNotFoundRunError\n | BetaManagedAgentsMemoryStoreArchivedRunError\n | BetaManagedAgentsSkillNotFoundRunError\n | BetaManagedAgentsSessionResourceNotFoundRunError\n | BetaManagedAgentsWorkspaceArchivedRunError\n | BetaManagedAgentsOrganizationDisabledRunError\n | BetaManagedAgentsSessionRateLimitedRunError\n | BetaManagedAgentsSessionCreationRejectedRunError\n | BetaManagedAgentsUnknownRunError\n | BetaManagedAgentsSelfHostedResourcesUnsupportedRunError\n | BetaManagedAgentsMCPEgressBlockedRunError\n | null;\n\n /**\n * Populated on success. Null on creation failure. Exactly one of session_id or\n * error is non-null.\n */\n session_id: string | null;\n\n /**\n * Describes what triggered a deployment run, with trigger-specific metadata.\n */\n trigger_context: BetaManagedAgentsTriggerContext;\n\n type: 'deployment_run';\n}\n\n/**\n * The deployment's environment was archived.\n */\nexport interface BetaManagedAgentsEnvironmentArchivedRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'environment_archived_error';\n}\n\n/**\n * The deployment's environment no longer exists.\n */\nexport interface BetaManagedAgentsEnvironmentNotFoundRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'environment_not_found_error';\n}\n\n/**\n * A file resource referenced by the deployment no longer exists.\n */\nexport interface BetaManagedAgentsFileNotFoundRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'file_not_found_error';\n}\n\n/**\n * The run was started manually by creating a session directly against the\n * deployment.\n */\nexport interface BetaManagedAgentsManualTriggerContext {\n type: 'manual';\n}\n\n/**\n * An MCP server host used by the deployment's agent is blocked by the\n * environment's network policy.\n */\nexport interface BetaManagedAgentsMCPEgressBlockedRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'mcp_egress_blocked_error';\n}\n\n/**\n * A memory store referenced by the deployment is archived.\n */\nexport interface BetaManagedAgentsMemoryStoreArchivedRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'memory_store_archived_error';\n}\n\n/**\n * The deployment's organization is disabled.\n */\nexport interface BetaManagedAgentsOrganizationDisabledRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'organization_disabled_error';\n}\n\n/**\n * The run was fired by the deployment's cron schedule.\n */\nexport interface BetaManagedAgentsScheduleTriggerContext {\n /**\n * A timestamp in RFC 3339 format\n */\n scheduled_at: string;\n\n type: 'schedule';\n}\n\n/**\n * The deployment configures resources, but its environment is self-hosted and\n * cannot mount them.\n */\nexport interface BetaManagedAgentsSelfHostedResourcesUnsupportedRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'self_hosted_resources_unsupported_error';\n}\n\n/**\n * The session create request was rejected with a non-retryable validation error.\n */\nexport interface BetaManagedAgentsSessionCreationRejectedRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'session_creation_rejected_error';\n}\n\n/**\n * Session creation was rejected due to rate limiting. The schedule keeps firing;\n * subsequent runs may succeed.\n */\nexport interface BetaManagedAgentsSessionRateLimitedRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'session_rate_limited_error';\n}\n\n/**\n * A referenced resource no longer exists and its kind was not reported.\n */\nexport interface BetaManagedAgentsSessionResourceNotFoundRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'session_resource_not_found_error';\n}\n\n/**\n * A skill referenced by the deployment's agent no longer exists.\n */\nexport interface BetaManagedAgentsSkillNotFoundRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'skill_not_found_error';\n}\n\n/**\n * Describes what triggered a deployment run, with trigger-specific metadata.\n */\nexport type BetaManagedAgentsTriggerContext =\n | BetaManagedAgentsScheduleTriggerContext\n | BetaManagedAgentsManualTriggerContext;\n\n/**\n * What triggered a deployment run.\n */\nexport type BetaManagedAgentsTriggerType = 'schedule' | 'manual';\n\n/**\n * An unknown or unexpected error caused the run to fail. A fallback variant;\n * clients that do not recognize a new error type can match on message alone.\n */\nexport interface BetaManagedAgentsUnknownRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'unknown_error';\n}\n\n/**\n * A vault referenced by the deployment is archived.\n */\nexport interface BetaManagedAgentsVaultArchivedRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'vault_archived_error';\n}\n\n/**\n * A vault referenced by the deployment no longer exists.\n */\nexport interface BetaManagedAgentsVaultNotFoundRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'vault_not_found_error';\n}\n\n/**\n * The deployment's workspace was archived.\n */\nexport interface BetaManagedAgentsWorkspaceArchivedRunError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n type: 'workspace_archived_error';\n}\n\nexport interface DeploymentRunRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface DeploymentRunListParams extends PageCursorParams {\n /**\n * Query param: Return runs created strictly after this time (exclusive).\n */\n 'created_at[gt]'?: string;\n\n /**\n * Query param: Return runs created at or after this time (inclusive).\n */\n 'created_at[gte]'?: string;\n\n /**\n * Query param: Return runs created strictly before this time (exclusive).\n */\n 'created_at[lt]'?: string;\n\n /**\n * Query param: Return runs created at or before this time (inclusive).\n */\n 'created_at[lte]'?: string;\n\n /**\n * Query param: Filter to a specific deployment. Omit to list across all\n * deployments in the workspace. Filtering by a non-existent deployment_id returns\n * 200 with empty data.\n */\n deployment_id?: string;\n\n /**\n * Query param: Filter: true for runs with non-null error, false for runs with\n * non-null session_id. Omit for all.\n */\n has_error?: boolean;\n\n /**\n * Query param: Filter runs by what triggered them. Omit to return all runs.\n */\n trigger_type?: BetaManagedAgentsTriggerType;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace DeploymentRuns {\n export {\n type BetaManagedAgentsAgentArchivedRunError as BetaManagedAgentsAgentArchivedRunError,\n type BetaManagedAgentsDeploymentRun as BetaManagedAgentsDeploymentRun,\n type BetaManagedAgentsEnvironmentArchivedRunError as BetaManagedAgentsEnvironmentArchivedRunError,\n type BetaManagedAgentsEnvironmentNotFoundRunError as BetaManagedAgentsEnvironmentNotFoundRunError,\n type BetaManagedAgentsFileNotFoundRunError as BetaManagedAgentsFileNotFoundRunError,\n type BetaManagedAgentsManualTriggerContext as BetaManagedAgentsManualTriggerContext,\n type BetaManagedAgentsMCPEgressBlockedRunError as BetaManagedAgentsMCPEgressBlockedRunError,\n type BetaManagedAgentsMemoryStoreArchivedRunError as BetaManagedAgentsMemoryStoreArchivedRunError,\n type BetaManagedAgentsOrganizationDisabledRunError as BetaManagedAgentsOrganizationDisabledRunError,\n type BetaManagedAgentsScheduleTriggerContext as BetaManagedAgentsScheduleTriggerContext,\n type BetaManagedAgentsSelfHostedResourcesUnsupportedRunError as BetaManagedAgentsSelfHostedResourcesUnsupportedRunError,\n type BetaManagedAgentsSessionCreationRejectedRunError as BetaManagedAgentsSessionCreationRejectedRunError,\n type BetaManagedAgentsSessionRateLimitedRunError as BetaManagedAgentsSessionRateLimitedRunError,\n type BetaManagedAgentsSessionResourceNotFoundRunError as BetaManagedAgentsSessionResourceNotFoundRunError,\n type BetaManagedAgentsSkillNotFoundRunError as BetaManagedAgentsSkillNotFoundRunError,\n type BetaManagedAgentsTriggerContext as BetaManagedAgentsTriggerContext,\n type BetaManagedAgentsTriggerType as BetaManagedAgentsTriggerType,\n type BetaManagedAgentsUnknownRunError as BetaManagedAgentsUnknownRunError,\n type BetaManagedAgentsVaultArchivedRunError as BetaManagedAgentsVaultArchivedRunError,\n type BetaManagedAgentsVaultNotFoundRunError as BetaManagedAgentsVaultNotFoundRunError,\n type BetaManagedAgentsWorkspaceArchivedRunError as BetaManagedAgentsWorkspaceArchivedRunError,\n type BetaManagedAgentsDeploymentRunsPageCursor as BetaManagedAgentsDeploymentRunsPageCursor,\n type DeploymentRunRetrieveParams as DeploymentRunRetrieveParams,\n type DeploymentRunListParams as DeploymentRunListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport * as BetaAPI from './beta';\nimport * as DeploymentRunsAPI from './deployment-runs';\nimport * as AgentsAPI from './agents/agents';\nimport * as EventsAPI from './sessions/events';\nimport * as SessionsAPI from './sessions/sessions';\nimport { APIPromise } from '../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../core/pagination';\nimport { buildHeaders } from '../../internal/headers';\nimport { RequestOptions } from '../../internal/request-options';\nimport { path } from '../../internal/utils/path';\n\nexport class Deployments extends APIResource {\n /**\n * Create Deployment\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeployment =\n * await client.beta.deployments.create({\n * agent: 'string',\n * environment_id: 'x',\n * initial_events: [\n * {\n * content: [\n * {\n * text: 'Where is my order #1234?',\n * type: 'text',\n * },\n * ],\n * type: 'user.message',\n * },\n * ],\n * name: 'x',\n * });\n * ```\n */\n create(params: DeploymentCreateParams, options?: RequestOptions): APIPromise<BetaManagedAgentsDeployment> {\n const { betas, ...body } = params;\n return this._client.post('/v1/deployments?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Get Deployment\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeployment =\n * await client.beta.deployments.retrieve('deployment_id');\n * ```\n */\n retrieve(\n deploymentID: string,\n params: DeploymentRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeployment> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/deployments/${deploymentID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update Deployment\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeployment =\n * await client.beta.deployments.update('deployment_id');\n * ```\n */\n update(\n deploymentID: string,\n params: DeploymentUpdateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeployment> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/deployments/${deploymentID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Deployments\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsDeployment of client.beta.deployments.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: DeploymentListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsDeploymentsPageCursor, BetaManagedAgentsDeployment> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/deployments?beta=true', PageCursor<BetaManagedAgentsDeployment>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Archive Deployment\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeployment =\n * await client.beta.deployments.archive('deployment_id');\n * ```\n */\n archive(\n deploymentID: string,\n params: DeploymentArchiveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeployment> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/deployments/${deploymentID}/archive?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Pause Deployment\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeployment =\n * await client.beta.deployments.pause('deployment_id');\n * ```\n */\n pause(\n deploymentID: string,\n params: DeploymentPauseParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeployment> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/deployments/${deploymentID}/pause?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Run Deployment Now\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeploymentRun =\n * await client.beta.deployments.run('deployment_id');\n * ```\n */\n run(\n deploymentID: string,\n params: DeploymentRunParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<DeploymentRunsAPI.BetaManagedAgentsDeploymentRun> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/deployments/${deploymentID}/run?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Unpause Deployment\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeployment =\n * await client.beta.deployments.unpause('deployment_id');\n * ```\n */\n unpause(\n deploymentID: string,\n params: DeploymentUnpauseParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeployment> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/deployments/${deploymentID}/unpause?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaManagedAgentsDeploymentsPageCursor = PageCursor<BetaManagedAgentsDeployment>;\n\n/**\n * The deployment's agent was archived.\n */\nexport interface BetaManagedAgentsAgentArchivedDeploymentPausedReasonError {\n type: 'agent_archived_error';\n}\n\n/**\n * 5-field POSIX cron schedule with computed runtime timestamps.\n */\nexport interface BetaManagedAgentsCronSchedule {\n /**\n * 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g.,\n * \"0 9 \\* \\* 1-5\" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean\n * Sunday. Extended cron syntax - seconds or year fields, and the special\n * characters L, W, #, and ? - is not supported, nor are predefined shortcuts\n * (@daily).\n */\n expression: string;\n\n /**\n * IANA timezone identifier (e.g., \"America/Los_Angeles\", \"UTC\").\n */\n timezone: string;\n\n type: 'cron';\n\n /**\n * A timestamp in RFC 3339 format\n */\n last_run_at?: string | null;\n\n /**\n * Up to 5 timestamps of upcoming cron occurrences. Non-empty for active and paused\n * deployments (reflects what the schedule would do if unpaused); empty once the\n * deployment is archived (`archived_at` set). Each fire is offset by a small\n * per-schedule jitter, so a run will actually start at or shortly after its listed\n * time.\n */\n upcoming_runs_at?: Array<string>;\n}\n\n/**\n * 5-field POSIX cron schedule. Literal wall-clock matching in the configured\n * timezone.\n */\nexport interface BetaManagedAgentsCronScheduleParams {\n /**\n * 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g.,\n * \"0 9 \\* \\* 1-5\" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean\n * Sunday. Extended cron syntax - seconds or year fields, and the special\n * characters L, W, #, and ? - is not supported, nor are predefined shortcuts\n * (@daily).\n */\n expression: string;\n\n /**\n * Required. IANA timezone identifier (e.g., \"America/Los_Angeles\", \"UTC\").\n * Validated against the IANA timezone database.\n */\n timezone: string;\n\n type: 'cron';\n}\n\n/**\n * A deployment is a configured instance of an agent — it binds the agent to\n * everything needed to run it autonomously: an environment, credentials, initial\n * events, and an optional schedule.\n */\nexport interface BetaManagedAgentsDeployment {\n /**\n * Unique identifier for this deployment.\n */\n id: string;\n\n /**\n * A resolved agent reference with a concrete version.\n */\n agent: AgentsAPI.BetaManagedAgentsAgentReference;\n\n /**\n * A timestamp in RFC 3339 format\n */\n archived_at: string | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n /**\n * Description of what the deployment does.\n */\n description: string | null;\n\n /**\n * ID of the `environment` where sessions run.\n */\n environment_id: string;\n\n /**\n * Events sent to each session immediately after creation.\n */\n initial_events: Array<BetaManagedAgentsDeploymentInitialEvent>;\n\n /**\n * Arbitrary key-value metadata. Maximum 16 pairs.\n */\n metadata: { [key: string]: string };\n\n /**\n * Human-readable name.\n */\n name: string;\n\n /**\n * Why a deployment is paused. Non-null exactly when `status` is `paused`.\n */\n paused_reason: BetaManagedAgentsDeploymentPausedReason | null;\n\n /**\n * Resources attached to sessions created from this deployment. Echoes the input\n * minus write-only credentials.\n */\n resources: Array<BetaManagedAgentsSessionResourceConfig>;\n\n /**\n * 5-field POSIX cron schedule with computed runtime timestamps.\n */\n schedule: BetaManagedAgentsSchedule | null;\n\n /**\n * Lifecycle status of a deployment.\n */\n status: BetaManagedAgentsDeploymentStatus;\n\n type: 'deployment';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n\n /**\n * Vault IDs supplying stored credentials for sessions created from this\n * deployment.\n */\n vault_ids: Array<string>;\n}\n\n/**\n * An event sent to a session immediately after it is created. Supports\n * `user.message`, `user.define_outcome`, and `system.message`.\n */\nexport type BetaManagedAgentsDeploymentInitialEvent =\n | BetaManagedAgentsDeploymentUserMessageEvent\n | BetaManagedAgentsDeploymentUserDefineOutcomeEvent\n | BetaManagedAgentsDeploymentSystemMessageEvent;\n\n/**\n * An event sent to a session immediately after it is created. Supports\n * `user.message`, `user.define_outcome`, and `system.message`.\n */\nexport type BetaManagedAgentsDeploymentInitialEventParams =\n | EventsAPI.BetaManagedAgentsUserMessageEventParams\n | EventsAPI.BetaManagedAgentsUserDefineOutcomeEventParams\n | EventsAPI.BetaManagedAgentsSystemMessageEventParams;\n\n/**\n * Why a deployment is paused. Non-null exactly when `status` is `paused`.\n */\nexport type BetaManagedAgentsDeploymentPausedReason =\n | BetaManagedAgentsManualDeploymentPausedReason\n | BetaManagedAgentsErrorDeploymentPausedReason;\n\n/**\n * The error that triggered an auto-pause. Matches the failed run's `error.type`.\n */\nexport type BetaManagedAgentsDeploymentPausedReasonError =\n | BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError\n | BetaManagedAgentsAgentArchivedDeploymentPausedReasonError\n | BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError\n | BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError\n | BetaManagedAgentsFileNotFoundDeploymentPausedReasonError\n | BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError\n | BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError\n | BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError\n | BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError\n | BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError\n | BetaManagedAgentsVaultArchivedDeploymentPausedReasonError\n | BetaManagedAgentsUnknownDeploymentPausedReasonError\n | BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError\n | BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError;\n\n/**\n * Lifecycle status of a deployment.\n */\nexport type BetaManagedAgentsDeploymentStatus = 'active' | 'paused';\n\n/**\n * Privileged context for the accompanying turn and all subsequent turns, appended\n * to the session's system context as a `role: \"system\"` turn rather than replacing\n * the top-level system prompt.\n */\nexport interface BetaManagedAgentsDeploymentSystemMessageEvent {\n /**\n * System content blocks to append. Text-only.\n */\n content: Array<SessionsAPI.BetaManagedAgentsSystemContentBlock>;\n\n type: 'system.message';\n}\n\n/**\n * An outcome the agent should work toward. The agent begins work on receipt.\n */\nexport interface BetaManagedAgentsDeploymentUserDefineOutcomeEvent {\n /**\n * What the agent should produce. This is the task specification.\n */\n description: string;\n\n /**\n * Rubric for grading the quality of an outcome.\n */\n rubric: EventsAPI.BetaManagedAgentsFileRubric | EventsAPI.BetaManagedAgentsTextRubric;\n\n type: 'user.define_outcome';\n\n /**\n * Eval→revision cycles before giving up. Default 3, max 20.\n */\n max_iterations?: number | null;\n}\n\n/**\n * A user message sent to the session.\n */\nexport interface BetaManagedAgentsDeploymentUserMessageEvent {\n /**\n * Array of content blocks for the user message.\n */\n content: Array<\n | EventsAPI.BetaManagedAgentsTextBlock\n | EventsAPI.BetaManagedAgentsImageBlock\n | EventsAPI.BetaManagedAgentsDocumentBlock\n >;\n\n type: 'user.message';\n}\n\n/**\n * The deployment's environment was archived.\n */\nexport interface BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError {\n type: 'environment_archived_error';\n}\n\n/**\n * The deployment's environment no longer exists.\n */\nexport interface BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError {\n type: 'environment_not_found_error';\n}\n\n/**\n * A scheduled fire recorded a failed run whose error auto-pauses the deployment.\n */\nexport interface BetaManagedAgentsErrorDeploymentPausedReason {\n /**\n * The error that triggered an auto-pause. Matches the failed run's `error.type`.\n */\n error: BetaManagedAgentsDeploymentPausedReasonError;\n\n type: 'error';\n}\n\n/**\n * A file resource referenced by the deployment no longer exists.\n */\nexport interface BetaManagedAgentsFileNotFoundDeploymentPausedReasonError {\n type: 'file_not_found_error';\n}\n\n/**\n * A file mounted into each session's container.\n */\nexport interface BetaManagedAgentsFileResourceConfig {\n /**\n * ID of a previously uploaded file.\n */\n file_id: string;\n\n type: 'file';\n\n /**\n * Mount path in the container. Defaults to `/mnt/session/uploads/<file_id>`.\n */\n mount_path?: string | null;\n}\n\n/**\n * A GitHub repository mounted into each session's container. The authorization\n * token is write-only and never returned.\n */\nexport interface BetaManagedAgentsGitHubRepositoryResourceConfig {\n type: 'github_repository';\n\n /**\n * Github URL of the repository\n */\n url: string;\n\n /**\n * Branch or commit to check out. Defaults to the repository's default branch.\n */\n checkout?: SessionsAPI.BetaManagedAgentsBranchCheckout | SessionsAPI.BetaManagedAgentsCommitCheckout | null;\n\n /**\n * Mount path in the container. Defaults to `/workspace/<repo-name>`.\n */\n mount_path?: string | null;\n}\n\n/**\n * The caller invoked the pause endpoint on the deployment.\n */\nexport interface BetaManagedAgentsManualDeploymentPausedReason {\n type: 'manual';\n}\n\n/**\n * An MCP server host used by the deployment's agent is blocked by the\n * environment's network policy.\n */\nexport interface BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError {\n type: 'mcp_egress_blocked_error';\n}\n\n/**\n * A memory store referenced by the deployment is archived.\n */\nexport interface BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError {\n type: 'memory_store_archived_error';\n}\n\n/**\n * A memory store attached to each session created from this deployment.\n */\nexport interface BetaManagedAgentsMemoryStoreResourceConfig {\n /**\n * The memory store ID (memstore\\_...). Must belong to the caller's organization\n * and workspace.\n */\n memory_store_id: string;\n\n type: 'memory_store';\n\n /**\n * Access mode for an attached memory store.\n */\n access?: 'read_write' | 'read_only' | null;\n\n /**\n * Per-attachment guidance for the agent on how to use this store. Rendered into\n * the memory section of the system prompt. Max 4096 chars.\n */\n instructions?: string | null;\n}\n\n/**\n * The deployment's organization is disabled.\n */\nexport interface BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError {\n type: 'organization_disabled_error';\n}\n\n/**\n * 5-field POSIX cron schedule with computed runtime timestamps.\n */\nexport interface BetaManagedAgentsSchedule {\n /**\n * 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g.,\n * \"0 9 \\* \\* 1-5\" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean\n * Sunday. Extended cron syntax - seconds or year fields, and the special\n * characters L, W, #, and ? - is not supported, nor are predefined shortcuts\n * (@daily).\n */\n expression: string;\n\n /**\n * IANA timezone identifier (e.g., \"America/Los_Angeles\", \"UTC\").\n */\n timezone: string;\n\n type: 'cron';\n\n /**\n * A timestamp in RFC 3339 format\n */\n last_run_at?: string | null;\n\n /**\n * Up to 5 timestamps of upcoming cron occurrences. Non-empty for active and paused\n * deployments (reflects what the schedule would do if unpaused); empty once the\n * deployment is archived (`archived_at` set). Each fire is offset by a small\n * per-schedule jitter, so a run will actually start at or shortly after its listed\n * time.\n */\n upcoming_runs_at?: Array<string>;\n}\n\n/**\n * 5-field POSIX cron schedule. Literal wall-clock matching in the configured\n * timezone.\n */\nexport interface BetaManagedAgentsScheduleParams {\n /**\n * 5-field POSIX cron expression: minute hour day-of-month month day-of-week (e.g.,\n * \"0 9 \\* \\* 1-5\" for weekdays at 9am). Day-of-week is 0-7 where 0 and 7 both mean\n * Sunday. Extended cron syntax - seconds or year fields, and the special\n * characters L, W, #, and ? - is not supported, nor are predefined shortcuts\n * (@daily).\n */\n expression: string;\n\n /**\n * Required. IANA timezone identifier (e.g., \"America/Los_Angeles\", \"UTC\").\n * Validated against the IANA timezone database.\n */\n timezone: string;\n\n type: 'cron';\n}\n\n/**\n * The deployment configures resources, but its environment is self-hosted and\n * cannot mount them.\n */\nexport interface BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError {\n type: 'self_hosted_resources_unsupported_error';\n}\n\n/**\n * A configured session resource. Echoes the input minus write-only credentials.\n */\nexport type BetaManagedAgentsSessionResourceConfig =\n | BetaManagedAgentsGitHubRepositoryResourceConfig\n | BetaManagedAgentsFileResourceConfig\n | BetaManagedAgentsMemoryStoreResourceConfig;\n\n/**\n * A referenced resource no longer exists and its kind was not reported.\n */\nexport interface BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError {\n type: 'session_resource_not_found_error';\n}\n\n/**\n * A skill referenced by the deployment's agent no longer exists.\n */\nexport interface BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError {\n type: 'skill_not_found_error';\n}\n\n/**\n * An unrecognized error auto-paused the deployment. A fallback variant; matches a\n * run whose `error.type` is `unknown_error`.\n */\nexport interface BetaManagedAgentsUnknownDeploymentPausedReasonError {\n type: 'unknown_error';\n}\n\n/**\n * A vault referenced by the deployment is archived.\n */\nexport interface BetaManagedAgentsVaultArchivedDeploymentPausedReasonError {\n type: 'vault_archived_error';\n}\n\n/**\n * A vault referenced by the deployment no longer exists.\n */\nexport interface BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError {\n type: 'vault_not_found_error';\n}\n\n/**\n * The deployment's workspace was archived.\n */\nexport interface BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError {\n type: 'workspace_archived_error';\n}\n\nexport interface DeploymentCreateParams {\n /**\n * Body param: Agent to deploy. Accepts the `agent` ID string, which pins the\n * latest version, or an `agent` object with both id and version specified. The\n * agent must exist and not be archived.\n */\n agent: string | SessionsAPI.BetaManagedAgentsAgentParams;\n\n /**\n * Body param: ID of the `environment` defining the container configuration for\n * sessions created from this deployment.\n */\n environment_id: string;\n\n /**\n * Body param: Events to send to each session immediately after creation. At least\n * 1, maximum 50.\n */\n initial_events: Array<BetaManagedAgentsDeploymentInitialEventParams>;\n\n /**\n * Body param: Human-readable name for the deployment.\n */\n name: string;\n\n /**\n * Body param: Description of what the deployment does.\n */\n description?: string | null;\n\n /**\n * Body param: Arbitrary key-value metadata. Maximum 16 pairs, keys up to 64 chars,\n * values up to 512 chars.\n */\n metadata?: { [key: string]: string };\n\n /**\n * Body param: Resources (e.g. repositories, files) to mount into each session's\n * container. Maximum 500.\n */\n resources?: Array<\n | SessionsAPI.BetaManagedAgentsGitHubRepositoryResourceParams\n | SessionsAPI.BetaManagedAgentsFileResourceParams\n | SessionsAPI.BetaManagedAgentsMemoryStoreResourceParam\n >;\n\n /**\n * Body param: 5-field POSIX cron schedule. Literal wall-clock matching in the\n * configured timezone.\n */\n schedule?: BetaManagedAgentsScheduleParams | null;\n\n /**\n * Body param: Vault IDs for stored credentials the agent can use during sessions\n * created from this deployment. Maximum 50.\n */\n vault_ids?: Array<string>;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface DeploymentRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface DeploymentUpdateParams {\n /**\n * Body param: Agent to deploy. Accepts the `agent` ID string, which re-pins to the\n * latest version, or an `agent` object with both id and version specified. Omit to\n * preserve. Cannot be cleared.\n */\n agent?: string | SessionsAPI.BetaManagedAgentsAgentParams;\n\n /**\n * Body param: Description. Omit to preserve; send empty string or null to clear.\n */\n description?: string | null;\n\n /**\n * Body param: ID of the `environment` where sessions run. Omit to preserve. Cannot\n * be cleared.\n */\n environment_id?: string;\n\n /**\n * Body param: Initial events. Full replacement. Omit to preserve. Cannot be\n * cleared. At least 1, maximum 50.\n */\n initial_events?: Array<BetaManagedAgentsDeploymentInitialEventParams>;\n\n /**\n * Body param: Metadata patch. Set a key to a string to upsert it, or to null to\n * delete it. Omit the field to preserve. The stored bag is limited to 16 keys (up\n * to 64 chars each) with values up to 512 chars.\n */\n metadata?: { [key: string]: string | null } | null;\n\n /**\n * Body param: Human-readable name. Must be non-empty. Omit to preserve. Cannot be\n * cleared.\n */\n name?: string;\n\n /**\n * Body param: Session resources. Full replacement. Omit to preserve; send empty\n * array or null to clear. Maximum 500.\n */\n resources?: Array<\n | SessionsAPI.BetaManagedAgentsGitHubRepositoryResourceParams\n | SessionsAPI.BetaManagedAgentsFileResourceParams\n | SessionsAPI.BetaManagedAgentsMemoryStoreResourceParam\n > | null;\n\n /**\n * Body param: 5-field POSIX cron schedule. Literal wall-clock matching in the\n * configured timezone.\n */\n schedule?: BetaManagedAgentsScheduleParams | null;\n\n /**\n * Body param: Vault IDs. Full replacement. Omit to preserve; send empty array or\n * null to clear. Maximum 50.\n */\n vault_ids?: Array<string> | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface DeploymentListParams extends PageCursorParams {\n /**\n * Query param: Filter by agent ID.\n */\n agent_id?: string;\n\n /**\n * Query param: Return deployments created at or after this time (inclusive).\n */\n 'created_at[gte]'?: string;\n\n /**\n * Query param: Return deployments created at or before this time (inclusive).\n */\n 'created_at[lte]'?: string;\n\n /**\n * Query param: When true, includes archived deployments. Default: false (exclude\n * archived).\n */\n include_archived?: boolean;\n\n /**\n * Query param: Filter by status: active or paused. Omit for both. To include\n * archived deployments, use include_archived instead; the two cannot be combined.\n */\n status?: BetaManagedAgentsDeploymentStatus;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface DeploymentArchiveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface DeploymentPauseParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface DeploymentRunParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface DeploymentUnpauseParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Deployments {\n export {\n type BetaManagedAgentsAgentArchivedDeploymentPausedReasonError as BetaManagedAgentsAgentArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsCronSchedule as BetaManagedAgentsCronSchedule,\n type BetaManagedAgentsCronScheduleParams as BetaManagedAgentsCronScheduleParams,\n type BetaManagedAgentsDeployment as BetaManagedAgentsDeployment,\n type BetaManagedAgentsDeploymentInitialEvent as BetaManagedAgentsDeploymentInitialEvent,\n type BetaManagedAgentsDeploymentInitialEventParams as BetaManagedAgentsDeploymentInitialEventParams,\n type BetaManagedAgentsDeploymentPausedReason as BetaManagedAgentsDeploymentPausedReason,\n type BetaManagedAgentsDeploymentPausedReasonError as BetaManagedAgentsDeploymentPausedReasonError,\n type BetaManagedAgentsDeploymentStatus as BetaManagedAgentsDeploymentStatus,\n type BetaManagedAgentsDeploymentSystemMessageEvent as BetaManagedAgentsDeploymentSystemMessageEvent,\n type BetaManagedAgentsDeploymentUserDefineOutcomeEvent as BetaManagedAgentsDeploymentUserDefineOutcomeEvent,\n type BetaManagedAgentsDeploymentUserMessageEvent as BetaManagedAgentsDeploymentUserMessageEvent,\n type BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError as BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError as BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsErrorDeploymentPausedReason as BetaManagedAgentsErrorDeploymentPausedReason,\n type BetaManagedAgentsFileNotFoundDeploymentPausedReasonError as BetaManagedAgentsFileNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsFileResourceConfig as BetaManagedAgentsFileResourceConfig,\n type BetaManagedAgentsGitHubRepositoryResourceConfig as BetaManagedAgentsGitHubRepositoryResourceConfig,\n type BetaManagedAgentsManualDeploymentPausedReason as BetaManagedAgentsManualDeploymentPausedReason,\n type BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError as BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError,\n type BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError as BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsMemoryStoreResourceConfig as BetaManagedAgentsMemoryStoreResourceConfig,\n type BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError as BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError,\n type BetaManagedAgentsSchedule as BetaManagedAgentsSchedule,\n type BetaManagedAgentsScheduleParams as BetaManagedAgentsScheduleParams,\n type BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError as BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError,\n type BetaManagedAgentsSessionResourceConfig as BetaManagedAgentsSessionResourceConfig,\n type BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError as BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError as BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsUnknownDeploymentPausedReasonError as BetaManagedAgentsUnknownDeploymentPausedReasonError,\n type BetaManagedAgentsVaultArchivedDeploymentPausedReasonError as BetaManagedAgentsVaultArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError as BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError as BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsDeploymentsPageCursor as BetaManagedAgentsDeploymentsPageCursor,\n type DeploymentCreateParams as DeploymentCreateParams,\n type DeploymentRetrieveParams as DeploymentRetrieveParams,\n type DeploymentUpdateParams as DeploymentUpdateParams,\n type DeploymentListParams as DeploymentListParams,\n type DeploymentArchiveParams as DeploymentArchiveParams,\n type DeploymentPauseParams as DeploymentPauseParams,\n type DeploymentRunParams as DeploymentRunParams,\n type DeploymentUnpauseParams as DeploymentUnpauseParams,\n };\n}\n","/**\n * Single source of truth for the `x-stainless-helper` telemetry header — the\n * key, the closed value vocabulary, and per-object helper tagging. The\n * append-don't-clobber merge for the header itself lives in\n * {@link import('../internal/headers').buildHeaders} via `APPEND_HEADERS`.\n */\n\n/**\n * Telemetry header naming the SDK helper(s) a request came from. Always this\n * lowercase form; `buildHeaders` matches it case-insensitively for its append\n * semantics, but a single canonical casing keeps every call site greppable.\n */\nexport const STAINLESS_HELPER_HEADER = 'x-stainless-helper';\n\n/** Telemetry header naming the SDK method (e.g. `stream`) in use. */\nexport const STAINLESS_HELPER_METHOD_HEADER = 'x-stainless-helper-method';\n\n/**\n * The closed set of helper telemetry tags, shared verbatim across SDKs. A\n * typo at any call site is a type error rather than silently mistagged\n * telemetry. Existing values keep their original spellings — telemetry\n * consumers match on them, so renames lose history. New tags are hyphenated\n * lowercase.\n */\nexport type StainlessHelperHeaderValue =\n | 'BetaToolRunner'\n | 'betaZodTool'\n | 'compaction'\n | 'environments-work-poller'\n | 'environments-worker'\n | 'fallback-refusal-middleware'\n | 'mcpContent'\n | 'mcpMessage'\n | 'mcpResourceToContent'\n | 'mcpResourceToFile'\n | 'mcpTool'\n | 'session-tool-runner';\n\n/**\n * The `{ 'x-stainless-helper': value }` header dict, for passing into\n * `buildHeaders` (which comma-appends `x-stainless-helper` across sources)\n * or as `defaultHeaders`/per-request `headers`.\n */\nexport function helperHeader(value: StainlessHelperHeaderValue): { [STAINLESS_HELPER_HEADER]: string } {\n return { [STAINLESS_HELPER_HEADER]: value };\n}\n\n/**\n * Symbol used to mark objects created by SDK helpers for tracking.\n * The value is the helper name (e.g., 'mcpTool', 'betaZodTool').\n */\nexport const SDK_HELPER_SYMBOL = Symbol('anthropic.sdk.stainlessHelper');\n\ntype StainlessHelperObject = { [SDK_HELPER_SYMBOL]: string };\n\nexport function wasCreatedByStainlessHelper(value: unknown): value is StainlessHelperObject {\n return typeof value === 'object' && value !== null && SDK_HELPER_SYMBOL in value;\n}\n\n/**\n * Collects helper names from tools and messages arrays.\n * Returns a deduplicated array of helper names found.\n */\nexport function collectStainlessHelpers(\n tools: readonly unknown[] | undefined,\n messages: readonly unknown[] | undefined,\n): string[] {\n const helpers = new Set<string>();\n\n // Collect from tools\n if (tools) {\n for (const tool of tools) {\n if (wasCreatedByStainlessHelper(tool)) {\n helpers.add(tool[SDK_HELPER_SYMBOL]);\n }\n }\n }\n\n // Collect from messages and their content blocks\n if (messages) {\n for (const message of messages) {\n if (wasCreatedByStainlessHelper(message)) {\n helpers.add(message[SDK_HELPER_SYMBOL]);\n }\n\n const content = (message as { content?: unknown }).content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (wasCreatedByStainlessHelper(block)) {\n helpers.add(block[SDK_HELPER_SYMBOL]);\n }\n }\n }\n }\n }\n\n return Array.from(helpers);\n}\n\n/**\n * Builds x-stainless-helper header value from tools and messages.\n * Returns an empty object if no helpers are found.\n */\nexport function stainlessHelperHeader(\n tools: readonly unknown[] | undefined,\n messages: readonly unknown[] | undefined,\n): { 'x-stainless-helper'?: string } {\n const helpers = collectStainlessHelpers(tools, messages);\n if (helpers.length === 0) return {};\n return { [STAINLESS_HELPER_HEADER]: helpers.join(', ') };\n}\n\n/**\n * Builds x-stainless-helper header value from a file object.\n * Returns an empty object if the file is not marked with a helper.\n */\nexport function stainlessHelperHeaderFromFile(file: unknown): { 'x-stainless-helper'?: string } {\n if (wasCreatedByStainlessHelper(file)) {\n return { [STAINLESS_HELPER_HEADER]: file[SDK_HELPER_SYMBOL] };\n }\n return {};\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport * as BetaAPI from './beta';\nimport { APIPromise } from '../../core/api-promise';\nimport { Page, type PageParams, PagePromise } from '../../core/pagination';\nimport { type Uploadable } from '../../core/uploads';\nimport { buildHeaders } from '../../internal/headers';\nimport { RequestOptions } from '../../internal/request-options';\nimport { stainlessHelperHeaderFromFile } from '../../internal/stainless-helper-header';\nimport { multipartFormRequestOptions } from '../../internal/uploads';\nimport { path } from '../../internal/utils/path';\n\nexport class Files extends APIResource {\n /**\n * List Files\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const fileMetadata of client.beta.files.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: FileListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<FileMetadataPage, FileMetadata> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/files?beta=true', Page<FileMetadata>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Delete File\n *\n * @example\n * ```ts\n * const deletedFile = await client.beta.files.delete(\n * 'file_id',\n * );\n * ```\n */\n delete(\n fileID: string,\n params: FileDeleteParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<DeletedFile> {\n const { betas } = params ?? {};\n return this._client.delete(path`/v1/files/${fileID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Download File\n *\n * @example\n * ```ts\n * const response = await client.beta.files.download(\n * 'file_id',\n * );\n *\n * const content = await response.blob();\n * console.log(content);\n * ```\n */\n download(\n fileID: string,\n params: FileDownloadParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<Response> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/files/${fileID}/content?beta=true`, {\n ...options,\n headers: buildHeaders([\n {\n 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(),\n Accept: 'application/binary',\n },\n options?.headers,\n ]),\n __binaryResponse: true,\n });\n }\n\n /**\n * Get File Metadata\n *\n * @example\n * ```ts\n * const fileMetadata =\n * await client.beta.files.retrieveMetadata('file_id');\n * ```\n */\n retrieveMetadata(\n fileID: string,\n params: FileRetrieveMetadataParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<FileMetadata> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/files/${fileID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Upload File\n *\n * @example\n * ```ts\n * const fileMetadata = await client.beta.files.upload({\n * file: fs.createReadStream('path/to/file'),\n * });\n * ```\n */\n upload(params: FileUploadParams, options?: RequestOptions): APIPromise<FileMetadata> {\n const { betas, ...body } = params;\n\n return this._client.post(\n '/v1/files?beta=true',\n multipartFormRequestOptions(\n {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },\n stainlessHelperHeaderFromFile(body.file),\n options?.headers,\n ]),\n },\n this._client,\n ),\n );\n }\n}\n\nexport type FileMetadataPage = Page<FileMetadata>;\n\nexport interface BetaFileScope {\n /**\n * The ID of the scoping resource (e.g., the session ID).\n */\n id: string;\n\n /**\n * The type of scope (e.g., `\"session\"`).\n */\n type: 'session';\n}\n\nexport interface DeletedFile {\n /**\n * ID of the deleted file.\n */\n id: string;\n\n /**\n * Deleted object type.\n *\n * For file deletion, this is always `\"file_deleted\"`.\n */\n type?: 'file_deleted';\n}\n\nexport interface FileMetadata {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing when the file was created.\n */\n created_at: string;\n\n /**\n * Original filename of the uploaded file.\n */\n filename: string;\n\n /**\n * MIME type of the file.\n */\n mime_type: string;\n\n /**\n * Size of the file in bytes.\n */\n size_bytes: number;\n\n /**\n * Object type.\n *\n * For files, this is always `\"file\"`.\n */\n type: 'file';\n\n /**\n * Whether the file can be downloaded.\n */\n downloadable?: boolean;\n\n /**\n * The scope of this file, indicating the context in which it was created (e.g., a\n * session).\n */\n scope?: BetaFileScope | null;\n}\n\nexport interface FileListParams extends PageParams {\n /**\n * Query param: Filter by scope ID. Only returns files associated with the\n * specified scope (e.g., a session ID).\n */\n scope_id?: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface FileDeleteParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface FileDownloadParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface FileRetrieveMetadataParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface FileUploadParams {\n /**\n * Body param: The file to upload\n */\n file: Uploadable;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Files {\n export {\n type BetaFileScope as BetaFileScope,\n type DeletedFile as DeletedFile,\n type FileMetadata as FileMetadata,\n type FileMetadataPage as FileMetadataPage,\n type FileListParams as FileListParams,\n type FileDeleteParams as FileDeleteParams,\n type FileDownloadParams as FileDownloadParams,\n type FileRetrieveMetadataParams as FileRetrieveMetadataParams,\n type FileUploadParams as FileUploadParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport * as BetaAPI from './beta';\nimport { APIPromise } from '../../core/api-promise';\nimport { Page, type PageParams, PagePromise } from '../../core/pagination';\nimport { buildHeaders } from '../../internal/headers';\nimport { RequestOptions } from '../../internal/request-options';\nimport { path } from '../../internal/utils/path';\n\nexport class Models extends APIResource {\n /**\n * Get a specific model.\n *\n * The Models API response can be used to determine information about a specific\n * model or resolve a model alias to a model ID.\n *\n * @example\n * ```ts\n * const betaModelInfo = await client.beta.models.retrieve(\n * 'model_id',\n * );\n * ```\n */\n retrieve(\n modelID: string,\n params: ModelRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaModelInfo> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/models/${modelID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List available models.\n *\n * The Models API response can be used to determine which models are available for\n * use in the API. More recently released models are listed first.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaModelInfo of client.beta.models.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: ModelListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaModelInfosPage, BetaModelInfo> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/models?beta=true', Page<BetaModelInfo>, {\n query,\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaModelInfosPage = Page<BetaModelInfo>;\n\n/**\n * Indicates whether a capability is supported.\n */\nexport interface BetaCapabilitySupport {\n /**\n * Whether this capability is supported by the model.\n */\n supported: boolean;\n}\n\n/**\n * Context management capability details.\n */\nexport interface BetaContextManagementCapability {\n /**\n * Indicates whether a capability is supported.\n */\n clear_thinking_20251015: BetaCapabilitySupport | null;\n\n /**\n * Indicates whether a capability is supported.\n */\n clear_tool_uses_20250919: BetaCapabilitySupport | null;\n\n /**\n * Indicates whether a capability is supported.\n */\n compact_20260112: BetaCapabilitySupport | null;\n\n /**\n * Whether this capability is supported by the model.\n */\n supported: boolean;\n}\n\n/**\n * Effort (reasoning_effort) capability details.\n */\nexport interface BetaEffortCapability {\n /**\n * Whether the model supports high effort level.\n */\n high: BetaCapabilitySupport;\n\n /**\n * Whether the model supports low effort level.\n */\n low: BetaCapabilitySupport;\n\n /**\n * Whether the model supports max effort level.\n */\n max: BetaCapabilitySupport;\n\n /**\n * Whether the model supports medium effort level.\n */\n medium: BetaCapabilitySupport;\n\n /**\n * Whether this capability is supported by the model.\n */\n supported: boolean;\n\n /**\n * Indicates whether a capability is supported.\n */\n xhigh: BetaCapabilitySupport | null;\n}\n\n/**\n * Model capability information.\n */\nexport interface BetaModelCapabilities {\n /**\n * Whether the model supports the Batch API.\n */\n batch: BetaCapabilitySupport;\n\n /**\n * Whether the model supports citation generation.\n */\n citations: BetaCapabilitySupport;\n\n /**\n * Whether the model supports code execution tools.\n */\n code_execution: BetaCapabilitySupport;\n\n /**\n * Context management support and available strategies.\n */\n context_management: BetaContextManagementCapability;\n\n /**\n * Effort (reasoning_effort) support and available levels.\n */\n effort: BetaEffortCapability;\n\n /**\n * Whether the model accepts image content blocks.\n */\n image_input: BetaCapabilitySupport;\n\n /**\n * Whether the model accepts PDF content blocks.\n */\n pdf_input: BetaCapabilitySupport;\n\n /**\n * Whether the model supports structured output / JSON mode / strict tool schemas.\n */\n structured_outputs: BetaCapabilitySupport;\n\n /**\n * Thinking capability and supported type configurations.\n */\n thinking: BetaThinkingCapability;\n}\n\nexport interface BetaModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\n\n /**\n * Model IDs this model accepts as `fallbacks[i].model` on the Messages API. An\n * empty list means the `fallbacks` parameter is not supported for this model as\n * primary.\n */\n allowed_fallback_models: Array<string> | null;\n\n /**\n * Model capability information.\n */\n capabilities: BetaModelCapabilities | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the model was released.\n * May be set to an epoch value if the release date is unknown.\n */\n created_at: string;\n\n /**\n * A human-readable name for the model.\n */\n display_name: string;\n\n /**\n * Maximum input context window size in tokens for this model.\n */\n max_input_tokens: number | null;\n\n /**\n * Maximum value for the `max_tokens` parameter when using this model.\n */\n max_tokens: number | null;\n\n /**\n * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\n}\n\n/**\n * Thinking capability details.\n */\nexport interface BetaThinkingCapability {\n /**\n * Whether this capability is supported by the model.\n */\n supported: boolean;\n\n /**\n * Supported thinking type configurations.\n */\n types: BetaThinkingTypes;\n}\n\n/**\n * Supported thinking type configurations.\n */\nexport interface BetaThinkingTypes {\n /**\n * Whether the model supports thinking with type 'adaptive' (auto).\n */\n adaptive: BetaCapabilitySupport;\n\n /**\n * Whether the model supports thinking with type 'enabled'.\n */\n enabled: BetaCapabilitySupport;\n}\n\nexport interface ModelRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface ModelListParams extends PageParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Models {\n export {\n type BetaCapabilitySupport as BetaCapabilitySupport,\n type BetaContextManagementCapability as BetaContextManagementCapability,\n type BetaEffortCapability as BetaEffortCapability,\n type BetaModelCapabilities as BetaModelCapabilities,\n type BetaModelInfo as BetaModelInfo,\n type BetaThinkingCapability as BetaThinkingCapability,\n type BetaThinkingTypes as BetaThinkingTypes,\n type BetaModelInfosPage as BetaModelInfosPage,\n type ModelRetrieveParams as ModelRetrieveParams,\n type ModelListParams as ModelListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport * as BetaAPI from './beta';\nimport { APIPromise } from '../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../core/pagination';\nimport { buildHeaders } from '../../internal/headers';\nimport { RequestOptions } from '../../internal/request-options';\nimport { path } from '../../internal/utils/path';\n\nexport class UserProfiles extends APIResource {\n /**\n * Create User Profile\n *\n * @example\n * ```ts\n * const betaUserProfile =\n * await client.beta.userProfiles.create();\n * ```\n */\n create(params: UserProfileCreateParams, options?: RequestOptions): APIPromise<BetaUserProfile> {\n const { betas, ...body } = params;\n return this._client.post('/v1/user_profiles?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'user-profiles-2026-03-24'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Get User Profile\n *\n * @example\n * ```ts\n * const betaUserProfile =\n * await client.beta.userProfiles.retrieve(\n * 'uprof_011CZkZCu8hGbp5mYRQgUmz9',\n * );\n * ```\n */\n retrieve(\n userProfileID: string,\n params: UserProfileRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaUserProfile> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/user_profiles/${userProfileID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'user-profiles-2026-03-24'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update User Profile\n *\n * @example\n * ```ts\n * const betaUserProfile =\n * await client.beta.userProfiles.update(\n * 'uprof_011CZkZCu8hGbp5mYRQgUmz9',\n * );\n * ```\n */\n update(\n userProfileID: string,\n params: UserProfileUpdateParams,\n options?: RequestOptions,\n ): APIPromise<BetaUserProfile> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/user_profiles/${userProfileID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'user-profiles-2026-03-24'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List User Profiles\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaUserProfile of client.beta.userProfiles.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: UserProfileListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaUserProfilesPageCursor, BetaUserProfile> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/user_profiles?beta=true', PageCursor<BetaUserProfile>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'user-profiles-2026-03-24'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Create Enrollment URL\n *\n * @example\n * ```ts\n * const betaUserProfileEnrollmentURL =\n * await client.beta.userProfiles.createEnrollmentURL(\n * 'uprof_011CZkZCu8hGbp5mYRQgUmz9',\n * );\n * ```\n */\n createEnrollmentURL(\n userProfileID: string,\n params: UserProfileCreateEnrollmentURLParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaUserProfileEnrollmentURL> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/user_profiles/${userProfileID}/enrollment_url?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'user-profiles-2026-03-24'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaUserProfilesPageCursor = PageCursor<BetaUserProfile>;\n\nexport interface BetaUserProfile {\n /**\n * Unique identifier for this user profile, prefixed `uprof_`.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n /**\n * Arbitrary key-value metadata. Maximum 16 pairs, keys up to 64 chars, values up\n * to 512 chars.\n */\n metadata: { [key: string]: string };\n\n /**\n * How the entity behind a user profile relates to the platform that owns the API\n * key. `external`: an individual end-user of the platform. `resold`: a company the\n * platform resells Claude access to. `internal`: the platform's own usage.\n */\n relationship: 'external' | 'resold' | 'internal';\n\n /**\n * Trust grants for this profile, keyed by grant name. Key omitted when no grant is\n * active or in flight.\n */\n trust_grants: { [key: string]: BetaUserProfileTrustGrant };\n\n /**\n * Object type. Always `user_profile`.\n */\n type: 'user_profile';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n\n /**\n * Platform's own identifier for this user. Not enforced unique.\n */\n external_id?: string | null;\n\n /**\n * Display name of the entity this profile represents. For `resold` this is the\n * resold-to company's name.\n */\n name?: string | null;\n}\n\nexport interface BetaUserProfileEnrollmentURL {\n /**\n * A timestamp in RFC 3339 format\n */\n expires_at: string;\n\n /**\n * Object type. Always `enrollment_url`.\n */\n type: 'enrollment_url';\n\n /**\n * Enrollment URL to send to the end user. Valid until `expires_at`.\n */\n url: string;\n}\n\nexport interface BetaUserProfileTrustGrant {\n /**\n * Status of the trust grant.\n */\n status: 'active' | 'pending' | 'rejected';\n}\n\nexport interface UserProfileCreateParams {\n /**\n * Body param: Platform's own identifier for this user. Not enforced unique.\n * Maximum 255 characters.\n */\n external_id?: string | null;\n\n /**\n * Body param: Free-form key-value data to attach to this user profile. Maximum 16\n * keys, with keys up to 64 characters and values up to 512 characters. Values must\n * be non-empty strings.\n */\n metadata?: { [key: string]: string };\n\n /**\n * Body param: Display name of the entity this profile represents. Required when\n * relationship is `resold` (the resold-to company's name); optional otherwise.\n * Maximum 255 characters.\n */\n name?: string | null;\n\n /**\n * Body param: How the entity behind a user profile relates to the platform that\n * owns the API key. `external`: an individual end-user of the platform. `resold`:\n * a company the platform resells Claude access to. `internal`: the platform's own\n * usage.\n */\n relationship?: 'external' | 'resold' | 'internal';\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface UserProfileRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface UserProfileUpdateParams {\n /**\n * Body param: If present, replaces the stored external_id. Omit to leave\n * unchanged. Maximum 255 characters.\n */\n external_id?: string | null;\n\n /**\n * Body param: Key-value pairs to merge into the stored metadata. Keys provided\n * overwrite existing values. To remove a key, set its value to an empty string.\n * Keys not provided are left unchanged. Maximum 16 keys, with keys up to 64\n * characters and values up to 512 characters.\n */\n metadata?: { [key: string]: string };\n\n /**\n * Body param: If present, replaces the stored name. Omit to leave unchanged.\n * Maximum 255 characters.\n */\n name?: string | null;\n\n /**\n * Body param: How the entity behind a user profile relates to the platform that\n * owns the API key. `external`: an individual end-user of the platform. `resold`:\n * a company the platform resells Claude access to. `internal`: the platform's own\n * usage.\n */\n relationship?: 'external' | 'resold' | 'internal' | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface UserProfileListParams extends PageCursorParams {\n /**\n * Query param: Query parameter for order\n */\n order?: 'asc' | 'desc';\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface UserProfileCreateEnrollmentURLParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace UserProfiles {\n export {\n type BetaUserProfile as BetaUserProfile,\n type BetaUserProfileEnrollmentURL as BetaUserProfileEnrollmentURL,\n type BetaUserProfileTrustGrant as BetaUserProfileTrustGrant,\n type BetaUserProfilesPageCursor as BetaUserProfilesPageCursor,\n type UserProfileCreateParams as UserProfileCreateParams,\n type UserProfileRetrieveParams as UserProfileRetrieveParams,\n type UserProfileUpdateParams as UserProfileUpdateParams,\n type UserProfileListParams as UserProfileListParams,\n type UserProfileCreateEnrollmentURLParams as UserProfileCreateEnrollmentURLParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport { Webhook } from 'standardwebhooks';\n\nexport class Webhooks extends APIResource {\n unwrap(\n body: string,\n { headers, key }: { headers: Record<string, string>; key?: string },\n ): UnwrapWebhookEvent {\n if (headers !== undefined) {\n const keyStr: string | null = key === undefined ? this._client.webhookKey : key;\n if (keyStr === null) throw new Error('Webhook key must not be null in order to unwrap');\n const wh = new Webhook(keyStr);\n wh.verify(body, headers);\n }\n return JSON.parse(body) as UnwrapWebhookEvent;\n }\n}\n\nexport interface BetaWebhookEvent {\n /**\n * Unique event identifier for idempotency.\n */\n id: string;\n\n /**\n * RFC 3339 timestamp when the event occurred.\n */\n created_at: string;\n\n data: BetaWebhookEventData;\n\n /**\n * Object type. Always `event` for webhook payloads.\n */\n type: 'event';\n}\n\nexport type BetaWebhookEventData =\n | BetaWebhookSessionCreatedEventData\n | BetaWebhookSessionPendingEventData\n | BetaWebhookSessionRunningEventData\n | BetaWebhookSessionIdledEventData\n | BetaWebhookSessionRequiresActionEventData\n | BetaWebhookSessionArchivedEventData\n | BetaWebhookSessionDeletedEventData\n | BetaWebhookSessionStatusRescheduledEventData\n | BetaWebhookSessionStatusRunStartedEventData\n | BetaWebhookSessionStatusIdledEventData\n | BetaWebhookSessionStatusTerminatedEventData\n | BetaWebhookSessionThreadCreatedEventData\n | BetaWebhookSessionThreadIdledEventData\n | BetaWebhookSessionThreadTerminatedEventData\n | BetaWebhookSessionOutcomeEvaluationEndedEventData\n | BetaWebhookVaultCreatedEventData\n | BetaWebhookVaultArchivedEventData\n | BetaWebhookVaultDeletedEventData\n | BetaWebhookVaultCredentialCreatedEventData\n | BetaWebhookVaultCredentialArchivedEventData\n | BetaWebhookVaultCredentialDeletedEventData\n | BetaWebhookVaultCredentialRefreshFailedEventData\n | BetaWebhookSessionUpdatedEventData;\n\nexport interface BetaWebhookSessionArchivedEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.archived';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionCreatedEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.created';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionDeletedEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.deleted';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionIdledEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.idled';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionOutcomeEvaluationEndedEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.outcome_evaluation_ended';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionPendingEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.pending';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionRequiresActionEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.requires_action';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionRunningEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.running';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionStatusIdledEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.status_idled';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionStatusRescheduledEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.status_rescheduled';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionStatusRunStartedEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.status_run_started';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionStatusTerminatedEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.status_terminated';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionThreadCreatedEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n /**\n * ID of the session thread this event refers to.\n */\n session_thread_id: string;\n\n type: 'session.thread_created';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionThreadIdledEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n /**\n * ID of the session thread this event refers to.\n */\n session_thread_id: string;\n\n type: 'session.thread_idled';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionThreadTerminatedEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n /**\n * ID of the session thread this event refers to.\n */\n session_thread_id: string;\n\n type: 'session.thread_terminated';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookSessionUpdatedEventData {\n /**\n * ID of the session that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'session.updated';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookVaultArchivedEventData {\n /**\n * ID of the vault that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'vault.archived';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookVaultCreatedEventData {\n /**\n * ID of the vault that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'vault.created';\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookVaultCredentialArchivedEventData {\n /**\n * ID of the vault credential that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'vault_credential.archived';\n\n /**\n * ID of the vault that owns this credential.\n */\n vault_id: string;\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookVaultCredentialCreatedEventData {\n /**\n * ID of the vault credential that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'vault_credential.created';\n\n /**\n * ID of the vault that owns this credential.\n */\n vault_id: string;\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookVaultCredentialDeletedEventData {\n /**\n * ID of the vault credential that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'vault_credential.deleted';\n\n /**\n * ID of the vault that owns this credential.\n */\n vault_id: string;\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookVaultCredentialRefreshFailedEventData {\n /**\n * ID of the vault credential that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'vault_credential.refresh_failed';\n\n /**\n * ID of the vault that owns this credential.\n */\n vault_id: string;\n\n workspace_id: string;\n}\n\nexport interface BetaWebhookVaultDeletedEventData {\n /**\n * ID of the vault that triggered the event.\n */\n id: string;\n\n organization_id: string;\n\n type: 'vault.deleted';\n\n workspace_id: string;\n}\n\nexport interface UnwrapWebhookEvent {\n /**\n * Unique event identifier for idempotency.\n */\n id: string;\n\n /**\n * RFC 3339 timestamp when the event occurred.\n */\n created_at: string;\n\n data: BetaWebhookEventData;\n\n /**\n * Object type. Always `event` for webhook payloads.\n */\n type: 'event';\n}\n\nexport declare namespace Webhooks {\n export {\n type BetaWebhookEvent as BetaWebhookEvent,\n type BetaWebhookEventData as BetaWebhookEventData,\n type BetaWebhookSessionArchivedEventData as BetaWebhookSessionArchivedEventData,\n type BetaWebhookSessionCreatedEventData as BetaWebhookSessionCreatedEventData,\n type BetaWebhookSessionDeletedEventData as BetaWebhookSessionDeletedEventData,\n type BetaWebhookSessionIdledEventData as BetaWebhookSessionIdledEventData,\n type BetaWebhookSessionOutcomeEvaluationEndedEventData as BetaWebhookSessionOutcomeEvaluationEndedEventData,\n type BetaWebhookSessionPendingEventData as BetaWebhookSessionPendingEventData,\n type BetaWebhookSessionRequiresActionEventData as BetaWebhookSessionRequiresActionEventData,\n type BetaWebhookSessionRunningEventData as BetaWebhookSessionRunningEventData,\n type BetaWebhookSessionStatusIdledEventData as BetaWebhookSessionStatusIdledEventData,\n type BetaWebhookSessionStatusRescheduledEventData as BetaWebhookSessionStatusRescheduledEventData,\n type BetaWebhookSessionStatusRunStartedEventData as BetaWebhookSessionStatusRunStartedEventData,\n type BetaWebhookSessionStatusTerminatedEventData as BetaWebhookSessionStatusTerminatedEventData,\n type BetaWebhookSessionThreadCreatedEventData as BetaWebhookSessionThreadCreatedEventData,\n type BetaWebhookSessionThreadIdledEventData as BetaWebhookSessionThreadIdledEventData,\n type BetaWebhookSessionThreadTerminatedEventData as BetaWebhookSessionThreadTerminatedEventData,\n type BetaWebhookSessionUpdatedEventData as BetaWebhookSessionUpdatedEventData,\n type BetaWebhookVaultArchivedEventData as BetaWebhookVaultArchivedEventData,\n type BetaWebhookVaultCreatedEventData as BetaWebhookVaultCreatedEventData,\n type BetaWebhookVaultCredentialArchivedEventData as BetaWebhookVaultCredentialArchivedEventData,\n type BetaWebhookVaultCredentialCreatedEventData as BetaWebhookVaultCredentialCreatedEventData,\n type BetaWebhookVaultCredentialDeletedEventData as BetaWebhookVaultCredentialDeletedEventData,\n type BetaWebhookVaultCredentialRefreshFailedEventData as BetaWebhookVaultCredentialRefreshFailedEventData,\n type BetaWebhookVaultDeletedEventData as BetaWebhookVaultDeletedEventData,\n type UnwrapWebhookEvent as UnwrapWebhookEvent,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as AgentsAPI from './agents';\nimport { BetaManagedAgentsAgentsPageCursor } from './agents';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class Versions extends APIResource {\n /**\n * List Agent Versions\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsAgent of client.beta.agents.versions.list(\n * 'agent_011CZkYpogX7uDKUyvBTophP',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n agentID: string,\n params: VersionListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsAgentsPageCursor, AgentsAPI.BetaManagedAgentsAgent> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n path`/v1/agents/${agentID}/versions?beta=true`,\n PageCursor<AgentsAPI.BetaManagedAgentsAgent>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n}\n\nexport interface VersionListParams extends PageCursorParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Versions {\n export { type VersionListParams as VersionListParams };\n}\n\nexport { type BetaManagedAgentsAgentsPageCursor };\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as VersionsAPI from './versions';\nimport { VersionListParams, Versions } from './versions';\nimport * as SessionsAPI from '../sessions/sessions';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class Agents extends APIResource {\n versions: VersionsAPI.Versions = new VersionsAPI.Versions(this._client);\n\n /**\n * Create Agent\n *\n * @example\n * ```ts\n * const betaManagedAgentsAgent =\n * await client.beta.agents.create({\n * model: 'claude-sonnet-4-6',\n * name: 'My First Agent',\n * });\n * ```\n */\n create(params: AgentCreateParams, options?: RequestOptions): APIPromise<BetaManagedAgentsAgent> {\n const { betas, ...body } = params;\n return this._client.post('/v1/agents?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Get Agent\n *\n * @example\n * ```ts\n * const betaManagedAgentsAgent =\n * await client.beta.agents.retrieve(\n * 'agent_011CZkYpogX7uDKUyvBTophP',\n * );\n * ```\n */\n retrieve(\n agentID: string,\n params: AgentRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsAgent> {\n const { betas, ...query } = params ?? {};\n return this._client.get(path`/v1/agents/${agentID}?beta=true`, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update Agent\n *\n * @example\n * ```ts\n * const betaManagedAgentsAgent =\n * await client.beta.agents.update(\n * 'agent_011CZkYpogX7uDKUyvBTophP',\n * { version: 1 },\n * );\n * ```\n */\n update(\n agentID: string,\n params: AgentUpdateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsAgent> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/agents/${agentID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Agents\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsAgent of client.beta.agents.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: AgentListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsAgentsPageCursor, BetaManagedAgentsAgent> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/agents?beta=true', PageCursor<BetaManagedAgentsAgent>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Archive Agent\n *\n * @example\n * ```ts\n * const betaManagedAgentsAgent =\n * await client.beta.agents.archive(\n * 'agent_011CZkYpogX7uDKUyvBTophP',\n * );\n * ```\n */\n archive(\n agentID: string,\n params: AgentArchiveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsAgent> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/agents/${agentID}/archive?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaManagedAgentsAgentsPageCursor = PageCursor<BetaManagedAgentsAgent>;\n\n/**\n * A Managed Agents `agent`.\n */\nexport interface BetaManagedAgentsAgent {\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n archived_at: string | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n description: string | null;\n\n mcp_servers: Array<BetaManagedAgentsMCPServerURLDefinition>;\n\n metadata: { [key: string]: string };\n\n /**\n * Model identifier and configuration.\n */\n model: BetaManagedAgentsModelConfig;\n\n /**\n * Resolved coordinator topology with a concrete agent roster.\n */\n multiagent: SessionsAPI.BetaManagedAgentsMultiagent | null;\n\n name: string;\n\n skills: Array<BetaManagedAgentsAnthropicSkill | BetaManagedAgentsCustomSkill>;\n\n system: string | null;\n\n tools: Array<\n BetaManagedAgentsAgentToolset20260401 | BetaManagedAgentsMCPToolset | BetaManagedAgentsCustomTool\n >;\n\n type: 'agent';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n\n /**\n * The agent's current version. Starts at 1 and increments when the agent is\n * modified.\n */\n version: number;\n}\n\n/**\n * A resolved agent reference with a concrete version.\n */\nexport interface BetaManagedAgentsAgentReference {\n id: string;\n\n type: 'agent';\n\n version: number;\n}\n\n/**\n * Configuration for a specific agent tool.\n */\nexport interface BetaManagedAgentsAgentToolConfig {\n enabled: boolean;\n\n /**\n * Built-in agent tool identifier.\n */\n name: 'bash' | 'edit' | 'read' | 'write' | 'glob' | 'grep' | 'web_fetch' | 'web_search';\n\n /**\n * Permission policy for tool execution.\n */\n permission_policy: BetaManagedAgentsAlwaysAllowPolicy | BetaManagedAgentsAlwaysAskPolicy;\n}\n\n/**\n * Configuration override for a specific tool within a toolset.\n */\nexport interface BetaManagedAgentsAgentToolConfigParams {\n /**\n * Built-in agent tool identifier.\n */\n name: 'bash' | 'edit' | 'read' | 'write' | 'glob' | 'grep' | 'web_fetch' | 'web_search';\n\n /**\n * Whether this tool is enabled and available to Claude. Overrides the\n * default_config setting.\n */\n enabled?: boolean | null;\n\n /**\n * Permission policy for tool execution.\n */\n permission_policy?: BetaManagedAgentsAlwaysAllowPolicy | BetaManagedAgentsAlwaysAskPolicy | null;\n}\n\n/**\n * Resolved default configuration for agent tools.\n */\nexport interface BetaManagedAgentsAgentToolsetDefaultConfig {\n enabled: boolean;\n\n /**\n * Permission policy for tool execution.\n */\n permission_policy: BetaManagedAgentsAlwaysAllowPolicy | BetaManagedAgentsAlwaysAskPolicy;\n}\n\n/**\n * Default configuration for all tools in a toolset.\n */\nexport interface BetaManagedAgentsAgentToolsetDefaultConfigParams {\n /**\n * Whether tools are enabled and available to Claude by default. Defaults to true\n * if not specified.\n */\n enabled?: boolean | null;\n\n /**\n * Permission policy for tool execution.\n */\n permission_policy?: BetaManagedAgentsAlwaysAllowPolicy | BetaManagedAgentsAlwaysAskPolicy | null;\n}\n\nexport interface BetaManagedAgentsAgentToolset20260401 {\n configs: Array<BetaManagedAgentsAgentToolConfig>;\n\n /**\n * Resolved default configuration for agent tools.\n */\n default_config: BetaManagedAgentsAgentToolsetDefaultConfig;\n\n type: 'agent_toolset_20260401';\n}\n\n/**\n * Input payload for the `bash` tool of the `agent_toolset_20260401` toolset. All\n * fields are optional; a normal invocation supplies `command`, while\n * `restart=true` (with no `command`) reboots the runner-side bash session.\n */\nexport interface BetaManagedAgentsAgentToolset20260401BashInput {\n /**\n * Shell command to execute. Omit only when `restart` is true.\n */\n command?: string;\n\n /**\n * When true, restart the persistent bash session instead of running a command.\n * Subsequent calls without `restart` will run against the fresh session.\n */\n restart?: boolean;\n\n /**\n * Per-call timeout in milliseconds. Defaults to the runner-wide tool timeout when\n * omitted or zero.\n */\n timeout_ms?: number;\n}\n\n/**\n * Input payload for the `edit` tool. Performs a string replacement in the named\n * file; by default `old_string` must occur exactly once.\n */\nexport interface BetaManagedAgentsAgentToolset20260401EditInput {\n /**\n * Path of the file to edit.\n */\n file_path: string;\n\n /**\n * Replacement text.\n */\n new_string: string;\n\n /**\n * Substring to find and replace.\n */\n old_string: string;\n\n /**\n * When true, replace every occurrence of `old_string` instead of requiring a\n * unique match.\n */\n replace_all?: boolean;\n}\n\n/**\n * Input payload for the `glob` tool. Returns paths matching a doublestar glob\n * pattern, newest first.\n */\nexport interface BetaManagedAgentsAgentToolset20260401GlobInput {\n /**\n * Doublestar glob pattern (e.g. `** /*.go`). Absolute patterns are only permitted\n * when the runner is configured to allow them.\n */\n pattern: string;\n\n /**\n * Optional directory root to search under. Defaults to the runner's working\n * directory.\n */\n path?: string;\n}\n\n/**\n * Input payload for the `grep` tool. Searches file contents for a regular\n * expression, returning matching lines.\n */\nexport interface BetaManagedAgentsAgentToolset20260401GrepInput {\n /**\n * Regular expression to search for.\n */\n pattern: string;\n\n /**\n * Optional directory root to search under. Defaults to the runner's working\n * directory.\n */\n path?: string;\n}\n\n/**\n * Configuration for built-in agent tools. Use this to enable or disable groups of\n * tools available to the agent.\n */\nexport interface BetaManagedAgentsAgentToolset20260401Params {\n type: 'agent_toolset_20260401';\n\n /**\n * Per-tool configuration overrides.\n */\n configs?: Array<BetaManagedAgentsAgentToolConfigParams>;\n\n /**\n * Default configuration for all tools in a toolset.\n */\n default_config?: BetaManagedAgentsAgentToolsetDefaultConfigParams | null;\n}\n\n/**\n * Input payload for the `read` tool. Reads file contents relative to the runner's\n * working directory (or absolute when the runner permits).\n */\nexport interface BetaManagedAgentsAgentToolset20260401ReadInput {\n /**\n * Path of the file to read.\n */\n file_path: string;\n\n /**\n * Optional `[start_line, end_line]` 1-indexed inclusive range. When omitted the\n * entire file is returned. `end_line` of 0 or negative means \"to end of file\".\n */\n view_range?: Array<number>;\n}\n\n/**\n * Input payload for the `write` tool. Writes (overwriting) the entire file\n * contents.\n */\nexport interface BetaManagedAgentsAgentToolset20260401WriteInput {\n /**\n * Full file contents to write.\n */\n content: string;\n\n /**\n * Path of the file to write.\n */\n file_path: string;\n}\n\n/**\n * Tool calls are automatically approved without user confirmation.\n */\nexport interface BetaManagedAgentsAlwaysAllowPolicy {\n type: 'always_allow';\n}\n\n/**\n * Tool calls require user confirmation before execution.\n */\nexport interface BetaManagedAgentsAlwaysAskPolicy {\n type: 'always_ask';\n}\n\n/**\n * A resolved Anthropic-managed skill.\n */\nexport interface BetaManagedAgentsAnthropicSkill {\n skill_id: string;\n\n type: 'anthropic';\n\n version: string;\n}\n\n/**\n * An Anthropic-managed skill.\n */\nexport interface BetaManagedAgentsAnthropicSkillParams {\n /**\n * Identifier of the Anthropic skill (e.g., \"xlsx\").\n */\n skill_id: string;\n\n type: 'anthropic';\n\n /**\n * Version to pin. Defaults to latest if omitted.\n */\n version?: string | null;\n}\n\n/**\n * A resolved user-created custom skill.\n */\nexport interface BetaManagedAgentsCustomSkill {\n skill_id: string;\n\n type: 'custom';\n\n version: string;\n}\n\n/**\n * A user-created custom skill.\n */\nexport interface BetaManagedAgentsCustomSkillParams {\n /**\n * Tagged ID of the custom skill (e.g., \"skill_01XJ5...\").\n */\n skill_id: string;\n\n type: 'custom';\n\n /**\n * Version to pin. Defaults to latest if omitted.\n */\n version?: string | null;\n}\n\n/**\n * A custom tool as returned in API responses.\n */\nexport interface BetaManagedAgentsCustomTool {\n description: string;\n\n /**\n * JSON Schema for custom tool input parameters.\n */\n input_schema: BetaManagedAgentsCustomToolInputSchema;\n\n name: string;\n\n type: 'custom';\n}\n\n/**\n * JSON Schema for custom tool input parameters.\n */\nexport interface BetaManagedAgentsCustomToolInputSchema {\n type: 'object';\n\n properties?: { [key: string]: unknown } | null;\n\n required?: Array<string> | null;\n\n [k: string]: unknown;\n}\n\n/**\n * A custom tool that is executed by the API client rather than the agent. When the\n * agent calls this tool, an `agent.custom_tool_use` event is emitted and the\n * session goes idle, waiting for the client to provide the result via a\n * `user.custom_tool_result` event.\n */\nexport interface BetaManagedAgentsCustomToolParams {\n /**\n * Description of what the tool does, shown to the agent to help it decide when to\n * use the tool. 1-1024 characters.\n */\n description: string;\n\n /**\n * JSON Schema for custom tool input parameters.\n */\n input_schema: BetaManagedAgentsCustomToolInputSchema;\n\n /**\n * Unique name for the tool. 1-128 characters; letters, digits, underscores, and\n * hyphens.\n */\n name: string;\n\n type: 'custom';\n}\n\n/**\n * URL-based MCP server connection as returned in API responses.\n */\nexport interface BetaManagedAgentsMCPServerURLDefinition {\n name: string;\n\n type: 'url';\n\n url: string;\n}\n\n/**\n * Resolved configuration for a specific MCP tool.\n */\nexport interface BetaManagedAgentsMCPToolConfig {\n enabled: boolean;\n\n name: string;\n\n /**\n * Permission policy for tool execution.\n */\n permission_policy: BetaManagedAgentsAlwaysAllowPolicy | BetaManagedAgentsAlwaysAskPolicy;\n}\n\n/**\n * Configuration override for a specific MCP tool.\n */\nexport interface BetaManagedAgentsMCPToolConfigParams {\n /**\n * Name of the MCP tool to configure. 1-128 characters.\n */\n name: string;\n\n /**\n * Whether this tool is enabled. Overrides the `default_config` setting.\n */\n enabled?: boolean | null;\n\n /**\n * Permission policy for tool execution.\n */\n permission_policy?: BetaManagedAgentsAlwaysAllowPolicy | BetaManagedAgentsAlwaysAskPolicy | null;\n}\n\nexport interface BetaManagedAgentsMCPToolset {\n configs: Array<BetaManagedAgentsMCPToolConfig>;\n\n /**\n * Resolved default configuration for all tools from an MCP server.\n */\n default_config: BetaManagedAgentsMCPToolsetDefaultConfig;\n\n mcp_server_name: string;\n\n type: 'mcp_toolset';\n}\n\n/**\n * Resolved default configuration for all tools from an MCP server.\n */\nexport interface BetaManagedAgentsMCPToolsetDefaultConfig {\n enabled: boolean;\n\n /**\n * Permission policy for tool execution.\n */\n permission_policy: BetaManagedAgentsAlwaysAllowPolicy | BetaManagedAgentsAlwaysAskPolicy;\n}\n\n/**\n * Default configuration for all tools from an MCP server.\n */\nexport interface BetaManagedAgentsMCPToolsetDefaultConfigParams {\n /**\n * Whether tools are enabled by default. Defaults to true if not specified.\n */\n enabled?: boolean | null;\n\n /**\n * Permission policy for tool execution.\n */\n permission_policy?: BetaManagedAgentsAlwaysAllowPolicy | BetaManagedAgentsAlwaysAskPolicy | null;\n}\n\n/**\n * Configuration for tools from an MCP server defined in `mcp_servers`.\n */\nexport interface BetaManagedAgentsMCPToolsetParams {\n /**\n * Name of the MCP server. Must match a server name from the mcp_servers array.\n * 1-255 characters.\n */\n mcp_server_name: string;\n\n type: 'mcp_toolset';\n\n /**\n * Per-tool configuration overrides.\n */\n configs?: Array<BetaManagedAgentsMCPToolConfigParams>;\n\n /**\n * Default configuration for all tools from an MCP server.\n */\n default_config?: BetaManagedAgentsMCPToolsetDefaultConfigParams | null;\n}\n\n/**\n * The model that will power your agent.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\nexport type BetaManagedAgentsModel =\n | 'claude-fable-5'\n | 'claude-opus-4-8'\n | 'claude-opus-4-7'\n | 'claude-opus-4-6'\n | 'claude-sonnet-4-6'\n | 'claude-haiku-4-5'\n | 'claude-haiku-4-5-20251001'\n | 'claude-opus-4-5'\n | 'claude-opus-4-5-20251101'\n | 'claude-sonnet-4-5'\n | 'claude-sonnet-4-5-20250929'\n | (string & {});\n\n/**\n * Model identifier and configuration.\n */\nexport interface BetaManagedAgentsModelConfig {\n /**\n * The model that will power your agent.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n id: BetaManagedAgentsModel;\n\n /**\n * Inference speed mode. `fast` provides significantly faster output token\n * generation at premium pricing. Not all models support `fast`; invalid\n * combinations are rejected at create time.\n */\n speed?: 'standard' | 'fast';\n}\n\n/**\n * An object that defines additional configuration control over model use\n */\nexport interface BetaManagedAgentsModelConfigParams {\n /**\n * The model that will power your agent.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n id: BetaManagedAgentsModel;\n\n /**\n * Inference speed mode. `fast` provides significantly faster output token\n * generation at premium pricing. Not all models support `fast`; invalid\n * combinations are rejected at create time.\n */\n speed?: 'standard' | 'fast' | null;\n}\n\n/**\n * Resolved coordinator topology with a concrete agent roster.\n */\nexport interface BetaManagedAgentsMultiagentCoordinator {\n /**\n * Agents the coordinator may spawn as session threads, each resolved to a specific\n * version.\n */\n agents: Array<BetaManagedAgentsAgentReference>;\n\n type: 'coordinator';\n}\n\n/**\n * A coordinator topology: the session's primary thread orchestrates work by\n * spawning session threads, each running an agent drawn from the `agents` roster.\n */\nexport interface BetaManagedAgentsMultiagentCoordinatorParams {\n /**\n * Agents the coordinator may spawn as session threads. 1–20 entries. Each entry is\n * an agent ID string, a versioned `{\"type\":\"agent\",\"id\",\"version\"}` reference, or\n * `{\"type\":\"self\"}` to allow recursive self-invocation. Entries must reference\n * distinct agents (after resolving `self` and string forms); at most one `self`.\n * Referenced agents must exist, must not be archived, and must not themselves have\n * `multiagent` set (depth limit 1).\n */\n agents: Array<SessionsAPI.BetaManagedAgentsMultiagentRosterEntryParams>;\n\n type: 'coordinator';\n}\n\n/**\n * Sentinel roster entry meaning \"the agent that owns this configuration\". Resolved\n * server-side to a concrete agent reference.\n */\nexport interface BetaManagedAgentsMultiagentSelfParams {\n type: 'self';\n}\n\n/**\n * Resolved `agent` definition for a single `session_thread`. Snapshot of the agent\n * at thread creation time. The multiagent roster is not repeated here; read it\n * from `Session.agent`.\n */\nexport interface BetaManagedAgentsSessionThreadAgent {\n id: string;\n\n description: string | null;\n\n mcp_servers: Array<BetaManagedAgentsMCPServerURLDefinition>;\n\n /**\n * Model identifier and configuration.\n */\n model: BetaManagedAgentsModelConfig;\n\n name: string;\n\n skills: Array<BetaManagedAgentsAnthropicSkill | BetaManagedAgentsCustomSkill>;\n\n system: string | null;\n\n tools: Array<\n BetaManagedAgentsAgentToolset20260401 | BetaManagedAgentsMCPToolset | BetaManagedAgentsCustomTool\n >;\n\n type: 'agent';\n\n version: number;\n}\n\n/**\n * Skill to load in the session container.\n */\nexport type BetaManagedAgentsSkillParams =\n | BetaManagedAgentsAnthropicSkillParams\n | BetaManagedAgentsCustomSkillParams;\n\n/**\n * URL-based MCP server connection.\n */\nexport interface BetaManagedAgentsURLMCPServerParams {\n /**\n * Unique name for this server, referenced by mcp_toolset configurations. 1-255\n * characters.\n */\n name: string;\n\n type: 'url';\n\n /**\n * Endpoint URL for the MCP server.\n */\n url: string;\n}\n\nexport interface AgentCreateParams {\n /**\n * Body param: Model identifier. Accepts the\n * [model string](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison),\n * e.g. `claude-opus-4-6`, or a `model_config` object for additional configuration\n * control\n */\n model: BetaManagedAgentsModel | BetaManagedAgentsModelConfigParams;\n\n /**\n * Body param: Human-readable name for the agent.\n */\n name: string;\n\n /**\n * Body param: Description of what the agent does.\n */\n description?: string | null;\n\n /**\n * Body param: MCP servers this agent connects to. Maximum 20. Names must be unique\n * within the array. Every server must be referenced by an `mcp_toolset` in\n * `tools`; unreferenced servers are rejected. See the\n * [MCP connector guide](https://platform.claude.com/docs/en/managed-agents/mcp-connector).\n */\n mcp_servers?: Array<BetaManagedAgentsURLMCPServerParams>;\n\n /**\n * Body param: Arbitrary key-value metadata. Maximum 16 pairs, keys up to 64 chars,\n * values up to 512 chars.\n */\n metadata?: { [key: string]: string };\n\n /**\n * Body param: A coordinator topology: the session's primary thread orchestrates\n * work by spawning session threads, each running an agent drawn from the `agents`\n * roster.\n */\n multiagent?: SessionsAPI.BetaManagedAgentsMultiagentParams | null;\n\n /**\n * Body param: Skills available to the agent.\n */\n skills?: Array<BetaManagedAgentsSkillParams>;\n\n /**\n * Body param: System prompt for the agent.\n */\n system?: string | null;\n\n /**\n * Body param: Tool configurations available to the agent. Maximum of 128 tools\n * across all toolsets allowed.\n */\n tools?: Array<\n | BetaManagedAgentsAgentToolset20260401Params\n | BetaManagedAgentsMCPToolsetParams\n | BetaManagedAgentsCustomToolParams\n >;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface AgentRetrieveParams {\n /**\n * Query param: Agent version. Omit for the most recent version. Must be at least 1\n * if specified.\n */\n version?: number;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface AgentUpdateParams {\n /**\n * Body param: The agent's current version, used to prevent concurrent overwrites.\n * Obtain this value from a create or retrieve response. The request fails if this\n * does not match the server's current version.\n */\n version: number;\n\n /**\n * Body param: Description. Omit to preserve; send empty string or null to clear.\n */\n description?: string | null;\n\n /**\n * Body param: MCP servers. Full replacement. Omit to preserve; send empty array or\n * `null` to clear. Names must be unique. Maximum 20. Every server must be\n * referenced by an `mcp_toolset` in the agent's resulting `tools`; unreferenced\n * servers are rejected. See the\n * [MCP connector guide](https://platform.claude.com/docs/en/managed-agents/mcp-connector).\n */\n mcp_servers?: Array<BetaManagedAgentsURLMCPServerParams> | null;\n\n /**\n * Body param: Metadata patch. Set a key to a string to upsert it, or to null to\n * delete it. Omit the field to preserve. The stored bag is limited to 16 keys (up\n * to 64 chars each) with values up to 512 chars.\n */\n metadata?: { [key: string]: string | null } | null;\n\n /**\n * Body param: Model identifier. Accepts the\n * [model string](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison),\n * e.g. `claude-opus-4-6`, or a `model_config` object for additional configuration\n * control. Omit to preserve. Cannot be cleared.\n */\n model?: BetaManagedAgentsModel | BetaManagedAgentsModelConfigParams;\n\n /**\n * Body param: A coordinator topology: the session's primary thread orchestrates\n * work by spawning session threads, each running an agent drawn from the `agents`\n * roster.\n */\n multiagent?: SessionsAPI.BetaManagedAgentsMultiagentParams | null;\n\n /**\n * Body param: Human-readable name. Must be non-empty. Omit to preserve. Cannot be\n * cleared.\n */\n name?: string;\n\n /**\n * Body param: Skills. Full replacement. Omit to preserve; send empty array or null\n * to clear.\n */\n skills?: Array<BetaManagedAgentsSkillParams> | null;\n\n /**\n * Body param: System prompt. Omit to preserve; send empty string or null to clear.\n */\n system?: string | null;\n\n /**\n * Body param: Tool configurations available to the agent. Full replacement. Omit\n * to preserve; send empty array or null to clear. Maximum of 128 tools across all\n * toolsets allowed.\n */\n tools?: Array<\n | BetaManagedAgentsAgentToolset20260401Params\n | BetaManagedAgentsMCPToolsetParams\n | BetaManagedAgentsCustomToolParams\n > | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface AgentListParams extends PageCursorParams {\n /**\n * Query param: Return agents created at or after this time (inclusive).\n */\n 'created_at[gte]'?: string;\n\n /**\n * Query param: Return agents created at or before this time (inclusive).\n */\n 'created_at[lte]'?: string;\n\n /**\n * Query param: Include archived agents in results. Defaults to false.\n */\n include_archived?: boolean;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface AgentArchiveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nAgents.Versions = Versions;\n\nexport declare namespace Agents {\n export {\n type BetaManagedAgentsAgent as BetaManagedAgentsAgent,\n type BetaManagedAgentsAgentReference as BetaManagedAgentsAgentReference,\n type BetaManagedAgentsAgentToolConfig as BetaManagedAgentsAgentToolConfig,\n type BetaManagedAgentsAgentToolConfigParams as BetaManagedAgentsAgentToolConfigParams,\n type BetaManagedAgentsAgentToolsetDefaultConfig as BetaManagedAgentsAgentToolsetDefaultConfig,\n type BetaManagedAgentsAgentToolsetDefaultConfigParams as BetaManagedAgentsAgentToolsetDefaultConfigParams,\n type BetaManagedAgentsAgentToolset20260401 as BetaManagedAgentsAgentToolset20260401,\n type BetaManagedAgentsAgentToolset20260401BashInput as BetaManagedAgentsAgentToolset20260401BashInput,\n type BetaManagedAgentsAgentToolset20260401EditInput as BetaManagedAgentsAgentToolset20260401EditInput,\n type BetaManagedAgentsAgentToolset20260401GlobInput as BetaManagedAgentsAgentToolset20260401GlobInput,\n type BetaManagedAgentsAgentToolset20260401GrepInput as BetaManagedAgentsAgentToolset20260401GrepInput,\n type BetaManagedAgentsAgentToolset20260401Params as BetaManagedAgentsAgentToolset20260401Params,\n type BetaManagedAgentsAgentToolset20260401ReadInput as BetaManagedAgentsAgentToolset20260401ReadInput,\n type BetaManagedAgentsAgentToolset20260401WriteInput as BetaManagedAgentsAgentToolset20260401WriteInput,\n type BetaManagedAgentsAlwaysAllowPolicy as BetaManagedAgentsAlwaysAllowPolicy,\n type BetaManagedAgentsAlwaysAskPolicy as BetaManagedAgentsAlwaysAskPolicy,\n type BetaManagedAgentsAnthropicSkill as BetaManagedAgentsAnthropicSkill,\n type BetaManagedAgentsAnthropicSkillParams as BetaManagedAgentsAnthropicSkillParams,\n type BetaManagedAgentsCustomSkill as BetaManagedAgentsCustomSkill,\n type BetaManagedAgentsCustomSkillParams as BetaManagedAgentsCustomSkillParams,\n type BetaManagedAgentsCustomTool as BetaManagedAgentsCustomTool,\n type BetaManagedAgentsCustomToolInputSchema as BetaManagedAgentsCustomToolInputSchema,\n type BetaManagedAgentsCustomToolParams as BetaManagedAgentsCustomToolParams,\n type BetaManagedAgentsMCPServerURLDefinition as BetaManagedAgentsMCPServerURLDefinition,\n type BetaManagedAgentsMCPToolConfig as BetaManagedAgentsMCPToolConfig,\n type BetaManagedAgentsMCPToolConfigParams as BetaManagedAgentsMCPToolConfigParams,\n type BetaManagedAgentsMCPToolset as BetaManagedAgentsMCPToolset,\n type BetaManagedAgentsMCPToolsetDefaultConfig as BetaManagedAgentsMCPToolsetDefaultConfig,\n type BetaManagedAgentsMCPToolsetDefaultConfigParams as BetaManagedAgentsMCPToolsetDefaultConfigParams,\n type BetaManagedAgentsMCPToolsetParams as BetaManagedAgentsMCPToolsetParams,\n type BetaManagedAgentsModel as BetaManagedAgentsModel,\n type BetaManagedAgentsModelConfig as BetaManagedAgentsModelConfig,\n type BetaManagedAgentsModelConfigParams as BetaManagedAgentsModelConfigParams,\n type BetaManagedAgentsMultiagentCoordinator as BetaManagedAgentsMultiagentCoordinator,\n type BetaManagedAgentsMultiagentCoordinatorParams as BetaManagedAgentsMultiagentCoordinatorParams,\n type BetaManagedAgentsMultiagentSelfParams as BetaManagedAgentsMultiagentSelfParams,\n type BetaManagedAgentsSessionThreadAgent as BetaManagedAgentsSessionThreadAgent,\n type BetaManagedAgentsSkillParams as BetaManagedAgentsSkillParams,\n type BetaManagedAgentsURLMCPServerParams as BetaManagedAgentsURLMCPServerParams,\n type BetaManagedAgentsAgentsPageCursor as BetaManagedAgentsAgentsPageCursor,\n type AgentCreateParams as AgentCreateParams,\n type AgentRetrieveParams as AgentRetrieveParams,\n type AgentUpdateParams as AgentUpdateParams,\n type AgentListParams as AgentListParams,\n type AgentArchiveParams as AgentArchiveParams,\n };\n\n export { Versions as Versions, type VersionListParams as VersionListParams };\n}\n","/**\n * Chain an external {@link AbortSignal} into a local {@link AbortController}:\n * the controller aborts whenever `external` aborts (synchronously if it is\n * already aborted).\n *\n * Returns a cleanup function that detaches the listener. Callers MUST invoke it\n * on their normal teardown path — `{ once: true }` only removes the listener if\n * abort actually fires, so a long-lived `external` signal (e.g. a daemon-wide\n * signal reused across many short-lived controllers) would otherwise leak one\n * listener per controller.\n */\nexport function linkAbort(external: AbortSignal | null | undefined, controller: AbortController): () => void {\n if (!external) return () => {};\n if (external.aborted) {\n controller.abort();\n return () => {};\n }\n const onAbort = () => controller.abort();\n external.addEventListener('abort', onAbort);\n return () => external.removeEventListener('abort', onAbort);\n}\n","import { APIError } from '../../core/error';\n\n/** True when `e` is an {@link APIError} whose HTTP status equals `code`. */\nexport function isStatus(e: unknown, code: number): boolean {\n return e instanceof APIError && e.status === code;\n}\n\n/** True when `e` is an {@link APIError} with a 4xx status. */\nexport function is4xx(e: unknown): boolean {\n return e instanceof APIError && typeof e.status === 'number' && e.status >= 400 && e.status < 500;\n}\n\n/**\n * True for a 4xx that the core client's retry policy would *not* retry, i.e. a\n * permanent client error. 408 (request timeout), 409 (lock timeout) and 429\n * (rate limit) are retryable for the base client (`Anthropic.shouldRetry`), so\n * they are not treated as fatal here — keeping helper retry behaviour aligned\n * with the rest of the SDK.\n */\nexport function isFatal4xx(e: unknown): boolean {\n return is4xx(e) && !isStatus(e, 408) && !isStatus(e, 409) && !isStatus(e, 429);\n}\n\n/** Exponential backoff: `baseMs * 2 ** attempt`, clamped to `capMs`. */\nexport function backoff(attempt: number, baseMs: number, capMs: number): number {\n return Math.min(baseMs * 2 ** attempt, capMs);\n}\n\n/** Uniform random delay in the half-open interval `[lowMs, highMs)`. */\nexport function jitter(lowMs: number, highMs: number): number {\n return lowMs + Math.random() * (highMs - lowMs);\n}\n\n/**\n * Trim up to 25% off `ms` at random so a fleet of clients backing off after a\n * shared outage does not retry in lockstep — mirrors the jitter the core client\n * applies to its own retry timeout.\n */\nexport function applyJitter(ms: number): number {\n return ms * (1 - Math.random() * 0.25);\n}\n","import { AnthropicError } from '../core/error';\nimport type { Anthropic } from '../client';\nimport { buildHeaders, type HeadersLike, type NullableHeaders } from '../internal/headers';\nimport {\n STAINLESS_HELPER_HEADER,\n type StainlessHelperHeaderValue,\n} from '../internal/stainless-helper-header';\n\n/**\n * Shared util for building a runner-helper-bound sub-client.\n *\n * The work poller, the environment worker, and the session tool runner each\n * need to issue requests authenticated by a per-helper credential (a\n * self-hosted environment key, today) rather than the parent client's own\n * `X-Api-Key`, *and* tagged with their own `x-stainless-helper` telemetry\n * value. Each wants to inherit the parent's full configuration — `timeout`,\n * `maxRetries`, `fetch`, `fetchOptions`, custom `defaultHeaders`,\n * `defaultQuery` — and override only the auth + telemetry bits.\n *\n * {@link copyClientForHelper} is the one shared construction.\n */\n\ninterface ClientInternalAccess {\n _options: { defaultHeaders?: HeadersLike };\n _authState?: { extraHeaders?: Record<string, string> };\n}\n\n/**\n * Return a `withOptions()` clone of `client` set up for use *by* one of the\n * runner helpers: authenticated with `authToken` as Bearer credentials, with\n * the parent's `X-Api-Key` cleared, and tagged with the helper's\n * `x-stainless-helper` value on every outgoing request.\n *\n * The returned sub-client inherits the parent's full configuration\n * (`baseURL`, `timeout`, `maxRetries`, `fetch`, `fetchOptions`, custom\n * `defaultHeaders`, `defaultQuery`). Overrides applied:\n *\n * - `authToken: authToken` — the new credential.\n * - `apiKey: null` — the parent's `X-Api-Key` is cleared. `withOptions`\n * inherits the parent's `apiKey` by default; without this, both\n * `X-Api-Key` *and* `Authorization: Bearer …` would land on the wire.\n * `client.ts` only triggers the env-var fallback when `apiKey === undefined`,\n * so explicit `null` is honored.\n * - `credentials: undefined` — opts the clone out of any inherited\n * credentials/config/profile so the explicit bearer is the unambiguous auth.\n * - `baseURL: client.baseURL` — pins the parent's resolved host (auth override otherwise resets it).\n * - `defaultHeaders` is rebuilt as `parent._authState.extraHeaders ⊕ parent.defaultHeaders ⊕\n * {'x-stainless-helper': helper}`. `withOptions` *replaces* (does not\n * merge) `defaultHeaders`, so we merge here so any custom headers the\n * caller set on the parent client survive on the sub-client.\n */\nexport function copyClientForHelper<T extends Anthropic>(\n client: T,\n { authToken, helper }: { authToken: string; helper: StainlessHelperHeaderValue },\n): T {\n if (!authToken) {\n throw new AnthropicError(\n `copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(authToken)}`,\n );\n }\n const internal = client as unknown as ClientInternalAccess;\n const parentDefaults = internal._options.defaultHeaders;\n // Carry the parent's credential/profile headers; strip the auth ones (we re-auth below).\n const parentAuthExtraHeaders = internal._authState?.extraHeaders;\n const inheritedAuthExtraHeaders: Record<string, string> | undefined =\n parentAuthExtraHeaders ?\n Object.fromEntries(\n Object.entries(parentAuthExtraHeaders).filter(([name]) => {\n const lower = name.toLowerCase();\n return lower !== 'authorization' && lower !== 'x-api-key';\n }),\n )\n : undefined;\n const defaultHeaders: NullableHeaders = buildHeaders([\n inheritedAuthExtraHeaders,\n parentDefaults,\n { [STAINLESS_HELPER_HEADER]: helper },\n ]);\n return client.withOptions({\n apiKey: null,\n authToken,\n baseURL: client.baseURL,\n credentials: undefined,\n defaultHeaders,\n }) as T;\n}\n","import { AnthropicError } from '../../core/error';\nimport type { Anthropic } from '../../client';\nimport type { BetaSelfHostedWork } from '../../resources/beta/environments/work';\nimport { loggerFor } from '../../internal/utils/log';\nimport { sleep } from '../../internal/utils/sleep';\nimport { uuid4 } from '../../internal/utils/uuid';\nimport { linkAbort } from '../../internal/utils/abort';\nimport { buildHeaders } from '../../internal/headers';\nimport type { BetaToolRunnerRequestOptions } from '../tools/BetaToolRunner';\nimport {\n applyJitter,\n backoff as expBackoff,\n isFatal4xx,\n isStatus,\n jitter,\n} from '../../internal/utils/backoff';\nimport { copyClientForHelper } from '../helper-client';\n\nexport { is4xx, isFatal4xx, isStatus, jitter } from '../../internal/utils/backoff';\n\n// API caps block_ms at 999; rely on client-side jitter between empty polls.\nexport const POLL_BLOCK_MS = 999;\nconst POLL_BACKOFF_BASE_MS = 1000;\nconst POLL_BACKOFF_CAP_MS = 60_000;\n\nexport interface WorkPollerOptions {\n client: Anthropic;\n environmentId: string;\n /**\n * The environment key — the single credential for the self-hosted runner. It\n * authenticates the work-poll calls here and every per-session call the\n * consumer makes afterwards.\n */\n environmentKey: string;\n workerId?: string;\n /** External abort signal. Aborting it ends the iteration. */\n signal?: AbortSignal;\n /**\n * Whether the poller posts `work.stop` itself after the consumer's loop body\n * returns. Defaults to `true`. Set `false` when the consumer already owns the\n * stop (e.g. {@link EnvironmentWorker} force-stops every item) so the work\n * item is not stopped twice.\n *\n * Orthogonal to {@link WorkPollerOptions.drain}: `autoStop` is a per-item\n * lifecycle flag (does the poller `work.stop` each item), `drain` controls\n * loop termination (does the poller return when the queue is empty). They are\n * not two names for the same thing — `EnvironmentWorker.run` uses\n * `autoStop: false` with `drain` defaulting `false`.\n */\n autoStop?: boolean;\n /**\n * When `true`, the poller returns (ends iteration) as soon as the work queue\n * is empty instead of long-polling forever. Defaults to `false` (long-poll\n * until aborted). Pair with `blockMs: null` for a single non-blocking pass\n * over whatever is already queued.\n */\n drain?: boolean;\n /**\n * Block timeout in milliseconds passed through to `work.poll` — the server\n * long-polls up to this long for an item before returning empty. Defaults to\n * {@link POLL_BLOCK_MS} (the API cap, 999). Pass `null` to omit it entirely\n * for a non-blocking single poll (useful with {@link WorkPollerOptions.drain}).\n */\n blockMs?: number | null;\n /**\n * Reclaim unacknowledged work items older than this many milliseconds, passed\n * through to `work.poll`'s `reclaim_older_than_ms`. Defaults to `undefined`\n * (omitted — the server applies its own default).\n */\n reclaimOlderThanMs?: number | null;\n /**\n * Extra per-request options merged into the poll/ack/stop calls. Custom\n * `headers` (e.g. a proxy's auth/routing headers) are layered on top of the\n * environment-key auth + helper telemetry headers; the poller owns the abort\n * signal, so a `signal` here is ignored.\n */\n requestOptions?: BetaToolRunnerRequestOptions;\n}\n\n/**\n * Async-iterable that long-polls a self-hosted environment for work, ack's\n * each item, yields the {@link BetaSelfHostedWork} item, and posts `stop` after\n * the consumer's loop body returns (or when the consumer `break`s).\n *\n * @example\n * ```ts\n * for await (const work of client.beta.environments.work.poller({\n * environmentId,\n * environmentKey,\n * })) {\n * // ...service the work...\n * }\n * ```\n */\nexport class WorkPoller implements AsyncIterable<BetaSelfHostedWork> {\n readonly client: Anthropic;\n readonly environmentId: string;\n readonly environmentKey: string;\n readonly workerId: string;\n\n // Sub-client scoped to the environment key. Every poll / ack / stop call\n // is routed through this so the parent's `X-Api-Key` never lands on the\n // wire alongside the bearer credential. The helper-telemetry header is\n // attached as a default on this client; per-call plumbing is unnecessary.\n readonly #runnerClient: Anthropic;\n #consumed = false;\n readonly #controller: AbortController;\n readonly #detachExternal: () => void;\n readonly #autoStop: boolean;\n readonly #drain: boolean;\n readonly #blockMs: number | null;\n readonly #reclaimOlderThanMs: number | null;\n readonly #requestOpts: BetaToolRunnerRequestOptions | undefined;\n\n constructor(opts: WorkPollerOptions) {\n this.client = opts.client;\n this.environmentId = opts.environmentId;\n this.environmentKey = opts.environmentKey;\n this.workerId = opts.workerId ?? defaultWorkerId();\n this.#runnerClient = copyClientForHelper(opts.client, {\n authToken: opts.environmentKey,\n helper: 'environments-work-poller',\n });\n this.#autoStop = opts.autoStop ?? true;\n this.#drain = opts.drain ?? false;\n // `undefined` => default to the API cap; an explicit `null` => omit\n // `block_ms` for a non-blocking poll.\n this.#blockMs = opts.blockMs === undefined ? POLL_BLOCK_MS : opts.blockMs;\n this.#reclaimOlderThanMs = opts.reclaimOlderThanMs ?? null;\n this.#requestOpts = opts.requestOptions;\n this.#controller = new AbortController();\n this.#detachExternal = linkAbort(opts.signal, this.#controller);\n }\n\n /** Read-only view of this iterator's abort signal. */\n get signal(): AbortSignal {\n return this.#controller.signal;\n }\n\n /** Abort the iterator. The current `for await` will exit cleanly. */\n abort(): void {\n this.#controller.abort();\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<BetaSelfHostedWork> {\n if (this.#consumed) {\n throw new AnthropicError('Cannot iterate over a consumed WorkPoller');\n }\n this.#consumed = true;\n const log = loggerFor(this.client);\n log.info('poller starting', {\n component: 'work-poller',\n environment_id: this.environmentId,\n });\n\n try {\n let attempt = 0;\n while (!this.#controller.signal.aborted) {\n let work: BetaSelfHostedWork | null;\n try {\n work = await this.#runnerClient.beta.environments.work.poll(\n this.environmentId,\n {\n 'Anthropic-Worker-ID': this.workerId,\n ...(this.#blockMs !== null ? { block_ms: this.#blockMs } : {}),\n ...(this.#reclaimOlderThanMs !== null ?\n { reclaim_older_than_ms: this.#reclaimOlderThanMs }\n : {}),\n },\n { headers: buildHeaders([this.#requestOpts?.headers]), signal: this.#controller.signal },\n );\n } catch (e) {\n if (this.#controller.signal.aborted) return;\n // A bad environment key / missing environment never recovers — surface\n // it instead of spinning forever at the backoff cap.\n if (isFatal4xx(e)) {\n log.error('poll failed permanently, stopping poller', { error: String(e) });\n throw e;\n }\n // Jittered exponential backoff so a fleet of pollers doesn't retry in\n // lockstep after a shared outage.\n const wait = applyJitter(backoff(attempt));\n log.warn('poll failed, backing off', { error: String(e), backoff_ms: wait });\n attempt++;\n await sleep(wait, this.#controller.signal);\n continue;\n }\n attempt = 0;\n if (work == null) {\n // Queue empty: either return now (drain) or wait and poll again.\n if (this.#drain) return;\n await sleep(jitter(1000, 3000), this.#controller.signal);\n continue;\n }\n log.info('claimed work', {\n component: 'work-poller',\n environment_id: this.environmentId,\n work_id: work.id,\n work_type: work.data.type,\n });\n\n try {\n await this.#runnerClient.beta.environments.work.ack(\n work.id,\n { environment_id: work.environment_id },\n { headers: buildHeaders([this.#requestOpts?.headers]), signal: this.#controller.signal },\n );\n } catch (e) {\n log.error('ack failed', { work_id: work.id, error: String(e) });\n continue;\n }\n\n try {\n yield work;\n } finally {\n // Post-handler stop. Runs whether the consumer body returned\n // normally, threw, or `break`d out of the loop — unless the consumer\n // owns the stop itself (`autoStop: false`).\n if (this.#autoStop) {\n try {\n await this.#runnerClient.beta.environments.work.stop(\n work.id,\n { environment_id: work.environment_id },\n { headers: buildHeaders([this.#requestOpts?.headers]) },\n );\n } catch (e) {\n if (!isStatus(e, 409)) log.warn('stop failed', { work_id: work.id, error: String(e) });\n }\n }\n }\n }\n } finally {\n // Detach from the external signal so the consumer can drop their\n // signal reference without leaking this iterator instance.\n this.#detachExternal();\n }\n }\n}\n\n/** Exponential poll backoff: 1s, 2s, 4s … clamped to a 60s cap. */\nexport function backoff(attempt: number): number {\n return expBackoff(attempt, POLL_BACKOFF_BASE_MS, POLL_BACKOFF_CAP_MS);\n}\n\nfunction defaultWorkerId(): string {\n // The API documents the worker id as a *unique* identifier for Redis consumer\n // groups, so the fallback must be unique even when several pollers share a\n // host. Prefix with the hostname when one is exposed for readability, but rely\n // on the uuid for uniqueness.\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n const host = env?.['HOSTNAME'];\n return host ? `${host}-${uuid4()}` : uuid4();\n}\n","export type AsyncQueueResult<T> = { done: false; value: T } | { done: true; value: undefined };\n\n/**\n * Single-consumer async queue that bridges background producers to an\n * `AsyncIterator`-style reader. Producers `push()` items; the consumer awaits\n * `next()`. `close()` is idempotent and wakes any pending `next()` with\n * `done: true`. `tryShift()` synchronously drains remaining items after\n * iteration has been signalled to stop.\n */\nexport class AsyncQueue<T> {\n #items: T[] = [];\n #waiters: Array<(r: AsyncQueueResult<T>) => void> = [];\n #closed = false;\n\n /** Enqueue an item, or hand it directly to a waiting reader. Returns `false` once closed. */\n push(item: T): boolean {\n if (this.#closed) return false;\n const w = this.#waiters.shift();\n if (w) w({ done: false, value: item });\n else this.#items.push(item);\n return true;\n }\n\n /** Mark the queue done. Idempotent; wakes every pending reader with `done: true`. */\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n while (this.#waiters.length > 0) {\n const w = this.#waiters.shift()!;\n w({ done: true, value: undefined });\n }\n }\n\n /**\n * Resolve with the next item, or `done: true` once the queue is closed and\n * drained. When `signal` is supplied, aborting it resolves a pending read\n * with `done: true` (cancellation is pushed down here rather than handled by\n * an outer `Promise.race`).\n */\n next(signal?: AbortSignal): Promise<AsyncQueueResult<T>> {\n if (this.#items.length > 0) {\n return Promise.resolve({ done: false, value: this.#items.shift()! });\n }\n if (this.#closed || signal?.aborted) {\n return Promise.resolve({ done: true, value: undefined });\n }\n return new Promise<AsyncQueueResult<T>>((resolve) => {\n const waiter = (r: AsyncQueueResult<T>) => {\n signal?.removeEventListener('abort', onAbort);\n resolve(r);\n };\n const onAbort = () => {\n const idx = this.#waiters.indexOf(waiter);\n if (idx >= 0) this.#waiters.splice(idx, 1);\n resolve({ done: true, value: undefined });\n };\n this.#waiters.push(waiter);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /** Synchronously remove and return the next buffered item, or `undefined` if empty. */\n tryShift(): T | undefined {\n return this.#items.shift();\n }\n}\n","import {\n BetaMemoryTool20250818,\n BetaTool,\n BetaToolBash20241022,\n BetaToolBash20250124,\n BetaToolComputerUse20241022,\n BetaToolComputerUse20250124,\n BetaToolComputerUse20251124,\n BetaToolResultContentBlockParam,\n BetaToolTextEditor20241022,\n BetaToolTextEditor20250124,\n BetaToolTextEditor20250429,\n BetaToolTextEditor20250728,\n BetaToolUnion,\n BetaToolUseBlock,\n} from '../../resources/beta';\nimport type {\n BetaManagedAgentsAgentCustomToolUseEvent,\n BetaManagedAgentsAgentToolUseEvent,\n} from '../../resources/beta/sessions/events';\nimport { ToolError } from './ToolError';\n\nexport type Promisable<T> = T | Promise<T>;\n\n/**\n * Tool types that can be implemented on the client.\n * Excludes server-side tools like code execution, web search, and MCP toolsets.\n */\nexport type BetaClientRunnableToolType =\n | BetaTool\n | BetaMemoryTool20250818\n | BetaToolBash20241022\n | BetaToolBash20250124\n | BetaToolComputerUse20241022\n | BetaToolComputerUse20250124\n | BetaToolComputerUse20251124\n | BetaToolTextEditor20241022\n | BetaToolTextEditor20250124\n | BetaToolTextEditor20250429\n | BetaToolTextEditor20250728;\n\n/**\n * The tool-use that triggered a {@link BetaRunnableTool.run}:\n *\n * - from `client.beta.messages.toolRunner`, a Messages `tool_use` content block;\n * - from `client.beta.sessions.events.toolRunner`, the `agent.tool_use` /\n * `agent.custom_tool_use` session event.\n *\n * The shapes overlap on the common fields (`id`, `name`, `input`), so code that\n * only reads those works without narrowing; narrow on the shape (e.g. `'type' in\n * x`) when you need surface-specific properties.\n */\nexport type BetaToolUse =\n | BetaToolUseBlock\n | BetaManagedAgentsAgentToolUseEvent\n | BetaManagedAgentsAgentCustomToolUseEvent;\n\nexport type BetaToolRunContext = {\n /** The tool-use that triggered this run. See {@link BetaToolUse}. */\n toolUse: BetaToolUse;\n /**\n * @deprecated Renamed to `toolUse`. Also note that for\n * `client.beta.sessions.events.toolRunner` this is the `agent.tool_use` /\n * `agent.custom_tool_use` *event*, not a Messages content block, despite the\n * name — which is why it was renamed.\n */\n toolUseBlock: BetaToolUse;\n signal?: AbortSignal | null | undefined;\n};\n\n// this type is just an extension of BetaTool with a run and parse method\n// that will be called by `toolRunner()` helpers\nexport type BetaRunnableTool<Input = any> = BetaClientRunnableToolType & {\n run: (\n args: Input,\n context?: BetaToolRunContext,\n ) => Promisable<string | Array<BetaToolResultContentBlockParam>>;\n parse: (content: unknown) => Input;\n /**\n * Optional cleanup hook for tools that hold process-level resources (e.g. a\n * persistent shell). `SessionToolRunner` (`client.beta.sessions.events.toolRunner`)\n * calls it once when iteration ends.\n */\n close?: () => Promisable<void>;\n};\n\n/**\n * Resolve the registry key for a tool — the name the model addresses it by.\n * MCP toolsets are keyed on `mcp_server_name`; every other tool on `name`.\n * Shared so the tool-name lookup is identical across `toolRunner()` surfaces.\n */\nexport function toolName(tool: BetaToolUnion | BetaRunnableTool): string {\n return 'name' in tool ? tool.name : tool.mcp_server_name;\n}\n\n/**\n * Format a thrown value into tool-result content: a {@link ToolError} carries\n * its own structured content, anything else becomes an `Error: <message>`\n * string. Shared so every `toolRunner()` surface reports tool failures the\n * same way to the model.\n */\nexport function toolErrorContent(e: unknown): string | Array<BetaToolResultContentBlockParam> {\n return e instanceof ToolError ? e.content : `Error: ${e instanceof Error ? e.message : String(e)}`;\n}\n\n/** Outcome of {@link runRunnableTool}: the content to post back and whether it is an error. */\nexport interface RunnableToolOutcome {\n content: string | Array<BetaToolResultContentBlockParam>;\n isError: boolean;\n}\n\n/**\n * Run a {@link BetaRunnableTool} end-to-end: parse the raw input, invoke `run`,\n * and format any thrown value via {@link toolErrorContent}. Shared so the\n * parse → run → catch → format pipeline is identical across `toolRunner()`\n * surfaces.\n */\nexport async function runRunnableTool(\n tool: BetaRunnableTool,\n rawInput: unknown,\n context: BetaToolRunContext,\n): Promise<RunnableToolOutcome> {\n try {\n const input = tool.parse ? tool.parse(rawInput) : rawInput;\n const content = await tool.run(input, context);\n return { content, isError: false };\n } catch (e) {\n return { content: toolErrorContent(e), isError: true };\n }\n}\n","import { AnthropicError } from '../../core/error';\nimport type { Anthropic } from '../../client';\nimport type {\n BetaManagedAgentsAgentCustomToolUseEvent,\n BetaManagedAgentsAgentToolUseEvent,\n BetaManagedAgentsSessionEvent,\n BetaManagedAgentsStreamSessionEvents,\n BetaManagedAgentsUserCustomToolResultEventParams,\n BetaManagedAgentsUserToolResultEventParams,\n} from '../../resources/beta/sessions/events';\nimport type { BetaToolResultContentBlockParam } from '../../resources/beta';\nimport { loggerFor, type Logger } from '../../internal/utils/log';\nimport { sleep } from '../../internal/utils/sleep';\nimport { isFatal4xx } from '../../internal/utils/backoff';\nimport { linkAbort } from '../../internal/utils/abort';\nimport { AsyncQueue } from '../../internal/utils/async-queue';\nimport { buildHeaders } from '../../internal/headers';\nimport { helperHeader } from '../../internal/stainless-helper-header';\nimport type { RequestOptions } from '../../internal/request-options';\nimport { runRunnableTool, toolName, type BetaRunnableTool } from './BetaRunnableTool';\nimport type { BetaToolRunnerRequestOptions } from './BetaToolRunner';\n\n/** Beta header for the managed-agents API. */\nexport const MANAGED_AGENTS_BETA = 'managed-agents-2026-04-01';\n\nconst STREAM_BACKOFF_START_MS = 500;\nconst STREAM_BACKOFF_CAP_MS = 10_000;\nconst TOOL_TIMEOUT_MS = 120_000;\nconst DRAIN_TIMEOUT_MS = 30_000;\nconst SEND_RETRIES = 3;\n\n/** Block type accepted in a `user.tool_result` event's content — codegen'd, stays in sync with the API. */\ntype SessionContentBlock = NonNullable<BetaManagedAgentsUserToolResultEventParams['content']>[number];\n\n/**\n * A tool-call event the runner dispatches against the local registry: either a\n * builtin `agent.tool_use` (answered with `user.tool_result`) or a custom\n * `agent.custom_tool_use` (answered with `user.custom_tool_result`). Server-side\n * `agent.mcp_tool_use` calls are intentionally excluded — the runner does not\n * handle them.\n */\ntype DispatchedToolUseEvent = BetaManagedAgentsAgentToolUseEvent | BetaManagedAgentsAgentCustomToolUseEvent;\n\n/**\n * The result-event params paired with a {@link DispatchedToolUseEvent}: a\n * `user.tool_result` answers an `agent.tool_use`, a `user.custom_tool_result`\n * answers an `agent.custom_tool_use`. The two pairs must be matched exactly.\n */\ntype DispatchedToolResultParams =\n | BetaManagedAgentsUserToolResultEventParams\n | BetaManagedAgentsUserCustomToolResultEventParams;\n\nexport interface SessionToolRunnerOptions {\n client: Anthropic;\n /**\n * Tools to expose to the session, in the same {@link BetaRunnableTool} shape\n * `client.beta.messages.toolRunner` accepts. Use\n * `betaAgentToolset20260401({ workdir })` from\n * `@anthropic-ai/sdk/tools/agent-toolset/node` for the standard\n * `agent_toolset_20260401` set; filter or extend the array to customise.\n */\n tools: Array<BetaRunnableTool>;\n /**\n * Once the session goes idle with `stop_reason.type === \"end_turn\"`, the\n * runner keeps running for this many milliseconds before stopping; any new\n * event resets the countdown and it re-arms on the next `end_turn` idle.\n * Defaults to {@link DEFAULT_MAX_IDLE_MS} (60s). `0` (or negative) disables\n * it — the runner then only stops on session termination or the consumer\n * breaking out / aborting.\n */\n maxIdleMs?: number;\n /** External abort signal. Aborting it ends the iteration. */\n signal?: AbortSignal;\n /**\n * Extra per-request options merged into every call this runner issues\n * (event stream / list / send). Mirrors what `client.beta.messages.toolRunner`\n * accepts: custom `headers` (e.g. a proxy's auth/routing headers) reach the\n * poll/heartbeat/stop/stream/list/send calls. The runner always owns the abort\n * signal, so a `signal` here is ignored — pass {@link SessionToolRunnerOptions.signal}\n * to abort externally.\n */\n requestOptions?: BetaToolRunnerRequestOptions;\n}\n\n/** Default {@link SessionToolRunnerOptions.maxIdleMs}: 60 seconds. */\nexport const DEFAULT_MAX_IDLE_MS = 60_000;\n\n/**\n * Outcome of a single tool execution dispatched by {@link SessionToolRunner}.\n *\n * Yielded after the tool ran (or failed) and after the result was posted back\n * to the session as a `user.tool_result` event. Consumers can read either the\n * embedded {@link DispatchedToolCall.event} / {@link DispatchedToolCall.result}\n * blocks or the flat top-level convenience fields.\n */\nexport interface DispatchedToolCall {\n /**\n * The `agent.tool_use` or `agent.custom_tool_use` event that triggered this\n * dispatch. Read `event.input` for the raw tool input and `event.name` for the\n * tool name; `event.type` distinguishes a builtin tool call from a custom one.\n */\n readonly event: DispatchedToolUseEvent;\n /**\n * The result event posted (or attempted) back to the session for this call: a\n * `user.tool_result` for an `agent.tool_use`, a `user.custom_tool_result` for\n * an `agent.custom_tool_use`. Read `result.content` for the tool's output\n * blocks and `result.is_error` for the error flag.\n *\n * `undefined` when no result event was ever built — i.e. the tool name is\n * not one this runner owns and, under the split-client behavior, it\n * deliberately posted nothing and left the id pending for its owner.\n */\n readonly result?: DispatchedToolResultParams;\n /**\n * Flat convenience for `event.id` — the id of the tool-use event this result\n * answers (echoed back as `tool_use_id` / `custom_tool_use_id` on the result).\n */\n readonly toolUseId: string;\n /** Flat convenience for `event.name` — the dispatched tool's name. */\n readonly name: string;\n /**\n * Flat convenience for `result.is_error` — `true` when the tool threw,\n * `false` on success and for a skipped unowned call.\n */\n readonly isError: boolean;\n /**\n * Whether a result event for this call reached the session. `false` when the\n * post itself failed (typically a permanent 4xx or send-retry exhaustion)\n * and also `false` — with no `result` event ever built — for a tool name\n * this runner does not own when it deliberately posts nothing and leaves the\n * id pending for its owner (the split-client behavior).\n */\n readonly posted: boolean;\n}\n\n/** Returns true if `ev` is a `session.status_idle` with `stop_reason` `end_turn`. */\nfunction isEndTurnIdle(ev: { type?: string; stop_reason?: { type?: string } }): boolean {\n return ev.type === 'session.status_idle' && ev.stop_reason?.type === 'end_turn';\n}\n\n/**\n * The sessions-side counterpart to `client.beta.messages.toolRunner`: an\n * async-iterable that attaches to a managed-agents session, executes every\n * incoming `agent.tool_use` and `agent.custom_tool_use` event against a local\n * tool registry, posts the matching result back (`user.tool_result` for the\n * former, `user.custom_tool_result` for the latter), and yields one\n * {@link DispatchedToolCall} per completed call. Server-side `agent.mcp_tool_use`\n * calls are not dispatched. Internally drives event-stream reconnect and result\n * posting.\n *\n * Iteration ends when the session terminates (`session.status_terminated` /\n * `session.deleted`), when the consumer `break`s out of the loop or aborts the\n * supplied signal, or — once the session has gone idle with\n * `stop_reason.type === \"end_turn\"` — when `maxIdleMs` elapses with no new\n * event (any new event resets that countdown; it re-arms on the next `end_turn`\n * idle; `maxIdleMs <= 0` disables it). The `finally` branch drains any in-flight\n * tool calls and runs each tool's `close()` cleanup hook. It does *not* touch\n * the work-item lease — wrap it in an `EnvironmentWorker` if you need\n * heartbeating / force-stop.\n *\n * @example\n * ```ts\n * import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node';\n *\n * for await (const call of client.beta.sessions.events.toolRunner(work.data.id, {\n * tools: [...betaAgentToolset20260401({ workdir }), myTool],\n * })) {\n * console.log(`${call.name} -> ${call.isError ? 'error' : 'ok'}`);\n * }\n * ```\n */\nexport class SessionToolRunner implements AsyncIterable<DispatchedToolCall> {\n readonly client: Anthropic;\n readonly sessionId: string;\n readonly tools: ReadonlyArray<BetaRunnableTool>;\n readonly maxIdleMs: number;\n\n #consumed = false;\n readonly #controller: AbortController;\n readonly #detachExternal: () => void;\n readonly #requestOpts: BetaToolRunnerRequestOptions | undefined;\n readonly #toolByName: Map<string, BetaRunnableTool>;\n readonly #logger: Logger;\n readonly #seen = new Set<string>();\n readonly #answered = new Set<string>();\n readonly #results = new AsyncQueue<DispatchedToolCall>();\n #inFlightCount = 0;\n #onIdle: (() => void) | null = null;\n // When the session is idle past an `end_turn`, the pending stop timer; cleared\n // by any new event. Event-driven — there is no polling watchdog.\n #idleTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(sessionId: string, opts: SessionToolRunnerOptions) {\n this.client = opts.client;\n this.sessionId = sessionId;\n this.tools = opts.tools;\n this.maxIdleMs = opts.maxIdleMs ?? DEFAULT_MAX_IDLE_MS;\n this.#logger = loggerFor(opts.client);\n this.#toolByName = new Map(opts.tools.map((t) => [toolName(t), t]));\n this.#controller = new AbortController();\n this.#detachExternal = linkAbort(opts.signal, this.#controller);\n this.#requestOpts = opts.requestOptions;\n }\n\n /** Read-only view of this runner's abort signal. */\n get signal(): AbortSignal {\n return this.#controller.signal;\n }\n\n /** Abort the runner. Background tasks will wind down and `for await` will exit cleanly. */\n abort(): void {\n this.#controller.abort();\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<DispatchedToolCall> {\n if (this.#consumed) {\n throw new AnthropicError('Cannot iterate over a consumed SessionToolRunner');\n }\n this.#consumed = true;\n this.#logger.info('session tool runner starting', {\n component: 'session-tool-runner',\n session_id: this.sessionId,\n });\n\n // The one background promise: drives the event stream and dispatches tools.\n // Its `.catch` aborts the controller so the main loop unwinds.\n const streamPromise = this.#streamLoop().catch((e) => {\n if (!this.#controller.signal.aborted) {\n this.#logger.error('stream loop failed', { error: String(e) });\n }\n this.#controller.abort();\n });\n\n try {\n // Phase 1: yield results as they arrive. `next(signal)` resolves\n // `done: true` when the controller aborts — cancellation is handled in\n // the queue read, no outer `Promise.race` needed.\n while (true) {\n const next = await this.#results.next(this.#controller.signal);\n if (next.done) break;\n yield next.value;\n }\n\n // Phase 2: let the stream loop settle (and push any final results), then\n // drain whatever is still queued before closing.\n await streamPromise;\n let pending: DispatchedToolCall | undefined;\n while ((pending = this.#results.tryShift()) !== undefined) {\n yield pending;\n }\n } finally {\n this.#controller.abort();\n this.#disarmIdleTimer();\n // Re-await defensively in case the consumer broke out of phase 1 before\n // phase 2 ran — a no-op if it already settled.\n await streamPromise;\n try {\n await this.#drain();\n } catch (e) {\n this.#logger.warn('drain failed', { error: String(e) });\n }\n this.#results.close();\n for (const t of this.tools) {\n try {\n // `close` is typed `() => Promisable<void>`, so a single `await`\n // covers both the sync and async return.\n await t.close?.();\n } catch (e) {\n this.#logger.warn('tool.close failed', { tool: toolName(t), error: String(e) });\n }\n }\n // Detach from the external signal so the consumer can drop their signal\n // reference without leaking this iterator instance.\n this.#detachExternal();\n }\n }\n\n // ===== request options =====\n\n /**\n * Request options for every helper-issued call: the caller's `requestOptions`\n * (custom proxy headers etc.) with the helper telemetry header stamped on and\n * the runner's own abort signal forced last so it always owns cancellation.\n */\n #requestOptions(): RequestOptions {\n return {\n ...this.#requestOpts,\n headers: buildHeaders([helperHeader('session-tool-runner'), this.#requestOpts?.headers]),\n signal: this.#controller.signal,\n };\n }\n\n // ===== event stream =====\n\n async #streamLoop(): Promise<void> {\n const ctrl = this.#controller;\n let backoff = STREAM_BACKOFF_START_MS;\n while (!ctrl.signal.aborted) {\n try {\n // Establish the event stream *before* reconciling history, so an event\n // emitted in the gap between listing and attaching is buffered on the\n // stream rather than lost. `seen`/`answered` dedup any event that shows\n // up both in the reconcile pass and on the live stream.\n const stream = await this.client.beta.sessions.events.stream(\n this.sessionId,\n {},\n this.#requestOptions(),\n );\n await this.#reconcile();\n for await (const ev of stream) {\n backoff = STREAM_BACKOFF_START_MS;\n if (await this.#handleStreamEvent(ev)) return;\n }\n } catch (e) {\n // An abort throws to unwind the caller (the iterator's `streamPromise`\n // `.catch`) rather than returning early and letting it carry on.\n ctrl.signal.throwIfAborted();\n if (isFatal4xx(e)) {\n this.#logger.error('permanent stream failure, shutting down', { error: String(e) });\n ctrl.abort();\n throw e;\n }\n this.#logger.warn('stream disconnected, reconnecting', {\n error: String(e),\n backoff_ms: backoff,\n });\n }\n ctrl.signal.throwIfAborted();\n await sleep(backoff, ctrl.signal);\n backoff = Math.min(backoff * 2, STREAM_BACKOFF_CAP_MS);\n }\n }\n\n /**\n * Read full history before dispatching so a `tool_use` whose result appears\n * later in the same history is not re-executed. Runs after the live stream is\n * already attached (see {@link SessionToolRunner.#streamLoop}).\n */\n async #reconcile(): Promise<void> {\n const ctrl = this.#controller;\n const pending: DispatchedToolUseEvent[] = [];\n let lastWasEndTurn = false;\n try {\n for await (const ev of this.client.beta.sessions.events.list(\n this.sessionId,\n { limit: 1000 },\n this.#requestOptions(),\n )) {\n this.#ingestHistory(ev, pending);\n lastWasEndTurn = isEndTurnIdle(ev);\n }\n } catch (e) {\n // An abort throws to unwind the caller; a real list failure is\n // non-fatal — undo the speculative `seen` entries and let `#streamLoop`\n // carry on with the live stream.\n ctrl.signal.throwIfAborted();\n this.#logger.warn('reconcile list failed', { error: String(e) });\n // If list itself failed, undo the speculative `seen` entries so the next\n // reconcile pass (or the live stream) can pick them up. Leave the idle\n // timer untouched — the history we read may be incomplete.\n for (const ev of pending) this.#seen.delete(ev.id);\n return;\n }\n const unanswered = pending.filter((ev) => !this.#answered.has(ev.id));\n // If the most recent event in history is an `end_turn` idle and there's no\n // outstanding tool work, the session is done — arm the idle timer so the\n // runner stops even if that `end_turn` arrived during a disconnect.\n if (lastWasEndTurn && unanswered.length === 0) this.#armIdleTimer();\n else this.#disarmIdleTimer();\n for (const ev of unanswered) await this.#execute(ev);\n }\n\n #ingestHistory(ev: BetaManagedAgentsSessionEvent, pending: DispatchedToolUseEvent[]): void {\n if (ev.type === 'agent.tool_use' || ev.type === 'agent.custom_tool_use') {\n // Mark the event seen so a replay on the live stream is not dispatched\n // twice, but decide whether it still needs executing from `answered`, not\n // `seen`: a call whose result post failed is seen-but-unanswered, and must\n // be retried on the next reconcile pass rather than silently dropped.\n this.#seen.add(ev.id);\n if (!this.#answered.has(ev.id)) pending.push(ev);\n } else if (ev.type === 'user.tool_result') {\n this.#answered.add(ev.tool_use_id);\n } else if (ev.type === 'user.custom_tool_result') {\n this.#answered.add(ev.custom_tool_use_id);\n }\n }\n\n /** Returns true when the runner should exit. */\n async #handleStreamEvent(ev: BetaManagedAgentsStreamSessionEvents): Promise<boolean> {\n // Arm/disarm the idle timer: an `end_turn` idle starts the grace countdown;\n // any other event cancels it.\n if (isEndTurnIdle(ev)) this.#armIdleTimer();\n else this.#disarmIdleTimer();\n switch (ev.type) {\n case 'agent.tool_use':\n case 'agent.custom_tool_use':\n if (!this.#seen.has(ev.id)) {\n this.#seen.add(ev.id);\n await this.#execute(ev);\n }\n return false;\n case 'user.tool_result':\n this.#answered.add(ev.tool_use_id);\n return false;\n case 'user.custom_tool_result':\n this.#answered.add(ev.custom_tool_use_id);\n return false;\n case 'session.status_terminated':\n case 'session.deleted':\n this.#logger.info('session terminated', {\n component: 'session-tool-runner',\n session_id: this.sessionId,\n });\n this.#controller.abort();\n return true;\n default:\n return false;\n }\n }\n\n // ===== idle timer =====\n\n /** (Re)start the grace countdown that stops the runner after `maxIdleMs` of idle. */\n #armIdleTimer(): void {\n this.#disarmIdleTimer();\n if (this.maxIdleMs <= 0) return;\n this.#idleTimer = setTimeout(() => {\n this.#logger.info('session idle after end_turn; stopping', {\n component: 'session-tool-runner',\n session_id: this.sessionId,\n max_idle_ms: this.maxIdleMs,\n });\n this.#controller.abort();\n }, this.maxIdleMs);\n }\n\n /** Cancel a pending idle countdown, if any. */\n #disarmIdleTimer(): void {\n if (this.#idleTimer !== undefined) {\n clearTimeout(this.#idleTimer);\n this.#idleTimer = undefined;\n }\n }\n\n // ===== tool execution =====\n\n async #execute(ev: DispatchedToolUseEvent): Promise<void> {\n if (this.#answered.has(ev.id)) return;\n this.#logger.info('executing tool', {\n component: 'session-tool-runner',\n session_id: this.sessionId,\n tool: ev.name,\n tool_use_id: ev.id,\n });\n this.#inFlightCount++;\n try {\n const tool = this.#toolByName.get(ev.name);\n if (!tool) {\n // Skip (split-client partial fulfilment): a name this runner\n // is not registered for belongs to the other client servicing this\n // session (typically the customer's app backend handling custom tools).\n // Post NO result, do not mark it answered, and leave the tool_use_id\n // pending for its owner — claiming it would corrupt the conversation.\n // Still yield the call so the consumer can observe the unowned\n // dispatch; nothing was sent, so `posted`/`isError` stay false and no\n // `result` event is populated. The id stays unanswered, so reconcile\n // keeps it out of the idle/end-turn accounting and re-surfaces it after\n // a reconnect until its owner answers it.\n this.#logger.info('tool not owned by this runner; leaving the tool_use_id pending for its owner', {\n component: 'session-tool-runner',\n session_id: this.sessionId,\n tool: ev.name,\n tool_use_id: ev.id,\n });\n this.#results.push({ event: ev, toolUseId: ev.id, name: ev.name, isError: false, posted: false });\n return;\n }\n let content: string | Array<BetaToolResultContentBlockParam>;\n let isError: boolean;\n // Per-tool controller: aborts on the runner's own signal *or* the\n // per-tool timeout, so an in-flight tool stops promptly when the runner\n // is aborted instead of running until the timeout.\n const toolCtrl = new AbortController();\n const detachTool = linkAbort(this.#controller.signal, toolCtrl);\n const timer = setTimeout(() => toolCtrl.abort(), TOOL_TIMEOUT_MS);\n try {\n // Pass the source `agent.tool_use` / `agent.custom_tool_use` event\n // straight through as the run context's `toolUse` — it is a union\n // member of `BetaToolUse`, no Messages-block adapter needed.\n const outcome = await runRunnableTool(tool, ev.input, {\n toolUse: ev,\n toolUseBlock: ev,\n signal: toolCtrl.signal,\n });\n content = outcome.content;\n isError = outcome.isError;\n } finally {\n clearTimeout(timer);\n detachTool();\n }\n // Answer with the result event that matches the call kind: a\n // `user.tool_result` for an `agent.tool_use`, a `user.custom_tool_result`\n // for an `agent.custom_tool_use`. Posting the wrong one leaves the call\n // unanswered and the session stuck.\n const result = buildResultEvent(ev, isError, toSessionContent(content));\n const posted = await this.#sendResult(result, ev.id);\n this.#results.push({\n event: ev,\n result,\n toolUseId: ev.id,\n name: ev.name,\n isError,\n posted,\n });\n } finally {\n this.#inFlightCount--;\n if (this.#inFlightCount === 0) this.#onIdle?.();\n }\n }\n\n async #sendResult(result: DispatchedToolResultParams, toolUseId: string): Promise<boolean> {\n const ctrl = this.#controller;\n let lastErr: unknown;\n for (let i = 0; i < SEND_RETRIES; i++) {\n // An abort throws to unwind the caller rather than returning a\n // `posted: false` result the iterator would carry on past.\n ctrl.signal.throwIfAborted();\n try {\n await this.client.beta.sessions.events.send(\n this.sessionId,\n { events: [result] },\n this.#requestOptions(),\n );\n this.#answered.add(toolUseId);\n return true;\n } catch (e) {\n lastErr = e;\n // Only short-circuit on a permanent 4xx; 408/409/429 deserve the\n // remaining retries (aligned with the core client's retry policy).\n if (isFatal4xx(e)) break;\n // Back off only *between* attempts — never after the final one, since\n // there is no further try left to wait for.\n if (i < SEND_RETRIES - 1) await sleep((i + 1) * 1000, ctrl.signal);\n }\n }\n this.#logger.error('failed to send tool result', {\n tool_use_id: toolUseId,\n error: String(lastErr),\n });\n return false;\n }\n\n /** Wait (bounded) for in-flight tool executions to finish during teardown. */\n async #drain(): Promise<void> {\n if (this.#inFlightCount === 0) return;\n await Promise.race([new Promise<void>((r) => (this.#onIdle = r)), sleep(DRAIN_TIMEOUT_MS)]);\n this.#onIdle = null;\n if (this.#inFlightCount > 0) {\n this.#logger.warn('drain timeout exceeded');\n }\n }\n}\n\n/**\n * Build the result event that answers `ev`: a `user.tool_result` for a builtin\n * `agent.tool_use`, a `user.custom_tool_result` for a custom\n * `agent.custom_tool_use`. The two `(use, result)` pairs are distinct API event\n * types and must be matched exactly — a `user.tool_result` does not answer a\n * custom tool call.\n */\nfunction buildResultEvent(\n ev: DispatchedToolUseEvent,\n isError: boolean,\n content: SessionContentBlock[],\n): DispatchedToolResultParams {\n if (ev.type === 'agent.custom_tool_use') {\n return { type: 'user.custom_tool_result', custom_tool_use_id: ev.id, is_error: isError, content };\n }\n return { type: 'user.tool_result', tool_use_id: ev.id, is_error: isError, content };\n}\n\n// The Messages-API tool-result block union is wider than the Sessions-API\n// tool_result content union; pass through text/image/document and stringify\n// anything else so a BetaRunnableTool authored for toolRunner still works here.\nfunction toSessionContent(content: string | Array<BetaToolResultContentBlockParam>): SessionContentBlock[] {\n if (typeof content === 'string') return [{ type: 'text', text: content || '(no output)' }];\n const out = content.map((b): SessionContentBlock => {\n if (b.type === 'text') return { type: 'text', text: b.text || '(no output)' };\n if (b.type === 'image' || b.type === 'document') return b as SessionContentBlock;\n if (b.type === 'search_result') {\n // The Messages `search_result` block param maps field-for-field onto the\n // Sessions `BetaManagedAgentsSearchResultBlock`; map it explicitly rather\n // than letting it fall through to the JSON.stringify branch (which would\n // bury a structured result inside a text block). `citations` is required\n // on the Sessions side and optional on the Messages side — default the\n // flag to `false` when the producer left it unset.\n return {\n type: 'search_result',\n source: b.source,\n title: b.title,\n content: b.content.map((c) => ({ type: 'text', text: c.text })),\n citations: { enabled: b.citations?.enabled ?? false },\n };\n }\n return { type: 'text', text: JSON.stringify(b) };\n });\n return out.length > 0 ? out : [{ type: 'text', text: '(no output)' }];\n}\n","import { AnthropicError } from '../../core/error';\nimport type { Anthropic } from '../../client';\nimport type { BetaSelfHostedWork } from '../../resources/beta/environments/work';\nimport { loggerFor, type Logger } from '../../internal/utils/log';\nimport { readEnv } from '../../internal/utils/env';\nimport { sleep } from '../../internal/utils/sleep';\nimport { isFatal4xx, isStatus } from '../../internal/utils/backoff';\nimport { linkAbort } from '../../internal/utils/abort';\nimport { buildHeaders } from '../../internal/headers';\nimport type { BetaRunnableTool } from '../tools/BetaRunnableTool';\nimport type { BetaToolRunnerRequestOptions } from '../tools/BetaToolRunner';\nimport { SessionToolRunner } from '../tools/SessionToolRunner';\nimport { WorkPoller } from './poller';\nimport { copyClientForHelper } from '../helper-client';\n// `tools/agent-toolset/node` is Node-only (node:child_process, node:fs, …).\n// Only the type is imported statically (erased at build); the module's values\n// (`setupSkills`, `betaAgentToolset20260401`) are loaded lazily inside the\n// per-item handler. That keeps this file free of Node-only deps in the static\n// import graph, which is what lets `client.beta.environments.work.worker()`\n// exist as a resource method without pulling Node built-ins into the SDK core.\nimport type { AgentToolContext } from '../../tools/agent-toolset/node';\n\nconst HEARTBEAT_DEFAULT_MS = 30_000;\nconst NO_HEARTBEAT_SENTINEL = 'NO_HEARTBEAT';\n\n/**\n * Either a fixed tool array or a factory invoked once per claimed session with\n * that session's {@link AgentToolContext} — use the factory form to bind\n * `betaAgentToolset20260401` (or any tool that needs the workdir / session\n * id) to the right session.\n */\nexport type EnvironmentWorkerTools =\n | Array<BetaRunnableTool>\n | ((ctx: AgentToolContext) => Array<BetaRunnableTool>);\n\nexport interface EnvironmentWorkerOptions {\n client: Anthropic;\n /**\n * The self-hosted environment to poll for work. Required by\n * {@link EnvironmentWorker.run}; not used by {@link EnvironmentWorker.handleItem}.\n */\n environmentId?: string;\n /**\n * The environment key — the single credential for the runner. It authenticates\n * the work-poll calls and every per-session call (event stream, lease\n * heartbeat, force-stop). Required by {@link EnvironmentWorker.run}; falls back\n * to `ANTHROPIC_ENVIRONMENT_KEY` in {@link EnvironmentWorker.handleItem}.\n */\n environmentKey?: string;\n /**\n * Tools to expose to each claimed session. Defaults to\n * `betaAgentToolset20260401(ctx)` (the standard `agent_toolset_20260401` set\n * bound to the per-session {@link AgentToolContext}).\n */\n tools?: EnvironmentWorkerTools;\n /** Base directory for the per-session {@link AgentToolContext}. Defaults to `process.cwd()`. */\n workdir?: string;\n /** Forwarded to the per-session {@link AgentToolContext}. */\n unrestrictedPaths?: boolean;\n /** Forwarded to the per-session {@link AgentToolContext} (`maxFileBytes`). */\n maxFileBytes?: number | null;\n /** Forwarded to {@link SessionToolRunner} (`maxIdleMs`). */\n maxIdleMs?: number;\n /** Forwarded to the {@link WorkPoller}. */\n workerId?: string;\n /** External abort signal; aborting it ends the run. */\n signal?: AbortSignal;\n /**\n * Extra per-request options merged into every call this worker issues — the\n * work poll/ack/heartbeat/stop control-plane calls and the per-session\n * SessionToolRunner's stream/list/send. Mirrors what\n * `client.beta.messages.toolRunner` accepts: custom `headers` (e.g. a proxy's\n * auth/routing headers) reach all of them. The worker owns the abort signals,\n * so a `signal` here is ignored — use {@link EnvironmentWorkerOptions.signal}.\n */\n requestOptions?: BetaToolRunnerRequestOptions;\n}\n\n/**\n * Options for {@link EnvironmentWorker.handleItem}. Every field falls back to the\n * matching `ANTHROPIC_*` environment variable — the ones the\n * `ant worker poll --on-work` command sets for the process it spawns — when not\n * passed explicitly.\n */\nexport interface HandleItemOptions {\n /** Work item id. Falls back to `ANTHROPIC_WORK_ID`. */\n workId?: string;\n /** Self-hosted environment id. Falls back to `ANTHROPIC_ENVIRONMENT_ID`. */\n environmentId?: string;\n /** Session id. Falls back to `ANTHROPIC_SESSION_ID`. */\n sessionId?: string;\n /**\n * The environment key used to authenticate every per-session call. Resolution\n * order: this option, then the worker's own `environmentKey`, then\n * `ANTHROPIC_ENVIRONMENT_KEY`.\n */\n environmentKey?: string;\n /** External abort signal; aborting it ends the run. Defaults to the constructor's signal. */\n signal?: AbortSignal;\n}\n\n/** The fields of {@link BetaSelfHostedWork} the per-item flow reads. */\ntype ClaimedWork = Pick<BetaSelfHostedWork, 'id' | 'environment_id' | 'data'>;\n\n/**\n * The self-hosted environment runner, composed from the control-plane\n * {@link WorkPoller} and the per-session {@link SessionToolRunner}.\n *\n * For each claimed `session` work item it: builds the per-session\n * {@link AgentToolContext}, downloads the session agent's skills\n * (`setupSkills`), then runs a {@link SessionToolRunner} for the session\n * *while* heartbeating the work-item lease in parallel; on exit it force-stops\n * the work item, cleans up the downloaded skills, and loops to the next one. The\n * lease heartbeat reports `state === \"stopping\"` / a lost lease back into the run\n * by aborting the session runner.\n *\n * Use {@link EnvironmentWorker.handleItem} if you already hold a claimed work\n * item (e.g. a `worker poll --on-work` script handed one to a fresh process) and\n * just want the per-item flow without the poll loop — with no arguments it reads\n * the `ANTHROPIC_*` env vars that command sets.\n *\n * Construct it via `client.beta.environments.work.worker({ ... })` (or\n * `new EnvironmentWorker({ client, ... })` directly).\n *\n * @example\n * ```ts\n * // Long-running daemon: poll for work, serve each session, loop.\n * await client.beta.environments.work\n * .worker({ environmentId, environmentKey, workdir: '/workspace' })\n * .run(AbortSignal.timeout(60 * 60_000));\n *\n * // Already-claimed item (e.g. inside `ant worker poll --on-work ...`):\n * await client.beta.environments.work.worker({ workdir: '/workspace' }).handleItem();\n * ```\n */\nexport class EnvironmentWorker {\n readonly client: Anthropic;\n readonly environmentId: string | undefined;\n readonly environmentKey: string | undefined;\n readonly tools: EnvironmentWorkerTools | undefined;\n readonly workdir: string;\n readonly unrestrictedPaths: boolean | undefined;\n readonly maxFileBytes: number | null | undefined;\n readonly maxIdleMs: number | undefined;\n readonly workerId: string | undefined;\n readonly requestOptions: BetaToolRunnerRequestOptions | undefined;\n readonly #signal: AbortSignal | undefined;\n\n constructor(opts: EnvironmentWorkerOptions) {\n this.client = opts.client;\n this.environmentId = opts.environmentId;\n this.environmentKey = opts.environmentKey;\n this.tools = opts.tools;\n this.workdir = opts.workdir ?? process.cwd();\n this.unrestrictedPaths = opts.unrestrictedPaths;\n this.maxFileBytes = opts.maxFileBytes;\n this.maxIdleMs = opts.maxIdleMs;\n this.workerId = opts.workerId;\n this.requestOptions = opts.requestOptions;\n this.#signal = opts.signal;\n }\n\n /**\n * Poll the environment and service each claimed session until the supplied\n * signal (or the one passed to the constructor) aborts. Throws if\n * `environmentId` / `environmentKey` were not provided to the constructor.\n */\n async run(signal?: AbortSignal): Promise<void> {\n const { environmentId, environmentKey } = this;\n if (environmentId === undefined || environmentKey === undefined) {\n throw new AnthropicError(\n 'EnvironmentWorker.run: environmentId and environmentKey are required to poll for work',\n );\n }\n const externalSignal = signal ?? this.#signal;\n const poller = new WorkPoller({\n client: this.client,\n environmentId,\n environmentKey,\n ...(this.workerId !== undefined ? { workerId: this.workerId } : {}),\n ...(externalSignal ? { signal: externalSignal } : {}),\n ...(this.requestOptions !== undefined ? { requestOptions: this.requestOptions } : {}),\n // The per-item handler force-stops every work item on exit; let it be the\n // single owner of `work.stop` rather than double-posting from the poller.\n autoStop: false,\n });\n\n for await (const work of poller) {\n await this.#handleItem(work, environmentKey, poller.signal);\n }\n }\n\n /**\n * Service a single, already-claimed work item without the poll loop: build the\n * per-session {@link AgentToolContext} (workdir from this worker's options),\n * download the session agent's skills (`setupSkills`), run a\n * {@link SessionToolRunner} for the session while heartbeating the work-item\n * lease in parallel, and force-stop the work item on exit (whether the runner\n * finishes normally, throws, or the heartbeat loop signals shutdown).\n *\n * Use this when something else does the claiming — e.g. a `worker poll\n * --on-work` script that hands an already-claimed item to a fresh process. The\n * work id / environment id / session id each fall back to `ANTHROPIC_WORK_ID` /\n * `ANTHROPIC_ENVIRONMENT_ID` / `ANTHROPIC_SESSION_ID` (the env vars that\n * command sets) when not passed; the environment key resolves from this\n * option, then the worker's own `environmentKey`, then\n * `ANTHROPIC_ENVIRONMENT_KEY`. With no arguments inside that command it just\n * works. Throws a clear error naming the first of the four required values\n * still missing after resolution.\n */\n async handleItem(opts?: HandleItemOptions): Promise<void> {\n const workId = opts?.workId ?? readEnv('ANTHROPIC_WORK_ID');\n const environmentId = opts?.environmentId ?? readEnv('ANTHROPIC_ENVIRONMENT_ID');\n const sessionId = opts?.sessionId ?? readEnv('ANTHROPIC_SESSION_ID');\n const environmentKey =\n opts?.environmentKey ?? this.environmentKey ?? readEnv('ANTHROPIC_ENVIRONMENT_KEY');\n\n if (!workId) {\n throw new AnthropicError('handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID');\n }\n if (!environmentId) {\n throw new AnthropicError(\n 'handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID',\n );\n }\n if (!sessionId) {\n throw new AnthropicError('handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID');\n }\n if (!environmentKey) {\n throw new AnthropicError(\n 'handleItem: environmentKey is required — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY',\n );\n }\n\n const work: ClaimedWork = {\n id: workId,\n environment_id: environmentId,\n data: { type: 'session', id: sessionId },\n };\n await this.#handleItem(work, environmentKey, opts?.signal ?? this.#signal);\n }\n\n /**\n * The per-item body shared by {@link EnvironmentWorker.run}'s poll loop and\n * {@link EnvironmentWorker.handleItem}: run a {@link SessionToolRunner} for the\n * work item's session while heartbeating its lease, force-stopping on exit.\n * Non-session work items are ignored.\n */\n async #handleItem(\n work: ClaimedWork,\n environmentKey: string,\n externalSignal: AbortSignal | undefined,\n ): Promise<void> {\n const log = loggerFor(this.client);\n // Every per-session call — the SessionToolRunner event stream/list/send, the\n // lease heartbeat, and the work force-stop — authenticates with the\n // environment key. Scope a client to it once and thread that through.\n // `copyClientForHelper` also clears the parent's `apiKey`, so the sub-client\n // emits *only* the bearer credential on the wire (a plain\n // `withOptions({authToken})` would leave `X-Api-Key` set as well).\n const sessionClient = copyClientForHelper(this.client, {\n authToken: environmentKey,\n helper: 'environments-worker',\n });\n\n // The poller runs with `autoStop: false`, so the per-item handler is the\n // single owner of `work.stop` for every claimed item.\n const sessionId = work.data.id;\n\n const ctx: AgentToolContext = {\n workdir: this.workdir,\n client: this.client,\n sessionId,\n ...(this.unrestrictedPaths !== undefined ? { unrestrictedPaths: this.unrestrictedPaths } : {}),\n ...(this.maxFileBytes !== undefined ? { maxFileBytes: this.maxFileBytes } : {}),\n };\n // Lazily load the Node-only toolset module — see the import note at the top.\n const agentToolset = await import('../../tools/agent-toolset/node');\n let cleanupSkills: () => Promise<void> = async () => {};\n try {\n cleanupSkills = await agentToolset.setupSkills(ctx);\n } catch (e) {\n log.warn('skill setup failed', { session_id: sessionId, work_id: work.id, error: String(e) });\n }\n const tools =\n typeof this.tools === 'function' ?\n this.tools(ctx)\n : this.tools ?? agentToolset.betaAgentToolset20260401(ctx);\n\n // A per-session controller: aborts when the supplied signal aborts, when the\n // session runner finishes, or when the lease heartbeat says to stop.\n const ctrl = new AbortController();\n const detachExternal = linkAbort(externalSignal, ctrl);\n\n const heartbeatPromise = heartbeatLoop(sessionClient, work, ctrl, log, this.requestOptions).catch((e) => {\n if (!ctrl.signal.aborted) log.error('heartbeat loop failed', { work_id: work.id, error: String(e) });\n ctrl.abort();\n });\n\n try {\n const runner = new SessionToolRunner(sessionId, {\n client: sessionClient,\n tools,\n ...(this.maxIdleMs !== undefined ? { maxIdleMs: this.maxIdleMs } : {}),\n ...(this.requestOptions !== undefined ? { requestOptions: this.requestOptions } : {}),\n signal: ctrl.signal,\n });\n for await (const _ of runner) {\n // Drive the runner to completion; per-call observability is not part\n // of this composition's surface — use `SessionToolRunner` directly\n // (via `client.beta.sessions.events.toolRunner`) if you want it.\n }\n } finally {\n ctrl.abort();\n detachExternal();\n await heartbeatPromise;\n await cleanupSkills().catch((e) => {\n log.warn('skill cleanup failed', { session_id: sessionId, work_id: work.id, error: String(e) });\n });\n await forceStop(sessionClient, work, log, this.requestOptions);\n }\n }\n}\n\n/** Force-stop a claimed work item, swallowing the 409 that means it's already stopped. */\nasync function forceStop(\n client: Anthropic,\n work: Pick<BetaSelfHostedWork, 'id' | 'environment_id'>,\n log: Logger,\n requestOptions?: BetaToolRunnerRequestOptions,\n): Promise<void> {\n try {\n await client.beta.environments.work.stop(\n work.id,\n { environment_id: work.environment_id, force: true },\n // Caller's headers pass through; the helper-tag header is on the scoped\n // sub-client's default_headers via copyClientForHelper, so no per-call\n // re-stamping needed.\n { ...requestOptions, headers: buildHeaders([requestOptions?.headers]) },\n );\n } catch (e) {\n if (!isStatus(e, 409)) {\n log.error('force-stop on exit failed', { work_id: work.id, error: String(e) });\n }\n }\n}\n\n/**\n * Keep the work-item lease alive while a session is being served. Aborts `ctrl`\n * when the control plane reports the work is `stopping`/`stopped`, when the\n * lease is no longer extended, or on a permanent heartbeat failure.\n */\nasync function heartbeatLoop(\n client: Anthropic,\n work: Pick<BetaSelfHostedWork, 'id' | 'environment_id'>,\n ctrl: AbortController,\n logger: Logger,\n requestOptions?: BetaToolRunnerRequestOptions,\n): Promise<void> {\n let intervalMs = HEARTBEAT_DEFAULT_MS;\n let last = NO_HEARTBEAT_SENTINEL;\n const beat = async (): Promise<void> => {\n try {\n const resp = await client.beta.environments.work.heartbeat(\n work.id,\n { environment_id: work.environment_id, expected_last_heartbeat: last },\n { ...requestOptions, headers: buildHeaders([requestOptions?.headers]), signal: ctrl.signal },\n );\n last = resp.last_heartbeat;\n if (resp.ttl_seconds > 0) {\n intervalMs = Math.max(1_000, Math.min((resp.ttl_seconds * 1000) / 2, HEARTBEAT_DEFAULT_MS));\n }\n if (resp.state === 'stopping' || resp.state === 'stopped') {\n logger.info('heartbeat signals shutdown', { work_id: work.id, state: resp.state });\n ctrl.abort();\n }\n if (!resp.lease_extended) {\n logger.warn('lease not extended, shutting down', { work_id: work.id });\n ctrl.abort();\n }\n } catch (e) {\n // An abort throws to unwind the caller (the `heartbeatLoop(...).catch`\n // in `#handleItem`) rather than returning early.\n ctrl.signal.throwIfAborted();\n if (isFatal4xx(e)) {\n logger.error('permanent heartbeat failure', { work_id: work.id, error: String(e) });\n ctrl.abort();\n throw e;\n }\n logger.warn('transient heartbeat failure', { work_id: work.id, error: String(e) });\n }\n };\n\n await beat();\n while (!ctrl.signal.aborted) {\n await sleep(intervalMs, ctrl.signal);\n ctrl.signal.throwIfAborted();\n await beat();\n }\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport type { Anthropic } from '../../../client';\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\nimport {\n WorkPoller,\n type WorkPollerOptions as RunnerWorkPollerOptions,\n} from '../../../lib/environments/poller';\nimport {\n EnvironmentWorker,\n type EnvironmentWorkerOptions as RunnerEnvironmentWorkerOptions,\n} from '../../../lib/environments/worker';\n\nexport class Work extends APIResource {\n /**\n * Note: these endpoints are called automatically by the pre-built environment\n * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted\n * sandbox environments. They are included here as a reference; you do not need to\n * invoke them directly.\n *\n * Retrieve detailed information about a specific work item.\n *\n * @example\n * ```ts\n * const betaSelfHostedWork =\n * await client.beta.environments.work.retrieve('work_id', {\n * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * });\n * ```\n */\n retrieve(\n workID: string,\n params: WorkRetrieveParams,\n options?: RequestOptions,\n ): APIPromise<BetaSelfHostedWork> {\n const { environment_id, betas } = params;\n return this._client.get(path`/v1/environments/${environment_id}/work/${workID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Note: these endpoints are called automatically by the pre-built environment\n * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted\n * sandbox environments. They are included here as a reference; you do not need to\n * invoke them directly.\n *\n * Update work item metadata with merge semantics.\n *\n * @example\n * ```ts\n * const betaSelfHostedWork =\n * await client.beta.environments.work.update('work_id', {\n * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * metadata: { foo: 'string' },\n * });\n * ```\n */\n update(workID: string, params: WorkUpdateParams, options?: RequestOptions): APIPromise<BetaSelfHostedWork> {\n const { environment_id, betas, ...body } = params;\n return this._client.post(path`/v1/environments/${environment_id}/work/${workID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Note: these endpoints are called automatically by the pre-built environment\n * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted\n * sandbox environments. They are included here as a reference; you do not need to\n * invoke them directly.\n *\n * List work items in an environment.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaSelfHostedWork of client.beta.environments.work.list(\n * 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n environmentID: string,\n params: WorkListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaSelfHostedWorksPageCursor, BetaSelfHostedWork> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n path`/v1/environments/${environmentID}/work?beta=true`,\n PageCursor<BetaSelfHostedWork>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * Note: these endpoints are called automatically by the pre-built environment\n * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted\n * sandbox environments. They are included here as a reference; you do not need to\n * invoke them directly.\n *\n * Acknowledge receipt of a work item, transitioning it from 'queued' to 'starting'\n * and removing it from the queue.\n *\n * @example\n * ```ts\n * const betaSelfHostedWork =\n * await client.beta.environments.work.ack('work_id', {\n * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * });\n * ```\n */\n ack(workID: string, params: WorkAckParams, options?: RequestOptions): APIPromise<BetaSelfHostedWork> {\n const { environment_id, betas } = params;\n return this._client.post(path`/v1/environments/${environment_id}/work/${workID}/ack?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Note: these endpoints are called automatically by the pre-built environment\n * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted\n * sandbox environments. They are included here as a reference; you do not need to\n * invoke them directly.\n *\n * Record a heartbeat for a work item to maintain the lease.\n *\n * @example\n * ```ts\n * const betaSelfHostedWorkHeartbeatResponse =\n * await client.beta.environments.work.heartbeat('work_id', {\n * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * });\n * ```\n */\n heartbeat(\n workID: string,\n params: WorkHeartbeatParams,\n options?: RequestOptions,\n ): APIPromise<BetaSelfHostedWorkHeartbeatResponse> {\n const { environment_id, desired_ttl_seconds, expected_last_heartbeat, betas } = params;\n return this._client.post(path`/v1/environments/${environment_id}/work/${workID}/heartbeat?beta=true`, {\n query: { desired_ttl_seconds, expected_last_heartbeat },\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Note: these endpoints are called automatically by the pre-built environment\n * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted\n * sandbox environments. They are included here as a reference; you do not need to\n * invoke them directly.\n *\n * Long poll for work items in the queue.\n *\n * @example\n * ```ts\n * const betaSelfHostedWork =\n * await client.beta.environments.work.poll(\n * 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * );\n * ```\n */\n poll(\n environmentID: string,\n params: WorkPollParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaSelfHostedWork | null> {\n const { betas, 'Anthropic-Worker-ID': anthropicWorkerID, ...query } = params ?? {};\n return this._client.get(path`/v1/environments/${environmentID}/work/poll?beta=true`, {\n query,\n ...options,\n headers: buildHeaders([\n {\n 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString(),\n ...(anthropicWorkerID != null ? { 'Anthropic-Worker-ID': anthropicWorkerID } : undefined),\n },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Get statistics about the work queue for an environment.\n *\n * @example\n * ```ts\n * const betaSelfHostedWorkQueueStats =\n * await client.beta.environments.work.stats(\n * 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * );\n * ```\n */\n stats(\n environmentID: string,\n params: WorkStatsParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaSelfHostedWorkQueueStats> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/environments/${environmentID}/work/stats?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Note: these endpoints are called automatically by the pre-built environment\n * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted\n * sandbox environments. They are included here as a reference; you do not need to\n * invoke them directly.\n *\n * Stop a work item, initiating graceful or forced shutdown.\n *\n * @example\n * ```ts\n * const betaSelfHostedWork =\n * await client.beta.environments.work.stop('work_id', {\n * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * });\n * ```\n */\n stop(workID: string, params: WorkStopParams, options?: RequestOptions): APIPromise<BetaSelfHostedWork> {\n const { environment_id, betas, ...body } = params;\n return this._client.post(path`/v1/environments/${environment_id}/work/${workID}/stop?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Continuously claim work from a self-hosted environment, ack each item,\n * and yield it. Posts `stop` automatically when the consumer's loop body\n * returns or when iteration ends.\n *\n * @example\n * ```ts\n * for await (const work of client.beta.environments.work.poller({\n * environmentId,\n * environmentKey,\n * })) {\n * if (work.data.type !== 'session') continue;\n * // ...service the work...\n * }\n * ```\n */\n poller(opts: Omit<RunnerWorkPollerOptions, 'client'>): WorkPoller {\n return new WorkPoller({ ...opts, client: this._client as Anthropic });\n }\n\n /**\n * The self-hosted environment runner: poll for work, and for each claimed\n * session set up the workdir, download the agent's skills, run the tools while\n * heartbeating the lease, and force-stop on exit.\n *\n * @example\n * ```ts\n * // Long-running daemon — poll, serve each session, loop:\n * await client.beta.environments.work\n * .worker({ environmentId, environmentKey, workdir: '/workspace' })\n * .run();\n *\n * // Or service one already-claimed work item (e.g. inside a sandbox spawned\n * // by `ant worker poll --on-work`) — handleItem() reads the ANTHROPIC_* env vars:\n * await client.beta.environments.work.worker({ workdir: '/workspace' }).handleItem();\n * ```\n */\n worker(opts: Omit<RunnerEnvironmentWorkerOptions, 'client'>): EnvironmentWorker {\n return new EnvironmentWorker({ ...opts, client: this._client as Anthropic });\n }\n}\n\nexport type BetaSelfHostedWorksPageCursor = PageCursor<BetaSelfHostedWork>;\n\n/**\n * Work data for environment health checks.\n *\n * This resource type is used for assessing the health of containers where work\n * occurs. The data is opaque to users; the runner handles the health check by\n * probing connectivity to required services.\n */\nexport interface BetaHealthCheckWorkData {\n /**\n * Health check identifier\n */\n id: string;\n\n /**\n * Type of work data\n */\n type?: 'healthcheck';\n}\n\n/**\n * Work resource representing a unit of work in a self-hosted environment.\n *\n * Work items are queued when sessions are created or when long-dormant sessions\n * receive new messages. The Environment Manager polls for work items and executes\n * them on customer-hosted infrastructure.\n */\nexport interface BetaSelfHostedWork {\n /**\n * Work identifier (e.g., 'work\\_...')\n */\n id: string;\n\n /**\n * RFC 3339 timestamp when work was acknowledged by Environment Manager\n */\n acknowledged_at: string | null;\n\n /**\n * RFC 3339 timestamp when work was created\n */\n created_at: string;\n\n /**\n * The actual work to be performed (session or health check)\n */\n data: BetaSessionWorkData | BetaHealthCheckWorkData;\n\n /**\n * Environment identifier this work belongs to (e.g., `env_...`)\n */\n environment_id: string;\n\n /**\n * RFC 3339 timestamp of the most recent heartbeat\n */\n latest_heartbeat_at: string | null;\n\n /**\n * User-provided metadata key-value pairs associated with this work item\n */\n metadata: { [key: string]: string };\n\n /**\n * Session instance JWT secret (only included in certain retrieval paths)\n */\n secret: string | null;\n\n /**\n * RFC 3339 timestamp when work execution started\n */\n started_at: string | null;\n\n /**\n * Current state of the work item\n */\n state: 'queued' | 'starting' | 'active' | 'stopping' | 'stopped';\n\n /**\n * RFC 3339 timestamp when stop was requested\n */\n stop_requested_at: string | null;\n\n /**\n * RFC 3339 timestamp when work execution stopped\n */\n stopped_at: string | null;\n\n /**\n * The type of object (always 'work')\n */\n type: 'work';\n}\n\n/**\n * Response after recording a heartbeat for a work item.\n */\nexport interface BetaSelfHostedWorkHeartbeatResponse {\n /**\n * RFC 3339 timestamp of the actual heartbeat from DB\n */\n last_heartbeat: string;\n\n /**\n * Whether the heartbeat succeeded in extending the lease\n */\n lease_extended: boolean;\n\n /**\n * Current state of the work item (active/stopping/stopped)\n */\n state: 'queued' | 'starting' | 'active' | 'stopping' | 'stopped';\n\n /**\n * Effective TTL applied to the lease\n */\n ttl_seconds: number;\n\n /**\n * The type of response\n */\n type: 'work_heartbeat';\n}\n\n/**\n * Response when listing work items with cursor-based pagination.\n */\nexport interface BetaSelfHostedWorkListResponse {\n /**\n * List of work items\n */\n data: Array<BetaSelfHostedWork>;\n\n /**\n * Opaque cursor for fetching the next page of results\n */\n next_page: string | null;\n}\n\n/**\n * Statistics about the work queue for an environment.\n *\n * Uses Redis Stream consumer group metrics for O(1) queries.\n */\nexport interface BetaSelfHostedWorkQueueStats {\n /**\n * Number of work items waiting to be picked up (lag from consumer group)\n */\n depth: number;\n\n /**\n * RFC 3339 timestamp of oldest item in the work stream (includes both queued and\n * pending items), null if stream empty\n */\n oldest_queued_at: string | null;\n\n /**\n * Number of work items being processed (polled but not acknowledged)\n */\n pending: number;\n\n /**\n * The type of object\n */\n type: 'work_queue_stats';\n\n /**\n * Number of workers that have polled for work in the last 30 seconds. Requires\n * worker_id to be sent with poll requests.\n */\n workers_polling: number | null;\n}\n\n/**\n * Request to stop a work item.\n */\nexport interface BetaSelfHostedWorkStopRequest {\n /**\n * If true, immediately stop work without graceful shutdown\n */\n force?: boolean;\n}\n\n/**\n * Request to update work item metadata.\n */\nexport interface BetaSelfHostedWorkUpdateRequest {\n /**\n * Metadata patch. Set a key to a string to upsert it, or to null to delete it.\n * Omit the field to preserve existing metadata.\n */\n metadata: { [key: string]: string | null };\n}\n\n/**\n * Work data for session work items.\n *\n * This resource type is used when work represents a session that needs to be\n * executed in a self-hosted environment.\n */\nexport interface BetaSessionWorkData {\n /**\n * Session identifier (e.g., 'session\\_...')\n */\n id: string;\n\n /**\n * Type of work data\n */\n type: 'session';\n}\n\n/**\n * Decoded payload of the `secret` field on a self-hosted work item. The wire value\n * of `secret` is a base64url-encoded JSON document matching this schema. SDKs that\n * ship a runner helper for self-hosted environments use this type as the return\n * value of their secret-decoding utility.\n */\nexport interface BetaWorkSecret {\n /**\n * Bearer credential the runner uses for all per-session downstream calls\n * (heartbeat, ack, event stream, send, stop). Format: `sk-ant-req-...`.\n */\n sessions_token: string;\n\n /**\n * API base URL the runner should use for downstream calls. When absent the runner\n * falls back to its default Anthropic endpoint.\n */\n api_base_url?: string;\n}\n\nexport interface WorkRetrieveParams {\n /**\n * Path param\n */\n environment_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface WorkUpdateParams {\n /**\n * Path param\n */\n environment_id: string;\n\n /**\n * Body param: Metadata patch. Set a key to a string to upsert it, or to null to\n * delete it. Omit the field to preserve existing metadata.\n */\n metadata: { [key: string]: string | null };\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface WorkListParams extends PageCursorParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface WorkAckParams {\n /**\n * Path param\n */\n environment_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface WorkHeartbeatParams {\n /**\n * Path param\n */\n environment_id: string;\n\n /**\n * Query param: Desired TTL in seconds\n */\n desired_ttl_seconds?: number | null;\n\n /**\n * Query param: Expected last_heartbeat for conditional update (optimistic\n * concurrency). Use literal 'NO_HEARTBEAT' to claim an unclaimed lease (first\n * heartbeat). For subsequent heartbeats, echo the server's previous last_heartbeat\n * value exactly. Returns 412 Precondition Failed if the actual value doesn't\n * match.\n */\n expected_last_heartbeat?: string | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface WorkPollParams {\n /**\n * Query param: How long to wait for work to arrive before returning. Must be 1-999\n * in milliseconds. Defaults to non-blocking (returns immediately if no work is\n * available).\n */\n block_ms?: number | null;\n\n /**\n * Query param: Reclaim unacknowledged work items older than this many\n * milliseconds. If omitted, uses the default (5000ms).\n */\n reclaim_older_than_ms?: number | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n\n /**\n * Header param: Unique identifier for the specific worker polling, used to track\n * aggregated environment-level work metrics in Console\n */\n 'Anthropic-Worker-ID'?: string;\n}\n\nexport interface WorkStatsParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface WorkStopParams {\n /**\n * Path param\n */\n environment_id: string;\n\n /**\n * Body param: If true, immediately stop work without graceful shutdown\n */\n force?: boolean;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport { WorkPoller, type WorkPollerOptions } from '../../../lib/environments/poller';\nexport { EnvironmentWorker, type EnvironmentWorkerOptions } from '../../../lib/environments/worker';\n\nWork.WorkPoller = WorkPoller;\nWork.EnvironmentWorker = EnvironmentWorker;\n\nexport declare namespace Work {\n export { WorkPoller, EnvironmentWorker };\n\n export {\n type BetaHealthCheckWorkData as BetaHealthCheckWorkData,\n type BetaSelfHostedWork as BetaSelfHostedWork,\n type BetaSelfHostedWorkHeartbeatResponse as BetaSelfHostedWorkHeartbeatResponse,\n type BetaSelfHostedWorkListResponse as BetaSelfHostedWorkListResponse,\n type BetaSelfHostedWorkQueueStats as BetaSelfHostedWorkQueueStats,\n type BetaSelfHostedWorkStopRequest as BetaSelfHostedWorkStopRequest,\n type BetaSelfHostedWorkUpdateRequest as BetaSelfHostedWorkUpdateRequest,\n type BetaSessionWorkData as BetaSessionWorkData,\n type BetaWorkSecret as BetaWorkSecret,\n type BetaSelfHostedWorksPageCursor as BetaSelfHostedWorksPageCursor,\n type WorkRetrieveParams as WorkRetrieveParams,\n type WorkUpdateParams as WorkUpdateParams,\n type WorkListParams as WorkListParams,\n type WorkAckParams as WorkAckParams,\n type WorkHeartbeatParams as WorkHeartbeatParams,\n type WorkPollParams as WorkPollParams,\n type WorkStatsParams as WorkStatsParams,\n type WorkStopParams as WorkStopParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as WorkAPI from './work';\nimport {\n BetaSelfHostedWork,\n BetaSelfHostedWorkHeartbeatResponse,\n BetaSelfHostedWorkListResponse,\n BetaSelfHostedWorkQueueStats,\n BetaSelfHostedWorkStopRequest,\n BetaSelfHostedWorkUpdateRequest,\n BetaSelfHostedWorksPageCursor,\n BetaSessionWorkData,\n Work,\n WorkAckParams,\n WorkHeartbeatParams,\n WorkListParams,\n WorkPollParams,\n WorkRetrieveParams,\n WorkStatsParams,\n WorkStopParams,\n WorkUpdateParams,\n} from './work';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class Environments extends APIResource {\n work: WorkAPI.Work = new WorkAPI.Work(this._client);\n\n /**\n * Create a new environment with the specified configuration.\n *\n * @example\n * ```ts\n * const betaEnvironment =\n * await client.beta.environments.create({\n * name: 'python-data-analysis',\n * });\n * ```\n */\n create(params: EnvironmentCreateParams, options?: RequestOptions): APIPromise<BetaEnvironment> {\n const { betas, ...body } = params;\n return this._client.post('/v1/environments?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Retrieve a specific environment by ID.\n *\n * @example\n * ```ts\n * const betaEnvironment =\n * await client.beta.environments.retrieve(\n * 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * );\n * ```\n */\n retrieve(\n environmentID: string,\n params: EnvironmentRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaEnvironment> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/environments/${environmentID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update an existing environment's configuration.\n *\n * @example\n * ```ts\n * const betaEnvironment =\n * await client.beta.environments.update(\n * 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * );\n * ```\n */\n update(\n environmentID: string,\n params: EnvironmentUpdateParams,\n options?: RequestOptions,\n ): APIPromise<BetaEnvironment> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/environments/${environmentID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List environments with pagination support.\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaEnvironment of client.beta.environments.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: EnvironmentListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaEnvironmentsPageCursor, BetaEnvironment> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/environments?beta=true', PageCursor<BetaEnvironment>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Delete an environment by ID. Returns a confirmation of the deletion.\n *\n * @example\n * ```ts\n * const betaEnvironmentDeleteResponse =\n * await client.beta.environments.delete(\n * 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * );\n * ```\n */\n delete(\n environmentID: string,\n params: EnvironmentDeleteParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaEnvironmentDeleteResponse> {\n const { betas } = params ?? {};\n return this._client.delete(path`/v1/environments/${environmentID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Archive an environment by ID. Archived environments cannot be used to create new\n * sessions.\n *\n * @example\n * ```ts\n * const betaEnvironment =\n * await client.beta.environments.archive(\n * 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * );\n * ```\n */\n archive(\n environmentID: string,\n params: EnvironmentArchiveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaEnvironment> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/environments/${environmentID}/archive?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaEnvironmentsPageCursor = PageCursor<BetaEnvironment>;\n\n/**\n * `cloud` environment configuration.\n */\nexport interface BetaCloudConfig {\n /**\n * Network configuration policy.\n */\n networking: BetaUnrestrictedNetwork | BetaLimitedNetwork;\n\n /**\n * Package manager configuration.\n */\n packages: BetaPackages;\n\n /**\n * Environment type\n */\n type: 'cloud';\n}\n\n/**\n * Request params for `cloud` environment configuration.\n *\n * Fields default to null; on update, omitted fields preserve the existing value.\n */\nexport interface BetaCloudConfigParams {\n /**\n * Environment type\n */\n type: 'cloud';\n\n /**\n * Network configuration policy. Omit on update to preserve the existing value.\n */\n networking?: BetaUnrestrictedNetwork | BetaLimitedNetworkParams | null;\n\n /**\n * Specify packages (and optionally their versions) available in this environment.\n *\n * When versioning, use the version semantics relevant for the package manager,\n * e.g. for `pip` use `package==1.0.0`. You are responsible for validating the\n * package and version exist. Unversioned installs the latest.\n */\n packages?: BetaPackagesParams | null;\n}\n\n/**\n * Unified Environment resource for both cloud and self-hosted environments.\n */\nexport interface BetaEnvironment {\n /**\n * Environment identifier (e.g., 'env\\_...')\n */\n id: string;\n\n /**\n * RFC 3339 timestamp when environment was archived, or null if not archived\n */\n archived_at: string | null;\n\n /**\n * Environment configuration (either Anthropic Cloud or self-hosted)\n */\n config: BetaCloudConfig | BetaSelfHostedConfig;\n\n /**\n * RFC 3339 timestamp when environment was created\n */\n created_at: string;\n\n /**\n * User-provided description for the environment\n */\n description: string;\n\n /**\n * User-provided metadata key-value pairs\n */\n metadata: { [key: string]: string };\n\n /**\n * Human-readable name for the environment\n */\n name: string;\n\n /**\n * The type of object (always 'environment')\n */\n type: 'environment';\n\n /**\n * RFC 3339 timestamp when environment was last updated\n */\n updated_at: string;\n\n /**\n * The visibility scope for this environment. 'organization' means visible to all\n * accounts. 'account' means visible only to the owning account.\n */\n scope?: 'organization' | 'account';\n}\n\n/**\n * Response after deleting an environment.\n */\nexport interface BetaEnvironmentDeleteResponse {\n /**\n * Environment identifier\n */\n id: string;\n\n /**\n * The type of response\n */\n type: 'environment_deleted';\n}\n\n/**\n * Limited network access.\n */\nexport interface BetaLimitedNetwork {\n /**\n * Permits outbound access to MCP server endpoints configured on the agent, beyond\n * those listed in the `allowed_hosts` array.\n */\n allow_mcp_servers: boolean;\n\n /**\n * Permits outbound access to public package registries (PyPI, npm, etc.) beyond\n * those listed in the `allowed_hosts` array.\n */\n allow_package_managers: boolean;\n\n /**\n * Specifies domains the container can reach.\n */\n allowed_hosts: Array<string>;\n\n /**\n * Network policy type\n */\n type: 'limited';\n}\n\n/**\n * Limited network request params.\n *\n * Fields default to null; on update, omitted fields preserve the existing value.\n */\nexport interface BetaLimitedNetworkParams {\n /**\n * Network policy type\n */\n type: 'limited';\n\n /**\n * Permits outbound access to MCP server endpoints configured on the agent, beyond\n * those listed in the `allowed_hosts` array. Defaults to `false`.\n */\n allow_mcp_servers?: boolean | null;\n\n /**\n * Permits outbound access to public package registries (PyPI, npm, etc.) beyond\n * those listed in the `allowed_hosts` array. Defaults to `false`.\n */\n allow_package_managers?: boolean | null;\n\n /**\n * Specifies domains the container can reach.\n */\n allowed_hosts?: Array<string> | null;\n}\n\n/**\n * Packages (and their versions) available in this environment.\n */\nexport interface BetaPackages {\n /**\n * Ubuntu/Debian packages to install\n */\n apt: Array<string>;\n\n /**\n * Rust packages to install\n */\n cargo: Array<string>;\n\n /**\n * Ruby packages to install\n */\n gem: Array<string>;\n\n /**\n * Go packages to install\n */\n go: Array<string>;\n\n /**\n * Node.js packages to install\n */\n npm: Array<string>;\n\n /**\n * Python packages to install\n */\n pip: Array<string>;\n\n /**\n * Package configuration type\n */\n type?: 'packages';\n}\n\n/**\n * Specify packages (and optionally their versions) available in this environment.\n *\n * When versioning, use the version semantics relevant for the package manager,\n * e.g. for `pip` use `package==1.0.0`. You are responsible for validating the\n * package and version exist. Unversioned installs the latest.\n */\nexport interface BetaPackagesParams {\n /**\n * Ubuntu/Debian packages to install\n */\n apt?: Array<string> | null;\n\n /**\n * Rust packages to install\n */\n cargo?: Array<string> | null;\n\n /**\n * Ruby packages to install\n */\n gem?: Array<string> | null;\n\n /**\n * Go packages to install\n */\n go?: Array<string> | null;\n\n /**\n * Node.js packages to install\n */\n npm?: Array<string> | null;\n\n /**\n * Python packages to install\n */\n pip?: Array<string> | null;\n\n /**\n * Package configuration type\n */\n type?: 'packages';\n}\n\n/**\n * Configuration for self-hosted environments.\n */\nexport interface BetaSelfHostedConfig {\n /**\n * Environment type\n */\n type: 'self_hosted';\n}\n\n/**\n * Request params for `self_hosted` environment configuration.\n */\nexport interface BetaSelfHostedConfigParams {\n /**\n * Environment type\n */\n type: 'self_hosted';\n}\n\n/**\n * Unrestricted network access.\n */\nexport interface BetaUnrestrictedNetwork {\n /**\n * Network policy type\n */\n type: 'unrestricted';\n}\n\nexport interface EnvironmentCreateParams {\n /**\n * Body param: Human-readable name for the environment\n */\n name: string;\n\n /**\n * Body param: Environment configuration\n */\n config?: BetaCloudConfigParams | BetaSelfHostedConfigParams | null;\n\n /**\n * Body param: Optional description of the environment\n */\n description?: string | null;\n\n /**\n * Body param: User-provided metadata key-value pairs\n */\n metadata?: { [key: string]: string };\n\n /**\n * Body param: The visibility scope for this environment. 'organization' makes the\n * environment visible to all accounts. 'account' restricts visibility to the\n * owning account only. Only applicable for self-hosted environments. If not\n * specified, defaults based on organization type.\n */\n scope?: 'organization' | 'account' | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface EnvironmentRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface EnvironmentUpdateParams {\n /**\n * Body param: Updated environment configuration\n */\n config?: BetaCloudConfigParams | BetaSelfHostedConfigParams | null;\n\n /**\n * Body param: Updated description of the environment\n */\n description?: string | null;\n\n /**\n * Body param: User-provided metadata key-value pairs. Set a value to null or empty\n * string to delete the key.\n */\n metadata?: { [key: string]: string | null };\n\n /**\n * Body param: Updated name for the environment\n */\n name?: string | null;\n\n /**\n * Body param: The visibility scope for this environment. 'organization' makes the\n * environment visible to all accounts. 'account' restricts visibility to the\n * owning account only.\n */\n scope?: 'organization' | 'account' | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface EnvironmentListParams extends PageCursorParams {\n /**\n * Query param: Include archived environments in the response\n */\n include_archived?: boolean;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface EnvironmentDeleteParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface EnvironmentArchiveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nEnvironments.Work = Work;\n\nexport declare namespace Environments {\n export {\n type BetaCloudConfig as BetaCloudConfig,\n type BetaCloudConfigParams as BetaCloudConfigParams,\n type BetaEnvironment as BetaEnvironment,\n type BetaEnvironmentDeleteResponse as BetaEnvironmentDeleteResponse,\n type BetaLimitedNetwork as BetaLimitedNetwork,\n type BetaLimitedNetworkParams as BetaLimitedNetworkParams,\n type BetaPackages as BetaPackages,\n type BetaPackagesParams as BetaPackagesParams,\n type BetaSelfHostedConfig as BetaSelfHostedConfig,\n type BetaSelfHostedConfigParams as BetaSelfHostedConfigParams,\n type BetaUnrestrictedNetwork as BetaUnrestrictedNetwork,\n type BetaEnvironmentsPageCursor as BetaEnvironmentsPageCursor,\n type EnvironmentCreateParams as EnvironmentCreateParams,\n type EnvironmentRetrieveParams as EnvironmentRetrieveParams,\n type EnvironmentUpdateParams as EnvironmentUpdateParams,\n type EnvironmentListParams as EnvironmentListParams,\n type EnvironmentDeleteParams as EnvironmentDeleteParams,\n type EnvironmentArchiveParams as EnvironmentArchiveParams,\n };\n\n export {\n Work as Work,\n type BetaSelfHostedWork as BetaSelfHostedWork,\n type BetaSelfHostedWorkHeartbeatResponse as BetaSelfHostedWorkHeartbeatResponse,\n type BetaSelfHostedWorkListResponse as BetaSelfHostedWorkListResponse,\n type BetaSelfHostedWorkQueueStats as BetaSelfHostedWorkQueueStats,\n type BetaSelfHostedWorkStopRequest as BetaSelfHostedWorkStopRequest,\n type BetaSelfHostedWorkUpdateRequest as BetaSelfHostedWorkUpdateRequest,\n type BetaSessionWorkData as BetaSessionWorkData,\n type BetaSelfHostedWorksPageCursor as BetaSelfHostedWorksPageCursor,\n type WorkRetrieveParams as WorkRetrieveParams,\n type WorkUpdateParams as WorkUpdateParams,\n type WorkListParams as WorkListParams,\n type WorkAckParams as WorkAckParams,\n type WorkHeartbeatParams as WorkHeartbeatParams,\n type WorkPollParams as WorkPollParams,\n type WorkStatsParams as WorkStatsParams,\n type WorkStopParams as WorkStopParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class Memories extends APIResource {\n /**\n * Create a memory\n *\n * @example\n * ```ts\n * const betaManagedAgentsMemory =\n * await client.beta.memoryStores.memories.create(\n * 'memory_store_id',\n * { content: 'content', path: 'xx' },\n * );\n * ```\n */\n create(\n memoryStoreID: string,\n params: MemoryCreateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsMemory> {\n const { view, betas, ...body } = params;\n return this._client.post(path`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, {\n query: { view },\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Retrieve a memory\n *\n * @example\n * ```ts\n * const betaManagedAgentsMemory =\n * await client.beta.memoryStores.memories.retrieve(\n * 'memory_id',\n * { memory_store_id: 'memory_store_id' },\n * );\n * ```\n */\n retrieve(\n memoryID: string,\n params: MemoryRetrieveParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsMemory> {\n const { memory_store_id, betas, ...query } = params;\n return this._client.get(path`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update a memory\n *\n * @example\n * ```ts\n * const betaManagedAgentsMemory =\n * await client.beta.memoryStores.memories.update(\n * 'memory_id',\n * { memory_store_id: 'memory_store_id' },\n * );\n * ```\n */\n update(\n memoryID: string,\n params: MemoryUpdateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsMemory> {\n const { memory_store_id, view, betas, ...body } = params;\n return this._client.post(path`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, {\n query: { view },\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List memories\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsMemoryListItem of client.beta.memoryStores.memories.list(\n * 'memory_store_id',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n memoryStoreID: string,\n params: MemoryListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsMemoryListItemsPageCursor, BetaManagedAgentsMemoryListItem> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n path`/v1/memory_stores/${memoryStoreID}/memories?beta=true`,\n PageCursor<BetaManagedAgentsMemoryListItem>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * Delete a memory\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeletedMemory =\n * await client.beta.memoryStores.memories.delete(\n * 'memory_id',\n * { memory_store_id: 'memory_store_id' },\n * );\n * ```\n */\n delete(\n memoryID: string,\n params: MemoryDeleteParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeletedMemory> {\n const { memory_store_id, expected_content_sha256, betas } = params;\n return this._client.delete(path`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, {\n query: { expected_content_sha256 },\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaManagedAgentsMemoryListItemsPageCursor = PageCursor<BetaManagedAgentsMemoryListItem>;\n\nexport interface BetaManagedAgentsConflictError {\n type: 'conflict_error';\n\n message?: string;\n}\n\n/**\n * Optimistic-concurrency precondition: the update applies only if the memory's\n * stored `content_sha256` equals the supplied value. On mismatch, the request\n * returns `memory_precondition_failed_error` (HTTP 409); re-read the memory and\n * retry against the fresh state. If the precondition fails but the stored state\n * already exactly matches the requested `content` and `path`, the server returns\n * 200 instead of 409.\n */\nexport interface BetaManagedAgentsContentSha256Precondition {\n type: 'content_sha256';\n\n /**\n * Expected `content_sha256` of the stored memory (64 lowercase hexadecimal\n * characters). Typically the `content_sha256` returned by a prior read or list\n * call. Because the server applies no content normalization, clients can also\n * compute this locally as the SHA-256 of the UTF-8 content bytes.\n */\n content_sha256?: string;\n}\n\n/**\n * Tombstone returned by\n * [Delete a memory](/en/api/beta/memory_stores/memories/delete). The memory's\n * version history persists and remains listable via\n * [List memory versions](/en/api/beta/memory_stores/memory_versions/list) until\n * the store itself is deleted.\n */\nexport interface BetaManagedAgentsDeletedMemory {\n /**\n * ID of the deleted memory (a `mem_...` value).\n */\n id: string;\n\n type: 'memory_deleted';\n}\n\nexport type BetaManagedAgentsError =\n | BetaAPI.BetaInvalidRequestError\n | BetaAPI.BetaAuthenticationError\n | BetaAPI.BetaBillingError\n | BetaAPI.BetaPermissionError\n | BetaAPI.BetaNotFoundError\n | BetaAPI.BetaRateLimitError\n | BetaAPI.BetaGatewayTimeoutError\n | BetaAPI.BetaAPIError\n | BetaAPI.BetaOverloadedError\n | BetaManagedAgentsMemoryPreconditionFailedError\n | BetaManagedAgentsMemoryPathConflictError\n | BetaManagedAgentsConflictError;\n\n/**\n * A `memory` object: a single text document at a hierarchical path inside a memory\n * store. The `content` field is populated when `view=full` and `null` when\n * `view=basic`; the `content_size_bytes` and `content_sha256` fields are always\n * populated so sync clients can diff without fetching content. Memories are\n * addressed by their `mem_...` ID; the path is the create key and can be changed\n * via update.\n */\nexport interface BetaManagedAgentsMemory {\n /**\n * Unique identifier for this memory (a `mem_...` value). Stable across renames;\n * use this ID, not the path, to read, update, or delete the memory.\n */\n id: string;\n\n /**\n * Lowercase hex SHA-256 digest of the UTF-8 `content` bytes (64 characters). The\n * server applies no normalization, so clients can compute the same hash locally\n * for staleness checks and as the value for a `content_sha256` precondition on\n * update. Always populated, regardless of `view`.\n */\n content_sha256: string;\n\n /**\n * Size of `content` in bytes (the UTF-8 plaintext length). Always populated,\n * regardless of `view`.\n */\n content_size_bytes: number;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n /**\n * ID of the memory store this memory belongs to (a `memstore_...` value).\n */\n memory_store_id: string;\n\n /**\n * ID of the `memory_version` representing this memory's current content (a\n * `memver_...` value). This is the authoritative head pointer; `memory_version`\n * objects do not carry an `is_latest` flag, so compare against this field instead.\n * Enumerate the full history via\n * [List memory versions](/en/api/beta/memory_stores/memory_versions/list).\n */\n memory_version_id: string;\n\n /**\n * Hierarchical path of the memory within the store, e.g. `/projects/foo/notes.md`.\n * Always starts with `/`. Paths are case-sensitive and unique within a store.\n * Maximum 1,024 bytes.\n */\n path: string;\n\n type: 'memory';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n\n /**\n * The memory's UTF-8 text content. Populated when `view=full`; `null` when\n * `view=basic`. Maximum 100 kB (102,400 bytes).\n */\n content?: string | null;\n}\n\n/**\n * One item in a [List memories](/en/api/beta/memory_stores/memories/list)\n * response: either a `memory` object or, when `depth` is set, a `memory_prefix`\n * rollup marker.\n */\nexport type BetaManagedAgentsMemoryListItem = BetaManagedAgentsMemory | BetaManagedAgentsMemoryPrefix;\n\nexport interface BetaManagedAgentsMemoryPathConflictError {\n type: 'memory_path_conflict_error';\n\n conflicting_memory_id?: string;\n\n conflicting_path?: string;\n\n message?: string;\n}\n\nexport interface BetaManagedAgentsMemoryPreconditionFailedError {\n type: 'memory_precondition_failed_error';\n\n message?: string;\n}\n\n/**\n * A rolled-up directory marker returned by\n * [List memories](/en/api/beta/memory_stores/memories/list) when `depth` is set.\n * Indicates that one or more memories exist deeper than the requested depth under\n * this prefix. This is a list-time rollup, not a stored resource; it has no ID and\n * no lifecycle. Each prefix counts toward the page `limit` and interleaves with\n * `memory` items in path order.\n */\nexport interface BetaManagedAgentsMemoryPrefix {\n /**\n * The rolled-up path prefix, including a trailing `/` (e.g. `/projects/foo/`).\n * Pass this value as `path_prefix` on a subsequent list call to drill into the\n * directory.\n */\n path: string;\n\n type: 'memory_prefix';\n}\n\n/**\n * Selects which projection of a `memory` or `memory_version` the server returns.\n * `basic` returns the object with `content` set to `null`; `full` populates\n * `content`. When omitted, the default is endpoint-specific: retrieve operations\n * default to `full`; list, create, and update operations default to `basic`.\n * Listing with `view=full` caps `limit` at 20.\n */\nexport type BetaManagedAgentsMemoryView = 'basic' | 'full';\n\n/**\n * Optimistic-concurrency precondition: the update applies only if the memory's\n * stored `content_sha256` equals the supplied value. On mismatch, the request\n * returns `memory_precondition_failed_error` (HTTP 409); re-read the memory and\n * retry against the fresh state. If the precondition fails but the stored state\n * already exactly matches the requested `content` and `path`, the server returns\n * 200 instead of 409.\n */\nexport interface BetaManagedAgentsPrecondition {\n type: 'content_sha256';\n\n /**\n * Expected `content_sha256` of the stored memory (64 lowercase hexadecimal\n * characters). Typically the `content_sha256` returned by a prior read or list\n * call. Because the server applies no content normalization, clients can also\n * compute this locally as the SHA-256 of the UTF-8 content bytes.\n */\n content_sha256?: string;\n}\n\nexport interface MemoryCreateParams {\n /**\n * Body param: UTF-8 text content for the new memory. Maximum 100 kB (102,400\n * bytes). Required; pass `\"\"` explicitly to create an empty memory.\n */\n content: string | null;\n\n /**\n * Body param: Hierarchical path for the new memory, e.g. `/projects/foo/notes.md`.\n * Must start with `/`, contain at least one non-empty segment, and be at most\n * 1,024 bytes. Must not contain empty segments, `.` or `..` segments, control or\n * format characters, and must be NFC-normalized. Paths are case-sensitive.\n */\n path: string;\n\n /**\n * Query param: Query parameter for view\n */\n view?: BetaManagedAgentsMemoryView;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryRetrieveParams {\n /**\n * Path param: Path parameter memory_store_id\n */\n memory_store_id: string;\n\n /**\n * Query param: Query parameter for view\n */\n view?: BetaManagedAgentsMemoryView;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryUpdateParams {\n /**\n * Path param: Path parameter memory_store_id\n */\n memory_store_id: string;\n\n /**\n * Query param: Query parameter for view\n */\n view?: BetaManagedAgentsMemoryView;\n\n /**\n * Body param: New UTF-8 text content for the memory. Maximum 100 kB (102,400\n * bytes). Omit to leave the content unchanged (e.g., for a rename-only update).\n */\n content?: string | null;\n\n /**\n * Body param: New path for the memory (a rename). Must start with `/`, contain at\n * least one non-empty segment, and be at most 1,024 bytes. Must not contain empty\n * segments, `.` or `..` segments, control or format characters, and must be\n * NFC-normalized. Paths are case-sensitive. The memory's `id` is preserved across\n * renames. Omit to leave the path unchanged.\n */\n path?: string | null;\n\n /**\n * Body param: Optimistic-concurrency precondition: the update applies only if the\n * memory's stored `content_sha256` equals the supplied value. On mismatch, the\n * request returns `memory_precondition_failed_error` (HTTP 409); re-read the\n * memory and retry against the fresh state. If the precondition fails but the\n * stored state already exactly matches the requested `content` and `path`, the\n * server returns 200 instead of 409.\n */\n precondition?: BetaManagedAgentsPrecondition;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryListParams extends PageCursorParams {\n /**\n * Query param: Query parameter for depth\n */\n depth?: number;\n\n /**\n * Query param: Query parameter for order\n */\n order?: 'asc' | 'desc';\n\n /**\n * Query param: Query parameter for order_by\n */\n order_by?: string;\n\n /**\n * Query param: Optional path prefix filter (raw string-prefix match; include a\n * trailing slash for directory-scoped lists). This value appears in request URLs.\n * Do not include secrets or personally identifiable information.\n */\n path_prefix?: string;\n\n /**\n * Query param: Query parameter for view\n */\n view?: BetaManagedAgentsMemoryView;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryDeleteParams {\n /**\n * Path param: Path parameter memory_store_id\n */\n memory_store_id: string;\n\n /**\n * Query param: Query parameter for expected_content_sha256\n */\n expected_content_sha256?: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Memories {\n export {\n type BetaManagedAgentsConflictError as BetaManagedAgentsConflictError,\n type BetaManagedAgentsContentSha256Precondition as BetaManagedAgentsContentSha256Precondition,\n type BetaManagedAgentsDeletedMemory as BetaManagedAgentsDeletedMemory,\n type BetaManagedAgentsError as BetaManagedAgentsError,\n type BetaManagedAgentsMemory as BetaManagedAgentsMemory,\n type BetaManagedAgentsMemoryListItem as BetaManagedAgentsMemoryListItem,\n type BetaManagedAgentsMemoryPathConflictError as BetaManagedAgentsMemoryPathConflictError,\n type BetaManagedAgentsMemoryPreconditionFailedError as BetaManagedAgentsMemoryPreconditionFailedError,\n type BetaManagedAgentsMemoryPrefix as BetaManagedAgentsMemoryPrefix,\n type BetaManagedAgentsMemoryView as BetaManagedAgentsMemoryView,\n type BetaManagedAgentsPrecondition as BetaManagedAgentsPrecondition,\n type BetaManagedAgentsMemoryListItemsPageCursor as BetaManagedAgentsMemoryListItemsPageCursor,\n type MemoryCreateParams as MemoryCreateParams,\n type MemoryRetrieveParams as MemoryRetrieveParams,\n type MemoryUpdateParams as MemoryUpdateParams,\n type MemoryListParams as MemoryListParams,\n type MemoryDeleteParams as MemoryDeleteParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as MemoriesAPI from './memories';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class MemoryVersions extends APIResource {\n /**\n * Retrieve a memory version\n *\n * @example\n * ```ts\n * const betaManagedAgentsMemoryVersion =\n * await client.beta.memoryStores.memoryVersions.retrieve(\n * 'memory_version_id',\n * { memory_store_id: 'memory_store_id' },\n * );\n * ```\n */\n retrieve(\n memoryVersionID: string,\n params: MemoryVersionRetrieveParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsMemoryVersion> {\n const { memory_store_id, betas, ...query } = params;\n return this._client.get(\n path`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}?beta=true`,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * List memory versions\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsMemoryVersion of client.beta.memoryStores.memoryVersions.list(\n * 'memory_store_id',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n memoryStoreID: string,\n params: MemoryVersionListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsMemoryVersionsPageCursor, BetaManagedAgentsMemoryVersion> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n path`/v1/memory_stores/${memoryStoreID}/memory_versions?beta=true`,\n PageCursor<BetaManagedAgentsMemoryVersion>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * Redact a memory version\n *\n * @example\n * ```ts\n * const betaManagedAgentsMemoryVersion =\n * await client.beta.memoryStores.memoryVersions.redact(\n * 'memory_version_id',\n * { memory_store_id: 'memory_store_id' },\n * );\n * ```\n */\n redact(\n memoryVersionID: string,\n params: MemoryVersionRedactParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsMemoryVersion> {\n const { memory_store_id, betas } = params;\n return this._client.post(\n path`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}/redact?beta=true`,\n {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n}\n\nexport type BetaManagedAgentsMemoryVersionsPageCursor = PageCursor<BetaManagedAgentsMemoryVersion>;\n\n/**\n * Identifies who performed a write or redact operation. Captured at write time on\n * the `memory_version` row. The API key that created a session is not recorded on\n * agent writes; attribution answers who made the write, not who is ultimately\n * responsible. Look up session provenance separately via the\n * [Sessions API](/en/api/sessions-retrieve).\n */\nexport type BetaManagedAgentsActor =\n | BetaManagedAgentsSessionActor\n | BetaManagedAgentsAPIActor\n | BetaManagedAgentsUserActor;\n\n/**\n * Attribution for a write made directly via the public API (outside of any\n * session).\n */\nexport interface BetaManagedAgentsAPIActor {\n /**\n * ID of the API key that performed the write. This identifies the key, not the\n * secret.\n */\n api_key_id: string;\n\n type: 'api_actor';\n}\n\n/**\n * A `memory_version` object: one immutable, attributed row in a memory's\n * append-only history. Every non-no-op mutation to a memory produces a new\n * version. Versions belong to the store (not the individual memory) and persist\n * after the memory is deleted. Retrieving a redacted version returns 200 with\n * `content`, `path`, `content_size_bytes`, and `content_sha256` set to `null`;\n * branch on `redacted_at`, not HTTP status.\n */\nexport interface BetaManagedAgentsMemoryVersion {\n /**\n * Unique identifier for this version (a `memver_...` value).\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n /**\n * ID of the memory this version snapshots (a `mem_...` value). Remains valid after\n * the memory is deleted; pass it as `memory_id` to\n * [List memory versions](/en/api/beta/memory_stores/memory_versions/list) to\n * retrieve the full lineage including the `deleted` row.\n */\n memory_id: string;\n\n /**\n * ID of the memory store this version belongs to (a `memstore_...` value).\n */\n memory_store_id: string;\n\n /**\n * The kind of mutation a `memory_version` records. Every non-no-op mutation to a\n * memory appends exactly one version row with one of these values.\n */\n operation: BetaManagedAgentsMemoryVersionOperation;\n\n type: 'memory_version';\n\n /**\n * The memory's UTF-8 text content as of this version. `null` when `view=basic`,\n * when `operation` is `deleted`, or when `redacted_at` is set.\n */\n content?: string | null;\n\n /**\n * Lowercase hex SHA-256 digest of `content` as of this version (64 characters).\n * `null` when `redacted_at` is set or `operation` is `deleted`. Populated\n * regardless of `view` otherwise.\n */\n content_sha256?: string | null;\n\n /**\n * Size of `content` in bytes as of this version. `null` when `redacted_at` is set\n * or `operation` is `deleted`. Populated regardless of `view` otherwise.\n */\n content_size_bytes?: number | null;\n\n /**\n * Identifies who performed a write or redact operation. Captured at write time on\n * the `memory_version` row. The API key that created a session is not recorded on\n * agent writes; attribution answers who made the write, not who is ultimately\n * responsible. Look up session provenance separately via the\n * [Sessions API](/en/api/sessions-retrieve).\n */\n created_by?: BetaManagedAgentsActor;\n\n /**\n * The memory's path at the time of this write. `null` if and only if `redacted_at`\n * is set.\n */\n path?: string | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n redacted_at?: string | null;\n\n /**\n * Identifies who performed a write or redact operation. Captured at write time on\n * the `memory_version` row. The API key that created a session is not recorded on\n * agent writes; attribution answers who made the write, not who is ultimately\n * responsible. Look up session provenance separately via the\n * [Sessions API](/en/api/sessions-retrieve).\n */\n redacted_by?: BetaManagedAgentsActor;\n}\n\n/**\n * The kind of mutation a `memory_version` records. Every non-no-op mutation to a\n * memory appends exactly one version row with one of these values.\n */\nexport type BetaManagedAgentsMemoryVersionOperation = 'created' | 'modified' | 'deleted';\n\n/**\n * Attribution for a write made by an agent during a session, through the mounted\n * filesystem at `/mnt/memory/`.\n */\nexport interface BetaManagedAgentsSessionActor {\n /**\n * ID of the session that performed the write (a `sesn_...` value). Look up the\n * session via [Retrieve a session](/en/api/sessions-retrieve) for further\n * provenance.\n */\n session_id: string;\n\n type: 'session_actor';\n}\n\n/**\n * Attribution for a write made by a human user through the Anthropic Console.\n */\nexport interface BetaManagedAgentsUserActor {\n type: 'user_actor';\n\n /**\n * ID of the user who performed the write (a `user_...` value).\n */\n user_id: string;\n}\n\nexport interface MemoryVersionRetrieveParams {\n /**\n * Path param: Path parameter memory_store_id\n */\n memory_store_id: string;\n\n /**\n * Query param: Query parameter for view\n */\n view?: MemoriesAPI.BetaManagedAgentsMemoryView;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryVersionListParams extends PageCursorParams {\n /**\n * Query param: Query parameter for api_key_id\n */\n api_key_id?: string;\n\n /**\n * Query param: Return versions created at or after this time (inclusive).\n */\n 'created_at[gte]'?: string;\n\n /**\n * Query param: Return versions created at or before this time (inclusive).\n */\n 'created_at[lte]'?: string;\n\n /**\n * Query param: Query parameter for memory_id\n */\n memory_id?: string;\n\n /**\n * Query param: Query parameter for operation\n */\n operation?: BetaManagedAgentsMemoryVersionOperation;\n\n /**\n * Query param: Query parameter for session_id\n */\n session_id?: string;\n\n /**\n * Query param: Query parameter for view\n */\n view?: MemoriesAPI.BetaManagedAgentsMemoryView;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryVersionRedactParams {\n /**\n * Path param: Path parameter memory_store_id\n */\n memory_store_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace MemoryVersions {\n export {\n type BetaManagedAgentsActor as BetaManagedAgentsActor,\n type BetaManagedAgentsAPIActor as BetaManagedAgentsAPIActor,\n type BetaManagedAgentsMemoryVersion as BetaManagedAgentsMemoryVersion,\n type BetaManagedAgentsMemoryVersionOperation as BetaManagedAgentsMemoryVersionOperation,\n type BetaManagedAgentsSessionActor as BetaManagedAgentsSessionActor,\n type BetaManagedAgentsUserActor as BetaManagedAgentsUserActor,\n type BetaManagedAgentsMemoryVersionsPageCursor as BetaManagedAgentsMemoryVersionsPageCursor,\n type MemoryVersionRetrieveParams as MemoryVersionRetrieveParams,\n type MemoryVersionListParams as MemoryVersionListParams,\n type MemoryVersionRedactParams as MemoryVersionRedactParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as MemoriesAPI from './memories';\nimport {\n BetaManagedAgentsConflictError,\n BetaManagedAgentsContentSha256Precondition,\n BetaManagedAgentsDeletedMemory,\n BetaManagedAgentsError,\n BetaManagedAgentsMemory,\n BetaManagedAgentsMemoryListItem,\n BetaManagedAgentsMemoryListItemsPageCursor,\n BetaManagedAgentsMemoryPathConflictError,\n BetaManagedAgentsMemoryPreconditionFailedError,\n BetaManagedAgentsMemoryPrefix,\n BetaManagedAgentsMemoryView,\n BetaManagedAgentsPrecondition,\n Memories,\n MemoryCreateParams,\n MemoryDeleteParams,\n MemoryListParams,\n MemoryRetrieveParams,\n MemoryUpdateParams,\n} from './memories';\nimport * as MemoryVersionsAPI from './memory-versions';\nimport {\n BetaManagedAgentsAPIActor,\n BetaManagedAgentsActor,\n BetaManagedAgentsMemoryVersion,\n BetaManagedAgentsMemoryVersionOperation,\n BetaManagedAgentsMemoryVersionsPageCursor,\n BetaManagedAgentsSessionActor,\n BetaManagedAgentsUserActor,\n MemoryVersionListParams,\n MemoryVersionRedactParams,\n MemoryVersionRetrieveParams,\n MemoryVersions,\n} from './memory-versions';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class MemoryStores extends APIResource {\n memories: MemoriesAPI.Memories = new MemoriesAPI.Memories(this._client);\n memoryVersions: MemoryVersionsAPI.MemoryVersions = new MemoryVersionsAPI.MemoryVersions(this._client);\n\n /**\n * Create a memory store\n *\n * @example\n * ```ts\n * const betaManagedAgentsMemoryStore =\n * await client.beta.memoryStores.create({ name: 'x' });\n * ```\n */\n create(\n params: MemoryStoreCreateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsMemoryStore> {\n const { betas, ...body } = params;\n return this._client.post('/v1/memory_stores?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Retrieve a memory store\n *\n * @example\n * ```ts\n * const betaManagedAgentsMemoryStore =\n * await client.beta.memoryStores.retrieve(\n * 'memory_store_id',\n * );\n * ```\n */\n retrieve(\n memoryStoreID: string,\n params: MemoryStoreRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsMemoryStore> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/memory_stores/${memoryStoreID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update a memory store\n *\n * @example\n * ```ts\n * const betaManagedAgentsMemoryStore =\n * await client.beta.memoryStores.update('memory_store_id');\n * ```\n */\n update(\n memoryStoreID: string,\n params: MemoryStoreUpdateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsMemoryStore> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/memory_stores/${memoryStoreID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List memory stores\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsMemoryStore of client.beta.memoryStores.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: MemoryStoreListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsMemoryStoresPageCursor, BetaManagedAgentsMemoryStore> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/memory_stores?beta=true', PageCursor<BetaManagedAgentsMemoryStore>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Delete a memory store\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeletedMemoryStore =\n * await client.beta.memoryStores.delete('memory_store_id');\n * ```\n */\n delete(\n memoryStoreID: string,\n params: MemoryStoreDeleteParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeletedMemoryStore> {\n const { betas } = params ?? {};\n return this._client.delete(path`/v1/memory_stores/${memoryStoreID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Archive a memory store\n *\n * @example\n * ```ts\n * const betaManagedAgentsMemoryStore =\n * await client.beta.memoryStores.archive('memory_store_id');\n * ```\n */\n archive(\n memoryStoreID: string,\n params: MemoryStoreArchiveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsMemoryStore> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/memory_stores/${memoryStoreID}/archive?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaManagedAgentsMemoryStoresPageCursor = PageCursor<BetaManagedAgentsMemoryStore>;\n\n/**\n * Confirmation that a `memory_store` was deleted.\n */\nexport interface BetaManagedAgentsDeletedMemoryStore {\n /**\n * ID of the deleted memory store (a `memstore_...` identifier). The store and all\n * its memories and versions are no longer retrievable.\n */\n id: string;\n\n type: 'memory_store_deleted';\n}\n\n/**\n * A `memory_store`: a named container for agent memories, scoped to a workspace.\n * Attach a store to a session via `resources[]` to mount it as a directory the\n * agent can read and write.\n */\nexport interface BetaManagedAgentsMemoryStore {\n /**\n * Unique identifier for the memory store (a `memstore_...` tagged ID). Use this\n * when attaching the store to a session, or in the `{memory_store_id}` path\n * parameter of subsequent calls.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n /**\n * Human-readable name for the store. 1–255 characters. The store's mount-path slug\n * under `/mnt/memory/` is derived from this name.\n */\n name: string;\n\n type: 'memory_store';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n archived_at?: string | null;\n\n /**\n * Free-text description of what the store contains, up to 1024 characters.\n * Included in the agent's system prompt when the store is attached, so word it to\n * be useful to the agent. Empty string when unset.\n */\n description?: string;\n\n /**\n * Arbitrary key-value tags for your own bookkeeping (such as the end user a store\n * belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512 characters.\n * Returned on retrieve/list but not filterable.\n */\n metadata?: { [key: string]: string };\n}\n\nexport interface MemoryStoreCreateParams {\n /**\n * Body param: Human-readable name for the store. Required; 1–255 characters; no\n * control characters. The mount-path slug under `/mnt/memory/` is derived from\n * this name (lowercased, non-alphanumeric runs collapsed to a hyphen). Names need\n * not be unique within a workspace.\n */\n name: string;\n\n /**\n * Body param: Free-text description of what the store contains, up to 1024\n * characters. Included in the agent's system prompt when the store is attached, so\n * word it to be useful to the agent.\n */\n description?: string;\n\n /**\n * Body param: Arbitrary key-value tags for your own bookkeeping (such as the end\n * user a store belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512\n * characters. Not visible to the agent.\n */\n metadata?: { [key: string]: string };\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryStoreRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryStoreUpdateParams {\n /**\n * Body param: New description for the store, up to 1024 characters. Pass an empty\n * string to clear it.\n */\n description?: string | null;\n\n /**\n * Body param: Metadata patch. Set a key to a string to upsert it, or to null to\n * delete it. Omit the field to preserve. The stored bag is limited to 16 keys (up\n * to 64 chars each) with values up to 512 chars.\n */\n metadata?: { [key: string]: string | null } | null;\n\n /**\n * Body param: New human-readable name for the store. 1–255 characters; no control\n * characters. Renaming changes the slug used for the store's `mount_path` in\n * sessions created after the update.\n */\n name?: string | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryStoreListParams extends PageCursorParams {\n /**\n * Query param: Return only stores whose `created_at` is at or after this time\n * (inclusive). Sent on the wire as `created_at[gte]`.\n */\n 'created_at[gte]'?: string;\n\n /**\n * Query param: Return only stores whose `created_at` is at or before this time\n * (inclusive). Sent on the wire as `created_at[lte]`.\n */\n 'created_at[lte]'?: string;\n\n /**\n * Query param: When `true`, archived stores are included in the results. Defaults\n * to `false` (archived stores are excluded).\n */\n include_archived?: boolean;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryStoreDeleteParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface MemoryStoreArchiveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nMemoryStores.Memories = Memories;\nMemoryStores.MemoryVersions = MemoryVersions;\n\nexport declare namespace MemoryStores {\n export {\n type BetaManagedAgentsDeletedMemoryStore as BetaManagedAgentsDeletedMemoryStore,\n type BetaManagedAgentsMemoryStore as BetaManagedAgentsMemoryStore,\n type BetaManagedAgentsMemoryStoresPageCursor as BetaManagedAgentsMemoryStoresPageCursor,\n type MemoryStoreCreateParams as MemoryStoreCreateParams,\n type MemoryStoreRetrieveParams as MemoryStoreRetrieveParams,\n type MemoryStoreUpdateParams as MemoryStoreUpdateParams,\n type MemoryStoreListParams as MemoryStoreListParams,\n type MemoryStoreDeleteParams as MemoryStoreDeleteParams,\n type MemoryStoreArchiveParams as MemoryStoreArchiveParams,\n };\n\n export {\n Memories as Memories,\n type BetaManagedAgentsConflictError as BetaManagedAgentsConflictError,\n type BetaManagedAgentsContentSha256Precondition as BetaManagedAgentsContentSha256Precondition,\n type BetaManagedAgentsDeletedMemory as BetaManagedAgentsDeletedMemory,\n type BetaManagedAgentsError as BetaManagedAgentsError,\n type BetaManagedAgentsMemory as BetaManagedAgentsMemory,\n type BetaManagedAgentsMemoryListItem as BetaManagedAgentsMemoryListItem,\n type BetaManagedAgentsMemoryPathConflictError as BetaManagedAgentsMemoryPathConflictError,\n type BetaManagedAgentsMemoryPreconditionFailedError as BetaManagedAgentsMemoryPreconditionFailedError,\n type BetaManagedAgentsMemoryPrefix as BetaManagedAgentsMemoryPrefix,\n type BetaManagedAgentsMemoryView as BetaManagedAgentsMemoryView,\n type BetaManagedAgentsPrecondition as BetaManagedAgentsPrecondition,\n type BetaManagedAgentsMemoryListItemsPageCursor as BetaManagedAgentsMemoryListItemsPageCursor,\n type MemoryCreateParams as MemoryCreateParams,\n type MemoryRetrieveParams as MemoryRetrieveParams,\n type MemoryUpdateParams as MemoryUpdateParams,\n type MemoryListParams as MemoryListParams,\n type MemoryDeleteParams as MemoryDeleteParams,\n };\n\n export {\n MemoryVersions as MemoryVersions,\n type BetaManagedAgentsActor as BetaManagedAgentsActor,\n type BetaManagedAgentsAPIActor as BetaManagedAgentsAPIActor,\n type BetaManagedAgentsMemoryVersion as BetaManagedAgentsMemoryVersion,\n type BetaManagedAgentsMemoryVersionOperation as BetaManagedAgentsMemoryVersionOperation,\n type BetaManagedAgentsSessionActor as BetaManagedAgentsSessionActor,\n type BetaManagedAgentsUserActor as BetaManagedAgentsUserActor,\n type BetaManagedAgentsMemoryVersionsPageCursor as BetaManagedAgentsMemoryVersionsPageCursor,\n type MemoryVersionRetrieveParams as MemoryVersionRetrieveParams,\n type MemoryVersionListParams as MemoryVersionListParams,\n type MemoryVersionRedactParams as MemoryVersionRedactParams,\n };\n}\n","import { AnthropicError } from '../../core/error';\nimport { ReadableStreamToAsyncIterable } from '../shims';\nimport { LineDecoder, type Bytes } from './line';\n\nexport class JSONLDecoder<T> {\n controller: AbortController;\n\n constructor(\n private iterator: AsyncIterableIterator<Bytes>,\n controller: AbortController,\n ) {\n this.controller = controller;\n }\n\n private async *decoder(): AsyncIterator<T, any, undefined> {\n const lineDecoder = new LineDecoder();\n for await (const chunk of this.iterator) {\n for (const line of lineDecoder.decode(chunk)) {\n yield JSON.parse(line) as T;\n }\n }\n\n for (const line of lineDecoder.flush()) {\n yield JSON.parse(line) as T;\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this.decoder();\n }\n\n static fromResponse<T>(response: Response, controller: AbortController): JSONLDecoder<T> {\n if (!response.body) {\n controller.abort();\n if (\n typeof (globalThis as any).navigator !== 'undefined' &&\n (globalThis as any).navigator.product === 'ReactNative'\n ) {\n throw new AnthropicError(\n `The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`,\n );\n }\n throw new AnthropicError(`Attempted to iterate over a response with no body`);\n }\n\n return new JSONLDecoder(ReadableStreamToAsyncIterable<Bytes>(response.body), controller);\n }\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport { APIPromise } from '../../../core/api-promise';\nimport * as BetaMessagesAPI from './messages';\nimport { Page, type PageParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { JSONLDecoder } from '../../../internal/decoders/jsonl';\nimport { AnthropicError } from '../../../error';\nimport { path } from '../../../internal/utils/path';\nimport * as MessagesApi from '../../messages/messages';\n\nexport class Batches extends APIResource {\n /**\n * Send a batch of Message creation requests.\n *\n * The Message Batches API can be used to process multiple Messages API requests at\n * once. Once a Message Batch is created, it begins processing immediately. Batches\n * can take up to 24 hours to complete.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaMessageBatch =\n * await client.beta.messages.batches.create({\n * requests: [\n * {\n * custom_id: 'my-custom-id-1',\n * params: {\n * max_tokens: 1024,\n * messages: [\n * { content: 'Hello, world', role: 'user' },\n * ],\n * model: 'claude-opus-4-6',\n * },\n * },\n * ],\n * });\n * ```\n */\n create(params: BatchCreateParams, options?: RequestOptions): APIPromise<BetaMessageBatch> {\n const { betas, user_profile_id, ...body } = params;\n return this._client.post('/v1/messages/batches?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n ...(user_profile_id != null ? { 'anthropic-user-profile-id': user_profile_id } : undefined),\n },\n options?.headers,\n ]),\n });\n }\n\n /**\n * This endpoint is idempotent and can be used to poll for Message Batch\n * completion. To access the results of a Message Batch, make a request to the\n * `results_url` field in the response.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaMessageBatch =\n * await client.beta.messages.batches.retrieve(\n * 'message_batch_id',\n * );\n * ```\n */\n retrieve(\n messageBatchID: string,\n params: BatchRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaMessageBatch> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/messages/batches/${messageBatchID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List all Message Batches within a Workspace. Most recently created batches are\n * returned first.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaMessageBatch of client.beta.messages.batches.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: BatchListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaMessageBatchesPage, BetaMessageBatch> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/messages/batches?beta=true', Page<BetaMessageBatch>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Delete a Message Batch.\n *\n * Message Batches can only be deleted once they've finished processing. If you'd\n * like to delete an in-progress batch, you must first cancel it.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaDeletedMessageBatch =\n * await client.beta.messages.batches.delete(\n * 'message_batch_id',\n * );\n * ```\n */\n delete(\n messageBatchID: string,\n params: BatchDeleteParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaDeletedMessageBatch> {\n const { betas } = params ?? {};\n return this._client.delete(path`/v1/messages/batches/${messageBatchID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Batches may be canceled any time before processing ends. Once cancellation is\n * initiated, the batch enters a `canceling` state, at which time the system may\n * complete any in-progress, non-interruptible requests before finalizing\n * cancellation.\n *\n * The number of canceled requests is specified in `request_counts`. To determine\n * which requests were canceled, check the individual results within the batch.\n * Note that cancellation may not result in any canceled requests if they were\n * non-interruptible.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaMessageBatch =\n * await client.beta.messages.batches.cancel(\n * 'message_batch_id',\n * );\n * ```\n */\n cancel(\n messageBatchID: string,\n params: BatchCancelParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaMessageBatch> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Streams the results of a Message Batch as a `.jsonl` file.\n *\n * Each line in the file is a JSON object containing the result of a single request\n * in the Message Batch. Results are not guaranteed to be in the same order as\n * requests. Use the `custom_id` field to match results to requests.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const betaMessageBatchIndividualResponse =\n * await client.beta.messages.batches.results(\n * 'message_batch_id',\n * );\n * ```\n */\n async results(\n messageBatchID: string,\n params: BatchResultsParams | undefined = {},\n options?: RequestOptions,\n ): Promise<JSONLDecoder<BetaMessageBatchIndividualResponse>> {\n const batch = await this.retrieve(messageBatchID);\n if (!batch.results_url) {\n throw new AnthropicError(\n `No batch \\`results_url\\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`,\n );\n }\n\n const { betas } = params ?? {};\n return this._client\n .get(batch.results_url, {\n ...options,\n headers: buildHeaders([\n {\n 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),\n Accept: 'application/binary',\n },\n options?.headers,\n ]),\n stream: true,\n __binaryResponse: true,\n })\n ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)) as APIPromise<\n JSONLDecoder<BetaMessageBatchIndividualResponse>\n >;\n }\n}\n\nexport type BetaMessageBatchesPage = Page<BetaMessageBatch>;\n\nexport interface BetaDeletedMessageBatch {\n /**\n * ID of the Message Batch.\n */\n id: string;\n\n /**\n * Deleted object type.\n *\n * For Message Batches, this is always `\"message_batch_deleted\"`.\n */\n type: 'message_batch_deleted';\n}\n\nexport interface BetaMessageBatch {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * archived and its results became unavailable.\n */\n archived_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which cancellation was\n * initiated for the Message Batch. Specified only if cancellation was initiated.\n */\n cancel_initiated_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * created.\n */\n created_at: string;\n\n /**\n * RFC 3339 datetime string representing the time at which processing for the\n * Message Batch ended. Specified only once processing ends.\n *\n * Processing ends when every request in a Message Batch has either succeeded,\n * errored, canceled, or expired.\n */\n ended_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch will\n * expire and end processing, which is 24 hours after creation.\n */\n expires_at: string;\n\n /**\n * Processing status of the Message Batch.\n */\n processing_status: 'in_progress' | 'canceling' | 'ended';\n\n /**\n * Tallies requests within the Message Batch, categorized by their status.\n *\n * Requests start as `processing` and move to one of the other statuses only once\n * processing of the entire batch ends. The sum of all values always matches the\n * total number of requests in the batch.\n */\n request_counts: BetaMessageBatchRequestCounts;\n\n /**\n * URL to a `.jsonl` file containing the results of the Message Batch requests.\n * Specified only once processing ends.\n *\n * Results in the file are not guaranteed to be in the same order as requests. Use\n * the `custom_id` field to match results to requests.\n */\n results_url: string | null;\n\n /**\n * Object type.\n *\n * For Message Batches, this is always `\"message_batch\"`.\n */\n type: 'message_batch';\n}\n\nexport interface BetaMessageBatchCanceledResult {\n type: 'canceled';\n}\n\nexport interface BetaMessageBatchErroredResult {\n error: BetaAPI.BetaErrorResponse;\n\n type: 'errored';\n}\n\nexport interface BetaMessageBatchExpiredResult {\n type: 'expired';\n}\n\n/**\n * This is a single line in the response `.jsonl` file and does not represent the\n * response as a whole.\n */\nexport interface BetaMessageBatchIndividualResponse {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\n result: BetaMessageBatchResult;\n}\n\nexport interface BetaMessageBatchRequestCounts {\n /**\n * Number of requests in the Message Batch that have been canceled.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n canceled: number;\n\n /**\n * Number of requests in the Message Batch that encountered an error.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n errored: number;\n\n /**\n * Number of requests in the Message Batch that have expired.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n expired: number;\n\n /**\n * Number of requests in the Message Batch that are processing.\n */\n processing: number;\n\n /**\n * Number of requests in the Message Batch that have completed successfully.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n succeeded: number;\n}\n\n/**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\nexport type BetaMessageBatchResult =\n | BetaMessageBatchSucceededResult\n | BetaMessageBatchErroredResult\n | BetaMessageBatchCanceledResult\n | BetaMessageBatchExpiredResult;\n\nexport interface BetaMessageBatchSucceededResult {\n message: BetaMessagesAPI.BetaMessage;\n\n type: 'succeeded';\n}\n\nexport interface BatchCreateParams {\n /**\n * Body param: List of requests for prompt completion. Each is an individual\n * request to create a Message.\n */\n requests: Array<BatchCreateParams.Request>;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n\n /**\n * Header param: The user profile ID to attribute the requests in this batch to.\n * Use when acting on behalf of a party other than your organization. Requires the\n * `user-profiles` beta header. Applies to every request in the batch; an\n * individual request whose `user_profile_id` body field conflicts with this header\n * is errored.\n */\n user_profile_id?: string;\n}\n\nexport namespace BatchCreateParams {\n export interface Request {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Messages API creation parameters for the individual request.\n *\n * See the [Messages API reference](https://docs.claude.com/en/api/messages) for\n * full documentation on available parameters.\n */\n params: Request.Params;\n }\n\n export namespace Request {\n /**\n * Messages API creation parameters for the individual request.\n *\n * See the [Messages API reference](https://docs.claude.com/en/api/messages) for\n * full documentation on available parameters.\n */\n export interface Params {\n /**\n * The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n *\n * Set to `0` to populate the\n * [prompt cache](https://docs.claude.com/en/docs/build-with-claude/prompt-caching#pre-warming-the-cache)\n * without generating a response.\n *\n * Different models have different maximum values for this parameter. See\n * [models](https://docs.claude.com/en/docs/models-overview) for details.\n */\n max_tokens: number;\n\n /**\n * Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * See [input examples](https://docs.claude.com/en/api/messages-examples).\n *\n * Note that if you want to include a\n * [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the\n * top-level `system` parameter — there is no `\"system\"` role for input messages in\n * the Messages API.\n *\n * There is a limit of 100,000 messages in a single request.\n */\n messages: Array<BetaMessagesAPI.BetaMessageParam>;\n\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesApi.Model;\n\n /**\n * Top-level cache control automatically applies a cache_control marker to the last\n * cacheable block in the request.\n */\n cache_control?: BetaMessagesAPI.BetaCacheControlEphemeral | null;\n\n /**\n * Container identifier for reuse across requests.\n */\n container?: BetaMessagesAPI.BetaContainerParams | string | null;\n\n /**\n * Context management configuration.\n *\n * This allows you to control how Claude manages context across multiple requests,\n * such as whether to clear function results or not.\n */\n context_management?: BetaMessagesAPI.BetaContextManagementConfig | null;\n\n /**\n * Request-level diagnostics. Currently carries the previous response id for\n * prompt-cache divergence reporting.\n */\n diagnostics?: BetaMessagesAPI.BetaDiagnosticsParam | null;\n\n /**\n * The `fallback_credit_token` from a prior refusal's `stop_details`.\n *\n * When a preceding request was refused and returned a `fallback_credit_token`,\n * pass that code here on the retry to have the retry's cache-creation tokens for\n * the prefix that was warm on the refused model billed at the cache-read rate.\n * Must be redeemed by the same organization and workspace, with the same request\n * body (optionally extended by one appended `assistant` message whose content is\n * the partial text — with any trailing whitespace stripped from the final text\n * block — and paired server-tool blocks streamed before the refusal; the\n * appended-assistant form is not available for requests with `output_format` set\n * or forced `tool_choice`), on an eligible fallback model, on the same platform,\n * and within 5 minutes of the refusal; a mismatch is a 400. A token minted\n * mid-server-tool-loop whose partial content was continuable may only be redeemed\n * with the appended-assistant form — if an exact-body retry is rejected with a 400\n * saying the token must be redeemed by continuing the partial response, retry with\n * the appended-assistant form instead.\n *\n * When the appended-assistant form is used on a model that otherwise disallows\n * assistant-turn prefill, this token also authorizes that one prefill.\n */\n fallback_credit_token?: string | null;\n\n /**\n * Opt-in server-side retry on one or more substitute models when the requested\n * model declines for policy reasons. Tried in order: if the first entry also\n * declines, the second is tried, and so on.\n */\n fallbacks?: Array<BetaMessagesAPI.BetaFallbackParam> | null;\n\n /**\n * Specifies the geographic region for inference processing. If not specified, the\n * workspace's `default_inference_geo` is used.\n */\n inference_geo?: string | null;\n\n /**\n * MCP servers to be utilized in this request\n */\n mcp_servers?: Array<BetaMessagesAPI.BetaRequestMCPServerURLDefinition>;\n\n /**\n * An object describing metadata about the request.\n */\n metadata?: BetaMessagesAPI.BetaMetadata;\n\n /**\n * Configuration options for the model's output, such as the output format.\n */\n output_config?: BetaMessagesAPI.BetaOutputConfig;\n\n /**\n * @deprecated Deprecated: Use `output_config.format` instead. See\n * [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)\n *\n * A schema to specify Claude's output format in responses. This parameter will be\n * removed in a future release.\n */\n output_format?: BetaMessagesAPI.BetaJSONOutputFormat | null;\n\n /**\n * Determines whether to use priority capacity (if available) or standard capacity\n * for this request.\n *\n * Anthropic offers different levels of service for your API requests. See\n * [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.\n */\n service_tier?: 'auto' | 'standard_only';\n\n /**\n * The inference speed mode for this request. `\"fast\"` enables high\n * output-tokens-per-second inference.\n */\n speed?: 'standard' | 'fast' | null;\n\n /**\n * Custom text sequences that will cause the model to stop generating.\n *\n * Our models will normally stop when they have naturally completed their turn,\n * which will result in a response `stop_reason` of `\"end_turn\"`.\n *\n * If you want the model to stop generating when it encounters custom strings of\n * text, you can use the `stop_sequences` parameter. If the model encounters one of\n * the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"`\n * and the response `stop_sequence` value will contain the matched stop sequence.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Whether to incrementally stream the response using server-sent events.\n *\n * See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.\n */\n stream?: boolean;\n\n /**\n * System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).\n */\n system?: string | Array<BetaMessagesAPI.BetaTextBlockParam>;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not support\n * setting temperature. A value of 1.0 of will be accepted for backwards\n * compatibility, all other values will be rejected with a 400 error.\n */\n temperature?: number;\n\n /**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: BetaMessagesAPI.BetaThinkingConfigParam;\n\n /**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: BetaMessagesAPI.BetaToolChoice;\n\n /**\n * Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * There are two types of tools: **client tools** and **server tools**. The\n * behavior described below applies to client tools. For\n * [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools),\n * see their individual documentation as each has its own behavior (e.g., the\n * [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.\n */\n tools?: Array<BetaMessagesAPI.BetaToolUnion>;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not accept\n * top_k; any value will be rejected with a 400 error.\n */\n top_k?: number;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not support\n * setting top_p. A value >= 0.99 will be accepted for backwards compatibility, all\n * other values will be rejected with a 400 error.\n */\n top_p?: number;\n }\n }\n}\n\nexport interface BatchRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchListParams extends PageParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchDeleteParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchCancelParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface BatchResultsParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Batches {\n export {\n type BetaDeletedMessageBatch as BetaDeletedMessageBatch,\n type BetaMessageBatch as BetaMessageBatch,\n type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult,\n type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult,\n type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult,\n type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse,\n type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts,\n type BetaMessageBatchResult as BetaMessageBatchResult,\n type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult,\n type BetaMessageBatchesPage as BetaMessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchRetrieveParams as BatchRetrieveParams,\n type BatchListParams as BatchListParams,\n type BatchDeleteParams as BatchDeleteParams,\n type BatchCancelParams as BatchCancelParams,\n type BatchResultsParams as BatchResultsParams,\n };\n}\n","// File containing shared constants\n\n/**\n * Model-specific timeout constraints for non-streaming requests\n */\nexport const MODEL_NONSTREAMING_TOKENS: Record<string, number> = {\n 'claude-opus-4-20250514': 8192,\n 'claude-opus-4-0': 8192,\n 'claude-4-opus-20250514': 8192,\n 'anthropic.claude-opus-4-20250514-v1:0': 8192,\n 'claude-opus-4@20250514': 8192,\n 'claude-opus-4-1-20250805': 8192,\n 'anthropic.claude-opus-4-1-20250805-v1:0': 8192,\n 'claude-opus-4-1@20250805': 8192,\n};\n","import type { Logger } from '../client';\nimport { AnthropicError } from '../core/error';\nimport {\n BetaContentBlock,\n BetaJSONOutputFormat,\n BetaMessage,\n BetaOutputConfig,\n BetaTextBlock,\n MessageCreateParams,\n} from '../resources/beta/messages/messages';\n\n// vendored from typefest just to make things look a bit nicer on hover\ntype Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};\n\ntype AutoParseableBetaOutputConfig = Omit<BetaOutputConfig, 'format'> & {\n format?: BetaJSONOutputFormat | AutoParseableBetaOutputFormat<any> | null;\n};\n\nexport type BetaParseableMessageCreateParams = Simplify<\n Omit<MessageCreateParams, 'output_format' | 'output_config'> & {\n /**\n * @deprecated Use `output_config.format` instead. This parameter will be removed in a future\n * release.\n */\n output_format?: BetaJSONOutputFormat | AutoParseableBetaOutputFormat<any> | null;\n output_config?: AutoParseableBetaOutputConfig | null;\n }\n>;\n\nexport type ExtractParsedContentFromBetaParams<Params extends BetaParseableMessageCreateParams> =\n Params['output_format'] extends AutoParseableBetaOutputFormat<infer P> ? P\n : Params['output_config'] extends { format: AutoParseableBetaOutputFormat<infer P> } ? P\n : null;\n\nexport type AutoParseableBetaOutputFormat<ParsedT> = BetaJSONOutputFormat & {\n parse(content: string): ParsedT;\n};\n\nexport type ParsedBetaMessage<ParsedT> = BetaMessage & {\n content: Array<ParsedBetaContentBlock<ParsedT>>;\n parsed_output: ParsedT | null;\n};\n\nexport type ParsedBetaContentBlock<ParsedT> =\n | (BetaTextBlock & { parsed_output: ParsedT | null })\n | Exclude<BetaContentBlock, BetaTextBlock>;\n\nfunction getOutputFormat(\n params: BetaParseableMessageCreateParams | null,\n): BetaJSONOutputFormat | AutoParseableBetaOutputFormat<any> | null | undefined {\n // Prefer output_format (deprecated) over output_config.format for backward compatibility\n return params?.output_format ?? params?.output_config?.format;\n}\n\nexport function maybeParseBetaMessage<Params extends BetaParseableMessageCreateParams | null>(\n message: BetaMessage,\n params: Params,\n opts: { logger: Logger },\n): ParsedBetaMessage<ExtractParsedContentFromBetaParams<NonNullable<Params>>> {\n const outputFormat = getOutputFormat(params);\n if (!params || !('parse' in (outputFormat ?? {}))) {\n return {\n ...message,\n content: message.content.map((block) => {\n if (block.type === 'text') {\n const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {\n value: null,\n enumerable: false,\n }) as ParsedBetaContentBlock<ExtractParsedContentFromBetaParams<NonNullable<Params>>>;\n\n return Object.defineProperty(parsedBlock, 'parsed', {\n get() {\n opts.logger.warn(\n 'The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.',\n );\n return null;\n },\n enumerable: false,\n });\n }\n return block;\n }),\n parsed_output: null,\n } as ParsedBetaMessage<ExtractParsedContentFromBetaParams<NonNullable<Params>>>;\n }\n\n return parseBetaMessage(message, params, opts);\n}\n\nexport function parseBetaMessage<Params extends BetaParseableMessageCreateParams>(\n message: BetaMessage,\n params: Params,\n opts: { logger: Logger },\n): ParsedBetaMessage<ExtractParsedContentFromBetaParams<Params>> {\n let firstParsedOutput: ReturnType<typeof parseBetaOutputFormat<Params>> | null = null;\n\n const content: Array<ParsedBetaContentBlock<ExtractParsedContentFromBetaParams<Params>>> =\n message.content.map((block) => {\n if (block.type === 'text') {\n const parsedOutput = parseBetaOutputFormat(params, block.text);\n\n if (firstParsedOutput === null) {\n firstParsedOutput = parsedOutput;\n }\n\n const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {\n value: parsedOutput,\n enumerable: false,\n }) as ParsedBetaContentBlock<ExtractParsedContentFromBetaParams<Params>>;\n return Object.defineProperty(parsedBlock, 'parsed', {\n get() {\n opts.logger.warn(\n 'The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.',\n );\n return parsedOutput;\n },\n enumerable: false,\n });\n }\n return block;\n });\n\n return {\n ...message,\n content,\n parsed_output: firstParsedOutput,\n } as ParsedBetaMessage<ExtractParsedContentFromBetaParams<Params>>;\n}\n\nfunction parseBetaOutputFormat<Params extends BetaParseableMessageCreateParams>(\n params: Params,\n content: string,\n): ExtractParsedContentFromBetaParams<Params> | null {\n const outputFormat = getOutputFormat(params);\n if (outputFormat?.type !== 'json_schema') {\n return null;\n }\n\n try {\n if ('parse' in outputFormat) {\n return outputFormat.parse(content);\n }\n\n return JSON.parse(content);\n } catch (error) {\n throw new AnthropicError(`Failed to parse structured output: ${error}`);\n }\n}\n","type Token = {\n type: string;\n value: string;\n};\n\nconst tokenize = (input: string): Token[] => {\n let current = 0;\n let tokens: Token[] = [];\n\n while (current < input.length) {\n let char = input[current];\n\n if (char === '\\\\') {\n current++;\n continue;\n }\n\n if (char === '{') {\n tokens.push({\n type: 'brace',\n value: '{',\n });\n\n current++;\n continue;\n }\n\n if (char === '}') {\n tokens.push({\n type: 'brace',\n value: '}',\n });\n\n current++;\n continue;\n }\n\n if (char === '[') {\n tokens.push({\n type: 'paren',\n value: '[',\n });\n\n current++;\n continue;\n }\n\n if (char === ']') {\n tokens.push({\n type: 'paren',\n value: ']',\n });\n\n current++;\n continue;\n }\n\n if (char === ':') {\n tokens.push({\n type: 'separator',\n value: ':',\n });\n\n current++;\n continue;\n }\n\n if (char === ',') {\n tokens.push({\n type: 'delimiter',\n value: ',',\n });\n\n current++;\n continue;\n }\n\n if (char === '\"') {\n let value = '';\n let danglingQuote = false;\n\n char = input[++current];\n\n while (char !== '\"') {\n if (current === input.length) {\n danglingQuote = true;\n break;\n }\n\n if (char === '\\\\') {\n current++;\n if (current === input.length) {\n danglingQuote = true;\n break;\n }\n value += char + input[current];\n char = input[++current];\n } else {\n value += char;\n char = input[++current];\n }\n }\n\n char = input[++current];\n\n if (!danglingQuote) {\n tokens.push({\n type: 'string',\n value,\n });\n }\n continue;\n }\n\n let WHITESPACE = /\\s/;\n if (char && WHITESPACE.test(char)) {\n current++;\n continue;\n }\n\n let NUMBERS = /[0-9]/;\n if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {\n let value = '';\n\n if (char === '-') {\n value += char;\n char = input[++current];\n }\n\n while (\n char &&\n (NUMBERS.test(char) ||\n char === '.' ||\n // exponent marker, e.g. `1e10` or `1.5E-9`\n char === 'e' ||\n char === 'E' ||\n // exponent sign, only valid immediately after the exponent marker\n ((char === '-' || char === '+') &&\n (value[value.length - 1] === 'e' || value[value.length - 1] === 'E')))\n ) {\n value += char;\n char = input[++current];\n }\n\n tokens.push({\n type: 'number',\n value,\n });\n continue;\n }\n\n let LETTERS = /[a-z]/i;\n if (char && LETTERS.test(char)) {\n let value = '';\n\n while (char && LETTERS.test(char)) {\n if (current === input.length) {\n break;\n }\n value += char;\n char = input[++current];\n }\n\n if (value == 'true' || value == 'false' || value === 'null') {\n tokens.push({\n type: 'name',\n value,\n });\n } else {\n // unknown token, e.g. `nul` which isn't quite `null`\n current++;\n continue;\n }\n continue;\n }\n\n current++;\n }\n\n return tokens;\n },\n strip = (tokens: Token[]): Token[] => {\n if (tokens.length === 0) {\n return tokens;\n }\n\n let lastToken = tokens[tokens.length - 1]!;\n\n switch (lastToken.type) {\n case 'separator':\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n break;\n case 'number':\n let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];\n if (\n lastCharacterOfLastToken === '.' ||\n lastCharacterOfLastToken === '-' ||\n lastCharacterOfLastToken === '+' ||\n lastCharacterOfLastToken === 'e' ||\n lastCharacterOfLastToken === 'E'\n ) {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n }\n case 'string':\n let tokenBeforeTheLastToken = tokens[tokens.length - 2];\n if (tokenBeforeTheLastToken?.type === 'delimiter') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n } else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n }\n break;\n case 'delimiter':\n tokens = tokens.slice(0, tokens.length - 1);\n return strip(tokens);\n break;\n }\n\n return tokens;\n },\n unstrip = (tokens: Token[]): Token[] => {\n let tail: string[] = [];\n\n tokens.map((token) => {\n if (token.type === 'brace') {\n if (token.value === '{') {\n tail.push('}');\n } else {\n tail.splice(tail.lastIndexOf('}'), 1);\n }\n }\n if (token.type === 'paren') {\n if (token.value === '[') {\n tail.push(']');\n } else {\n tail.splice(tail.lastIndexOf(']'), 1);\n }\n }\n });\n\n if (tail.length > 0) {\n tail.reverse().map((item) => {\n if (item === '}') {\n tokens.push({\n type: 'brace',\n value: '}',\n });\n } else if (item === ']') {\n tokens.push({\n type: 'paren',\n value: ']',\n });\n }\n });\n }\n\n return tokens;\n },\n generate = (tokens: Token[]): string => {\n let output = '';\n\n tokens.map((token) => {\n switch (token.type) {\n case 'string':\n output += '\"' + token.value + '\"';\n break;\n default:\n output += token.value;\n break;\n }\n });\n\n return output;\n },\n partialParse = (input: string): unknown => JSON.parse(generate(unstrip(strip(tokenize(input)))));\n\nexport { partialParse };\n","import { partialParse } from '../_vendor/partial-json-parser/parser';\n\nexport const JSON_BUF_PROPERTY = '__json_buf';\n\n/**\n * Copies a tool-use block with an updated `__json_buf`, installing `.input` as\n * a memoized getter so the partial-JSON parse happens on first read instead of\n * on every delta.\n */\nexport function withLazyInput<T extends { input: unknown }>(prev: T, jsonBuf: string): T {\n const next = {} as T;\n for (const key of Object.keys(prev) as (keyof T)[]) {\n if (key !== 'input') next[key] = prev[key];\n }\n Object.defineProperty(next, JSON_BUF_PROPERTY, { value: jsonBuf, enumerable: false, writable: true });\n let input: unknown;\n let parsed = false;\n Object.defineProperty(next, 'input', {\n enumerable: true,\n configurable: true,\n get() {\n if (!parsed) {\n input = jsonBuf ? partialParse(jsonBuf) : {};\n parsed = true;\n }\n return input;\n },\n });\n return next;\n}\n","import { STAINLESS_HELPER_METHOD_HEADER } from '../internal/stainless-helper-header';\nimport type { Logger } from '../client';\nimport { AnthropicError, APIUserAbortError } from '../error';\nimport { isAbortError } from '../internal/errors';\nimport { type RequestOptions } from '../internal/request-options';\nimport {\n type BetaContentBlock,\n type BetaMCPToolUseBlock,\n type BetaMessage,\n type BetaMessageParam,\n Messages as BetaMessages,\n type BetaRawMessageStreamEvent as BetaMessageStreamEvent,\n type BetaServerToolUseBlock,\n type BetaTextBlock,\n type BetaTextCitation,\n type BetaToolUseBlock,\n type MessageCreateParams,\n type MessageCreateParamsBase,\n MessageCreateParamsStreaming,\n} from '../resources/beta/messages/messages';\nimport { Stream } from '../streaming';\nimport { maybeParseBetaMessage, type ParsedBetaMessage } from './beta-parser';\nimport { JSON_BUF_PROPERTY, withLazyInput } from '../internal/message-stream-utils';\n\nexport interface MessageStreamEvents {\n connect: () => void;\n streamEvent: (event: BetaMessageStreamEvent, snapshot: BetaMessage) => void;\n text: (textDelta: string, textSnapshot: string) => void;\n citation: (citation: BetaTextCitation, citationsSnapshot: BetaTextCitation[]) => void;\n inputJson: (partialJson: string, jsonSnapshot: unknown) => void;\n thinking: (thinkingDelta: string, thinkingSnapshot: string) => void;\n signature: (signature: string) => void;\n compaction: (compactedContent: string) => void;\n message: (message: BetaMessage) => void;\n contentBlock: (content: BetaContentBlock) => void;\n finalMessage: (message: BetaMessage) => void;\n error: (error: AnthropicError) => void;\n abort: (error: APIUserAbortError) => void;\n end: () => void;\n}\n\ntype MessageStreamEventListeners<Event extends keyof MessageStreamEvents> = {\n listener: MessageStreamEvents[Event];\n once?: boolean;\n}[];\n\nexport type TracksToolInput = BetaToolUseBlock | BetaServerToolUseBlock | BetaMCPToolUseBlock;\n\nfunction tracksToolInput(content: BetaContentBlock): content is TracksToolInput {\n return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use';\n}\n\nexport class BetaMessageStream<ParsedT = null> implements AsyncIterable<BetaMessageStreamEvent> {\n messages: BetaMessageParam[] = [];\n receivedMessages: ParsedBetaMessage<ParsedT>[] = [];\n #currentMessageSnapshot: BetaMessage | undefined;\n #params: MessageCreateParams | null = null;\n\n controller: AbortController = new AbortController();\n\n #connectedPromise: Promise<Response | null>;\n #resolveConnectedPromise: (response: Response | null) => void = () => {};\n #rejectConnectedPromise: (error: AnthropicError) => void = () => {};\n\n #endPromise: Promise<void>;\n #resolveEndPromise: () => void = () => {};\n #rejectEndPromise: (error: AnthropicError) => void = () => {};\n\n #listeners: { [Event in keyof MessageStreamEvents]?: MessageStreamEventListeners<Event> } = {};\n\n #ended = false;\n #errored = false;\n #aborted = false;\n #catchingPromiseCreated = false;\n #response: Response | null | undefined;\n #request_id: string | null | undefined;\n #logger: Logger;\n\n constructor(params: MessageCreateParamsBase | null, opts?: { logger?: Logger | undefined }) {\n this.#connectedPromise = new Promise<Response | null>((resolve, reject) => {\n this.#resolveConnectedPromise = resolve;\n this.#rejectConnectedPromise = reject;\n });\n\n this.#endPromise = new Promise<void>((resolve, reject) => {\n this.#resolveEndPromise = resolve;\n this.#rejectEndPromise = reject;\n });\n\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n this.#connectedPromise.catch(() => {});\n this.#endPromise.catch(() => {});\n\n this.#params = params;\n this.#logger = opts?.logger ?? console;\n }\n\n get response(): Response | null | undefined {\n return this.#response;\n }\n\n get request_id(): string | null | undefined {\n return this.#request_id;\n }\n\n /**\n * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * This is the same as the `APIPromise.withResponse()` method.\n *\n * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`\n * as no `Response` is available.\n */\n async withResponse(): Promise<{\n data: BetaMessageStream<ParsedT>;\n response: Response;\n request_id: string | null | undefined;\n }> {\n this.#catchingPromiseCreated = true;\n\n const response = await this.#connectedPromise;\n if (!response) {\n throw new Error('Could not resolve a `Response` object');\n }\n\n return {\n data: this,\n response,\n request_id: response.headers.get('request-id'),\n };\n }\n\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream: ReadableStream): BetaMessageStream {\n const runner = new BetaMessageStream(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n\n static createMessage<ParsedT>(\n messages: BetaMessages,\n params: MessageCreateParamsBase,\n options?: RequestOptions,\n { logger }: { logger?: Logger | undefined } = {},\n ): BetaMessageStream<ParsedT> {\n const runner = new BetaMessageStream<ParsedT>(params as MessageCreateParamsStreaming, { logger });\n for (const message of params.messages) {\n runner._addMessageParam(message);\n }\n runner.#params = { ...params, stream: true };\n runner._run(() =>\n runner._createMessage(\n messages,\n { ...params, stream: true },\n { ...options, headers: { ...options?.headers, [STAINLESS_HELPER_METHOD_HEADER]: 'stream' } },\n ),\n );\n return runner;\n }\n\n protected _run(executor: () => Promise<any>) {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, this.#handleError);\n }\n\n protected _addMessageParam(message: BetaMessageParam) {\n this.messages.push(message);\n }\n\n protected _addMessage(message: ParsedBetaMessage<ParsedT>, emit = true) {\n this.receivedMessages.push(message);\n if (emit) {\n this._emit('message', message);\n }\n }\n\n protected async _createMessage(\n messages: BetaMessages,\n params: MessageCreateParams,\n options?: RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n let abortHandler: (() => void) | undefined;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n abortHandler = this.controller.abort.bind(this.controller);\n signal.addEventListener('abort', abortHandler);\n }\n try {\n this.#beginRequest();\n const { response, data: stream } = await messages\n .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })\n .withResponse();\n this._connected(response);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n } finally {\n if (signal && abortHandler) {\n signal.removeEventListener('abort', abortHandler);\n }\n }\n }\n\n protected _connected(response: Response | null) {\n if (this.ended) return;\n this.#response = response;\n this.#request_id = response?.headers.get('request-id');\n this.#resolveConnectedPromise(response);\n this._emit('connect');\n }\n\n get ended(): boolean {\n return this.#ended;\n }\n\n get errored(): boolean {\n return this.#errored;\n }\n\n get aborted(): boolean {\n return this.#aborted;\n }\n\n abort() {\n this.controller.abort();\n }\n\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this MessageStream, so that calls can be chained\n */\n on<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener });\n return this;\n }\n\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this MessageStream, so that calls can be chained\n */\n off<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners = this.#listeners[event];\n if (!listeners) return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0) listeners.splice(index, 1);\n return this;\n }\n\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this MessageStream, so that calls can be chained\n */\n once<Event extends keyof MessageStreamEvents>(event: Event, listener: MessageStreamEvents[Event]): this {\n const listeners: MessageStreamEventListeners<Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted<Event extends keyof MessageStreamEvents>(\n event: Event,\n ): Promise<\n Parameters<MessageStreamEvents[Event]> extends [infer Param] ? Param\n : Parameters<MessageStreamEvents[Event]> extends [] ? void\n : Parameters<MessageStreamEvents[Event]>\n > {\n return new Promise((resolve, reject) => {\n this.#catchingPromiseCreated = true;\n if (event !== 'error') this.once('error', reject);\n this.once(event, resolve as any);\n });\n }\n\n async done(): Promise<void> {\n this.#catchingPromiseCreated = true;\n await this.#endPromise;\n }\n\n get currentMessage(): BetaMessage | undefined {\n return this.#currentMessageSnapshot;\n }\n\n #getFinalMessage(): ParsedBetaMessage<ParsedT> {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n return this.receivedMessages.at(-1)!;\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message response,\n * or rejects if an error occurred or the stream ended prematurely without producing a Message.\n * If structured outputs were used, this will be a ParsedMessage with a `parsed` field.\n */\n async finalMessage(): Promise<ParsedBetaMessage<ParsedT>> {\n await this.done();\n return this.#getFinalMessage();\n }\n\n #getFinalText(): string {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n const textBlocks = this.receivedMessages\n .at(-1)!\n .content.filter((block): block is BetaTextBlock => block.type === 'text')\n .map((block) => block.text);\n if (textBlocks.length === 0) {\n throw new AnthropicError('stream ended without producing a content block with type=text');\n }\n return textBlocks.join(' ');\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message's text response, concatenated\n * together if there are more than one text blocks.\n * Rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalText(): Promise<string> {\n await this.done();\n return this.#getFinalText();\n }\n\n #handleError = (error: unknown) => {\n this.#errored = true;\n if (isAbortError(error)) {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n this.#aborted = true;\n return this._emit('abort', error);\n }\n if (error instanceof AnthropicError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const anthropicError: AnthropicError = new AnthropicError(error.message);\n // @ts-ignore\n anthropicError.cause = error;\n return this._emit('error', anthropicError);\n }\n return this._emit('error', new AnthropicError(String(error)));\n };\n\n protected _emit<Event extends keyof MessageStreamEvents>(\n event: Event,\n ...args: Parameters<MessageStreamEvents[Event]>\n ) {\n // make sure we don't emit any MessageStreamEvents after end\n if (this.#ended) return;\n\n if (event === 'end') {\n this.#ended = true;\n this.#resolveEndPromise();\n }\n\n const listeners: MessageStreamEventListeners<Event> | undefined = this.#listeners[event];\n if (listeners) {\n this.#listeners[event] = listeners.filter((l) => !l.once) as any;\n listeners.forEach(({ listener }: any) => listener(...args));\n }\n\n if (event === 'abort') {\n const error = args[0] as APIUserAbortError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n return;\n }\n\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n\n const error = args[0] as AnthropicError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.final...()\n // - etc.\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n }\n }\n\n protected _emitFinal() {\n const finalMessage = this.receivedMessages.at(-1);\n if (finalMessage) {\n this._emit('finalMessage', this.#getFinalMessage());\n }\n }\n\n #beginRequest() {\n if (this.ended) return;\n this.#currentMessageSnapshot = undefined;\n }\n #addStreamEvent(event: BetaMessageStreamEvent) {\n if (this.ended) return;\n const messageSnapshot = this.#accumulateMessage(event);\n this._emit('streamEvent', event, messageSnapshot);\n\n switch (event.type) {\n case 'content_block_delta': {\n const content = messageSnapshot.content.at(-1)!;\n switch (event.delta.type) {\n case 'text_delta': {\n if (content.type === 'text') {\n this._emit('text', event.delta.text, content.text || '');\n }\n break;\n }\n case 'citations_delta': {\n if (content.type === 'text') {\n this._emit('citation', event.delta.citation, content.citations ?? []);\n }\n break;\n }\n case 'input_json_delta': {\n if (tracksToolInput(content) && this.#listeners.inputJson?.length) {\n let jsonSnapshot: unknown;\n try {\n jsonSnapshot = content.input;\n } catch (err) {\n this.#handleError(this.#toolInputParseError(content, err));\n break;\n }\n this._emit('inputJson', event.delta.partial_json, jsonSnapshot);\n }\n break;\n }\n case 'thinking_delta': {\n if (content.type === 'thinking') {\n this._emit('thinking', event.delta.thinking, content.thinking);\n }\n break;\n }\n case 'signature_delta': {\n if (content.type === 'thinking') {\n this._emit('signature', content.signature);\n }\n break;\n }\n case 'compaction_delta': {\n if (content.type === 'compaction' && content.content) {\n this._emit('compaction', content.content);\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n break;\n }\n case 'message_stop': {\n this._addMessageParam(messageSnapshot);\n this._addMessage(\n maybeParseBetaMessage(messageSnapshot, this.#params, { logger: this.#logger }),\n true,\n );\n break;\n }\n case 'content_block_stop': {\n this._emit('contentBlock', messageSnapshot.content.at(-1)!);\n break;\n }\n case 'message_start': {\n this.#currentMessageSnapshot = messageSnapshot;\n break;\n }\n case 'content_block_start':\n case 'message_delta':\n break;\n }\n }\n #endRequest(): ParsedBetaMessage<ParsedT> {\n if (this.ended) {\n throw new AnthropicError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = this.#currentMessageSnapshot;\n if (!snapshot) {\n throw new AnthropicError(`request ended without sending any chunks`);\n }\n this.#currentMessageSnapshot = undefined;\n return maybeParseBetaMessage(snapshot, this.#params, { logger: this.#logger });\n }\n\n protected async _fromReadableStream(\n readableStream: ReadableStream,\n options?: RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n let abortHandler: (() => void) | undefined;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n abortHandler = this.controller.abort.bind(this.controller);\n signal.addEventListener('abort', abortHandler);\n }\n try {\n this.#beginRequest();\n this._connected(null);\n const stream = Stream.fromReadableStream<BetaMessageStreamEvent>(readableStream, this.controller);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n } finally {\n if (signal && abortHandler) {\n signal.removeEventListener('abort', abortHandler);\n }\n }\n }\n\n /**\n * Mutates this.#currentMessage with the current event. Handling the accumulation of multiple messages\n * will be needed to be handled by the caller, this method will throw if you try to accumulate for multiple\n * messages.\n */\n #accumulateMessage(event: BetaMessageStreamEvent): BetaMessage {\n let snapshot = this.#currentMessageSnapshot;\n\n if (event.type === 'message_start') {\n if (snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving \"message_stop\"`);\n }\n return event.message;\n }\n\n if (!snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before \"message_start\"`);\n }\n\n switch (event.type) {\n case 'message_stop':\n return snapshot;\n case 'message_delta':\n snapshot.container = event.delta.container;\n snapshot.stop_reason = event.delta.stop_reason;\n snapshot.stop_sequence = event.delta.stop_sequence;\n if (event.delta.stop_details != null) {\n snapshot.stop_details = event.delta.stop_details;\n }\n snapshot.usage.output_tokens = event.usage.output_tokens;\n snapshot.context_management = event.context_management;\n\n if (event.usage.input_tokens != null) {\n snapshot.usage.input_tokens = event.usage.input_tokens;\n }\n\n if (event.usage.cache_creation_input_tokens != null) {\n snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;\n }\n\n if (event.usage.cache_read_input_tokens != null) {\n snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;\n }\n\n if (event.usage.server_tool_use != null) {\n snapshot.usage.server_tool_use = event.usage.server_tool_use;\n }\n\n if (event.usage.iterations != null) {\n snapshot.usage.iterations = event.usage.iterations;\n }\n\n return snapshot;\n case 'content_block_start':\n snapshot.content.push(event.content_block);\n if (event.content_block.type === 'fallback') {\n // the final hop's fallback block names the model that served the response —\n // keeps the snapshot consistent with the relabeled non-streaming message\n snapshot.model = event.content_block.to.model;\n }\n return snapshot;\n case 'content_block_delta': {\n const snapshotContent = snapshot.content.at(event.index);\n\n switch (event.delta.type) {\n case 'text_delta': {\n if (snapshotContent?.type === 'text') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n text: (snapshotContent.text || '') + event.delta.text,\n };\n }\n break;\n }\n case 'citations_delta': {\n if (snapshotContent?.type === 'text') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n citations: [...(snapshotContent.citations ?? []), event.delta.citation],\n };\n }\n break;\n }\n case 'input_json_delta': {\n if (snapshotContent && tracksToolInput(snapshotContent)) {\n const jsonBuf = ((snapshotContent as any)[JSON_BUF_PROPERTY] || '') + event.delta.partial_json;\n snapshot.content[event.index] = withLazyInput(snapshotContent, jsonBuf);\n }\n break;\n }\n case 'thinking_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n thinking: snapshotContent.thinking + event.delta.thinking,\n };\n }\n break;\n }\n case 'signature_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n signature: event.delta.signature,\n };\n }\n break;\n }\n case 'compaction_delta': {\n if (snapshotContent?.type === 'compaction') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n content: (snapshotContent.content || '') + event.delta.content,\n encrypted_content: event.delta.encrypted_content,\n };\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n return snapshot;\n }\n case 'content_block_stop': {\n const snapshotContent = snapshot.content.at(event.index);\n if (snapshotContent && tracksToolInput(snapshotContent) && JSON_BUF_PROPERTY in snapshotContent) {\n let input: unknown;\n try {\n input = snapshotContent.input;\n } catch (err) {\n input = {};\n this.#handleError(this.#toolInputParseError(snapshotContent, err));\n }\n Object.defineProperty(snapshotContent, 'input', {\n value: input,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return snapshot;\n }\n }\n }\n\n #toolInputParseError(block: TracksToolInput, err: unknown): AnthropicError {\n const jsonBuf = (block as any)[JSON_BUF_PROPERTY];\n return new AnthropicError(\n `Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`,\n );\n }\n\n [Symbol.asyncIterator](): AsyncIterator<BetaMessageStreamEvent> {\n const pushQueue: BetaMessageStreamEvent[] = [];\n const readQueue: {\n resolve: (chunk: BetaMessageStreamEvent | undefined) => void;\n reject: (error: unknown) => void;\n }[] = [];\n let done = false;\n\n this.on('streamEvent', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n } else {\n pushQueue.push(event);\n }\n });\n\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n return {\n next: async (): Promise<IteratorResult<BetaMessageStreamEvent>> => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise<BetaMessageStreamEvent | undefined>((resolve, reject) =>\n readQueue.push({ resolve, reject }),\n ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift()!;\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n\n toReadableStream(): ReadableStream {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\n\n// used to ensure exhaustive case matching without throwing a runtime error\nfunction checkNever(x: never) {}\n","import { Model } from '../../resources';\n\nexport const DEFAULT_TOKEN_THRESHOLD = 100_000;\n\nexport const DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:\n1. Task Overview\nThe user's core request and success criteria\nAny clarifications or constraints they specified\n2. Current State\nWhat has been completed so far\nFiles created, modified, or analyzed (with paths if relevant)\nKey outputs or artifacts produced\n3. Important Discoveries\nTechnical constraints or requirements uncovered\nDecisions made and their rationale\nErrors encountered and how they were resolved\nWhat approaches were tried that didn't work (and why)\n4. Next Steps\nSpecific actions needed to complete the task\nAny blockers or open questions to resolve\nPriority order if multiple steps remain\n5. Context to Preserve\nUser preferences or style requirements\nDomain-specific details that aren't obvious\nAny promises made to the user\nBe concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.\nWrap your summary in <summary></summary> tags.`;\n\n/**\n * @deprecated Use server-side compaction instead by passing\n * `edits: [{ type: 'compact_20260112' }]` in the params passed to `toolRunner()`.\n * See https://platform.claude.com/docs/en/build-with-claude/compaction\n */\nexport interface CompactionControl {\n /**\n * The context token threshold at which to trigger compaction.\n *\n * When the cumulative token count (input + output) across all messages exceeds this threshold,\n * the message history will be automatically summarized and compressed.\n *\n * @default 100000\n */\n contextTokenThreshold?: number;\n\n /**\n * The model to use for generating the compaction summary.\n * If not specified, defaults to the same model used for the tool runner.\n */\n model?: Model;\n\n /**\n * The prompt used to instruct the model on how to generate the summary.\n */\n summaryPrompt?: string;\n\n enabled: boolean;\n}\n","import { BetaRunnableTool } from './BetaRunnableTool';\nimport { ToolError } from './ToolError';\nimport { Anthropic } from '../..';\nimport { AnthropicError } from '../../core/error';\nimport { BetaMessage, BetaMessageParam, BetaToolUnion, MessageCreateParams } from '../../resources/beta';\nimport { BetaMessageStream } from '../BetaMessageStream';\nimport { RequestOptions } from '../../internal/request-options';\nimport { buildHeaders } from '../../internal/headers';\nimport { promiseWithResolvers } from '../../internal/utils/promise';\nimport { CompactionControl, DEFAULT_SUMMARY_PROMPT, DEFAULT_TOKEN_THRESHOLD } from './CompactionControl';\nimport {\n collectStainlessHelpers,\n helperHeader,\n STAINLESS_HELPER_HEADER,\n} from '../../internal/stainless-helper-header';\n\n/**\n * A ToolRunner handles the automatic conversation loop between the assistant and tools.\n *\n * A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects\n * depending on the streaming configuration.\n */\nexport class BetaToolRunner<Stream extends boolean> {\n /** Whether the async iterator has been consumed */\n #consumed = false;\n /** Whether parameters have been mutated since the last API call */\n #mutated = false;\n /** Current state containing the request parameters */\n #state: { params: BetaToolRunnerParams };\n #options: BetaToolRunnerRequestOptions;\n /** Promise for the last message received from the assistant */\n #message?: Promise<BetaMessage> | undefined;\n /** Cached tool response to avoid redundant executions */\n #toolResponse?: Promise<BetaMessageParam | null> | undefined;\n /** Promise resolvers for waiting on completion */\n #completion: {\n promise: Promise<BetaMessage>;\n resolve: (value: BetaMessage) => void;\n reject: (reason?: any) => void;\n };\n /** Number of iterations (API requests) made so far */\n #iterationCount = 0;\n\n constructor(\n private client: Anthropic,\n params: BetaToolRunnerParams,\n options?: BetaToolRunnerRequestOptions,\n ) {\n this.#state = {\n params: {\n // You can't clone the entire params since there are functions as handlers.\n // You also don't really need to clone params.messages, but it probably will prevent a foot gun\n // somewhere.\n ...params,\n messages: structuredClone(params.messages),\n },\n };\n\n // structuredClone drops symbol-keyed properties, so collect helper marks\n // from the original params here — the create()-side collector won't see\n // them on the cloned messages.\n const collected = collectStainlessHelpers(params.tools, params.messages);\n this.#options = {\n ...options,\n headers: buildHeaders([\n helperHeader('BetaToolRunner'),\n collected.length ? { [STAINLESS_HELPER_HEADER]: collected.join(', ') } : undefined,\n options?.headers,\n ]),\n };\n this.#completion = promiseWithResolvers();\n\n if (params.compactionControl?.enabled) {\n console.warn(\n 'Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. ' +\n 'Use server-side compaction instead by passing `edits: [{ type: \"compact_20260112\" }]` in the params passed to `toolRunner()`. ' +\n 'See https://platform.claude.com/docs/en/build-with-claude/compaction',\n );\n }\n }\n\n async #checkAndCompact(): Promise<boolean> {\n const compactionControl = this.#state.params.compactionControl;\n if (!compactionControl || !compactionControl.enabled) {\n return false;\n }\n\n let tokensUsed = 0;\n if (this.#message !== undefined) {\n try {\n const message = await this.#message;\n const totalInputTokens =\n message.usage.input_tokens +\n (message.usage.cache_creation_input_tokens ?? 0) +\n (message.usage.cache_read_input_tokens ?? 0);\n tokensUsed = totalInputTokens + message.usage.output_tokens;\n } catch {\n // If we can't get the message, skip compaction\n return false;\n }\n }\n\n const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD;\n\n if (tokensUsed < threshold) {\n return false;\n }\n\n const model = compactionControl.model ?? this.#state.params.model;\n const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT;\n\n const messages = this.#state.params.messages;\n\n if (messages[messages.length - 1]!.role === 'assistant') {\n // Remove tool_use blocks from the last message to avoid 400 error\n // (tool_use requires tool_result, which we don't have yet)\n const lastMessage = messages[messages.length - 1]!;\n if (Array.isArray(lastMessage.content)) {\n const nonToolBlocks = lastMessage.content.filter((block) => block.type !== 'tool_use');\n\n if (nonToolBlocks.length === 0) {\n // If all blocks were tool_use, just remove the message entirely\n messages.pop();\n } else {\n lastMessage.content = nonToolBlocks;\n }\n }\n }\n\n const response = await this.client.beta.messages.create(\n {\n model,\n messages: [\n ...messages,\n {\n role: 'user',\n content: [\n {\n type: 'text',\n text: summaryPrompt,\n },\n ],\n },\n ],\n max_tokens: this.#state.params.max_tokens,\n },\n {\n signal: this.#options.signal,\n headers: buildHeaders([this.#options.headers, helperHeader('compaction')]),\n },\n );\n\n if (response.content[0]?.type !== 'text') {\n throw new AnthropicError('Expected text response for compaction');\n }\n this.#state.params.messages = [\n {\n role: 'user',\n content: response.content,\n },\n ];\n return true;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<\n Stream extends true ? BetaMessageStream\n : Stream extends false ? BetaMessage\n : BetaMessage | BetaMessageStream\n > {\n if (this.#consumed) {\n throw new AnthropicError('Cannot iterate over a consumed stream');\n }\n\n this.#consumed = true;\n this.#mutated = true;\n this.#toolResponse = undefined;\n\n try {\n while (true) {\n let stream;\n try {\n if (\n this.#state.params.max_iterations &&\n this.#iterationCount >= this.#state.params.max_iterations\n ) {\n break;\n }\n\n this.#mutated = false;\n this.#toolResponse = undefined;\n this.#iterationCount++;\n this.#message = undefined;\n\n const { max_iterations, compactionControl, ...params } = this.#state.params;\n\n if (params.stream) {\n stream = this.client.beta.messages.stream({ ...params }, this.#options);\n this.#message = stream.finalMessage();\n // Make sure that this promise doesn't throw before we get the option to do something about it.\n // Error will be caught when we call await this.#message ultimately\n this.#message.catch(() => {});\n yield stream as any;\n } else {\n this.#message = this.client.beta.messages.create({ ...params, stream: false }, this.#options);\n yield this.#message as any;\n }\n\n const isCompacted = await this.#checkAndCompact();\n if (!isCompacted) {\n if (!this.#mutated) {\n const message = await this.#message;\n this.#state.params.messages.push({ role: message.role, content: message.content });\n\n // Refusal-terminated turns are terminal: the refusal may have cut a tool_use off\n // with partial input, so executing this turn's tools would fire side effects the\n // model never confirmed — and once middleware strips the refusal turn, their\n // tool_results could never be replayed coherently. Surface the refusal as the\n // final message instead.\n if (message.stop_reason === 'refusal') {\n break;\n }\n }\n\n const toolMessage = await this.#generateToolResponse(this.#state.params.messages.at(-1)!);\n if (toolMessage) {\n this.#state.params.messages.push(toolMessage);\n } else if (!this.#mutated) {\n break;\n }\n }\n } finally {\n if (stream) {\n stream.abort();\n }\n }\n }\n\n if (!this.#message) {\n throw new AnthropicError('ToolRunner concluded without a message from the server');\n }\n\n this.#completion.resolve(await this.#message);\n } catch (error) {\n this.#consumed = false;\n // Silence unhandled promise errors\n this.#completion.promise.catch(() => {});\n this.#completion.reject(error);\n this.#completion = promiseWithResolvers();\n throw error;\n }\n }\n\n /**\n * Update the parameters for the next API call. This invalidates any cached tool responses.\n *\n * @param paramsOrMutator - Either new parameters or a function to mutate existing parameters\n *\n * @example\n * // Direct parameter update\n * runner.setMessagesParams({\n * model: 'claude-haiku-4-5',\n * max_tokens: 500,\n * });\n *\n * @example\n * // Using a mutator function\n * runner.setMessagesParams((params) => ({\n * ...params,\n * max_tokens: 100,\n * }));\n */\n setMessagesParams(params: BetaToolRunnerParams): void;\n setMessagesParams(mutator: (prevParams: BetaToolRunnerParams) => BetaToolRunnerParams): void;\n setMessagesParams(\n paramsOrMutator: BetaToolRunnerParams | ((prevParams: BetaToolRunnerParams) => BetaToolRunnerParams),\n ) {\n if (typeof paramsOrMutator === 'function') {\n this.#state.params = paramsOrMutator(this.#state.params);\n } else {\n this.#state.params = paramsOrMutator;\n }\n this.#mutated = true;\n // Invalidate cached tool response since parameters changed\n this.#toolResponse = undefined;\n }\n\n /**\n * Update the request options for future API calls.\n *\n * @param optionsOrMutator - Either new options or a function to mutate existing options\n *\n * @example\n * // Direct options update\n * runner.setRequestOptions({\n * signal: controller.signal,\n * });\n *\n * @example\n * // Using a mutator function\n * runner.setRequestOptions((prevOptions) => ({\n * ...prevOptions,\n * signal: controller.signal,\n * }));\n */\n setRequestOptions(options: BetaToolRunnerRequestOptions): void;\n setRequestOptions(\n mutator: (prevOptions: BetaToolRunnerRequestOptions) => BetaToolRunnerRequestOptions,\n ): void;\n setRequestOptions(\n optionsOrMutator:\n | BetaToolRunnerRequestOptions\n | ((prevOptions: BetaToolRunnerRequestOptions) => BetaToolRunnerRequestOptions),\n ) {\n if (typeof optionsOrMutator === 'function') {\n this.#options = optionsOrMutator(this.#options);\n } else {\n this.#options = { ...this.#options, ...optionsOrMutator };\n }\n }\n\n /**\n * Get the tool response for the last message from the assistant.\n * Avoids redundant tool executions by caching results.\n *\n * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed\n *\n * @example\n * const toolResponse = await runner.generateToolResponse();\n * if (toolResponse) {\n * console.log('Tool results:', toolResponse.content);\n * }\n */\n async generateToolResponse(signal: AbortSignal | null | undefined = this.#options.signal) {\n const message = (await this.#message) ?? this.params.messages.at(-1);\n if (!message) {\n return null;\n }\n return this.#generateToolResponse(message, signal);\n }\n\n async #generateToolResponse(\n lastMessage: BetaMessageParam,\n signal: AbortSignal | null | undefined = this.#options.signal,\n ) {\n if (this.#toolResponse !== undefined) {\n return this.#toolResponse;\n }\n this.#toolResponse = generateToolResponse(this.#state.params, lastMessage, {\n ...this.#options,\n signal,\n });\n return this.#toolResponse;\n }\n\n /**\n * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and\n * will wait for an instance to start and go to completion.\n *\n * @returns A promise that resolves to the final BetaMessage when the iterator completes\n *\n * @example\n * // Start consuming the iterator\n * for await (const message of runner) {\n * console.log('Message:', message.content);\n * }\n *\n * // Meanwhile, wait for completion from another part of the code\n * const finalMessage = await runner.done();\n * console.log('Final response:', finalMessage.content);\n */\n done(): Promise<BetaMessage> {\n return this.#completion.promise;\n }\n\n /**\n * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream:\n * * If the iterator has not been consumed, consume the entire iterator and return the final message from the\n * assistant.\n * * If the iterator has been consumed, waits for it to complete and returns the final message.\n *\n * @returns A promise that resolves to the final BetaMessage from the conversation\n * @throws {AnthropicError} If no messages were processed during the conversation\n *\n * @example\n * const finalMessage = await runner.runUntilDone();\n * console.log('Final response:', finalMessage.content);\n */\n async runUntilDone(): Promise<BetaMessage> {\n // If not yet consumed, start consuming and wait for completion\n if (!this.#consumed) {\n for await (const _ of this) {\n // Iterator naturally populates this.#message\n }\n }\n\n // If consumed but not completed, wait for completion\n return this.done();\n }\n\n /**\n * Get the current parameters being used by the ToolRunner.\n *\n * @returns A readonly view of the current ToolRunnerParams\n *\n * @example\n * const currentParams = runner.params;\n * console.log('Current model:', currentParams.model);\n * console.log('Message count:', currentParams.messages.length);\n */\n get params(): Readonly<BetaToolRunnerParams> {\n return this.#state.params as Readonly<BetaToolRunnerParams>;\n }\n\n /**\n * Add one or more messages to the conversation history.\n *\n * @param messages - One or more BetaMessageParam objects to add to the conversation\n *\n * @example\n * runner.pushMessages(\n * { role: 'user', content: 'Also, what about the weather in NYC?' }\n * );\n *\n * @example\n * // Adding multiple messages\n * runner.pushMessages(\n * { role: 'user', content: 'What about NYC?' },\n * { role: 'user', content: 'And Boston?' }\n * );\n */\n pushMessages(...messages: BetaMessageParam[]) {\n this.setMessagesParams((params) => ({\n ...params,\n messages: [...params.messages, ...messages],\n }));\n }\n\n /**\n * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone()\n * This allows using `await runner` instead of `await runner.runUntilDone()`\n */\n then<TResult1 = BetaMessage, TResult2 = never>(\n onfulfilled?: ((value: BetaMessage) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): Promise<TResult1 | TResult2> {\n return this.runUntilDone().then(onfulfilled, onrejected);\n }\n}\n\nasync function generateToolResponse(\n params: BetaToolRunnerParams,\n lastMessage = params.messages.at(-1),\n requestOptions?: BetaToolRunnerRequestOptions,\n): Promise<BetaMessageParam | null> {\n // Only process if the last message is from the assistant and has tool use blocks\n if (\n !lastMessage ||\n lastMessage.role !== 'assistant' ||\n !lastMessage.content ||\n typeof lastMessage.content === 'string'\n ) {\n return null;\n }\n\n const toolUseBlocks = lastMessage.content.filter((content) => content.type === 'tool_use');\n if (toolUseBlocks.length === 0) {\n return null;\n }\n\n const toolResults = await Promise.all(\n toolUseBlocks.map(async (toolUse) => {\n const tool = params.tools.find((t) => ('name' in t ? t.name : t.mcp_server_name) === toolUse.name);\n if (!tool || !('run' in tool)) {\n return {\n type: 'tool_result' as const,\n tool_use_id: toolUse.id,\n content: `Error: Tool '${toolUse.name}' not found`,\n is_error: true,\n };\n }\n\n try {\n let input = toolUse.input;\n if ('parse' in tool && tool.parse) {\n input = tool.parse(input);\n }\n\n const result = await tool.run(input, {\n toolUse: toolUse,\n toolUseBlock: toolUse,\n signal: requestOptions?.signal,\n });\n return {\n type: 'tool_result' as const,\n tool_use_id: toolUse.id,\n content: result,\n };\n } catch (error) {\n return {\n type: 'tool_result' as const,\n tool_use_id: toolUse.id,\n content:\n error instanceof ToolError ?\n error.content\n : `Error: ${error instanceof Error ? error.message : String(error)}`,\n is_error: true,\n };\n }\n }),\n );\n\n return {\n role: 'user' as const,\n content: toolResults,\n };\n}\n\n// vendored from typefest just to make things look a bit nicer on hover\ntype Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};\n\n/**\n * Parameters for creating a ToolRunner, extending MessageCreateParams with runnable tools.\n */\nexport type BetaToolRunnerParams = Simplify<\n Omit<MessageCreateParams, 'tools'> & {\n tools: (BetaToolUnion | BetaRunnableTool<any>)[];\n /**\n * Maximum number of iterations (API requests) to make in the tool execution loop.\n * Each iteration consists of: assistant response → tool execution → tool results.\n * When exceeded, the loop will terminate even if tools are still being requested.\n */\n max_iterations?: number;\n /**\n * @deprecated Use server-side compaction instead by passing\n * `edits: [{ type: 'compact_20260112' }]` in the params passed to `toolRunner()`.\n * See https://platform.claude.com/docs/en/build-with-claude/compaction\n */\n compactionControl?: CompactionControl;\n }\n>;\n\nexport type BetaToolRunnerRequestOptions = Pick<RequestOptions, 'headers' | 'signal' | 'fallbackState'>;\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { AnthropicError } from '../../../error';\nimport { Anthropic } from '../../../client';\nimport * as BatchesAPI from './batches';\nimport { APIPromise } from '../../../core/api-promise';\nimport { APIResource } from '../../../core/resource';\nimport { Stream } from '../../../core/streaming';\nimport { MODEL_NONSTREAMING_TOKENS } from '../../../internal/constants';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { stainlessHelperHeader } from '../../../internal/stainless-helper-header';\nimport {\n parseBetaMessage,\n type ExtractParsedContentFromBetaParams,\n type ParsedBetaMessage,\n} from '../../../lib/beta-parser';\nimport { BetaMessageStream } from '../../../lib/BetaMessageStream';\nimport {\n BetaToolRunner,\n BetaToolRunnerParams,\n BetaToolRunnerRequestOptions,\n} from '../../../lib/tools/BetaToolRunner';\nimport { ToolError } from '../../../lib/tools/ToolError';\nimport type { Model } from '../../messages/messages';\nimport * as BetaMessagesAPI from './messages';\nimport * as MessagesAPI from '../../messages/messages';\nimport * as BetaAPI from '../beta';\nimport {\n BatchCancelParams,\n BatchCreateParams,\n BatchDeleteParams,\n BatchListParams,\n BatchResultsParams,\n BatchRetrieveParams,\n Batches,\n BetaDeletedMessageBatch,\n BetaMessageBatch,\n BetaMessageBatchCanceledResult,\n BetaMessageBatchErroredResult,\n BetaMessageBatchExpiredResult,\n BetaMessageBatchIndividualResponse,\n BetaMessageBatchRequestCounts,\n BetaMessageBatchResult,\n BetaMessageBatchSucceededResult,\n BetaMessageBatchesPage,\n} from './batches';\n\nconst DEPRECATED_MODELS: {\n [K in Model]?: string;\n} = {\n 'claude-1.3': 'November 6th, 2024',\n 'claude-1.3-100k': 'November 6th, 2024',\n 'claude-instant-1.1': 'November 6th, 2024',\n 'claude-instant-1.1-100k': 'November 6th, 2024',\n 'claude-instant-1.2': 'November 6th, 2024',\n 'claude-3-sonnet-20240229': 'July 21st, 2025',\n 'claude-3-opus-20240229': 'January 5th, 2026',\n 'claude-2.1': 'July 21st, 2025',\n 'claude-2.0': 'July 21st, 2025',\n 'claude-3-7-sonnet-latest': 'February 19th, 2026',\n 'claude-3-7-sonnet-20250219': 'February 19th, 2026',\n 'claude-3-5-haiku-latest': 'February 19th, 2026',\n 'claude-3-5-haiku-20241022': 'February 19th, 2026',\n 'claude-opus-4-0': 'June 15th, 2026',\n 'claude-opus-4-20250514': 'June 15th, 2026',\n 'claude-sonnet-4-0': 'June 15th, 2026',\n 'claude-sonnet-4-20250514': 'June 15th, 2026',\n 'claude-opus-4-1': 'August 5th, 2026',\n 'claude-opus-4-1-20250805': 'August 5th, 2026',\n 'claude-mythos-preview': 'June 30th, 2026',\n};\n\nconst MODELS_TO_WARN_WITH_THINKING_ENABLED: Model[] = ['claude-mythos-preview', 'claude-opus-4-6'];\n\nexport class Messages extends APIResource {\n batches: BatchesAPI.Batches = new BatchesAPI.Batches(this._client);\n\n /**\n * Send a structured list of input messages with text and/or image content, and the\n * model will generate the next message in the conversation.\n *\n * The Messages API can be used for either single queries or stateless multi-turn\n * conversations.\n *\n * Learn more about the Messages API in our\n * [user guide](https://docs.claude.com/en/docs/initial-setup)\n *\n * @example\n * ```ts\n * const betaMessage = await client.beta.messages.create({\n * max_tokens: 1024,\n * messages: [{ content: 'Hello, world', role: 'user' }],\n * model: 'claude-opus-4-6',\n * });\n * ```\n */\n create(params: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<BetaMessage>;\n create(\n params: MessageCreateParamsStreaming,\n options?: RequestOptions,\n ): APIPromise<Stream<BetaRawMessageStreamEvent>>;\n create(\n params: MessageCreateParamsBase,\n options?: RequestOptions,\n ): APIPromise<Stream<BetaRawMessageStreamEvent> | BetaMessage>;\n create(\n params: MessageCreateParams,\n options?: RequestOptions,\n ): APIPromise<BetaMessage> | APIPromise<Stream<BetaRawMessageStreamEvent>> {\n // Transform deprecated output_format to output_config.format\n const modifiedParams = transformOutputFormat(params);\n\n const { betas, user_profile_id, ...body } = modifiedParams;\n\n if (body.model in DEPRECATED_MODELS) {\n console.warn(\n `The model '${body.model}' is deprecated and will reach end-of-life on ${\n DEPRECATED_MODELS[body.model]\n }\\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`,\n );\n }\n\n if (\n MODELS_TO_WARN_WITH_THINKING_ENABLED.includes(body.model) &&\n body.thinking &&\n body.thinking.type === 'enabled'\n ) {\n console.warn(\n `Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`,\n );\n }\n\n let timeout = (this._client as any)._options.timeout as number | null;\n if (!body.stream && timeout == null) {\n const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;\n timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);\n }\n\n // Collect helper info from tools and messages\n const helperHeader = stainlessHelperHeader(body.tools, body.messages);\n\n return this._client.post('/v1/messages?beta=true', {\n body,\n timeout: timeout ?? 600000,\n ...options,\n headers: buildHeaders([\n {\n ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined),\n ...(user_profile_id != null ? { 'anthropic-user-profile-id': user_profile_id } : undefined),\n },\n helperHeader,\n options?.headers,\n ]),\n stream: modifiedParams.stream ?? false,\n }) as APIPromise<BetaMessage> | APIPromise<Stream<BetaRawMessageStreamEvent>>;\n }\n\n /**\n * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and\n * the response will be automatically parsed and available in the `parsed_output` property of the message.\n *\n * @example\n * ```ts\n * const message = await client.beta.messages.parse({\n * model: 'claude-3-5-sonnet-20241022',\n * max_tokens: 1024,\n * messages: [{ role: 'user', content: 'What is 2+2?' }],\n * output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'),\n * });\n *\n * console.log(message.parsed_output?.answer); // 4\n * ```\n */\n parse<Params extends MessageCreateParamsNonStreaming>(\n params: Params,\n options?: RequestOptions,\n ): APIPromise<ParsedBetaMessage<ExtractParsedContentFromBetaParams<Params>>> {\n options = {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(params.betas ?? []), 'structured-outputs-2025-12-15'].toString() },\n options?.headers,\n ]),\n };\n\n return this.create(params, options).then((message) =>\n parseBetaMessage(message, params, { logger: this._client.logger ?? console }),\n ) as APIPromise<ParsedBetaMessage<ExtractParsedContentFromBetaParams<Params>>>;\n }\n\n /**\n * Create a Message stream\n */\n stream<Params extends BetaMessageStreamParams>(\n body: Params,\n options?: RequestOptions,\n ): BetaMessageStream<ExtractParsedContentFromBetaParams<Params>> {\n return BetaMessageStream.createMessage(this, body, options);\n }\n\n /**\n * Count the number of tokens in a Message.\n *\n * The Token Count API can be used to count the number of tokens in a Message,\n * including tools, images, and documents, without creating it.\n *\n * Learn more about token counting in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)\n *\n * @example\n * ```ts\n * const betaMessageTokensCount =\n * await client.beta.messages.countTokens({\n * messages: [{ content: 'Hello, world', role: 'user' }],\n * model: 'claude-opus-4-6',\n * });\n * ```\n */\n countTokens(\n params: MessageCountTokensParams,\n options?: RequestOptions,\n ): APIPromise<BetaMessageTokensCount> {\n // Transform deprecated output_format to output_config.format\n const modifiedParams = transformOutputFormat(params);\n\n const { betas, ...body } = modifiedParams;\n return this._client.post('/v1/messages/count_tokens?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n toolRunner(\n body: BetaToolRunnerParams & { stream?: false },\n options?: BetaToolRunnerRequestOptions,\n ): BetaToolRunner<false>;\n toolRunner(\n body: BetaToolRunnerParams & { stream: true },\n options?: BetaToolRunnerRequestOptions,\n ): BetaToolRunner<true>;\n toolRunner(body: BetaToolRunnerParams, options?: BetaToolRunnerRequestOptions): BetaToolRunner<boolean>;\n toolRunner(body: BetaToolRunnerParams, options?: BetaToolRunnerRequestOptions): BetaToolRunner<boolean> {\n return new BetaToolRunner(this._client as Anthropic, body, options);\n }\n}\n\n/**\n * Transform deprecated output_format to output_config.format\n * Returns a modified copy of the params without mutating the original\n */\nfunction transformOutputFormat<T extends MessageCreateParams | MessageCountTokensParams>(params: T): T {\n if (!params.output_format) {\n return params;\n }\n\n if (params.output_config?.format) {\n throw new AnthropicError(\n 'Both output_format and output_config.format were provided. ' +\n 'Please use only output_config.format (output_format is deprecated).',\n );\n }\n\n const { output_format, ...rest } = params;\n\n return {\n ...rest,\n output_config: {\n ...params.output_config,\n format: output_format,\n },\n } as T;\n}\n\n/**\n * Token usage for an advisor sub-inference iteration.\n */\nexport interface BetaAdvisorMessageIterationUsage {\n /**\n * Breakdown of cached tokens by TTL\n */\n cache_creation: BetaCacheCreation | null;\n\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n\n /**\n * Usage for an advisor sub-inference iteration\n */\n type: 'advisor_message';\n}\n\nexport interface BetaAdvisorRedactedResultBlock {\n /**\n * Opaque blob containing the advisor's output. Round-trip verbatim; do not inspect\n * or modify.\n */\n encrypted_content: string;\n\n /**\n * The advisor sub-inference's stop reason (same values as the top-level message\n * `stop_reason`).\n */\n stop_reason: string | null;\n\n type: 'advisor_redacted_result';\n}\n\nexport interface BetaAdvisorRedactedResultBlockParam {\n /**\n * Opaque blob produced by a prior response; must be round-tripped verbatim.\n */\n encrypted_content: string;\n\n type: 'advisor_redacted_result';\n\n stop_reason?: string | null;\n}\n\nexport interface BetaAdvisorResultBlock {\n /**\n * The advisor sub-inference's stop reason (same values as the top-level message\n * `stop_reason`). `max_tokens` indicates the advisor's output was truncated at the\n * tool's `max_tokens` value or the advisor model's policy cap.\n */\n stop_reason: string | null;\n\n text: string;\n\n type: 'advisor_result';\n}\n\nexport interface BetaAdvisorResultBlockParam {\n text: string;\n\n type: 'advisor_result';\n\n stop_reason?: string | null;\n}\n\nexport interface BetaAdvisorTool20260301 {\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'advisor';\n\n type: 'advisor_20260301';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Caching for the advisor's own prompt. When set, each advisor call writes a cache\n * entry at the given TTL so subsequent calls in the same conversation read the\n * stable prefix. When omitted, the advisor prompt is not cached.\n */\n caching?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Bounds the advisor's total output (thinking + text) per call. When the advisor\n * hits this cap, the returned advisor_result or advisor_redacted_result block\n * carries stop_reason='max_tokens', and a truncation note is appended to the\n * advice text the worker model sees (inside the encrypted blob in redacted mode).\n * When set, the server also emits a remaining-tokens budget block in the advisor's\n * prompt so the advisor self-shapes toward the cap. When omitted, the advisor\n * model's default output cap applies and no budget block is emitted.\n */\n max_tokens?: number | null;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaAdvisorToolResultBlock {\n content: BetaAdvisorToolResultError | BetaAdvisorResultBlock | BetaAdvisorRedactedResultBlock;\n\n tool_use_id: string;\n\n type: 'advisor_tool_result';\n}\n\nexport interface BetaAdvisorToolResultBlockParam {\n content:\n | BetaAdvisorToolResultErrorParam\n | BetaAdvisorResultBlockParam\n | BetaAdvisorRedactedResultBlockParam;\n\n tool_use_id: string;\n\n type: 'advisor_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaAdvisorToolResultError {\n error_code:\n | 'max_uses_exceeded'\n | 'prompt_too_long'\n | 'too_many_requests'\n | 'overloaded'\n | 'unavailable'\n | 'execution_time_exceeded'\n | 'model_not_found';\n\n type: 'advisor_tool_result_error';\n}\n\nexport interface BetaAdvisorToolResultErrorParam {\n error_code:\n | 'max_uses_exceeded'\n | 'prompt_too_long'\n | 'too_many_requests'\n | 'overloaded'\n | 'unavailable'\n | 'execution_time_exceeded'\n | 'model_not_found';\n\n type: 'advisor_tool_result_error';\n}\n\nexport interface BetaAllThinkingTurns {\n type: 'all';\n}\n\nexport type BetaMessageStreamParams = MessageCreateParamsBase;\n\nexport interface BetaBase64ImageSource {\n data: string;\n\n media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';\n\n type: 'base64';\n}\n\nexport interface BetaBase64PDFSource {\n data: string;\n\n media_type: 'application/pdf';\n\n type: 'base64';\n}\n\nexport interface BetaBashCodeExecutionOutputBlock {\n file_id: string;\n\n type: 'bash_code_execution_output';\n}\n\nexport interface BetaBashCodeExecutionOutputBlockParam {\n file_id: string;\n\n type: 'bash_code_execution_output';\n}\n\nexport interface BetaBashCodeExecutionResultBlock {\n content: Array<BetaBashCodeExecutionOutputBlock>;\n\n return_code: number;\n\n stderr: string;\n\n stdout: string;\n\n type: 'bash_code_execution_result';\n}\n\nexport interface BetaBashCodeExecutionResultBlockParam {\n content: Array<BetaBashCodeExecutionOutputBlockParam>;\n\n return_code: number;\n\n stderr: string;\n\n stdout: string;\n\n type: 'bash_code_execution_result';\n}\n\nexport interface BetaBashCodeExecutionToolResultBlock {\n content: BetaBashCodeExecutionToolResultError | BetaBashCodeExecutionResultBlock;\n\n tool_use_id: string;\n\n type: 'bash_code_execution_tool_result';\n}\n\nexport interface BetaBashCodeExecutionToolResultBlockParam {\n content: BetaBashCodeExecutionToolResultErrorParam | BetaBashCodeExecutionResultBlockParam;\n\n tool_use_id: string;\n\n type: 'bash_code_execution_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaBashCodeExecutionToolResultError {\n error_code:\n | 'invalid_tool_input'\n | 'unavailable'\n | 'too_many_requests'\n | 'execution_time_exceeded'\n | 'output_file_too_large';\n\n type: 'bash_code_execution_tool_result_error';\n}\n\nexport interface BetaBashCodeExecutionToolResultErrorParam {\n error_code:\n | 'invalid_tool_input'\n | 'unavailable'\n | 'too_many_requests'\n | 'execution_time_exceeded'\n | 'output_file_too_large';\n\n type: 'bash_code_execution_tool_result_error';\n}\n\nexport interface BetaCacheControlEphemeral {\n type: 'ephemeral';\n\n /**\n * The time-to-live for the cache control breakpoint.\n *\n * This may be one the following values:\n *\n * - `5m`: 5 minutes\n * - `1h`: 1 hour\n *\n * Defaults to `5m`. See\n * [prompt caching pricing](https://docs.claude.com/en/docs/build-with-claude/prompt-caching)\n * for details.\n */\n ttl?: '5m' | '1h';\n}\n\nexport interface BetaCacheCreation {\n /**\n * The number of input tokens used to create the 1 hour cache entry.\n */\n ephemeral_1h_input_tokens: number;\n\n /**\n * The number of input tokens used to create the 5 minute cache entry.\n */\n ephemeral_5m_input_tokens: number;\n}\n\nexport interface BetaCacheMissMessagesChanged {\n /**\n * Approximate number of input tokens that would have been read from cache had the\n * prefix matched the previous request.\n */\n cache_missed_input_tokens: number;\n\n type: 'messages_changed';\n}\n\nexport interface BetaCacheMissModelChanged {\n /**\n * Approximate number of input tokens that would have been read from cache had the\n * prefix matched the previous request.\n */\n cache_missed_input_tokens: number;\n\n type: 'model_changed';\n}\n\nexport interface BetaCacheMissPreviousMessageNotFound {\n type: 'previous_message_not_found';\n}\n\nexport interface BetaCacheMissSystemChanged {\n /**\n * Approximate number of input tokens that would have been read from cache had the\n * prefix matched the previous request.\n */\n cache_missed_input_tokens: number;\n\n type: 'system_changed';\n}\n\nexport interface BetaCacheMissToolsChanged {\n /**\n * Approximate number of input tokens that would have been read from cache had the\n * prefix matched the previous request.\n */\n cache_missed_input_tokens: number;\n\n type: 'tools_changed';\n}\n\nexport interface BetaCacheMissUnavailable {\n type: 'unavailable';\n}\n\nexport interface BetaCitationCharLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n file_id: string | null;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface BetaCitationCharLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface BetaCitationConfig {\n enabled: boolean;\n}\n\nexport interface BetaCitationContentBlockLocation {\n /**\n * The full text of the cited block range, concatenated.\n *\n * Always equals the contents of `content[start_block_index:end_block_index]`\n * joined together. The text block is the minimal citable unit; this field is never\n * a substring of a single block. Not counted toward output tokens, and not counted\n * toward input tokens when sent back in subsequent turns.\n */\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n /**\n * Exclusive 0-based end index of the cited block range in the source's `content`\n * array.\n *\n * Always greater than `start_block_index`; a single-block citation has\n * `end_block_index = start_block_index + 1`.\n */\n end_block_index: number;\n\n file_id: string | null;\n\n /**\n * 0-based index of the first cited block in the source's `content` array.\n */\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface BetaCitationContentBlockLocationParam {\n /**\n * The full text of the cited block range, concatenated.\n *\n * Always equals the contents of `content[start_block_index:end_block_index]`\n * joined together. The text block is the minimal citable unit; this field is never\n * a substring of a single block. Not counted toward output tokens, and not counted\n * toward input tokens when sent back in subsequent turns.\n */\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n /**\n * Exclusive 0-based end index of the cited block range in the source's `content`\n * array.\n *\n * Always greater than `start_block_index`; a single-block citation has\n * `end_block_index = start_block_index + 1`.\n */\n end_block_index: number;\n\n /**\n * 0-based index of the first cited block in the source's `content` array.\n */\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface BetaCitationPageLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n file_id: string | null;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface BetaCitationPageLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface BetaCitationSearchResultLocation {\n /**\n * The full text of the cited block range, concatenated.\n *\n * Always equals the contents of `content[start_block_index:end_block_index]`\n * joined together. The text block is the minimal citable unit; this field is never\n * a substring of a single block. Not counted toward output tokens, and not counted\n * toward input tokens when sent back in subsequent turns.\n */\n cited_text: string;\n\n /**\n * Exclusive 0-based end index of the cited block range in the source's `content`\n * array.\n *\n * Always greater than `start_block_index`; a single-block citation has\n * `end_block_index = start_block_index + 1`.\n */\n end_block_index: number;\n\n /**\n * 0-based index of the cited search result among all `search_result` content\n * blocks in the request, in the order they appear across messages and tool\n * results.\n *\n * Counted separately from `document_index`; server-side web search results are not\n * included in this count.\n */\n search_result_index: number;\n\n source: string;\n\n /**\n * 0-based index of the first cited block in the source's `content` array.\n */\n start_block_index: number;\n\n title: string | null;\n\n type: 'search_result_location';\n}\n\nexport interface BetaCitationSearchResultLocationParam {\n /**\n * The full text of the cited block range, concatenated.\n *\n * Always equals the contents of `content[start_block_index:end_block_index]`\n * joined together. The text block is the minimal citable unit; this field is never\n * a substring of a single block. Not counted toward output tokens, and not counted\n * toward input tokens when sent back in subsequent turns.\n */\n cited_text: string;\n\n /**\n * Exclusive 0-based end index of the cited block range in the source's `content`\n * array.\n *\n * Always greater than `start_block_index`; a single-block citation has\n * `end_block_index = start_block_index + 1`.\n */\n end_block_index: number;\n\n /**\n * 0-based index of the cited search result among all `search_result` content\n * blocks in the request, in the order they appear across messages and tool\n * results.\n *\n * Counted separately from `document_index`; server-side web search results are not\n * included in this count.\n */\n search_result_index: number;\n\n source: string;\n\n /**\n * 0-based index of the first cited block in the source's `content` array.\n */\n start_block_index: number;\n\n title: string | null;\n\n type: 'search_result_location';\n}\n\nexport interface BetaCitationWebSearchResultLocationParam {\n cited_text: string;\n\n encrypted_index: string;\n\n title: string | null;\n\n type: 'web_search_result_location';\n\n url: string;\n}\n\nexport interface BetaCitationsConfigParam {\n enabled?: boolean;\n}\n\nexport interface BetaCitationsDelta {\n citation:\n | BetaCitationCharLocation\n | BetaCitationPageLocation\n | BetaCitationContentBlockLocation\n | BetaCitationsWebSearchResultLocation\n | BetaCitationSearchResultLocation;\n\n type: 'citations_delta';\n}\n\nexport interface BetaCitationsWebSearchResultLocation {\n cited_text: string;\n\n encrypted_index: string;\n\n title: string | null;\n\n type: 'web_search_result_location';\n\n url: string;\n}\n\nexport interface BetaClearThinking20251015Edit {\n type: 'clear_thinking_20251015';\n\n /**\n * Number of most recent assistant turns to keep thinking blocks for. Older turns\n * will have their thinking blocks removed.\n */\n keep?: BetaThinkingTurns | BetaAllThinkingTurns | 'all';\n}\n\nexport interface BetaClearThinking20251015EditResponse {\n /**\n * Number of input tokens cleared by this edit.\n */\n cleared_input_tokens: number;\n\n /**\n * Number of thinking turns that were cleared.\n */\n cleared_thinking_turns: number;\n\n /**\n * The type of context management edit applied.\n */\n type: 'clear_thinking_20251015';\n}\n\nexport interface BetaClearToolUses20250919Edit {\n type: 'clear_tool_uses_20250919';\n\n /**\n * Minimum number of tokens that must be cleared when triggered. Context will only\n * be modified if at least this many tokens can be removed.\n */\n clear_at_least?: BetaInputTokensClearAtLeast | null;\n\n /**\n * Whether to clear all tool inputs (bool) or specific tool inputs to clear (list)\n */\n clear_tool_inputs?: boolean | Array<string> | null;\n\n /**\n * Tool names whose uses are preserved from clearing\n */\n exclude_tools?: Array<string> | null;\n\n /**\n * Number of tool uses to retain in the conversation\n */\n keep?: BetaToolUsesKeep;\n\n /**\n * Condition that triggers the context management strategy\n */\n trigger?: BetaInputTokensTrigger | BetaToolUsesTrigger;\n}\n\nexport interface BetaClearToolUses20250919EditResponse {\n /**\n * Number of input tokens cleared by this edit.\n */\n cleared_input_tokens: number;\n\n /**\n * Number of tool uses that were cleared.\n */\n cleared_tool_uses: number;\n\n /**\n * The type of context management edit applied.\n */\n type: 'clear_tool_uses_20250919';\n}\n\nexport interface BetaCodeExecutionOutputBlock {\n file_id: string;\n\n type: 'code_execution_output';\n}\n\nexport interface BetaCodeExecutionOutputBlockParam {\n file_id: string;\n\n type: 'code_execution_output';\n}\n\nexport interface BetaCodeExecutionResultBlock {\n content: Array<BetaCodeExecutionOutputBlock>;\n\n return_code: number;\n\n stderr: string;\n\n stdout: string;\n\n type: 'code_execution_result';\n}\n\nexport interface BetaCodeExecutionResultBlockParam {\n content: Array<BetaCodeExecutionOutputBlockParam>;\n\n return_code: number;\n\n stderr: string;\n\n stdout: string;\n\n type: 'code_execution_result';\n}\n\nexport interface BetaCodeExecutionTool20250522 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'code_execution';\n\n type: 'code_execution_20250522';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaCodeExecutionTool20250825 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'code_execution';\n\n type: 'code_execution_20250825';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * Code execution tool with REPL state persistence (daemon mode + gVisor\n * checkpoint).\n */\nexport interface BetaCodeExecutionTool20260120 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'code_execution';\n\n type: 'code_execution_20260120';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * Code execution tool with REPL state persistence.\n */\nexport interface BetaCodeExecutionTool20260521 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'code_execution';\n\n type: 'code_execution_20260521';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaCodeExecutionToolResultBlock {\n /**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\n content: BetaCodeExecutionToolResultBlockContent;\n\n tool_use_id: string;\n\n type: 'code_execution_tool_result';\n}\n\n/**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\nexport type BetaCodeExecutionToolResultBlockContent =\n | BetaCodeExecutionToolResultError\n | BetaCodeExecutionResultBlock\n | BetaEncryptedCodeExecutionResultBlock;\n\nexport interface BetaCodeExecutionToolResultBlockParam {\n /**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\n content: BetaCodeExecutionToolResultBlockParamContent;\n\n tool_use_id: string;\n\n type: 'code_execution_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\n/**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\nexport type BetaCodeExecutionToolResultBlockParamContent =\n | BetaCodeExecutionToolResultErrorParam\n | BetaCodeExecutionResultBlockParam\n | BetaEncryptedCodeExecutionResultBlockParam;\n\nexport interface BetaCodeExecutionToolResultError {\n error_code: BetaCodeExecutionToolResultErrorCode;\n\n type: 'code_execution_tool_result_error';\n}\n\nexport type BetaCodeExecutionToolResultErrorCode =\n | 'invalid_tool_input'\n | 'unavailable'\n | 'too_many_requests'\n | 'execution_time_exceeded';\n\nexport interface BetaCodeExecutionToolResultErrorParam {\n error_code: BetaCodeExecutionToolResultErrorCode;\n\n type: 'code_execution_tool_result_error';\n}\n\n/**\n * Automatically compact older context when reaching the configured trigger\n * threshold.\n */\nexport interface BetaCompact20260112Edit {\n type: 'compact_20260112';\n\n /**\n * Additional instructions for summarization.\n */\n instructions?: string | null;\n\n /**\n * Whether to pause after compaction and return the compaction block to the user.\n */\n pause_after_compaction?: boolean;\n\n /**\n * When to trigger compaction. Defaults to 150000 input tokens.\n */\n trigger?: BetaInputTokensTrigger | null;\n}\n\n/**\n * A compaction block returned when autocompact is triggered.\n *\n * When content is None, it indicates the compaction failed to produce a valid\n * summary (e.g., malformed output from the model). Clients may round-trip\n * compaction blocks with null content; the server treats them as no-ops.\n */\nexport interface BetaCompactionBlock {\n /**\n * Summary of compacted content, or null if compaction failed\n */\n content: string | null;\n\n /**\n * Opaque metadata from prior compaction, to be round-tripped verbatim\n */\n encrypted_content: string | null;\n\n type: 'compaction';\n}\n\n/**\n * A compaction block containing summary of previous context.\n *\n * Users should round-trip these blocks from responses to subsequent requests to\n * maintain context across compaction boundaries.\n *\n * When content is None, the block represents a failed compaction. The server\n * treats these as no-ops. Empty string content is not allowed.\n */\nexport interface BetaCompactionBlockParam {\n type: 'compaction';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Summary of previously compacted content, or null if compaction failed\n */\n content?: string | null;\n\n /**\n * Opaque metadata from prior compaction, to be round-tripped verbatim\n */\n encrypted_content?: string | null;\n}\n\nexport interface BetaCompactionContentBlockDelta {\n content: string | null;\n\n /**\n * Opaque metadata from prior compaction, to be round-tripped verbatim\n */\n encrypted_content: string | null;\n\n type: 'compaction_delta';\n}\n\n/**\n * Token usage for a compaction iteration.\n */\nexport interface BetaCompactionIterationUsage {\n /**\n * Breakdown of cached tokens by TTL\n */\n cache_creation: BetaCacheCreation | null;\n\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n\n /**\n * Usage for a compaction iteration\n */\n type: 'compaction';\n}\n\n/**\n * Information about the container used in the request (for the code execution\n * tool)\n */\nexport interface BetaContainer {\n /**\n * Identifier for the container used in this request\n */\n id: string;\n\n /**\n * The time at which the container will expire.\n */\n expires_at: string;\n\n /**\n * Skills loaded in the container\n */\n skills: Array<BetaSkill> | null;\n}\n\n/**\n * Container parameters with skills to be loaded.\n */\nexport interface BetaContainerParams {\n /**\n * Container id\n */\n id?: string | null;\n\n /**\n * List of skills to load in the container\n */\n skills?: Array<BetaSkillParams> | null;\n}\n\n/**\n * Response model for a file uploaded to the container.\n */\nexport interface BetaContainerUploadBlock {\n file_id: string;\n\n type: 'container_upload';\n}\n\n/**\n * A content block that represents a file to be uploaded to the container Files\n * uploaded via this block will be available in the container's input directory.\n */\nexport interface BetaContainerUploadBlockParam {\n file_id: string;\n\n type: 'container_upload';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\n/**\n * Response model for a file uploaded to the container.\n */\nexport type BetaContentBlock =\n | BetaTextBlock\n | BetaThinkingBlock\n | BetaRedactedThinkingBlock\n | BetaToolUseBlock\n | BetaServerToolUseBlock\n | BetaWebSearchToolResultBlock\n | BetaWebFetchToolResultBlock\n | BetaAdvisorToolResultBlock\n | BetaCodeExecutionToolResultBlock\n | BetaBashCodeExecutionToolResultBlock\n | BetaTextEditorCodeExecutionToolResultBlock\n | BetaToolSearchToolResultBlock\n | BetaMCPToolUseBlock\n | BetaMCPToolResultBlock\n | BetaContainerUploadBlock\n | BetaCompactionBlock\n | BetaFallbackBlock;\n\n/**\n * Regular text content.\n */\nexport type BetaContentBlockParam =\n | BetaTextBlockParam\n | BetaImageBlockParam\n | BetaRequestDocumentBlock\n | BetaSearchResultBlockParam\n | BetaThinkingBlockParam\n | BetaRedactedThinkingBlockParam\n | BetaToolUseBlockParam\n | BetaToolResultBlockParam\n | BetaServerToolUseBlockParam\n | BetaWebSearchToolResultBlockParam\n | BetaWebFetchToolResultBlockParam\n | BetaAdvisorToolResultBlockParam\n | BetaCodeExecutionToolResultBlockParam\n | BetaBashCodeExecutionToolResultBlockParam\n | BetaTextEditorCodeExecutionToolResultBlockParam\n | BetaToolSearchToolResultBlockParam\n | BetaMCPToolUseBlockParam\n | BetaRequestMCPToolResultBlockParam\n | BetaContainerUploadBlockParam\n | BetaCompactionBlockParam\n | BetaMidConversationSystemBlockParam\n | BetaFallbackBlockParam;\n\nexport interface BetaContentBlockSource {\n content: string | Array<BetaContentBlockSourceContent>;\n\n type: 'content';\n}\n\nexport type BetaContentBlockSourceContent = BetaTextBlockParam | BetaImageBlockParam;\n\nexport interface BetaContextManagementConfig {\n /**\n * List of context management edits to apply\n */\n edits?: Array<BetaClearToolUses20250919Edit | BetaClearThinking20251015Edit | BetaCompact20260112Edit>;\n}\n\nexport interface BetaContextManagementResponse {\n /**\n * List of context management edits that were applied.\n */\n applied_edits: Array<BetaClearToolUses20250919EditResponse | BetaClearThinking20251015EditResponse>;\n}\n\nexport interface BetaCountTokensContextManagementResponse {\n /**\n * The original token count before context management was applied\n */\n original_input_tokens: number;\n}\n\n/**\n * Response envelope for request-level diagnostics. Present (possibly null)\n * whenever the caller supplied `diagnostics` on the request.\n */\nexport interface BetaDiagnostics {\n /**\n * Explains why the prompt cache could not fully reuse the prefix from the request\n * identified by `diagnostics.previous_message_id`. `null` means diagnosis is still\n * pending — the response was serialized before the background comparison\n * completed.\n */\n cache_miss_reason:\n | BetaCacheMissModelChanged\n | BetaCacheMissSystemChanged\n | BetaCacheMissToolsChanged\n | BetaCacheMissMessagesChanged\n | BetaCacheMissPreviousMessageNotFound\n | BetaCacheMissUnavailable\n | null;\n}\n\n/**\n * Request-level diagnostics. Currently carries the previous response id for\n * prompt-cache divergence reporting.\n */\nexport interface BetaDiagnosticsParam {\n /**\n * The `id` (`msg_...`) from this client's previous /v1/messages response. The\n * server compares that request's prompt fingerprint against this one and returns\n * `diagnostics.cache_miss_reason` when the prompt-cache prefix could not be\n * reused. Pass `null` on the first turn to opt in without a prior message to\n * compare.\n */\n previous_message_id?: string | null;\n}\n\n/**\n * Tool invocation directly from the model.\n */\nexport interface BetaDirectCaller {\n type: 'direct';\n}\n\nexport interface BetaDocumentBlock {\n /**\n * Citation configuration for the document\n */\n citations: BetaCitationConfig | null;\n\n source: BetaBase64PDFSource | BetaPlainTextSource;\n\n /**\n * The title of the document\n */\n title: string | null;\n\n type: 'document';\n}\n\n/**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\nexport interface BetaEncryptedCodeExecutionResultBlock {\n content: Array<BetaCodeExecutionOutputBlock>;\n\n encrypted_stdout: string;\n\n return_code: number;\n\n stderr: string;\n\n type: 'encrypted_code_execution_result';\n}\n\n/**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\nexport interface BetaEncryptedCodeExecutionResultBlockParam {\n content: Array<BetaCodeExecutionOutputBlockParam>;\n\n encrypted_stdout: string;\n\n return_code: number;\n\n stderr: string;\n\n type: 'encrypted_code_execution_result';\n}\n\n/**\n * Marks the point in `content` where one model's output gives way to the next.\n *\n * One block appears per hop where a preceding model actually ran this turn and\n * declined. A turn where no preceding model ran and declined has no such boundary\n * and carries no block — the signal for whether a fallback model served the\n * response is the presence of a `fallback_message` entry in `usage.iterations`,\n * not this block.\n *\n * The block is treated like a server-tool content block for streaming: it arrives\n * via the standard `content_block_start` / `content_block_stop` pair and carries\n * no deltas.\n */\nexport interface BetaFallbackBlock {\n /**\n * The model whose output ends at this point — the model that declined at this hop.\n * When the declining hop is the requested model, its `model` echoes the top-level\n * `model` string the caller sent (alias or canonical); when the declining hop is a\n * fallback model, its `model` is that model's canonical id.\n */\n from: BetaFallbackInfo;\n\n /**\n * The fallback model producing the content that follows this block. Its `model` is\n * always the canonical id.\n */\n to: BetaFallbackInfo;\n\n /**\n * What caused the `from` model to hand over at this hop.\n */\n trigger: BetaFallbackRefusalTrigger;\n\n type: 'fallback';\n}\n\n/**\n * A `fallback` block echoed back from a prior response.\n *\n * Accepted in `messages[].content` and not rendered into the prompt; not validated\n * against the request's `fallbacks` chain or top-level `model`.\n *\n * Echo the assistant turn back verbatim, including this block in its original\n * position. The block marks the boundary between content produced before and after\n * a fallback hop, and the server relies on that boundary to validate the turn:\n * when thinking runs flank the boundary, omitting the block merges them into one\n * span the server cannot validate (the request is rejected), and moving it into\n * the middle of a single run is likewise rejected; between non-thinking blocks the\n * block's placement has no validation effect.\n */\nexport interface BetaFallbackBlockParam {\n /**\n * Identifies one hop of a fallback transition.\n */\n from: BetaFallbackInfoParam;\n\n /**\n * Identifies one hop of a fallback transition.\n */\n to: BetaFallbackInfoParam;\n\n type: 'fallback';\n\n /**\n * The response block's `trigger`, echoed verbatim. Accepted and ignored by the\n * server; any object or `null` is allowed.\n */\n trigger?: unknown;\n}\n\n/**\n * Identifies one hop of a fallback transition.\n */\nexport interface BetaFallbackInfo {\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n}\n\n/**\n * Identifies one hop of a fallback transition.\n */\nexport interface BetaFallbackInfoParam {\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n}\n\n/**\n * Token usage for the fallback-model attempt of a server-side fallback request.\n *\n * Produced in place of a `message` entry for whichever hop served the response. A\n * declined hop produces the existing `message` entry. Whether a fallback model\n * served the response is signalled by the presence of this entry in\n * `usage.iterations`.\n */\nexport interface BetaFallbackMessageIterationUsage {\n /**\n * Breakdown of cached tokens by TTL\n */\n cache_creation: BetaCacheCreation | null;\n\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n\n /**\n * Usage for the fallback-model attempt that served the response\n */\n type: 'fallback_message';\n}\n\n/**\n * One entry in the `fallbacks` chain on a `/v1/messages` request.\n *\n * `model` is required. The four override fields (`max_tokens`, `thinking`,\n * `output_config`, and `speed`) replace the corresponding top-level field for this\n * attempt only and are validated as if the request were made to `model`. Any other\n * key is rejected at parse time.\n */\nexport interface BetaFallbackParam {\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n max_tokens?: number | null;\n\n output_config?: BetaOutputConfig | null;\n\n speed?: 'standard' | 'fast' | null;\n\n thinking?: BetaThinkingConfigEnabled | BetaThinkingConfigDisabled | BetaThinkingConfigAdaptive | null;\n\n [k: string]: unknown;\n}\n\n/**\n * The `from` model declined for policy reasons.\n */\nexport interface BetaFallbackRefusalTrigger {\n /**\n * The policy category that triggered a refusal.\n */\n category: 'cyber' | 'bio' | 'frontier_llm' | 'reasoning_extraction' | 'military_weapons' | null;\n\n type: 'refusal';\n}\n\nexport interface BetaFileDocumentSource {\n file_id: string;\n\n type: 'file';\n}\n\nexport interface BetaFileImageSource {\n file_id: string;\n\n type: 'file';\n}\n\nexport interface BetaImageBlockParam {\n source: BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource;\n\n type: 'image';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaInputJSONDelta {\n partial_json: string;\n\n type: 'input_json_delta';\n}\n\nexport interface BetaInputTokensClearAtLeast {\n type: 'input_tokens';\n\n value: number;\n}\n\nexport interface BetaInputTokensTrigger {\n type: 'input_tokens';\n\n value: number;\n}\n\n/**\n * Per-iteration token usage breakdown.\n *\n * Each entry represents one sampling iteration, with its own input/output token\n * counts and cache statistics. This allows you to:\n *\n * - Determine which iterations exceeded long context thresholds (>=200k tokens)\n * - Calculate the true context window size from the last iteration\n * - Understand token accumulation across server-side tool use loops\n */\nexport type BetaIterationsUsage = Array<\n | BetaMessageIterationUsage\n | BetaCompactionIterationUsage\n | BetaAdvisorMessageIterationUsage\n | BetaFallbackMessageIterationUsage\n>;\n\nexport interface BetaJSONOutputFormat {\n /**\n * The JSON schema of the format\n */\n schema: { [key: string]: unknown };\n\n type: 'json_schema';\n}\n\n/**\n * Configuration for a specific tool in an MCP toolset.\n */\nexport interface BetaMCPToolConfig {\n defer_loading?: boolean;\n\n enabled?: boolean;\n}\n\n/**\n * Default configuration for tools in an MCP toolset.\n */\nexport interface BetaMCPToolDefaultConfig {\n defer_loading?: boolean;\n\n enabled?: boolean;\n}\n\nexport interface BetaMCPToolResultBlock {\n content: string | Array<BetaTextBlock>;\n\n is_error: boolean;\n\n tool_use_id: string;\n\n type: 'mcp_tool_result';\n}\n\nexport interface BetaMCPToolUseBlock {\n id: string;\n\n input: unknown;\n\n /**\n * The name of the MCP tool\n */\n name: string;\n\n /**\n * The name of the MCP server\n */\n server_name: string;\n\n type: 'mcp_tool_use';\n}\n\nexport interface BetaMCPToolUseBlockParam {\n id: string;\n\n input: unknown;\n\n name: string;\n\n /**\n * The name of the MCP server\n */\n server_name: string;\n\n type: 'mcp_tool_use';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\n/**\n * Configuration for a group of tools from an MCP server.\n *\n * Allows configuring enabled status and defer_loading for all tools from an MCP\n * server, with optional per-tool overrides.\n */\nexport interface BetaMCPToolset {\n /**\n * Name of the MCP server to configure tools for\n */\n mcp_server_name: string;\n\n type: 'mcp_toolset';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Configuration overrides for specific tools, keyed by tool name\n */\n configs?: { [key: string]: BetaMCPToolConfig } | null;\n\n /**\n * Default configuration applied to all tools from this server\n */\n default_config?: BetaMCPToolDefaultConfig;\n}\n\nexport interface BetaMemoryTool20250818 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'memory';\n\n type: 'memory_20250818';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport type BetaMemoryTool20250818Command =\n | BetaMemoryTool20250818ViewCommand\n | BetaMemoryTool20250818CreateCommand\n | BetaMemoryTool20250818StrReplaceCommand\n | BetaMemoryTool20250818InsertCommand\n | BetaMemoryTool20250818DeleteCommand\n | BetaMemoryTool20250818RenameCommand;\n\nexport interface BetaMemoryTool20250818CreateCommand {\n /**\n * Command type identifier\n */\n command: 'create';\n\n /**\n * Content to write to the file\n */\n file_text: string;\n\n /**\n * Path where the file should be created\n */\n path: string;\n}\n\nexport interface BetaMemoryTool20250818DeleteCommand {\n /**\n * Command type identifier\n */\n command: 'delete';\n\n /**\n * Path to the file or directory to delete\n */\n path: string;\n}\n\nexport interface BetaMemoryTool20250818InsertCommand {\n /**\n * Command type identifier\n */\n command: 'insert';\n\n /**\n * Line number where text should be inserted\n */\n insert_line: number;\n\n /**\n * Text to insert at the specified line\n */\n insert_text: string;\n\n /**\n * Path to the file where text should be inserted\n */\n path: string;\n}\n\nexport interface BetaMemoryTool20250818RenameCommand {\n /**\n * Command type identifier\n */\n command: 'rename';\n\n /**\n * New path for the file or directory\n */\n new_path: string;\n\n /**\n * Current path of the file or directory\n */\n old_path: string;\n}\n\nexport interface BetaMemoryTool20250818StrReplaceCommand {\n /**\n * Command type identifier\n */\n command: 'str_replace';\n\n /**\n * Text to replace with\n */\n new_str: string;\n\n /**\n * Text to search for and replace\n */\n old_str: string;\n\n /**\n * Path to the file where text should be replaced\n */\n path: string;\n}\n\nexport interface BetaMemoryTool20250818ViewCommand {\n /**\n * Command type identifier\n */\n command: 'view';\n\n /**\n * Path to directory or file to view\n */\n path: string;\n\n /**\n * Optional line range for viewing specific lines\n */\n view_range?: Array<number>;\n}\n\nexport interface BetaMessage {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * Information about the container used in the request (for the code execution\n * tool)\n */\n container: BetaContainer | null;\n\n /**\n * Content generated by the model.\n *\n * This is an array of content blocks, each of which has a `type` that determines\n * its shape.\n *\n * Example:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"Hi, I'm Claude.\" }]\n * ```\n *\n * If the request input `messages` ended with an `assistant` turn, then the\n * response `content` will continue directly from that last turn. You can use this\n * to constrain the model's output.\n *\n * For example, if the input `messages` were:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Then the response `content` might be:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"B)\" }]\n * ```\n */\n content: Array<BetaContentBlock>;\n\n /**\n * Context management response.\n *\n * Information about context management strategies applied during the request.\n */\n context_management: BetaContextManagementResponse | null;\n\n /**\n * Response envelope for request-level diagnostics. Present (possibly null)\n * whenever the caller supplied `diagnostics` on the request.\n */\n diagnostics: BetaDiagnostics | null;\n\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Conversational role of the generated message.\n *\n * This will always be `\"assistant\"`.\n */\n role: 'assistant';\n\n /**\n * Structured information about a refusal.\n */\n stop_details: BetaRefusalStopDetails | null;\n\n /**\n * The reason that we stopped.\n *\n * This may be one the following values:\n *\n * - `\"end_turn\"`: the model reached a natural stopping point\n * - `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n * - `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n * - `\"tool_use\"`: the model invoked one or more tools\n * - `\"pause_turn\"`: we paused a long-running turn. You may provide the response\n * back as-is in a subsequent request to let the model continue.\n * - `\"refusal\"`: when streaming classifiers intervene to handle potential policy\n * violations\n *\n * In non-streaming mode this value is always non-null. In streaming mode, it is\n * null in the `message_start` event and non-null otherwise.\n */\n stop_reason: BetaStopReason | null;\n\n /**\n * Which custom stop sequence was generated, if any.\n *\n * This value will be a non-null string if one of your custom stop sequences was\n * generated.\n */\n stop_sequence: string | null;\n\n /**\n * Object type.\n *\n * For Messages, this is always `\"message\"`.\n */\n type: 'message';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: BetaUsage;\n}\n\nexport interface BetaMessageDeltaUsage {\n /**\n * The cumulative number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number | null;\n\n /**\n * The cumulative number of input tokens read from the cache.\n */\n cache_read_input_tokens: number | null;\n\n /**\n * The cumulative number of input tokens which were used.\n */\n input_tokens: number | null;\n\n /**\n * Per-iteration token usage breakdown.\n *\n * Each entry represents one sampling iteration, with its own input/output token\n * counts and cache statistics. This allows you to:\n *\n * - Determine which iterations exceeded long context thresholds (>=200k tokens)\n * - Calculate the true context window size from the last iteration\n * - Understand token accumulation across server-side tool use loops\n */\n iterations: BetaIterationsUsage | null;\n\n /**\n * The cumulative number of output tokens which were used.\n */\n output_tokens: number;\n\n /**\n * Breakdown of output tokens by category.\n *\n * `output_tokens` remains the inclusive, authoritative total used for billing.\n * This object provides a read-only decomposition for observability — for example,\n * how many of the billed output tokens were spent on internal reasoning that may\n * have been summarized before being returned to you.\n */\n output_tokens_details: BetaOutputTokensDetails | null;\n\n /**\n * The number of server tool requests.\n */\n server_tool_use: BetaServerToolUsage | null;\n}\n\n/**\n * Token usage for a sampling iteration.\n */\nexport interface BetaMessageIterationUsage {\n /**\n * Breakdown of cached tokens by TTL\n */\n cache_creation: BetaCacheCreation | null;\n\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n\n /**\n * Usage for a sampling iteration\n */\n type: 'message';\n}\n\nexport interface BetaMessageParam {\n content: string | Array<BetaContentBlockParam>;\n\n role: 'user' | 'assistant' | 'system';\n}\n\nexport interface BetaMessageTokensCount {\n /**\n * Information about context management applied to the message.\n */\n context_management: BetaCountTokensContextManagementResponse | null;\n\n /**\n * The total number of tokens across the provided list of messages, system prompt,\n * and tools.\n */\n input_tokens: number;\n}\n\nexport interface BetaMetadata {\n /**\n * An external identifier for the user who is associated with the request.\n *\n * This should be a uuid, hash value, or other opaque identifier. Anthropic may use\n * this id to help detect abuse. Do not include any identifying information such as\n * name, email address, or phone number.\n */\n user_id?: string | null;\n}\n\n/**\n * System instructions that appear mid-conversation.\n *\n * Use this block to provide or update system-level instructions at a specific\n * point in the conversation, rather than only via the top-level `system`\n * parameter.\n */\nexport interface BetaMidConversationSystemBlockParam {\n /**\n * System instruction text blocks.\n */\n content: Array<BetaTextBlockParam>;\n\n type: 'mid_conv_system';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaOutputConfig {\n /**\n * All possible effort levels.\n */\n effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | null;\n\n /**\n * A schema to specify Claude's output format in responses. See\n * [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)\n */\n format?: BetaJSONOutputFormat | null;\n\n /**\n * User-configurable total token budget across contexts.\n */\n task_budget?: BetaTokenTaskBudget | null;\n}\n\nexport interface BetaOutputTokensDetails {\n /**\n * Number of output tokens the model generated as internal reasoning, including the\n * thinking-block delimiter tokens.\n *\n * Reflects the raw reasoning the model produced, not the (possibly shorter)\n * summarized thinking text returned in the response body. Computed by\n * re-tokenizing the raw reasoning text, so it may differ from the model's exact\n * generation count by a small number of tokens. Always ≤ `output_tokens`;\n * `output_tokens - thinking_tokens` approximates the non-reasoning output.\n */\n thinking_tokens: number;\n}\n\nexport interface BetaPlainTextSource {\n data: string;\n\n media_type: 'text/plain';\n\n type: 'text';\n}\n\nexport type BetaRawContentBlockDelta =\n | BetaTextDelta\n | BetaInputJSONDelta\n | BetaCitationsDelta\n | BetaThinkingDelta\n | BetaSignatureDelta\n | BetaCompactionContentBlockDelta;\n\nexport interface BetaRawContentBlockDeltaEvent {\n delta: BetaRawContentBlockDelta;\n\n index: number;\n\n type: 'content_block_delta';\n}\n\nexport interface BetaRawContentBlockStartEvent {\n /**\n * Response model for a file uploaded to the container.\n */\n content_block:\n | BetaTextBlock\n | BetaThinkingBlock\n | BetaRedactedThinkingBlock\n | BetaToolUseBlock\n | BetaServerToolUseBlock\n | BetaWebSearchToolResultBlock\n | BetaWebFetchToolResultBlock\n | BetaAdvisorToolResultBlock\n | BetaCodeExecutionToolResultBlock\n | BetaBashCodeExecutionToolResultBlock\n | BetaTextEditorCodeExecutionToolResultBlock\n | BetaToolSearchToolResultBlock\n | BetaMCPToolUseBlock\n | BetaMCPToolResultBlock\n | BetaContainerUploadBlock\n | BetaCompactionBlock\n | BetaFallbackBlock;\n\n index: number;\n\n type: 'content_block_start';\n}\n\nexport interface BetaRawContentBlockStopEvent {\n index: number;\n\n type: 'content_block_stop';\n}\n\nexport interface BetaRawMessageDeltaEvent {\n /**\n * Information about context management strategies applied during the request\n */\n context_management: BetaContextManagementResponse | null;\n\n delta: BetaRawMessageDeltaEvent.Delta;\n\n type: 'message_delta';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: BetaMessageDeltaUsage;\n}\n\nexport namespace BetaRawMessageDeltaEvent {\n export interface Delta {\n /**\n * Information about the container used in the request (for the code execution\n * tool)\n */\n container: BetaMessagesAPI.BetaContainer | null;\n\n /**\n * Structured information about a refusal.\n */\n stop_details: BetaMessagesAPI.BetaRefusalStopDetails | null;\n\n stop_reason: BetaMessagesAPI.BetaStopReason | null;\n\n stop_sequence: string | null;\n }\n}\n\nexport interface BetaRawMessageStartEvent {\n message: BetaMessage;\n\n type: 'message_start';\n}\n\nexport interface BetaRawMessageStopEvent {\n type: 'message_stop';\n}\n\nexport type BetaRawMessageStreamEvent =\n | BetaRawMessageStartEvent\n | BetaRawMessageDeltaEvent\n | BetaRawMessageStopEvent\n | BetaRawContentBlockStartEvent\n | BetaRawContentBlockDeltaEvent\n | BetaRawContentBlockStopEvent;\n\nexport interface BetaRedactedThinkingBlock {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface BetaRedactedThinkingBlockParam {\n data: string;\n\n type: 'redacted_thinking';\n}\n\n/**\n * Structured information about a refusal.\n */\nexport interface BetaRefusalStopDetails {\n /**\n * The policy category that triggered a refusal.\n */\n category: 'cyber' | 'bio' | 'frontier_llm' | 'reasoning_extraction' | 'military_weapons' | null;\n\n /**\n * Human-readable explanation of the refusal.\n *\n * This text is not guaranteed to be stable. `null` when no explanation is\n * available for the category.\n */\n explanation: string | null;\n\n /**\n * Opaque code that refunds the cache-miss cost when retrying this refused request\n * on the fallback model. Pass it as `fallback_credit_token` on the retry request.\n * Expires 5 minutes after the refusal.\n *\n * The retry is sent either with the same request body (`system`, `messages`,\n * `tools`, and other render-shaping fields), or with the same body plus one\n * appended `assistant` message whose content is the partial text (with any\n * trailing whitespace stripped from the final text block) and paired server-tool\n * blocks from this refusal — which also authorizes that appended turn as an\n * assistant-prefill continuation on models that otherwise disallow prefill. A\n * token minted mid-server-tool-loop whose partial content was continuable may only\n * be redeemed the second way — if a same-body retry is rejected with a 400 saying\n * the token must be redeemed by continuing the partial response, retry the second\n * way instead. Either way: same workspace, same platform; a mismatch is a 400.\n * Resending a token for an already-warm prefix is permitted but yields no\n * additional credit.\n *\n * `null` when the refused model isn't eligible for a fallback credit.\n */\n fallback_credit_token: string | null;\n\n /**\n * Whether the accompanying `fallback_credit_token` may be redeemed with the\n * appended-assistant retry form. Only set when `fallback_credit_token` is present.\n *\n * `true`: retry by resending the same request body plus one appended `assistant`\n * message whose content is this response's `content` with any trailing whitespace\n * stripped from the final text block and unpaired `tool_use` blocks omitted (the\n * same appended-turn shape described on `fallback_credit_token`), with the token\n * attached. `false`: retry by resending the original request body unchanged, with\n * the token attached — the appended-assistant form is not available for this\n * refusal (no continuable partial content, or the request uses `output_format` or\n * a `tool_choice` that forces tool use). One exception: when the request used\n * `output_format` or a forced `tool_choice` and the refusal arrived after server\n * tools (including MCP connector tools) had already executed, the token may not be\n * redeemable by either retry form; if the exact-body retry is then rejected with a\n * 400 saying the token must be redeemed by continuing the partial response,\n * discard the token and retry without it.\n *\n * Advisory: if an appended-assistant retry is rejected with a 400 despite `true`,\n * fall back to resending the original request body with the token.\n */\n fallback_has_prefill_claim: boolean | null;\n\n /**\n * The server's suggested retry target for this refusal. Populated when a fallback\n * attempt could not be made (the fallback model's rate limit was exhausted, or it\n * was overloaded); names the fallback model the caller can retry directly. Null\n * otherwise.\n */\n recommended_model: string | null;\n\n type: 'refusal';\n}\n\nexport interface BetaRequestDocumentBlock {\n source:\n | BetaBase64PDFSource\n | BetaPlainTextSource\n | BetaContentBlockSource\n | BetaURLPDFSource\n | BetaFileDocumentSource;\n\n type: 'document';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n citations?: BetaCitationsConfigParam | null;\n\n context?: string | null;\n\n title?: string | null;\n}\n\nexport interface BetaRequestMCPServerToolConfiguration {\n allowed_tools?: Array<string> | null;\n\n enabled?: boolean | null;\n}\n\nexport interface BetaRequestMCPServerURLDefinition {\n name: string;\n\n type: 'url';\n\n url: string;\n\n authorization_token?: string | null;\n\n tool_configuration?: BetaRequestMCPServerToolConfiguration | null;\n}\n\nexport interface BetaRequestMCPToolResultBlockParam {\n tool_use_id: string;\n\n type: 'mcp_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n content?: string | Array<BetaTextBlockParam>;\n\n is_error?: boolean;\n}\n\nexport interface BetaSearchResultBlockParam {\n content: Array<BetaTextBlockParam>;\n\n source: string;\n\n title: string;\n\n type: 'search_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n citations?: BetaCitationsConfigParam;\n}\n\n/**\n * Tool invocation generated by a server-side tool.\n */\nexport interface BetaServerToolCaller {\n tool_id: string;\n\n type: 'code_execution_20250825';\n}\n\nexport interface BetaServerToolCaller20260120 {\n tool_id: string;\n\n type: 'code_execution_20260120';\n}\n\nexport interface BetaServerToolUsage {\n /**\n * The number of web fetch tool requests.\n */\n web_fetch_requests: number;\n\n /**\n * The number of web search tool requests.\n */\n web_search_requests: number;\n}\n\nexport interface BetaServerToolUseBlock {\n id: string;\n\n input: { [key: string]: unknown };\n\n name:\n | 'advisor'\n | 'web_search'\n | 'web_fetch'\n | 'code_execution'\n | 'bash_code_execution'\n | 'text_editor_code_execution'\n | 'tool_search_tool_regex'\n | 'tool_search_tool_bm25';\n\n type: 'server_tool_use';\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller20260120;\n}\n\nexport interface BetaServerToolUseBlockParam {\n id: string;\n\n input: unknown;\n\n name:\n | 'advisor'\n | 'web_search'\n | 'web_fetch'\n | 'code_execution'\n | 'bash_code_execution'\n | 'text_editor_code_execution'\n | 'tool_search_tool_regex'\n | 'tool_search_tool_bm25';\n\n type: 'server_tool_use';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller20260120;\n}\n\nexport interface BetaSignatureDelta {\n signature: string;\n\n type: 'signature_delta';\n}\n\n/**\n * A skill that was loaded in a container (response model).\n */\nexport interface BetaSkill {\n /**\n * Skill ID\n */\n skill_id: string;\n\n /**\n * Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)\n */\n type: 'anthropic' | 'custom';\n\n /**\n * Skill version or 'latest' for most recent version\n */\n version: string;\n}\n\n/**\n * Specification for a skill to be loaded in a container (request model).\n */\nexport interface BetaSkillParams {\n /**\n * Skill ID\n */\n skill_id: string;\n\n /**\n * Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)\n */\n type: 'anthropic' | 'custom';\n\n /**\n * Skill version or 'latest' for most recent version\n */\n version?: string;\n}\n\nexport type BetaStopReason =\n | 'end_turn'\n | 'max_tokens'\n | 'stop_sequence'\n | 'tool_use'\n | 'pause_turn'\n | 'compaction'\n | 'refusal'\n | 'model_context_window_exceeded';\n\nexport interface BetaTextBlock {\n /**\n * Citations supporting the text block.\n *\n * The type of citation returned will depend on the type of document being cited.\n * Citing a PDF results in `page_location`, plain text results in `char_location`,\n * and content document results in `content_block_location`.\n */\n citations: Array<BetaTextCitation> | null;\n\n text: string;\n\n type: 'text';\n}\n\nexport interface BetaTextBlockParam {\n text: string;\n\n type: 'text';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n citations?: Array<BetaTextCitationParam> | null;\n}\n\nexport type BetaTextCitation =\n | BetaCitationCharLocation\n | BetaCitationPageLocation\n | BetaCitationContentBlockLocation\n | BetaCitationsWebSearchResultLocation\n | BetaCitationSearchResultLocation;\n\nexport type BetaTextCitationParam =\n | BetaCitationCharLocationParam\n | BetaCitationPageLocationParam\n | BetaCitationContentBlockLocationParam\n | BetaCitationWebSearchResultLocationParam\n | BetaCitationSearchResultLocationParam;\n\nexport interface BetaTextDelta {\n text: string;\n\n type: 'text_delta';\n}\n\nexport interface BetaTextEditorCodeExecutionCreateResultBlock {\n is_file_update: boolean;\n\n type: 'text_editor_code_execution_create_result';\n}\n\nexport interface BetaTextEditorCodeExecutionCreateResultBlockParam {\n is_file_update: boolean;\n\n type: 'text_editor_code_execution_create_result';\n}\n\nexport interface BetaTextEditorCodeExecutionStrReplaceResultBlock {\n lines: Array<string> | null;\n\n new_lines: number | null;\n\n new_start: number | null;\n\n old_lines: number | null;\n\n old_start: number | null;\n\n type: 'text_editor_code_execution_str_replace_result';\n}\n\nexport interface BetaTextEditorCodeExecutionStrReplaceResultBlockParam {\n type: 'text_editor_code_execution_str_replace_result';\n\n lines?: Array<string> | null;\n\n new_lines?: number | null;\n\n new_start?: number | null;\n\n old_lines?: number | null;\n\n old_start?: number | null;\n}\n\nexport interface BetaTextEditorCodeExecutionToolResultBlock {\n content:\n | BetaTextEditorCodeExecutionToolResultError\n | BetaTextEditorCodeExecutionViewResultBlock\n | BetaTextEditorCodeExecutionCreateResultBlock\n | BetaTextEditorCodeExecutionStrReplaceResultBlock;\n\n tool_use_id: string;\n\n type: 'text_editor_code_execution_tool_result';\n}\n\nexport interface BetaTextEditorCodeExecutionToolResultBlockParam {\n content:\n | BetaTextEditorCodeExecutionToolResultErrorParam\n | BetaTextEditorCodeExecutionViewResultBlockParam\n | BetaTextEditorCodeExecutionCreateResultBlockParam\n | BetaTextEditorCodeExecutionStrReplaceResultBlockParam;\n\n tool_use_id: string;\n\n type: 'text_editor_code_execution_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaTextEditorCodeExecutionToolResultError {\n error_code:\n | 'invalid_tool_input'\n | 'unavailable'\n | 'too_many_requests'\n | 'execution_time_exceeded'\n | 'file_not_found';\n\n error_message: string | null;\n\n type: 'text_editor_code_execution_tool_result_error';\n}\n\nexport interface BetaTextEditorCodeExecutionToolResultErrorParam {\n error_code:\n | 'invalid_tool_input'\n | 'unavailable'\n | 'too_many_requests'\n | 'execution_time_exceeded'\n | 'file_not_found';\n\n type: 'text_editor_code_execution_tool_result_error';\n\n error_message?: string | null;\n}\n\nexport interface BetaTextEditorCodeExecutionViewResultBlock {\n content: string;\n\n file_type: 'text' | 'image' | 'pdf';\n\n num_lines: number | null;\n\n start_line: number | null;\n\n total_lines: number | null;\n\n type: 'text_editor_code_execution_view_result';\n}\n\nexport interface BetaTextEditorCodeExecutionViewResultBlockParam {\n content: string;\n\n file_type: 'text' | 'image' | 'pdf';\n\n type: 'text_editor_code_execution_view_result';\n\n num_lines?: number | null;\n\n start_line?: number | null;\n\n total_lines?: number | null;\n}\n\nexport interface BetaThinkingBlock {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface BetaThinkingBlockParam {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface BetaThinkingConfigAdaptive {\n type: 'adaptive';\n\n /**\n * Controls how thinking content appears in the response. When set to `summarized`,\n * thinking is returned normally. When set to `omitted`, thinking content is\n * redacted but a signature is returned for multi-turn continuity. Defaults to\n * `summarized`.\n */\n display?: 'summarized' | 'omitted' | null;\n}\n\nexport interface BetaThinkingConfigDisabled {\n type: 'disabled';\n}\n\nexport interface BetaThinkingConfigEnabled {\n /**\n * Determines how many tokens Claude can use for its internal reasoning process.\n * Larger budgets can enable more thorough analysis for complex problems, improving\n * response quality.\n *\n * Must be ≥1024 and less than `max_tokens`.\n *\n * See\n * [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n budget_tokens: number;\n\n type: 'enabled';\n\n /**\n * Controls how thinking content appears in the response. When set to `summarized`,\n * thinking is returned normally. When set to `omitted`, thinking content is\n * redacted but a signature is returned for multi-turn continuity. Defaults to\n * `summarized`.\n */\n display?: 'summarized' | 'omitted' | null;\n}\n\n/**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\nexport type BetaThinkingConfigParam =\n | BetaThinkingConfigEnabled\n | BetaThinkingConfigDisabled\n | BetaThinkingConfigAdaptive;\n\nexport interface BetaThinkingDelta {\n /**\n * Per-frame increment of a coarse, running estimate of the tokens this thinking\n * block has produced so far. Present whenever the\n * `thinking-token-count-2026-05-13` beta is set; `null` unless `thinking.display`\n * resolves to `\"omitted\"` and a count is due this frame. Sum the increments across\n * `thinking_delta` frames on this block for a progress indicator. Each increment\n * is a non-negative multiple of a fixed quantum and the cadence is rate-limited,\n * so this is a deliberately lossy display hint, not a billable count;\n * `usage.output_tokens` remains authoritative.\n */\n estimated_tokens: number | null;\n\n thinking: string;\n\n type: 'thinking_delta';\n}\n\nexport interface BetaThinkingTurns {\n type: 'thinking_turns';\n\n value: number;\n}\n\n/**\n * User-configurable total token budget across contexts.\n */\nexport interface BetaTokenTaskBudget {\n /**\n * Total token budget across all contexts in the session.\n */\n total: number;\n\n /**\n * The budget type. Currently only 'tokens' is supported.\n */\n type: 'tokens';\n\n /**\n * Remaining tokens in the budget. Use this to track usage across contexts when\n * implementing compaction client-side. Defaults to total if not provided.\n */\n remaining?: number | null;\n}\n\nexport interface BetaTool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n input_schema: BetaTool.InputSchema;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: string;\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Description of what this tool does.\n *\n * Tool descriptions should be as detailed as possible. The more information that\n * the model has about what the tool is and how to use it, the better it will\n * perform. You can use natural language descriptions to reinforce important\n * aspects of the tool input JSON schema.\n */\n description?: string;\n\n /**\n * Enable eager input streaming for this tool. When true, tool input parameters\n * will be streamed incrementally as they are generated, and types will be inferred\n * on-the-fly rather than buffering the full JSON output. When false, streaming is\n * disabled for this tool even if the fine-grained-tool-streaming beta is active.\n * When null (default), uses the default behavior based on beta headers.\n */\n eager_input_streaming?: boolean | null;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n\n type?: 'custom' | null;\n}\n\nexport namespace BetaTool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n export interface InputSchema {\n type: 'object';\n\n properties?: unknown | null;\n\n required?: string[] | readonly string[] | null;\n\n [k: string]: unknown;\n }\n}\n\nexport interface BetaToolBash20241022 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'bash';\n\n type: 'bash_20241022';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaToolBash20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'bash';\n\n type: 'bash_20250124';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\nexport type BetaToolChoice = BetaToolChoiceAuto | BetaToolChoiceAny | BetaToolChoiceTool | BetaToolChoiceNone;\n\n/**\n * The model will use any available tools.\n */\nexport interface BetaToolChoiceAny {\n type: 'any';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will automatically decide whether to use tools.\n */\nexport interface BetaToolChoiceAuto {\n type: 'auto';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output at most one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will not be allowed to use tools.\n */\nexport interface BetaToolChoiceNone {\n type: 'none';\n}\n\n/**\n * The model will use the specified tool with `tool_choice.name`.\n */\nexport interface BetaToolChoiceTool {\n /**\n * The name of the tool to use.\n */\n name: string;\n\n type: 'tool';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\nexport interface BetaToolComputerUse20241022 {\n /**\n * The height of the display in pixels.\n */\n display_height_px: number;\n\n /**\n * The width of the display in pixels.\n */\n display_width_px: number;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'computer';\n\n type: 'computer_20241022';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * The X11 display number (e.g. 0, 1) for the display.\n */\n display_number?: number | null;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaToolComputerUse20250124 {\n /**\n * The height of the display in pixels.\n */\n display_height_px: number;\n\n /**\n * The width of the display in pixels.\n */\n display_width_px: number;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'computer';\n\n type: 'computer_20250124';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * The X11 display number (e.g. 0, 1) for the display.\n */\n display_number?: number | null;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaToolComputerUse20251124 {\n /**\n * The height of the display in pixels.\n */\n display_height_px: number;\n\n /**\n * The width of the display in pixels.\n */\n display_width_px: number;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'computer';\n\n type: 'computer_20251124';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * The X11 display number (e.g. 0, 1) for the display.\n */\n display_number?: number | null;\n\n /**\n * Whether to enable an action to take a zoomed-in screenshot of the screen.\n */\n enable_zoom?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaToolReferenceBlock {\n tool_name: string;\n\n type: 'tool_reference';\n}\n\n/**\n * Tool reference block that can be included in tool_result content.\n */\nexport interface BetaToolReferenceBlockParam {\n tool_name: string;\n\n type: 'tool_reference';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaToolResultBlockParam {\n tool_use_id: string;\n\n type: 'tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n content?:\n | string\n | Array<\n | BetaTextBlockParam\n | BetaImageBlockParam\n | BetaSearchResultBlockParam\n | BetaRequestDocumentBlock\n | BetaToolReferenceBlockParam\n >;\n\n is_error?: boolean;\n}\n\nexport interface BetaToolSearchToolBm25_20251119 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'tool_search_tool_bm25';\n\n type: 'tool_search_tool_bm25_20251119' | 'tool_search_tool_bm25';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaToolSearchToolRegex20251119 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'tool_search_tool_regex';\n\n type: 'tool_search_tool_regex_20251119' | 'tool_search_tool_regex';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaToolSearchToolResultBlock {\n content: BetaToolSearchToolResultError | BetaToolSearchToolSearchResultBlock;\n\n tool_use_id: string;\n\n type: 'tool_search_tool_result';\n}\n\nexport interface BetaToolSearchToolResultBlockParam {\n content: BetaToolSearchToolResultErrorParam | BetaToolSearchToolSearchResultBlockParam;\n\n tool_use_id: string;\n\n type: 'tool_search_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaToolSearchToolResultError {\n error_code: 'invalid_tool_input' | 'unavailable' | 'too_many_requests' | 'execution_time_exceeded';\n\n error_message: string | null;\n\n type: 'tool_search_tool_result_error';\n}\n\nexport interface BetaToolSearchToolResultErrorParam {\n error_code: 'invalid_tool_input' | 'unavailable' | 'too_many_requests' | 'execution_time_exceeded';\n\n type: 'tool_search_tool_result_error';\n\n error_message?: string | null;\n}\n\nexport interface BetaToolSearchToolSearchResultBlock {\n tool_references: Array<BetaToolReferenceBlock>;\n\n type: 'tool_search_tool_search_result';\n}\n\nexport interface BetaToolSearchToolSearchResultBlockParam {\n tool_references: Array<BetaToolReferenceBlockParam>;\n\n type: 'tool_search_tool_search_result';\n}\n\nexport type BetaToolResultContentBlockParam = Extract<BetaToolResultBlockParam['content'], any[]>[number];\n\nexport interface BetaToolTextEditor20241022 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'str_replace_editor';\n\n type: 'text_editor_20241022';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaToolTextEditor20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'str_replace_editor';\n\n type: 'text_editor_20250124';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaToolTextEditor20250429 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'str_replace_based_edit_tool';\n\n type: 'text_editor_20250429';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaToolTextEditor20250728 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'str_replace_based_edit_tool';\n\n type: 'text_editor_20250728';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * Maximum number of characters to display when viewing a file. If not specified,\n * defaults to displaying the full file.\n */\n max_characters?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * Code execution tool with REPL state persistence (daemon mode + gVisor\n * checkpoint).\n */\nexport type BetaToolUnion =\n | BetaTool\n | BetaToolBash20241022\n | BetaToolBash20250124\n | BetaCodeExecutionTool20250522\n | BetaCodeExecutionTool20250825\n | BetaCodeExecutionTool20260120\n | BetaCodeExecutionTool20260521\n | BetaToolComputerUse20241022\n | BetaMemoryTool20250818\n | BetaToolComputerUse20250124\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20251124\n | BetaToolTextEditor20250124\n | BetaToolTextEditor20250429\n | BetaToolTextEditor20250728\n | BetaWebSearchTool20250305\n | BetaWebFetchTool20250910\n | BetaWebSearchTool20260209\n | BetaWebFetchTool20260209\n | BetaWebFetchTool20260309\n | BetaAdvisorTool20260301\n | BetaToolSearchToolBm25_20251119\n | BetaToolSearchToolRegex20251119\n | BetaMCPToolset;\n\nexport interface BetaToolUseBlock {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller20260120;\n}\n\nexport interface BetaToolUseBlockParam {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller20260120;\n}\n\nexport interface BetaToolUsesKeep {\n type: 'tool_uses';\n\n value: number;\n}\n\nexport interface BetaToolUsesTrigger {\n type: 'tool_uses';\n\n value: number;\n}\n\nexport interface BetaURLImageSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface BetaURLPDFSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface BetaUsage {\n /**\n * Breakdown of cached tokens by TTL\n */\n cache_creation: BetaCacheCreation | null;\n\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number | null;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number | null;\n\n /**\n * The geographic region where inference was performed for this request.\n */\n inference_geo: string | null;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * Per-iteration token usage breakdown.\n *\n * Each entry represents one sampling iteration, with its own input/output token\n * counts and cache statistics. This allows you to:\n *\n * - Determine which iterations exceeded long context thresholds (>=200k tokens)\n * - Calculate the true context window size from the last iteration\n * - Understand token accumulation across server-side tool use loops\n */\n iterations: BetaIterationsUsage | null;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n\n /**\n * Breakdown of output tokens by category.\n *\n * `output_tokens` remains the inclusive, authoritative total used for billing.\n * This object provides a read-only decomposition for observability — for example,\n * how many of the billed output tokens were spent on internal reasoning that may\n * have been summarized before being returned to you.\n */\n output_tokens_details: BetaOutputTokensDetails | null;\n\n /**\n * The number of server tool requests.\n */\n server_tool_use: BetaServerToolUsage | null;\n\n /**\n * If the request used the priority, standard, or batch tier.\n */\n service_tier: 'standard' | 'priority' | 'batch' | null;\n\n /**\n * The inference speed mode used for this request.\n */\n speed: 'standard' | 'fast' | null;\n}\n\nexport interface BetaUserLocation {\n type: 'approximate';\n\n /**\n * The city of the user.\n */\n city?: string | null;\n\n /**\n * The two letter\n * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the\n * user.\n */\n country?: string | null;\n\n /**\n * The region of the user.\n */\n region?: string | null;\n\n /**\n * The [IANA timezone](https://nodatime.org/TimeZones) of the user.\n */\n timezone?: string | null;\n}\n\nexport interface BetaWebFetchBlock {\n content: BetaDocumentBlock;\n\n /**\n * ISO 8601 timestamp when the content was retrieved\n */\n retrieved_at: string | null;\n\n type: 'web_fetch_result';\n\n /**\n * Fetched content URL\n */\n url: string;\n}\n\nexport interface BetaWebFetchBlockParam {\n content: BetaRequestDocumentBlock;\n\n type: 'web_fetch_result';\n\n /**\n * Fetched content URL\n */\n url: string;\n\n /**\n * ISO 8601 timestamp when the content was retrieved\n */\n retrieved_at?: string | null;\n}\n\nexport interface BetaWebFetchTool20250910 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_fetch';\n\n type: 'web_fetch_20250910';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * List of domains to allow fetching from\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * List of domains to block fetching from\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Citations configuration for fetched documents. Citations are disabled by\n * default.\n */\n citations?: BetaCitationsConfigParam | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of tokens used by including web page text content in the context.\n * The limit is approximate and does not apply to binary content such as PDFs.\n */\n max_content_tokens?: number | null;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface BetaWebFetchTool20260209 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_fetch';\n\n type: 'web_fetch_20260209';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * List of domains to allow fetching from\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * List of domains to block fetching from\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Citations configuration for fetched documents. Citations are disabled by\n * default.\n */\n citations?: BetaCitationsConfigParam | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of tokens used by including web page text content in the context.\n * The limit is approximate and does not apply to binary content such as PDFs.\n */\n max_content_tokens?: number | null;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * Web fetch tool with use_cache parameter for bypassing cached content.\n */\nexport interface BetaWebFetchTool20260309 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_fetch';\n\n type: 'web_fetch_20260309';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * List of domains to allow fetching from\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * List of domains to block fetching from\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Citations configuration for fetched documents. Citations are disabled by\n * default.\n */\n citations?: BetaCitationsConfigParam | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of tokens used by including web page text content in the context.\n * The limit is approximate and does not apply to binary content such as PDFs.\n */\n max_content_tokens?: number | null;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n\n /**\n * Whether to use cached content. Set to false to bypass the cache and fetch fresh\n * content. Only set to false when the user explicitly requests fresh content or\n * when fetching rapidly-changing sources.\n */\n use_cache?: boolean;\n}\n\nexport interface BetaWebFetchToolResultBlock {\n content: BetaWebFetchToolResultErrorBlock | BetaWebFetchBlock;\n\n tool_use_id: string;\n\n type: 'web_fetch_tool_result';\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller20260120;\n}\n\nexport interface BetaWebFetchToolResultBlockParam {\n content: BetaWebFetchToolResultErrorBlockParam | BetaWebFetchBlockParam;\n\n tool_use_id: string;\n\n type: 'web_fetch_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller20260120;\n}\n\nexport interface BetaWebFetchToolResultErrorBlock {\n error_code: BetaWebFetchToolResultErrorCode;\n\n type: 'web_fetch_tool_result_error';\n}\n\nexport interface BetaWebFetchToolResultErrorBlockParam {\n error_code: BetaWebFetchToolResultErrorCode;\n\n type: 'web_fetch_tool_result_error';\n}\n\nexport type BetaWebFetchToolResultErrorCode =\n | 'invalid_tool_input'\n | 'url_too_long'\n | 'url_not_allowed'\n | 'url_not_in_prior_context'\n | 'url_not_accessible'\n | 'unsupported_content_type'\n | 'too_many_requests'\n | 'max_uses_exceeded'\n | 'unavailable';\n\nexport interface BetaWebSearchResultBlock {\n encrypted_content: string;\n\n page_age: string | null;\n\n title: string;\n\n type: 'web_search_result';\n\n url: string;\n}\n\nexport interface BetaWebSearchResultBlockParam {\n encrypted_content: string;\n\n title: string;\n\n type: 'web_search_result';\n\n url: string;\n\n page_age?: string | null;\n}\n\nexport interface BetaWebSearchTool20250305 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_search';\n\n type: 'web_search_20250305';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * If provided, only these domains will be included in results. Cannot be used\n * alongside `blocked_domains`.\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * If provided, these domains will never appear in results. Cannot be used\n * alongside `allowed_domains`.\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n\n /**\n * Parameters for the user's location. Used to provide more relevant search\n * results.\n */\n user_location?: BetaUserLocation | null;\n}\n\nexport interface BetaWebSearchTool20260209 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_search';\n\n type: 'web_search_20260209';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * If provided, only these domains will be included in results. Cannot be used\n * alongside `blocked_domains`.\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * If provided, these domains will never appear in results. Cannot be used\n * alongside `allowed_domains`.\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n\n /**\n * Parameters for the user's location. Used to provide more relevant search\n * results.\n */\n user_location?: BetaUserLocation | null;\n}\n\nexport interface BetaWebSearchToolRequestError {\n error_code: BetaWebSearchToolResultErrorCode;\n\n type: 'web_search_tool_result_error';\n}\n\nexport interface BetaWebSearchToolResultBlock {\n content: BetaWebSearchToolResultBlockContent;\n\n tool_use_id: string;\n\n type: 'web_search_tool_result';\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller20260120;\n}\n\nexport type BetaWebSearchToolResultBlockContent =\n | BetaWebSearchToolResultError\n | Array<BetaWebSearchResultBlock>;\n\nexport interface BetaWebSearchToolResultBlockParam {\n content: BetaWebSearchToolResultBlockParamContent;\n\n tool_use_id: string;\n\n type: 'web_search_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller20260120;\n}\n\nexport type BetaWebSearchToolResultBlockParamContent =\n | Array<BetaWebSearchResultBlockParam>\n | BetaWebSearchToolRequestError;\n\nexport interface BetaWebSearchToolResultError {\n error_code: BetaWebSearchToolResultErrorCode;\n\n type: 'web_search_tool_result_error';\n}\n\nexport type BetaWebSearchToolResultErrorCode =\n | 'invalid_tool_input'\n | 'unavailable'\n | 'max_uses_exceeded'\n | 'too_many_requests'\n | 'query_too_long'\n | 'request_too_large';\n\n/**\n * @deprecated BetaRequestDocumentBlock should be used insated\n */\nexport type BetaBase64PDFBlock = BetaRequestDocumentBlock;\n\nexport type MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming;\n\nexport interface MessageCreateParamsBase {\n /**\n * Body param: The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n *\n * Set to `0` to populate the\n * [prompt cache](https://docs.claude.com/en/docs/build-with-claude/prompt-caching#pre-warming-the-cache)\n * without generating a response.\n *\n * Different models have different maximum values for this parameter. See\n * [models](https://docs.claude.com/en/docs/models-overview) for details.\n */\n max_tokens: number;\n\n /**\n * Body param: Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * See [input examples](https://docs.claude.com/en/api/messages-examples).\n *\n * Note that if you want to include a\n * [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the\n * top-level `system` parameter — there is no `\"system\"` role for input messages in\n * the Messages API.\n *\n * There is a limit of 100,000 messages in a single request.\n */\n messages: Array<BetaMessageParam>;\n\n /**\n * Body param: The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Body param: Top-level cache control automatically applies a cache_control marker\n * to the last cacheable block in the request.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Body param: Container identifier for reuse across requests.\n */\n container?: BetaContainerParams | string | null;\n\n /**\n * Body param: Context management configuration.\n *\n * This allows you to control how Claude manages context across multiple requests,\n * such as whether to clear function results or not.\n */\n context_management?: BetaContextManagementConfig | null;\n\n /**\n * Body param: Request-level diagnostics. Currently carries the previous response\n * id for prompt-cache divergence reporting.\n */\n diagnostics?: BetaDiagnosticsParam | null;\n\n /**\n * Body param: The `fallback_credit_token` from a prior refusal's `stop_details`.\n *\n * When a preceding request was refused and returned a `fallback_credit_token`,\n * pass that code here on the retry to have the retry's cache-creation tokens for\n * the prefix that was warm on the refused model billed at the cache-read rate.\n * Must be redeemed by the same organization and workspace, with the same request\n * body (optionally extended by one appended `assistant` message whose content is\n * the partial text — with any trailing whitespace stripped from the final text\n * block — and paired server-tool blocks streamed before the refusal; the\n * appended-assistant form is not available for requests with `output_format` set\n * or forced `tool_choice`), on an eligible fallback model, on the same platform,\n * and within 5 minutes of the refusal; a mismatch is a 400. A token minted\n * mid-server-tool-loop whose partial content was continuable may only be redeemed\n * with the appended-assistant form — if an exact-body retry is rejected with a 400\n * saying the token must be redeemed by continuing the partial response, retry with\n * the appended-assistant form instead.\n *\n * When the appended-assistant form is used on a model that otherwise disallows\n * assistant-turn prefill, this token also authorizes that one prefill.\n */\n fallback_credit_token?: string | null;\n\n /**\n * Body param: Opt-in server-side retry on one or more substitute models when the\n * requested model declines for policy reasons. Tried in order: if the first entry\n * also declines, the second is tried, and so on.\n */\n fallbacks?: Array<BetaFallbackParam> | null;\n\n /**\n * Body param: Specifies the geographic region for inference processing. If not\n * specified, the workspace's `default_inference_geo` is used.\n */\n inference_geo?: string | null;\n\n /**\n * Body param: MCP servers to be utilized in this request\n */\n mcp_servers?: Array<BetaRequestMCPServerURLDefinition>;\n\n /**\n * Body param: An object describing metadata about the request.\n */\n metadata?: BetaMetadata;\n\n /**\n * Body param: Configuration options for the model's output, such as the output\n * format.\n */\n output_config?: BetaOutputConfig;\n\n /**\n * Body param: Deprecated: Use `output_config.format` instead. See\n * [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)\n *\n * A schema to specify Claude's output format in responses. This parameter will be\n * removed in a future release.\n */\n output_format?: BetaJSONOutputFormat | null;\n\n /**\n * Body param: Determines whether to use priority capacity (if available) or\n * standard capacity for this request.\n *\n * Anthropic offers different levels of service for your API requests. See\n * [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.\n */\n service_tier?: 'auto' | 'standard_only';\n\n /**\n * Body param: The inference speed mode for this request. `\"fast\"` enables high\n * output-tokens-per-second inference.\n */\n speed?: 'standard' | 'fast' | null;\n\n /**\n * Body param: Custom text sequences that will cause the model to stop generating.\n *\n * Our models will normally stop when they have naturally completed their turn,\n * which will result in a response `stop_reason` of `\"end_turn\"`.\n *\n * If you want the model to stop generating when it encounters custom strings of\n * text, you can use the `stop_sequences` parameter. If the model encounters one of\n * the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"`\n * and the response `stop_sequence` value will contain the matched stop sequence.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.\n */\n stream?: boolean;\n\n /**\n * Body param: System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).\n */\n system?: string | Array<BetaTextBlockParam>;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not support\n * setting temperature. A value of 1.0 of will be accepted for backwards\n * compatibility, all other values will be rejected with a 400 error.\n */\n temperature?: number;\n\n /**\n * Body param: Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: BetaThinkingConfigParam;\n\n /**\n * Body param: How the model should use the provided tools. The model can use a\n * specific tool, any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: BetaToolChoice;\n\n /**\n * Body param: Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * There are two types of tools: **client tools** and **server tools**. The\n * behavior described below applies to client tools. For\n * [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools),\n * see their individual documentation as each has its own behavior (e.g., the\n * [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.\n */\n tools?: Array<BetaToolUnion>;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not accept\n * top_k; any value will be rejected with a 400 error.\n */\n top_k?: number;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not support\n * setting top_p. A value >= 0.99 will be accepted for backwards compatibility, all\n * other values will be rejected with a 400 error.\n */\n top_p?: number;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n\n /**\n * Header param: The user profile ID to attribute this request to. Use when acting\n * on behalf of a party other than your organization. Requires the `user-profiles`\n * beta header.\n */\n user_profile_id?: string;\n}\n\nexport namespace MessageCreateParams {\n export type MessageCreateParamsNonStreaming = BetaMessagesAPI.MessageCreateParamsNonStreaming;\n export type MessageCreateParamsStreaming = BetaMessagesAPI.MessageCreateParamsStreaming;\n}\n\nexport interface MessageCreateParamsNonStreaming extends MessageCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.\n */\n stream?: false;\n}\n\nexport interface MessageCreateParamsStreaming extends MessageCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.\n */\n stream: true;\n}\n\nexport interface MessageCountTokensParams {\n /**\n * Body param: Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * See [input examples](https://docs.claude.com/en/api/messages-examples).\n *\n * Note that if you want to include a\n * [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the\n * top-level `system` parameter — there is no `\"system\"` role for input messages in\n * the Messages API.\n *\n * There is a limit of 100,000 messages in a single request.\n */\n messages: Array<BetaMessageParam>;\n\n /**\n * Body param: The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Body param: Top-level cache control automatically applies a cache_control marker\n * to the last cacheable block in the request.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n\n /**\n * Body param: Context management configuration.\n *\n * This allows you to control how Claude manages context across multiple requests,\n * such as whether to clear function results or not.\n */\n context_management?: BetaContextManagementConfig | null;\n\n /**\n * Body param: MCP servers to be utilized in this request\n */\n mcp_servers?: Array<BetaRequestMCPServerURLDefinition>;\n\n /**\n * Body param: Configuration options for the model's output, such as the output\n * format.\n */\n output_config?: BetaOutputConfig;\n\n /**\n * Body param: Deprecated: Use `output_config.format` instead. See\n * [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)\n *\n * A schema to specify Claude's output format in responses. This parameter will be\n * removed in a future release.\n */\n output_format?: BetaJSONOutputFormat | null;\n\n /**\n * Body param: The inference speed mode for this request. `\"fast\"` enables high\n * output-tokens-per-second inference.\n */\n speed?: 'standard' | 'fast' | null;\n\n /**\n * Body param: System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).\n */\n system?: string | Array<BetaTextBlockParam>;\n\n /**\n * Body param: Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: BetaThinkingConfigParam;\n\n /**\n * Body param: How the model should use the provided tools. The model can use a\n * specific tool, any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: BetaToolChoice;\n\n /**\n * Body param: Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * There are two types of tools: **client tools** and **server tools**. The\n * behavior described below applies to client tools. For\n * [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools),\n * see their individual documentation as each has its own behavior (e.g., the\n * [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.\n */\n tools?: Array<\n | BetaTool\n | BetaToolBash20241022\n | BetaToolBash20250124\n | BetaCodeExecutionTool20250522\n | BetaCodeExecutionTool20250825\n | BetaCodeExecutionTool20260120\n | BetaCodeExecutionTool20260521\n | BetaToolComputerUse20241022\n | BetaMemoryTool20250818\n | BetaToolComputerUse20250124\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20251124\n | BetaToolTextEditor20250124\n | BetaToolTextEditor20250429\n | BetaToolTextEditor20250728\n | BetaWebSearchTool20250305\n | BetaWebFetchTool20250910\n | BetaWebSearchTool20260209\n | BetaWebFetchTool20260209\n | BetaWebFetchTool20260309\n | BetaAdvisorTool20260301\n | BetaToolSearchToolBm25_20251119\n | BetaToolSearchToolRegex20251119\n | BetaMCPToolset\n >;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport { BetaToolRunner, type BetaToolRunnerParams } from '../../../lib/tools/BetaToolRunner';\nexport { ToolError } from '../../../lib/tools/ToolError';\n\nMessages.Batches = Batches;\n\nMessages.BetaToolRunner = BetaToolRunner;\nMessages.ToolError = ToolError;\n\nexport declare namespace Messages {\n export {\n type BetaAdvisorMessageIterationUsage as BetaAdvisorMessageIterationUsage,\n type BetaAdvisorRedactedResultBlock as BetaAdvisorRedactedResultBlock,\n type BetaAdvisorRedactedResultBlockParam as BetaAdvisorRedactedResultBlockParam,\n type BetaAdvisorResultBlock as BetaAdvisorResultBlock,\n type BetaAdvisorResultBlockParam as BetaAdvisorResultBlockParam,\n type BetaAdvisorTool20260301 as BetaAdvisorTool20260301,\n type BetaAdvisorToolResultBlock as BetaAdvisorToolResultBlock,\n type BetaAdvisorToolResultBlockParam as BetaAdvisorToolResultBlockParam,\n type BetaAdvisorToolResultError as BetaAdvisorToolResultError,\n type BetaAdvisorToolResultErrorParam as BetaAdvisorToolResultErrorParam,\n type BetaAllThinkingTurns as BetaAllThinkingTurns,\n type BetaBase64ImageSource as BetaBase64ImageSource,\n type BetaBase64PDFSource as BetaBase64PDFSource,\n type BetaBashCodeExecutionOutputBlock as BetaBashCodeExecutionOutputBlock,\n type BetaBashCodeExecutionOutputBlockParam as BetaBashCodeExecutionOutputBlockParam,\n type BetaBashCodeExecutionResultBlock as BetaBashCodeExecutionResultBlock,\n type BetaBashCodeExecutionResultBlockParam as BetaBashCodeExecutionResultBlockParam,\n type BetaBashCodeExecutionToolResultBlock as BetaBashCodeExecutionToolResultBlock,\n type BetaBashCodeExecutionToolResultBlockParam as BetaBashCodeExecutionToolResultBlockParam,\n type BetaBashCodeExecutionToolResultError as BetaBashCodeExecutionToolResultError,\n type BetaBashCodeExecutionToolResultErrorParam as BetaBashCodeExecutionToolResultErrorParam,\n type BetaCacheControlEphemeral as BetaCacheControlEphemeral,\n type BetaCacheCreation as BetaCacheCreation,\n type BetaCacheMissMessagesChanged as BetaCacheMissMessagesChanged,\n type BetaCacheMissModelChanged as BetaCacheMissModelChanged,\n type BetaCacheMissPreviousMessageNotFound as BetaCacheMissPreviousMessageNotFound,\n type BetaCacheMissSystemChanged as BetaCacheMissSystemChanged,\n type BetaCacheMissToolsChanged as BetaCacheMissToolsChanged,\n type BetaCacheMissUnavailable as BetaCacheMissUnavailable,\n type BetaCitationCharLocation as BetaCitationCharLocation,\n type BetaCitationCharLocationParam as BetaCitationCharLocationParam,\n type BetaCitationConfig as BetaCitationConfig,\n type BetaCitationContentBlockLocation as BetaCitationContentBlockLocation,\n type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,\n type BetaCitationPageLocation as BetaCitationPageLocation,\n type BetaCitationPageLocationParam as BetaCitationPageLocationParam,\n type BetaCitationSearchResultLocation as BetaCitationSearchResultLocation,\n type BetaCitationSearchResultLocationParam as BetaCitationSearchResultLocationParam,\n type BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam,\n type BetaCitationsConfigParam as BetaCitationsConfigParam,\n type BetaCitationsDelta as BetaCitationsDelta,\n type BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation,\n type BetaClearThinking20251015Edit as BetaClearThinking20251015Edit,\n type BetaClearThinking20251015EditResponse as BetaClearThinking20251015EditResponse,\n type BetaClearToolUses20250919Edit as BetaClearToolUses20250919Edit,\n type BetaClearToolUses20250919EditResponse as BetaClearToolUses20250919EditResponse,\n type BetaCodeExecutionOutputBlock as BetaCodeExecutionOutputBlock,\n type BetaCodeExecutionOutputBlockParam as BetaCodeExecutionOutputBlockParam,\n type BetaCodeExecutionResultBlock as BetaCodeExecutionResultBlock,\n type BetaCodeExecutionResultBlockParam as BetaCodeExecutionResultBlockParam,\n type BetaCodeExecutionTool20250522 as BetaCodeExecutionTool20250522,\n type BetaCodeExecutionTool20250825 as BetaCodeExecutionTool20250825,\n type BetaCodeExecutionTool20260120 as BetaCodeExecutionTool20260120,\n type BetaCodeExecutionTool20260521 as BetaCodeExecutionTool20260521,\n type BetaCodeExecutionToolResultBlock as BetaCodeExecutionToolResultBlock,\n type BetaCodeExecutionToolResultBlockContent as BetaCodeExecutionToolResultBlockContent,\n type BetaCodeExecutionToolResultBlockParam as BetaCodeExecutionToolResultBlockParam,\n type BetaCodeExecutionToolResultBlockParamContent as BetaCodeExecutionToolResultBlockParamContent,\n type BetaCodeExecutionToolResultError as BetaCodeExecutionToolResultError,\n type BetaCodeExecutionToolResultErrorCode as BetaCodeExecutionToolResultErrorCode,\n type BetaCodeExecutionToolResultErrorParam as BetaCodeExecutionToolResultErrorParam,\n type BetaCompact20260112Edit as BetaCompact20260112Edit,\n type BetaCompactionBlock as BetaCompactionBlock,\n type BetaCompactionBlockParam as BetaCompactionBlockParam,\n type BetaCompactionContentBlockDelta as BetaCompactionContentBlockDelta,\n type BetaCompactionIterationUsage as BetaCompactionIterationUsage,\n type BetaContainer as BetaContainer,\n type BetaContainerParams as BetaContainerParams,\n type BetaContainerUploadBlock as BetaContainerUploadBlock,\n type BetaContainerUploadBlockParam as BetaContainerUploadBlockParam,\n type BetaContentBlock as BetaContentBlock,\n type BetaContentBlockParam as BetaContentBlockParam,\n type BetaContentBlockSource as BetaContentBlockSource,\n type BetaContentBlockSourceContent as BetaContentBlockSourceContent,\n type BetaContextManagementConfig as BetaContextManagementConfig,\n type BetaContextManagementResponse as BetaContextManagementResponse,\n type BetaCountTokensContextManagementResponse as BetaCountTokensContextManagementResponse,\n type BetaDiagnostics as BetaDiagnostics,\n type BetaDiagnosticsParam as BetaDiagnosticsParam,\n type BetaDirectCaller as BetaDirectCaller,\n type BetaDocumentBlock as BetaDocumentBlock,\n type BetaEncryptedCodeExecutionResultBlock as BetaEncryptedCodeExecutionResultBlock,\n type BetaEncryptedCodeExecutionResultBlockParam as BetaEncryptedCodeExecutionResultBlockParam,\n type BetaFallbackBlock as BetaFallbackBlock,\n type BetaFallbackBlockParam as BetaFallbackBlockParam,\n type BetaFallbackInfo as BetaFallbackInfo,\n type BetaFallbackInfoParam as BetaFallbackInfoParam,\n type BetaFallbackMessageIterationUsage as BetaFallbackMessageIterationUsage,\n type BetaFallbackParam as BetaFallbackParam,\n type BetaFallbackRefusalTrigger as BetaFallbackRefusalTrigger,\n type BetaFileDocumentSource as BetaFileDocumentSource,\n type BetaFileImageSource as BetaFileImageSource,\n type BetaImageBlockParam as BetaImageBlockParam,\n type BetaInputJSONDelta as BetaInputJSONDelta,\n type BetaInputTokensClearAtLeast as BetaInputTokensClearAtLeast,\n type BetaInputTokensTrigger as BetaInputTokensTrigger,\n type BetaIterationsUsage as BetaIterationsUsage,\n type BetaJSONOutputFormat as BetaJSONOutputFormat,\n type BetaMCPToolConfig as BetaMCPToolConfig,\n type BetaMCPToolDefaultConfig as BetaMCPToolDefaultConfig,\n type BetaMCPToolResultBlock as BetaMCPToolResultBlock,\n type BetaMCPToolUseBlock as BetaMCPToolUseBlock,\n type BetaMCPToolUseBlockParam as BetaMCPToolUseBlockParam,\n type BetaMCPToolset as BetaMCPToolset,\n type BetaMemoryTool20250818 as BetaMemoryTool20250818,\n type BetaMemoryTool20250818Command as BetaMemoryTool20250818Command,\n type BetaMemoryTool20250818CreateCommand as BetaMemoryTool20250818CreateCommand,\n type BetaMemoryTool20250818DeleteCommand as BetaMemoryTool20250818DeleteCommand,\n type BetaMemoryTool20250818InsertCommand as BetaMemoryTool20250818InsertCommand,\n type BetaMemoryTool20250818RenameCommand as BetaMemoryTool20250818RenameCommand,\n type BetaMemoryTool20250818StrReplaceCommand as BetaMemoryTool20250818StrReplaceCommand,\n type BetaMemoryTool20250818ViewCommand as BetaMemoryTool20250818ViewCommand,\n type BetaMessage as BetaMessage,\n type BetaMessageDeltaUsage as BetaMessageDeltaUsage,\n type BetaMessageIterationUsage as BetaMessageIterationUsage,\n type BetaMessageParam as BetaMessageParam,\n type BetaMessageTokensCount as BetaMessageTokensCount,\n type BetaMetadata as BetaMetadata,\n type BetaMidConversationSystemBlockParam as BetaMidConversationSystemBlockParam,\n type BetaOutputConfig as BetaOutputConfig,\n type BetaOutputTokensDetails as BetaOutputTokensDetails,\n type BetaPlainTextSource as BetaPlainTextSource,\n type BetaRawContentBlockDelta as BetaRawContentBlockDelta,\n type BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent,\n type BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent,\n type BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent,\n type BetaRawMessageDeltaEvent as BetaRawMessageDeltaEvent,\n type BetaRawMessageStartEvent as BetaRawMessageStartEvent,\n type BetaRawMessageStopEvent as BetaRawMessageStopEvent,\n type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,\n type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,\n type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,\n type BetaRefusalStopDetails as BetaRefusalStopDetails,\n type BetaRequestDocumentBlock as BetaRequestDocumentBlock,\n type BetaRequestMCPServerToolConfiguration as BetaRequestMCPServerToolConfiguration,\n type BetaRequestMCPServerURLDefinition as BetaRequestMCPServerURLDefinition,\n type BetaRequestMCPToolResultBlockParam as BetaRequestMCPToolResultBlockParam,\n type BetaSearchResultBlockParam as BetaSearchResultBlockParam,\n type BetaServerToolCaller as BetaServerToolCaller,\n type BetaServerToolCaller20260120 as BetaServerToolCaller20260120,\n type BetaServerToolUsage as BetaServerToolUsage,\n type BetaServerToolUseBlock as BetaServerToolUseBlock,\n type BetaServerToolUseBlockParam as BetaServerToolUseBlockParam,\n type BetaSignatureDelta as BetaSignatureDelta,\n type BetaSkill as BetaSkill,\n type BetaSkillParams as BetaSkillParams,\n type BetaStopReason as BetaStopReason,\n type BetaTextBlock as BetaTextBlock,\n type BetaTextBlockParam as BetaTextBlockParam,\n type BetaTextCitation as BetaTextCitation,\n type BetaTextCitationParam as BetaTextCitationParam,\n type BetaTextDelta as BetaTextDelta,\n type BetaTextEditorCodeExecutionCreateResultBlock as BetaTextEditorCodeExecutionCreateResultBlock,\n type BetaTextEditorCodeExecutionCreateResultBlockParam as BetaTextEditorCodeExecutionCreateResultBlockParam,\n type BetaTextEditorCodeExecutionStrReplaceResultBlock as BetaTextEditorCodeExecutionStrReplaceResultBlock,\n type BetaTextEditorCodeExecutionStrReplaceResultBlockParam as BetaTextEditorCodeExecutionStrReplaceResultBlockParam,\n type BetaTextEditorCodeExecutionToolResultBlock as BetaTextEditorCodeExecutionToolResultBlock,\n type BetaTextEditorCodeExecutionToolResultBlockParam as BetaTextEditorCodeExecutionToolResultBlockParam,\n type BetaTextEditorCodeExecutionToolResultError as BetaTextEditorCodeExecutionToolResultError,\n type BetaTextEditorCodeExecutionToolResultErrorParam as BetaTextEditorCodeExecutionToolResultErrorParam,\n type BetaTextEditorCodeExecutionViewResultBlock as BetaTextEditorCodeExecutionViewResultBlock,\n type BetaTextEditorCodeExecutionViewResultBlockParam as BetaTextEditorCodeExecutionViewResultBlockParam,\n type BetaThinkingBlock as BetaThinkingBlock,\n type BetaThinkingBlockParam as BetaThinkingBlockParam,\n type BetaThinkingConfigAdaptive as BetaThinkingConfigAdaptive,\n type BetaThinkingConfigDisabled as BetaThinkingConfigDisabled,\n type BetaThinkingConfigEnabled as BetaThinkingConfigEnabled,\n type BetaThinkingConfigParam as BetaThinkingConfigParam,\n type BetaThinkingDelta as BetaThinkingDelta,\n type BetaThinkingTurns as BetaThinkingTurns,\n type BetaTokenTaskBudget as BetaTokenTaskBudget,\n type BetaTool as BetaTool,\n type BetaToolBash20241022 as BetaToolBash20241022,\n type BetaToolBash20250124 as BetaToolBash20250124,\n type BetaToolChoice as BetaToolChoice,\n type BetaToolChoiceAny as BetaToolChoiceAny,\n type BetaToolChoiceAuto as BetaToolChoiceAuto,\n type BetaToolChoiceNone as BetaToolChoiceNone,\n type BetaToolChoiceTool as BetaToolChoiceTool,\n type BetaToolComputerUse20241022 as BetaToolComputerUse20241022,\n type BetaToolComputerUse20250124 as BetaToolComputerUse20250124,\n type BetaToolComputerUse20251124 as BetaToolComputerUse20251124,\n type BetaToolReferenceBlock as BetaToolReferenceBlock,\n type BetaToolReferenceBlockParam as BetaToolReferenceBlockParam,\n type BetaToolResultBlockParam as BetaToolResultBlockParam,\n type BetaToolResultContentBlockParam as BetaToolResultContentBlockParam,\n type BetaToolSearchToolBm25_20251119 as BetaToolSearchToolBm25_20251119,\n type BetaToolSearchToolRegex20251119 as BetaToolSearchToolRegex20251119,\n type BetaToolSearchToolResultBlock as BetaToolSearchToolResultBlock,\n type BetaToolSearchToolResultBlockParam as BetaToolSearchToolResultBlockParam,\n type BetaToolSearchToolResultError as BetaToolSearchToolResultError,\n type BetaToolSearchToolResultErrorParam as BetaToolSearchToolResultErrorParam,\n type BetaToolSearchToolSearchResultBlock as BetaToolSearchToolSearchResultBlock,\n type BetaToolSearchToolSearchResultBlockParam as BetaToolSearchToolSearchResultBlockParam,\n type BetaToolTextEditor20241022 as BetaToolTextEditor20241022,\n type BetaToolTextEditor20250124 as BetaToolTextEditor20250124,\n type BetaToolTextEditor20250429 as BetaToolTextEditor20250429,\n type BetaToolTextEditor20250728 as BetaToolTextEditor20250728,\n type BetaToolUnion as BetaToolUnion,\n type BetaToolUseBlock as BetaToolUseBlock,\n type BetaToolUseBlockParam as BetaToolUseBlockParam,\n type BetaToolUsesKeep as BetaToolUsesKeep,\n type BetaToolUsesTrigger as BetaToolUsesTrigger,\n type BetaURLImageSource as BetaURLImageSource,\n type BetaURLPDFSource as BetaURLPDFSource,\n type BetaUsage as BetaUsage,\n type BetaUserLocation as BetaUserLocation,\n type BetaWebFetchBlock as BetaWebFetchBlock,\n type BetaWebFetchBlockParam as BetaWebFetchBlockParam,\n type BetaWebFetchTool20250910 as BetaWebFetchTool20250910,\n type BetaWebFetchTool20260209 as BetaWebFetchTool20260209,\n type BetaWebFetchTool20260309 as BetaWebFetchTool20260309,\n type BetaWebFetchToolResultBlock as BetaWebFetchToolResultBlock,\n type BetaWebFetchToolResultBlockParam as BetaWebFetchToolResultBlockParam,\n type BetaWebFetchToolResultErrorBlock as BetaWebFetchToolResultErrorBlock,\n type BetaWebFetchToolResultErrorBlockParam as BetaWebFetchToolResultErrorBlockParam,\n type BetaWebFetchToolResultErrorCode as BetaWebFetchToolResultErrorCode,\n type BetaWebSearchResultBlock as BetaWebSearchResultBlock,\n type BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam,\n type BetaWebSearchTool20250305 as BetaWebSearchTool20250305,\n type BetaWebSearchTool20260209 as BetaWebSearchTool20260209,\n type BetaWebSearchToolRequestError as BetaWebSearchToolRequestError,\n type BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock,\n type BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent,\n type BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam,\n type BetaWebSearchToolResultBlockParamContent as BetaWebSearchToolResultBlockParamContent,\n type BetaWebSearchToolResultError as BetaWebSearchToolResultError,\n type BetaWebSearchToolResultErrorCode as BetaWebSearchToolResultErrorCode,\n type BetaBase64PDFBlock as BetaBase64PDFBlock,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export { type BetaToolRunnerParams, BetaToolRunner };\n export { ToolError };\n\n export {\n Batches as Batches,\n type BetaDeletedMessageBatch as BetaDeletedMessageBatch,\n type BetaMessageBatch as BetaMessageBatch,\n type BetaMessageBatchCanceledResult as BetaMessageBatchCanceledResult,\n type BetaMessageBatchErroredResult as BetaMessageBatchErroredResult,\n type BetaMessageBatchExpiredResult as BetaMessageBatchExpiredResult,\n type BetaMessageBatchIndividualResponse as BetaMessageBatchIndividualResponse,\n type BetaMessageBatchRequestCounts as BetaMessageBatchRequestCounts,\n type BetaMessageBatchResult as BetaMessageBatchResult,\n type BetaMessageBatchSucceededResult as BetaMessageBatchSucceededResult,\n type BetaMessageBatchesPage as BetaMessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchRetrieveParams as BatchRetrieveParams,\n type BatchListParams as BatchListParams,\n type BatchDeleteParams as BatchDeleteParams,\n type BatchCancelParams as BatchCancelParams,\n type BatchResultsParams as BatchResultsParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport type { Anthropic } from '../../../client';\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as SessionsAPI from './sessions';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { Stream } from '../../../core/streaming';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\nimport {\n SessionToolRunner,\n type SessionToolRunnerOptions as RunnerSessionToolRunnerOptions,\n} from '../../../lib/tools/SessionToolRunner';\n\nexport class Events extends APIResource {\n /**\n * List Events\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsSessionEvent of client.beta.sessions.events.list(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n sessionID: string,\n params: EventListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsSessionEventsPageCursor, BetaManagedAgentsSessionEvent> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n path`/v1/sessions/${sessionID}/events?beta=true`,\n PageCursor<BetaManagedAgentsSessionEvent>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * Send Events\n *\n * @example\n * ```ts\n * const betaManagedAgentsSendSessionEvents =\n * await client.beta.sessions.events.send(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * {\n * events: [\n * {\n * content: [\n * {\n * text: 'Where is my order #1234?',\n * type: 'text',\n * },\n * ],\n * type: 'user.message',\n * },\n * ],\n * },\n * );\n * ```\n */\n send(\n sessionID: string,\n params: EventSendParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsSendSessionEvents> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/sessions/${sessionID}/events?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Stream Events\n *\n * @example\n * ```ts\n * const betaManagedAgentsStreamSessionEvents =\n * await client.beta.sessions.events.stream(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * );\n * ```\n */\n stream(\n sessionID: string,\n params: EventStreamParams | undefined = {},\n options?: RequestOptions,\n ): APIPromise<Stream<BetaManagedAgentsStreamSessionEvents>> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/sessions/${sessionID}/events/stream?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n stream: true,\n }) as APIPromise<Stream<BetaManagedAgentsStreamSessionEvents>>;\n }\n\n /**\n * Attach to a session and dispatch every incoming `agent.tool_use` and\n * `agent.custom_tool_use` event to a local tool registry, sending the matching\n * result back (`user.tool_result` / `user.custom_tool_result`). The\n * sessions-side counterpart to `client.beta.messages.toolRunner`: yields one\n * entry per completed tool call so callers can observe each dispatch (and\n * `break` to abort cleanly).\n *\n * @example\n * ```ts\n * import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node';\n *\n * for await (const call of client.beta.sessions.events.toolRunner(work.data.id, {\n * tools: [...betaAgentToolset20260401({ workdir }), myTool],\n * })) {\n * console.log(`${call.name} -> ${call.isError ? 'error' : 'ok'}`);\n * }\n * ```\n */\n toolRunner(sessionID: string, opts: Omit<RunnerSessionToolRunnerOptions, 'client'>): SessionToolRunner {\n return new SessionToolRunner(sessionID, { ...opts, client: this._client as Anthropic });\n }\n}\n\nexport type BetaManagedAgentsSessionEventsPageCursor = PageCursor<BetaManagedAgentsSessionEvent>;\n\n/**\n * Event emitted when the agent calls a custom tool. The session goes idle until\n * the client sends a `user.custom_tool_result` event with the result.\n */\nexport interface BetaManagedAgentsAgentCustomToolUseEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Input parameters for the tool call.\n */\n input: { [key: string]: unknown };\n\n /**\n * Name of the custom tool being called.\n */\n name: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'agent.custom_tool_use';\n\n /**\n * When set, this event was cross-posted from a subagent's thread to surface its\n * custom tool use on the primary thread's stream. Empty on the thread's own\n * events. Echo this on a `user.custom_tool_result` event to route the result back.\n */\n session_thread_id?: string | null;\n}\n\n/**\n * Event representing the result of an MCP tool execution.\n */\nexport interface BetaManagedAgentsAgentMCPToolResultEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * The id of the `agent.mcp_tool_use` event this result corresponds to.\n */\n mcp_tool_use_id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'agent.mcp_tool_result';\n\n /**\n * The result content returned by the tool.\n */\n content?: Array<\n | BetaManagedAgentsTextBlock\n | BetaManagedAgentsImageBlock\n | BetaManagedAgentsDocumentBlock\n | BetaManagedAgentsSearchResultBlock\n >;\n\n /**\n * Whether the tool execution resulted in an error.\n */\n is_error?: boolean | null;\n}\n\n/**\n * Event emitted when the agent invokes a tool provided by an MCP server.\n */\nexport interface BetaManagedAgentsAgentMCPToolUseEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Input parameters for the tool call.\n */\n input: { [key: string]: unknown };\n\n /**\n * Name of the MCP server providing the tool.\n */\n mcp_server_name: string;\n\n /**\n * Name of the MCP tool being used.\n */\n name: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'agent.mcp_tool_use';\n\n /**\n * AgentEvaluatedPermission enum\n */\n evaluated_permission?: 'allow' | 'ask' | 'deny';\n\n /**\n * When set, this event was cross-posted from a subagent's thread to surface its\n * permission request on the primary thread's stream. Empty on the thread's own\n * events. Echo this on a `user.tool_confirmation` event to route the approval\n * back.\n */\n session_thread_id?: string | null;\n}\n\n/**\n * An agent response event in the session conversation.\n */\nexport interface BetaManagedAgentsAgentMessageEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Array of text blocks comprising the agent response.\n */\n content: Array<BetaManagedAgentsTextBlock>;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'agent.message';\n}\n\n/**\n * Indicates the agent is making forward progress via extended thinking. A progress\n * signal, not a content carrier.\n */\nexport interface BetaManagedAgentsAgentThinkingEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'agent.thinking';\n}\n\n/**\n * Indicates that context compaction (summarization) occurred during the session.\n */\nexport interface BetaManagedAgentsAgentThreadContextCompactedEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'agent.thread_context_compacted';\n}\n\n/**\n * Delivery event written to the target thread's input stream when an\n * agent-to-agent message arrives.\n */\nexport interface BetaManagedAgentsAgentThreadMessageReceivedEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Message content blocks.\n */\n content: Array<BetaManagedAgentsTextBlock | BetaManagedAgentsImageBlock | BetaManagedAgentsDocumentBlock>;\n\n /**\n * Public `sthr_` ID of the thread that sent the message.\n */\n from_session_thread_id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'agent.thread_message_received';\n\n /**\n * Name of the callable agent this message came from. Absent when received from the\n * primary agent.\n */\n from_agent_name?: string | null;\n}\n\n/**\n * Observability event emitted to the sender's output stream when an agent-to-agent\n * message is sent.\n */\nexport interface BetaManagedAgentsAgentThreadMessageSentEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Message content blocks.\n */\n content: Array<BetaManagedAgentsTextBlock | BetaManagedAgentsImageBlock | BetaManagedAgentsDocumentBlock>;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * Public `sthr_` ID of the thread the message was sent to.\n */\n to_session_thread_id: string;\n\n type: 'agent.thread_message_sent';\n\n /**\n * Name of the callable agent this message was sent to. Absent when sent to the\n * primary agent.\n */\n to_agent_name?: string | null;\n}\n\n/**\n * Event representing the result of an agent tool execution.\n */\nexport interface BetaManagedAgentsAgentToolResultEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * The id of the `agent.tool_use` event this result corresponds to.\n */\n tool_use_id: string;\n\n type: 'agent.tool_result';\n\n /**\n * The result content returned by the tool.\n */\n content?: Array<\n | BetaManagedAgentsTextBlock\n | BetaManagedAgentsImageBlock\n | BetaManagedAgentsDocumentBlock\n | BetaManagedAgentsSearchResultBlock\n >;\n\n /**\n * Whether the tool execution resulted in an error.\n */\n is_error?: boolean | null;\n}\n\n/**\n * Event emitted when the agent invokes a built-in agent tool.\n */\nexport interface BetaManagedAgentsAgentToolUseEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Input parameters for the tool call.\n */\n input: { [key: string]: unknown };\n\n /**\n * Name of the agent tool being used.\n */\n name: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'agent.tool_use';\n\n /**\n * AgentEvaluatedPermission enum\n */\n evaluated_permission?: 'allow' | 'ask' | 'deny';\n\n /**\n * When set, this event was cross-posted from a subagent's thread to surface its\n * permission request on the primary thread's stream. Empty on the thread's own\n * events. Echo this on a `user.tool_confirmation` event to route the approval\n * back.\n */\n session_thread_id?: string | null;\n}\n\n/**\n * Base64-encoded document data.\n */\nexport interface BetaManagedAgentsBase64DocumentSource {\n /**\n * Base64-encoded document data.\n */\n data: string;\n\n /**\n * MIME type of the document (e.g., \"application/pdf\").\n */\n media_type: string;\n\n type: 'base64';\n}\n\n/**\n * Base64-encoded image data.\n */\nexport interface BetaManagedAgentsBase64ImageSource {\n /**\n * Base64-encoded image data.\n */\n data: string;\n\n /**\n * MIME type of the image (e.g., \"image/png\", \"image/jpeg\", \"image/gif\",\n * \"image/webp\").\n */\n media_type: string;\n\n type: 'base64';\n}\n\n/**\n * The caller's organization or workspace cannot make model requests — out of\n * credits or spend limit reached. Retrying with the same credentials will not\n * succeed; the caller must resolve the billing state.\n */\nexport interface BetaManagedAgentsBillingError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n /**\n * What the client should do next in response to this error.\n */\n retry_status:\n | BetaManagedAgentsRetryStatusRetrying\n | BetaManagedAgentsRetryStatusExhausted\n | BetaManagedAgentsRetryStatusTerminal;\n\n type: 'billing_error';\n}\n\n/**\n * An `environment_variable` credential's `auth.networking.allowed_hosts` includes\n * a host the environment's network policy does not permit.\n */\nexport interface BetaManagedAgentsCredentialHostUnreachableError {\n /**\n * ID of the affected credential.\n */\n credential_id: string;\n\n /**\n * Human-readable error description.\n */\n message: string;\n\n /**\n * What the client should do next in response to this error.\n */\n retry_status:\n | BetaManagedAgentsRetryStatusRetrying\n | BetaManagedAgentsRetryStatusExhausted\n | BetaManagedAgentsRetryStatusTerminal;\n\n type: 'credential_host_unreachable_error';\n\n /**\n * ID of the vault containing the affected credential.\n */\n vault_id: string;\n}\n\n/**\n * Document content, either specified directly as base64 data, as text, or as a\n * reference via a URL.\n */\nexport interface BetaManagedAgentsDocumentBlock {\n /**\n * Union type for document source variants.\n */\n source:\n | BetaManagedAgentsBase64DocumentSource\n | BetaManagedAgentsPlainTextDocumentSource\n | BetaManagedAgentsURLDocumentSource\n | BetaManagedAgentsFileDocumentSource;\n\n type: 'document';\n\n /**\n * Additional context about the document for the model.\n */\n context?: string | null;\n\n /**\n * The title of the document.\n */\n title?: string | null;\n}\n\n/**\n * Union type for event parameters that can be sent to a session.\n */\nexport type BetaManagedAgentsEventParams =\n | BetaManagedAgentsUserMessageEventParams\n | BetaManagedAgentsUserInterruptEventParams\n | BetaManagedAgentsUserToolConfirmationEventParams\n | BetaManagedAgentsUserCustomToolResultEventParams\n | BetaManagedAgentsUserDefineOutcomeEventParams\n | BetaManagedAgentsUserToolResultEventParams\n | BetaManagedAgentsSystemMessageEventParams;\n\n/**\n * Document referenced by file ID.\n */\nexport interface BetaManagedAgentsFileDocumentSource {\n /**\n * ID of a previously uploaded file.\n */\n file_id: string;\n\n type: 'file';\n}\n\n/**\n * Image referenced by file ID.\n */\nexport interface BetaManagedAgentsFileImageSource {\n /**\n * ID of a previously uploaded file.\n */\n file_id: string;\n\n type: 'file';\n}\n\n/**\n * Rubric referenced by a file uploaded via the Files API.\n */\nexport interface BetaManagedAgentsFileRubric {\n /**\n * ID of the rubric file.\n */\n file_id: string;\n\n type: 'file';\n}\n\n/**\n * Rubric referenced by a file uploaded via the Files API.\n */\nexport interface BetaManagedAgentsFileRubricParams {\n /**\n * ID of the rubric file.\n */\n file_id: string;\n\n type: 'file';\n}\n\n/**\n * Image content specified directly as base64 data or as a reference via a URL.\n */\nexport interface BetaManagedAgentsImageBlock {\n /**\n * Union type for image source variants.\n */\n source:\n | BetaManagedAgentsBase64ImageSource\n | BetaManagedAgentsURLImageSource\n | BetaManagedAgentsFileImageSource;\n\n type: 'image';\n}\n\n/**\n * Authentication to an MCP server failed.\n */\nexport interface BetaManagedAgentsMCPAuthenticationFailedError {\n /**\n * Name of the MCP server that failed authentication.\n */\n mcp_server_name: string;\n\n /**\n * Human-readable error description.\n */\n message: string;\n\n /**\n * What the client should do next in response to this error.\n */\n retry_status:\n | BetaManagedAgentsRetryStatusRetrying\n | BetaManagedAgentsRetryStatusExhausted\n | BetaManagedAgentsRetryStatusTerminal;\n\n type: 'mcp_authentication_failed_error';\n}\n\n/**\n * Failed to connect to an MCP server.\n */\nexport interface BetaManagedAgentsMCPConnectionFailedError {\n /**\n * Name of the MCP server that failed to connect.\n */\n mcp_server_name: string;\n\n /**\n * Human-readable error description.\n */\n message: string;\n\n /**\n * What the client should do next in response to this error.\n */\n retry_status:\n | BetaManagedAgentsRetryStatusRetrying\n | BetaManagedAgentsRetryStatusExhausted\n | BetaManagedAgentsRetryStatusTerminal;\n\n type: 'mcp_connection_failed_error';\n}\n\n/**\n * The model is currently overloaded. Emitted after automatic retries are\n * exhausted.\n */\nexport interface BetaManagedAgentsModelOverloadedError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n /**\n * What the client should do next in response to this error.\n */\n retry_status:\n | BetaManagedAgentsRetryStatusRetrying\n | BetaManagedAgentsRetryStatusExhausted\n | BetaManagedAgentsRetryStatusTerminal;\n\n type: 'model_overloaded_error';\n}\n\n/**\n * The model request was rate-limited.\n */\nexport interface BetaManagedAgentsModelRateLimitedError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n /**\n * What the client should do next in response to this error.\n */\n retry_status:\n | BetaManagedAgentsRetryStatusRetrying\n | BetaManagedAgentsRetryStatusExhausted\n | BetaManagedAgentsRetryStatusTerminal;\n\n type: 'model_rate_limited_error';\n}\n\n/**\n * A model request failed for a reason other than overload or rate-limiting.\n */\nexport interface BetaManagedAgentsModelRequestFailedError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n /**\n * What the client should do next in response to this error.\n */\n retry_status:\n | BetaManagedAgentsRetryStatusRetrying\n | BetaManagedAgentsRetryStatusExhausted\n | BetaManagedAgentsRetryStatusTerminal;\n\n type: 'model_request_failed_error';\n}\n\n/**\n * Plain text document content.\n */\nexport interface BetaManagedAgentsPlainTextDocumentSource {\n /**\n * The plain text content.\n */\n data: string;\n\n /**\n * MIME type of the text content. Must be \"text/plain\".\n */\n media_type: 'text/plain';\n\n type: 'text';\n}\n\n/**\n * This turn is dead; queued inputs are flushed and the session returns to idle.\n * Client may send a new prompt.\n */\nexport interface BetaManagedAgentsRetryStatusExhausted {\n type: 'exhausted';\n}\n\n/**\n * The server is retrying automatically. Client should wait; the same error type\n * may fire again as retrying, then once as exhausted when the retry budget runs\n * out.\n */\nexport interface BetaManagedAgentsRetryStatusRetrying {\n type: 'retrying';\n}\n\n/**\n * The session encountered a terminal error and will transition to `terminated`\n * state.\n */\nexport interface BetaManagedAgentsRetryStatusTerminal {\n type: 'terminal';\n}\n\n/**\n * A block containing a web search result.\n */\nexport interface BetaManagedAgentsSearchResultBlock {\n /**\n * Citation settings for a search result.\n */\n citations: BetaManagedAgentsSearchResultCitations;\n\n /**\n * Array of text content blocks from the search result.\n */\n content: Array<BetaManagedAgentsSearchResultContent>;\n\n /**\n * The URL source of the search result.\n */\n source: string;\n\n /**\n * The title of the search result.\n */\n title: string;\n\n type: 'search_result';\n}\n\n/**\n * Citation settings for a search result.\n */\nexport interface BetaManagedAgentsSearchResultCitations {\n /**\n * Whether citations are enabled for this search result.\n */\n enabled: boolean;\n}\n\n/**\n * Text content within a search result.\n */\nexport interface BetaManagedAgentsSearchResultContent {\n /**\n * The text content.\n */\n text: string;\n\n type: 'text';\n}\n\n/**\n * Events that were successfully sent to the session.\n */\nexport interface BetaManagedAgentsSendSessionEvents {\n /**\n * Sent events\n */\n data?: Array<\n | BetaManagedAgentsUserMessageEvent\n | BetaManagedAgentsUserInterruptEvent\n | BetaManagedAgentsUserToolConfirmationEvent\n | BetaManagedAgentsUserCustomToolResultEvent\n | BetaManagedAgentsUserDefineOutcomeEvent\n | SessionsAPI.BetaManagedAgentsUserToolResultEvent\n | SessionsAPI.BetaManagedAgentsSystemMessageEvent\n >;\n}\n\n/**\n * Emitted when a session has been deleted. Terminates any active event stream — no\n * further events will be emitted for this session.\n */\nexport interface BetaManagedAgentsSessionDeletedEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'session.deleted';\n}\n\n/**\n * The agent completed its turn naturally and is ready for the next user message.\n */\nexport interface BetaManagedAgentsSessionEndTurn {\n type: 'end_turn';\n}\n\n/**\n * An error event indicating a problem occurred during session execution.\n */\nexport interface BetaManagedAgentsSessionErrorEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * An unknown or unexpected error occurred during session execution. A fallback\n * variant; clients that don't recognize a new error code can match on\n * `retry_status` and `message` alone.\n */\n error:\n | BetaManagedAgentsUnknownError\n | BetaManagedAgentsModelOverloadedError\n | BetaManagedAgentsModelRateLimitedError\n | BetaManagedAgentsModelRequestFailedError\n | BetaManagedAgentsMCPConnectionFailedError\n | BetaManagedAgentsMCPAuthenticationFailedError\n | BetaManagedAgentsBillingError\n | BetaManagedAgentsCredentialHostUnreachableError;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'session.error';\n}\n\n/**\n * Union type for all event types in a session.\n */\nexport type BetaManagedAgentsSessionEvent =\n | BetaManagedAgentsUserMessageEvent\n | BetaManagedAgentsUserInterruptEvent\n | BetaManagedAgentsUserToolConfirmationEvent\n | BetaManagedAgentsUserCustomToolResultEvent\n | BetaManagedAgentsAgentCustomToolUseEvent\n | BetaManagedAgentsAgentMessageEvent\n | BetaManagedAgentsAgentThinkingEvent\n | BetaManagedAgentsAgentMCPToolUseEvent\n | BetaManagedAgentsAgentMCPToolResultEvent\n | BetaManagedAgentsAgentToolUseEvent\n | BetaManagedAgentsAgentToolResultEvent\n | BetaManagedAgentsAgentThreadMessageReceivedEvent\n | BetaManagedAgentsAgentThreadMessageSentEvent\n | BetaManagedAgentsAgentThreadContextCompactedEvent\n | BetaManagedAgentsSessionErrorEvent\n | BetaManagedAgentsSessionStatusRescheduledEvent\n | BetaManagedAgentsSessionStatusRunningEvent\n | BetaManagedAgentsSessionStatusIdleEvent\n | BetaManagedAgentsSessionStatusTerminatedEvent\n | BetaManagedAgentsSessionThreadCreatedEvent\n | BetaManagedAgentsSpanOutcomeEvaluationStartEvent\n | BetaManagedAgentsSpanOutcomeEvaluationEndEvent\n | BetaManagedAgentsSpanModelRequestStartEvent\n | BetaManagedAgentsSpanModelRequestEndEvent\n | BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent\n | BetaManagedAgentsUserDefineOutcomeEvent\n | BetaManagedAgentsSessionDeletedEvent\n | BetaManagedAgentsSessionThreadStatusRunningEvent\n | BetaManagedAgentsSessionThreadStatusIdleEvent\n | BetaManagedAgentsSessionThreadStatusTerminatedEvent\n | SessionsAPI.BetaManagedAgentsUserToolResultEvent\n | BetaManagedAgentsSessionThreadStatusRescheduledEvent\n | SessionsAPI.BetaManagedAgentsSessionUpdatedEvent\n | SessionsAPI.BetaManagedAgentsSystemMessageEvent;\n\n/**\n * The agent is idle waiting on one or more blocking user-input events (tool\n * confirmation, custom tool result, etc.). Resolving all of them transitions the\n * session back to running.\n */\nexport interface BetaManagedAgentsSessionRequiresAction {\n /**\n * The ids of events the agent is blocked on. Resolving fewer than all re-emits\n * `session.status_idle` with the remainder.\n */\n event_ids: Array<string>;\n\n type: 'requires_action';\n}\n\n/**\n * The turn ended because the retry budget was exhausted (`max_iterations` hit or\n * an error escalated to `retry_status: 'exhausted'`).\n */\nexport interface BetaManagedAgentsSessionRetriesExhausted {\n type: 'retries_exhausted';\n}\n\n/**\n * Indicates the agent has paused and is awaiting user input.\n */\nexport interface BetaManagedAgentsSessionStatusIdleEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * The agent completed its turn naturally and is ready for the next user message.\n */\n stop_reason:\n | BetaManagedAgentsSessionEndTurn\n | BetaManagedAgentsSessionRequiresAction\n | BetaManagedAgentsSessionRetriesExhausted;\n\n type: 'session.status_idle';\n}\n\n/**\n * Indicates the session is recovering from an error state and is rescheduled for\n * execution.\n */\nexport interface BetaManagedAgentsSessionStatusRescheduledEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'session.status_rescheduled';\n}\n\n/**\n * Indicates the session is actively running and the agent is working.\n */\nexport interface BetaManagedAgentsSessionStatusRunningEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'session.status_running';\n}\n\n/**\n * Indicates the session has terminated, either due to an error or completion.\n */\nexport interface BetaManagedAgentsSessionStatusTerminatedEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'session.status_terminated';\n}\n\n/**\n * Emitted when a subagent is spawned as a new thread. Written to the parent\n * thread's output stream so clients observing the session see child creation.\n */\nexport interface BetaManagedAgentsSessionThreadCreatedEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Name of the callable agent the thread runs.\n */\n agent_name: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * Public `sthr_` ID of the newly created thread.\n */\n session_thread_id: string;\n\n type: 'session.thread_created';\n}\n\n/**\n * A session thread has yielded and is awaiting input. Emitted on the thread's own\n * stream and cross-posted to the primary stream for child threads.\n */\nexport interface BetaManagedAgentsSessionThreadStatusIdleEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Name of the agent the thread runs.\n */\n agent_name: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * Public sthr\\_ ID of the thread that went idle.\n */\n session_thread_id: string;\n\n /**\n * The agent completed its turn naturally and is ready for the next user message.\n */\n stop_reason:\n | BetaManagedAgentsSessionEndTurn\n | BetaManagedAgentsSessionRequiresAction\n | BetaManagedAgentsSessionRetriesExhausted;\n\n type: 'session.thread_status_idle';\n}\n\n/**\n * A session thread hit a transient error and is retrying automatically. Emitted on\n * the thread's own stream and cross-posted to the primary stream for child\n * threads.\n */\nexport interface BetaManagedAgentsSessionThreadStatusRescheduledEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Name of the agent the thread runs.\n */\n agent_name: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * Public sthr\\_ ID of the thread that is retrying.\n */\n session_thread_id: string;\n\n type: 'session.thread_status_rescheduled';\n}\n\n/**\n * A session thread has begun executing. Emitted on the thread's own stream and\n * cross-posted to the primary stream for child threads.\n */\nexport interface BetaManagedAgentsSessionThreadStatusRunningEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Name of the agent the thread runs.\n */\n agent_name: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * Public sthr\\_ ID of the thread that started running.\n */\n session_thread_id: string;\n\n type: 'session.thread_status_running';\n}\n\n/**\n * A session thread has terminated and will accept no further input. Emitted on the\n * thread's own stream and cross-posted to the primary stream for child threads.\n */\nexport interface BetaManagedAgentsSessionThreadStatusTerminatedEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Name of the agent the thread runs.\n */\n agent_name: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * Public sthr\\_ ID of the thread that terminated.\n */\n session_thread_id: string;\n\n type: 'session.thread_status_terminated';\n}\n\n/**\n * Emitted when a model request completes.\n */\nexport interface BetaManagedAgentsSpanModelRequestEndEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Whether the model request resulted in an error.\n */\n is_error: boolean | null;\n\n /**\n * The id of the corresponding `span.model_request_start` event.\n */\n model_request_start_id: string;\n\n /**\n * Token usage for a single model request.\n */\n model_usage: BetaManagedAgentsSpanModelUsage;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'span.model_request_end';\n}\n\n/**\n * Emitted when a model request is initiated by the agent.\n */\nexport interface BetaManagedAgentsSpanModelRequestStartEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'span.model_request_start';\n}\n\n/**\n * Token usage for a single model request.\n */\nexport interface BetaManagedAgentsSpanModelUsage {\n /**\n * Tokens used to create prompt cache in this request.\n */\n cache_creation_input_tokens: number;\n\n /**\n * Tokens read from prompt cache in this request.\n */\n cache_read_input_tokens: number;\n\n /**\n * Input tokens consumed by this request.\n */\n input_tokens: number;\n\n /**\n * Output tokens generated by this request.\n */\n output_tokens: number;\n\n /**\n * Inference speed mode. `fast` provides significantly faster output token\n * generation at premium pricing. Not all models support `fast`; invalid\n * combinations are rejected at create time.\n */\n speed?: 'standard' | 'fast' | null;\n}\n\n/**\n * Emitted when an outcome evaluation cycle completes. Carries the verdict and\n * aggregate token usage. A verdict of `needs_revision` means another evaluation\n * cycle follows; `satisfied`, `max_iterations_reached`, `failed`, or `interrupted`\n * are terminal — no further evaluation cycles follow.\n */\nexport interface BetaManagedAgentsSpanOutcomeEvaluationEndEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Human-readable explanation of the verdict. For `needs_revision`, describes which\n * criteria failed and why.\n */\n explanation: string;\n\n /**\n * 0-indexed revision cycle, matching the corresponding\n * `span.outcome_evaluation_start`.\n */\n iteration: number;\n\n /**\n * The id of the corresponding `span.outcome_evaluation_start` event.\n */\n outcome_evaluation_start_id: string;\n\n /**\n * The `outc_` ID of the outcome being evaluated.\n */\n outcome_id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * Evaluation verdict. 'satisfied': criteria met, session goes idle.\n * 'needs_revision': criteria not met, another revision cycle follows.\n * 'max_iterations_reached': evaluation budget exhausted with criteria still unmet\n * — one final acknowledgment turn follows before the session goes idle, but no\n * further evaluation runs. 'failed': grader determined the rubric does not apply\n * to the deliverables. 'interrupted': user sent an interrupt while evaluation was\n * in progress.\n */\n result: string;\n\n type: 'span.outcome_evaluation_end';\n\n /**\n * Token usage for a single model request.\n */\n usage: BetaManagedAgentsSpanModelUsage;\n}\n\n/**\n * Periodic heartbeat emitted while an outcome evaluation cycle is in progress.\n * Distinguishes 'evaluation is actively running' from 'evaluation is stuck'\n * between the corresponding `span.outcome_evaluation_start` and\n * `span.outcome_evaluation_end` events.\n */\nexport interface BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * 0-indexed revision cycle, matching the corresponding\n * `span.outcome_evaluation_start`.\n */\n iteration: number;\n\n /**\n * The `outc_` ID of the outcome being evaluated.\n */\n outcome_id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'span.outcome_evaluation_ongoing';\n}\n\n/**\n * Emitted when an outcome evaluation cycle begins.\n */\nexport interface BetaManagedAgentsSpanOutcomeEvaluationStartEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * 0-indexed revision cycle. 0 is the first evaluation; 1 is the re-evaluation\n * after the first revision; etc.\n */\n iteration: number;\n\n /**\n * The `outc_` ID of the outcome being evaluated.\n */\n outcome_id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'span.outcome_evaluation_start';\n}\n\n/**\n * Server-sent event in the session stream.\n */\nexport type BetaManagedAgentsStreamSessionEvents =\n | BetaManagedAgentsUserMessageEvent\n | BetaManagedAgentsUserInterruptEvent\n | BetaManagedAgentsUserToolConfirmationEvent\n | BetaManagedAgentsUserCustomToolResultEvent\n | BetaManagedAgentsAgentCustomToolUseEvent\n | BetaManagedAgentsAgentMessageEvent\n | BetaManagedAgentsAgentThinkingEvent\n | BetaManagedAgentsAgentMCPToolUseEvent\n | BetaManagedAgentsAgentMCPToolResultEvent\n | BetaManagedAgentsAgentToolUseEvent\n | BetaManagedAgentsAgentToolResultEvent\n | BetaManagedAgentsAgentThreadMessageReceivedEvent\n | BetaManagedAgentsAgentThreadMessageSentEvent\n | BetaManagedAgentsAgentThreadContextCompactedEvent\n | BetaManagedAgentsSessionErrorEvent\n | BetaManagedAgentsSessionStatusRescheduledEvent\n | BetaManagedAgentsSessionStatusRunningEvent\n | BetaManagedAgentsSessionStatusIdleEvent\n | BetaManagedAgentsSessionStatusTerminatedEvent\n | BetaManagedAgentsSessionThreadCreatedEvent\n | BetaManagedAgentsSpanOutcomeEvaluationStartEvent\n | BetaManagedAgentsSpanOutcomeEvaluationEndEvent\n | BetaManagedAgentsSpanModelRequestStartEvent\n | BetaManagedAgentsSpanModelRequestEndEvent\n | BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent\n | BetaManagedAgentsUserDefineOutcomeEvent\n | BetaManagedAgentsSessionDeletedEvent\n | BetaManagedAgentsSessionThreadStatusRunningEvent\n | BetaManagedAgentsSessionThreadStatusIdleEvent\n | BetaManagedAgentsSessionThreadStatusTerminatedEvent\n | SessionsAPI.BetaManagedAgentsUserToolResultEvent\n | BetaManagedAgentsSessionThreadStatusRescheduledEvent\n | SessionsAPI.BetaManagedAgentsSessionUpdatedEvent\n | SessionsAPI.BetaManagedAgentsSystemMessageEvent;\n\n/**\n * Privileged context for the accompanying turn and all subsequent turns, appended\n * to the session's system context as a `role: \"system\"` turn rather than replacing\n * the top-level system prompt. At most one per request: it must be the final event\n * and immediately follow the `user.message`, `user.tool_result`, or\n * `user.custom_tool_result` it accompanies. Only supported on models that accept\n * mid-conversation system messages.\n */\nexport interface BetaManagedAgentsSystemMessageEventParams {\n /**\n * System content blocks to append. Text-only.\n */\n content: Array<SessionsAPI.BetaManagedAgentsSystemContentBlock>;\n\n type: 'system.message';\n}\n\n/**\n * Regular text content.\n */\nexport interface BetaManagedAgentsTextBlock {\n /**\n * The text content.\n */\n text: string;\n\n type: 'text';\n}\n\n/**\n * Rubric content provided inline as text.\n */\nexport interface BetaManagedAgentsTextRubric {\n /**\n * Rubric content. Plain text or markdown — the grader treats it as freeform text.\n */\n content: string;\n\n type: 'text';\n}\n\n/**\n * Rubric content provided inline as text.\n */\nexport interface BetaManagedAgentsTextRubricParams {\n /**\n * Rubric content. Plain text or markdown — the grader treats it as freeform text.\n * Maximum 262144 characters.\n */\n content: string;\n\n type: 'text';\n}\n\n/**\n * An unknown or unexpected error occurred during session execution. A fallback\n * variant; clients that don't recognize a new error code can match on\n * `retry_status` and `message` alone.\n */\nexport interface BetaManagedAgentsUnknownError {\n /**\n * Human-readable error description.\n */\n message: string;\n\n /**\n * What the client should do next in response to this error.\n */\n retry_status:\n | BetaManagedAgentsRetryStatusRetrying\n | BetaManagedAgentsRetryStatusExhausted\n | BetaManagedAgentsRetryStatusTerminal;\n\n type: 'unknown_error';\n}\n\n/**\n * Document referenced by URL.\n */\nexport interface BetaManagedAgentsURLDocumentSource {\n type: 'url';\n\n /**\n * URL of the document to fetch.\n */\n url: string;\n}\n\n/**\n * Image referenced by URL.\n */\nexport interface BetaManagedAgentsURLImageSource {\n type: 'url';\n\n /**\n * URL of the image to fetch.\n */\n url: string;\n}\n\n/**\n * Event sent by the client providing the result of a custom tool execution.\n */\nexport interface BetaManagedAgentsUserCustomToolResultEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * The id of the `agent.custom_tool_use` event this result corresponds to, which\n * can be found in the last `session.status_idle`\n * [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids)\n * `stop_reason.event_ids` field.\n */\n custom_tool_use_id: string;\n\n type: 'user.custom_tool_result';\n\n /**\n * The result content returned by the tool.\n */\n content?: Array<\n | BetaManagedAgentsTextBlock\n | BetaManagedAgentsImageBlock\n | BetaManagedAgentsDocumentBlock\n | BetaManagedAgentsSearchResultBlock\n >;\n\n /**\n * Whether the tool execution resulted in an error.\n */\n is_error?: boolean | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at?: string | null;\n\n /**\n * Routes this result to a subagent thread. Copy from the `agent.custom_tool_use`\n * event's `session_thread_id`.\n */\n session_thread_id?: string | null;\n}\n\n/**\n * Parameters for providing the result of a custom tool execution.\n */\nexport interface BetaManagedAgentsUserCustomToolResultEventParams {\n /**\n * The id of the `agent.custom_tool_use` event this result corresponds to, which\n * can be found in the last `session.status_idle`\n * [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids)\n * `stop_reason.event_ids` field.\n */\n custom_tool_use_id: string;\n\n type: 'user.custom_tool_result';\n\n /**\n * The result content returned by the tool.\n */\n content?: Array<\n | BetaManagedAgentsTextBlock\n | BetaManagedAgentsImageBlock\n | BetaManagedAgentsDocumentBlock\n | BetaManagedAgentsSearchResultBlock\n >;\n\n /**\n * Whether the tool execution resulted in an error.\n */\n is_error?: boolean | null;\n}\n\n/**\n * Echo of a `user.define_outcome` input event. Carries the server-generated\n * `outcome_id` that subsequent `span.outcome_evaluation_*` events reference.\n */\nexport interface BetaManagedAgentsUserDefineOutcomeEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * What the agent should produce. Copied from the input event.\n */\n description: string;\n\n /**\n * Evaluate-then-revise cycles before giving up. Default 3, max 20.\n */\n max_iterations: number | null;\n\n /**\n * Server-generated `outc_` ID for this outcome. Referenced by\n * `span.outcome_evaluation_*` events and the session's `outcome_evaluations` list.\n */\n outcome_id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n /**\n * Rubric for grading the quality of an outcome.\n */\n rubric: BetaManagedAgentsFileRubric | BetaManagedAgentsTextRubric;\n\n type: 'user.define_outcome';\n}\n\n/**\n * Parameters for defining an outcome the agent should work toward. The agent\n * begins work on receipt.\n */\nexport interface BetaManagedAgentsUserDefineOutcomeEventParams {\n /**\n * What the agent should produce. This is the task specification.\n */\n description: string;\n\n /**\n * Rubric for grading the quality of an outcome.\n */\n rubric: BetaManagedAgentsFileRubricParams | BetaManagedAgentsTextRubricParams;\n\n type: 'user.define_outcome';\n\n /**\n * Eval→revision cycles before giving up. Default 3, max 20.\n */\n max_iterations?: number | null;\n}\n\n/**\n * An interrupt event that pauses agent execution and returns control to the user.\n */\nexport interface BetaManagedAgentsUserInterruptEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n type: 'user.interrupt';\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at?: string | null;\n\n /**\n * If absent, interrupts every non-archived thread in a multiagent session (or the\n * primary alone in a single-agent session). If present, interrupts only the named\n * thread.\n */\n session_thread_id?: string | null;\n}\n\n/**\n * Parameters for sending an interrupt to pause the agent.\n */\nexport interface BetaManagedAgentsUserInterruptEventParams {\n type: 'user.interrupt';\n\n /**\n * If absent, interrupts every non-archived thread in a multiagent session (or the\n * primary alone in a single-agent session). If present, interrupts only the named\n * thread.\n */\n session_thread_id?: string | null;\n}\n\n/**\n * A user message event in the session conversation.\n */\nexport interface BetaManagedAgentsUserMessageEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * Array of content blocks comprising the user message.\n */\n content: Array<BetaManagedAgentsTextBlock | BetaManagedAgentsImageBlock | BetaManagedAgentsDocumentBlock>;\n\n type: 'user.message';\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at?: string | null;\n}\n\n/**\n * Parameters for sending a user message to the session.\n */\nexport interface BetaManagedAgentsUserMessageEventParams {\n /**\n * Array of content blocks for the user message.\n */\n content: Array<BetaManagedAgentsTextBlock | BetaManagedAgentsImageBlock | BetaManagedAgentsDocumentBlock>;\n\n type: 'user.message';\n}\n\n/**\n * A tool confirmation event that approves or denies a pending tool execution.\n */\nexport interface BetaManagedAgentsUserToolConfirmationEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * UserToolConfirmationResult enum\n */\n result: 'allow' | 'deny';\n\n /**\n * The id of the `agent.tool_use` or `agent.mcp_tool_use` event this result\n * corresponds to, which can be found in the last `session.status_idle`\n * [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids)\n * `stop_reason.event_ids` field.\n */\n tool_use_id: string;\n\n type: 'user.tool_confirmation';\n\n /**\n * Optional message providing context for a 'deny' decision. Only allowed when\n * result is 'deny'.\n */\n deny_message?: string | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at?: string | null;\n\n /**\n * When set, the confirmation routes to this subagent's thread rather than the\n * primary. Echo this from the `session_thread_id` on the `agent.tool_use` or\n * `agent.mcp_tool_use` event that prompted the approval.\n */\n session_thread_id?: string | null;\n}\n\n/**\n * Parameters for confirming or denying a tool execution request.\n */\nexport interface BetaManagedAgentsUserToolConfirmationEventParams {\n /**\n * UserToolConfirmationResult enum\n */\n result: 'allow' | 'deny';\n\n /**\n * The id of the `agent.tool_use` or `agent.mcp_tool_use` event this result\n * corresponds to, which can be found in the last `session.status_idle`\n * [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids)\n * `stop_reason.event_ids` field.\n */\n tool_use_id: string;\n\n type: 'user.tool_confirmation';\n\n /**\n * Optional message providing context for a 'deny' decision. Only allowed when\n * result is 'deny'.\n */\n deny_message?: string | null;\n}\n\n/**\n * Parameters for providing the result of an agent-toolset tool execution. Only\n * valid on `self_hosted` environments, where sandbox-routed tools are executed by\n * the client rather than the server.\n */\nexport interface BetaManagedAgentsUserToolResultEventParams {\n /**\n * The id of the `agent.tool_use` event this result corresponds to, which can be\n * found in the last `session.status_idle`\n * [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids)\n * `stop_reason.event_ids` field.\n */\n tool_use_id: string;\n\n type: 'user.tool_result';\n\n /**\n * The result content returned by the tool.\n */\n content?: Array<\n | BetaManagedAgentsTextBlock\n | BetaManagedAgentsImageBlock\n | BetaManagedAgentsDocumentBlock\n | BetaManagedAgentsSearchResultBlock\n >;\n\n /**\n * Whether the tool execution resulted in an error.\n */\n is_error?: boolean | null;\n}\n\nexport interface EventListParams extends PageCursorParams {\n /**\n * Query param: Return events created after this time (exclusive).\n */\n 'created_at[gt]'?: string;\n\n /**\n * Query param: Return events created at or after this time (inclusive).\n */\n 'created_at[gte]'?: string;\n\n /**\n * Query param: Return events created before this time (exclusive).\n */\n 'created_at[lt]'?: string;\n\n /**\n * Query param: Return events created at or before this time (inclusive).\n */\n 'created_at[lte]'?: string;\n\n /**\n * Query param: Sort direction for results, ordered by created_at. Defaults to asc\n * (chronological).\n */\n order?: 'asc' | 'desc';\n\n /**\n * Query param: Filter by event type. Values match the `type` field on returned\n * events (for example, `user.message` or `agent.tool_use`). Omit to return all\n * event types.\n */\n types?: Array<string>;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface EventSendParams {\n /**\n * Body param: Events to send to the `session`.\n */\n events: Array<BetaManagedAgentsEventParams>;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface EventStreamParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport { SessionToolRunner, type SessionToolRunnerOptions } from '../../../lib/tools/SessionToolRunner';\n\nEvents.SessionToolRunner = SessionToolRunner;\n\nexport declare namespace Events {\n export { SessionToolRunner };\n\n export {\n type BetaManagedAgentsAgentCustomToolUseEvent as BetaManagedAgentsAgentCustomToolUseEvent,\n type BetaManagedAgentsAgentMCPToolResultEvent as BetaManagedAgentsAgentMCPToolResultEvent,\n type BetaManagedAgentsAgentMCPToolUseEvent as BetaManagedAgentsAgentMCPToolUseEvent,\n type BetaManagedAgentsAgentMessageEvent as BetaManagedAgentsAgentMessageEvent,\n type BetaManagedAgentsAgentThinkingEvent as BetaManagedAgentsAgentThinkingEvent,\n type BetaManagedAgentsAgentThreadContextCompactedEvent as BetaManagedAgentsAgentThreadContextCompactedEvent,\n type BetaManagedAgentsAgentThreadMessageReceivedEvent as BetaManagedAgentsAgentThreadMessageReceivedEvent,\n type BetaManagedAgentsAgentThreadMessageSentEvent as BetaManagedAgentsAgentThreadMessageSentEvent,\n type BetaManagedAgentsAgentToolResultEvent as BetaManagedAgentsAgentToolResultEvent,\n type BetaManagedAgentsAgentToolUseEvent as BetaManagedAgentsAgentToolUseEvent,\n type BetaManagedAgentsBase64DocumentSource as BetaManagedAgentsBase64DocumentSource,\n type BetaManagedAgentsBase64ImageSource as BetaManagedAgentsBase64ImageSource,\n type BetaManagedAgentsBillingError as BetaManagedAgentsBillingError,\n type BetaManagedAgentsCredentialHostUnreachableError as BetaManagedAgentsCredentialHostUnreachableError,\n type BetaManagedAgentsDocumentBlock as BetaManagedAgentsDocumentBlock,\n type BetaManagedAgentsEventParams as BetaManagedAgentsEventParams,\n type BetaManagedAgentsFileDocumentSource as BetaManagedAgentsFileDocumentSource,\n type BetaManagedAgentsFileImageSource as BetaManagedAgentsFileImageSource,\n type BetaManagedAgentsFileRubric as BetaManagedAgentsFileRubric,\n type BetaManagedAgentsFileRubricParams as BetaManagedAgentsFileRubricParams,\n type BetaManagedAgentsImageBlock as BetaManagedAgentsImageBlock,\n type BetaManagedAgentsMCPAuthenticationFailedError as BetaManagedAgentsMCPAuthenticationFailedError,\n type BetaManagedAgentsMCPConnectionFailedError as BetaManagedAgentsMCPConnectionFailedError,\n type BetaManagedAgentsModelOverloadedError as BetaManagedAgentsModelOverloadedError,\n type BetaManagedAgentsModelRateLimitedError as BetaManagedAgentsModelRateLimitedError,\n type BetaManagedAgentsModelRequestFailedError as BetaManagedAgentsModelRequestFailedError,\n type BetaManagedAgentsPlainTextDocumentSource as BetaManagedAgentsPlainTextDocumentSource,\n type BetaManagedAgentsRetryStatusExhausted as BetaManagedAgentsRetryStatusExhausted,\n type BetaManagedAgentsRetryStatusRetrying as BetaManagedAgentsRetryStatusRetrying,\n type BetaManagedAgentsRetryStatusTerminal as BetaManagedAgentsRetryStatusTerminal,\n type BetaManagedAgentsSearchResultBlock as BetaManagedAgentsSearchResultBlock,\n type BetaManagedAgentsSearchResultCitations as BetaManagedAgentsSearchResultCitations,\n type BetaManagedAgentsSearchResultContent as BetaManagedAgentsSearchResultContent,\n type BetaManagedAgentsSendSessionEvents as BetaManagedAgentsSendSessionEvents,\n type BetaManagedAgentsSessionDeletedEvent as BetaManagedAgentsSessionDeletedEvent,\n type BetaManagedAgentsSessionEndTurn as BetaManagedAgentsSessionEndTurn,\n type BetaManagedAgentsSessionErrorEvent as BetaManagedAgentsSessionErrorEvent,\n type BetaManagedAgentsSessionEvent as BetaManagedAgentsSessionEvent,\n type BetaManagedAgentsSessionRequiresAction as BetaManagedAgentsSessionRequiresAction,\n type BetaManagedAgentsSessionRetriesExhausted as BetaManagedAgentsSessionRetriesExhausted,\n type BetaManagedAgentsSessionStatusIdleEvent as BetaManagedAgentsSessionStatusIdleEvent,\n type BetaManagedAgentsSessionStatusRescheduledEvent as BetaManagedAgentsSessionStatusRescheduledEvent,\n type BetaManagedAgentsSessionStatusRunningEvent as BetaManagedAgentsSessionStatusRunningEvent,\n type BetaManagedAgentsSessionStatusTerminatedEvent as BetaManagedAgentsSessionStatusTerminatedEvent,\n type BetaManagedAgentsSessionThreadCreatedEvent as BetaManagedAgentsSessionThreadCreatedEvent,\n type BetaManagedAgentsSessionThreadStatusIdleEvent as BetaManagedAgentsSessionThreadStatusIdleEvent,\n type BetaManagedAgentsSessionThreadStatusRescheduledEvent as BetaManagedAgentsSessionThreadStatusRescheduledEvent,\n type BetaManagedAgentsSessionThreadStatusRunningEvent as BetaManagedAgentsSessionThreadStatusRunningEvent,\n type BetaManagedAgentsSessionThreadStatusTerminatedEvent as BetaManagedAgentsSessionThreadStatusTerminatedEvent,\n type BetaManagedAgentsSpanModelRequestEndEvent as BetaManagedAgentsSpanModelRequestEndEvent,\n type BetaManagedAgentsSpanModelRequestStartEvent as BetaManagedAgentsSpanModelRequestStartEvent,\n type BetaManagedAgentsSpanModelUsage as BetaManagedAgentsSpanModelUsage,\n type BetaManagedAgentsSpanOutcomeEvaluationEndEvent as BetaManagedAgentsSpanOutcomeEvaluationEndEvent,\n type BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent as BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent,\n type BetaManagedAgentsSpanOutcomeEvaluationStartEvent as BetaManagedAgentsSpanOutcomeEvaluationStartEvent,\n type BetaManagedAgentsStreamSessionEvents as BetaManagedAgentsStreamSessionEvents,\n type BetaManagedAgentsSystemMessageEventParams as BetaManagedAgentsSystemMessageEventParams,\n type BetaManagedAgentsTextBlock as BetaManagedAgentsTextBlock,\n type BetaManagedAgentsTextRubric as BetaManagedAgentsTextRubric,\n type BetaManagedAgentsTextRubricParams as BetaManagedAgentsTextRubricParams,\n type BetaManagedAgentsUnknownError as BetaManagedAgentsUnknownError,\n type BetaManagedAgentsURLDocumentSource as BetaManagedAgentsURLDocumentSource,\n type BetaManagedAgentsURLImageSource as BetaManagedAgentsURLImageSource,\n type BetaManagedAgentsUserCustomToolResultEvent as BetaManagedAgentsUserCustomToolResultEvent,\n type BetaManagedAgentsUserCustomToolResultEventParams as BetaManagedAgentsUserCustomToolResultEventParams,\n type BetaManagedAgentsUserDefineOutcomeEvent as BetaManagedAgentsUserDefineOutcomeEvent,\n type BetaManagedAgentsUserDefineOutcomeEventParams as BetaManagedAgentsUserDefineOutcomeEventParams,\n type BetaManagedAgentsUserInterruptEvent as BetaManagedAgentsUserInterruptEvent,\n type BetaManagedAgentsUserInterruptEventParams as BetaManagedAgentsUserInterruptEventParams,\n type BetaManagedAgentsUserMessageEvent as BetaManagedAgentsUserMessageEvent,\n type BetaManagedAgentsUserMessageEventParams as BetaManagedAgentsUserMessageEventParams,\n type BetaManagedAgentsUserToolConfirmationEvent as BetaManagedAgentsUserToolConfirmationEvent,\n type BetaManagedAgentsUserToolConfirmationEventParams as BetaManagedAgentsUserToolConfirmationEventParams,\n type BetaManagedAgentsUserToolResultEventParams as BetaManagedAgentsUserToolResultEventParams,\n type BetaManagedAgentsSessionEventsPageCursor as BetaManagedAgentsSessionEventsPageCursor,\n type EventListParams as EventListParams,\n type EventSendParams as EventSendParams,\n type EventStreamParams as EventStreamParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as SessionsAPI from './sessions';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class Resources extends APIResource {\n /**\n * Get Session Resource\n *\n * @example\n * ```ts\n * const resource =\n * await client.beta.sessions.resources.retrieve(\n * 'sesrsc_011CZkZBJq5dWxk9fVLNcPht',\n * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },\n * );\n * ```\n */\n retrieve(\n resourceID: string,\n params: ResourceRetrieveParams,\n options?: RequestOptions,\n ): APIPromise<ResourceRetrieveResponse> {\n const { session_id, betas } = params;\n return this._client.get(path`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update Session Resource\n *\n * @example\n * ```ts\n * const resource =\n * await client.beta.sessions.resources.update(\n * 'sesrsc_011CZkZBJq5dWxk9fVLNcPht',\n * {\n * session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * authorization_token: 'ghp_exampletoken',\n * },\n * );\n * ```\n */\n update(\n resourceID: string,\n params: ResourceUpdateParams,\n options?: RequestOptions,\n ): APIPromise<ResourceUpdateResponse> {\n const { session_id, betas, ...body } = params;\n return this._client.post(path`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Session Resources\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsSessionResource of client.beta.sessions.resources.list(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n sessionID: string,\n params: ResourceListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsSessionResourcesPageCursor, BetaManagedAgentsSessionResource> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n path`/v1/sessions/${sessionID}/resources?beta=true`,\n PageCursor<BetaManagedAgentsSessionResource>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * Delete Session Resource\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeleteSessionResource =\n * await client.beta.sessions.resources.delete(\n * 'sesrsc_011CZkZBJq5dWxk9fVLNcPht',\n * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },\n * );\n * ```\n */\n delete(\n resourceID: string,\n params: ResourceDeleteParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeleteSessionResource> {\n const { session_id, betas } = params;\n return this._client.delete(path`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Add Session Resource\n *\n * @example\n * ```ts\n * const betaManagedAgentsFileResource =\n * await client.beta.sessions.resources.add(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * {\n * file_id: 'file_011CNha8iCJcU1wXNR6q4V8w',\n * type: 'file',\n * },\n * );\n * ```\n */\n add(\n sessionID: string,\n params: ResourceAddParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsFileResource> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/sessions/${sessionID}/resources?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaManagedAgentsSessionResourcesPageCursor = PageCursor<BetaManagedAgentsSessionResource>;\n\n/**\n * Confirmation of resource deletion.\n */\nexport interface BetaManagedAgentsDeleteSessionResource {\n id: string;\n\n type: 'session_resource_deleted';\n}\n\nexport interface BetaManagedAgentsFileResource {\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n file_id: string;\n\n mount_path: string;\n\n type: 'file';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n}\n\nexport interface BetaManagedAgentsGitHubRepositoryResource {\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n mount_path: string;\n\n type: 'github_repository';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n\n url: string;\n\n checkout?: SessionsAPI.BetaManagedAgentsBranchCheckout | SessionsAPI.BetaManagedAgentsCommitCheckout | null;\n}\n\n/**\n * A memory store attached to an agent session.\n */\nexport interface BetaManagedAgentsMemoryStoreResource {\n /**\n * The memory store ID (memstore\\_...). Must belong to the caller's organization\n * and workspace.\n */\n memory_store_id: string;\n\n type: 'memory_store';\n\n /**\n * Access mode for an attached memory store.\n */\n access?: 'read_write' | 'read_only' | null;\n\n /**\n * Description of the memory store, snapshotted at attach time. Rendered into the\n * agent's system prompt. Empty string when the store has no description.\n */\n description?: string;\n\n /**\n * Per-attachment guidance for the agent on how to use this store. Rendered into\n * the memory section of the system prompt. Max 4096 chars.\n */\n instructions?: string | null;\n\n /**\n * Filesystem path where the store is mounted in the session container, e.g.\n * /mnt/memory/user-preferences. Derived from the store's name. Output-only.\n */\n mount_path?: string | null;\n\n /**\n * Display name of the memory store, snapshotted at attach time. Later edits to the\n * store's name do not propagate to this resource.\n */\n name?: string | null;\n}\n\n/**\n * A memory store attached to an agent session.\n */\nexport type BetaManagedAgentsSessionResource =\n | BetaManagedAgentsGitHubRepositoryResource\n | BetaManagedAgentsFileResource\n | BetaManagedAgentsMemoryStoreResource;\n\n/**\n * The requested session resource.\n */\nexport type ResourceRetrieveResponse =\n | BetaManagedAgentsGitHubRepositoryResource\n | BetaManagedAgentsFileResource\n | BetaManagedAgentsMemoryStoreResource;\n\n/**\n * The updated session resource.\n */\nexport type ResourceUpdateResponse =\n | BetaManagedAgentsGitHubRepositoryResource\n | BetaManagedAgentsFileResource\n | BetaManagedAgentsMemoryStoreResource;\n\nexport interface ResourceRetrieveParams {\n /**\n * Path param: Path parameter session_id\n */\n session_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface ResourceUpdateParams {\n /**\n * Path param: Path parameter session_id\n */\n session_id: string;\n\n /**\n * Body param: New authorization token for the resource. Currently only\n * `github_repository` resources support token rotation.\n */\n authorization_token: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface ResourceListParams extends PageCursorParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface ResourceDeleteParams {\n /**\n * Path param: Path parameter session_id\n */\n session_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface ResourceAddParams {\n /**\n * Body param: ID of a previously uploaded file.\n */\n file_id: string;\n\n /**\n * Body param\n */\n type: 'file';\n\n /**\n * Body param: Mount path in the container. Defaults to\n * `/mnt/session/uploads/<file_id>`.\n */\n mount_path?: string | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Resources {\n export {\n type BetaManagedAgentsDeleteSessionResource as BetaManagedAgentsDeleteSessionResource,\n type BetaManagedAgentsFileResource as BetaManagedAgentsFileResource,\n type BetaManagedAgentsGitHubRepositoryResource as BetaManagedAgentsGitHubRepositoryResource,\n type BetaManagedAgentsMemoryStoreResource as BetaManagedAgentsMemoryStoreResource,\n type BetaManagedAgentsSessionResource as BetaManagedAgentsSessionResource,\n type ResourceRetrieveResponse as ResourceRetrieveResponse,\n type ResourceUpdateResponse as ResourceUpdateResponse,\n type BetaManagedAgentsSessionResourcesPageCursor as BetaManagedAgentsSessionResourcesPageCursor,\n type ResourceRetrieveParams as ResourceRetrieveParams,\n type ResourceUpdateParams as ResourceUpdateParams,\n type ResourceListParams as ResourceListParams,\n type ResourceDeleteParams as ResourceDeleteParams,\n type ResourceAddParams as ResourceAddParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../../core/resource';\nimport * as BetaAPI from '../../beta';\nimport * as EventsAPI from '../events';\nimport { BetaManagedAgentsSessionEventsPageCursor } from '../events';\nimport * as ThreadsAPI from './threads';\nimport { APIPromise } from '../../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../../core/pagination';\nimport { Stream } from '../../../../core/streaming';\nimport { buildHeaders } from '../../../../internal/headers';\nimport { RequestOptions } from '../../../../internal/request-options';\nimport { path } from '../../../../internal/utils/path';\n\nexport class Events extends APIResource {\n /**\n * List Session Thread Events\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsSessionEvent of client.beta.sessions.threads.events.list(\n * 'sthr_011CZkZVWa6oIjw0rgXZpnBt',\n * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n threadID: string,\n params: EventListParams,\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsSessionEventsPageCursor, EventsAPI.BetaManagedAgentsSessionEvent> {\n const { session_id, betas, ...query } = params;\n return this._client.getAPIList(\n path`/v1/sessions/${session_id}/threads/${threadID}/events?beta=true`,\n PageCursor<EventsAPI.BetaManagedAgentsSessionEvent>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * Stream Session Thread Events\n *\n * @example\n * ```ts\n * const betaManagedAgentsStreamSessionThreadEvents =\n * await client.beta.sessions.threads.events.stream(\n * 'sthr_011CZkZVWa6oIjw0rgXZpnBt',\n * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },\n * );\n * ```\n */\n stream(\n threadID: string,\n params: EventStreamParams,\n options?: RequestOptions,\n ): APIPromise<Stream<ThreadsAPI.BetaManagedAgentsStreamSessionThreadEvents>> {\n const { session_id, betas } = params;\n return this._client.get(path`/v1/sessions/${session_id}/threads/${threadID}/stream?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n stream: true,\n }) as APIPromise<Stream<ThreadsAPI.BetaManagedAgentsStreamSessionThreadEvents>>;\n }\n}\n\nexport interface EventListParams extends PageCursorParams {\n /**\n * Path param: Path parameter session_id\n */\n session_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface EventStreamParams {\n /**\n * Path param: Path parameter session_id\n */\n session_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Events {\n export { type EventListParams as EventListParams, type EventStreamParams as EventStreamParams };\n}\n\nexport { type BetaManagedAgentsSessionEventsPageCursor };\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../../core/resource';\nimport * as BetaAPI from '../../beta';\nimport * as AgentsAPI from '../../agents/agents';\nimport * as EventsAPI from '../events';\nimport * as SessionsAPI from '../sessions';\nimport * as ThreadsEventsAPI from './events';\nimport { EventListParams, EventStreamParams, Events } from './events';\nimport { APIPromise } from '../../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../../core/pagination';\nimport { buildHeaders } from '../../../../internal/headers';\nimport { RequestOptions } from '../../../../internal/request-options';\nimport { path } from '../../../../internal/utils/path';\n\nexport class Threads extends APIResource {\n events: ThreadsEventsAPI.Events = new ThreadsEventsAPI.Events(this._client);\n\n /**\n * Get Session Thread\n *\n * @example\n * ```ts\n * const betaManagedAgentsSessionThread =\n * await client.beta.sessions.threads.retrieve(\n * 'sthr_011CZkZVWa6oIjw0rgXZpnBt',\n * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },\n * );\n * ```\n */\n retrieve(\n threadID: string,\n params: ThreadRetrieveParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsSessionThread> {\n const { session_id, betas } = params;\n return this._client.get(path`/v1/sessions/${session_id}/threads/${threadID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Session Threads\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsSessionThread of client.beta.sessions.threads.list(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n sessionID: string,\n params: ThreadListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsSessionThreadsPageCursor, BetaManagedAgentsSessionThread> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n path`/v1/sessions/${sessionID}/threads?beta=true`,\n PageCursor<BetaManagedAgentsSessionThread>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * Archive Session Thread\n *\n * @example\n * ```ts\n * const betaManagedAgentsSessionThread =\n * await client.beta.sessions.threads.archive(\n * 'sthr_011CZkZVWa6oIjw0rgXZpnBt',\n * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },\n * );\n * ```\n */\n archive(\n threadID: string,\n params: ThreadArchiveParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsSessionThread> {\n const { session_id, betas } = params;\n return this._client.post(path`/v1/sessions/${session_id}/threads/${threadID}/archive?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaManagedAgentsSessionThreadsPageCursor = PageCursor<BetaManagedAgentsSessionThread>;\n\n/**\n * An execution thread within a `session`. Each session has one primary thread plus\n * zero or more child threads spawned by the coordinator.\n */\nexport interface BetaManagedAgentsSessionThread {\n /**\n * Unique identifier for this thread.\n */\n id: string;\n\n /**\n * Resolved `agent` definition for a single `session_thread`. Snapshot of the agent\n * at thread creation time. The multiagent roster is not repeated here; read it\n * from `Session.agent`.\n */\n agent: AgentsAPI.BetaManagedAgentsSessionThreadAgent;\n\n /**\n * A timestamp in RFC 3339 format\n */\n archived_at: string | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n /**\n * Parent thread that spawned this thread. Null for the primary thread.\n */\n parent_thread_id: string | null;\n\n /**\n * The session this thread belongs to.\n */\n session_id: string;\n\n /**\n * Timing statistics for a session thread.\n */\n stats: BetaManagedAgentsSessionThreadStats | null;\n\n /**\n * SessionThreadStatus enum\n */\n status: BetaManagedAgentsSessionThreadStatus;\n\n type: 'session_thread';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n\n /**\n * Cumulative token usage for a session thread across all turns.\n */\n usage: BetaManagedAgentsSessionThreadUsage | null;\n}\n\n/**\n * Timing statistics for a session thread.\n */\nexport interface BetaManagedAgentsSessionThreadStats {\n /**\n * Cumulative time in seconds the thread spent actively running. Excludes idle\n * time.\n */\n active_seconds?: number;\n\n /**\n * Elapsed time since thread creation in seconds. For archived threads, frozen at\n * the final update.\n */\n duration_seconds?: number;\n\n /**\n * Time in seconds for the thread to begin running. Zero for child threads, which\n * start immediately.\n */\n startup_seconds?: number;\n}\n\n/**\n * SessionThreadStatus enum\n */\nexport type BetaManagedAgentsSessionThreadStatus = 'running' | 'idle' | 'rescheduling' | 'terminated';\n\n/**\n * Cumulative token usage for a session thread across all turns.\n */\nexport interface BetaManagedAgentsSessionThreadUsage {\n /**\n * Prompt-cache creation token usage broken down by cache lifetime.\n */\n cache_creation?: SessionsAPI.BetaManagedAgentsCacheCreationUsage;\n\n /**\n * Total tokens read from prompt cache.\n */\n cache_read_input_tokens?: number;\n\n /**\n * Total input tokens consumed across all turns.\n */\n input_tokens?: number;\n\n /**\n * Total output tokens generated across all turns.\n */\n output_tokens?: number;\n}\n\n/**\n * Server-sent event in a single thread's stream.\n */\nexport type BetaManagedAgentsStreamSessionThreadEvents =\n | EventsAPI.BetaManagedAgentsUserMessageEvent\n | EventsAPI.BetaManagedAgentsUserInterruptEvent\n | EventsAPI.BetaManagedAgentsUserToolConfirmationEvent\n | EventsAPI.BetaManagedAgentsUserCustomToolResultEvent\n | EventsAPI.BetaManagedAgentsAgentCustomToolUseEvent\n | EventsAPI.BetaManagedAgentsAgentMessageEvent\n | EventsAPI.BetaManagedAgentsAgentThinkingEvent\n | EventsAPI.BetaManagedAgentsAgentMCPToolUseEvent\n | EventsAPI.BetaManagedAgentsAgentMCPToolResultEvent\n | EventsAPI.BetaManagedAgentsAgentToolUseEvent\n | EventsAPI.BetaManagedAgentsAgentToolResultEvent\n | EventsAPI.BetaManagedAgentsAgentThreadMessageReceivedEvent\n | EventsAPI.BetaManagedAgentsAgentThreadMessageSentEvent\n | EventsAPI.BetaManagedAgentsAgentThreadContextCompactedEvent\n | EventsAPI.BetaManagedAgentsSessionErrorEvent\n | EventsAPI.BetaManagedAgentsSessionStatusRescheduledEvent\n | EventsAPI.BetaManagedAgentsSessionStatusRunningEvent\n | EventsAPI.BetaManagedAgentsSessionStatusIdleEvent\n | EventsAPI.BetaManagedAgentsSessionStatusTerminatedEvent\n | EventsAPI.BetaManagedAgentsSessionThreadCreatedEvent\n | EventsAPI.BetaManagedAgentsSpanOutcomeEvaluationStartEvent\n | EventsAPI.BetaManagedAgentsSpanOutcomeEvaluationEndEvent\n | EventsAPI.BetaManagedAgentsSpanModelRequestStartEvent\n | EventsAPI.BetaManagedAgentsSpanModelRequestEndEvent\n | EventsAPI.BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent\n | EventsAPI.BetaManagedAgentsUserDefineOutcomeEvent\n | EventsAPI.BetaManagedAgentsSessionDeletedEvent\n | EventsAPI.BetaManagedAgentsSessionThreadStatusRunningEvent\n | EventsAPI.BetaManagedAgentsSessionThreadStatusIdleEvent\n | EventsAPI.BetaManagedAgentsSessionThreadStatusTerminatedEvent\n | SessionsAPI.BetaManagedAgentsUserToolResultEvent\n | EventsAPI.BetaManagedAgentsSessionThreadStatusRescheduledEvent\n | SessionsAPI.BetaManagedAgentsSessionUpdatedEvent\n | SessionsAPI.BetaManagedAgentsSystemMessageEvent;\n\nexport interface ThreadRetrieveParams {\n /**\n * Path param: Path parameter session_id\n */\n session_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface ThreadListParams extends PageCursorParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface ThreadArchiveParams {\n /**\n * Path param: Path parameter session_id\n */\n session_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nThreads.Events = Events;\n\nexport declare namespace Threads {\n export {\n type BetaManagedAgentsSessionThread as BetaManagedAgentsSessionThread,\n type BetaManagedAgentsSessionThreadStats as BetaManagedAgentsSessionThreadStats,\n type BetaManagedAgentsSessionThreadStatus as BetaManagedAgentsSessionThreadStatus,\n type BetaManagedAgentsSessionThreadUsage as BetaManagedAgentsSessionThreadUsage,\n type BetaManagedAgentsStreamSessionThreadEvents as BetaManagedAgentsStreamSessionThreadEvents,\n type BetaManagedAgentsSessionThreadsPageCursor as BetaManagedAgentsSessionThreadsPageCursor,\n type ThreadRetrieveParams as ThreadRetrieveParams,\n type ThreadListParams as ThreadListParams,\n type ThreadArchiveParams as ThreadArchiveParams,\n };\n\n export {\n Events as Events,\n type EventListParams as EventListParams,\n type EventStreamParams as EventStreamParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as AgentsAPI from '../agents/agents';\nimport * as EventsAPI from './events';\nimport {\n BetaManagedAgentsAgentCustomToolUseEvent,\n BetaManagedAgentsAgentMCPToolResultEvent,\n BetaManagedAgentsAgentMCPToolUseEvent,\n BetaManagedAgentsAgentMessageEvent,\n BetaManagedAgentsAgentThinkingEvent,\n BetaManagedAgentsAgentThreadContextCompactedEvent,\n BetaManagedAgentsAgentThreadMessageReceivedEvent,\n BetaManagedAgentsAgentThreadMessageSentEvent,\n BetaManagedAgentsAgentToolResultEvent,\n BetaManagedAgentsAgentToolUseEvent,\n BetaManagedAgentsBase64DocumentSource,\n BetaManagedAgentsBase64ImageSource,\n BetaManagedAgentsBillingError,\n BetaManagedAgentsCredentialHostUnreachableError,\n BetaManagedAgentsDocumentBlock,\n BetaManagedAgentsEventParams,\n BetaManagedAgentsFileDocumentSource,\n BetaManagedAgentsFileImageSource,\n BetaManagedAgentsFileRubric,\n BetaManagedAgentsFileRubricParams,\n BetaManagedAgentsImageBlock,\n BetaManagedAgentsMCPAuthenticationFailedError,\n BetaManagedAgentsMCPConnectionFailedError,\n BetaManagedAgentsModelOverloadedError,\n BetaManagedAgentsModelRateLimitedError,\n BetaManagedAgentsModelRequestFailedError,\n BetaManagedAgentsPlainTextDocumentSource,\n BetaManagedAgentsRetryStatusExhausted,\n BetaManagedAgentsRetryStatusRetrying,\n BetaManagedAgentsRetryStatusTerminal,\n BetaManagedAgentsSearchResultBlock,\n BetaManagedAgentsSearchResultCitations,\n BetaManagedAgentsSearchResultContent,\n BetaManagedAgentsSendSessionEvents,\n BetaManagedAgentsSessionDeletedEvent,\n BetaManagedAgentsSessionEndTurn,\n BetaManagedAgentsSessionErrorEvent,\n BetaManagedAgentsSessionEvent,\n BetaManagedAgentsSessionEventsPageCursor,\n BetaManagedAgentsSessionRequiresAction,\n BetaManagedAgentsSessionRetriesExhausted,\n BetaManagedAgentsSessionStatusIdleEvent,\n BetaManagedAgentsSessionStatusRescheduledEvent,\n BetaManagedAgentsSessionStatusRunningEvent,\n BetaManagedAgentsSessionStatusTerminatedEvent,\n BetaManagedAgentsSessionThreadCreatedEvent,\n BetaManagedAgentsSessionThreadStatusIdleEvent,\n BetaManagedAgentsSessionThreadStatusRescheduledEvent,\n BetaManagedAgentsSessionThreadStatusRunningEvent,\n BetaManagedAgentsSessionThreadStatusTerminatedEvent,\n BetaManagedAgentsSpanModelRequestEndEvent,\n BetaManagedAgentsSpanModelRequestStartEvent,\n BetaManagedAgentsSpanModelUsage,\n BetaManagedAgentsSpanOutcomeEvaluationEndEvent,\n BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent,\n BetaManagedAgentsSpanOutcomeEvaluationStartEvent,\n BetaManagedAgentsStreamSessionEvents,\n BetaManagedAgentsSystemMessageEventParams,\n BetaManagedAgentsTextBlock,\n BetaManagedAgentsTextRubric,\n BetaManagedAgentsTextRubricParams,\n BetaManagedAgentsURLDocumentSource,\n BetaManagedAgentsURLImageSource,\n BetaManagedAgentsUnknownError,\n BetaManagedAgentsUserCustomToolResultEvent,\n BetaManagedAgentsUserCustomToolResultEventParams,\n BetaManagedAgentsUserDefineOutcomeEvent,\n BetaManagedAgentsUserDefineOutcomeEventParams,\n BetaManagedAgentsUserInterruptEvent,\n BetaManagedAgentsUserInterruptEventParams,\n BetaManagedAgentsUserMessageEvent,\n BetaManagedAgentsUserMessageEventParams,\n BetaManagedAgentsUserToolConfirmationEvent,\n BetaManagedAgentsUserToolConfirmationEventParams,\n BetaManagedAgentsUserToolResultEventParams,\n EventListParams,\n EventSendParams,\n EventStreamParams,\n Events,\n} from './events';\nimport * as ResourcesAPI from './resources';\nimport {\n BetaManagedAgentsDeleteSessionResource,\n BetaManagedAgentsFileResource,\n BetaManagedAgentsGitHubRepositoryResource,\n BetaManagedAgentsMemoryStoreResource,\n BetaManagedAgentsSessionResource,\n BetaManagedAgentsSessionResourcesPageCursor,\n ResourceAddParams,\n ResourceDeleteParams,\n ResourceListParams,\n ResourceRetrieveParams,\n ResourceRetrieveResponse,\n ResourceUpdateParams,\n ResourceUpdateResponse,\n Resources,\n} from './resources';\nimport * as ThreadsAPI from './threads/threads';\nimport {\n BetaManagedAgentsSessionThread,\n BetaManagedAgentsSessionThreadStats,\n BetaManagedAgentsSessionThreadStatus,\n BetaManagedAgentsSessionThreadUsage,\n BetaManagedAgentsSessionThreadsPageCursor,\n BetaManagedAgentsStreamSessionThreadEvents,\n ThreadArchiveParams,\n ThreadListParams,\n ThreadRetrieveParams,\n Threads,\n} from './threads/threads';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class Sessions extends APIResource {\n events: EventsAPI.Events = new EventsAPI.Events(this._client);\n resources: ResourcesAPI.Resources = new ResourcesAPI.Resources(this._client);\n threads: ThreadsAPI.Threads = new ThreadsAPI.Threads(this._client);\n\n /**\n * Create Session\n *\n * @example\n * ```ts\n * const betaManagedAgentsSession =\n * await client.beta.sessions.create({\n * agent: 'agent_011CZkYpogX7uDKUyvBTophP',\n * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',\n * });\n * ```\n */\n create(params: SessionCreateParams, options?: RequestOptions): APIPromise<BetaManagedAgentsSession> {\n const { betas, ...body } = params;\n return this._client.post('/v1/sessions?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Get Session\n *\n * @example\n * ```ts\n * const betaManagedAgentsSession =\n * await client.beta.sessions.retrieve(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * );\n * ```\n */\n retrieve(\n sessionID: string,\n params: SessionRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsSession> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/sessions/${sessionID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update Session\n *\n * @example\n * ```ts\n * const betaManagedAgentsSession =\n * await client.beta.sessions.update(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * );\n * ```\n */\n update(\n sessionID: string,\n params: SessionUpdateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsSession> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/sessions/${sessionID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Sessions\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsSession of client.beta.sessions.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: SessionListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsSessionsPageCursor, BetaManagedAgentsSession> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/sessions?beta=true', PageCursor<BetaManagedAgentsSession>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Delete Session\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeletedSession =\n * await client.beta.sessions.delete(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * );\n * ```\n */\n delete(\n sessionID: string,\n params: SessionDeleteParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeletedSession> {\n const { betas } = params ?? {};\n return this._client.delete(path`/v1/sessions/${sessionID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Archive Session\n *\n * @example\n * ```ts\n * const betaManagedAgentsSession =\n * await client.beta.sessions.archive(\n * 'sesn_011CZkZAtmR3yMPDzynEDxu7',\n * );\n * ```\n */\n archive(\n sessionID: string,\n params: SessionArchiveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsSession> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/sessions/${sessionID}/archive?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaManagedAgentsSessionsPageCursor = PageCursor<BetaManagedAgentsSession>;\n\n/**\n * Specification for an Agent. Provide a specific `version` or use the short-form\n * `agent=\"agent_id\"` for the most recent version\n */\nexport interface BetaManagedAgentsAgentParams {\n /**\n * The `agent` ID.\n */\n id: string;\n\n type: 'agent';\n\n /**\n * The specific `agent` version to use. Omit to use the latest version. Must be at\n * least 1 if specified.\n */\n version?: number;\n}\n\nexport interface BetaManagedAgentsBranchCheckout {\n /**\n * Branch name to check out.\n */\n name: string;\n\n type: 'branch';\n}\n\n/**\n * Prompt-cache creation token usage broken down by cache lifetime.\n */\nexport interface BetaManagedAgentsCacheCreationUsage {\n /**\n * Tokens used to create 1-hour ephemeral cache entries.\n */\n ephemeral_1h_input_tokens?: number;\n\n /**\n * Tokens used to create 5-minute ephemeral cache entries.\n */\n ephemeral_5m_input_tokens?: number;\n}\n\nexport interface BetaManagedAgentsCommitCheckout {\n /**\n * Full commit SHA to check out.\n */\n sha: string;\n\n type: 'commit';\n}\n\n/**\n * Confirmation that a `session` has been permanently deleted.\n */\nexport interface BetaManagedAgentsDeletedSession {\n id: string;\n\n type: 'session_deleted';\n}\n\n/**\n * Mount a file uploaded via the Files API into the session.\n */\nexport interface BetaManagedAgentsFileResourceParams {\n /**\n * ID of a previously uploaded file.\n */\n file_id: string;\n\n type: 'file';\n\n /**\n * Mount path in the container. Defaults to `/mnt/session/uploads/<file_id>`.\n */\n mount_path?: string | null;\n}\n\n/**\n * Mount a GitHub repository into the session's container.\n */\nexport interface BetaManagedAgentsGitHubRepositoryResourceParams {\n /**\n * GitHub authorization token used to clone the repository.\n */\n authorization_token: string;\n\n type: 'github_repository';\n\n /**\n * Github URL of the repository\n */\n url: string;\n\n /**\n * Branch or commit to check out. Defaults to the repository's default branch.\n */\n checkout?: BetaManagedAgentsBranchCheckout | BetaManagedAgentsCommitCheckout | null;\n\n /**\n * Mount path in the container. Defaults to `/workspace/<repo-name>`.\n */\n mount_path?: string | null;\n}\n\n/**\n * Parameters for attaching a memory store to an agent session.\n */\nexport interface BetaManagedAgentsMemoryStoreResourceParam {\n /**\n * The memory store ID (memstore\\_...). Must belong to the caller's organization\n * and workspace.\n */\n memory_store_id: string;\n\n type: 'memory_store';\n\n /**\n * Access mode for an attached memory store.\n */\n access?: 'read_write' | 'read_only' | null;\n\n /**\n * Per-attachment guidance for the agent on how to use this store. Rendered into\n * the memory section of the system prompt. Max 4096 chars.\n */\n instructions?: string | null;\n}\n\n/**\n * Resolved coordinator topology with a concrete agent roster.\n */\nexport interface BetaManagedAgentsMultiagent {\n /**\n * Agents the coordinator may spawn as session threads, each resolved to a specific\n * version.\n */\n agents: Array<AgentsAPI.BetaManagedAgentsAgentReference>;\n\n type: 'coordinator';\n}\n\n/**\n * A coordinator topology: the session's primary thread orchestrates work by\n * spawning session threads, each running an agent drawn from the `agents` roster.\n */\nexport interface BetaManagedAgentsMultiagentParams {\n /**\n * Agents the coordinator may spawn as session threads. 1–20 entries. Each entry is\n * an agent ID string, a versioned `{\"type\":\"agent\",\"id\",\"version\"}` reference, or\n * `{\"type\":\"self\"}` to allow recursive self-invocation. Entries must reference\n * distinct agents (after resolving `self` and string forms); at most one `self`.\n * Referenced agents must exist, must not be archived, and must not themselves have\n * `multiagent` set (depth limit 1).\n */\n agents: Array<BetaManagedAgentsMultiagentRosterEntryParams>;\n\n type: 'coordinator';\n}\n\n/**\n * An entry in a multiagent roster: an agent ID string, a versioned agent\n * reference, or `self`.\n */\nexport type BetaManagedAgentsMultiagentRosterEntryParams =\n | string\n | BetaManagedAgentsAgentParams\n | AgentsAPI.BetaManagedAgentsMultiagentSelfParams;\n\n/**\n * Evaluation state for a single outcome defined via a define_outcome event.\n */\nexport interface BetaManagedAgentsOutcomeEvaluationResource {\n /**\n * A timestamp in RFC 3339 format\n */\n completed_at: string | null;\n\n /**\n * What the agent should produce.\n */\n description: string;\n\n /**\n * Grader's verdict text from the most recent evaluation. For satisfied, explains\n * why criteria are met; for needs_revision (intermediate), what's missing; for\n * failed, why unrecoverable.\n */\n explanation: string | null;\n\n /**\n * 0-indexed revision cycle the outcome is currently on.\n */\n iteration: number;\n\n /**\n * Server-generated outc\\_ ID for this outcome.\n */\n outcome_id: string;\n\n /**\n * Current evaluation state. `pending` before the agent begins work; `running`\n * while producing or revising; `evaluating` while the grader scores;\n * `satisfied`/`max_iterations_reached`/`failed`/`interrupted` are terminal.\n */\n result: string;\n\n type: 'outcome_evaluation';\n}\n\n/**\n * A Managed Agents `session`.\n */\nexport interface BetaManagedAgentsSession {\n id: string;\n\n /**\n * Resolved `agent` definition for a `session`. Snapshot of the `agent` at\n * `session` creation time.\n */\n agent: BetaManagedAgentsSessionAgent;\n\n /**\n * A timestamp in RFC 3339 format\n */\n archived_at: string | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n environment_id: string;\n\n metadata: { [key: string]: string };\n\n /**\n * Per-outcome evaluation state. One entry per define_outcome event sent to the\n * session.\n */\n outcome_evaluations: Array<BetaManagedAgentsOutcomeEvaluationResource>;\n\n resources: Array<ResourcesAPI.BetaManagedAgentsSessionResource>;\n\n /**\n * Timing statistics for a session.\n */\n stats: BetaManagedAgentsSessionStats;\n\n /**\n * SessionStatus enum\n */\n status: 'rescheduling' | 'running' | 'idle' | 'terminated';\n\n title: string | null;\n\n type: 'session';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n\n /**\n * Cumulative token usage for a session across all turns.\n */\n usage: BetaManagedAgentsSessionUsage;\n\n /**\n * Vault IDs attached to the session at creation. Empty when no vaults were\n * supplied.\n */\n vault_ids: Array<string>;\n\n /**\n * Deployment ID when the session was created from a deployment reference. Null\n * otherwise.\n */\n deployment_id?: string | null;\n}\n\n/**\n * Resolved `agent` definition for a `session`. Snapshot of the `agent` at\n * `session` creation time.\n */\nexport interface BetaManagedAgentsSessionAgent {\n id: string;\n\n description: string | null;\n\n mcp_servers: Array<AgentsAPI.BetaManagedAgentsMCPServerURLDefinition>;\n\n /**\n * Model identifier and configuration.\n */\n model: AgentsAPI.BetaManagedAgentsModelConfig;\n\n /**\n * Resolved coordinator topology with full agent definitions for each roster\n * member.\n */\n multiagent: BetaManagedAgentsSessionMultiagentCoordinator | null;\n\n name: string;\n\n skills: Array<AgentsAPI.BetaManagedAgentsAnthropicSkill | AgentsAPI.BetaManagedAgentsCustomSkill>;\n\n system: string | null;\n\n tools: Array<\n | AgentsAPI.BetaManagedAgentsAgentToolset20260401\n | AgentsAPI.BetaManagedAgentsMCPToolset\n | AgentsAPI.BetaManagedAgentsCustomTool\n >;\n\n type: 'agent';\n\n version: number;\n}\n\n/**\n * Mid-session agent configuration update. Only `tools` and `mcp_servers` are\n * updatable. Full replacement: the provided array becomes the new value. To\n * preserve existing entries, GET the session, modify the array, and POST it back.\n */\nexport interface BetaManagedAgentsSessionAgentUpdate {\n /**\n * Replacement MCP server list. Full replacement: the provided array becomes the\n * new value. Send an empty array to clear; omit to preserve.\n */\n mcp_servers?: Array<AgentsAPI.BetaManagedAgentsURLMCPServerParams>;\n\n /**\n * Replacement tool list. Full replacement: the provided array becomes the new\n * value. Send an empty array to clear; omit to preserve.\n */\n tools?: Array<\n | AgentsAPI.BetaManagedAgentsAgentToolset20260401Params\n | AgentsAPI.BetaManagedAgentsMCPToolsetParams\n | AgentsAPI.BetaManagedAgentsCustomToolParams\n >;\n}\n\n/**\n * Resolved coordinator topology with full agent definitions for each roster\n * member.\n */\nexport interface BetaManagedAgentsSessionMultiagentCoordinator {\n /**\n * Full `agent` definitions the coordinator may spawn as session threads.\n */\n agents: Array<AgentsAPI.BetaManagedAgentsSessionThreadAgent>;\n\n type: 'coordinator';\n}\n\n/**\n * Timing statistics for a session.\n */\nexport interface BetaManagedAgentsSessionStats {\n /**\n * Cumulative time in seconds the session spent in running status. Excludes idle\n * time.\n */\n active_seconds?: number;\n\n /**\n * Elapsed time since session creation in seconds. For terminated sessions, frozen\n * at the final update.\n */\n duration_seconds?: number;\n}\n\n/**\n * Emitted when an UpdateSession request changed at least one field. Carries only\n * the fields that changed; absent fields were not part of the update. The new\n * configuration applies from the next turn.\n */\nexport interface BetaManagedAgentsSessionUpdatedEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at: string;\n\n type: 'session.updated';\n\n /**\n * Resolved `agent` definition for a `session`. Snapshot of the `agent` at\n * `session` creation time.\n */\n agent?: BetaManagedAgentsSessionAgent | null;\n\n /**\n * The session's full metadata bag after the update. Present when the update set\n * non-empty metadata; absent when metadata was unchanged or cleared to empty.\n */\n metadata?: { [key: string]: string };\n\n /**\n * The session's new title. Present only when the update changed it.\n */\n title?: string | null;\n}\n\n/**\n * Cumulative token usage for a session across all turns.\n */\nexport interface BetaManagedAgentsSessionUsage {\n /**\n * Prompt-cache creation token usage broken down by cache lifetime.\n */\n cache_creation?: BetaManagedAgentsCacheCreationUsage;\n\n /**\n * Total tokens read from prompt cache.\n */\n cache_read_input_tokens?: number;\n\n /**\n * Total input tokens consumed across all turns.\n */\n input_tokens?: number;\n\n /**\n * Total output tokens generated across all turns.\n */\n output_tokens?: number;\n}\n\n/**\n * Regular text content.\n */\nexport interface BetaManagedAgentsSystemContentBlock {\n /**\n * The text content.\n */\n text: string;\n\n type: 'text';\n}\n\n/**\n * A mid-conversation system message event. Carries system-role content that is\n * appended to the session as a `role: \"system\"` turn.\n */\nexport interface BetaManagedAgentsSystemMessageEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * System content blocks. Text-only.\n */\n content: Array<BetaManagedAgentsSystemContentBlock>;\n\n type: 'system.message';\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at?: string | null;\n}\n\n/**\n * Event sent by the client providing the result of an agent-toolset tool\n * execution. Only valid on `self_hosted` environments, where sandbox-routed tools\n * are executed by the client rather than the server.\n */\nexport interface BetaManagedAgentsUserToolResultEvent {\n /**\n * Unique identifier for this event.\n */\n id: string;\n\n /**\n * The id of the `agent.tool_use` event this result corresponds to, which can be\n * found in the last `session.status_idle`\n * [event's](https://platform.claude.com/docs/en/api/beta/sessions/events/list#beta_managed_agents_session_requires_action.event_ids)\n * `stop_reason.event_ids` field.\n */\n tool_use_id: string;\n\n type: 'user.tool_result';\n\n /**\n * The result content returned by the tool.\n */\n content?: Array<\n | EventsAPI.BetaManagedAgentsTextBlock\n | EventsAPI.BetaManagedAgentsImageBlock\n | EventsAPI.BetaManagedAgentsDocumentBlock\n | EventsAPI.BetaManagedAgentsSearchResultBlock\n >;\n\n /**\n * Whether the tool execution resulted in an error.\n */\n is_error?: boolean | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n processed_at?: string | null;\n\n /**\n * Routes this result to a subagent thread. Copy from the `agent.tool_use` event's\n * `session_thread_id`.\n */\n session_thread_id?: string | null;\n}\n\nexport interface SessionCreateParams {\n /**\n * Body param: Agent identifier. Accepts the `agent` ID string, which pins the\n * latest version for the session, or an `agent` object with both id and version\n * specified.\n */\n agent: string | BetaManagedAgentsAgentParams;\n\n /**\n * Body param: ID of the `environment` defining the container configuration for\n * this session.\n */\n environment_id: string;\n\n /**\n * Body param: Arbitrary key-value metadata attached to the session. Maximum 16\n * pairs, keys up to 64 chars, values up to 512 chars.\n */\n metadata?: { [key: string]: string };\n\n /**\n * Body param: Resources (e.g. repositories, files) to mount into the session's\n * container.\n */\n resources?: Array<\n | BetaManagedAgentsGitHubRepositoryResourceParams\n | BetaManagedAgentsFileResourceParams\n | BetaManagedAgentsMemoryStoreResourceParam\n >;\n\n /**\n * Body param: Human-readable session title.\n */\n title?: string | null;\n\n /**\n * Body param: Vault IDs for stored credentials the agent can use during the\n * session.\n */\n vault_ids?: Array<string>;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface SessionRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface SessionUpdateParams {\n /**\n * Body param: Mid-session agent configuration update. Only `tools` and\n * `mcp_servers` are updatable. Full replacement: the provided array becomes the\n * new value. To preserve existing entries, GET the session, modify the array, and\n * POST it back.\n */\n agent?: BetaManagedAgentsSessionAgentUpdate;\n\n /**\n * Body param: Metadata patch. Set a key to a string to upsert it, or to null to\n * delete it. Omit the field to preserve.\n */\n metadata?: { [key: string]: string | null } | null;\n\n /**\n * Body param: Human-readable session title.\n */\n title?: string | null;\n\n /**\n * Body param: Vault IDs (`vlt_*`) to attach to the session. Not yet supported;\n * requests setting this field are rejected. Reserved for future use.\n */\n vault_ids?: Array<string>;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface SessionListParams extends PageCursorParams {\n /**\n * Query param: Filter sessions created with this agent ID.\n */\n agent_id?: string;\n\n /**\n * Query param: Filter by agent version. Only applies when agent_id is also set.\n */\n agent_version?: number;\n\n /**\n * Query param: Return sessions created after this time (exclusive).\n */\n 'created_at[gt]'?: string;\n\n /**\n * Query param: Return sessions created at or after this time (inclusive).\n */\n 'created_at[gte]'?: string;\n\n /**\n * Query param: Return sessions created before this time (exclusive).\n */\n 'created_at[lt]'?: string;\n\n /**\n * Query param: Return sessions created at or before this time (inclusive).\n */\n 'created_at[lte]'?: string;\n\n /**\n * Query param: Filter sessions created by this deployment ID.\n */\n deployment_id?: string;\n\n /**\n * Query param: When true, includes archived sessions. Default: false (exclude\n * archived).\n */\n include_archived?: boolean;\n\n /**\n * Query param: Filter sessions whose resources contain a memory_store with this\n * memory store ID.\n */\n memory_store_id?: string;\n\n /**\n * Query param: Sort direction for results, ordered by created_at. Defaults to desc\n * (newest first).\n */\n order?: 'asc' | 'desc';\n\n /**\n * Query param: Filter by session status. Repeat the parameter to match any of\n * multiple statuses.\n */\n statuses?: Array<'rescheduling' | 'running' | 'idle' | 'terminated'>;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface SessionDeleteParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface SessionArchiveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nSessions.Events = Events;\nSessions.Resources = Resources;\nSessions.Threads = Threads;\n\nexport declare namespace Sessions {\n export {\n type BetaManagedAgentsAgentParams as BetaManagedAgentsAgentParams,\n type BetaManagedAgentsBranchCheckout as BetaManagedAgentsBranchCheckout,\n type BetaManagedAgentsCacheCreationUsage as BetaManagedAgentsCacheCreationUsage,\n type BetaManagedAgentsCommitCheckout as BetaManagedAgentsCommitCheckout,\n type BetaManagedAgentsDeletedSession as BetaManagedAgentsDeletedSession,\n type BetaManagedAgentsFileResourceParams as BetaManagedAgentsFileResourceParams,\n type BetaManagedAgentsGitHubRepositoryResourceParams as BetaManagedAgentsGitHubRepositoryResourceParams,\n type BetaManagedAgentsMemoryStoreResourceParam as BetaManagedAgentsMemoryStoreResourceParam,\n type BetaManagedAgentsMultiagent as BetaManagedAgentsMultiagent,\n type BetaManagedAgentsMultiagentParams as BetaManagedAgentsMultiagentParams,\n type BetaManagedAgentsMultiagentRosterEntryParams as BetaManagedAgentsMultiagentRosterEntryParams,\n type BetaManagedAgentsOutcomeEvaluationResource as BetaManagedAgentsOutcomeEvaluationResource,\n type BetaManagedAgentsSession as BetaManagedAgentsSession,\n type BetaManagedAgentsSessionAgent as BetaManagedAgentsSessionAgent,\n type BetaManagedAgentsSessionAgentUpdate as BetaManagedAgentsSessionAgentUpdate,\n type BetaManagedAgentsSessionMultiagentCoordinator as BetaManagedAgentsSessionMultiagentCoordinator,\n type BetaManagedAgentsSessionStats as BetaManagedAgentsSessionStats,\n type BetaManagedAgentsSessionUpdatedEvent as BetaManagedAgentsSessionUpdatedEvent,\n type BetaManagedAgentsSessionUsage as BetaManagedAgentsSessionUsage,\n type BetaManagedAgentsSystemContentBlock as BetaManagedAgentsSystemContentBlock,\n type BetaManagedAgentsSystemMessageEvent as BetaManagedAgentsSystemMessageEvent,\n type BetaManagedAgentsUserToolResultEvent as BetaManagedAgentsUserToolResultEvent,\n type BetaManagedAgentsSessionsPageCursor as BetaManagedAgentsSessionsPageCursor,\n type SessionCreateParams as SessionCreateParams,\n type SessionRetrieveParams as SessionRetrieveParams,\n type SessionUpdateParams as SessionUpdateParams,\n type SessionListParams as SessionListParams,\n type SessionDeleteParams as SessionDeleteParams,\n type SessionArchiveParams as SessionArchiveParams,\n };\n\n export {\n Events as Events,\n type BetaManagedAgentsAgentCustomToolUseEvent as BetaManagedAgentsAgentCustomToolUseEvent,\n type BetaManagedAgentsAgentMCPToolResultEvent as BetaManagedAgentsAgentMCPToolResultEvent,\n type BetaManagedAgentsAgentMCPToolUseEvent as BetaManagedAgentsAgentMCPToolUseEvent,\n type BetaManagedAgentsAgentMessageEvent as BetaManagedAgentsAgentMessageEvent,\n type BetaManagedAgentsAgentThinkingEvent as BetaManagedAgentsAgentThinkingEvent,\n type BetaManagedAgentsAgentThreadContextCompactedEvent as BetaManagedAgentsAgentThreadContextCompactedEvent,\n type BetaManagedAgentsAgentThreadMessageReceivedEvent as BetaManagedAgentsAgentThreadMessageReceivedEvent,\n type BetaManagedAgentsAgentThreadMessageSentEvent as BetaManagedAgentsAgentThreadMessageSentEvent,\n type BetaManagedAgentsAgentToolResultEvent as BetaManagedAgentsAgentToolResultEvent,\n type BetaManagedAgentsAgentToolUseEvent as BetaManagedAgentsAgentToolUseEvent,\n type BetaManagedAgentsBase64DocumentSource as BetaManagedAgentsBase64DocumentSource,\n type BetaManagedAgentsBase64ImageSource as BetaManagedAgentsBase64ImageSource,\n type BetaManagedAgentsBillingError as BetaManagedAgentsBillingError,\n type BetaManagedAgentsCredentialHostUnreachableError as BetaManagedAgentsCredentialHostUnreachableError,\n type BetaManagedAgentsDocumentBlock as BetaManagedAgentsDocumentBlock,\n type BetaManagedAgentsEventParams as BetaManagedAgentsEventParams,\n type BetaManagedAgentsFileDocumentSource as BetaManagedAgentsFileDocumentSource,\n type BetaManagedAgentsFileImageSource as BetaManagedAgentsFileImageSource,\n type BetaManagedAgentsFileRubric as BetaManagedAgentsFileRubric,\n type BetaManagedAgentsFileRubricParams as BetaManagedAgentsFileRubricParams,\n type BetaManagedAgentsImageBlock as BetaManagedAgentsImageBlock,\n type BetaManagedAgentsMCPAuthenticationFailedError as BetaManagedAgentsMCPAuthenticationFailedError,\n type BetaManagedAgentsMCPConnectionFailedError as BetaManagedAgentsMCPConnectionFailedError,\n type BetaManagedAgentsModelOverloadedError as BetaManagedAgentsModelOverloadedError,\n type BetaManagedAgentsModelRateLimitedError as BetaManagedAgentsModelRateLimitedError,\n type BetaManagedAgentsModelRequestFailedError as BetaManagedAgentsModelRequestFailedError,\n type BetaManagedAgentsPlainTextDocumentSource as BetaManagedAgentsPlainTextDocumentSource,\n type BetaManagedAgentsRetryStatusExhausted as BetaManagedAgentsRetryStatusExhausted,\n type BetaManagedAgentsRetryStatusRetrying as BetaManagedAgentsRetryStatusRetrying,\n type BetaManagedAgentsRetryStatusTerminal as BetaManagedAgentsRetryStatusTerminal,\n type BetaManagedAgentsSearchResultBlock as BetaManagedAgentsSearchResultBlock,\n type BetaManagedAgentsSearchResultCitations as BetaManagedAgentsSearchResultCitations,\n type BetaManagedAgentsSearchResultContent as BetaManagedAgentsSearchResultContent,\n type BetaManagedAgentsSendSessionEvents as BetaManagedAgentsSendSessionEvents,\n type BetaManagedAgentsSessionDeletedEvent as BetaManagedAgentsSessionDeletedEvent,\n type BetaManagedAgentsSessionEndTurn as BetaManagedAgentsSessionEndTurn,\n type BetaManagedAgentsSessionErrorEvent as BetaManagedAgentsSessionErrorEvent,\n type BetaManagedAgentsSessionEvent as BetaManagedAgentsSessionEvent,\n type BetaManagedAgentsSessionRequiresAction as BetaManagedAgentsSessionRequiresAction,\n type BetaManagedAgentsSessionRetriesExhausted as BetaManagedAgentsSessionRetriesExhausted,\n type BetaManagedAgentsSessionStatusIdleEvent as BetaManagedAgentsSessionStatusIdleEvent,\n type BetaManagedAgentsSessionStatusRescheduledEvent as BetaManagedAgentsSessionStatusRescheduledEvent,\n type BetaManagedAgentsSessionStatusRunningEvent as BetaManagedAgentsSessionStatusRunningEvent,\n type BetaManagedAgentsSessionStatusTerminatedEvent as BetaManagedAgentsSessionStatusTerminatedEvent,\n type BetaManagedAgentsSessionThreadCreatedEvent as BetaManagedAgentsSessionThreadCreatedEvent,\n type BetaManagedAgentsSessionThreadStatusIdleEvent as BetaManagedAgentsSessionThreadStatusIdleEvent,\n type BetaManagedAgentsSessionThreadStatusRescheduledEvent as BetaManagedAgentsSessionThreadStatusRescheduledEvent,\n type BetaManagedAgentsSessionThreadStatusRunningEvent as BetaManagedAgentsSessionThreadStatusRunningEvent,\n type BetaManagedAgentsSessionThreadStatusTerminatedEvent as BetaManagedAgentsSessionThreadStatusTerminatedEvent,\n type BetaManagedAgentsSpanModelRequestEndEvent as BetaManagedAgentsSpanModelRequestEndEvent,\n type BetaManagedAgentsSpanModelRequestStartEvent as BetaManagedAgentsSpanModelRequestStartEvent,\n type BetaManagedAgentsSpanModelUsage as BetaManagedAgentsSpanModelUsage,\n type BetaManagedAgentsSpanOutcomeEvaluationEndEvent as BetaManagedAgentsSpanOutcomeEvaluationEndEvent,\n type BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent as BetaManagedAgentsSpanOutcomeEvaluationOngoingEvent,\n type BetaManagedAgentsSpanOutcomeEvaluationStartEvent as BetaManagedAgentsSpanOutcomeEvaluationStartEvent,\n type BetaManagedAgentsStreamSessionEvents as BetaManagedAgentsStreamSessionEvents,\n type BetaManagedAgentsSystemMessageEventParams as BetaManagedAgentsSystemMessageEventParams,\n type BetaManagedAgentsTextBlock as BetaManagedAgentsTextBlock,\n type BetaManagedAgentsTextRubric as BetaManagedAgentsTextRubric,\n type BetaManagedAgentsTextRubricParams as BetaManagedAgentsTextRubricParams,\n type BetaManagedAgentsUnknownError as BetaManagedAgentsUnknownError,\n type BetaManagedAgentsURLDocumentSource as BetaManagedAgentsURLDocumentSource,\n type BetaManagedAgentsURLImageSource as BetaManagedAgentsURLImageSource,\n type BetaManagedAgentsUserCustomToolResultEvent as BetaManagedAgentsUserCustomToolResultEvent,\n type BetaManagedAgentsUserCustomToolResultEventParams as BetaManagedAgentsUserCustomToolResultEventParams,\n type BetaManagedAgentsUserDefineOutcomeEvent as BetaManagedAgentsUserDefineOutcomeEvent,\n type BetaManagedAgentsUserDefineOutcomeEventParams as BetaManagedAgentsUserDefineOutcomeEventParams,\n type BetaManagedAgentsUserInterruptEvent as BetaManagedAgentsUserInterruptEvent,\n type BetaManagedAgentsUserInterruptEventParams as BetaManagedAgentsUserInterruptEventParams,\n type BetaManagedAgentsUserMessageEvent as BetaManagedAgentsUserMessageEvent,\n type BetaManagedAgentsUserMessageEventParams as BetaManagedAgentsUserMessageEventParams,\n type BetaManagedAgentsUserToolConfirmationEvent as BetaManagedAgentsUserToolConfirmationEvent,\n type BetaManagedAgentsUserToolConfirmationEventParams as BetaManagedAgentsUserToolConfirmationEventParams,\n type BetaManagedAgentsUserToolResultEventParams as BetaManagedAgentsUserToolResultEventParams,\n type BetaManagedAgentsSessionEventsPageCursor as BetaManagedAgentsSessionEventsPageCursor,\n type EventListParams as EventListParams,\n type EventSendParams as EventSendParams,\n type EventStreamParams as EventStreamParams,\n };\n\n export {\n Resources as Resources,\n type BetaManagedAgentsDeleteSessionResource as BetaManagedAgentsDeleteSessionResource,\n type BetaManagedAgentsFileResource as BetaManagedAgentsFileResource,\n type BetaManagedAgentsGitHubRepositoryResource as BetaManagedAgentsGitHubRepositoryResource,\n type BetaManagedAgentsMemoryStoreResource as BetaManagedAgentsMemoryStoreResource,\n type BetaManagedAgentsSessionResource as BetaManagedAgentsSessionResource,\n type ResourceRetrieveResponse as ResourceRetrieveResponse,\n type ResourceUpdateResponse as ResourceUpdateResponse,\n type BetaManagedAgentsSessionResourcesPageCursor as BetaManagedAgentsSessionResourcesPageCursor,\n type ResourceRetrieveParams as ResourceRetrieveParams,\n type ResourceUpdateParams as ResourceUpdateParams,\n type ResourceListParams as ResourceListParams,\n type ResourceDeleteParams as ResourceDeleteParams,\n type ResourceAddParams as ResourceAddParams,\n };\n\n export {\n Threads as Threads,\n type BetaManagedAgentsSessionThread as BetaManagedAgentsSessionThread,\n type BetaManagedAgentsSessionThreadStats as BetaManagedAgentsSessionThreadStats,\n type BetaManagedAgentsSessionThreadStatus as BetaManagedAgentsSessionThreadStatus,\n type BetaManagedAgentsSessionThreadUsage as BetaManagedAgentsSessionThreadUsage,\n type BetaManagedAgentsStreamSessionThreadEvents as BetaManagedAgentsStreamSessionThreadEvents,\n type BetaManagedAgentsSessionThreadsPageCursor as BetaManagedAgentsSessionThreadsPageCursor,\n type ThreadRetrieveParams as ThreadRetrieveParams,\n type ThreadListParams as ThreadListParams,\n type ThreadArchiveParams as ThreadArchiveParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { type Uploadable } from '../../../core/uploads';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { multipartFormRequestOptions } from '../../../internal/uploads';\nimport { path } from '../../../internal/utils/path';\n\nexport class Versions extends APIResource {\n /**\n * Create Skill Version\n *\n * @example\n * ```ts\n * const version = await client.beta.skills.versions.create(\n * 'skill_id',\n * );\n * ```\n */\n create(\n skillID: string,\n params: VersionCreateParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<VersionCreateResponse> {\n const { betas, ...body } = params ?? {};\n return this._client.post(\n path`/v1/skills/${skillID}/versions?beta=true`,\n multipartFormRequestOptions(\n {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },\n options?.headers,\n ]),\n },\n this._client,\n false,\n ),\n );\n }\n\n /**\n * Get Skill Version\n *\n * @example\n * ```ts\n * const version = await client.beta.skills.versions.retrieve(\n * 'version',\n * { skill_id: 'skill_id' },\n * );\n * ```\n */\n retrieve(\n version: string,\n params: VersionRetrieveParams,\n options?: RequestOptions,\n ): APIPromise<VersionRetrieveResponse> {\n const { skill_id, betas } = params;\n return this._client.get(path`/v1/skills/${skill_id}/versions/${version}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Skill Versions\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const versionListResponse of client.beta.skills.versions.list(\n * 'skill_id',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n skillID: string,\n params: VersionListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<VersionListResponsesPageCursor, VersionListResponse> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n path`/v1/skills/${skillID}/versions?beta=true`,\n PageCursor<VersionListResponse>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * Delete Skill Version\n *\n * @example\n * ```ts\n * const version = await client.beta.skills.versions.delete(\n * 'version',\n * { skill_id: 'skill_id' },\n * );\n * ```\n */\n delete(\n version: string,\n params: VersionDeleteParams,\n options?: RequestOptions,\n ): APIPromise<VersionDeleteResponse> {\n const { skill_id, betas } = params;\n return this._client.delete(path`/v1/skills/${skill_id}/versions/${version}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Download a skill version's content as a zip archive.\n *\n * @example\n * ```ts\n * const response = await client.beta.skills.versions.download(\n * 'version',\n * { skill_id: 'skill_id' },\n * );\n *\n * const content = await response.blob();\n * console.log(content);\n * ```\n */\n download(version: string, params: VersionDownloadParams, options?: RequestOptions): APIPromise<Response> {\n const { skill_id, betas } = params;\n return this._client.get(path`/v1/skills/${skill_id}/versions/${version}/content?beta=true`, {\n ...options,\n headers: buildHeaders([\n {\n 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString(),\n Accept: 'application/binary',\n },\n options?.headers,\n ]),\n __binaryResponse: true,\n });\n }\n}\n\nexport type VersionListResponsesPageCursor = PageCursor<VersionListResponse>;\n\nexport interface VersionCreateResponse {\n /**\n * Unique identifier for the skill version.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * ISO 8601 timestamp of when the skill version was created.\n */\n created_at: string;\n\n /**\n * Description of the skill version.\n *\n * This is extracted from the SKILL.md file in the skill upload.\n */\n description: string;\n\n /**\n * Directory name of the skill version.\n *\n * This is the top-level directory name that was extracted from the uploaded files.\n */\n directory: string;\n\n /**\n * Human-readable name of the skill version.\n *\n * This is extracted from the SKILL.md file in the skill upload.\n */\n name: string;\n\n /**\n * Identifier for the skill that this version belongs to.\n */\n skill_id: string;\n\n /**\n * Object type.\n *\n * For Skill Versions, this is always `\"skill_version\"`.\n */\n type: string;\n\n /**\n * Version identifier for the skill.\n *\n * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n */\n version: string;\n}\n\nexport interface VersionRetrieveResponse {\n /**\n * Unique identifier for the skill version.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * ISO 8601 timestamp of when the skill version was created.\n */\n created_at: string;\n\n /**\n * Description of the skill version.\n *\n * This is extracted from the SKILL.md file in the skill upload.\n */\n description: string;\n\n /**\n * Directory name of the skill version.\n *\n * This is the top-level directory name that was extracted from the uploaded files.\n */\n directory: string;\n\n /**\n * Human-readable name of the skill version.\n *\n * This is extracted from the SKILL.md file in the skill upload.\n */\n name: string;\n\n /**\n * Identifier for the skill that this version belongs to.\n */\n skill_id: string;\n\n /**\n * Object type.\n *\n * For Skill Versions, this is always `\"skill_version\"`.\n */\n type: string;\n\n /**\n * Version identifier for the skill.\n *\n * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n */\n version: string;\n}\n\nexport interface VersionListResponse {\n /**\n * Unique identifier for the skill version.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * ISO 8601 timestamp of when the skill version was created.\n */\n created_at: string;\n\n /**\n * Description of the skill version.\n *\n * This is extracted from the SKILL.md file in the skill upload.\n */\n description: string;\n\n /**\n * Directory name of the skill version.\n *\n * This is the top-level directory name that was extracted from the uploaded files.\n */\n directory: string;\n\n /**\n * Human-readable name of the skill version.\n *\n * This is extracted from the SKILL.md file in the skill upload.\n */\n name: string;\n\n /**\n * Identifier for the skill that this version belongs to.\n */\n skill_id: string;\n\n /**\n * Object type.\n *\n * For Skill Versions, this is always `\"skill_version\"`.\n */\n type: string;\n\n /**\n * Version identifier for the skill.\n *\n * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n */\n version: string;\n}\n\nexport interface VersionDeleteResponse {\n /**\n * Version identifier for the skill.\n *\n * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n */\n id: string;\n\n /**\n * Deleted object type.\n *\n * For Skill Versions, this is always `\"skill_version_deleted\"`.\n */\n type: string;\n}\n\nexport interface VersionCreateParams {\n /**\n * Body param: Files to upload for the skill.\n *\n * All files must be in the same top-level directory and must include a SKILL.md\n * file at the root of that directory.\n */\n files?: Array<Uploadable> | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface VersionRetrieveParams {\n /**\n * Path param: Unique identifier for the skill.\n *\n * The format and length of IDs may change over time.\n */\n skill_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface VersionListParams extends PageCursorParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface VersionDeleteParams {\n /**\n * Path param: Unique identifier for the skill.\n *\n * The format and length of IDs may change over time.\n */\n skill_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface VersionDownloadParams {\n /**\n * Path param: Unique identifier for the skill.\n *\n * The format and length of IDs may change over time.\n */\n skill_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Versions {\n export {\n type VersionCreateResponse as VersionCreateResponse,\n type VersionRetrieveResponse as VersionRetrieveResponse,\n type VersionListResponse as VersionListResponse,\n type VersionDeleteResponse as VersionDeleteResponse,\n type VersionListResponsesPageCursor as VersionListResponsesPageCursor,\n type VersionCreateParams as VersionCreateParams,\n type VersionRetrieveParams as VersionRetrieveParams,\n type VersionListParams as VersionListParams,\n type VersionDeleteParams as VersionDeleteParams,\n type VersionDownloadParams as VersionDownloadParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as VersionsAPI from './versions';\nimport {\n VersionCreateParams,\n VersionCreateResponse,\n VersionDeleteParams,\n VersionDeleteResponse,\n VersionDownloadParams,\n VersionListParams,\n VersionListResponse,\n VersionListResponsesPageCursor,\n VersionRetrieveParams,\n VersionRetrieveResponse,\n Versions,\n} from './versions';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { type Uploadable } from '../../../core/uploads';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { multipartFormRequestOptions } from '../../../internal/uploads';\nimport { path } from '../../../internal/utils/path';\n\nexport class Skills extends APIResource {\n versions: VersionsAPI.Versions = new VersionsAPI.Versions(this._client);\n\n /**\n * Create Skill\n *\n * @example\n * ```ts\n * const skill = await client.beta.skills.create();\n * ```\n */\n create(\n params: SkillCreateParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<SkillCreateResponse> {\n const { betas, ...body } = params ?? {};\n return this._client.post(\n '/v1/skills?beta=true',\n multipartFormRequestOptions(\n {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },\n options?.headers,\n ]),\n },\n this._client,\n false,\n ),\n );\n }\n\n /**\n * Get Skill\n *\n * @example\n * ```ts\n * const skill = await client.beta.skills.retrieve('skill_id');\n * ```\n */\n retrieve(\n skillID: string,\n params: SkillRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<SkillRetrieveResponse> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/skills/${skillID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Skills\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const skillListResponse of client.beta.skills.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: SkillListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<SkillListResponsesPageCursor, SkillListResponse> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/skills?beta=true', PageCursor<SkillListResponse>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Delete Skill\n *\n * @example\n * ```ts\n * const skill = await client.beta.skills.delete('skill_id');\n * ```\n */\n delete(\n skillID: string,\n params: SkillDeleteParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<SkillDeleteResponse> {\n const { betas } = params ?? {};\n return this._client.delete(path`/v1/skills/${skillID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type SkillListResponsesPageCursor = PageCursor<SkillListResponse>;\n\nexport interface SkillCreateResponse {\n /**\n * Unique identifier for the skill.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * ISO 8601 timestamp of when the skill was created.\n */\n created_at: string;\n\n /**\n * Display title for the skill.\n *\n * This is a human-readable label that is not included in the prompt sent to the\n * model.\n */\n display_title: string | null;\n\n /**\n * The latest version identifier for the skill.\n *\n * This represents the most recent version of the skill that has been created.\n */\n latest_version: string | null;\n\n /**\n * Source of the skill.\n *\n * This may be one of the following values:\n *\n * - `\"custom\"`: the skill was created by a user\n * - `\"anthropic\"`: the skill was created by Anthropic\n */\n source: string;\n\n /**\n * Object type.\n *\n * For Skills, this is always `\"skill\"`.\n */\n type: string;\n\n /**\n * ISO 8601 timestamp of when the skill was last updated.\n */\n updated_at: string;\n}\n\nexport interface SkillRetrieveResponse {\n /**\n * Unique identifier for the skill.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * ISO 8601 timestamp of when the skill was created.\n */\n created_at: string;\n\n /**\n * Display title for the skill.\n *\n * This is a human-readable label that is not included in the prompt sent to the\n * model.\n */\n display_title: string | null;\n\n /**\n * The latest version identifier for the skill.\n *\n * This represents the most recent version of the skill that has been created.\n */\n latest_version: string | null;\n\n /**\n * Source of the skill.\n *\n * This may be one of the following values:\n *\n * - `\"custom\"`: the skill was created by a user\n * - `\"anthropic\"`: the skill was created by Anthropic\n */\n source: string;\n\n /**\n * Object type.\n *\n * For Skills, this is always `\"skill\"`.\n */\n type: string;\n\n /**\n * ISO 8601 timestamp of when the skill was last updated.\n */\n updated_at: string;\n}\n\nexport interface SkillListResponse {\n /**\n * Unique identifier for the skill.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * ISO 8601 timestamp of when the skill was created.\n */\n created_at: string;\n\n /**\n * Display title for the skill.\n *\n * This is a human-readable label that is not included in the prompt sent to the\n * model.\n */\n display_title: string | null;\n\n /**\n * The latest version identifier for the skill.\n *\n * This represents the most recent version of the skill that has been created.\n */\n latest_version: string | null;\n\n /**\n * Source of the skill.\n *\n * This may be one of the following values:\n *\n * - `\"custom\"`: the skill was created by a user\n * - `\"anthropic\"`: the skill was created by Anthropic\n */\n source: string;\n\n /**\n * Object type.\n *\n * For Skills, this is always `\"skill\"`.\n */\n type: string;\n\n /**\n * ISO 8601 timestamp of when the skill was last updated.\n */\n updated_at: string;\n}\n\nexport interface SkillDeleteResponse {\n /**\n * Unique identifier for the skill.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * Deleted object type.\n *\n * For Skills, this is always `\"skill_deleted\"`.\n */\n type: string;\n}\n\nexport interface SkillCreateParams {\n /**\n * Body param: Display title for the skill.\n *\n * This is a human-readable label that is not included in the prompt sent to the\n * model.\n */\n display_title?: string | null;\n\n /**\n * Body param: Files to upload for the skill.\n *\n * All files must be in the same top-level directory and must include a SKILL.md\n * file at the root of that directory.\n */\n files?: Array<Uploadable> | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface SkillRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface SkillListParams extends PageCursorParams {\n /**\n * Query param: Filter skills by source.\n *\n * If provided, only skills from the specified source will be returned:\n *\n * - `\"custom\"`: only return user-created skills\n * - `\"anthropic\"`: only return Anthropic-created skills\n */\n source?: string | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface SkillDeleteParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nSkills.Versions = Versions;\n\nexport declare namespace Skills {\n export {\n type SkillCreateResponse as SkillCreateResponse,\n type SkillRetrieveResponse as SkillRetrieveResponse,\n type SkillListResponse as SkillListResponse,\n type SkillDeleteResponse as SkillDeleteResponse,\n type SkillListResponsesPageCursor as SkillListResponsesPageCursor,\n type SkillCreateParams as SkillCreateParams,\n type SkillRetrieveParams as SkillRetrieveParams,\n type SkillListParams as SkillListParams,\n type SkillDeleteParams as SkillDeleteParams,\n };\n\n export {\n Versions as Versions,\n type VersionCreateResponse as VersionCreateResponse,\n type VersionRetrieveResponse as VersionRetrieveResponse,\n type VersionListResponse as VersionListResponse,\n type VersionDeleteResponse as VersionDeleteResponse,\n type VersionListResponsesPageCursor as VersionListResponsesPageCursor,\n type VersionCreateParams as VersionCreateParams,\n type VersionRetrieveParams as VersionRetrieveParams,\n type VersionListParams as VersionListParams,\n type VersionDeleteParams as VersionDeleteParams,\n type VersionDownloadParams as VersionDownloadParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class Credentials extends APIResource {\n /**\n * Create Credential\n *\n * @example\n * ```ts\n * const betaManagedAgentsCredential =\n * await client.beta.vaults.credentials.create(\n * 'vlt_011CZkZDLs7fYzm1hXNPeRjv',\n * {\n * auth: {\n * token: 'bearer_exampletoken',\n * mcp_server_url:\n * 'https://example-server.modelcontextprotocol.io/sse',\n * type: 'static_bearer',\n * },\n * },\n * );\n * ```\n */\n create(\n vaultID: string,\n params: CredentialCreateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsCredential> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/vaults/${vaultID}/credentials?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Get Credential\n *\n * @example\n * ```ts\n * const betaManagedAgentsCredential =\n * await client.beta.vaults.credentials.retrieve(\n * 'vcrd_011CZkZEMt8gZan2iYOQfSkw',\n * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },\n * );\n * ```\n */\n retrieve(\n credentialID: string,\n params: CredentialRetrieveParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsCredential> {\n const { vault_id, betas } = params;\n return this._client.get(path`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update Credential\n *\n * @example\n * ```ts\n * const betaManagedAgentsCredential =\n * await client.beta.vaults.credentials.update(\n * 'vcrd_011CZkZEMt8gZan2iYOQfSkw',\n * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },\n * );\n * ```\n */\n update(\n credentialID: string,\n params: CredentialUpdateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsCredential> {\n const { vault_id, betas, ...body } = params;\n return this._client.post(path`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Credentials\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsCredential of client.beta.vaults.credentials.list(\n * 'vlt_011CZkZDLs7fYzm1hXNPeRjv',\n * )) {\n * // ...\n * }\n * ```\n */\n list(\n vaultID: string,\n params: CredentialListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsCredentialsPageCursor, BetaManagedAgentsCredential> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList(\n path`/v1/vaults/${vaultID}/credentials?beta=true`,\n PageCursor<BetaManagedAgentsCredential>,\n {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n\n /**\n * Delete Credential\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeletedCredential =\n * await client.beta.vaults.credentials.delete(\n * 'vcrd_011CZkZEMt8gZan2iYOQfSkw',\n * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },\n * );\n * ```\n */\n delete(\n credentialID: string,\n params: CredentialDeleteParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeletedCredential> {\n const { vault_id, betas } = params;\n return this._client.delete(path`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Archive Credential\n *\n * @example\n * ```ts\n * const betaManagedAgentsCredential =\n * await client.beta.vaults.credentials.archive(\n * 'vcrd_011CZkZEMt8gZan2iYOQfSkw',\n * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },\n * );\n * ```\n */\n archive(\n credentialID: string,\n params: CredentialArchiveParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsCredential> {\n const { vault_id, betas } = params;\n return this._client.post(path`/v1/vaults/${vault_id}/credentials/${credentialID}/archive?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Validate Credential\n *\n * @example\n * ```ts\n * const betaManagedAgentsCredentialValidation =\n * await client.beta.vaults.credentials.mcpOAuthValidate(\n * 'vcrd_011CZkZEMt8gZan2iYOQfSkw',\n * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },\n * );\n * ```\n */\n mcpOAuthValidate(\n credentialID: string,\n params: CredentialMCPOAuthValidateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsCredentialValidation> {\n const { vault_id, betas } = params;\n return this._client.post(\n path`/v1/vaults/${vault_id}/credentials/${credentialID}/mcp_oauth_validate?beta=true`,\n {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n },\n );\n }\n}\n\nexport type BetaManagedAgentsCredentialsPageCursor = PageCursor<BetaManagedAgentsCredential>;\n\n/**\n * A credential stored in a vault. Sensitive fields are never returned in\n * responses.\n */\nexport interface BetaManagedAgentsCredential {\n /**\n * Unique identifier for the credential.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n archived_at: string | null;\n\n /**\n * Authentication details for a credential.\n */\n auth:\n | BetaManagedAgentsMCPOAuthAuthResponse\n | BetaManagedAgentsStaticBearerAuthResponse\n | BetaManagedAgentsEnvironmentVariableAuthResponse;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n /**\n * Arbitrary key-value metadata attached to the credential.\n */\n metadata: { [key: string]: string };\n\n type: 'vault_credential';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n\n /**\n * Identifier of the vault this credential belongs to.\n */\n vault_id: string;\n\n /**\n * Human-readable name for the credential.\n */\n display_name?: string | null;\n}\n\n/**\n * Substitute the secret on any host the session's Environment network policy\n * permits egress to. The Environment's network policy is the only boundary on\n * where the secret can reach.\n */\nexport type BetaManagedAgentsCredentialNetworkingParams =\n | BetaManagedAgentsUnrestrictedCredentialNetworkingParams\n | BetaManagedAgentsLimitedCredentialNetworkingParams;\n\n/**\n * Result of live-probing a credential against its configured MCP server.\n */\nexport interface BetaManagedAgentsCredentialValidation {\n /**\n * Unique identifier of the credential that was validated.\n */\n credential_id: string;\n\n /**\n * Whether the credential has a refresh token configured.\n */\n has_refresh_token: boolean;\n\n /**\n * The failing step of an MCP validation probe.\n */\n mcp_probe: BetaManagedAgentsMCPProbe | null;\n\n /**\n * Outcome of a refresh-token exchange attempted during credential validation.\n */\n refresh: BetaManagedAgentsRefreshObject | null;\n\n /**\n * Overall verdict of a credential validation probe.\n */\n status: BetaManagedAgentsCredentialValidationStatus;\n\n type: 'vault_credential_validation';\n\n /**\n * A timestamp in RFC 3339 format\n */\n validated_at: string;\n\n /**\n * Identifier of the vault containing the credential.\n */\n vault_id: string;\n}\n\n/**\n * Overall verdict of a credential validation probe.\n */\nexport type BetaManagedAgentsCredentialValidationStatus = 'valid' | 'invalid' | 'unknown';\n\n/**\n * Confirmation of a deleted credential.\n */\nexport interface BetaManagedAgentsDeletedCredential {\n /**\n * Unique identifier of the deleted credential.\n */\n id: string;\n\n type: 'vault_credential_deleted';\n}\n\n/**\n * Environment variable credential details. The secret value is never returned.\n */\nexport interface BetaManagedAgentsEnvironmentVariableAuthResponse {\n /**\n * Outbound hosts the secret value is substituted on.\n */\n networking:\n | BetaManagedAgentsUnrestrictedCredentialNetworkingResponse\n | BetaManagedAgentsLimitedCredentialNetworkingResponse;\n\n /**\n * Name of the environment variable.\n */\n secret_name: string;\n\n type: 'environment_variable';\n}\n\n/**\n * Parameters for creating an environment variable credential.\n */\nexport interface BetaManagedAgentsEnvironmentVariableCreateParams {\n /**\n * Outbound hosts the secret value is substituted on.\n */\n networking: BetaManagedAgentsCredentialNetworkingParams;\n\n /**\n * Name of the environment variable. Immutable after create.\n */\n secret_name: string;\n\n /**\n * Secret value. Write-only; never returned in responses.\n */\n secret_value: string;\n\n type: 'environment_variable';\n}\n\n/**\n * Parameters for updating an environment variable credential. `secret_name` is\n * immutable.\n */\nexport interface BetaManagedAgentsEnvironmentVariableUpdateParams {\n type: 'environment_variable';\n\n /**\n * Updated networking scope. Full replacement.\n */\n networking?: BetaManagedAgentsCredentialNetworkingParams | null;\n\n /**\n * Updated secret value.\n */\n secret_value?: string | null;\n}\n\n/**\n * Substitute the secret only on requests to the listed hosts.\n */\nexport interface BetaManagedAgentsLimitedCredentialNetworkingParams {\n /**\n * Hostnames on which the secret will be substituted. Each entry is a bare hostname\n * (`api.example.com`), an IPv4 address (`192.0.2.1`), or a `*.`-prefixed wildcard\n * (`*.example.com`). URLs, ports, paths, and IPv6 addresses are not accepted. At\n * most 16 entries.\n */\n allowed_hosts: Array<string>;\n\n type: 'limited';\n}\n\n/**\n * The secret is substituted only on requests to the listed hosts.\n */\nexport interface BetaManagedAgentsLimitedCredentialNetworkingResponse {\n /**\n * Hostnames on which the secret will be substituted. An entry matches the request\n * host exactly; a `*.`-prefixed entry matches any subdomain of the named domain\n * but not the domain itself.\n */\n allowed_hosts: Array<string>;\n\n type: 'limited';\n}\n\n/**\n * OAuth credential details for an MCP server.\n */\nexport interface BetaManagedAgentsMCPOAuthAuthResponse {\n /**\n * URL of the MCP server this credential authenticates against.\n */\n mcp_server_url: string;\n\n type: 'mcp_oauth';\n\n /**\n * A timestamp in RFC 3339 format\n */\n expires_at?: string | null;\n\n /**\n * OAuth refresh token configuration returned in credential responses.\n */\n refresh?: BetaManagedAgentsMCPOAuthRefreshResponse | null;\n}\n\n/**\n * Parameters for creating an MCP OAuth credential.\n */\nexport interface BetaManagedAgentsMCPOAuthCreateParams {\n /**\n * OAuth access token.\n */\n access_token: string;\n\n /**\n * URL of the MCP server this credential authenticates against.\n */\n mcp_server_url: string;\n\n type: 'mcp_oauth';\n\n /**\n * A timestamp in RFC 3339 format\n */\n expires_at?: string | null;\n\n /**\n * OAuth refresh token parameters for creating a credential with refresh support.\n */\n refresh?: BetaManagedAgentsMCPOAuthRefreshParams | null;\n}\n\n/**\n * OAuth refresh token parameters for creating a credential with refresh support.\n */\nexport interface BetaManagedAgentsMCPOAuthRefreshParams {\n /**\n * OAuth client ID.\n */\n client_id: string;\n\n /**\n * OAuth refresh token.\n */\n refresh_token: string;\n\n /**\n * Token endpoint URL used to refresh the access token.\n */\n token_endpoint: string;\n\n /**\n * Token endpoint requires no client authentication.\n */\n token_endpoint_auth:\n | BetaManagedAgentsTokenEndpointAuthNoneParam\n | BetaManagedAgentsTokenEndpointAuthBasicParam\n | BetaManagedAgentsTokenEndpointAuthPostParam;\n\n /**\n * OAuth resource indicator.\n */\n resource?: string | null;\n\n /**\n * OAuth scope for the refresh request.\n */\n scope?: string | null;\n}\n\n/**\n * OAuth refresh token configuration returned in credential responses.\n */\nexport interface BetaManagedAgentsMCPOAuthRefreshResponse {\n /**\n * OAuth client ID.\n */\n client_id: string;\n\n /**\n * Token endpoint URL used to refresh the access token.\n */\n token_endpoint: string;\n\n /**\n * Token endpoint requires no client authentication.\n */\n token_endpoint_auth:\n | BetaManagedAgentsTokenEndpointAuthNoneResponse\n | BetaManagedAgentsTokenEndpointAuthBasicResponse\n | BetaManagedAgentsTokenEndpointAuthPostResponse;\n\n /**\n * OAuth resource indicator.\n */\n resource?: string | null;\n\n /**\n * OAuth scope for the refresh request.\n */\n scope?: string | null;\n}\n\n/**\n * Parameters for updating OAuth refresh token configuration.\n */\nexport interface BetaManagedAgentsMCPOAuthRefreshUpdateParams {\n /**\n * Updated OAuth refresh token.\n */\n refresh_token?: string | null;\n\n /**\n * Updated OAuth scope for the refresh request.\n */\n scope?: string | null;\n\n /**\n * Updated HTTP Basic authentication parameters for the token endpoint.\n */\n token_endpoint_auth?:\n | BetaManagedAgentsTokenEndpointAuthBasicUpdateParam\n | BetaManagedAgentsTokenEndpointAuthPostUpdateParam;\n}\n\n/**\n * Parameters for updating an MCP OAuth credential. The `mcp_server_url` is\n * immutable.\n */\nexport interface BetaManagedAgentsMCPOAuthUpdateParams {\n type: 'mcp_oauth';\n\n /**\n * Updated OAuth access token.\n */\n access_token?: string | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n expires_at?: string | null;\n\n /**\n * Parameters for updating OAuth refresh token configuration.\n */\n refresh?: BetaManagedAgentsMCPOAuthRefreshUpdateParams | null;\n}\n\n/**\n * The failing step of an MCP validation probe.\n */\nexport interface BetaManagedAgentsMCPProbe {\n /**\n * An HTTP response captured during a credential validation probe.\n */\n http_response: BetaManagedAgentsRefreshHTTPResponse | null;\n\n /**\n * The MCP method that failed (for example `initialize` or `tools/list`).\n */\n method: string;\n}\n\n/**\n * An HTTP response captured during a credential validation probe.\n */\nexport interface BetaManagedAgentsRefreshHTTPResponse {\n /**\n * Response body. May be truncated and has sensitive values scrubbed.\n */\n body: string;\n\n /**\n * Whether `body` was truncated.\n */\n body_truncated: boolean;\n\n /**\n * Value of the `Content-Type` response header.\n */\n content_type: string;\n\n /**\n * HTTP status code.\n */\n status_code: number;\n}\n\n/**\n * Outcome of a refresh-token exchange attempted during credential validation.\n */\nexport interface BetaManagedAgentsRefreshObject {\n /**\n * An HTTP response captured during a credential validation probe.\n */\n http_response: BetaManagedAgentsRefreshHTTPResponse | null;\n\n /**\n * Outcome of a refresh-token exchange attempted during credential validation.\n */\n status: 'succeeded' | 'failed' | 'connect_error' | 'no_refresh_token';\n}\n\n/**\n * Static bearer token credential details for an MCP server.\n */\nexport interface BetaManagedAgentsStaticBearerAuthResponse {\n /**\n * URL of the MCP server this credential authenticates against.\n */\n mcp_server_url: string;\n\n type: 'static_bearer';\n}\n\n/**\n * Parameters for creating a static bearer token credential.\n */\nexport interface BetaManagedAgentsStaticBearerCreateParams {\n /**\n * Static bearer token value.\n */\n token: string;\n\n /**\n * URL of the MCP server this credential authenticates against.\n */\n mcp_server_url: string;\n\n type: 'static_bearer';\n}\n\n/**\n * Parameters for updating a static bearer token credential. The `mcp_server_url`\n * is immutable.\n */\nexport interface BetaManagedAgentsStaticBearerUpdateParams {\n type: 'static_bearer';\n\n /**\n * Updated static bearer token value.\n */\n token?: string | null;\n}\n\n/**\n * Token endpoint uses HTTP Basic authentication with client credentials.\n */\nexport interface BetaManagedAgentsTokenEndpointAuthBasicParam {\n /**\n * OAuth client secret.\n */\n client_secret: string;\n\n type: 'client_secret_basic';\n}\n\n/**\n * Token endpoint uses HTTP Basic authentication with client credentials.\n */\nexport interface BetaManagedAgentsTokenEndpointAuthBasicResponse {\n type: 'client_secret_basic';\n}\n\n/**\n * Updated HTTP Basic authentication parameters for the token endpoint.\n */\nexport interface BetaManagedAgentsTokenEndpointAuthBasicUpdateParam {\n type: 'client_secret_basic';\n\n /**\n * Updated OAuth client secret.\n */\n client_secret?: string | null;\n}\n\n/**\n * Token endpoint requires no client authentication.\n */\nexport interface BetaManagedAgentsTokenEndpointAuthNoneParam {\n type: 'none';\n}\n\n/**\n * Token endpoint requires no client authentication.\n */\nexport interface BetaManagedAgentsTokenEndpointAuthNoneResponse {\n type: 'none';\n}\n\n/**\n * Token endpoint uses POST body authentication with client credentials.\n */\nexport interface BetaManagedAgentsTokenEndpointAuthPostParam {\n /**\n * OAuth client secret.\n */\n client_secret: string;\n\n type: 'client_secret_post';\n}\n\n/**\n * Token endpoint uses POST body authentication with client credentials.\n */\nexport interface BetaManagedAgentsTokenEndpointAuthPostResponse {\n type: 'client_secret_post';\n}\n\n/**\n * Updated POST body authentication parameters for the token endpoint.\n */\nexport interface BetaManagedAgentsTokenEndpointAuthPostUpdateParam {\n type: 'client_secret_post';\n\n /**\n * Updated OAuth client secret.\n */\n client_secret?: string | null;\n}\n\n/**\n * Substitute the secret on any host the session's Environment network policy\n * permits egress to. The Environment's network policy is the only boundary on\n * where the secret can reach.\n */\nexport interface BetaManagedAgentsUnrestrictedCredentialNetworkingParams {\n type: 'unrestricted';\n}\n\n/**\n * The secret is substituted on any host the session's Environment network policy\n * permits egress to.\n */\nexport interface BetaManagedAgentsUnrestrictedCredentialNetworkingResponse {\n type: 'unrestricted';\n}\n\nexport interface CredentialCreateParams {\n /**\n * Body param: Authentication details for creating a credential.\n */\n auth:\n | BetaManagedAgentsMCPOAuthCreateParams\n | BetaManagedAgentsStaticBearerCreateParams\n | BetaManagedAgentsEnvironmentVariableCreateParams;\n\n /**\n * Body param: Human-readable name for the credential. Up to 255 characters.\n */\n display_name?: string | null;\n\n /**\n * Body param: Arbitrary key-value metadata to attach to the credential. Maximum 16\n * pairs, keys up to 64 chars, values up to 512 chars.\n */\n metadata?: { [key: string]: string };\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface CredentialRetrieveParams {\n /**\n * Path param: Path parameter vault_id\n */\n vault_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface CredentialUpdateParams {\n /**\n * Path param: Path parameter vault_id\n */\n vault_id: string;\n\n /**\n * Body param: Updated authentication details for a credential.\n */\n auth?:\n | BetaManagedAgentsMCPOAuthUpdateParams\n | BetaManagedAgentsStaticBearerUpdateParams\n | BetaManagedAgentsEnvironmentVariableUpdateParams;\n\n /**\n * Body param: Updated human-readable name for the credential. 1-255 characters.\n */\n display_name?: string | null;\n\n /**\n * Body param: Metadata patch. Set a key to a string to upsert it, or to null to\n * delete it. Omitted keys are preserved.\n */\n metadata?: { [key: string]: string | null } | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface CredentialListParams extends PageCursorParams {\n /**\n * Query param: Whether to include archived credentials in the results.\n */\n include_archived?: boolean;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface CredentialDeleteParams {\n /**\n * Path param: Path parameter vault_id\n */\n vault_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface CredentialArchiveParams {\n /**\n * Path param: Path parameter vault_id\n */\n vault_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface CredentialMCPOAuthValidateParams {\n /**\n * Path param: Path parameter vault_id\n */\n vault_id: string;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Credentials {\n export {\n type BetaManagedAgentsCredential as BetaManagedAgentsCredential,\n type BetaManagedAgentsCredentialNetworkingParams as BetaManagedAgentsCredentialNetworkingParams,\n type BetaManagedAgentsCredentialValidation as BetaManagedAgentsCredentialValidation,\n type BetaManagedAgentsCredentialValidationStatus as BetaManagedAgentsCredentialValidationStatus,\n type BetaManagedAgentsDeletedCredential as BetaManagedAgentsDeletedCredential,\n type BetaManagedAgentsEnvironmentVariableAuthResponse as BetaManagedAgentsEnvironmentVariableAuthResponse,\n type BetaManagedAgentsEnvironmentVariableCreateParams as BetaManagedAgentsEnvironmentVariableCreateParams,\n type BetaManagedAgentsEnvironmentVariableUpdateParams as BetaManagedAgentsEnvironmentVariableUpdateParams,\n type BetaManagedAgentsLimitedCredentialNetworkingParams as BetaManagedAgentsLimitedCredentialNetworkingParams,\n type BetaManagedAgentsLimitedCredentialNetworkingResponse as BetaManagedAgentsLimitedCredentialNetworkingResponse,\n type BetaManagedAgentsMCPOAuthAuthResponse as BetaManagedAgentsMCPOAuthAuthResponse,\n type BetaManagedAgentsMCPOAuthCreateParams as BetaManagedAgentsMCPOAuthCreateParams,\n type BetaManagedAgentsMCPOAuthRefreshParams as BetaManagedAgentsMCPOAuthRefreshParams,\n type BetaManagedAgentsMCPOAuthRefreshResponse as BetaManagedAgentsMCPOAuthRefreshResponse,\n type BetaManagedAgentsMCPOAuthRefreshUpdateParams as BetaManagedAgentsMCPOAuthRefreshUpdateParams,\n type BetaManagedAgentsMCPOAuthUpdateParams as BetaManagedAgentsMCPOAuthUpdateParams,\n type BetaManagedAgentsMCPProbe as BetaManagedAgentsMCPProbe,\n type BetaManagedAgentsRefreshHTTPResponse as BetaManagedAgentsRefreshHTTPResponse,\n type BetaManagedAgentsRefreshObject as BetaManagedAgentsRefreshObject,\n type BetaManagedAgentsStaticBearerAuthResponse as BetaManagedAgentsStaticBearerAuthResponse,\n type BetaManagedAgentsStaticBearerCreateParams as BetaManagedAgentsStaticBearerCreateParams,\n type BetaManagedAgentsStaticBearerUpdateParams as BetaManagedAgentsStaticBearerUpdateParams,\n type BetaManagedAgentsTokenEndpointAuthBasicParam as BetaManagedAgentsTokenEndpointAuthBasicParam,\n type BetaManagedAgentsTokenEndpointAuthBasicResponse as BetaManagedAgentsTokenEndpointAuthBasicResponse,\n type BetaManagedAgentsTokenEndpointAuthBasicUpdateParam as BetaManagedAgentsTokenEndpointAuthBasicUpdateParam,\n type BetaManagedAgentsTokenEndpointAuthNoneParam as BetaManagedAgentsTokenEndpointAuthNoneParam,\n type BetaManagedAgentsTokenEndpointAuthNoneResponse as BetaManagedAgentsTokenEndpointAuthNoneResponse,\n type BetaManagedAgentsTokenEndpointAuthPostParam as BetaManagedAgentsTokenEndpointAuthPostParam,\n type BetaManagedAgentsTokenEndpointAuthPostResponse as BetaManagedAgentsTokenEndpointAuthPostResponse,\n type BetaManagedAgentsTokenEndpointAuthPostUpdateParam as BetaManagedAgentsTokenEndpointAuthPostUpdateParam,\n type BetaManagedAgentsUnrestrictedCredentialNetworkingParams as BetaManagedAgentsUnrestrictedCredentialNetworkingParams,\n type BetaManagedAgentsUnrestrictedCredentialNetworkingResponse as BetaManagedAgentsUnrestrictedCredentialNetworkingResponse,\n type BetaManagedAgentsCredentialsPageCursor as BetaManagedAgentsCredentialsPageCursor,\n type CredentialCreateParams as CredentialCreateParams,\n type CredentialRetrieveParams as CredentialRetrieveParams,\n type CredentialUpdateParams as CredentialUpdateParams,\n type CredentialListParams as CredentialListParams,\n type CredentialDeleteParams as CredentialDeleteParams,\n type CredentialArchiveParams as CredentialArchiveParams,\n type CredentialMCPOAuthValidateParams as CredentialMCPOAuthValidateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../../core/resource';\nimport * as BetaAPI from '../beta';\nimport * as CredentialsAPI from './credentials';\nimport {\n BetaManagedAgentsCredential,\n BetaManagedAgentsCredentialNetworkingParams,\n BetaManagedAgentsCredentialValidation,\n BetaManagedAgentsCredentialValidationStatus,\n BetaManagedAgentsCredentialsPageCursor,\n BetaManagedAgentsDeletedCredential,\n BetaManagedAgentsEnvironmentVariableAuthResponse,\n BetaManagedAgentsEnvironmentVariableCreateParams,\n BetaManagedAgentsEnvironmentVariableUpdateParams,\n BetaManagedAgentsLimitedCredentialNetworkingParams,\n BetaManagedAgentsLimitedCredentialNetworkingResponse,\n BetaManagedAgentsMCPOAuthAuthResponse,\n BetaManagedAgentsMCPOAuthCreateParams,\n BetaManagedAgentsMCPOAuthRefreshParams,\n BetaManagedAgentsMCPOAuthRefreshResponse,\n BetaManagedAgentsMCPOAuthRefreshUpdateParams,\n BetaManagedAgentsMCPOAuthUpdateParams,\n BetaManagedAgentsMCPProbe,\n BetaManagedAgentsRefreshHTTPResponse,\n BetaManagedAgentsRefreshObject,\n BetaManagedAgentsStaticBearerAuthResponse,\n BetaManagedAgentsStaticBearerCreateParams,\n BetaManagedAgentsStaticBearerUpdateParams,\n BetaManagedAgentsTokenEndpointAuthBasicParam,\n BetaManagedAgentsTokenEndpointAuthBasicResponse,\n BetaManagedAgentsTokenEndpointAuthBasicUpdateParam,\n BetaManagedAgentsTokenEndpointAuthNoneParam,\n BetaManagedAgentsTokenEndpointAuthNoneResponse,\n BetaManagedAgentsTokenEndpointAuthPostParam,\n BetaManagedAgentsTokenEndpointAuthPostResponse,\n BetaManagedAgentsTokenEndpointAuthPostUpdateParam,\n BetaManagedAgentsUnrestrictedCredentialNetworkingParams,\n BetaManagedAgentsUnrestrictedCredentialNetworkingResponse,\n CredentialArchiveParams,\n CredentialCreateParams,\n CredentialDeleteParams,\n CredentialListParams,\n CredentialMCPOAuthValidateParams,\n CredentialRetrieveParams,\n CredentialUpdateParams,\n Credentials,\n} from './credentials';\nimport { APIPromise } from '../../../core/api-promise';\nimport { PageCursor, type PageCursorParams, PagePromise } from '../../../core/pagination';\nimport { buildHeaders } from '../../../internal/headers';\nimport { RequestOptions } from '../../../internal/request-options';\nimport { path } from '../../../internal/utils/path';\n\nexport class Vaults extends APIResource {\n credentials: CredentialsAPI.Credentials = new CredentialsAPI.Credentials(this._client);\n\n /**\n * Create Vault\n *\n * @example\n * ```ts\n * const betaManagedAgentsVault =\n * await client.beta.vaults.create({\n * display_name: 'Example vault',\n * });\n * ```\n */\n create(params: VaultCreateParams, options?: RequestOptions): APIPromise<BetaManagedAgentsVault> {\n const { betas, ...body } = params;\n return this._client.post('/v1/vaults?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Get Vault\n *\n * @example\n * ```ts\n * const betaManagedAgentsVault =\n * await client.beta.vaults.retrieve(\n * 'vlt_011CZkZDLs7fYzm1hXNPeRjv',\n * );\n * ```\n */\n retrieve(\n vaultID: string,\n params: VaultRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsVault> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/vaults/${vaultID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Update Vault\n *\n * @example\n * ```ts\n * const betaManagedAgentsVault =\n * await client.beta.vaults.update(\n * 'vlt_011CZkZDLs7fYzm1hXNPeRjv',\n * );\n * ```\n */\n update(\n vaultID: string,\n params: VaultUpdateParams,\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsVault> {\n const { betas, ...body } = params;\n return this._client.post(path`/v1/vaults/${vaultID}?beta=true`, {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List Vaults\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const betaManagedAgentsVault of client.beta.vaults.list()) {\n * // ...\n * }\n * ```\n */\n list(\n params: VaultListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<BetaManagedAgentsVaultsPageCursor, BetaManagedAgentsVault> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/vaults?beta=true', PageCursor<BetaManagedAgentsVault>, {\n query,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Delete Vault\n *\n * @example\n * ```ts\n * const betaManagedAgentsDeletedVault =\n * await client.beta.vaults.delete(\n * 'vlt_011CZkZDLs7fYzm1hXNPeRjv',\n * );\n * ```\n */\n delete(\n vaultID: string,\n params: VaultDeleteParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsDeletedVault> {\n const { betas } = params ?? {};\n return this._client.delete(path`/v1/vaults/${vaultID}?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n\n /**\n * Archive Vault\n *\n * @example\n * ```ts\n * const betaManagedAgentsVault =\n * await client.beta.vaults.archive(\n * 'vlt_011CZkZDLs7fYzm1hXNPeRjv',\n * );\n * ```\n */\n archive(\n vaultID: string,\n params: VaultArchiveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<BetaManagedAgentsVault> {\n const { betas } = params ?? {};\n return this._client.post(path`/v1/vaults/${vaultID}/archive?beta=true`, {\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'managed-agents-2026-04-01'].toString() },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type BetaManagedAgentsVaultsPageCursor = PageCursor<BetaManagedAgentsVault>;\n\n/**\n * Confirmation of a deleted vault.\n */\nexport interface BetaManagedAgentsDeletedVault {\n /**\n * Unique identifier of the deleted vault.\n */\n id: string;\n\n type: 'vault_deleted';\n}\n\n/**\n * A vault that stores credentials for use by agents during sessions.\n */\nexport interface BetaManagedAgentsVault {\n /**\n * Unique identifier for the vault.\n */\n id: string;\n\n /**\n * A timestamp in RFC 3339 format\n */\n archived_at: string | null;\n\n /**\n * A timestamp in RFC 3339 format\n */\n created_at: string;\n\n /**\n * Human-readable name for the vault.\n */\n display_name: string;\n\n /**\n * Arbitrary key-value metadata attached to the vault.\n */\n metadata: { [key: string]: string };\n\n type: 'vault';\n\n /**\n * A timestamp in RFC 3339 format\n */\n updated_at: string;\n}\n\nexport interface VaultCreateParams {\n /**\n * Body param: Human-readable name for the vault. 1-255 characters.\n */\n display_name: string;\n\n /**\n * Body param: Arbitrary key-value metadata to attach to the vault. Maximum 16\n * pairs, keys up to 64 chars, values up to 512 chars.\n */\n metadata?: { [key: string]: string };\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface VaultRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface VaultUpdateParams {\n /**\n * Body param: Updated human-readable name for the vault. 1-255 characters.\n */\n display_name?: string | null;\n\n /**\n * Body param: Metadata patch. Set a key to a string to upsert it, or to null to\n * delete it. Omitted keys are preserved.\n */\n metadata?: { [key: string]: string | null } | null;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface VaultListParams extends PageCursorParams {\n /**\n * Query param: Whether to include archived vaults in the results.\n */\n include_archived?: boolean;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface VaultDeleteParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface VaultArchiveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nVaults.Credentials = Credentials;\n\nexport declare namespace Vaults {\n export {\n type BetaManagedAgentsDeletedVault as BetaManagedAgentsDeletedVault,\n type BetaManagedAgentsVault as BetaManagedAgentsVault,\n type BetaManagedAgentsVaultsPageCursor as BetaManagedAgentsVaultsPageCursor,\n type VaultCreateParams as VaultCreateParams,\n type VaultRetrieveParams as VaultRetrieveParams,\n type VaultUpdateParams as VaultUpdateParams,\n type VaultListParams as VaultListParams,\n type VaultDeleteParams as VaultDeleteParams,\n type VaultArchiveParams as VaultArchiveParams,\n };\n\n export {\n Credentials as Credentials,\n type BetaManagedAgentsCredential as BetaManagedAgentsCredential,\n type BetaManagedAgentsCredentialNetworkingParams as BetaManagedAgentsCredentialNetworkingParams,\n type BetaManagedAgentsCredentialValidation as BetaManagedAgentsCredentialValidation,\n type BetaManagedAgentsCredentialValidationStatus as BetaManagedAgentsCredentialValidationStatus,\n type BetaManagedAgentsDeletedCredential as BetaManagedAgentsDeletedCredential,\n type BetaManagedAgentsEnvironmentVariableAuthResponse as BetaManagedAgentsEnvironmentVariableAuthResponse,\n type BetaManagedAgentsEnvironmentVariableCreateParams as BetaManagedAgentsEnvironmentVariableCreateParams,\n type BetaManagedAgentsEnvironmentVariableUpdateParams as BetaManagedAgentsEnvironmentVariableUpdateParams,\n type BetaManagedAgentsLimitedCredentialNetworkingParams as BetaManagedAgentsLimitedCredentialNetworkingParams,\n type BetaManagedAgentsLimitedCredentialNetworkingResponse as BetaManagedAgentsLimitedCredentialNetworkingResponse,\n type BetaManagedAgentsMCPOAuthAuthResponse as BetaManagedAgentsMCPOAuthAuthResponse,\n type BetaManagedAgentsMCPOAuthCreateParams as BetaManagedAgentsMCPOAuthCreateParams,\n type BetaManagedAgentsMCPOAuthRefreshParams as BetaManagedAgentsMCPOAuthRefreshParams,\n type BetaManagedAgentsMCPOAuthRefreshResponse as BetaManagedAgentsMCPOAuthRefreshResponse,\n type BetaManagedAgentsMCPOAuthRefreshUpdateParams as BetaManagedAgentsMCPOAuthRefreshUpdateParams,\n type BetaManagedAgentsMCPOAuthUpdateParams as BetaManagedAgentsMCPOAuthUpdateParams,\n type BetaManagedAgentsMCPProbe as BetaManagedAgentsMCPProbe,\n type BetaManagedAgentsRefreshHTTPResponse as BetaManagedAgentsRefreshHTTPResponse,\n type BetaManagedAgentsRefreshObject as BetaManagedAgentsRefreshObject,\n type BetaManagedAgentsStaticBearerAuthResponse as BetaManagedAgentsStaticBearerAuthResponse,\n type BetaManagedAgentsStaticBearerCreateParams as BetaManagedAgentsStaticBearerCreateParams,\n type BetaManagedAgentsStaticBearerUpdateParams as BetaManagedAgentsStaticBearerUpdateParams,\n type BetaManagedAgentsTokenEndpointAuthBasicParam as BetaManagedAgentsTokenEndpointAuthBasicParam,\n type BetaManagedAgentsTokenEndpointAuthBasicResponse as BetaManagedAgentsTokenEndpointAuthBasicResponse,\n type BetaManagedAgentsTokenEndpointAuthBasicUpdateParam as BetaManagedAgentsTokenEndpointAuthBasicUpdateParam,\n type BetaManagedAgentsTokenEndpointAuthNoneParam as BetaManagedAgentsTokenEndpointAuthNoneParam,\n type BetaManagedAgentsTokenEndpointAuthNoneResponse as BetaManagedAgentsTokenEndpointAuthNoneResponse,\n type BetaManagedAgentsTokenEndpointAuthPostParam as BetaManagedAgentsTokenEndpointAuthPostParam,\n type BetaManagedAgentsTokenEndpointAuthPostResponse as BetaManagedAgentsTokenEndpointAuthPostResponse,\n type BetaManagedAgentsTokenEndpointAuthPostUpdateParam as BetaManagedAgentsTokenEndpointAuthPostUpdateParam,\n type BetaManagedAgentsUnrestrictedCredentialNetworkingParams as BetaManagedAgentsUnrestrictedCredentialNetworkingParams,\n type BetaManagedAgentsUnrestrictedCredentialNetworkingResponse as BetaManagedAgentsUnrestrictedCredentialNetworkingResponse,\n type BetaManagedAgentsCredentialsPageCursor as BetaManagedAgentsCredentialsPageCursor,\n type CredentialCreateParams as CredentialCreateParams,\n type CredentialRetrieveParams as CredentialRetrieveParams,\n type CredentialUpdateParams as CredentialUpdateParams,\n type CredentialListParams as CredentialListParams,\n type CredentialDeleteParams as CredentialDeleteParams,\n type CredentialArchiveParams as CredentialArchiveParams,\n type CredentialMCPOAuthValidateParams as CredentialMCPOAuthValidateParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport * as DeploymentRunsAPI from './deployment-runs';\nimport {\n BetaManagedAgentsAgentArchivedRunError,\n BetaManagedAgentsDeploymentRun,\n BetaManagedAgentsDeploymentRunsPageCursor,\n BetaManagedAgentsEnvironmentArchivedRunError,\n BetaManagedAgentsEnvironmentNotFoundRunError,\n BetaManagedAgentsFileNotFoundRunError,\n BetaManagedAgentsMCPEgressBlockedRunError,\n BetaManagedAgentsManualTriggerContext,\n BetaManagedAgentsMemoryStoreArchivedRunError,\n BetaManagedAgentsOrganizationDisabledRunError,\n BetaManagedAgentsScheduleTriggerContext,\n BetaManagedAgentsSelfHostedResourcesUnsupportedRunError,\n BetaManagedAgentsSessionCreationRejectedRunError,\n BetaManagedAgentsSessionRateLimitedRunError,\n BetaManagedAgentsSessionResourceNotFoundRunError,\n BetaManagedAgentsSkillNotFoundRunError,\n BetaManagedAgentsTriggerContext,\n BetaManagedAgentsTriggerType,\n BetaManagedAgentsUnknownRunError,\n BetaManagedAgentsVaultArchivedRunError,\n BetaManagedAgentsVaultNotFoundRunError,\n BetaManagedAgentsWorkspaceArchivedRunError,\n DeploymentRunListParams,\n DeploymentRunRetrieveParams,\n DeploymentRuns,\n} from './deployment-runs';\nimport * as DeploymentsAPI from './deployments';\nimport {\n BetaManagedAgentsAgentArchivedDeploymentPausedReasonError,\n BetaManagedAgentsCronSchedule,\n BetaManagedAgentsCronScheduleParams,\n BetaManagedAgentsDeployment,\n BetaManagedAgentsDeploymentInitialEvent,\n BetaManagedAgentsDeploymentInitialEventParams,\n BetaManagedAgentsDeploymentPausedReason,\n BetaManagedAgentsDeploymentPausedReasonError,\n BetaManagedAgentsDeploymentStatus,\n BetaManagedAgentsDeploymentSystemMessageEvent,\n BetaManagedAgentsDeploymentUserDefineOutcomeEvent,\n BetaManagedAgentsDeploymentUserMessageEvent,\n BetaManagedAgentsDeploymentsPageCursor,\n BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError,\n BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError,\n BetaManagedAgentsErrorDeploymentPausedReason,\n BetaManagedAgentsFileNotFoundDeploymentPausedReasonError,\n BetaManagedAgentsFileResourceConfig,\n BetaManagedAgentsGitHubRepositoryResourceConfig,\n BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError,\n BetaManagedAgentsManualDeploymentPausedReason,\n BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError,\n BetaManagedAgentsMemoryStoreResourceConfig,\n BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError,\n BetaManagedAgentsSchedule,\n BetaManagedAgentsScheduleParams,\n BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError,\n BetaManagedAgentsSessionResourceConfig,\n BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError,\n BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError,\n BetaManagedAgentsUnknownDeploymentPausedReasonError,\n BetaManagedAgentsVaultArchivedDeploymentPausedReasonError,\n BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError,\n BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError,\n DeploymentArchiveParams,\n DeploymentCreateParams,\n DeploymentListParams,\n DeploymentPauseParams,\n DeploymentRetrieveParams,\n DeploymentRunParams,\n DeploymentUnpauseParams,\n DeploymentUpdateParams,\n Deployments,\n} from './deployments';\nimport * as FilesAPI from './files';\nimport {\n BetaFileScope,\n DeletedFile,\n FileDeleteParams,\n FileDownloadParams,\n FileListParams,\n FileMetadata,\n FileMetadataPage,\n FileRetrieveMetadataParams,\n FileUploadParams,\n Files,\n} from './files';\nimport * as ModelsAPI from './models';\nimport {\n BetaCapabilitySupport,\n BetaContextManagementCapability,\n BetaEffortCapability,\n BetaModelCapabilities,\n BetaModelInfo,\n BetaModelInfosPage,\n BetaThinkingCapability,\n BetaThinkingTypes,\n ModelListParams,\n ModelRetrieveParams,\n Models,\n} from './models';\nimport * as UserProfilesAPI from './user-profiles';\nimport {\n BetaUserProfile,\n BetaUserProfileEnrollmentURL,\n BetaUserProfileTrustGrant,\n BetaUserProfilesPageCursor,\n UserProfileCreateEnrollmentURLParams,\n UserProfileCreateParams,\n UserProfileListParams,\n UserProfileRetrieveParams,\n UserProfileUpdateParams,\n UserProfiles,\n} from './user-profiles';\nimport * as WebhooksAPI from './webhooks';\nimport {\n BetaWebhookEvent,\n BetaWebhookEventData,\n BetaWebhookSessionArchivedEventData,\n BetaWebhookSessionCreatedEventData,\n BetaWebhookSessionDeletedEventData,\n BetaWebhookSessionIdledEventData,\n BetaWebhookSessionOutcomeEvaluationEndedEventData,\n BetaWebhookSessionPendingEventData,\n BetaWebhookSessionRequiresActionEventData,\n BetaWebhookSessionRunningEventData,\n BetaWebhookSessionStatusIdledEventData,\n BetaWebhookSessionStatusRescheduledEventData,\n BetaWebhookSessionStatusRunStartedEventData,\n BetaWebhookSessionStatusTerminatedEventData,\n BetaWebhookSessionThreadCreatedEventData,\n BetaWebhookSessionThreadIdledEventData,\n BetaWebhookSessionThreadTerminatedEventData,\n BetaWebhookSessionUpdatedEventData,\n BetaWebhookVaultArchivedEventData,\n BetaWebhookVaultCreatedEventData,\n BetaWebhookVaultCredentialArchivedEventData,\n BetaWebhookVaultCredentialCreatedEventData,\n BetaWebhookVaultCredentialDeletedEventData,\n BetaWebhookVaultCredentialRefreshFailedEventData,\n BetaWebhookVaultDeletedEventData,\n UnwrapWebhookEvent,\n Webhooks,\n} from './webhooks';\nimport * as AgentsAPI from './agents/agents';\nimport {\n AgentArchiveParams,\n AgentCreateParams,\n AgentListParams,\n AgentRetrieveParams,\n AgentUpdateParams,\n Agents,\n BetaManagedAgentsAgent,\n BetaManagedAgentsAgentReference,\n BetaManagedAgentsAgentToolConfig,\n BetaManagedAgentsAgentToolConfigParams,\n BetaManagedAgentsAgentToolset20260401,\n BetaManagedAgentsAgentToolset20260401BashInput,\n BetaManagedAgentsAgentToolset20260401EditInput,\n BetaManagedAgentsAgentToolset20260401GlobInput,\n BetaManagedAgentsAgentToolset20260401GrepInput,\n BetaManagedAgentsAgentToolset20260401Params,\n BetaManagedAgentsAgentToolset20260401ReadInput,\n BetaManagedAgentsAgentToolset20260401WriteInput,\n BetaManagedAgentsAgentToolsetDefaultConfig,\n BetaManagedAgentsAgentToolsetDefaultConfigParams,\n BetaManagedAgentsAgentsPageCursor,\n BetaManagedAgentsAlwaysAllowPolicy,\n BetaManagedAgentsAlwaysAskPolicy,\n BetaManagedAgentsAnthropicSkill,\n BetaManagedAgentsAnthropicSkillParams,\n BetaManagedAgentsCustomSkill,\n BetaManagedAgentsCustomSkillParams,\n BetaManagedAgentsCustomTool,\n BetaManagedAgentsCustomToolInputSchema,\n BetaManagedAgentsCustomToolParams,\n BetaManagedAgentsMCPServerURLDefinition,\n BetaManagedAgentsMCPToolConfig,\n BetaManagedAgentsMCPToolConfigParams,\n BetaManagedAgentsMCPToolset,\n BetaManagedAgentsMCPToolsetDefaultConfig,\n BetaManagedAgentsMCPToolsetDefaultConfigParams,\n BetaManagedAgentsMCPToolsetParams,\n BetaManagedAgentsModel,\n BetaManagedAgentsModelConfig,\n BetaManagedAgentsModelConfigParams,\n BetaManagedAgentsMultiagentCoordinator,\n BetaManagedAgentsMultiagentCoordinatorParams,\n BetaManagedAgentsMultiagentSelfParams,\n BetaManagedAgentsSessionThreadAgent,\n BetaManagedAgentsSkillParams,\n BetaManagedAgentsURLMCPServerParams,\n} from './agents/agents';\nimport * as EnvironmentsAPI from './environments/environments';\nimport {\n BetaCloudConfig,\n BetaCloudConfigParams,\n BetaEnvironment,\n BetaEnvironmentDeleteResponse,\n BetaEnvironmentsPageCursor,\n BetaLimitedNetwork,\n BetaLimitedNetworkParams,\n BetaPackages,\n BetaPackagesParams,\n BetaSelfHostedConfig,\n BetaSelfHostedConfigParams,\n BetaUnrestrictedNetwork,\n EnvironmentArchiveParams,\n EnvironmentCreateParams,\n EnvironmentDeleteParams,\n EnvironmentListParams,\n EnvironmentRetrieveParams,\n EnvironmentUpdateParams,\n Environments,\n} from './environments/environments';\nimport * as MemoryStoresAPI from './memory-stores/memory-stores';\nimport {\n BetaManagedAgentsDeletedMemoryStore,\n BetaManagedAgentsMemoryStore,\n BetaManagedAgentsMemoryStoresPageCursor,\n MemoryStoreArchiveParams,\n MemoryStoreCreateParams,\n MemoryStoreDeleteParams,\n MemoryStoreListParams,\n MemoryStoreRetrieveParams,\n MemoryStoreUpdateParams,\n MemoryStores,\n} from './memory-stores/memory-stores';\nimport * as MessagesAPI from './messages/messages';\nimport {\n BetaAdvisorMessageIterationUsage,\n BetaAdvisorRedactedResultBlock,\n BetaAdvisorRedactedResultBlockParam,\n BetaAdvisorResultBlock,\n BetaAdvisorResultBlockParam,\n BetaAdvisorTool20260301,\n BetaAdvisorToolResultBlock,\n BetaAdvisorToolResultBlockParam,\n BetaAdvisorToolResultError,\n BetaAdvisorToolResultErrorParam,\n BetaAllThinkingTurns,\n BetaBase64ImageSource,\n BetaBase64PDFBlock,\n BetaBase64PDFSource,\n BetaBashCodeExecutionOutputBlock,\n BetaBashCodeExecutionOutputBlockParam,\n BetaBashCodeExecutionResultBlock,\n BetaBashCodeExecutionResultBlockParam,\n BetaBashCodeExecutionToolResultBlock,\n BetaBashCodeExecutionToolResultBlockParam,\n BetaBashCodeExecutionToolResultError,\n BetaBashCodeExecutionToolResultErrorParam,\n BetaCacheControlEphemeral,\n BetaCacheCreation,\n BetaCacheMissMessagesChanged,\n BetaCacheMissModelChanged,\n BetaCacheMissPreviousMessageNotFound,\n BetaCacheMissSystemChanged,\n BetaCacheMissToolsChanged,\n BetaCacheMissUnavailable,\n BetaCitationCharLocation,\n BetaCitationCharLocationParam,\n BetaCitationConfig,\n BetaCitationContentBlockLocation,\n BetaCitationContentBlockLocationParam,\n BetaCitationPageLocation,\n BetaCitationPageLocationParam,\n BetaCitationSearchResultLocation,\n BetaCitationSearchResultLocationParam,\n BetaCitationWebSearchResultLocationParam,\n BetaCitationsConfigParam,\n BetaCitationsDelta,\n BetaCitationsWebSearchResultLocation,\n BetaClearThinking20251015Edit,\n BetaClearThinking20251015EditResponse,\n BetaClearToolUses20250919Edit,\n BetaClearToolUses20250919EditResponse,\n BetaCodeExecutionOutputBlock,\n BetaCodeExecutionOutputBlockParam,\n BetaCodeExecutionResultBlock,\n BetaCodeExecutionResultBlockParam,\n BetaCodeExecutionTool20250522,\n BetaCodeExecutionTool20250825,\n BetaCodeExecutionTool20260120,\n BetaCodeExecutionTool20260521,\n BetaCodeExecutionToolResultBlock,\n BetaCodeExecutionToolResultBlockContent,\n BetaCodeExecutionToolResultBlockParam,\n BetaCodeExecutionToolResultBlockParamContent,\n BetaCodeExecutionToolResultError,\n BetaCodeExecutionToolResultErrorCode,\n BetaCodeExecutionToolResultErrorParam,\n BetaCompact20260112Edit,\n BetaCompactionBlock,\n BetaCompactionBlockParam,\n BetaCompactionContentBlockDelta,\n BetaCompactionIterationUsage,\n BetaContainer,\n BetaContainerParams,\n BetaContainerUploadBlock,\n BetaContainerUploadBlockParam,\n BetaContentBlock,\n BetaContentBlockParam,\n BetaContentBlockSource,\n BetaContentBlockSourceContent,\n BetaContextManagementConfig,\n BetaContextManagementResponse,\n BetaCountTokensContextManagementResponse,\n BetaDiagnostics,\n BetaDiagnosticsParam,\n BetaDirectCaller,\n BetaDocumentBlock,\n BetaEncryptedCodeExecutionResultBlock,\n BetaEncryptedCodeExecutionResultBlockParam,\n BetaFallbackBlock,\n BetaFallbackBlockParam,\n BetaFallbackInfo,\n BetaFallbackInfoParam,\n BetaFallbackMessageIterationUsage,\n BetaFallbackParam,\n BetaFallbackRefusalTrigger,\n BetaFileDocumentSource,\n BetaFileImageSource,\n BetaImageBlockParam,\n BetaInputJSONDelta,\n BetaJSONOutputFormat,\n BetaInputTokensClearAtLeast,\n BetaInputTokensTrigger,\n BetaMCPToolResultBlock,\n BetaMCPToolUseBlock,\n BetaMCPToolUseBlockParam,\n BetaMCPToolset,\n BetaMemoryTool20250818,\n BetaMemoryTool20250818Command,\n BetaMemoryTool20250818CreateCommand,\n BetaMemoryTool20250818DeleteCommand,\n BetaMemoryTool20250818InsertCommand,\n BetaMemoryTool20250818RenameCommand,\n BetaMemoryTool20250818StrReplaceCommand,\n BetaMemoryTool20250818ViewCommand,\n BetaMessage,\n BetaMessageDeltaUsage,\n BetaMessageIterationUsage,\n BetaMessageParam,\n BetaMessageTokensCount,\n BetaMetadata,\n BetaMidConversationSystemBlockParam,\n BetaOutputConfig,\n BetaOutputTokensDetails,\n BetaPlainTextSource,\n BetaRawContentBlockDelta,\n BetaRawContentBlockDeltaEvent,\n BetaRawContentBlockStartEvent,\n BetaRawContentBlockStopEvent,\n BetaRawMessageDeltaEvent,\n BetaRawMessageStartEvent,\n BetaRawMessageStopEvent,\n BetaRawMessageStreamEvent,\n BetaRedactedThinkingBlock,\n BetaRedactedThinkingBlockParam,\n BetaRefusalStopDetails,\n BetaRequestDocumentBlock,\n BetaRequestMCPServerToolConfiguration,\n BetaRequestMCPServerURLDefinition,\n BetaRequestMCPToolResultBlockParam,\n BetaSearchResultBlockParam,\n BetaServerToolCaller,\n BetaServerToolCaller20260120,\n BetaServerToolUsage,\n BetaServerToolUseBlock,\n BetaServerToolUseBlockParam,\n BetaSignatureDelta,\n BetaSkill,\n BetaSkillParams,\n BetaStopReason,\n BetaTextBlock,\n BetaTextBlockParam,\n BetaTextCitation,\n BetaTextCitationParam,\n BetaTextDelta,\n BetaTextEditorCodeExecutionCreateResultBlock,\n BetaTextEditorCodeExecutionCreateResultBlockParam,\n BetaTextEditorCodeExecutionStrReplaceResultBlock,\n BetaTextEditorCodeExecutionStrReplaceResultBlockParam,\n BetaTextEditorCodeExecutionToolResultBlock,\n BetaTextEditorCodeExecutionToolResultBlockParam,\n BetaTextEditorCodeExecutionToolResultError,\n BetaTextEditorCodeExecutionToolResultErrorParam,\n BetaTextEditorCodeExecutionViewResultBlock,\n BetaTextEditorCodeExecutionViewResultBlockParam,\n BetaThinkingBlock,\n BetaThinkingBlockParam,\n BetaThinkingConfigAdaptive,\n BetaThinkingConfigDisabled,\n BetaThinkingConfigEnabled,\n BetaThinkingConfigParam,\n BetaThinkingDelta,\n BetaThinkingTurns,\n BetaTokenTaskBudget,\n BetaTool,\n BetaToolBash20241022,\n BetaToolBash20250124,\n BetaToolChoice,\n BetaToolChoiceAny,\n BetaToolChoiceAuto,\n BetaToolChoiceNone,\n BetaToolChoiceTool,\n BetaToolComputerUse20241022,\n BetaToolComputerUse20250124,\n BetaToolComputerUse20251124,\n BetaToolReferenceBlock,\n BetaToolReferenceBlockParam,\n BetaToolResultBlockParam,\n BetaToolTextEditor20241022,\n BetaToolTextEditor20250124,\n BetaToolTextEditor20250429,\n BetaToolTextEditor20250728,\n BetaToolUnion,\n BetaToolUseBlock,\n BetaToolUseBlockParam,\n BetaToolUsesKeep,\n BetaToolUsesTrigger,\n BetaURLImageSource,\n BetaURLPDFSource,\n BetaUsage,\n BetaUserLocation,\n BetaWebFetchBlock,\n BetaWebFetchBlockParam,\n BetaWebFetchTool20250910,\n BetaWebFetchTool20260209,\n BetaWebFetchTool20260309,\n BetaWebFetchToolResultBlock,\n BetaWebFetchToolResultBlockParam,\n BetaWebFetchToolResultErrorBlock,\n BetaWebFetchToolResultErrorBlockParam,\n BetaWebFetchToolResultErrorCode,\n BetaWebSearchResultBlock,\n BetaWebSearchResultBlockParam,\n BetaWebSearchTool20250305,\n BetaWebSearchTool20260209,\n BetaWebSearchToolRequestError,\n BetaWebSearchToolResultBlock,\n BetaWebSearchToolResultBlockContent,\n BetaWebSearchToolResultBlockParam,\n BetaWebSearchToolResultBlockParamContent,\n BetaWebSearchToolResultError,\n BetaWebSearchToolResultErrorCode,\n MessageCountTokensParams,\n MessageCreateParams,\n MessageCreateParamsNonStreaming,\n MessageCreateParamsStreaming,\n Messages,\n BetaMCPToolConfig,\n BetaMCPToolDefaultConfig,\n} from './messages/messages';\nimport * as SessionsAPI from './sessions/sessions';\nimport {\n BetaManagedAgentsAgentParams,\n BetaManagedAgentsBranchCheckout,\n BetaManagedAgentsCacheCreationUsage,\n BetaManagedAgentsCommitCheckout,\n BetaManagedAgentsDeletedSession,\n BetaManagedAgentsFileResourceParams,\n BetaManagedAgentsGitHubRepositoryResourceParams,\n BetaManagedAgentsMemoryStoreResourceParam,\n BetaManagedAgentsMultiagent,\n BetaManagedAgentsMultiagentParams,\n BetaManagedAgentsMultiagentRosterEntryParams,\n BetaManagedAgentsOutcomeEvaluationResource,\n BetaManagedAgentsSession,\n BetaManagedAgentsSessionAgent,\n BetaManagedAgentsSessionAgentUpdate,\n BetaManagedAgentsSessionMultiagentCoordinator,\n BetaManagedAgentsSessionStats,\n BetaManagedAgentsSessionUpdatedEvent,\n BetaManagedAgentsSessionUsage,\n BetaManagedAgentsSessionsPageCursor,\n BetaManagedAgentsSystemContentBlock,\n BetaManagedAgentsSystemMessageEvent,\n BetaManagedAgentsUserToolResultEvent,\n SessionArchiveParams,\n SessionCreateParams,\n SessionDeleteParams,\n SessionListParams,\n SessionRetrieveParams,\n SessionUpdateParams,\n Sessions,\n} from './sessions/sessions';\nimport * as SkillsAPI from './skills/skills';\nimport {\n SkillCreateParams,\n SkillCreateResponse,\n SkillDeleteParams,\n SkillDeleteResponse,\n SkillListParams,\n SkillListResponse,\n SkillListResponsesPageCursor,\n SkillRetrieveParams,\n SkillRetrieveResponse,\n Skills,\n} from './skills/skills';\nimport * as VaultsAPI from './vaults/vaults';\nimport {\n BetaManagedAgentsDeletedVault,\n BetaManagedAgentsVault,\n BetaManagedAgentsVaultsPageCursor,\n VaultArchiveParams,\n VaultCreateParams,\n VaultDeleteParams,\n VaultListParams,\n VaultRetrieveParams,\n VaultUpdateParams,\n Vaults,\n} from './vaults/vaults';\n\nexport class Beta extends APIResource {\n models: ModelsAPI.Models = new ModelsAPI.Models(this._client);\n messages: MessagesAPI.Messages = new MessagesAPI.Messages(this._client);\n agents: AgentsAPI.Agents = new AgentsAPI.Agents(this._client);\n environments: EnvironmentsAPI.Environments = new EnvironmentsAPI.Environments(this._client);\n sessions: SessionsAPI.Sessions = new SessionsAPI.Sessions(this._client);\n deployments: DeploymentsAPI.Deployments = new DeploymentsAPI.Deployments(this._client);\n deploymentRuns: DeploymentRunsAPI.DeploymentRuns = new DeploymentRunsAPI.DeploymentRuns(this._client);\n vaults: VaultsAPI.Vaults = new VaultsAPI.Vaults(this._client);\n memoryStores: MemoryStoresAPI.MemoryStores = new MemoryStoresAPI.MemoryStores(this._client);\n files: FilesAPI.Files = new FilesAPI.Files(this._client);\n skills: SkillsAPI.Skills = new SkillsAPI.Skills(this._client);\n webhooks: WebhooksAPI.Webhooks = new WebhooksAPI.Webhooks(this._client);\n userProfiles: UserProfilesAPI.UserProfiles = new UserProfilesAPI.UserProfiles(this._client);\n}\n\nexport type AnthropicBeta =\n | (string & {})\n | 'message-batches-2024-09-24'\n | 'prompt-caching-2024-07-31'\n | 'computer-use-2024-10-22'\n | 'computer-use-2025-01-24'\n | 'pdfs-2024-09-25'\n | 'token-counting-2024-11-01'\n | 'token-efficient-tools-2025-02-19'\n | 'output-128k-2025-02-19'\n | 'files-api-2025-04-14'\n | 'mcp-client-2025-04-04'\n | 'mcp-client-2025-11-20'\n | 'dev-full-thinking-2025-05-14'\n | 'interleaved-thinking-2025-05-14'\n | 'code-execution-2025-05-22'\n | 'extended-cache-ttl-2025-04-11'\n | 'context-1m-2025-08-07'\n | 'context-management-2025-06-27'\n | 'model-context-window-exceeded-2025-08-26'\n | 'skills-2025-10-02'\n | 'fast-mode-2026-02-01'\n | 'output-300k-2026-03-24'\n | 'user-profiles-2026-03-24'\n | 'advisor-tool-2026-03-01'\n | 'managed-agents-2026-04-01'\n | 'cache-diagnosis-2026-04-07'\n | 'thinking-token-count-2026-05-13'\n | 'server-side-fallback-2026-06-01'\n | 'fallback-credit-2026-06-01';\n\nexport interface BetaAPIError {\n message: string;\n\n type: 'api_error';\n}\n\nexport interface BetaAuthenticationError {\n message: string;\n\n type: 'authentication_error';\n}\n\nexport interface BetaBillingError {\n message: string;\n\n type: 'billing_error';\n}\n\nexport type BetaError =\n | BetaInvalidRequestError\n | BetaAuthenticationError\n | BetaBillingError\n | BetaPermissionError\n | BetaNotFoundError\n | BetaRateLimitError\n | BetaGatewayTimeoutError\n | BetaAPIError\n | BetaOverloadedError;\n\nexport interface BetaErrorResponse {\n error: BetaError;\n\n request_id: string | null;\n\n type: 'error';\n}\n\nexport interface BetaGatewayTimeoutError {\n message: string;\n\n type: 'timeout_error';\n}\n\nexport interface BetaInvalidRequestError {\n message: string;\n\n type: 'invalid_request_error';\n}\n\nexport interface BetaNotFoundError {\n message: string;\n\n type: 'not_found_error';\n}\n\nexport interface BetaOverloadedError {\n message: string;\n\n type: 'overloaded_error';\n}\n\nexport interface BetaPermissionError {\n message: string;\n\n type: 'permission_error';\n}\n\nexport interface BetaRateLimitError {\n message: string;\n\n type: 'rate_limit_error';\n}\n\nBeta.Models = Models;\nBeta.Messages = Messages;\nBeta.Agents = Agents;\nBeta.Environments = Environments;\nBeta.Sessions = Sessions;\nBeta.Deployments = Deployments;\nBeta.DeploymentRuns = DeploymentRuns;\nBeta.Vaults = Vaults;\nBeta.MemoryStores = MemoryStores;\nBeta.Files = Files;\nBeta.Skills = Skills;\nBeta.Webhooks = Webhooks;\nBeta.UserProfiles = UserProfiles;\n\nexport declare namespace Beta {\n export {\n type AnthropicBeta as AnthropicBeta,\n type BetaAPIError as BetaAPIError,\n type BetaAuthenticationError as BetaAuthenticationError,\n type BetaBillingError as BetaBillingError,\n type BetaError as BetaError,\n type BetaErrorResponse as BetaErrorResponse,\n type BetaGatewayTimeoutError as BetaGatewayTimeoutError,\n type BetaInvalidRequestError as BetaInvalidRequestError,\n type BetaNotFoundError as BetaNotFoundError,\n type BetaOverloadedError as BetaOverloadedError,\n type BetaPermissionError as BetaPermissionError,\n type BetaRateLimitError as BetaRateLimitError,\n };\n\n export {\n Models as Models,\n type BetaCapabilitySupport as BetaCapabilitySupport,\n type BetaContextManagementCapability as BetaContextManagementCapability,\n type BetaEffortCapability as BetaEffortCapability,\n type BetaModelCapabilities as BetaModelCapabilities,\n type BetaModelInfo as BetaModelInfo,\n type BetaThinkingCapability as BetaThinkingCapability,\n type BetaThinkingTypes as BetaThinkingTypes,\n type BetaModelInfosPage as BetaModelInfosPage,\n type ModelRetrieveParams as ModelRetrieveParams,\n type ModelListParams as ModelListParams,\n };\n\n export {\n Messages as Messages,\n type BetaAdvisorMessageIterationUsage as BetaAdvisorMessageIterationUsage,\n type BetaAdvisorRedactedResultBlock as BetaAdvisorRedactedResultBlock,\n type BetaAdvisorRedactedResultBlockParam as BetaAdvisorRedactedResultBlockParam,\n type BetaAdvisorResultBlock as BetaAdvisorResultBlock,\n type BetaAdvisorResultBlockParam as BetaAdvisorResultBlockParam,\n type BetaAdvisorTool20260301 as BetaAdvisorTool20260301,\n type BetaAdvisorToolResultBlock as BetaAdvisorToolResultBlock,\n type BetaAdvisorToolResultBlockParam as BetaAdvisorToolResultBlockParam,\n type BetaAdvisorToolResultError as BetaAdvisorToolResultError,\n type BetaAdvisorToolResultErrorParam as BetaAdvisorToolResultErrorParam,\n type BetaAllThinkingTurns as BetaAllThinkingTurns,\n type BetaBase64ImageSource as BetaBase64ImageSource,\n type BetaBase64PDFSource as BetaBase64PDFSource,\n type BetaBashCodeExecutionOutputBlock as BetaBashCodeExecutionOutputBlock,\n type BetaBashCodeExecutionOutputBlockParam as BetaBashCodeExecutionOutputBlockParam,\n type BetaBashCodeExecutionResultBlock as BetaBashCodeExecutionResultBlock,\n type BetaBashCodeExecutionResultBlockParam as BetaBashCodeExecutionResultBlockParam,\n type BetaBashCodeExecutionToolResultBlock as BetaBashCodeExecutionToolResultBlock,\n type BetaBashCodeExecutionToolResultBlockParam as BetaBashCodeExecutionToolResultBlockParam,\n type BetaBashCodeExecutionToolResultError as BetaBashCodeExecutionToolResultError,\n type BetaBashCodeExecutionToolResultErrorParam as BetaBashCodeExecutionToolResultErrorParam,\n type BetaCacheControlEphemeral as BetaCacheControlEphemeral,\n type BetaCacheCreation as BetaCacheCreation,\n type BetaCacheMissMessagesChanged as BetaCacheMissMessagesChanged,\n type BetaCacheMissModelChanged as BetaCacheMissModelChanged,\n type BetaCacheMissPreviousMessageNotFound as BetaCacheMissPreviousMessageNotFound,\n type BetaCacheMissSystemChanged as BetaCacheMissSystemChanged,\n type BetaCacheMissToolsChanged as BetaCacheMissToolsChanged,\n type BetaCacheMissUnavailable as BetaCacheMissUnavailable,\n type BetaCitationCharLocation as BetaCitationCharLocation,\n type BetaCitationCharLocationParam as BetaCitationCharLocationParam,\n type BetaCitationConfig as BetaCitationConfig,\n type BetaCitationContentBlockLocation as BetaCitationContentBlockLocation,\n type BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam,\n type BetaCitationPageLocation as BetaCitationPageLocation,\n type BetaCitationPageLocationParam as BetaCitationPageLocationParam,\n type BetaCitationSearchResultLocation as BetaCitationSearchResultLocation,\n type BetaCitationSearchResultLocationParam as BetaCitationSearchResultLocationParam,\n type BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam,\n type BetaCitationsConfigParam as BetaCitationsConfigParam,\n type BetaCitationsDelta as BetaCitationsDelta,\n type BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation,\n type BetaClearThinking20251015Edit as BetaClearThinking20251015Edit,\n type BetaClearThinking20251015EditResponse as BetaClearThinking20251015EditResponse,\n type BetaClearToolUses20250919Edit as BetaClearToolUses20250919Edit,\n type BetaClearToolUses20250919EditResponse as BetaClearToolUses20250919EditResponse,\n type BetaCodeExecutionOutputBlock as BetaCodeExecutionOutputBlock,\n type BetaCodeExecutionOutputBlockParam as BetaCodeExecutionOutputBlockParam,\n type BetaCodeExecutionResultBlock as BetaCodeExecutionResultBlock,\n type BetaCodeExecutionResultBlockParam as BetaCodeExecutionResultBlockParam,\n type BetaCodeExecutionTool20250522 as BetaCodeExecutionTool20250522,\n type BetaCodeExecutionTool20250825 as BetaCodeExecutionTool20250825,\n type BetaCodeExecutionTool20260120 as BetaCodeExecutionTool20260120,\n type BetaCodeExecutionTool20260521 as BetaCodeExecutionTool20260521,\n type BetaCodeExecutionToolResultBlock as BetaCodeExecutionToolResultBlock,\n type BetaCodeExecutionToolResultBlockContent as BetaCodeExecutionToolResultBlockContent,\n type BetaCodeExecutionToolResultBlockParam as BetaCodeExecutionToolResultBlockParam,\n type BetaCodeExecutionToolResultBlockParamContent as BetaCodeExecutionToolResultBlockParamContent,\n type BetaCodeExecutionToolResultError as BetaCodeExecutionToolResultError,\n type BetaCodeExecutionToolResultErrorCode as BetaCodeExecutionToolResultErrorCode,\n type BetaCodeExecutionToolResultErrorParam as BetaCodeExecutionToolResultErrorParam,\n type BetaCompact20260112Edit as BetaCompact20260112Edit,\n type BetaCompactionBlock as BetaCompactionBlock,\n type BetaCompactionBlockParam as BetaCompactionBlockParam,\n type BetaCompactionContentBlockDelta as BetaCompactionContentBlockDelta,\n type BetaCompactionIterationUsage as BetaCompactionIterationUsage,\n type BetaContainer as BetaContainer,\n type BetaContainerParams as BetaContainerParams,\n type BetaContainerUploadBlock as BetaContainerUploadBlock,\n type BetaContainerUploadBlockParam as BetaContainerUploadBlockParam,\n type BetaContentBlock as BetaContentBlock,\n type BetaContentBlockParam as BetaContentBlockParam,\n type BetaContentBlockSource as BetaContentBlockSource,\n type BetaContentBlockSourceContent as BetaContentBlockSourceContent,\n type BetaContextManagementConfig as BetaContextManagementConfig,\n type BetaContextManagementResponse as BetaContextManagementResponse,\n type BetaCountTokensContextManagementResponse as BetaCountTokensContextManagementResponse,\n type BetaDiagnostics as BetaDiagnostics,\n type BetaDiagnosticsParam as BetaDiagnosticsParam,\n type BetaDirectCaller as BetaDirectCaller,\n type BetaDocumentBlock as BetaDocumentBlock,\n type BetaEncryptedCodeExecutionResultBlock as BetaEncryptedCodeExecutionResultBlock,\n type BetaEncryptedCodeExecutionResultBlockParam as BetaEncryptedCodeExecutionResultBlockParam,\n type BetaFallbackBlock as BetaFallbackBlock,\n type BetaFallbackBlockParam as BetaFallbackBlockParam,\n type BetaFallbackInfo as BetaFallbackInfo,\n type BetaFallbackInfoParam as BetaFallbackInfoParam,\n type BetaFallbackMessageIterationUsage as BetaFallbackMessageIterationUsage,\n type BetaFallbackParam as BetaFallbackParam,\n type BetaFallbackRefusalTrigger as BetaFallbackRefusalTrigger,\n type BetaFileDocumentSource as BetaFileDocumentSource,\n type BetaFileImageSource as BetaFileImageSource,\n type BetaImageBlockParam as BetaImageBlockParam,\n type BetaInputJSONDelta as BetaInputJSONDelta,\n type BetaJSONOutputFormat as BetaJSONOutputFormat,\n type BetaInputTokensClearAtLeast as BetaInputTokensClearAtLeast,\n type BetaInputTokensTrigger as BetaInputTokensTrigger,\n type BetaMCPToolConfig as BetaMCPToolConfig,\n type BetaMCPToolDefaultConfig as BetaMCPToolDefaultConfig,\n type BetaMCPToolResultBlock as BetaMCPToolResultBlock,\n type BetaMCPToolUseBlock as BetaMCPToolUseBlock,\n type BetaMCPToolUseBlockParam as BetaMCPToolUseBlockParam,\n type BetaMCPToolset as BetaMCPToolset,\n type BetaMemoryTool20250818 as BetaMemoryTool20250818,\n type BetaMemoryTool20250818Command as BetaMemoryTool20250818Command,\n type BetaMemoryTool20250818CreateCommand as BetaMemoryTool20250818CreateCommand,\n type BetaMemoryTool20250818DeleteCommand as BetaMemoryTool20250818DeleteCommand,\n type BetaMemoryTool20250818InsertCommand as BetaMemoryTool20250818InsertCommand,\n type BetaMemoryTool20250818RenameCommand as BetaMemoryTool20250818RenameCommand,\n type BetaMemoryTool20250818StrReplaceCommand as BetaMemoryTool20250818StrReplaceCommand,\n type BetaMemoryTool20250818ViewCommand as BetaMemoryTool20250818ViewCommand,\n type BetaMessage as BetaMessage,\n type BetaMessageDeltaUsage as BetaMessageDeltaUsage,\n type BetaMessageIterationUsage as BetaMessageIterationUsage,\n type BetaMessageParam as BetaMessageParam,\n type BetaMessageTokensCount as BetaMessageTokensCount,\n type BetaMetadata as BetaMetadata,\n type BetaMidConversationSystemBlockParam as BetaMidConversationSystemBlockParam,\n type BetaOutputConfig as BetaOutputConfig,\n type BetaOutputTokensDetails as BetaOutputTokensDetails,\n type BetaPlainTextSource as BetaPlainTextSource,\n type BetaRawContentBlockDelta as BetaRawContentBlockDelta,\n type BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent,\n type BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent,\n type BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent,\n type BetaRawMessageDeltaEvent as BetaRawMessageDeltaEvent,\n type BetaRawMessageStartEvent as BetaRawMessageStartEvent,\n type BetaRawMessageStopEvent as BetaRawMessageStopEvent,\n type BetaRawMessageStreamEvent as BetaRawMessageStreamEvent,\n type BetaRedactedThinkingBlock as BetaRedactedThinkingBlock,\n type BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam,\n type BetaRefusalStopDetails as BetaRefusalStopDetails,\n type BetaRequestDocumentBlock as BetaRequestDocumentBlock,\n type BetaRequestMCPServerToolConfiguration as BetaRequestMCPServerToolConfiguration,\n type BetaRequestMCPServerURLDefinition as BetaRequestMCPServerURLDefinition,\n type BetaRequestMCPToolResultBlockParam as BetaRequestMCPToolResultBlockParam,\n type BetaSearchResultBlockParam as BetaSearchResultBlockParam,\n type BetaServerToolCaller as BetaServerToolCaller,\n type BetaServerToolCaller20260120 as BetaServerToolCaller20260120,\n type BetaServerToolUsage as BetaServerToolUsage,\n type BetaServerToolUseBlock as BetaServerToolUseBlock,\n type BetaServerToolUseBlockParam as BetaServerToolUseBlockParam,\n type BetaSignatureDelta as BetaSignatureDelta,\n type BetaSkill as BetaSkill,\n type BetaSkillParams as BetaSkillParams,\n type BetaStopReason as BetaStopReason,\n type BetaTextBlock as BetaTextBlock,\n type BetaTextBlockParam as BetaTextBlockParam,\n type BetaTextCitation as BetaTextCitation,\n type BetaTextCitationParam as BetaTextCitationParam,\n type BetaTextDelta as BetaTextDelta,\n type BetaTextEditorCodeExecutionCreateResultBlock as BetaTextEditorCodeExecutionCreateResultBlock,\n type BetaTextEditorCodeExecutionCreateResultBlockParam as BetaTextEditorCodeExecutionCreateResultBlockParam,\n type BetaTextEditorCodeExecutionStrReplaceResultBlock as BetaTextEditorCodeExecutionStrReplaceResultBlock,\n type BetaTextEditorCodeExecutionStrReplaceResultBlockParam as BetaTextEditorCodeExecutionStrReplaceResultBlockParam,\n type BetaTextEditorCodeExecutionToolResultBlock as BetaTextEditorCodeExecutionToolResultBlock,\n type BetaTextEditorCodeExecutionToolResultBlockParam as BetaTextEditorCodeExecutionToolResultBlockParam,\n type BetaTextEditorCodeExecutionToolResultError as BetaTextEditorCodeExecutionToolResultError,\n type BetaTextEditorCodeExecutionToolResultErrorParam as BetaTextEditorCodeExecutionToolResultErrorParam,\n type BetaTextEditorCodeExecutionViewResultBlock as BetaTextEditorCodeExecutionViewResultBlock,\n type BetaTextEditorCodeExecutionViewResultBlockParam as BetaTextEditorCodeExecutionViewResultBlockParam,\n type BetaThinkingBlock as BetaThinkingBlock,\n type BetaThinkingBlockParam as BetaThinkingBlockParam,\n type BetaThinkingConfigAdaptive as BetaThinkingConfigAdaptive,\n type BetaThinkingConfigDisabled as BetaThinkingConfigDisabled,\n type BetaThinkingConfigEnabled as BetaThinkingConfigEnabled,\n type BetaThinkingConfigParam as BetaThinkingConfigParam,\n type BetaThinkingDelta as BetaThinkingDelta,\n type BetaThinkingTurns as BetaThinkingTurns,\n type BetaTokenTaskBudget as BetaTokenTaskBudget,\n type BetaTool as BetaTool,\n type BetaToolBash20241022 as BetaToolBash20241022,\n type BetaToolBash20250124 as BetaToolBash20250124,\n type BetaToolChoice as BetaToolChoice,\n type BetaToolChoiceAny as BetaToolChoiceAny,\n type BetaToolChoiceAuto as BetaToolChoiceAuto,\n type BetaToolChoiceNone as BetaToolChoiceNone,\n type BetaToolChoiceTool as BetaToolChoiceTool,\n type BetaToolComputerUse20241022 as BetaToolComputerUse20241022,\n type BetaToolComputerUse20250124 as BetaToolComputerUse20250124,\n type BetaToolComputerUse20251124 as BetaToolComputerUse20251124,\n type BetaToolReferenceBlock as BetaToolReferenceBlock,\n type BetaToolReferenceBlockParam as BetaToolReferenceBlockParam,\n type BetaToolResultBlockParam as BetaToolResultBlockParam,\n type BetaToolTextEditor20241022 as BetaToolTextEditor20241022,\n type BetaToolTextEditor20250124 as BetaToolTextEditor20250124,\n type BetaToolTextEditor20250429 as BetaToolTextEditor20250429,\n type BetaToolTextEditor20250728 as BetaToolTextEditor20250728,\n type BetaToolUnion as BetaToolUnion,\n type BetaToolUseBlock as BetaToolUseBlock,\n type BetaToolUseBlockParam as BetaToolUseBlockParam,\n type BetaToolUsesKeep as BetaToolUsesKeep,\n type BetaToolUsesTrigger as BetaToolUsesTrigger,\n type BetaURLImageSource as BetaURLImageSource,\n type BetaURLPDFSource as BetaURLPDFSource,\n type BetaUsage as BetaUsage,\n type BetaUserLocation as BetaUserLocation,\n type BetaWebFetchBlock as BetaWebFetchBlock,\n type BetaWebFetchBlockParam as BetaWebFetchBlockParam,\n type BetaWebFetchTool20250910 as BetaWebFetchTool20250910,\n type BetaWebFetchTool20260209 as BetaWebFetchTool20260209,\n type BetaWebFetchTool20260309 as BetaWebFetchTool20260309,\n type BetaWebFetchToolResultBlock as BetaWebFetchToolResultBlock,\n type BetaWebFetchToolResultBlockParam as BetaWebFetchToolResultBlockParam,\n type BetaWebFetchToolResultErrorBlock as BetaWebFetchToolResultErrorBlock,\n type BetaWebFetchToolResultErrorBlockParam as BetaWebFetchToolResultErrorBlockParam,\n type BetaWebFetchToolResultErrorCode as BetaWebFetchToolResultErrorCode,\n type BetaWebSearchResultBlock as BetaWebSearchResultBlock,\n type BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam,\n type BetaWebSearchTool20250305 as BetaWebSearchTool20250305,\n type BetaWebSearchTool20260209 as BetaWebSearchTool20260209,\n type BetaWebSearchToolRequestError as BetaWebSearchToolRequestError,\n type BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock,\n type BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent,\n type BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam,\n type BetaWebSearchToolResultBlockParamContent as BetaWebSearchToolResultBlockParamContent,\n type BetaWebSearchToolResultError as BetaWebSearchToolResultError,\n type BetaWebSearchToolResultErrorCode as BetaWebSearchToolResultErrorCode,\n type BetaBase64PDFBlock as BetaBase64PDFBlock,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export {\n Agents as Agents,\n type BetaManagedAgentsAgent as BetaManagedAgentsAgent,\n type BetaManagedAgentsAgentReference as BetaManagedAgentsAgentReference,\n type BetaManagedAgentsAgentToolConfig as BetaManagedAgentsAgentToolConfig,\n type BetaManagedAgentsAgentToolConfigParams as BetaManagedAgentsAgentToolConfigParams,\n type BetaManagedAgentsAgentToolsetDefaultConfig as BetaManagedAgentsAgentToolsetDefaultConfig,\n type BetaManagedAgentsAgentToolsetDefaultConfigParams as BetaManagedAgentsAgentToolsetDefaultConfigParams,\n type BetaManagedAgentsAgentToolset20260401 as BetaManagedAgentsAgentToolset20260401,\n type BetaManagedAgentsAgentToolset20260401BashInput as BetaManagedAgentsAgentToolset20260401BashInput,\n type BetaManagedAgentsAgentToolset20260401EditInput as BetaManagedAgentsAgentToolset20260401EditInput,\n type BetaManagedAgentsAgentToolset20260401GlobInput as BetaManagedAgentsAgentToolset20260401GlobInput,\n type BetaManagedAgentsAgentToolset20260401GrepInput as BetaManagedAgentsAgentToolset20260401GrepInput,\n type BetaManagedAgentsAgentToolset20260401Params as BetaManagedAgentsAgentToolset20260401Params,\n type BetaManagedAgentsAgentToolset20260401ReadInput as BetaManagedAgentsAgentToolset20260401ReadInput,\n type BetaManagedAgentsAgentToolset20260401WriteInput as BetaManagedAgentsAgentToolset20260401WriteInput,\n type BetaManagedAgentsAlwaysAllowPolicy as BetaManagedAgentsAlwaysAllowPolicy,\n type BetaManagedAgentsAlwaysAskPolicy as BetaManagedAgentsAlwaysAskPolicy,\n type BetaManagedAgentsAnthropicSkill as BetaManagedAgentsAnthropicSkill,\n type BetaManagedAgentsAnthropicSkillParams as BetaManagedAgentsAnthropicSkillParams,\n type BetaManagedAgentsCustomSkill as BetaManagedAgentsCustomSkill,\n type BetaManagedAgentsCustomSkillParams as BetaManagedAgentsCustomSkillParams,\n type BetaManagedAgentsCustomTool as BetaManagedAgentsCustomTool,\n type BetaManagedAgentsCustomToolInputSchema as BetaManagedAgentsCustomToolInputSchema,\n type BetaManagedAgentsCustomToolParams as BetaManagedAgentsCustomToolParams,\n type BetaManagedAgentsMCPServerURLDefinition as BetaManagedAgentsMCPServerURLDefinition,\n type BetaManagedAgentsMCPToolConfig as BetaManagedAgentsMCPToolConfig,\n type BetaManagedAgentsMCPToolConfigParams as BetaManagedAgentsMCPToolConfigParams,\n type BetaManagedAgentsMCPToolset as BetaManagedAgentsMCPToolset,\n type BetaManagedAgentsMCPToolsetDefaultConfig as BetaManagedAgentsMCPToolsetDefaultConfig,\n type BetaManagedAgentsMCPToolsetDefaultConfigParams as BetaManagedAgentsMCPToolsetDefaultConfigParams,\n type BetaManagedAgentsMCPToolsetParams as BetaManagedAgentsMCPToolsetParams,\n type BetaManagedAgentsModel as BetaManagedAgentsModel,\n type BetaManagedAgentsModelConfig as BetaManagedAgentsModelConfig,\n type BetaManagedAgentsModelConfigParams as BetaManagedAgentsModelConfigParams,\n type BetaManagedAgentsMultiagentCoordinator as BetaManagedAgentsMultiagentCoordinator,\n type BetaManagedAgentsMultiagentCoordinatorParams as BetaManagedAgentsMultiagentCoordinatorParams,\n type BetaManagedAgentsMultiagentSelfParams as BetaManagedAgentsMultiagentSelfParams,\n type BetaManagedAgentsSessionThreadAgent as BetaManagedAgentsSessionThreadAgent,\n type BetaManagedAgentsSkillParams as BetaManagedAgentsSkillParams,\n type BetaManagedAgentsURLMCPServerParams as BetaManagedAgentsURLMCPServerParams,\n type BetaManagedAgentsAgentsPageCursor as BetaManagedAgentsAgentsPageCursor,\n type AgentCreateParams as AgentCreateParams,\n type AgentRetrieveParams as AgentRetrieveParams,\n type AgentUpdateParams as AgentUpdateParams,\n type AgentListParams as AgentListParams,\n type AgentArchiveParams as AgentArchiveParams,\n };\n\n export {\n Environments as Environments,\n type BetaCloudConfig as BetaCloudConfig,\n type BetaCloudConfigParams as BetaCloudConfigParams,\n type BetaEnvironment as BetaEnvironment,\n type BetaEnvironmentDeleteResponse as BetaEnvironmentDeleteResponse,\n type BetaLimitedNetwork as BetaLimitedNetwork,\n type BetaLimitedNetworkParams as BetaLimitedNetworkParams,\n type BetaPackages as BetaPackages,\n type BetaPackagesParams as BetaPackagesParams,\n type BetaSelfHostedConfig as BetaSelfHostedConfig,\n type BetaSelfHostedConfigParams as BetaSelfHostedConfigParams,\n type BetaUnrestrictedNetwork as BetaUnrestrictedNetwork,\n type BetaEnvironmentsPageCursor as BetaEnvironmentsPageCursor,\n type EnvironmentCreateParams as EnvironmentCreateParams,\n type EnvironmentRetrieveParams as EnvironmentRetrieveParams,\n type EnvironmentUpdateParams as EnvironmentUpdateParams,\n type EnvironmentListParams as EnvironmentListParams,\n type EnvironmentDeleteParams as EnvironmentDeleteParams,\n type EnvironmentArchiveParams as EnvironmentArchiveParams,\n };\n\n export {\n Sessions as Sessions,\n type BetaManagedAgentsAgentParams as BetaManagedAgentsAgentParams,\n type BetaManagedAgentsBranchCheckout as BetaManagedAgentsBranchCheckout,\n type BetaManagedAgentsCacheCreationUsage as BetaManagedAgentsCacheCreationUsage,\n type BetaManagedAgentsCommitCheckout as BetaManagedAgentsCommitCheckout,\n type BetaManagedAgentsDeletedSession as BetaManagedAgentsDeletedSession,\n type BetaManagedAgentsFileResourceParams as BetaManagedAgentsFileResourceParams,\n type BetaManagedAgentsGitHubRepositoryResourceParams as BetaManagedAgentsGitHubRepositoryResourceParams,\n type BetaManagedAgentsMemoryStoreResourceParam as BetaManagedAgentsMemoryStoreResourceParam,\n type BetaManagedAgentsMultiagent as BetaManagedAgentsMultiagent,\n type BetaManagedAgentsMultiagentParams as BetaManagedAgentsMultiagentParams,\n type BetaManagedAgentsMultiagentRosterEntryParams as BetaManagedAgentsMultiagentRosterEntryParams,\n type BetaManagedAgentsOutcomeEvaluationResource as BetaManagedAgentsOutcomeEvaluationResource,\n type BetaManagedAgentsSession as BetaManagedAgentsSession,\n type BetaManagedAgentsSessionAgent as BetaManagedAgentsSessionAgent,\n type BetaManagedAgentsSessionAgentUpdate as BetaManagedAgentsSessionAgentUpdate,\n type BetaManagedAgentsSessionMultiagentCoordinator as BetaManagedAgentsSessionMultiagentCoordinator,\n type BetaManagedAgentsSessionStats as BetaManagedAgentsSessionStats,\n type BetaManagedAgentsSessionUpdatedEvent as BetaManagedAgentsSessionUpdatedEvent,\n type BetaManagedAgentsSessionUsage as BetaManagedAgentsSessionUsage,\n type BetaManagedAgentsSystemContentBlock as BetaManagedAgentsSystemContentBlock,\n type BetaManagedAgentsSystemMessageEvent as BetaManagedAgentsSystemMessageEvent,\n type BetaManagedAgentsUserToolResultEvent as BetaManagedAgentsUserToolResultEvent,\n type BetaManagedAgentsSessionsPageCursor as BetaManagedAgentsSessionsPageCursor,\n type SessionCreateParams as SessionCreateParams,\n type SessionRetrieveParams as SessionRetrieveParams,\n type SessionUpdateParams as SessionUpdateParams,\n type SessionListParams as SessionListParams,\n type SessionDeleteParams as SessionDeleteParams,\n type SessionArchiveParams as SessionArchiveParams,\n };\n\n export {\n Deployments as Deployments,\n type BetaManagedAgentsAgentArchivedDeploymentPausedReasonError as BetaManagedAgentsAgentArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsCronSchedule as BetaManagedAgentsCronSchedule,\n type BetaManagedAgentsCronScheduleParams as BetaManagedAgentsCronScheduleParams,\n type BetaManagedAgentsDeployment as BetaManagedAgentsDeployment,\n type BetaManagedAgentsDeploymentInitialEvent as BetaManagedAgentsDeploymentInitialEvent,\n type BetaManagedAgentsDeploymentInitialEventParams as BetaManagedAgentsDeploymentInitialEventParams,\n type BetaManagedAgentsDeploymentPausedReason as BetaManagedAgentsDeploymentPausedReason,\n type BetaManagedAgentsDeploymentPausedReasonError as BetaManagedAgentsDeploymentPausedReasonError,\n type BetaManagedAgentsDeploymentStatus as BetaManagedAgentsDeploymentStatus,\n type BetaManagedAgentsDeploymentSystemMessageEvent as BetaManagedAgentsDeploymentSystemMessageEvent,\n type BetaManagedAgentsDeploymentUserDefineOutcomeEvent as BetaManagedAgentsDeploymentUserDefineOutcomeEvent,\n type BetaManagedAgentsDeploymentUserMessageEvent as BetaManagedAgentsDeploymentUserMessageEvent,\n type BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError as BetaManagedAgentsEnvironmentArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError as BetaManagedAgentsEnvironmentNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsErrorDeploymentPausedReason as BetaManagedAgentsErrorDeploymentPausedReason,\n type BetaManagedAgentsFileNotFoundDeploymentPausedReasonError as BetaManagedAgentsFileNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsFileResourceConfig as BetaManagedAgentsFileResourceConfig,\n type BetaManagedAgentsGitHubRepositoryResourceConfig as BetaManagedAgentsGitHubRepositoryResourceConfig,\n type BetaManagedAgentsManualDeploymentPausedReason as BetaManagedAgentsManualDeploymentPausedReason,\n type BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError as BetaManagedAgentsMCPEgressBlockedDeploymentPausedReasonError,\n type BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError as BetaManagedAgentsMemoryStoreArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsMemoryStoreResourceConfig as BetaManagedAgentsMemoryStoreResourceConfig,\n type BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError as BetaManagedAgentsOrganizationDisabledDeploymentPausedReasonError,\n type BetaManagedAgentsSchedule as BetaManagedAgentsSchedule,\n type BetaManagedAgentsScheduleParams as BetaManagedAgentsScheduleParams,\n type BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError as BetaManagedAgentsSelfHostedResourcesUnsupportedDeploymentPausedReasonError,\n type BetaManagedAgentsSessionResourceConfig as BetaManagedAgentsSessionResourceConfig,\n type BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError as BetaManagedAgentsSessionResourceNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError as BetaManagedAgentsSkillNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsUnknownDeploymentPausedReasonError as BetaManagedAgentsUnknownDeploymentPausedReasonError,\n type BetaManagedAgentsVaultArchivedDeploymentPausedReasonError as BetaManagedAgentsVaultArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError as BetaManagedAgentsVaultNotFoundDeploymentPausedReasonError,\n type BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError as BetaManagedAgentsWorkspaceArchivedDeploymentPausedReasonError,\n type BetaManagedAgentsDeploymentsPageCursor as BetaManagedAgentsDeploymentsPageCursor,\n type DeploymentCreateParams as DeploymentCreateParams,\n type DeploymentRetrieveParams as DeploymentRetrieveParams,\n type DeploymentUpdateParams as DeploymentUpdateParams,\n type DeploymentListParams as DeploymentListParams,\n type DeploymentArchiveParams as DeploymentArchiveParams,\n type DeploymentPauseParams as DeploymentPauseParams,\n type DeploymentRunParams as DeploymentRunParams,\n type DeploymentUnpauseParams as DeploymentUnpauseParams,\n };\n\n export {\n DeploymentRuns as DeploymentRuns,\n type BetaManagedAgentsAgentArchivedRunError as BetaManagedAgentsAgentArchivedRunError,\n type BetaManagedAgentsDeploymentRun as BetaManagedAgentsDeploymentRun,\n type BetaManagedAgentsEnvironmentArchivedRunError as BetaManagedAgentsEnvironmentArchivedRunError,\n type BetaManagedAgentsEnvironmentNotFoundRunError as BetaManagedAgentsEnvironmentNotFoundRunError,\n type BetaManagedAgentsFileNotFoundRunError as BetaManagedAgentsFileNotFoundRunError,\n type BetaManagedAgentsManualTriggerContext as BetaManagedAgentsManualTriggerContext,\n type BetaManagedAgentsMCPEgressBlockedRunError as BetaManagedAgentsMCPEgressBlockedRunError,\n type BetaManagedAgentsMemoryStoreArchivedRunError as BetaManagedAgentsMemoryStoreArchivedRunError,\n type BetaManagedAgentsOrganizationDisabledRunError as BetaManagedAgentsOrganizationDisabledRunError,\n type BetaManagedAgentsScheduleTriggerContext as BetaManagedAgentsScheduleTriggerContext,\n type BetaManagedAgentsSelfHostedResourcesUnsupportedRunError as BetaManagedAgentsSelfHostedResourcesUnsupportedRunError,\n type BetaManagedAgentsSessionCreationRejectedRunError as BetaManagedAgentsSessionCreationRejectedRunError,\n type BetaManagedAgentsSessionRateLimitedRunError as BetaManagedAgentsSessionRateLimitedRunError,\n type BetaManagedAgentsSessionResourceNotFoundRunError as BetaManagedAgentsSessionResourceNotFoundRunError,\n type BetaManagedAgentsSkillNotFoundRunError as BetaManagedAgentsSkillNotFoundRunError,\n type BetaManagedAgentsTriggerContext as BetaManagedAgentsTriggerContext,\n type BetaManagedAgentsTriggerType as BetaManagedAgentsTriggerType,\n type BetaManagedAgentsUnknownRunError as BetaManagedAgentsUnknownRunError,\n type BetaManagedAgentsVaultArchivedRunError as BetaManagedAgentsVaultArchivedRunError,\n type BetaManagedAgentsVaultNotFoundRunError as BetaManagedAgentsVaultNotFoundRunError,\n type BetaManagedAgentsWorkspaceArchivedRunError as BetaManagedAgentsWorkspaceArchivedRunError,\n type BetaManagedAgentsDeploymentRunsPageCursor as BetaManagedAgentsDeploymentRunsPageCursor,\n type DeploymentRunRetrieveParams as DeploymentRunRetrieveParams,\n type DeploymentRunListParams as DeploymentRunListParams,\n };\n\n export {\n Vaults as Vaults,\n type BetaManagedAgentsDeletedVault as BetaManagedAgentsDeletedVault,\n type BetaManagedAgentsVault as BetaManagedAgentsVault,\n type BetaManagedAgentsVaultsPageCursor as BetaManagedAgentsVaultsPageCursor,\n type VaultCreateParams as VaultCreateParams,\n type VaultRetrieveParams as VaultRetrieveParams,\n type VaultUpdateParams as VaultUpdateParams,\n type VaultListParams as VaultListParams,\n type VaultDeleteParams as VaultDeleteParams,\n type VaultArchiveParams as VaultArchiveParams,\n };\n\n export {\n MemoryStores as MemoryStores,\n type BetaManagedAgentsDeletedMemoryStore as BetaManagedAgentsDeletedMemoryStore,\n type BetaManagedAgentsMemoryStore as BetaManagedAgentsMemoryStore,\n type BetaManagedAgentsMemoryStoresPageCursor as BetaManagedAgentsMemoryStoresPageCursor,\n type MemoryStoreCreateParams as MemoryStoreCreateParams,\n type MemoryStoreRetrieveParams as MemoryStoreRetrieveParams,\n type MemoryStoreUpdateParams as MemoryStoreUpdateParams,\n type MemoryStoreListParams as MemoryStoreListParams,\n type MemoryStoreDeleteParams as MemoryStoreDeleteParams,\n type MemoryStoreArchiveParams as MemoryStoreArchiveParams,\n };\n\n export {\n Files as Files,\n type BetaFileScope as BetaFileScope,\n type DeletedFile as DeletedFile,\n type FileMetadata as FileMetadata,\n type FileMetadataPage as FileMetadataPage,\n type FileListParams as FileListParams,\n type FileDeleteParams as FileDeleteParams,\n type FileDownloadParams as FileDownloadParams,\n type FileRetrieveMetadataParams as FileRetrieveMetadataParams,\n type FileUploadParams as FileUploadParams,\n };\n\n export {\n Skills as Skills,\n type SkillCreateResponse as SkillCreateResponse,\n type SkillRetrieveResponse as SkillRetrieveResponse,\n type SkillListResponse as SkillListResponse,\n type SkillDeleteResponse as SkillDeleteResponse,\n type SkillListResponsesPageCursor as SkillListResponsesPageCursor,\n type SkillCreateParams as SkillCreateParams,\n type SkillRetrieveParams as SkillRetrieveParams,\n type SkillListParams as SkillListParams,\n type SkillDeleteParams as SkillDeleteParams,\n };\n\n export {\n Webhooks as Webhooks,\n type BetaWebhookEvent as BetaWebhookEvent,\n type BetaWebhookEventData as BetaWebhookEventData,\n type BetaWebhookSessionArchivedEventData as BetaWebhookSessionArchivedEventData,\n type BetaWebhookSessionCreatedEventData as BetaWebhookSessionCreatedEventData,\n type BetaWebhookSessionDeletedEventData as BetaWebhookSessionDeletedEventData,\n type BetaWebhookSessionIdledEventData as BetaWebhookSessionIdledEventData,\n type BetaWebhookSessionOutcomeEvaluationEndedEventData as BetaWebhookSessionOutcomeEvaluationEndedEventData,\n type BetaWebhookSessionPendingEventData as BetaWebhookSessionPendingEventData,\n type BetaWebhookSessionRequiresActionEventData as BetaWebhookSessionRequiresActionEventData,\n type BetaWebhookSessionRunningEventData as BetaWebhookSessionRunningEventData,\n type BetaWebhookSessionStatusIdledEventData as BetaWebhookSessionStatusIdledEventData,\n type BetaWebhookSessionStatusRescheduledEventData as BetaWebhookSessionStatusRescheduledEventData,\n type BetaWebhookSessionStatusRunStartedEventData as BetaWebhookSessionStatusRunStartedEventData,\n type BetaWebhookSessionStatusTerminatedEventData as BetaWebhookSessionStatusTerminatedEventData,\n type BetaWebhookSessionThreadCreatedEventData as BetaWebhookSessionThreadCreatedEventData,\n type BetaWebhookSessionThreadIdledEventData as BetaWebhookSessionThreadIdledEventData,\n type BetaWebhookSessionThreadTerminatedEventData as BetaWebhookSessionThreadTerminatedEventData,\n type BetaWebhookSessionUpdatedEventData as BetaWebhookSessionUpdatedEventData,\n type BetaWebhookVaultArchivedEventData as BetaWebhookVaultArchivedEventData,\n type BetaWebhookVaultCreatedEventData as BetaWebhookVaultCreatedEventData,\n type BetaWebhookVaultCredentialArchivedEventData as BetaWebhookVaultCredentialArchivedEventData,\n type BetaWebhookVaultCredentialCreatedEventData as BetaWebhookVaultCredentialCreatedEventData,\n type BetaWebhookVaultCredentialDeletedEventData as BetaWebhookVaultCredentialDeletedEventData,\n type BetaWebhookVaultCredentialRefreshFailedEventData as BetaWebhookVaultCredentialRefreshFailedEventData,\n type BetaWebhookVaultDeletedEventData as BetaWebhookVaultDeletedEventData,\n type UnwrapWebhookEvent as UnwrapWebhookEvent,\n };\n\n export {\n UserProfiles as UserProfiles,\n type BetaUserProfile as BetaUserProfile,\n type BetaUserProfileEnrollmentURL as BetaUserProfileEnrollmentURL,\n type BetaUserProfileTrustGrant as BetaUserProfileTrustGrant,\n type BetaUserProfilesPageCursor as BetaUserProfilesPageCursor,\n type UserProfileCreateParams as UserProfileCreateParams,\n type UserProfileRetrieveParams as UserProfileRetrieveParams,\n type UserProfileUpdateParams as UserProfileUpdateParams,\n type UserProfileListParams as UserProfileListParams,\n type UserProfileCreateEnrollmentURLParams as UserProfileCreateEnrollmentURLParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../core/resource';\nimport * as CompletionsAPI from './completions';\nimport * as BetaAPI from './beta/beta';\nimport * as MessagesAPI from './messages/messages';\nimport { APIPromise } from '../core/api-promise';\nimport { Stream } from '../core/streaming';\nimport { buildHeaders } from '../internal/headers';\nimport { RequestOptions } from '../internal/request-options';\n\nexport class Completions extends APIResource {\n /**\n * [Legacy] Create a Text Completion.\n *\n * The Text Completions API is a legacy API. We recommend using the\n * [Messages API](https://docs.claude.com/en/api/messages) going forward.\n *\n * Future models and features will not be compatible with Text Completions. See our\n * [migration guide](https://docs.claude.com/en/api/migrating-from-text-completions-to-messages)\n * for guidance in migrating from Text Completions to Messages.\n *\n * @example\n * ```ts\n * const completion = await client.completions.create({\n * max_tokens_to_sample: 256,\n * model: 'claude-2.1',\n * prompt: '\\n\\nHuman: Hello, world!\\n\\nAssistant:',\n * });\n * ```\n */\n create(params: CompletionCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Completion>;\n create(params: CompletionCreateParamsStreaming, options?: RequestOptions): APIPromise<Stream<Completion>>;\n create(\n params: CompletionCreateParamsBase,\n options?: RequestOptions,\n ): APIPromise<Stream<Completion> | Completion>;\n create(\n params: CompletionCreateParams,\n options?: RequestOptions,\n ): APIPromise<Completion> | APIPromise<Stream<Completion>> {\n const { betas, ...body } = params;\n return this._client.post('/v1/complete', {\n body,\n timeout: (this._client as any)._options.timeout ?? 600000,\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n stream: params.stream ?? false,\n }) as APIPromise<Completion> | APIPromise<Stream<Completion>>;\n }\n}\n\nexport interface Completion {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * The resulting completion up to and excluding the stop sequences.\n */\n completion: string;\n\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * The reason that we stopped.\n *\n * This may be one the following values:\n *\n * - `\"stop_sequence\"`: we reached a stop sequence — either provided by you via the\n * `stop_sequences` parameter, or a stop sequence built into the model\n * - `\"max_tokens\"`: we exceeded `max_tokens_to_sample` or the model's maximum\n */\n stop_reason: string | null;\n\n /**\n * Object type.\n *\n * For Text Completions, this is always `\"completion\"`.\n */\n type: 'completion';\n}\n\nexport type CompletionCreateParams = CompletionCreateParamsNonStreaming | CompletionCreateParamsStreaming;\n\nexport interface CompletionCreateParamsBase {\n /**\n * Body param: The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n */\n max_tokens_to_sample: number;\n\n /**\n * Body param: The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: MessagesAPI.Model;\n\n /**\n * Body param: The prompt that you want Claude to complete.\n *\n * For proper response generation you will need to format your prompt using\n * alternating `\\n\\nHuman:` and `\\n\\nAssistant:` conversational turns. For example:\n *\n * ```\n * \"\\n\\nHuman: {userQuestion}\\n\\nAssistant:\"\n * ```\n *\n * See [prompt validation](https://docs.claude.com/en/api/prompt-validation) and\n * our guide to [prompt design](https://docs.claude.com/en/docs/intro-to-prompting)\n * for more details.\n */\n prompt: string;\n\n /**\n * Body param: An object describing metadata about the request.\n */\n metadata?: MessagesAPI.Metadata;\n\n /**\n * Body param: Sequences that will cause the model to stop generating.\n *\n * Our models stop on `\"\\n\\nHuman:\"`, and may include additional built-in stop\n * sequences in the future. By providing the stop_sequences parameter, you may\n * include additional strings that will cause the model to stop generating.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.claude.com/en/api/streaming) for details.\n */\n stream?: boolean;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not support\n * setting temperature. A value of 1.0 of will be accepted for backwards\n * compatibility, all other values will be rejected with a 400 error.\n */\n temperature?: number;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not accept\n * top_k; any value will be rejected with a 400 error.\n */\n top_k?: number;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not support\n * setting top_p. A value >= 0.99 will be accepted for backwards compatibility, all\n * other values will be rejected with a 400 error.\n */\n top_p?: number;\n\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport namespace CompletionCreateParams {\n /**\n * @deprecated use `Anthropic.Messages.Metadata` instead\n */\n export type Metadata = MessagesAPI.Metadata;\n\n export type CompletionCreateParamsNonStreaming = CompletionsAPI.CompletionCreateParamsNonStreaming;\n export type CompletionCreateParamsStreaming = CompletionsAPI.CompletionCreateParamsStreaming;\n}\n\nexport interface CompletionCreateParamsNonStreaming extends CompletionCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.claude.com/en/api/streaming) for details.\n */\n stream?: false;\n}\n\nexport interface CompletionCreateParamsStreaming extends CompletionCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.claude.com/en/api/streaming) for details.\n */\n stream: true;\n}\n\nexport declare namespace Completions {\n export {\n type Completion as Completion,\n type CompletionCreateParams as CompletionCreateParams,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n };\n}\n","import type { Logger } from '../client';\nimport { AnthropicError } from '../core/error';\nimport {\n ContentBlock,\n JSONOutputFormat,\n Message,\n OutputConfig,\n TextBlock,\n MessageCreateParams,\n} from '../resources/messages/messages';\n\n// vendored from typefest just to make things look a bit nicer on hover\ntype Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};\n\ntype AutoParseableOutputConfig = Omit<OutputConfig, 'format'> & {\n format?: JSONOutputFormat | AutoParseableOutputFormat<any> | null;\n};\n\nexport type ParseableMessageCreateParams = Simplify<\n Omit<MessageCreateParams, 'output_config'> & {\n output_config?: AutoParseableOutputConfig | null;\n }\n>;\n\nexport type ExtractParsedContentFromParams<Params extends ParseableMessageCreateParams> =\n Params['output_config'] extends { format: AutoParseableOutputFormat<infer P> } ? P : null;\n\nexport type AutoParseableOutputFormat<ParsedT> = JSONOutputFormat & {\n parse(content: string): ParsedT;\n};\n\nexport type ParsedMessage<ParsedT> = Message & {\n content: Array<ParsedContentBlock<ParsedT>>;\n parsed_output: ParsedT | null;\n};\n\nexport type ParsedContentBlock<ParsedT> =\n | (TextBlock & { parsed_output: ParsedT | null })\n | Exclude<ContentBlock, TextBlock>;\n\nfunction getOutputFormat(\n params: ParseableMessageCreateParams | null,\n): JSONOutputFormat | AutoParseableOutputFormat<any> | null | undefined {\n return params?.output_config?.format;\n}\n\nexport function maybeParseMessage<Params extends ParseableMessageCreateParams | null>(\n message: Message,\n params: Params,\n opts: { logger: Logger },\n): ParsedMessage<ExtractParsedContentFromParams<NonNullable<Params>>> {\n const outputFormat = getOutputFormat(params);\n if (!params || !('parse' in (outputFormat ?? {}))) {\n return {\n ...message,\n content: message.content.map((block) => {\n if (block.type === 'text') {\n const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {\n value: null,\n enumerable: false,\n }) as ParsedContentBlock<ExtractParsedContentFromParams<NonNullable<Params>>>;\n\n return parsedBlock;\n }\n return block;\n }),\n parsed_output: null,\n } as ParsedMessage<ExtractParsedContentFromParams<NonNullable<Params>>>;\n }\n\n return parseMessage(message, params, opts);\n}\n\nexport function parseMessage<Params extends ParseableMessageCreateParams>(\n message: Message,\n params: Params,\n opts: { logger: Logger },\n): ParsedMessage<ExtractParsedContentFromParams<Params>> {\n let firstParsedOutput: ReturnType<typeof parseOutputFormat<Params>> | null = null;\n\n const content: Array<ParsedContentBlock<ExtractParsedContentFromParams<Params>>> = message.content.map(\n (block) => {\n if (block.type === 'text') {\n const parsedOutput = parseOutputFormat(params, block.text);\n\n if (firstParsedOutput === null) {\n firstParsedOutput = parsedOutput;\n }\n\n const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {\n value: parsedOutput,\n enumerable: false,\n }) as ParsedContentBlock<ExtractParsedContentFromParams<Params>>;\n return parsedBlock;\n }\n return block;\n },\n );\n\n return {\n ...message,\n content,\n parsed_output: firstParsedOutput,\n } as ParsedMessage<ExtractParsedContentFromParams<Params>>;\n}\n\nfunction parseOutputFormat<Params extends ParseableMessageCreateParams>(\n params: Params,\n content: string,\n): ExtractParsedContentFromParams<Params> | null {\n const outputFormat = getOutputFormat(params);\n if (outputFormat?.type !== 'json_schema') {\n return null;\n }\n\n try {\n if ('parse' in outputFormat) {\n return outputFormat.parse(content);\n }\n\n return JSON.parse(content);\n } catch (error) {\n throw new AnthropicError(`Failed to parse structured output: ${error}`);\n }\n}\n","import { STAINLESS_HELPER_METHOD_HEADER } from '../internal/stainless-helper-header';\nimport { isAbortError } from '../internal/errors';\nimport { AnthropicError, APIUserAbortError } from '../error';\nimport {\n type ContentBlock,\n Messages,\n type Message,\n type MessageStreamEvent,\n type MessageParam,\n type MessageCreateParams,\n type MessageCreateParamsBase,\n type TextBlock,\n type TextCitation,\n type ToolUseBlock,\n type ServerToolUseBlock,\n} from '../resources/messages';\nimport { Stream } from '../streaming';\nimport { RequestOptions } from '../internal/request-options';\nimport type { Logger } from '../client';\nimport { maybeParseMessage, type ParsedMessage } from './parser';\nimport { JSON_BUF_PROPERTY, withLazyInput } from '../internal/message-stream-utils';\n\nexport interface MessageStreamEvents<ParsedT = null> {\n connect: () => void;\n streamEvent: (event: MessageStreamEvent, snapshot: Message) => void;\n text: (textDelta: string, textSnapshot: string) => void;\n citation: (citation: TextCitation, citationsSnapshot: TextCitation[]) => void;\n inputJson: (partialJson: string, jsonSnapshot: unknown) => void;\n thinking: (thinkingDelta: string, thinkingSnapshot: string) => void;\n signature: (signature: string) => void;\n message: (message: ParsedMessage<ParsedT>) => void;\n contentBlock: (content: ContentBlock) => void;\n finalMessage: (message: ParsedMessage<ParsedT>) => void;\n error: (error: AnthropicError) => void;\n abort: (error: APIUserAbortError) => void;\n end: () => void;\n}\n\ntype MessageStreamEventListeners<ParsedT, Event extends keyof MessageStreamEvents<ParsedT>> = {\n listener: MessageStreamEvents<ParsedT>[Event];\n once?: boolean;\n}[];\n\nexport type TracksToolInput = ToolUseBlock | ServerToolUseBlock;\n\nfunction tracksToolInput(content: ContentBlock): content is TracksToolInput {\n return content.type === 'tool_use' || content.type === 'server_tool_use';\n}\n\nexport class MessageStream<ParsedT = null> implements AsyncIterable<MessageStreamEvent> {\n messages: MessageParam[] = [];\n receivedMessages: ParsedMessage<ParsedT>[] = [];\n #currentMessageSnapshot: Message | undefined;\n #params: MessageCreateParams | null = null;\n\n controller: AbortController = new AbortController();\n\n #connectedPromise: Promise<Response | null>;\n #resolveConnectedPromise: (response: Response | null) => void = () => {};\n #rejectConnectedPromise: (error: AnthropicError) => void = () => {};\n\n #endPromise: Promise<void>;\n #resolveEndPromise: () => void = () => {};\n #rejectEndPromise: (error: AnthropicError) => void = () => {};\n\n #listeners: {\n [Event in keyof MessageStreamEvents<ParsedT>]?: MessageStreamEventListeners<ParsedT, Event>;\n } = {};\n\n #ended = false;\n #errored = false;\n #aborted = false;\n #catchingPromiseCreated = false;\n #response: Response | null | undefined;\n #request_id: string | null | undefined;\n #logger: Logger;\n\n constructor(params: MessageCreateParamsBase | null, opts?: { logger?: Logger | undefined }) {\n this.#connectedPromise = new Promise<Response | null>((resolve, reject) => {\n this.#resolveConnectedPromise = resolve;\n this.#rejectConnectedPromise = reject;\n });\n\n this.#endPromise = new Promise<void>((resolve, reject) => {\n this.#resolveEndPromise = resolve;\n this.#rejectEndPromise = reject;\n });\n\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n this.#connectedPromise.catch(() => {});\n this.#endPromise.catch(() => {});\n\n this.#params = params;\n this.#logger = opts?.logger ?? console;\n }\n\n get response(): Response | null | undefined {\n return this.#response;\n }\n\n get request_id(): string | null | undefined {\n return this.#request_id;\n }\n\n /**\n * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,\n * returned vie the `request-id` header which is useful for debugging requests and resporting\n * issues to Anthropic.\n *\n * This is the same as the `APIPromise.withResponse()` method.\n *\n * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`\n * as no `Response` is available.\n */\n async withResponse(): Promise<{\n data: MessageStream<ParsedT>;\n response: Response;\n request_id: string | null | undefined;\n }> {\n this.#catchingPromiseCreated = true;\n\n const response = await this.#connectedPromise;\n if (!response) {\n throw new Error('Could not resolve a `Response` object');\n }\n\n return {\n data: this,\n response,\n request_id: response.headers.get('request-id'),\n };\n }\n\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream: ReadableStream): MessageStream {\n const runner = new MessageStream(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n\n static createMessage<ParsedT>(\n messages: Messages,\n params: MessageCreateParamsBase,\n options?: RequestOptions,\n { logger }: { logger?: Logger | undefined } = {},\n ): MessageStream<ParsedT> {\n const runner = new MessageStream<ParsedT>(params, { logger });\n for (const message of params.messages) {\n runner._addMessageParam(message);\n }\n runner.#params = { ...params, stream: true };\n runner._run(() =>\n runner._createMessage(\n messages,\n { ...params, stream: true },\n { ...options, headers: { ...options?.headers, [STAINLESS_HELPER_METHOD_HEADER]: 'stream' } },\n ),\n );\n return runner;\n }\n\n protected _run(executor: () => Promise<any>) {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, this.#handleError);\n }\n\n protected _addMessageParam(message: MessageParam) {\n this.messages.push(message);\n }\n\n protected _addMessage(message: ParsedMessage<ParsedT>, emit = true) {\n this.receivedMessages.push(message);\n if (emit) {\n this._emit('message', message);\n }\n }\n\n protected async _createMessage(\n messages: Messages,\n params: MessageCreateParams,\n options?: RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n let abortHandler: (() => void) | undefined;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n abortHandler = this.controller.abort.bind(this.controller);\n signal.addEventListener('abort', abortHandler);\n }\n try {\n this.#beginRequest();\n const { response, data: stream } = await messages\n .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })\n .withResponse();\n this._connected(response);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n } finally {\n if (signal && abortHandler) {\n signal.removeEventListener('abort', abortHandler);\n }\n }\n }\n\n protected _connected(response: Response | null) {\n if (this.ended) return;\n this.#response = response;\n this.#request_id = response?.headers.get('request-id');\n this.#resolveConnectedPromise(response);\n this._emit('connect');\n }\n\n get ended(): boolean {\n return this.#ended;\n }\n\n get errored(): boolean {\n return this.#errored;\n }\n\n get aborted(): boolean {\n return this.#aborted;\n }\n\n abort() {\n this.controller.abort();\n }\n\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this MessageStream, so that calls can be chained\n */\n on<Event extends keyof MessageStreamEvents<ParsedT>>(\n event: Event,\n listener: MessageStreamEvents<ParsedT>[Event],\n ): this {\n const listeners: MessageStreamEventListeners<ParsedT, Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener });\n return this;\n }\n\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this MessageStream, so that calls can be chained\n */\n off<Event extends keyof MessageStreamEvents<ParsedT>>(\n event: Event,\n listener: MessageStreamEvents<ParsedT>[Event],\n ): this {\n const listeners = this.#listeners[event];\n if (!listeners) return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0) listeners.splice(index, 1);\n return this;\n }\n\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this MessageStream, so that calls can be chained\n */\n once<Event extends keyof MessageStreamEvents<ParsedT>>(\n event: Event,\n listener: MessageStreamEvents<ParsedT>[Event],\n ): this {\n const listeners: MessageStreamEventListeners<ParsedT, Event> =\n this.#listeners[event] || (this.#listeners[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted<Event extends keyof MessageStreamEvents<ParsedT>>(\n event: Event,\n ): Promise<\n Parameters<MessageStreamEvents<ParsedT>[Event]> extends [infer Param] ? Param\n : Parameters<MessageStreamEvents<ParsedT>[Event]> extends [] ? void\n : Parameters<MessageStreamEvents<ParsedT>[Event]>\n > {\n return new Promise((resolve, reject) => {\n this.#catchingPromiseCreated = true;\n if (event !== 'error') this.once('error', reject);\n this.once(event, resolve as any);\n });\n }\n\n async done(): Promise<void> {\n this.#catchingPromiseCreated = true;\n await this.#endPromise;\n }\n\n get currentMessage(): Message | undefined {\n return this.#currentMessageSnapshot;\n }\n\n #getFinalMessage(): ParsedMessage<ParsedT> {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n return this.receivedMessages.at(-1)!;\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message response,\n * or rejects if an error occurred or the stream ended prematurely without producing a Message.\n * If structured outputs were used, this will be a ParsedMessage with a `parsed_output` field.\n */\n async finalMessage(): Promise<ParsedMessage<ParsedT>> {\n await this.done();\n return this.#getFinalMessage();\n }\n\n #getFinalText(): string {\n if (this.receivedMessages.length === 0) {\n throw new AnthropicError('stream ended without producing a Message with role=assistant');\n }\n const textBlocks = this.receivedMessages\n .at(-1)!\n .content.filter((block): block is TextBlock => block.type === 'text')\n .map((block) => block.text);\n if (textBlocks.length === 0) {\n throw new AnthropicError('stream ended without producing a content block with type=text');\n }\n return textBlocks.join(' ');\n }\n\n /**\n * @returns a promise that resolves with the the final assistant Message's text response, concatenated\n * together if there are more than one text blocks.\n * Rejects if an error occurred or the stream ended prematurely without producing a Message.\n */\n async finalText(): Promise<string> {\n await this.done();\n return this.#getFinalText();\n }\n\n #handleError = (error: unknown) => {\n this.#errored = true;\n if (isAbortError(error)) {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n this.#aborted = true;\n return this._emit('abort', error);\n }\n if (error instanceof AnthropicError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const anthropicError: AnthropicError = new AnthropicError(error.message);\n // @ts-ignore\n anthropicError.cause = error;\n return this._emit('error', anthropicError);\n }\n return this._emit('error', new AnthropicError(String(error)));\n };\n\n protected _emit<Event extends keyof MessageStreamEvents<ParsedT>>(\n event: Event,\n ...args: Parameters<MessageStreamEvents<ParsedT>[Event]>\n ) {\n // make sure we don't emit any MessageStreamEvents after end\n if (this.#ended) return;\n\n if (event === 'end') {\n this.#ended = true;\n this.#resolveEndPromise();\n }\n\n const listeners: MessageStreamEventListeners<ParsedT, Event> | undefined = this.#listeners[event];\n if (listeners) {\n this.#listeners[event] = listeners.filter((l: { once?: boolean }) => !l.once) as any;\n listeners.forEach(({ listener }: any) => listener(...args));\n }\n\n if (event === 'abort') {\n const error = args[0] as APIUserAbortError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n return;\n }\n\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n\n const error = args[0] as AnthropicError;\n if (!this.#catchingPromiseCreated && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.final...()\n // - etc.\n Promise.reject(error);\n }\n this.#rejectConnectedPromise(error);\n this.#rejectEndPromise(error);\n this._emit('end');\n }\n }\n\n protected _emitFinal() {\n const finalMessage = this.receivedMessages.at(-1);\n if (finalMessage) {\n this._emit('finalMessage', this.#getFinalMessage());\n }\n }\n\n #beginRequest() {\n if (this.ended) return;\n this.#currentMessageSnapshot = undefined;\n }\n #addStreamEvent(event: MessageStreamEvent) {\n if (this.ended) return;\n const messageSnapshot = this.#accumulateMessage(event);\n this._emit('streamEvent', event, messageSnapshot);\n\n switch (event.type) {\n case 'content_block_delta': {\n const content = messageSnapshot.content.at(-1)!;\n switch (event.delta.type) {\n case 'text_delta': {\n if (content.type === 'text') {\n this._emit('text', event.delta.text, content.text || '');\n }\n break;\n }\n case 'citations_delta': {\n if (content.type === 'text') {\n this._emit('citation', event.delta.citation, content.citations ?? []);\n }\n break;\n }\n case 'input_json_delta': {\n if (tracksToolInput(content) && this.#listeners.inputJson?.length) {\n this._emit('inputJson', event.delta.partial_json, content.input);\n }\n break;\n }\n case 'thinking_delta': {\n if (content.type === 'thinking') {\n this._emit('thinking', event.delta.thinking, content.thinking);\n }\n break;\n }\n case 'signature_delta': {\n if (content.type === 'thinking') {\n this._emit('signature', content.signature);\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n break;\n }\n case 'message_stop': {\n this._addMessageParam(messageSnapshot);\n this._addMessage(maybeParseMessage(messageSnapshot, this.#params, { logger: this.#logger }), true);\n break;\n }\n case 'content_block_stop': {\n this._emit('contentBlock', messageSnapshot.content.at(-1)!);\n break;\n }\n case 'message_start': {\n this.#currentMessageSnapshot = messageSnapshot;\n break;\n }\n case 'content_block_start':\n case 'message_delta':\n break;\n }\n }\n #endRequest(): ParsedMessage<ParsedT> {\n if (this.ended) {\n throw new AnthropicError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = this.#currentMessageSnapshot;\n if (!snapshot) {\n throw new AnthropicError(`request ended without sending any chunks`);\n }\n this.#currentMessageSnapshot = undefined;\n return maybeParseMessage(snapshot, this.#params, { logger: this.#logger });\n }\n\n protected async _fromReadableStream(\n readableStream: ReadableStream,\n options?: RequestOptions,\n ): Promise<void> {\n const signal = options?.signal;\n let abortHandler: (() => void) | undefined;\n if (signal) {\n if (signal.aborted) this.controller.abort();\n abortHandler = this.controller.abort.bind(this.controller);\n signal.addEventListener('abort', abortHandler);\n }\n try {\n this.#beginRequest();\n this._connected(null);\n const stream = Stream.fromReadableStream<MessageStreamEvent>(readableStream, this.controller);\n for await (const event of stream) {\n this.#addStreamEvent(event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n this.#endRequest();\n } finally {\n if (signal && abortHandler) {\n signal.removeEventListener('abort', abortHandler);\n }\n }\n }\n\n /**\n * Mutates this.#currentMessage with the current event. Handling the accumulation of multiple messages\n * will be needed to be handled by the caller, this method will throw if you try to accumulate for multiple\n * messages.\n */\n #accumulateMessage(event: MessageStreamEvent): Message {\n let snapshot = this.#currentMessageSnapshot;\n\n if (event.type === 'message_start') {\n if (snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving \"message_stop\"`);\n }\n return event.message;\n }\n\n if (!snapshot) {\n throw new AnthropicError(`Unexpected event order, got ${event.type} before \"message_start\"`);\n }\n\n switch (event.type) {\n case 'message_stop':\n return snapshot;\n case 'message_delta':\n snapshot.stop_reason = event.delta.stop_reason;\n snapshot.stop_sequence = event.delta.stop_sequence;\n if (event.delta.stop_details != null) {\n snapshot.stop_details = event.delta.stop_details;\n }\n snapshot.usage.output_tokens = event.usage.output_tokens;\n\n // Update other usage fields if they exist in the event\n if (event.usage.input_tokens != null) {\n snapshot.usage.input_tokens = event.usage.input_tokens;\n }\n\n if (event.usage.cache_creation_input_tokens != null) {\n snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;\n }\n\n if (event.usage.cache_read_input_tokens != null) {\n snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;\n }\n\n if (event.usage.server_tool_use != null) {\n snapshot.usage.server_tool_use = event.usage.server_tool_use;\n }\n\n return snapshot;\n case 'content_block_start':\n snapshot.content.push({ ...event.content_block });\n return snapshot;\n case 'content_block_delta': {\n const snapshotContent = snapshot.content.at(event.index);\n\n switch (event.delta.type) {\n case 'text_delta': {\n if (snapshotContent?.type === 'text') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n text: (snapshotContent.text || '') + event.delta.text,\n };\n }\n break;\n }\n case 'citations_delta': {\n if (snapshotContent?.type === 'text') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n citations: [...(snapshotContent.citations ?? []), event.delta.citation],\n };\n }\n break;\n }\n case 'input_json_delta': {\n if (snapshotContent && tracksToolInput(snapshotContent)) {\n const jsonBuf = ((snapshotContent as any)[JSON_BUF_PROPERTY] || '') + event.delta.partial_json;\n snapshot.content[event.index] = withLazyInput(snapshotContent, jsonBuf);\n }\n break;\n }\n case 'thinking_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n thinking: snapshotContent.thinking + event.delta.thinking,\n };\n }\n break;\n }\n case 'signature_delta': {\n if (snapshotContent?.type === 'thinking') {\n snapshot.content[event.index] = {\n ...snapshotContent,\n signature: event.delta.signature,\n };\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n\n return snapshot;\n }\n case 'content_block_stop': {\n const snapshotContent = snapshot.content.at(event.index);\n if (snapshotContent && tracksToolInput(snapshotContent) && JSON_BUF_PROPERTY in snapshotContent) {\n Object.defineProperty(snapshotContent, 'input', {\n value: snapshotContent.input,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return snapshot;\n }\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<MessageStreamEvent> {\n const pushQueue: MessageStreamEvent[] = [];\n const readQueue: {\n resolve: (chunk: MessageStreamEvent | undefined) => void;\n reject: (error: unknown) => void;\n }[] = [];\n let done = false;\n\n this.on('streamEvent', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n } else {\n pushQueue.push(event);\n }\n });\n\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n\n return {\n next: async (): Promise<IteratorResult<MessageStreamEvent>> => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise<MessageStreamEvent | undefined>((resolve, reject) =>\n readQueue.push({ resolve, reject }),\n ).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift()!;\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n\n toReadableStream(): ReadableStream {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\n\n// used to ensure exhaustive case matching without throwing a runtime error\nfunction checkNever(x: never) {}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport * as Shared from '../shared';\nimport * as MessagesAPI from './messages';\nimport { APIPromise } from '../../core/api-promise';\nimport { Page, type PageParams, PagePromise } from '../../core/pagination';\nimport { buildHeaders } from '../../internal/headers';\nimport { RequestOptions } from '../../internal/request-options';\nimport { JSONLDecoder } from '../../internal/decoders/jsonl';\nimport { AnthropicError } from '../../error';\nimport { path } from '../../internal/utils/path';\n\nexport class Batches extends APIResource {\n /**\n * Send a batch of Message creation requests.\n *\n * The Message Batches API can be used to process multiple Messages API requests at\n * once. Once a Message Batch is created, it begins processing immediately. Batches\n * can take up to 24 hours to complete.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const messageBatch = await client.messages.batches.create({\n * requests: [\n * {\n * custom_id: 'my-custom-id-1',\n * params: {\n * max_tokens: 1024,\n * messages: [\n * { content: 'Hello, world', role: 'user' },\n * ],\n * model: 'claude-opus-4-6',\n * },\n * },\n * ],\n * });\n * ```\n */\n create(params: BatchCreateParams, options?: RequestOptions): APIPromise<MessageBatch> {\n const { user_profile_id, ...body } = params;\n return this._client.post('/v1/messages/batches', {\n body,\n ...options,\n headers: buildHeaders([\n { ...(user_profile_id != null ? { 'anthropic-user-profile-id': user_profile_id } : undefined) },\n options?.headers,\n ]),\n });\n }\n\n /**\n * This endpoint is idempotent and can be used to poll for Message Batch\n * completion. To access the results of a Message Batch, make a request to the\n * `results_url` field in the response.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const messageBatch = await client.messages.batches.retrieve(\n * 'message_batch_id',\n * );\n * ```\n */\n retrieve(messageBatchID: string, options?: RequestOptions): APIPromise<MessageBatch> {\n return this._client.get(path`/v1/messages/batches/${messageBatchID}`, options);\n }\n\n /**\n * List all Message Batches within a Workspace. Most recently created batches are\n * returned first.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * // Automatically fetches more pages as needed.\n * for await (const messageBatch of client.messages.batches.list()) {\n * // ...\n * }\n * ```\n */\n list(\n query: BatchListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<MessageBatchesPage, MessageBatch> {\n return this._client.getAPIList('/v1/messages/batches', Page<MessageBatch>, { query, ...options });\n }\n\n /**\n * Delete a Message Batch.\n *\n * Message Batches can only be deleted once they've finished processing. If you'd\n * like to delete an in-progress batch, you must first cancel it.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const deletedMessageBatch =\n * await client.messages.batches.delete('message_batch_id');\n * ```\n */\n delete(messageBatchID: string, options?: RequestOptions): APIPromise<DeletedMessageBatch> {\n return this._client.delete(path`/v1/messages/batches/${messageBatchID}`, options);\n }\n\n /**\n * Batches may be canceled any time before processing ends. Once cancellation is\n * initiated, the batch enters a `canceling` state, at which time the system may\n * complete any in-progress, non-interruptible requests before finalizing\n * cancellation.\n *\n * The number of canceled requests is specified in `request_counts`. To determine\n * which requests were canceled, check the individual results within the batch.\n * Note that cancellation may not result in any canceled requests if they were\n * non-interruptible.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const messageBatch = await client.messages.batches.cancel(\n * 'message_batch_id',\n * );\n * ```\n */\n cancel(messageBatchID: string, options?: RequestOptions): APIPromise<MessageBatch> {\n return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel`, options);\n }\n\n /**\n * Streams the results of a Message Batch as a `.jsonl` file.\n *\n * Each line in the file is a JSON object containing the result of a single request\n * in the Message Batch. Results are not guaranteed to be in the same order as\n * requests. Use the `custom_id` field to match results to requests.\n *\n * Learn more about the Message Batches API in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)\n *\n * @example\n * ```ts\n * const messageBatchIndividualResponse =\n * await client.messages.batches.results('message_batch_id');\n * ```\n */\n async results(\n messageBatchID: string,\n options?: RequestOptions,\n ): Promise<JSONLDecoder<MessageBatchIndividualResponse>> {\n const batch = await this.retrieve(messageBatchID);\n if (!batch.results_url) {\n throw new AnthropicError(\n `No batch \\`results_url\\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`,\n );\n }\n\n return this._client\n .get(batch.results_url, {\n ...options,\n headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]),\n stream: true,\n __binaryResponse: true,\n })\n ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)) as APIPromise<\n JSONLDecoder<MessageBatchIndividualResponse>\n >;\n }\n}\n\nexport type MessageBatchesPage = Page<MessageBatch>;\n\nexport interface DeletedMessageBatch {\n /**\n * ID of the Message Batch.\n */\n id: string;\n\n /**\n * Deleted object type.\n *\n * For Message Batches, this is always `\"message_batch_deleted\"`.\n */\n type: 'message_batch_deleted';\n}\n\nexport interface MessageBatch {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * archived and its results became unavailable.\n */\n archived_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which cancellation was\n * initiated for the Message Batch. Specified only if cancellation was initiated.\n */\n cancel_initiated_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch was\n * created.\n */\n created_at: string;\n\n /**\n * RFC 3339 datetime string representing the time at which processing for the\n * Message Batch ended. Specified only once processing ends.\n *\n * Processing ends when every request in a Message Batch has either succeeded,\n * errored, canceled, or expired.\n */\n ended_at: string | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the Message Batch will\n * expire and end processing, which is 24 hours after creation.\n */\n expires_at: string;\n\n /**\n * Processing status of the Message Batch.\n */\n processing_status: 'in_progress' | 'canceling' | 'ended';\n\n /**\n * Tallies requests within the Message Batch, categorized by their status.\n *\n * Requests start as `processing` and move to one of the other statuses only once\n * processing of the entire batch ends. The sum of all values always matches the\n * total number of requests in the batch.\n */\n request_counts: MessageBatchRequestCounts;\n\n /**\n * URL to a `.jsonl` file containing the results of the Message Batch requests.\n * Specified only once processing ends.\n *\n * Results in the file are not guaranteed to be in the same order as requests. Use\n * the `custom_id` field to match results to requests.\n */\n results_url: string | null;\n\n /**\n * Object type.\n *\n * For Message Batches, this is always `\"message_batch\"`.\n */\n type: 'message_batch';\n}\n\nexport interface MessageBatchCanceledResult {\n type: 'canceled';\n}\n\nexport interface MessageBatchErroredResult {\n error: Shared.ErrorResponse;\n\n type: 'errored';\n}\n\nexport interface MessageBatchExpiredResult {\n type: 'expired';\n}\n\n/**\n * This is a single line in the response `.jsonl` file and does not represent the\n * response as a whole.\n */\nexport interface MessageBatchIndividualResponse {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\n result: MessageBatchResult;\n}\n\nexport interface MessageBatchRequestCounts {\n /**\n * Number of requests in the Message Batch that have been canceled.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n canceled: number;\n\n /**\n * Number of requests in the Message Batch that encountered an error.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n errored: number;\n\n /**\n * Number of requests in the Message Batch that have expired.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n expired: number;\n\n /**\n * Number of requests in the Message Batch that are processing.\n */\n processing: number;\n\n /**\n * Number of requests in the Message Batch that have completed successfully.\n *\n * This is zero until processing of the entire Message Batch has ended.\n */\n succeeded: number;\n}\n\n/**\n * Processing result for this request.\n *\n * Contains a Message output if processing was successful, an error response if\n * processing failed, or the reason why processing was not attempted, such as\n * cancellation or expiration.\n */\nexport type MessageBatchResult =\n | MessageBatchSucceededResult\n | MessageBatchErroredResult\n | MessageBatchCanceledResult\n | MessageBatchExpiredResult;\n\nexport interface MessageBatchSucceededResult {\n message: MessagesAPI.Message;\n\n type: 'succeeded';\n}\n\nexport interface BatchCreateParams {\n /**\n * Body param: List of requests for prompt completion. Each is an individual\n * request to create a Message.\n */\n requests: Array<BatchCreateParams.Request>;\n\n /**\n * Header param: The user profile ID to attribute the requests in this batch to.\n * Use when acting on behalf of a party other than your organization. Requires the\n * `user-profiles` beta header. Applies to every request in the batch; an\n * individual request whose `user_profile_id` body field conflicts with this header\n * is errored.\n */\n user_profile_id?: string;\n}\n\nexport namespace BatchCreateParams {\n export interface Request {\n /**\n * Developer-provided ID created for each request in a Message Batch. Useful for\n * matching results to requests, as results may be given out of request order.\n *\n * Must be unique for each request within the Message Batch.\n */\n custom_id: string;\n\n /**\n * Messages API creation parameters for the individual request.\n *\n * See the [Messages API reference](https://docs.claude.com/en/api/messages) for\n * full documentation on available parameters.\n */\n params: MessagesAPI.MessageCreateParamsNonStreaming;\n }\n}\n\nexport interface BatchListParams extends PageParams {}\n\nexport declare namespace Batches {\n export {\n type DeletedMessageBatch as DeletedMessageBatch,\n type MessageBatch as MessageBatch,\n type MessageBatchCanceledResult as MessageBatchCanceledResult,\n type MessageBatchErroredResult as MessageBatchErroredResult,\n type MessageBatchExpiredResult as MessageBatchExpiredResult,\n type MessageBatchIndividualResponse as MessageBatchIndividualResponse,\n type MessageBatchRequestCounts as MessageBatchRequestCounts,\n type MessageBatchResult as MessageBatchResult,\n type MessageBatchSucceededResult as MessageBatchSucceededResult,\n type MessageBatchesPage as MessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchListParams as BatchListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIPromise } from '../../core/api-promise';\nimport { APIResource } from '../../core/resource';\nimport { Stream } from '../../core/streaming';\nimport { buildHeaders } from '../../internal/headers';\nimport { RequestOptions } from '../../internal/request-options';\nimport { stainlessHelperHeader } from '../../internal/stainless-helper-header';\nimport { MessageStream } from '../../lib/MessageStream';\nimport {\n parseMessage,\n type ExtractParsedContentFromParams,\n type ParseableMessageCreateParams,\n type ParsedMessage,\n} from '../../lib/parser';\nimport * as BatchesAPI from './batches';\nimport {\n BatchCreateParams,\n BatchListParams,\n Batches,\n DeletedMessageBatch,\n MessageBatch,\n MessageBatchCanceledResult,\n MessageBatchErroredResult,\n MessageBatchExpiredResult,\n MessageBatchIndividualResponse,\n MessageBatchRequestCounts,\n MessageBatchResult,\n MessageBatchSucceededResult,\n MessageBatchesPage,\n} from './batches';\nimport * as MessagesAPI from './messages';\n\nimport { MODEL_NONSTREAMING_TOKENS } from '../../internal/constants';\n\nexport class Messages extends APIResource {\n batches: BatchesAPI.Batches = new BatchesAPI.Batches(this._client);\n\n /**\n * Send a structured list of input messages with text and/or image content, and the\n * model will generate the next message in the conversation.\n *\n * The Messages API can be used for either single queries or stateless multi-turn\n * conversations.\n *\n * Learn more about the Messages API in our\n * [user guide](https://docs.claude.com/en/docs/initial-setup)\n *\n * @example\n * ```ts\n * const message = await client.messages.create({\n * max_tokens: 1024,\n * messages: [{ content: 'Hello, world', role: 'user' }],\n * model: 'claude-opus-4-6',\n * });\n * ```\n */\n create(params: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Message>;\n create(\n params: MessageCreateParamsStreaming,\n options?: RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent>>;\n create(\n params: MessageCreateParamsBase,\n options?: RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent> | Message>;\n create(\n params: MessageCreateParams,\n options?: RequestOptions,\n ): APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>> {\n const { user_profile_id, ...body } = params;\n if (body.model in DEPRECATED_MODELS) {\n console.warn(\n `The model '${body.model}' is deprecated and will reach end-of-life on ${\n DEPRECATED_MODELS[body.model]\n }\\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`,\n );\n }\n if (\n MODELS_TO_WARN_WITH_THINKING_ENABLED.includes(body.model) &&\n body.thinking &&\n body.thinking.type === 'enabled'\n ) {\n console.warn(\n `Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`,\n );\n }\n\n let timeout = (this._client as any)._options.timeout as number | null;\n if (!body.stream && timeout == null) {\n const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;\n timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);\n }\n\n // Collect helper info from tools and messages\n const helperHeader = stainlessHelperHeader(body.tools, body.messages);\n return this._client.post('/v1/messages', {\n body,\n timeout: timeout ?? 600000,\n ...options,\n headers: buildHeaders([\n { ...(user_profile_id != null ? { 'anthropic-user-profile-id': user_profile_id } : undefined) },\n helperHeader,\n options?.headers,\n ]),\n stream: params.stream ?? false,\n }) as APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>>;\n }\n\n /**\n * Send a structured list of input messages with text and/or image content, along with an expected `output_config.format` and\n * the response will be automatically parsed and available in the `parsed_output` property of the message.\n *\n * @example\n * ```ts\n * const message = await client.messages.parse({\n * model: 'claude-sonnet-4-5-20250929',\n * max_tokens: 1024,\n * messages: [{ role: 'user', content: 'What is 2+2?' }],\n * output_config: {\n * format: zodOutputFormat(z.object({ answer: z.number() })),\n * },\n * });\n *\n * console.log(message.parsed_output?.answer); // 4\n * ```\n */\n parse<Params extends MessageCreateParamsNonStreaming>(\n params: Params,\n options?: RequestOptions,\n ): APIPromise<ParsedMessage<ExtractParsedContentFromParams<Params>>> {\n return this.create(params, options).then((message) =>\n parseMessage(message, params, { logger: this._client.logger ?? console }),\n ) as APIPromise<ParsedMessage<ExtractParsedContentFromParams<Params>>>;\n }\n\n /**\n * Create a Message stream.\n *\n * If `output_config.format` is provided with a parseable format (like `zodOutputFormat()`),\n * the final message will include a `parsed_output` property with the parsed content.\n *\n * @example\n * ```ts\n * const stream = client.messages.stream({\n * model: 'claude-sonnet-4-5-20250929',\n * max_tokens: 1024,\n * messages: [{ role: 'user', content: 'What is 2+2?' }],\n * output_config: {\n * format: zodOutputFormat(z.object({ answer: z.number() })),\n * },\n * });\n *\n * const message = await stream.finalMessage();\n * console.log(message.parsed_output?.answer); // 4\n * ```\n */\n stream<Params extends MessageStreamParams>(\n body: Params,\n options?: RequestOptions,\n ): MessageStream<ExtractParsedContentFromParams<Params>> {\n return MessageStream.createMessage<ExtractParsedContentFromParams<Params>>(\n this,\n body as MessageCreateParamsBase,\n options,\n { logger: this._client.logger ?? console },\n );\n }\n\n /**\n * Count the number of tokens in a Message.\n *\n * The Token Count API can be used to count the number of tokens in a Message,\n * including tools, images, and documents, without creating it.\n *\n * Learn more about token counting in our\n * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)\n *\n * @example\n * ```ts\n * const messageTokensCount =\n * await client.messages.countTokens({\n * messages: [{ content: 'Hello, world', role: 'user' }],\n * model: 'claude-opus-4-6',\n * });\n * ```\n */\n countTokens(body: MessageCountTokensParams, options?: RequestOptions): APIPromise<MessageTokensCount> {\n return this._client.post('/v1/messages/count_tokens', { body, ...options });\n }\n}\n\nexport interface Base64ImageSource {\n data: string;\n\n media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';\n\n type: 'base64';\n}\n\nexport interface Base64PDFSource {\n data: string;\n\n media_type: 'application/pdf';\n\n type: 'base64';\n}\n\nexport interface BashCodeExecutionOutputBlock {\n file_id: string;\n\n type: 'bash_code_execution_output';\n}\n\nexport interface BashCodeExecutionOutputBlockParam {\n file_id: string;\n\n type: 'bash_code_execution_output';\n}\n\nexport interface BashCodeExecutionResultBlock {\n content: Array<BashCodeExecutionOutputBlock>;\n\n return_code: number;\n\n stderr: string;\n\n stdout: string;\n\n type: 'bash_code_execution_result';\n}\n\nexport interface BashCodeExecutionResultBlockParam {\n content: Array<BashCodeExecutionOutputBlockParam>;\n\n return_code: number;\n\n stderr: string;\n\n stdout: string;\n\n type: 'bash_code_execution_result';\n}\n\nexport interface BashCodeExecutionToolResultBlock {\n content: BashCodeExecutionToolResultError | BashCodeExecutionResultBlock;\n\n tool_use_id: string;\n\n type: 'bash_code_execution_tool_result';\n}\n\nexport interface BashCodeExecutionToolResultBlockParam {\n content: BashCodeExecutionToolResultErrorParam | BashCodeExecutionResultBlockParam;\n\n tool_use_id: string;\n\n type: 'bash_code_execution_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport interface BashCodeExecutionToolResultError {\n error_code: BashCodeExecutionToolResultErrorCode;\n\n type: 'bash_code_execution_tool_result_error';\n}\n\nexport type BashCodeExecutionToolResultErrorCode =\n | 'invalid_tool_input'\n | 'unavailable'\n | 'too_many_requests'\n | 'execution_time_exceeded'\n | 'output_file_too_large';\n\nexport interface BashCodeExecutionToolResultErrorParam {\n error_code: BashCodeExecutionToolResultErrorCode;\n\n type: 'bash_code_execution_tool_result_error';\n}\n\nexport interface CacheControlEphemeral {\n type: 'ephemeral';\n\n /**\n * The time-to-live for the cache control breakpoint.\n *\n * This may be one the following values:\n *\n * - `5m`: 5 minutes\n * - `1h`: 1 hour\n *\n * Defaults to `5m`. See\n * [prompt caching pricing](https://docs.claude.com/en/docs/build-with-claude/prompt-caching)\n * for details.\n */\n ttl?: '5m' | '1h';\n}\n\nexport interface CacheCreation {\n /**\n * The number of input tokens used to create the 1 hour cache entry.\n */\n ephemeral_1h_input_tokens: number;\n\n /**\n * The number of input tokens used to create the 5 minute cache entry.\n */\n ephemeral_5m_input_tokens: number;\n}\n\nexport interface CitationCharLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n file_id: string | null;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface CitationCharLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_char_index: number;\n\n start_char_index: number;\n\n type: 'char_location';\n}\n\nexport interface CitationContentBlockLocation {\n /**\n * The full text of the cited block range, concatenated.\n *\n * Always equals the contents of `content[start_block_index:end_block_index]`\n * joined together. The text block is the minimal citable unit; this field is never\n * a substring of a single block. Not counted toward output tokens, and not counted\n * toward input tokens when sent back in subsequent turns.\n */\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n /**\n * Exclusive 0-based end index of the cited block range in the source's `content`\n * array.\n *\n * Always greater than `start_block_index`; a single-block citation has\n * `end_block_index = start_block_index + 1`.\n */\n end_block_index: number;\n\n file_id: string | null;\n\n /**\n * 0-based index of the first cited block in the source's `content` array.\n */\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface CitationContentBlockLocationParam {\n /**\n * The full text of the cited block range, concatenated.\n *\n * Always equals the contents of `content[start_block_index:end_block_index]`\n * joined together. The text block is the minimal citable unit; this field is never\n * a substring of a single block. Not counted toward output tokens, and not counted\n * toward input tokens when sent back in subsequent turns.\n */\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n /**\n * Exclusive 0-based end index of the cited block range in the source's `content`\n * array.\n *\n * Always greater than `start_block_index`; a single-block citation has\n * `end_block_index = start_block_index + 1`.\n */\n end_block_index: number;\n\n /**\n * 0-based index of the first cited block in the source's `content` array.\n */\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface CitationPageLocation {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n file_id: string | null;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface CitationPageLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_page_number: number;\n\n start_page_number: number;\n\n type: 'page_location';\n}\n\nexport interface CitationSearchResultLocationParam {\n /**\n * The full text of the cited block range, concatenated.\n *\n * Always equals the contents of `content[start_block_index:end_block_index]`\n * joined together. The text block is the minimal citable unit; this field is never\n * a substring of a single block. Not counted toward output tokens, and not counted\n * toward input tokens when sent back in subsequent turns.\n */\n cited_text: string;\n\n /**\n * Exclusive 0-based end index of the cited block range in the source's `content`\n * array.\n *\n * Always greater than `start_block_index`; a single-block citation has\n * `end_block_index = start_block_index + 1`.\n */\n end_block_index: number;\n\n /**\n * 0-based index of the cited search result among all `search_result` content\n * blocks in the request, in the order they appear across messages and tool\n * results.\n *\n * Counted separately from `document_index`; server-side web search results are not\n * included in this count.\n */\n search_result_index: number;\n\n source: string;\n\n /**\n * 0-based index of the first cited block in the source's `content` array.\n */\n start_block_index: number;\n\n title: string | null;\n\n type: 'search_result_location';\n}\n\nexport interface CitationWebSearchResultLocationParam {\n cited_text: string;\n\n encrypted_index: string;\n\n title: string | null;\n\n type: 'web_search_result_location';\n\n url: string;\n}\n\nexport interface CitationsConfig {\n enabled: boolean;\n}\n\nexport interface CitationsConfigParam {\n enabled?: boolean;\n}\n\nexport interface CitationsDelta {\n citation:\n | CitationCharLocation\n | CitationPageLocation\n | CitationContentBlockLocation\n | CitationsWebSearchResultLocation\n | CitationsSearchResultLocation;\n\n type: 'citations_delta';\n}\n\nexport interface CitationsSearchResultLocation {\n /**\n * The full text of the cited block range, concatenated.\n *\n * Always equals the contents of `content[start_block_index:end_block_index]`\n * joined together. The text block is the minimal citable unit; this field is never\n * a substring of a single block. Not counted toward output tokens, and not counted\n * toward input tokens when sent back in subsequent turns.\n */\n cited_text: string;\n\n /**\n * Exclusive 0-based end index of the cited block range in the source's `content`\n * array.\n *\n * Always greater than `start_block_index`; a single-block citation has\n * `end_block_index = start_block_index + 1`.\n */\n end_block_index: number;\n\n /**\n * 0-based index of the cited search result among all `search_result` content\n * blocks in the request, in the order they appear across messages and tool\n * results.\n *\n * Counted separately from `document_index`; server-side web search results are not\n * included in this count.\n */\n search_result_index: number;\n\n source: string;\n\n /**\n * 0-based index of the first cited block in the source's `content` array.\n */\n start_block_index: number;\n\n title: string | null;\n\n type: 'search_result_location';\n}\n\nexport interface CitationsWebSearchResultLocation {\n cited_text: string;\n\n encrypted_index: string;\n\n title: string | null;\n\n type: 'web_search_result_location';\n\n url: string;\n}\n\nexport interface CodeExecutionOutputBlock {\n file_id: string;\n\n type: 'code_execution_output';\n}\n\nexport interface CodeExecutionOutputBlockParam {\n file_id: string;\n\n type: 'code_execution_output';\n}\n\nexport interface CodeExecutionResultBlock {\n content: Array<CodeExecutionOutputBlock>;\n\n return_code: number;\n\n stderr: string;\n\n stdout: string;\n\n type: 'code_execution_result';\n}\n\nexport interface CodeExecutionResultBlockParam {\n content: Array<CodeExecutionOutputBlockParam>;\n\n return_code: number;\n\n stderr: string;\n\n stdout: string;\n\n type: 'code_execution_result';\n}\n\nexport interface CodeExecutionTool20250522 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'code_execution';\n\n type: 'code_execution_20250522';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface CodeExecutionTool20250825 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'code_execution';\n\n type: 'code_execution_20250825';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * Code execution tool with REPL state persistence (daemon mode + gVisor\n * checkpoint).\n */\nexport interface CodeExecutionTool20260120 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'code_execution';\n\n type: 'code_execution_20260120';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * Code execution tool with REPL state persistence.\n */\nexport interface CodeExecutionTool20260521 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'code_execution';\n\n type: 'code_execution_20260521';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface CodeExecutionToolResultBlock {\n /**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\n content: CodeExecutionToolResultBlockContent;\n\n tool_use_id: string;\n\n type: 'code_execution_tool_result';\n}\n\n/**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\nexport type CodeExecutionToolResultBlockContent =\n | CodeExecutionToolResultError\n | CodeExecutionResultBlock\n | EncryptedCodeExecutionResultBlock;\n\nexport interface CodeExecutionToolResultBlockParam {\n /**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\n content: CodeExecutionToolResultBlockParamContent;\n\n tool_use_id: string;\n\n type: 'code_execution_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n}\n\n/**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\nexport type CodeExecutionToolResultBlockParamContent =\n | CodeExecutionToolResultErrorParam\n | CodeExecutionResultBlockParam\n | EncryptedCodeExecutionResultBlockParam;\n\nexport interface CodeExecutionToolResultError {\n error_code: CodeExecutionToolResultErrorCode;\n\n type: 'code_execution_tool_result_error';\n}\n\nexport type CodeExecutionToolResultErrorCode =\n | 'invalid_tool_input'\n | 'unavailable'\n | 'too_many_requests'\n | 'execution_time_exceeded';\n\nexport interface CodeExecutionToolResultErrorParam {\n error_code: CodeExecutionToolResultErrorCode;\n\n type: 'code_execution_tool_result_error';\n}\n\n/**\n * Information about the container used in the request (for the code execution\n * tool)\n */\nexport interface Container {\n /**\n * Identifier for the container used in this request\n */\n id: string;\n\n /**\n * The time at which the container will expire.\n */\n expires_at: string;\n}\n\n/**\n * Response model for a file uploaded to the container.\n */\nexport interface ContainerUploadBlock {\n file_id: string;\n\n type: 'container_upload';\n}\n\n/**\n * A content block that represents a file to be uploaded to the container Files\n * uploaded via this block will be available in the container's input directory.\n */\nexport interface ContainerUploadBlockParam {\n file_id: string;\n\n type: 'container_upload';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n}\n\n/**\n * Response model for a file uploaded to the container.\n */\nexport type ContentBlock =\n | TextBlock\n | ThinkingBlock\n | RedactedThinkingBlock\n | ToolUseBlock\n | ServerToolUseBlock\n | WebSearchToolResultBlock\n | WebFetchToolResultBlock\n | CodeExecutionToolResultBlock\n | BashCodeExecutionToolResultBlock\n | TextEditorCodeExecutionToolResultBlock\n | ToolSearchToolResultBlock\n | ContainerUploadBlock;\n\n/**\n * Regular text content.\n */\nexport type ContentBlockParam =\n | TextBlockParam\n | ImageBlockParam\n | DocumentBlockParam\n | SearchResultBlockParam\n | ThinkingBlockParam\n | RedactedThinkingBlockParam\n | ToolUseBlockParam\n | ToolResultBlockParam\n | ServerToolUseBlockParam\n | WebSearchToolResultBlockParam\n | WebFetchToolResultBlockParam\n | CodeExecutionToolResultBlockParam\n | BashCodeExecutionToolResultBlockParam\n | TextEditorCodeExecutionToolResultBlockParam\n | ToolSearchToolResultBlockParam\n | ContainerUploadBlockParam\n | MidConversationSystemBlockParam;\n\nexport interface ContentBlockSource {\n content: string | Array<ContentBlockSourceContent>;\n\n type: 'content';\n}\n\nexport type ContentBlockSourceContent = TextBlockParam | ImageBlockParam;\n\n/**\n * Tool invocation directly from the model.\n */\nexport interface DirectCaller {\n type: 'direct';\n}\n\nexport interface DocumentBlock {\n /**\n * Citation configuration for the document\n */\n citations: CitationsConfig | null;\n\n source: Base64PDFSource | PlainTextSource;\n\n /**\n * The title of the document\n */\n title: string | null;\n\n type: 'document';\n}\n\nexport interface DocumentBlockParam {\n source: Base64PDFSource | PlainTextSource | ContentBlockSource | URLPDFSource;\n\n type: 'document';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n citations?: CitationsConfigParam | null;\n\n context?: string | null;\n\n title?: string | null;\n}\n\n/**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\nexport interface EncryptedCodeExecutionResultBlock {\n content: Array<CodeExecutionOutputBlock>;\n\n encrypted_stdout: string;\n\n return_code: number;\n\n stderr: string;\n\n type: 'encrypted_code_execution_result';\n}\n\n/**\n * Code execution result with encrypted stdout for PFC + web_search results.\n */\nexport interface EncryptedCodeExecutionResultBlockParam {\n content: Array<CodeExecutionOutputBlockParam>;\n\n encrypted_stdout: string;\n\n return_code: number;\n\n stderr: string;\n\n type: 'encrypted_code_execution_result';\n}\n\nexport interface ImageBlockParam {\n source: Base64ImageSource | URLImageSource;\n\n type: 'image';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport interface InputJSONDelta {\n partial_json: string;\n\n type: 'input_json_delta';\n}\n\nexport interface JSONOutputFormat {\n /**\n * The JSON schema of the format\n */\n schema: { [key: string]: unknown };\n\n type: 'json_schema';\n}\n\nexport interface MemoryTool20250818 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'memory';\n\n type: 'memory_20250818';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface Message {\n /**\n * Unique object identifier.\n *\n * The format and length of IDs may change over time.\n */\n id: string;\n\n /**\n * Information about the container used in the request (for the code execution\n * tool)\n */\n container: Container | null;\n\n /**\n * Content generated by the model.\n *\n * This is an array of content blocks, each of which has a `type` that determines\n * its shape.\n *\n * Example:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"Hi, I'm Claude.\" }]\n * ```\n *\n * If the request input `messages` ended with an `assistant` turn, then the\n * response `content` will continue directly from that last turn. You can use this\n * to constrain the model's output.\n *\n * For example, if the input `messages` were:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Then the response `content` might be:\n *\n * ```json\n * [{ \"type\": \"text\", \"text\": \"B)\" }]\n * ```\n */\n content: Array<ContentBlock>;\n\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: Model;\n\n /**\n * Conversational role of the generated message.\n *\n * This will always be `\"assistant\"`.\n */\n role: 'assistant';\n\n /**\n * Structured information about a refusal.\n */\n stop_details: RefusalStopDetails | null;\n\n /**\n * The reason that we stopped.\n *\n * This may be one the following values:\n *\n * - `\"end_turn\"`: the model reached a natural stopping point\n * - `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n * - `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n * - `\"tool_use\"`: the model invoked one or more tools\n * - `\"pause_turn\"`: we paused a long-running turn. You may provide the response\n * back as-is in a subsequent request to let the model continue.\n * - `\"refusal\"`: when streaming classifiers intervene to handle potential policy\n * violations\n *\n * In non-streaming mode this value is always non-null. In streaming mode, it is\n * null in the `message_start` event and non-null otherwise.\n */\n stop_reason: StopReason | null;\n\n /**\n * Which custom stop sequence was generated, if any.\n *\n * This value will be a non-null string if one of your custom stop sequences was\n * generated.\n */\n stop_sequence: string | null;\n\n /**\n * Object type.\n *\n * For Messages, this is always `\"message\"`.\n */\n type: 'message';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: Usage;\n}\n\n/**\n * Code execution tool with REPL state persistence (daemon mode + gVisor\n * checkpoint).\n */\nexport type MessageCountTokensTool =\n | Tool\n | ToolBash20250124\n | CodeExecutionTool20250522\n | CodeExecutionTool20250825\n | CodeExecutionTool20260120\n | CodeExecutionTool20260521\n | MemoryTool20250818\n | ToolTextEditor20250124\n | ToolTextEditor20250429\n | ToolTextEditor20250728\n | WebSearchTool20250305\n | WebFetchTool20250910\n | WebSearchTool20260209\n | WebFetchTool20260209\n | WebFetchTool20260309\n | ToolSearchToolBm25_20251119\n | ToolSearchToolRegex20251119;\n\nexport interface MessageDeltaUsage {\n /**\n * The cumulative number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number | null;\n\n /**\n * The cumulative number of input tokens read from the cache.\n */\n cache_read_input_tokens: number | null;\n\n /**\n * The cumulative number of input tokens which were used.\n */\n input_tokens: number | null;\n\n /**\n * The cumulative number of output tokens which were used.\n */\n output_tokens: number;\n\n /**\n * Breakdown of output tokens by category.\n *\n * `output_tokens` remains the inclusive, authoritative total used for billing.\n * This object provides a read-only decomposition for observability — for example,\n * how many of the billed output tokens were spent on internal reasoning that may\n * have been summarized before being returned to you.\n */\n output_tokens_details: OutputTokensDetails | null;\n\n /**\n * The number of server tool requests.\n */\n server_tool_use: ServerToolUsage | null;\n}\n\nexport interface MessageParam {\n content: string | Array<ContentBlockParam>;\n\n role: 'user' | 'assistant' | 'system';\n}\n\nexport interface MessageTokensCount {\n /**\n * The total number of tokens across the provided list of messages, system prompt,\n * and tools.\n */\n input_tokens: number;\n}\n\nexport interface Metadata {\n /**\n * An external identifier for the user who is associated with the request.\n *\n * This should be a uuid, hash value, or other opaque identifier. Anthropic may use\n * this id to help detect abuse. Do not include any identifying information such as\n * name, email address, or phone number.\n */\n user_id?: string | null;\n}\n\n/**\n * System instructions that appear mid-conversation.\n *\n * Use this block to provide or update system-level instructions at a specific\n * point in the conversation, rather than only via the top-level `system`\n * parameter.\n */\nexport interface MidConversationSystemBlockParam {\n /**\n * System instruction text blocks.\n */\n content: Array<TextBlockParam>;\n\n type: 'mid_conv_system';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n}\n\n/**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\nexport type Model =\n | 'claude-fable-5'\n | 'claude-mythos-5'\n | 'claude-opus-4-8'\n | 'claude-opus-4-7'\n | 'claude-mythos-preview'\n | 'claude-opus-4-6'\n | 'claude-sonnet-4-6'\n | 'claude-haiku-4-5'\n | 'claude-haiku-4-5-20251001'\n | 'claude-opus-4-5'\n | 'claude-opus-4-5-20251101'\n | 'claude-sonnet-4-5'\n | 'claude-sonnet-4-5-20250929'\n | 'claude-opus-4-1'\n | 'claude-opus-4-1-20250805'\n | (string & {});\n\nexport interface OutputConfig {\n /**\n * All possible effort levels.\n */\n effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | null;\n\n /**\n * A schema to specify Claude's output format in responses. See\n * [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)\n */\n format?: JSONOutputFormat | null;\n}\n\nexport interface OutputTokensDetails {\n /**\n * Number of output tokens the model generated as internal reasoning, including the\n * thinking-block delimiter tokens.\n *\n * Reflects the raw reasoning the model produced, not the (possibly shorter)\n * summarized thinking text returned in the response body. Computed by\n * re-tokenizing the raw reasoning text, so it may differ from the model's exact\n * generation count by a small number of tokens. Always ≤ `output_tokens`;\n * `output_tokens - thinking_tokens` approximates the non-reasoning output.\n */\n thinking_tokens: number;\n}\nconst DEPRECATED_MODELS: {\n [K in Model]?: string;\n} = {\n 'claude-1.3': 'November 6th, 2024',\n 'claude-1.3-100k': 'November 6th, 2024',\n 'claude-instant-1.1': 'November 6th, 2024',\n 'claude-instant-1.1-100k': 'November 6th, 2024',\n 'claude-instant-1.2': 'November 6th, 2024',\n 'claude-3-sonnet-20240229': 'July 21st, 2025',\n 'claude-3-opus-20240229': 'January 5th, 2026',\n 'claude-2.1': 'July 21st, 2025',\n 'claude-2.0': 'July 21st, 2025',\n 'claude-3-7-sonnet-latest': 'February 19th, 2026',\n 'claude-3-7-sonnet-20250219': 'February 19th, 2026',\n 'claude-3-5-haiku-latest': 'February 19th, 2026',\n 'claude-3-5-haiku-20241022': 'February 19th, 2026',\n 'claude-opus-4-0': 'June 15th, 2026',\n 'claude-opus-4-20250514': 'June 15th, 2026',\n 'claude-sonnet-4-0': 'June 15th, 2026',\n 'claude-sonnet-4-20250514': 'June 15th, 2026',\n 'claude-opus-4-1': 'August 5th, 2026',\n 'claude-opus-4-1-20250805': 'August 5th, 2026',\n 'claude-mythos-preview': 'June 30th, 2026',\n};\n\nconst MODELS_TO_WARN_WITH_THINKING_ENABLED: Model[] = ['claude-mythos-preview', 'claude-opus-4-6'];\n\nexport interface PlainTextSource {\n data: string;\n\n media_type: 'text/plain';\n\n type: 'text';\n}\n\nexport type RawContentBlockDelta =\n | TextDelta\n | InputJSONDelta\n | CitationsDelta\n | ThinkingDelta\n | SignatureDelta;\n\nexport interface RawContentBlockDeltaEvent {\n delta: RawContentBlockDelta;\n\n index: number;\n\n type: 'content_block_delta';\n}\n\nexport interface RawContentBlockStartEvent {\n /**\n * Response model for a file uploaded to the container.\n */\n content_block:\n | TextBlock\n | ThinkingBlock\n | RedactedThinkingBlock\n | ToolUseBlock\n | ServerToolUseBlock\n | WebSearchToolResultBlock\n | WebFetchToolResultBlock\n | CodeExecutionToolResultBlock\n | BashCodeExecutionToolResultBlock\n | TextEditorCodeExecutionToolResultBlock\n | ToolSearchToolResultBlock\n | ContainerUploadBlock;\n\n index: number;\n\n type: 'content_block_start';\n}\n\nexport interface RawContentBlockStopEvent {\n index: number;\n\n type: 'content_block_stop';\n}\n\nexport interface RawMessageDeltaEvent {\n delta: RawMessageDeltaEvent.Delta;\n\n type: 'message_delta';\n\n /**\n * Billing and rate-limit usage.\n *\n * Anthropic's API bills and rate-limits by token counts, as tokens represent the\n * underlying cost to our systems.\n *\n * Under the hood, the API transforms requests into a format suitable for the\n * model. The model's output then goes through a parsing stage before becoming an\n * API response. As a result, the token counts in `usage` will not match one-to-one\n * with the exact visible content of an API request or response.\n *\n * For example, `output_tokens` will be non-zero, even for an empty string response\n * from Claude.\n *\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n usage: MessageDeltaUsage;\n}\n\nexport namespace RawMessageDeltaEvent {\n export interface Delta {\n /**\n * Information about the container used in the request (for the code execution\n * tool)\n */\n container: MessagesAPI.Container | null;\n\n /**\n * Structured information about a refusal.\n */\n stop_details: MessagesAPI.RefusalStopDetails | null;\n\n stop_reason: MessagesAPI.StopReason | null;\n\n stop_sequence: string | null;\n }\n}\n\nexport interface RawMessageStartEvent {\n message: Message;\n\n type: 'message_start';\n}\n\nexport interface RawMessageStopEvent {\n type: 'message_stop';\n}\n\nexport type RawMessageStreamEvent =\n | RawMessageStartEvent\n | RawMessageDeltaEvent\n | RawMessageStopEvent\n | RawContentBlockStartEvent\n | RawContentBlockDeltaEvent\n | RawContentBlockStopEvent;\n\nexport interface RedactedThinkingBlock {\n data: string;\n\n type: 'redacted_thinking';\n}\n\nexport interface RedactedThinkingBlockParam {\n data: string;\n\n type: 'redacted_thinking';\n}\n\n/**\n * Structured information about a refusal.\n */\nexport interface RefusalStopDetails {\n /**\n * The policy category that triggered a refusal.\n */\n category: 'cyber' | 'bio' | 'frontier_llm' | 'reasoning_extraction' | 'military_weapons' | null;\n\n /**\n * Human-readable explanation of the refusal.\n *\n * This text is not guaranteed to be stable. `null` when no explanation is\n * available for the category.\n */\n explanation: string | null;\n\n type: 'refusal';\n}\n\nexport interface SearchResultBlockParam {\n content: Array<TextBlockParam>;\n\n source: string;\n\n title: string;\n\n type: 'search_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n citations?: CitationsConfigParam;\n}\n\n/**\n * Tool invocation generated by a server-side tool.\n */\nexport interface ServerToolCaller {\n tool_id: string;\n\n type: 'code_execution_20250825';\n}\n\nexport interface ServerToolCaller20260120 {\n tool_id: string;\n\n type: 'code_execution_20260120';\n}\n\nexport interface ServerToolUsage {\n /**\n * The number of web fetch tool requests.\n */\n web_fetch_requests: number;\n\n /**\n * The number of web search tool requests.\n */\n web_search_requests: number;\n}\n\nexport interface ServerToolUseBlock {\n id: string;\n\n /**\n * Tool invocation directly from the model.\n */\n caller: DirectCaller | ServerToolCaller | ServerToolCaller20260120;\n\n input: unknown;\n\n name:\n | 'web_search'\n | 'web_fetch'\n | 'code_execution'\n | 'bash_code_execution'\n | 'text_editor_code_execution'\n | 'tool_search_tool_regex'\n | 'tool_search_tool_bm25';\n\n type: 'server_tool_use';\n}\n\nexport interface ServerToolUseBlockParam {\n id: string;\n\n input: unknown;\n\n name:\n | 'web_search'\n | 'web_fetch'\n | 'code_execution'\n | 'bash_code_execution'\n | 'text_editor_code_execution'\n | 'tool_search_tool_regex'\n | 'tool_search_tool_bm25';\n\n type: 'server_tool_use';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: DirectCaller | ServerToolCaller | ServerToolCaller20260120;\n}\n\nexport interface SignatureDelta {\n signature: string;\n\n type: 'signature_delta';\n}\n\nexport type StopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | 'pause_turn' | 'refusal';\n\nexport interface TextBlock {\n /**\n * Citations supporting the text block.\n *\n * The type of citation returned will depend on the type of document being cited.\n * Citing a PDF results in `page_location`, plain text results in `char_location`,\n * and content document results in `content_block_location`.\n */\n citations: Array<TextCitation> | null;\n\n text: string;\n\n type: 'text';\n}\n\nexport interface TextBlockParam {\n text: string;\n\n type: 'text';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n citations?: Array<TextCitationParam> | null;\n}\n\nexport type TextCitation =\n | CitationCharLocation\n | CitationPageLocation\n | CitationContentBlockLocation\n | CitationsWebSearchResultLocation\n | CitationsSearchResultLocation;\n\nexport type TextCitationParam =\n | CitationCharLocationParam\n | CitationPageLocationParam\n | CitationContentBlockLocationParam\n | CitationWebSearchResultLocationParam\n | CitationSearchResultLocationParam;\n\nexport interface TextDelta {\n text: string;\n\n type: 'text_delta';\n}\n\nexport interface TextEditorCodeExecutionCreateResultBlock {\n is_file_update: boolean;\n\n type: 'text_editor_code_execution_create_result';\n}\n\nexport interface TextEditorCodeExecutionCreateResultBlockParam {\n is_file_update: boolean;\n\n type: 'text_editor_code_execution_create_result';\n}\n\nexport interface TextEditorCodeExecutionStrReplaceResultBlock {\n lines: Array<string> | null;\n\n new_lines: number | null;\n\n new_start: number | null;\n\n old_lines: number | null;\n\n old_start: number | null;\n\n type: 'text_editor_code_execution_str_replace_result';\n}\n\nexport interface TextEditorCodeExecutionStrReplaceResultBlockParam {\n type: 'text_editor_code_execution_str_replace_result';\n\n lines?: Array<string> | null;\n\n new_lines?: number | null;\n\n new_start?: number | null;\n\n old_lines?: number | null;\n\n old_start?: number | null;\n}\n\nexport interface TextEditorCodeExecutionToolResultBlock {\n content:\n | TextEditorCodeExecutionToolResultError\n | TextEditorCodeExecutionViewResultBlock\n | TextEditorCodeExecutionCreateResultBlock\n | TextEditorCodeExecutionStrReplaceResultBlock;\n\n tool_use_id: string;\n\n type: 'text_editor_code_execution_tool_result';\n}\n\nexport interface TextEditorCodeExecutionToolResultBlockParam {\n content:\n | TextEditorCodeExecutionToolResultErrorParam\n | TextEditorCodeExecutionViewResultBlockParam\n | TextEditorCodeExecutionCreateResultBlockParam\n | TextEditorCodeExecutionStrReplaceResultBlockParam;\n\n tool_use_id: string;\n\n type: 'text_editor_code_execution_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport interface TextEditorCodeExecutionToolResultError {\n error_code: TextEditorCodeExecutionToolResultErrorCode;\n\n error_message: string | null;\n\n type: 'text_editor_code_execution_tool_result_error';\n}\n\nexport type TextEditorCodeExecutionToolResultErrorCode =\n | 'invalid_tool_input'\n | 'unavailable'\n | 'too_many_requests'\n | 'execution_time_exceeded'\n | 'file_not_found';\n\nexport interface TextEditorCodeExecutionToolResultErrorParam {\n error_code: TextEditorCodeExecutionToolResultErrorCode;\n\n type: 'text_editor_code_execution_tool_result_error';\n\n error_message?: string | null;\n}\n\nexport interface TextEditorCodeExecutionViewResultBlock {\n content: string;\n\n file_type: 'text' | 'image' | 'pdf';\n\n num_lines: number | null;\n\n start_line: number | null;\n\n total_lines: number | null;\n\n type: 'text_editor_code_execution_view_result';\n}\n\nexport interface TextEditorCodeExecutionViewResultBlockParam {\n content: string;\n\n file_type: 'text' | 'image' | 'pdf';\n\n type: 'text_editor_code_execution_view_result';\n\n num_lines?: number | null;\n\n start_line?: number | null;\n\n total_lines?: number | null;\n}\n\nexport interface ThinkingBlock {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface ThinkingBlockParam {\n signature: string;\n\n thinking: string;\n\n type: 'thinking';\n}\n\nexport interface ThinkingConfigAdaptive {\n type: 'adaptive';\n\n /**\n * Controls how thinking content appears in the response. When set to `summarized`,\n * thinking is returned normally. When set to `omitted`, thinking content is\n * redacted but a signature is returned for multi-turn continuity. Defaults to\n * `summarized`.\n */\n display?: 'summarized' | 'omitted' | null;\n}\n\nexport interface ThinkingConfigDisabled {\n type: 'disabled';\n}\n\nexport interface ThinkingConfigEnabled {\n /**\n * Determines how many tokens Claude can use for its internal reasoning process.\n * Larger budgets can enable more thorough analysis for complex problems, improving\n * response quality.\n *\n * Must be ≥1024 and less than `max_tokens`.\n *\n * See\n * [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n budget_tokens: number;\n\n type: 'enabled';\n\n /**\n * Controls how thinking content appears in the response. When set to `summarized`,\n * thinking is returned normally. When set to `omitted`, thinking content is\n * redacted but a signature is returned for multi-turn continuity. Defaults to\n * `summarized`.\n */\n display?: 'summarized' | 'omitted' | null;\n}\n\n/**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\nexport type ThinkingConfigParam = ThinkingConfigEnabled | ThinkingConfigDisabled | ThinkingConfigAdaptive;\n\nexport interface ThinkingDelta {\n thinking: string;\n\n type: 'thinking_delta';\n}\n\nexport interface Tool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n input_schema: Tool.InputSchema;\n\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: string;\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Description of what this tool does.\n *\n * Tool descriptions should be as detailed as possible. The more information that\n * the model has about what the tool is and how to use it, the better it will\n * perform. You can use natural language descriptions to reinforce important\n * aspects of the tool input JSON schema.\n */\n description?: string;\n\n /**\n * Enable eager input streaming for this tool. When true, tool input parameters\n * will be streamed incrementally as they are generated, and types will be inferred\n * on-the-fly rather than buffering the full JSON output. When false, streaming is\n * disabled for this tool even if the fine-grained-tool-streaming beta is active.\n * When null (default), uses the default behavior based on beta headers.\n */\n eager_input_streaming?: boolean | null;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n\n type?: 'custom' | null;\n}\n\nexport namespace Tool {\n /**\n * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n *\n * This defines the shape of the `input` that your tool accepts and that the model\n * will produce.\n */\n export interface InputSchema {\n type: 'object';\n\n properties?: unknown | null;\n\n required?: Array<string> | null;\n\n [k: string]: unknown;\n }\n}\n\nexport interface ToolBash20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'bash';\n\n type: 'bash_20250124';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\nexport type ToolChoice = ToolChoiceAuto | ToolChoiceAny | ToolChoiceTool | ToolChoiceNone;\n\n/**\n * The model will use any available tools.\n */\nexport interface ToolChoiceAny {\n type: 'any';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will automatically decide whether to use tools.\n */\nexport interface ToolChoiceAuto {\n type: 'auto';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output at most one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\n/**\n * The model will not be allowed to use tools.\n */\nexport interface ToolChoiceNone {\n type: 'none';\n}\n\n/**\n * The model will use the specified tool with `tool_choice.name`.\n */\nexport interface ToolChoiceTool {\n /**\n * The name of the tool to use.\n */\n name: string;\n\n type: 'tool';\n\n /**\n * Whether to disable parallel tool use.\n *\n * Defaults to `false`. If set to `true`, the model will output exactly one tool\n * use.\n */\n disable_parallel_tool_use?: boolean;\n}\n\nexport interface ToolReferenceBlock {\n tool_name: string;\n\n type: 'tool_reference';\n}\n\n/**\n * Tool reference block that can be included in tool_result content.\n */\nexport interface ToolReferenceBlockParam {\n tool_name: string;\n\n type: 'tool_reference';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport interface ToolResultBlockParam {\n tool_use_id: string;\n\n type: 'tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n content?:\n | string\n | Array<\n | TextBlockParam\n | ImageBlockParam\n | SearchResultBlockParam\n | DocumentBlockParam\n | ToolReferenceBlockParam\n >;\n\n is_error?: boolean;\n}\n\nexport interface ToolSearchToolBm25_20251119 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'tool_search_tool_bm25';\n\n type: 'tool_search_tool_bm25_20251119' | 'tool_search_tool_bm25';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface ToolSearchToolRegex20251119 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'tool_search_tool_regex';\n\n type: 'tool_search_tool_regex_20251119' | 'tool_search_tool_regex';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface ToolSearchToolResultBlock {\n content: ToolSearchToolResultError | ToolSearchToolSearchResultBlock;\n\n tool_use_id: string;\n\n type: 'tool_search_tool_result';\n}\n\nexport interface ToolSearchToolResultBlockParam {\n content: ToolSearchToolResultErrorParam | ToolSearchToolSearchResultBlockParam;\n\n tool_use_id: string;\n\n type: 'tool_search_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n}\n\nexport interface ToolSearchToolResultError {\n error_code: ToolSearchToolResultErrorCode;\n\n error_message: string | null;\n\n type: 'tool_search_tool_result_error';\n}\n\nexport type ToolSearchToolResultErrorCode =\n | 'invalid_tool_input'\n | 'unavailable'\n | 'too_many_requests'\n | 'execution_time_exceeded';\n\nexport interface ToolSearchToolResultErrorParam {\n error_code: ToolSearchToolResultErrorCode;\n\n type: 'tool_search_tool_result_error';\n\n error_message?: string | null;\n}\n\nexport interface ToolSearchToolSearchResultBlock {\n tool_references: Array<ToolReferenceBlock>;\n\n type: 'tool_search_tool_search_result';\n}\n\nexport interface ToolSearchToolSearchResultBlockParam {\n tool_references: Array<ToolReferenceBlockParam>;\n\n type: 'tool_search_tool_search_result';\n}\n\nexport interface ToolTextEditor20250124 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'str_replace_editor';\n\n type: 'text_editor_20250124';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface ToolTextEditor20250429 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'str_replace_based_edit_tool';\n\n type: 'text_editor_20250429';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface ToolTextEditor20250728 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'str_replace_based_edit_tool';\n\n type: 'text_editor_20250728';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n input_examples?: Array<{ [key: string]: unknown }>;\n\n /**\n * Maximum number of characters to display when viewing a file. If not specified,\n * defaults to displaying the full file.\n */\n max_characters?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * Code execution tool with REPL state persistence (daemon mode + gVisor\n * checkpoint).\n */\nexport type ToolUnion =\n | Tool\n | ToolBash20250124\n | CodeExecutionTool20250522\n | CodeExecutionTool20250825\n | CodeExecutionTool20260120\n | CodeExecutionTool20260521\n | MemoryTool20250818\n | ToolTextEditor20250124\n | ToolTextEditor20250429\n | ToolTextEditor20250728\n | WebSearchTool20250305\n | WebFetchTool20250910\n | WebSearchTool20260209\n | WebFetchTool20260209\n | WebFetchTool20260309\n | ToolSearchToolBm25_20251119\n | ToolSearchToolRegex20251119;\n\nexport interface ToolUseBlock {\n id: string;\n\n /**\n * Tool invocation directly from the model.\n */\n caller: DirectCaller | ServerToolCaller | ServerToolCaller20260120;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n}\n\nexport interface ToolUseBlockParam {\n id: string;\n\n input: unknown;\n\n name: string;\n\n type: 'tool_use';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: DirectCaller | ServerToolCaller | ServerToolCaller20260120;\n}\n\nexport interface URLImageSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface URLPDFSource {\n type: 'url';\n\n url: string;\n}\n\nexport interface Usage {\n /**\n * Breakdown of cached tokens by TTL\n */\n cache_creation: CacheCreation | null;\n\n /**\n * The number of input tokens used to create the cache entry.\n */\n cache_creation_input_tokens: number | null;\n\n /**\n * The number of input tokens read from the cache.\n */\n cache_read_input_tokens: number | null;\n\n /**\n * The geographic region where inference was performed for this request.\n */\n inference_geo: string | null;\n\n /**\n * The number of input tokens which were used.\n */\n input_tokens: number;\n\n /**\n * The number of output tokens which were used.\n */\n output_tokens: number;\n\n /**\n * Breakdown of output tokens by category.\n *\n * `output_tokens` remains the inclusive, authoritative total used for billing.\n * This object provides a read-only decomposition for observability — for example,\n * how many of the billed output tokens were spent on internal reasoning that may\n * have been summarized before being returned to you.\n */\n output_tokens_details: OutputTokensDetails | null;\n\n /**\n * The number of server tool requests.\n */\n server_tool_use: ServerToolUsage | null;\n\n /**\n * If the request used the priority, standard, or batch tier.\n */\n service_tier: 'standard' | 'priority' | 'batch' | null;\n}\n\nexport interface UserLocation {\n type: 'approximate';\n\n /**\n * The city of the user.\n */\n city?: string | null;\n\n /**\n * The two letter\n * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the\n * user.\n */\n country?: string | null;\n\n /**\n * The region of the user.\n */\n region?: string | null;\n\n /**\n * The [IANA timezone](https://nodatime.org/TimeZones) of the user.\n */\n timezone?: string | null;\n}\n\nexport interface WebFetchBlock {\n content: DocumentBlock;\n\n /**\n * ISO 8601 timestamp when the content was retrieved\n */\n retrieved_at: string | null;\n\n type: 'web_fetch_result';\n\n /**\n * Fetched content URL\n */\n url: string;\n}\n\nexport interface WebFetchBlockParam {\n content: DocumentBlockParam;\n\n type: 'web_fetch_result';\n\n /**\n * Fetched content URL\n */\n url: string;\n\n /**\n * ISO 8601 timestamp when the content was retrieved\n */\n retrieved_at?: string | null;\n}\n\nexport interface WebFetchTool20250910 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_fetch';\n\n type: 'web_fetch_20250910';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * List of domains to allow fetching from\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * List of domains to block fetching from\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Citations configuration for fetched documents. Citations are disabled by\n * default.\n */\n citations?: CitationsConfigParam | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of tokens used by including web page text content in the context.\n * The limit is approximate and does not apply to binary content such as PDFs.\n */\n max_content_tokens?: number | null;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\nexport interface WebFetchTool20260209 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_fetch';\n\n type: 'web_fetch_20260209';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * List of domains to allow fetching from\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * List of domains to block fetching from\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Citations configuration for fetched documents. Citations are disabled by\n * default.\n */\n citations?: CitationsConfigParam | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of tokens used by including web page text content in the context.\n * The limit is approximate and does not apply to binary content such as PDFs.\n */\n max_content_tokens?: number | null;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n}\n\n/**\n * Web fetch tool with use_cache parameter for bypassing cached content.\n */\nexport interface WebFetchTool20260309 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_fetch';\n\n type: 'web_fetch_20260309';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * List of domains to allow fetching from\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * List of domains to block fetching from\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Citations configuration for fetched documents. Citations are disabled by\n * default.\n */\n citations?: CitationsConfigParam | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of tokens used by including web page text content in the context.\n * The limit is approximate and does not apply to binary content such as PDFs.\n */\n max_content_tokens?: number | null;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n\n /**\n * Whether to use cached content. Set to false to bypass the cache and fetch fresh\n * content. Only set to false when the user explicitly requests fresh content or\n * when fetching rapidly-changing sources.\n */\n use_cache?: boolean;\n}\n\nexport interface WebFetchToolResultBlock {\n /**\n * Tool invocation directly from the model.\n */\n caller: DirectCaller | ServerToolCaller | ServerToolCaller20260120;\n\n content: WebFetchToolResultErrorBlock | WebFetchBlock;\n\n tool_use_id: string;\n\n type: 'web_fetch_tool_result';\n}\n\nexport interface WebFetchToolResultBlockParam {\n content: WebFetchToolResultErrorBlockParam | WebFetchBlockParam;\n\n tool_use_id: string;\n\n type: 'web_fetch_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: DirectCaller | ServerToolCaller | ServerToolCaller20260120;\n}\n\nexport interface WebFetchToolResultErrorBlock {\n error_code: WebFetchToolResultErrorCode;\n\n type: 'web_fetch_tool_result_error';\n}\n\nexport interface WebFetchToolResultErrorBlockParam {\n error_code: WebFetchToolResultErrorCode;\n\n type: 'web_fetch_tool_result_error';\n}\n\nexport type WebFetchToolResultErrorCode =\n | 'invalid_tool_input'\n | 'url_too_long'\n | 'url_not_allowed'\n | 'url_not_in_prior_context'\n | 'url_not_accessible'\n | 'unsupported_content_type'\n | 'too_many_requests'\n | 'max_uses_exceeded'\n | 'unavailable';\n\nexport interface WebSearchResultBlock {\n encrypted_content: string;\n\n page_age: string | null;\n\n title: string;\n\n type: 'web_search_result';\n\n url: string;\n}\n\nexport interface WebSearchResultBlockParam {\n encrypted_content: string;\n\n title: string;\n\n type: 'web_search_result';\n\n url: string;\n\n page_age?: string | null;\n}\n\nexport interface WebSearchTool20250305 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_search';\n\n type: 'web_search_20250305';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * If provided, only these domains will be included in results. Cannot be used\n * alongside `blocked_domains`.\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * If provided, these domains will never appear in results. Cannot be used\n * alongside `allowed_domains`.\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n\n /**\n * Parameters for the user's location. Used to provide more relevant search\n * results.\n */\n user_location?: UserLocation | null;\n}\n\n// backward compat\nexport namespace WebSearchTool20250305 {\n /**\n * @deprecated Import `UserLocation` from `anthropic` directly instead of using\n * `WebSearchTool20250305.UserLocation`.\n */\n export type UserLocation = Messages.UserLocation;\n}\n\nexport interface WebSearchTool20260209 {\n /**\n * Name of the tool.\n *\n * This is how the tool will be called by the model and in `tool_use` blocks.\n */\n name: 'web_search';\n\n type: 'web_search_20260209';\n\n allowed_callers?: Array<\n 'direct' | 'code_execution_20250825' | 'code_execution_20260120' | 'code_execution_20260521'\n >;\n\n /**\n * If provided, only these domains will be included in results. Cannot be used\n * alongside `blocked_domains`.\n */\n allowed_domains?: Array<string> | null;\n\n /**\n * If provided, these domains will never appear in results. Cannot be used\n * alongside `allowed_domains`.\n */\n blocked_domains?: Array<string> | null;\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * If true, tool will not be included in initial system prompt. Only loaded when\n * returned via tool_reference from tool search.\n */\n defer_loading?: boolean;\n\n /**\n * Maximum number of times the tool can be used in the API request.\n */\n max_uses?: number | null;\n\n /**\n * When true, guarantees schema validation on tool names and inputs\n */\n strict?: boolean;\n\n /**\n * Parameters for the user's location. Used to provide more relevant search\n * results.\n */\n user_location?: UserLocation | null;\n}\n\n// backward compat\nexport namespace WebSearchTool20260209 {\n /**\n * @deprecated Import `UserLocation` from `anthropic` directly instead of using\n * `WebSearchTool20260209.UserLocation`.\n */\n export type UserLocation = Messages.UserLocation;\n}\n\nexport interface WebSearchToolRequestError {\n error_code: WebSearchToolResultErrorCode;\n\n type: 'web_search_tool_result_error';\n}\n\nexport interface WebSearchToolResultBlock {\n /**\n * Tool invocation directly from the model.\n */\n caller: DirectCaller | ServerToolCaller | ServerToolCaller20260120;\n\n content: WebSearchToolResultBlockContent;\n\n tool_use_id: string;\n\n type: 'web_search_tool_result';\n}\n\nexport type WebSearchToolResultBlockContent = WebSearchToolResultError | Array<WebSearchResultBlock>;\n\nexport interface WebSearchToolResultBlockParam {\n content: WebSearchToolResultBlockParamContent;\n\n tool_use_id: string;\n\n type: 'web_search_tool_result';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Tool invocation directly from the model.\n */\n caller?: DirectCaller | ServerToolCaller | ServerToolCaller20260120;\n}\n\nexport type WebSearchToolResultBlockParamContent =\n | Array<WebSearchResultBlockParam>\n | WebSearchToolRequestError;\n\nexport interface WebSearchToolResultError {\n error_code: WebSearchToolResultErrorCode;\n\n type: 'web_search_tool_result_error';\n}\n\nexport type WebSearchToolResultErrorCode =\n | 'invalid_tool_input'\n | 'unavailable'\n | 'max_uses_exceeded'\n | 'too_many_requests'\n | 'query_too_long'\n | 'request_too_large';\n\nexport type MessageStreamEvent = RawMessageStreamEvent;\n\nexport type MessageStartEvent = RawMessageStartEvent;\n\nexport type MessageDeltaEvent = RawMessageDeltaEvent;\n\nexport type MessageStopEvent = RawMessageStopEvent;\n\nexport type ContentBlockStartEvent = RawContentBlockStartEvent;\n\nexport type ContentBlockDeltaEvent = RawContentBlockDeltaEvent;\n\nexport type ContentBlockStopEvent = RawContentBlockStopEvent;\n\nexport type MessageCreateParams = MessageCreateParamsNonStreaming | MessageCreateParamsStreaming;\n\nexport interface MessageCreateParamsBase {\n /**\n * Body param: The maximum number of tokens to generate before stopping.\n *\n * Note that our models may stop _before_ reaching this maximum. This parameter\n * only specifies the absolute maximum number of tokens to generate.\n *\n * Set to `0` to populate the\n * [prompt cache](https://docs.claude.com/en/docs/build-with-claude/prompt-caching#pre-warming-the-cache)\n * without generating a response.\n *\n * Different models have different maximum values for this parameter. See\n * [models](https://docs.claude.com/en/docs/models-overview) for details.\n */\n max_tokens: number;\n\n /**\n * Body param: Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * See [input examples](https://docs.claude.com/en/api/messages-examples).\n *\n * Note that if you want to include a\n * [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the\n * top-level `system` parameter — there is no `\"system\"` role for input messages in\n * the Messages API.\n *\n * There is a limit of 100,000 messages in a single request.\n */\n messages: Array<MessageParam>;\n\n /**\n * Body param: The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: Model;\n\n /**\n * Body param: Top-level cache control automatically applies a cache_control marker\n * to the last cacheable block in the request.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Body param: Container identifier for reuse across requests.\n */\n container?: string | null;\n\n /**\n * Body param: Specifies the geographic region for inference processing. If not\n * specified, the workspace's `default_inference_geo` is used.\n */\n inference_geo?: string | null;\n\n /**\n * Body param: An object describing metadata about the request.\n */\n metadata?: Metadata;\n\n /**\n * Body param: Configuration options for the model's output, such as the output\n * format.\n */\n output_config?: OutputConfig;\n\n /**\n * Body param: Determines whether to use priority capacity (if available) or\n * standard capacity for this request.\n *\n * Anthropic offers different levels of service for your API requests. See\n * [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.\n */\n service_tier?: 'auto' | 'standard_only';\n\n /**\n * Body param: Custom text sequences that will cause the model to stop generating.\n *\n * Our models will normally stop when they have naturally completed their turn,\n * which will result in a response `stop_reason` of `\"end_turn\"`.\n *\n * If you want the model to stop generating when it encounters custom strings of\n * text, you can use the `stop_sequences` parameter. If the model encounters one of\n * the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"`\n * and the response `stop_sequence` value will contain the matched stop sequence.\n */\n stop_sequences?: Array<string>;\n\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.\n */\n stream?: boolean;\n\n /**\n * Body param: System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).\n */\n system?: string | Array<TextBlockParam>;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not support\n * setting temperature. A value of 1.0 of will be accepted for backwards\n * compatibility, all other values will be rejected with a 400 error.\n */\n temperature?: number;\n\n /**\n * Body param: Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: ThinkingConfigParam;\n\n /**\n * Body param: How the model should use the provided tools. The model can use a\n * specific tool, any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: ToolChoice;\n\n /**\n * Body param: Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * There are two types of tools: **client tools** and **server tools**. The\n * behavior described below applies to client tools. For\n * [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools),\n * see their individual documentation as each has its own behavior (e.g., the\n * [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.\n */\n tools?: Array<ToolUnion>;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not accept\n * top_k; any value will be rejected with a 400 error.\n */\n top_k?: number;\n\n /**\n * @deprecated Deprecated. Models released after Claude Opus 4.6 do not support\n * setting top_p. A value >= 0.99 will be accepted for backwards compatibility, all\n * other values will be rejected with a 400 error.\n */\n top_p?: number;\n\n /**\n * Header param: The user profile ID to attribute this request to. Use when acting\n * on behalf of a party other than your organization. Requires the `user-profiles`\n * beta header.\n */\n user_profile_id?: string;\n}\n\nexport namespace MessageCreateParams {\n export type MessageCreateParamsNonStreaming = MessagesAPI.MessageCreateParamsNonStreaming;\n export type MessageCreateParamsStreaming = MessagesAPI.MessageCreateParamsStreaming;\n}\n\nexport interface MessageCreateParamsNonStreaming extends MessageCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.\n */\n stream?: false;\n}\n\nexport interface MessageCreateParamsStreaming extends MessageCreateParamsBase {\n /**\n * Body param: Whether to incrementally stream the response using server-sent\n * events.\n *\n * See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.\n */\n stream: true;\n}\n\nexport type MessageStreamParams = ParseableMessageCreateParams;\n\nexport interface MessageCountTokensParams {\n /**\n * Input messages.\n *\n * Our models are trained to operate on alternating `user` and `assistant`\n * conversational turns. When creating a new `Message`, you specify the prior\n * conversational turns with the `messages` parameter, and the model then generates\n * the next `Message` in the conversation. Consecutive `user` or `assistant` turns\n * in your request will be combined into a single turn.\n *\n * Each input message must be an object with a `role` and `content`. You can\n * specify a single `user`-role message, or you can include multiple `user` and\n * `assistant` messages.\n *\n * If the final message uses the `assistant` role, the response content will\n * continue immediately from the content in that message. This can be used to\n * constrain part of the model's response.\n *\n * Example with a single `user` message:\n *\n * ```json\n * [{ \"role\": \"user\", \"content\": \"Hello, Claude\" }]\n * ```\n *\n * Example with multiple conversational turns:\n *\n * ```json\n * [\n * { \"role\": \"user\", \"content\": \"Hello there.\" },\n * { \"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\" },\n * { \"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\" }\n * ]\n * ```\n *\n * Example with a partially-filled response from Claude:\n *\n * ```json\n * [\n * {\n * \"role\": \"user\",\n * \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"\n * },\n * { \"role\": \"assistant\", \"content\": \"The best answer is (\" }\n * ]\n * ```\n *\n * Each input message `content` may be either a single `string` or an array of\n * content blocks, where each block has a specific `type`. Using a `string` for\n * `content` is shorthand for an array of one content block of type `\"text\"`. The\n * following input messages are equivalent:\n *\n * ```json\n * { \"role\": \"user\", \"content\": \"Hello, Claude\" }\n * ```\n *\n * ```json\n * { \"role\": \"user\", \"content\": [{ \"type\": \"text\", \"text\": \"Hello, Claude\" }] }\n * ```\n *\n * See [input examples](https://docs.claude.com/en/api/messages-examples).\n *\n * Note that if you want to include a\n * [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the\n * top-level `system` parameter — there is no `\"system\"` role for input messages in\n * the Messages API.\n *\n * There is a limit of 100,000 messages in a single request.\n */\n messages: Array<MessageParam>;\n\n /**\n * The model that will complete your prompt.\n *\n * See [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\n model: Model;\n\n /**\n * Top-level cache control automatically applies a cache_control marker to the last\n * cacheable block in the request.\n */\n cache_control?: CacheControlEphemeral | null;\n\n /**\n * Configuration options for the model's output, such as the output format.\n */\n output_config?: OutputConfig;\n\n /**\n * System prompt.\n *\n * A system prompt is a way of providing context and instructions to Claude, such\n * as specifying a particular goal or role. See our\n * [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).\n */\n system?: string | Array<TextBlockParam>;\n\n /**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's\n * thinking process before the final answer. Requires a minimum budget of 1,024\n * tokens and counts towards your `max_tokens` limit.\n *\n * See\n * [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking)\n * for details.\n */\n thinking?: ThinkingConfigParam;\n\n /**\n * How the model should use the provided tools. The model can use a specific tool,\n * any available tool, decide by itself, or not use tools at all.\n */\n tool_choice?: ToolChoice;\n\n /**\n * Definitions of tools that the model may use.\n *\n * If you include `tools` in your API request, the model may return `tool_use`\n * content blocks that represent the model's use of those tools. You can then run\n * those tools using the tool input generated by the model and then optionally\n * return results back to the model using `tool_result` content blocks.\n *\n * There are two types of tools: **client tools** and **server tools**. The\n * behavior described below applies to client tools. For\n * [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools),\n * see their individual documentation as each has its own behavior (e.g., the\n * [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n *\n * Each tool definition includes:\n *\n * - `name`: Name of the tool.\n * - `description`: Optional, but strongly-recommended description of the tool.\n * - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the\n * tool `input` shape that the model will produce in `tool_use` output content\n * blocks.\n *\n * For example, if you defined `tools` as:\n *\n * ```json\n * [\n * {\n * \"name\": \"get_stock_price\",\n * \"description\": \"Get the current stock price for a given ticker symbol.\",\n * \"input_schema\": {\n * \"type\": \"object\",\n * \"properties\": {\n * \"ticker\": {\n * \"type\": \"string\",\n * \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n * }\n * },\n * \"required\": [\"ticker\"]\n * }\n * }\n * ]\n * ```\n *\n * And then asked the model \"What's the S&P 500 at today?\", the model might produce\n * `tool_use` content blocks in the response like this:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_use\",\n * \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"name\": \"get_stock_price\",\n * \"input\": { \"ticker\": \"^GSPC\" }\n * }\n * ]\n * ```\n *\n * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an\n * input, and return the following back to the model in a subsequent `user`\n * message:\n *\n * ```json\n * [\n * {\n * \"type\": \"tool_result\",\n * \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n * \"content\": \"259.75 USD\"\n * }\n * ]\n * ```\n *\n * Tools can be used for workflows that include running client-side tools and\n * functions, or more generally whenever you want the model to produce a particular\n * JSON structure of output.\n *\n * See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.\n */\n tools?: Array<MessageCountTokensTool>;\n}\n\nMessages.Batches = Batches;\n\nexport declare namespace Messages {\n export {\n type Base64ImageSource as Base64ImageSource,\n type Base64PDFSource as Base64PDFSource,\n type BashCodeExecutionOutputBlock as BashCodeExecutionOutputBlock,\n type BashCodeExecutionOutputBlockParam as BashCodeExecutionOutputBlockParam,\n type BashCodeExecutionResultBlock as BashCodeExecutionResultBlock,\n type BashCodeExecutionResultBlockParam as BashCodeExecutionResultBlockParam,\n type BashCodeExecutionToolResultBlock as BashCodeExecutionToolResultBlock,\n type BashCodeExecutionToolResultBlockParam as BashCodeExecutionToolResultBlockParam,\n type BashCodeExecutionToolResultError as BashCodeExecutionToolResultError,\n type BashCodeExecutionToolResultErrorCode as BashCodeExecutionToolResultErrorCode,\n type BashCodeExecutionToolResultErrorParam as BashCodeExecutionToolResultErrorParam,\n type CacheControlEphemeral as CacheControlEphemeral,\n type CacheCreation as CacheCreation,\n type CitationCharLocation as CitationCharLocation,\n type CitationCharLocationParam as CitationCharLocationParam,\n type CitationContentBlockLocation as CitationContentBlockLocation,\n type CitationContentBlockLocationParam as CitationContentBlockLocationParam,\n type CitationPageLocation as CitationPageLocation,\n type CitationPageLocationParam as CitationPageLocationParam,\n type CitationSearchResultLocationParam as CitationSearchResultLocationParam,\n type CitationWebSearchResultLocationParam as CitationWebSearchResultLocationParam,\n type CitationsConfig as CitationsConfig,\n type CitationsConfigParam as CitationsConfigParam,\n type CitationsDelta as CitationsDelta,\n type CitationsSearchResultLocation as CitationsSearchResultLocation,\n type CitationsWebSearchResultLocation as CitationsWebSearchResultLocation,\n type CodeExecutionOutputBlock as CodeExecutionOutputBlock,\n type CodeExecutionOutputBlockParam as CodeExecutionOutputBlockParam,\n type CodeExecutionResultBlock as CodeExecutionResultBlock,\n type CodeExecutionResultBlockParam as CodeExecutionResultBlockParam,\n type CodeExecutionTool20250522 as CodeExecutionTool20250522,\n type CodeExecutionTool20250825 as CodeExecutionTool20250825,\n type CodeExecutionTool20260120 as CodeExecutionTool20260120,\n type CodeExecutionTool20260521 as CodeExecutionTool20260521,\n type CodeExecutionToolResultBlock as CodeExecutionToolResultBlock,\n type CodeExecutionToolResultBlockContent as CodeExecutionToolResultBlockContent,\n type CodeExecutionToolResultBlockParam as CodeExecutionToolResultBlockParam,\n type CodeExecutionToolResultBlockParamContent as CodeExecutionToolResultBlockParamContent,\n type CodeExecutionToolResultError as CodeExecutionToolResultError,\n type CodeExecutionToolResultErrorCode as CodeExecutionToolResultErrorCode,\n type CodeExecutionToolResultErrorParam as CodeExecutionToolResultErrorParam,\n type Container as Container,\n type ContainerUploadBlock as ContainerUploadBlock,\n type ContainerUploadBlockParam as ContainerUploadBlockParam,\n type ContentBlock as ContentBlock,\n type ContentBlockParam as ContentBlockParam,\n type ContentBlockStartEvent as ContentBlockStartEvent,\n type ContentBlockStopEvent as ContentBlockStopEvent,\n type ContentBlockSource as ContentBlockSource,\n type ContentBlockSourceContent as ContentBlockSourceContent,\n type DirectCaller as DirectCaller,\n type DocumentBlock as DocumentBlock,\n type DocumentBlockParam as DocumentBlockParam,\n type EncryptedCodeExecutionResultBlock as EncryptedCodeExecutionResultBlock,\n type EncryptedCodeExecutionResultBlockParam as EncryptedCodeExecutionResultBlockParam,\n type ImageBlockParam as ImageBlockParam,\n type InputJSONDelta as InputJSONDelta,\n type JSONOutputFormat as JSONOutputFormat,\n type MemoryTool20250818 as MemoryTool20250818,\n type Message as Message,\n type MessageCountTokensTool as MessageCountTokensTool,\n type MessageDeltaEvent as MessageDeltaEvent,\n type MessageDeltaUsage as MessageDeltaUsage,\n type MessageParam as MessageParam,\n type MessageTokensCount as MessageTokensCount,\n type Metadata as Metadata,\n type MidConversationSystemBlockParam as MidConversationSystemBlockParam,\n type Model as Model,\n type OutputConfig as OutputConfig,\n type OutputTokensDetails as OutputTokensDetails,\n type PlainTextSource as PlainTextSource,\n type RawContentBlockDelta as RawContentBlockDelta,\n type RawContentBlockDeltaEvent as RawContentBlockDeltaEvent,\n type RawContentBlockStartEvent as RawContentBlockStartEvent,\n type RawContentBlockStopEvent as RawContentBlockStopEvent,\n type RawMessageDeltaEvent as RawMessageDeltaEvent,\n type RawMessageStartEvent as RawMessageStartEvent,\n type RawMessageStopEvent as RawMessageStopEvent,\n type RawMessageStreamEvent as RawMessageStreamEvent,\n type RedactedThinkingBlock as RedactedThinkingBlock,\n type RedactedThinkingBlockParam as RedactedThinkingBlockParam,\n type RefusalStopDetails as RefusalStopDetails,\n type SearchResultBlockParam as SearchResultBlockParam,\n type ServerToolCaller as ServerToolCaller,\n type ServerToolCaller20260120 as ServerToolCaller20260120,\n type ServerToolUsage as ServerToolUsage,\n type ServerToolUseBlock as ServerToolUseBlock,\n type ServerToolUseBlockParam as ServerToolUseBlockParam,\n type SignatureDelta as SignatureDelta,\n type StopReason as StopReason,\n type TextBlock as TextBlock,\n type TextBlockParam as TextBlockParam,\n type TextCitation as TextCitation,\n type TextCitationParam as TextCitationParam,\n type TextDelta as TextDelta,\n type TextEditorCodeExecutionCreateResultBlock as TextEditorCodeExecutionCreateResultBlock,\n type TextEditorCodeExecutionCreateResultBlockParam as TextEditorCodeExecutionCreateResultBlockParam,\n type TextEditorCodeExecutionStrReplaceResultBlock as TextEditorCodeExecutionStrReplaceResultBlock,\n type TextEditorCodeExecutionStrReplaceResultBlockParam as TextEditorCodeExecutionStrReplaceResultBlockParam,\n type TextEditorCodeExecutionToolResultBlock as TextEditorCodeExecutionToolResultBlock,\n type TextEditorCodeExecutionToolResultBlockParam as TextEditorCodeExecutionToolResultBlockParam,\n type TextEditorCodeExecutionToolResultError as TextEditorCodeExecutionToolResultError,\n type TextEditorCodeExecutionToolResultErrorCode as TextEditorCodeExecutionToolResultErrorCode,\n type TextEditorCodeExecutionToolResultErrorParam as TextEditorCodeExecutionToolResultErrorParam,\n type TextEditorCodeExecutionViewResultBlock as TextEditorCodeExecutionViewResultBlock,\n type TextEditorCodeExecutionViewResultBlockParam as TextEditorCodeExecutionViewResultBlockParam,\n type ThinkingBlock as ThinkingBlock,\n type ThinkingBlockParam as ThinkingBlockParam,\n type ThinkingConfigAdaptive as ThinkingConfigAdaptive,\n type ThinkingConfigDisabled as ThinkingConfigDisabled,\n type ThinkingConfigEnabled as ThinkingConfigEnabled,\n type ThinkingConfigParam as ThinkingConfigParam,\n type ThinkingDelta as ThinkingDelta,\n type Tool as Tool,\n type ToolBash20250124 as ToolBash20250124,\n type ToolChoice as ToolChoice,\n type ToolChoiceAny as ToolChoiceAny,\n type ToolChoiceAuto as ToolChoiceAuto,\n type ToolChoiceNone as ToolChoiceNone,\n type ToolChoiceTool as ToolChoiceTool,\n type ToolReferenceBlock as ToolReferenceBlock,\n type ToolReferenceBlockParam as ToolReferenceBlockParam,\n type ToolResultBlockParam as ToolResultBlockParam,\n type ToolSearchToolBm25_20251119 as ToolSearchToolBm25_20251119,\n type ToolSearchToolRegex20251119 as ToolSearchToolRegex20251119,\n type ToolSearchToolResultBlock as ToolSearchToolResultBlock,\n type ToolSearchToolResultBlockParam as ToolSearchToolResultBlockParam,\n type ToolSearchToolResultError as ToolSearchToolResultError,\n type ToolSearchToolResultErrorCode as ToolSearchToolResultErrorCode,\n type ToolSearchToolResultErrorParam as ToolSearchToolResultErrorParam,\n type ToolSearchToolSearchResultBlock as ToolSearchToolSearchResultBlock,\n type ToolSearchToolSearchResultBlockParam as ToolSearchToolSearchResultBlockParam,\n type ToolTextEditor20250124 as ToolTextEditor20250124,\n type ToolTextEditor20250429 as ToolTextEditor20250429,\n type ToolTextEditor20250728 as ToolTextEditor20250728,\n type ToolUnion as ToolUnion,\n type ToolUseBlock as ToolUseBlock,\n type ToolUseBlockParam as ToolUseBlockParam,\n type URLImageSource as URLImageSource,\n type URLPDFSource as URLPDFSource,\n type Usage as Usage,\n type UserLocation as UserLocation,\n type WebFetchBlock as WebFetchBlock,\n type WebFetchBlockParam as WebFetchBlockParam,\n type WebFetchTool20250910 as WebFetchTool20250910,\n type WebFetchTool20260209 as WebFetchTool20260209,\n type WebFetchTool20260309 as WebFetchTool20260309,\n type WebFetchToolResultBlock as WebFetchToolResultBlock,\n type WebFetchToolResultBlockParam as WebFetchToolResultBlockParam,\n type WebFetchToolResultErrorBlock as WebFetchToolResultErrorBlock,\n type WebFetchToolResultErrorBlockParam as WebFetchToolResultErrorBlockParam,\n type WebFetchToolResultErrorCode as WebFetchToolResultErrorCode,\n type WebSearchResultBlock as WebSearchResultBlock,\n type WebSearchResultBlockParam as WebSearchResultBlockParam,\n type WebSearchTool20250305 as WebSearchTool20250305,\n type WebSearchTool20260209 as WebSearchTool20260209,\n type WebSearchToolRequestError as WebSearchToolRequestError,\n type WebSearchToolResultBlock as WebSearchToolResultBlock,\n type WebSearchToolResultBlockContent as WebSearchToolResultBlockContent,\n type WebSearchToolResultBlockParam as WebSearchToolResultBlockParam,\n type WebSearchToolResultBlockParamContent as WebSearchToolResultBlockParamContent,\n type WebSearchToolResultError as WebSearchToolResultError,\n type MessageStreamEvent as MessageStreamEvent,\n type MessageStartEvent as MessageStartEvent,\n type MessageStopEvent as MessageStopEvent,\n type ContentBlockDeltaEvent as ContentBlockDeltaEvent,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageStreamParams as MessageStreamParams,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export {\n Batches as Batches,\n type DeletedMessageBatch as DeletedMessageBatch,\n type MessageBatch as MessageBatch,\n type MessageBatchCanceledResult as MessageBatchCanceledResult,\n type MessageBatchErroredResult as MessageBatchErroredResult,\n type MessageBatchExpiredResult as MessageBatchExpiredResult,\n type MessageBatchIndividualResponse as MessageBatchIndividualResponse,\n type MessageBatchRequestCounts as MessageBatchRequestCounts,\n type MessageBatchResult as MessageBatchResult,\n type MessageBatchSucceededResult as MessageBatchSucceededResult,\n type MessageBatchesPage as MessageBatchesPage,\n type BatchCreateParams as BatchCreateParams,\n type BatchListParams as BatchListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../core/resource';\nimport * as BetaAPI from './beta/beta';\nimport { APIPromise } from '../core/api-promise';\nimport { Page, type PageParams, PagePromise } from '../core/pagination';\nimport { buildHeaders } from '../internal/headers';\nimport { RequestOptions } from '../internal/request-options';\nimport { path } from '../internal/utils/path';\n\nexport class Models extends APIResource {\n /**\n * Get a specific model.\n *\n * The Models API response can be used to determine information about a specific\n * model or resolve a model alias to a model ID.\n */\n retrieve(\n modelID: string,\n params: ModelRetrieveParams | null | undefined = {},\n options?: RequestOptions,\n ): APIPromise<ModelInfo> {\n const { betas } = params ?? {};\n return this._client.get(path`/v1/models/${modelID}`, {\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n });\n }\n\n /**\n * List available models.\n *\n * The Models API response can be used to determine which models are available for\n * use in the API. More recently released models are listed first.\n */\n list(\n params: ModelListParams | null | undefined = {},\n options?: RequestOptions,\n ): PagePromise<ModelInfosPage, ModelInfo> {\n const { betas, ...query } = params ?? {};\n return this._client.getAPIList('/v1/models', Page<ModelInfo>, {\n query,\n ...options,\n headers: buildHeaders([\n { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\n options?.headers,\n ]),\n });\n }\n}\n\nexport type ModelInfosPage = Page<ModelInfo>;\n\n/**\n * Indicates whether a capability is supported.\n */\nexport interface CapabilitySupport {\n /**\n * Whether this capability is supported by the model.\n */\n supported: boolean;\n}\n\n/**\n * Context management capability details.\n */\nexport interface ContextManagementCapability {\n /**\n * Indicates whether a capability is supported.\n */\n clear_thinking_20251015: CapabilitySupport | null;\n\n /**\n * Indicates whether a capability is supported.\n */\n clear_tool_uses_20250919: CapabilitySupport | null;\n\n /**\n * Indicates whether a capability is supported.\n */\n compact_20260112: CapabilitySupport | null;\n\n /**\n * Whether this capability is supported by the model.\n */\n supported: boolean;\n}\n\n/**\n * Effort (reasoning_effort) capability details.\n */\nexport interface EffortCapability {\n /**\n * Whether the model supports high effort level.\n */\n high: CapabilitySupport;\n\n /**\n * Whether the model supports low effort level.\n */\n low: CapabilitySupport;\n\n /**\n * Whether the model supports max effort level.\n */\n max: CapabilitySupport;\n\n /**\n * Whether the model supports medium effort level.\n */\n medium: CapabilitySupport;\n\n /**\n * Whether this capability is supported by the model.\n */\n supported: boolean;\n\n /**\n * Indicates whether a capability is supported.\n */\n xhigh: CapabilitySupport | null;\n}\n\n/**\n * Model capability information.\n */\nexport interface ModelCapabilities {\n /**\n * Whether the model supports the Batch API.\n */\n batch: CapabilitySupport;\n\n /**\n * Whether the model supports citation generation.\n */\n citations: CapabilitySupport;\n\n /**\n * Whether the model supports code execution tools.\n */\n code_execution: CapabilitySupport;\n\n /**\n * Context management support and available strategies.\n */\n context_management: ContextManagementCapability;\n\n /**\n * Effort (reasoning_effort) support and available levels.\n */\n effort: EffortCapability;\n\n /**\n * Whether the model accepts image content blocks.\n */\n image_input: CapabilitySupport;\n\n /**\n * Whether the model accepts PDF content blocks.\n */\n pdf_input: CapabilitySupport;\n\n /**\n * Whether the model supports structured output / JSON mode / strict tool schemas.\n */\n structured_outputs: CapabilitySupport;\n\n /**\n * Thinking capability and supported type configurations.\n */\n thinking: ThinkingCapability;\n}\n\nexport interface ModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\n\n /**\n * Model capability information.\n */\n capabilities: ModelCapabilities | null;\n\n /**\n * RFC 3339 datetime string representing the time at which the model was released.\n * May be set to an epoch value if the release date is unknown.\n */\n created_at: string;\n\n /**\n * A human-readable name for the model.\n */\n display_name: string;\n\n /**\n * Maximum input context window size in tokens for this model.\n */\n max_input_tokens: number | null;\n\n /**\n * Maximum value for the `max_tokens` parameter when using this model.\n */\n max_tokens: number | null;\n\n /**\n * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\n}\n\n/**\n * Thinking capability details.\n */\nexport interface ThinkingCapability {\n /**\n * Whether this capability is supported by the model.\n */\n supported: boolean;\n\n /**\n * Supported thinking type configurations.\n */\n types: ThinkingTypes;\n}\n\n/**\n * Supported thinking type configurations.\n */\nexport interface ThinkingTypes {\n /**\n * Whether the model supports thinking with type 'adaptive' (auto).\n */\n adaptive: CapabilitySupport;\n\n /**\n * Whether the model supports thinking with type 'enabled'.\n */\n enabled: CapabilitySupport;\n}\n\nexport interface ModelRetrieveParams {\n /**\n * Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport interface ModelListParams extends PageParams {\n /**\n * Header param: Optional header to specify the beta version(s) you want to use.\n */\n betas?: Array<BetaAPI.AnthropicBeta>;\n}\n\nexport declare namespace Models {\n export {\n type CapabilitySupport as CapabilitySupport,\n type ContextManagementCapability as ContextManagementCapability,\n type EffortCapability as EffortCapability,\n type ModelCapabilities as ModelCapabilities,\n type ModelInfo as ModelInfo,\n type ThinkingCapability as ThinkingCapability,\n type ThinkingTypes as ThinkingTypes,\n type ModelInfosPage as ModelInfosPage,\n type ModelRetrieveParams as ModelRetrieveParams,\n type ModelListParams as ModelListParams,\n };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport type { RequestInit, RequestInfo, BodyInit } from './internal/builtin-types';\nimport type { HTTPMethod, PromiseOrValue, MergedRequestInit, FinalizedRequestInit } from './internal/types';\nimport { uuid4 } from './internal/utils/uuid';\nimport { validatePositiveInteger, isAbsoluteURL, safeJSON } from './internal/utils/values';\nimport { sleep } from './internal/utils/sleep';\nexport type { Logger, LogLevel } from './internal/utils/log';\nimport { castToError, isAbortError } from './internal/errors';\nimport type { APIResponseProps } from './internal/parse';\nimport { getPlatformHeaders } from './internal/detect-platform';\nimport * as Shims from './internal/shims';\nimport * as Opts from './internal/request-options';\nimport { stringifyQuery } from './internal/utils/query';\nimport { VERSION } from './version';\nimport * as Errors from './core/error';\nimport type { AccessTokenProvider } from './lib/credentials/types';\nimport { OAUTH_API_BETA_HEADER } from './lib/credentials/types';\nimport { TokenCache } from './lib/credentials/token-cache';\nimport { defaultCredentials, resolveCredentialsFromConfig } from './lib/credentials/credential-chain';\nimport type { AnthropicConfig } from './core/credentials';\nimport {\n type Middleware,\n isFetchOriginError,\n isRetryableError,\n wrapFetchWithMiddleware,\n} from './core/middleware';\nexport type { Middleware, MiddlewareContext, MiddlewareNext } from './core/middleware';\nexport type { APIRequest } from './core/api';\nimport * as Pagination from './core/pagination';\nimport {\n type PageCursorParams,\n PageCursorResponse,\n type PageParams,\n PageResponse,\n type TokenPageParams,\n TokenPageResponse,\n} from './core/pagination';\nimport * as Uploads from './core/uploads';\nimport * as API from './resources/index';\nimport { APIPromise } from './core/api-promise';\nimport {\n Completion,\n CompletionCreateParams,\n CompletionCreateParamsNonStreaming,\n CompletionCreateParamsStreaming,\n Completions,\n} from './resources/completions';\nimport {\n CapabilitySupport,\n ContextManagementCapability,\n EffortCapability,\n ModelCapabilities,\n ModelInfo,\n ModelInfosPage,\n ModelListParams,\n ModelRetrieveParams,\n Models,\n ThinkingCapability,\n ThinkingTypes,\n} from './resources/models';\nimport {\n AnthropicBeta,\n Beta,\n BetaAPIError,\n BetaAuthenticationError,\n BetaBillingError,\n BetaError,\n BetaErrorResponse,\n BetaGatewayTimeoutError,\n BetaInvalidRequestError,\n BetaNotFoundError,\n BetaOverloadedError,\n BetaPermissionError,\n BetaRateLimitError,\n} from './resources/beta/beta';\nimport {\n Base64ImageSource,\n Base64PDFSource,\n BashCodeExecutionOutputBlock,\n BashCodeExecutionOutputBlockParam,\n BashCodeExecutionResultBlock,\n BashCodeExecutionResultBlockParam,\n BashCodeExecutionToolResultBlock,\n BashCodeExecutionToolResultBlockParam,\n BashCodeExecutionToolResultError,\n BashCodeExecutionToolResultErrorCode,\n BashCodeExecutionToolResultErrorParam,\n CacheControlEphemeral,\n CacheCreation,\n CitationCharLocation,\n CitationCharLocationParam,\n CitationContentBlockLocation,\n CitationContentBlockLocationParam,\n CitationPageLocation,\n CitationPageLocationParam,\n CitationSearchResultLocationParam,\n CitationWebSearchResultLocationParam,\n CitationsConfig,\n CitationsConfigParam,\n CitationsDelta,\n CitationsSearchResultLocation,\n CitationsWebSearchResultLocation,\n CodeExecutionOutputBlock,\n CodeExecutionOutputBlockParam,\n CodeExecutionResultBlock,\n CodeExecutionResultBlockParam,\n CodeExecutionTool20250522,\n CodeExecutionTool20250825,\n CodeExecutionTool20260120,\n CodeExecutionTool20260521,\n CodeExecutionToolResultBlock,\n CodeExecutionToolResultBlockContent,\n CodeExecutionToolResultBlockParam,\n CodeExecutionToolResultBlockParamContent,\n CodeExecutionToolResultError,\n CodeExecutionToolResultErrorCode,\n CodeExecutionToolResultErrorParam,\n Container,\n ContainerUploadBlock,\n ContainerUploadBlockParam,\n ContentBlock,\n ContentBlockDeltaEvent,\n ContentBlockParam,\n ContentBlockStartEvent,\n ContentBlockStopEvent,\n ContentBlockSource,\n ContentBlockSourceContent,\n DirectCaller,\n DocumentBlock,\n DocumentBlockParam,\n EncryptedCodeExecutionResultBlock,\n EncryptedCodeExecutionResultBlockParam,\n ImageBlockParam,\n InputJSONDelta,\n JSONOutputFormat,\n MemoryTool20250818,\n Message,\n MessageStreamParams,\n MessageCountTokensParams,\n MessageCountTokensTool,\n MessageCreateParams,\n MessageCreateParamsNonStreaming,\n MessageCreateParamsStreaming,\n MessageDeltaEvent,\n MessageDeltaUsage,\n MessageParam,\n MessageStartEvent,\n MessageStopEvent,\n MessageStreamEvent,\n MessageTokensCount,\n Messages,\n Metadata,\n MidConversationSystemBlockParam,\n Model,\n OutputConfig,\n OutputTokensDetails,\n PlainTextSource,\n RawContentBlockDelta,\n RawContentBlockDeltaEvent,\n RawContentBlockStartEvent,\n RawContentBlockStopEvent,\n RawMessageDeltaEvent,\n RawMessageStartEvent,\n RawMessageStopEvent,\n RawMessageStreamEvent,\n RedactedThinkingBlock,\n RedactedThinkingBlockParam,\n RefusalStopDetails,\n SearchResultBlockParam,\n ServerToolCaller,\n ServerToolCaller20260120,\n ServerToolUsage,\n ServerToolUseBlock,\n ServerToolUseBlockParam,\n SignatureDelta,\n StopReason,\n TextBlock,\n TextBlockParam,\n TextCitation,\n TextCitationParam,\n TextDelta,\n TextEditorCodeExecutionCreateResultBlock,\n TextEditorCodeExecutionCreateResultBlockParam,\n TextEditorCodeExecutionStrReplaceResultBlock,\n TextEditorCodeExecutionStrReplaceResultBlockParam,\n TextEditorCodeExecutionToolResultBlock,\n TextEditorCodeExecutionToolResultBlockParam,\n TextEditorCodeExecutionToolResultError,\n TextEditorCodeExecutionToolResultErrorCode,\n TextEditorCodeExecutionToolResultErrorParam,\n TextEditorCodeExecutionViewResultBlock,\n TextEditorCodeExecutionViewResultBlockParam,\n ThinkingBlock,\n ThinkingBlockParam,\n ThinkingConfigAdaptive,\n ThinkingConfigDisabled,\n ThinkingConfigEnabled,\n ThinkingConfigParam,\n ThinkingDelta,\n Tool,\n ToolBash20250124,\n ToolChoice,\n ToolChoiceAny,\n ToolChoiceAuto,\n ToolChoiceNone,\n ToolChoiceTool,\n ToolReferenceBlock,\n ToolReferenceBlockParam,\n ToolResultBlockParam,\n ToolSearchToolBm25_20251119,\n ToolSearchToolRegex20251119,\n ToolSearchToolResultBlock,\n ToolSearchToolResultBlockParam,\n ToolSearchToolResultError,\n ToolSearchToolResultErrorCode,\n ToolSearchToolResultErrorParam,\n ToolSearchToolSearchResultBlock,\n ToolSearchToolSearchResultBlockParam,\n ToolTextEditor20250124,\n ToolTextEditor20250429,\n ToolTextEditor20250728,\n ToolUnion,\n ToolUseBlock,\n ToolUseBlockParam,\n URLImageSource,\n URLPDFSource,\n Usage,\n UserLocation,\n WebFetchBlock,\n WebFetchBlockParam,\n WebFetchTool20250910,\n WebFetchTool20260209,\n WebFetchTool20260309,\n WebFetchToolResultBlock,\n WebFetchToolResultBlockParam,\n WebFetchToolResultErrorBlock,\n WebFetchToolResultErrorBlockParam,\n WebFetchToolResultErrorCode,\n WebSearchResultBlock,\n WebSearchResultBlockParam,\n WebSearchTool20250305,\n WebSearchTool20260209,\n WebSearchToolRequestError,\n WebSearchToolResultBlock,\n WebSearchToolResultBlockContent,\n WebSearchToolResultBlockParam,\n WebSearchToolResultBlockParamContent,\n WebSearchToolResultError,\n WebSearchToolResultErrorCode,\n} from './resources/messages/messages';\nimport { type Fetch } from './internal/builtin-types';\nimport { isRunningInBrowser } from './internal/detect-platform';\nimport { HeadersLike, NullableHeaders, buildHeaders } from './internal/headers';\nimport { FinalRequestOptions, RequestOptions } from './internal/request-options';\nimport { readEnv } from './internal/utils/env';\nimport {\n type LogLevel,\n type Logger,\n defaultLogLevel,\n formatRequestDetails,\n loggerFor,\n parseLogLevel,\n} from './internal/utils/log';\nimport { isEmptyObj } from './internal/utils/values';\n\n/**\n * Shared auth state. A `withOptions()` clone receives the parent's instance\n * (unless the caller overrides auth options) so a clone created before lazy\n * resolution settles observes the same provider/tokenCache/error/extraHeaders\n * as the parent rather than starting an independent resolution.\n */\ntype AuthState = {\n provider: AccessTokenProvider | null;\n tokenCache: TokenCache | null;\n resolution: Promise<void> | null;\n error: unknown;\n extraHeaders: Record<string, string>;\n /**\n * `base_url` from the resolved profile/config, normalized (no trailing\n * slash). Stored on the shared auth state so `withOptions()` clones created\n * before lazy resolution settles can still adopt it on their first request.\n */\n baseURL?: string | undefined;\n};\n\n/**\n * Per-request auth flags, keyed by the FinalRequestOptions object so\n * caller-owned options aren't mutated.\n */\ntype RequestAuthFlags = {\n usedTokenCache: boolean;\n didRefreshFor401: boolean;\n};\n\ntype InternalClientOptions = ClientOptions & {\n __auth?: AuthState | undefined;\n __baseURLIsExplicit?: boolean | undefined;\n};\n\nexport type ApiKeySetter = () => Promise<string>;\n\nexport interface ClientOptions {\n /**\n * API key used for authentication.\n *\n * - Accepts either a static string or an async function that resolves to a string.\n * - Defaults to process.env['ANTHROPIC_API_KEY'].\n * - When a function is provided, it is invoked before each request so you can rotate\n * or refresh credentials at runtime.\n * - The function must return a non-empty string; otherwise an AnthropicError is thrown.\n * - If the function throws, the error is wrapped in an AnthropicError with the original\n * error available as `cause`.\n */\n apiKey?: string | ApiKeySetter | null | undefined;\n\n /**\n * Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].\n */\n authToken?: string | null | undefined;\n\n /**\n * An {@link AccessTokenProvider} for OAuth/workload-identity authentication.\n *\n * When set, the provider is wrapped in a {@link TokenCache} and used for\n * Bearer token auth on every request. Takes precedence over `authToken`\n * but not `apiKey`.\n *\n * If omitted (and no `apiKey` or `authToken` is provided), the client\n * automatically resolves credentials from config files or environment\n * variables on the first request.\n */\n credentials?: AccessTokenProvider | null | undefined;\n\n /**\n * An {@link AnthropicConfig} object to resolve credentials from directly,\n * bypassing config-file and environment-variable lookup. This is the\n * TypeScript equivalent of Go's `option.WithConfig(cfg)`.\n *\n * Ignored when `credentials` is set. For `oidc_federation`, the SDK\n * performs the jwt-bearer exchange in-process; for `user_oauth`,\n * `authentication.credentials_path` must point at the credentials file.\n */\n config?: AnthropicConfig | null | undefined;\n\n /**\n * Name of a profile to load from `<config_dir>/configs/<profile>.json`.\n *\n * Equivalent to setting the `ANTHROPIC_PROFILE` environment variable, but\n * scoped to this client instance. As an explicit constructor argument it\n * takes precedence over `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` in the\n * environment. Mutually exclusive with `credentials` and `config`.\n */\n profile?: string | null | undefined;\n\n /**\n * Defaults to process.env['ANTHROPIC_WEBHOOK_SIGNING_KEY'].\n */\n webhookKey?: string | null | undefined;\n\n /**\n * Override the default base URL for the API, e.g., \"https://api.example.com/v2/\"\n *\n * Defaults to process.env['ANTHROPIC_BASE_URL'].\n */\n baseURL?: string | null | undefined;\n\n /**\n * The maximum amount of time (in milliseconds) that the client should wait for a response\n * from the server before timing out a single request.\n *\n * Note that request timeouts are retried by default, so in a worst-case scenario you may wait\n * much longer than this timeout before the promise succeeds or fails.\n *\n * @unit milliseconds\n */\n timeout?: number | undefined;\n /**\n * Additional `RequestInit` options to be passed to `fetch` calls.\n * Properties will be overridden by per-request `fetchOptions`.\n */\n fetchOptions?: MergedRequestInit | undefined;\n\n /**\n * Specify a custom `fetch` function implementation.\n *\n * If not provided, we expect that `fetch` is defined globally.\n */\n fetch?: Fetch | undefined;\n\n /**\n * {@link Middleware} functions that wrap every HTTP request made by the\n * client.\n *\n * Middleware runs per HTTP attempt, including retries. It observes the\n * canonical Anthropic-shaped request and response on every backend: on\n * clients for third-party backends (Bedrock, Vertex, Foundry), the\n * backend's URL/body rewriting, request signing, and response\n * normalization happen inside `next`.\n */\n middleware?: ReadonlyArray<Middleware> | undefined;\n\n /**\n * The maximum number of times that the client will retry a request in case of a\n * temporary failure, like a network error or a 5XX error from the server.\n *\n * @default 2\n */\n maxRetries?: number | undefined;\n\n /**\n * Default headers to include with every request to the API.\n *\n * These can be removed in individual requests by explicitly setting the\n * header to `null` in request options.\n */\n defaultHeaders?: HeadersLike | undefined;\n\n /**\n * Default query parameters to include with every request to the API.\n *\n * These can be removed in individual requests by explicitly setting the\n * param to `undefined` in request options.\n */\n defaultQuery?: Record<string, string | undefined> | undefined;\n\n /**\n * By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n * Only set this option to `true` if you understand the risks and have appropriate mitigations in place.\n */\n dangerouslyAllowBrowser?: boolean | undefined;\n\n /**\n * Set the log level.\n *\n * Defaults to process.env['ANTHROPIC_LOG'] or 'warn' if it isn't set.\n */\n logLevel?: LogLevel | undefined;\n\n /**\n * Set the logger.\n *\n * Defaults to globalThis.console.\n */\n logger?: Logger | undefined;\n}\n\nexport const HUMAN_PROMPT = '\\\\n\\\\nHuman:';\nexport const AI_PROMPT = '\\\\n\\\\nAssistant:';\n\n/**\n * Base class for Anthropic API clients.\n */\nexport class BaseAnthropic {\n apiKey: string | null;\n authToken: string | null;\n webhookKey: string | null;\n\n /**\n * The active credential provider. Default credential resolution runs once\n * at construction time. If it fails, the error is surfaced on every\n * request and the client must be reconstructed — there is no retry path.\n *\n * Clones returned by {@link withOptions} share the parent's auth state\n * (provider, token cache, pending resolution, and any resolution error)\n * unless the caller passes an explicit `apiKey`, `authToken`,\n * `credentials`, `config`, or `profile` override.\n */\n get credentials(): AccessTokenProvider | null {\n return this._authState.provider;\n }\n private _authState: AuthState;\n private _baseURLIsExplicit: boolean;\n private _requestAuthFlags = new WeakMap<FinalRequestOptions, RequestAuthFlags>();\n\n baseURL: string;\n maxRetries: number;\n timeout: number;\n logger: Logger;\n logLevel: LogLevel | undefined;\n fetchOptions: MergedRequestInit | undefined;\n middleware: ReadonlyArray<Middleware>;\n\n private fetch: Fetch;\n #encoder: Opts.RequestEncoder;\n protected idempotencyHeader?: string;\n protected _options: ClientOptions;\n\n /**\n * API Client for interfacing with the Anthropic API.\n *\n * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]\n * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]\n * @param {string | null | undefined} [opts.webhookKey=process.env['ANTHROPIC_WEBHOOK_SIGNING_KEY'] ?? null]\n * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.\n * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @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.\n */\n constructor({\n baseURL = readEnv('ANTHROPIC_BASE_URL'),\n apiKey,\n authToken,\n webhookKey = readEnv('ANTHROPIC_WEBHOOK_SIGNING_KEY') ?? null,\n ...opts\n }: ClientOptions = {}) {\n // An explicit `profile` is a constructor-level credential choice; when set,\n // do not let env ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN shadow it.\n if (apiKey === undefined) {\n apiKey = opts.profile != null ? null : readEnv('ANTHROPIC_API_KEY') ?? null;\n }\n if (authToken === undefined) {\n authToken = opts.profile != null ? null : readEnv('ANTHROPIC_AUTH_TOKEN') ?? null;\n }\n if (opts.profile != null && (opts.credentials != null || opts.config != null)) {\n throw new TypeError('Pass at most one of `profile`, `credentials`, or `config`.');\n }\n const options: ClientOptions = {\n apiKey,\n authToken,\n webhookKey,\n ...opts,\n baseURL: baseURL || `https://api.anthropic.com`,\n };\n\n if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {\n throw new Errors.AnthropicError(\n \"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\",\n );\n }\n\n this.baseURL = options.baseURL!;\n // After destructuring, `baseURL` is the constructor arg or\n // ANTHROPIC_BASE_URL — both count as an explicit choice that a profile\n // base_url must not override. A falsy value means we fell through to the\n // hardcoded default above and a profile may supply the host. withOptions()\n // propagates the parent's flag via __baseURLIsExplicit so a non-overriding\n // clone doesn't mistake the inherited baseURL for a caller-supplied one.\n this._baseURLIsExplicit = (opts as InternalClientOptions).__baseURLIsExplicit ?? !!baseURL;\n this.timeout = options.timeout ?? BaseAnthropic.DEFAULT_TIMEOUT /* 10 minutes */;\n this.logger = options.logger ?? console;\n // Set default logLevel early so that we can log a warning in parseLogLevel.\n this.logLevel = defaultLogLevel;\n this.logLevel =\n parseLogLevel(options.logLevel, 'ClientOptions.logLevel', loggerFor(this)) ??\n parseLogLevel(readEnv('ANTHROPIC_LOG'), \"process.env['ANTHROPIC_LOG']\", loggerFor(this)) ??\n defaultLogLevel;\n this.fetchOptions = options.fetchOptions;\n this.maxRetries = options.maxRetries ?? 2;\n this.fetch = options.fetch ?? Shims.getDefaultFetch();\n this.#encoder = Opts.FallbackEncoder;\n\n this.middleware = [...(options.middleware ?? [])];\n\n const customHeadersEnv = readEnv('ANTHROPIC_CUSTOM_HEADERS');\n if (customHeadersEnv) {\n const parsed: Record<string, string> = {};\n for (const line of customHeadersEnv.split('\\n')) {\n const colon = line.indexOf(':');\n if (colon >= 0) {\n parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();\n }\n }\n options.defaultHeaders = { ...parsed, ...options.defaultHeaders };\n }\n\n const inherited = (opts as InternalClientOptions).__auth;\n // Never persist the internal __auth handle on _options — it's a\n // one-shot constructor signal, and leaking it through _options would\n // cause withOptions() to spread a stale value into clones.\n delete (options as InternalClientOptions).__auth;\n delete (options as InternalClientOptions).__baseURLIsExplicit;\n this._options = options;\n\n this.apiKey = typeof apiKey === 'string' ? apiKey : null;\n this.authToken = authToken;\n this.webhookKey = webhookKey;\n\n if (inherited) {\n this._authState = inherited;\n if (!this._baseURLIsExplicit && inherited.baseURL) {\n this.baseURL = inherited.baseURL;\n }\n } else {\n this._authState = { provider: null, tokenCache: null, resolution: null, error: null, extraHeaders: {} };\n\n // apiKey/authToken win over credentials/config/profile; don't build a\n // token cache or resolve a config that the request path will then ignore.\n if (this.apiKey == null && this.authToken == null) {\n const credentials = options.credentials ?? null;\n if (credentials) {\n this._authState.provider = credentials;\n this._authState.tokenCache = this._makeTokenCache(credentials);\n } else if (options.config != null) {\n const result = resolveCredentialsFromConfig(options.config, this._credentialResolverOptions());\n this._authState.provider = result.provider;\n this._authState.tokenCache = this._makeTokenCache(result.provider);\n this._authState.extraHeaders = result.extraHeaders;\n this._applyCredentialBaseURL(result.baseURL);\n } else if (options.profile != null) {\n this._authState.resolution = this._resolveDefaultCredentials(options.profile);\n } else {\n // No explicit auth provided — lazily resolve from the credential\n // chain on first request. Errors are captured into _auth.error and\n // surfaced on first use rather than as an unhandled rejection.\n this._authState.resolution = this._resolveDefaultCredentials();\n }\n }\n }\n }\n\n /**\n * Stores a profile/config-supplied base URL on the shared auth state and, if\n * the caller did not pin `baseURL` via constructor option or env, adopts it\n * as this client's outbound API host. Precedence: ctor opt > env > profile >\n * hardcoded default.\n */\n private _applyCredentialBaseURL(baseURL: string | undefined): void {\n if (!baseURL) return;\n const normalized = baseURL.replace(/\\/+$/, '');\n this._authState.baseURL = normalized;\n if (!this._baseURLIsExplicit) {\n this.baseURL = normalized;\n }\n }\n\n /**\n * Options bag passed into the credential chain. `baseURL` here is only the\n * fallback host for the token-exchange POST when the config itself omits\n * `base_url`; the chain returns the config's own `base_url` (if any) on\n * {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL}\n * then adopts for outbound API requests. The two are deliberately decoupled\n * so this fallback never round-trips into precedence.\n */\n private _credentialResolverOptions() {\n return {\n baseURL: this.baseURL,\n fetch: this._credentialsFetch(),\n userAgent: this.getUserAgent(),\n onCacheWriteError: (err: unknown) => {\n loggerFor(this).debug('credential cache write failed (best-effort)', err);\n },\n onSafetyWarning: (msg: string) => {\n loggerFor(this).warn(msg);\n },\n };\n }\n\n /**\n * A `Fetch` for first-party credential token-exchange requests (OIDC\n * federation jwt-bearer grants, user-OAuth refresh grants) that routes\n * through this client's middleware chain, so middleware observes token\n * traffic like any other request. Only client-level middleware applies:\n * a minted token is shared across requests, so attributing the exchange\n * to any one request's per-request middleware would be arbitrary. For the\n * same reason, `ctx.options` is undefined for these requests.\n */\n private _credentialsFetch(): Fetch {\n return wrapFetchWithMiddleware(this.fetch, this.middleware, undefined, this);\n }\n\n private _makeTokenCache(provider: AccessTokenProvider): TokenCache {\n return new TokenCache(provider, (err) => {\n loggerFor(this).debug('advisory token refresh failed; serving cached token', err);\n });\n }\n\n /**\n * Create a new client instance re-using the same options given to the current client with optional overriding.\n */\n withOptions(options: Partial<ClientOptions>): this {\n // Share the auth state object unless the caller passes any auth-related\n // key. The `in` check is intentional: even `apiKey: undefined` opts the\n // clone out of sharing (it gets its own _auth and TokenCache, though it\n // may still wrap the parent's provider via the credentials spread below).\n const overridesStructuredAuth = 'credentials' in options || 'config' in options || 'profile' in options;\n const overridesAuth = 'apiKey' in options || 'authToken' in options || overridesStructuredAuth;\n const internal: InternalClientOptions = {\n ...this._options,\n // Only forward baseURL when the caller (or env) explicitly chose it.\n // For a non-explicit parent, this.baseURL may have been mutated to the\n // profile-resolved host; pinning that as the clone's options.baseURL\n // would make _options on the clone misreport caller intent and would\n // leave the clone stuck on the parent's host across an auth override.\n // The clone instead receives the construction-time value via\n // ...this._options above and re-adopts the profile host through the\n // shared _authState.baseURL + __baseURLIsExplicit=false path.\n ...(this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}),\n maxRetries: this.maxRetries,\n timeout: this.timeout,\n logger: this.logger,\n logLevel: this.logLevel,\n fetch: this.fetch,\n fetchOptions: this.fetchOptions,\n middleware: this.middleware,\n apiKey: this.apiKey,\n authToken: this.authToken,\n webhookKey: this.webhookKey,\n // credentials: this.credentials is a no-op when __auth is shared (the\n // ctor takes the inherited path and ignores options.credentials); when\n // overridesAuth is true via apiKey/authToken only, it lets the clone\n // build a fresh TokenCache around the parent's provider.\n credentials: this.credentials,\n // When the caller passes a structured-credential override, drop inherited\n // structured-credential options so only `...options` supplies them —\n // otherwise an inherited `credentials`/`config`/`profile` would trip the\n // mutual-exclusion check or precedence over the override.\n ...(overridesStructuredAuth ? { credentials: undefined, config: undefined, profile: undefined } : {}),\n ...options,\n // Always set __auth so any stale value from ...this._options is\n // overwritten. undefined means \"build fresh auth from these options\".\n __auth: overridesAuth ? undefined : this._authState,\n __baseURLIsExplicit: 'baseURL' in options ? true : this._baseURLIsExplicit,\n };\n return new (this.constructor as any as new (props: ClientOptions) => typeof this)(internal);\n }\n\n /**\n * Lazily resolves credentials from config files or environment variables.\n * Called once from the constructor when no explicit auth is provided, or\n * when an explicit `profile` was passed (in which case a missing/unresolved\n * profile is surfaced as an error instead of falling through to \"no auth\").\n * The returned promise is stored and awaited on the first request.\n */\n private async _resolveDefaultCredentials(profile?: string): Promise<void> {\n try {\n const result = await defaultCredentials(this._credentialResolverOptions(), profile);\n if (result) {\n this._authState.provider = result.provider;\n this._authState.tokenCache = this._makeTokenCache(result.provider);\n this._authState.extraHeaders = result.extraHeaders;\n this._applyCredentialBaseURL(result.baseURL);\n } else if (profile != null) {\n throw new Errors.AnthropicError(\n `Profile \"${profile}\" could not be resolved (no <config_dir>/configs/${profile}.json found).`,\n );\n }\n } catch (err) {\n this._authState.error = err;\n } finally {\n this._authState.resolution = null;\n }\n }\n\n /**\n * Check whether the base URL is set to its default.\n *\n * A profile-supplied `base_url` counts as an override here: a profile that\n * pins a non-default host is declaring \"this whole client targets deployment\n * X\", so per-endpoint {@link RequestOptions.defaultBaseURL} hints must not\n * silently route individual calls back to production. No generated resource\n * currently sets `defaultBaseURL`, so this is documenting intent for when\n * one does.\n */\n #baseURLOverridden(): boolean {\n return this.baseURL !== 'https://api.anthropic.com';\n }\n\n protected defaultQuery(): Record<string, string | undefined> | undefined {\n return this._options.defaultQuery;\n }\n\n protected validateHeaders({ values, nulls }: NullableHeaders) {\n if (values.get('x-api-key') || values.get('authorization')) {\n return;\n }\n if (this._authState.error) {\n throw this._authState.error;\n }\n if (this._authState.tokenCache || this._authState.resolution) {\n return; // auth will be injected per-request via authHeaders\n }\n\n if (this.apiKey && values.get('x-api-key')) {\n return;\n }\n if (nulls.has('x-api-key')) {\n return;\n }\n\n if (this.authToken && values.get('authorization')) {\n return;\n }\n if (nulls.has('authorization')) {\n return;\n }\n\n throw new Error(\n 'Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the \"X-Api-Key\" or \"Authorization\" headers to be explicitly omitted',\n );\n }\n\n private _authFlags(opts: FinalRequestOptions): RequestAuthFlags {\n let flags = this._requestAuthFlags.get(opts);\n if (!flags) {\n flags = { usedTokenCache: false, didRefreshFor401: false };\n this._requestAuthFlags.set(opts, flags);\n }\n return flags;\n }\n\n protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {\n // Wait for lazy credential resolution if it's in progress. If it failed,\n // return no auth headers — validateHeaders surfaces the stored error\n // after the explicit-header escape hatch has had a chance to apply.\n if (this._authState.resolution) {\n await this._authState.resolution;\n }\n if (this._authState.error) {\n return undefined;\n }\n // If we have a token cache and no API key is set, use token auth\n if (this._authState.tokenCache && this.apiKey == null) {\n const token = await this._authState.tokenCache.getToken();\n this._authFlags(opts).usedTokenCache = true;\n return buildHeaders([{ Authorization: `Bearer ${token}` }]);\n }\n return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);\n }\n\n protected async apiKeyAuth(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {\n if (this.apiKey == null) {\n return undefined;\n }\n return buildHeaders([{ 'X-Api-Key': this.apiKey }]);\n }\n\n protected async bearerAuth(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {\n if (this.authToken == null) {\n return undefined;\n }\n return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]);\n }\n\n protected stringifyQuery(query: object | Record<string, unknown>): string {\n return stringifyQuery(query);\n }\n\n private getUserAgent(): string {\n return `${this.constructor.name}/JS ${VERSION}`;\n }\n\n protected defaultIdempotencyKey(): string {\n return `stainless-node-retry-${uuid4()}`;\n }\n\n protected makeStatusError(\n status: number,\n error: Object,\n message: string | undefined,\n headers: Headers,\n ): Errors.APIError {\n return Errors.APIError.generate(status, error, message, headers);\n }\n\n buildURL(\n path: string,\n query: Record<string, unknown> | null | undefined,\n defaultBaseURL?: string | undefined,\n ): string {\n const baseURL = (!this.#baseURLOverridden() && defaultBaseURL) || this.baseURL;\n const url =\n isAbsoluteURL(path) ?\n new URL(path)\n : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));\n\n const defaultQuery = this.defaultQuery();\n const pathQuery = Object.fromEntries(url.searchParams);\n if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {\n query = { ...pathQuery, ...defaultQuery, ...query };\n }\n\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query);\n }\n\n return url.toString();\n }\n\n _calculateNonstreamingTimeout(maxTokens: number): number {\n const defaultTimeout = 10 * 60;\n const expectedTimeout = (60 * 60 * maxTokens) / 128_000;\n if (expectedTimeout > defaultTimeout) {\n throw new Errors.AnthropicError(\n 'Streaming is required for operations that may take longer than 10 minutes. ' +\n 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details',\n );\n }\n return defaultTimeout * 1000;\n }\n\n /**\n * Used as a callback for mutating the given `FinalRequestOptions` object.\n */\n protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}\n\n /**\n * Used as a callback for mutating the given `RequestInit` object.\n *\n * This is useful for cases where you want to add certain headers based off of\n * the request properties, e.g. `method` or `url`.\n *\n * Runs after all middleware (including {@link backendMiddleware}),\n * immediately before each underlying fetch call, so it sees exactly what\n * goes over the wire. Middleware may replay a request by calling `next()`\n * more than once, so this hook can run multiple times per attempt:\n * overrides must be idempotent and overwrite headers from a previous\n * invocation rather than append to them.\n */\n protected async prepareRequest(\n request: RequestInit,\n { url, options }: { url: string; options: FinalRequestOptions },\n ): Promise<void> {\n // Append auth-derived headers when using token auth. Done here (after all\n // header merging) rather than in authHeaders() so we append to any existing\n // anthropic-beta values instead of being overwritten by later header sources.\n if (this._authState.tokenCache && this.apiKey == null) {\n // Normalize to a Headers instance — custom fetch impls or polyfills can\n // hand back arrays / plain objects, and silently dropping the beta\n // header in that case would surface as a confusing server-side 4xx.\n const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers);\n for (const [k, v] of Object.entries(this._authState.extraHeaders)) {\n if (!headers.has(k)) headers.set(k, v);\n }\n const existing = headers\n .get('anthropic-beta')\n ?.split(',')\n .map((s) => s.trim());\n if (!existing?.includes(OAUTH_API_BETA_HEADER)) {\n headers.append('anthropic-beta', OAUTH_API_BETA_HEADER);\n }\n request.headers = headers;\n }\n }\n\n /**\n * Internal {@link Middleware} composed innermost in the chain — inside both\n * client-level and per-request middleware, immediately around the underlying\n * `fetch`. Subclasses for third-party backends override this to adapt the\n * canonical Anthropic-shaped request to the backend's wire shape (URL/body\n * rewriting, request signing) and to normalize the wire response back to the\n * canonical shape (e.g. AWS EventStream to SSE).\n *\n * Running inside the user's middleware means user middleware always observes\n * canonical Anthropic-shaped traffic, and the adaptation re-runs (e.g.\n * re-signs) on every `next()` invocation, covering whatever the middleware\n * mutated.\n *\n * Errors thrown here follow the middleware error policy: they propagate to\n * the caller as-is — no retries, no `APIConnectionError` wrapping — unless\n * retryable (see {@link Middleware}); throw a `RetryableError` to opt into\n * the retry path.\n */\n protected backendMiddleware(): ReadonlyArray<Middleware> {\n return [];\n }\n\n get<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n return this.methodRequest('get', path, opts);\n }\n\n post<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n return this.methodRequest('post', path, opts);\n }\n\n patch<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n return this.methodRequest('patch', path, opts);\n }\n\n put<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n return this.methodRequest('put', path, opts);\n }\n\n delete<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n return this.methodRequest('delete', path, opts);\n }\n\n private methodRequest<Rsp>(\n method: HTTPMethod,\n path: string,\n opts?: PromiseOrValue<RequestOptions>,\n ): APIPromise<Rsp> {\n return this.request(\n Promise.resolve(opts).then((opts) => {\n return { method, path, ...opts };\n }),\n );\n }\n\n request<Rsp>(\n options: PromiseOrValue<FinalRequestOptions>,\n remainingRetries: number | null = null,\n ): APIPromise<Rsp> {\n return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));\n }\n\n private async makeRequest(\n optionsInput: PromiseOrValue<FinalRequestOptions>,\n retriesRemaining: number | null,\n retryOfRequestLogID: string | undefined,\n ): Promise<APIResponseProps> {\n const options = await optionsInput;\n const maxRetries = options.maxRetries ?? this.maxRetries;\n if (retriesRemaining == null) {\n retriesRemaining = maxRetries;\n // Top-level call: reset per-request auth flags so a reused options object\n // (via client.request(opts)) doesn't carry stale 401-refresh state.\n this._requestAuthFlags.delete(options);\n }\n\n await this.prepareOptions(options);\n\n const { req, url, timeout } = await this.buildRequest(options, {\n retryCount: maxRetries - retriesRemaining,\n });\n\n /** Not an API request ID, just for correlating local log entries. */\n const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');\n const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;\n const startTime = Date.now();\n\n if (options.signal?.aborted) {\n throw new Errors.APIUserAbortError();\n }\n\n const controller = new AbortController();\n const response = await this.fetchWithTimeout(url, req, timeout, controller, options, {\n requestLogID,\n retryOfRequestLogID,\n }).catch(castToError);\n const headersTime = Date.now();\n\n if (response instanceof globalThis.Error) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n if (options.signal?.aborted) {\n throw new Errors.APIUserAbortError();\n }\n // detect native connection timeout errors\n // deno throws \"TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)\"\n // undici throws \"TypeError: fetch failed\" with cause \"ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)\"\n // others do not provide enough information to distinguish timeouts from other connection errors\n const isTimeout =\n isAbortError(response) ||\n /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));\n\n // Errors thrown by middleware (user middleware and the backend adaptation\n // alike) propagate to the caller as-is — no retries, no APIConnectionError\n // wrapping — except retryable errors (timeouts/aborts, APIConnectionErrors,\n // and RetryableErrors, directly or in the `cause` chain), which stay on the\n // retry path.\n const hasMiddleware =\n this.middleware.length > 0 || !!options.middleware?.length || this.backendMiddleware().length > 0;\n if (hasMiddleware && !isTimeout && !isRetryableError(response)) {\n loggerFor(this).info(`[${requestLogID}] middleware error (not retryable)`);\n loggerFor(this).debug(\n `[${requestLogID}] middleware error (not retryable)`,\n formatRequestDetails({\n retryOfRequestLogID,\n url,\n durationMs: headersTime - startTime,\n message: response.message,\n }),\n );\n throw response;\n }\n if (retriesRemaining) {\n loggerFor(this).info(\n `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`,\n );\n loggerFor(this).debug(\n `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`,\n formatRequestDetails({\n retryOfRequestLogID,\n url,\n durationMs: headersTime - startTime,\n message: response.message,\n }),\n );\n return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);\n }\n loggerFor(this).info(\n `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`,\n );\n loggerFor(this).debug(\n `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`,\n formatRequestDetails({\n retryOfRequestLogID,\n url,\n durationMs: headersTime - startTime,\n message: response.message,\n }),\n );\n if (isTimeout) {\n throw new Errors.APIConnectionTimeoutError();\n }\n // a retryable middleware-origin error is still the caller's error: once retries are\n // exhausted it propagates as-is rather than wrapped in APIConnectionError\n if (hasMiddleware && !isFetchOriginError(response)) {\n throw response;\n }\n throw new Errors.APIConnectionError({ cause: response });\n }\n\n const specialHeaders = [...response.headers.entries()]\n .filter(([name]) => name === 'request-id')\n .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))\n .join('');\n const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${\n response.ok ? 'succeeded' : 'failed'\n } with status ${response.status} in ${headersTime - startTime}ms`;\n\n if (!response.ok) {\n const shouldRetry = await this.shouldRetry(response, options);\n if (retriesRemaining && shouldRetry) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n\n // We don't need the body of this response.\n await Shims.CancelReadableStream(response.body);\n loggerFor(this).info(`${responseInfo} - ${retryMessage}`);\n loggerFor(this).debug(\n `[${requestLogID}] response error (${retryMessage})`,\n formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n headers: response.headers,\n durationMs: headersTime - startTime,\n }),\n );\n return this.retryRequest(\n options,\n retriesRemaining,\n retryOfRequestLogID ?? requestLogID,\n response.headers,\n );\n }\n\n const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;\n\n loggerFor(this).info(`${responseInfo} - ${retryMessage}`);\n\n const errText = await response.text().catch((err: any) => castToError(err).message);\n const errJSON = safeJSON(errText) as any;\n const errMessage = errJSON ? undefined : errText;\n\n loggerFor(this).debug(\n `[${requestLogID}] response error (${retryMessage})`,\n formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n headers: response.headers,\n message: errMessage,\n durationMs: Date.now() - startTime,\n }),\n );\n\n const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);\n throw err;\n }\n\n loggerFor(this).info(responseInfo);\n loggerFor(this).debug(\n `[${requestLogID}] response start`,\n formatRequestDetails({\n retryOfRequestLogID,\n url: response.url,\n status: response.status,\n headers: response.headers,\n durationMs: headersTime - startTime,\n }),\n );\n\n return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };\n }\n\n getAPIList<Item, PageClass extends Pagination.AbstractPage<Item> = Pagination.AbstractPage<Item>>(\n path: string,\n Page: new (...args: any[]) => PageClass,\n opts?: PromiseOrValue<RequestOptions>,\n ): Pagination.PagePromise<PageClass, Item> {\n return this.requestAPIList(\n Page,\n opts && 'then' in opts ?\n opts.then((opts) => ({ method: 'get', path, ...opts }))\n : { method: 'get', path, ...opts },\n );\n }\n\n requestAPIList<\n Item = unknown,\n PageClass extends Pagination.AbstractPage<Item> = Pagination.AbstractPage<Item>,\n >(\n Page: new (...args: ConstructorParameters<typeof Pagination.AbstractPage>) => PageClass,\n options: PromiseOrValue<FinalRequestOptions>,\n ): Pagination.PagePromise<PageClass, Item> {\n const request = this.makeRequest(options, null, undefined);\n return new Pagination.PagePromise<PageClass, Item>(this as any as Anthropic, request, Page);\n }\n\n async fetchWithTimeout(\n url: RequestInfo,\n init: RequestInit | undefined,\n ms: number,\n controller: AbortController,\n requestOptions?: FinalRequestOptions | undefined,\n logCtx?: { requestLogID: string; retryOfRequestLogID?: string | undefined } | undefined,\n ): Promise<Response> {\n const { signal, method, ...options } = init || {};\n // Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks.\n // An arrow function like `() => controller.abort()` captures the surrounding scope,\n // which includes the request body and other large objects. When the user passes a\n // long-lived AbortSignal, the listener prevents those objects from being GC'd for\n // the lifetime of the signal. Using `.bind()` only retains a reference to the\n // controller itself.\n const abort = this._makeAbort(controller);\n if (signal) signal.addEventListener('abort', abort, { once: true });\n\n const isReadableBody =\n ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) ||\n (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);\n\n const fetchOptions: RequestInit = {\n signal: controller.signal as any,\n ...(isReadableBody ? { duplex: 'half' } : {}),\n method: 'GET',\n ...options,\n };\n if (method) {\n // Custom methods like 'patch' need to be uppercased\n // See https://github.com/nodejs/undici/issues/2294\n fetchOptions.method = method.toUpperCase();\n }\n\n // Arm the timeout around the underlying fetch only, not the middleware\n // chain — middleware can take arbitrarily long (or call `next` more than\n // once), and each inner-fetch invocation gets its own `ms` timer.\n const baseFetch = this.fetch;\n const timedFetch: Fetch = async (innerUrl, innerInit) => {\n const timeout = setTimeout(abort, ms);\n try {\n return await baseFetch.call(undefined, innerUrl, innerInit);\n } finally {\n clearTimeout(timeout);\n }\n };\n\n // Prepare the request (auth signing and other `prepareRequest` hooks) as\n // the innermost step, after any middleware — including the backend\n // middleware, so it sees exactly what goes over the wire. Runs per\n // inner-fetch invocation, so a request middleware rewrote — or replayed\n // via a second `next()` call — is prepared fresh each time. Preparation is\n // outside the timeout timer, matching its pre-middleware behavior.\n const innerFetch: Fetch =\n requestOptions === undefined ? timedFetch : (\n async (innerUrl, innerInit = {}) => {\n const innerUrlStr =\n typeof innerUrl === 'string' ? innerUrl\n : innerUrl instanceof URL ? innerUrl.href\n : innerUrl.url;\n innerInit.headers =\n innerInit.headers instanceof Headers ? innerInit.headers : new Headers(innerInit.headers);\n\n await this.prepareRequest(innerInit, { url: innerUrlStr, options: requestOptions });\n\n if (logCtx) {\n loggerFor(this).debug(\n `[${logCtx.requestLogID}] sending request`,\n formatRequestDetails({\n retryOfRequestLogID: logCtx.retryOfRequestLogID,\n method: innerInit.method,\n url: innerUrlStr,\n options: requestOptions,\n headers: innerInit.headers,\n }),\n );\n }\n\n return timedFetch(innerUrl, innerInit);\n }\n );\n\n const requestMiddleware = requestOptions?.middleware;\n const backendMiddleware = this.backendMiddleware();\n const allMiddleware =\n requestMiddleware?.length || backendMiddleware.length ?\n [...this.middleware, ...(requestMiddleware ?? []), ...backendMiddleware]\n : this.middleware;\n return await wrapFetchWithMiddleware(innerFetch, allMiddleware, requestOptions, this)(url, fetchOptions);\n }\n\n private async shouldRetry(response: Response, options: FinalRequestOptions): Promise<boolean> {\n // Reactive refresh: on a 401 from a request that used the token cache,\n // invalidate and retry once. Only fires when this specific request was\n // bearer-authenticated (not when an apiKey was used) and only once per\n // request — a second 401 after refresh falls through to the normal\n // retry policy below (which treats 4xx as non-retryable).\n const flags = this._authFlags(options);\n if (\n response.status === 401 &&\n this._authState.tokenCache &&\n flags.usedTokenCache &&\n !flags.didRefreshFor401\n ) {\n flags.didRefreshFor401 = true;\n this._authState.tokenCache.invalidate();\n return true;\n }\n\n // Note this is not a standard header.\n const shouldRetryHeader = response.headers.get('x-should-retry');\n\n // If the server explicitly says whether or not to retry, obey.\n if (shouldRetryHeader === 'true') return true;\n if (shouldRetryHeader === 'false') return false;\n\n // Retry on request timeouts.\n if (response.status === 408) return true;\n\n // Retry on lock timeouts.\n if (response.status === 409) return true;\n\n // Retry on rate limits.\n if (response.status === 429) return true;\n\n // Retry internal errors.\n if (response.status >= 500) return true;\n\n return false;\n }\n\n private async retryRequest(\n options: FinalRequestOptions,\n retriesRemaining: number,\n requestLogID: string,\n responseHeaders?: Headers | undefined,\n ): Promise<APIResponseProps> {\n let timeoutMillis: number | undefined;\n\n // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.\n const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');\n if (retryAfterMillisHeader) {\n const timeoutMs = parseFloat(retryAfterMillisHeader);\n if (!Number.isNaN(timeoutMs)) {\n timeoutMillis = timeoutMs;\n }\n }\n\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfterHeader = responseHeaders?.get('retry-after');\n if (retryAfterHeader && !timeoutMillis) {\n const timeoutSeconds = parseFloat(retryAfterHeader);\n if (!Number.isNaN(timeoutSeconds)) {\n timeoutMillis = timeoutSeconds * 1000;\n } else {\n timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\n }\n }\n\n // If the API asks us to wait a certain amount of time, just do what it\n // says, but otherwise calculate a default\n if (timeoutMillis === undefined) {\n const maxRetries = options.maxRetries ?? this.maxRetries;\n timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\n }\n await sleep(timeoutMillis);\n\n return this.makeRequest(options, retriesRemaining - 1, requestLogID);\n }\n\n private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {\n const initialRetryDelay = 0.5;\n const maxRetryDelay = 8.0;\n\n const numRetries = maxRetries - retriesRemaining;\n\n // Apply exponential backoff, but not more than the max.\n const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\n\n // Apply some jitter, take up to at most 25 percent of the retry time.\n const jitter = 1 - Math.random() * 0.25;\n\n return sleepSeconds * jitter * 1000;\n }\n\n public calculateNonstreamingTimeout(maxTokens: number, maxNonstreamingTokens?: number): number {\n const maxTime = 60 * 60 * 1000; // 60 minutes\n const defaultTime = 60 * 10 * 1000; // 10 minutes\n\n const expectedTime = (maxTime * maxTokens) / 128000;\n if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {\n throw new Errors.AnthropicError(\n 'Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details',\n );\n }\n\n return defaultTime;\n }\n\n async buildRequest(\n inputOptions: FinalRequestOptions,\n { retryCount = 0 }: { retryCount?: number } = {},\n ): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {\n const options = { ...inputOptions };\n const { method, path, query, defaultBaseURL } = options;\n\n // Lazy credential resolution may carry a profile-supplied baseURL. Await\n // it before building the request URL so the very first request — and\n // requests on withOptions() clones created before resolution settled —\n // hit the profile's host rather than the hardcoded default.\n if (this._authState.resolution) {\n await this._authState.resolution;\n }\n if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) {\n this.baseURL = this._authState.baseURL;\n }\n\n const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);\n if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);\n options.timeout = options.timeout ?? this.timeout;\n const { bodyHeaders, body } = this.buildBody({ options });\n const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });\n\n const req: FinalizedRequestInit = {\n method,\n headers: reqHeaders,\n ...(options.signal && { signal: options.signal }),\n ...((globalThis as any).ReadableStream &&\n body instanceof (globalThis as any).ReadableStream && { duplex: 'half' }),\n ...(body && { body }),\n ...((this.fetchOptions as any) ?? {}),\n ...((options.fetchOptions as any) ?? {}),\n };\n\n return { req, url, timeout: options.timeout };\n }\n\n private async buildHeaders({\n options,\n method,\n bodyHeaders,\n retryCount,\n }: {\n options: FinalRequestOptions;\n method: HTTPMethod;\n bodyHeaders: HeadersLike;\n retryCount: number;\n }): Promise<Headers> {\n let idempotencyHeaders: HeadersLike = {};\n if (this.idempotencyHeader && method !== 'get') {\n if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();\n idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;\n }\n\n const headers = buildHeaders([\n idempotencyHeaders,\n {\n Accept: 'application/json',\n 'User-Agent': this.getUserAgent(),\n 'X-Stainless-Retry-Count': String(retryCount),\n ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),\n ...getPlatformHeaders(),\n ...(this._options.dangerouslyAllowBrowser ?\n { 'anthropic-dangerous-direct-browser-access': 'true' }\n : undefined),\n 'anthropic-version': '2023-06-01',\n },\n await this.authHeaders(options),\n this._options.defaultHeaders,\n bodyHeaders,\n options.headers,\n ]);\n\n this.validateHeaders(headers);\n\n return headers.values;\n }\n\n private _makeAbort(controller: AbortController) {\n // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure\n // would capture all request options, and cause a memory leak.\n return () => controller.abort();\n }\n\n private buildBody({ options: { body, headers: rawHeaders } }: { options: FinalRequestOptions }): {\n bodyHeaders: HeadersLike;\n body: BodyInit | undefined;\n } {\n if (!body) {\n return { bodyHeaders: undefined, body: undefined };\n }\n const headers = buildHeaders([rawHeaders]);\n if (\n // Pass raw type verbatim\n ArrayBuffer.isView(body) ||\n body instanceof ArrayBuffer ||\n body instanceof DataView ||\n (typeof body === 'string' &&\n // Preserve legacy string encoding behavior for now\n headers.values.has('content-type')) ||\n // `Blob` is superset of `File`\n ((globalThis as any).Blob && body instanceof (globalThis as any).Blob) ||\n // `FormData` -> `multipart/form-data`\n body instanceof FormData ||\n // `URLSearchParams` -> `application/x-www-form-urlencoded`\n body instanceof URLSearchParams ||\n // Send chunked stream (each chunk has own `length`)\n ((globalThis as any).ReadableStream && body instanceof (globalThis as any).ReadableStream)\n ) {\n return { bodyHeaders: undefined, body: body as BodyInit };\n } else if (\n typeof body === 'object' &&\n (Symbol.asyncIterator in body ||\n (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))\n ) {\n return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body as AsyncIterable<Uint8Array>) };\n } else if (\n typeof body === 'object' &&\n headers.values.get('content-type') === 'application/x-www-form-urlencoded'\n ) {\n return {\n bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },\n body: this.stringifyQuery(body),\n };\n } else {\n return this.#encoder({ body, headers });\n }\n }\n\n static Anthropic = this;\n static HUMAN_PROMPT = HUMAN_PROMPT;\n static AI_PROMPT = AI_PROMPT;\n static DEFAULT_TIMEOUT = 600000; // 10 minutes\n\n static AnthropicError = Errors.AnthropicError;\n static APIError = Errors.APIError;\n static APIConnectionError = Errors.APIConnectionError;\n static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;\n static APIUserAbortError = Errors.APIUserAbortError;\n static NotFoundError = Errors.NotFoundError;\n static ConflictError = Errors.ConflictError;\n static RateLimitError = Errors.RateLimitError;\n static BadRequestError = Errors.BadRequestError;\n static AuthenticationError = Errors.AuthenticationError;\n static InternalServerError = Errors.InternalServerError;\n static PermissionDeniedError = Errors.PermissionDeniedError;\n static UnprocessableEntityError = Errors.UnprocessableEntityError;\n\n static toFile = Uploads.toFile;\n}\n\n/**\n * API Client for interfacing with the Anthropic API.\n */\nexport class Anthropic extends BaseAnthropic {\n completions: API.Completions = new API.Completions(this);\n messages: API.Messages = new API.Messages(this);\n models: API.Models = new API.Models(this);\n beta: API.Beta = new API.Beta(this);\n}\n\nAnthropic.Completions = Completions;\nAnthropic.Messages = Messages;\nAnthropic.Models = Models;\nAnthropic.Beta = Beta;\n\nexport declare namespace Anthropic {\n export type RequestOptions = Opts.RequestOptions;\n export type FinalRequestOptions = Opts.FinalRequestOptions;\n\n export type { ApiKeySetter };\n\n export import Page = Pagination.Page;\n export { type PageParams as PageParams, type PageResponse as PageResponse };\n\n export import TokenPage = Pagination.TokenPage;\n export { type TokenPageParams as TokenPageParams, type TokenPageResponse as TokenPageResponse };\n\n export import PageCursor = Pagination.PageCursor;\n export { type PageCursorParams as PageCursorParams, type PageCursorResponse as PageCursorResponse };\n\n export {\n Completions as Completions,\n type Completion as Completion,\n type CompletionCreateParams as CompletionCreateParams,\n type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,\n type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,\n };\n\n export {\n Messages as Messages,\n type Base64ImageSource as Base64ImageSource,\n type Base64PDFSource as Base64PDFSource,\n type BashCodeExecutionOutputBlock as BashCodeExecutionOutputBlock,\n type BashCodeExecutionOutputBlockParam as BashCodeExecutionOutputBlockParam,\n type BashCodeExecutionResultBlock as BashCodeExecutionResultBlock,\n type BashCodeExecutionResultBlockParam as BashCodeExecutionResultBlockParam,\n type BashCodeExecutionToolResultBlock as BashCodeExecutionToolResultBlock,\n type BashCodeExecutionToolResultBlockParam as BashCodeExecutionToolResultBlockParam,\n type BashCodeExecutionToolResultError as BashCodeExecutionToolResultError,\n type BashCodeExecutionToolResultErrorCode as BashCodeExecutionToolResultErrorCode,\n type BashCodeExecutionToolResultErrorParam as BashCodeExecutionToolResultErrorParam,\n type CacheControlEphemeral as CacheControlEphemeral,\n type CacheCreation as CacheCreation,\n type CitationCharLocation as CitationCharLocation,\n type CitationCharLocationParam as CitationCharLocationParam,\n type CitationContentBlockLocation as CitationContentBlockLocation,\n type CitationContentBlockLocationParam as CitationContentBlockLocationParam,\n type CitationPageLocation as CitationPageLocation,\n type CitationPageLocationParam as CitationPageLocationParam,\n type CitationSearchResultLocationParam as CitationSearchResultLocationParam,\n type CitationWebSearchResultLocationParam as CitationWebSearchResultLocationParam,\n type CitationsConfig as CitationsConfig,\n type CitationsConfigParam as CitationsConfigParam,\n type CitationsDelta as CitationsDelta,\n type CitationsSearchResultLocation as CitationsSearchResultLocation,\n type CitationsWebSearchResultLocation as CitationsWebSearchResultLocation,\n type CodeExecutionOutputBlock as CodeExecutionOutputBlock,\n type CodeExecutionOutputBlockParam as CodeExecutionOutputBlockParam,\n type CodeExecutionResultBlock as CodeExecutionResultBlock,\n type CodeExecutionResultBlockParam as CodeExecutionResultBlockParam,\n type CodeExecutionTool20250522 as CodeExecutionTool20250522,\n type CodeExecutionTool20250825 as CodeExecutionTool20250825,\n type CodeExecutionTool20260120 as CodeExecutionTool20260120,\n type CodeExecutionTool20260521 as CodeExecutionTool20260521,\n type CodeExecutionToolResultBlock as CodeExecutionToolResultBlock,\n type CodeExecutionToolResultBlockContent as CodeExecutionToolResultBlockContent,\n type CodeExecutionToolResultBlockParam as CodeExecutionToolResultBlockParam,\n type CodeExecutionToolResultBlockParamContent as CodeExecutionToolResultBlockParamContent,\n type CodeExecutionToolResultError as CodeExecutionToolResultError,\n type CodeExecutionToolResultErrorCode as CodeExecutionToolResultErrorCode,\n type CodeExecutionToolResultErrorParam as CodeExecutionToolResultErrorParam,\n type Container as Container,\n type ContainerUploadBlock as ContainerUploadBlock,\n type ContainerUploadBlockParam as ContainerUploadBlockParam,\n type ContentBlock as ContentBlock,\n type ContentBlockDeltaEvent as ContentBlockDeltaEvent,\n type ContentBlockParam as ContentBlockParam,\n type ContentBlockStartEvent as ContentBlockStartEvent,\n type ContentBlockStopEvent as ContentBlockStopEvent,\n type ContentBlockSource as ContentBlockSource,\n type ContentBlockSourceContent as ContentBlockSourceContent,\n type DirectCaller as DirectCaller,\n type DocumentBlock as DocumentBlock,\n type DocumentBlockParam as DocumentBlockParam,\n type EncryptedCodeExecutionResultBlock as EncryptedCodeExecutionResultBlock,\n type EncryptedCodeExecutionResultBlockParam as EncryptedCodeExecutionResultBlockParam,\n type ImageBlockParam as ImageBlockParam,\n type InputJSONDelta as InputJSONDelta,\n type JSONOutputFormat as JSONOutputFormat,\n type MemoryTool20250818 as MemoryTool20250818,\n type Message as Message,\n type MessageCountTokensTool as MessageCountTokensTool,\n type MessageDeltaEvent as MessageDeltaEvent,\n type MessageDeltaUsage as MessageDeltaUsage,\n type MessageParam as MessageParam,\n type MessageStartEvent as MessageStartEvent,\n type MessageStopEvent as MessageStopEvent,\n type MessageStreamEvent as MessageStreamEvent,\n type MessageTokensCount as MessageTokensCount,\n type Metadata as Metadata,\n type MidConversationSystemBlockParam as MidConversationSystemBlockParam,\n type Model as Model,\n type OutputConfig as OutputConfig,\n type OutputTokensDetails as OutputTokensDetails,\n type PlainTextSource as PlainTextSource,\n type RawContentBlockDelta as RawContentBlockDelta,\n type RawContentBlockDeltaEvent as RawContentBlockDeltaEvent,\n type RawContentBlockStartEvent as RawContentBlockStartEvent,\n type RawContentBlockStopEvent as RawContentBlockStopEvent,\n type RawMessageDeltaEvent as RawMessageDeltaEvent,\n type RawMessageStartEvent as RawMessageStartEvent,\n type RawMessageStopEvent as RawMessageStopEvent,\n type RawMessageStreamEvent as RawMessageStreamEvent,\n type RedactedThinkingBlock as RedactedThinkingBlock,\n type RedactedThinkingBlockParam as RedactedThinkingBlockParam,\n type RefusalStopDetails as RefusalStopDetails,\n type SearchResultBlockParam as SearchResultBlockParam,\n type ServerToolCaller as ServerToolCaller,\n type ServerToolCaller20260120 as ServerToolCaller20260120,\n type ServerToolUsage as ServerToolUsage,\n type ServerToolUseBlock as ServerToolUseBlock,\n type ServerToolUseBlockParam as ServerToolUseBlockParam,\n type SignatureDelta as SignatureDelta,\n type StopReason as StopReason,\n type TextBlock as TextBlock,\n type TextBlockParam as TextBlockParam,\n type TextCitation as TextCitation,\n type TextCitationParam as TextCitationParam,\n type TextDelta as TextDelta,\n type TextEditorCodeExecutionCreateResultBlock as TextEditorCodeExecutionCreateResultBlock,\n type TextEditorCodeExecutionCreateResultBlockParam as TextEditorCodeExecutionCreateResultBlockParam,\n type TextEditorCodeExecutionStrReplaceResultBlock as TextEditorCodeExecutionStrReplaceResultBlock,\n type TextEditorCodeExecutionStrReplaceResultBlockParam as TextEditorCodeExecutionStrReplaceResultBlockParam,\n type TextEditorCodeExecutionToolResultBlock as TextEditorCodeExecutionToolResultBlock,\n type TextEditorCodeExecutionToolResultBlockParam as TextEditorCodeExecutionToolResultBlockParam,\n type TextEditorCodeExecutionToolResultError as TextEditorCodeExecutionToolResultError,\n type TextEditorCodeExecutionToolResultErrorCode as TextEditorCodeExecutionToolResultErrorCode,\n type TextEditorCodeExecutionToolResultErrorParam as TextEditorCodeExecutionToolResultErrorParam,\n type TextEditorCodeExecutionViewResultBlock as TextEditorCodeExecutionViewResultBlock,\n type TextEditorCodeExecutionViewResultBlockParam as TextEditorCodeExecutionViewResultBlockParam,\n type ThinkingBlock as ThinkingBlock,\n type ThinkingBlockParam as ThinkingBlockParam,\n type ThinkingConfigAdaptive as ThinkingConfigAdaptive,\n type ThinkingConfigDisabled as ThinkingConfigDisabled,\n type ThinkingConfigEnabled as ThinkingConfigEnabled,\n type ThinkingConfigParam as ThinkingConfigParam,\n type ThinkingDelta as ThinkingDelta,\n type Tool as Tool,\n type ToolBash20250124 as ToolBash20250124,\n type ToolChoice as ToolChoice,\n type ToolChoiceAny as ToolChoiceAny,\n type ToolChoiceAuto as ToolChoiceAuto,\n type ToolChoiceNone as ToolChoiceNone,\n type ToolChoiceTool as ToolChoiceTool,\n type ToolReferenceBlock as ToolReferenceBlock,\n type ToolReferenceBlockParam as ToolReferenceBlockParam,\n type ToolResultBlockParam as ToolResultBlockParam,\n type ToolSearchToolBm25_20251119 as ToolSearchToolBm25_20251119,\n type ToolSearchToolRegex20251119 as ToolSearchToolRegex20251119,\n type ToolSearchToolResultBlock as ToolSearchToolResultBlock,\n type ToolSearchToolResultBlockParam as ToolSearchToolResultBlockParam,\n type ToolSearchToolResultError as ToolSearchToolResultError,\n type ToolSearchToolResultErrorCode as ToolSearchToolResultErrorCode,\n type ToolSearchToolResultErrorParam as ToolSearchToolResultErrorParam,\n type ToolSearchToolSearchResultBlock as ToolSearchToolSearchResultBlock,\n type ToolSearchToolSearchResultBlockParam as ToolSearchToolSearchResultBlockParam,\n type ToolTextEditor20250124 as ToolTextEditor20250124,\n type ToolTextEditor20250429 as ToolTextEditor20250429,\n type ToolTextEditor20250728 as ToolTextEditor20250728,\n type ToolUnion as ToolUnion,\n type ToolUseBlock as ToolUseBlock,\n type ToolUseBlockParam as ToolUseBlockParam,\n type URLImageSource as URLImageSource,\n type URLPDFSource as URLPDFSource,\n type Usage as Usage,\n type UserLocation as UserLocation,\n type WebFetchBlock as WebFetchBlock,\n type WebFetchBlockParam as WebFetchBlockParam,\n type WebFetchTool20250910 as WebFetchTool20250910,\n type WebFetchTool20260209 as WebFetchTool20260209,\n type WebFetchTool20260309 as WebFetchTool20260309,\n type WebFetchToolResultBlock as WebFetchToolResultBlock,\n type WebFetchToolResultBlockParam as WebFetchToolResultBlockParam,\n type WebFetchToolResultErrorBlock as WebFetchToolResultErrorBlock,\n type WebFetchToolResultErrorBlockParam as WebFetchToolResultErrorBlockParam,\n type WebFetchToolResultErrorCode as WebFetchToolResultErrorCode,\n type WebSearchResultBlock as WebSearchResultBlock,\n type WebSearchResultBlockParam as WebSearchResultBlockParam,\n type WebSearchTool20250305 as WebSearchTool20250305,\n type WebSearchTool20260209 as WebSearchTool20260209,\n type WebSearchToolRequestError as WebSearchToolRequestError,\n type WebSearchToolResultBlock as WebSearchToolResultBlock,\n type WebSearchToolResultBlockContent as WebSearchToolResultBlockContent,\n type WebSearchToolResultBlockParam as WebSearchToolResultBlockParam,\n type WebSearchToolResultBlockParamContent as WebSearchToolResultBlockParamContent,\n type WebSearchToolResultError as WebSearchToolResultError,\n type WebSearchToolResultErrorCode as WebSearchToolResultErrorCode,\n type MessageCreateParams as MessageCreateParams,\n type MessageCreateParamsNonStreaming as MessageCreateParamsNonStreaming,\n type MessageCreateParamsStreaming as MessageCreateParamsStreaming,\n type MessageStreamParams as MessageStreamParams,\n type MessageCountTokensParams as MessageCountTokensParams,\n };\n\n export {\n Models as Models,\n type CapabilitySupport as CapabilitySupport,\n type ContextManagementCapability as ContextManagementCapability,\n type EffortCapability as EffortCapability,\n type ModelCapabilities as ModelCapabilities,\n type ModelInfo as ModelInfo,\n type ThinkingCapability as ThinkingCapability,\n type ThinkingTypes as ThinkingTypes,\n type ModelInfosPage as ModelInfosPage,\n type ModelRetrieveParams as ModelRetrieveParams,\n type ModelListParams as ModelListParams,\n };\n\n export {\n Beta as Beta,\n type AnthropicBeta as AnthropicBeta,\n type BetaAPIError as BetaAPIError,\n type BetaAuthenticationError as BetaAuthenticationError,\n type BetaBillingError as BetaBillingError,\n type BetaError as BetaError,\n type BetaErrorResponse as BetaErrorResponse,\n type BetaGatewayTimeoutError as BetaGatewayTimeoutError,\n type BetaInvalidRequestError as BetaInvalidRequestError,\n type BetaNotFoundError as BetaNotFoundError,\n type BetaOverloadedError as BetaOverloadedError,\n type BetaPermissionError as BetaPermissionError,\n type BetaRateLimitError as BetaRateLimitError,\n };\n\n export type APIErrorObject = API.APIErrorObject;\n export type AuthenticationError = API.AuthenticationError;\n export type BillingError = API.BillingError;\n export type ErrorObject = API.ErrorObject;\n export type ErrorResponse = API.ErrorResponse;\n export type ErrorType = API.ErrorType;\n export type GatewayTimeoutError = API.GatewayTimeoutError;\n export type InvalidRequestError = API.InvalidRequestError;\n export type NotFoundError = API.NotFoundError;\n export type OverloadedError = API.OverloadedError;\n export type PermissionError = API.PermissionError;\n export type RateLimitError = API.RateLimitError;\n}\n","import type { APIRequest } from '../core/api';\nimport { AnthropicError } from '../core/error';\nimport type { Middleware, MiddlewareContext, MiddlewareNext } from '../core/middleware';\nimport { Stream, type ServerSentEvent } from '../core/streaming';\nimport { isAbortError } from '../internal/errors';\nimport { appendHeaderValue } from '../internal/headers';\nimport { STAINLESS_HELPER_HEADER } from '../internal/stainless-helper-header';\nimport { safeJSON } from '../internal/utils/values';\nimport type { AnthropicBeta } from '../resources/beta/beta';\nimport type {\n BetaContentBlockParam,\n BetaFallbackBlock,\n BetaFallbackMessageIterationUsage,\n BetaFallbackParam,\n BetaMessage,\n BetaMessageDeltaUsage,\n BetaMessageIterationUsage,\n BetaRawContentBlockDeltaEvent,\n BetaRawContentBlockStartEvent,\n BetaRawContentBlockStopEvent,\n BetaRawMessageDeltaEvent,\n BetaRawMessageStopEvent,\n BetaRawMessageStreamEvent,\n BetaRefusalStopDetails,\n BetaUsage,\n MessageCreateParams,\n} from '../resources/beta/messages/messages';\n\nexport { BetaFallbackState } from '../internal/request-options';\n\nconst encoder = new TextEncoder();\n\n/** Betas sent by default; override with {@link BetaRefusalFallbackOptions.betas}. */\nconst DEFAULT_BETAS: readonly AnthropicBeta[] = ['fallback-credit-2026-06-01'];\n\n/**\n * Remove `fallback` blocks replayed in history. They only parse under the\n * server-side fallback beta, which belongs to the caller-owned server-side\n * `fallbacks` feature — this middleware never sends it, so a request\n * replaying them would 400. An assistant turn left empty is dropped whole.\n */\nfunction stripFallbackBlocks(body: MessageCreateParams): MessageCreateParams {\n const messages = body.messages\n .map((message) =>\n Array.isArray(message.content) ?\n { ...message, content: message.content.filter((block) => block.type !== 'fallback') }\n : message,\n )\n .filter((message) => !Array.isArray(message.content) || message.content.length > 0);\n return { ...body, messages };\n}\n\n/** Why {@link BetaRefusalFallbackOptions.onError} fired. */\nexport type BetaRefusalFallbackError =\n | {\n /** The refusal carries no `fallback_credit_token`, so it can't be retried. */\n kind: 'no_credit_token';\n message: string;\n /** The refusal `message_delta` event, verbatim. */\n event: BetaRawMessageDeltaEvent;\n }\n | {\n /** The stream refused but every fallback entry has been used up. */\n kind: 'chain_exhausted';\n message: string;\n /** The refusal `message_delta` event, verbatim. */\n event: BetaRawMessageDeltaEvent;\n }\n | {\n /** A streaming fallback request failed; the hop was skipped. */\n kind: 'request_failed';\n message: string;\n /** The fallback model whose request failed. */\n model: string;\n /** The HTTP status, or `null` when the request threw instead of resolving. */\n status: number | null;\n /** The parsed error body, or the thrown error when `status` is `null`. */\n detail: unknown;\n };\n\nexport interface BetaRefusalFallbackOptions {\n /**\n * Betas added to the `anthropic-beta` header of every `/v1/messages`\n * request this middleware handles — the original request included, since\n * refusals only carry a `fallback_credit_token` when the beta is enabled.\n * Defaults to `['fallback-credit-2026-06-01']`; pass `[]` to send none.\n */\n betas?: readonly AnthropicBeta[] | undefined;\n\n /**\n * Called when a refusal is surfaced to the client rather than retried —\n * it carries no `fallback_credit_token`, no fallback entries remain, or a\n * streaming fallback request failed. Discriminate on `error.kind`.\n * Defaults to logging through the client logger.\n */\n onError?: ((error: BetaRefusalFallbackError) => void) | undefined;\n}\n\n/**\n * Middleware that retries refused `/v1/messages` requests down a fallback chain.\n *\n * Non-streaming: when a response comes back with `stop_reason: 'refusal'`, the\n * request is retried with each entry of `fallbacks` merged over the original\n * params — passing along the refusal's `fallback_credit_token` — until a model\n * accepts or the chain is exhausted. A message served by a fallback carries a\n * `fallback` content block prepended at each model boundary — the same seam\n * block shape the server-side `fallbacks` param places in `content`, though\n * the rest of the envelope is the serving hop's as returned (see the\n * known-divergences note below); an exhausted chain surfaces the final\n * refusal verbatim.\n *\n * Streaming: when the stream ends in `stop_reason: 'refusal'`, a second\n * request is issued to the fallback model — carrying the refused model's\n * partial output as a trailing assistant prefill when the refusal grants one\n * (`fallback_has_prefill_claim`), plus the refusal's `fallback_credit_token`\n * — and the fallback's events are spliced onto the\n * still-open stream, so the client sees one continuous message in the\n * server-side `fallbacks` wire shape: a `fallback` content block at each model\n * boundary, monotonic block indices, and per-hop `usage.iterations` on the\n * final `message_delta`. Only `model` is honored from each entry on this path:\n * the credit token is redeemable only against the refused request's body, so\n * the other per-entry overrides (`max_tokens`, `thinking`, ...) would be\n * rejected.\n *\n * The fallback-credit beta the credit tokens require is sent by default on\n * every request the middleware handles; the `betas` option controls this.\n *\n * In both modes a fallback that itself refuses with a fresh credit token\n * continues down the chain. A streaming fallback whose prefill the server\n * rejects (HTTP 400) is retried once without it; a fallback whose request\n * fails outright is skipped — its token was never redeemed, so it carries to\n * the next entry.\n *\n * To keep later requests on the model that accepted, pass a\n * {@link BetaFallbackState} via the `fallbackState` request option; requests\n * sharing that state start directly at the pinned fallback. Reuse one state\n * across whatever scope the pin should apply to — typically a conversation.\n *\n * @example\n * ```ts\n * const client = new Anthropic({\n * middleware: [betaRefusalFallbackMiddleware([{ model: 'claude-opus-4-8' }])],\n * });\n *\n * const fallbackState = new BetaFallbackState();\n * const message = await client.beta.messages.create(params, { fallbackState });\n * ```\n */\nexport function betaRefusalFallbackMiddleware(\n fallbacks: readonly BetaFallbackParam[],\n options: BetaRefusalFallbackOptions = {},\n): Middleware {\n let warnedMissingState = false;\n\n return async (request, next, ctx) => {\n // This middleware only applies to the beta messages API\n // (`client.beta.messages`, which posts to `/v1/messages?beta=true`).\n // An empty chain also disables this middleware.\n const [path, query] = (ctx.options?.path ?? '').split('?');\n if (\n fallbacks.length === 0 ||\n ctx.options?.method !== 'post' ||\n path !== '/v1/messages' ||\n new URLSearchParams(query).get('beta') !== 'true' ||\n typeof ctx.options.body !== 'object' ||\n ctx.options.body == null\n ) {\n return next(request);\n }\n\n if ((ctx.options.body as MessageCreateParams).fallbacks != null) {\n throw new AnthropicError(\n 'Sending the `fallbacks:` request param is not supported when using the `betaRefusalFallbackMiddleware`. ' +\n 'You should either remove the middleware and send `fallbacks:` with the `server-side-fallback-2026-06-01` beta header to let the API handle refusal fallbacks, ' +\n \"or omit the `fallbacks:` param if you'd like `betaRefusalFallbackMiddleware` to handle fallbacks on the client side.\",\n );\n }\n\n const onError =\n options.onError ??\n ((error: BetaRefusalFallbackError) =>\n ctx.logger.error(`anthropic-sdk: betaRefusalFallbackMiddleware: ${error.message}`));\n\n // Send the configured betas on this and every hop request derived from it,\n // and tag this and every hop with the middleware's helper telemetry.\n request = withMiddlewareHeaders(request, options.betas ?? DEFAULT_BETAS);\n\n const body = stripFallbackBlocks(ctx.options.body as MessageCreateParams);\n const state = ctx.options.fallbackState;\n\n // start from the pinned fallback (-1 = the original params)\n const startIndex = state?.index ?? -1;\n if (!Number.isInteger(startIndex) || startIndex < -1 || startIndex >= fallbacks.length) {\n throw new AnthropicError(\n `fallbackState.index ${startIndex} is out of bounds for a chain of ${fallbacks.length} fallback(s); was the state shared with a different middleware?`,\n );\n }\n\n // pin requests sharing the state to the entry being tried\n const pin = (index: number) => {\n if (state) {\n state.index = index;\n } else if (!warnedMissingState) {\n warnedMissingState = true;\n ctx.logger.warn(\n 'anthropic-sdk: betaRefusalFallbackMiddleware fell back without a `fallbackState` request option; follow-up requests will retry models that already refused. Pass a shared `{ fallbackState: new BetaFallbackState() }` to pin them to the accepted model.',\n );\n }\n };\n\n // a non-string body can't be respliced or redeemed against — leave the\n // request untouched (the streaming path stands down on it below too)\n const initialRequest =\n typeof request.body !== 'string' ?\n request\n : {\n ...request,\n body: JSON.stringify(startIndex === -1 ? body : { ...body, ...fallbacks[startIndex] }),\n };\n\n const response = await next(initialRequest);\n if (!response.ok) {\n return response;\n }\n\n if (ctx.options.stream === true) {\n const firstHop = startIndex + 1;\n // Splicing needs at least one entry left to hop to and the JSON request\n // body the credit token is redeemable against (an earlier middleware\n // may have rewritten it to another BodyInit); otherwise the stream\n // passes through untouched.\n if (firstHop >= fallbacks.length || typeof initialRequest.body !== 'string') {\n return response;\n }\n return spliceFallbackStream({\n request: initialRequest,\n response,\n next,\n ctx,\n fallbacks,\n firstHop,\n onError,\n pin,\n });\n }\n\n let index = startIndex;\n let res = response;\n // The model the current hop was requested as — the caller's spelling, not\n // the server's `message.model` echo; the seam block's `from` carries it.\n let requestedModel = (startIndex === -1 ? body : { ...body, ...fallbacks[startIndex] }).model;\n const fallbackBlocks: BetaFallbackBlock[] = [];\n while (index < fallbacks.length - 1) {\n const message = await ctx.parse<BetaMessage | null>(res);\n if (message?.type !== 'message' || message.stop_reason !== 'refusal') {\n break;\n }\n\n index += 1;\n pin(index);\n const entry = fallbacks[index]!;\n // One `fallback` seam block per model boundary, prepended to the serving\n // hop's content below — the same block shape the server places in\n // `content`, not a claim of full envelope parity.\n fallbackBlocks.push({\n type: 'fallback',\n // `requestedModel` is always set for a typed body; the `??` defends\n // against an untyped body that carried no `model` field.\n from: { model: requestedModel ?? message.model },\n to: { model: entry.model },\n trigger: { type: 'refusal', category: message.stop_details?.category ?? null },\n });\n requestedModel = entry.model;\n res = await next({\n ...request,\n body: JSON.stringify({\n ...body,\n ...entry,\n ...(message.stop_details?.fallback_credit_token ?\n { fallback_credit_token: message.stop_details.fallback_credit_token }\n : undefined),\n }),\n });\n }\n\n if (fallbackBlocks.length === 0) {\n return res;\n }\n const served = await ctx.parse<BetaMessage | null>(res);\n // Chain exhausted on a refusal (or an error/malformed body): surface it\n // verbatim. The array guard keeps a message-shaped body with non-array\n // `content` from throwing at the spread below.\n if (served?.type !== 'message' || served.stop_reason === 'refusal' || !Array.isArray(served.content)) {\n return res;\n }\n // A fallback hop served (or exhausted the chain with output): prepend the\n // seam blocks so the app-visible `content` opens with one `fallback` block\n // per model boundary. Response init is preserved (same `_request_id`);\n // `content-length` is dropped since the body grew.\n const headers = new Headers(res.headers);\n headers.delete('content-length');\n return new Response(JSON.stringify({ ...served, content: [...fallbackBlocks, ...served.content] }), {\n status: res.status,\n statusText: res.statusText,\n headers,\n });\n };\n}\n\n// --- streaming fallback (credit-token continuation) -------------------------\n//\n// The retry uses the appended-assistant form documented on\n// `fallback_credit_token`: the refused request's body, extended by one\n// trailing assistant turn carrying the refused model's partial output. The\n// token authorizes that turn as a prefill continuation and applies the\n// fallback credit. The refusal's `fallback_has_prefill_claim` says whether\n// the partial output may be resent verbatim: when true the accumulated\n// blocks are appended as-is; when false the refused hop's output is dropped\n// and the token is redeemed against the same body.\n//\n// Known divergences from server-side `fallbacks` (applies to both paths):\n//\n// * Seam `to.model` and non-first `from.model` carry the chain entry's\n// spelling, not the canonical id the server emits.\n// * Streaming: `message.model` keeps the refused model's id — `message_start`\n// has already been sent when the refusal arrives; the seam's `to.model`\n// carries the serving model.\n// * Streaming: `usage.iterations` survives stream accumulation only on the\n// beta surface (`client.beta.messages.stream`); the non-beta accumulator\n// drops it. Non-streaming: no `fallback_message` entry is synthesized in\n// `usage.iterations` — the serving hop's `usage` passes through as-is.\n// * Streaming: refusal text streamed before the refusal stays in the message\n// and is resent as-is (the appended turn must match the partial output\n// verbatim). Non-streaming: a refused hop's partial content is dropped.\n// * First-seam `from.model` differs by path: non-streaming uses the caller's\n// body spelling; streaming uses the server's `message.model` echo.\n\ninterface FallbackStreamArgs {\n /** The request stream A was made with — the body its credit token is redeemable against. */\n request: APIRequest;\n /** Stream A: the OK SSE response that may end in a refusal. */\n response: Response;\n next: MiddlewareNext;\n ctx: MiddlewareContext;\n fallbacks: readonly BetaFallbackParam[];\n /** Index into `fallbacks` of the first entry to try when stream A refuses. */\n firstHop: number;\n onError: (error: BetaRefusalFallbackError) => void;\n /** Pin shared state to the entry being tried (or warn that there is none). */\n pin: (index: number) => void;\n}\n\n/**\n * Wrap stream A in a response whose body passes events through until a\n * retryable refusal, then splices the fallback chain's events on (see\n * {@link splicedEvents}). Cancelling the returned body tears down whichever\n * stream is being read and aborts any in-flight fallback request or retry\n * backoff: hop requests run under `controller`'s signal, which fires on\n * cancel and mirrors the original request's signal — a user abort has no\n * other way to reach a hop, since this synthetic body isn't fetch-backed.\n */\nfunction spliceFallbackStream(args: FallbackStreamArgs): Response {\n const controller = new AbortController();\n const signal = args.request.signal;\n if (signal?.aborted) {\n controller.abort(signal.reason);\n } else {\n signal?.addEventListener('abort', makeAbort(controller, signal), { once: true });\n }\n const iter = splicedEvents(args, controller);\n const body = new ReadableStream<Uint8Array>({\n async pull(ctrl) {\n try {\n const { value, done } = await iter.next();\n if (done) return ctrl.close();\n ctrl.enqueue(value);\n } catch (err) {\n ctrl.error(err);\n }\n },\n async cancel() {\n controller.abort();\n await iter.return?.(undefined);\n },\n });\n return new Response(body, args.response);\n}\n\n/** A response content block being accumulated from its streaming deltas. */\ntype AccumulatedBlock = { index: number; block: any };\n\nasync function* splicedEvents(\n { request, response, next, ctx, fallbacks, firstHop, onError, pin }: FallbackStreamArgs,\n controller: AbortController,\n): AsyncGenerator<Uint8Array> {\n // --- stream A: pass through until a chainable refusal ---\n const a = yield* consumeHop({\n response,\n controller,\n indexBase: 0,\n hasNext: true, // the caller guarantees firstHop < fallbacks.length\n onError,\n splice: null,\n });\n if (!a.refused) return; // non-refusal or not-retryable: pure pass-through.\n\n // --- fallback chain: try each entry in order ---\n // `base` is the assistant-turn content the current token's request already\n // carried — the token is redeemable only with it resent verbatim. `partial`\n // is the newest refused hop's output, included only when its refusal\n // granted a prefill claim (any other change to the body is a 400).\n let nextIndex = a.nextIndex; // monotonic block index across all spliced streams\n let token = a.refused.token;\n let base: BetaContentBlockParam[] = [];\n let partial = a.refused.hasPrefillClaim ? toPrefillBlocks(a.blocks) : [];\n let fromModel = a.model ?? '';\n let lastUsage: BetaMessageDeltaUsage | null = a.refused.usage;\n // The refusal whose token is currently in flight — surfaced verbatim (with a\n // recommended_model added) if every fallback request fails and we degrade.\n let refusalDetails = a.refused.stopDetails;\n\n // One `message` entry per refused hop, in order — A first. Failed hops are\n // skipped (no usage came back); the serving hop is appended as\n // `fallback_message` when its message_delta arrives.\n const iterations: BetaMessageIterationUsage[] = [\n toIterationUsage('message', a.model ?? '', a.refused.usage),\n ];\n\n for (let hop = firstHop; hop < fallbacks.length; hop++) {\n const model = fallbacks[hop]!.model;\n const hasNext = hop + 1 < fallbacks.length;\n pin(hop);\n\n // --- boundary: a `fallback` content block at the next monotonic index ---\n // Emitted before the request, so a hop that fails leaves its boundary in\n // place and the next attempt emits its own (still `from: fromModel` — the\n // last model that contributed output).\n const fbIndex = nextIndex++;\n yield emit<BetaRawContentBlockStartEvent>('content_block_start', {\n type: 'content_block_start',\n index: fbIndex,\n content_block: {\n type: 'fallback',\n from: { model: fromModel },\n to: { model },\n trigger: { type: 'refusal', category: refusalDetails?.category ?? null },\n },\n });\n yield emit<BetaRawContentBlockStopEvent>('content_block_stop', {\n type: 'content_block_stop',\n index: fbIndex,\n });\n\n // --- build the request: appended-assistant continuation ---\n // First attempt carries the newest partial appended (when its refusal\n // granted a prefill claim); a 400 on that form means the server rejected\n // the prefill, so the hop is retried once without it — the same-body\n // form the token always supports.\n let continuation = [...base, ...partial];\n let resB: Response | null = null;\n let failure: BetaRefusalFallbackError | null = null;\n for (let attempt = 0; attempt < 2; attempt++) {\n const reqB = buildFallbackRequest(request, { model, creditToken: token, continuation });\n // controller mirrors the original signal and additionally fires when the\n // spliced body is cancelled — either must abort an in-flight hop request.\n reqB.signal = controller.signal;\n\n try {\n resB = await next(reqB);\n } catch (err) {\n // the consumer cancelled (or the original request was aborted): unwind\n if (isAbortError(err)) throw err;\n failure = {\n kind: 'request_failed',\n message: `fallback request failed: ${err}`,\n model,\n status: null,\n detail: err,\n };\n break;\n }\n if (resB.ok) break;\n // ctx.parse reads through an internal clone, so it works even though\n // the client will also read this body; resB.text() would conflict.\n const errBody = await ctx.parse(resB).catch(() => null);\n if (attempt === 0 && resB.status === 400 && partial.length) {\n ctx.logger.warn(\n `anthropic-sdk: betaRefusalFallbackMiddleware: fallback request with the partial output appended was rejected (HTTP 400: ${JSON.stringify(\n errBody,\n )}); retrying without it`,\n );\n continuation = base;\n resB = null;\n continue;\n }\n failure = {\n kind: 'request_failed',\n message: `fallback request failed: HTTP ${resB.status}: ${JSON.stringify(errBody)}`,\n model,\n status: resB.status,\n detail: errBody,\n };\n break;\n }\n\n if (failure) {\n onError(failure);\n // The token was never redeemed — retry it against the next entry.\n if (hasNext) continue;\n // Surface the held refusal verbatim — its category/explanation and the\n // still-unredeemed credit token — and point recommended_model at the hop\n // we last tried.\n const stopDetails: BetaRefusalStopDetails = {\n ...refusalDetails,\n recommended_model: model,\n };\n yield emit<BetaRawMessageDeltaEvent>('message_delta', {\n type: 'message_delta',\n context_management: null,\n delta: {\n stop_reason: 'refusal',\n stop_sequence: null,\n container: null,\n stop_details: stopDetails,\n },\n usage: (lastUsage ?? {}) as BetaMessageDeltaUsage,\n });\n yield emit<BetaRawMessageStopEvent>('message_stop', { type: 'message_stop' });\n return;\n }\n\n // --- splice: monotonic indices, suppressed message_start, usage.iterations ---\n const b = yield* consumeHop({\n response: resB!,\n controller,\n indexBase: nextIndex,\n hasNext,\n onError,\n splice: { iterations, model },\n });\n if (!b.refused) return;\n\n // This hop refused too, with a fresh token: its emitted partial stays in\n // the client's message, becomes the next partial segment, and the chain\n // continues.\n token = b.refused.token;\n refusalDetails = b.refused.stopDetails;\n base = continuation;\n partial = b.refused.hasPrefillClaim ? toPrefillBlocks(b.blocks) : [];\n iterations.push(toIterationUsage('message', model, b.refused.usage));\n lastUsage = b.refused.usage;\n fromModel = model;\n nextIndex = b.nextIndex;\n }\n}\n\n/** The outcome of consuming one hop's stream. */\ninterface HopOutcome {\n /** Set when the hop refused with a credit token and an entry remained to chain to. */\n refused: {\n token: string;\n hasPrefillClaim: boolean;\n usage: BetaMessageDeltaUsage;\n /** The refusal's stop_details verbatim, surfaced if the whole chain degrades. */\n stopDetails: BetaRefusalStopDetails;\n } | null;\n /** The hop's serving model, from its message_start. */\n model: string | undefined;\n /** The hop's accumulated content blocks, in start order — the next partial segment. */\n blocks: any[];\n /** One past the highest (shifted) block index emitted — where the next boundary goes. */\n nextIndex: number;\n}\n\n/**\n * Consume one hop's SSE events, forwarding them to the client while\n * accumulating its content blocks (returned in the outcome).\n *\n * Stream A (`splice: null`) is forwarded in its original wire bytes; a\n * spliced hop (`splice` set) has its message_start suppressed (the client\n * already saw A's), its block indices shifted by `indexBase`, and its\n * terminal message_delta's usage rewritten to the `usage.iterations`\n * chain shape.\n *\n * A refusal that can be chained — it carries a `fallback_credit_token` and a\n * fallback entry remains — ends the hop early: open blocks are closed, the\n * terminal message_delta + message_stop are suppressed, and the token+usage\n * are returned so the caller can issue the next hop. Any other refusal is\n * reported through `onError` and passes through to the client.\n */\nasync function* consumeHop(args: {\n response: Response;\n controller: AbortController;\n /** Shift wire block indices by this much, keeping them monotonic across hops. */\n indexBase: number;\n /** Whether a fallback entry exists to chain to if this hop refuses. */\n hasNext: boolean;\n onError: (error: BetaRefusalFallbackError) => void;\n /** Splice context for fallback hops; null for stream A. */\n splice: { iterations: BetaMessageIterationUsage[]; model: string } | null;\n}): AsyncGenerator<Uint8Array, HopOutcome> {\n const { response, controller, indexBase, hasNext, onError, splice } = args;\n const tracker = new BlockTracker(indexBase);\n let model: string | undefined;\n let startUsage: BetaUsage | null = null;\n\n for await (const sse of Stream.rawEvents(response, controller)) {\n const p = safeJSON(sse.data) as BetaRawMessageStreamEvent | undefined;\n switch (p?.type) {\n case 'message_start': {\n model = p.message.model;\n startUsage = p.message.usage;\n if (splice) continue;\n break;\n }\n case 'content_block_start': {\n tracker.start(p);\n if (splice) {\n yield emit(p.type, p);\n continue;\n }\n break;\n }\n case 'content_block_delta': {\n tracker.delta(p);\n if (splice) {\n yield emit(p.type, p);\n continue;\n }\n break;\n }\n case 'content_block_stop': {\n tracker.stop(p);\n if (splice) {\n yield emit(p.type, p);\n continue;\n }\n break;\n }\n case 'message_delta': {\n if (p.delta.stop_reason === 'refusal') {\n // `fallback_credit_token` is null when the refusal isn't eligible\n // for a fallback credit; without one we don't retry.\n const details = p.delta.stop_details?.type === 'refusal' ? p.delta.stop_details : null;\n if (details?.fallback_credit_token && hasNext) {\n const usage = backfill(p.usage, startUsage);\n yield* tracker.closeOpenBlocks();\n // suppress this hop's message_delta + message_stop\n return {\n refused: {\n token: details.fallback_credit_token,\n hasPrefillClaim: details.fallback_has_prefill_claim === true,\n usage,\n stopDetails: details,\n },\n model,\n blocks: tracker.contentBlocks(),\n nextIndex: tracker.nextIndex,\n };\n }\n if (!details?.fallback_credit_token) {\n onError({\n kind: 'no_credit_token',\n message: 'refusal stop_details has no fallback_credit_token',\n event: p,\n });\n } else {\n onError({\n kind: 'chain_exhausted',\n message: 'refusal but no fallback entries remain',\n event: p,\n });\n }\n }\n if (splice) {\n // Terminal hop. Replace iterations, don't append: this hop's own\n // message_delta self-reports a single `{type:\"message\",\n // model:undefined}` iteration (a fresh non-fallback request counts\n // itself as one message hop). Server-side `fallbacks` relabels the\n // whole chain instead — refused hops as `message`, the serving hop\n // as `fallback_message` — so spreading the self-report would\n // prepend a spurious `message:undefined` entry.\n const usage = backfill(p.usage, startUsage);\n usage.iterations = [\n ...splice.iterations,\n toIterationUsage('fallback_message', splice.model, usage),\n ];\n p.usage = usage;\n yield emit('message_delta', p);\n continue;\n }\n break;\n }\n }\n\n // message_stop, ping, error, unrecognised — and for stream A every\n // event — pass through in their original wire bytes.\n yield passthroughSSE(sse);\n }\n return { refused: null, model, blocks: tracker.contentBlocks(), nextIndex: tracker.nextIndex };\n}\n\n/**\n * Block bookkeeping for one stream of the splice: accumulates each content\n * block from its deltas (for the continuation prefill), shifts wire indices\n * by `indexBase` so they stay monotonic across hops, and tracks which blocks\n * are still open so a refusal that cuts mid-block can close them.\n */\nclass BlockTracker {\n /** The stream's accumulated blocks keyed by their original wire index. */\n private blocks: AccumulatedBlock[] = [];\n /** One past the highest shifted block index seen. */\n nextIndex: number;\n /** Shifted indices of blocks started but not yet stopped. */\n private open: number[] = [];\n\n constructor(private indexBase: number = 0) {\n this.nextIndex = indexBase;\n }\n\n /** The accumulated content blocks, in start order. */\n contentBlocks(): any[] {\n return this.blocks.map((b) => b.block);\n }\n\n /** Track a content_block_start, shifting `event.index`. */\n start(event: BetaRawContentBlockStartEvent): void {\n this.blocks.push({ index: event.index, block: { ...event.content_block } });\n event.index += this.indexBase;\n this.open.push(event.index);\n this.nextIndex = Math.max(this.nextIndex, event.index + 1);\n }\n\n /** Apply a content_block_delta to its accumulating block, shifting `event.index`. */\n delta(event: BetaRawContentBlockDeltaEvent): void {\n applyDelta(this.blocks, event.index, event.delta);\n event.index += this.indexBase;\n }\n\n /** Track a content_block_stop, shifting `event.index`. */\n stop(event: BetaRawContentBlockStopEvent): void {\n event.index += this.indexBase;\n const i = this.open.indexOf(event.index);\n if (i !== -1) this.open.splice(i, 1);\n this.nextIndex = Math.max(this.nextIndex, event.index + 1);\n }\n\n /** content_block_stop events for any blocks still open. */\n *closeOpenBlocks(): Generator<Uint8Array> {\n for (const index of this.open) {\n yield emit<BetaRawContentBlockStopEvent>('content_block_stop', {\n type: 'content_block_stop',\n index,\n });\n }\n this.open.length = 0;\n }\n}\n\n// --- fallback request construction (appended-assistant continuation) -------\n\nfunction buildFallbackRequest(\n orig: APIRequest,\n {\n model,\n creditToken,\n continuation,\n }: {\n model: string;\n creditToken: string;\n continuation: BetaContentBlockParam[];\n },\n): APIRequest {\n // the caller guarantees a JSON string body (checked before stream A is read)\n const body = JSON.parse(orig.body as string);\n\n body.model = model;\n body.fallback_credit_token = creditToken;\n\n // Append the continuation (decided by the chain loop) as a trailing\n // assistant turn; everything else must stay identical to the refused\n // request. When the refusal granted no prefill claim, omit the turn\n // entirely and send the same-body form.\n if (continuation.length) {\n body.messages = [...body.messages, { role: 'assistant', content: continuation }];\n }\n\n // Do NOT touch max_tokens (or any other render-shaping field): the token is\n // only redeemable against the same request body as the refused request —\n // model, fallback_credit_token, and the one appended assistant turn are the\n // only permitted deltas; anything else is a 400 (\"request body ... does not\n // match the original refused request\"). This is also why the per-entry\n // BetaFallbackParam overrides are ignored on the streaming path.\n\n return { ...orig, headers: new Headers(orig.headers), body: JSON.stringify(body) };\n}\n\n// --- block accumulation & prefill conversion -------------------------------\n\n/** Apply a content_block_delta to the accumulating block at `index`. */\nfunction applyDelta(\n blocks: AccumulatedBlock[],\n index: number,\n delta: BetaRawContentBlockDeltaEvent['delta'],\n): void {\n const block = blocks.find((x) => x.index === index)?.block;\n if (!block) return;\n switch (delta.type) {\n case 'text_delta': {\n block.text = (block.text ?? '') + delta.text;\n break;\n }\n case 'input_json_delta': {\n block._partial_json = (block._partial_json ?? '') + delta.partial_json;\n break;\n }\n case 'citations_delta':\n (block.citations ??= []).push(delta.citation);\n break;\n case 'thinking_delta': {\n block.thinking = (block.thinking ?? '') + delta.thinking;\n break;\n }\n case 'signature_delta': {\n block.signature = delta.signature;\n break;\n }\n case 'compaction_delta': {\n break;\n }\n default:\n ((_: never) => {})(delta);\n }\n}\n\n/**\n * Convert a hop's accumulated response blocks to the appended assistant turn,\n * as-is: a `fallback_has_prefill_claim` refusal guarantees the partial output\n * is resendable verbatim, so no client-side filtering is applied. The only\n * rewrite is reassembling tool inputs from their accumulated\n * `input_json_delta` JSON (content_block_start carries `input: {}`).\n */\nfunction toPrefillBlocks(responseBlocks: any[]): BetaContentBlockParam[] {\n return responseBlocks.map((b) => {\n if (typeof b?._partial_json !== 'string') return b;\n const { _partial_json, ...block } = b;\n return { ...block, input: safeJSON(_partial_json) ?? block.input };\n });\n}\n\n// --- helpers --------------------------------------------------------------\n\n/**\n * A copy of `request` with `betas` appended to its `anthropic-beta` header,\n * skipping values already present (set by the caller or another middleware).\n */\nfunction withMiddlewareHeaders(request: APIRequest, betas: readonly AnthropicBeta[]): APIRequest {\n const headers = new Headers(request.headers);\n const existing = new Set(\n headers\n .get('anthropic-beta')\n ?.split(',')\n .map((s) => s.trim()),\n );\n for (const beta of betas) {\n if (!existing.has(beta)) {\n headers.append('anthropic-beta', beta);\n existing.add(beta);\n }\n }\n headers.set(\n STAINLESS_HELPER_HEADER,\n appendHeaderValue(headers.get(STAINLESS_HELPER_HEADER), 'fallback-refusal-middleware'),\n );\n return { ...request, headers };\n}\n\nfunction emit<T extends { type: string }>(event: T['type'], payload: T): Uint8Array {\n const sse: ServerSentEvent = { event, data: JSON.stringify(payload), raw: [] };\n return encoder.encode(serializeSSE(sse));\n}\n\n/**\n * Forward a decoded event in its original wire bytes, preserving SSE fields\n * the decoder doesn't model (`id:`, `retry:`, comment lines). Falls back to\n * re-serializing for events with no raw lines.\n */\nfunction passthroughSSE(sse: ServerSentEvent): Uint8Array {\n return encoder.encode(sse.raw.length ? sse.raw.join('\\n') + '\\n\\n' : serializeSSE(sse));\n}\n\n// Field-wise union of BetaUsage and BetaMessageDeltaUsage, all nullable —\n// a plain Partial<A & B> intersects `number` with `number | null` down to\n// `number`, which rejects delta usage objects.\ntype UsageLike =\n | { [K in keyof (BetaUsage & BetaMessageDeltaUsage)]?: (BetaUsage & BetaMessageDeltaUsage)[K] | null }\n | null\n | undefined;\n\nfunction toIterationUsage(type: 'message', model: string, u: UsageLike): BetaMessageIterationUsage;\nfunction toIterationUsage(\n type: 'fallback_message',\n model: string,\n u: UsageLike,\n): BetaFallbackMessageIterationUsage;\nfunction toIterationUsage(\n type: 'message' | 'fallback_message',\n model: string,\n u: UsageLike,\n): BetaMessageIterationUsage | BetaFallbackMessageIterationUsage {\n return {\n type,\n model,\n input_tokens: u?.input_tokens ?? 0,\n output_tokens: u?.output_tokens ?? 0,\n cache_read_input_tokens: u?.cache_read_input_tokens ?? 0,\n cache_creation_input_tokens: u?.cache_creation_input_tokens ?? 0,\n cache_creation: u?.cache_creation ?? null,\n };\n}\n\n/** Fill null/undefined fields on `primary` from `fallback`. */\nfunction backfill(\n primary: BetaMessageDeltaUsage | null | undefined,\n fallback: BetaUsage | null | undefined,\n): BetaMessageDeltaUsage {\n const out: any = { ...(fallback ?? {}), ...(primary ?? {}) };\n for (const k of Object.keys(out)) {\n if (out[k] == null && (fallback as any)?.[k] != null) out[k] = (fallback as any)[k];\n }\n return out;\n}\n\n/**\n * Serialize a {@link ServerSentEvent} back to its SSE wire form\n * (`event: ...\\ndata: ...\\n\\n`). Multi-line `data` is emitted as one\n * `data:` line per line, matching the spec. The inverse of the decoder\n * behind {@link Stream.rawEvents}.\n */\nfunction serializeSSE(sse: ServerSentEvent): string {\n let out = '';\n if (sse.event !== null) out += `event: ${sse.event}\\n`;\n for (const line of sse.data.split('\\n')) out += `data: ${line}\\n`;\n return out + '\\n';\n}\n\nfunction makeAbort(controller: AbortController, signal: AbortSignal) {\n return () => controller.abort(signal.reason);\n}\n"],"mappings":";;;;;;;;;;;AAIA,aAAS,OAAO,MAAe,MAAM,IAAE;AACrC,UAAI,CAAC,MAAM;AACT,cAAM,IAAI,MAAM,GAAG;MACrB;IACF;AAIA,aAAgB,gBACd,GACA,GAA+C;AAE/C,UAAI,EAAE,eAAe,EAAE,YAAY;AACjC,eAAO;MACT;AACA,UAAI,EAAE,aAAa,WAAW;AAC5B,YAAI,IAAI,SAAS,YAAY,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC;MACvD;AACA,UAAI,EAAE,aAAa,WAAW;AAC5B,YAAI,IAAI,SAAS,YAAY,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC;MACvD;AACA,aAAO,aAAa,QAAQ;AAC5B,aAAO,aAAa,QAAQ;AAC5B,YAAM,SAAS,EAAE;AACjB,UAAI,MAAM;AACV,UAAI,IAAI;AACR,aAAO,EAAE,IAAI,QAAQ;AACnB,eAAO,EAAE,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC;MACrC;AACA,aAAO,QAAQ;IACjB;AAtBA,YAAA,kBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;ACFA,QAAM,eAAe;AAOrB,QAAA;;OAAA,WAAA;AAGI,iBAAAA,OAAoB,mBAAuB;AAAvB,cAAA,sBAAA,QAAA;AAAA,gCAAA;UAAuB;AAAvB,eAAA,oBAAA;QAA2B;AAE/C,QAAAA,OAAA,UAAA,gBAAA,SAAc,QAAc;AACxB,cAAI,CAAC,KAAK,mBAAmB;AACzB,oBAAQ,SAAS,IAAI,KAAK,IAAI;;AAElC,kBAAQ,SAAS,KAAK,IAAI,IAAI;QAClC;AAEA,QAAAA,OAAA,UAAA,SAAA,SAAO,MAAgB;AACnB,cAAI,MAAM;AAEV,cAA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iB;AAMpB,IAAO,YAAP,cAAyB,cAAa;EAA5C,cAAA;;AACE,SAAA,cAA+B,IAAQ,YAAY,IAAI;AACvD,SAAA,WAAyB,IAAQM,UAAS,IAAI;AAC9C,SAAA,SAAqB,IAAQC,QAAO,IAAI;AACxC,SAAA,OAAiB,IAAQ,KAAK,IAAI;EACpC;;AAEA,UAAU,cAAc;AACxB,UAAU,WAAWD;AACrB,UAAU,SAASC;AACnB,UAAU,OAAO;;;AClgDjB,IAAM,UAAU,IAAI,YAAW;","names":["Coder","encode","URLSafeCoder","exports","Hash","HMAC","hmac","Webhook","encoder","ReadableStream","encoder","path","token","encoder","path","_a","path","path","Page","client","process","fetch","path","backoff","_SessionToolRunner_streamLoop","backoff","_SessionToolRunner_reconcile","_SessionToolRunner_ingestHistory","_SessionToolRunner_handleStreamEvent","_SessionToolRunner_armIdleTimer","_SessionToolRunner_disarmIdleTimer","_SessionToolRunner_execute","_a","_SessionToolRunner_sendResult","_SessionToolRunner_drain","_EnvironmentWorker_handleItem","_BetaMessageStream_getFinalMessage","_BetaMessageStream_getFinalText","_BetaMessageStream_beginRequest","_BetaMessageStream_addStreamEvent","_BetaMessageStream_endRequest","_BetaMessageStream_accumulateMessage","_BetaMessageStream_toolInputParseError","chunk","_BetaToolRunner_checkAndCompact","_a","_BetaToolRunner_generateToolResponse","helperHeader","Events","Events","Versions","Versions","getOutputFormat","tracksToolInput","_MessageStream_getFinalMessage","_MessageStream_getFinalText","_MessageStream_beginRequest","_MessageStream_addStreamEvent","checkNever","_MessageStream_endRequest","_MessageStream_accumulateMessage","chunk","Batches","Messages","Batches","DEPRECATED_MODELS","MODELS_TO_WARN_WITH_THINKING_ENABLED","helperHeader","Models","path","opts","retryMessage","err","Page","jitter","Messages","Models"]}