@anthropic-ai/sdk 0.91.1 → 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.
Files changed (167) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/client.d.mts +73 -0
  3. package/client.d.mts.map +1 -1
  4. package/client.d.ts +73 -0
  5. package/client.d.ts.map +1 -1
  6. package/client.js +269 -9
  7. package/client.js.map +1 -1
  8. package/client.mjs +269 -9
  9. package/client.mjs.map +1 -1
  10. package/core/credentials.d.mts +111 -0
  11. package/core/credentials.d.mts.map +1 -0
  12. package/core/credentials.d.ts +111 -0
  13. package/core/credentials.d.ts.map +1 -0
  14. package/core/credentials.js +298 -0
  15. package/core/credentials.js.map +1 -0
  16. package/core/credentials.mjs +259 -0
  17. package/core/credentials.mjs.map +1 -0
  18. package/internal/types.d.mts +12 -6
  19. package/internal/types.d.ts +12 -6
  20. package/internal/utils/time.d.mts +3 -0
  21. package/internal/utils/time.d.mts.map +1 -0
  22. package/internal/utils/time.d.ts +3 -0
  23. package/internal/utils/time.d.ts.map +1 -0
  24. package/internal/utils/time.js +8 -0
  25. package/internal/utils/time.js.map +1 -0
  26. package/internal/utils/time.mjs +5 -0
  27. package/internal/utils/time.mjs.map +1 -0
  28. package/lib/credentials/credential-chain.d.mts +39 -0
  29. package/lib/credentials/credential-chain.d.mts.map +1 -0
  30. package/lib/credentials/credential-chain.d.ts +39 -0
  31. package/lib/credentials/credential-chain.d.ts.map +1 -0
  32. package/lib/credentials/credential-chain.js +237 -0
  33. package/lib/credentials/credential-chain.js.map +1 -0
  34. package/lib/credentials/credential-chain.mjs +200 -0
  35. package/lib/credentials/credential-chain.mjs.map +1 -0
  36. package/lib/credentials/identity-token.d.mts +11 -0
  37. package/lib/credentials/identity-token.d.mts.map +1 -0
  38. package/lib/credentials/identity-token.d.ts +11 -0
  39. package/lib/credentials/identity-token.d.ts.map +1 -0
  40. package/lib/credentials/identity-token.js +72 -0
  41. package/lib/credentials/identity-token.js.map +1 -0
  42. package/lib/credentials/identity-token.mjs +35 -0
  43. package/lib/credentials/identity-token.mjs.map +1 -0
  44. package/lib/credentials/oidc-federation.d.mts +28 -0
  45. package/lib/credentials/oidc-federation.d.mts.map +1 -0
  46. package/lib/credentials/oidc-federation.d.ts +28 -0
  47. package/lib/credentials/oidc-federation.d.ts.map +1 -0
  48. package/lib/credentials/oidc-federation.js +69 -0
  49. package/lib/credentials/oidc-federation.js.map +1 -0
  50. package/lib/credentials/oidc-federation.mjs +66 -0
  51. package/lib/credentials/oidc-federation.mjs.map +1 -0
  52. package/lib/credentials/token-cache.d.mts +54 -0
  53. package/lib/credentials/token-cache.d.mts.map +1 -0
  54. package/lib/credentials/token-cache.d.ts +54 -0
  55. package/lib/credentials/token-cache.d.ts.map +1 -0
  56. package/lib/credentials/token-cache.js +112 -0
  57. package/lib/credentials/token-cache.js.map +1 -0
  58. package/lib/credentials/token-cache.mjs +108 -0
  59. package/lib/credentials/token-cache.mjs.map +1 -0
  60. package/lib/credentials/types.d.mts +96 -0
  61. package/lib/credentials/types.d.mts.map +1 -0
  62. package/lib/credentials/types.d.ts +96 -0
  63. package/lib/credentials/types.d.ts.map +1 -0
  64. package/lib/credentials/types.js +266 -0
  65. package/lib/credentials/types.js.map +1 -0
  66. package/lib/credentials/types.mjs +224 -0
  67. package/lib/credentials/types.mjs.map +1 -0
  68. package/lib/credentials/user-oauth.d.mts +21 -0
  69. package/lib/credentials/user-oauth.d.mts.map +1 -0
  70. package/lib/credentials/user-oauth.d.ts +21 -0
  71. package/lib/credentials/user-oauth.d.ts.map +1 -0
  72. package/lib/credentials/user-oauth.js +130 -0
  73. package/lib/credentials/user-oauth.js.map +1 -0
  74. package/lib/credentials/user-oauth.mjs +94 -0
  75. package/lib/credentials/user-oauth.mjs.map +1 -0
  76. package/lib/credentials.d.mts +4 -0
  77. package/lib/credentials.d.mts.map +1 -0
  78. package/lib/credentials.d.ts +4 -0
  79. package/lib/credentials.d.ts.map +1 -0
  80. package/lib/credentials.js +8 -0
  81. package/lib/credentials.js.map +1 -0
  82. package/lib/credentials.mjs +3 -0
  83. package/lib/credentials.mjs.map +1 -0
  84. package/package.json +1 -1
  85. package/resources/beta/environments.d.mts +1 -1
  86. package/resources/beta/environments.d.ts +1 -1
  87. package/resources/beta/index.d.mts +1 -1
  88. package/resources/beta/index.d.mts.map +1 -1
  89. package/resources/beta/index.d.ts +1 -1
  90. package/resources/beta/index.d.ts.map +1 -1
  91. package/resources/beta/index.js.map +1 -1
  92. package/resources/beta/index.mjs.map +1 -1
  93. package/resources/beta/memory-stores/memories.d.mts +126 -11
  94. package/resources/beta/memory-stores/memories.d.mts.map +1 -1
  95. package/resources/beta/memory-stores/memories.d.ts +126 -11
  96. package/resources/beta/memory-stores/memories.d.ts.map +1 -1
  97. package/resources/beta/memory-stores/memories.js +5 -5
  98. package/resources/beta/memory-stores/memories.mjs +5 -5
  99. package/resources/beta/memory-stores/memory-stores.d.mts +58 -14
  100. package/resources/beta/memory-stores/memory-stores.d.mts.map +1 -1
  101. package/resources/beta/memory-stores/memory-stores.d.ts +58 -14
  102. package/resources/beta/memory-stores/memory-stores.d.ts.map +1 -1
  103. package/resources/beta/memory-stores/memory-stores.js +6 -6
  104. package/resources/beta/memory-stores/memory-stores.js.map +1 -1
  105. package/resources/beta/memory-stores/memory-stores.mjs +6 -6
  106. package/resources/beta/memory-stores/memory-stores.mjs.map +1 -1
  107. package/resources/beta/memory-stores/memory-versions.d.mts +88 -5
  108. package/resources/beta/memory-stores/memory-versions.d.mts.map +1 -1
  109. package/resources/beta/memory-stores/memory-versions.d.ts +88 -5
  110. package/resources/beta/memory-stores/memory-versions.d.ts.map +1 -1
  111. package/resources/beta/memory-stores/memory-versions.js +3 -3
  112. package/resources/beta/memory-stores/memory-versions.mjs +3 -3
  113. package/resources/beta/messages/batches.d.mts +4 -0
  114. package/resources/beta/messages/batches.d.mts.map +1 -1
  115. package/resources/beta/messages/batches.d.ts +4 -0
  116. package/resources/beta/messages/batches.d.ts.map +1 -1
  117. package/resources/beta/messages/index.d.mts +1 -1
  118. package/resources/beta/messages/index.d.mts.map +1 -1
  119. package/resources/beta/messages/index.d.ts +1 -1
  120. package/resources/beta/messages/index.d.ts.map +1 -1
  121. package/resources/beta/messages/index.js.map +1 -1
  122. package/resources/beta/messages/index.mjs.map +1 -1
  123. package/resources/beta/messages/messages.d.mts +5 -1
  124. package/resources/beta/messages/messages.d.mts.map +1 -1
  125. package/resources/beta/messages/messages.d.ts +5 -1
  126. package/resources/beta/messages/messages.d.ts.map +1 -1
  127. package/resources/beta/messages/messages.js +1 -1
  128. package/resources/beta/messages/messages.js.map +1 -1
  129. package/resources/beta/messages/messages.mjs +1 -1
  130. package/resources/beta/messages/messages.mjs.map +1 -1
  131. package/resources/beta/sessions/sessions.d.mts +5 -0
  132. package/resources/beta/sessions/sessions.d.mts.map +1 -1
  133. package/resources/beta/sessions/sessions.d.ts +5 -0
  134. package/resources/beta/sessions/sessions.d.ts.map +1 -1
  135. package/resources/beta/sessions/sessions.js.map +1 -1
  136. package/resources/beta/sessions/sessions.mjs.map +1 -1
  137. package/resources/messages/messages.d.mts +4 -0
  138. package/resources/messages/messages.d.mts.map +1 -1
  139. package/resources/messages/messages.d.ts +4 -0
  140. package/resources/messages/messages.d.ts.map +1 -1
  141. package/resources/messages/messages.js.map +1 -1
  142. package/resources/messages/messages.mjs.map +1 -1
  143. package/src/client.ts +354 -14
  144. package/src/core/credentials.ts +349 -0
  145. package/src/internal/utils/time.ts +4 -0
  146. package/src/lib/credentials/credential-chain.ts +284 -0
  147. package/src/lib/credentials/identity-token.ts +37 -0
  148. package/src/lib/credentials/oidc-federation.ts +112 -0
  149. package/src/lib/credentials/token-cache.ts +130 -0
  150. package/src/lib/credentials/types.ts +295 -0
  151. package/src/lib/credentials/user-oauth.ts +144 -0
  152. package/src/lib/credentials.ts +3 -0
  153. package/src/resources/beta/environments.ts +1 -1
  154. package/src/resources/beta/index.ts +1 -0
  155. package/src/resources/beta/memory-stores/memories.ts +126 -11
  156. package/src/resources/beta/memory-stores/memory-stores.ts +58 -14
  157. package/src/resources/beta/memory-stores/memory-versions.ts +88 -5
  158. package/src/resources/beta/messages/batches.ts +4 -0
  159. package/src/resources/beta/messages/index.ts +1 -0
  160. package/src/resources/beta/messages/messages.ts +5 -1
  161. package/src/resources/beta/sessions/sessions.ts +6 -0
  162. package/src/resources/messages/messages.ts +4 -0
  163. package/src/version.ts +1 -1
  164. package/version.d.mts +1 -1
  165. package/version.d.ts +1 -1
  166. package/version.js +1 -1
  167. 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
