@anthropic-ai/sdk 0.92.0 → 0.93.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/client.d.mts +73 -0
- package/client.d.mts.map +1 -1
- package/client.d.ts +73 -0
- package/client.d.ts.map +1 -1
- package/client.js +258 -9
- package/client.js.map +1 -1
- package/client.mjs +258 -9
- package/client.mjs.map +1 -1
- package/core/credentials.d.mts +111 -0
- package/core/credentials.d.mts.map +1 -0
- package/core/credentials.d.ts +111 -0
- package/core/credentials.d.ts.map +1 -0
- package/core/credentials.js +298 -0
- package/core/credentials.js.map +1 -0
- package/core/credentials.mjs +259 -0
- package/core/credentials.mjs.map +1 -0
- package/internal/utils/time.d.mts +3 -0
- package/internal/utils/time.d.mts.map +1 -0
- package/internal/utils/time.d.ts +3 -0
- package/internal/utils/time.d.ts.map +1 -0
- package/internal/utils/time.js +8 -0
- package/internal/utils/time.js.map +1 -0
- package/internal/utils/time.mjs +5 -0
- package/internal/utils/time.mjs.map +1 -0
- package/lib/credentials/credential-chain.d.mts +39 -0
- package/lib/credentials/credential-chain.d.mts.map +1 -0
- package/lib/credentials/credential-chain.d.ts +39 -0
- package/lib/credentials/credential-chain.d.ts.map +1 -0
- package/lib/credentials/credential-chain.js +237 -0
- package/lib/credentials/credential-chain.js.map +1 -0
- package/lib/credentials/credential-chain.mjs +200 -0
- package/lib/credentials/credential-chain.mjs.map +1 -0
- package/lib/credentials/identity-token.d.mts +11 -0
- package/lib/credentials/identity-token.d.mts.map +1 -0
- package/lib/credentials/identity-token.d.ts +11 -0
- package/lib/credentials/identity-token.d.ts.map +1 -0
- package/lib/credentials/identity-token.js +72 -0
- package/lib/credentials/identity-token.js.map +1 -0
- package/lib/credentials/identity-token.mjs +35 -0
- package/lib/credentials/identity-token.mjs.map +1 -0
- package/lib/credentials/oidc-federation.d.mts +28 -0
- package/lib/credentials/oidc-federation.d.mts.map +1 -0
- package/lib/credentials/oidc-federation.d.ts +28 -0
- package/lib/credentials/oidc-federation.d.ts.map +1 -0
- package/lib/credentials/oidc-federation.js +69 -0
- package/lib/credentials/oidc-federation.js.map +1 -0
- package/lib/credentials/oidc-federation.mjs +66 -0
- package/lib/credentials/oidc-federation.mjs.map +1 -0
- package/lib/credentials/token-cache.d.mts +54 -0
- package/lib/credentials/token-cache.d.mts.map +1 -0
- package/lib/credentials/token-cache.d.ts +54 -0
- package/lib/credentials/token-cache.d.ts.map +1 -0
- package/lib/credentials/token-cache.js +112 -0
- package/lib/credentials/token-cache.js.map +1 -0
- package/lib/credentials/token-cache.mjs +108 -0
- package/lib/credentials/token-cache.mjs.map +1 -0
- package/lib/credentials/types.d.mts +96 -0
- package/lib/credentials/types.d.mts.map +1 -0
- package/lib/credentials/types.d.ts +96 -0
- package/lib/credentials/types.d.ts.map +1 -0
- package/lib/credentials/types.js +266 -0
- package/lib/credentials/types.js.map +1 -0
- package/lib/credentials/types.mjs +224 -0
- package/lib/credentials/types.mjs.map +1 -0
- package/lib/credentials/user-oauth.d.mts +21 -0
- package/lib/credentials/user-oauth.d.mts.map +1 -0
- package/lib/credentials/user-oauth.d.ts +21 -0
- package/lib/credentials/user-oauth.d.ts.map +1 -0
- package/lib/credentials/user-oauth.js +130 -0
- package/lib/credentials/user-oauth.js.map +1 -0
- package/lib/credentials/user-oauth.mjs +94 -0
- package/lib/credentials/user-oauth.mjs.map +1 -0
- package/lib/credentials.d.mts +4 -0
- package/lib/credentials.d.mts.map +1 -0
- package/lib/credentials.d.ts +4 -0
- package/lib/credentials.d.ts.map +1 -0
- package/lib/credentials.js +8 -0
- package/lib/credentials.js.map +1 -0
- package/lib/credentials.mjs +3 -0
- package/lib/credentials.mjs.map +1 -0
- package/package.json +1 -1
- package/src/client.ts +342 -14
- package/src/core/credentials.ts +349 -0
- package/src/internal/utils/time.ts +4 -0
- package/src/lib/credentials/credential-chain.ts +284 -0
- package/src/lib/credentials/identity-token.ts +37 -0
- package/src/lib/credentials/oidc-federation.ts +112 -0
- package/src/lib/credentials/token-cache.ts +130 -0
- package/src/lib/credentials/types.ts +295 -0
- package/src/lib/credentials/user-oauth.ts +144 -0
- package/src/lib/credentials.ts +3 -0
- package/src/version.ts +1 -1
- package/version.d.mts +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
package/src/client.ts
CHANGED
|
@@ -14,6 +14,11 @@ import * as Opts from './internal/request-options';
|
|
|
14
14
|
import { stringifyQuery } from './internal/utils/query';
|
|
15
15
|
import { VERSION } from './version';
|
|
16
16
|
import * as Errors from './core/error';
|
|
17
|
+
import type { AccessTokenProvider } from './lib/credentials/types';
|
|
18
|
+
import { OAUTH_API_BETA_HEADER } from './lib/credentials/types';
|
|
19
|
+
import { TokenCache } from './lib/credentials/token-cache';
|
|
20
|
+
import { defaultCredentials, resolveCredentialsFromConfig } from './lib/credentials/credential-chain';
|
|
21
|
+
import type { AnthropicConfig } from './core/credentials';
|
|
17
22
|
import * as Pagination from './core/pagination';
|
|
18
23
|
import {
|
|
19
24
|
type PageCursorParams,
|
|
@@ -247,6 +252,40 @@ import {
|
|
|
247
252
|
} from './internal/utils/log';
|
|
248
253
|
import { isEmptyObj } from './internal/utils/values';
|
|
249
254
|
|
|
255
|
+
/**
|
|
256
|
+
* Shared auth state. A `withOptions()` clone receives the parent's instance
|
|
257
|
+
* (unless the caller overrides auth options) so a clone created before lazy
|
|
258
|
+
* resolution settles observes the same provider/tokenCache/error/extraHeaders
|
|
259
|
+
* as the parent rather than starting an independent resolution.
|
|
260
|
+
*/
|
|
261
|
+
type AuthState = {
|
|
262
|
+
provider: AccessTokenProvider | null;
|
|
263
|
+
tokenCache: TokenCache | null;
|
|
264
|
+
resolution: Promise<void> | null;
|
|
265
|
+
error: unknown;
|
|
266
|
+
extraHeaders: Record<string, string>;
|
|
267
|
+
/**
|
|
268
|
+
* `base_url` from the resolved profile/config, normalized (no trailing
|
|
269
|
+
* slash). Stored on the shared auth state so `withOptions()` clones created
|
|
270
|
+
* before lazy resolution settles can still adopt it on their first request.
|
|
271
|
+
*/
|
|
272
|
+
baseURL?: string | undefined;
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Per-request auth flags, keyed by the FinalRequestOptions object so
|
|
277
|
+
* caller-owned options aren't mutated.
|
|
278
|
+
*/
|
|
279
|
+
type RequestAuthFlags = {
|
|
280
|
+
usedTokenCache: boolean;
|
|
281
|
+
didRefreshFor401: boolean;
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
type InternalClientOptions = ClientOptions & {
|
|
285
|
+
__auth?: AuthState | undefined;
|
|
286
|
+
__baseURLIsExplicit?: boolean | undefined;
|
|
287
|
+
};
|
|
288
|
+
|
|
250
289
|
export type ApiKeySetter = () => Promise<string>;
|
|
251
290
|
|
|
252
291
|
export interface ClientOptions {
|
|
@@ -268,6 +307,40 @@ export interface ClientOptions {
|
|
|
268
307
|
*/
|
|
269
308
|
authToken?: string | null | undefined;
|
|
270
309
|
|
|
310
|
+
/**
|
|
311
|
+
* An {@link AccessTokenProvider} for OAuth/workload-identity authentication.
|
|
312
|
+
*
|
|
313
|
+
* When set, the provider is wrapped in a {@link TokenCache} and used for
|
|
314
|
+
* Bearer token auth on every request. Takes precedence over `authToken`
|
|
315
|
+
* but not `apiKey`.
|
|
316
|
+
*
|
|
317
|
+
* If omitted (and no `apiKey` or `authToken` is provided), the client
|
|
318
|
+
* automatically resolves credentials from config files or environment
|
|
319
|
+
* variables on the first request.
|
|
320
|
+
*/
|
|
321
|
+
credentials?: AccessTokenProvider | null | undefined;
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* An {@link AnthropicConfig} object to resolve credentials from directly,
|
|
325
|
+
* bypassing config-file and environment-variable lookup. This is the
|
|
326
|
+
* TypeScript equivalent of Go's `option.WithConfig(cfg)`.
|
|
327
|
+
*
|
|
328
|
+
* Ignored when `credentials` is set. For `oidc_federation`, the SDK
|
|
329
|
+
* performs the jwt-bearer exchange in-process; for `user_oauth`,
|
|
330
|
+
* `authentication.credentials_path` must point at the credentials file.
|
|
331
|
+
*/
|
|
332
|
+
config?: AnthropicConfig | null | undefined;
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Name of a profile to load from `<config_dir>/configs/<profile>.json`.
|
|
336
|
+
*
|
|
337
|
+
* Equivalent to setting the `ANTHROPIC_PROFILE` environment variable, but
|
|
338
|
+
* scoped to this client instance. As an explicit constructor argument it
|
|
339
|
+
* takes precedence over `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` in the
|
|
340
|
+
* environment. Mutually exclusive with `credentials` and `config`.
|
|
341
|
+
*/
|
|
342
|
+
profile?: string | null | undefined;
|
|
343
|
+
|
|
271
344
|
/**
|
|
272
345
|
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
|
|
273
346
|
*
|
|
@@ -353,6 +426,23 @@ export class BaseAnthropic {
|
|
|
353
426
|
apiKey: string | null;
|
|
354
427
|
authToken: string | null;
|
|
355
428
|
|
|
429
|
+
/**
|
|
430
|
+
* The active credential provider. Default credential resolution runs once
|
|
431
|
+
* at construction time. If it fails, the error is surfaced on every
|
|
432
|
+
* request and the client must be reconstructed — there is no retry path.
|
|
433
|
+
*
|
|
434
|
+
* Clones returned by {@link withOptions} share the parent's auth state
|
|
435
|
+
* (provider, token cache, pending resolution, and any resolution error)
|
|
436
|
+
* unless the caller passes an explicit `apiKey`, `authToken`,
|
|
437
|
+
* `credentials`, `config`, or `profile` override.
|
|
438
|
+
*/
|
|
439
|
+
get credentials(): AccessTokenProvider | null {
|
|
440
|
+
return this._authState.provider;
|
|
441
|
+
}
|
|
442
|
+
private _authState: AuthState;
|
|
443
|
+
private _baseURLIsExplicit: boolean;
|
|
444
|
+
private _requestAuthFlags = new WeakMap<FinalRequestOptions, RequestAuthFlags>();
|
|
445
|
+
|
|
356
446
|
baseURL: string;
|
|
357
447
|
maxRetries: number;
|
|
358
448
|
timeout: number;
|
|
@@ -379,12 +469,18 @@ export class BaseAnthropic {
|
|
|
379
469
|
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
|
|
380
470
|
* @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.
|
|
381
471
|
*/
|
|
382
|
-
constructor({
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
472
|
+
constructor({ baseURL = readEnv('ANTHROPIC_BASE_URL'), apiKey, authToken, ...opts }: ClientOptions = {}) {
|
|
473
|
+
// An explicit `profile` is a constructor-level credential choice; when set,
|
|
474
|
+
// do not let env ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN shadow it.
|
|
475
|
+
if (apiKey === undefined) {
|
|
476
|
+
apiKey = opts.profile != null ? null : readEnv('ANTHROPIC_API_KEY') ?? null;
|
|
477
|
+
}
|
|
478
|
+
if (authToken === undefined) {
|
|
479
|
+
authToken = opts.profile != null ? null : readEnv('ANTHROPIC_AUTH_TOKEN') ?? null;
|
|
480
|
+
}
|
|
481
|
+
if (opts.profile != null && (opts.credentials != null || opts.config != null)) {
|
|
482
|
+
throw new TypeError('Pass at most one of `profile`, `credentials`, or `config`.');
|
|
483
|
+
}
|
|
388
484
|
const options: ClientOptions = {
|
|
389
485
|
apiKey,
|
|
390
486
|
authToken,
|
|
@@ -399,6 +495,13 @@ export class BaseAnthropic {
|
|
|
399
495
|
}
|
|
400
496
|
|
|
401
497
|
this.baseURL = options.baseURL!;
|
|
498
|
+
// After destructuring, `baseURL` is the constructor arg or
|
|
499
|
+
// ANTHROPIC_BASE_URL — both count as an explicit choice that a profile
|
|
500
|
+
// base_url must not override. A falsy value means we fell through to the
|
|
501
|
+
// hardcoded default above and a profile may supply the host. withOptions()
|
|
502
|
+
// propagates the parent's flag via __baseURLIsExplicit so a non-overriding
|
|
503
|
+
// clone doesn't mistake the inherited baseURL for a caller-supplied one.
|
|
504
|
+
this._baseURLIsExplicit = (opts as InternalClientOptions).__baseURLIsExplicit ?? !!baseURL;
|
|
402
505
|
this.timeout = options.timeout ?? BaseAnthropic.DEFAULT_TIMEOUT /* 10 minutes */;
|
|
403
506
|
this.logger = options.logger ?? console;
|
|
404
507
|
const defaultLogLevel = 'warn';
|
|
@@ -425,19 +528,114 @@ export class BaseAnthropic {
|
|
|
425
528
|
options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
|
|
426
529
|
}
|
|
427
530
|
|
|
531
|
+
const inherited = (opts as InternalClientOptions).__auth;
|
|
532
|
+
// Never persist the internal __auth handle on _options — it's a
|
|
533
|
+
// one-shot constructor signal, and leaking it through _options would
|
|
534
|
+
// cause withOptions() to spread a stale value into clones.
|
|
535
|
+
delete (options as InternalClientOptions).__auth;
|
|
536
|
+
delete (options as InternalClientOptions).__baseURLIsExplicit;
|
|
428
537
|
this._options = options;
|
|
429
538
|
|
|
430
539
|
this.apiKey = typeof apiKey === 'string' ? apiKey : null;
|
|
431
540
|
this.authToken = authToken;
|
|
541
|
+
|
|
542
|
+
if (inherited) {
|
|
543
|
+
this._authState = inherited;
|
|
544
|
+
if (!this._baseURLIsExplicit && inherited.baseURL) {
|
|
545
|
+
this.baseURL = inherited.baseURL;
|
|
546
|
+
}
|
|
547
|
+
} else {
|
|
548
|
+
this._authState = { provider: null, tokenCache: null, resolution: null, error: null, extraHeaders: {} };
|
|
549
|
+
|
|
550
|
+
// apiKey/authToken win over credentials/config/profile; don't build a
|
|
551
|
+
// token cache or resolve a config that the request path will then ignore.
|
|
552
|
+
if (this.apiKey == null && this.authToken == null) {
|
|
553
|
+
const credentials = options.credentials ?? null;
|
|
554
|
+
if (credentials) {
|
|
555
|
+
this._authState.provider = credentials;
|
|
556
|
+
this._authState.tokenCache = this._makeTokenCache(credentials);
|
|
557
|
+
} else if (options.config != null) {
|
|
558
|
+
const result = resolveCredentialsFromConfig(options.config, this._credentialResolverOptions());
|
|
559
|
+
this._authState.provider = result.provider;
|
|
560
|
+
this._authState.tokenCache = this._makeTokenCache(result.provider);
|
|
561
|
+
this._authState.extraHeaders = result.extraHeaders;
|
|
562
|
+
this._applyCredentialBaseURL(result.baseURL);
|
|
563
|
+
} else if (options.profile != null) {
|
|
564
|
+
this._authState.resolution = this._resolveDefaultCredentials(options.profile);
|
|
565
|
+
} else {
|
|
566
|
+
// No explicit auth provided — lazily resolve from the credential
|
|
567
|
+
// chain on first request. Errors are captured into _auth.error and
|
|
568
|
+
// surfaced on first use rather than as an unhandled rejection.
|
|
569
|
+
this._authState.resolution = this._resolveDefaultCredentials();
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Stores a profile/config-supplied base URL on the shared auth state and, if
|
|
577
|
+
* the caller did not pin `baseURL` via constructor option or env, adopts it
|
|
578
|
+
* as this client's outbound API host. Precedence: ctor opt > env > profile >
|
|
579
|
+
* hardcoded default.
|
|
580
|
+
*/
|
|
581
|
+
private _applyCredentialBaseURL(baseURL: string | undefined): void {
|
|
582
|
+
if (!baseURL) return;
|
|
583
|
+
const normalized = baseURL.replace(/\/+$/, '');
|
|
584
|
+
this._authState.baseURL = normalized;
|
|
585
|
+
if (!this._baseURLIsExplicit) {
|
|
586
|
+
this.baseURL = normalized;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Options bag passed into the credential chain. `baseURL` here is only the
|
|
592
|
+
* fallback host for the token-exchange POST when the config itself omits
|
|
593
|
+
* `base_url`; the chain returns the config's own `base_url` (if any) on
|
|
594
|
+
* {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL}
|
|
595
|
+
* then adopts for outbound API requests. The two are deliberately decoupled
|
|
596
|
+
* so this fallback never round-trips into precedence.
|
|
597
|
+
*/
|
|
598
|
+
private _credentialResolverOptions() {
|
|
599
|
+
return {
|
|
600
|
+
baseURL: this.baseURL,
|
|
601
|
+
fetch: this.fetch,
|
|
602
|
+
userAgent: this.getUserAgent(),
|
|
603
|
+
onCacheWriteError: (err: unknown) => {
|
|
604
|
+
loggerFor(this).debug('credential cache write failed (best-effort)', err);
|
|
605
|
+
},
|
|
606
|
+
onSafetyWarning: (msg: string) => {
|
|
607
|
+
loggerFor(this).warn(msg);
|
|
608
|
+
},
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
private _makeTokenCache(provider: AccessTokenProvider): TokenCache {
|
|
613
|
+
return new TokenCache(provider, (err) => {
|
|
614
|
+
loggerFor(this).debug('advisory token refresh failed; serving cached token', err);
|
|
615
|
+
});
|
|
432
616
|
}
|
|
433
617
|
|
|
434
618
|
/**
|
|
435
619
|
* Create a new client instance re-using the same options given to the current client with optional overriding.
|
|
436
620
|
*/
|
|
437
621
|
withOptions(options: Partial<ClientOptions>): this {
|
|
438
|
-
|
|
622
|
+
// Share the auth state object unless the caller passes any auth-related
|
|
623
|
+
// key. The `in` check is intentional: even `apiKey: undefined` opts the
|
|
624
|
+
// clone out of sharing (it gets its own _auth and TokenCache, though it
|
|
625
|
+
// may still wrap the parent's provider via the credentials spread below).
|
|
626
|
+
const overridesStructuredAuth = 'credentials' in options || 'config' in options || 'profile' in options;
|
|
627
|
+
const overridesAuth = 'apiKey' in options || 'authToken' in options || overridesStructuredAuth;
|
|
628
|
+
const internal: InternalClientOptions = {
|
|
439
629
|
...this._options,
|
|
440
|
-
baseURL
|
|
630
|
+
// Only forward baseURL when the caller (or env) explicitly chose it.
|
|
631
|
+
// For a non-explicit parent, this.baseURL may have been mutated to the
|
|
632
|
+
// profile-resolved host; pinning that as the clone's options.baseURL
|
|
633
|
+
// would make _options on the clone misreport caller intent and would
|
|
634
|
+
// leave the clone stuck on the parent's host across an auth override.
|
|
635
|
+
// The clone instead receives the construction-time value via
|
|
636
|
+
// ...this._options above and re-adopts the profile host through the
|
|
637
|
+
// shared _authState.baseURL + __baseURLIsExplicit=false path.
|
|
638
|
+
...(this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}),
|
|
441
639
|
maxRetries: this.maxRetries,
|
|
442
640
|
timeout: this.timeout,
|
|
443
641
|
logger: this.logger,
|
|
@@ -446,13 +644,61 @@ export class BaseAnthropic {
|
|
|
446
644
|
fetchOptions: this.fetchOptions,
|
|
447
645
|
apiKey: this.apiKey,
|
|
448
646
|
authToken: this.authToken,
|
|
647
|
+
// credentials: this.credentials is a no-op when __auth is shared (the
|
|
648
|
+
// ctor takes the inherited path and ignores options.credentials); when
|
|
649
|
+
// overridesAuth is true via apiKey/authToken only, it lets the clone
|
|
650
|
+
// build a fresh TokenCache around the parent's provider.
|
|
651
|
+
credentials: this.credentials,
|
|
652
|
+
// When the caller passes a structured-credential override, drop inherited
|
|
653
|
+
// structured-credential options so only `...options` supplies them —
|
|
654
|
+
// otherwise an inherited `credentials`/`config`/`profile` would trip the
|
|
655
|
+
// mutual-exclusion check or precedence over the override.
|
|
656
|
+
...(overridesStructuredAuth ? { credentials: undefined, config: undefined, profile: undefined } : {}),
|
|
449
657
|
...options,
|
|
450
|
-
|
|
451
|
-
|
|
658
|
+
// Always set __auth so any stale value from ...this._options is
|
|
659
|
+
// overwritten. undefined means "build fresh auth from these options".
|
|
660
|
+
__auth: overridesAuth ? undefined : this._authState,
|
|
661
|
+
__baseURLIsExplicit: 'baseURL' in options ? true : this._baseURLIsExplicit,
|
|
662
|
+
};
|
|
663
|
+
return new (this.constructor as any as new (props: ClientOptions) => typeof this)(internal);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* Lazily resolves credentials from config files or environment variables.
|
|
668
|
+
* Called once from the constructor when no explicit auth is provided, or
|
|
669
|
+
* when an explicit `profile` was passed (in which case a missing/unresolved
|
|
670
|
+
* profile is surfaced as an error instead of falling through to "no auth").
|
|
671
|
+
* The returned promise is stored and awaited on the first request.
|
|
672
|
+
*/
|
|
673
|
+
private async _resolveDefaultCredentials(profile?: string): Promise<void> {
|
|
674
|
+
try {
|
|
675
|
+
const result = await defaultCredentials(this._credentialResolverOptions(), profile);
|
|
676
|
+
if (result) {
|
|
677
|
+
this._authState.provider = result.provider;
|
|
678
|
+
this._authState.tokenCache = this._makeTokenCache(result.provider);
|
|
679
|
+
this._authState.extraHeaders = result.extraHeaders;
|
|
680
|
+
this._applyCredentialBaseURL(result.baseURL);
|
|
681
|
+
} else if (profile != null) {
|
|
682
|
+
throw new Errors.AnthropicError(
|
|
683
|
+
`Profile "${profile}" could not be resolved (no <config_dir>/configs/${profile}.json found).`,
|
|
684
|
+
);
|
|
685
|
+
}
|
|
686
|
+
} catch (err) {
|
|
687
|
+
this._authState.error = err;
|
|
688
|
+
} finally {
|
|
689
|
+
this._authState.resolution = null;
|
|
690
|
+
}
|
|
452
691
|
}
|
|
453
692
|
|
|
454
693
|
/**
|
|
455
694
|
* Check whether the base URL is set to its default.
|
|
695
|
+
*
|
|
696
|
+
* A profile-supplied `base_url` counts as an override here: a profile that
|
|
697
|
+
* pins a non-default host is declaring "this whole client targets deployment
|
|
698
|
+
* X", so per-endpoint {@link RequestOptions.defaultBaseURL} hints must not
|
|
699
|
+
* silently route individual calls back to production. No generated resource
|
|
700
|
+
* currently sets `defaultBaseURL`, so this is documenting intent for when
|
|
701
|
+
* one does.
|
|
456
702
|
*/
|
|
457
703
|
#baseURLOverridden(): boolean {
|
|
458
704
|
return this.baseURL !== 'https://api.anthropic.com';
|
|
@@ -466,6 +712,12 @@ export class BaseAnthropic {
|
|
|
466
712
|
if (values.get('x-api-key') || values.get('authorization')) {
|
|
467
713
|
return;
|
|
468
714
|
}
|
|
715
|
+
if (this._authState.error) {
|
|
716
|
+
throw this._authState.error;
|
|
717
|
+
}
|
|
718
|
+
if (this._authState.tokenCache || this._authState.resolution) {
|
|
719
|
+
return; // auth will be injected per-request via authHeaders
|
|
720
|
+
}
|
|
469
721
|
|
|
470
722
|
if (this.apiKey && values.get('x-api-key')) {
|
|
471
723
|
return;
|
|
@@ -482,11 +734,35 @@ export class BaseAnthropic {
|
|
|
482
734
|
}
|
|
483
735
|
|
|
484
736
|
throw new Error(
|
|
485
|
-
'Could not resolve authentication method. Expected
|
|
737
|
+
'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',
|
|
486
738
|
);
|
|
487
739
|
}
|
|
488
740
|
|
|
741
|
+
private _authFlags(opts: FinalRequestOptions): RequestAuthFlags {
|
|
742
|
+
let flags = this._requestAuthFlags.get(opts);
|
|
743
|
+
if (!flags) {
|
|
744
|
+
flags = { usedTokenCache: false, didRefreshFor401: false };
|
|
745
|
+
this._requestAuthFlags.set(opts, flags);
|
|
746
|
+
}
|
|
747
|
+
return flags;
|
|
748
|
+
}
|
|
749
|
+
|
|
489
750
|
protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
|
|
751
|
+
// Wait for lazy credential resolution if it's in progress. If it failed,
|
|
752
|
+
// return no auth headers — validateHeaders surfaces the stored error
|
|
753
|
+
// after the explicit-header escape hatch has had a chance to apply.
|
|
754
|
+
if (this._authState.resolution) {
|
|
755
|
+
await this._authState.resolution;
|
|
756
|
+
}
|
|
757
|
+
if (this._authState.error) {
|
|
758
|
+
return undefined;
|
|
759
|
+
}
|
|
760
|
+
// If we have a token cache and no API key is set, use token auth
|
|
761
|
+
if (this._authState.tokenCache && this.apiKey == null) {
|
|
762
|
+
const token = await this._authState.tokenCache.getToken();
|
|
763
|
+
this._authFlags(opts).usedTokenCache = true;
|
|
764
|
+
return buildHeaders([{ Authorization: `Bearer ${token}` }]);
|
|
765
|
+
}
|
|
490
766
|
return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
|
|
491
767
|
}
|
|
492
768
|
|
|
@@ -578,7 +854,28 @@ export class BaseAnthropic {
|
|
|
578
854
|
protected async prepareRequest(
|
|
579
855
|
request: RequestInit,
|
|
580
856
|
{ url, options }: { url: string; options: FinalRequestOptions },
|
|
581
|
-
): Promise<void> {
|
|
857
|
+
): Promise<void> {
|
|
858
|
+
// Append auth-derived headers when using token auth. Done here (after all
|
|
859
|
+
// header merging) rather than in authHeaders() so we append to any existing
|
|
860
|
+
// anthropic-beta values instead of being overwritten by later header sources.
|
|
861
|
+
if (this._authState.tokenCache && this.apiKey == null) {
|
|
862
|
+
// Normalize to a Headers instance — custom fetch impls or polyfills can
|
|
863
|
+
// hand back arrays / plain objects, and silently dropping the beta
|
|
864
|
+
// header in that case would surface as a confusing server-side 4xx.
|
|
865
|
+
const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers);
|
|
866
|
+
for (const [k, v] of Object.entries(this._authState.extraHeaders)) {
|
|
867
|
+
if (!headers.has(k)) headers.set(k, v);
|
|
868
|
+
}
|
|
869
|
+
const existing = headers
|
|
870
|
+
.get('anthropic-beta')
|
|
871
|
+
?.split(',')
|
|
872
|
+
.map((s) => s.trim());
|
|
873
|
+
if (!existing?.includes(OAUTH_API_BETA_HEADER)) {
|
|
874
|
+
headers.append('anthropic-beta', OAUTH_API_BETA_HEADER);
|
|
875
|
+
}
|
|
876
|
+
request.headers = headers;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
582
879
|
|
|
583
880
|
get<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
|
|
584
881
|
return this.methodRequest('get', path, opts);
|
|
@@ -628,6 +925,9 @@ export class BaseAnthropic {
|
|
|
628
925
|
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
629
926
|
if (retriesRemaining == null) {
|
|
630
927
|
retriesRemaining = maxRetries;
|
|
928
|
+
// Top-level call: reset per-request auth flags so a reused options object
|
|
929
|
+
// (via client.request(opts)) doesn't carry stale 401-refresh state.
|
|
930
|
+
this._requestAuthFlags.delete(options);
|
|
631
931
|
}
|
|
632
932
|
|
|
633
933
|
await this.prepareOptions(options);
|
|
@@ -716,7 +1016,7 @@ export class BaseAnthropic {
|
|
|
716
1016
|
} with status ${response.status} in ${headersTime - startTime}ms`;
|
|
717
1017
|
|
|
718
1018
|
if (!response.ok) {
|
|
719
|
-
const shouldRetry = await this.shouldRetry(response);
|
|
1019
|
+
const shouldRetry = await this.shouldRetry(response, options);
|
|
720
1020
|
if (retriesRemaining && shouldRetry) {
|
|
721
1021
|
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
722
1022
|
|
|
@@ -846,7 +1146,24 @@ export class BaseAnthropic {
|
|
|
846
1146
|
}
|
|
847
1147
|
}
|
|
848
1148
|
|
|
849
|
-
private async shouldRetry(response: Response): Promise<boolean> {
|
|
1149
|
+
private async shouldRetry(response: Response, options: FinalRequestOptions): Promise<boolean> {
|
|
1150
|
+
// Reactive refresh: on a 401 from a request that used the token cache,
|
|
1151
|
+
// invalidate and retry once. Only fires when this specific request was
|
|
1152
|
+
// bearer-authenticated (not when an apiKey was used) and only once per
|
|
1153
|
+
// request — a second 401 after refresh falls through to the normal
|
|
1154
|
+
// retry policy below (which treats 4xx as non-retryable).
|
|
1155
|
+
const flags = this._authFlags(options);
|
|
1156
|
+
if (
|
|
1157
|
+
response.status === 401 &&
|
|
1158
|
+
this._authState.tokenCache &&
|
|
1159
|
+
flags.usedTokenCache &&
|
|
1160
|
+
!flags.didRefreshFor401
|
|
1161
|
+
) {
|
|
1162
|
+
flags.didRefreshFor401 = true;
|
|
1163
|
+
this._authState.tokenCache.invalidate();
|
|
1164
|
+
return true;
|
|
1165
|
+
}
|
|
1166
|
+
|
|
850
1167
|
// Note this is not a standard header.
|
|
851
1168
|
const shouldRetryHeader = response.headers.get('x-should-retry');
|
|
852
1169
|
|
|
@@ -944,6 +1261,17 @@ export class BaseAnthropic {
|
|
|
944
1261
|
const options = { ...inputOptions };
|
|
945
1262
|
const { method, path, query, defaultBaseURL } = options;
|
|
946
1263
|
|
|
1264
|
+
// Lazy credential resolution may carry a profile-supplied baseURL. Await
|
|
1265
|
+
// it before building the request URL so the very first request — and
|
|
1266
|
+
// requests on withOptions() clones created before resolution settled —
|
|
1267
|
+
// hit the profile's host rather than the hardcoded default.
|
|
1268
|
+
if (this._authState.resolution) {
|
|
1269
|
+
await this._authState.resolution;
|
|
1270
|
+
}
|
|
1271
|
+
if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) {
|
|
1272
|
+
this.baseURL = this._authState.baseURL;
|
|
1273
|
+
}
|
|
1274
|
+
|
|
947
1275
|
const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
|
|
948
1276
|
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
|
|
949
1277
|
options.timeout = options.timeout ?? this.timeout;
|