first commit
SAP-ERP Portal CI/CD / build (push) Failing after 5m20s

This commit is contained in:
John
2026-09-23 17:31:02 +05:30
commit 69b4e68baf
51657 changed files with 3864077 additions and 0 deletions
@@ -0,0 +1,3 @@
<svg width="248" height="248" viewBox="0 0 248 248" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M52.4285 162.873L98.7844 136.879L99.5485 134.602L98.7844 133.334H96.4921L88.7237 132.862L62.2346 132.153L39.3113 131.207L17.0249 130.026L11.4214 128.844L6.2 121.873L6.7094 118.447L11.4214 115.257L18.171 115.847L33.0711 116.911L55.485 118.447L71.6586 119.392L95.728 121.873H99.5485L100.058 120.337L98.7844 119.392L97.7656 118.447L74.5877 102.732L49.4995 86.1905L36.3823 76.62L29.3779 71.7757L25.8121 67.2858L24.2839 57.3608L30.6515 50.2716L39.3113 50.8623L41.4763 51.4531L50.2636 58.1879L68.9842 72.7209L93.4357 90.6804L97.0015 93.6343L98.4374 92.6652L98.6571 91.9801L97.0015 89.2625L83.757 65.2772L69.621 40.8192L63.2534 30.6579L61.5978 24.632C60.9565 22.1032 60.579 20.0111 60.579 17.4246L67.8381 7.49965L71.9133 6.19995L81.7193 7.49965L85.7946 11.0443L91.9074 24.9865L101.714 46.8451L116.996 76.62L121.453 85.4816L123.873 93.6343L124.764 96.1155H126.292V94.6976L127.566 77.9197L129.858 57.3608L132.15 30.8942L132.915 23.4505L136.608 14.4708L143.994 9.62643L149.725 12.344L154.437 19.0788L153.8 23.4505L150.998 41.6463L145.522 70.1215L141.957 89.2625H143.994L146.414 86.7813L156.093 74.0206L172.266 53.698L179.398 45.6635L187.803 36.802L193.152 32.5484H203.34L210.726 43.6549L207.415 55.1159L196.972 68.3492L188.312 79.5739L175.896 96.2095L168.191 109.585L168.882 110.689L170.738 110.53L198.755 104.504L213.91 101.787L231.994 98.7149L240.144 102.496L241.036 106.395L237.852 114.311L218.495 119.037L195.826 123.645L162.07 131.592L161.696 131.893L162.137 132.547L177.36 133.925L183.855 134.279H199.774L229.447 136.524L237.215 141.605L241.8 147.867L241.036 152.711L229.065 158.737L213.019 154.956L175.45 145.977L162.587 142.787H160.805V143.85L171.502 154.366L191.242 172.089L215.82 195.011L217.094 200.682L213.91 205.172L210.599 204.699L188.949 188.394L180.544 181.069L161.696 165.118H160.422V166.772L164.752 173.152L187.803 207.771L188.949 218.405L187.294 221.832L181.308 223.959L174.813 222.777L161.187 203.754L147.305 182.486L136.098 163.345L134.745 164.2L128.075 235.42L125.019 239.082L117.887 241.8L111.902 237.31L108.718 229.984L111.902 215.452L115.722 196.547L118.779 181.541L121.58 162.873L123.291 156.636L123.14 156.219L121.773 156.449L107.699 175.752L86.304 204.699L69.3663 222.777L65.291 224.431L58.2867 220.768L58.9235 214.27L62.8713 208.48L86.304 178.705L100.44 160.155L109.551 149.507L109.462 147.967L108.959 147.924L46.6977 188.512L35.6182 189.93L30.7788 185.44L31.4156 178.115L33.7079 175.752L52.4285 162.873Z" fill="#D97757"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
Copyright 2023 Anthropic, PBC.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,45 @@
# <img src=".github/logo.svg" alt="" width="32"> Claude SDK for TypeScript
[![NPM version](https://img.shields.io/npm/v/@anthropic-ai/sdk.svg)](https://npmjs.org/package/@anthropic-ai/sdk)
The Claude SDK for TypeScript provides access to the [Claude API](https://docs.anthropic.com/en/api/) from server-side TypeScript or JavaScript applications.
## Documentation
Full documentation is available at **[platform.claude.com/docs/en/api/sdks/typescript](https://platform.claude.com/docs/en/api/sdks/typescript)**.
## Installation
```sh
npm install @anthropic-ai/sdk
```
## Getting started
```js
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env['ANTHROPIC_API_KEY'], // This is the default and can be omitted
});
const message = await client.messages.create({
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude' }],
model: 'claude-opus-4-6',
});
console.log(message.content);
```
## Requirements
Node.js 18+
## Contributing
See [CONTRIBUTING.md](./CONTRIBUTING.md).
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,3 @@
declare const partialParse: (input: string) => unknown;
export { partialParse };
//# sourceMappingURL=parser.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"parser.d.mts","sourceRoot":"","sources":["../../src/_vendor/partial-json-parser/parser.ts"],"names":[],"mappings":"AAKA,QAAA,MAgQE,YAAY,GAAI,OAAO,MAAM,KAAG,OAAgE,CAAC;AAEnG,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,3 @@
declare const partialParse: (input: string) => unknown;
export { partialParse };
//# sourceMappingURL=parser.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../src/_vendor/partial-json-parser/parser.ts"],"names":[],"mappings":"AAKA,QAAA,MAgQE,YAAY,GAAI,OAAO,MAAM,KAAG,OAAgE,CAAC;AAEnG,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,226 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.partialParse = void 0;
const tokenize = (input) => {
let current = 0;
let tokens = [];
while (current < input.length) {
let char = input[current];
if (char === '\\') {
current++;
continue;
}
if (char === '{') {
tokens.push({
type: 'brace',
value: '{',
});
current++;
continue;
}
if (char === '}') {
tokens.push({
type: 'brace',
value: '}',
});
current++;
continue;
}
if (char === '[') {
tokens.push({
type: 'paren',
value: '[',
});
current++;
continue;
}
if (char === ']') {
tokens.push({
type: 'paren',
value: ']',
});
current++;
continue;
}
if (char === ':') {
tokens.push({
type: 'separator',
value: ':',
});
current++;
continue;
}
if (char === ',') {
tokens.push({
type: 'delimiter',
value: ',',
});
current++;
continue;
}
if (char === '"') {
let value = '';
let danglingQuote = false;
char = input[++current];
while (char !== '"') {
if (current === input.length) {
danglingQuote = true;
break;
}
if (char === '\\') {
current++;
if (current === input.length) {
danglingQuote = true;
break;
}
value += char + input[current];
char = input[++current];
}
else {
value += char;
char = input[++current];
}
}
char = input[++current];
if (!danglingQuote) {
tokens.push({
type: 'string',
value,
});
}
continue;
}
let WHITESPACE = /\s/;
if (char && WHITESPACE.test(char)) {
current++;
continue;
}
let NUMBERS = /[0-9]/;
if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {
let value = '';
if (char === '-') {
value += char;
char = input[++current];
}
while ((char && NUMBERS.test(char)) || char === '.') {
value += char;
char = input[++current];
}
tokens.push({
type: 'number',
value,
});
continue;
}
let LETTERS = /[a-z]/i;
if (char && LETTERS.test(char)) {
let value = '';
while (char && LETTERS.test(char)) {
if (current === input.length) {
break;
}
value += char;
char = input[++current];
}
if (value == 'true' || value == 'false' || value === 'null') {
tokens.push({
type: 'name',
value,
});
}
else {
// unknown token, e.g. `nul` which isn't quite `null`
current++;
continue;
}
continue;
}
current++;
}
return tokens;
}, strip = (tokens) => {
if (tokens.length === 0) {
return tokens;
}
let lastToken = tokens[tokens.length - 1];
switch (lastToken.type) {
case 'separator':
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
break;
case 'number':
let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
case 'string':
let tokenBeforeTheLastToken = tokens[tokens.length - 2];
if (tokenBeforeTheLastToken?.type === 'delimiter') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
break;
case 'delimiter':
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
break;
}
return tokens;
}, unstrip = (tokens) => {
let tail = [];
tokens.map((token) => {
if (token.type === 'brace') {
if (token.value === '{') {
tail.push('}');
}
else {
tail.splice(tail.lastIndexOf('}'), 1);
}
}
if (token.type === 'paren') {
if (token.value === '[') {
tail.push(']');
}
else {
tail.splice(tail.lastIndexOf(']'), 1);
}
}
});
if (tail.length > 0) {
tail.reverse().map((item) => {
if (item === '}') {
tokens.push({
type: 'brace',
value: '}',
});
}
else if (item === ']') {
tokens.push({
type: 'paren',
value: ']',
});
}
});
}
return tokens;
}, generate = (tokens) => {
let output = '';
tokens.map((token) => {
switch (token.type) {
case 'string':
output += '"' + token.value + '"';
break;
default:
output += token.value;
break;
}
});
return output;
}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
exports.partialParse = partialParse;
//# sourceMappingURL=parser.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,223 @@
const tokenize = (input) => {
let current = 0;
let tokens = [];
while (current < input.length) {
let char = input[current];
if (char === '\\') {
current++;
continue;
}
if (char === '{') {
tokens.push({
type: 'brace',
value: '{',
});
current++;
continue;
}
if (char === '}') {
tokens.push({
type: 'brace',
value: '}',
});
current++;
continue;
}
if (char === '[') {
tokens.push({
type: 'paren',
value: '[',
});
current++;
continue;
}
if (char === ']') {
tokens.push({
type: 'paren',
value: ']',
});
current++;
continue;
}
if (char === ':') {
tokens.push({
type: 'separator',
value: ':',
});
current++;
continue;
}
if (char === ',') {
tokens.push({
type: 'delimiter',
value: ',',
});
current++;
continue;
}
if (char === '"') {
let value = '';
let danglingQuote = false;
char = input[++current];
while (char !== '"') {
if (current === input.length) {
danglingQuote = true;
break;
}
if (char === '\\') {
current++;
if (current === input.length) {
danglingQuote = true;
break;
}
value += char + input[current];
char = input[++current];
}
else {
value += char;
char = input[++current];
}
}
char = input[++current];
if (!danglingQuote) {
tokens.push({
type: 'string',
value,
});
}
continue;
}
let WHITESPACE = /\s/;
if (char && WHITESPACE.test(char)) {
current++;
continue;
}
let NUMBERS = /[0-9]/;
if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {
let value = '';
if (char === '-') {
value += char;
char = input[++current];
}
while ((char && NUMBERS.test(char)) || char === '.') {
value += char;
char = input[++current];
}
tokens.push({
type: 'number',
value,
});
continue;
}
let LETTERS = /[a-z]/i;
if (char && LETTERS.test(char)) {
let value = '';
while (char && LETTERS.test(char)) {
if (current === input.length) {
break;
}
value += char;
char = input[++current];
}
if (value == 'true' || value == 'false' || value === 'null') {
tokens.push({
type: 'name',
value,
});
}
else {
// unknown token, e.g. `nul` which isn't quite `null`
current++;
continue;
}
continue;
}
current++;
}
return tokens;
}, strip = (tokens) => {
if (tokens.length === 0) {
return tokens;
}
let lastToken = tokens[tokens.length - 1];
switch (lastToken.type) {
case 'separator':
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
break;
case 'number':
let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
case 'string':
let tokenBeforeTheLastToken = tokens[tokens.length - 2];
if (tokenBeforeTheLastToken?.type === 'delimiter') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
break;
case 'delimiter':
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
break;
}
return tokens;
}, unstrip = (tokens) => {
let tail = [];
tokens.map((token) => {
if (token.type === 'brace') {
if (token.value === '{') {
tail.push('}');
}
else {
tail.splice(tail.lastIndexOf('}'), 1);
}
}
if (token.type === 'paren') {
if (token.value === '[') {
tail.push(']');
}
else {
tail.splice(tail.lastIndexOf(']'), 1);
}
}
});
if (tail.length > 0) {
tail.reverse().map((item) => {
if (item === '}') {
tokens.push({
type: 'brace',
value: '}',
});
}
else if (item === ']') {
tokens.push({
type: 'paren',
value: ']',
});
}
});
}
return tokens;
}, generate = (tokens) => {
let output = '';
tokens.map((token) => {
switch (token.type) {
case 'string':
output += '"' + token.value + '"';
break;
default:
output += token.value;
break;
}
});
return output;
}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
export { partialParse };
//# sourceMappingURL=parser.mjs.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
export * from "./core/api-promise.mjs";
//# sourceMappingURL=api-promise.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.d.mts","sourceRoot":"","sources":["src/api-promise.ts"],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
export * from "./core/api-promise.js";
//# sourceMappingURL=api-promise.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.d.ts","sourceRoot":"","sources":["src/api-promise.ts"],"names":[],"mappings":""}
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("./internal/tslib.js");
/** @deprecated Import from ./core/api-promise instead */
tslib_1.__exportStar(require("./core/api-promise.js"), exports);
//# sourceMappingURL=api-promise.js.map
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.js","sourceRoot":"","sources":["src/api-promise.ts"],"names":[],"mappings":";;;AAAA,yDAAyD;AACzD,gEAAmC"}
@@ -0,0 +1,2 @@
export * from "./core/api-promise.mjs";
//# sourceMappingURL=api-promise.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.mjs","sourceRoot":"","sources":["src/api-promise.ts"],"names":[],"mappings":""}
@@ -0,0 +1,53 @@
#!/usr/bin/env node
const { spawnSync } = require('child_process');
const commands = {
migrate: {
description:
'Run migrations to update your code using @anthropic-ai/sdk@0.41 to be compatible with @anthropic-ai/sdk@0.50',
fn: () => {
const result = spawnSync(
'npx',
[
'-y',
'https://github.com/stainless-api/migrate-ts/releases/download/0.0.2/stainless-api-migrate-0.0.2-6.tgz',
'--migrationConfig',
require.resolve('./migration-config.json'),
...process.argv.slice(3),
],
{ stdio: 'inherit' },
);
if (result.status !== 0) {
process.exit(result.status);
}
},
},
};
function exitWithHelp() {
console.log(`Usage: anthropic-ai-sdk <subcommand>`);
console.log();
console.log('Subcommands:');
for (const [name, info] of Object.entries(commands)) {
console.log(` ${name} ${info.description}`);
}
console.log();
process.exit(1);
}
if (process.argv.length < 3) {
exitWithHelp();
}
const commandName = process.argv[2];
const command = commands[commandName];
if (!command) {
console.log(`Unknown subcommand ${commandName}.`);
exitWithHelp();
}
command.fn();
@@ -0,0 +1,711 @@
{
"pkg": "@anthropic-ai/sdk",
"githubRepo": "https://github.com/anthropics/anthropic-sdk-typescript",
"clientClass": "Anthropic",
"baseClientClass": "BaseAnthropic",
"methods": [
{
"base": "beta.sessions.resources",
"name": "retrieve",
"params": [
{
"type": "param",
"key": "resource_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "session_id",
"location": "path"
},
{
"type": "param",
"key": "resource_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.sessions.resources",
"name": "update",
"params": [
{
"type": "param",
"key": "resource_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "session_id",
"location": "path"
},
{
"type": "param",
"key": "resource_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
]
},
{
"base": "beta.sessions.resources",
"name": "delete",
"params": [
{
"type": "param",
"key": "resource_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "session_id",
"location": "path"
},
{
"type": "param",
"key": "resource_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.sessions.threads",
"name": "retrieve",
"params": [
{
"type": "param",
"key": "thread_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "session_id",
"location": "path"
},
{
"type": "param",
"key": "thread_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.sessions.threads",
"name": "archive",
"params": [
{
"type": "param",
"key": "thread_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "session_id",
"location": "path"
},
{
"type": "param",
"key": "thread_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.sessions.threads.events",
"name": "list",
"params": [
{
"type": "param",
"key": "thread_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "session_id",
"location": "path"
},
{
"type": "param",
"key": "thread_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.sessions.threads.events",
"name": "stream",
"params": [
{
"type": "param",
"key": "thread_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "session_id",
"location": "path"
},
{
"type": "param",
"key": "thread_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.vaults.credentials",
"name": "retrieve",
"params": [
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "vault_id",
"location": "path"
},
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.vaults.credentials",
"name": "update",
"params": [
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "vault_id",
"location": "path"
},
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
]
},
{
"base": "beta.vaults.credentials",
"name": "delete",
"params": [
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "vault_id",
"location": "path"
},
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.vaults.credentials",
"name": "archive",
"params": [
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "vault_id",
"location": "path"
},
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.vaults.credentials",
"name": "mcpOAuthValidate",
"params": [
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "vault_id",
"location": "path"
},
{
"type": "param",
"key": "credential_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.memoryStores.memories",
"name": "retrieve",
"params": [
{
"type": "param",
"key": "memory_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "memory_store_id",
"location": "path"
},
{
"type": "param",
"key": "memory_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.memoryStores.memories",
"name": "update",
"params": [
{
"type": "param",
"key": "memory_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "memory_store_id",
"location": "path"
},
{
"type": "param",
"key": "memory_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
]
},
{
"base": "beta.memoryStores.memories",
"name": "delete",
"params": [
{
"type": "param",
"key": "memory_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "memory_store_id",
"location": "path"
},
{
"type": "param",
"key": "memory_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.memoryStores.memoryVersions",
"name": "retrieve",
"params": [
{
"type": "param",
"key": "memory_version_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "memory_store_id",
"location": "path"
},
{
"type": "param",
"key": "memory_version_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.memoryStores.memoryVersions",
"name": "redact",
"params": [
{
"type": "param",
"key": "memory_version_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "memory_store_id",
"location": "path"
},
{
"type": "param",
"key": "memory_version_id",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.skills.versions",
"name": "retrieve",
"params": [
{
"type": "param",
"key": "version",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "skill_id",
"location": "path"
},
{
"type": "param",
"key": "version",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
},
{
"base": "beta.skills.versions",
"name": "delete",
"params": [
{
"type": "param",
"key": "version",
"location": "path"
},
{
"type": "params",
"maybeOverload": false
},
{
"type": "options"
}
],
"oldParams": [
{
"type": "param",
"key": "skill_id",
"location": "path"
},
{
"type": "param",
"key": "version",
"location": "path"
},
{
"type": "params",
"maybeOverload": true
},
{
"type": "options"
}
]
}
]
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,823 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _BaseAnthropic_instances, _a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Anthropic = exports.BaseAnthropic = exports.AI_PROMPT = exports.HUMAN_PROMPT = void 0;
const tslib_1 = require("./internal/tslib.js");
const uuid_1 = require("./internal/utils/uuid.js");
const values_1 = require("./internal/utils/values.js");
const sleep_1 = require("./internal/utils/sleep.js");
const errors_1 = require("./internal/errors.js");
const detect_platform_1 = require("./internal/detect-platform.js");
const Shims = tslib_1.__importStar(require("./internal/shims.js"));
const Opts = tslib_1.__importStar(require("./internal/request-options.js"));
const query_1 = require("./internal/utils/query.js");
const version_1 = require("./version.js");
const Errors = tslib_1.__importStar(require("./core/error.js"));
const types_1 = require("./lib/credentials/types.js");
const token_cache_1 = require("./lib/credentials/token-cache.js");
const credential_chain_1 = require("./lib/credentials/credential-chain.js");
const Pagination = tslib_1.__importStar(require("./core/pagination.js"));
const Uploads = tslib_1.__importStar(require("./core/uploads.js"));
const API = tslib_1.__importStar(require("./resources/index.js"));
const api_promise_1 = require("./core/api-promise.js");
const completions_1 = require("./resources/completions.js");
const models_1 = require("./resources/models.js");
const beta_1 = require("./resources/beta/beta.js");
const messages_1 = require("./resources/messages/messages.js");
const detect_platform_2 = require("./internal/detect-platform.js");
const headers_1 = require("./internal/headers.js");
const env_1 = require("./internal/utils/env.js");
const log_1 = require("./internal/utils/log.js");
const values_2 = require("./internal/utils/values.js");
exports.HUMAN_PROMPT = '\\n\\nHuman:';
exports.AI_PROMPT = '\\n\\nAssistant:';
/**
* Base class for Anthropic API clients.
*/
class BaseAnthropic {
/**
* The active credential provider. Default credential resolution runs once
* at construction time. If it fails, the error is surfaced on every
* request and the client must be reconstructed — there is no retry path.
*
* Clones returned by {@link withOptions} share the parent's auth state
* (provider, token cache, pending resolution, and any resolution error)
* unless the caller passes an explicit `apiKey`, `authToken`,
* `credentials`, `config`, or `profile` override.
*/
get credentials() {
return this._authState.provider;
}
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string | null | undefined} [opts.webhookKey=process.env['ANTHROPIC_WEBHOOK_SIGNING_KEY'] ?? null]
* @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
* @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.
*/
constructor({ baseURL = (0, env_1.readEnv)('ANTHROPIC_BASE_URL'), apiKey, authToken, webhookKey = (0, env_1.readEnv)('ANTHROPIC_WEBHOOK_SIGNING_KEY') ?? null, ...opts } = {}) {
_BaseAnthropic_instances.add(this);
this._requestAuthFlags = new WeakMap();
_BaseAnthropic_encoder.set(this, void 0);
// An explicit `profile` is a constructor-level credential choice; when set,
// do not let env ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN shadow it.
if (apiKey === undefined) {
apiKey = opts.profile != null ? null : (0, env_1.readEnv)('ANTHROPIC_API_KEY') ?? null;
}
if (authToken === undefined) {
authToken = opts.profile != null ? null : (0, env_1.readEnv)('ANTHROPIC_AUTH_TOKEN') ?? null;
}
if (opts.profile != null && (opts.credentials != null || opts.config != null)) {
throw new TypeError('Pass at most one of `profile`, `credentials`, or `config`.');
}
const options = {
apiKey,
authToken,
webhookKey,
...opts,
baseURL: baseURL || `https://api.anthropic.com`,
};
if (!options.dangerouslyAllowBrowser && (0, detect_platform_2.isRunningInBrowser)()) {
throw new Errors.AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
}
this.baseURL = options.baseURL;
// After destructuring, `baseURL` is the constructor arg or
// ANTHROPIC_BASE_URL — both count as an explicit choice that a profile
// base_url must not override. A falsy value means we fell through to the
// hardcoded default above and a profile may supply the host. withOptions()
// propagates the parent's flag via __baseURLIsExplicit so a non-overriding
// clone doesn't mistake the inherited baseURL for a caller-supplied one.
this._baseURLIsExplicit = opts.__baseURLIsExplicit ?? !!baseURL;
this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
this.logger = options.logger ?? console;
const defaultLogLevel = 'warn';
// Set default logLevel early so that we can log a warning in parseLogLevel.
this.logLevel = defaultLogLevel;
this.logLevel =
(0, log_1.parseLogLevel)(options.logLevel, 'ClientOptions.logLevel', this) ??
(0, log_1.parseLogLevel)((0, env_1.readEnv)('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ??
defaultLogLevel;
this.fetchOptions = options.fetchOptions;
this.maxRetries = options.maxRetries ?? 2;
this.fetch = options.fetch ?? Shims.getDefaultFetch();
tslib_1.__classPrivateFieldSet(this, _BaseAnthropic_encoder, Opts.FallbackEncoder, "f");
const customHeadersEnv = (0, env_1.readEnv)('ANTHROPIC_CUSTOM_HEADERS');
if (customHeadersEnv) {
const parsed = {};
for (const line of customHeadersEnv.split('\n')) {
const colon = line.indexOf(':');
if (colon >= 0) {
parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
}
}
options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
}
const inherited = opts.__auth;
// Never persist the internal __auth handle on _options — it's a
// one-shot constructor signal, and leaking it through _options would
// cause withOptions() to spread a stale value into clones.
delete options.__auth;
delete options.__baseURLIsExplicit;
this._options = options;
this.apiKey = typeof apiKey === 'string' ? apiKey : null;
this.authToken = authToken;
this.webhookKey = webhookKey;
if (inherited) {
this._authState = inherited;
if (!this._baseURLIsExplicit && inherited.baseURL) {
this.baseURL = inherited.baseURL;
}
}
else {
this._authState = { provider: null, tokenCache: null, resolution: null, error: null, extraHeaders: {} };
// apiKey/authToken win over credentials/config/profile; don't build a
// token cache or resolve a config that the request path will then ignore.
if (this.apiKey == null && this.authToken == null) {
const credentials = options.credentials ?? null;
if (credentials) {
this._authState.provider = credentials;
this._authState.tokenCache = this._makeTokenCache(credentials);
}
else if (options.config != null) {
const result = (0, credential_chain_1.resolveCredentialsFromConfig)(options.config, this._credentialResolverOptions());
this._authState.provider = result.provider;
this._authState.tokenCache = this._makeTokenCache(result.provider);
this._authState.extraHeaders = result.extraHeaders;
this._applyCredentialBaseURL(result.baseURL);
}
else if (options.profile != null) {
this._authState.resolution = this._resolveDefaultCredentials(options.profile);
}
else {
// No explicit auth provided — lazily resolve from the credential
// chain on first request. Errors are captured into _auth.error and
// surfaced on first use rather than as an unhandled rejection.
this._authState.resolution = this._resolveDefaultCredentials();
}
}
}
}
/**
* Stores a profile/config-supplied base URL on the shared auth state and, if
* the caller did not pin `baseURL` via constructor option or env, adopts it
* as this client's outbound API host. Precedence: ctor opt > env > profile >
* hardcoded default.
*/
_applyCredentialBaseURL(baseURL) {
if (!baseURL)
return;
const normalized = baseURL.replace(/\/+$/, '');
this._authState.baseURL = normalized;
if (!this._baseURLIsExplicit) {
this.baseURL = normalized;
}
}
/**
* Options bag passed into the credential chain. `baseURL` here is only the
* fallback host for the token-exchange POST when the config itself omits
* `base_url`; the chain returns the config's own `base_url` (if any) on
* {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL}
* then adopts for outbound API requests. The two are deliberately decoupled
* so this fallback never round-trips into precedence.
*/
_credentialResolverOptions() {
return {
baseURL: this.baseURL,
fetch: this.fetch,
userAgent: this.getUserAgent(),
onCacheWriteError: (err) => {
(0, log_1.loggerFor)(this).debug('credential cache write failed (best-effort)', err);
},
onSafetyWarning: (msg) => {
(0, log_1.loggerFor)(this).warn(msg);
},
};
}
_makeTokenCache(provider) {
return new token_cache_1.TokenCache(provider, (err) => {
(0, log_1.loggerFor)(this).debug('advisory token refresh failed; serving cached token', err);
});
}
/**
* Create a new client instance re-using the same options given to the current client with optional overriding.
*/
withOptions(options) {
// Share the auth state object unless the caller passes any auth-related
// key. The `in` check is intentional: even `apiKey: undefined` opts the
// clone out of sharing (it gets its own _auth and TokenCache, though it
// may still wrap the parent's provider via the credentials spread below).
const overridesStructuredAuth = 'credentials' in options || 'config' in options || 'profile' in options;
const overridesAuth = 'apiKey' in options || 'authToken' in options || overridesStructuredAuth;
const internal = {
...this._options,
// Only forward baseURL when the caller (or env) explicitly chose it.
// For a non-explicit parent, this.baseURL may have been mutated to the
// profile-resolved host; pinning that as the clone's options.baseURL
// would make _options on the clone misreport caller intent and would
// leave the clone stuck on the parent's host across an auth override.
// The clone instead receives the construction-time value via
// ...this._options above and re-adopts the profile host through the
// shared _authState.baseURL + __baseURLIsExplicit=false path.
...(this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}),
maxRetries: this.maxRetries,
timeout: this.timeout,
logger: this.logger,
logLevel: this.logLevel,
fetch: this.fetch,
fetchOptions: this.fetchOptions,
apiKey: this.apiKey,
authToken: this.authToken,
webhookKey: this.webhookKey,
// credentials: this.credentials is a no-op when __auth is shared (the
// ctor takes the inherited path and ignores options.credentials); when
// overridesAuth is true via apiKey/authToken only, it lets the clone
// build a fresh TokenCache around the parent's provider.
credentials: this.credentials,
// When the caller passes a structured-credential override, drop inherited
// structured-credential options so only `...options` supplies them —
// otherwise an inherited `credentials`/`config`/`profile` would trip the
// mutual-exclusion check or precedence over the override.
...(overridesStructuredAuth ? { credentials: undefined, config: undefined, profile: undefined } : {}),
...options,
// Always set __auth so any stale value from ...this._options is
// overwritten. undefined means "build fresh auth from these options".
__auth: overridesAuth ? undefined : this._authState,
__baseURLIsExplicit: 'baseURL' in options ? true : this._baseURLIsExplicit,
};
return new this.constructor(internal);
}
/**
* Lazily resolves credentials from config files or environment variables.
* Called once from the constructor when no explicit auth is provided, or
* when an explicit `profile` was passed (in which case a missing/unresolved
* profile is surfaced as an error instead of falling through to "no auth").
* The returned promise is stored and awaited on the first request.
*/
async _resolveDefaultCredentials(profile) {
try {
const result = await (0, credential_chain_1.defaultCredentials)(this._credentialResolverOptions(), profile);
if (result) {
this._authState.provider = result.provider;
this._authState.tokenCache = this._makeTokenCache(result.provider);
this._authState.extraHeaders = result.extraHeaders;
this._applyCredentialBaseURL(result.baseURL);
}
else if (profile != null) {
throw new Errors.AnthropicError(`Profile "${profile}" could not be resolved (no <config_dir>/configs/${profile}.json found).`);
}
}
catch (err) {
this._authState.error = err;
}
finally {
this._authState.resolution = null;
}
}
defaultQuery() {
return this._options.defaultQuery;
}
validateHeaders({ values, nulls }) {
if (values.get('x-api-key') || values.get('authorization')) {
return;
}
if (this._authState.error) {
throw this._authState.error;
}
if (this._authState.tokenCache || this._authState.resolution) {
return; // auth will be injected per-request via authHeaders
}
if (this.apiKey && values.get('x-api-key')) {
return;
}
if (nulls.has('x-api-key')) {
return;
}
if (this.authToken && values.get('authorization')) {
return;
}
if (nulls.has('authorization')) {
return;
}
throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
}
_authFlags(opts) {
let flags = this._requestAuthFlags.get(opts);
if (!flags) {
flags = { usedTokenCache: false, didRefreshFor401: false };
this._requestAuthFlags.set(opts, flags);
}
return flags;
}
async authHeaders(opts) {
// Wait for lazy credential resolution if it's in progress. If it failed,
// return no auth headers — validateHeaders surfaces the stored error
// after the explicit-header escape hatch has had a chance to apply.
if (this._authState.resolution) {
await this._authState.resolution;
}
if (this._authState.error) {
return undefined;
}
// If we have a token cache and no API key is set, use token auth
if (this._authState.tokenCache && this.apiKey == null) {
const token = await this._authState.tokenCache.getToken();
this._authFlags(opts).usedTokenCache = true;
return (0, headers_1.buildHeaders)([{ Authorization: `Bearer ${token}` }]);
}
return (0, headers_1.buildHeaders)([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
}
async apiKeyAuth(opts) {
if (this.apiKey == null) {
return undefined;
}
return (0, headers_1.buildHeaders)([{ 'X-Api-Key': this.apiKey }]);
}
async bearerAuth(opts) {
if (this.authToken == null) {
return undefined;
}
return (0, headers_1.buildHeaders)([{ Authorization: `Bearer ${this.authToken}` }]);
}
stringifyQuery(query) {
return (0, query_1.stringifyQuery)(query);
}
getUserAgent() {
return `${this.constructor.name}/JS ${version_1.VERSION}`;
}
defaultIdempotencyKey() {
return `stainless-node-retry-${(0, uuid_1.uuid4)()}`;
}
makeStatusError(status, error, message, headers) {
return Errors.APIError.generate(status, error, message, headers);
}
buildURL(path, query, defaultBaseURL) {
const baseURL = (!tslib_1.__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
const url = (0, values_1.isAbsoluteURL)(path) ?
new URL(path)
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
const defaultQuery = this.defaultQuery();
const pathQuery = Object.fromEntries(url.searchParams);
if (!(0, values_2.isEmptyObj)(defaultQuery) || !(0, values_2.isEmptyObj)(pathQuery)) {
query = { ...pathQuery, ...defaultQuery, ...query };
}
if (typeof query === 'object' && query && !Array.isArray(query)) {
url.search = this.stringifyQuery(query);
}
return url.toString();
}
_calculateNonstreamingTimeout(maxTokens) {
const defaultTimeout = 10 * 60;
const expectedTimeout = (60 * 60 * maxTokens) / 128000;
if (expectedTimeout > defaultTimeout) {
throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' +
'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details');
}
return defaultTimeout * 1000;
}
/**
* Used as a callback for mutating the given `FinalRequestOptions` object.
*/
async prepareOptions(options) { }
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
async prepareRequest(request, { url, options }) {
// Append auth-derived headers when using token auth. Done here (after all
// header merging) rather than in authHeaders() so we append to any existing
// anthropic-beta values instead of being overwritten by later header sources.
if (this._authState.tokenCache && this.apiKey == null) {
// Normalize to a Headers instance — custom fetch impls or polyfills can
// hand back arrays / plain objects, and silently dropping the beta
// header in that case would surface as a confusing server-side 4xx.
const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers);
for (const [k, v] of Object.entries(this._authState.extraHeaders)) {
if (!headers.has(k))
headers.set(k, v);
}
const existing = headers
.get('anthropic-beta')
?.split(',')
.map((s) => s.trim());
if (!existing?.includes(types_1.OAUTH_API_BETA_HEADER)) {
headers.append('anthropic-beta', types_1.OAUTH_API_BETA_HEADER);
}
request.headers = headers;
}
}
get(path, opts) {
return this.methodRequest('get', path, opts);
}
post(path, opts) {
return this.methodRequest('post', path, opts);
}
patch(path, opts) {
return this.methodRequest('patch', path, opts);
}
put(path, opts) {
return this.methodRequest('put', path, opts);
}
delete(path, opts) {
return this.methodRequest('delete', path, opts);
}
methodRequest(method, path, opts) {
return this.request(Promise.resolve(opts).then((opts) => {
return { method, path, ...opts };
}));
}
request(options, remainingRetries = null) {
return new api_promise_1.APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
}
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
const options = await optionsInput;
const maxRetries = options.maxRetries ?? this.maxRetries;
if (retriesRemaining == null) {
retriesRemaining = maxRetries;
// Top-level call: reset per-request auth flags so a reused options object
// (via client.request(opts)) doesn't carry stale 401-refresh state.
this._requestAuthFlags.delete(options);
}
await this.prepareOptions(options);
const { req, url, timeout } = await this.buildRequest(options, {
retryCount: maxRetries - retriesRemaining,
});
await this.prepareRequest(req, { url, options });
/** Not an API request ID, just for correlating local log entries. */
const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
const startTime = Date.now();
(0, log_1.loggerFor)(this).debug(`[${requestLogID}] sending request`, (0, log_1.formatRequestDetails)({
retryOfRequestLogID,
method: options.method,
url,
options,
headers: req.headers,
}));
if (options.signal?.aborted) {
throw new Errors.APIUserAbortError();
}
const controller = new AbortController();
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(errors_1.castToError);
const headersTime = Date.now();
if (response instanceof globalThis.Error) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
if (options.signal?.aborted) {
throw new Errors.APIUserAbortError();
}
// detect native connection timeout errors
// 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)"
// undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
// others do not provide enough information to distinguish timeouts from other connection errors
const isTimeout = (0, errors_1.isAbortError)(response) ||
/timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
if (retriesRemaining) {
(0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
(0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, (0, log_1.formatRequestDetails)({
retryOfRequestLogID,
url,
durationMs: headersTime - startTime,
message: response.message,
}));
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
}
(0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
(0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, (0, log_1.formatRequestDetails)({
retryOfRequestLogID,
url,
durationMs: headersTime - startTime,
message: response.message,
}));
if (isTimeout) {
throw new Errors.APIConnectionTimeoutError();
}
throw new Errors.APIConnectionError({ cause: response });
}
const specialHeaders = [...response.headers.entries()]
.filter(([name]) => name === 'request-id')
.map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
.join('');
const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
if (!response.ok) {
const shouldRetry = await this.shouldRetry(response, options);
if (retriesRemaining && shouldRetry) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
// We don't need the body of this response.
await Shims.CancelReadableStream(response.body);
(0, log_1.loggerFor)(this).info(`${responseInfo} - ${retryMessage}`);
(0, log_1.loggerFor)(this).debug(`[${requestLogID}] response error (${retryMessage})`, (0, log_1.formatRequestDetails)({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
durationMs: headersTime - startTime,
}));
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
}
const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
(0, log_1.loggerFor)(this).info(`${responseInfo} - ${retryMessage}`);
const errText = await response.text().catch((err) => (0, errors_1.castToError)(err).message);
const errJSON = (0, values_1.safeJSON)(errText);
const errMessage = errJSON ? undefined : errText;
(0, log_1.loggerFor)(this).debug(`[${requestLogID}] response error (${retryMessage})`, (0, log_1.formatRequestDetails)({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
message: errMessage,
durationMs: Date.now() - startTime,
}));
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
throw err;
}
(0, log_1.loggerFor)(this).info(responseInfo);
(0, log_1.loggerFor)(this).debug(`[${requestLogID}] response start`, (0, log_1.formatRequestDetails)({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
durationMs: headersTime - startTime,
}));
return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
}
getAPIList(path, Page, opts) {
return this.requestAPIList(Page, opts && 'then' in opts ?
opts.then((opts) => ({ method: 'get', path, ...opts }))
: { method: 'get', path, ...opts });
}
requestAPIList(Page, options) {
const request = this.makeRequest(options, null, undefined);
return new Pagination.PagePromise(this, request, Page);
}
async fetchWithTimeout(url, init, ms, controller) {
const { signal, method, ...options } = init || {};
// Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks.
// An arrow function like `() => controller.abort()` captures the surrounding scope,
// which includes the request body and other large objects. When the user passes a
// long-lived AbortSignal, the listener prevents those objects from being GC'd for
// the lifetime of the signal. Using `.bind()` only retains a reference to the
// controller itself.
const abort = this._makeAbort(controller);
if (signal)
signal.addEventListener('abort', abort, { once: true });
const timeout = setTimeout(abort, ms);
const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
(typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
const fetchOptions = {
signal: controller.signal,
...(isReadableBody ? { duplex: 'half' } : {}),
method: 'GET',
...options,
};
if (method) {
// Custom methods like 'patch' need to be uppercased
// See https://github.com/nodejs/undici/issues/2294
fetchOptions.method = method.toUpperCase();
}
try {
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
return await this.fetch.call(undefined, url, fetchOptions);
}
finally {
clearTimeout(timeout);
}
}
async shouldRetry(response, options) {
// Reactive refresh: on a 401 from a request that used the token cache,
// invalidate and retry once. Only fires when this specific request was
// bearer-authenticated (not when an apiKey was used) and only once per
// request — a second 401 after refresh falls through to the normal
// retry policy below (which treats 4xx as non-retryable).
const flags = this._authFlags(options);
if (response.status === 401 &&
this._authState.tokenCache &&
flags.usedTokenCache &&
!flags.didRefreshFor401) {
flags.didRefreshFor401 = true;
this._authState.tokenCache.invalidate();
return true;
}
// Note this is not a standard header.
const shouldRetryHeader = response.headers.get('x-should-retry');
// If the server explicitly says whether or not to retry, obey.
if (shouldRetryHeader === 'true')
return true;
if (shouldRetryHeader === 'false')
return false;
// Retry on request timeouts.
if (response.status === 408)
return true;
// Retry on lock timeouts.
if (response.status === 409)
return true;
// Retry on rate limits.
if (response.status === 429)
return true;
// Retry internal errors.
if (response.status >= 500)
return true;
return false;
}
async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
let timeoutMillis;
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
if (retryAfterMillisHeader) {
const timeoutMs = parseFloat(retryAfterMillisHeader);
if (!Number.isNaN(timeoutMs)) {
timeoutMillis = timeoutMs;
}
}
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
const retryAfterHeader = responseHeaders?.get('retry-after');
if (retryAfterHeader && !timeoutMillis) {
const timeoutSeconds = parseFloat(retryAfterHeader);
if (!Number.isNaN(timeoutSeconds)) {
timeoutMillis = timeoutSeconds * 1000;
}
else {
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
}
}
// If the API asks us to wait a certain amount of time, just do what it
// says, but otherwise calculate a default
if (timeoutMillis === undefined) {
const maxRetries = options.maxRetries ?? this.maxRetries;
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
}
await (0, sleep_1.sleep)(timeoutMillis);
return this.makeRequest(options, retriesRemaining - 1, requestLogID);
}
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
const initialRetryDelay = 0.5;
const maxRetryDelay = 8.0;
const numRetries = maxRetries - retriesRemaining;
// Apply exponential backoff, but not more than the max.
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
// Apply some jitter, take up to at most 25 percent of the retry time.
const jitter = 1 - Math.random() * 0.25;
return sleepSeconds * jitter * 1000;
}
calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
const maxTime = 60 * 60 * 1000; // 60 minutes
const defaultTime = 60 * 10 * 1000; // 10 minutes
const expectedTime = (maxTime * maxTokens) / 128000;
if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {
throw new Errors.AnthropicError('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');
}
return defaultTime;
}
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
const options = { ...inputOptions };
const { method, path, query, defaultBaseURL } = options;
// Lazy credential resolution may carry a profile-supplied baseURL. Await
// it before building the request URL so the very first request — and
// requests on withOptions() clones created before resolution settled —
// hit the profile's host rather than the hardcoded default.
if (this._authState.resolution) {
await this._authState.resolution;
}
if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) {
this.baseURL = this._authState.baseURL;
}
const url = this.buildURL(path, query, defaultBaseURL);
if ('timeout' in options)
(0, values_1.validatePositiveInteger)('timeout', options.timeout);
options.timeout = options.timeout ?? this.timeout;
const { bodyHeaders, body } = this.buildBody({ options });
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
const req = {
method,
headers: reqHeaders,
...(options.signal && { signal: options.signal }),
...(globalThis.ReadableStream &&
body instanceof globalThis.ReadableStream && { duplex: 'half' }),
...(body && { body }),
...(this.fetchOptions ?? {}),
...(options.fetchOptions ?? {}),
};
return { req, url, timeout: options.timeout };
}
async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
let idempotencyHeaders = {};
if (this.idempotencyHeader && method !== 'get') {
if (!options.idempotencyKey)
options.idempotencyKey = this.defaultIdempotencyKey();
idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
}
const headers = (0, headers_1.buildHeaders)([
idempotencyHeaders,
{
Accept: 'application/json',
'User-Agent': this.getUserAgent(),
'X-Stainless-Retry-Count': String(retryCount),
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
...(0, detect_platform_1.getPlatformHeaders)(),
...(this._options.dangerouslyAllowBrowser ?
{ 'anthropic-dangerous-direct-browser-access': 'true' }
: undefined),
'anthropic-version': '2023-06-01',
},
await this.authHeaders(options),
this._options.defaultHeaders,
bodyHeaders,
options.headers,
]);
this.validateHeaders(headers);
return headers.values;
}
_makeAbort(controller) {
// note: we can't just inline this method inside `fetchWithTimeout()` because then the closure
// would capture all request options, and cause a memory leak.
return () => controller.abort();
}
buildBody({ options: { body, headers: rawHeaders } }) {
if (!body) {
return { bodyHeaders: undefined, body: undefined };
}
const headers = (0, headers_1.buildHeaders)([rawHeaders]);
if (
// Pass raw type verbatim
ArrayBuffer.isView(body) ||
body instanceof ArrayBuffer ||
body instanceof DataView ||
(typeof body === 'string' &&
// Preserve legacy string encoding behavior for now
headers.values.has('content-type')) ||
// `Blob` is superset of `File`
(globalThis.Blob && body instanceof globalThis.Blob) ||
// `FormData` -> `multipart/form-data`
body instanceof FormData ||
// `URLSearchParams` -> `application/x-www-form-urlencoded`
body instanceof URLSearchParams ||
// Send chunked stream (each chunk has own `length`)
(globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
return { bodyHeaders: undefined, body: body };
}
else if (typeof body === 'object' &&
(Symbol.asyncIterator in body ||
(Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
}
else if (typeof body === 'object' &&
headers.values.get('content-type') === 'application/x-www-form-urlencoded') {
return {
bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },
body: this.stringifyQuery(body),
};
}
else {
return tslib_1.__classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
}
}
}
exports.BaseAnthropic = BaseAnthropic;
_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() {
return this.baseURL !== 'https://api.anthropic.com';
};
BaseAnthropic.Anthropic = _a;
BaseAnthropic.HUMAN_PROMPT = exports.HUMAN_PROMPT;
BaseAnthropic.AI_PROMPT = exports.AI_PROMPT;
BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes
BaseAnthropic.AnthropicError = Errors.AnthropicError;
BaseAnthropic.APIError = Errors.APIError;
BaseAnthropic.APIConnectionError = Errors.APIConnectionError;
BaseAnthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
BaseAnthropic.APIUserAbortError = Errors.APIUserAbortError;
BaseAnthropic.NotFoundError = Errors.NotFoundError;
BaseAnthropic.ConflictError = Errors.ConflictError;
BaseAnthropic.RateLimitError = Errors.RateLimitError;
BaseAnthropic.BadRequestError = Errors.BadRequestError;
BaseAnthropic.AuthenticationError = Errors.AuthenticationError;
BaseAnthropic.InternalServerError = Errors.InternalServerError;
BaseAnthropic.PermissionDeniedError = Errors.PermissionDeniedError;
BaseAnthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
BaseAnthropic.toFile = Uploads.toFile;
/**
* API Client for interfacing with the Anthropic API.
*/
class Anthropic extends BaseAnthropic {
constructor() {
super(...arguments);
this.completions = new API.Completions(this);
this.messages = new API.Messages(this);
this.models = new API.Models(this);
this.beta = new API.Beta(this);
}
}
exports.Anthropic = Anthropic;
Anthropic.Completions = completions_1.Completions;
Anthropic.Messages = messages_1.Messages;
Anthropic.Models = models_1.Models;
Anthropic.Beta = beta_1.Beta;
//# sourceMappingURL=client.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,818 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _BaseAnthropic_instances, _a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "./internal/tslib.mjs";
import { uuid4 } from "./internal/utils/uuid.mjs";
import { validatePositiveInteger, isAbsoluteURL, safeJSON } from "./internal/utils/values.mjs";
import { sleep } from "./internal/utils/sleep.mjs";
import { castToError, isAbortError } from "./internal/errors.mjs";
import { getPlatformHeaders } from "./internal/detect-platform.mjs";
import * as Shims from "./internal/shims.mjs";
import * as Opts from "./internal/request-options.mjs";
import { stringifyQuery } from "./internal/utils/query.mjs";
import { VERSION } from "./version.mjs";
import * as Errors from "./core/error.mjs";
import { OAUTH_API_BETA_HEADER } from "./lib/credentials/types.mjs";
import { TokenCache } from "./lib/credentials/token-cache.mjs";
import { defaultCredentials, resolveCredentialsFromConfig } from "./lib/credentials/credential-chain.mjs";
import * as Pagination from "./core/pagination.mjs";
import * as Uploads from "./core/uploads.mjs";
import * as API from "./resources/index.mjs";
import { APIPromise } from "./core/api-promise.mjs";
import { Completions, } from "./resources/completions.mjs";
import { Models, } from "./resources/models.mjs";
import { Beta, } from "./resources/beta/beta.mjs";
import { Messages, } from "./resources/messages/messages.mjs";
import { isRunningInBrowser } from "./internal/detect-platform.mjs";
import { buildHeaders } from "./internal/headers.mjs";
import { readEnv } from "./internal/utils/env.mjs";
import { formatRequestDetails, loggerFor, parseLogLevel, } from "./internal/utils/log.mjs";
import { isEmptyObj } from "./internal/utils/values.mjs";
export const HUMAN_PROMPT = '\\n\\nHuman:';
export const AI_PROMPT = '\\n\\nAssistant:';
/**
* Base class for Anthropic API clients.
*/
export class BaseAnthropic {
/**
* The active credential provider. Default credential resolution runs once
* at construction time. If it fails, the error is surfaced on every
* request and the client must be reconstructed — there is no retry path.
*
* Clones returned by {@link withOptions} share the parent's auth state
* (provider, token cache, pending resolution, and any resolution error)
* unless the caller passes an explicit `apiKey`, `authToken`,
* `credentials`, `config`, or `profile` override.
*/
get credentials() {
return this._authState.provider;
}
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string | null | undefined} [opts.webhookKey=process.env['ANTHROPIC_WEBHOOK_SIGNING_KEY'] ?? null]
* @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
* @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.
*/
constructor({ baseURL = readEnv('ANTHROPIC_BASE_URL'), apiKey, authToken, webhookKey = readEnv('ANTHROPIC_WEBHOOK_SIGNING_KEY') ?? null, ...opts } = {}) {
_BaseAnthropic_instances.add(this);
this._requestAuthFlags = new WeakMap();
_BaseAnthropic_encoder.set(this, void 0);
// An explicit `profile` is a constructor-level credential choice; when set,
// do not let env ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN shadow it.
if (apiKey === undefined) {
apiKey = opts.profile != null ? null : readEnv('ANTHROPIC_API_KEY') ?? null;
}
if (authToken === undefined) {
authToken = opts.profile != null ? null : readEnv('ANTHROPIC_AUTH_TOKEN') ?? null;
}
if (opts.profile != null && (opts.credentials != null || opts.config != null)) {
throw new TypeError('Pass at most one of `profile`, `credentials`, or `config`.');
}
const options = {
apiKey,
authToken,
webhookKey,
...opts,
baseURL: baseURL || `https://api.anthropic.com`,
};
if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
throw new Errors.AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
}
this.baseURL = options.baseURL;
// After destructuring, `baseURL` is the constructor arg or
// ANTHROPIC_BASE_URL — both count as an explicit choice that a profile
// base_url must not override. A falsy value means we fell through to the
// hardcoded default above and a profile may supply the host. withOptions()
// propagates the parent's flag via __baseURLIsExplicit so a non-overriding
// clone doesn't mistake the inherited baseURL for a caller-supplied one.
this._baseURLIsExplicit = opts.__baseURLIsExplicit ?? !!baseURL;
this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
this.logger = options.logger ?? console;
const defaultLogLevel = 'warn';
// Set default logLevel early so that we can log a warning in parseLogLevel.
this.logLevel = defaultLogLevel;
this.logLevel =
parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
parseLogLevel(readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ??
defaultLogLevel;
this.fetchOptions = options.fetchOptions;
this.maxRetries = options.maxRetries ?? 2;
this.fetch = options.fetch ?? Shims.getDefaultFetch();
__classPrivateFieldSet(this, _BaseAnthropic_encoder, Opts.FallbackEncoder, "f");
const customHeadersEnv = readEnv('ANTHROPIC_CUSTOM_HEADERS');
if (customHeadersEnv) {
const parsed = {};
for (const line of customHeadersEnv.split('\n')) {
const colon = line.indexOf(':');
if (colon >= 0) {
parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
}
}
options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
}
const inherited = opts.__auth;
// Never persist the internal __auth handle on _options — it's a
// one-shot constructor signal, and leaking it through _options would
// cause withOptions() to spread a stale value into clones.
delete options.__auth;
delete options.__baseURLIsExplicit;
this._options = options;
this.apiKey = typeof apiKey === 'string' ? apiKey : null;
this.authToken = authToken;
this.webhookKey = webhookKey;
if (inherited) {
this._authState = inherited;
if (!this._baseURLIsExplicit && inherited.baseURL) {
this.baseURL = inherited.baseURL;
}
}
else {
this._authState = { provider: null, tokenCache: null, resolution: null, error: null, extraHeaders: {} };
// apiKey/authToken win over credentials/config/profile; don't build a
// token cache or resolve a config that the request path will then ignore.
if (this.apiKey == null && this.authToken == null) {
const credentials = options.credentials ?? null;
if (credentials) {
this._authState.provider = credentials;
this._authState.tokenCache = this._makeTokenCache(credentials);
}
else if (options.config != null) {
const result = resolveCredentialsFromConfig(options.config, this._credentialResolverOptions());
this._authState.provider = result.provider;
this._authState.tokenCache = this._makeTokenCache(result.provider);
this._authState.extraHeaders = result.extraHeaders;
this._applyCredentialBaseURL(result.baseURL);
}
else if (options.profile != null) {
this._authState.resolution = this._resolveDefaultCredentials(options.profile);
}
else {
// No explicit auth provided — lazily resolve from the credential
// chain on first request. Errors are captured into _auth.error and
// surfaced on first use rather than as an unhandled rejection.
this._authState.resolution = this._resolveDefaultCredentials();
}
}
}
}
/**
* Stores a profile/config-supplied base URL on the shared auth state and, if
* the caller did not pin `baseURL` via constructor option or env, adopts it
* as this client's outbound API host. Precedence: ctor opt > env > profile >
* hardcoded default.
*/
_applyCredentialBaseURL(baseURL) {
if (!baseURL)
return;
const normalized = baseURL.replace(/\/+$/, '');
this._authState.baseURL = normalized;
if (!this._baseURLIsExplicit) {
this.baseURL = normalized;
}
}
/**
* Options bag passed into the credential chain. `baseURL` here is only the
* fallback host for the token-exchange POST when the config itself omits
* `base_url`; the chain returns the config's own `base_url` (if any) on
* {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL}
* then adopts for outbound API requests. The two are deliberately decoupled
* so this fallback never round-trips into precedence.
*/
_credentialResolverOptions() {
return {
baseURL: this.baseURL,
fetch: this.fetch,
userAgent: this.getUserAgent(),
onCacheWriteError: (err) => {
loggerFor(this).debug('credential cache write failed (best-effort)', err);
},
onSafetyWarning: (msg) => {
loggerFor(this).warn(msg);
},
};
}
_makeTokenCache(provider) {
return new TokenCache(provider, (err) => {
loggerFor(this).debug('advisory token refresh failed; serving cached token', err);
});
}
/**
* Create a new client instance re-using the same options given to the current client with optional overriding.
*/
withOptions(options) {
// Share the auth state object unless the caller passes any auth-related
// key. The `in` check is intentional: even `apiKey: undefined` opts the
// clone out of sharing (it gets its own _auth and TokenCache, though it
// may still wrap the parent's provider via the credentials spread below).
const overridesStructuredAuth = 'credentials' in options || 'config' in options || 'profile' in options;
const overridesAuth = 'apiKey' in options || 'authToken' in options || overridesStructuredAuth;
const internal = {
...this._options,
// Only forward baseURL when the caller (or env) explicitly chose it.
// For a non-explicit parent, this.baseURL may have been mutated to the
// profile-resolved host; pinning that as the clone's options.baseURL
// would make _options on the clone misreport caller intent and would
// leave the clone stuck on the parent's host across an auth override.
// The clone instead receives the construction-time value via
// ...this._options above and re-adopts the profile host through the
// shared _authState.baseURL + __baseURLIsExplicit=false path.
...(this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}),
maxRetries: this.maxRetries,
timeout: this.timeout,
logger: this.logger,
logLevel: this.logLevel,
fetch: this.fetch,
fetchOptions: this.fetchOptions,
apiKey: this.apiKey,
authToken: this.authToken,
webhookKey: this.webhookKey,
// credentials: this.credentials is a no-op when __auth is shared (the
// ctor takes the inherited path and ignores options.credentials); when
// overridesAuth is true via apiKey/authToken only, it lets the clone
// build a fresh TokenCache around the parent's provider.
credentials: this.credentials,
// When the caller passes a structured-credential override, drop inherited
// structured-credential options so only `...options` supplies them —
// otherwise an inherited `credentials`/`config`/`profile` would trip the
// mutual-exclusion check or precedence over the override.
...(overridesStructuredAuth ? { credentials: undefined, config: undefined, profile: undefined } : {}),
...options,
// Always set __auth so any stale value from ...this._options is
// overwritten. undefined means "build fresh auth from these options".
__auth: overridesAuth ? undefined : this._authState,
__baseURLIsExplicit: 'baseURL' in options ? true : this._baseURLIsExplicit,
};
return new this.constructor(internal);
}
/**
* Lazily resolves credentials from config files or environment variables.
* Called once from the constructor when no explicit auth is provided, or
* when an explicit `profile` was passed (in which case a missing/unresolved
* profile is surfaced as an error instead of falling through to "no auth").
* The returned promise is stored and awaited on the first request.
*/
async _resolveDefaultCredentials(profile) {
try {
const result = await defaultCredentials(this._credentialResolverOptions(), profile);
if (result) {
this._authState.provider = result.provider;
this._authState.tokenCache = this._makeTokenCache(result.provider);
this._authState.extraHeaders = result.extraHeaders;
this._applyCredentialBaseURL(result.baseURL);
}
else if (profile != null) {
throw new Errors.AnthropicError(`Profile "${profile}" could not be resolved (no <config_dir>/configs/${profile}.json found).`);
}
}
catch (err) {
this._authState.error = err;
}
finally {
this._authState.resolution = null;
}
}
defaultQuery() {
return this._options.defaultQuery;
}
validateHeaders({ values, nulls }) {
if (values.get('x-api-key') || values.get('authorization')) {
return;
}
if (this._authState.error) {
throw this._authState.error;
}
if (this._authState.tokenCache || this._authState.resolution) {
return; // auth will be injected per-request via authHeaders
}
if (this.apiKey && values.get('x-api-key')) {
return;
}
if (nulls.has('x-api-key')) {
return;
}
if (this.authToken && values.get('authorization')) {
return;
}
if (nulls.has('authorization')) {
return;
}
throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
}
_authFlags(opts) {
let flags = this._requestAuthFlags.get(opts);
if (!flags) {
flags = { usedTokenCache: false, didRefreshFor401: false };
this._requestAuthFlags.set(opts, flags);
}
return flags;
}
async authHeaders(opts) {
// Wait for lazy credential resolution if it's in progress. If it failed,
// return no auth headers — validateHeaders surfaces the stored error
// after the explicit-header escape hatch has had a chance to apply.
if (this._authState.resolution) {
await this._authState.resolution;
}
if (this._authState.error) {
return undefined;
}
// If we have a token cache and no API key is set, use token auth
if (this._authState.tokenCache && this.apiKey == null) {
const token = await this._authState.tokenCache.getToken();
this._authFlags(opts).usedTokenCache = true;
return buildHeaders([{ Authorization: `Bearer ${token}` }]);
}
return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
}
async apiKeyAuth(opts) {
if (this.apiKey == null) {
return undefined;
}
return buildHeaders([{ 'X-Api-Key': this.apiKey }]);
}
async bearerAuth(opts) {
if (this.authToken == null) {
return undefined;
}
return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]);
}
stringifyQuery(query) {
return stringifyQuery(query);
}
getUserAgent() {
return `${this.constructor.name}/JS ${VERSION}`;
}
defaultIdempotencyKey() {
return `stainless-node-retry-${uuid4()}`;
}
makeStatusError(status, error, message, headers) {
return Errors.APIError.generate(status, error, message, headers);
}
buildURL(path, query, defaultBaseURL) {
const baseURL = (!__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
const url = isAbsoluteURL(path) ?
new URL(path)
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
const defaultQuery = this.defaultQuery();
const pathQuery = Object.fromEntries(url.searchParams);
if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
query = { ...pathQuery, ...defaultQuery, ...query };
}
if (typeof query === 'object' && query && !Array.isArray(query)) {
url.search = this.stringifyQuery(query);
}
return url.toString();
}
_calculateNonstreamingTimeout(maxTokens) {
const defaultTimeout = 10 * 60;
const expectedTimeout = (60 * 60 * maxTokens) / 128000;
if (expectedTimeout > defaultTimeout) {
throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' +
'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details');
}
return defaultTimeout * 1000;
}
/**
* Used as a callback for mutating the given `FinalRequestOptions` object.
*/
async prepareOptions(options) { }
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
async prepareRequest(request, { url, options }) {
// Append auth-derived headers when using token auth. Done here (after all
// header merging) rather than in authHeaders() so we append to any existing
// anthropic-beta values instead of being overwritten by later header sources.
if (this._authState.tokenCache && this.apiKey == null) {
// Normalize to a Headers instance — custom fetch impls or polyfills can
// hand back arrays / plain objects, and silently dropping the beta
// header in that case would surface as a confusing server-side 4xx.
const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers);
for (const [k, v] of Object.entries(this._authState.extraHeaders)) {
if (!headers.has(k))
headers.set(k, v);
}
const existing = headers
.get('anthropic-beta')
?.split(',')
.map((s) => s.trim());
if (!existing?.includes(OAUTH_API_BETA_HEADER)) {
headers.append('anthropic-beta', OAUTH_API_BETA_HEADER);
}
request.headers = headers;
}
}
get(path, opts) {
return this.methodRequest('get', path, opts);
}
post(path, opts) {
return this.methodRequest('post', path, opts);
}
patch(path, opts) {
return this.methodRequest('patch', path, opts);
}
put(path, opts) {
return this.methodRequest('put', path, opts);
}
delete(path, opts) {
return this.methodRequest('delete', path, opts);
}
methodRequest(method, path, opts) {
return this.request(Promise.resolve(opts).then((opts) => {
return { method, path, ...opts };
}));
}
request(options, remainingRetries = null) {
return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
}
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
const options = await optionsInput;
const maxRetries = options.maxRetries ?? this.maxRetries;
if (retriesRemaining == null) {
retriesRemaining = maxRetries;
// Top-level call: reset per-request auth flags so a reused options object
// (via client.request(opts)) doesn't carry stale 401-refresh state.
this._requestAuthFlags.delete(options);
}
await this.prepareOptions(options);
const { req, url, timeout } = await this.buildRequest(options, {
retryCount: maxRetries - retriesRemaining,
});
await this.prepareRequest(req, { url, options });
/** Not an API request ID, just for correlating local log entries. */
const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
const startTime = Date.now();
loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
retryOfRequestLogID,
method: options.method,
url,
options,
headers: req.headers,
}));
if (options.signal?.aborted) {
throw new Errors.APIUserAbortError();
}
const controller = new AbortController();
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
const headersTime = Date.now();
if (response instanceof globalThis.Error) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
if (options.signal?.aborted) {
throw new Errors.APIUserAbortError();
}
// detect native connection timeout errors
// 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)"
// undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
// others do not provide enough information to distinguish timeouts from other connection errors
const isTimeout = isAbortError(response) ||
/timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
if (retriesRemaining) {
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
retryOfRequestLogID,
url,
durationMs: headersTime - startTime,
message: response.message,
}));
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
}
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
retryOfRequestLogID,
url,
durationMs: headersTime - startTime,
message: response.message,
}));
if (isTimeout) {
throw new Errors.APIConnectionTimeoutError();
}
throw new Errors.APIConnectionError({ cause: response });
}
const specialHeaders = [...response.headers.entries()]
.filter(([name]) => name === 'request-id')
.map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
.join('');
const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
if (!response.ok) {
const shouldRetry = await this.shouldRetry(response, options);
if (retriesRemaining && shouldRetry) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
// We don't need the body of this response.
await Shims.CancelReadableStream(response.body);
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
durationMs: headersTime - startTime,
}));
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
}
const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
const errText = await response.text().catch((err) => castToError(err).message);
const errJSON = safeJSON(errText);
const errMessage = errJSON ? undefined : errText;
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
message: errMessage,
durationMs: Date.now() - startTime,
}));
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
throw err;
}
loggerFor(this).info(responseInfo);
loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
durationMs: headersTime - startTime,
}));
return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
}
getAPIList(path, Page, opts) {
return this.requestAPIList(Page, opts && 'then' in opts ?
opts.then((opts) => ({ method: 'get', path, ...opts }))
: { method: 'get', path, ...opts });
}
requestAPIList(Page, options) {
const request = this.makeRequest(options, null, undefined);
return new Pagination.PagePromise(this, request, Page);
}
async fetchWithTimeout(url, init, ms, controller) {
const { signal, method, ...options } = init || {};
// Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks.
// An arrow function like `() => controller.abort()` captures the surrounding scope,
// which includes the request body and other large objects. When the user passes a
// long-lived AbortSignal, the listener prevents those objects from being GC'd for
// the lifetime of the signal. Using `.bind()` only retains a reference to the
// controller itself.
const abort = this._makeAbort(controller);
if (signal)
signal.addEventListener('abort', abort, { once: true });
const timeout = setTimeout(abort, ms);
const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
(typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
const fetchOptions = {
signal: controller.signal,
...(isReadableBody ? { duplex: 'half' } : {}),
method: 'GET',
...options,
};
if (method) {
// Custom methods like 'patch' need to be uppercased
// See https://github.com/nodejs/undici/issues/2294
fetchOptions.method = method.toUpperCase();
}
try {
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
return await this.fetch.call(undefined, url, fetchOptions);
}
finally {
clearTimeout(timeout);
}
}
async shouldRetry(response, options) {
// Reactive refresh: on a 401 from a request that used the token cache,
// invalidate and retry once. Only fires when this specific request was
// bearer-authenticated (not when an apiKey was used) and only once per
// request — a second 401 after refresh falls through to the normal
// retry policy below (which treats 4xx as non-retryable).
const flags = this._authFlags(options);
if (response.status === 401 &&
this._authState.tokenCache &&
flags.usedTokenCache &&
!flags.didRefreshFor401) {
flags.didRefreshFor401 = true;
this._authState.tokenCache.invalidate();
return true;
}
// Note this is not a standard header.
const shouldRetryHeader = response.headers.get('x-should-retry');
// If the server explicitly says whether or not to retry, obey.
if (shouldRetryHeader === 'true')
return true;
if (shouldRetryHeader === 'false')
return false;
// Retry on request timeouts.
if (response.status === 408)
return true;
// Retry on lock timeouts.
if (response.status === 409)
return true;
// Retry on rate limits.
if (response.status === 429)
return true;
// Retry internal errors.
if (response.status >= 500)
return true;
return false;
}
async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
let timeoutMillis;
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
if (retryAfterMillisHeader) {
const timeoutMs = parseFloat(retryAfterMillisHeader);
if (!Number.isNaN(timeoutMs)) {
timeoutMillis = timeoutMs;
}
}
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
const retryAfterHeader = responseHeaders?.get('retry-after');
if (retryAfterHeader && !timeoutMillis) {
const timeoutSeconds = parseFloat(retryAfterHeader);
if (!Number.isNaN(timeoutSeconds)) {
timeoutMillis = timeoutSeconds * 1000;
}
else {
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
}
}
// If the API asks us to wait a certain amount of time, just do what it
// says, but otherwise calculate a default
if (timeoutMillis === undefined) {
const maxRetries = options.maxRetries ?? this.maxRetries;
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
}
await sleep(timeoutMillis);
return this.makeRequest(options, retriesRemaining - 1, requestLogID);
}
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
const initialRetryDelay = 0.5;
const maxRetryDelay = 8.0;
const numRetries = maxRetries - retriesRemaining;
// Apply exponential backoff, but not more than the max.
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
// Apply some jitter, take up to at most 25 percent of the retry time.
const jitter = 1 - Math.random() * 0.25;
return sleepSeconds * jitter * 1000;
}
calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
const maxTime = 60 * 60 * 1000; // 60 minutes
const defaultTime = 60 * 10 * 1000; // 10 minutes
const expectedTime = (maxTime * maxTokens) / 128000;
if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {
throw new Errors.AnthropicError('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');
}
return defaultTime;
}
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
const options = { ...inputOptions };
const { method, path, query, defaultBaseURL } = options;
// Lazy credential resolution may carry a profile-supplied baseURL. Await
// it before building the request URL so the very first request — and
// requests on withOptions() clones created before resolution settled —
// hit the profile's host rather than the hardcoded default.
if (this._authState.resolution) {
await this._authState.resolution;
}
if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) {
this.baseURL = this._authState.baseURL;
}
const url = this.buildURL(path, query, defaultBaseURL);
if ('timeout' in options)
validatePositiveInteger('timeout', options.timeout);
options.timeout = options.timeout ?? this.timeout;
const { bodyHeaders, body } = this.buildBody({ options });
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
const req = {
method,
headers: reqHeaders,
...(options.signal && { signal: options.signal }),
...(globalThis.ReadableStream &&
body instanceof globalThis.ReadableStream && { duplex: 'half' }),
...(body && { body }),
...(this.fetchOptions ?? {}),
...(options.fetchOptions ?? {}),
};
return { req, url, timeout: options.timeout };
}
async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
let idempotencyHeaders = {};
if (this.idempotencyHeader && method !== 'get') {
if (!options.idempotencyKey)
options.idempotencyKey = this.defaultIdempotencyKey();
idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
}
const headers = buildHeaders([
idempotencyHeaders,
{
Accept: 'application/json',
'User-Agent': this.getUserAgent(),
'X-Stainless-Retry-Count': String(retryCount),
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
...getPlatformHeaders(),
...(this._options.dangerouslyAllowBrowser ?
{ 'anthropic-dangerous-direct-browser-access': 'true' }
: undefined),
'anthropic-version': '2023-06-01',
},
await this.authHeaders(options),
this._options.defaultHeaders,
bodyHeaders,
options.headers,
]);
this.validateHeaders(headers);
return headers.values;
}
_makeAbort(controller) {
// note: we can't just inline this method inside `fetchWithTimeout()` because then the closure
// would capture all request options, and cause a memory leak.
return () => controller.abort();
}
buildBody({ options: { body, headers: rawHeaders } }) {
if (!body) {
return { bodyHeaders: undefined, body: undefined };
}
const headers = buildHeaders([rawHeaders]);
if (
// Pass raw type verbatim
ArrayBuffer.isView(body) ||
body instanceof ArrayBuffer ||
body instanceof DataView ||
(typeof body === 'string' &&
// Preserve legacy string encoding behavior for now
headers.values.has('content-type')) ||
// `Blob` is superset of `File`
(globalThis.Blob && body instanceof globalThis.Blob) ||
// `FormData` -> `multipart/form-data`
body instanceof FormData ||
// `URLSearchParams` -> `application/x-www-form-urlencoded`
body instanceof URLSearchParams ||
// Send chunked stream (each chunk has own `length`)
(globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
return { bodyHeaders: undefined, body: body };
}
else if (typeof body === 'object' &&
(Symbol.asyncIterator in body ||
(Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
}
else if (typeof body === 'object' &&
headers.values.get('content-type') === 'application/x-www-form-urlencoded') {
return {
bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },
body: this.stringifyQuery(body),
};
}
else {
return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
}
}
}
_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() {
return this.baseURL !== 'https://api.anthropic.com';
};
BaseAnthropic.Anthropic = _a;
BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT;
BaseAnthropic.AI_PROMPT = AI_PROMPT;
BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes
BaseAnthropic.AnthropicError = Errors.AnthropicError;
BaseAnthropic.APIError = Errors.APIError;
BaseAnthropic.APIConnectionError = Errors.APIConnectionError;
BaseAnthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
BaseAnthropic.APIUserAbortError = Errors.APIUserAbortError;
BaseAnthropic.NotFoundError = Errors.NotFoundError;
BaseAnthropic.ConflictError = Errors.ConflictError;
BaseAnthropic.RateLimitError = Errors.RateLimitError;
BaseAnthropic.BadRequestError = Errors.BadRequestError;
BaseAnthropic.AuthenticationError = Errors.AuthenticationError;
BaseAnthropic.InternalServerError = Errors.InternalServerError;
BaseAnthropic.PermissionDeniedError = Errors.PermissionDeniedError;
BaseAnthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
BaseAnthropic.toFile = Uploads.toFile;
/**
* API Client for interfacing with the Anthropic API.
*/
export class Anthropic extends BaseAnthropic {
constructor() {
super(...arguments);
this.completions = new API.Completions(this);
this.messages = new API.Messages(this);
this.models = new API.Models(this);
this.beta = new API.Beta(this);
}
}
Anthropic.Completions = Completions;
Anthropic.Messages = Messages;
Anthropic.Models = Models;
Anthropic.Beta = Beta;
//# sourceMappingURL=client.mjs.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,49 @@
import { type BaseAnthropic } from "../client.mjs";
import { type PromiseOrValue } from "../internal/types.mjs";
import { type APIResponseProps, type WithRequestID } from "../internal/parse.mjs";
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export declare class APIPromise<T> extends Promise<WithRequestID<T>> {
#private;
private responsePromise;
private parseResponse;
private parsedPromise;
constructor(client: BaseAnthropic, responsePromise: Promise<APIResponseProps>, parseResponse?: (client: BaseAnthropic, props: APIResponseProps) => PromiseOrValue<WithRequestID<T>>);
_thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U>;
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse(): Promise<Response>;
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
withResponse(): Promise<{
data: T;
response: Response;
request_id: string | null | undefined;
}>;
private parse;
then<TResult1 = WithRequestID<T>, TResult2 = never>(onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<WithRequestID<T> | TResult>;
finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<T>>;
}
//# sourceMappingURL=api-promise.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.d.mts","sourceRoot":"","sources":["../src/core/api-promise.ts"],"names":[],"mappings":"OAEO,EAAE,KAAK,aAAa,EAAE;OAEtB,EAAE,KAAK,cAAc,EAAE;OACvB,EACL,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAGnB;AAED;;;GAGG;AACH,qBAAa,UAAU,CAAC,CAAC,CAAE,SAAQ,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;;IAMxD,OAAO,CAAC,eAAe;IACvB,OAAO,CAAC,aAAa;IANvB,OAAO,CAAC,aAAa,CAAwC;gBAI3D,MAAM,EAAE,aAAa,EACb,eAAe,EAAE,OAAO,CAAC,gBAAgB,CAAC,EAC1C,aAAa,GAAE,CACrB,MAAM,EAAE,aAAa,EACrB,KAAK,EAAE,gBAAgB,KACpB,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAwB;IAW9D,WAAW,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,gBAAgB,KAAK,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC;IAMjF;;;;;;;;;;OAUG;IACH,UAAU,IAAI,OAAO,CAAC,QAAQ,CAAC;IAI/B;;;;;;;;;;;OAWG;IACG,YAAY,IAAI,OAAO,CAAC;QAAE,IAAI,EAAE,CAAC,CAAC;QAAC,QAAQ,EAAE,QAAQ,CAAC;QAAC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;KAAE,CAAC;IAKrG,OAAO,CAAC,KAAK;IASJ,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC,CAAC,CAAC,EAAE,QAAQ,GAAG,KAAK,EACzD,WAAW,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,EAChG,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,GAClF,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAItB,KAAK,CAAC,OAAO,GAAG,KAAK,EAC5B,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,GAChF,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC;IAI7B,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;CAGzF"}
@@ -0,0 +1,49 @@
import { type BaseAnthropic } from "../client.js";
import { type PromiseOrValue } from "../internal/types.js";
import { type APIResponseProps, type WithRequestID } from "../internal/parse.js";
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export declare class APIPromise<T> extends Promise<WithRequestID<T>> {
#private;
private responsePromise;
private parseResponse;
private parsedPromise;
constructor(client: BaseAnthropic, responsePromise: Promise<APIResponseProps>, parseResponse?: (client: BaseAnthropic, props: APIResponseProps) => PromiseOrValue<WithRequestID<T>>);
_thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U>;
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse(): Promise<Response>;
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
withResponse(): Promise<{
data: T;
response: Response;
request_id: string | null | undefined;
}>;
private parse;
then<TResult1 = WithRequestID<T>, TResult2 = never>(onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<WithRequestID<T> | TResult>;
finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<T>>;
}
//# sourceMappingURL=api-promise.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.d.ts","sourceRoot":"","sources":["../src/core/api-promise.ts"],"names":[],"mappings":"OAEO,EAAE,KAAK,aAAa,EAAE;OAEtB,EAAE,KAAK,cAAc,EAAE;OACvB,EACL,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAGnB;AAED;;;GAGG;AACH,qBAAa,UAAU,CAAC,CAAC,CAAE,SAAQ,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;;IAMxD,OAAO,CAAC,eAAe;IACvB,OAAO,CAAC,aAAa;IANvB,OAAO,CAAC,aAAa,CAAwC;gBAI3D,MAAM,EAAE,aAAa,EACb,eAAe,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AM,IAAI,CAAC,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;CAGzF"}
@@ -0,0 +1,76 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _APIPromise_client;
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIPromise = void 0;
const tslib_1 = require("../internal/tslib.js");
const parse_1 = require("../internal/parse.js");
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
class APIPromise extends Promise {
constructor(client, responsePromise, parseResponse = parse_1.defaultParseResponse) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
_APIPromise_client.set(this, void 0);
tslib_1.__classPrivateFieldSet(this, _APIPromise_client, client, "f");
}
_thenUnwrap(transform) {
return new APIPromise(tslib_1.__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => (0, parse_1.addRequestID)(transform(await this.parseResponse(client, props), props), props.response));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response, request_id: response.headers.get('request-id') };
}
parse() {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_1.__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
}
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
}
exports.APIPromise = APIPromise;
_APIPromise_client = new WeakMap();
//# sourceMappingURL=api-promise.js.map
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.js","sourceRoot":"","sources":["../src/core/api-promise.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;AAKtF,gDAK2B;AAE3B;;;GAGG;AACH,MAAa,UAAc,SAAQ,OAAyB;IAI1D,YACE,MAAqB,EACb,eAA0C,EAC1C,gBAGgC,4BAAoB;QAE5D,KAAK,CAAC,CAAC,OAAO,EAAE,EAAE;YAChB,yEAAyE;YACzE,0EAA0E;YAC1E,wBAAwB;YACxB,OAAO,CAAC,IAAW,CAAC,CAAC;QACvB,CAAC,CAAC,CAAC;QAXK,oBAAe,GAAf,eAAe,CAA2B;QAC1C,kBAAa,GAAb,aAAa,CAGuC;QAR9D,qCAAuB;QAgBrB,+BAAA,IAAI,sBAAW,MAAM,MAAA,CAAC;IACxB,CAAC;IAED,WAAW,CAAI,SAAkD;QAC/D,OAAO,IAAI,UAAU,CAAC,+BAAA,IAAI,0BAAQ,EAAE,IAAI,CAAC,eAAe,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,CAChF,IAAA,oBAAY,EAAC,SAAS,CAAC,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,CAAC,EAAE,KAAK,CAAC,QAAQ,CAAC,CACxF,CAAC;IACJ,CAAC;IAED;;;;;;;;;;OAUG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;IACtD,CAAC;IAED;;;;;;;;;;;OAWG;IACH,KAAK,CAAC,YAAY;QAChB,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;QAC9E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;IAC5E,CAAC;IAEO,KAAK;QACX,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACxB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC5C,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,+BAAA,IAAI,0BAAQ,EAAE,IAAI,CAAqC,CACrF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAEQ,IAAI,CACX,WAAgG,EAChG,UAAmF;QAEnF,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IACpD,CAAC;IAEQ,KAAK,CACZ,UAAiF;QAEjF,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACxC,CAAC;IAEQ,OAAO,CAAC,SAA2C;QAC1D,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACzC,CAAC;CACF;AApFD,gCAoFC"}
@@ -0,0 +1,72 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _APIPromise_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { defaultParseResponse, addRequestID, } from "../internal/parse.mjs";
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export class APIPromise extends Promise {
constructor(client, responsePromise, parseResponse = defaultParseResponse) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
_APIPromise_client.set(this, void 0);
__classPrivateFieldSet(this, _APIPromise_client, client, "f");
}
_thenUnwrap(transform) {
return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response, request_id: response.headers.get('request-id') };
}
parse() {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
}
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
}
_APIPromise_client = new WeakMap();
//# sourceMappingURL=api-promise.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.mjs","sourceRoot":"","sources":["../src/core/api-promise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CAAC,EAAE,CAAC;IAC5E,CAAC;IAEO,KAAK;QACX,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACxB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC5C,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,uBAAA,IAAI,0BAAQ,EAAE,IAAI,CAAqC,CACrF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAEQ,IAAI,CACX,WAAgG,EAChG,UAAmF;QAEnF,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IACpD,CAAC;IAEQ,KAAK,CACZ,UAAiF;QAEjF,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACxC,CAAC;IAEQ,OAAO,CAAC,SAA2C;QAC1D,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACzC,CAAC;CACF"}
@@ -0,0 +1,131 @@
/** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ "1.0". */
export declare const CONFIG_FILE_VERSION = "1.0";
/** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ "1.0". */
export declare const CREDENTIALS_FILE_VERSION = "1.0";
/**
* Authentication-mode-specific configuration. On the wire (configs/<profile>.json)
* this is a flat JSON object under the top-level `authentication` key — `type`,
* `credentials_path`, and the variant-specific fields all sit at the same level.
*
* Unknown fields are silently ignored for forward compatibility. Unknown
* authentication types are rejected because the SDK has no way to resolve
* credentials for them.
*/
export type AuthenticationInfo = {
/**
* Filesystem path to the credentials JSON that stores access/refresh tokens.
* Defaults to `<config_dir>/credentials/<profile>.json` when omitted.
*/
credentials_path?: string | undefined;
} & ({
type: 'oidc_federation';
/** Tagged ID (`fdrl_...`) of the federation rule. Required. */
federation_rule_id: string;
/** Optional `svac_...` expected-target check. */
service_account_id?: string | undefined;
identity_token?: {
source: 'file';
path: string;
} | undefined;
/** Display-only; the SDK does not send this on the jwt-bearer exchange. */
scope?: string | undefined;
} | {
type: 'user_oauth';
/** OAuth client ID for refresh. Empty → access token is treated as static. */
client_id?: string | undefined;
/** Display-only; the SDK does not send this on refresh. */
scope?: string | undefined;
/** Console URL the profile was created against. Display-only. */
console_url?: string | undefined;
});
export type AnthropicConfig = {
version?: string;
authentication: AuthenticationInfo;
base_url?: string | undefined;
organization_id?: string | undefined;
workspace_id?: string | undefined;
};
export type AnthropicCredentials = {
version?: string;
type: 'oauth_token';
access_token: string;
expires_at?: number;
refresh_token?: string;
scope?: string;
organization_uuid?: string;
organization_name?: string;
account_email?: string;
};
/**
* Loads the Anthropic configuration for the given (or active) profile.
*
* Returns `null` when running in a browser or no configuration can be resolved.
* Otherwise, returns the configuration based on the config file and environment variables.
*
* **Profile resolution** (first match wins):
* 1. Explicit `profile` argument
* 2. `ANTHROPIC_PROFILE` environment variable
* 3. Contents of `<config_dir>/active_config` file
* 4. `"default"`
*
* **Config resolution:**
* - If `<config_dir>/configs/<profile>.json` exists, it is loaded and
* missing fields are filled from environment variables. Values present
* in the file take precedence — env vars only fill gaps:
* - `ANTHROPIC_BASE_URL` → `base_url`
* - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`
* - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`
* - `ANTHROPIC_SCOPE` → `authentication.scope`
* - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
* - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
* - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
* - If no config file exists, an `oidc_federation` config is synthesized
* entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
* and `ANTHROPIC_ORGANIZATION_ID` are set.
*/
export declare const loadConfig: (profile?: string) => Promise<AnthropicConfig | null>;
/**
* Source-tagged result of {@link loadConfigWithSource}. `fromFile` is `true`
* when `<config_dir>/configs/<profile>.json` exists on disk; `false` when the
* config was synthesized purely from environment variables.
*
* The credential chain uses this distinction to decide whether to back the
* federation exchange with a disk cache: file-backed profiles get a cache at
* `<config_dir>/credentials/<profile>.json`, env-only configs do not.
*/
export type LoadedConfig = {
config: AnthropicConfig;
fromFile: boolean;
};
/**
* Same as {@link loadConfig}, but also reports whether the config was loaded
* from a profile file on disk (`fromFile: true`) or synthesized entirely from
* environment variables (`fromFile: false`).
*/
export declare const loadConfigWithSource: (profile?: string) => Promise<LoadedConfig | null>;
/**
* Loads the credential material for the active profile.
*
* Returns the parsed credentials or `null` when running in a browser or
* no credentials file can be found.
*
* **Profile resolution** (first match wins):
* 1. `ANTHROPIC_PROFILE` environment variable
* 2. Contents of `<config_dir>/active_config` file
* 3. `"default"`
*
* **Credentials path resolution** (first match wins):
* 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
* 2. `<config_dir>/credentials/<profile>.json`
*/
export declare const loadCredentials: () => Promise<AnthropicCredentials | null>;
/**
* Resolves the credentials file path for the given config.
*
* Uses `authentication.credentials_path` from the config if set, otherwise
* falls back to `<config_dir>/credentials/<profile>.json`.
*
* Returns `null` when running in a browser or the path cannot be resolved.
*/
export declare const getCredentialsPath: (config: AnthropicConfig | null, profile?: string) => Promise<string | null>;
//# sourceMappingURL=credentials.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"credentials.d.mts","sourceRoot":"","sources":["../src/core/credentials.ts"],"names":[],"mappings":"AAGA,0FAA0F;AAC1F,eAAO,MAAM,mBAAmB,QAAQ,CAAC;AACzC,8FAA8F;AAC9F,eAAO,MAAM,wBAAwB,QAAQ,CAAC;AAE9C;;;;;;;;GAQG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACvC,GAAG,CACA;IACE,IAAI,EAA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AAU,GAAU,UAAU,MAAM,KAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAEjF,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GAAG;IAAE,MAAM,EAAE,eAAe,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,GAAU,UAAU,MAAM,KAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CA8FxF,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,eAAe,QAAa,OAAO,CAAC,oBAAoB,GAAG,IAAI,CA8B3E,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,GAC7B,QAAQ,eAAe,GAAG,IAAI,EAC9B,UAAU,MAAM,KACf,OAAO,CAAC,MAAM,GAAG,IAAI,CAkBvB,CAAC"}
@@ -0,0 +1,131 @@
/** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ "1.0". */
export declare const CONFIG_FILE_VERSION = "1.0";
/** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ "1.0". */
export declare const CREDENTIALS_FILE_VERSION = "1.0";
/**
* Authentication-mode-specific configuration. On the wire (configs/<profile>.json)
* this is a flat JSON object under the top-level `authentication` key — `type`,
* `credentials_path`, and the variant-specific fields all sit at the same level.
*
* Unknown fields are silently ignored for forward compatibility. Unknown
* authentication types are rejected because the SDK has no way to resolve
* credentials for them.
*/
export type AuthenticationInfo = {
/**
* Filesystem path to the credentials JSON that stores access/refresh tokens.
* Defaults to `<config_dir>/credentials/<profile>.json` when omitted.
*/
credentials_path?: string | undefined;
} & ({
type: 'oidc_federation';
/** Tagged ID (`fdrl_...`) of the federation rule. Required. */
federation_rule_id: string;
/** Optional `svac_...` expected-target check. */
service_account_id?: string | undefined;
identity_token?: {
source: 'file';
path: string;
} | undefined;
/** Display-only; the SDK does not send this on the jwt-bearer exchange. */
scope?: string | undefined;
} | {
type: 'user_oauth';
/** OAuth client ID for refresh. Empty → access token is treated as static. */
client_id?: string | undefined;
/** Display-only; the SDK does not send this on refresh. */
scope?: string | undefined;
/** Console URL the profile was created against. Display-only. */
console_url?: string | undefined;
});
export type AnthropicConfig = {
version?: string;
authentication: AuthenticationInfo;
base_url?: string | undefined;
organization_id?: string | undefined;
workspace_id?: string | undefined;
};
export type AnthropicCredentials = {
version?: string;
type: 'oauth_token';
access_token: string;
expires_at?: number;
refresh_token?: string;
scope?: string;
organization_uuid?: string;
organization_name?: string;
account_email?: string;
};
/**
* Loads the Anthropic configuration for the given (or active) profile.
*
* Returns `null` when running in a browser or no configuration can be resolved.
* Otherwise, returns the configuration based on the config file and environment variables.
*
* **Profile resolution** (first match wins):
* 1. Explicit `profile` argument
* 2. `ANTHROPIC_PROFILE` environment variable
* 3. Contents of `<config_dir>/active_config` file
* 4. `"default"`
*
* **Config resolution:**
* - If `<config_dir>/configs/<profile>.json` exists, it is loaded and
* missing fields are filled from environment variables. Values present
* in the file take precedence — env vars only fill gaps:
* - `ANTHROPIC_BASE_URL` → `base_url`
* - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`
* - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`
* - `ANTHROPIC_SCOPE` → `authentication.scope`
* - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
* - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
* - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
* - If no config file exists, an `oidc_federation` config is synthesized
* entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
* and `ANTHROPIC_ORGANIZATION_ID` are set.
*/
export declare const loadConfig: (profile?: string) => Promise<AnthropicConfig | null>;
/**
* Source-tagged result of {@link loadConfigWithSource}. `fromFile` is `true`
* when `<config_dir>/configs/<profile>.json` exists on disk; `false` when the
* config was synthesized purely from environment variables.
*
* The credential chain uses this distinction to decide whether to back the
* federation exchange with a disk cache: file-backed profiles get a cache at
* `<config_dir>/credentials/<profile>.json`, env-only configs do not.
*/
export type LoadedConfig = {
config: AnthropicConfig;
fromFile: boolean;
};
/**
* Same as {@link loadConfig}, but also reports whether the config was loaded
* from a profile file on disk (`fromFile: true`) or synthesized entirely from
* environment variables (`fromFile: false`).
*/
export declare const loadConfigWithSource: (profile?: string) => Promise<LoadedConfig | null>;
/**
* Loads the credential material for the active profile.
*
* Returns the parsed credentials or `null` when running in a browser or
* no credentials file can be found.
*
* **Profile resolution** (first match wins):
* 1. `ANTHROPIC_PROFILE` environment variable
* 2. Contents of `<config_dir>/active_config` file
* 3. `"default"`
*
* **Credentials path resolution** (first match wins):
* 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
* 2. `<config_dir>/credentials/<profile>.json`
*/
export declare const loadCredentials: () => Promise<AnthropicCredentials | null>;
/**
* Resolves the credentials file path for the given config.
*
* Uses `authentication.credentials_path` from the config if set, otherwise
* falls back to `<config_dir>/credentials/<profile>.json`.
*
* Returns `null` when running in a browser or the path cannot be resolved.
*/
export declare const getCredentialsPath: (config: AnthropicConfig | null, profile?: string) => Promise<string | null>;
//# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../src/core/credentials.ts"],"names":[],"mappings":"AAGA,0FAA0F;AAC1F,eAAO,MAAM,mBAAmB,QAAQ,CAAC;AACzC,8FAA8F;AAC9F,eAAO,MAAM,wBAAwB,QAAQ,CAAC;AAE9C;;;;;;;;GAQG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACvC,GAAG,CACA;IACE,IAAI,EAAE,iBAAiB,CAAC;IACxB,+DAA+D;IAC/D,kBAAkB,EAAE,MAAM,CAAC;IAC3B,iDAAiD;IACjD,kBAAkB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACx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AAE,eAAe,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,GAAU,UAAU,MAAM,KAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CA8FxF,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,eAAe,QAAa,OAAO,CAAC,oBAAoB,GAAG,IAAI,CA8B3E,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,GAC7B,QAAQ,eAAe,GAAG,IAAI,EAC9B,UAAU,MAAM,KACf,OAAO,CAAC,MAAM,GAAG,IAAI,CAkBvB,CAAC"}
@@ -0,0 +1,317 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCredentialsPath = exports.loadCredentials = exports.loadConfigWithSource = exports.loadConfig = exports.CREDENTIALS_FILE_VERSION = exports.CONFIG_FILE_VERSION = void 0;
const detect_platform_1 = require("../internal/detect-platform.js");
const utils_1 = require("../internal/utils.js");
/** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ "1.0". */
exports.CONFIG_FILE_VERSION = '1.0';
/** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ "1.0". */
exports.CREDENTIALS_FILE_VERSION = '1.0';
const PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
function validateProfileName(name) {
if (!name) {
throw new Error('profile name is empty');
}
if (name === '.' || name === '..') {
throw new Error(`profile name "${name}" is not allowed`);
}
if (name.includes('/') || name.includes('\\')) {
throw new Error(`profile name "${name}" must not contain path separators`);
}
if (!PROFILE_NAME_PATTERN.test(name)) {
throw new Error(`profile name "${name}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`);
}
}
/**
* Loads the Anthropic configuration for the given (or active) profile.
*
* Returns `null` when running in a browser or no configuration can be resolved.
* Otherwise, returns the configuration based on the config file and environment variables.
*
* **Profile resolution** (first match wins):
* 1. Explicit `profile` argument
* 2. `ANTHROPIC_PROFILE` environment variable
* 3. Contents of `<config_dir>/active_config` file
* 4. `"default"`
*
* **Config resolution:**
* - If `<config_dir>/configs/<profile>.json` exists, it is loaded and
* missing fields are filled from environment variables. Values present
* in the file take precedence — env vars only fill gaps:
* - `ANTHROPIC_BASE_URL` → `base_url`
* - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`
* - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`
* - `ANTHROPIC_SCOPE` → `authentication.scope`
* - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
* - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
* - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
* - If no config file exists, an `oidc_federation` config is synthesized
* entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
* and `ANTHROPIC_ORGANIZATION_ID` are set.
*/
const loadConfig = async (profile) => {
return (await (0, exports.loadConfigWithSource)(profile))?.config ?? null;
};
exports.loadConfig = loadConfig;
/**
* Same as {@link loadConfig}, but also reports whether the config was loaded
* from a profile file on disk (`fromFile: true`) or synthesized entirely from
* environment variables (`fromFile: false`).
*/
const loadConfigWithSource = async (profile) => {
var _a, _b;
const rootConfigPath = await getRootConfigPath();
if (rootConfigPath === null) {
return null;
}
const profileName = profile ?? (await getActiveProfileName());
if (profileName === null) {
return null;
}
validateProfileName(profileName);
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
const path = await Promise.resolve().then(() => __importStar(require('node:path')));
const configPath = path.join(rootConfigPath, 'configs', `${profileName}.json`);
let configRaw;
try {
configRaw = await fs.promises.readFile(configPath, 'utf-8');
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read config file ${configPath}: ${err}`);
}
configRaw = null;
}
if (configRaw === null) {
const organizationId = (0, utils_1.readEnv)('ANTHROPIC_ORGANIZATION_ID');
const identityTokenFile = (0, utils_1.readEnv)('ANTHROPIC_IDENTITY_TOKEN_FILE');
const federationRuleId = (0, utils_1.readEnv)('ANTHROPIC_FEDERATION_RULE_ID');
if (federationRuleId && organizationId) {
return {
fromFile: false,
config: {
organization_id: organizationId,
// A defaulted-but-empty CI variable (`ANTHROPIC_WORKSPACE_ID=""`) is
// treated as unset — readEnv coerces empty to undefined, and the body
// builder's truthy check skips it — so `"workspace_id": ""` never goes
// on the wire.
workspace_id: (0, utils_1.readEnv)('ANTHROPIC_WORKSPACE_ID'),
base_url: (0, utils_1.readEnv)('ANTHROPIC_BASE_URL'),
authentication: {
type: 'oidc_federation',
federation_rule_id: federationRuleId,
service_account_id: (0, utils_1.readEnv)('ANTHROPIC_SERVICE_ACCOUNT_ID'),
identity_token: identityTokenFile ? { source: 'file', path: identityTokenFile } : undefined,
scope: (0, utils_1.readEnv)('ANTHROPIC_SCOPE'),
},
},
};
}
return null;
}
let config;
try {
config = JSON.parse(configRaw);
}
catch (err) {
throw new Error(`failed to parse config file ${configPath}: ${err}`);
}
if (!config.authentication) {
throw new Error(`config file ${configPath} is missing "authentication"`);
}
const authType = config.authentication.type;
if (authType !== 'oidc_federation' && authType !== 'user_oauth') {
throw new Error(`authentication.type "${authType}" is not a known authentication type`);
}
// File values are authoritative; env vars only fill fields the file left unset.
config.organization_id ?? (config.organization_id = (0, utils_1.readEnv)('ANTHROPIC_ORGANIZATION_ID'));
config.workspace_id ?? (config.workspace_id = (0, utils_1.readEnv)('ANTHROPIC_WORKSPACE_ID'));
config.base_url ?? (config.base_url = (0, utils_1.readEnv)('ANTHROPIC_BASE_URL'));
(_a = config.authentication).scope ?? (_a.scope = (0, utils_1.readEnv)('ANTHROPIC_SCOPE'));
if (config.authentication.type === 'oidc_federation') {
if (!config.authentication.identity_token) {
const identityTokenFile = (0, utils_1.readEnv)('ANTHROPIC_IDENTITY_TOKEN_FILE');
if (identityTokenFile) {
config.authentication.identity_token = {
source: 'file',
path: identityTokenFile,
};
}
}
// Unlike siblings using `??= readEnv()` (which leaves `undefined`), coerce
// to '' so the type stays `string` (always set). The downstream required
// check in credential-chain rejects empty, so semantics match but types are
// cleaner.
if (!config.authentication.federation_rule_id) {
config.authentication.federation_rule_id = (0, utils_1.readEnv)('ANTHROPIC_FEDERATION_RULE_ID') ?? '';
}
(_b = config.authentication).service_account_id ?? (_b.service_account_id = (0, utils_1.readEnv)('ANTHROPIC_SERVICE_ACCOUNT_ID'));
}
return { config, fromFile: true };
};
exports.loadConfigWithSource = loadConfigWithSource;
/**
* Loads the credential material for the active profile.
*
* Returns the parsed credentials or `null` when running in a browser or
* no credentials file can be found.
*
* **Profile resolution** (first match wins):
* 1. `ANTHROPIC_PROFILE` environment variable
* 2. Contents of `<config_dir>/active_config` file
* 3. `"default"`
*
* **Credentials path resolution** (first match wins):
* 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
* 2. `<config_dir>/credentials/<profile>.json`
*/
const loadCredentials = async () => {
const config = await (0, exports.loadConfig)();
const credentialsPath = await (0, exports.getCredentialsPath)(config);
if (!credentialsPath) {
return null;
}
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
let raw;
try {
raw = await fs.promises.readFile(credentialsPath, 'utf-8');
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read credentials file ${credentialsPath}: ${err}`);
}
return null;
}
let creds;
try {
creds = JSON.parse(raw);
}
catch (err) {
throw new Error(`failed to parse credentials file ${credentialsPath}: ${err}`);
}
if (creds.type && creds.type !== 'oauth_token') {
throw new Error(`credentials file ${credentialsPath} has unsupported type "${creds.type}" (want "oauth_token")`);
}
return creds;
};
exports.loadCredentials = loadCredentials;
/**
* Resolves the credentials file path for the given config.
*
* Uses `authentication.credentials_path` from the config if set, otherwise
* falls back to `<config_dir>/credentials/<profile>.json`.
*
* Returns `null` when running in a browser or the path cannot be resolved.
*/
const getCredentialsPath = async (config, profile) => {
if (config?.authentication.credentials_path) {
return config.authentication.credentials_path;
}
const rootConfigPath = await getRootConfigPath();
if (!rootConfigPath) {
return null;
}
const profileName = profile ?? (await getActiveProfileName());
if (!profileName) {
return null;
}
validateProfileName(profileName);
const path = await Promise.resolve().then(() => __importStar(require('node:path')));
return path.join(rootConfigPath, 'credentials', `${profileName}.json`);
};
exports.getCredentialsPath = getCredentialsPath;
const getRootConfigPath = async () => {
if (!supportsLocalConfigFiles()) {
return null;
}
const path = await Promise.resolve().then(() => __importStar(require('node:path')));
// ANTHROPIC_CONFIG_DIR is treated as a trusted path: it is set by the
// process operator, not by remote input, so it is not validated.
const configDir = (0, utils_1.readEnv)('ANTHROPIC_CONFIG_DIR');
if (configDir) {
return configDir;
}
const os = (0, detect_platform_1.getPlatformHeaders)()['X-Stainless-OS'];
if (os === 'Windows') {
const appData = (0, utils_1.readEnv)('APPDATA');
if (appData) {
return path.join(appData, 'Anthropic');
}
const userProfile = (0, utils_1.readEnv)('USERPROFILE');
if (userProfile) {
return path.join(userProfile, 'AppData', 'Roaming', 'Anthropic');
}
// No usable Windows config root — return null so callers fall through to
// "no config available" rather than silently writing under C:\.
return null;
}
const xdgConfigHome = (0, utils_1.readEnv)('XDG_CONFIG_HOME');
if (xdgConfigHome) {
return path.join(xdgConfigHome, 'anthropic');
}
const home = (0, utils_1.readEnv)('HOME');
if (home) {
return path.join(home, '.config', 'anthropic');
}
return null;
};
const supportsLocalConfigFiles = () => {
const runtime = (0, detect_platform_1.getPlatformHeaders)()['X-Stainless-Runtime'];
return runtime === 'node' || runtime === 'deno';
};
const getActiveProfileName = async () => {
const rootConfigPath = await getRootConfigPath();
if (!rootConfigPath) {
return null;
}
const profileName = (0, utils_1.readEnv)('ANTHROPIC_PROFILE');
if (profileName) {
return profileName;
}
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
const path = await Promise.resolve().then(() => __importStar(require('node:path')));
const filePath = path.join(rootConfigPath, 'active_config');
try {
return (await fs.promises.readFile(filePath, 'utf-8')).trim() || 'default';
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read ${filePath}: ${err}`);
}
return 'default';
}
};
//# sourceMappingURL=credentials.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,277 @@
import { getPlatformHeaders } from "../internal/detect-platform.mjs";
import { readEnv } from "../internal/utils.mjs";
/** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ "1.0". */
export const CONFIG_FILE_VERSION = '1.0';
/** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ "1.0". */
export const CREDENTIALS_FILE_VERSION = '1.0';
const PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
function validateProfileName(name) {
if (!name) {
throw new Error('profile name is empty');
}
if (name === '.' || name === '..') {
throw new Error(`profile name "${name}" is not allowed`);
}
if (name.includes('/') || name.includes('\\')) {
throw new Error(`profile name "${name}" must not contain path separators`);
}
if (!PROFILE_NAME_PATTERN.test(name)) {
throw new Error(`profile name "${name}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`);
}
}
/**
* Loads the Anthropic configuration for the given (or active) profile.
*
* Returns `null` when running in a browser or no configuration can be resolved.
* Otherwise, returns the configuration based on the config file and environment variables.
*
* **Profile resolution** (first match wins):
* 1. Explicit `profile` argument
* 2. `ANTHROPIC_PROFILE` environment variable
* 3. Contents of `<config_dir>/active_config` file
* 4. `"default"`
*
* **Config resolution:**
* - If `<config_dir>/configs/<profile>.json` exists, it is loaded and
* missing fields are filled from environment variables. Values present
* in the file take precedence — env vars only fill gaps:
* - `ANTHROPIC_BASE_URL` → `base_url`
* - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`
* - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`
* - `ANTHROPIC_SCOPE` → `authentication.scope`
* - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
* - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
* - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
* - If no config file exists, an `oidc_federation` config is synthesized
* entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
* and `ANTHROPIC_ORGANIZATION_ID` are set.
*/
export const loadConfig = async (profile) => {
return (await loadConfigWithSource(profile))?.config ?? null;
};
/**
* Same as {@link loadConfig}, but also reports whether the config was loaded
* from a profile file on disk (`fromFile: true`) or synthesized entirely from
* environment variables (`fromFile: false`).
*/
export const loadConfigWithSource = async (profile) => {
var _a, _b;
const rootConfigPath = await getRootConfigPath();
if (rootConfigPath === null) {
return null;
}
const profileName = profile ?? (await getActiveProfileName());
if (profileName === null) {
return null;
}
validateProfileName(profileName);
const fs = await import('node:fs');
const path = await import('node:path');
const configPath = path.join(rootConfigPath, 'configs', `${profileName}.json`);
let configRaw;
try {
configRaw = await fs.promises.readFile(configPath, 'utf-8');
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read config file ${configPath}: ${err}`);
}
configRaw = null;
}
if (configRaw === null) {
const organizationId = readEnv('ANTHROPIC_ORGANIZATION_ID');
const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
const federationRuleId = readEnv('ANTHROPIC_FEDERATION_RULE_ID');
if (federationRuleId && organizationId) {
return {
fromFile: false,
config: {
organization_id: organizationId,
// A defaulted-but-empty CI variable (`ANTHROPIC_WORKSPACE_ID=""`) is
// treated as unset — readEnv coerces empty to undefined, and the body
// builder's truthy check skips it — so `"workspace_id": ""` never goes
// on the wire.
workspace_id: readEnv('ANTHROPIC_WORKSPACE_ID'),
base_url: readEnv('ANTHROPIC_BASE_URL'),
authentication: {
type: 'oidc_federation',
federation_rule_id: federationRuleId,
service_account_id: readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID'),
identity_token: identityTokenFile ? { source: 'file', path: identityTokenFile } : undefined,
scope: readEnv('ANTHROPIC_SCOPE'),
},
},
};
}
return null;
}
let config;
try {
config = JSON.parse(configRaw);
}
catch (err) {
throw new Error(`failed to parse config file ${configPath}: ${err}`);
}
if (!config.authentication) {
throw new Error(`config file ${configPath} is missing "authentication"`);
}
const authType = config.authentication.type;
if (authType !== 'oidc_federation' && authType !== 'user_oauth') {
throw new Error(`authentication.type "${authType}" is not a known authentication type`);
}
// File values are authoritative; env vars only fill fields the file left unset.
config.organization_id ?? (config.organization_id = readEnv('ANTHROPIC_ORGANIZATION_ID'));
config.workspace_id ?? (config.workspace_id = readEnv('ANTHROPIC_WORKSPACE_ID'));
config.base_url ?? (config.base_url = readEnv('ANTHROPIC_BASE_URL'));
(_a = config.authentication).scope ?? (_a.scope = readEnv('ANTHROPIC_SCOPE'));
if (config.authentication.type === 'oidc_federation') {
if (!config.authentication.identity_token) {
const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
if (identityTokenFile) {
config.authentication.identity_token = {
source: 'file',
path: identityTokenFile,
};
}
}
// Unlike siblings using `??= readEnv()` (which leaves `undefined`), coerce
// to '' so the type stays `string` (always set). The downstream required
// check in credential-chain rejects empty, so semantics match but types are
// cleaner.
if (!config.authentication.federation_rule_id) {
config.authentication.federation_rule_id = readEnv('ANTHROPIC_FEDERATION_RULE_ID') ?? '';
}
(_b = config.authentication).service_account_id ?? (_b.service_account_id = readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID'));
}
return { config, fromFile: true };
};
/**
* Loads the credential material for the active profile.
*
* Returns the parsed credentials or `null` when running in a browser or
* no credentials file can be found.
*
* **Profile resolution** (first match wins):
* 1. `ANTHROPIC_PROFILE` environment variable
* 2. Contents of `<config_dir>/active_config` file
* 3. `"default"`
*
* **Credentials path resolution** (first match wins):
* 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
* 2. `<config_dir>/credentials/<profile>.json`
*/
export const loadCredentials = async () => {
const config = await loadConfig();
const credentialsPath = await getCredentialsPath(config);
if (!credentialsPath) {
return null;
}
const fs = await import('node:fs');
let raw;
try {
raw = await fs.promises.readFile(credentialsPath, 'utf-8');
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read credentials file ${credentialsPath}: ${err}`);
}
return null;
}
let creds;
try {
creds = JSON.parse(raw);
}
catch (err) {
throw new Error(`failed to parse credentials file ${credentialsPath}: ${err}`);
}
if (creds.type && creds.type !== 'oauth_token') {
throw new Error(`credentials file ${credentialsPath} has unsupported type "${creds.type}" (want "oauth_token")`);
}
return creds;
};
/**
* Resolves the credentials file path for the given config.
*
* Uses `authentication.credentials_path` from the config if set, otherwise
* falls back to `<config_dir>/credentials/<profile>.json`.
*
* Returns `null` when running in a browser or the path cannot be resolved.
*/
export const getCredentialsPath = async (config, profile) => {
if (config?.authentication.credentials_path) {
return config.authentication.credentials_path;
}
const rootConfigPath = await getRootConfigPath();
if (!rootConfigPath) {
return null;
}
const profileName = profile ?? (await getActiveProfileName());
if (!profileName) {
return null;
}
validateProfileName(profileName);
const path = await import('node:path');
return path.join(rootConfigPath, 'credentials', `${profileName}.json`);
};
const getRootConfigPath = async () => {
if (!supportsLocalConfigFiles()) {
return null;
}
const path = await import('node:path');
// ANTHROPIC_CONFIG_DIR is treated as a trusted path: it is set by the
// process operator, not by remote input, so it is not validated.
const configDir = readEnv('ANTHROPIC_CONFIG_DIR');
if (configDir) {
return configDir;
}
const os = getPlatformHeaders()['X-Stainless-OS'];
if (os === 'Windows') {
const appData = readEnv('APPDATA');
if (appData) {
return path.join(appData, 'Anthropic');
}
const userProfile = readEnv('USERPROFILE');
if (userProfile) {
return path.join(userProfile, 'AppData', 'Roaming', 'Anthropic');
}
// No usable Windows config root — return null so callers fall through to
// "no config available" rather than silently writing under C:\.
return null;
}
const xdgConfigHome = readEnv('XDG_CONFIG_HOME');
if (xdgConfigHome) {
return path.join(xdgConfigHome, 'anthropic');
}
const home = readEnv('HOME');
if (home) {
return path.join(home, '.config', 'anthropic');
}
return null;
};
const supportsLocalConfigFiles = () => {
const runtime = getPlatformHeaders()['X-Stainless-Runtime'];
return runtime === 'node' || runtime === 'deno';
};
const getActiveProfileName = async () => {
const rootConfigPath = await getRootConfigPath();
if (!rootConfigPath) {
return null;
}
const profileName = readEnv('ANTHROPIC_PROFILE');
if (profileName) {
return profileName;
}
const fs = await import('node:fs');
const path = await import('node:path');
const filePath = path.join(rootConfigPath, 'active_config');
try {
return (await fs.promises.readFile(filePath, 'utf-8')).trim() || 'default';
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read ${filePath}: ${err}`);
}
return 'default';
}
};
//# sourceMappingURL=credentials.mjs.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,50 @@
import type { ErrorType } from "../resources/shared.mjs";
export declare class AnthropicError extends Error {
}
export declare class APIError<TStatus extends number | undefined = number | undefined, THeaders extends Headers | undefined = Headers | undefined, TError extends Object | undefined = Object | undefined> extends AnthropicError {
/** HTTP status for the response that caused the error */
readonly status: TStatus;
/** HTTP headers for the response that caused the error */
readonly headers: THeaders;
/** JSON body of the response that caused the error */
readonly error: TError;
readonly requestID: string | null | undefined;
/** The `error.type` from the API response body, e.g. `"rate_limit_error"` */
readonly type: ErrorType | null;
constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders, type?: ErrorType | null);
private static makeMessage;
static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError;
}
export declare class APIUserAbortError extends APIError<undefined, undefined, undefined> {
constructor({ message }?: {
message?: string;
});
}
export declare class APIConnectionError extends APIError<undefined, undefined, undefined> {
constructor({ message, cause }: {
message?: string | undefined;
cause?: Error | undefined;
});
}
export declare class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message }?: {
message?: string;
});
}
export declare class BadRequestError extends APIError<400, Headers> {
}
export declare class AuthenticationError extends APIError<401, Headers> {
}
export declare class PermissionDeniedError extends APIError<403, Headers> {
}
export declare class NotFoundError extends APIError<404, Headers> {
}
export declare class ConflictError extends APIError<409, Headers> {
}
export declare class UnprocessableEntityError extends APIError<422, Headers> {
}
export declare class RateLimitError extends APIError<429, Headers> {
}
export declare class InternalServerError extends APIError<number, Headers> {
}
//# sourceMappingURL=error.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"error.d.mts","sourceRoot":"","sources":["../src/core/error.ts"],"names":[],"mappings":"OAGO,KAAK,EAAE,SAAS,EAAE;AAEzB,qBAAa,cAAe,SAAQ,KAAK;CAAG;AAE5C,qBAAa,QAAQ,CACnB,OAAO,SAAS,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,EACvD,QAAQ,SAAS,OAAO,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,EAC1D,MAAM,SAAS,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CACtD,SAAQ,cAAc;IACtB,yDAAyD;IACzD,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,0DAA0D;IAC1D,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;IAC3B,sDAAsD;IACtD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAEvB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAA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QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE5D,qBAAa,aAAc,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE5D,qBAAa,wBAAyB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAEvE,qBAAa,cAAe,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE7D,qBAAa,mBAAoB,SAAQ,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAAG"}
@@ -0,0 +1,50 @@
import type { ErrorType } from "../resources/shared.js";
export declare class AnthropicError extends Error {
}
export declare class APIError<TStatus extends number | undefined = number | undefined, THeaders extends Headers | undefined = Headers | undefined, TError extends Object | undefined = Object | undefined> extends AnthropicError {
/** HTTP status for the response that caused the error */
readonly status: TStatus;
/** HTTP headers for the response that caused the error */
readonly headers: THeaders;
/** JSON body of the response that caused the error */
readonly error: TError;
readonly requestID: string | null | undefined;
/** The `error.type` from the API response body, e.g. `"rate_limit_error"` */
readonly type: ErrorType | null;
constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders, type?: ErrorType | null);
private static makeMessage;
static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError;
}
export declare class APIUserAbortError extends APIError<undefined, undefined, undefined> {
constructor({ message }?: {
message?: string;
});
}
export declare class APIConnectionError extends APIError<undefined, undefined, undefined> {
constructor({ message, cause }: {
message?: string | undefined;
cause?: Error | undefined;
});
}
export declare class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message }?: {
message?: string;
});
}
export declare class BadRequestError extends APIError<400, Headers> {
}
export declare class AuthenticationError extends APIError<401, Headers> {
}
export declare class PermissionDeniedError extends APIError<403, Headers> {
}
export declare class NotFoundError extends APIError<404, Headers> {
}
export declare class ConflictError extends APIError<409, Headers> {
}
export declare class UnprocessableEntityError extends APIError<422, Headers> {
}
export declare class RateLimitError extends APIError<429, Headers> {
}
export declare class Internal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QAAE,OAAO,CAAC,EAAE,MAAM,CAAA;KAAO;CAGnD;AAED,qBAAa,kBAAmB,SAAQ,QAAQ,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC;gBACnE,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QAAC,KAAK,CAAC,EAAE,KAAK,GAAG,SAAS,CAAA;KAAE;CAM5F;AAED,qBAAa,yBAA0B,SAAQ,kBAAkB;gBACnD,EAAE,OAAO,EAAE,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAA;KAAO;CAGnD;AAED,qBAAa,eAAgB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE9D,qBAAa,mBAAoB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAElE,qBAAa,qBAAsB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAEpE,qBAAa,aAAc,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE5D,qBAAa,aAAc,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE5D,qBAAa,wBAAyB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAEvE,qBAAa,cAAe,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE7D,qBAAa,mBAAoB,SAAQ,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAAG"}
@@ -0,0 +1,116 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.InternalServerError = exports.RateLimitError = exports.UnprocessableEntityError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.AuthenticationError = exports.BadRequestError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIUserAbortError = exports.APIError = exports.AnthropicError = void 0;
const errors_1 = require("../internal/errors.js");
class AnthropicError extends Error {
}
exports.AnthropicError = AnthropicError;
class APIError extends AnthropicError {
constructor(status, error, message, headers, type) {
super(`${APIError.makeMessage(status, error, message)}`);
this.status = status;
this.headers = headers;
this.requestID = headers?.get('request-id');
this.error = error;
this.type = type ?? null;
}
static makeMessage(status, error, message) {
const msg = error?.message ?
typeof error.message === 'string' ?
error.message
: JSON.stringify(error.message)
: error ? JSON.stringify(error)
: message;
if (status && msg) {
return `${status} ${msg}`;
}
if (status) {
return `${status} status code (no body)`;
}
if (msg) {
return msg;
}
return '(no status code or body)';
}
static generate(status, errorResponse, message, headers) {
if (!status || !headers) {
return new APIConnectionError({ message, cause: (0, errors_1.castToError)(errorResponse) });
}
const error = errorResponse;
const type = error?.['error']?.['type'];
if (status === 400) {
return new BadRequestError(status, error, message, headers, type);
}
if (status === 401) {
return new AuthenticationError(status, error, message, headers, type);
}
if (status === 403) {
return new PermissionDeniedError(status, error, message, headers, type);
}
if (status === 404) {
return new NotFoundError(status, error, message, headers, type);
}
if (status === 409) {
return new ConflictError(status, error, message, headers, type);
}
if (status === 422) {
return new UnprocessableEntityError(status, error, message, headers, type);
}
if (status === 429) {
return new RateLimitError(status, error, message, headers, type);
}
if (status >= 500) {
return new InternalServerError(status, error, message, headers, type);
}
return new APIError(status, error, message, headers, type);
}
}
exports.APIError = APIError;
class APIUserAbortError extends APIError {
constructor({ message } = {}) {
super(undefined, undefined, message || 'Request was aborted.', undefined);
}
}
exports.APIUserAbortError = APIUserAbortError;
class APIConnectionError extends APIError {
constructor({ message, cause }) {
super(undefined, undefined, message || 'Connection error.', undefined);
// in some environments the 'cause' property is already declared
// @ts-ignore
if (cause)
this.cause = cause;
}
}
exports.APIConnectionError = APIConnectionError;
class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message } = {}) {
super({ message: message ?? 'Request timed out.' });
}
}
exports.APIConnectionTimeoutError = APIConnectionTimeoutError;
class BadRequestError extends APIError {
}
exports.BadRequestError = BadRequestError;
class AuthenticationError extends APIError {
}
exports.AuthenticationError = AuthenticationError;
class PermissionDeniedError extends APIError {
}
exports.PermissionDeniedError = PermissionDeniedError;
class NotFoundError extends APIError {
}
exports.NotFoundError = NotFoundError;
class ConflictError extends APIError {
}
exports.ConflictError = ConflictError;
class UnprocessableEntityError extends APIError {
}
exports.UnprocessableEntityError = UnprocessableEntityError;
class RateLimitError extends APIError {
}
exports.RateLimitError = RateLimitError;
class InternalServerError extends APIError {
}
exports.InternalServerError = InternalServerError;
//# sourceMappingURL=error.js.map
@@ -0,0 +1 @@
{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/core/error.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,kDAAiD;AAGjD,MAAa,cAAe,SAAQ,KAAK;CAAG;AAA5C,wCAA4C;AAE5C,MAAa,QAIX,SAAQ,cAAc;IAatB,YACE,MAAe,EACf,KAAa,EACb,OAA2B,EAC3B,OAAiB,EACjB,IAAuB;QAEvB,KAAK,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,GAAG,CAAC,YAAY,CAAC,CAAC;QAC5C,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,IAAI,CAAC;IAC3B,CAAC;IAEO,MAAM,CAAC,WAAW,CAAC,MAA0B,EAAE,KAAU,EAAE,OAA2B;QAC5F,MAAM,GAAG,GACP,KAAK,EAAE,OAAO,CAAC,CAAC;YACd,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC;gBACjC,KAAK,CAAC,OAAO;gBACf,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK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E,SAAS,CAAC,CAAC;QACvE,gEAAgE;QAChE,aAAa;QACb,IAAI,KAAK;YAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAChC,CAAC;CACF;AAPD,gDAOC;AAED,MAAa,yBAA0B,SAAQ,kBAAkB;IAC/D,YAAY,EAAE,OAAO,KAA2B,EAAE;QAChD,KAAK,CAAC,EAAE,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACtD,CAAC;CACF;AAJD,8DAIC;AAED,MAAa,eAAgB,SAAQ,QAAsB;CAAG;AAA9D,0CAA8D;AAE9D,MAAa,mBAAoB,SAAQ,QAAsB;CAAG;AAAlE,kDAAkE;AAElE,MAAa,qBAAsB,SAAQ,QAAsB;CAAG;AAApE,sDAAoE;AAEpE,MAAa,aAAc,SAAQ,QAAsB;CAAG;AAA5D,sCAA4D;AAE5D,MAAa,aAAc,SAAQ,QAAsB;CAAG;AAA5D,sCAA4D;AAE5D,MAAa,wBAAyB,SAAQ,QAAsB;CAAG;AAAvE,4DAAuE;AAEvE,MAAa,cAAe,SAAQ,QAAsB;CAAG;AAA7D,wCAA6D;AAE7D,MAAa,mBAAoB,SAAQ,QAAyB;CAAG;AAArE,kDAAqE"}
@@ -0,0 +1,100 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { castToError } from "../internal/errors.mjs";
export class AnthropicError extends Error {
}
export class APIError extends AnthropicError {
constructor(status, error, message, headers, type) {
super(`${APIError.makeMessage(status, error, message)}`);
this.status = status;
this.headers = headers;
this.requestID = headers?.get('request-id');
this.error = error;
this.type = type ?? null;
}
static makeMessage(status, error, message) {
const msg = error?.message ?
typeof error.message === 'string' ?
error.message
: JSON.stringify(error.message)
: error ? JSON.stringify(error)
: message;
if (status && msg) {
return `${status} ${msg}`;
}
if (status) {
return `${status} status code (no body)`;
}
if (msg) {
return msg;
}
return '(no status code or body)';
}
static generate(status, errorResponse, message, headers) {
if (!status || !headers) {
return new APIConnectionError({ message, cause: castToError(errorResponse) });
}
const error = errorResponse;
const type = error?.['error']?.['type'];
if (status === 400) {
return new BadRequestError(status, error, message, headers, type);
}
if (status === 401) {
return new AuthenticationError(status, error, message, headers, type);
}
if (status === 403) {
return new PermissionDeniedError(status, error, message, headers, type);
}
if (status === 404) {
return new NotFoundError(status, error, message, headers, type);
}
if (status === 409) {
return new ConflictError(status, error, message, headers, type);
}
if (status === 422) {
return new UnprocessableEntityError(status, error, message, headers, type);
}
if (status === 429) {
return new RateLimitError(status, error, message, headers, type);
}
if (status >= 500) {
return new InternalServerError(status, error, message, headers, type);
}
return new APIError(status, error, message, headers, type);
}
}
export class APIUserAbortError extends APIError {
constructor({ message } = {}) {
super(undefined, undefined, message || 'Request was aborted.', undefined);
}
}
export class APIConnectionError extends APIError {
constructor({ message, cause }) {
super(undefined, undefined, message || 'Connection error.', undefined);
// in some environments the 'cause' property is already declared
// @ts-ignore
if (cause)
this.cause = cause;
}
}
export class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message } = {}) {
super({ message: message ?? 'Request timed out.' });
}
}
export class BadRequestError extends APIError {
}
export class AuthenticationError extends APIError {
}
export class PermissionDeniedError extends APIError {
}
export class NotFoundError extends APIError {
}
export class ConflictError extends APIError {
}
export class UnprocessableEntityError extends APIError {
}
export class RateLimitError extends APIError {
}
export class InternalServerError extends APIError {
}
//# sourceMappingURL=error.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"error.mjs","sourceRoot":"","sources":["../src/core/error.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE;AAGtB,MAAM,OAAO,cAAe,SAAQ,KAAK;CAAG;AAE5C,MAAM,OAAO,QAIX,SAAQ,cAAc;IAatB,YACE,MAAe,EACf,KAAa,EACb,OAA2B,EAC3B,OAAiB,EACjB,IAAuB;QAEvB,KAAK,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;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";
import { APIPromise } from "./api-promise.mjs";
import { type APIResponseProps } from "../internal/parse.mjs";
export type PageRequestOptions = Pick<FinalRequestOptions, 'query' | 'headers' | 'body' | 'path' | 'method'>;
export declare abstract class AbstractPage<Item> implements AsyncIterable<Item> {
#private;
protected options: FinalRequestOptions;
protected response: Response;
protected body: unknown;
constructor(client: BaseAnthropic, response: Response, body: unknown, options: FinalRequestOptions);
abstract nextPageRequestOptions(): PageRequestOptions | null;
abstract getPaginatedItems(): Item[];
hasNextPage(): boolean;
getNextPage(): Promise<this>;
iterPages(): AsyncGenerator<this>;
[Symbol.asyncIterator](): AsyncGenerator<Item>;
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export declare class PagePromise<PageClass extends AbstractPage<Item>, Item = ReturnType<PageClass['getPaginatedItems']>[number]> extends APIPromise<PageClass> implements AsyncIterable<Item> {
constructor(client: BaseAnthropic, request: Promise<APIResponseProps>, Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass);
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
[Symbol.asyncIterator](): AsyncGenerator<Item>;
}
export interface PageResponse<Item> {
data: Array<Item>;
has_more: boolean;
first_id: string | null;
last_id: string | null;
}
export interface PageParams {
/**
* Number of items per page.
*/
limit?: number;
before_id?: string;
after_id?: string;
}
export declare class Page<Item> extends AbstractPage<Item> implements PageResponse<Item> {
data: Array<Item>;
has_more: boolean;
first_id: string | null;
last_id: string | null;
constructor(client: BaseAnthropic, response: Response, body: PageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
hasNextPage(): boolean;
nextPageRequestOptions(): PageRequestOptions | null;
}
export interface TokenPageResponse<Item> {
data: Array<Item>;
has_more: boolean;
next_page: string | null;
}
export interface TokenPageParams {
/**
* Number of items per page.
*/
limit?: number;
page_token?: string;
}
export declare class TokenPage<Item> extends AbstractPage<Item> implements TokenPageResponse<Item> {
data: Array<Item>;
has_more: boolean;
next_page: string | null;
constructor(client: BaseAnthropic, response: Response, body: TokenPageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
hasNextPage(): boolean;
nextPageRequestOptions(): PageRequestOptions | null;
}
export interface PageCursorResponse<Item> {
data: Array<Item>;
next_page: string | null;
}
export interface PageCursorParams {
/**
* Number of items per page.
*/
limit?: number;
page?: string | null;
}
export declare class PageCursor<Item> extends AbstractPage<Item> implements PageCursorResponse<Item> {
data: Array<Item>;
next_page: string | null;
constructor(client: BaseAnthropic, response: Response, body: PageCursorResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
nextPageRequestOptions(): PageRequestOptions | null;
}
//# sourceMappingURL=pagination.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"pagination.d.mts","sourceRoot":"","sources":["../src/core/pagination.ts"],"names":[],"mappings":"OAGO,EAAE,mBAAmB,EAAE;OAEvB,EAAE,KAAK,aAAa,EAAE;OACtB,EAAE,UAAU,EAAE;OACd,EAAE,KAAK,gBAAgB,EAAE;AAGhC,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,mBAAmB,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAC,CAAC;AAE7G,8BAAsB,YAAY,CAAC,IAAI,CAAE,YAAW,aAAa,CAAC,IAAI,CAAC;;IAErE,SAAS,CAAC,OAAO,EAAE,mBAAmB,CAAC;IAEvC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC;gBAEZ,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,mBAAmB;IAOlG,QAAQ,CAAC,sBAAsB,IAAI,kBAAkB,GAAG,IAAI;IAE5D,QAAQ,CAAC,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,CAAC,EAAE,MAAM,CAAC;IAEf,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAED,qBAAa,UAAU,CAAC,IAAI,CAAE,SAAQ,YAAY,CAAC,IAAI,CAAE,YAAW,kBAAkB,CAAC,IAAI,CAAC;IAC1F,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAElB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;gBAGvB,MAAM,EAAE,aAAa,EACrB,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,kBAAkB,CAAC,IAAI,CAAC,EAC9B,OAAO,EAAE,mBAAmB;IAQ9B,iBAAiB,IAAI,IAAI,EAAE;IAI3B,sBAAsB,IAAI,kBAAkB,GAAG,IAAI;CAcpD"}
@@ -0,0 +1,102 @@
import { FinalRequestOptions } from "../internal/request-options.js";
import { type BaseAnthropic } from "../client.js";
import { APIPromise } from "./api-promise.js";
import { type APIResponseProps } from "../internal/parse.js";
export type PageRequestOptions = Pick<FinalRequestOptions, 'query' | 'headers' | 'body' | 'path' | 'method'>;
export declare abstract class AbstractPage<Item> implements AsyncIterable<Item> {
#private;
protected options: FinalRequestOptions;
protected response: Response;
protected body: unknown;
constructor(client: BaseAnthropic, response: Response, body: unknown, options: FinalRequestOptions);
abstract nextPageRequestOptions(): PageRequestOptions | null;
abstract getPaginatedItems(): Item[];
hasNextPage(): boolean;
getNextPage(): Promise<this>;
iterPages(): AsyncGenerator<this>;
[Symbol.asyncIterator](): AsyncGenerator<Item>;
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export declare class PagePromise<PageClass extends AbstractPage<Item>, Item = ReturnType<PageClass['getPaginatedItems']>[number]> extends APIPromise<PageClass> implements AsyncIterable<Item> {
constructor(client: BaseAnthropic, request: Promise<APIResponseProps>, Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass);
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
[Symbol.asyncIterator](): AsyncGenerator<Item>;
}
export interface PageResponse<Item> {
data: Array<Item>;
has_more: boolean;
first_id: string | null;
last_id: string | null;
}
export interface PageParams {
/**
* Number of items per page.
*/
limit?: number;
before_id?: string;
after_id?: string;
}
export declare class Page<Item> extends AbstractPage<Item> implements PageResponse<Item> {
data: Array<Item>;
has_more: boolean;
first_id: string | null;
last_id: string | null;
constructor(client: BaseAnthropic, response: Response, body: PageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
hasNextPage(): boolean;
nextPageRequestOptions(): PageRequestOptions | null;
}
export interface TokenPageResponse<Item> {
data: Array<Item>;
has_more: boolean;
next_page: string | null;
}
export interface TokenPageParams {
/**
* Number of items per page.
*/
limit?: number;
page_token?: string;
}
export declare class TokenPage<Item> extends AbstractPage<Item> implements TokenPageResponse<Item> {
data: Array<Item>;
has_more: boolean;
next_page: string | null;
constructor(client: BaseAnthropic, response: Response, body: TokenPageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
hasNextPage(): boolean;
nextPageRequestOptions(): PageRequestOptions | null;
}
export interface PageCursorResponse<Item> {
data: Array<Item>;
next_page: string | null;
}
export interface PageCursorParams {
/**
* Number of items per page.
*/
limit?: number;
page?: string | null;
}
export declare class PageCursor<Item> extends AbstractPage<Item> implements PageCursorResponse<Item> {
data: Array<Item>;
next_page: string | null;
constructor(client: BaseAnthropic, response: Response, body: PageCursorResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
nextPageRequestOptions(): PageRequestOptions | null;
}
//# sourceMappingURL=pagination.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../src/core/pagination.ts"],"names":[],"mappings":"OAGO,EAAE,mBAAmB,EAAE;OAEvB,EAAE,KAAK,aAAa,EAAE;OACtB,EAAE,UAAU,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I,CAAC;IACxF,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAElB,QAAQ,EAAE,OAAO,CAAC;IAElB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;gBAGvB,MAAM,EAAE,aAAa,EACrB,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,iBAAiB,CAAC,IAAI,CAAC,EAC7B,OAAO,EAAE,mBAAmB;IAS9B,iBAAiB,IAAI,IAAI,EAAE;IAIlB,WAAW,IAAI,OAAO;IAQ/B,sBAAsB,IAAI,kBAAkB,GAAG,IAAI;CAcpD;AAED,MAAM,WAAW,kBAAkB,CAAC,IAAI;IACtC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAElB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAED,qBAAa,UAAU,CAAC,IAAI,CAAE,SAAQ,YAAY,CAAC,IAAI,CAAE,YAAW,kBAAkB,CAAC,IAAI,CAAC;IAC1F,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAElB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;gBAGvB,MAAM,EAAE,aAAa,EACrB,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,kBAAkB,CAAC,IAAI,CAAC,EAC9B,OAAO,EAAE,mBAAmB;IAQ9B,iBAAiB,IAAI,IAAI,EAAE;IAI3B,sBAAsB,IAAI,kBAAkB,GAAG,IAAI;CAcpD"}
@@ -0,0 +1,178 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _AbstractPage_client;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PageCursor = exports.TokenPage = exports.Page = exports.PagePromise = exports.AbstractPage = void 0;
const tslib_1 = require("../internal/tslib.js");
const error_1 = require("./error.js");
const parse_1 = require("../internal/parse.js");
const api_promise_1 = require("./api-promise.js");
const values_1 = require("../internal/utils/values.js");
class AbstractPage {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
tslib_1.__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
this.options = options;
this.response = response;
this.body = body;
}
hasNextPage() {
const items = this.getPaginatedItems();
if (!items.length)
return false;
return this.nextPageRequestOptions() != null;
}
async getNextPage() {
const nextOptions = this.nextPageRequestOptions();
if (!nextOptions) {
throw new error_1.AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
return await tslib_1.__classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
let page = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
for await (const page of this.iterPages()) {
for (const item of page.getPaginatedItems()) {
yield item;
}
}
}
}
exports.AbstractPage = AbstractPage;
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
class PagePromise extends api_promise_1.APIPromise {
constructor(client, request, Page) {
super(client, request, async (client, props) => new Page(client, props.response, await (0, parse_1.defaultParseResponse)(client, props), props.options));
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
async *[Symbol.asyncIterator]() {
const page = await this;
for await (const item of page) {
yield item;
}
}
}
exports.PagePromise = PagePromise;
class Page extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.first_id = body.first_id || null;
this.last_id = body.last_id || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
if (this.options.query?.['before_id']) {
// in reverse
const first_id = this.first_id;
if (!first_id) {
return null;
}
return {
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
before_id: first_id,
},
};
}
const cursor = this.last_id;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
after_id: cursor,
},
};
}
}
exports.Page = Page;
class TokenPage extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
page_token: cursor,
},
};
}
}
exports.TokenPage = TokenPage;
class PageCursor extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
page: cursor,
},
};
}
}
exports.PageCursor = PageCursor;
//# sourceMappingURL=pagination.js.map
@@ -0,0 +1 @@
{"version":3,"file":"pagination.js","sourceRoot":"","sources":["../src/core/pagination.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;AAEtF,sCAAyC;AAEzC,gDAAwE;AAExE,kDAA2C;AAE3C,wDAAoD;AAIpD,MAAsB,YAAY;IAOhC,YAAY,MAAqB,EAAE,QAAkB,EAAE,IAAa,EAAE,OAA4B;QANlG,uCAAuB;QAOrB,+BAAA,IAAI,wBAAW,MAAM,MAAA,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAM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AAM,EAAE,CAAC;YACZ,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO;YACL,GAAG,IAAI,CAAC,OAAO;YACf,KAAK,EAAE;gBACL,GAAG,IAAA,iBAAQ,EAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;gBAC/B,UAAU,EAAE,MAAM;aACnB;SACF,CAAC;IACJ,CAAC;CACF;AA9CD,8BA8CC;AAiBD,MAAa,UAAiB,SAAQ,YAAkB;IAKtD,YACE,MAAqB,EACrB,QAAkB,EAClB,IAA8B,EAC9B,OAA4B;QAE5B,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAEvC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC;IAC1C,CAAC;IAED,iBAAiB;QACf,OAAO,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;IACzB,CAAC;IAED,sBAAsB;QACpB,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC;QAC9B,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO;YACL,GAAG,IAAI,CAAC,OAAO;YACf,KAAK,EAAE;gBACL,GAAG,IAAA,iBAAQ,EAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;gBAC/B,IAAI,EAAE,MAAM;aACb;SACF,CAAC;IACJ,CAAC;CACF;AAnCD,gCAmCC"}
@@ -0,0 +1,170 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _AbstractPage_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { AnthropicError } from "./error.mjs";
import { defaultParseResponse } from "../internal/parse.mjs";
import { APIPromise } from "./api-promise.mjs";
import { maybeObj } from "../internal/utils/values.mjs";
export class AbstractPage {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
this.options = options;
this.response = response;
this.body = body;
}
hasNextPage() {
const items = this.getPaginatedItems();
if (!items.length)
return false;
return this.nextPageRequestOptions() != null;
}
async getNextPage() {
const nextOptions = this.nextPageRequestOptions();
if (!nextOptions) {
throw new AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
let page = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
for await (const page of this.iterPages()) {
for (const item of page.getPaginatedItems()) {
yield item;
}
}
}
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export class PagePromise extends APIPromise {
constructor(client, request, Page) {
super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options));
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
async *[Symbol.asyncIterator]() {
const page = await this;
for await (const item of page) {
yield item;
}
}
}
export class Page extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.first_id = body.first_id || null;
this.last_id = body.last_id || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
if (this.options.query?.['before_id']) {
// in reverse
const first_id = this.first_id;
if (!first_id) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
before_id: first_id,
},
};
}
const cursor = this.last_id;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
after_id: cursor,
},
};
}
}
export class TokenPage extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
page_token: cursor,
},
};
}
}
export class PageCursor extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
page: cursor,
},
};
}
}
//# sourceMappingURL=pagination.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"pagination.mjs","sourceRoot":"","sources":["../src/core/pagination.ts"],"names":[],"mappings":"AAAA,sFAAsF;;;OAE/E,EAAE,cAAc,EAAE;OAElB,EAAE,oBAAoB,EAAiB;OAEvC,EAAE,UAAU,EAAE;OAEd,EAAE,QAAQ,EAAE;AAInB,MAAM,OAAgB,YAAY;IAOhC,YAAY,MAAqB,EAAE,QAAkB,EAAE,IAAa,EAAE,OAA4B;QANlG,uCAAuB;QAOrB,uBAAA,IAAI,wBAAW,MAAM,MAAA,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAMD,WAAW;QACT,MAAM,KAAK,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvC,IAAI,CAAC,KAAK,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAChC,OAAO,IAAI,CAAC,sBAAsB,EAAE,IAAI,IAAI,CAAC;IAC/C,CAAC;IAED,KAAK,CAAC,WAAW;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kB;IAKtD,YACE,MAAqB,EACrB,QAAkB,EAClB,IAA8B,EAC9B,OAA4B;QAE5B,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAEvC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC;IAC1C,CAAC;IAED,iBAAiB;QACf,OAAO,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;IACzB,CAAC;IAED,sBAAsB;QACpB,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC;QAC9B,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO;YACL,GAAG,IAAI,CAAC,OAAO;YACf,KAAK,EAAE;gBACL,GAAG,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;gBAC/B,IAAI,EAAE,MAAM;aACb;SACF,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,6 @@
import { BaseAnthropic } from "../client.mjs";
export declare abstract class APIResource {
protected _client: BaseAnthropic;
constructor(client: BaseAnthropic);
}
//# sourceMappingURL=resource.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"resource.d.mts","sourceRoot":"","sources":["../src/core/resource.ts"],"names":[],"mappings":"OAEO,EAAE,aAAa,EAAE;AAExB,8BAAsB,WAAW;IAC/B,SAAS,CAAC,OAAO,EAAE,aAAa,CAAC;gBAErB,MAAM,EAAE,aAAa;CAGlC"}
@@ -0,0 +1,6 @@
import { BaseAnthropic } from "../client.js";
export declare abstract class APIResource {
protected _client: BaseAnthropic;
constructor(client: BaseAnthropic);
}
//# sourceMappingURL=resource.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/core/resource.ts"],"names":[],"mappings":"OAEO,EAAE,aAAa,EAAE;AAExB,8BAAsB,WAAW;IAC/B,SAAS,CAAC,OAAO,EAAE,aAAa,CAAC;gBAErB,MAAM,EAAE,aAAa;CAGlC"}
@@ -0,0 +1,11 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIResource = void 0;
class APIResource {
constructor(client) {
this._client = client;
}
}
exports.APIResource = APIResource;
//# sourceMappingURL=resource.js.map
@@ -0,0 +1 @@
{"version":3,"file":"resource.js","sourceRoot":"","sources":["../src/core/resource.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAItF,MAAsB,WAAW;IAG/B,YAAY,MAAqB;QAC/B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;CACF;AAND,kCAMC"}
@@ -0,0 +1,7 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export class APIResource {
constructor(client) {
this._client = client;
}
}
//# sourceMappingURL=resource.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"resource.mjs","sourceRoot":"","sources":["../src/core/resource.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAItF,MAAM,OAAgB,WAAW;IAG/B,YAAY,MAAqB;QAC/B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;CACF"}
@@ -0,0 +1,33 @@
import { type ReadableStream } from "../internal/shim-types.mjs";
import type { BaseAnthropic } from "../client.mjs";
export type ServerSentEvent = {
event: string | null;
data: string;
raw: string[];
};
export declare class Stream<Item> implements AsyncIterable<Item> {
#private;
private iterator;
controller: AbortController;
constructor(iterator: () => AsyncIterator<Item>, controller: AbortController, client?: BaseAnthropic);
static fromSSEResponse<Item>(response: Response, controller: AbortController, client?: BaseAnthropic): Stream<Item>;
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController, client?: BaseAnthropic): Stream<Item>;
[Symbol.asyncIterator](): AsyncIterator<Item>;
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee(): [Stream<Item>, Stream<Item>];
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream(): ReadableStream;
}
export declare function _iterSSEMessages(response: Response, controller: AbortController): AsyncGenerator<ServerSentEvent, void, unknown>;
//# sourceMappingURL=streaming.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"streaming.d.mts","sourceRoot":"","sources":["../src/core/streaming.ts"],"names":[],"mappings":"OACO,EAAE,KAAK,cAAc,EAAE;OAQvB,KAAK,EAAE,aAAa,EAAE;AAO7B,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,EAAE,CAAC;CACf,CAAC;AAEF,qBAAa,MAAM,CAAC,IAAI,CAAE,YAAW,aAAa,CAAC,IAAI,CAAC;;IAKpD,OAAO,CAAC,QAAQ;IAJlB,UAAU,EAAE,eAAe,CAAC;gBAIlB,QAAQ,EAAE,MAAM,aAAa,CAAC,IAAI,CAAC,EAC3C,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa;IAMxB,MAAM,CAAC,eAAe,CAAC,IAAI,EACzB,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CAAC,IAAI,CAAC;IAkGf;;;OAGG;IACH,MAAM,CAAC,kBAAkB,CAAC,IAAI,EAC5B,cAAc,EAAE,cAAc,EAC9B,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CAAC,IAAI,CAAC;IA2Cf,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,IAAI,CAAC;IAI7C;;;OAGG;IACH,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAwBnC;;;;OAIG;IACH,gBAAgB,IAAI,cAAc;CAyBnC;AAED,wBAAuB,gBAAgB,CACrC,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,eAAe,GAC1B,cAAc,CAAC,eAAe,EAAE,IAAI,EAAE,OAAO,CAAC,CA6BhD"}
@@ -0,0 +1,33 @@
import { type ReadableStream } from "../internal/shim-types.js";
import type { BaseAnthropic } from "../client.js";
export type ServerSentEvent = {
event: string | null;
data: string;
raw: string[];
};
export declare class Stream<Item> implements AsyncIterable<Item> {
#private;
private iterator;
controller: AbortController;
constructor(iterator: () => AsyncIterator<Item>, controller: AbortController, client?: BaseAnthropic);
static fromSSEResponse<Item>(response: Response, controller: AbortController, client?: BaseAnthropic): Stream<Item>;
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController, client?: BaseAnthropic): Stream<Item>;
[Symbol.asyncIterator](): AsyncIterator<Item>;
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee(): [Stream<Item>, Stream<Item>];
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream(): ReadableStream;
}
export declare function _iterSSEMessages(response: Response, controller: AbortController): AsyncGenerator<ServerSentEvent, void, unknown>;
//# sourceMappingURL=streaming.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"streaming.d.ts","sourceRoot":"","sources":["../src/core/streaming.ts"],"names":[],"mappings":"OACO,EAAE,KAAK,cAAc,EAAE;OAQvB,KAAK,EAAE,aAAa,EAAE;AAO7B,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,EAAE,CAAC;CACf,CAAC;AAEF,qBAAa,MAAM,CAAC,IAAI,CAAE,YAAW,aAAa,CAAC,IAAI,CAAC;;IAKpD,OAAO,CAAC,QAAQ;IAJlB,UAAU,EAAE,eAAe,CAAC;gBAIlB,QAAQ,EAAE,MAAM,aAAa,CAAC,IAAI,CAAC,EAC3C,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa;IAMxB,MAAM,CAAC,eAAe,CAAC,IAAI,EACzB,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CAAC,IAAI,CAAC;IAkGf;;;OAGG;IACH,MAAM,CAAC,kBAAkB,CAAC,IAAI,EAC5B,cAAc,EAAE,cAAc,EAC9B,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CAAC,IAAI,CAAC;IA2Cf,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,IAAI,CAAC;IAI7C;;;OAGG;IACH,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAwBnC;;;;OAIG;IACH,gBAAgB,IAAI,cAAc;CAyBnC;AAED,wBAAuB,gBAAgB,CACrC,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,eAAe,GAC1B,cAAc,CAAC,eAAe,EAAE,IAAI,EAAE,OAAO,CAAC,CA6BhD"}
@@ -0,0 +1,325 @@
"use strict";
var _Stream_client;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stream = void 0;
exports._iterSSEMessages = _iterSSEMessages;
const tslib_1 = require("../internal/tslib.js");
const error_1 = require("./error.js");
const shims_1 = require("../internal/shims.js");
const line_1 = require("../internal/decoders/line.js");
const shims_2 = require("../internal/shims.js");
const errors_1 = require("../internal/errors.js");
const values_1 = require("../internal/utils/values.js");
const bytes_1 = require("../internal/utils/bytes.js");
const log_1 = require("../internal/utils/log.js");
const error_2 = require("./error.js");
class Stream {
constructor(iterator, controller, client) {
this.iterator = iterator;
_Stream_client.set(this, void 0);
this.controller = controller;
tslib_1.__classPrivateFieldSet(this, _Stream_client, client, "f");
}
static fromSSEResponse(response, controller, client) {
let consumed = false;
const logger = client ? (0, log_1.loggerFor)(client) : console;
async function* iterator() {
if (consumed) {
throw new error_1.AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const sse of _iterSSEMessages(response, controller)) {
if (sse.event === 'completion') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'message_start' ||
sse.event === 'message_delta' ||
sse.event === 'message_stop' ||
sse.event === 'content_block_start' ||
sse.event === 'content_block_delta' ||
sse.event === 'content_block_stop' ||
sse.event === 'message' ||
sse.event === 'user.message' ||
sse.event === 'user.interrupt' ||
sse.event === 'user.tool_confirmation' ||
sse.event === 'user.custom_tool_result' ||
sse.event === 'agent.message' ||
sse.event === 'agent.thinking' ||
sse.event === 'agent.tool_use' ||
sse.event === 'agent.tool_result' ||
sse.event === 'agent.mcp_tool_use' ||
sse.event === 'agent.mcp_tool_result' ||
sse.event === 'agent.custom_tool_use' ||
sse.event === 'agent.thread_context_compacted' ||
sse.event === 'session.status_running' ||
sse.event === 'session.status_idle' ||
sse.event === 'session.status_rescheduled' ||
sse.event === 'session.status_terminated' ||
sse.event === 'session.error' ||
sse.event === 'session.deleted' ||
sse.event === 'span.model_request_start' ||
sse.event === 'span.model_request_end' ||
sse.event === 'span.outcome_evaluation_start' ||
sse.event === 'span.outcome_evaluation_ongoing' ||
sse.event === 'span.outcome_evaluation_end' ||
sse.event === 'user.define_outcome' ||
sse.event === 'agent.thread_message_received' ||
sse.event === 'agent.thread_message_sent' ||
sse.event === 'agent.session_thread_message_received' ||
sse.event === 'agent.session_thread_message_sent' ||
sse.event === 'session.thread_created' ||
sse.event === 'session.thread_status_created' ||
sse.event === 'session.thread_status_running' ||
sse.event === 'session.thread_status_idle' ||
sse.event === 'session.thread_status_rescheduled' ||
sse.event === 'session.thread_status_terminated') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'ping') {
continue;
}
if (sse.event === 'error') {
const body = (0, values_1.safeJSON)(sse.data) ?? sse.data;
const type = body?.error?.type;
throw new error_2.APIError(undefined, body, undefined, response.headers, type);
}
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if ((0, errors_1.isAbortError)(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream(readableStream, controller, client) {
let consumed = false;
async function* iterLines() {
const lineDecoder = new line_1.LineDecoder();
const iter = (0, shims_2.ReadableStreamToAsyncIterable)(readableStream);
for await (const chunk of iter) {
for (const line of lineDecoder.decode(chunk)) {
yield line;
}
}
for (const line of lineDecoder.flush()) {
yield line;
}
}
async function* iterator() {
if (consumed) {
throw new error_1.AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const line of iterLines()) {
if (done)
continue;
if (line)
yield JSON.parse(line);
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if ((0, errors_1.isAbortError)(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
[(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {
return this.iterator();
}
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee() {
const left = [];
const right = [];
const iterator = this.iterator();
const teeIterator = (queue) => {
return {
next: () => {
if (queue.length === 0) {
const result = iterator.next();
left.push(result);
right.push(result);
}
return queue.shift();
},
};
};
return [
new Stream(() => teeIterator(left), this.controller, tslib_1.__classPrivateFieldGet(this, _Stream_client, "f")),
new Stream(() => teeIterator(right), this.controller, tslib_1.__classPrivateFieldGet(this, _Stream_client, "f")),
];
}
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream() {
const self = this;
let iter;
return (0, shims_1.makeReadableStream)({
async start() {
iter = self[Symbol.asyncIterator]();
},
async pull(ctrl) {
try {
const { value, done } = await iter.next();
if (done)
return ctrl.close();
const bytes = (0, bytes_1.encodeUTF8)(JSON.stringify(value) + '\n');
ctrl.enqueue(bytes);
}
catch (err) {
ctrl.error(err);
}
},
async cancel() {
await iter.return?.();
},
});
}
}
exports.Stream = Stream;
async function* _iterSSEMessages(response, controller) {
if (!response.body) {
controller.abort();
if (typeof globalThis.navigator !== 'undefined' &&
globalThis.navigator.product === 'ReactNative') {
throw new error_1.AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
}
throw new error_1.AnthropicError(`Attempted to iterate over a response with no body`);
}
const sseDecoder = new SSEDecoder();
const lineDecoder = new line_1.LineDecoder();
const iter = (0, shims_2.ReadableStreamToAsyncIterable)(response.body);
for await (const sseChunk of iterSSEChunks(iter)) {
for (const line of lineDecoder.decode(sseChunk)) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
for (const line of lineDecoder.flush()) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
/**
* Given an async iterable iterator, iterates over it and yields full
* SSE chunks, i.e. yields when a double new-line is encountered.
*/
async function* iterSSEChunks(iterator) {
let data = new Uint8Array();
for await (const chunk of iterator) {
if (chunk == null) {
continue;
}
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
: typeof chunk === 'string' ? (0, bytes_1.encodeUTF8)(chunk)
: chunk;
let newData = new Uint8Array(data.length + binaryChunk.length);
newData.set(data);
newData.set(binaryChunk, data.length);
data = newData;
let patternIndex;
while ((patternIndex = (0, line_1.findDoubleNewlineIndex)(data)) !== -1) {
yield data.slice(0, patternIndex);
data = data.slice(patternIndex);
}
}
if (data.length > 0) {
yield data;
}
}
class SSEDecoder {
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length)
return null;
const sse = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
}
else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
function partition(str, delimiter) {
const index = str.indexOf(delimiter);
if (index !== -1) {
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
}
return [str, '', ''];
}
//# sourceMappingURL=streaming.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,320 @@
var _Stream_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { AnthropicError } from "./error.mjs";
import { makeReadableStream } from "../internal/shims.mjs";
import { findDoubleNewlineIndex, LineDecoder } from "../internal/decoders/line.mjs";
import { ReadableStreamToAsyncIterable } from "../internal/shims.mjs";
import { isAbortError } from "../internal/errors.mjs";
import { safeJSON } from "../internal/utils/values.mjs";
import { encodeUTF8 } from "../internal/utils/bytes.mjs";
import { loggerFor } from "../internal/utils/log.mjs";
import { APIError } from "./error.mjs";
export class Stream {
constructor(iterator, controller, client) {
this.iterator = iterator;
_Stream_client.set(this, void 0);
this.controller = controller;
__classPrivateFieldSet(this, _Stream_client, client, "f");
}
static fromSSEResponse(response, controller, client) {
let consumed = false;
const logger = client ? loggerFor(client) : console;
async function* iterator() {
if (consumed) {
throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const sse of _iterSSEMessages(response, controller)) {
if (sse.event === 'completion') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'message_start' ||
sse.event === 'message_delta' ||
sse.event === 'message_stop' ||
sse.event === 'content_block_start' ||
sse.event === 'content_block_delta' ||
sse.event === 'content_block_stop' ||
sse.event === 'message' ||
sse.event === 'user.message' ||
sse.event === 'user.interrupt' ||
sse.event === 'user.tool_confirmation' ||
sse.event === 'user.custom_tool_result' ||
sse.event === 'agent.message' ||
sse.event === 'agent.thinking' ||
sse.event === 'agent.tool_use' ||
sse.event === 'agent.tool_result' ||
sse.event === 'agent.mcp_tool_use' ||
sse.event === 'agent.mcp_tool_result' ||
sse.event === 'agent.custom_tool_use' ||
sse.event === 'agent.thread_context_compacted' ||
sse.event === 'session.status_running' ||
sse.event === 'session.status_idle' ||
sse.event === 'session.status_rescheduled' ||
sse.event === 'session.status_terminated' ||
sse.event === 'session.error' ||
sse.event === 'session.deleted' ||
sse.event === 'span.model_request_start' ||
sse.event === 'span.model_request_end' ||
sse.event === 'span.outcome_evaluation_start' ||
sse.event === 'span.outcome_evaluation_ongoing' ||
sse.event === 'span.outcome_evaluation_end' ||
sse.event === 'user.define_outcome' ||
sse.event === 'agent.thread_message_received' ||
sse.event === 'agent.thread_message_sent' ||
sse.event === 'agent.session_thread_message_received' ||
sse.event === 'agent.session_thread_message_sent' ||
sse.event === 'session.thread_created' ||
sse.event === 'session.thread_status_created' ||
sse.event === 'session.thread_status_running' ||
sse.event === 'session.thread_status_idle' ||
sse.event === 'session.thread_status_rescheduled' ||
sse.event === 'session.thread_status_terminated') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'ping') {
continue;
}
if (sse.event === 'error') {
const body = safeJSON(sse.data) ?? sse.data;
const type = body?.error?.type;
throw new APIError(undefined, body, undefined, response.headers, type);
}
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if (isAbortError(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream(readableStream, controller, client) {
let consumed = false;
async function* iterLines() {
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(readableStream);
for await (const chunk of iter) {
for (const line of lineDecoder.decode(chunk)) {
yield line;
}
}
for (const line of lineDecoder.flush()) {
yield line;
}
}
async function* iterator() {
if (consumed) {
throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const line of iterLines()) {
if (done)
continue;
if (line)
yield JSON.parse(line);
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if (isAbortError(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
[(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {
return this.iterator();
}
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee() {
const left = [];
const right = [];
const iterator = this.iterator();
const teeIterator = (queue) => {
return {
next: () => {
if (queue.length === 0) {
const result = iterator.next();
left.push(result);
right.push(result);
}
return queue.shift();
},
};
};
return [
new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
];
}
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream() {
const self = this;
let iter;
return makeReadableStream({
async start() {
iter = self[Symbol.asyncIterator]();
},
async pull(ctrl) {
try {
const { value, done } = await iter.next();
if (done)
return ctrl.close();
const bytes = encodeUTF8(JSON.stringify(value) + '\n');
ctrl.enqueue(bytes);
}
catch (err) {
ctrl.error(err);
}
},
async cancel() {
await iter.return?.();
},
});
}
}
export async function* _iterSSEMessages(response, controller) {
if (!response.body) {
controller.abort();
if (typeof globalThis.navigator !== 'undefined' &&
globalThis.navigator.product === 'ReactNative') {
throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
}
throw new AnthropicError(`Attempted to iterate over a response with no body`);
}
const sseDecoder = new SSEDecoder();
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(response.body);
for await (const sseChunk of iterSSEChunks(iter)) {
for (const line of lineDecoder.decode(sseChunk)) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
for (const line of lineDecoder.flush()) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
/**
* Given an async iterable iterator, iterates over it and yields full
* SSE chunks, i.e. yields when a double new-line is encountered.
*/
async function* iterSSEChunks(iterator) {
let data = new Uint8Array();
for await (const chunk of iterator) {
if (chunk == null) {
continue;
}
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
: typeof chunk === 'string' ? encodeUTF8(chunk)
: chunk;
let newData = new Uint8Array(data.length + binaryChunk.length);
newData.set(data);
newData.set(binaryChunk, data.length);
data = newData;
let patternIndex;
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
yield data.slice(0, patternIndex);
data = data.slice(patternIndex);
}
}
if (data.length > 0) {
yield data;
}
}
class SSEDecoder {
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length)
return null;
const sse = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
}
else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
function partition(str, delimiter) {
const index = str.indexOf(delimiter);
if (index !== -1) {
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
}
return [str, '', ''];
}
//# sourceMappingURL=streaming.mjs.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
export { type Uploadable } from "../internal/uploads.mjs";
export { toFile, type ToFileInput } from "../internal/to-file.mjs";
//# sourceMappingURL=uploads.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"uploads.d.mts","sourceRoot":"","sources":["../src/core/uploads.ts"],"names":[],"mappings":"OAAO,EAAE,KAAK,UAAU,EAAE;OACnB,EAAE,MAAM,EAAE,KAAK,WAAW,EAAE"}
@@ -0,0 +1,3 @@
export { type Uploadable } from "../internal/uploads.js";
export { toFile, type ToFileInput } from "../internal/to-file.js";
//# sourceMappingURL=uploads.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"uploads.d.ts","sourceRoot":"","sources":["../src/core/uploads.ts"],"names":[],"mappings":"OAAO,EAAE,KAAK,UAAU,EAAE;OACnB,EAAE,MAAM,EAAE,KAAK,WAAW,EAAE"}
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toFile = void 0;
var to_file_1 = require("../internal/to-file.js");
Object.defineProperty(exports, "toFile", { enumerable: true, get: function () { return to_file_1.toFile; } });
//# sourceMappingURL=uploads.js.map
@@ -0,0 +1 @@
{"version":3,"file":"uploads.js","sourceRoot":"","sources":["../src/core/uploads.ts"],"names":[],"mappings":";;;AACA,kDAA+D;AAAtD,iGAAA,MAAM,OAAA"}
@@ -0,0 +1,2 @@
export { toFile } from "../internal/to-file.mjs";
//# sourceMappingURL=uploads.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"uploads.mjs","sourceRoot":"","sources":["../src/core/uploads.ts"],"names":[],"mappings":"OACO,EAAE,MAAM,EAAoB"}
@@ -0,0 +1,2 @@
export * from "./core/error.mjs";
//# sourceMappingURL=error.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"error.d.mts","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
export * from "./core/error.js";
//# sourceMappingURL=error.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":""}
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("./internal/tslib.js");
/** @deprecated Import from ./core/error instead */
tslib_1.__exportStar(require("./core/error.js"), exports);
//# sourceMappingURL=error.js.map
@@ -0,0 +1 @@
{"version":3,"file":"error.js","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":";;;AAAA,mDAAmD;AACnD,0DAA6B"}
@@ -0,0 +1,2 @@
export * from "./core/error.mjs";
//# sourceMappingURL=error.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"error.mjs","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":""}
@@ -0,0 +1,31 @@
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { Promisable, BetaRunnableTool, BetaToolRunContext } from "../../lib/tools/BetaRunnableTool.mjs";
import { BetaToolResultContentBlockParam } from "../../resources/beta.mjs";
import { AutoParseableBetaOutputFormat } from "../../lib/beta-parser.mjs";
type NoInfer<T> = T extends infer R ? R : never;
/**
* Creates a Tool with a provided JSON schema that can be passed
* to the `.toolRunner()` method. The schema is used to automatically validate
* the input arguments for the tool.
*/
export declare function betaTool<const Schema extends Exclude<JSONSchema, boolean> & {
type: 'object';
}>(options: {
name: string;
inputSchema: Schema;
description: string;
run: (args: NoInfer<FromSchema<Schema>>, context?: BetaToolRunContext) => Promisable<string | Array<BetaToolResultContentBlockParam>>;
}): BetaRunnableTool<NoInfer<FromSchema<Schema>>>;
/**
* Creates a JSON schema output format object from the given JSON schema.
* If this is passed to the `.parse()` method then the response message will contain a
* `.parsed_output` property that is the result of parsing the content with the given JSON schema.
*
*/
export declare function betaJSONSchemaOutputFormat<const Schema extends Exclude<JSONSchema, boolean> & {
type: 'object';
}>(jsonSchema: Schema, options?: {
transform?: boolean;
}): AutoParseableBetaOutputFormat<NoInfer<FromSchema<Schema>>>;
export {};
//# sourceMappingURL=json-schema.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"json-schema.d.mts","sourceRoot":"","sources":["../../src/helpers/beta/json-schema.ts"],"names":[],"mappings":"OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,mBAAmB;OACnD,EAAE,UAAU,EAAE,gBAAgB,EAAE,kBAAkB,EAAE;OACpD,EAAE,+BAA+B,EAAE;OACnC,EAAE,6BAA6B,EAAE;AAIxC,KAAK,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAEhD;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,KAAK,CAAC,MAAM,SAAS,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,EAAE,OAAO,EAAE;IACxG,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,CACH,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,EACjC,OAAO,CAAC,EAAE,kBAAkB,KACzB,UAAU,CAAC,MAAM,GAAG,KAAK,CAAC,+BAA+B,CAAC,CAAC,CAAC;CAClE,GAAG,gBAAgB,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAehD;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACxC,KAAK,CAAC,MAAM,SAAS,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,EAEtE,UAAU,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE;IACR,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,GACA,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAyB5D"}
@@ -0,0 +1,31 @@
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { Promisable, BetaRunnableTool, BetaToolRunContext } from "../../lib/tools/BetaRunnableTool.js";
import { BetaToolResultContentBlockParam } from "../../resources/beta.js";
import { AutoParseableBetaOutputFormat } from "../../lib/beta-parser.js";
type NoInfer<T> = T extends infer R ? R : never;
/**
* Creates a Tool with a provided JSON schema that can be passed
* to the `.toolRunner()` method. The schema is used to automatically validate
* the input arguments for the tool.
*/
export declare function betaTool<const Schema extends Exclude<JSONSchema, boolean> & {
type: 'object';
}>(options: {
name: string;
inputSchema: Schema;
description: string;
run: (args: NoInfer<FromSchema<Schema>>, context?: BetaToolRunContext) => Promisable<string | Array<BetaToolResultContentBlockParam>>;
}): BetaRunnableTool<NoInfer<FromSchema<Schema>>>;
/**
* Creates a JSON schema output format object from the given JSON schema.
* If this is passed to the `.parse()` method then the response message will contain a
* `.parsed_output` property that is the result of parsing the content with the given JSON schema.
*
*/
export declare function betaJSONSchemaOutputFormat<const Schema extends Exclude<JSONSchema, boolean> & {
type: 'object';
}>(jsonSchema: Schema, options?: {
transform?: boolean;
}): AutoParseableBetaOutputFormat<NoInfer<FromSchema<Schema>>>;
export {};
//# sourceMappingURL=json-schema.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"json-schema.d.ts","sourceRoot":"","sources":["../../src/helpers/beta/json-schema.ts"],"names":[],"mappings":"OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,mBAAmB;OACnD,EAAE,UAAU,EAAE,gBAAgB,EAAE,kBAAkB,EAAE;OACpD,EAAE,+BAA+B,EAAE;OACnC,EAAE,6BAA6B,EAAE;AAIxC,KAAK,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAEhD;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,KAAK,CAAC,MAAM,SAAS,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,EAAE,OAAO,EAAE;IACxG,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,CACH,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,EACjC,OAAO,CAAC,EAAE,kBAAkB,KACzB,UAAU,CAAC,MAAM,GAAG,KAAK,CAAC,+BAA+B,CAAC,CAAC,CAAC;CAClE,GAAG,gBAAgB,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAehD;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACxC,KAAK,CAAC,MAAM,SAAS,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,EAEtE,UAAU,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE;IACR,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,GACA,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAyB5D"}
@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.betaTool = betaTool;
exports.betaJSONSchemaOutputFormat = betaJSONSchemaOutputFormat;
const __1 = require("../../index.js");
const transform_json_schema_1 = require("../../lib/transform-json-schema.js");
/**
* Creates a Tool with a provided JSON schema that can be passed
* to the `.toolRunner()` method. The schema is used to automatically validate
* the input arguments for the tool.
*/
function betaTool(options) {
if (options.inputSchema.type !== 'object') {
throw new Error(`JSON schema for tool "${options.name}" must be an object, but got ${options.inputSchema.type}`);
}
return {
type: 'custom',
name: options.name,
input_schema: options.inputSchema,
description: options.description,
run: options.run,
parse: (content) => content,
};
}
/**
* Creates a JSON schema output format object from the given JSON schema.
* If this is passed to the `.parse()` method then the response message will contain a
* `.parsed_output` property that is the result of parsing the content with the given JSON schema.
*
*/
function betaJSONSchemaOutputFormat(jsonSchema, options) {
if (jsonSchema.type !== 'object') {
throw new Error(`JSON schema for tool must be an object, but got ${jsonSchema.type}`);
}
const transform = options?.transform ?? true;
if (transform) {
// todo: doing this is arguably necessary, but it does change the schema the user passed in
// so I'm not sure how we should handle that
jsonSchema = (0, transform_json_schema_1.transformJSONSchema)(jsonSchema);
}
return {
type: 'json_schema',
schema: {
...jsonSchema,
},
parse: (content) => {
try {
return JSON.parse(content);
}
catch (error) {
throw new __1.AnthropicError(`Failed to parse structured output: ${error}`);
}
},
};
}
//# sourceMappingURL=json-schema.js.map
@@ -0,0 +1 @@
{"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../../src/helpers/beta/json-schema.ts"],"names":[],"mappings":";;AAcA,4BAuBC;AAQD,gEAgCC;AAzED,sCAAuC;AACvC,8EAAsE;AAItE;;;;GAIG;AACH,SAAgB,QAAQ,CAAyE,OAQhG;IACC,IAAI,OAAO,CAAC,WAAW,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CACb,yBAAyB,OAAO,CAAC,IAAI,gCAAgC,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,CAChG,CAAC;IACJ,CAAC;IAED,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE,OAAO,CAAC,IAAI;QAClB,YAAY,EAAE,OAAO,CAAC,WAAW;QACjC,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,GA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