- baseURL = readEnv('ANTHROPIC_BASE_URL'),
384
- apiKey = readEnv('ANTHROPIC_API_KEY') ?? null,
385
- authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null,
386
- ...opts
387
- }: ClientOptions = {}) {
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';
@@ -413,19 +516,126 @@ export class BaseAnthropic {
413
516
  this.fetch = options.fetch ?? Shims.getDefaultFetch();
414
517
  this.#encoder = Opts.FallbackEncoder;
415
518
 
519
+ const customHeadersEnv = readEnv('ANTHROPIC_CUSTOM_HEADERS');
520
+ if (customHeadersEnv) {
521
+ const parsed: Record<string, string> = {};
522
+ for (const line of customHeadersEnv.split('\n')) {
523
+ const colon = line.indexOf(':');
524
+ if (colon >= 0) {
525
+ parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
526
+ }
527
+ }
528
+ options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
529
+ }
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;
416
537
  this._options = options;
417
538
 
418
539
  this.apiKey = typeof apiKey === 'string' ? apiKey : null;
419
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
+ });
420
616
  }
421
617
 
422
618
  /**
423
619
  * Create a new client instance re-using the same options given to the current client with optional overriding.
424
620
  */
425
621
  withOptions(options: Partial<ClientOptions>): this {
426
- const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({
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 = {
427
629
  ...this._options,
428
- baseURL: this.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 } : {}),
429
639
  maxRetries: this.maxRetries,
430
640
  timeout: this.timeout,
431
641
  logger: this.logger,
@@ -434,13 +644,61 @@ export class BaseAnthropic {
434
644
  fetchOptions: this.fetchOptions,
435
645
  apiKey: this.apiKey,
436
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 } : {}),
437
657
  ...options,
438
- });
439
- return client;
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
+ }
440
691
  }
