@goondocks/myco 0.2.12 → 0.2.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/dist/{chunk-AOMX45LH.js → chunk-6C26YFOA.js} +4 -6
- package/dist/{chunk-AOMX45LH.js.map → chunk-6C26YFOA.js.map} +1 -1
- package/dist/{chunk-TWDS6MSU.js → chunk-BXFS4PCJ.js} +2 -2
- package/dist/{chunk-SVUINMDD.js → chunk-C2YPBQQM.js} +3 -3
- package/dist/{chunk-ZJQ5G637.js → chunk-MAFUTKOZ.js} +2 -2
- package/dist/{chunk-ZTZVX5E6.js → chunk-NKJIZSPD.js} +3 -3
- package/dist/{chunk-NYNEJ5QY.js → chunk-O5VSPHDL.js} +40 -1
- package/dist/{chunk-NYNEJ5QY.js.map → chunk-O5VSPHDL.js.map} +1 -1
- package/dist/{chunk-TH6GIBXG.js → chunk-S4WBXXO6.js} +2 -2
- package/dist/{chunk-4JML636J.js → chunk-UUFDD2FB.js} +6 -2
- package/dist/chunk-UUFDD2FB.js.map +1 -0
- package/dist/{chunk-UIIZRTJU.js → chunk-YXZEP5U6.js} +2 -2
- package/dist/{cli-K5FSKLQC.js → cli-KMWJFK5Y.js} +8 -10
- package/dist/{cli-K5FSKLQC.js.map → cli-KMWJFK5Y.js.map} +1 -1
- package/dist/client-TEUHXGOY.js +10 -0
- package/dist/{main-5W4ADOBG.js → main-UJAXPP6S.js} +39 -19
- package/dist/{main-5W4ADOBG.js.map → main-UJAXPP6S.js.map} +1 -1
- package/dist/{server-PIEPVUUH.js → server-J3AQ3YFA.js} +11 -21
- package/dist/{server-PIEPVUUH.js.map → server-J3AQ3YFA.js.map} +1 -1
- package/dist/{session-start-2NNQHT5S.js → session-start-BEC4JMNZ.js} +6 -7
- package/dist/{session-start-2NNQHT5S.js.map → session-start-BEC4JMNZ.js.map} +1 -1
- package/dist/src/cli.js +4 -3
- package/dist/src/cli.js.map +1 -1
- package/dist/src/daemon/main.js +5 -3
- package/dist/src/daemon/main.js.map +1 -1
- package/dist/src/hooks/post-tool-use.js +4 -5
- package/dist/src/hooks/post-tool-use.js.map +1 -1
- package/dist/src/hooks/session-end.js +4 -5
- package/dist/src/hooks/session-end.js.map +1 -1
- package/dist/src/hooks/session-start.js +4 -3
- package/dist/src/hooks/session-start.js.map +1 -1
- package/dist/src/hooks/stop.js +5 -6
- package/dist/src/hooks/stop.js.map +1 -1
- package/dist/src/hooks/user-prompt-submit.js +4 -5
- package/dist/src/hooks/user-prompt-submit.js.map +1 -1
- package/dist/src/mcp/server.js +5 -3
- package/dist/src/mcp/server.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-4JML636J.js.map +0 -1
- package/dist/chunk-PZUWP5VK.js +0 -44
- package/dist/client-4JMOYNKK.js +0 -11
- package/dist/client-4JMOYNKK.js.map +0 -1
- /package/dist/{chunk-TWDS6MSU.js.map → chunk-BXFS4PCJ.js.map} +0 -0
- /package/dist/{chunk-SVUINMDD.js.map → chunk-C2YPBQQM.js.map} +0 -0
- /package/dist/{chunk-ZJQ5G637.js.map → chunk-MAFUTKOZ.js.map} +0 -0
- /package/dist/{chunk-ZTZVX5E6.js.map → chunk-NKJIZSPD.js.map} +0 -0
- /package/dist/{chunk-TH6GIBXG.js.map → chunk-S4WBXXO6.js.map} +0 -0
- /package/dist/{chunk-UIIZRTJU.js.map → chunk-YXZEP5U6.js.map} +0 -0
- /package/dist/{chunk-PZUWP5VK.js.map → client-TEUHXGOY.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/kind-of/index.js","../node_modules/is-extendable/index.js","../node_modules/extend-shallow/index.js","../node_modules/section-matter/index.js","../node_modules/js-yaml/lib/js-yaml/common.js","../node_modules/js-yaml/lib/js-yaml/exception.js","../node_modules/js-yaml/lib/js-yaml/mark.js","../node_modules/js-yaml/lib/js-yaml/type.js","../node_modules/js-yaml/lib/js-yaml/schema.js","../node_modules/js-yaml/lib/js-yaml/type/str.js","../node_modules/js-yaml/lib/js-yaml/type/seq.js","../node_modules/js-yaml/lib/js-yaml/type/map.js","../node_modules/js-yaml/lib/js-yaml/schema/failsafe.js","../node_modules/js-yaml/lib/js-yaml/type/null.js","../node_modules/js-yaml/lib/js-yaml/type/bool.js","../node_modules/js-yaml/lib/js-yaml/type/int.js","../node_modules/js-yaml/lib/js-yaml/type/float.js","../node_modules/js-yaml/lib/js-yaml/schema/json.js","../node_modules/js-yaml/lib/js-yaml/schema/core.js","../node_modules/js-yaml/lib/js-yaml/type/timestamp.js","../node_modules/js-yaml/lib/js-yaml/type/merge.js","../node_modules/js-yaml/lib/js-yaml/type/binary.js","../node_modules/js-yaml/lib/js-yaml/type/omap.js","../node_modules/js-yaml/lib/js-yaml/type/pairs.js","../node_modules/js-yaml/lib/js-yaml/type/set.js","../node_modules/js-yaml/lib/js-yaml/schema/default_safe.js","../node_modules/js-yaml/lib/js-yaml/type/js/undefined.js","../node_modules/js-yaml/lib/js-yaml/type/js/regexp.js","../node_modules/js-yaml/lib/js-yaml/type/js/function.js","../node_modules/js-yaml/lib/js-yaml/schema/default_full.js","../node_modules/js-yaml/lib/js-yaml/loader.js","../node_modules/js-yaml/lib/js-yaml/dumper.js","../node_modules/js-yaml/lib/js-yaml.js","../node_modules/js-yaml/index.js","../node_modules/gray-matter/lib/engines.js","../node_modules/strip-bom-string/index.js","../node_modules/gray-matter/lib/utils.js","../node_modules/gray-matter/lib/defaults.js","../node_modules/gray-matter/lib/engine.js","../node_modules/gray-matter/lib/stringify.js","../node_modules/gray-matter/lib/excerpt.js","../node_modules/gray-matter/lib/to-file.js","../node_modules/gray-matter/lib/parse.js","../node_modules/gray-matter/index.js","../src/index/fts.ts","../src/intelligence/embeddings.ts","../src/vault/types.ts","../src/vault/reader.ts","../src/index/rebuild.ts","../src/daemon/logger.ts","../src/intelligence/ollama.ts","../src/intelligence/lm-studio.ts","../node_modules/@anthropic-ai/sdk/internal/tslib.mjs","../node_modules/@anthropic-ai/sdk/src/internal/utils/uuid.ts","../node_modules/@anthropic-ai/sdk/src/internal/errors.ts","../node_modules/@anthropic-ai/sdk/src/core/error.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/values.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/utils/bytes.ts","../node_modules/@anthropic-ai/sdk/src/internal/decoders/line.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/log.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/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/lib/stainless-helper-header.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/path.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/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/lib/BetaMessageStream.ts","../node_modules/@anthropic-ai/sdk/src/lib/tools/ToolError.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/internal/decoders/jsonl.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/messages/batches.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/messages/messages.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/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/internal/utils/env.ts","../node_modules/@anthropic-ai/sdk/src/client.ts","../src/intelligence/anthropic.ts","../src/intelligence/llm.ts","../src/index/vectors.ts"],"sourcesContent":["var toString = Object.prototype.toString;\n\nmodule.exports = function kindOf(val) {\n if (val === void 0) return 'undefined';\n if (val === null) return 'null';\n\n var type = typeof val;\n if (type === 'boolean') return 'boolean';\n if (type === 'string') return 'string';\n if (type === 'number') return 'number';\n if (type === 'symbol') return 'symbol';\n if (type === 'function') {\n return isGeneratorFn(val) ? 'generatorfunction' : 'function';\n }\n\n if (isArray(val)) return 'array';\n if (isBuffer(val)) return 'buffer';\n if (isArguments(val)) return 'arguments';\n if (isDate(val)) return 'date';\n if (isError(val)) return 'error';\n if (isRegexp(val)) return 'regexp';\n\n switch (ctorName(val)) {\n case 'Symbol': return 'symbol';\n case 'Promise': return 'promise';\n\n // Set, Map, WeakSet, WeakMap\n case 'WeakMap': return 'weakmap';\n case 'WeakSet': return 'weakset';\n case 'Map': return 'map';\n case 'Set': return 'set';\n\n // 8-bit typed arrays\n case 'Int8Array': return 'int8array';\n case 'Uint8Array': return 'uint8array';\n case 'Uint8ClampedArray': return 'uint8clampedarray';\n\n // 16-bit typed arrays\n case 'Int16Array': return 'int16array';\n case 'Uint16Array': return 'uint16array';\n\n // 32-bit typed arrays\n case 'Int32Array': return 'int32array';\n case 'Uint32Array': return 'uint32array';\n case 'Float32Array': return 'float32array';\n case 'Float64Array': return 'float64array';\n }\n\n if (isGeneratorObj(val)) {\n return 'generator';\n }\n\n // Non-plain objects\n type = toString.call(val);\n switch (type) {\n case '[object Object]': return 'object';\n // iterators\n case '[object Map Iterator]': return 'mapiterator';\n case '[object Set Iterator]': return 'setiterator';\n case '[object String Iterator]': return 'stringiterator';\n case '[object Array Iterator]': return 'arrayiterator';\n }\n\n // other\n return type.slice(8, -1).toLowerCase().replace(/\\s/g, '');\n};\n\nfunction ctorName(val) {\n return typeof val.constructor === 'function' ? val.constructor.name : null;\n}\n\nfunction isArray(val) {\n if (Array.isArray) return Array.isArray(val);\n return val instanceof Array;\n}\n\nfunction isError(val) {\n return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number');\n}\n\nfunction isDate(val) {\n if (val instanceof Date) return true;\n return typeof val.toDateString === 'function'\n && typeof val.getDate === 'function'\n && typeof val.setDate === 'function';\n}\n\nfunction isRegexp(val) {\n if (val instanceof RegExp) return true;\n return typeof val.flags === 'string'\n && typeof val.ignoreCase === 'boolean'\n && typeof val.multiline === 'boolean'\n && typeof val.global === 'boolean';\n}\n\nfunction isGeneratorFn(name, val) {\n return ctorName(name) === 'GeneratorFunction';\n}\n\nfunction isGeneratorObj(val) {\n return typeof val.throw === 'function'\n && typeof val.return === 'function'\n && typeof val.next === 'function';\n}\n\nfunction isArguments(val) {\n try {\n if (typeof val.length === 'number' && typeof val.callee === 'function') {\n return true;\n }\n } catch (err) {\n if (err.message.indexOf('callee') !== -1) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * If you need to support Safari 5-7 (8-10 yr-old browser),\n * take a look at https://github.com/feross/is-buffer\n */\n\nfunction isBuffer(val) {\n if (val.constructor && typeof val.constructor.isBuffer === 'function') {\n return val.constructor.isBuffer(val);\n }\n return false;\n}\n","/*!\n * is-extendable <https://github.com/jonschlinkert/is-extendable>\n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function isExtendable(val) {\n return typeof val !== 'undefined' && val !== null\n && (typeof val === 'object' || typeof val === 'function');\n};\n","'use strict';\n\nvar isObject = require('is-extendable');\n\nmodule.exports = function extend(o/*, objects*/) {\n if (!isObject(o)) { o = {}; }\n\n var len = arguments.length;\n for (var i = 1; i < len; i++) {\n var obj = arguments[i];\n\n if (isObject(obj)) {\n assign(o, obj);\n }\n }\n return o;\n};\n\nfunction assign(a, b) {\n for (var key in b) {\n if (hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n}\n\n/**\n * Returns true if the given `key` is an own property of `obj`.\n */\n\nfunction hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n","'use strict';\n\nvar typeOf = require('kind-of');\nvar extend = require('extend-shallow');\n\n/**\n * Parse sections in `input` with the given `options`.\n *\n * ```js\n * var sections = require('{%= name %}');\n * var result = sections(input, options);\n * // { content: 'Content before sections', sections: [] }\n * ```\n * @param {String|Buffer|Object} `input` If input is an object, it's `content` property must be a string or buffer.\n * @param {Object} options\n * @return {Object} Returns an object with a `content` string and an array of `sections` objects.\n * @api public\n */\n\nmodule.exports = function(input, options) {\n if (typeof options === 'function') {\n options = { parse: options };\n }\n\n var file = toObject(input);\n var defaults = {section_delimiter: '---', parse: identity};\n var opts = extend({}, defaults, options);\n var delim = opts.section_delimiter;\n var lines = file.content.split(/\\r?\\n/);\n var sections = null;\n var section = createSection();\n var content = [];\n var stack = [];\n\n function initSections(val) {\n file.content = val;\n sections = [];\n content = [];\n }\n\n function closeSection(val) {\n if (stack.length) {\n section.key = getKey(stack[0], delim);\n section.content = val;\n opts.parse(section, sections);\n sections.push(section);\n section = createSection();\n content = [];\n stack = [];\n }\n }\n\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n var len = stack.length;\n var ln = line.trim();\n\n if (isDelimiter(ln, delim)) {\n if (ln.length === 3 && i !== 0) {\n if (len === 0 || len === 2) {\n content.push(line);\n continue;\n }\n stack.push(ln);\n section.data = content.join('\\n');\n content = [];\n continue;\n }\n\n if (sections === null) {\n initSections(content.join('\\n'));\n }\n\n if (len === 2) {\n closeSection(content.join('\\n'));\n }\n\n stack.push(ln);\n continue;\n }\n\n content.push(line);\n }\n\n if (sections === null) {\n initSections(content.join('\\n'));\n } else {\n closeSection(content.join('\\n'));\n }\n\n file.sections = sections;\n return file;\n};\n\nfunction isDelimiter(line, delim) {\n if (line.slice(0, delim.length) !== delim) {\n return false;\n }\n if (line.charAt(delim.length + 1) === delim.slice(-1)) {\n return false;\n }\n return true;\n}\n\nfunction toObject(input) {\n if (typeOf(input) !== 'object') {\n input = { content: input };\n }\n\n if (typeof input.content !== 'string' && !isBuffer(input.content)) {\n throw new TypeError('expected a buffer or string');\n }\n\n input.content = input.content.toString();\n input.sections = [];\n return input;\n}\n\nfunction getKey(val, delim) {\n return val ? val.slice(delim.length).trim() : '';\n}\n\nfunction createSection() {\n return { key: '', data: '', content: '' };\n}\n\nfunction identity(val) {\n return val;\n}\n\nfunction isBuffer(val) {\n if (val && val.constructor && typeof val.constructor.isBuffer === 'function') {\n return val.constructor.isBuffer(val);\n }\n return false;\n}\n","'use strict';\n\n\nfunction isNothing(subject) {\n return (typeof subject === 'undefined') || (subject === null);\n}\n\n\nfunction isObject(subject) {\n return (typeof subject === 'object') && (subject !== null);\n}\n\n\nfunction toArray(sequence) {\n if (Array.isArray(sequence)) return sequence;\n else if (isNothing(sequence)) return [];\n\n return [ sequence ];\n}\n\n\nfunction extend(target, source) {\n var index, length, key, sourceKeys;\n\n if (source) {\n sourceKeys = Object.keys(source);\n\n for (index = 0, length = sourceKeys.length; index < length; index += 1) {\n key = sourceKeys[index];\n target[key] = source[key];\n }\n }\n\n return target;\n}\n\n\nfunction repeat(string, count) {\n var result = '', cycle;\n\n for (cycle = 0; cycle < count; cycle += 1) {\n result += string;\n }\n\n return result;\n}\n\n\nfunction isNegativeZero(number) {\n return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);\n}\n\n\nmodule.exports.isNothing = isNothing;\nmodule.exports.isObject = isObject;\nmodule.exports.toArray = toArray;\nmodule.exports.repeat = repeat;\nmodule.exports.isNegativeZero = isNegativeZero;\nmodule.exports.extend = extend;\n","// YAML error class. http://stackoverflow.com/questions/8458984\n//\n'use strict';\n\nfunction YAMLException(reason, mark) {\n // Super constructor\n Error.call(this);\n\n this.name = 'YAMLException';\n this.reason = reason;\n this.mark = mark;\n this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');\n\n // Include stack trace in error object\n if (Error.captureStackTrace) {\n // Chrome and NodeJS\n Error.captureStackTrace(this, this.constructor);\n } else {\n // FF, IE 10+ and Safari 6+. Fallback for others\n this.stack = (new Error()).stack || '';\n }\n}\n\n\n// Inherit from Error\nYAMLException.prototype = Object.create(Error.prototype);\nYAMLException.prototype.constructor = YAMLException;\n\n\nYAMLException.prototype.toString = function toString(compact) {\n var result = this.name + ': ';\n\n result += this.reason || '(unknown reason)';\n\n if (!compact && this.mark) {\n result += ' ' + this.mark.toString();\n }\n\n return result;\n};\n\n\nmodule.exports = YAMLException;\n","'use strict';\n\n\nvar common = require('./common');\n\n\nfunction Mark(name, buffer, position, line, column) {\n this.name = name;\n this.buffer = buffer;\n this.position = position;\n this.line = line;\n this.column = column;\n}\n\n\nMark.prototype.getSnippet = function getSnippet(indent, maxLength) {\n var head, start, tail, end, snippet;\n\n if (!this.buffer) return null;\n\n indent = indent || 4;\n maxLength = maxLength || 75;\n\n head = '';\n start = this.position;\n\n while (start > 0 && '\\x00\\r\\n\\x85\\u2028\\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {\n start -= 1;\n if (this.position - start > (maxLength / 2 - 1)) {\n head = ' ... ';\n start += 5;\n break;\n }\n }\n\n tail = '';\n end = this.position;\n\n while (end < this.buffer.length && '\\x00\\r\\n\\x85\\u2028\\u2029'.indexOf(this.buffer.charAt(end)) === -1) {\n end += 1;\n if (end - this.position > (maxLength / 2 - 1)) {\n tail = ' ... ';\n end -= 5;\n break;\n }\n }\n\n snippet = this.buffer.slice(start, end);\n\n return common.repeat(' ', indent) + head + snippet + tail + '\\n' +\n common.repeat(' ', indent + this.position - start + head.length) + '^';\n};\n\n\nMark.prototype.toString = function toString(compact) {\n var snippet, where = '';\n\n if (this.name) {\n where += 'in \"' + this.name + '\" ';\n }\n\n where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);\n\n if (!compact) {\n snippet = this.getSnippet();\n\n if (snippet) {\n where += ':\\n' + snippet;\n }\n }\n\n return where;\n};\n\n\nmodule.exports = Mark;\n","'use strict';\n\nvar YAMLException = require('./exception');\n\nvar TYPE_CONSTRUCTOR_OPTIONS = [\n 'kind',\n 'resolve',\n 'construct',\n 'instanceOf',\n 'predicate',\n 'represent',\n 'defaultStyle',\n 'styleAliases'\n];\n\nvar YAML_NODE_KINDS = [\n 'scalar',\n 'sequence',\n 'mapping'\n];\n\nfunction compileStyleAliases(map) {\n var result = {};\n\n if (map !== null) {\n Object.keys(map).forEach(function (style) {\n map[style].forEach(function (alias) {\n result[String(alias)] = style;\n });\n });\n }\n\n return result;\n}\n\nfunction Type(tag, options) {\n options = options || {};\n\n Object.keys(options).forEach(function (name) {\n if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {\n throw new YAMLException('Unknown option \"' + name + '\" is met in definition of \"' + tag + '\" YAML type.');\n }\n });\n\n // TODO: Add tag format check.\n this.tag = tag;\n this.kind = options['kind'] || null;\n this.resolve = options['resolve'] || function () { return true; };\n this.construct = options['construct'] || function (data) { return data; };\n this.instanceOf = options['instanceOf'] || null;\n this.predicate = options['predicate'] || null;\n this.represent = options['represent'] || null;\n this.defaultStyle = options['defaultStyle'] || null;\n this.styleAliases = compileStyleAliases(options['styleAliases'] || null);\n\n if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n throw new YAMLException('Unknown kind \"' + this.kind + '\" is specified for \"' + tag + '\" YAML type.');\n }\n}\n\nmodule.exports = Type;\n","'use strict';\n\n/*eslint-disable max-len*/\n\nvar common = require('./common');\nvar YAMLException = require('./exception');\nvar Type = require('./type');\n\n\nfunction compileList(schema, name, result) {\n var exclude = [];\n\n schema.include.forEach(function (includedSchema) {\n result = compileList(includedSchema, name, result);\n });\n\n schema[name].forEach(function (currentType) {\n result.forEach(function (previousType, previousIndex) {\n if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {\n exclude.push(previousIndex);\n }\n });\n\n result.push(currentType);\n });\n\n return result.filter(function (type, index) {\n return exclude.indexOf(index) === -1;\n });\n}\n\n\nfunction compileMap(/* lists... */) {\n var result = {\n scalar: {},\n sequence: {},\n mapping: {},\n fallback: {}\n }, index, length;\n\n function collectType(type) {\n result[type.kind][type.tag] = result['fallback'][type.tag] = type;\n }\n\n for (index = 0, length = arguments.length; index < length; index += 1) {\n arguments[index].forEach(collectType);\n }\n return result;\n}\n\n\nfunction Schema(definition) {\n this.include = definition.include || [];\n this.implicit = definition.implicit || [];\n this.explicit = definition.explicit || [];\n\n this.implicit.forEach(function (type) {\n if (type.loadKind && type.loadKind !== 'scalar') {\n throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');\n }\n });\n\n this.compiledImplicit = compileList(this, 'implicit', []);\n this.compiledExplicit = compileList(this, 'explicit', []);\n this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);\n}\n\n\nSchema.DEFAULT = null;\n\n\nSchema.create = function createSchema() {\n var schemas, types;\n\n switch (arguments.length) {\n case 1:\n schemas = Schema.DEFAULT;\n types = arguments[0];\n break;\n\n case 2:\n schemas = arguments[0];\n types = arguments[1];\n break;\n\n default:\n throw new YAMLException('Wrong number of arguments for Schema.create function');\n }\n\n schemas = common.toArray(schemas);\n types = common.toArray(types);\n\n if (!schemas.every(function (schema) { return schema instanceof Schema; })) {\n throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');\n }\n\n if (!types.every(function (type) { return type instanceof Type; })) {\n throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');\n }\n\n return new Schema({\n include: schemas,\n explicit: types\n });\n};\n\n\nmodule.exports = Schema;\n","'use strict';\n\nvar Type = require('../type');\n\nmodule.exports = new Type('tag:yaml.org,2002:str', {\n kind: 'scalar',\n construct: function (data) { return data !== null ? data : ''; }\n});\n","'use strict';\n\nvar Type = require('../type');\n\nmodule.exports = new Type('tag:yaml.org,2002:seq', {\n kind: 'sequence',\n construct: function (data) { return data !== null ? data : []; }\n});\n","'use strict';\n\nvar Type = require('../type');\n\nmodule.exports = new Type('tag:yaml.org,2002:map', {\n kind: 'mapping',\n construct: function (data) { return data !== null ? data : {}; }\n});\n","// Standard YAML's Failsafe schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2802346\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n explicit: [\n require('../type/str'),\n require('../type/seq'),\n require('../type/map')\n ]\n});\n","'use strict';\n\nvar Type = require('../type');\n\nfunction resolveYamlNull(data) {\n if (data === null) return true;\n\n var max = data.length;\n\n return (max === 1 && data === '~') ||\n (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));\n}\n\nfunction constructYamlNull() {\n return null;\n}\n\nfunction isNull(object) {\n return object === null;\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:null', {\n kind: 'scalar',\n resolve: resolveYamlNull,\n construct: constructYamlNull,\n predicate: isNull,\n represent: {\n canonical: function () { return '~'; },\n lowercase: function () { return 'null'; },\n uppercase: function () { return 'NULL'; },\n camelcase: function () { return 'Null'; }\n },\n defaultStyle: 'lowercase'\n});\n","'use strict';\n\nvar Type = require('../type');\n\nfunction resolveYamlBoolean(data) {\n if (data === null) return false;\n\n var max = data.length;\n\n return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||\n (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));\n}\n\nfunction constructYamlBoolean(data) {\n return data === 'true' ||\n data === 'True' ||\n data === 'TRUE';\n}\n\nfunction isBoolean(object) {\n return Object.prototype.toString.call(object) === '[object Boolean]';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:bool', {\n kind: 'scalar',\n resolve: resolveYamlBoolean,\n construct: constructYamlBoolean,\n predicate: isBoolean,\n represent: {\n lowercase: function (object) { return object ? 'true' : 'false'; },\n uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },\n camelcase: function (object) { return object ? 'True' : 'False'; }\n },\n defaultStyle: 'lowercase'\n});\n","'use strict';\n\nvar common = require('../common');\nvar Type = require('../type');\n\nfunction isHexCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||\n ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||\n ((0x61/* a */ <= c) && (c <= 0x66/* f */));\n}\n\nfunction isOctCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));\n}\n\nfunction isDecCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));\n}\n\nfunction resolveYamlInteger(data) {\n if (data === null) return false;\n\n var max = data.length,\n index = 0,\n hasDigits = false,\n ch;\n\n if (!max) return false;\n\n ch = data[index];\n\n // sign\n if (ch === '-' || ch === '+') {\n ch = data[++index];\n }\n\n if (ch === '0') {\n // 0\n if (index + 1 === max) return true;\n ch = data[++index];\n\n // base 2, base 8, base 16\n\n if (ch === 'b') {\n // base 2\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (ch !== '0' && ch !== '1') return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n\n if (ch === 'x') {\n // base 16\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isHexCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n // base 8\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isOctCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n // base 10 (except 0) or base 60\n\n // value should not start with `_`;\n if (ch === '_') return false;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (ch === ':') break;\n if (!isDecCode(data.charCodeAt(index))) {\n return false;\n }\n hasDigits = true;\n }\n\n // Should have digits and should not end with `_`\n if (!hasDigits || ch === '_') return false;\n\n // if !base60 - done;\n if (ch !== ':') return true;\n\n // base60 almost not used, no needs to optimize\n return /^(:[0-5]?[0-9])+$/.test(data.slice(index));\n}\n\nfunction constructYamlInteger(data) {\n var value = data, sign = 1, ch, base, digits = [];\n\n if (value.indexOf('_') !== -1) {\n value = value.replace(/_/g, '');\n }\n\n ch = value[0];\n\n if (ch === '-' || ch === '+') {\n if (ch === '-') sign = -1;\n value = value.slice(1);\n ch = value[0];\n }\n\n if (value === '0') return 0;\n\n if (ch === '0') {\n if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);\n if (value[1] === 'x') return sign * parseInt(value, 16);\n return sign * parseInt(value, 8);\n }\n\n if (value.indexOf(':') !== -1) {\n value.split(':').forEach(function (v) {\n digits.unshift(parseInt(v, 10));\n });\n\n value = 0;\n base = 1;\n\n digits.forEach(function (d) {\n value += (d * base);\n base *= 60;\n });\n\n return sign * value;\n\n }\n\n return sign * parseInt(value, 10);\n}\n\nfunction isInteger(object) {\n return (Object.prototype.toString.call(object)) === '[object Number]' &&\n (object % 1 === 0 && !common.isNegativeZero(object));\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:int', {\n kind: 'scalar',\n resolve: resolveYamlInteger,\n construct: constructYamlInteger,\n predicate: isInteger,\n represent: {\n binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },\n octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },\n decimal: function (obj) { return obj.toString(10); },\n /* eslint-disable max-len */\n hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }\n },\n defaultStyle: 'decimal',\n styleAliases: {\n binary: [ 2, 'bin' ],\n octal: [ 8, 'oct' ],\n decimal: [ 10, 'dec' ],\n hexadecimal: [ 16, 'hex' ]\n }\n});\n","'use strict';\n\nvar common = require('../common');\nvar Type = require('../type');\n\nvar YAML_FLOAT_PATTERN = new RegExp(\n // 2.5e4, 2.5 and integers\n '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +\n // .2e4, .2\n // special case, seems not from spec\n '|\\\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +\n // 20:59\n '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]*' +\n // .inf\n '|[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$');\n\nfunction resolveYamlFloat(data) {\n if (data === null) return false;\n\n if (!YAML_FLOAT_PATTERN.test(data) ||\n // Quick hack to not allow integers end with `_`\n // Probably should update regexp & check speed\n data[data.length - 1] === '_') {\n return false;\n }\n\n return true;\n}\n\nfunction constructYamlFloat(data) {\n var value, sign, base, digits;\n\n value = data.replace(/_/g, '').toLowerCase();\n sign = value[0] === '-' ? -1 : 1;\n digits = [];\n\n if ('+-'.indexOf(value[0]) >= 0) {\n value = value.slice(1);\n }\n\n if (value === '.inf') {\n return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;\n\n } else if (value === '.nan') {\n return NaN;\n\n } else if (value.indexOf(':') >= 0) {\n value.split(':').forEach(function (v) {\n digits.unshift(parseFloat(v, 10));\n });\n\n value = 0.0;\n base = 1;\n\n digits.forEach(function (d) {\n value += d * base;\n base *= 60;\n });\n\n return sign * value;\n\n }\n return sign * parseFloat(value, 10);\n}\n\n\nvar SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;\n\nfunction representYamlFloat(object, style) {\n var res;\n\n if (isNaN(object)) {\n switch (style) {\n case 'lowercase': return '.nan';\n case 'uppercase': return '.NAN';\n case 'camelcase': return '.NaN';\n }\n } else if (Number.POSITIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '.inf';\n case 'uppercase': return '.INF';\n case 'camelcase': return '.Inf';\n }\n } else if (Number.NEGATIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '-.inf';\n case 'uppercase': return '-.INF';\n case 'camelcase': return '-.Inf';\n }\n } else if (common.isNegativeZero(object)) {\n return '-0.0';\n }\n\n res = object.toString(10);\n\n // JS stringifier can build scientific format without dots: 5e-100,\n // while YAML requres dot: 5.e-100. Fix it with simple hack\n\n return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;\n}\n\nfunction isFloat(object) {\n return (Object.prototype.toString.call(object) === '[object Number]') &&\n (object % 1 !== 0 || common.isNegativeZero(object));\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:float', {\n kind: 'scalar',\n resolve: resolveYamlFloat,\n construct: constructYamlFloat,\n predicate: isFloat,\n represent: representYamlFloat,\n defaultStyle: 'lowercase'\n});\n","// Standard YAML's JSON schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2803231\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, this schema is not such strict as defined in the YAML specification.\n// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n include: [\n require('./failsafe')\n ],\n implicit: [\n require('../type/null'),\n require('../type/bool'),\n require('../type/int'),\n require('../type/float')\n ]\n});\n","// Standard YAML's Core schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2804923\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, Core schema has no distinctions from JSON schema is JS-YAML.\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n include: [\n require('./json')\n ]\n});\n","'use strict';\n\nvar Type = require('../type');\n\nvar YAML_DATE_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9])' + // [2] month\n '-([0-9][0-9])$'); // [3] day\n\nvar YAML_TIMESTAMP_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9]?)' + // [2] month\n '-([0-9][0-9]?)' + // [3] day\n '(?:[Tt]|[ \\\\t]+)' + // ...\n '([0-9][0-9]?)' + // [4] hour\n ':([0-9][0-9])' + // [5] minute\n ':([0-9][0-9])' + // [6] second\n '(?:\\\\.([0-9]*))?' + // [7] fraction\n '(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour\n '(?::([0-9][0-9]))?))?$'); // [11] tz_minute\n\nfunction resolveYamlTimestamp(data) {\n if (data === null) return false;\n if (YAML_DATE_REGEXP.exec(data) !== null) return true;\n if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;\n return false;\n}\n\nfunction constructYamlTimestamp(data) {\n var match, year, month, day, hour, minute, second, fraction = 0,\n delta = null, tz_hour, tz_minute, date;\n\n match = YAML_DATE_REGEXP.exec(data);\n if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);\n\n if (match === null) throw new Error('Date resolve error');\n\n // match: [1] year [2] month [3] day\n\n year = +(match[1]);\n month = +(match[2]) - 1; // JS month starts with 0\n day = +(match[3]);\n\n if (!match[4]) { // no hour\n return new Date(Date.UTC(year, month, day));\n }\n\n // match: [4] hour [5] minute [6] second [7] fraction\n\n hour = +(match[4]);\n minute = +(match[5]);\n second = +(match[6]);\n\n if (match[7]) {\n fraction = match[7].slice(0, 3);\n while (fraction.length < 3) { // milli-seconds\n fraction += '0';\n }\n fraction = +fraction;\n }\n\n // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute\n\n if (match[9]) {\n tz_hour = +(match[10]);\n tz_minute = +(match[11] || 0);\n delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds\n if (match[9] === '-') delta = -delta;\n }\n\n date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));\n\n if (delta) date.setTime(date.getTime() - delta);\n\n return date;\n}\n\nfunction representYamlTimestamp(object /*, style*/) {\n return object.toISOString();\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:timestamp', {\n kind: 'scalar',\n resolve: resolveYamlTimestamp,\n construct: constructYamlTimestamp,\n instanceOf: Date,\n represent: representYamlTimestamp\n});\n","'use strict';\n\nvar Type = require('../type');\n\nfunction resolveYamlMerge(data) {\n return data === '<<' || data === null;\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:merge', {\n kind: 'scalar',\n resolve: resolveYamlMerge\n});\n","'use strict';\n\n/*eslint-disable no-bitwise*/\n\nvar NodeBuffer;\n\ntry {\n // A trick for browserified version, to not include `Buffer` shim\n var _require = require;\n NodeBuffer = _require('buffer').Buffer;\n} catch (__) {}\n\nvar Type = require('../type');\n\n\n// [ 64, 65, 66 ] -> [ padding, CR, LF ]\nvar BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r';\n\n\nfunction resolveYamlBinary(data) {\n if (data === null) return false;\n\n var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;\n\n // Convert one by one.\n for (idx = 0; idx < max; idx++) {\n code = map.indexOf(data.charAt(idx));\n\n // Skip CR/LF\n if (code > 64) continue;\n\n // Fail on illegal characters\n if (code < 0) return false;\n\n bitlen += 6;\n }\n\n // If there are any bits left, source was corrupted\n return (bitlen % 8) === 0;\n}\n\nfunction constructYamlBinary(data) {\n var idx, tailbits,\n input = data.replace(/[\\r\\n=]/g, ''), // remove CR/LF & padding to simplify scan\n max = input.length,\n map = BASE64_MAP,\n bits = 0,\n result = [];\n\n // Collect by 6*4 bits (3 bytes)\n\n for (idx = 0; idx < max; idx++) {\n if ((idx % 4 === 0) && idx) {\n result.push((bits >> 16) & 0xFF);\n result.push((bits >> 8) & 0xFF);\n result.push(bits & 0xFF);\n }\n\n bits = (bits << 6) | map.indexOf(input.charAt(idx));\n }\n\n // Dump tail\n\n tailbits = (max % 4) * 6;\n\n if (tailbits === 0) {\n result.push((bits >> 16) & 0xFF);\n result.push((bits >> 8) & 0xFF);\n result.push(bits & 0xFF);\n } else if (tailbits === 18) {\n result.push((bits >> 10) & 0xFF);\n result.push((bits >> 2) & 0xFF);\n } else if (tailbits === 12) {\n result.push((bits >> 4) & 0xFF);\n }\n\n // Wrap into Buffer for NodeJS and leave Array for browser\n if (NodeBuffer) {\n // Support node 6.+ Buffer API when available\n return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);\n }\n\n return result;\n}\n\nfunction representYamlBinary(object /*, style*/) {\n var result = '', bits = 0, idx, tail,\n max = object.length,\n map = BASE64_MAP;\n\n // Convert every three bytes to 4 ASCII characters.\n\n for (idx = 0; idx < max; idx++) {\n if ((idx % 3 === 0) && idx) {\n result += map[(bits >> 18) & 0x3F];\n result += map[(bits >> 12) & 0x3F];\n result += map[(bits >> 6) & 0x3F];\n result += map[bits & 0x3F];\n }\n\n bits = (bits << 8) + object[idx];\n }\n\n // Dump tail\n\n tail = max % 3;\n\n if (tail === 0) {\n result += map[(bits >> 18) & 0x3F];\n result += map[(bits >> 12) & 0x3F];\n result += map[(bits >> 6) & 0x3F];\n result += map[bits & 0x3F];\n } else if (tail === 2) {\n result += map[(bits >> 10) & 0x3F];\n result += map[(bits >> 4) & 0x3F];\n result += map[(bits << 2) & 0x3F];\n result += map[64];\n } else if (tail === 1) {\n result += map[(bits >> 2) & 0x3F];\n result += map[(bits << 4) & 0x3F];\n result += map[64];\n result += map[64];\n }\n\n return result;\n}\n\nfunction isBinary(object) {\n return NodeBuffer && NodeBuffer.isBuffer(object);\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:binary', {\n kind: 'scalar',\n resolve: resolveYamlBinary,\n construct: constructYamlBinary,\n predicate: isBinary,\n represent: representYamlBinary\n});\n","'use strict';\n\nvar Type = require('../type');\n\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\nvar _toString = Object.prototype.toString;\n\nfunction resolveYamlOmap(data) {\n if (data === null) return true;\n\n var objectKeys = [], index, length, pair, pairKey, pairHasKey,\n object = data;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n pairHasKey = false;\n\n if (_toString.call(pair) !== '[object Object]') return false;\n\n for (pairKey in pair) {\n if (_hasOwnProperty.call(pair, pairKey)) {\n if (!pairHasKey) pairHasKey = true;\n else return false;\n }\n }\n\n if (!pairHasKey) return false;\n\n if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);\n else return false;\n }\n\n return true;\n}\n\nfunction constructYamlOmap(data) {\n return data !== null ? data : [];\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:omap', {\n kind: 'sequence',\n resolve: resolveYamlOmap,\n construct: constructYamlOmap\n});\n","'use strict';\n\nvar Type = require('../type');\n\nvar _toString = Object.prototype.toString;\n\nfunction resolveYamlPairs(data) {\n if (data === null) return true;\n\n var index, length, pair, keys, result,\n object = data;\n\n result = new Array(object.length);\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n\n if (_toString.call(pair) !== '[object Object]') return false;\n\n keys = Object.keys(pair);\n\n if (keys.length !== 1) return false;\n\n result[index] = [ keys[0], pair[keys[0]] ];\n }\n\n return true;\n}\n\nfunction constructYamlPairs(data) {\n if (data === null) return [];\n\n var index, length, pair, keys, result,\n object = data;\n\n result = new Array(object.length);\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n\n keys = Object.keys(pair);\n\n result[index] = [ keys[0], pair[keys[0]] ];\n }\n\n return result;\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:pairs', {\n kind: 'sequence',\n resolve: resolveYamlPairs,\n construct: constructYamlPairs\n});\n","'use strict';\n\nvar Type = require('../type');\n\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction resolveYamlSet(data) {\n if (data === null) return true;\n\n var key, object = data;\n\n for (key in object) {\n if (_hasOwnProperty.call(object, key)) {\n if (object[key] !== null) return false;\n }\n }\n\n return true;\n}\n\nfunction constructYamlSet(data) {\n return data !== null ? data : {};\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:set', {\n kind: 'mapping',\n resolve: resolveYamlSet,\n construct: constructYamlSet\n});\n","// JS-YAML's default schema for `safeLoad` function.\n// It is not described in the YAML specification.\n//\n// This schema is based on standard YAML's Core schema and includes most of\n// extra types described at YAML tag repository. (http://yaml.org/type/)\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n include: [\n require('./core')\n ],\n implicit: [\n require('../type/timestamp'),\n require('../type/merge')\n ],\n explicit: [\n require('../type/binary'),\n require('../type/omap'),\n require('../type/pairs'),\n require('../type/set')\n ]\n});\n","'use strict';\n\nvar Type = require('../../type');\n\nfunction resolveJavascriptUndefined() {\n return true;\n}\n\nfunction constructJavascriptUndefined() {\n /*eslint-disable no-undefined*/\n return undefined;\n}\n\nfunction representJavascriptUndefined() {\n return '';\n}\n\nfunction isUndefined(object) {\n return typeof object === 'undefined';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:js/undefined', {\n kind: 'scalar',\n resolve: resolveJavascriptUndefined,\n construct: constructJavascriptUndefined,\n predicate: isUndefined,\n represent: representJavascriptUndefined\n});\n","'use strict';\n\nvar Type = require('../../type');\n\nfunction resolveJavascriptRegExp(data) {\n if (data === null) return false;\n if (data.length === 0) return false;\n\n var regexp = data,\n tail = /\\/([gim]*)$/.exec(data),\n modifiers = '';\n\n // if regexp starts with '/' it can have modifiers and must be properly closed\n // `/foo/gim` - modifiers tail can be maximum 3 chars\n if (regexp[0] === '/') {\n if (tail) modifiers = tail[1];\n\n if (modifiers.length > 3) return false;\n // if expression starts with /, is should be properly terminated\n if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;\n }\n\n return true;\n}\n\nfunction constructJavascriptRegExp(data) {\n var regexp = data,\n tail = /\\/([gim]*)$/.exec(data),\n modifiers = '';\n\n // `/foo/gim` - tail can be maximum 4 chars\n if (regexp[0] === '/') {\n if (tail) modifiers = tail[1];\n regexp = regexp.slice(1, regexp.length - modifiers.length - 1);\n }\n\n return new RegExp(regexp, modifiers);\n}\n\nfunction representJavascriptRegExp(object /*, style*/) {\n var result = '/' + object.source + '/';\n\n if (object.global) result += 'g';\n if (object.multiline) result += 'm';\n if (object.ignoreCase) result += 'i';\n\n return result;\n}\n\nfunction isRegExp(object) {\n return Object.prototype.toString.call(object) === '[object RegExp]';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:js/regexp', {\n kind: 'scalar',\n resolve: resolveJavascriptRegExp,\n construct: constructJavascriptRegExp,\n predicate: isRegExp,\n represent: representJavascriptRegExp\n});\n","'use strict';\n\nvar esprima;\n\n// Browserified version does not have esprima\n//\n// 1. For node.js just require module as deps\n// 2. For browser try to require mudule via external AMD system.\n// If not found - try to fallback to window.esprima. If not\n// found too - then fail to parse.\n//\ntry {\n // workaround to exclude package from browserify list.\n var _require = require;\n esprima = _require('esprima');\n} catch (_) {\n /* eslint-disable no-redeclare */\n /* global window */\n if (typeof window !== 'undefined') esprima = window.esprima;\n}\n\nvar Type = require('../../type');\n\nfunction resolveJavascriptFunction(data) {\n if (data === null) return false;\n\n try {\n var source = '(' + data + ')',\n ast = esprima.parse(source, { range: true });\n\n if (ast.type !== 'Program' ||\n ast.body.length !== 1 ||\n ast.body[0].type !== 'ExpressionStatement' ||\n (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&\n ast.body[0].expression.type !== 'FunctionExpression')) {\n return false;\n }\n\n return true;\n } catch (err) {\n return false;\n }\n}\n\nfunction constructJavascriptFunction(data) {\n /*jslint evil:true*/\n\n var source = '(' + data + ')',\n ast = esprima.parse(source, { range: true }),\n params = [],\n body;\n\n if (ast.type !== 'Program' ||\n ast.body.length !== 1 ||\n ast.body[0].type !== 'ExpressionStatement' ||\n (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&\n ast.body[0].expression.type !== 'FunctionExpression')) {\n throw new Error('Failed to resolve function');\n }\n\n ast.body[0].expression.params.forEach(function (param) {\n params.push(param.name);\n });\n\n body = ast.body[0].expression.body.range;\n\n // Esprima's ranges include the first '{' and the last '}' characters on\n // function expressions. So cut them out.\n if (ast.body[0].expression.body.type === 'BlockStatement') {\n /*eslint-disable no-new-func*/\n return new Function(params, source.slice(body[0] + 1, body[1] - 1));\n }\n // ES6 arrow functions can omit the BlockStatement. In that case, just return\n // the body.\n /*eslint-disable no-new-func*/\n return new Function(params, 'return ' + source.slice(body[0], body[1]));\n}\n\nfunction representJavascriptFunction(object /*, style*/) {\n return object.toString();\n}\n\nfunction isFunction(object) {\n return Object.prototype.toString.call(object) === '[object Function]';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:js/function', {\n kind: 'scalar',\n resolve: resolveJavascriptFunction,\n construct: constructJavascriptFunction,\n predicate: isFunction,\n represent: representJavascriptFunction\n});\n","// JS-YAML's default schema for `load` function.\n// It is not described in the YAML specification.\n//\n// This schema is based on JS-YAML's default safe schema and includes\n// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.\n//\n// Also this schema is used as default base schema at `Schema.create` function.\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = Schema.DEFAULT = new Schema({\n include: [\n require('./default_safe')\n ],\n explicit: [\n require('../type/js/undefined'),\n require('../type/js/regexp'),\n require('../type/js/function')\n ]\n});\n","'use strict';\n\n/*eslint-disable max-len,no-use-before-define*/\n\nvar common = require('./common');\nvar YAMLException = require('./exception');\nvar Mark = require('./mark');\nvar DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');\nvar DEFAULT_FULL_SCHEMA = require('./schema/default_full');\n\n\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\n\nvar CONTEXT_FLOW_IN = 1;\nvar CONTEXT_FLOW_OUT = 2;\nvar CONTEXT_BLOCK_IN = 3;\nvar CONTEXT_BLOCK_OUT = 4;\n\n\nvar CHOMPING_CLIP = 1;\nvar CHOMPING_STRIP = 2;\nvar CHOMPING_KEEP = 3;\n\n\nvar PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\nvar PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/;\nvar PATTERN_FLOW_INDICATORS = /[,\\[\\]\\{\\}]/;\nvar PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\\-]+!)$/i;\nvar PATTERN_TAG_URI = /^(?:!|[^,\\[\\]\\{\\}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;\\/\\?:@&=\\+\\$,_\\.!~\\*'\\(\\)\\[\\]])*$/i;\n\n\nfunction _class(obj) { return Object.prototype.toString.call(obj); }\n\nfunction is_EOL(c) {\n return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);\n}\n\nfunction is_WHITE_SPACE(c) {\n return (c === 0x09/* Tab */) || (c === 0x20/* Space */);\n}\n\nfunction is_WS_OR_EOL(c) {\n return (c === 0x09/* Tab */) ||\n (c === 0x20/* Space */) ||\n (c === 0x0A/* LF */) ||\n (c === 0x0D/* CR */);\n}\n\nfunction is_FLOW_INDICATOR(c) {\n return c === 0x2C/* , */ ||\n c === 0x5B/* [ */ ||\n c === 0x5D/* ] */ ||\n c === 0x7B/* { */ ||\n c === 0x7D/* } */;\n}\n\nfunction fromHexCode(c) {\n var lc;\n\n if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n return c - 0x30;\n }\n\n /*eslint-disable no-bitwise*/\n lc = c | 0x20;\n\n if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {\n return lc - 0x61 + 10;\n }\n\n return -1;\n}\n\nfunction escapedHexLen(c) {\n if (c === 0x78/* x */) { return 2; }\n if (c === 0x75/* u */) { return 4; }\n if (c === 0x55/* U */) { return 8; }\n return 0;\n}\n\nfunction fromDecimalCode(c) {\n if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n return c - 0x30;\n }\n\n return -1;\n}\n\nfunction simpleEscapeSequence(c) {\n /* eslint-disable indent */\n return (c === 0x30/* 0 */) ? '\\x00' :\n (c === 0x61/* a */) ? '\\x07' :\n (c === 0x62/* b */) ? '\\x08' :\n (c === 0x74/* t */) ? '\\x09' :\n (c === 0x09/* Tab */) ? '\\x09' :\n (c === 0x6E/* n */) ? '\\x0A' :\n (c === 0x76/* v */) ? '\\x0B' :\n (c === 0x66/* f */) ? '\\x0C' :\n (c === 0x72/* r */) ? '\\x0D' :\n (c === 0x65/* e */) ? '\\x1B' :\n (c === 0x20/* Space */) ? ' ' :\n (c === 0x22/* \" */) ? '\\x22' :\n (c === 0x2F/* / */) ? '/' :\n (c === 0x5C/* \\ */) ? '\\x5C' :\n (c === 0x4E/* N */) ? '\\x85' :\n (c === 0x5F/* _ */) ? '\\xA0' :\n (c === 0x4C/* L */) ? '\\u2028' :\n (c === 0x50/* P */) ? '\\u2029' : '';\n}\n\nfunction charFromCodepoint(c) {\n if (c <= 0xFFFF) {\n return String.fromCharCode(c);\n }\n // Encode UTF-16 surrogate pair\n // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF\n return String.fromCharCode(\n ((c - 0x010000) >> 10) + 0xD800,\n ((c - 0x010000) & 0x03FF) + 0xDC00\n );\n}\n\n// set a property of a literal object, while protecting against prototype pollution,\n// see https://github.com/nodeca/js-yaml/issues/164 for more details\nfunction setProperty(object, key, value) {\n // used for this specific key only because Object.defineProperty is slow\n if (key === '__proto__') {\n Object.defineProperty(object, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: value\n });\n } else {\n object[key] = value;\n }\n}\n\nvar simpleEscapeCheck = new Array(256); // integer, for fast access\nvar simpleEscapeMap = new Array(256);\nfor (var i = 0; i < 256; i++) {\n simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;\n simpleEscapeMap[i] = simpleEscapeSequence(i);\n}\n\n\nfunction State(input, options) {\n this.input = input;\n\n this.filename = options['filename'] || null;\n this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;\n this.onWarning = options['onWarning'] || null;\n this.legacy = options['legacy'] || false;\n this.json = options['json'] || false;\n this.listener = options['listener'] || null;\n\n this.implicitTypes = this.schema.compiledImplicit;\n this.typeMap = this.schema.compiledTypeMap;\n\n this.length = input.length;\n this.position = 0;\n this.line = 0;\n this.lineStart = 0;\n this.lineIndent = 0;\n\n this.documents = [];\n\n /*\n this.version;\n this.checkLineBreaks;\n this.tagMap;\n this.anchorMap;\n this.tag;\n this.anchor;\n this.kind;\n this.result;*/\n\n}\n\n\nfunction generateError(state, message) {\n return new YAMLException(\n message,\n new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));\n}\n\nfunction throwError(state, message) {\n throw generateError(state, message);\n}\n\nfunction throwWarning(state, message) {\n if (state.onWarning) {\n state.onWarning.call(null, generateError(state, message));\n }\n}\n\n\nvar directiveHandlers = {\n\n YAML: function handleYamlDirective(state, name, args) {\n\n var match, major, minor;\n\n if (state.version !== null) {\n throwError(state, 'duplication of %YAML directive');\n }\n\n if (args.length !== 1) {\n throwError(state, 'YAML directive accepts exactly one argument');\n }\n\n match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0]);\n\n if (match === null) {\n throwError(state, 'ill-formed argument of the YAML directive');\n }\n\n major = parseInt(match[1], 10);\n minor = parseInt(match[2], 10);\n\n if (major !== 1) {\n throwError(state, 'unacceptable YAML version of the document');\n }\n\n state.version = args[0];\n state.checkLineBreaks = (minor < 2);\n\n if (minor !== 1 && minor !== 2) {\n throwWarning(state, 'unsupported YAML version of the document');\n }\n },\n\n TAG: function handleTagDirective(state, name, args) {\n\n var handle, prefix;\n\n if (args.length !== 2) {\n throwError(state, 'TAG directive accepts exactly two arguments');\n }\n\n handle = args[0];\n prefix = args[1];\n\n if (!PATTERN_TAG_HANDLE.test(handle)) {\n throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');\n }\n\n if (_hasOwnProperty.call(state.tagMap, handle)) {\n throwError(state, 'there is a previously declared suffix for \"' + handle + '\" tag handle');\n }\n\n if (!PATTERN_TAG_URI.test(prefix)) {\n throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');\n }\n\n state.tagMap[handle] = prefix;\n }\n};\n\n\nfunction captureSegment(state, start, end, checkJson) {\n var _position, _length, _character, _result;\n\n if (start < end) {\n _result = state.input.slice(start, end);\n\n if (checkJson) {\n for (_position = 0, _length = _result.length; _position < _length; _position += 1) {\n _character = _result.charCodeAt(_position);\n if (!(_character === 0x09 ||\n (0x20 <= _character && _character <= 0x10FFFF))) {\n throwError(state, 'expected valid JSON character');\n }\n }\n } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n throwError(state, 'the stream contains non-printable characters');\n }\n\n state.result += _result;\n }\n}\n\nfunction mergeMappings(state, destination, source, overridableKeys) {\n var sourceKeys, key, index, quantity;\n\n if (!common.isObject(source)) {\n throwError(state, 'cannot merge mappings; the provided source object is unacceptable');\n }\n\n sourceKeys = Object.keys(source);\n\n for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n key = sourceKeys[index];\n\n if (!_hasOwnProperty.call(destination, key)) {\n setProperty(destination, key, source[key]);\n overridableKeys[key] = true;\n }\n }\n}\n\nfunction storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {\n var index, quantity;\n\n // The output is a plain object here, so keys can only be strings.\n // We need to convert keyNode to a string, but doing so can hang the process\n // (deeply nested arrays that explode exponentially using aliases).\n if (Array.isArray(keyNode)) {\n keyNode = Array.prototype.slice.call(keyNode);\n\n for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n if (Array.isArray(keyNode[index])) {\n throwError(state, 'nested arrays are not supported inside keys');\n }\n\n if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {\n keyNode[index] = '[object Object]';\n }\n }\n }\n\n // Avoid code execution in load() via toString property\n // (still use its own toString for arrays, timestamps,\n // and whatever user schema extensions happen to have @@toStringTag)\n if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {\n keyNode = '[object Object]';\n }\n\n\n keyNode = String(keyNode);\n\n if (_result === null) {\n _result = {};\n }\n\n if (keyTag === 'tag:yaml.org,2002:merge') {\n if (Array.isArray(valueNode)) {\n for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n mergeMappings(state, _result, valueNode[index], overridableKeys);\n }\n } else {\n mergeMappings(state, _result, valueNode, overridableKeys);\n }\n } else {\n if (!state.json &&\n !_hasOwnProperty.call(overridableKeys, keyNode) &&\n _hasOwnProperty.call(_result, keyNode)) {\n state.line = startLine || state.line;\n state.position = startPos || state.position;\n throwError(state, 'duplicated mapping key');\n }\n setProperty(_result, keyNode, valueNode);\n delete overridableKeys[keyNode];\n }\n\n return _result;\n}\n\nfunction readLineBreak(state) {\n var ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x0A/* LF */) {\n state.position++;\n } else if (ch === 0x0D/* CR */) {\n state.position++;\n if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {\n state.position++;\n }\n } else {\n throwError(state, 'a line break is expected');\n }\n\n state.line += 1;\n state.lineStart = state.position;\n}\n\nfunction skipSeparationSpace(state, allowComments, checkIndent) {\n var lineBreaks = 0,\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (allowComments && ch === 0x23/* # */) {\n do {\n ch = state.input.charCodeAt(++state.position);\n } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);\n }\n\n if (is_EOL(ch)) {\n readLineBreak(state);\n\n ch = state.input.charCodeAt(state.position);\n lineBreaks++;\n state.lineIndent = 0;\n\n while (ch === 0x20/* Space */) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n } else {\n break;\n }\n }\n\n if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n throwWarning(state, 'deficient indentation');\n }\n\n return lineBreaks;\n}\n\nfunction testDocumentSeparator(state) {\n var _position = state.position,\n ch;\n\n ch = state.input.charCodeAt(_position);\n\n // Condition state.position === state.lineStart is tested\n // in parent on each call, for efficiency. No needs to test here again.\n if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&\n ch === state.input.charCodeAt(_position + 1) &&\n ch === state.input.charCodeAt(_position + 2)) {\n\n _position += 3;\n\n ch = state.input.charCodeAt(_position);\n\n if (ch === 0 || is_WS_OR_EOL(ch)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction writeFoldedLines(state, count) {\n if (count === 1) {\n state.result += ' ';\n } else if (count > 1) {\n state.result += common.repeat('\\n', count - 1);\n }\n}\n\n\nfunction readPlainScalar(state, nodeIndent, withinFlowCollection) {\n var preceding,\n following,\n captureStart,\n captureEnd,\n hasPendingContent,\n _line,\n _lineStart,\n _lineIndent,\n _kind = state.kind,\n _result = state.result,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (is_WS_OR_EOL(ch) ||\n is_FLOW_INDICATOR(ch) ||\n ch === 0x23/* # */ ||\n ch === 0x26/* & */ ||\n ch === 0x2A/* * */ ||\n ch === 0x21/* ! */ ||\n ch === 0x7C/* | */ ||\n ch === 0x3E/* > */ ||\n ch === 0x27/* ' */ ||\n ch === 0x22/* \" */ ||\n ch === 0x25/* % */ ||\n ch === 0x40/* @ */ ||\n ch === 0x60/* ` */) {\n return false;\n }\n\n if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following) ||\n withinFlowCollection && is_FLOW_INDICATOR(following)) {\n return false;\n }\n }\n\n state.kind = 'scalar';\n state.result = '';\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n\n while (ch !== 0) {\n if (ch === 0x3A/* : */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following) ||\n withinFlowCollection && is_FLOW_INDICATOR(following)) {\n break;\n }\n\n } else if (ch === 0x23/* # */) {\n preceding = state.input.charCodeAt(state.position - 1);\n\n if (is_WS_OR_EOL(preceding)) {\n break;\n }\n\n } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||\n withinFlowCollection && is_FLOW_INDICATOR(ch)) {\n break;\n\n } else if (is_EOL(ch)) {\n _line = state.line;\n _lineStart = state.lineStart;\n _lineIndent = state.lineIndent;\n skipSeparationSpace(state, false, -1);\n\n if (state.lineIndent >= nodeIndent) {\n hasPendingContent = true;\n ch = state.input.charCodeAt(state.position);\n continue;\n } else {\n state.position = captureEnd;\n state.line = _line;\n state.lineStart = _lineStart;\n state.lineIndent = _lineIndent;\n break;\n }\n }\n\n if (hasPendingContent) {\n captureSegment(state, captureStart, captureEnd, false);\n writeFoldedLines(state, state.line - _line);\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n }\n\n if (!is_WHITE_SPACE(ch)) {\n captureEnd = state.position + 1;\n }\n\n ch = state.input.charCodeAt(++state.position);\n }\n\n captureSegment(state, captureStart, captureEnd, false);\n\n if (state.result) {\n return true;\n }\n\n state.kind = _kind;\n state.result = _result;\n return false;\n}\n\nfunction readSingleQuotedScalar(state, nodeIndent) {\n var ch,\n captureStart, captureEnd;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x27/* ' */) {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n state.position++;\n captureStart = captureEnd = state.position;\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x27/* ' */) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x27/* ' */) {\n captureStart = state.position;\n state.position++;\n captureEnd = state.position;\n } else {\n return true;\n }\n\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a single quoted scalar');\n\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a single quoted scalar');\n}\n\nfunction readDoubleQuotedScalar(state, nodeIndent) {\n var captureStart,\n captureEnd,\n hexLength,\n hexResult,\n tmp,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x22/* \" */) {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n state.position++;\n captureStart = captureEnd = state.position;\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x22/* \" */) {\n captureSegment(state, captureStart, state.position, true);\n state.position++;\n return true;\n\n } else if (ch === 0x5C/* \\ */) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n\n if (is_EOL(ch)) {\n skipSeparationSpace(state, false, nodeIndent);\n\n // TODO: rework to inline fn with no type cast?\n } else if (ch < 256 && simpleEscapeCheck[ch]) {\n state.result += simpleEscapeMap[ch];\n state.position++;\n\n } else if ((tmp = escapedHexLen(ch)) > 0) {\n hexLength = tmp;\n hexResult = 0;\n\n for (; hexLength > 0; hexLength--) {\n ch = state.input.charCodeAt(++state.position);\n\n if ((tmp = fromHexCode(ch)) >= 0) {\n hexResult = (hexResult << 4) + tmp;\n\n } else {\n throwError(state, 'expected hexadecimal character');\n }\n }\n\n state.result += charFromCodepoint(hexResult);\n\n state.position++;\n\n } else {\n throwError(state, 'unknown escape sequence');\n }\n\n captureStart = captureEnd = state.position;\n\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a double quoted scalar');\n\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a double quoted scalar');\n}\n\nfunction readFlowCollection(state, nodeIndent) {\n var readNext = true,\n _line,\n _tag = state.tag,\n _result,\n _anchor = state.anchor,\n following,\n terminator,\n isPair,\n isExplicitPair,\n isMapping,\n overridableKeys = {},\n keyNode,\n keyTag,\n valueNode,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x5B/* [ */) {\n terminator = 0x5D;/* ] */\n isMapping = false;\n _result = [];\n } else if (ch === 0x7B/* { */) {\n terminator = 0x7D;/* } */\n isMapping = true;\n _result = {};\n } else {\n return false;\n }\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(++state.position);\n\n while (ch !== 0) {\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === terminator) {\n state.position++;\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = isMapping ? 'mapping' : 'sequence';\n state.result = _result;\n return true;\n } else if (!readNext) {\n throwError(state, 'missed comma between flow collection entries');\n }\n\n keyTag = keyNode = valueNode = null;\n isPair = isExplicitPair = false;\n\n if (ch === 0x3F/* ? */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following)) {\n isPair = isExplicitPair = true;\n state.position++;\n skipSeparationSpace(state, true, nodeIndent);\n }\n }\n\n _line = state.line;\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n keyTag = state.tag;\n keyNode = state.result;\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {\n isPair = true;\n ch = state.input.charCodeAt(++state.position);\n skipSeparationSpace(state, true, nodeIndent);\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n valueNode = state.result;\n }\n\n if (isMapping) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);\n } else if (isPair) {\n _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));\n } else {\n _result.push(keyNode);\n }\n\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x2C/* , */) {\n readNext = true;\n ch = state.input.charCodeAt(++state.position);\n } else {\n readNext = false;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a flow collection');\n}\n\nfunction readBlockScalar(state, nodeIndent) {\n var captureStart,\n folding,\n chomping = CHOMPING_CLIP,\n didReadContent = false,\n detectedIndent = false,\n textIndent = nodeIndent,\n emptyLines = 0,\n atMoreIndented = false,\n tmp,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x7C/* | */) {\n folding = false;\n } else if (ch === 0x3E/* > */) {\n folding = true;\n } else {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n\n while (ch !== 0) {\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {\n if (CHOMPING_CLIP === chomping) {\n chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;\n } else {\n throwError(state, 'repeat of a chomping mode identifier');\n }\n\n } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n if (tmp === 0) {\n throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');\n } else if (!detectedIndent) {\n textIndent = nodeIndent + tmp - 1;\n detectedIndent = true;\n } else {\n throwError(state, 'repeat of an indentation width identifier');\n }\n\n } else {\n break;\n }\n }\n\n if (is_WHITE_SPACE(ch)) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (is_WHITE_SPACE(ch));\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (!is_EOL(ch) && (ch !== 0));\n }\n }\n\n while (ch !== 0) {\n readLineBreak(state);\n state.lineIndent = 0;\n\n ch = state.input.charCodeAt(state.position);\n\n while ((!detectedIndent || state.lineIndent < textIndent) &&\n (ch === 0x20/* Space */)) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (!detectedIndent && state.lineIndent > textIndent) {\n textIndent = state.lineIndent;\n }\n\n if (is_EOL(ch)) {\n emptyLines++;\n continue;\n }\n\n // End of the scalar.\n if (state.lineIndent < textIndent) {\n\n // Perform the chomping.\n if (chomping === CHOMPING_KEEP) {\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n } else if (chomping === CHOMPING_CLIP) {\n if (didReadContent) { // i.e. only if the scalar is not empty.\n state.result += '\\n';\n }\n }\n\n // Break this `while` cycle and go to the funciton's epilogue.\n break;\n }\n\n // Folded style: use fancy rules to handle line breaks.\n if (folding) {\n\n // Lines starting with white space characters (more-indented lines) are not folded.\n if (is_WHITE_SPACE(ch)) {\n atMoreIndented = true;\n // except for the first content line (cf. Example 8.1)\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n\n // End of more-indented block.\n } else if (atMoreIndented) {\n atMoreIndented = false;\n state.result += common.repeat('\\n', emptyLines + 1);\n\n // Just one line break - perceive as the same line.\n } else if (emptyLines === 0) {\n if (didReadContent) { // i.e. only if we have already read some scalar content.\n state.result += ' ';\n }\n\n // Several line breaks - perceive as different lines.\n } else {\n state.result += common.repeat('\\n', emptyLines);\n }\n\n // Literal style: just add exact number of line breaks between content lines.\n } else {\n // Keep all line breaks except the header line break.\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n }\n\n didReadContent = true;\n detectedIndent = true;\n emptyLines = 0;\n captureStart = state.position;\n\n while (!is_EOL(ch) && (ch !== 0)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n captureSegment(state, captureStart, state.position, false);\n }\n\n return true;\n}\n\nfunction readBlockSequence(state, nodeIndent) {\n var _line,\n _tag = state.tag,\n _anchor = state.anchor,\n _result = [],\n following,\n detected = false,\n ch;\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n\n if (ch !== 0x2D/* - */) {\n break;\n }\n\n following = state.input.charCodeAt(state.position + 1);\n\n if (!is_WS_OR_EOL(following)) {\n break;\n }\n\n detected = true;\n state.position++;\n\n if (skipSeparationSpace(state, true, -1)) {\n if (state.lineIndent <= nodeIndent) {\n _result.push(null);\n ch = state.input.charCodeAt(state.position);\n continue;\n }\n }\n\n _line = state.line;\n composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);\n _result.push(state.result);\n skipSeparationSpace(state, true, -1);\n\n ch = state.input.charCodeAt(state.position);\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a sequence entry');\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = 'sequence';\n state.result = _result;\n return true;\n }\n return false;\n}\n\nfunction readBlockMapping(state, nodeIndent, flowIndent) {\n var following,\n allowCompact,\n _line,\n _pos,\n _tag = state.tag,\n _anchor = state.anchor,\n _result = {},\n overridableKeys = {},\n keyTag = null,\n keyNode = null,\n valueNode = null,\n atExplicitKey = false,\n detected = false,\n ch;\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n following = state.input.charCodeAt(state.position + 1);\n _line = state.line; // Save the current line.\n _pos = state.position;\n\n //\n // Explicit notation case. There are two separate blocks:\n // first for the key (denoted by \"?\") and second for the value (denoted by \":\")\n //\n if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {\n\n if (ch === 0x3F/* ? */) {\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);\n keyTag = keyNode = valueNode = null;\n }\n\n detected = true;\n atExplicitKey = true;\n allowCompact = true;\n\n } else if (atExplicitKey) {\n // i.e. 0x3A/* : */ === character after the explicit key.\n atExplicitKey = false;\n allowCompact = true;\n\n } else {\n throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');\n }\n\n state.position += 1;\n ch = following;\n\n //\n // Implicit notation case. Flow-style node as the key first, then \":\", and the value.\n //\n } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n\n if (state.line === _line) {\n ch = state.input.charCodeAt(state.position);\n\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (ch === 0x3A/* : */) {\n ch = state.input.charCodeAt(++state.position);\n\n if (!is_WS_OR_EOL(ch)) {\n throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');\n }\n\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);\n keyTag = keyNode = valueNode = null;\n }\n\n detected = true;\n atExplicitKey = false;\n allowCompact = false;\n keyTag = state.tag;\n keyNode = state.result;\n\n } else if (detected) {\n throwError(state, 'can not read an implicit mapping pair; a colon is missed');\n\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true; // Keep the result of `composeNode`.\n }\n\n } else if (detected) {\n throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');\n\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true; // Keep the result of `composeNode`.\n }\n\n } else {\n break; // Reading is done. Go to the epilogue.\n }\n\n //\n // Common reading code for both explicit and implicit notations.\n //\n if (state.line === _line || state.lineIndent > nodeIndent) {\n if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n if (atExplicitKey) {\n keyNode = state.result;\n } else {\n valueNode = state.result;\n }\n }\n\n if (!atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);\n keyTag = keyNode = valueNode = null;\n }\n\n skipSeparationSpace(state, true, -1);\n ch = state.input.charCodeAt(state.position);\n }\n\n if (state.lineIndent > nodeIndent && (ch !== 0)) {\n throwError(state, 'bad indentation of a mapping entry');\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n\n //\n // Epilogue.\n //\n\n // Special case: last mapping's node contains only the key in explicit notation.\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);\n }\n\n // Expose the resulting mapping.\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = 'mapping';\n state.result = _result;\n }\n\n return detected;\n}\n\nfunction readTagProperty(state) {\n var _position,\n isVerbatim = false,\n isNamed = false,\n tagHandle,\n tagName,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x21/* ! */) return false;\n\n if (state.tag !== null) {\n throwError(state, 'duplication of a tag property');\n }\n\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x3C/* < */) {\n isVerbatim = true;\n ch = state.input.charCodeAt(++state.position);\n\n } else if (ch === 0x21/* ! */) {\n isNamed = true;\n tagHandle = '!!';\n ch = state.input.charCodeAt(++state.position);\n\n } else {\n tagHandle = '!';\n }\n\n _position = state.position;\n\n if (isVerbatim) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (ch !== 0 && ch !== 0x3E/* > */);\n\n if (state.position < state.length) {\n tagName = state.input.slice(_position, state.position);\n ch = state.input.charCodeAt(++state.position);\n } else {\n throwError(state, 'unexpected end of the stream within a verbatim tag');\n }\n } else {\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n\n if (ch === 0x21/* ! */) {\n if (!isNamed) {\n tagHandle = state.input.slice(_position - 1, state.position + 1);\n\n if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n throwError(state, 'named tag handle cannot contain such characters');\n }\n\n isNamed = true;\n _position = state.position + 1;\n } else {\n throwError(state, 'tag suffix cannot contain exclamation marks');\n }\n }\n\n ch = state.input.charCodeAt(++state.position);\n }\n\n tagName = state.input.slice(_position, state.position);\n\n if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n throwError(state, 'tag suffix cannot contain flow indicator characters');\n }\n }\n\n if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n throwError(state, 'tag name cannot contain such characters: ' + tagName);\n }\n\n if (isVerbatim) {\n state.tag = tagName;\n\n } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {\n state.tag = state.tagMap[tagHandle] + tagName;\n\n } else if (tagHandle === '!') {\n state.tag = '!' + tagName;\n\n } else if (tagHandle === '!!') {\n state.tag = 'tag:yaml.org,2002:' + tagName;\n\n } else {\n throwError(state, 'undeclared tag handle \"' + tagHandle + '\"');\n }\n\n return true;\n}\n\nfunction readAnchorProperty(state) {\n var _position,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x26/* & */) return false;\n\n if (state.anchor !== null) {\n throwError(state, 'duplication of an anchor property');\n }\n\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an anchor node must contain at least one character');\n }\n\n state.anchor = state.input.slice(_position, state.position);\n return true;\n}\n\nfunction readAlias(state) {\n var _position, alias,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x2A/* * */) return false;\n\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an alias node must contain at least one character');\n }\n\n alias = state.input.slice(_position, state.position);\n\n if (!_hasOwnProperty.call(state.anchorMap, alias)) {\n throwError(state, 'unidentified alias \"' + alias + '\"');\n }\n\n state.result = state.anchorMap[alias];\n skipSeparationSpace(state, true, -1);\n return true;\n}\n\nfunction composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n var allowBlockStyles,\n allowBlockScalars,\n allowBlockCollections,\n indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent\n atNewLine = false,\n hasContent = false,\n typeIndex,\n typeQuantity,\n type,\n flowIndent,\n blockIndent;\n\n if (state.listener !== null) {\n state.listener('open', state);\n }\n\n state.tag = null;\n state.anchor = null;\n state.kind = null;\n state.result = null;\n\n allowBlockStyles = allowBlockScalars = allowBlockCollections =\n CONTEXT_BLOCK_OUT === nodeContext ||\n CONTEXT_BLOCK_IN === nodeContext;\n\n if (allowToSeek) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n }\n }\n\n if (indentStatus === 1) {\n while (readTagProperty(state) || readAnchorProperty(state)) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n allowBlockCollections = allowBlockStyles;\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n } else {\n allowBlockCollections = false;\n }\n }\n }\n\n if (allowBlockCollections) {\n allowBlockCollections = atNewLine || allowCompact;\n }\n\n if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n flowIndent = parentIndent;\n } else {\n flowIndent = parentIndent + 1;\n }\n\n blockIndent = state.position - state.lineStart;\n\n if (indentStatus === 1) {\n if (allowBlockCollections &&\n (readBlockSequence(state, blockIndent) ||\n readBlockMapping(state, blockIndent, flowIndent)) ||\n readFlowCollection(state, flowIndent)) {\n hasContent = true;\n } else {\n if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||\n readSingleQuotedScalar(state, flowIndent) ||\n readDoubleQuotedScalar(state, flowIndent)) {\n hasContent = true;\n\n } else if (readAlias(state)) {\n hasContent = true;\n\n if (state.tag !== null || state.anchor !== null) {\n throwError(state, 'alias node should not have any properties');\n }\n\n } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n hasContent = true;\n\n if (state.tag === null) {\n state.tag = '?';\n }\n }\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n } else if (indentStatus === 0) {\n // Special case: block sequences are allowed to have same indentation level as the parent.\n // http://www.yaml.org/spec/1.2/spec.html#id2799784\n hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);\n }\n }\n\n if (state.tag !== null && state.tag !== '!') {\n if (state.tag === '?') {\n // Implicit resolving is not allowed for non-scalar types, and '?'\n // non-specific tag is only automatically assigned to plain scalars.\n //\n // We only need to check kind conformity in case user explicitly assigns '?'\n // tag, for example like this: \"!<?> [0]\"\n //\n if (state.result !== null && state.kind !== 'scalar') {\n throwError(state, 'unacceptable node kind for !<?> tag; it should be \"scalar\", not \"' + state.kind + '\"');\n }\n\n for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n type = state.implicitTypes[typeIndex];\n\n if (type.resolve(state.result)) { // `state.result` updated in resolver if matched\n state.result = type.construct(state.result);\n state.tag = type.tag;\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n break;\n }\n }\n } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {\n type = state.typeMap[state.kind || 'fallback'][state.tag];\n\n if (state.result !== null && type.kind !== state.kind) {\n throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be \"' + type.kind + '\", not \"' + state.kind + '\"');\n }\n\n if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched\n throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');\n } else {\n state.result = type.construct(state.result);\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n } else {\n throwError(state, 'unknown tag !<' + state.tag + '>');\n }\n }\n\n if (state.listener !== null) {\n state.listener('close', state);\n }\n return state.tag !== null || state.anchor !== null || hasContent;\n}\n\nfunction readDocument(state) {\n var documentStart = state.position,\n _position,\n directiveName,\n directiveArgs,\n hasDirectives = false,\n ch;\n\n state.version = null;\n state.checkLineBreaks = state.legacy;\n state.tagMap = {};\n state.anchorMap = {};\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n skipSeparationSpace(state, true, -1);\n\n ch = state.input.charCodeAt(state.position);\n\n if (state.lineIndent > 0 || ch !== 0x25/* % */) {\n break;\n }\n\n hasDirectives = true;\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n directiveName = state.input.slice(_position, state.position);\n directiveArgs = [];\n\n if (directiveName.length < 1) {\n throwError(state, 'directive name must not be less than one character in length');\n }\n\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (ch !== 0 && !is_EOL(ch));\n break;\n }\n\n if (is_EOL(ch)) break;\n\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n directiveArgs.push(state.input.slice(_position, state.position));\n }\n\n if (ch !== 0) readLineBreak(state);\n\n if (_hasOwnProperty.call(directiveHandlers, directiveName)) {\n directiveHandlers[directiveName](state, directiveName, directiveArgs);\n } else {\n throwWarning(state, 'unknown document directive \"' + directiveName + '\"');\n }\n }\n\n skipSeparationSpace(state, true, -1);\n\n if (state.lineIndent === 0 &&\n state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n\n } else if (hasDirectives) {\n throwError(state, 'directives end mark is expected');\n }\n\n composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);\n skipSeparationSpace(state, true, -1);\n\n if (state.checkLineBreaks &&\n PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n throwWarning(state, 'non-ASCII line breaks are interpreted as content');\n }\n\n state.documents.push(state.result);\n\n if (state.position === state.lineStart && testDocumentSeparator(state)) {\n\n if (state.input.charCodeAt(state.position) === 0x2E/* . */) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n }\n return;\n }\n\n if (state.position < (state.length - 1)) {\n throwError(state, 'end of the stream or a document separator is expected');\n } else {\n return;\n }\n}\n\n\nfunction loadDocuments(input, options) {\n input = String(input);\n options = options || {};\n\n if (input.length !== 0) {\n\n // Add tailing `\\n` if not exists\n if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&\n input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {\n input += '\\n';\n }\n\n // Strip BOM\n if (input.charCodeAt(0) === 0xFEFF) {\n input = input.slice(1);\n }\n }\n\n var state = new State(input, options);\n\n var nullpos = input.indexOf('\\0');\n\n if (nullpos !== -1) {\n state.position = nullpos;\n throwError(state, 'null byte is not allowed in input');\n }\n\n // Use 0 as string terminator. That significantly simplifies bounds check.\n state.input += '\\0';\n\n while (state.input.charCodeAt(state.position) === 0x20/* Space */) {\n state.lineIndent += 1;\n state.position += 1;\n }\n\n while (state.position < (state.length - 1)) {\n readDocument(state);\n }\n\n return state.documents;\n}\n\n\nfunction loadAll(input, iterator, options) {\n if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {\n options = iterator;\n iterator = null;\n }\n\n var documents = loadDocuments(input, options);\n\n if (typeof iterator !== 'function') {\n return documents;\n }\n\n for (var index = 0, length = documents.length; index < length; index += 1) {\n iterator(documents[index]);\n }\n}\n\n\nfunction load(input, options) {\n var documents = loadDocuments(input, options);\n\n if (documents.length === 0) {\n /*eslint-disable no-undefined*/\n return undefined;\n } else if (documents.length === 1) {\n return documents[0];\n }\n throw new YAMLException('expected a single document in the stream, but found more');\n}\n\n\nfunction safeLoadAll(input, iterator, options) {\n if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {\n options = iterator;\n iterator = null;\n }\n\n return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));\n}\n\n\nfunction safeLoad(input, options) {\n return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));\n}\n\n\nmodule.exports.loadAll = loadAll;\nmodule.exports.load = load;\nmodule.exports.safeLoadAll = safeLoadAll;\nmodule.exports.safeLoad = safeLoad;\n","'use strict';\n\n/*eslint-disable no-use-before-define*/\n\nvar common = require('./common');\nvar YAMLException = require('./exception');\nvar DEFAULT_FULL_SCHEMA = require('./schema/default_full');\nvar DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');\n\nvar _toString = Object.prototype.toString;\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar CHAR_TAB = 0x09; /* Tab */\nvar CHAR_LINE_FEED = 0x0A; /* LF */\nvar CHAR_CARRIAGE_RETURN = 0x0D; /* CR */\nvar CHAR_SPACE = 0x20; /* Space */\nvar CHAR_EXCLAMATION = 0x21; /* ! */\nvar CHAR_DOUBLE_QUOTE = 0x22; /* \" */\nvar CHAR_SHARP = 0x23; /* # */\nvar CHAR_PERCENT = 0x25; /* % */\nvar CHAR_AMPERSAND = 0x26; /* & */\nvar CHAR_SINGLE_QUOTE = 0x27; /* ' */\nvar CHAR_ASTERISK = 0x2A; /* * */\nvar CHAR_COMMA = 0x2C; /* , */\nvar CHAR_MINUS = 0x2D; /* - */\nvar CHAR_COLON = 0x3A; /* : */\nvar CHAR_EQUALS = 0x3D; /* = */\nvar CHAR_GREATER_THAN = 0x3E; /* > */\nvar CHAR_QUESTION = 0x3F; /* ? */\nvar CHAR_COMMERCIAL_AT = 0x40; /* @ */\nvar CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */\nvar CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */\nvar CHAR_GRAVE_ACCENT = 0x60; /* ` */\nvar CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */\nvar CHAR_VERTICAL_LINE = 0x7C; /* | */\nvar CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */\n\nvar ESCAPE_SEQUENCES = {};\n\nESCAPE_SEQUENCES[0x00] = '\\\\0';\nESCAPE_SEQUENCES[0x07] = '\\\\a';\nESCAPE_SEQUENCES[0x08] = '\\\\b';\nESCAPE_SEQUENCES[0x09] = '\\\\t';\nESCAPE_SEQUENCES[0x0A] = '\\\\n';\nESCAPE_SEQUENCES[0x0B] = '\\\\v';\nESCAPE_SEQUENCES[0x0C] = '\\\\f';\nESCAPE_SEQUENCES[0x0D] = '\\\\r';\nESCAPE_SEQUENCES[0x1B] = '\\\\e';\nESCAPE_SEQUENCES[0x22] = '\\\\\"';\nESCAPE_SEQUENCES[0x5C] = '\\\\\\\\';\nESCAPE_SEQUENCES[0x85] = '\\\\N';\nESCAPE_SEQUENCES[0xA0] = '\\\\_';\nESCAPE_SEQUENCES[0x2028] = '\\\\L';\nESCAPE_SEQUENCES[0x2029] = '\\\\P';\n\nvar DEPRECATED_BOOLEANS_SYNTAX = [\n 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',\n 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'\n];\n\nfunction compileStyleMap(schema, map) {\n var result, keys, index, length, tag, style, type;\n\n if (map === null) return {};\n\n result = {};\n keys = Object.keys(map);\n\n for (index = 0, length = keys.length; index < length; index += 1) {\n tag = keys[index];\n style = String(map[tag]);\n\n if (tag.slice(0, 2) === '!!') {\n tag = 'tag:yaml.org,2002:' + tag.slice(2);\n }\n type = schema.compiledTypeMap['fallback'][tag];\n\n if (type && _hasOwnProperty.call(type.styleAliases, style)) {\n style = type.styleAliases[style];\n }\n\n result[tag] = style;\n }\n\n return result;\n}\n\nfunction encodeHex(character) {\n var string, handle, length;\n\n string = character.toString(16).toUpperCase();\n\n if (character <= 0xFF) {\n handle = 'x';\n length = 2;\n } else if (character <= 0xFFFF) {\n handle = 'u';\n length = 4;\n } else if (character <= 0xFFFFFFFF) {\n handle = 'U';\n length = 8;\n } else {\n throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');\n }\n\n return '\\\\' + handle + common.repeat('0', length - string.length) + string;\n}\n\nfunction State(options) {\n this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;\n this.indent = Math.max(1, (options['indent'] || 2));\n this.noArrayIndent = options['noArrayIndent'] || false;\n this.skipInvalid = options['skipInvalid'] || false;\n this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);\n this.styleMap = compileStyleMap(this.schema, options['styles'] || null);\n this.sortKeys = options['sortKeys'] || false;\n this.lineWidth = options['lineWidth'] || 80;\n this.noRefs = options['noRefs'] || false;\n this.noCompatMode = options['noCompatMode'] || false;\n this.condenseFlow = options['condenseFlow'] || false;\n\n this.implicitTypes = this.schema.compiledImplicit;\n this.explicitTypes = this.schema.compiledExplicit;\n\n this.tag = null;\n this.result = '';\n\n this.duplicates = [];\n this.usedDuplicates = null;\n}\n\n// Indents every line in a string. Empty lines (\\n only) are not indented.\nfunction indentString(string, spaces) {\n var ind = common.repeat(' ', spaces),\n position = 0,\n next = -1,\n result = '',\n line,\n length = string.length;\n\n while (position < length) {\n next = string.indexOf('\\n', position);\n if (next === -1) {\n line = string.slice(position);\n position = length;\n } else {\n line = string.slice(position, next + 1);\n position = next + 1;\n }\n\n if (line.length && line !== '\\n') result += ind;\n\n result += line;\n }\n\n return result;\n}\n\nfunction generateNextLine(state, level) {\n return '\\n' + common.repeat(' ', state.indent * level);\n}\n\nfunction testImplicitResolving(state, str) {\n var index, length, type;\n\n for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n type = state.implicitTypes[index];\n\n if (type.resolve(str)) {\n return true;\n }\n }\n\n return false;\n}\n\n// [33] s-white ::= s-space | s-tab\nfunction isWhitespace(c) {\n return c === CHAR_SPACE || c === CHAR_TAB;\n}\n\n// Returns true if the character can be printed without escaping.\n// From YAML 1.2: \"any allowed characters known to be non-printable\n// should also be escaped. [However,] This isn’t mandatory\"\n// Derived from nb-char - \\t - #x85 - #xA0 - #x2028 - #x2029.\nfunction isPrintable(c) {\n return (0x00020 <= c && c <= 0x00007E)\n || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)\n || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)\n || (0x10000 <= c && c <= 0x10FFFF);\n}\n\n// [34] ns-char ::= nb-char - s-white\n// [27] nb-char ::= c-printable - b-char - c-byte-order-mark\n// [26] b-char ::= b-line-feed | b-carriage-return\n// [24] b-line-feed ::= #xA /* LF */\n// [25] b-carriage-return ::= #xD /* CR */\n// [3] c-byte-order-mark ::= #xFEFF\nfunction isNsChar(c) {\n return isPrintable(c) && !isWhitespace(c)\n // byte-order-mark\n && c !== 0xFEFF\n // b-char\n && c !== CHAR_CARRIAGE_RETURN\n && c !== CHAR_LINE_FEED;\n}\n\n// Simplified test for values allowed after the first character in plain style.\nfunction isPlainSafe(c, prev) {\n // Uses a subset of nb-char - c-flow-indicator - \":\" - \"#\"\n // where nb-char ::= c-printable - b-char - c-byte-order-mark.\n return isPrintable(c) && c !== 0xFEFF\n // - c-flow-indicator\n && c !== CHAR_COMMA\n && c !== CHAR_LEFT_SQUARE_BRACKET\n && c !== CHAR_RIGHT_SQUARE_BRACKET\n && c !== CHAR_LEFT_CURLY_BRACKET\n && c !== CHAR_RIGHT_CURLY_BRACKET\n // - \":\" - \"#\"\n // /* An ns-char preceding */ \"#\"\n && c !== CHAR_COLON\n && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));\n}\n\n// Simplified test for values allowed as the first character in plain style.\nfunction isPlainSafeFirst(c) {\n // Uses a subset of ns-char - c-indicator\n // where ns-char = nb-char - s-white.\n return isPrintable(c) && c !== 0xFEFF\n && !isWhitespace(c) // - s-white\n // - (c-indicator ::=\n // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”\n && c !== CHAR_MINUS\n && c !== CHAR_QUESTION\n && c !== CHAR_COLON\n && c !== CHAR_COMMA\n && c !== CHAR_LEFT_SQUARE_BRACKET\n && c !== CHAR_RIGHT_SQUARE_BRACKET\n && c !== CHAR_LEFT_CURLY_BRACKET\n && c !== CHAR_RIGHT_CURLY_BRACKET\n // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “\"”\n && c !== CHAR_SHARP\n && c !== CHAR_AMPERSAND\n && c !== CHAR_ASTERISK\n && c !== CHAR_EXCLAMATION\n && c !== CHAR_VERTICAL_LINE\n && c !== CHAR_EQUALS\n && c !== CHAR_GREATER_THAN\n && c !== CHAR_SINGLE_QUOTE\n && c !== CHAR_DOUBLE_QUOTE\n // | “%” | “@” | “`”)\n && c !== CHAR_PERCENT\n && c !== CHAR_COMMERCIAL_AT\n && c !== CHAR_GRAVE_ACCENT;\n}\n\n// Determines whether block indentation indicator is required.\nfunction needIndentIndicator(string) {\n var leadingSpaceRe = /^\\n* /;\n return leadingSpaceRe.test(string);\n}\n\nvar STYLE_PLAIN = 1,\n STYLE_SINGLE = 2,\n STYLE_LITERAL = 3,\n STYLE_FOLDED = 4,\n STYLE_DOUBLE = 5;\n\n// Determines which scalar styles are possible and returns the preferred style.\n// lineWidth = -1 => no limit.\n// Pre-conditions: str.length > 0.\n// Post-conditions:\n// STYLE_PLAIN or STYLE_SINGLE => no \\n are in the string.\n// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).\n// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).\nfunction chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {\n var i;\n var char, prev_char;\n var hasLineBreak = false;\n var hasFoldableLine = false; // only checked if shouldTrackWidth\n var shouldTrackWidth = lineWidth !== -1;\n var previousLineBreak = -1; // count the first line correctly\n var plain = isPlainSafeFirst(string.charCodeAt(0))\n && !isWhitespace(string.charCodeAt(string.length - 1));\n\n if (singleLineOnly) {\n // Case: no block styles.\n // Check for disallowed characters to rule out plain and single.\n for (i = 0; i < string.length; i++) {\n char = string.charCodeAt(i);\n if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n prev_char = i > 0 ? string.charCodeAt(i - 1) : null;\n plain = plain && isPlainSafe(char, prev_char);\n }\n } else {\n // Case: block styles permitted.\n for (i = 0; i < string.length; i++) {\n char = string.charCodeAt(i);\n if (char === CHAR_LINE_FEED) {\n hasLineBreak = true;\n // Check if any line can be folded.\n if (shouldTrackWidth) {\n hasFoldableLine = hasFoldableLine ||\n // Foldable line = too long, and not more-indented.\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' ');\n previousLineBreak = i;\n }\n } else if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n prev_char = i > 0 ? string.charCodeAt(i - 1) : null;\n plain = plain && isPlainSafe(char, prev_char);\n }\n // in case the end is missing a \\n\n hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' '));\n }\n // Although every style can represent \\n without escaping, prefer block styles\n // for multiline, since they're more readable and they don't add empty lines.\n // Also prefer folding a super-long line.\n if (!hasLineBreak && !hasFoldableLine) {\n // Strings interpretable as another type have to be quoted;\n // e.g. the string 'true' vs. the boolean true.\n return plain && !testAmbiguousType(string)\n ? STYLE_PLAIN : STYLE_SINGLE;\n }\n // Edge case: block indentation indicator can only have one digit.\n if (indentPerLevel > 9 && needIndentIndicator(string)) {\n return STYLE_DOUBLE;\n }\n // At this point we know block styles are valid.\n // Prefer literal style unless we want to fold.\n return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;\n}\n\n// Note: line breaking/folding is implemented for only the folded style.\n// NB. We drop the last trailing newline (if any) of a returned block scalar\n// since the dumper adds its own newline. This always works:\n// • No ending newline => unaffected; already using strip \"-\" chomping.\n// • Ending newline => removed then restored.\n// Importantly, this keeps the \"+\" chomp indicator from gaining an extra line.\nfunction writeScalar(state, string, level, iskey) {\n state.dump = (function () {\n if (string.length === 0) {\n return \"''\";\n }\n if (!state.noCompatMode &&\n DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {\n return \"'\" + string + \"'\";\n }\n\n var indent = state.indent * Math.max(1, level); // no 0-indent scalars\n // As indentation gets deeper, let the width decrease monotonically\n // to the lower bound min(state.lineWidth, 40).\n // Note that this implies\n // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.\n // state.lineWidth > 40 + state.indent: width decreases until the lower bound.\n // This behaves better than a constant minimum width which disallows narrower options,\n // or an indent threshold which causes the width to suddenly increase.\n var lineWidth = state.lineWidth === -1\n ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);\n\n // Without knowing if keys are implicit/explicit, assume implicit for safety.\n var singleLineOnly = iskey\n // No block styles in flow mode.\n || (state.flowLevel > -1 && level >= state.flowLevel);\n function testAmbiguity(string) {\n return testImplicitResolving(state, string);\n }\n\n switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {\n case STYLE_PLAIN:\n return string;\n case STYLE_SINGLE:\n return \"'\" + string.replace(/'/g, \"''\") + \"'\";\n case STYLE_LITERAL:\n return '|' + blockHeader(string, state.indent)\n + dropEndingNewline(indentString(string, indent));\n case STYLE_FOLDED:\n return '>' + blockHeader(string, state.indent)\n + dropEndingNewline(indentString(foldString(string, lineWidth), indent));\n case STYLE_DOUBLE:\n return '\"' + escapeString(string, lineWidth) + '\"';\n default:\n throw new YAMLException('impossible error: invalid scalar style');\n }\n }());\n}\n\n// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.\nfunction blockHeader(string, indentPerLevel) {\n var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';\n\n // note the special case: the string '\\n' counts as a \"trailing\" empty line.\n var clip = string[string.length - 1] === '\\n';\n var keep = clip && (string[string.length - 2] === '\\n' || string === '\\n');\n var chomp = keep ? '+' : (clip ? '' : '-');\n\n return indentIndicator + chomp + '\\n';\n}\n\n// (See the note for writeScalar.)\nfunction dropEndingNewline(string) {\n return string[string.length - 1] === '\\n' ? string.slice(0, -1) : string;\n}\n\n// Note: a long line without a suitable break point will exceed the width limit.\n// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.\nfunction foldString(string, width) {\n // In folded style, $k$ consecutive newlines output as $k+1$ newlines—\n // unless they're before or after a more-indented line, or at the very\n // beginning or end, in which case $k$ maps to $k$.\n // Therefore, parse each chunk as newline(s) followed by a content line.\n var lineRe = /(\\n+)([^\\n]*)/g;\n\n // first line (possibly an empty line)\n var result = (function () {\n var nextLF = string.indexOf('\\n');\n nextLF = nextLF !== -1 ? nextLF : string.length;\n lineRe.lastIndex = nextLF;\n return foldLine(string.slice(0, nextLF), width);\n }());\n // If we haven't reached the first content line yet, don't add an extra \\n.\n var prevMoreIndented = string[0] === '\\n' || string[0] === ' ';\n var moreIndented;\n\n // rest of the lines\n var match;\n while ((match = lineRe.exec(string))) {\n var prefix = match[1], line = match[2];\n moreIndented = (line[0] === ' ');\n result += prefix\n + (!prevMoreIndented && !moreIndented && line !== ''\n ? '\\n' : '')\n + foldLine(line, width);\n prevMoreIndented = moreIndented;\n }\n\n return result;\n}\n\n// Greedy line breaking.\n// Picks the longest line under the limit each time,\n// otherwise settles for the shortest line over the limit.\n// NB. More-indented lines *cannot* be folded, as that would add an extra \\n.\nfunction foldLine(line, width) {\n if (line === '' || line[0] === ' ') return line;\n\n // Since a more-indented line adds a \\n, breaks can't be followed by a space.\n var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.\n var match;\n // start is an inclusive index. end, curr, and next are exclusive.\n var start = 0, end, curr = 0, next = 0;\n var result = '';\n\n // Invariants: 0 <= start <= length-1.\n // 0 <= curr <= next <= max(0, length-2). curr - start <= width.\n // Inside the loop:\n // A match implies length >= 2, so curr and next are <= length-2.\n while ((match = breakRe.exec(line))) {\n next = match.index;\n // maintain invariant: curr - start <= width\n if (next - start > width) {\n end = (curr > start) ? curr : next; // derive end <= length-2\n result += '\\n' + line.slice(start, end);\n // skip the space that was output as \\n\n start = end + 1; // derive start <= length-1\n }\n curr = next;\n }\n\n // By the invariants, start <= length-1, so there is something left over.\n // It is either the whole string or a part starting from non-whitespace.\n result += '\\n';\n // Insert a break if the remainder is too long and there is a break available.\n if (line.length - start > width && curr > start) {\n result += line.slice(start, curr) + '\\n' + line.slice(curr + 1);\n } else {\n result += line.slice(start);\n }\n\n return result.slice(1); // drop extra \\n joiner\n}\n\n// Escapes a double-quoted string.\nfunction escapeString(string) {\n var result = '';\n var char, nextChar;\n var escapeSeq;\n\n for (var i = 0; i < string.length; i++) {\n char = string.charCodeAt(i);\n // Check for surrogate pairs (reference Unicode 3.0 section \"3.7 Surrogates\").\n if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {\n nextChar = string.charCodeAt(i + 1);\n if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {\n // Combine the surrogate pair and store it escaped.\n result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);\n // Advance index one extra since we already used that char here.\n i++; continue;\n }\n }\n escapeSeq = ESCAPE_SEQUENCES[char];\n result += !escapeSeq && isPrintable(char)\n ? string[i]\n : escapeSeq || encodeHex(char);\n }\n\n return result;\n}\n\nfunction writeFlowSequence(state, level, object) {\n var _result = '',\n _tag = state.tag,\n index,\n length;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n // Write only valid elements.\n if (writeNode(state, level, object[index], false, false)) {\n if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');\n _result += state.dump;\n }\n }\n\n state.tag = _tag;\n state.dump = '[' + _result + ']';\n}\n\nfunction writeBlockSequence(state, level, object, compact) {\n var _result = '',\n _tag = state.tag,\n index,\n length;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n // Write only valid elements.\n if (writeNode(state, level + 1, object[index], true, true)) {\n if (!compact || index !== 0) {\n _result += generateNextLine(state, level);\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n _result += '-';\n } else {\n _result += '- ';\n }\n\n _result += state.dump;\n }\n }\n\n state.tag = _tag;\n state.dump = _result || '[]'; // Empty sequence if no valid values.\n}\n\nfunction writeFlowMapping(state, level, object) {\n var _result = '',\n _tag = state.tag,\n objectKeyList = Object.keys(object),\n index,\n length,\n objectKey,\n objectValue,\n pairBuffer;\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n\n pairBuffer = '';\n if (index !== 0) pairBuffer += ', ';\n\n if (state.condenseFlow) pairBuffer += '\"';\n\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n\n if (!writeNode(state, level, objectKey, false, false)) {\n continue; // Skip this pair because of invalid key;\n }\n\n if (state.dump.length > 1024) pairBuffer += '? ';\n\n pairBuffer += state.dump + (state.condenseFlow ? '\"' : '') + ':' + (state.condenseFlow ? '' : ' ');\n\n if (!writeNode(state, level, objectValue, false, false)) {\n continue; // Skip this pair because of invalid value.\n }\n\n pairBuffer += state.dump;\n\n // Both key and value are valid.\n _result += pairBuffer;\n }\n\n state.tag = _tag;\n state.dump = '{' + _result + '}';\n}\n\nfunction writeBlockMapping(state, level, object, compact) {\n var _result = '',\n _tag = state.tag,\n objectKeyList = Object.keys(object),\n index,\n length,\n objectKey,\n objectValue,\n explicitPair,\n pairBuffer;\n\n // Allow sorting keys so that the output file is deterministic\n if (state.sortKeys === true) {\n // Default sorting\n objectKeyList.sort();\n } else if (typeof state.sortKeys === 'function') {\n // Custom sort function\n objectKeyList.sort(state.sortKeys);\n } else if (state.sortKeys) {\n // Something is wrong\n throw new YAMLException('sortKeys must be a boolean or a function');\n }\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n pairBuffer = '';\n\n if (!compact || index !== 0) {\n pairBuffer += generateNextLine(state, level);\n }\n\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n\n if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n continue; // Skip this pair because of invalid key.\n }\n\n explicitPair = (state.tag !== null && state.tag !== '?') ||\n (state.dump && state.dump.length > 1024);\n\n if (explicitPair) {\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += '?';\n } else {\n pairBuffer += '? ';\n }\n }\n\n pairBuffer += state.dump;\n\n if (explicitPair) {\n pairBuffer += generateNextLine(state, level);\n }\n\n if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n continue; // Skip this pair because of invalid value.\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += ':';\n } else {\n pairBuffer += ': ';\n }\n\n pairBuffer += state.dump;\n\n // Both key and value are valid.\n _result += pairBuffer;\n }\n\n state.tag = _tag;\n state.dump = _result || '{}'; // Empty mapping if no valid pairs.\n}\n\nfunction detectType(state, object, explicit) {\n var _result, typeList, index, length, type, style;\n\n typeList = explicit ? state.explicitTypes : state.implicitTypes;\n\n for (index = 0, length = typeList.length; index < length; index += 1) {\n type = typeList[index];\n\n if ((type.instanceOf || type.predicate) &&\n (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&\n (!type.predicate || type.predicate(object))) {\n\n state.tag = explicit ? type.tag : '?';\n\n if (type.represent) {\n style = state.styleMap[type.tag] || type.defaultStyle;\n\n if (_toString.call(type.represent) === '[object Function]') {\n _result = type.represent(object, style);\n } else if (_hasOwnProperty.call(type.represent, style)) {\n _result = type.represent[style](object, style);\n } else {\n throw new YAMLException('!<' + type.tag + '> tag resolver accepts not \"' + style + '\" style');\n }\n\n state.dump = _result;\n }\n\n return true;\n }\n }\n\n return false;\n}\n\n// Serializes `object` and writes it to global `result`.\n// Returns true on success, or false on invalid object.\n//\nfunction writeNode(state, level, object, block, compact, iskey) {\n state.tag = null;\n state.dump = object;\n\n if (!detectType(state, object, false)) {\n detectType(state, object, true);\n }\n\n var type = _toString.call(state.dump);\n\n if (block) {\n block = (state.flowLevel < 0 || state.flowLevel > level);\n }\n\n var objectOrArray = type === '[object Object]' || type === '[object Array]',\n duplicateIndex,\n duplicate;\n\n if (objectOrArray) {\n duplicateIndex = state.duplicates.indexOf(object);\n duplicate = duplicateIndex !== -1;\n }\n\n if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {\n compact = false;\n }\n\n if (duplicate && state.usedDuplicates[duplicateIndex]) {\n state.dump = '*ref_' + duplicateIndex;\n } else {\n if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n state.usedDuplicates[duplicateIndex] = true;\n }\n if (type === '[object Object]') {\n if (block && (Object.keys(state.dump).length !== 0)) {\n writeBlockMapping(state, level, state.dump, compact);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump;\n }\n } else {\n writeFlowMapping(state, level, state.dump);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n }\n }\n } else if (type === '[object Array]') {\n var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;\n if (block && (state.dump.length !== 0)) {\n writeBlockSequence(state, arrayLevel, state.dump, compact);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump;\n }\n } else {\n writeFlowSequence(state, arrayLevel, state.dump);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n }\n }\n } else if (type === '[object String]') {\n if (state.tag !== '?') {\n writeScalar(state, state.dump, level, iskey);\n }\n } else {\n if (state.skipInvalid) return false;\n throw new YAMLException('unacceptable kind of an object to dump ' + type);\n }\n\n if (state.tag !== null && state.tag !== '?') {\n state.dump = '!<' + state.tag + '> ' + state.dump;\n }\n }\n\n return true;\n}\n\nfunction getDuplicateReferences(object, state) {\n var objects = [],\n duplicatesIndexes = [],\n index,\n length;\n\n inspectNode(object, objects, duplicatesIndexes);\n\n for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {\n state.duplicates.push(objects[duplicatesIndexes[index]]);\n }\n state.usedDuplicates = new Array(length);\n}\n\nfunction inspectNode(object, objects, duplicatesIndexes) {\n var objectKeyList,\n index,\n length;\n\n if (object !== null && typeof object === 'object') {\n index = objects.indexOf(object);\n if (index !== -1) {\n if (duplicatesIndexes.indexOf(index) === -1) {\n duplicatesIndexes.push(index);\n }\n } else {\n objects.push(object);\n\n if (Array.isArray(object)) {\n for (index = 0, length = object.length; index < length; index += 1) {\n inspectNode(object[index], objects, duplicatesIndexes);\n }\n } else {\n objectKeyList = Object.keys(object);\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);\n }\n }\n }\n }\n}\n\nfunction dump(input, options) {\n options = options || {};\n\n var state = new State(options);\n\n if (!state.noRefs) getDuplicateReferences(input, state);\n\n if (writeNode(state, 0, input, true, true)) return state.dump + '\\n';\n\n return '';\n}\n\nfunction safeDump(input, options) {\n return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));\n}\n\nmodule.exports.dump = dump;\nmodule.exports.safeDump = safeDump;\n","'use strict';\n\n\nvar loader = require('./js-yaml/loader');\nvar dumper = require('./js-yaml/dumper');\n\n\nfunction deprecated(name) {\n return function () {\n throw new Error('Function ' + name + ' is deprecated and cannot be used.');\n };\n}\n\n\nmodule.exports.Type = require('./js-yaml/type');\nmodule.exports.Schema = require('./js-yaml/schema');\nmodule.exports.FAILSAFE_SCHEMA = require('./js-yaml/schema/failsafe');\nmodule.exports.JSON_SCHEMA = require('./js-yaml/schema/json');\nmodule.exports.CORE_SCHEMA = require('./js-yaml/schema/core');\nmodule.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe');\nmodule.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full');\nmodule.exports.load = loader.load;\nmodule.exports.loadAll = loader.loadAll;\nmodule.exports.safeLoad = loader.safeLoad;\nmodule.exports.safeLoadAll = loader.safeLoadAll;\nmodule.exports.dump = dumper.dump;\nmodule.exports.safeDump = dumper.safeDump;\nmodule.exports.YAMLException = require('./js-yaml/exception');\n\n// Deprecated schema names from JS-YAML 2.0.x\nmodule.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');\nmodule.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe');\nmodule.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');\n\n// Deprecated functions from JS-YAML 1.x.x\nmodule.exports.scan = deprecated('scan');\nmodule.exports.parse = deprecated('parse');\nmodule.exports.compose = deprecated('compose');\nmodule.exports.addConstructor = deprecated('addConstructor');\n","'use strict';\n\n\nvar yaml = require('./lib/js-yaml.js');\n\n\nmodule.exports = yaml;\n","'use strict';\n\nconst yaml = require('js-yaml');\n\n/**\n * Default engines\n */\n\nconst engines = exports = module.exports;\n\n/**\n * YAML\n */\n\nengines.yaml = {\n parse: yaml.safeLoad.bind(yaml),\n stringify: yaml.safeDump.bind(yaml)\n};\n\n/**\n * JSON\n */\n\nengines.json = {\n parse: JSON.parse.bind(JSON),\n stringify: function(obj, options) {\n const opts = Object.assign({replacer: null, space: 2}, options);\n return JSON.stringify(obj, opts.replacer, opts.space);\n }\n};\n\n/**\n * JavaScript\n */\n\nengines.javascript = {\n parse: function parse(str, options, wrap) {\n /* eslint no-eval: 0 */\n try {\n if (wrap !== false) {\n str = '(function() {\\nreturn ' + str.trim() + ';\\n}());';\n }\n return eval(str) || {};\n } catch (err) {\n if (wrap !== false && /(unexpected|identifier)/i.test(err.message)) {\n return parse(str, options, false);\n }\n throw new SyntaxError(err);\n }\n },\n stringify: function() {\n throw new Error('stringifying JavaScript is not supported');\n }\n};\n","/*!\n * strip-bom-string <https://github.com/jonschlinkert/strip-bom-string>\n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function(str) {\n if (typeof str === 'string' && str.charAt(0) === '\\ufeff') {\n return str.slice(1);\n }\n return str;\n};\n","'use strict';\n\nconst stripBom = require('strip-bom-string');\nconst typeOf = require('kind-of');\n\nexports.define = function(obj, key, val) {\n Reflect.defineProperty(obj, key, {\n enumerable: false,\n configurable: true,\n writable: true,\n value: val\n });\n};\n\n/**\n * Returns true if `val` is a buffer\n */\n\nexports.isBuffer = function(val) {\n return typeOf(val) === 'buffer';\n};\n\n/**\n * Returns true if `val` is an object\n */\n\nexports.isObject = function(val) {\n return typeOf(val) === 'object';\n};\n\n/**\n * Cast `input` to a buffer\n */\n\nexports.toBuffer = function(input) {\n return typeof input === 'string' ? Buffer.from(input) : input;\n};\n\n/**\n * Cast `val` to a string.\n */\n\nexports.toString = function(input) {\n if (exports.isBuffer(input)) return stripBom(String(input));\n if (typeof input !== 'string') {\n throw new TypeError('expected input to be a string or buffer');\n }\n return stripBom(input);\n};\n\n/**\n * Cast `val` to an array.\n */\n\nexports.arrayify = function(val) {\n return val ? (Array.isArray(val) ? val : [val]) : [];\n};\n\n/**\n * Returns true if `str` starts with `substr`.\n */\n\nexports.startsWith = function(str, substr, len) {\n if (typeof len !== 'number') len = substr.length;\n return str.slice(0, len) === substr;\n};\n","'use strict';\n\nconst engines = require('./engines');\nconst utils = require('./utils');\n\nmodule.exports = function(options) {\n const opts = Object.assign({}, options);\n\n // ensure that delimiters are an array\n opts.delimiters = utils.arrayify(opts.delims || opts.delimiters || '---');\n if (opts.delimiters.length === 1) {\n opts.delimiters.push(opts.delimiters[0]);\n }\n\n opts.language = (opts.language || opts.lang || 'yaml').toLowerCase();\n opts.engines = Object.assign({}, engines, opts.parsers, opts.engines);\n return opts;\n};\n","'use strict';\n\nmodule.exports = function(name, options) {\n let engine = options.engines[name] || options.engines[aliase(name)];\n if (typeof engine === 'undefined') {\n throw new Error('gray-matter engine \"' + name + '\" is not registered');\n }\n if (typeof engine === 'function') {\n engine = { parse: engine };\n }\n return engine;\n};\n\nfunction aliase(name) {\n switch (name.toLowerCase()) {\n case 'js':\n case 'javascript':\n return 'javascript';\n case 'coffee':\n case 'coffeescript':\n case 'cson':\n return 'coffee';\n case 'yaml':\n case 'yml':\n return 'yaml';\n default: {\n return name;\n }\n }\n}\n","'use strict';\n\nconst typeOf = require('kind-of');\nconst getEngine = require('./engine');\nconst defaults = require('./defaults');\n\nmodule.exports = function(file, data, options) {\n if (data == null && options == null) {\n switch (typeOf(file)) {\n case 'object':\n data = file.data;\n options = {};\n break;\n case 'string':\n return file;\n default: {\n throw new TypeError('expected file to be a string or object');\n }\n }\n }\n\n const str = file.content;\n const opts = defaults(options);\n if (data == null) {\n if (!opts.data) return file;\n data = opts.data;\n }\n\n const language = file.language || opts.language;\n const engine = getEngine(language, opts);\n if (typeof engine.stringify !== 'function') {\n throw new TypeError('expected \"' + language + '.stringify\" to be a function');\n }\n\n data = Object.assign({}, file.data, data);\n const open = opts.delimiters[0];\n const close = opts.delimiters[1];\n const matter = engine.stringify(data, options).trim();\n let buf = '';\n\n if (matter !== '{}') {\n buf = newline(open) + newline(matter) + newline(close);\n }\n\n if (typeof file.excerpt === 'string' && file.excerpt !== '') {\n if (str.indexOf(file.excerpt.trim()) === -1) {\n buf += newline(file.excerpt) + newline(close);\n }\n }\n\n return buf + newline(str);\n};\n\nfunction newline(str) {\n return str.slice(-1) !== '\\n' ? str + '\\n' : str;\n}\n","'use strict';\n\nconst defaults = require('./defaults');\n\nmodule.exports = function(file, options) {\n const opts = defaults(options);\n\n if (file.data == null) {\n file.data = {};\n }\n\n if (typeof opts.excerpt === 'function') {\n return opts.excerpt(file, opts);\n }\n\n const sep = file.data.excerpt_separator || opts.excerpt_separator;\n if (sep == null && (opts.excerpt === false || opts.excerpt == null)) {\n return file;\n }\n\n const delimiter = typeof opts.excerpt === 'string'\n ? opts.excerpt\n : (sep || opts.delimiters[0]);\n\n // if enabled, get the excerpt defined after front-matter\n const idx = file.content.indexOf(delimiter);\n if (idx !== -1) {\n file.excerpt = file.content.slice(0, idx);\n }\n\n return file;\n};\n","'use strict';\n\nconst typeOf = require('kind-of');\nconst stringify = require('./stringify');\nconst utils = require('./utils');\n\n/**\n * Normalize the given value to ensure an object is returned\n * with the expected properties.\n */\n\nmodule.exports = function(file) {\n if (typeOf(file) !== 'object') {\n file = { content: file };\n }\n\n if (typeOf(file.data) !== 'object') {\n file.data = {};\n }\n\n // if file was passed as an object, ensure that\n // \"file.content\" is set\n if (file.contents && file.content == null) {\n file.content = file.contents;\n }\n\n // set non-enumerable properties on the file object\n utils.define(file, 'orig', utils.toBuffer(file.content));\n utils.define(file, 'language', file.language || '');\n utils.define(file, 'matter', file.matter || '');\n utils.define(file, 'stringify', function(data, options) {\n if (options && options.language) {\n file.language = options.language;\n }\n return stringify(file, data, options);\n });\n\n // strip BOM and ensure that \"file.content\" is a string\n file.content = utils.toString(file.content);\n file.isEmpty = false;\n file.excerpt = '';\n return file;\n};\n","'use strict';\n\nconst getEngine = require('./engine');\nconst defaults = require('./defaults');\n\nmodule.exports = function(language, str, options) {\n const opts = defaults(options);\n const engine = getEngine(language, opts);\n if (typeof engine.parse !== 'function') {\n throw new TypeError('expected \"' + language + '.parse\" to be a function');\n }\n return engine.parse(str, opts);\n};\n","'use strict';\n\nconst fs = require('fs');\nconst sections = require('section-matter');\nconst defaults = require('./lib/defaults');\nconst stringify = require('./lib/stringify');\nconst excerpt = require('./lib/excerpt');\nconst engines = require('./lib/engines');\nconst toFile = require('./lib/to-file');\nconst parse = require('./lib/parse');\nconst utils = require('./lib/utils');\n\n/**\n * Takes a string or object with `content` property, extracts\n * and parses front-matter from the string, then returns an object\n * with `data`, `content` and other [useful properties](#returned-object).\n *\n * ```js\n * const matter = require('gray-matter');\n * console.log(matter('---\\ntitle: Home\\n---\\nOther stuff'));\n * //=> { data: { title: 'Home'}, content: 'Other stuff' }\n * ```\n * @param {Object|String} `input` String, or object with `content` string\n * @param {Object} `options`\n * @return {Object}\n * @api public\n */\n\nfunction matter(input, options) {\n if (input === '') {\n return { data: {}, content: input, excerpt: '', orig: input };\n }\n\n let file = toFile(input);\n const cached = matter.cache[file.content];\n\n if (!options) {\n if (cached) {\n file = Object.assign({}, cached);\n file.orig = cached.orig;\n return file;\n }\n\n // only cache if there are no options passed. if we cache when options\n // are passed, we would need to also cache options values, which would\n // negate any performance benefits of caching\n matter.cache[file.content] = file;\n }\n\n return parseMatter(file, options);\n}\n\n/**\n * Parse front matter\n */\n\nfunction parseMatter(file, options) {\n const opts = defaults(options);\n const open = opts.delimiters[0];\n const close = '\\n' + opts.delimiters[1];\n let str = file.content;\n\n if (opts.language) {\n file.language = opts.language;\n }\n\n // get the length of the opening delimiter\n const openLen = open.length;\n if (!utils.startsWith(str, open, openLen)) {\n excerpt(file, opts);\n return file;\n }\n\n // if the next character after the opening delimiter is\n // a character from the delimiter, then it's not a front-\n // matter delimiter\n if (str.charAt(openLen) === open.slice(-1)) {\n return file;\n }\n\n // strip the opening delimiter\n str = str.slice(openLen);\n const len = str.length;\n\n // use the language defined after first delimiter, if it exists\n const language = matter.language(str, opts);\n if (language.name) {\n file.language = language.name;\n str = str.slice(language.raw.length);\n }\n\n // get the index of the closing delimiter\n let closeIndex = str.indexOf(close);\n if (closeIndex === -1) {\n closeIndex = len;\n }\n\n // get the raw front-matter block\n file.matter = str.slice(0, closeIndex);\n\n const block = file.matter.replace(/^\\s*#[^\\n]+/gm, '').trim();\n if (block === '') {\n file.isEmpty = true;\n file.empty = file.content;\n file.data = {};\n } else {\n\n // create file.data by parsing the raw file.matter block\n file.data = parse(file.language, file.matter, opts);\n }\n\n // update file.content\n if (closeIndex === len) {\n file.content = '';\n } else {\n file.content = str.slice(closeIndex + close.length);\n if (file.content[0] === '\\r') {\n file.content = file.content.slice(1);\n }\n if (file.content[0] === '\\n') {\n file.content = file.content.slice(1);\n }\n }\n\n excerpt(file, opts);\n\n if (opts.sections === true || typeof opts.section === 'function') {\n sections(file, opts.section);\n }\n return file;\n}\n\n/**\n * Expose engines\n */\n\nmatter.engines = engines;\n\n/**\n * Stringify an object to YAML or the specified language, and\n * append it to the given string. By default, only YAML and JSON\n * can be stringified. See the [engines](#engines) section to learn\n * how to stringify other languages.\n *\n * ```js\n * console.log(matter.stringify('foo bar baz', {title: 'Home'}));\n * // results in:\n * // ---\n * // title: Home\n * // ---\n * // foo bar baz\n * ```\n * @param {String|Object} `file` The content string to append to stringified front-matter, or a file object with `file.content` string.\n * @param {Object} `data` Front matter to stringify.\n * @param {Object} `options` [Options](#options) to pass to gray-matter and [js-yaml].\n * @return {String} Returns a string created by wrapping stringified yaml with delimiters, and appending that to the given string.\n * @api public\n */\n\nmatter.stringify = function(file, data, options) {\n if (typeof file === 'string') file = matter(file, options);\n return stringify(file, data, options);\n};\n\n/**\n * Synchronously read a file from the file system and parse\n * front matter. Returns the same object as the [main function](#matter).\n *\n * ```js\n * const file = matter.read('./content/blog-post.md');\n * ```\n * @param {String} `filepath` file path of the file to read.\n * @param {Object} `options` [Options](#options) to pass to gray-matter.\n * @return {Object} Returns [an object](#returned-object) with `data` and `content`\n * @api public\n */\n\nmatter.read = function(filepath, options) {\n const str = fs.readFileSync(filepath, 'utf8');\n const file = matter(str, options);\n file.path = filepath;\n return file;\n};\n\n/**\n * Returns true if the given `string` has front matter.\n * @param {String} `string`\n * @param {Object} `options`\n * @return {Boolean} True if front matter exists.\n * @api public\n */\n\nmatter.test = function(str, options) {\n return utils.startsWith(str, defaults(options).delimiters[0]);\n};\n\n/**\n * Detect the language to use, if one is defined after the\n * first front-matter delimiter.\n * @param {String} `string`\n * @param {Object} `options`\n * @return {Object} Object with `raw` (actual language string), and `name`, the language with whitespace trimmed\n */\n\nmatter.language = function(str, options) {\n const opts = defaults(options);\n const open = opts.delimiters[0];\n\n if (matter.test(str)) {\n str = str.slice(open.length);\n }\n\n const language = str.slice(0, str.search(/\\r?\\n/));\n return {\n raw: language,\n name: language ? language.trim() : ''\n };\n};\n\n/**\n * Expose `matter`\n */\n\nmatter.cache = {};\nmatter.clearCache = function() {\n matter.cache = {};\n};\nmodule.exports = matter;\n","import type { MycoIndex } from './sqlite.js';\n\nexport interface FtsResult {\n path: string;\n type: string;\n id: string;\n title: string;\n snippet: string;\n rank: number;\n}\n\nexport interface FtsSearchOptions {\n type?: string;\n limit?: number;\n}\n\nexport function initFts(index: MycoIndex): void {\n const db = index.getDb();\n db.exec(`\n CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(\n path UNINDEXED,\n type UNINDEXED,\n id UNINDEXED,\n title,\n content,\n content='notes',\n content_rowid='rowid'\n );\n\n CREATE TRIGGER IF NOT EXISTS notes_ai AFTER INSERT ON notes BEGIN\n INSERT INTO notes_fts(rowid, path, type, id, title, content)\n VALUES (new.rowid, new.path, new.type, new.id, new.title, new.content);\n END;\n\n CREATE TRIGGER IF NOT EXISTS notes_ad AFTER DELETE ON notes BEGIN\n INSERT INTO notes_fts(notes_fts, rowid, path, type, id, title, content)\n VALUES ('delete', old.rowid, old.path, old.type, old.id, old.title, old.content);\n END;\n\n CREATE TRIGGER IF NOT EXISTS notes_au AFTER UPDATE ON notes BEGIN\n INSERT INTO notes_fts(notes_fts, rowid, path, type, id, title, content)\n VALUES ('delete', old.rowid, old.path, old.type, old.id, old.title, old.content);\n INSERT INTO notes_fts(rowid, path, type, id, title, content)\n VALUES (new.rowid, new.path, new.type, new.id, new.title, new.content);\n END;\n `);\n}\n\nexport function searchFts(index: MycoIndex, query: string, options: FtsSearchOptions = {}): FtsResult[] {\n const db = index.getDb();\n const limit = options.limit ?? 20;\n const params: unknown[] = [query];\n\n let typeFilter = '';\n if (options.type) {\n typeFilter = ' AND type = ?';\n params.push(options.type);\n }\n params.push(limit);\n\n const sql = `\n SELECT path, type, id, title,\n snippet(notes_fts, 4, '<mark>', '</mark>', '...', 40) AS snippet,\n rank\n FROM notes_fts\n WHERE notes_fts MATCH ?${typeFilter}\n ORDER BY rank\n LIMIT ?\n `;\n\n return db.prepare(sql).all(...params) as FtsResult[];\n}\n","import type { EmbeddingProvider, EmbeddingResponse } from './llm.js';\n\nexport async function generateEmbedding(\n backend: EmbeddingProvider,\n text: string,\n): Promise<EmbeddingResponse> {\n const raw = await backend.embed(text);\n return {\n embedding: normalize(raw.embedding),\n model: raw.model,\n dimensions: raw.dimensions,\n };\n}\n\nfunction normalize(vec: number[]): number[] {\n const magnitude = Math.sqrt(vec.reduce((sum, v) => sum + v * v, 0));\n if (magnitude === 0) return vec;\n return vec.map((v) => v / magnitude);\n}\n","import { z } from 'zod';\n\nexport const SessionFrontmatterSchema = z.object({\n type: z.literal('session'),\n id: z.string(),\n agent: z.string(),\n user: z.string(),\n started: z.string(),\n ended: z.string().optional(),\n parent: z.string().optional(),\n parent_reason: z.string().optional(),\n plan: z.string().optional(), // backward compat read path\n plans: z.array(z.string()).optional(), // new: multiple plans\n branch: z.string().optional(),\n tags: z.array(z.string()).default([]),\n tools_used: z.number().int().optional(),\n files_changed: z.number().int().optional(),\n});\n\nexport const PlanFrontmatterSchema = z.object({\n type: z.literal('plan'),\n id: z.string(),\n status: z.enum(['active', 'in_progress', 'completed', 'abandoned']).default('active'),\n created: z.string(),\n author: z.string().optional(),\n tags: z.array(z.string()).default([]),\n});\n\nexport const MEMORY_STATUSES = ['active', 'superseded', 'archived'] as const;\nexport type MemoryStatus = (typeof MEMORY_STATUSES)[number];\n\nexport const MemoryFrontmatterSchema = z.object({\n type: z.literal('memory'),\n id: z.string(),\n observation_type: z.string(),\n status: z.enum(MEMORY_STATUSES).default('active'),\n session: z.string().optional(),\n plan: z.string().optional(),\n superseded_by: z.string().optional(),\n consolidated_from: z.array(z.string()).optional(),\n created: z.string(),\n tags: z.array(z.string()).default([]),\n});\n\nexport const ARTIFACT_TYPES = ['spec', 'plan', 'rfc', 'doc', 'other'] as const;\nexport type ArtifactType = (typeof ARTIFACT_TYPES)[number];\n\nexport const ArtifactFrontmatterSchema = z.object({\n type: z.literal('artifact'),\n id: z.string(),\n artifact_type: z.enum(ARTIFACT_TYPES).default('other'),\n source_path: z.string(),\n title: z.string(),\n last_captured_by: z.string(),\n created: z.string(),\n updated: z.string(),\n tags: z.array(z.string()).default([]),\n});\n\nexport const TeamMemberFrontmatterSchema = z.object({\n type: z.literal('team-member'),\n user: z.string(),\n joined: z.string(),\n role: z.string().optional(),\n tags: z.array(z.string()).default([]),\n});\n\nexport type SessionFrontmatter = z.infer<typeof SessionFrontmatterSchema>;\nexport type PlanFrontmatter = z.infer<typeof PlanFrontmatterSchema>;\nexport type MemoryFrontmatter = z.infer<typeof MemoryFrontmatterSchema>;\nexport type ObservationType = MemoryFrontmatter['observation_type'];\nexport type ArtifactFrontmatter = z.infer<typeof ArtifactFrontmatterSchema>;\nexport type TeamMemberFrontmatter = z.infer<typeof TeamMemberFrontmatterSchema>;\n\nexport type NoteFrontmatter =\n | SessionFrontmatter\n | PlanFrontmatter\n | MemoryFrontmatter\n | ArtifactFrontmatter\n | TeamMemberFrontmatter;\n\nexport interface VaultNote<T extends NoteFrontmatter = NoteFrontmatter> {\n path: string;\n frontmatter: T;\n content: string;\n}\n\nconst schemasByType: Record<string, z.ZodSchema> = {\n session: SessionFrontmatterSchema,\n plan: PlanFrontmatterSchema,\n memory: MemoryFrontmatterSchema,\n artifact: ArtifactFrontmatterSchema,\n 'team-member': TeamMemberFrontmatterSchema,\n};\n\nexport function parseNoteFrontmatter(data: Record<string, unknown>): NoteFrontmatter {\n const type = data.type as string;\n const schema = schemasByType[type];\n if (!schema) {\n throw new Error(`Unknown note type: ${type}`);\n }\n // gray-matter and YAML.parse return Date objects for ISO date strings.\n // Coerce them to strings before Zod validation.\n const coerced = coerceDatesToStrings(data);\n return schema.parse(coerced) as NoteFrontmatter;\n}\n\nfunction coerceDatesToStrings(obj: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value instanceof Date) {\n result[key] = value.toISOString();\n } else if (Array.isArray(value)) {\n result[key] = value.map((item) => item instanceof Date ? item.toISOString() : item);\n } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result[key] = coerceDatesToStrings(value as Record<string, unknown>);\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport matter from 'gray-matter';\nimport { parseNoteFrontmatter, type VaultNote } from './types.js';\n\nconst VAULT_SUBDIRS = ['sessions', 'plans', 'memories', 'artifacts', 'team'];\n\nexport class VaultReader {\n constructor(private vaultDir: string) {}\n\n readNote(relativePath: string): VaultNote {\n const fullPath = path.join(this.vaultDir, relativePath);\n const raw = fs.readFileSync(fullPath, 'utf-8');\n const { data, content } = matter(raw);\n const frontmatter = parseNoteFrontmatter(data as Record<string, unknown>);\n return { path: relativePath, frontmatter, content: content.trim() };\n }\n\n listNotes(subdir: string): VaultNote[] {\n const dirPath = path.join(this.vaultDir, subdir);\n if (!fs.existsSync(dirPath)) return [];\n\n const files = this.walkMarkdownFiles(dirPath);\n return files.map((filePath) => {\n const relativePath = path.relative(this.vaultDir, filePath);\n return this.readNote(relativePath);\n });\n }\n\n readAllNotes(): VaultNote[] {\n return VAULT_SUBDIRS.flatMap((subdir) => this.listNotes(subdir));\n }\n\n walkMarkdownFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n\n const results: string[] = [];\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...this.walkMarkdownFiles(fullPath));\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n results.push(fullPath);\n }\n }\n\n return results;\n }\n}\n","import { VaultReader } from '../vault/reader.js';\nimport type { MycoIndex } from './sqlite.js';\nimport type { VaultNote } from '../vault/types.js';\n\nexport function indexNote(index: MycoIndex, vaultDir: string, relativePath: string): void {\n const reader = new VaultReader(vaultDir);\n const note = reader.readNote(relativePath);\n indexVaultNote(index, note);\n}\n\nfunction indexVaultNote(index: MycoIndex, note: VaultNote): void {\n const fm = note.frontmatter;\n const title = extractTitle(note.content) || ('id' in fm ? String(fm.id) : note.path);\n const created = 'started' in fm ? fm.started\n : 'created' in fm ? fm.created\n : 'joined' in fm ? fm.joined\n : new Date().toISOString();\n\n index.upsertNote({\n path: note.path,\n type: fm.type,\n id: 'id' in fm ? String(fm.id) : 'user' in fm ? String(fm.user) : note.path,\n title,\n content: note.content,\n frontmatter: fm as Record<string, unknown>,\n created: String(created),\n });\n}\n\nexport function rebuildIndex(index: MycoIndex, vaultDir: string): number {\n const db = index.getDb();\n db.exec('DELETE FROM notes');\n\n const reader = new VaultReader(vaultDir);\n const notes = reader.readAllNotes();\n let count = 0;\n\n for (const note of notes) {\n indexVaultNote(index, note);\n count++;\n }\n\n return count;\n}\n\nfunction extractTitle(content: string): string {\n const match = content.match(/^#\\s+(.+)$/m);\n return match ? match[1].trim() : '';\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nexport interface LogEntry {\n timestamp: string;\n level: string;\n component: string;\n message: string;\n [key: string]: unknown;\n}\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport const LEVEL_ORDER: Record<LogLevel, number> = {\n debug: 0, info: 1, warn: 2, error: 3,\n};\n\ninterface LoggerOptions {\n level?: LogLevel;\n maxSize?: number;\n maxFiles?: number;\n}\n\nexport class DaemonLogger {\n private logPath: string;\n private fd: number | null = null;\n private currentSize = 0;\n private level: LogLevel;\n private maxSize: number;\n private maxFiles: number;\n private logDir: string;\n\n constructor(logDir: string, options: LoggerOptions = {}) {\n this.logDir = logDir;\n this.logPath = path.join(logDir, 'daemon.log');\n this.level = options.level ?? 'info';\n this.maxSize = options.maxSize ?? 5_242_880;\n this.maxFiles = options.maxFiles ?? 3;\n\n fs.mkdirSync(logDir, { recursive: true });\n this.fd = fs.openSync(this.logPath, 'a');\n try {\n this.currentSize = fs.fstatSync(this.fd).size;\n } catch {\n this.currentSize = 0;\n }\n }\n\n debug(component: string, message: string, data?: Record<string, unknown>): void {\n this.write('debug', component, message, data);\n }\n\n info(component: string, message: string, data?: Record<string, unknown>): void {\n this.write('info', component, message, data);\n }\n\n warn(component: string, message: string, data?: Record<string, unknown>): void {\n this.write('warn', component, message, data);\n }\n\n error(component: string, message: string, data?: Record<string, unknown>): void {\n this.write('error', component, message, data);\n }\n\n close(): void {\n if (this.fd !== null) {\n fs.closeSync(this.fd);\n this.fd = null;\n }\n }\n\n private write(level: LogLevel, component: string, message: string, data?: Record<string, unknown>): void {\n if (LEVEL_ORDER[level] < LEVEL_ORDER[this.level]) return;\n\n const entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n component,\n message,\n ...data,\n };\n\n const line = JSON.stringify(entry) + '\\n';\n const bytes = Buffer.byteLength(line);\n\n if (this.currentSize + bytes > this.maxSize) {\n this.rotate();\n }\n\n if (this.fd !== null) {\n fs.writeSync(this.fd, line);\n this.currentSize += bytes;\n }\n }\n\n private rotate(): void {\n this.close();\n\n for (let i = this.maxFiles - 1; i >= 1; i--) {\n const from = path.join(this.logDir, `daemon.${i}.log`);\n const to = path.join(this.logDir, `daemon.${i + 1}.log`);\n if (fs.existsSync(from)) {\n if (i + 1 > this.maxFiles) {\n fs.unlinkSync(from);\n } else {\n fs.renameSync(from, to);\n }\n }\n }\n\n if (fs.existsSync(this.logPath)) {\n fs.renameSync(this.logPath, path.join(this.logDir, 'daemon.1.log'));\n }\n\n this.fd = fs.openSync(this.logPath, 'a');\n this.currentSize = 0;\n }\n}\n","import type { LlmProvider, EmbeddingProvider, LlmResponse, EmbeddingResponse, LlmRequestOptions } from './llm.js';\nimport { CHARS_PER_TOKEN, LLM_REQUEST_TIMEOUT_MS, EMBEDDING_REQUEST_TIMEOUT_MS, DAEMON_CLIENT_TIMEOUT_MS } from '../constants.js';\n\ninterface OllamaConfig {\n model?: string;\n base_url?: string;\n context_window?: number;\n max_tokens?: number;\n // Legacy fields (ignored, kept for backward compat during migration)\n embedding_model?: string;\n summary_model?: string;\n}\n\nexport class OllamaBackend implements LlmProvider, EmbeddingProvider {\n readonly name = 'ollama';\n private baseUrl: string;\n private model: string;\n private contextWindow: number;\n private defaultMaxTokens: number;\n\n constructor(config?: OllamaConfig) {\n this.baseUrl = config?.base_url ?? 'http://localhost:11434';\n this.model = config?.model ?? config?.summary_model ?? 'llama3.2';\n this.contextWindow = config?.context_window ?? 8192;\n this.defaultMaxTokens = config?.max_tokens ?? 1024;\n }\n\n async summarize(prompt: string, opts?: LlmRequestOptions): Promise<LlmResponse> {\n const maxTokens = opts?.maxTokens ?? this.defaultMaxTokens;\n const promptTokens = Math.ceil(prompt.length / CHARS_PER_TOKEN);\n const numCtx = Math.max(promptTokens + maxTokens, this.contextWindow);\n\n const response = await fetch(`${this.baseUrl}/api/generate`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n prompt,\n stream: false,\n options: { num_ctx: numCtx },\n }),\n signal: AbortSignal.timeout(LLM_REQUEST_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`Ollama summarize failed: ${response.status} ${response.statusText}`);\n }\n\n const data = await response.json() as { response: string; model: string };\n return { text: data.response, model: data.model };\n }\n\n async embed(text: string): Promise<EmbeddingResponse> {\n const response = await fetch(`${this.baseUrl}/api/embed`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n input: text,\n }),\n signal: AbortSignal.timeout(EMBEDDING_REQUEST_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`Ollama embed failed: ${response.status} ${response.statusText}`);\n }\n\n const data = await response.json() as { embeddings: number[][]; model: string };\n const embedding = data.embeddings[0];\n return { embedding, model: data.model, dimensions: embedding.length };\n }\n\n async isAvailable(): Promise<boolean> {\n try {\n const response = await fetch(`${this.baseUrl}/api/tags`, {\n signal: AbortSignal.timeout(DAEMON_CLIENT_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","import type { LlmProvider, EmbeddingProvider, LlmResponse, EmbeddingResponse, LlmRequestOptions } from './llm.js';\nimport { LLM_REQUEST_TIMEOUT_MS, EMBEDDING_REQUEST_TIMEOUT_MS, DAEMON_CLIENT_TIMEOUT_MS } from '../constants.js';\n\ninterface LmStudioConfig {\n model?: string;\n base_url?: string;\n max_tokens?: number;\n // Legacy fields\n embedding_model?: string;\n summary_model?: string;\n}\n\nexport class LmStudioBackend implements LlmProvider, EmbeddingProvider {\n readonly name = 'lm-studio';\n private baseUrl: string;\n private model: string;\n private defaultMaxTokens: number;\n\n constructor(config?: LmStudioConfig) {\n this.baseUrl = config?.base_url ?? 'http://localhost:1234';\n this.model = config?.model ?? config?.summary_model ?? 'llama3.2';\n this.defaultMaxTokens = config?.max_tokens ?? 1024;\n }\n\n async summarize(prompt: string, opts?: LlmRequestOptions): Promise<LlmResponse> {\n const maxTokens = opts?.maxTokens ?? this.defaultMaxTokens;\n\n const response = await fetch(`${this.baseUrl}/v1/chat/completions`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n messages: [{ role: 'user', content: prompt }],\n max_tokens: maxTokens,\n }),\n signal: AbortSignal.timeout(LLM_REQUEST_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`LM Studio summarize failed: ${response.status}`);\n }\n\n const data = await response.json() as {\n choices: Array<{ message: { content: string } }>;\n model: string;\n };\n return { text: data.choices[0].message.content, model: data.model };\n }\n\n async embed(text: string): Promise<EmbeddingResponse> {\n const response = await fetch(`${this.baseUrl}/v1/embeddings`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n input: text,\n }),\n signal: AbortSignal.timeout(EMBEDDING_REQUEST_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`LM Studio embed failed: ${response.status}`);\n }\n\n const data = await response.json() as {\n data: Array<{ embedding: number[] }>;\n model: string;\n };\n const embedding = data.data[0].embedding;\n return { embedding, model: data.model, dimensions: embedding.length };\n }\n\n async isAvailable(): Promise<boolean> {\n try {\n const response = await fetch(`${this.baseUrl}/v1/models`, {\n signal: AbortSignal.timeout(DAEMON_CLIENT_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","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\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","// 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';\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 constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) {\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 }\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\n if (status === 400) {\n return new BadRequestError(status, error, message, headers);\n }\n\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers);\n }\n\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers);\n }\n\n if (status === 404) {\n return new NotFoundError(status, error, message, headers);\n }\n\n if (status === 409) {\n return new ConflictError(status, error, message, headers);\n }\n\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers);\n }\n\n if (status === 429) {\n return new RateLimitError(status, error, message, headers);\n }\n\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers);\n }\n\n return new APIError(status, error, message, headers);\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\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","// 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\nexport const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n","export const VERSION = '0.78.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 { HTTPMethod, MergedRequestInit } from './types';\nimport { type HeadersLike } from './headers';\n\nexport type FinalRequestOptions = RequestOptions & { method: HTTPMethod; path: string };\n\nexport type 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 * 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","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 { 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","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { hasOwn } from './values';\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\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 client: BaseAnthropic,\n): LogLevel | undefined => {\n if (!maybeLevel) {\n return undefined;\n }\n if (hasOwn(levelNumbers, maybeLevel)) {\n return maybeLevel;\n }\n loggerFor(client).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\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\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 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() === 'x-api-key' ||\n name.toLowerCase() === 'authorization' ||\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","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';\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 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 ) {\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 throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers);\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 if (props.options.__streamClass) {\n return props.options.__streamClass.fromSSEResponse(response, props.controller) as any;\n }\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","// 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 has_more: boolean;\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 has_more: boolean;\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.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: 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(headers: HeadersLike): IterableIterator<readonly [string, string | null]> {\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 a null to clear the header before adding the new values.\n if (shouldClear && !didClear) {\n didClear = true;\n yield [name, null];\n }\n yield [name, value];\n }\n }\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 (!seenHeaders.has(lowerName)) {\n targetHeaders.delete(name);\n seenHeaders.add(lowerName);\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","/**\n * Shared utilities for tracking SDK helper usage.\n */\n\nimport type { BetaMessageParam, BetaToolUnion } from '../resources/beta';\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: BetaToolUnion[] | undefined,\n messages: BetaMessageParam[] | 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 if (Array.isArray(message.content)) {\n for (const block of message.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: BetaToolUnion[] | undefined,\n messages: BetaMessageParam[] | undefined,\n): { 'x-stainless-helper'?: string } {\n const helpers = collectStainlessHelpers(tools, messages);\n if (helpers.length === 0) return {};\n return { 'x-stainless-helper': 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 { 'x-stainless-helper': file[SDK_HELPER_SYMBOL] };\n }\n return {};\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 { 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 '../../lib/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', 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}`, {\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`, {\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}`, {\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',\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 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\nexport interface FileListParams 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 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 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\nexport interface BetaModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\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 * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\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 BetaModelInfo as BetaModelInfo,\n type BetaModelInfosPage as BetaModelInfosPage,\n type ModelRetrieveParams as ModelRetrieveParams,\n type ModelListParams as ModelListParams,\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 ((char && NUMBERS.test(char)) || char === '.') {\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 (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {\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';\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';\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\nconst JSON_BUF_PROPERTY = '__json_buf';\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, 'X-Stainless-Helper-Method': '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) && content.input) {\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 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 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 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 // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = (snapshotContent as any)[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n\n const newContent = { ...snapshotContent };\n Object.defineProperty(newContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n\n if (jsonBuf) {\n try {\n newContent.input = partialParse(jsonBuf);\n } catch (err) {\n const error = 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 this.#handleError(error);\n }\n }\n snapshot.content[event.index] = newContent;\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 };\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n return snapshot;\n }\n case 'content_block_stop':\n return snapshot;\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 { 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","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\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 { CompactionControl, DEFAULT_SUMMARY_PROMPT, DEFAULT_TOKEN_THRESHOLD } from './CompactionControl';\nimport { collectStainlessHelpers } from '../stainless-helper-header';\n\n/**\n * Just Promise.withResolvers(), which is not available in all environments.\n */\nfunction promiseWithResolvers<T>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (reason?: any) => void;\n} {\n let resolve: (value: T) => void;\n let reject: (reason?: any) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve: resolve!, reject: reject! };\n}\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 const helpers = collectStainlessHelpers(params.tools, params.messages);\n const helperValue = ['BetaToolRunner', ...helpers].join(', ');\n\n this.#options = {\n ...options,\n headers: buildHeaders([{ 'x-stainless-helper': helperValue }, options?.headers]),\n };\n this.#completion = promiseWithResolvers();\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 headers: { 'x-stainless-helper': '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 { role, content } = await this.#message;\n this.#state.params.messages.push({ role, content });\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 * 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() {\n const message = (await this.#message) ?? this.params.messages.at(-1);\n if (!message) {\n return null;\n }\n return this.#generateToolResponse(message);\n }\n\n async #generateToolResponse(lastMessage: BetaMessageParam) {\n if (this.#toolResponse !== undefined) {\n return this.#toolResponse;\n }\n this.#toolResponse = generateToolResponse(this.#state.params, lastMessage);\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): 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 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 compactionControl?: CompactionControl;\n }\n>;\n\nexport type BetaToolRunnerRequestOptions = Pick<RequestOptions, 'headers'>;\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, ...body } = params;\n return this._client.post('/v1/messages/batches?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\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\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 * 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\\nSee\n * [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 * 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 * Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\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 * Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\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 generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { AnthropicError } from '../../../error';\nimport { Anthropic } from '../../../client';\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 '../../../lib/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 MessagesAPI from '../../messages/messages';\nimport * as BetaAPI from '../beta';\nimport * as BatchesAPI from './batches';\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';\nimport * as MessagesMessagesAPI from './messages';\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};\n\nconst MODELS_TO_WARN_WITH_THINKING_ENABLED: Model[] = ['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, ...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 body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED &&\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 { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\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: 'string', 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\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`.\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 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 cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n file_id: string | null;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface BetaCitationContentBlockLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\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 cited_text: string;\n\n end_block_index: number;\n\n search_result_index: number;\n\n source: string;\n\n start_block_index: number;\n\n title: string | null;\n\n type: 'search_result_location';\n}\n\nexport interface BetaCitationSearchResultLocationParam {\n cited_text: string;\n\n end_block_index: number;\n\n search_result_index: number;\n\n source: string;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 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 /**\n * Summary of previously compacted content, or null if compaction failed\n */\n content: string | null;\n\n type: 'compaction';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaCompactionContentBlockDelta {\n 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 | BetaCodeExecutionToolResultBlock\n | BetaBashCodeExecutionToolResultBlock\n | BetaTextEditorCodeExecutionToolResultBlock\n | BetaToolSearchToolResultBlock\n | BetaMCPToolUseBlock\n | BetaMCPToolResultBlock\n | BetaContainerUploadBlock\n | BetaCompactionBlock;\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 | BetaCodeExecutionToolResultBlockParam\n | BetaBashCodeExecutionToolResultBlockParam\n | BetaTextEditorCodeExecutionToolResultBlockParam\n | BetaToolSearchToolResultBlockParam\n | BetaMCPToolUseBlockParam\n | BetaRequestMCPToolResultBlockParam\n | BetaContainerUploadBlockParam\n | BetaCompactionBlockParam;\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 * 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\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<BetaMessageIterationUsage | BetaCompactionIterationUsage>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 * The model that will complete your prompt.\\n\\nSee\n * [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 * 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 * 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 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';\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\nexport interface BetaOutputConfig {\n /**\n * All possible effort levels.\n */\n effort?: 'low' | 'medium' | 'high' | '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\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 | BetaCodeExecutionToolResultBlock\n | BetaBashCodeExecutionToolResultBlock\n | BetaTextEditorCodeExecutionToolResultBlock\n | BetaToolSearchToolResultBlock\n | BetaMCPToolUseBlock\n | BetaMCPToolResultBlock\n | BetaContainerUploadBlock\n | BetaCompactionBlock;\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: MessagesMessagesAPI.BetaContainer | null;\n\n stop_reason: MessagesMessagesAPI.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\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 | '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 | '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\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/**\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 thinking: string;\n\n type: 'thinking_delta';\n}\n\nexport interface BetaThinkingTurns {\n type: 'thinking_turns';\n\n value: number;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 | BetaToolComputerUse20241022\n | BetaMemoryTool20250818\n | BetaToolComputerUse20250124\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20251124\n | BetaToolTextEditor20250124\n | BetaToolTextEditor20250429\n | BetaToolTextEditor20250728\n | BetaWebSearchTool20250305\n | BetaWebFetchTool20250910\n | BetaWebSearchTool20260209\n | BetaWebFetchTool20260209\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 * 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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 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_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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 * 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\\nSee\n * [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: 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 * Body param: Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\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 * Body param: Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Body param: Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\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 MessageCreateParams {\n export type MessageCreateParamsNonStreaming = MessagesMessagesAPI.MessageCreateParamsNonStreaming;\n export type MessageCreateParamsStreaming = MessagesMessagesAPI.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\\nSee\n * [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 | BetaToolComputerUse20241022\n | BetaMemoryTool20250818\n | BetaToolComputerUse20250124\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20251124\n | BetaToolTextEditor20250124\n | BetaToolTextEditor20250429\n | BetaToolTextEditor20250728\n | BetaWebSearchTool20250305\n | BetaWebFetchTool20250910\n | BetaWebSearchTool20260209\n | BetaWebFetchTool20260209\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 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 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 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 BetaDirectCaller as BetaDirectCaller,\n type BetaDocumentBlock as BetaDocumentBlock,\n type BetaEncryptedCodeExecutionResultBlock as BetaEncryptedCodeExecutionResultBlock,\n type BetaEncryptedCodeExecutionResultBlockParam as BetaEncryptedCodeExecutionResultBlockParam,\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 BetaOutputConfig as BetaOutputConfig,\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 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 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 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 { 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 ),\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\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 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 };\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 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 };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport * as FilesAPI from './files';\nimport {\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 { BetaModelInfo, BetaModelInfosPage, ModelListParams, ModelRetrieveParams, Models } from './models';\nimport * as MessagesAPI from './messages/messages';\nimport {\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 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 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 BetaDirectCaller,\n BetaDocumentBlock,\n BetaEncryptedCodeExecutionResultBlock,\n BetaEncryptedCodeExecutionResultBlockParam,\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 BetaOutputConfig,\n BetaPlainTextSource,\n BetaRawContentBlockDelta,\n BetaRawContentBlockDeltaEvent,\n BetaRawContentBlockStartEvent,\n BetaRawContentBlockStopEvent,\n BetaRawMessageDeltaEvent,\n BetaRawMessageStartEvent,\n BetaRawMessageStopEvent,\n BetaRawMessageStreamEvent,\n BetaRedactedThinkingBlock,\n BetaRedactedThinkingBlockParam,\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 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 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 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';\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 files: FilesAPI.Files = new FilesAPI.Files(this._client);\n skills: SkillsAPI.Skills = new SkillsAPI.Skills(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\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.Files = Files;\nBeta.Skills = Skills;\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 BetaModelInfo as BetaModelInfo,\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 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 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 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 BetaDirectCaller as BetaDirectCaller,\n type BetaDocumentBlock as BetaDocumentBlock,\n type BetaEncryptedCodeExecutionResultBlock as BetaEncryptedCodeExecutionResultBlock,\n type BetaEncryptedCodeExecutionResultBlockParam as BetaEncryptedCodeExecutionResultBlockParam,\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 BetaOutputConfig as BetaOutputConfig,\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 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 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 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 Files as Files,\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","// 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-opus-4-6',\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\\nSee\n * [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\\nSee\n * [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 * Body param: Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\n */\n temperature?: number;\n\n /**\n * Body param: Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Body param: Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\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 { 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 { partialParse } from '../_vendor/partial-json-parser/parser';\nimport { RequestOptions } from '../internal/request-options';\nimport type { Logger } from '../client';\nimport { maybeParseMessage, type ParsedMessage } from './parser';\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\nconst JSON_BUF_PROPERTY = '__json_buf';\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, 'X-Stainless-Helper-Method': '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) && content.input) {\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 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 // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = (snapshotContent as any)[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n\n const newContent = { ...snapshotContent };\n Object.defineProperty(newContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n\n if (jsonBuf) {\n newContent.input = partialParse(jsonBuf);\n }\n snapshot.content[event.index] = newContent;\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 return snapshot;\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(body: BatchCreateParams, options?: RequestOptions): APIPromise<MessageBatch> {\n return this._client.post('/v1/messages/batches', { body, ...options });\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 * List of requests for prompt completion. Each is an individual request to create\n * a Message.\n */\n requests: Array<BatchCreateParams.Request>;\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 '../../lib/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(body: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Message>;\n create(\n body: MessageCreateParamsStreaming,\n options?: RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent>>;\n create(\n body: MessageCreateParamsBase,\n options?: RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent> | Message>;\n create(\n body: MessageCreateParams,\n options?: RequestOptions,\n ): APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>> {\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 body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED &&\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', {\n body,\n timeout: timeout ?? 600000,\n ...options,\n headers: buildHeaders([helperHeader, options?.headers]),\n stream: body.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: 'string', 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`.\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 cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n file_id: string | null;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface CitationContentBlockLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\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 cited_text: string;\n\n end_block_index: number;\n\n search_result_index: number;\n\n source: string;\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 cited_text: string;\n\n end_block_index: number;\n\n search_result_index: number;\n\n source: string;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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\\nSee\n * [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 * 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 | MemoryTool20250818\n | ToolTextEditor20250124\n | ToolTextEditor20250429\n | ToolTextEditor20250728\n | WebSearchTool20250305\n | WebFetchTool20250910\n | WebSearchTool20260209\n | WebFetchTool20260209\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 * 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';\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 * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\nexport type Model =\n | 'claude-opus-4-6'\n | 'claude-sonnet-4-6'\n | 'claude-opus-4-5-20251101'\n | 'claude-opus-4-5'\n | 'claude-3-7-sonnet-latest'\n | 'claude-3-7-sonnet-20250219'\n | 'claude-3-5-haiku-latest'\n | 'claude-3-5-haiku-20241022'\n | 'claude-haiku-4-5'\n | 'claude-haiku-4-5-20251001'\n | 'claude-sonnet-4-20250514'\n | 'claude-sonnet-4-0'\n | 'claude-4-sonnet-20250514'\n | 'claude-sonnet-4-5'\n | 'claude-sonnet-4-5-20250929'\n | 'claude-opus-4-0'\n | 'claude-opus-4-20250514'\n | 'claude-4-opus-20250514'\n | 'claude-opus-4-1-20250805'\n | 'claude-3-opus-latest'\n | 'claude-3-opus-20240229'\n | 'claude-3-haiku-20240307'\n | (string & {});\n\nexport interface OutputConfig {\n /**\n * All possible effort levels.\n */\n effort?: 'low' | 'medium' | 'high' | '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\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};\n\nconst MODELS_TO_WARN_WITH_THINKING_ENABLED: Model[] = ['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 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\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\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/**\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 | MemoryTool20250818\n | ToolTextEditor20250124\n | ToolTextEditor20250429\n | ToolTextEditor20250728\n | WebSearchTool20250305\n | WebFetchTool20250910\n | WebSearchTool20260209\n | WebFetchTool20260209\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 * 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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 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_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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 * 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 * 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<MessageParam>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [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 * Container identifier for reuse across requests.\n */\n container?: string | 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 * An object describing metadata about the request.\n */\n metadata?: Metadata;\n\n /**\n * Configuration options for the model's output, such as the output format.\n */\n output_config?: OutputConfig;\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 * 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<TextBlockParam>;\n\n /**\n * Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\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?: 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<ToolUnion>;\n\n /**\n * Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_p?: number;\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 * 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?: false;\n}\n\nexport interface MessageCreateParamsStreaming extends MessageCreateParamsBase {\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: 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\\nSee\n * [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 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 Model as Model,\n type OutputConfig as OutputConfig,\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 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 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\nexport interface ModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\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 * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\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 ModelInfo as ModelInfo,\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\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();\n }\n return undefined;\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 { VERSION } from './version';\nimport * as Errors from './core/error';\nimport * as Pagination from './core/pagination';\nimport {\n type PageParams,\n PageResponse,\n type PageCursorParams,\n PageCursorResponse,\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 { ModelInfo, ModelInfosPage, ModelListParams, ModelRetrieveParams, Models } 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 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 Model,\n OutputConfig,\n PlainTextSource,\n RawContentBlockDelta,\n RawContentBlockDeltaEvent,\n RawContentBlockStartEvent,\n RawContentBlockStopEvent,\n RawMessageDeltaEvent,\n RawMessageStartEvent,\n RawMessageStopEvent,\n RawMessageStreamEvent,\n RedactedThinkingBlock,\n RedactedThinkingBlockParam,\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 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 formatRequestDetails,\n loggerFor,\n parseLogLevel,\n} from './internal/utils/log';\nimport { isEmptyObj } from './internal/utils/values';\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 * 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 * 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\n baseURL: string;\n maxRetries: number;\n timeout: number;\n logger: Logger;\n logLevel: LogLevel | undefined;\n fetchOptions: MergedRequestInit | undefined;\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} [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 = readEnv('ANTHROPIC_API_KEY') ?? null,\n authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null,\n ...opts\n }: ClientOptions = {}) {\n const options: ClientOptions = {\n apiKey,\n authToken,\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 this.timeout = options.timeout ?? BaseAnthropic.DEFAULT_TIMEOUT /* 10 minutes */;\n this.logger = options.logger ?? console;\n const defaultLogLevel = 'warn';\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', this) ??\n parseLogLevel(readEnv('ANTHROPIC_LOG'), \"process.env['ANTHROPIC_LOG']\", 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._options = options;\n\n this.apiKey = typeof apiKey === 'string' ? apiKey : null;\n this.authToken = authToken;\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 const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({\n ...this._options,\n 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 apiKey: this.apiKey,\n authToken: this.authToken,\n ...options,\n });\n return client;\n }\n\n /**\n * Check whether the base URL is set to its default.\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\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 either apiKey or authToken to be set. Or for one of the \"X-Api-Key\" or \"Authorization\" headers to be explicitly omitted',\n );\n }\n\n protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {\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 /**\n * Basic re-implementation of `qs.stringify` for primitive types.\n */\n protected stringifyQuery(query: Record<string, unknown>): string {\n return Object.entries(query)\n .filter(([_, value]) => typeof value !== 'undefined')\n .map(([key, value]) => {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n }\n if (value === null) {\n return `${encodeURIComponent(key)}=`;\n }\n throw new Errors.AnthropicError(\n `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`,\n );\n })\n .join('&');\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 if (!isEmptyObj(defaultQuery)) {\n query = { ...defaultQuery, ...query };\n }\n\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query as Record<string, unknown>);\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 protected async prepareRequest(\n request: RequestInit,\n { url, options }: { url: string; options: FinalRequestOptions },\n ): Promise<void> {}\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 }\n\n await this.prepareOptions(options);\n\n const { req, url, timeout } = await this.buildRequest(options, {\n retryCount: maxRetries - retriesRemaining,\n });\n\n await this.prepareRequest(req, { url, options });\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 loggerFor(this).debug(\n `[${requestLogID}] sending request`,\n formatRequestDetails({\n retryOfRequestLogID,\n method: options.method,\n url,\n options,\n headers: req.headers,\n }),\n );\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).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 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 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);\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 ): 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 timeout = setTimeout(abort, ms);\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 try {\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n return await this.fetch.call(undefined, url, fetchOptions);\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private async shouldRetry(response: Response): Promise<boolean> {\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 (and it's a reasonable amount),\n // just do what it says, but otherwise calculate a default\n if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\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 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 as Record<string, unknown>),\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\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 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 Model as Model,\n type OutputConfig as OutputConfig,\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 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 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 ModelInfo as ModelInfo,\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 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 Anthropic from '@anthropic-ai/sdk';\nimport type { LlmProvider, LlmResponse, EmbeddingResponse, LlmRequestOptions } from './llm.js';\nimport { LLM_REQUEST_TIMEOUT_MS } from '../constants.js';\n\ninterface AnthropicConfig {\n model?: string;\n // Legacy fields\n summary_model?: string;\n embedding_provider?: string;\n}\n\nexport class AnthropicBackend implements LlmProvider {\n readonly name = 'anthropic';\n private client: Anthropic;\n private model: string;\n\n constructor(config?: AnthropicConfig) {\n this.client = new Anthropic();\n this.model = config?.model ?? config?.summary_model ?? 'claude-haiku-4-5-20251001';\n }\n\n async summarize(prompt: string, opts?: LlmRequestOptions): Promise<LlmResponse> {\n const maxTokens = opts?.maxTokens ?? 1024;\n\n const response = await this.client.messages.create({\n model: this.model,\n max_tokens: maxTokens,\n messages: [{ role: 'user', content: prompt }],\n }, { timeout: LLM_REQUEST_TIMEOUT_MS });\n\n const text = response.content\n .filter((block): block is Anthropic.TextBlock => block.type === 'text')\n .map((block) => block.text)\n .join('');\n\n return { text, model: this.model };\n }\n\n async embed(_text: string): Promise<EmbeddingResponse> {\n throw new Error(\n 'AnthropicBackend does not support embeddings. Use a local provider (Ollama or LM Studio) for embeddings.'\n );\n }\n\n async isAvailable(): Promise<boolean> {\n try {\n return !!process.env.ANTHROPIC_API_KEY;\n } catch {\n return false;\n }\n }\n}\n","import { OllamaBackend } from './ollama.js';\nimport { LmStudioBackend } from './lm-studio.js';\nimport { AnthropicBackend } from './anthropic.js';\n\nexport interface LlmRequestOptions {\n maxTokens?: number;\n}\n\nexport interface LlmResponse {\n text: string;\n model: string;\n}\n\nexport interface EmbeddingResponse {\n embedding: number[];\n model: string;\n dimensions: number;\n}\n\nexport interface LlmProvider {\n name: string;\n summarize(prompt: string, opts?: LlmRequestOptions): Promise<LlmResponse>;\n isAvailable(): Promise<boolean>;\n}\n\nexport interface EmbeddingProvider {\n name: string;\n embed(text: string): Promise<EmbeddingResponse>;\n isAvailable(): Promise<boolean>;\n}\n\ninterface ProviderConfig {\n provider: string;\n model: string;\n base_url?: string;\n context_window?: number;\n max_tokens?: number;\n}\n\nexport function createLlmProvider(config: ProviderConfig): LlmProvider {\n switch (config.provider) {\n case 'ollama':\n return new OllamaBackend(config);\n case 'lm-studio':\n return new LmStudioBackend(config);\n case 'anthropic':\n return new AnthropicBackend(config);\n default:\n throw new Error(`Unknown LLM provider: ${config.provider}`);\n }\n}\n\nexport function createEmbeddingProvider(config: ProviderConfig): EmbeddingProvider {\n switch (config.provider) {\n case 'ollama':\n return new OllamaBackend(config);\n case 'lm-studio':\n return new LmStudioBackend(config);\n default:\n throw new Error(`Provider \"${config.provider}\" does not support embeddings. Use ollama or lm-studio.`);\n }\n}\n","import Database from 'better-sqlite3';\nimport * as sqliteVec from 'sqlite-vec';\n\nexport interface VectorSearchResult {\n id: string;\n similarity: number;\n metadata: Record<string, string>;\n}\n\nexport interface VectorSearchOptions {\n limit?: number;\n /** Drop results below this fraction of the top result's score (0-1). Default 0.5. */\n relativeThreshold?: number;\n type?: string;\n importance?: string;\n}\n\nexport class VectorIndex {\n private db: Database.Database;\n private dimensions: number;\n\n constructor(dbPath: string, dimensions: number) {\n this.dimensions = dimensions;\n this.db = new Database(dbPath);\n sqliteVec.load(this.db);\n this.init();\n }\n\n private init(): void {\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS vec_metadata (\n id TEXT PRIMARY KEY,\n type TEXT NOT NULL DEFAULT '',\n importance TEXT NOT NULL DEFAULT '',\n session_id TEXT NOT NULL DEFAULT '',\n file_path TEXT NOT NULL DEFAULT '',\n branch TEXT NOT NULL DEFAULT '',\n created TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE VIRTUAL TABLE IF NOT EXISTS vec_embeddings USING vec0(\n id TEXT PRIMARY KEY,\n embedding float[${this.dimensions}]\n );\n `);\n }\n\n upsert(id: string, embedding: number[], metadata: Record<string, string> = {}): void {\n this.db.prepare('DELETE FROM vec_metadata WHERE id = ?').run(id);\n this.db.prepare('DELETE FROM vec_embeddings WHERE id = ?').run(id);\n\n this.db.prepare(\n 'INSERT INTO vec_metadata (id, type, importance, session_id, file_path, branch) VALUES (?, ?, ?, ?, ?, ?)',\n ).run(id, metadata.type ?? '', metadata.importance ?? '', metadata.session_id ?? '', metadata.file_path ?? '', metadata.branch ?? '');\n\n this.db.prepare('INSERT INTO vec_embeddings (id, embedding) VALUES (?, ?)').run(id, new Float32Array(embedding));\n }\n\n search(query: number[], options: VectorSearchOptions = {}): VectorSearchResult[] {\n const limit = options.limit ?? 10;\n\n // vec0 KNN queries require LIMIT to be a direct constraint on the virtual table.\n // JOINs with additional WHERE filters confuse the query planner, so we use a\n // subquery to get KNN candidates first, then filter by metadata in the outer query.\n const knnParams: unknown[] = [new Float32Array(query), limit * 4];\n const knnRows = this.db.prepare(`\n SELECT id, distance\n FROM vec_embeddings\n WHERE embedding MATCH ?\n ORDER BY distance\n LIMIT ?\n `).all(...knnParams) as Array<{ id: string; distance: number }>;\n\n if (knnRows.length === 0) return [];\n\n // Now fetch metadata for the candidates and apply optional filters\n const metaConditions: string[] = ['id IN (' + knnRows.map(() => '?').join(',') + ')'];\n const metaParams: unknown[] = knnRows.map((r) => r.id);\n\n if (options.type) { metaConditions.push('type = ?'); metaParams.push(options.type); }\n if (options.importance) { metaConditions.push('importance = ?'); metaParams.push(options.importance); }\n\n const metaRows = this.db.prepare(`\n SELECT id, type, importance, session_id, file_path, branch\n FROM vec_metadata\n WHERE ${metaConditions.join(' AND ')}\n `).all(...metaParams) as Array<{ id: string; type: string; importance: string; session_id: string; file_path: string; branch: string }>;\n\n const metaMap = new Map(metaRows.map((m) => [m.id, m]));\n\n const scored = knnRows\n .filter((r) => metaMap.has(r.id))\n .map((r) => {\n const m = metaMap.get(r.id)!;\n return {\n id: r.id,\n similarity: 1 - r.distance,\n metadata: { type: m.type, importance: m.importance, session_id: m.session_id, file_path: m.file_path, branch: m.branch },\n };\n });\n\n if (scored.length === 0) return [];\n\n // Relative threshold: drop results below a fraction of the best score.\n // Adapts automatically to any embedding model's score distribution.\n const topScore = scored[0].similarity;\n const threshold = options.relativeThreshold ?? 0.5;\n const floor = topScore * threshold;\n\n return scored\n .filter((r) => r.similarity >= floor)\n .slice(0, limit);\n }\n\n delete(id: string): void {\n this.db.prepare('DELETE FROM vec_metadata WHERE id = ?').run(id);\n this.db.prepare('DELETE FROM vec_embeddings WHERE id = ?').run(id);\n }\n\n count(): number {\n return (this.db.prepare('SELECT COUNT(*) as c FROM vec_metadata').get() as { c: number }).c;\n }\n\n close(): void { this.db.close(); }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAAA,kCAAAA,UAAAC,SAAA;AAAA;AAAA,QAAI,WAAW,OAAO,UAAU;AAEhC,IAAAA,QAAO,UAAU,SAAS,OAAO,KAAK;AACpC,UAAI,QAAQ,OAAQ,QAAO;AAC3B,UAAI,QAAQ,KAAM,QAAO;AAEzB,UAAI,OAAO,OAAO;AAClB,UAAI,SAAS,UAAW,QAAO;AAC/B,UAA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SAAS,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;AAEtD,UAAM,SAAS,QACZ,OAAO,CAAC,MAAM,QAAQ,IAAI,EAAE,EAAE,CAAC,EAC/B,IAAI,CAAC,MAAM;AACV,YAAM,IAAI,QAAQ,IAAI,EAAE,EAAE;AAC1B,aAAO;AAAA,QACL,IAAI,EAAE;AAAA,QACN,YAAY,IAAI,EAAE;AAAA,QAClB,UAAU,EAAE,MAAM,EAAE,MAAM,YAAY,EAAE,YAAY,YAAY,EAAE,YAAY,WAAW,EAAE,WAAW,QAAQ,EAAE,OAAO;AAAA,MACzH;AAAA,IACF,CAAC;AAEH,QAAI,OAAO,WAAW,EAAG,QAAO,CAAC;AAIjC,UAAM,WAAW,OAAO,CAAC,EAAE;AAC3B,UAAM,YAAYA,SAAQ,qBAAqB;AAC/C,UAAM,QAAQ,WAAW;AAEzB,WAAO,OACJ,OAAO,CAAC,MAAM,EAAE,cAAc,KAAK,EACnC,MAAM,GAAG,KAAK;AAAA,EACnB;AAAA,EAEA,OAAO,IAAkB;AACvB,SAAK,GAAG,QAAQ,uCAAuC,EAAE,IAAI,EAAE;AAC/D,SAAK,GAAG,QAAQ,yCAAyC,EAAE,IAAI,EAAE;AAAA,EACnE;AAAA,EAEA,QAAgB;AACd,WAAQ,KAAK,GAAG,QAAQ,wCAAwC,EAAE,IAAI,EAAoB;AAAA,EAC5F;AAAA,EAEA,QAAc;AAAE,SAAK,GAAG,MAAM;AAAA,EAAG;AACnC;","names":["exports","module","isArray","exports","module","exports","module","hasOwn","exports","module","options","exports","module","exports","module","exports","module","exports","module","options","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","options","load","exports","module","options","str","string","exports","module","require_js_yaml","exports","module","yaml","options","exports","module","str","exports","str","exports","module","engines","options","exports","module","options","exports","module","options","str","matter","exports","module","options","exports","module","options","exports","module","str","options","exports","module","fs","engines","toFile","parse","matter","options","str","options","matter","fs","path","options","str","str","options","Page","client","options","process","options","fetch","options","options","str","path","options","path","options","path","options","_BetaMessageStream_getFinalMessage","_BetaMessageStream_getFinalText","_BetaMessageStream_beginRequest","_BetaMessageStream_addStreamEvent","_BetaMessageStream_endRequest","_BetaMessageStream_accumulateMessage","chunk","options","_BetaToolRunner_checkAndCompact","_a","_BetaToolRunner_generateToolResponse","options","path","options","options","path","options","path","options","getOutputFormat","JSON_BUF_PROPERTY","tracksToolInput","options","_MessageStream_getFinalMessage","_MessageStream_getFinalText","_MessageStream_beginRequest","_MessageStream_addStreamEvent","checkNever","_MessageStream_endRequest","_MessageStream_accumulateMessage","chunk","Batches","options","path","Messages","Batches","options","DEPRECATED_MODELS","MODELS_TO_WARN_WITH_THINKING_ENABLED","Models","options","path","options","path","opts","retryMessage","err","Page","Messages","Models","options"]}
|
|
1
|
+
{"version":3,"sources":["../node_modules/kind-of/index.js","../node_modules/is-extendable/index.js","../node_modules/extend-shallow/index.js","../node_modules/section-matter/index.js","../node_modules/js-yaml/lib/js-yaml/common.js","../node_modules/js-yaml/lib/js-yaml/exception.js","../node_modules/js-yaml/lib/js-yaml/mark.js","../node_modules/js-yaml/lib/js-yaml/type.js","../node_modules/js-yaml/lib/js-yaml/schema.js","../node_modules/js-yaml/lib/js-yaml/type/str.js","../node_modules/js-yaml/lib/js-yaml/type/seq.js","../node_modules/js-yaml/lib/js-yaml/type/map.js","../node_modules/js-yaml/lib/js-yaml/schema/failsafe.js","../node_modules/js-yaml/lib/js-yaml/type/null.js","../node_modules/js-yaml/lib/js-yaml/type/bool.js","../node_modules/js-yaml/lib/js-yaml/type/int.js","../node_modules/js-yaml/lib/js-yaml/type/float.js","../node_modules/js-yaml/lib/js-yaml/schema/json.js","../node_modules/js-yaml/lib/js-yaml/schema/core.js","../node_modules/js-yaml/lib/js-yaml/type/timestamp.js","../node_modules/js-yaml/lib/js-yaml/type/merge.js","../node_modules/js-yaml/lib/js-yaml/type/binary.js","../node_modules/js-yaml/lib/js-yaml/type/omap.js","../node_modules/js-yaml/lib/js-yaml/type/pairs.js","../node_modules/js-yaml/lib/js-yaml/type/set.js","../node_modules/js-yaml/lib/js-yaml/schema/default_safe.js","../node_modules/js-yaml/lib/js-yaml/type/js/undefined.js","../node_modules/js-yaml/lib/js-yaml/type/js/regexp.js","../node_modules/js-yaml/lib/js-yaml/type/js/function.js","../node_modules/js-yaml/lib/js-yaml/schema/default_full.js","../node_modules/js-yaml/lib/js-yaml/loader.js","../node_modules/js-yaml/lib/js-yaml/dumper.js","../node_modules/js-yaml/lib/js-yaml.js","../node_modules/js-yaml/index.js","../node_modules/gray-matter/lib/engines.js","../node_modules/strip-bom-string/index.js","../node_modules/gray-matter/lib/utils.js","../node_modules/gray-matter/lib/defaults.js","../node_modules/gray-matter/lib/engine.js","../node_modules/gray-matter/lib/stringify.js","../node_modules/gray-matter/lib/excerpt.js","../node_modules/gray-matter/lib/to-file.js","../node_modules/gray-matter/lib/parse.js","../node_modules/gray-matter/index.js","../src/index/fts.ts","../src/intelligence/embeddings.ts","../src/vault/types.ts","../src/vault/reader.ts","../src/index/rebuild.ts","../src/daemon/logger.ts","../src/intelligence/ollama.ts","../src/intelligence/lm-studio.ts","../node_modules/@anthropic-ai/sdk/internal/tslib.mjs","../node_modules/@anthropic-ai/sdk/src/internal/utils/uuid.ts","../node_modules/@anthropic-ai/sdk/src/internal/errors.ts","../node_modules/@anthropic-ai/sdk/src/core/error.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/values.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/utils/bytes.ts","../node_modules/@anthropic-ai/sdk/src/internal/decoders/line.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/log.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/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/lib/stainless-helper-header.ts","../node_modules/@anthropic-ai/sdk/src/internal/utils/path.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/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/lib/BetaMessageStream.ts","../node_modules/@anthropic-ai/sdk/src/lib/tools/ToolError.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/internal/decoders/jsonl.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/messages/batches.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/messages/messages.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/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/internal/utils/env.ts","../node_modules/@anthropic-ai/sdk/src/client.ts","../src/intelligence/anthropic.ts","../src/intelligence/llm.ts","../src/index/vectors.ts"],"sourcesContent":["var toString = Object.prototype.toString;\n\nmodule.exports = function kindOf(val) {\n if (val === void 0) return 'undefined';\n if (val === null) return 'null';\n\n var type = typeof val;\n if (type === 'boolean') return 'boolean';\n if (type === 'string') return 'string';\n if (type === 'number') return 'number';\n if (type === 'symbol') return 'symbol';\n if (type === 'function') {\n return isGeneratorFn(val) ? 'generatorfunction' : 'function';\n }\n\n if (isArray(val)) return 'array';\n if (isBuffer(val)) return 'buffer';\n if (isArguments(val)) return 'arguments';\n if (isDate(val)) return 'date';\n if (isError(val)) return 'error';\n if (isRegexp(val)) return 'regexp';\n\n switch (ctorName(val)) {\n case 'Symbol': return 'symbol';\n case 'Promise': return 'promise';\n\n // Set, Map, WeakSet, WeakMap\n case 'WeakMap': return 'weakmap';\n case 'WeakSet': return 'weakset';\n case 'Map': return 'map';\n case 'Set': return 'set';\n\n // 8-bit typed arrays\n case 'Int8Array': return 'int8array';\n case 'Uint8Array': return 'uint8array';\n case 'Uint8ClampedArray': return 'uint8clampedarray';\n\n // 16-bit typed arrays\n case 'Int16Array': return 'int16array';\n case 'Uint16Array': return 'uint16array';\n\n // 32-bit typed arrays\n case 'Int32Array': return 'int32array';\n case 'Uint32Array': return 'uint32array';\n case 'Float32Array': return 'float32array';\n case 'Float64Array': return 'float64array';\n }\n\n if (isGeneratorObj(val)) {\n return 'generator';\n }\n\n // Non-plain objects\n type = toString.call(val);\n switch (type) {\n case '[object Object]': return 'object';\n // iterators\n case '[object Map Iterator]': return 'mapiterator';\n case '[object Set Iterator]': return 'setiterator';\n case '[object String Iterator]': return 'stringiterator';\n case '[object Array Iterator]': return 'arrayiterator';\n }\n\n // other\n return type.slice(8, -1).toLowerCase().replace(/\\s/g, '');\n};\n\nfunction ctorName(val) {\n return typeof val.constructor === 'function' ? val.constructor.name : null;\n}\n\nfunction isArray(val) {\n if (Array.isArray) return Array.isArray(val);\n return val instanceof Array;\n}\n\nfunction isError(val) {\n return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number');\n}\n\nfunction isDate(val) {\n if (val instanceof Date) return true;\n return typeof val.toDateString === 'function'\n && typeof val.getDate === 'function'\n && typeof val.setDate === 'function';\n}\n\nfunction isRegexp(val) {\n if (val instanceof RegExp) return true;\n return typeof val.flags === 'string'\n && typeof val.ignoreCase === 'boolean'\n && typeof val.multiline === 'boolean'\n && typeof val.global === 'boolean';\n}\n\nfunction isGeneratorFn(name, val) {\n return ctorName(name) === 'GeneratorFunction';\n}\n\nfunction isGeneratorObj(val) {\n return typeof val.throw === 'function'\n && typeof val.return === 'function'\n && typeof val.next === 'function';\n}\n\nfunction isArguments(val) {\n try {\n if (typeof val.length === 'number' && typeof val.callee === 'function') {\n return true;\n }\n } catch (err) {\n if (err.message.indexOf('callee') !== -1) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * If you need to support Safari 5-7 (8-10 yr-old browser),\n * take a look at https://github.com/feross/is-buffer\n */\n\nfunction isBuffer(val) {\n if (val.constructor && typeof val.constructor.isBuffer === 'function') {\n return val.constructor.isBuffer(val);\n }\n return false;\n}\n","/*!\n * is-extendable <https://github.com/jonschlinkert/is-extendable>\n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function isExtendable(val) {\n return typeof val !== 'undefined' && val !== null\n && (typeof val === 'object' || typeof val === 'function');\n};\n","'use strict';\n\nvar isObject = require('is-extendable');\n\nmodule.exports = function extend(o/*, objects*/) {\n if (!isObject(o)) { o = {}; }\n\n var len = arguments.length;\n for (var i = 1; i < len; i++) {\n var obj = arguments[i];\n\n if (isObject(obj)) {\n assign(o, obj);\n }\n }\n return o;\n};\n\nfunction assign(a, b) {\n for (var key in b) {\n if (hasOwn(b, key)) {\n a[key] = b[key];\n }\n }\n}\n\n/**\n * Returns true if the given `key` is an own property of `obj`.\n */\n\nfunction hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n","'use strict';\n\nvar typeOf = require('kind-of');\nvar extend = require('extend-shallow');\n\n/**\n * Parse sections in `input` with the given `options`.\n *\n * ```js\n * var sections = require('{%= name %}');\n * var result = sections(input, options);\n * // { content: 'Content before sections', sections: [] }\n * ```\n * @param {String|Buffer|Object} `input` If input is an object, it's `content` property must be a string or buffer.\n * @param {Object} options\n * @return {Object} Returns an object with a `content` string and an array of `sections` objects.\n * @api public\n */\n\nmodule.exports = function(input, options) {\n if (typeof options === 'function') {\n options = { parse: options };\n }\n\n var file = toObject(input);\n var defaults = {section_delimiter: '---', parse: identity};\n var opts = extend({}, defaults, options);\n var delim = opts.section_delimiter;\n var lines = file.content.split(/\\r?\\n/);\n var sections = null;\n var section = createSection();\n var content = [];\n var stack = [];\n\n function initSections(val) {\n file.content = val;\n sections = [];\n content = [];\n }\n\n function closeSection(val) {\n if (stack.length) {\n section.key = getKey(stack[0], delim);\n section.content = val;\n opts.parse(section, sections);\n sections.push(section);\n section = createSection();\n content = [];\n stack = [];\n }\n }\n\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n var len = stack.length;\n var ln = line.trim();\n\n if (isDelimiter(ln, delim)) {\n if (ln.length === 3 && i !== 0) {\n if (len === 0 || len === 2) {\n content.push(line);\n continue;\n }\n stack.push(ln);\n section.data = content.join('\\n');\n content = [];\n continue;\n }\n\n if (sections === null) {\n initSections(content.join('\\n'));\n }\n\n if (len === 2) {\n closeSection(content.join('\\n'));\n }\n\n stack.push(ln);\n continue;\n }\n\n content.push(line);\n }\n\n if (sections === null) {\n initSections(content.join('\\n'));\n } else {\n closeSection(content.join('\\n'));\n }\n\n file.sections = sections;\n return file;\n};\n\nfunction isDelimiter(line, delim) {\n if (line.slice(0, delim.length) !== delim) {\n return false;\n }\n if (line.charAt(delim.length + 1) === delim.slice(-1)) {\n return false;\n }\n return true;\n}\n\nfunction toObject(input) {\n if (typeOf(input) !== 'object') {\n input = { content: input };\n }\n\n if (typeof input.content !== 'string' && !isBuffer(input.content)) {\n throw new TypeError('expected a buffer or string');\n }\n\n input.content = input.content.toString();\n input.sections = [];\n return input;\n}\n\nfunction getKey(val, delim) {\n return val ? val.slice(delim.length).trim() : '';\n}\n\nfunction createSection() {\n return { key: '', data: '', content: '' };\n}\n\nfunction identity(val) {\n return val;\n}\n\nfunction isBuffer(val) {\n if (val && val.constructor && typeof val.constructor.isBuffer === 'function') {\n return val.constructor.isBuffer(val);\n }\n return false;\n}\n","'use strict';\n\n\nfunction isNothing(subject) {\n return (typeof subject === 'undefined') || (subject === null);\n}\n\n\nfunction isObject(subject) {\n return (typeof subject === 'object') && (subject !== null);\n}\n\n\nfunction toArray(sequence) {\n if (Array.isArray(sequence)) return sequence;\n else if (isNothing(sequence)) return [];\n\n return [ sequence ];\n}\n\n\nfunction extend(target, source) {\n var index, length, key, sourceKeys;\n\n if (source) {\n sourceKeys = Object.keys(source);\n\n for (index = 0, length = sourceKeys.length; index < length; index += 1) {\n key = sourceKeys[index];\n target[key] = source[key];\n }\n }\n\n return target;\n}\n\n\nfunction repeat(string, count) {\n var result = '', cycle;\n\n for (cycle = 0; cycle < count; cycle += 1) {\n result += string;\n }\n\n return result;\n}\n\n\nfunction isNegativeZero(number) {\n return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);\n}\n\n\nmodule.exports.isNothing = isNothing;\nmodule.exports.isObject = isObject;\nmodule.exports.toArray = toArray;\nmodule.exports.repeat = repeat;\nmodule.exports.isNegativeZero = isNegativeZero;\nmodule.exports.extend = extend;\n","// YAML error class. http://stackoverflow.com/questions/8458984\n//\n'use strict';\n\nfunction YAMLException(reason, mark) {\n // Super constructor\n Error.call(this);\n\n this.name = 'YAMLException';\n this.reason = reason;\n this.mark = mark;\n this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');\n\n // Include stack trace in error object\n if (Error.captureStackTrace) {\n // Chrome and NodeJS\n Error.captureStackTrace(this, this.constructor);\n } else {\n // FF, IE 10+ and Safari 6+. Fallback for others\n this.stack = (new Error()).stack || '';\n }\n}\n\n\n// Inherit from Error\nYAMLException.prototype = Object.create(Error.prototype);\nYAMLException.prototype.constructor = YAMLException;\n\n\nYAMLException.prototype.toString = function toString(compact) {\n var result = this.name + ': ';\n\n result += this.reason || '(unknown reason)';\n\n if (!compact && this.mark) {\n result += ' ' + this.mark.toString();\n }\n\n return result;\n};\n\n\nmodule.exports = YAMLException;\n","'use strict';\n\n\nvar common = require('./common');\n\n\nfunction Mark(name, buffer, position, line, column) {\n this.name = name;\n this.buffer = buffer;\n this.position = position;\n this.line = line;\n this.column = column;\n}\n\n\nMark.prototype.getSnippet = function getSnippet(indent, maxLength) {\n var head, start, tail, end, snippet;\n\n if (!this.buffer) return null;\n\n indent = indent || 4;\n maxLength = maxLength || 75;\n\n head = '';\n start = this.position;\n\n while (start > 0 && '\\x00\\r\\n\\x85\\u2028\\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {\n start -= 1;\n if (this.position - start > (maxLength / 2 - 1)) {\n head = ' ... ';\n start += 5;\n break;\n }\n }\n\n tail = '';\n end = this.position;\n\n while (end < this.buffer.length && '\\x00\\r\\n\\x85\\u2028\\u2029'.indexOf(this.buffer.charAt(end)) === -1) {\n end += 1;\n if (end - this.position > (maxLength / 2 - 1)) {\n tail = ' ... ';\n end -= 5;\n break;\n }\n }\n\n snippet = this.buffer.slice(start, end);\n\n return common.repeat(' ', indent) + head + snippet + tail + '\\n' +\n common.repeat(' ', indent + this.position - start + head.length) + '^';\n};\n\n\nMark.prototype.toString = function toString(compact) {\n var snippet, where = '';\n\n if (this.name) {\n where += 'in \"' + this.name + '\" ';\n }\n\n where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);\n\n if (!compact) {\n snippet = this.getSnippet();\n\n if (snippet) {\n where += ':\\n' + snippet;\n }\n }\n\n return where;\n};\n\n\nmodule.exports = Mark;\n","'use strict';\n\nvar YAMLException = require('./exception');\n\nvar TYPE_CONSTRUCTOR_OPTIONS = [\n 'kind',\n 'resolve',\n 'construct',\n 'instanceOf',\n 'predicate',\n 'represent',\n 'defaultStyle',\n 'styleAliases'\n];\n\nvar YAML_NODE_KINDS = [\n 'scalar',\n 'sequence',\n 'mapping'\n];\n\nfunction compileStyleAliases(map) {\n var result = {};\n\n if (map !== null) {\n Object.keys(map).forEach(function (style) {\n map[style].forEach(function (alias) {\n result[String(alias)] = style;\n });\n });\n }\n\n return result;\n}\n\nfunction Type(tag, options) {\n options = options || {};\n\n Object.keys(options).forEach(function (name) {\n if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {\n throw new YAMLException('Unknown option \"' + name + '\" is met in definition of \"' + tag + '\" YAML type.');\n }\n });\n\n // TODO: Add tag format check.\n this.tag = tag;\n this.kind = options['kind'] || null;\n this.resolve = options['resolve'] || function () { return true; };\n this.construct = options['construct'] || function (data) { return data; };\n this.instanceOf = options['instanceOf'] || null;\n this.predicate = options['predicate'] || null;\n this.represent = options['represent'] || null;\n this.defaultStyle = options['defaultStyle'] || null;\n this.styleAliases = compileStyleAliases(options['styleAliases'] || null);\n\n if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n throw new YAMLException('Unknown kind \"' + this.kind + '\" is specified for \"' + tag + '\" YAML type.');\n }\n}\n\nmodule.exports = Type;\n","'use strict';\n\n/*eslint-disable max-len*/\n\nvar common = require('./common');\nvar YAMLException = require('./exception');\nvar Type = require('./type');\n\n\nfunction compileList(schema, name, result) {\n var exclude = [];\n\n schema.include.forEach(function (includedSchema) {\n result = compileList(includedSchema, name, result);\n });\n\n schema[name].forEach(function (currentType) {\n result.forEach(function (previousType, previousIndex) {\n if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {\n exclude.push(previousIndex);\n }\n });\n\n result.push(currentType);\n });\n\n return result.filter(function (type, index) {\n return exclude.indexOf(index) === -1;\n });\n}\n\n\nfunction compileMap(/* lists... */) {\n var result = {\n scalar: {},\n sequence: {},\n mapping: {},\n fallback: {}\n }, index, length;\n\n function collectType(type) {\n result[type.kind][type.tag] = result['fallback'][type.tag] = type;\n }\n\n for (index = 0, length = arguments.length; index < length; index += 1) {\n arguments[index].forEach(collectType);\n }\n return result;\n}\n\n\nfunction Schema(definition) {\n this.include = definition.include || [];\n this.implicit = definition.implicit || [];\n this.explicit = definition.explicit || [];\n\n this.implicit.forEach(function (type) {\n if (type.loadKind && type.loadKind !== 'scalar') {\n throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');\n }\n });\n\n this.compiledImplicit = compileList(this, 'implicit', []);\n this.compiledExplicit = compileList(this, 'explicit', []);\n this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);\n}\n\n\nSchema.DEFAULT = null;\n\n\nSchema.create = function createSchema() {\n var schemas, types;\n\n switch (arguments.length) {\n case 1:\n schemas = Schema.DEFAULT;\n types = arguments[0];\n break;\n\n case 2:\n schemas = arguments[0];\n types = arguments[1];\n break;\n\n default:\n throw new YAMLException('Wrong number of arguments for Schema.create function');\n }\n\n schemas = common.toArray(schemas);\n types = common.toArray(types);\n\n if (!schemas.every(function (schema) { return schema instanceof Schema; })) {\n throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');\n }\n\n if (!types.every(function (type) { return type instanceof Type; })) {\n throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');\n }\n\n return new Schema({\n include: schemas,\n explicit: types\n });\n};\n\n\nmodule.exports = Schema;\n","'use strict';\n\nvar Type = require('../type');\n\nmodule.exports = new Type('tag:yaml.org,2002:str', {\n kind: 'scalar',\n construct: function (data) { return data !== null ? data : ''; }\n});\n","'use strict';\n\nvar Type = require('../type');\n\nmodule.exports = new Type('tag:yaml.org,2002:seq', {\n kind: 'sequence',\n construct: function (data) { return data !== null ? data : []; }\n});\n","'use strict';\n\nvar Type = require('../type');\n\nmodule.exports = new Type('tag:yaml.org,2002:map', {\n kind: 'mapping',\n construct: function (data) { return data !== null ? data : {}; }\n});\n","// Standard YAML's Failsafe schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2802346\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n explicit: [\n require('../type/str'),\n require('../type/seq'),\n require('../type/map')\n ]\n});\n","'use strict';\n\nvar Type = require('../type');\n\nfunction resolveYamlNull(data) {\n if (data === null) return true;\n\n var max = data.length;\n\n return (max === 1 && data === '~') ||\n (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));\n}\n\nfunction constructYamlNull() {\n return null;\n}\n\nfunction isNull(object) {\n return object === null;\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:null', {\n kind: 'scalar',\n resolve: resolveYamlNull,\n construct: constructYamlNull,\n predicate: isNull,\n represent: {\n canonical: function () { return '~'; },\n lowercase: function () { return 'null'; },\n uppercase: function () { return 'NULL'; },\n camelcase: function () { return 'Null'; }\n },\n defaultStyle: 'lowercase'\n});\n","'use strict';\n\nvar Type = require('../type');\n\nfunction resolveYamlBoolean(data) {\n if (data === null) return false;\n\n var max = data.length;\n\n return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||\n (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));\n}\n\nfunction constructYamlBoolean(data) {\n return data === 'true' ||\n data === 'True' ||\n data === 'TRUE';\n}\n\nfunction isBoolean(object) {\n return Object.prototype.toString.call(object) === '[object Boolean]';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:bool', {\n kind: 'scalar',\n resolve: resolveYamlBoolean,\n construct: constructYamlBoolean,\n predicate: isBoolean,\n represent: {\n lowercase: function (object) { return object ? 'true' : 'false'; },\n uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },\n camelcase: function (object) { return object ? 'True' : 'False'; }\n },\n defaultStyle: 'lowercase'\n});\n","'use strict';\n\nvar common = require('../common');\nvar Type = require('../type');\n\nfunction isHexCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||\n ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||\n ((0x61/* a */ <= c) && (c <= 0x66/* f */));\n}\n\nfunction isOctCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));\n}\n\nfunction isDecCode(c) {\n return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));\n}\n\nfunction resolveYamlInteger(data) {\n if (data === null) return false;\n\n var max = data.length,\n index = 0,\n hasDigits = false,\n ch;\n\n if (!max) return false;\n\n ch = data[index];\n\n // sign\n if (ch === '-' || ch === '+') {\n ch = data[++index];\n }\n\n if (ch === '0') {\n // 0\n if (index + 1 === max) return true;\n ch = data[++index];\n\n // base 2, base 8, base 16\n\n if (ch === 'b') {\n // base 2\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (ch !== '0' && ch !== '1') return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n\n if (ch === 'x') {\n // base 16\n index++;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isHexCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n // base 8\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (!isOctCode(data.charCodeAt(index))) return false;\n hasDigits = true;\n }\n return hasDigits && ch !== '_';\n }\n\n // base 10 (except 0) or base 60\n\n // value should not start with `_`;\n if (ch === '_') return false;\n\n for (; index < max; index++) {\n ch = data[index];\n if (ch === '_') continue;\n if (ch === ':') break;\n if (!isDecCode(data.charCodeAt(index))) {\n return false;\n }\n hasDigits = true;\n }\n\n // Should have digits and should not end with `_`\n if (!hasDigits || ch === '_') return false;\n\n // if !base60 - done;\n if (ch !== ':') return true;\n\n // base60 almost not used, no needs to optimize\n return /^(:[0-5]?[0-9])+$/.test(data.slice(index));\n}\n\nfunction constructYamlInteger(data) {\n var value = data, sign = 1, ch, base, digits = [];\n\n if (value.indexOf('_') !== -1) {\n value = value.replace(/_/g, '');\n }\n\n ch = value[0];\n\n if (ch === '-' || ch === '+') {\n if (ch === '-') sign = -1;\n value = value.slice(1);\n ch = value[0];\n }\n\n if (value === '0') return 0;\n\n if (ch === '0') {\n if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);\n if (value[1] === 'x') return sign * parseInt(value, 16);\n return sign * parseInt(value, 8);\n }\n\n if (value.indexOf(':') !== -1) {\n value.split(':').forEach(function (v) {\n digits.unshift(parseInt(v, 10));\n });\n\n value = 0;\n base = 1;\n\n digits.forEach(function (d) {\n value += (d * base);\n base *= 60;\n });\n\n return sign * value;\n\n }\n\n return sign * parseInt(value, 10);\n}\n\nfunction isInteger(object) {\n return (Object.prototype.toString.call(object)) === '[object Number]' &&\n (object % 1 === 0 && !common.isNegativeZero(object));\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:int', {\n kind: 'scalar',\n resolve: resolveYamlInteger,\n construct: constructYamlInteger,\n predicate: isInteger,\n represent: {\n binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },\n octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },\n decimal: function (obj) { return obj.toString(10); },\n /* eslint-disable max-len */\n hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }\n },\n defaultStyle: 'decimal',\n styleAliases: {\n binary: [ 2, 'bin' ],\n octal: [ 8, 'oct' ],\n decimal: [ 10, 'dec' ],\n hexadecimal: [ 16, 'hex' ]\n }\n});\n","'use strict';\n\nvar common = require('../common');\nvar Type = require('../type');\n\nvar YAML_FLOAT_PATTERN = new RegExp(\n // 2.5e4, 2.5 and integers\n '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +\n // .2e4, .2\n // special case, seems not from spec\n '|\\\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +\n // 20:59\n '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]*' +\n // .inf\n '|[-+]?\\\\.(?:inf|Inf|INF)' +\n // .nan\n '|\\\\.(?:nan|NaN|NAN))$');\n\nfunction resolveYamlFloat(data) {\n if (data === null) return false;\n\n if (!YAML_FLOAT_PATTERN.test(data) ||\n // Quick hack to not allow integers end with `_`\n // Probably should update regexp & check speed\n data[data.length - 1] === '_') {\n return false;\n }\n\n return true;\n}\n\nfunction constructYamlFloat(data) {\n var value, sign, base, digits;\n\n value = data.replace(/_/g, '').toLowerCase();\n sign = value[0] === '-' ? -1 : 1;\n digits = [];\n\n if ('+-'.indexOf(value[0]) >= 0) {\n value = value.slice(1);\n }\n\n if (value === '.inf') {\n return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;\n\n } else if (value === '.nan') {\n return NaN;\n\n } else if (value.indexOf(':') >= 0) {\n value.split(':').forEach(function (v) {\n digits.unshift(parseFloat(v, 10));\n });\n\n value = 0.0;\n base = 1;\n\n digits.forEach(function (d) {\n value += d * base;\n base *= 60;\n });\n\n return sign * value;\n\n }\n return sign * parseFloat(value, 10);\n}\n\n\nvar SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;\n\nfunction representYamlFloat(object, style) {\n var res;\n\n if (isNaN(object)) {\n switch (style) {\n case 'lowercase': return '.nan';\n case 'uppercase': return '.NAN';\n case 'camelcase': return '.NaN';\n }\n } else if (Number.POSITIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '.inf';\n case 'uppercase': return '.INF';\n case 'camelcase': return '.Inf';\n }\n } else if (Number.NEGATIVE_INFINITY === object) {\n switch (style) {\n case 'lowercase': return '-.inf';\n case 'uppercase': return '-.INF';\n case 'camelcase': return '-.Inf';\n }\n } else if (common.isNegativeZero(object)) {\n return '-0.0';\n }\n\n res = object.toString(10);\n\n // JS stringifier can build scientific format without dots: 5e-100,\n // while YAML requres dot: 5.e-100. Fix it with simple hack\n\n return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;\n}\n\nfunction isFloat(object) {\n return (Object.prototype.toString.call(object) === '[object Number]') &&\n (object % 1 !== 0 || common.isNegativeZero(object));\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:float', {\n kind: 'scalar',\n resolve: resolveYamlFloat,\n construct: constructYamlFloat,\n predicate: isFloat,\n represent: representYamlFloat,\n defaultStyle: 'lowercase'\n});\n","// Standard YAML's JSON schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2803231\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, this schema is not such strict as defined in the YAML specification.\n// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n include: [\n require('./failsafe')\n ],\n implicit: [\n require('../type/null'),\n require('../type/bool'),\n require('../type/int'),\n require('../type/float')\n ]\n});\n","// Standard YAML's Core schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2804923\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, Core schema has no distinctions from JSON schema is JS-YAML.\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n include: [\n require('./json')\n ]\n});\n","'use strict';\n\nvar Type = require('../type');\n\nvar YAML_DATE_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9])' + // [2] month\n '-([0-9][0-9])$'); // [3] day\n\nvar YAML_TIMESTAMP_REGEXP = new RegExp(\n '^([0-9][0-9][0-9][0-9])' + // [1] year\n '-([0-9][0-9]?)' + // [2] month\n '-([0-9][0-9]?)' + // [3] day\n '(?:[Tt]|[ \\\\t]+)' + // ...\n '([0-9][0-9]?)' + // [4] hour\n ':([0-9][0-9])' + // [5] minute\n ':([0-9][0-9])' + // [6] second\n '(?:\\\\.([0-9]*))?' + // [7] fraction\n '(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour\n '(?::([0-9][0-9]))?))?$'); // [11] tz_minute\n\nfunction resolveYamlTimestamp(data) {\n if (data === null) return false;\n if (YAML_DATE_REGEXP.exec(data) !== null) return true;\n if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;\n return false;\n}\n\nfunction constructYamlTimestamp(data) {\n var match, year, month, day, hour, minute, second, fraction = 0,\n delta = null, tz_hour, tz_minute, date;\n\n match = YAML_DATE_REGEXP.exec(data);\n if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);\n\n if (match === null) throw new Error('Date resolve error');\n\n // match: [1] year [2] month [3] day\n\n year = +(match[1]);\n month = +(match[2]) - 1; // JS month starts with 0\n day = +(match[3]);\n\n if (!match[4]) { // no hour\n return new Date(Date.UTC(year, month, day));\n }\n\n // match: [4] hour [5] minute [6] second [7] fraction\n\n hour = +(match[4]);\n minute = +(match[5]);\n second = +(match[6]);\n\n if (match[7]) {\n fraction = match[7].slice(0, 3);\n while (fraction.length < 3) { // milli-seconds\n fraction += '0';\n }\n fraction = +fraction;\n }\n\n // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute\n\n if (match[9]) {\n tz_hour = +(match[10]);\n tz_minute = +(match[11] || 0);\n delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds\n if (match[9] === '-') delta = -delta;\n }\n\n date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));\n\n if (delta) date.setTime(date.getTime() - delta);\n\n return date;\n}\n\nfunction representYamlTimestamp(object /*, style*/) {\n return object.toISOString();\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:timestamp', {\n kind: 'scalar',\n resolve: resolveYamlTimestamp,\n construct: constructYamlTimestamp,\n instanceOf: Date,\n represent: representYamlTimestamp\n});\n","'use strict';\n\nvar Type = require('../type');\n\nfunction resolveYamlMerge(data) {\n return data === '<<' || data === null;\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:merge', {\n kind: 'scalar',\n resolve: resolveYamlMerge\n});\n","'use strict';\n\n/*eslint-disable no-bitwise*/\n\nvar NodeBuffer;\n\ntry {\n // A trick for browserified version, to not include `Buffer` shim\n var _require = require;\n NodeBuffer = _require('buffer').Buffer;\n} catch (__) {}\n\nvar Type = require('../type');\n\n\n// [ 64, 65, 66 ] -> [ padding, CR, LF ]\nvar BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r';\n\n\nfunction resolveYamlBinary(data) {\n if (data === null) return false;\n\n var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;\n\n // Convert one by one.\n for (idx = 0; idx < max; idx++) {\n code = map.indexOf(data.charAt(idx));\n\n // Skip CR/LF\n if (code > 64) continue;\n\n // Fail on illegal characters\n if (code < 0) return false;\n\n bitlen += 6;\n }\n\n // If there are any bits left, source was corrupted\n return (bitlen % 8) === 0;\n}\n\nfunction constructYamlBinary(data) {\n var idx, tailbits,\n input = data.replace(/[\\r\\n=]/g, ''), // remove CR/LF & padding to simplify scan\n max = input.length,\n map = BASE64_MAP,\n bits = 0,\n result = [];\n\n // Collect by 6*4 bits (3 bytes)\n\n for (idx = 0; idx < max; idx++) {\n if ((idx % 4 === 0) && idx) {\n result.push((bits >> 16) & 0xFF);\n result.push((bits >> 8) & 0xFF);\n result.push(bits & 0xFF);\n }\n\n bits = (bits << 6) | map.indexOf(input.charAt(idx));\n }\n\n // Dump tail\n\n tailbits = (max % 4) * 6;\n\n if (tailbits === 0) {\n result.push((bits >> 16) & 0xFF);\n result.push((bits >> 8) & 0xFF);\n result.push(bits & 0xFF);\n } else if (tailbits === 18) {\n result.push((bits >> 10) & 0xFF);\n result.push((bits >> 2) & 0xFF);\n } else if (tailbits === 12) {\n result.push((bits >> 4) & 0xFF);\n }\n\n // Wrap into Buffer for NodeJS and leave Array for browser\n if (NodeBuffer) {\n // Support node 6.+ Buffer API when available\n return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);\n }\n\n return result;\n}\n\nfunction representYamlBinary(object /*, style*/) {\n var result = '', bits = 0, idx, tail,\n max = object.length,\n map = BASE64_MAP;\n\n // Convert every three bytes to 4 ASCII characters.\n\n for (idx = 0; idx < max; idx++) {\n if ((idx % 3 === 0) && idx) {\n result += map[(bits >> 18) & 0x3F];\n result += map[(bits >> 12) & 0x3F];\n result += map[(bits >> 6) & 0x3F];\n result += map[bits & 0x3F];\n }\n\n bits = (bits << 8) + object[idx];\n }\n\n // Dump tail\n\n tail = max % 3;\n\n if (tail === 0) {\n result += map[(bits >> 18) & 0x3F];\n result += map[(bits >> 12) & 0x3F];\n result += map[(bits >> 6) & 0x3F];\n result += map[bits & 0x3F];\n } else if (tail === 2) {\n result += map[(bits >> 10) & 0x3F];\n result += map[(bits >> 4) & 0x3F];\n result += map[(bits << 2) & 0x3F];\n result += map[64];\n } else if (tail === 1) {\n result += map[(bits >> 2) & 0x3F];\n result += map[(bits << 4) & 0x3F];\n result += map[64];\n result += map[64];\n }\n\n return result;\n}\n\nfunction isBinary(object) {\n return NodeBuffer && NodeBuffer.isBuffer(object);\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:binary', {\n kind: 'scalar',\n resolve: resolveYamlBinary,\n construct: constructYamlBinary,\n predicate: isBinary,\n represent: representYamlBinary\n});\n","'use strict';\n\nvar Type = require('../type');\n\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\nvar _toString = Object.prototype.toString;\n\nfunction resolveYamlOmap(data) {\n if (data === null) return true;\n\n var objectKeys = [], index, length, pair, pairKey, pairHasKey,\n object = data;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n pairHasKey = false;\n\n if (_toString.call(pair) !== '[object Object]') return false;\n\n for (pairKey in pair) {\n if (_hasOwnProperty.call(pair, pairKey)) {\n if (!pairHasKey) pairHasKey = true;\n else return false;\n }\n }\n\n if (!pairHasKey) return false;\n\n if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);\n else return false;\n }\n\n return true;\n}\n\nfunction constructYamlOmap(data) {\n return data !== null ? data : [];\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:omap', {\n kind: 'sequence',\n resolve: resolveYamlOmap,\n construct: constructYamlOmap\n});\n","'use strict';\n\nvar Type = require('../type');\n\nvar _toString = Object.prototype.toString;\n\nfunction resolveYamlPairs(data) {\n if (data === null) return true;\n\n var index, length, pair, keys, result,\n object = data;\n\n result = new Array(object.length);\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n\n if (_toString.call(pair) !== '[object Object]') return false;\n\n keys = Object.keys(pair);\n\n if (keys.length !== 1) return false;\n\n result[index] = [ keys[0], pair[keys[0]] ];\n }\n\n return true;\n}\n\nfunction constructYamlPairs(data) {\n if (data === null) return [];\n\n var index, length, pair, keys, result,\n object = data;\n\n result = new Array(object.length);\n\n for (index = 0, length = object.length; index < length; index += 1) {\n pair = object[index];\n\n keys = Object.keys(pair);\n\n result[index] = [ keys[0], pair[keys[0]] ];\n }\n\n return result;\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:pairs', {\n kind: 'sequence',\n resolve: resolveYamlPairs,\n construct: constructYamlPairs\n});\n","'use strict';\n\nvar Type = require('../type');\n\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction resolveYamlSet(data) {\n if (data === null) return true;\n\n var key, object = data;\n\n for (key in object) {\n if (_hasOwnProperty.call(object, key)) {\n if (object[key] !== null) return false;\n }\n }\n\n return true;\n}\n\nfunction constructYamlSet(data) {\n return data !== null ? data : {};\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:set', {\n kind: 'mapping',\n resolve: resolveYamlSet,\n construct: constructYamlSet\n});\n","// JS-YAML's default schema for `safeLoad` function.\n// It is not described in the YAML specification.\n//\n// This schema is based on standard YAML's Core schema and includes most of\n// extra types described at YAML tag repository. (http://yaml.org/type/)\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n include: [\n require('./core')\n ],\n implicit: [\n require('../type/timestamp'),\n require('../type/merge')\n ],\n explicit: [\n require('../type/binary'),\n require('../type/omap'),\n require('../type/pairs'),\n require('../type/set')\n ]\n});\n","'use strict';\n\nvar Type = require('../../type');\n\nfunction resolveJavascriptUndefined() {\n return true;\n}\n\nfunction constructJavascriptUndefined() {\n /*eslint-disable no-undefined*/\n return undefined;\n}\n\nfunction representJavascriptUndefined() {\n return '';\n}\n\nfunction isUndefined(object) {\n return typeof object === 'undefined';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:js/undefined', {\n kind: 'scalar',\n resolve: resolveJavascriptUndefined,\n construct: constructJavascriptUndefined,\n predicate: isUndefined,\n represent: representJavascriptUndefined\n});\n","'use strict';\n\nvar Type = require('../../type');\n\nfunction resolveJavascriptRegExp(data) {\n if (data === null) return false;\n if (data.length === 0) return false;\n\n var regexp = data,\n tail = /\\/([gim]*)$/.exec(data),\n modifiers = '';\n\n // if regexp starts with '/' it can have modifiers and must be properly closed\n // `/foo/gim` - modifiers tail can be maximum 3 chars\n if (regexp[0] === '/') {\n if (tail) modifiers = tail[1];\n\n if (modifiers.length > 3) return false;\n // if expression starts with /, is should be properly terminated\n if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;\n }\n\n return true;\n}\n\nfunction constructJavascriptRegExp(data) {\n var regexp = data,\n tail = /\\/([gim]*)$/.exec(data),\n modifiers = '';\n\n // `/foo/gim` - tail can be maximum 4 chars\n if (regexp[0] === '/') {\n if (tail) modifiers = tail[1];\n regexp = regexp.slice(1, regexp.length - modifiers.length - 1);\n }\n\n return new RegExp(regexp, modifiers);\n}\n\nfunction representJavascriptRegExp(object /*, style*/) {\n var result = '/' + object.source + '/';\n\n if (object.global) result += 'g';\n if (object.multiline) result += 'm';\n if (object.ignoreCase) result += 'i';\n\n return result;\n}\n\nfunction isRegExp(object) {\n return Object.prototype.toString.call(object) === '[object RegExp]';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:js/regexp', {\n kind: 'scalar',\n resolve: resolveJavascriptRegExp,\n construct: constructJavascriptRegExp,\n predicate: isRegExp,\n represent: representJavascriptRegExp\n});\n","'use strict';\n\nvar esprima;\n\n// Browserified version does not have esprima\n//\n// 1. For node.js just require module as deps\n// 2. For browser try to require mudule via external AMD system.\n// If not found - try to fallback to window.esprima. If not\n// found too - then fail to parse.\n//\ntry {\n // workaround to exclude package from browserify list.\n var _require = require;\n esprima = _require('esprima');\n} catch (_) {\n /* eslint-disable no-redeclare */\n /* global window */\n if (typeof window !== 'undefined') esprima = window.esprima;\n}\n\nvar Type = require('../../type');\n\nfunction resolveJavascriptFunction(data) {\n if (data === null) return false;\n\n try {\n var source = '(' + data + ')',\n ast = esprima.parse(source, { range: true });\n\n if (ast.type !== 'Program' ||\n ast.body.length !== 1 ||\n ast.body[0].type !== 'ExpressionStatement' ||\n (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&\n ast.body[0].expression.type !== 'FunctionExpression')) {\n return false;\n }\n\n return true;\n } catch (err) {\n return false;\n }\n}\n\nfunction constructJavascriptFunction(data) {\n /*jslint evil:true*/\n\n var source = '(' + data + ')',\n ast = esprima.parse(source, { range: true }),\n params = [],\n body;\n\n if (ast.type !== 'Program' ||\n ast.body.length !== 1 ||\n ast.body[0].type !== 'ExpressionStatement' ||\n (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&\n ast.body[0].expression.type !== 'FunctionExpression')) {\n throw new Error('Failed to resolve function');\n }\n\n ast.body[0].expression.params.forEach(function (param) {\n params.push(param.name);\n });\n\n body = ast.body[0].expression.body.range;\n\n // Esprima's ranges include the first '{' and the last '}' characters on\n // function expressions. So cut them out.\n if (ast.body[0].expression.body.type === 'BlockStatement') {\n /*eslint-disable no-new-func*/\n return new Function(params, source.slice(body[0] + 1, body[1] - 1));\n }\n // ES6 arrow functions can omit the BlockStatement. In that case, just return\n // the body.\n /*eslint-disable no-new-func*/\n return new Function(params, 'return ' + source.slice(body[0], body[1]));\n}\n\nfunction representJavascriptFunction(object /*, style*/) {\n return object.toString();\n}\n\nfunction isFunction(object) {\n return Object.prototype.toString.call(object) === '[object Function]';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:js/function', {\n kind: 'scalar',\n resolve: resolveJavascriptFunction,\n construct: constructJavascriptFunction,\n predicate: isFunction,\n represent: representJavascriptFunction\n});\n","// JS-YAML's default schema for `load` function.\n// It is not described in the YAML specification.\n//\n// This schema is based on JS-YAML's default safe schema and includes\n// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.\n//\n// Also this schema is used as default base schema at `Schema.create` function.\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = Schema.DEFAULT = new Schema({\n include: [\n require('./default_safe')\n ],\n explicit: [\n require('../type/js/undefined'),\n require('../type/js/regexp'),\n require('../type/js/function')\n ]\n});\n","'use strict';\n\n/*eslint-disable max-len,no-use-before-define*/\n\nvar common = require('./common');\nvar YAMLException = require('./exception');\nvar Mark = require('./mark');\nvar DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');\nvar DEFAULT_FULL_SCHEMA = require('./schema/default_full');\n\n\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\n\nvar CONTEXT_FLOW_IN = 1;\nvar CONTEXT_FLOW_OUT = 2;\nvar CONTEXT_BLOCK_IN = 3;\nvar CONTEXT_BLOCK_OUT = 4;\n\n\nvar CHOMPING_CLIP = 1;\nvar CHOMPING_STRIP = 2;\nvar CHOMPING_KEEP = 3;\n\n\nvar PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\nvar PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/;\nvar PATTERN_FLOW_INDICATORS = /[,\\[\\]\\{\\}]/;\nvar PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\\-]+!)$/i;\nvar PATTERN_TAG_URI = /^(?:!|[^,\\[\\]\\{\\}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;\\/\\?:@&=\\+\\$,_\\.!~\\*'\\(\\)\\[\\]])*$/i;\n\n\nfunction _class(obj) { return Object.prototype.toString.call(obj); }\n\nfunction is_EOL(c) {\n return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);\n}\n\nfunction is_WHITE_SPACE(c) {\n return (c === 0x09/* Tab */) || (c === 0x20/* Space */);\n}\n\nfunction is_WS_OR_EOL(c) {\n return (c === 0x09/* Tab */) ||\n (c === 0x20/* Space */) ||\n (c === 0x0A/* LF */) ||\n (c === 0x0D/* CR */);\n}\n\nfunction is_FLOW_INDICATOR(c) {\n return c === 0x2C/* , */ ||\n c === 0x5B/* [ */ ||\n c === 0x5D/* ] */ ||\n c === 0x7B/* { */ ||\n c === 0x7D/* } */;\n}\n\nfunction fromHexCode(c) {\n var lc;\n\n if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n return c - 0x30;\n }\n\n /*eslint-disable no-bitwise*/\n lc = c | 0x20;\n\n if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {\n return lc - 0x61 + 10;\n }\n\n return -1;\n}\n\nfunction escapedHexLen(c) {\n if (c === 0x78/* x */) { return 2; }\n if (c === 0x75/* u */) { return 4; }\n if (c === 0x55/* U */) { return 8; }\n return 0;\n}\n\nfunction fromDecimalCode(c) {\n if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n return c - 0x30;\n }\n\n return -1;\n}\n\nfunction simpleEscapeSequence(c) {\n /* eslint-disable indent */\n return (c === 0x30/* 0 */) ? '\\x00' :\n (c === 0x61/* a */) ? '\\x07' :\n (c === 0x62/* b */) ? '\\x08' :\n (c === 0x74/* t */) ? '\\x09' :\n (c === 0x09/* Tab */) ? '\\x09' :\n (c === 0x6E/* n */) ? '\\x0A' :\n (c === 0x76/* v */) ? '\\x0B' :\n (c === 0x66/* f */) ? '\\x0C' :\n (c === 0x72/* r */) ? '\\x0D' :\n (c === 0x65/* e */) ? '\\x1B' :\n (c === 0x20/* Space */) ? ' ' :\n (c === 0x22/* \" */) ? '\\x22' :\n (c === 0x2F/* / */) ? '/' :\n (c === 0x5C/* \\ */) ? '\\x5C' :\n (c === 0x4E/* N */) ? '\\x85' :\n (c === 0x5F/* _ */) ? '\\xA0' :\n (c === 0x4C/* L */) ? '\\u2028' :\n (c === 0x50/* P */) ? '\\u2029' : '';\n}\n\nfunction charFromCodepoint(c) {\n if (c <= 0xFFFF) {\n return String.fromCharCode(c);\n }\n // Encode UTF-16 surrogate pair\n // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF\n return String.fromCharCode(\n ((c - 0x010000) >> 10) + 0xD800,\n ((c - 0x010000) & 0x03FF) + 0xDC00\n );\n}\n\n// set a property of a literal object, while protecting against prototype pollution,\n// see https://github.com/nodeca/js-yaml/issues/164 for more details\nfunction setProperty(object, key, value) {\n // used for this specific key only because Object.defineProperty is slow\n if (key === '__proto__') {\n Object.defineProperty(object, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value: value\n });\n } else {\n object[key] = value;\n }\n}\n\nvar simpleEscapeCheck = new Array(256); // integer, for fast access\nvar simpleEscapeMap = new Array(256);\nfor (var i = 0; i < 256; i++) {\n simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;\n simpleEscapeMap[i] = simpleEscapeSequence(i);\n}\n\n\nfunction State(input, options) {\n this.input = input;\n\n this.filename = options['filename'] || null;\n this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;\n this.onWarning = options['onWarning'] || null;\n this.legacy = options['legacy'] || false;\n this.json = options['json'] || false;\n this.listener = options['listener'] || null;\n\n this.implicitTypes = this.schema.compiledImplicit;\n this.typeMap = this.schema.compiledTypeMap;\n\n this.length = input.length;\n this.position = 0;\n this.line = 0;\n this.lineStart = 0;\n this.lineIndent = 0;\n\n this.documents = [];\n\n /*\n this.version;\n this.checkLineBreaks;\n this.tagMap;\n this.anchorMap;\n this.tag;\n this.anchor;\n this.kind;\n this.result;*/\n\n}\n\n\nfunction generateError(state, message) {\n return new YAMLException(\n message,\n new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));\n}\n\nfunction throwError(state, message) {\n throw generateError(state, message);\n}\n\nfunction throwWarning(state, message) {\n if (state.onWarning) {\n state.onWarning.call(null, generateError(state, message));\n }\n}\n\n\nvar directiveHandlers = {\n\n YAML: function handleYamlDirective(state, name, args) {\n\n var match, major, minor;\n\n if (state.version !== null) {\n throwError(state, 'duplication of %YAML directive');\n }\n\n if (args.length !== 1) {\n throwError(state, 'YAML directive accepts exactly one argument');\n }\n\n match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0]);\n\n if (match === null) {\n throwError(state, 'ill-formed argument of the YAML directive');\n }\n\n major = parseInt(match[1], 10);\n minor = parseInt(match[2], 10);\n\n if (major !== 1) {\n throwError(state, 'unacceptable YAML version of the document');\n }\n\n state.version = args[0];\n state.checkLineBreaks = (minor < 2);\n\n if (minor !== 1 && minor !== 2) {\n throwWarning(state, 'unsupported YAML version of the document');\n }\n },\n\n TAG: function handleTagDirective(state, name, args) {\n\n var handle, prefix;\n\n if (args.length !== 2) {\n throwError(state, 'TAG directive accepts exactly two arguments');\n }\n\n handle = args[0];\n prefix = args[1];\n\n if (!PATTERN_TAG_HANDLE.test(handle)) {\n throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');\n }\n\n if (_hasOwnProperty.call(state.tagMap, handle)) {\n throwError(state, 'there is a previously declared suffix for \"' + handle + '\" tag handle');\n }\n\n if (!PATTERN_TAG_URI.test(prefix)) {\n throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');\n }\n\n state.tagMap[handle] = prefix;\n }\n};\n\n\nfunction captureSegment(state, start, end, checkJson) {\n var _position, _length, _character, _result;\n\n if (start < end) {\n _result = state.input.slice(start, end);\n\n if (checkJson) {\n for (_position = 0, _length = _result.length; _position < _length; _position += 1) {\n _character = _result.charCodeAt(_position);\n if (!(_character === 0x09 ||\n (0x20 <= _character && _character <= 0x10FFFF))) {\n throwError(state, 'expected valid JSON character');\n }\n }\n } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n throwError(state, 'the stream contains non-printable characters');\n }\n\n state.result += _result;\n }\n}\n\nfunction mergeMappings(state, destination, source, overridableKeys) {\n var sourceKeys, key, index, quantity;\n\n if (!common.isObject(source)) {\n throwError(state, 'cannot merge mappings; the provided source object is unacceptable');\n }\n\n sourceKeys = Object.keys(source);\n\n for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n key = sourceKeys[index];\n\n if (!_hasOwnProperty.call(destination, key)) {\n setProperty(destination, key, source[key]);\n overridableKeys[key] = true;\n }\n }\n}\n\nfunction storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {\n var index, quantity;\n\n // The output is a plain object here, so keys can only be strings.\n // We need to convert keyNode to a string, but doing so can hang the process\n // (deeply nested arrays that explode exponentially using aliases).\n if (Array.isArray(keyNode)) {\n keyNode = Array.prototype.slice.call(keyNode);\n\n for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n if (Array.isArray(keyNode[index])) {\n throwError(state, 'nested arrays are not supported inside keys');\n }\n\n if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {\n keyNode[index] = '[object Object]';\n }\n }\n }\n\n // Avoid code execution in load() via toString property\n // (still use its own toString for arrays, timestamps,\n // and whatever user schema extensions happen to have @@toStringTag)\n if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {\n keyNode = '[object Object]';\n }\n\n\n keyNode = String(keyNode);\n\n if (_result === null) {\n _result = {};\n }\n\n if (keyTag === 'tag:yaml.org,2002:merge') {\n if (Array.isArray(valueNode)) {\n for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n mergeMappings(state, _result, valueNode[index], overridableKeys);\n }\n } else {\n mergeMappings(state, _result, valueNode, overridableKeys);\n }\n } else {\n if (!state.json &&\n !_hasOwnProperty.call(overridableKeys, keyNode) &&\n _hasOwnProperty.call(_result, keyNode)) {\n state.line = startLine || state.line;\n state.position = startPos || state.position;\n throwError(state, 'duplicated mapping key');\n }\n setProperty(_result, keyNode, valueNode);\n delete overridableKeys[keyNode];\n }\n\n return _result;\n}\n\nfunction readLineBreak(state) {\n var ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x0A/* LF */) {\n state.position++;\n } else if (ch === 0x0D/* CR */) {\n state.position++;\n if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {\n state.position++;\n }\n } else {\n throwError(state, 'a line break is expected');\n }\n\n state.line += 1;\n state.lineStart = state.position;\n}\n\nfunction skipSeparationSpace(state, allowComments, checkIndent) {\n var lineBreaks = 0,\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (allowComments && ch === 0x23/* # */) {\n do {\n ch = state.input.charCodeAt(++state.position);\n } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);\n }\n\n if (is_EOL(ch)) {\n readLineBreak(state);\n\n ch = state.input.charCodeAt(state.position);\n lineBreaks++;\n state.lineIndent = 0;\n\n while (ch === 0x20/* Space */) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n } else {\n break;\n }\n }\n\n if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n throwWarning(state, 'deficient indentation');\n }\n\n return lineBreaks;\n}\n\nfunction testDocumentSeparator(state) {\n var _position = state.position,\n ch;\n\n ch = state.input.charCodeAt(_position);\n\n // Condition state.position === state.lineStart is tested\n // in parent on each call, for efficiency. No needs to test here again.\n if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&\n ch === state.input.charCodeAt(_position + 1) &&\n ch === state.input.charCodeAt(_position + 2)) {\n\n _position += 3;\n\n ch = state.input.charCodeAt(_position);\n\n if (ch === 0 || is_WS_OR_EOL(ch)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction writeFoldedLines(state, count) {\n if (count === 1) {\n state.result += ' ';\n } else if (count > 1) {\n state.result += common.repeat('\\n', count - 1);\n }\n}\n\n\nfunction readPlainScalar(state, nodeIndent, withinFlowCollection) {\n var preceding,\n following,\n captureStart,\n captureEnd,\n hasPendingContent,\n _line,\n _lineStart,\n _lineIndent,\n _kind = state.kind,\n _result = state.result,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (is_WS_OR_EOL(ch) ||\n is_FLOW_INDICATOR(ch) ||\n ch === 0x23/* # */ ||\n ch === 0x26/* & */ ||\n ch === 0x2A/* * */ ||\n ch === 0x21/* ! */ ||\n ch === 0x7C/* | */ ||\n ch === 0x3E/* > */ ||\n ch === 0x27/* ' */ ||\n ch === 0x22/* \" */ ||\n ch === 0x25/* % */ ||\n ch === 0x40/* @ */ ||\n ch === 0x60/* ` */) {\n return false;\n }\n\n if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following) ||\n withinFlowCollection && is_FLOW_INDICATOR(following)) {\n return false;\n }\n }\n\n state.kind = 'scalar';\n state.result = '';\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n\n while (ch !== 0) {\n if (ch === 0x3A/* : */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following) ||\n withinFlowCollection && is_FLOW_INDICATOR(following)) {\n break;\n }\n\n } else if (ch === 0x23/* # */) {\n preceding = state.input.charCodeAt(state.position - 1);\n\n if (is_WS_OR_EOL(preceding)) {\n break;\n }\n\n } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||\n withinFlowCollection && is_FLOW_INDICATOR(ch)) {\n break;\n\n } else if (is_EOL(ch)) {\n _line = state.line;\n _lineStart = state.lineStart;\n _lineIndent = state.lineIndent;\n skipSeparationSpace(state, false, -1);\n\n if (state.lineIndent >= nodeIndent) {\n hasPendingContent = true;\n ch = state.input.charCodeAt(state.position);\n continue;\n } else {\n state.position = captureEnd;\n state.line = _line;\n state.lineStart = _lineStart;\n state.lineIndent = _lineIndent;\n break;\n }\n }\n\n if (hasPendingContent) {\n captureSegment(state, captureStart, captureEnd, false);\n writeFoldedLines(state, state.line - _line);\n captureStart = captureEnd = state.position;\n hasPendingContent = false;\n }\n\n if (!is_WHITE_SPACE(ch)) {\n captureEnd = state.position + 1;\n }\n\n ch = state.input.charCodeAt(++state.position);\n }\n\n captureSegment(state, captureStart, captureEnd, false);\n\n if (state.result) {\n return true;\n }\n\n state.kind = _kind;\n state.result = _result;\n return false;\n}\n\nfunction readSingleQuotedScalar(state, nodeIndent) {\n var ch,\n captureStart, captureEnd;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x27/* ' */) {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n state.position++;\n captureStart = captureEnd = state.position;\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x27/* ' */) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x27/* ' */) {\n captureStart = state.position;\n state.position++;\n captureEnd = state.position;\n } else {\n return true;\n }\n\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a single quoted scalar');\n\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a single quoted scalar');\n}\n\nfunction readDoubleQuotedScalar(state, nodeIndent) {\n var captureStart,\n captureEnd,\n hexLength,\n hexResult,\n tmp,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x22/* \" */) {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n state.position++;\n captureStart = captureEnd = state.position;\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n if (ch === 0x22/* \" */) {\n captureSegment(state, captureStart, state.position, true);\n state.position++;\n return true;\n\n } else if (ch === 0x5C/* \\ */) {\n captureSegment(state, captureStart, state.position, true);\n ch = state.input.charCodeAt(++state.position);\n\n if (is_EOL(ch)) {\n skipSeparationSpace(state, false, nodeIndent);\n\n // TODO: rework to inline fn with no type cast?\n } else if (ch < 256 && simpleEscapeCheck[ch]) {\n state.result += simpleEscapeMap[ch];\n state.position++;\n\n } else if ((tmp = escapedHexLen(ch)) > 0) {\n hexLength = tmp;\n hexResult = 0;\n\n for (; hexLength > 0; hexLength--) {\n ch = state.input.charCodeAt(++state.position);\n\n if ((tmp = fromHexCode(ch)) >= 0) {\n hexResult = (hexResult << 4) + tmp;\n\n } else {\n throwError(state, 'expected hexadecimal character');\n }\n }\n\n state.result += charFromCodepoint(hexResult);\n\n state.position++;\n\n } else {\n throwError(state, 'unknown escape sequence');\n }\n\n captureStart = captureEnd = state.position;\n\n } else if (is_EOL(ch)) {\n captureSegment(state, captureStart, captureEnd, true);\n writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n captureStart = captureEnd = state.position;\n\n } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n throwError(state, 'unexpected end of the document within a double quoted scalar');\n\n } else {\n state.position++;\n captureEnd = state.position;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a double quoted scalar');\n}\n\nfunction readFlowCollection(state, nodeIndent) {\n var readNext = true,\n _line,\n _tag = state.tag,\n _result,\n _anchor = state.anchor,\n following,\n terminator,\n isPair,\n isExplicitPair,\n isMapping,\n overridableKeys = {},\n keyNode,\n keyTag,\n valueNode,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x5B/* [ */) {\n terminator = 0x5D;/* ] */\n isMapping = false;\n _result = [];\n } else if (ch === 0x7B/* { */) {\n terminator = 0x7D;/* } */\n isMapping = true;\n _result = {};\n } else {\n return false;\n }\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(++state.position);\n\n while (ch !== 0) {\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === terminator) {\n state.position++;\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = isMapping ? 'mapping' : 'sequence';\n state.result = _result;\n return true;\n } else if (!readNext) {\n throwError(state, 'missed comma between flow collection entries');\n }\n\n keyTag = keyNode = valueNode = null;\n isPair = isExplicitPair = false;\n\n if (ch === 0x3F/* ? */) {\n following = state.input.charCodeAt(state.position + 1);\n\n if (is_WS_OR_EOL(following)) {\n isPair = isExplicitPair = true;\n state.position++;\n skipSeparationSpace(state, true, nodeIndent);\n }\n }\n\n _line = state.line;\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n keyTag = state.tag;\n keyNode = state.result;\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {\n isPair = true;\n ch = state.input.charCodeAt(++state.position);\n skipSeparationSpace(state, true, nodeIndent);\n composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n valueNode = state.result;\n }\n\n if (isMapping) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);\n } else if (isPair) {\n _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));\n } else {\n _result.push(keyNode);\n }\n\n skipSeparationSpace(state, true, nodeIndent);\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x2C/* , */) {\n readNext = true;\n ch = state.input.charCodeAt(++state.position);\n } else {\n readNext = false;\n }\n }\n\n throwError(state, 'unexpected end of the stream within a flow collection');\n}\n\nfunction readBlockScalar(state, nodeIndent) {\n var captureStart,\n folding,\n chomping = CHOMPING_CLIP,\n didReadContent = false,\n detectedIndent = false,\n textIndent = nodeIndent,\n emptyLines = 0,\n atMoreIndented = false,\n tmp,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch === 0x7C/* | */) {\n folding = false;\n } else if (ch === 0x3E/* > */) {\n folding = true;\n } else {\n return false;\n }\n\n state.kind = 'scalar';\n state.result = '';\n\n while (ch !== 0) {\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {\n if (CHOMPING_CLIP === chomping) {\n chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;\n } else {\n throwError(state, 'repeat of a chomping mode identifier');\n }\n\n } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n if (tmp === 0) {\n throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');\n } else if (!detectedIndent) {\n textIndent = nodeIndent + tmp - 1;\n detectedIndent = true;\n } else {\n throwError(state, 'repeat of an indentation width identifier');\n }\n\n } else {\n break;\n }\n }\n\n if (is_WHITE_SPACE(ch)) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (is_WHITE_SPACE(ch));\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (!is_EOL(ch) && (ch !== 0));\n }\n }\n\n while (ch !== 0) {\n readLineBreak(state);\n state.lineIndent = 0;\n\n ch = state.input.charCodeAt(state.position);\n\n while ((!detectedIndent || state.lineIndent < textIndent) &&\n (ch === 0x20/* Space */)) {\n state.lineIndent++;\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (!detectedIndent && state.lineIndent > textIndent) {\n textIndent = state.lineIndent;\n }\n\n if (is_EOL(ch)) {\n emptyLines++;\n continue;\n }\n\n // End of the scalar.\n if (state.lineIndent < textIndent) {\n\n // Perform the chomping.\n if (chomping === CHOMPING_KEEP) {\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n } else if (chomping === CHOMPING_CLIP) {\n if (didReadContent) { // i.e. only if the scalar is not empty.\n state.result += '\\n';\n }\n }\n\n // Break this `while` cycle and go to the funciton's epilogue.\n break;\n }\n\n // Folded style: use fancy rules to handle line breaks.\n if (folding) {\n\n // Lines starting with white space characters (more-indented lines) are not folded.\n if (is_WHITE_SPACE(ch)) {\n atMoreIndented = true;\n // except for the first content line (cf. Example 8.1)\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n\n // End of more-indented block.\n } else if (atMoreIndented) {\n atMoreIndented = false;\n state.result += common.repeat('\\n', emptyLines + 1);\n\n // Just one line break - perceive as the same line.\n } else if (emptyLines === 0) {\n if (didReadContent) { // i.e. only if we have already read some scalar content.\n state.result += ' ';\n }\n\n // Several line breaks - perceive as different lines.\n } else {\n state.result += common.repeat('\\n', emptyLines);\n }\n\n // Literal style: just add exact number of line breaks between content lines.\n } else {\n // Keep all line breaks except the header line break.\n state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n }\n\n didReadContent = true;\n detectedIndent = true;\n emptyLines = 0;\n captureStart = state.position;\n\n while (!is_EOL(ch) && (ch !== 0)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n captureSegment(state, captureStart, state.position, false);\n }\n\n return true;\n}\n\nfunction readBlockSequence(state, nodeIndent) {\n var _line,\n _tag = state.tag,\n _anchor = state.anchor,\n _result = [],\n following,\n detected = false,\n ch;\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n\n if (ch !== 0x2D/* - */) {\n break;\n }\n\n following = state.input.charCodeAt(state.position + 1);\n\n if (!is_WS_OR_EOL(following)) {\n break;\n }\n\n detected = true;\n state.position++;\n\n if (skipSeparationSpace(state, true, -1)) {\n if (state.lineIndent <= nodeIndent) {\n _result.push(null);\n ch = state.input.charCodeAt(state.position);\n continue;\n }\n }\n\n _line = state.line;\n composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);\n _result.push(state.result);\n skipSeparationSpace(state, true, -1);\n\n ch = state.input.charCodeAt(state.position);\n\n if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n throwError(state, 'bad indentation of a sequence entry');\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = 'sequence';\n state.result = _result;\n return true;\n }\n return false;\n}\n\nfunction readBlockMapping(state, nodeIndent, flowIndent) {\n var following,\n allowCompact,\n _line,\n _pos,\n _tag = state.tag,\n _anchor = state.anchor,\n _result = {},\n overridableKeys = {},\n keyTag = null,\n keyNode = null,\n valueNode = null,\n atExplicitKey = false,\n detected = false,\n ch;\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = _result;\n }\n\n ch = state.input.charCodeAt(state.position);\n\n while (ch !== 0) {\n following = state.input.charCodeAt(state.position + 1);\n _line = state.line; // Save the current line.\n _pos = state.position;\n\n //\n // Explicit notation case. There are two separate blocks:\n // first for the key (denoted by \"?\") and second for the value (denoted by \":\")\n //\n if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {\n\n if (ch === 0x3F/* ? */) {\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);\n keyTag = keyNode = valueNode = null;\n }\n\n detected = true;\n atExplicitKey = true;\n allowCompact = true;\n\n } else if (atExplicitKey) {\n // i.e. 0x3A/* : */ === character after the explicit key.\n atExplicitKey = false;\n allowCompact = true;\n\n } else {\n throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');\n }\n\n state.position += 1;\n ch = following;\n\n //\n // Implicit notation case. Flow-style node as the key first, then \":\", and the value.\n //\n } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n\n if (state.line === _line) {\n ch = state.input.charCodeAt(state.position);\n\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (ch === 0x3A/* : */) {\n ch = state.input.charCodeAt(++state.position);\n\n if (!is_WS_OR_EOL(ch)) {\n throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');\n }\n\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);\n keyTag = keyNode = valueNode = null;\n }\n\n detected = true;\n atExplicitKey = false;\n allowCompact = false;\n keyTag = state.tag;\n keyNode = state.result;\n\n } else if (detected) {\n throwError(state, 'can not read an implicit mapping pair; a colon is missed');\n\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true; // Keep the result of `composeNode`.\n }\n\n } else if (detected) {\n throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');\n\n } else {\n state.tag = _tag;\n state.anchor = _anchor;\n return true; // Keep the result of `composeNode`.\n }\n\n } else {\n break; // Reading is done. Go to the epilogue.\n }\n\n //\n // Common reading code for both explicit and implicit notations.\n //\n if (state.line === _line || state.lineIndent > nodeIndent) {\n if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n if (atExplicitKey) {\n keyNode = state.result;\n } else {\n valueNode = state.result;\n }\n }\n\n if (!atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);\n keyTag = keyNode = valueNode = null;\n }\n\n skipSeparationSpace(state, true, -1);\n ch = state.input.charCodeAt(state.position);\n }\n\n if (state.lineIndent > nodeIndent && (ch !== 0)) {\n throwError(state, 'bad indentation of a mapping entry');\n } else if (state.lineIndent < nodeIndent) {\n break;\n }\n }\n\n //\n // Epilogue.\n //\n\n // Special case: last mapping's node contains only the key in explicit notation.\n if (atExplicitKey) {\n storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);\n }\n\n // Expose the resulting mapping.\n if (detected) {\n state.tag = _tag;\n state.anchor = _anchor;\n state.kind = 'mapping';\n state.result = _result;\n }\n\n return detected;\n}\n\nfunction readTagProperty(state) {\n var _position,\n isVerbatim = false,\n isNamed = false,\n tagHandle,\n tagName,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x21/* ! */) return false;\n\n if (state.tag !== null) {\n throwError(state, 'duplication of a tag property');\n }\n\n ch = state.input.charCodeAt(++state.position);\n\n if (ch === 0x3C/* < */) {\n isVerbatim = true;\n ch = state.input.charCodeAt(++state.position);\n\n } else if (ch === 0x21/* ! */) {\n isNamed = true;\n tagHandle = '!!';\n ch = state.input.charCodeAt(++state.position);\n\n } else {\n tagHandle = '!';\n }\n\n _position = state.position;\n\n if (isVerbatim) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (ch !== 0 && ch !== 0x3E/* > */);\n\n if (state.position < state.length) {\n tagName = state.input.slice(_position, state.position);\n ch = state.input.charCodeAt(++state.position);\n } else {\n throwError(state, 'unexpected end of the stream within a verbatim tag');\n }\n } else {\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n\n if (ch === 0x21/* ! */) {\n if (!isNamed) {\n tagHandle = state.input.slice(_position - 1, state.position + 1);\n\n if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n throwError(state, 'named tag handle cannot contain such characters');\n }\n\n isNamed = true;\n _position = state.position + 1;\n } else {\n throwError(state, 'tag suffix cannot contain exclamation marks');\n }\n }\n\n ch = state.input.charCodeAt(++state.position);\n }\n\n tagName = state.input.slice(_position, state.position);\n\n if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n throwError(state, 'tag suffix cannot contain flow indicator characters');\n }\n }\n\n if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n throwError(state, 'tag name cannot contain such characters: ' + tagName);\n }\n\n if (isVerbatim) {\n state.tag = tagName;\n\n } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {\n state.tag = state.tagMap[tagHandle] + tagName;\n\n } else if (tagHandle === '!') {\n state.tag = '!' + tagName;\n\n } else if (tagHandle === '!!') {\n state.tag = 'tag:yaml.org,2002:' + tagName;\n\n } else {\n throwError(state, 'undeclared tag handle \"' + tagHandle + '\"');\n }\n\n return true;\n}\n\nfunction readAnchorProperty(state) {\n var _position,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x26/* & */) return false;\n\n if (state.anchor !== null) {\n throwError(state, 'duplication of an anchor property');\n }\n\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an anchor node must contain at least one character');\n }\n\n state.anchor = state.input.slice(_position, state.position);\n return true;\n}\n\nfunction readAlias(state) {\n var _position, alias,\n ch;\n\n ch = state.input.charCodeAt(state.position);\n\n if (ch !== 0x2A/* * */) return false;\n\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (state.position === _position) {\n throwError(state, 'name of an alias node must contain at least one character');\n }\n\n alias = state.input.slice(_position, state.position);\n\n if (!_hasOwnProperty.call(state.anchorMap, alias)) {\n throwError(state, 'unidentified alias \"' + alias + '\"');\n }\n\n state.result = state.anchorMap[alias];\n skipSeparationSpace(state, true, -1);\n return true;\n}\n\nfunction composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n var allowBlockStyles,\n allowBlockScalars,\n allowBlockCollections,\n indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent\n atNewLine = false,\n hasContent = false,\n typeIndex,\n typeQuantity,\n type,\n flowIndent,\n blockIndent;\n\n if (state.listener !== null) {\n state.listener('open', state);\n }\n\n state.tag = null;\n state.anchor = null;\n state.kind = null;\n state.result = null;\n\n allowBlockStyles = allowBlockScalars = allowBlockCollections =\n CONTEXT_BLOCK_OUT === nodeContext ||\n CONTEXT_BLOCK_IN === nodeContext;\n\n if (allowToSeek) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n }\n }\n\n if (indentStatus === 1) {\n while (readTagProperty(state) || readAnchorProperty(state)) {\n if (skipSeparationSpace(state, true, -1)) {\n atNewLine = true;\n allowBlockCollections = allowBlockStyles;\n\n if (state.lineIndent > parentIndent) {\n indentStatus = 1;\n } else if (state.lineIndent === parentIndent) {\n indentStatus = 0;\n } else if (state.lineIndent < parentIndent) {\n indentStatus = -1;\n }\n } else {\n allowBlockCollections = false;\n }\n }\n }\n\n if (allowBlockCollections) {\n allowBlockCollections = atNewLine || allowCompact;\n }\n\n if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n flowIndent = parentIndent;\n } else {\n flowIndent = parentIndent + 1;\n }\n\n blockIndent = state.position - state.lineStart;\n\n if (indentStatus === 1) {\n if (allowBlockCollections &&\n (readBlockSequence(state, blockIndent) ||\n readBlockMapping(state, blockIndent, flowIndent)) ||\n readFlowCollection(state, flowIndent)) {\n hasContent = true;\n } else {\n if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||\n readSingleQuotedScalar(state, flowIndent) ||\n readDoubleQuotedScalar(state, flowIndent)) {\n hasContent = true;\n\n } else if (readAlias(state)) {\n hasContent = true;\n\n if (state.tag !== null || state.anchor !== null) {\n throwError(state, 'alias node should not have any properties');\n }\n\n } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n hasContent = true;\n\n if (state.tag === null) {\n state.tag = '?';\n }\n }\n\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n } else if (indentStatus === 0) {\n // Special case: block sequences are allowed to have same indentation level as the parent.\n // http://www.yaml.org/spec/1.2/spec.html#id2799784\n hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);\n }\n }\n\n if (state.tag !== null && state.tag !== '!') {\n if (state.tag === '?') {\n // Implicit resolving is not allowed for non-scalar types, and '?'\n // non-specific tag is only automatically assigned to plain scalars.\n //\n // We only need to check kind conformity in case user explicitly assigns '?'\n // tag, for example like this: \"!<?> [0]\"\n //\n if (state.result !== null && state.kind !== 'scalar') {\n throwError(state, 'unacceptable node kind for !<?> tag; it should be \"scalar\", not \"' + state.kind + '\"');\n }\n\n for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n type = state.implicitTypes[typeIndex];\n\n if (type.resolve(state.result)) { // `state.result` updated in resolver if matched\n state.result = type.construct(state.result);\n state.tag = type.tag;\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n break;\n }\n }\n } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {\n type = state.typeMap[state.kind || 'fallback'][state.tag];\n\n if (state.result !== null && type.kind !== state.kind) {\n throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be \"' + type.kind + '\", not \"' + state.kind + '\"');\n }\n\n if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched\n throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');\n } else {\n state.result = type.construct(state.result);\n if (state.anchor !== null) {\n state.anchorMap[state.anchor] = state.result;\n }\n }\n } else {\n throwError(state, 'unknown tag !<' + state.tag + '>');\n }\n }\n\n if (state.listener !== null) {\n state.listener('close', state);\n }\n return state.tag !== null || state.anchor !== null || hasContent;\n}\n\nfunction readDocument(state) {\n var documentStart = state.position,\n _position,\n directiveName,\n directiveArgs,\n hasDirectives = false,\n ch;\n\n state.version = null;\n state.checkLineBreaks = state.legacy;\n state.tagMap = {};\n state.anchorMap = {};\n\n while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n skipSeparationSpace(state, true, -1);\n\n ch = state.input.charCodeAt(state.position);\n\n if (state.lineIndent > 0 || ch !== 0x25/* % */) {\n break;\n }\n\n hasDirectives = true;\n ch = state.input.charCodeAt(++state.position);\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n directiveName = state.input.slice(_position, state.position);\n directiveArgs = [];\n\n if (directiveName.length < 1) {\n throwError(state, 'directive name must not be less than one character in length');\n }\n\n while (ch !== 0) {\n while (is_WHITE_SPACE(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n if (ch === 0x23/* # */) {\n do { ch = state.input.charCodeAt(++state.position); }\n while (ch !== 0 && !is_EOL(ch));\n break;\n }\n\n if (is_EOL(ch)) break;\n\n _position = state.position;\n\n while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n ch = state.input.charCodeAt(++state.position);\n }\n\n directiveArgs.push(state.input.slice(_position, state.position));\n }\n\n if (ch !== 0) readLineBreak(state);\n\n if (_hasOwnProperty.call(directiveHandlers, directiveName)) {\n directiveHandlers[directiveName](state, directiveName, directiveArgs);\n } else {\n throwWarning(state, 'unknown document directive \"' + directiveName + '\"');\n }\n }\n\n skipSeparationSpace(state, true, -1);\n\n if (state.lineIndent === 0 &&\n state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&\n state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n\n } else if (hasDirectives) {\n throwError(state, 'directives end mark is expected');\n }\n\n composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);\n skipSeparationSpace(state, true, -1);\n\n if (state.checkLineBreaks &&\n PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n throwWarning(state, 'non-ASCII line breaks are interpreted as content');\n }\n\n state.documents.push(state.result);\n\n if (state.position === state.lineStart && testDocumentSeparator(state)) {\n\n if (state.input.charCodeAt(state.position) === 0x2E/* . */) {\n state.position += 3;\n skipSeparationSpace(state, true, -1);\n }\n return;\n }\n\n if (state.position < (state.length - 1)) {\n throwError(state, 'end of the stream or a document separator is expected');\n } else {\n return;\n }\n}\n\n\nfunction loadDocuments(input, options) {\n input = String(input);\n options = options || {};\n\n if (input.length !== 0) {\n\n // Add tailing `\\n` if not exists\n if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&\n input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {\n input += '\\n';\n }\n\n // Strip BOM\n if (input.charCodeAt(0) === 0xFEFF) {\n input = input.slice(1);\n }\n }\n\n var state = new State(input, options);\n\n var nullpos = input.indexOf('\\0');\n\n if (nullpos !== -1) {\n state.position = nullpos;\n throwError(state, 'null byte is not allowed in input');\n }\n\n // Use 0 as string terminator. That significantly simplifies bounds check.\n state.input += '\\0';\n\n while (state.input.charCodeAt(state.position) === 0x20/* Space */) {\n state.lineIndent += 1;\n state.position += 1;\n }\n\n while (state.position < (state.length - 1)) {\n readDocument(state);\n }\n\n return state.documents;\n}\n\n\nfunction loadAll(input, iterator, options) {\n if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {\n options = iterator;\n iterator = null;\n }\n\n var documents = loadDocuments(input, options);\n\n if (typeof iterator !== 'function') {\n return documents;\n }\n\n for (var index = 0, length = documents.length; index < length; index += 1) {\n iterator(documents[index]);\n }\n}\n\n\nfunction load(input, options) {\n var documents = loadDocuments(input, options);\n\n if (documents.length === 0) {\n /*eslint-disable no-undefined*/\n return undefined;\n } else if (documents.length === 1) {\n return documents[0];\n }\n throw new YAMLException('expected a single document in the stream, but found more');\n}\n\n\nfunction safeLoadAll(input, iterator, options) {\n if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {\n options = iterator;\n iterator = null;\n }\n\n return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));\n}\n\n\nfunction safeLoad(input, options) {\n return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));\n}\n\n\nmodule.exports.loadAll = loadAll;\nmodule.exports.load = load;\nmodule.exports.safeLoadAll = safeLoadAll;\nmodule.exports.safeLoad = safeLoad;\n","'use strict';\n\n/*eslint-disable no-use-before-define*/\n\nvar common = require('./common');\nvar YAMLException = require('./exception');\nvar DEFAULT_FULL_SCHEMA = require('./schema/default_full');\nvar DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');\n\nvar _toString = Object.prototype.toString;\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar CHAR_TAB = 0x09; /* Tab */\nvar CHAR_LINE_FEED = 0x0A; /* LF */\nvar CHAR_CARRIAGE_RETURN = 0x0D; /* CR */\nvar CHAR_SPACE = 0x20; /* Space */\nvar CHAR_EXCLAMATION = 0x21; /* ! */\nvar CHAR_DOUBLE_QUOTE = 0x22; /* \" */\nvar CHAR_SHARP = 0x23; /* # */\nvar CHAR_PERCENT = 0x25; /* % */\nvar CHAR_AMPERSAND = 0x26; /* & */\nvar CHAR_SINGLE_QUOTE = 0x27; /* ' */\nvar CHAR_ASTERISK = 0x2A; /* * */\nvar CHAR_COMMA = 0x2C; /* , */\nvar CHAR_MINUS = 0x2D; /* - */\nvar CHAR_COLON = 0x3A; /* : */\nvar CHAR_EQUALS = 0x3D; /* = */\nvar CHAR_GREATER_THAN = 0x3E; /* > */\nvar CHAR_QUESTION = 0x3F; /* ? */\nvar CHAR_COMMERCIAL_AT = 0x40; /* @ */\nvar CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */\nvar CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */\nvar CHAR_GRAVE_ACCENT = 0x60; /* ` */\nvar CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */\nvar CHAR_VERTICAL_LINE = 0x7C; /* | */\nvar CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */\n\nvar ESCAPE_SEQUENCES = {};\n\nESCAPE_SEQUENCES[0x00] = '\\\\0';\nESCAPE_SEQUENCES[0x07] = '\\\\a';\nESCAPE_SEQUENCES[0x08] = '\\\\b';\nESCAPE_SEQUENCES[0x09] = '\\\\t';\nESCAPE_SEQUENCES[0x0A] = '\\\\n';\nESCAPE_SEQUENCES[0x0B] = '\\\\v';\nESCAPE_SEQUENCES[0x0C] = '\\\\f';\nESCAPE_SEQUENCES[0x0D] = '\\\\r';\nESCAPE_SEQUENCES[0x1B] = '\\\\e';\nESCAPE_SEQUENCES[0x22] = '\\\\\"';\nESCAPE_SEQUENCES[0x5C] = '\\\\\\\\';\nESCAPE_SEQUENCES[0x85] = '\\\\N';\nESCAPE_SEQUENCES[0xA0] = '\\\\_';\nESCAPE_SEQUENCES[0x2028] = '\\\\L';\nESCAPE_SEQUENCES[0x2029] = '\\\\P';\n\nvar DEPRECATED_BOOLEANS_SYNTAX = [\n 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',\n 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'\n];\n\nfunction compileStyleMap(schema, map) {\n var result, keys, index, length, tag, style, type;\n\n if (map === null) return {};\n\n result = {};\n keys = Object.keys(map);\n\n for (index = 0, length = keys.length; index < length; index += 1) {\n tag = keys[index];\n style = String(map[tag]);\n\n if (tag.slice(0, 2) === '!!') {\n tag = 'tag:yaml.org,2002:' + tag.slice(2);\n }\n type = schema.compiledTypeMap['fallback'][tag];\n\n if (type && _hasOwnProperty.call(type.styleAliases, style)) {\n style = type.styleAliases[style];\n }\n\n result[tag] = style;\n }\n\n return result;\n}\n\nfunction encodeHex(character) {\n var string, handle, length;\n\n string = character.toString(16).toUpperCase();\n\n if (character <= 0xFF) {\n handle = 'x';\n length = 2;\n } else if (character <= 0xFFFF) {\n handle = 'u';\n length = 4;\n } else if (character <= 0xFFFFFFFF) {\n handle = 'U';\n length = 8;\n } else {\n throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');\n }\n\n return '\\\\' + handle + common.repeat('0', length - string.length) + string;\n}\n\nfunction State(options) {\n this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;\n this.indent = Math.max(1, (options['indent'] || 2));\n this.noArrayIndent = options['noArrayIndent'] || false;\n this.skipInvalid = options['skipInvalid'] || false;\n this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);\n this.styleMap = compileStyleMap(this.schema, options['styles'] || null);\n this.sortKeys = options['sortKeys'] || false;\n this.lineWidth = options['lineWidth'] || 80;\n this.noRefs = options['noRefs'] || false;\n this.noCompatMode = options['noCompatMode'] || false;\n this.condenseFlow = options['condenseFlow'] || false;\n\n this.implicitTypes = this.schema.compiledImplicit;\n this.explicitTypes = this.schema.compiledExplicit;\n\n this.tag = null;\n this.result = '';\n\n this.duplicates = [];\n this.usedDuplicates = null;\n}\n\n// Indents every line in a string. Empty lines (\\n only) are not indented.\nfunction indentString(string, spaces) {\n var ind = common.repeat(' ', spaces),\n position = 0,\n next = -1,\n result = '',\n line,\n length = string.length;\n\n while (position < length) {\n next = string.indexOf('\\n', position);\n if (next === -1) {\n line = string.slice(position);\n position = length;\n } else {\n line = string.slice(position, next + 1);\n position = next + 1;\n }\n\n if (line.length && line !== '\\n') result += ind;\n\n result += line;\n }\n\n return result;\n}\n\nfunction generateNextLine(state, level) {\n return '\\n' + common.repeat(' ', state.indent * level);\n}\n\nfunction testImplicitResolving(state, str) {\n var index, length, type;\n\n for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n type = state.implicitTypes[index];\n\n if (type.resolve(str)) {\n return true;\n }\n }\n\n return false;\n}\n\n// [33] s-white ::= s-space | s-tab\nfunction isWhitespace(c) {\n return c === CHAR_SPACE || c === CHAR_TAB;\n}\n\n// Returns true if the character can be printed without escaping.\n// From YAML 1.2: \"any allowed characters known to be non-printable\n// should also be escaped. [However,] This isn’t mandatory\"\n// Derived from nb-char - \\t - #x85 - #xA0 - #x2028 - #x2029.\nfunction isPrintable(c) {\n return (0x00020 <= c && c <= 0x00007E)\n || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)\n || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)\n || (0x10000 <= c && c <= 0x10FFFF);\n}\n\n// [34] ns-char ::= nb-char - s-white\n// [27] nb-char ::= c-printable - b-char - c-byte-order-mark\n// [26] b-char ::= b-line-feed | b-carriage-return\n// [24] b-line-feed ::= #xA /* LF */\n// [25] b-carriage-return ::= #xD /* CR */\n// [3] c-byte-order-mark ::= #xFEFF\nfunction isNsChar(c) {\n return isPrintable(c) && !isWhitespace(c)\n // byte-order-mark\n && c !== 0xFEFF\n // b-char\n && c !== CHAR_CARRIAGE_RETURN\n && c !== CHAR_LINE_FEED;\n}\n\n// Simplified test for values allowed after the first character in plain style.\nfunction isPlainSafe(c, prev) {\n // Uses a subset of nb-char - c-flow-indicator - \":\" - \"#\"\n // where nb-char ::= c-printable - b-char - c-byte-order-mark.\n return isPrintable(c) && c !== 0xFEFF\n // - c-flow-indicator\n && c !== CHAR_COMMA\n && c !== CHAR_LEFT_SQUARE_BRACKET\n && c !== CHAR_RIGHT_SQUARE_BRACKET\n && c !== CHAR_LEFT_CURLY_BRACKET\n && c !== CHAR_RIGHT_CURLY_BRACKET\n // - \":\" - \"#\"\n // /* An ns-char preceding */ \"#\"\n && c !== CHAR_COLON\n && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));\n}\n\n// Simplified test for values allowed as the first character in plain style.\nfunction isPlainSafeFirst(c) {\n // Uses a subset of ns-char - c-indicator\n // where ns-char = nb-char - s-white.\n return isPrintable(c) && c !== 0xFEFF\n && !isWhitespace(c) // - s-white\n // - (c-indicator ::=\n // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”\n && c !== CHAR_MINUS\n && c !== CHAR_QUESTION\n && c !== CHAR_COLON\n && c !== CHAR_COMMA\n && c !== CHAR_LEFT_SQUARE_BRACKET\n && c !== CHAR_RIGHT_SQUARE_BRACKET\n && c !== CHAR_LEFT_CURLY_BRACKET\n && c !== CHAR_RIGHT_CURLY_BRACKET\n // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “\"”\n && c !== CHAR_SHARP\n && c !== CHAR_AMPERSAND\n && c !== CHAR_ASTERISK\n && c !== CHAR_EXCLAMATION\n && c !== CHAR_VERTICAL_LINE\n && c !== CHAR_EQUALS\n && c !== CHAR_GREATER_THAN\n && c !== CHAR_SINGLE_QUOTE\n && c !== CHAR_DOUBLE_QUOTE\n // | “%” | “@” | “`”)\n && c !== CHAR_PERCENT\n && c !== CHAR_COMMERCIAL_AT\n && c !== CHAR_GRAVE_ACCENT;\n}\n\n// Determines whether block indentation indicator is required.\nfunction needIndentIndicator(string) {\n var leadingSpaceRe = /^\\n* /;\n return leadingSpaceRe.test(string);\n}\n\nvar STYLE_PLAIN = 1,\n STYLE_SINGLE = 2,\n STYLE_LITERAL = 3,\n STYLE_FOLDED = 4,\n STYLE_DOUBLE = 5;\n\n// Determines which scalar styles are possible and returns the preferred style.\n// lineWidth = -1 => no limit.\n// Pre-conditions: str.length > 0.\n// Post-conditions:\n// STYLE_PLAIN or STYLE_SINGLE => no \\n are in the string.\n// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).\n// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).\nfunction chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {\n var i;\n var char, prev_char;\n var hasLineBreak = false;\n var hasFoldableLine = false; // only checked if shouldTrackWidth\n var shouldTrackWidth = lineWidth !== -1;\n var previousLineBreak = -1; // count the first line correctly\n var plain = isPlainSafeFirst(string.charCodeAt(0))\n && !isWhitespace(string.charCodeAt(string.length - 1));\n\n if (singleLineOnly) {\n // Case: no block styles.\n // Check for disallowed characters to rule out plain and single.\n for (i = 0; i < string.length; i++) {\n char = string.charCodeAt(i);\n if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n prev_char = i > 0 ? string.charCodeAt(i - 1) : null;\n plain = plain && isPlainSafe(char, prev_char);\n }\n } else {\n // Case: block styles permitted.\n for (i = 0; i < string.length; i++) {\n char = string.charCodeAt(i);\n if (char === CHAR_LINE_FEED) {\n hasLineBreak = true;\n // Check if any line can be folded.\n if (shouldTrackWidth) {\n hasFoldableLine = hasFoldableLine ||\n // Foldable line = too long, and not more-indented.\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' ');\n previousLineBreak = i;\n }\n } else if (!isPrintable(char)) {\n return STYLE_DOUBLE;\n }\n prev_char = i > 0 ? string.charCodeAt(i - 1) : null;\n plain = plain && isPlainSafe(char, prev_char);\n }\n // in case the end is missing a \\n\n hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&\n (i - previousLineBreak - 1 > lineWidth &&\n string[previousLineBreak + 1] !== ' '));\n }\n // Although every style can represent \\n without escaping, prefer block styles\n // for multiline, since they're more readable and they don't add empty lines.\n // Also prefer folding a super-long line.\n if (!hasLineBreak && !hasFoldableLine) {\n // Strings interpretable as another type have to be quoted;\n // e.g. the string 'true' vs. the boolean true.\n return plain && !testAmbiguousType(string)\n ? STYLE_PLAIN : STYLE_SINGLE;\n }\n // Edge case: block indentation indicator can only have one digit.\n if (indentPerLevel > 9 && needIndentIndicator(string)) {\n return STYLE_DOUBLE;\n }\n // At this point we know block styles are valid.\n // Prefer literal style unless we want to fold.\n return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;\n}\n\n// Note: line breaking/folding is implemented for only the folded style.\n// NB. We drop the last trailing newline (if any) of a returned block scalar\n// since the dumper adds its own newline. This always works:\n// • No ending newline => unaffected; already using strip \"-\" chomping.\n// • Ending newline => removed then restored.\n// Importantly, this keeps the \"+\" chomp indicator from gaining an extra line.\nfunction writeScalar(state, string, level, iskey) {\n state.dump = (function () {\n if (string.length === 0) {\n return \"''\";\n }\n if (!state.noCompatMode &&\n DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {\n return \"'\" + string + \"'\";\n }\n\n var indent = state.indent * Math.max(1, level); // no 0-indent scalars\n // As indentation gets deeper, let the width decrease monotonically\n // to the lower bound min(state.lineWidth, 40).\n // Note that this implies\n // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.\n // state.lineWidth > 40 + state.indent: width decreases until the lower bound.\n // This behaves better than a constant minimum width which disallows narrower options,\n // or an indent threshold which causes the width to suddenly increase.\n var lineWidth = state.lineWidth === -1\n ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);\n\n // Without knowing if keys are implicit/explicit, assume implicit for safety.\n var singleLineOnly = iskey\n // No block styles in flow mode.\n || (state.flowLevel > -1 && level >= state.flowLevel);\n function testAmbiguity(string) {\n return testImplicitResolving(state, string);\n }\n\n switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {\n case STYLE_PLAIN:\n return string;\n case STYLE_SINGLE:\n return \"'\" + string.replace(/'/g, \"''\") + \"'\";\n case STYLE_LITERAL:\n return '|' + blockHeader(string, state.indent)\n + dropEndingNewline(indentString(string, indent));\n case STYLE_FOLDED:\n return '>' + blockHeader(string, state.indent)\n + dropEndingNewline(indentString(foldString(string, lineWidth), indent));\n case STYLE_DOUBLE:\n return '\"' + escapeString(string, lineWidth) + '\"';\n default:\n throw new YAMLException('impossible error: invalid scalar style');\n }\n }());\n}\n\n// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.\nfunction blockHeader(string, indentPerLevel) {\n var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';\n\n // note the special case: the string '\\n' counts as a \"trailing\" empty line.\n var clip = string[string.length - 1] === '\\n';\n var keep = clip && (string[string.length - 2] === '\\n' || string === '\\n');\n var chomp = keep ? '+' : (clip ? '' : '-');\n\n return indentIndicator + chomp + '\\n';\n}\n\n// (See the note for writeScalar.)\nfunction dropEndingNewline(string) {\n return string[string.length - 1] === '\\n' ? string.slice(0, -1) : string;\n}\n\n// Note: a long line without a suitable break point will exceed the width limit.\n// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.\nfunction foldString(string, width) {\n // In folded style, $k$ consecutive newlines output as $k+1$ newlines—\n // unless they're before or after a more-indented line, or at the very\n // beginning or end, in which case $k$ maps to $k$.\n // Therefore, parse each chunk as newline(s) followed by a content line.\n var lineRe = /(\\n+)([^\\n]*)/g;\n\n // first line (possibly an empty line)\n var result = (function () {\n var nextLF = string.indexOf('\\n');\n nextLF = nextLF !== -1 ? nextLF : string.length;\n lineRe.lastIndex = nextLF;\n return foldLine(string.slice(0, nextLF), width);\n }());\n // If we haven't reached the first content line yet, don't add an extra \\n.\n var prevMoreIndented = string[0] === '\\n' || string[0] === ' ';\n var moreIndented;\n\n // rest of the lines\n var match;\n while ((match = lineRe.exec(string))) {\n var prefix = match[1], line = match[2];\n moreIndented = (line[0] === ' ');\n result += prefix\n + (!prevMoreIndented && !moreIndented && line !== ''\n ? '\\n' : '')\n + foldLine(line, width);\n prevMoreIndented = moreIndented;\n }\n\n return result;\n}\n\n// Greedy line breaking.\n// Picks the longest line under the limit each time,\n// otherwise settles for the shortest line over the limit.\n// NB. More-indented lines *cannot* be folded, as that would add an extra \\n.\nfunction foldLine(line, width) {\n if (line === '' || line[0] === ' ') return line;\n\n // Since a more-indented line adds a \\n, breaks can't be followed by a space.\n var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.\n var match;\n // start is an inclusive index. end, curr, and next are exclusive.\n var start = 0, end, curr = 0, next = 0;\n var result = '';\n\n // Invariants: 0 <= start <= length-1.\n // 0 <= curr <= next <= max(0, length-2). curr - start <= width.\n // Inside the loop:\n // A match implies length >= 2, so curr and next are <= length-2.\n while ((match = breakRe.exec(line))) {\n next = match.index;\n // maintain invariant: curr - start <= width\n if (next - start > width) {\n end = (curr > start) ? curr : next; // derive end <= length-2\n result += '\\n' + line.slice(start, end);\n // skip the space that was output as \\n\n start = end + 1; // derive start <= length-1\n }\n curr = next;\n }\n\n // By the invariants, start <= length-1, so there is something left over.\n // It is either the whole string or a part starting from non-whitespace.\n result += '\\n';\n // Insert a break if the remainder is too long and there is a break available.\n if (line.length - start > width && curr > start) {\n result += line.slice(start, curr) + '\\n' + line.slice(curr + 1);\n } else {\n result += line.slice(start);\n }\n\n return result.slice(1); // drop extra \\n joiner\n}\n\n// Escapes a double-quoted string.\nfunction escapeString(string) {\n var result = '';\n var char, nextChar;\n var escapeSeq;\n\n for (var i = 0; i < string.length; i++) {\n char = string.charCodeAt(i);\n // Check for surrogate pairs (reference Unicode 3.0 section \"3.7 Surrogates\").\n if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {\n nextChar = string.charCodeAt(i + 1);\n if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {\n // Combine the surrogate pair and store it escaped.\n result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);\n // Advance index one extra since we already used that char here.\n i++; continue;\n }\n }\n escapeSeq = ESCAPE_SEQUENCES[char];\n result += !escapeSeq && isPrintable(char)\n ? string[i]\n : escapeSeq || encodeHex(char);\n }\n\n return result;\n}\n\nfunction writeFlowSequence(state, level, object) {\n var _result = '',\n _tag = state.tag,\n index,\n length;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n // Write only valid elements.\n if (writeNode(state, level, object[index], false, false)) {\n if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');\n _result += state.dump;\n }\n }\n\n state.tag = _tag;\n state.dump = '[' + _result + ']';\n}\n\nfunction writeBlockSequence(state, level, object, compact) {\n var _result = '',\n _tag = state.tag,\n index,\n length;\n\n for (index = 0, length = object.length; index < length; index += 1) {\n // Write only valid elements.\n if (writeNode(state, level + 1, object[index], true, true)) {\n if (!compact || index !== 0) {\n _result += generateNextLine(state, level);\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n _result += '-';\n } else {\n _result += '- ';\n }\n\n _result += state.dump;\n }\n }\n\n state.tag = _tag;\n state.dump = _result || '[]'; // Empty sequence if no valid values.\n}\n\nfunction writeFlowMapping(state, level, object) {\n var _result = '',\n _tag = state.tag,\n objectKeyList = Object.keys(object),\n index,\n length,\n objectKey,\n objectValue,\n pairBuffer;\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n\n pairBuffer = '';\n if (index !== 0) pairBuffer += ', ';\n\n if (state.condenseFlow) pairBuffer += '\"';\n\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n\n if (!writeNode(state, level, objectKey, false, false)) {\n continue; // Skip this pair because of invalid key;\n }\n\n if (state.dump.length > 1024) pairBuffer += '? ';\n\n pairBuffer += state.dump + (state.condenseFlow ? '\"' : '') + ':' + (state.condenseFlow ? '' : ' ');\n\n if (!writeNode(state, level, objectValue, false, false)) {\n continue; // Skip this pair because of invalid value.\n }\n\n pairBuffer += state.dump;\n\n // Both key and value are valid.\n _result += pairBuffer;\n }\n\n state.tag = _tag;\n state.dump = '{' + _result + '}';\n}\n\nfunction writeBlockMapping(state, level, object, compact) {\n var _result = '',\n _tag = state.tag,\n objectKeyList = Object.keys(object),\n index,\n length,\n objectKey,\n objectValue,\n explicitPair,\n pairBuffer;\n\n // Allow sorting keys so that the output file is deterministic\n if (state.sortKeys === true) {\n // Default sorting\n objectKeyList.sort();\n } else if (typeof state.sortKeys === 'function') {\n // Custom sort function\n objectKeyList.sort(state.sortKeys);\n } else if (state.sortKeys) {\n // Something is wrong\n throw new YAMLException('sortKeys must be a boolean or a function');\n }\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n pairBuffer = '';\n\n if (!compact || index !== 0) {\n pairBuffer += generateNextLine(state, level);\n }\n\n objectKey = objectKeyList[index];\n objectValue = object[objectKey];\n\n if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n continue; // Skip this pair because of invalid key.\n }\n\n explicitPair = (state.tag !== null && state.tag !== '?') ||\n (state.dump && state.dump.length > 1024);\n\n if (explicitPair) {\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += '?';\n } else {\n pairBuffer += '? ';\n }\n }\n\n pairBuffer += state.dump;\n\n if (explicitPair) {\n pairBuffer += generateNextLine(state, level);\n }\n\n if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n continue; // Skip this pair because of invalid value.\n }\n\n if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n pairBuffer += ':';\n } else {\n pairBuffer += ': ';\n }\n\n pairBuffer += state.dump;\n\n // Both key and value are valid.\n _result += pairBuffer;\n }\n\n state.tag = _tag;\n state.dump = _result || '{}'; // Empty mapping if no valid pairs.\n}\n\nfunction detectType(state, object, explicit) {\n var _result, typeList, index, length, type, style;\n\n typeList = explicit ? state.explicitTypes : state.implicitTypes;\n\n for (index = 0, length = typeList.length; index < length; index += 1) {\n type = typeList[index];\n\n if ((type.instanceOf || type.predicate) &&\n (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&\n (!type.predicate || type.predicate(object))) {\n\n state.tag = explicit ? type.tag : '?';\n\n if (type.represent) {\n style = state.styleMap[type.tag] || type.defaultStyle;\n\n if (_toString.call(type.represent) === '[object Function]') {\n _result = type.represent(object, style);\n } else if (_hasOwnProperty.call(type.represent, style)) {\n _result = type.represent[style](object, style);\n } else {\n throw new YAMLException('!<' + type.tag + '> tag resolver accepts not \"' + style + '\" style');\n }\n\n state.dump = _result;\n }\n\n return true;\n }\n }\n\n return false;\n}\n\n// Serializes `object` and writes it to global `result`.\n// Returns true on success, or false on invalid object.\n//\nfunction writeNode(state, level, object, block, compact, iskey) {\n state.tag = null;\n state.dump = object;\n\n if (!detectType(state, object, false)) {\n detectType(state, object, true);\n }\n\n var type = _toString.call(state.dump);\n\n if (block) {\n block = (state.flowLevel < 0 || state.flowLevel > level);\n }\n\n var objectOrArray = type === '[object Object]' || type === '[object Array]',\n duplicateIndex,\n duplicate;\n\n if (objectOrArray) {\n duplicateIndex = state.duplicates.indexOf(object);\n duplicate = duplicateIndex !== -1;\n }\n\n if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {\n compact = false;\n }\n\n if (duplicate && state.usedDuplicates[duplicateIndex]) {\n state.dump = '*ref_' + duplicateIndex;\n } else {\n if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n state.usedDuplicates[duplicateIndex] = true;\n }\n if (type === '[object Object]') {\n if (block && (Object.keys(state.dump).length !== 0)) {\n writeBlockMapping(state, level, state.dump, compact);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump;\n }\n } else {\n writeFlowMapping(state, level, state.dump);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n }\n }\n } else if (type === '[object Array]') {\n var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;\n if (block && (state.dump.length !== 0)) {\n writeBlockSequence(state, arrayLevel, state.dump, compact);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + state.dump;\n }\n } else {\n writeFlowSequence(state, arrayLevel, state.dump);\n if (duplicate) {\n state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n }\n }\n } else if (type === '[object String]') {\n if (state.tag !== '?') {\n writeScalar(state, state.dump, level, iskey);\n }\n } else {\n if (state.skipInvalid) return false;\n throw new YAMLException('unacceptable kind of an object to dump ' + type);\n }\n\n if (state.tag !== null && state.tag !== '?') {\n state.dump = '!<' + state.tag + '> ' + state.dump;\n }\n }\n\n return true;\n}\n\nfunction getDuplicateReferences(object, state) {\n var objects = [],\n duplicatesIndexes = [],\n index,\n length;\n\n inspectNode(object, objects, duplicatesIndexes);\n\n for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {\n state.duplicates.push(objects[duplicatesIndexes[index]]);\n }\n state.usedDuplicates = new Array(length);\n}\n\nfunction inspectNode(object, objects, duplicatesIndexes) {\n var objectKeyList,\n index,\n length;\n\n if (object !== null && typeof object === 'object') {\n index = objects.indexOf(object);\n if (index !== -1) {\n if (duplicatesIndexes.indexOf(index) === -1) {\n duplicatesIndexes.push(index);\n }\n } else {\n objects.push(object);\n\n if (Array.isArray(object)) {\n for (index = 0, length = object.length; index < length; index += 1) {\n inspectNode(object[index], objects, duplicatesIndexes);\n }\n } else {\n objectKeyList = Object.keys(object);\n\n for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);\n }\n }\n }\n }\n}\n\nfunction dump(input, options) {\n options = options || {};\n\n var state = new State(options);\n\n if (!state.noRefs) getDuplicateReferences(input, state);\n\n if (writeNode(state, 0, input, true, true)) return state.dump + '\\n';\n\n return '';\n}\n\nfunction safeDump(input, options) {\n return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));\n}\n\nmodule.exports.dump = dump;\nmodule.exports.safeDump = safeDump;\n","'use strict';\n\n\nvar loader = require('./js-yaml/loader');\nvar dumper = require('./js-yaml/dumper');\n\n\nfunction deprecated(name) {\n return function () {\n throw new Error('Function ' + name + ' is deprecated and cannot be used.');\n };\n}\n\n\nmodule.exports.Type = require('./js-yaml/type');\nmodule.exports.Schema = require('./js-yaml/schema');\nmodule.exports.FAILSAFE_SCHEMA = require('./js-yaml/schema/failsafe');\nmodule.exports.JSON_SCHEMA = require('./js-yaml/schema/json');\nmodule.exports.CORE_SCHEMA = require('./js-yaml/schema/core');\nmodule.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe');\nmodule.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full');\nmodule.exports.load = loader.load;\nmodule.exports.loadAll = loader.loadAll;\nmodule.exports.safeLoad = loader.safeLoad;\nmodule.exports.safeLoadAll = loader.safeLoadAll;\nmodule.exports.dump = dumper.dump;\nmodule.exports.safeDump = dumper.safeDump;\nmodule.exports.YAMLException = require('./js-yaml/exception');\n\n// Deprecated schema names from JS-YAML 2.0.x\nmodule.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');\nmodule.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe');\nmodule.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');\n\n// Deprecated functions from JS-YAML 1.x.x\nmodule.exports.scan = deprecated('scan');\nmodule.exports.parse = deprecated('parse');\nmodule.exports.compose = deprecated('compose');\nmodule.exports.addConstructor = deprecated('addConstructor');\n","'use strict';\n\n\nvar yaml = require('./lib/js-yaml.js');\n\n\nmodule.exports = yaml;\n","'use strict';\n\nconst yaml = require('js-yaml');\n\n/**\n * Default engines\n */\n\nconst engines = exports = module.exports;\n\n/**\n * YAML\n */\n\nengines.yaml = {\n parse: yaml.safeLoad.bind(yaml),\n stringify: yaml.safeDump.bind(yaml)\n};\n\n/**\n * JSON\n */\n\nengines.json = {\n parse: JSON.parse.bind(JSON),\n stringify: function(obj, options) {\n const opts = Object.assign({replacer: null, space: 2}, options);\n return JSON.stringify(obj, opts.replacer, opts.space);\n }\n};\n\n/**\n * JavaScript\n */\n\nengines.javascript = {\n parse: function parse(str, options, wrap) {\n /* eslint no-eval: 0 */\n try {\n if (wrap !== false) {\n str = '(function() {\\nreturn ' + str.trim() + ';\\n}());';\n }\n return eval(str) || {};\n } catch (err) {\n if (wrap !== false && /(unexpected|identifier)/i.test(err.message)) {\n return parse(str, options, false);\n }\n throw new SyntaxError(err);\n }\n },\n stringify: function() {\n throw new Error('stringifying JavaScript is not supported');\n }\n};\n","/*!\n * strip-bom-string <https://github.com/jonschlinkert/strip-bom-string>\n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function(str) {\n if (typeof str === 'string' && str.charAt(0) === '\\ufeff') {\n return str.slice(1);\n }\n return str;\n};\n","'use strict';\n\nconst stripBom = require('strip-bom-string');\nconst typeOf = require('kind-of');\n\nexports.define = function(obj, key, val) {\n Reflect.defineProperty(obj, key, {\n enumerable: false,\n configurable: true,\n writable: true,\n value: val\n });\n};\n\n/**\n * Returns true if `val` is a buffer\n */\n\nexports.isBuffer = function(val) {\n return typeOf(val) === 'buffer';\n};\n\n/**\n * Returns true if `val` is an object\n */\n\nexports.isObject = function(val) {\n return typeOf(val) === 'object';\n};\n\n/**\n * Cast `input` to a buffer\n */\n\nexports.toBuffer = function(input) {\n return typeof input === 'string' ? Buffer.from(input) : input;\n};\n\n/**\n * Cast `val` to a string.\n */\n\nexports.toString = function(input) {\n if (exports.isBuffer(input)) return stripBom(String(input));\n if (typeof input !== 'string') {\n throw new TypeError('expected input to be a string or buffer');\n }\n return stripBom(input);\n};\n\n/**\n * Cast `val` to an array.\n */\n\nexports.arrayify = function(val) {\n return val ? (Array.isArray(val) ? val : [val]) : [];\n};\n\n/**\n * Returns true if `str` starts with `substr`.\n */\n\nexports.startsWith = function(str, substr, len) {\n if (typeof len !== 'number') len = substr.length;\n return str.slice(0, len) === substr;\n};\n","'use strict';\n\nconst engines = require('./engines');\nconst utils = require('./utils');\n\nmodule.exports = function(options) {\n const opts = Object.assign({}, options);\n\n // ensure that delimiters are an array\n opts.delimiters = utils.arrayify(opts.delims || opts.delimiters || '---');\n if (opts.delimiters.length === 1) {\n opts.delimiters.push(opts.delimiters[0]);\n }\n\n opts.language = (opts.language || opts.lang || 'yaml').toLowerCase();\n opts.engines = Object.assign({}, engines, opts.parsers, opts.engines);\n return opts;\n};\n","'use strict';\n\nmodule.exports = function(name, options) {\n let engine = options.engines[name] || options.engines[aliase(name)];\n if (typeof engine === 'undefined') {\n throw new Error('gray-matter engine \"' + name + '\" is not registered');\n }\n if (typeof engine === 'function') {\n engine = { parse: engine };\n }\n return engine;\n};\n\nfunction aliase(name) {\n switch (name.toLowerCase()) {\n case 'js':\n case 'javascript':\n return 'javascript';\n case 'coffee':\n case 'coffeescript':\n case 'cson':\n return 'coffee';\n case 'yaml':\n case 'yml':\n return 'yaml';\n default: {\n return name;\n }\n }\n}\n","'use strict';\n\nconst typeOf = require('kind-of');\nconst getEngine = require('./engine');\nconst defaults = require('./defaults');\n\nmodule.exports = function(file, data, options) {\n if (data == null && options == null) {\n switch (typeOf(file)) {\n case 'object':\n data = file.data;\n options = {};\n break;\n case 'string':\n return file;\n default: {\n throw new TypeError('expected file to be a string or object');\n }\n }\n }\n\n const str = file.content;\n const opts = defaults(options);\n if (data == null) {\n if (!opts.data) return file;\n data = opts.data;\n }\n\n const language = file.language || opts.language;\n const engine = getEngine(language, opts);\n if (typeof engine.stringify !== 'function') {\n throw new TypeError('expected \"' + language + '.stringify\" to be a function');\n }\n\n data = Object.assign({}, file.data, data);\n const open = opts.delimiters[0];\n const close = opts.delimiters[1];\n const matter = engine.stringify(data, options).trim();\n let buf = '';\n\n if (matter !== '{}') {\n buf = newline(open) + newline(matter) + newline(close);\n }\n\n if (typeof file.excerpt === 'string' && file.excerpt !== '') {\n if (str.indexOf(file.excerpt.trim()) === -1) {\n buf += newline(file.excerpt) + newline(close);\n }\n }\n\n return buf + newline(str);\n};\n\nfunction newline(str) {\n return str.slice(-1) !== '\\n' ? str + '\\n' : str;\n}\n","'use strict';\n\nconst defaults = require('./defaults');\n\nmodule.exports = function(file, options) {\n const opts = defaults(options);\n\n if (file.data == null) {\n file.data = {};\n }\n\n if (typeof opts.excerpt === 'function') {\n return opts.excerpt(file, opts);\n }\n\n const sep = file.data.excerpt_separator || opts.excerpt_separator;\n if (sep == null && (opts.excerpt === false || opts.excerpt == null)) {\n return file;\n }\n\n const delimiter = typeof opts.excerpt === 'string'\n ? opts.excerpt\n : (sep || opts.delimiters[0]);\n\n // if enabled, get the excerpt defined after front-matter\n const idx = file.content.indexOf(delimiter);\n if (idx !== -1) {\n file.excerpt = file.content.slice(0, idx);\n }\n\n return file;\n};\n","'use strict';\n\nconst typeOf = require('kind-of');\nconst stringify = require('./stringify');\nconst utils = require('./utils');\n\n/**\n * Normalize the given value to ensure an object is returned\n * with the expected properties.\n */\n\nmodule.exports = function(file) {\n if (typeOf(file) !== 'object') {\n file = { content: file };\n }\n\n if (typeOf(file.data) !== 'object') {\n file.data = {};\n }\n\n // if file was passed as an object, ensure that\n // \"file.content\" is set\n if (file.contents && file.content == null) {\n file.content = file.contents;\n }\n\n // set non-enumerable properties on the file object\n utils.define(file, 'orig', utils.toBuffer(file.content));\n utils.define(file, 'language', file.language || '');\n utils.define(file, 'matter', file.matter || '');\n utils.define(file, 'stringify', function(data, options) {\n if (options && options.language) {\n file.language = options.language;\n }\n return stringify(file, data, options);\n });\n\n // strip BOM and ensure that \"file.content\" is a string\n file.content = utils.toString(file.content);\n file.isEmpty = false;\n file.excerpt = '';\n return file;\n};\n","'use strict';\n\nconst getEngine = require('./engine');\nconst defaults = require('./defaults');\n\nmodule.exports = function(language, str, options) {\n const opts = defaults(options);\n const engine = getEngine(language, opts);\n if (typeof engine.parse !== 'function') {\n throw new TypeError('expected \"' + language + '.parse\" to be a function');\n }\n return engine.parse(str, opts);\n};\n","'use strict';\n\nconst fs = require('fs');\nconst sections = require('section-matter');\nconst defaults = require('./lib/defaults');\nconst stringify = require('./lib/stringify');\nconst excerpt = require('./lib/excerpt');\nconst engines = require('./lib/engines');\nconst toFile = require('./lib/to-file');\nconst parse = require('./lib/parse');\nconst utils = require('./lib/utils');\n\n/**\n * Takes a string or object with `content` property, extracts\n * and parses front-matter from the string, then returns an object\n * with `data`, `content` and other [useful properties](#returned-object).\n *\n * ```js\n * const matter = require('gray-matter');\n * console.log(matter('---\\ntitle: Home\\n---\\nOther stuff'));\n * //=> { data: { title: 'Home'}, content: 'Other stuff' }\n * ```\n * @param {Object|String} `input` String, or object with `content` string\n * @param {Object} `options`\n * @return {Object}\n * @api public\n */\n\nfunction matter(input, options) {\n if (input === '') {\n return { data: {}, content: input, excerpt: '', orig: input };\n }\n\n let file = toFile(input);\n const cached = matter.cache[file.content];\n\n if (!options) {\n if (cached) {\n file = Object.assign({}, cached);\n file.orig = cached.orig;\n return file;\n }\n\n // only cache if there are no options passed. if we cache when options\n // are passed, we would need to also cache options values, which would\n // negate any performance benefits of caching\n matter.cache[file.content] = file;\n }\n\n return parseMatter(file, options);\n}\n\n/**\n * Parse front matter\n */\n\nfunction parseMatter(file, options) {\n const opts = defaults(options);\n const open = opts.delimiters[0];\n const close = '\\n' + opts.delimiters[1];\n let str = file.content;\n\n if (opts.language) {\n file.language = opts.language;\n }\n\n // get the length of the opening delimiter\n const openLen = open.length;\n if (!utils.startsWith(str, open, openLen)) {\n excerpt(file, opts);\n return file;\n }\n\n // if the next character after the opening delimiter is\n // a character from the delimiter, then it's not a front-\n // matter delimiter\n if (str.charAt(openLen) === open.slice(-1)) {\n return file;\n }\n\n // strip the opening delimiter\n str = str.slice(openLen);\n const len = str.length;\n\n // use the language defined after first delimiter, if it exists\n const language = matter.language(str, opts);\n if (language.name) {\n file.language = language.name;\n str = str.slice(language.raw.length);\n }\n\n // get the index of the closing delimiter\n let closeIndex = str.indexOf(close);\n if (closeIndex === -1) {\n closeIndex = len;\n }\n\n // get the raw front-matter block\n file.matter = str.slice(0, closeIndex);\n\n const block = file.matter.replace(/^\\s*#[^\\n]+/gm, '').trim();\n if (block === '') {\n file.isEmpty = true;\n file.empty = file.content;\n file.data = {};\n } else {\n\n // create file.data by parsing the raw file.matter block\n file.data = parse(file.language, file.matter, opts);\n }\n\n // update file.content\n if (closeIndex === len) {\n file.content = '';\n } else {\n file.content = str.slice(closeIndex + close.length);\n if (file.content[0] === '\\r') {\n file.content = file.content.slice(1);\n }\n if (file.content[0] === '\\n') {\n file.content = file.content.slice(1);\n }\n }\n\n excerpt(file, opts);\n\n if (opts.sections === true || typeof opts.section === 'function') {\n sections(file, opts.section);\n }\n return file;\n}\n\n/**\n * Expose engines\n */\n\nmatter.engines = engines;\n\n/**\n * Stringify an object to YAML or the specified language, and\n * append it to the given string. By default, only YAML and JSON\n * can be stringified. See the [engines](#engines) section to learn\n * how to stringify other languages.\n *\n * ```js\n * console.log(matter.stringify('foo bar baz', {title: 'Home'}));\n * // results in:\n * // ---\n * // title: Home\n * // ---\n * // foo bar baz\n * ```\n * @param {String|Object} `file` The content string to append to stringified front-matter, or a file object with `file.content` string.\n * @param {Object} `data` Front matter to stringify.\n * @param {Object} `options` [Options](#options) to pass to gray-matter and [js-yaml].\n * @return {String} Returns a string created by wrapping stringified yaml with delimiters, and appending that to the given string.\n * @api public\n */\n\nmatter.stringify = function(file, data, options) {\n if (typeof file === 'string') file = matter(file, options);\n return stringify(file, data, options);\n};\n\n/**\n * Synchronously read a file from the file system and parse\n * front matter. Returns the same object as the [main function](#matter).\n *\n * ```js\n * const file = matter.read('./content/blog-post.md');\n * ```\n * @param {String} `filepath` file path of the file to read.\n * @param {Object} `options` [Options](#options) to pass to gray-matter.\n * @return {Object} Returns [an object](#returned-object) with `data` and `content`\n * @api public\n */\n\nmatter.read = function(filepath, options) {\n const str = fs.readFileSync(filepath, 'utf8');\n const file = matter(str, options);\n file.path = filepath;\n return file;\n};\n\n/**\n * Returns true if the given `string` has front matter.\n * @param {String} `string`\n * @param {Object} `options`\n * @return {Boolean} True if front matter exists.\n * @api public\n */\n\nmatter.test = function(str, options) {\n return utils.startsWith(str, defaults(options).delimiters[0]);\n};\n\n/**\n * Detect the language to use, if one is defined after the\n * first front-matter delimiter.\n * @param {String} `string`\n * @param {Object} `options`\n * @return {Object} Object with `raw` (actual language string), and `name`, the language with whitespace trimmed\n */\n\nmatter.language = function(str, options) {\n const opts = defaults(options);\n const open = opts.delimiters[0];\n\n if (matter.test(str)) {\n str = str.slice(open.length);\n }\n\n const language = str.slice(0, str.search(/\\r?\\n/));\n return {\n raw: language,\n name: language ? language.trim() : ''\n };\n};\n\n/**\n * Expose `matter`\n */\n\nmatter.cache = {};\nmatter.clearCache = function() {\n matter.cache = {};\n};\nmodule.exports = matter;\n","import type { MycoIndex } from './sqlite.js';\n\nexport interface FtsResult {\n path: string;\n type: string;\n id: string;\n title: string;\n snippet: string;\n rank: number;\n}\n\nexport interface FtsSearchOptions {\n type?: string;\n limit?: number;\n}\n\nexport function initFts(index: MycoIndex): void {\n const db = index.getDb();\n db.exec(`\n CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(\n path UNINDEXED,\n type UNINDEXED,\n id UNINDEXED,\n title,\n content,\n content='notes',\n content_rowid='rowid'\n );\n\n CREATE TRIGGER IF NOT EXISTS notes_ai AFTER INSERT ON notes BEGIN\n INSERT INTO notes_fts(rowid, path, type, id, title, content)\n VALUES (new.rowid, new.path, new.type, new.id, new.title, new.content);\n END;\n\n CREATE TRIGGER IF NOT EXISTS notes_ad AFTER DELETE ON notes BEGIN\n INSERT INTO notes_fts(notes_fts, rowid, path, type, id, title, content)\n VALUES ('delete', old.rowid, old.path, old.type, old.id, old.title, old.content);\n END;\n\n CREATE TRIGGER IF NOT EXISTS notes_au AFTER UPDATE ON notes BEGIN\n INSERT INTO notes_fts(notes_fts, rowid, path, type, id, title, content)\n VALUES ('delete', old.rowid, old.path, old.type, old.id, old.title, old.content);\n INSERT INTO notes_fts(rowid, path, type, id, title, content)\n VALUES (new.rowid, new.path, new.type, new.id, new.title, new.content);\n END;\n `);\n}\n\nexport function searchFts(index: MycoIndex, query: string, options: FtsSearchOptions = {}): FtsResult[] {\n const db = index.getDb();\n const limit = options.limit ?? 20;\n const params: unknown[] = [query];\n\n let typeFilter = '';\n if (options.type) {\n typeFilter = ' AND type = ?';\n params.push(options.type);\n }\n params.push(limit);\n\n const sql = `\n SELECT path, type, id, title,\n snippet(notes_fts, 4, '<mark>', '</mark>', '...', 40) AS snippet,\n rank\n FROM notes_fts\n WHERE notes_fts MATCH ?${typeFilter}\n ORDER BY rank\n LIMIT ?\n `;\n\n return db.prepare(sql).all(...params) as FtsResult[];\n}\n","import type { EmbeddingProvider, EmbeddingResponse } from './llm.js';\n\nexport async function generateEmbedding(\n backend: EmbeddingProvider,\n text: string,\n): Promise<EmbeddingResponse> {\n const raw = await backend.embed(text);\n return {\n embedding: normalize(raw.embedding),\n model: raw.model,\n dimensions: raw.dimensions,\n };\n}\n\nfunction normalize(vec: number[]): number[] {\n const magnitude = Math.sqrt(vec.reduce((sum, v) => sum + v * v, 0));\n if (magnitude === 0) return vec;\n return vec.map((v) => v / magnitude);\n}\n","import { z } from 'zod';\n\nexport const SessionFrontmatterSchema = z.object({\n type: z.literal('session'),\n id: z.string(),\n agent: z.string(),\n user: z.string(),\n started: z.string(),\n ended: z.string().optional(),\n parent: z.string().optional(),\n parent_reason: z.string().optional(),\n plan: z.string().optional(), // backward compat read path\n plans: z.array(z.string()).optional(), // new: multiple plans\n branch: z.string().optional(),\n tags: z.array(z.string()).default([]),\n tools_used: z.number().int().optional(),\n files_changed: z.number().int().optional(),\n});\n\nexport const PlanFrontmatterSchema = z.object({\n type: z.literal('plan'),\n id: z.string(),\n status: z.enum(['active', 'in_progress', 'completed', 'abandoned']).default('active'),\n created: z.string(),\n author: z.string().optional(),\n tags: z.array(z.string()).default([]),\n});\n\nexport const MEMORY_STATUSES = ['active', 'superseded', 'archived'] as const;\nexport type MemoryStatus = (typeof MEMORY_STATUSES)[number];\n\nexport const MemoryFrontmatterSchema = z.object({\n type: z.literal('memory'),\n id: z.string(),\n observation_type: z.string(),\n status: z.enum(MEMORY_STATUSES).default('active'),\n session: z.string().optional(),\n plan: z.string().optional(),\n superseded_by: z.string().optional(),\n consolidated_from: z.array(z.string()).optional(),\n created: z.string(),\n tags: z.array(z.string()).default([]),\n});\n\nexport const ARTIFACT_TYPES = ['spec', 'plan', 'rfc', 'doc', 'other'] as const;\nexport type ArtifactType = (typeof ARTIFACT_TYPES)[number];\n\nexport const ArtifactFrontmatterSchema = z.object({\n type: z.literal('artifact'),\n id: z.string(),\n artifact_type: z.enum(ARTIFACT_TYPES).default('other'),\n source_path: z.string(),\n title: z.string(),\n last_captured_by: z.string(),\n created: z.string(),\n updated: z.string(),\n tags: z.array(z.string()).default([]),\n});\n\nexport const TeamMemberFrontmatterSchema = z.object({\n type: z.literal('team-member'),\n user: z.string(),\n joined: z.string(),\n role: z.string().optional(),\n tags: z.array(z.string()).default([]),\n});\n\nexport type SessionFrontmatter = z.infer<typeof SessionFrontmatterSchema>;\nexport type PlanFrontmatter = z.infer<typeof PlanFrontmatterSchema>;\nexport type MemoryFrontmatter = z.infer<typeof MemoryFrontmatterSchema>;\nexport type ObservationType = MemoryFrontmatter['observation_type'];\nexport type ArtifactFrontmatter = z.infer<typeof ArtifactFrontmatterSchema>;\nexport type TeamMemberFrontmatter = z.infer<typeof TeamMemberFrontmatterSchema>;\n\nexport type NoteFrontmatter =\n | SessionFrontmatter\n | PlanFrontmatter\n | MemoryFrontmatter\n | ArtifactFrontmatter\n | TeamMemberFrontmatter;\n\nexport interface VaultNote<T extends NoteFrontmatter = NoteFrontmatter> {\n path: string;\n frontmatter: T;\n content: string;\n}\n\nconst schemasByType: Record<string, z.ZodSchema> = {\n session: SessionFrontmatterSchema,\n plan: PlanFrontmatterSchema,\n memory: MemoryFrontmatterSchema,\n artifact: ArtifactFrontmatterSchema,\n 'team-member': TeamMemberFrontmatterSchema,\n};\n\nexport function parseNoteFrontmatter(data: Record<string, unknown>): NoteFrontmatter {\n const type = data.type as string;\n const schema = schemasByType[type];\n if (!schema) {\n throw new Error(`Unknown note type: ${type}`);\n }\n // gray-matter and YAML.parse return Date objects for ISO date strings.\n // Coerce them to strings before Zod validation.\n const coerced = coerceDatesToStrings(data);\n return schema.parse(coerced) as NoteFrontmatter;\n}\n\nfunction coerceDatesToStrings(obj: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value instanceof Date) {\n result[key] = value.toISOString();\n } else if (Array.isArray(value)) {\n result[key] = value.map((item) => item instanceof Date ? item.toISOString() : item);\n } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result[key] = coerceDatesToStrings(value as Record<string, unknown>);\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport matter from 'gray-matter';\nimport { parseNoteFrontmatter, type VaultNote } from './types.js';\n\nconst VAULT_SUBDIRS = ['sessions', 'plans', 'memories', 'artifacts', 'team'];\n\nexport class VaultReader {\n constructor(private vaultDir: string) {}\n\n readNote(relativePath: string): VaultNote {\n const fullPath = path.join(this.vaultDir, relativePath);\n const raw = fs.readFileSync(fullPath, 'utf-8');\n const { data, content } = matter(raw);\n const frontmatter = parseNoteFrontmatter(data as Record<string, unknown>);\n return { path: relativePath, frontmatter, content: content.trim() };\n }\n\n listNotes(subdir: string): VaultNote[] {\n const dirPath = path.join(this.vaultDir, subdir);\n if (!fs.existsSync(dirPath)) return [];\n\n const files = this.walkMarkdownFiles(dirPath);\n return files.map((filePath) => {\n const relativePath = path.relative(this.vaultDir, filePath);\n return this.readNote(relativePath);\n });\n }\n\n readAllNotes(): VaultNote[] {\n return VAULT_SUBDIRS.flatMap((subdir) => this.listNotes(subdir));\n }\n\n walkMarkdownFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n\n const results: string[] = [];\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...this.walkMarkdownFiles(fullPath));\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n results.push(fullPath);\n }\n }\n\n return results;\n }\n}\n","import { VaultReader } from '../vault/reader.js';\nimport type { MycoIndex } from './sqlite.js';\nimport type { VaultNote } from '../vault/types.js';\n\nexport function indexNote(index: MycoIndex, vaultDir: string, relativePath: string): void {\n const reader = new VaultReader(vaultDir);\n const note = reader.readNote(relativePath);\n indexVaultNote(index, note);\n}\n\nfunction indexVaultNote(index: MycoIndex, note: VaultNote): void {\n const fm = note.frontmatter;\n const title = extractTitle(note.content) || ('id' in fm ? String(fm.id) : note.path);\n const created = 'started' in fm ? fm.started\n : 'created' in fm ? fm.created\n : 'joined' in fm ? fm.joined\n : new Date().toISOString();\n\n index.upsertNote({\n path: note.path,\n type: fm.type,\n id: 'id' in fm ? String(fm.id) : 'user' in fm ? String(fm.user) : note.path,\n title,\n content: note.content,\n frontmatter: fm as Record<string, unknown>,\n created: String(created),\n });\n}\n\nexport function rebuildIndex(index: MycoIndex, vaultDir: string): number {\n const db = index.getDb();\n db.exec('DELETE FROM notes');\n\n const reader = new VaultReader(vaultDir);\n const notes = reader.readAllNotes();\n let count = 0;\n\n for (const note of notes) {\n indexVaultNote(index, note);\n count++;\n }\n\n return count;\n}\n\nfunction extractTitle(content: string): string {\n const match = content.match(/^#\\s+(.+)$/m);\n return match ? match[1].trim() : '';\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nexport interface LogEntry {\n timestamp: string;\n level: string;\n component: string;\n message: string;\n [key: string]: unknown;\n}\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport const LEVEL_ORDER: Record<LogLevel, number> = {\n debug: 0, info: 1, warn: 2, error: 3,\n};\n\ninterface LoggerOptions {\n level?: LogLevel;\n maxSize?: number;\n maxFiles?: number;\n}\n\nexport class DaemonLogger {\n private logPath: string;\n private fd: number | null = null;\n private currentSize = 0;\n private level: LogLevel;\n private maxSize: number;\n private maxFiles: number;\n private logDir: string;\n\n constructor(logDir: string, options: LoggerOptions = {}) {\n this.logDir = logDir;\n this.logPath = path.join(logDir, 'daemon.log');\n this.level = options.level ?? 'info';\n this.maxSize = options.maxSize ?? 5_242_880;\n this.maxFiles = options.maxFiles ?? 3;\n\n fs.mkdirSync(logDir, { recursive: true });\n this.fd = fs.openSync(this.logPath, 'a');\n try {\n this.currentSize = fs.fstatSync(this.fd).size;\n } catch {\n this.currentSize = 0;\n }\n }\n\n debug(component: string, message: string, data?: Record<string, unknown>): void {\n this.write('debug', component, message, data);\n }\n\n info(component: string, message: string, data?: Record<string, unknown>): void {\n this.write('info', component, message, data);\n }\n\n warn(component: string, message: string, data?: Record<string, unknown>): void {\n this.write('warn', component, message, data);\n }\n\n error(component: string, message: string, data?: Record<string, unknown>): void {\n this.write('error', component, message, data);\n }\n\n close(): void {\n if (this.fd !== null) {\n fs.closeSync(this.fd);\n this.fd = null;\n }\n }\n\n private write(level: LogLevel, component: string, message: string, data?: Record<string, unknown>): void {\n if (LEVEL_ORDER[level] < LEVEL_ORDER[this.level]) return;\n\n const entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n component,\n message,\n ...data,\n };\n\n const line = JSON.stringify(entry) + '\\n';\n const bytes = Buffer.byteLength(line);\n\n if (this.currentSize + bytes > this.maxSize) {\n this.rotate();\n }\n\n if (this.fd !== null) {\n fs.writeSync(this.fd, line);\n this.currentSize += bytes;\n }\n }\n\n private rotate(): void {\n this.close();\n\n for (let i = this.maxFiles - 1; i >= 1; i--) {\n const from = path.join(this.logDir, `daemon.${i}.log`);\n const to = path.join(this.logDir, `daemon.${i + 1}.log`);\n if (fs.existsSync(from)) {\n if (i + 1 > this.maxFiles) {\n fs.unlinkSync(from);\n } else {\n fs.renameSync(from, to);\n }\n }\n }\n\n if (fs.existsSync(this.logPath)) {\n fs.renameSync(this.logPath, path.join(this.logDir, 'daemon.1.log'));\n }\n\n this.fd = fs.openSync(this.logPath, 'a');\n this.currentSize = 0;\n }\n}\n","import type { LlmProvider, EmbeddingProvider, LlmResponse, EmbeddingResponse, LlmRequestOptions } from './llm.js';\nimport { CHARS_PER_TOKEN, LLM_REQUEST_TIMEOUT_MS, EMBEDDING_REQUEST_TIMEOUT_MS, DAEMON_CLIENT_TIMEOUT_MS } from '../constants.js';\n\ninterface OllamaConfig {\n model?: string;\n base_url?: string;\n context_window?: number;\n max_tokens?: number;\n // Legacy fields (ignored, kept for backward compat during migration)\n embedding_model?: string;\n summary_model?: string;\n}\n\nexport class OllamaBackend implements LlmProvider, EmbeddingProvider {\n readonly name = 'ollama';\n private baseUrl: string;\n private model: string;\n private contextWindow: number;\n private defaultMaxTokens: number;\n\n constructor(config?: OllamaConfig) {\n this.baseUrl = config?.base_url ?? 'http://localhost:11434';\n this.model = config?.model ?? config?.summary_model ?? 'llama3.2';\n this.contextWindow = config?.context_window ?? 8192;\n this.defaultMaxTokens = config?.max_tokens ?? 1024;\n }\n\n async summarize(prompt: string, opts?: LlmRequestOptions): Promise<LlmResponse> {\n const maxTokens = opts?.maxTokens ?? this.defaultMaxTokens;\n const promptTokens = Math.ceil(prompt.length / CHARS_PER_TOKEN);\n const numCtx = Math.max(promptTokens + maxTokens, this.contextWindow);\n\n const response = await fetch(`${this.baseUrl}/api/generate`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n prompt,\n stream: false,\n options: { num_ctx: numCtx },\n }),\n signal: AbortSignal.timeout(LLM_REQUEST_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`Ollama summarize failed: ${response.status} ${response.statusText}`);\n }\n\n const data = await response.json() as { response: string; model: string };\n return { text: data.response, model: data.model };\n }\n\n async embed(text: string): Promise<EmbeddingResponse> {\n const response = await fetch(`${this.baseUrl}/api/embed`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n input: text,\n }),\n signal: AbortSignal.timeout(EMBEDDING_REQUEST_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`Ollama embed failed: ${response.status} ${response.statusText}`);\n }\n\n const data = await response.json() as { embeddings: number[][]; model: string };\n const embedding = data.embeddings[0];\n return { embedding, model: data.model, dimensions: embedding.length };\n }\n\n async isAvailable(): Promise<boolean> {\n try {\n const response = await fetch(`${this.baseUrl}/api/tags`, {\n signal: AbortSignal.timeout(DAEMON_CLIENT_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","import type { LlmProvider, EmbeddingProvider, LlmResponse, EmbeddingResponse, LlmRequestOptions } from './llm.js';\nimport { LLM_REQUEST_TIMEOUT_MS, EMBEDDING_REQUEST_TIMEOUT_MS, DAEMON_CLIENT_TIMEOUT_MS } from '../constants.js';\n\ninterface LmStudioConfig {\n model?: string;\n base_url?: string;\n max_tokens?: number;\n // Legacy fields\n embedding_model?: string;\n summary_model?: string;\n}\n\nexport class LmStudioBackend implements LlmProvider, EmbeddingProvider {\n readonly name = 'lm-studio';\n private baseUrl: string;\n private model: string;\n private defaultMaxTokens: number;\n\n constructor(config?: LmStudioConfig) {\n this.baseUrl = config?.base_url ?? 'http://localhost:1234';\n this.model = config?.model ?? config?.summary_model ?? 'llama3.2';\n this.defaultMaxTokens = config?.max_tokens ?? 1024;\n }\n\n async summarize(prompt: string, opts?: LlmRequestOptions): Promise<LlmResponse> {\n const maxTokens = opts?.maxTokens ?? this.defaultMaxTokens;\n\n const response = await fetch(`${this.baseUrl}/v1/chat/completions`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n messages: [{ role: 'user', content: prompt }],\n max_tokens: maxTokens,\n }),\n signal: AbortSignal.timeout(LLM_REQUEST_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`LM Studio summarize failed: ${response.status}`);\n }\n\n const data = await response.json() as {\n choices: Array<{ message: { content: string } }>;\n model: string;\n };\n return { text: data.choices[0].message.content, model: data.model };\n }\n\n async embed(text: string): Promise<EmbeddingResponse> {\n const response = await fetch(`${this.baseUrl}/v1/embeddings`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model: this.model,\n input: text,\n }),\n signal: AbortSignal.timeout(EMBEDDING_REQUEST_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`LM Studio embed failed: ${response.status}`);\n }\n\n const data = await response.json() as {\n data: Array<{ embedding: number[] }>;\n model: string;\n };\n const embedding = data.data[0].embedding;\n return { embedding, model: data.model, dimensions: embedding.length };\n }\n\n async isAvailable(): Promise<boolean> {\n try {\n const response = await fetch(`${this.baseUrl}/v1/models`, {\n signal: AbortSignal.timeout(DAEMON_CLIENT_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n}\n","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\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","// 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';\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 constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) {\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 }\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\n if (status === 400) {\n return new BadRequestError(status, error, message, headers);\n }\n\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers);\n }\n\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers);\n }\n\n if (status === 404) {\n return new NotFoundError(status, error, message, headers);\n }\n\n if (status === 409) {\n return new ConflictError(status, error, message, headers);\n }\n\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers);\n }\n\n if (status === 429) {\n return new RateLimitError(status, error, message, headers);\n }\n\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers);\n }\n\n return new APIError(status, error, message, headers);\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\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","// 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\nexport const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n","export const VERSION = '0.78.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 { HTTPMethod, MergedRequestInit } from './types';\nimport { type HeadersLike } from './headers';\n\nexport type FinalRequestOptions = RequestOptions & { method: HTTPMethod; path: string };\n\nexport type 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 * 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","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 { 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","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { hasOwn } from './values';\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\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 client: BaseAnthropic,\n): LogLevel | undefined => {\n if (!maybeLevel) {\n return undefined;\n }\n if (hasOwn(levelNumbers, maybeLevel)) {\n return maybeLevel;\n }\n loggerFor(client).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\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\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 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() === 'x-api-key' ||\n name.toLowerCase() === 'authorization' ||\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","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';\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 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 ) {\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 throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers);\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 if (props.options.__streamClass) {\n return props.options.__streamClass.fromSSEResponse(response, props.controller) as any;\n }\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","// 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 has_more: boolean;\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 has_more: boolean;\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.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: 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(headers: HeadersLike): IterableIterator<readonly [string, string | null]> {\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 a null to clear the header before adding the new values.\n if (shouldClear && !didClear) {\n didClear = true;\n yield [name, null];\n }\n yield [name, value];\n }\n }\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 (!seenHeaders.has(lowerName)) {\n targetHeaders.delete(name);\n seenHeaders.add(lowerName);\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","/**\n * Shared utilities for tracking SDK helper usage.\n */\n\nimport type { BetaMessageParam, BetaToolUnion } from '../resources/beta';\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: BetaToolUnion[] | undefined,\n messages: BetaMessageParam[] | 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 if (Array.isArray(message.content)) {\n for (const block of message.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: BetaToolUnion[] | undefined,\n messages: BetaMessageParam[] | undefined,\n): { 'x-stainless-helper'?: string } {\n const helpers = collectStainlessHelpers(tools, messages);\n if (helpers.length === 0) return {};\n return { 'x-stainless-helper': 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 { 'x-stainless-helper': file[SDK_HELPER_SYMBOL] };\n }\n return {};\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 { 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 '../../lib/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', 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}`, {\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`, {\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}`, {\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',\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 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\nexport interface FileListParams 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 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 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\nexport interface BetaModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\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 * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\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 BetaModelInfo as BetaModelInfo,\n type BetaModelInfosPage as BetaModelInfosPage,\n type ModelRetrieveParams as ModelRetrieveParams,\n type ModelListParams as ModelListParams,\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 ((char && NUMBERS.test(char)) || char === '.') {\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 (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {\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';\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';\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\nconst JSON_BUF_PROPERTY = '__json_buf';\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, 'X-Stainless-Helper-Method': '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) && content.input) {\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 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 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 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 // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = (snapshotContent as any)[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n\n const newContent = { ...snapshotContent };\n Object.defineProperty(newContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n\n if (jsonBuf) {\n try {\n newContent.input = partialParse(jsonBuf);\n } catch (err) {\n const error = 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 this.#handleError(error);\n }\n }\n snapshot.content[event.index] = newContent;\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 };\n }\n break;\n }\n default:\n checkNever(event.delta);\n }\n return snapshot;\n }\n case 'content_block_stop':\n return snapshot;\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 { 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","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\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 { CompactionControl, DEFAULT_SUMMARY_PROMPT, DEFAULT_TOKEN_THRESHOLD } from './CompactionControl';\nimport { collectStainlessHelpers } from '../stainless-helper-header';\n\n/**\n * Just Promise.withResolvers(), which is not available in all environments.\n */\nfunction promiseWithResolvers<T>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (reason?: any) => void;\n} {\n let resolve: (value: T) => void;\n let reject: (reason?: any) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve: resolve!, reject: reject! };\n}\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 const helpers = collectStainlessHelpers(params.tools, params.messages);\n const helperValue = ['BetaToolRunner', ...helpers].join(', ');\n\n this.#options = {\n ...options,\n headers: buildHeaders([{ 'x-stainless-helper': helperValue }, options?.headers]),\n };\n this.#completion = promiseWithResolvers();\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 headers: { 'x-stainless-helper': '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 { role, content } = await this.#message;\n this.#state.params.messages.push({ role, content });\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 * 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() {\n const message = (await this.#message) ?? this.params.messages.at(-1);\n if (!message) {\n return null;\n }\n return this.#generateToolResponse(message);\n }\n\n async #generateToolResponse(lastMessage: BetaMessageParam) {\n if (this.#toolResponse !== undefined) {\n return this.#toolResponse;\n }\n this.#toolResponse = generateToolResponse(this.#state.params, lastMessage);\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): 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 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 compactionControl?: CompactionControl;\n }\n>;\n\nexport type BetaToolRunnerRequestOptions = Pick<RequestOptions, 'headers'>;\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, ...body } = params;\n return this._client.post('/v1/messages/batches?beta=true', {\n body,\n ...options,\n headers: buildHeaders([\n { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },\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\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 * 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\\nSee\n * [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 * 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 * Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\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 * Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\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 generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { AnthropicError } from '../../../error';\nimport { Anthropic } from '../../../client';\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 '../../../lib/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 MessagesAPI from '../../messages/messages';\nimport * as BetaAPI from '../beta';\nimport * as BatchesAPI from './batches';\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';\nimport * as MessagesMessagesAPI from './messages';\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};\n\nconst MODELS_TO_WARN_WITH_THINKING_ENABLED: Model[] = ['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, ...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 body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED &&\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 { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },\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: 'string', 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\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`.\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 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 cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n file_id: string | null;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface BetaCitationContentBlockLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\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 cited_text: string;\n\n end_block_index: number;\n\n search_result_index: number;\n\n source: string;\n\n start_block_index: number;\n\n title: string | null;\n\n type: 'search_result_location';\n}\n\nexport interface BetaCitationSearchResultLocationParam {\n cited_text: string;\n\n end_block_index: number;\n\n search_result_index: number;\n\n source: string;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 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 /**\n * Summary of previously compacted content, or null if compaction failed\n */\n content: string | null;\n\n type: 'compaction';\n\n /**\n * Create a cache control breakpoint at this content block.\n */\n cache_control?: BetaCacheControlEphemeral | null;\n}\n\nexport interface BetaCompactionContentBlockDelta {\n 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 | BetaCodeExecutionToolResultBlock\n | BetaBashCodeExecutionToolResultBlock\n | BetaTextEditorCodeExecutionToolResultBlock\n | BetaToolSearchToolResultBlock\n | BetaMCPToolUseBlock\n | BetaMCPToolResultBlock\n | BetaContainerUploadBlock\n | BetaCompactionBlock;\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 | BetaCodeExecutionToolResultBlockParam\n | BetaBashCodeExecutionToolResultBlockParam\n | BetaTextEditorCodeExecutionToolResultBlockParam\n | BetaToolSearchToolResultBlockParam\n | BetaMCPToolUseBlockParam\n | BetaRequestMCPToolResultBlockParam\n | BetaContainerUploadBlockParam\n | BetaCompactionBlockParam;\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 * 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\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<BetaMessageIterationUsage | BetaCompactionIterationUsage>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 * The model that will complete your prompt.\\n\\nSee\n * [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 * 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 * 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 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';\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\nexport interface BetaOutputConfig {\n /**\n * All possible effort levels.\n */\n effort?: 'low' | 'medium' | 'high' | '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\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 | BetaCodeExecutionToolResultBlock\n | BetaBashCodeExecutionToolResultBlock\n | BetaTextEditorCodeExecutionToolResultBlock\n | BetaToolSearchToolResultBlock\n | BetaMCPToolUseBlock\n | BetaMCPToolResultBlock\n | BetaContainerUploadBlock\n | BetaCompactionBlock;\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: MessagesMessagesAPI.BetaContainer | null;\n\n stop_reason: MessagesMessagesAPI.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\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 | '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 | '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\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/**\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 thinking: string;\n\n type: 'thinking_delta';\n}\n\nexport interface BetaThinkingTurns {\n type: 'thinking_turns';\n\n value: number;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 | BetaToolComputerUse20241022\n | BetaMemoryTool20250818\n | BetaToolComputerUse20250124\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20251124\n | BetaToolTextEditor20250124\n | BetaToolTextEditor20250429\n | BetaToolTextEditor20250728\n | BetaWebSearchTool20250305\n | BetaWebFetchTool20250910\n | BetaWebSearchTool20260209\n | BetaWebFetchTool20260209\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 * 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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 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_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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 * 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\\nSee\n * [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: 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 * Body param: Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\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 * Body param: Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Body param: Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\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 MessageCreateParams {\n export type MessageCreateParamsNonStreaming = MessagesMessagesAPI.MessageCreateParamsNonStreaming;\n export type MessageCreateParamsStreaming = MessagesMessagesAPI.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\\nSee\n * [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 | BetaToolComputerUse20241022\n | BetaMemoryTool20250818\n | BetaToolComputerUse20250124\n | BetaToolTextEditor20241022\n | BetaToolComputerUse20251124\n | BetaToolTextEditor20250124\n | BetaToolTextEditor20250429\n | BetaToolTextEditor20250728\n | BetaWebSearchTool20250305\n | BetaWebFetchTool20250910\n | BetaWebSearchTool20260209\n | BetaWebFetchTool20260209\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 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 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 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 BetaDirectCaller as BetaDirectCaller,\n type BetaDocumentBlock as BetaDocumentBlock,\n type BetaEncryptedCodeExecutionResultBlock as BetaEncryptedCodeExecutionResultBlock,\n type BetaEncryptedCodeExecutionResultBlockParam as BetaEncryptedCodeExecutionResultBlockParam,\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 BetaOutputConfig as BetaOutputConfig,\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 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 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 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 { 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 ),\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\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 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 };\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 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 };\n}\n","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../../core/resource';\nimport * as FilesAPI from './files';\nimport {\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 { BetaModelInfo, BetaModelInfosPage, ModelListParams, ModelRetrieveParams, Models } from './models';\nimport * as MessagesAPI from './messages/messages';\nimport {\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 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 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 BetaDirectCaller,\n BetaDocumentBlock,\n BetaEncryptedCodeExecutionResultBlock,\n BetaEncryptedCodeExecutionResultBlockParam,\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 BetaOutputConfig,\n BetaPlainTextSource,\n BetaRawContentBlockDelta,\n BetaRawContentBlockDeltaEvent,\n BetaRawContentBlockStartEvent,\n BetaRawContentBlockStopEvent,\n BetaRawMessageDeltaEvent,\n BetaRawMessageStartEvent,\n BetaRawMessageStopEvent,\n BetaRawMessageStreamEvent,\n BetaRedactedThinkingBlock,\n BetaRedactedThinkingBlockParam,\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 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 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 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';\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 files: FilesAPI.Files = new FilesAPI.Files(this._client);\n skills: SkillsAPI.Skills = new SkillsAPI.Skills(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\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.Files = Files;\nBeta.Skills = Skills;\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 BetaModelInfo as BetaModelInfo,\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 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 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 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 BetaDirectCaller as BetaDirectCaller,\n type BetaDocumentBlock as BetaDocumentBlock,\n type BetaEncryptedCodeExecutionResultBlock as BetaEncryptedCodeExecutionResultBlock,\n type BetaEncryptedCodeExecutionResultBlockParam as BetaEncryptedCodeExecutionResultBlockParam,\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 BetaOutputConfig as BetaOutputConfig,\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 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 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 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 Files as Files,\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","// 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-opus-4-6',\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\\nSee\n * [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\\nSee\n * [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 * Body param: Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\n */\n temperature?: number;\n\n /**\n * Body param: Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Body param: Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\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 { 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 { partialParse } from '../_vendor/partial-json-parser/parser';\nimport { RequestOptions } from '../internal/request-options';\nimport type { Logger } from '../client';\nimport { maybeParseMessage, type ParsedMessage } from './parser';\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\nconst JSON_BUF_PROPERTY = '__json_buf';\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, 'X-Stainless-Helper-Method': '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) && content.input) {\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 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 // we need to keep track of the raw JSON string as well so that we can\n // re-parse it for each delta, for now we just store it as an untyped\n // non-enumerable property on the snapshot\n let jsonBuf = (snapshotContent as any)[JSON_BUF_PROPERTY] || '';\n jsonBuf += event.delta.partial_json;\n\n const newContent = { ...snapshotContent };\n Object.defineProperty(newContent, JSON_BUF_PROPERTY, {\n value: jsonBuf,\n enumerable: false,\n writable: true,\n });\n\n if (jsonBuf) {\n newContent.input = partialParse(jsonBuf);\n }\n snapshot.content[event.index] = newContent;\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 return snapshot;\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(body: BatchCreateParams, options?: RequestOptions): APIPromise<MessageBatch> {\n return this._client.post('/v1/messages/batches', { body, ...options });\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 * List of requests for prompt completion. Each is an individual request to create\n * a Message.\n */\n requests: Array<BatchCreateParams.Request>;\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 '../../lib/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(body: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Message>;\n create(\n body: MessageCreateParamsStreaming,\n options?: RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent>>;\n create(\n body: MessageCreateParamsBase,\n options?: RequestOptions,\n ): APIPromise<Stream<RawMessageStreamEvent> | Message>;\n create(\n body: MessageCreateParams,\n options?: RequestOptions,\n ): APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>> {\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 body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED &&\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', {\n body,\n timeout: timeout ?? 600000,\n ...options,\n headers: buildHeaders([helperHeader, options?.headers]),\n stream: body.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: 'string', 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`.\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 cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\n\n file_id: string | null;\n\n start_block_index: number;\n\n type: 'content_block_location';\n}\n\nexport interface CitationContentBlockLocationParam {\n cited_text: string;\n\n document_index: number;\n\n document_title: string | null;\n\n end_block_index: number;\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 cited_text: string;\n\n end_block_index: number;\n\n search_result_index: number;\n\n source: string;\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 cited_text: string;\n\n end_block_index: number;\n\n search_result_index: number;\n\n source: string;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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\\nSee\n * [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 * 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 | MemoryTool20250818\n | ToolTextEditor20250124\n | ToolTextEditor20250429\n | ToolTextEditor20250728\n | WebSearchTool20250305\n | WebFetchTool20250910\n | WebSearchTool20260209\n | WebFetchTool20260209\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 * 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';\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 * The model that will complete your prompt.\\n\\nSee\n * [models](https://docs.anthropic.com/en/docs/models-overview) for additional\n * details and options.\n */\nexport type Model =\n | 'claude-opus-4-6'\n | 'claude-sonnet-4-6'\n | 'claude-opus-4-5-20251101'\n | 'claude-opus-4-5'\n | 'claude-3-7-sonnet-latest'\n | 'claude-3-7-sonnet-20250219'\n | 'claude-3-5-haiku-latest'\n | 'claude-3-5-haiku-20241022'\n | 'claude-haiku-4-5'\n | 'claude-haiku-4-5-20251001'\n | 'claude-sonnet-4-20250514'\n | 'claude-sonnet-4-0'\n | 'claude-4-sonnet-20250514'\n | 'claude-sonnet-4-5'\n | 'claude-sonnet-4-5-20250929'\n | 'claude-opus-4-0'\n | 'claude-opus-4-20250514'\n | 'claude-4-opus-20250514'\n | 'claude-opus-4-1-20250805'\n | 'claude-3-opus-latest'\n | 'claude-3-opus-20240229'\n | 'claude-3-haiku-20240307'\n | (string & {});\n\nexport interface OutputConfig {\n /**\n * All possible effort levels.\n */\n effort?: 'low' | 'medium' | 'high' | '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\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};\n\nconst MODELS_TO_WARN_WITH_THINKING_ENABLED: Model[] = ['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 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\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\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/**\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 | MemoryTool20250818\n | ToolTextEditor20250124\n | ToolTextEditor20250429\n | ToolTextEditor20250728\n | WebSearchTool20250305\n | WebFetchTool20250910\n | WebSearchTool20260209\n | WebFetchTool20260209\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 * 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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 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_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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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<'direct' | 'code_execution_20250825' | 'code_execution_20260120'>;\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 * 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 * 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<MessageParam>;\n\n /**\n * The model that will complete your prompt.\\n\\nSee\n * [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 * Container identifier for reuse across requests.\n */\n container?: string | 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 * An object describing metadata about the request.\n */\n metadata?: Metadata;\n\n /**\n * Configuration options for the model's output, such as the output format.\n */\n output_config?: OutputConfig;\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 * 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<TextBlockParam>;\n\n /**\n * Amount of randomness injected into the response.\n *\n * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0`\n * for analytical / multiple choice, and closer to `1.0` for creative and\n * generative tasks.\n *\n * Note that even with `temperature` of `0.0`, the results will not be fully\n * deterministic.\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?: 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<ToolUnion>;\n\n /**\n * Only sample from the top K options for each subsequent token.\n *\n * Used to remove \"long tail\" low probability responses.\n * [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_k?: number;\n\n /**\n * Use nucleus sampling.\n *\n * In nucleus sampling, we compute the cumulative distribution over all the options\n * for each subsequent token in decreasing probability order and cut it off once it\n * reaches a particular probability specified by `top_p`. You should either alter\n * `temperature` or `top_p`, but not both.\n *\n * Recommended for advanced use cases only. You usually only need to use\n * `temperature`.\n */\n top_p?: number;\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 * 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?: false;\n}\n\nexport interface MessageCreateParamsStreaming extends MessageCreateParamsBase {\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: 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\\nSee\n * [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 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 Model as Model,\n type OutputConfig as OutputConfig,\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 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 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\nexport interface ModelInfo {\n /**\n * Unique model identifier.\n */\n id: string;\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 * Object type.\n *\n * For Models, this is always `\"model\"`.\n */\n type: 'model';\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 ModelInfo as ModelInfo,\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\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();\n }\n return undefined;\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 { VERSION } from './version';\nimport * as Errors from './core/error';\nimport * as Pagination from './core/pagination';\nimport {\n type PageParams,\n PageResponse,\n type PageCursorParams,\n PageCursorResponse,\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 { ModelInfo, ModelInfosPage, ModelListParams, ModelRetrieveParams, Models } 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 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 Model,\n OutputConfig,\n PlainTextSource,\n RawContentBlockDelta,\n RawContentBlockDeltaEvent,\n RawContentBlockStartEvent,\n RawContentBlockStopEvent,\n RawMessageDeltaEvent,\n RawMessageStartEvent,\n RawMessageStopEvent,\n RawMessageStreamEvent,\n RedactedThinkingBlock,\n RedactedThinkingBlockParam,\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 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 formatRequestDetails,\n loggerFor,\n parseLogLevel,\n} from './internal/utils/log';\nimport { isEmptyObj } from './internal/utils/values';\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 * 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 * 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\n baseURL: string;\n maxRetries: number;\n timeout: number;\n logger: Logger;\n logLevel: LogLevel | undefined;\n fetchOptions: MergedRequestInit | undefined;\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} [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 = readEnv('ANTHROPIC_API_KEY') ?? null,\n authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null,\n ...opts\n }: ClientOptions = {}) {\n const options: ClientOptions = {\n apiKey,\n authToken,\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 this.timeout = options.timeout ?? BaseAnthropic.DEFAULT_TIMEOUT /* 10 minutes */;\n this.logger = options.logger ?? console;\n const defaultLogLevel = 'warn';\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', this) ??\n parseLogLevel(readEnv('ANTHROPIC_LOG'), \"process.env['ANTHROPIC_LOG']\", 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._options = options;\n\n this.apiKey = typeof apiKey === 'string' ? apiKey : null;\n this.authToken = authToken;\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 const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({\n ...this._options,\n 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 apiKey: this.apiKey,\n authToken: this.authToken,\n ...options,\n });\n return client;\n }\n\n /**\n * Check whether the base URL is set to its default.\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\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 either apiKey or authToken to be set. Or for one of the \"X-Api-Key\" or \"Authorization\" headers to be explicitly omitted',\n );\n }\n\n protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {\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 /**\n * Basic re-implementation of `qs.stringify` for primitive types.\n */\n protected stringifyQuery(query: Record<string, unknown>): string {\n return Object.entries(query)\n .filter(([_, value]) => typeof value !== 'undefined')\n .map(([key, value]) => {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n }\n if (value === null) {\n return `${encodeURIComponent(key)}=`;\n }\n throw new Errors.AnthropicError(\n `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`,\n );\n })\n .join('&');\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 if (!isEmptyObj(defaultQuery)) {\n query = { ...defaultQuery, ...query };\n }\n\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query as Record<string, unknown>);\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 protected async prepareRequest(\n request: RequestInit,\n { url, options }: { url: string; options: FinalRequestOptions },\n ): Promise<void> {}\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 }\n\n await this.prepareOptions(options);\n\n const { req, url, timeout } = await this.buildRequest(options, {\n retryCount: maxRetries - retriesRemaining,\n });\n\n await this.prepareRequest(req, { url, options });\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 loggerFor(this).debug(\n `[${requestLogID}] sending request`,\n formatRequestDetails({\n retryOfRequestLogID,\n method: options.method,\n url,\n options,\n headers: req.headers,\n }),\n );\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).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 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 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);\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 ): 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 timeout = setTimeout(abort, ms);\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 try {\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n return await this.fetch.call(undefined, url, fetchOptions);\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private async shouldRetry(response: Response): Promise<boolean> {\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 (and it's a reasonable amount),\n // just do what it says, but otherwise calculate a default\n if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\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 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 as Record<string, unknown>),\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\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 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 Model as Model,\n type OutputConfig as OutputConfig,\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 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 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 ModelInfo as ModelInfo,\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 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 Anthropic from '@anthropic-ai/sdk';\nimport type { LlmProvider, LlmResponse, EmbeddingResponse, LlmRequestOptions } from './llm.js';\nimport { LLM_REQUEST_TIMEOUT_MS } from '../constants.js';\n\ninterface AnthropicConfig {\n model?: string;\n // Legacy fields\n summary_model?: string;\n embedding_provider?: string;\n}\n\nexport class AnthropicBackend implements LlmProvider {\n readonly name = 'anthropic';\n private client: Anthropic;\n private model: string;\n\n constructor(config?: AnthropicConfig) {\n this.client = new Anthropic();\n this.model = config?.model ?? config?.summary_model ?? 'claude-haiku-4-5-20251001';\n }\n\n async summarize(prompt: string, opts?: LlmRequestOptions): Promise<LlmResponse> {\n const maxTokens = opts?.maxTokens ?? 1024;\n\n const response = await this.client.messages.create({\n model: this.model,\n max_tokens: maxTokens,\n messages: [{ role: 'user', content: prompt }],\n }, { timeout: LLM_REQUEST_TIMEOUT_MS });\n\n const text = response.content\n .filter((block): block is Anthropic.TextBlock => block.type === 'text')\n .map((block) => block.text)\n .join('');\n\n return { text, model: this.model };\n }\n\n async embed(_text: string): Promise<EmbeddingResponse> {\n throw new Error(\n 'AnthropicBackend does not support embeddings. Use a local provider (Ollama or LM Studio) for embeddings.'\n );\n }\n\n async isAvailable(): Promise<boolean> {\n try {\n return !!process.env.ANTHROPIC_API_KEY;\n } catch {\n return false;\n }\n }\n}\n","import { OllamaBackend } from './ollama.js';\nimport { LmStudioBackend } from './lm-studio.js';\nimport { AnthropicBackend } from './anthropic.js';\n\nexport interface LlmRequestOptions {\n maxTokens?: number;\n}\n\nexport interface LlmResponse {\n text: string;\n model: string;\n}\n\nexport interface EmbeddingResponse {\n embedding: number[];\n model: string;\n dimensions: number;\n}\n\nexport interface LlmProvider {\n name: string;\n summarize(prompt: string, opts?: LlmRequestOptions): Promise<LlmResponse>;\n isAvailable(): Promise<boolean>;\n}\n\nexport interface EmbeddingProvider {\n name: string;\n embed(text: string): Promise<EmbeddingResponse>;\n isAvailable(): Promise<boolean>;\n}\n\ninterface ProviderConfig {\n provider: string;\n model: string;\n base_url?: string;\n context_window?: number;\n max_tokens?: number;\n}\n\nexport function createLlmProvider(config: ProviderConfig): LlmProvider {\n switch (config.provider) {\n case 'ollama':\n return new OllamaBackend(config);\n case 'lm-studio':\n return new LmStudioBackend(config);\n case 'anthropic':\n return new AnthropicBackend(config);\n default:\n throw new Error(`Unknown LLM provider: ${config.provider}`);\n }\n}\n\nexport function createEmbeddingProvider(config: ProviderConfig): EmbeddingProvider {\n switch (config.provider) {\n case 'ollama':\n return new OllamaBackend(config);\n case 'lm-studio':\n return new LmStudioBackend(config);\n default:\n throw new Error(`Provider \"${config.provider}\" does not support embeddings. Use ollama or lm-studio.`);\n }\n}\n","import Database from 'better-sqlite3';\nimport * as sqliteVec from 'sqlite-vec';\n\nexport interface VectorSearchResult {\n id: string;\n similarity: number;\n metadata: Record<string, string>;\n}\n\nexport interface VectorSearchOptions {\n limit?: number;\n /** Drop results below this fraction of the top result's score (0-1). Default 0.5. */\n relativeThreshold?: number;\n type?: string;\n importance?: string;\n}\n\nexport class VectorIndex {\n private db: Database.Database;\n private dimensions: number;\n\n constructor(dbPath: string, dimensions: number) {\n this.dimensions = dimensions;\n this.db = new Database(dbPath);\n sqliteVec.load(this.db);\n this.init();\n }\n\n private init(): void {\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS vec_metadata (\n id TEXT PRIMARY KEY,\n type TEXT NOT NULL DEFAULT '',\n importance TEXT NOT NULL DEFAULT '',\n session_id TEXT NOT NULL DEFAULT '',\n file_path TEXT NOT NULL DEFAULT '',\n branch TEXT NOT NULL DEFAULT '',\n created TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE VIRTUAL TABLE IF NOT EXISTS vec_embeddings USING vec0(\n id TEXT PRIMARY KEY,\n embedding float[${this.dimensions}]\n );\n `);\n }\n\n upsert(id: string, embedding: number[], metadata: Record<string, string> = {}): void {\n this.db.prepare('DELETE FROM vec_metadata WHERE id = ?').run(id);\n this.db.prepare('DELETE FROM vec_embeddings WHERE id = ?').run(id);\n\n this.db.prepare(\n 'INSERT INTO vec_metadata (id, type, importance, session_id, file_path, branch) VALUES (?, ?, ?, ?, ?, ?)',\n ).run(id, metadata.type ?? '', metadata.importance ?? '', metadata.session_id ?? '', metadata.file_path ?? '', metadata.branch ?? '');\n\n this.db.prepare('INSERT INTO vec_embeddings (id, embedding) VALUES (?, ?)').run(id, new Float32Array(embedding));\n }\n\n search(query: number[], options: VectorSearchOptions = {}): VectorSearchResult[] {\n const limit = options.limit ?? 10;\n\n // vec0 KNN queries require LIMIT to be a direct constraint on the virtual table.\n // JOINs with additional WHERE filters confuse the query planner, so we use a\n // subquery to get KNN candidates first, then filter by metadata in the outer query.\n const knnParams: unknown[] = [new Float32Array(query), limit * 4];\n const knnRows = this.db.prepare(`\n SELECT id, distance\n FROM vec_embeddings\n WHERE embedding MATCH ?\n ORDER BY distance\n LIMIT ?\n `).all(...knnParams) as Array<{ id: string; distance: number }>;\n\n if (knnRows.length === 0) return [];\n\n // Now fetch metadata for the candidates and apply optional filters\n const metaConditions: string[] = ['id IN (' + knnRows.map(() => '?').join(',') + ')'];\n const metaParams: unknown[] = knnRows.map((r) => r.id);\n\n if (options.type) { metaConditions.push('type = ?'); metaParams.push(options.type); }\n if (options.importance) { metaConditions.push('importance = ?'); metaParams.push(options.importance); }\n\n const metaRows = this.db.prepare(`\n SELECT id, type, importance, session_id, file_path, branch\n FROM vec_metadata\n WHERE ${metaConditions.join(' AND ')}\n `).all(...metaParams) as Array<{ id: string; type: string; importance: string; session_id: string; file_path: string; branch: string }>;\n\n const metaMap = new Map(metaRows.map((m) => [m.id, m]));\n\n const scored = knnRows\n .filter((r) => metaMap.has(r.id))\n .map((r) => {\n const m = metaMap.get(r.id)!;\n return {\n id: r.id,\n similarity: 1 - r.distance,\n metadata: { type: m.type, importance: m.importance, session_id: m.session_id, file_path: m.file_path, branch: m.branch },\n };\n });\n\n if (scored.length === 0) return [];\n\n // Relative threshold: drop results below a fraction of the best score.\n // Adapts automatically to any embedding model's score distribution.\n const topScore = scored[0].similarity;\n const threshold = options.relativeThreshold ?? 0.5;\n const floor = topScore * threshold;\n\n return scored\n .filter((r) => r.similarity >= floor)\n .slice(0, limit);\n }\n\n delete(id: string): void {\n this.db.prepare('DELETE FROM vec_metadata WHERE id = ?').run(id);\n this.db.prepare('DELETE FROM vec_embeddings WHERE id = ?').run(id);\n }\n\n count(): number {\n return (this.db.prepare('SELECT COUNT(*) as c FROM vec_metadata').get() as { c: number }).c;\n }\n\n close(): void { this.db.close(); }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA,kCAAAA,UAAAC,SAAA;AAAA;AAAA,QAAI,WAAW,OAAO,UAAU;AAEhC,IAAAA,QAAO,UAAU,SAAS,OAAO,KAAK;AACpC,UAAI,QAAQ,OAAQ,QAAO;AAC3B,UAAI,QAAQ,KAAM,QAAO;AAEzB,UAAI,OAAO,OAAO;AAClB,UAAI,SAAS,UAAW,QAAO;AAC/B,UAAI,SAAS,SAAU,QAAO;AAC9B,UAAI,SAAS,SAAU,QAAO;AAC9B,UAAI,SAAS,SAAU,QAAO;AAC9B,UAAI,SAAS,YAAY;AACvB,eAAO,cAAc,GAAG,IAAI,sBAAsB;AAAA,MACpD;AAEA,UAAIC,SAAQ,GAAG,EAAG,QAAO;AACzB,UAAI,SAAS,GAAG,EAAG,QAAO;AAC1B,UAAI,YAAY,GAAG,EAAG,QAAO;AAC7B,UAAI,OAAO,GAAG,EAAG,QAAO;AACxB,UAAI,QAAQ,GAAG,EAAG,QAAO;AACzB,UAAI,SAAS,GAAG,EAAG,QAAO;AAE1B,cAAQ,SAAS,GAAG,GAAG;AA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,QAAI,OAAO,WAAW,EAAG,QAAO,CAAC;AAIjC,UAAM,WAAW,OAAO,CAAC,EAAE;AAC3B,UAAM,YAAYA,SAAQ,qBAAqB;AAC/C,UAAM,QAAQ,WAAW;AAEzB,WAAO,OACJ,OAAO,CAAC,MAAM,EAAE,cAAc,KAAK,EACnC,MAAM,GAAG,KAAK;AAAA,EACnB;AAAA,EAEA,OAAO,IAAkB;AACvB,SAAK,GAAG,QAAQ,uCAAuC,EAAE,IAAI,EAAE;AAC/D,SAAK,GAAG,QAAQ,yCAAyC,EAAE,IAAI,EAAE;AAAA,EACnE;AAAA,EAEA,QAAgB;AACd,WAAQ,KAAK,GAAG,QAAQ,wCAAwC,EAAE,IAAI,EAAoB;AAAA,EAC5F;AAAA,EAEA,QAAc;AAAE,SAAK,GAAG,MAAM;AAAA,EAAG;AACnC;","names":["exports","module","isArray","exports","module","exports","module","hasOwn","exports","module","options","exports","module","exports","module","exports","module","exports","module","options","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","exports","module","options","load","exports","module","options","str","string","exports","module","require_js_yaml","exports","module","yaml","options","exports","module","str","exports","str","exports","module","engines","options","exports","module","options","exports","module","options","str","matter","exports","module","options","exports","module","options","exports","module","str","options","exports","module","fs","engines","toFile","parse","matter","options","str","options","matter","fs","path","options","str","str","options","Page","client","options","process","options","fetch","options","options","str","path","options","path","options","path","options","_BetaMessageStream_getFinalMessage","_BetaMessageStream_getFinalText","_BetaMessageStream_beginRequest","_BetaMessageStream_addStreamEvent","_BetaMessageStream_endRequest","_BetaMessageStream_accumulateMessage","chunk","options","_BetaToolRunner_checkAndCompact","_a","_BetaToolRunner_generateToolResponse","options","path","options","options","path","options","path","options","getOutputFormat","JSON_BUF_PROPERTY","tracksToolInput","options","_MessageStream_getFinalMessage","_MessageStream_getFinalText","_MessageStream_beginRequest","_MessageStream_addStreamEvent","checkNever","_MessageStream_endRequest","_MessageStream_accumulateMessage","chunk","Batches","options","path","Messages","Batches","options","DEPRECATED_MODELS","MODELS_TO_WARN_WITH_THINKING_ENABLED","Models","options","path","options","path","opts","retryMessage","err","Page","Messages","Models","options"]}
|