441
692
 
442
693
  /**
443
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.
444
702
  */
445
703
  #baseURLOverridden(): boolean {
446
704
  return this.baseURL !== 'https://api.anthropic.com';
@@ -454,6 +712,12 @@ export class BaseAnthropic {
454
712
  if (values.get('x-api-key') || values.get('authorization')) {
455
713
  return;
456
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
+ }
457
721
 
458
722
  if (this.apiKey && values.get('x-api-key')) {
459
723
  return;
@@ -470,11 +734,35 @@ export class BaseAnthropic {
470
734
  }
471
735
 
472
736
  throw new Error(
473
- 'Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted',
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',
474
738
  );
475
739
  }
476
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
+
477
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
+ }
478
766
  return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
479
767
  }
480
768
 
@@ -566,7 +854,28 @@ export class BaseAnthropic {
566
854
  protected async prepareRequest(
567
855
  request: RequestInit,
568
856
  { url, options }: { url: string; options: FinalRequestOptions },
569
- ): 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
+ }
570
879
 
571
880
  get<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
572
881
  return this.methodRequest('get', path, opts);
@@ -616,6 +925,9 @@ export class BaseAnthropic {
616
925
  const maxRetries = options.maxRetries ?? this.maxRetries;
617
926
  if (retriesRemaining == null) {
618
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);
619
931
  }
620
932
 
621
933
  await this.prepareOptions(options);
@@ -704,7 +1016,7 @@ export class BaseAnthropic {
704
1016
  } with status ${response.status} in ${headersTime - startTime}ms`;
705
1017
 
706
1018
  if (!response.ok) {
707
- const shouldRetry = await this.shouldRetry(response);
1019
+ const shouldRetry = await this.shouldRetry(response, options);
708
1020
  if (retriesRemaining && shouldRetry) {
709
1021
  const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
710
1022
 
@@ -834,7 +1146,24 @@ export class BaseAnthropic {
834
1146
  }
835
1147
  }
836
1148
 
837
- 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
+
838
1167
  // Note this is not a standard header.
839
1168
  const shouldRetryHeader = response.headers.get('x-should-retry');
840
1169
 
@@ -932,6 +1261,17 @@ export class BaseAnthropic {
932
1261
  const options = { ...inputOptions };
933
1262
  const { method, path, query, defaultBaseURL } = options;
934
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
+
935
1275
  const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
936
1276
  if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
937
1277
  options.timeout = options.timeout ?? this.timeout;