@gajae-code/ai 0.22.2 → 0.22.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.22.3] - 2026-11-28
6
+
7
+ ### Added
8
+
9
+ - `AssistantMessage.credentialId` records the stored credential row that authenticated the request producing the message. `streamSimple` stamps `StreamOptions.credentialId` on every partial, the `done` or `error` message, and the stream result once the provider has answered (an event after `start`, completion, or an error carrying an HTTP status in `errorStatus` or `transportFailure.status`, or a structured provider diagnostic, currently minted by the Anthropic adapter); a failure before any response, such as a transport exception or an abort before the first event, stays unattributed, and a failed response carrying none of these facts (for example a stream-level failure after HTTP 200 before any content) can stay unattributed too; an auth retry that returns an `AuthRetryCredential` with its own `credentialId` attributes the retried response to that row, while a bare replacement key leaves the field unset. The value is the opaque, non-secret row id only, and it is never set for external, env, or pi-native gateway keys. Attribution is best-effort and never fails a request whose message object rejects the write. An attributed request now aborts its provider request and closes the provider stream (running its `onConsumerClose` cleanup) when the consumer stops iterating early; the auth-retry path and the custom API forwarder used with `onStreamCreated` now close the provider stream the same way. `EventStream.closeConsumers()` stops every iterator of a stream as if its consumer had returned early. `pi-native-client` never sends a `credentialId` to the gateway, neither the request option nor the field on prior assistant messages in the context. `stripCredentialIds(messages)` removes the field from assistant messages before a context leaves the process. The id is recorded for attribution only and does not change what thinking is replayed; the provider decides what a thinking signature is valid for.
10
+
11
+ ### Fixed
12
+
13
+ - Anthropic `429 credits_required` ("Usage credits are required for this model.") is now treated as account-level usage exhaustion: it is no longer retried on the same account and triggers rotation to another stored credential, including during auto-compaction.
14
+
15
+ - `SqliteAuthCredentialStore.deleteAuthCredential` and `deleteAuthCredentialsForProvider` now throw when the SQLite write fails instead of swallowing the error, so a credential that is still active on disk is no longer reported as removed. `AuthStorage.disableCredentialById`, `remove()`, and `logout()` change memory, selectors, and `credential_disabled` events only after the write succeeds.
16
+ - `tryDisableAuthCredentialIfMatches` and `tryDisableAuthCredentialIfRevision` return `false` only when no active row matched; a database error now throws instead of looking like a lost compare-and-swap.
17
+ - `deleteAuthCredential` no longer rewrites a row that is already disabled; the row keeps its first disabled cause and revision.
18
+ - When disabling a credential after a definitive OAuth refresh failure cannot be written, the original authentication error is raised, the credential stays in memory, and it is blocked in this process for five minutes so other sessions move to another credential instead of replaying the failed refresh.
19
+ - Deduplication keeps a duplicate credential whose delete failed, per row. A remote auth-broker store is no longer asked to delete duplicates it serves (its synchronous delete can only throw); the client keeps the rows the broker sends.
20
+ - The auth broker answers `POST /v1/credential/:id/disable` with 500 instead of `200 { ok: true }` (or 404 for a revision-checked disable) when its store cannot write, and the background refresher logs a failed disable and retries on the next sweep.
21
+ - `pi-ai logout` exits non-zero without printing a success line when the logout cannot be written.
22
+
23
+ - A legacy OpenAI Codex credential that learns its ChatGPT workspace on refresh now keeps the workspace name of the duplicate login row it replaces (the same applies to an Anthropic refresh that omits the organization name). Codex refresh does not return the workspace name, so the surviving row used to lose its `email (workspace name)` label and `org:<name>` matching until the next login, and a request that performed that refresh itself could fail to return the refreshed key.
24
+
5
25
  ## [0.22.2] - 2026-11-25
6
26
 
7
27
  ### Fixed
@@ -316,12 +316,30 @@ export interface AuthCredentialStore {
316
316
  /** Transactional local hard removal; remote stores must reject this capability. */
317
317
  removeAuthCredentialsHard?(provider: string, targets: readonly CredentialRemovalTarget[]): AuthCredentialHardRemovalResult;
318
318
  updateAuthCredential(id: number, credential: AuthCredential): void;
319
+ /**
320
+ * Atomically adds a display name to the active OAuth row `id` when it belongs to `organizationId` and has no name.
321
+ * Every other stored field, tokens included, is left as the row currently holds it.
322
+ * Returns the credential as stored after the write, or `undefined` when the condition does not hold.
323
+ * A store with refresh lease hooks but without this writer does not carry a duplicate's name on refresh: the
324
+ * refreshed row stays authoritative and the duplicate is pruned.
325
+ */
326
+ setOAuthOrganizationNameIfUnset?(id: number, organizationId: string, organizationName: string): AuthCredential | undefined;
327
+ /**
328
+ * Soft-deletes row `id`; a no-op for an already-disabled row. Throws when the write fails. A remote store always
329
+ * throws: it is read-only on the client.
330
+ */
319
331
  deleteAuthCredential(id: number, disabledCause: string): void;
332
+ /**
333
+ * Local stores return `false` only when no active row matched and throw when the write fails. A remote store
334
+ * cannot disable synchronously and always returns `false`; callers reach the broker via `disableAuthCredentialRemote`.
335
+ */
320
336
  tryDisableAuthCredentialIfMatches(id: number, expectedData: string, disabledCause: string): boolean;
337
+ /** Returns `false` only when no active row matched; throws when the write fails. Absent on remote stores. */
321
338
  tryDisableAuthCredentialIfRevision?(id: number, expectedRevision: number, disabledCause: string): boolean;
322
339
  replaceAuthCredentialsForProvider(provider: string, credentials: AuthCredential[]): StoredAuthCredential[];
323
340
  upsertAuthCredentialForProvider(provider: string, credential: AuthCredential): StoredAuthCredential[];
324
341
  upsertAuthCredentialForProviderIfAbsent(provider: string, credential: AuthCredential): AuthCredentialIfAbsentResult;
342
+ /** Soft-deletes every active row of `provider`. Throws when the write fails; a remote store always throws. */
325
343
  deleteAuthCredentialsForProvider(provider: string, disabledCause: string): void;
326
344
  getCache(key: string, options?: {
327
345
  includeExpired?: boolean;
@@ -970,6 +988,7 @@ export declare class AuthStorage {
970
988
  importCredentialIfAbsent(provider: string, credential: AuthCredential, owner?: object): Promise<AuthCredentialIfAbsentSnapshotResult>;
971
989
  /**
972
990
  * Remove credential for a provider.
991
+ * Throws when the store write fails; memory is cleared only after it succeeds.
973
992
  */
974
993
  remove(provider: string): Promise<void>;
975
994
  /**
@@ -980,6 +999,7 @@ export declare class AuthStorage {
980
999
  * Check if credentials exist for a provider in storage.
981
1000
  */
982
1001
  has(provider: string): boolean;
1002
+ /** Returns `false` for a lost revision check or an unknown row; throws when the store write fails. */
983
1003
  disableCredentialByIdIfRevision(id: number, expectedRevision: number, disabledCause: string): boolean;
984
1004
  hasAuth(provider: string, sessionId?: string, options?: Pick<AuthApiKeyOptions, "owner">): boolean;
985
1005
  /**
@@ -1203,6 +1223,9 @@ export declare class AuthStorage {
1203
1223
  * Disable the credential with the given id and emit a
1204
1224
  * {@link CredentialDisabledEvent}. Used by the auth-broker server to honour
1205
1225
  * `POST /v1/credential/:id/disable`. Returns `false` when no such row exists.
1226
+ * Throws when the store write fails; memory, selectors, and listeners are
1227
+ * updated only after it succeeds. A row a peer already disabled on disk is
1228
+ * left as the peer wrote it and is dropped from memory (returns `true`).
1206
1229
  */
1207
1230
  disableCredentialById(id: number, disabledCause: string): boolean;
1208
1231
  /**
@@ -1254,15 +1277,25 @@ export declare class SqliteAuthCredentialStore implements AuthCredentialStore {
1254
1277
  upsertAuthCredentialForProvider(provider: string, credential: AuthCredential): StoredAuthCredential[];
1255
1278
  upsertAuthCredentialForProviderIfAbsent(provider: string, credential: AuthCredential): AuthCredentialIfAbsentResult;
1256
1279
  updateAuthCredential(id: number, credential: AuthCredential): void;
1280
+ setOAuthOrganizationNameIfUnset(id: number, organizationId: string, organizationName: string): AuthCredential | undefined;
1281
+ /**
1282
+ * Soft-deletes one row. Throws when the write fails, so no caller treats a row
1283
+ * that is still active on disk as disabled. A row that is already disabled is
1284
+ * left unchanged (it keeps its first `disabled_cause` and revision), and the
1285
+ * call still succeeds because the row is not active.
1286
+ */
1257
1287
  deleteAuthCredential(id: number, disabledCause: string): void;
1258
1288
  /**
1259
1289
  * CAS-style disable: only soft-deletes the row when its `data` column still
1260
1290
  * matches `expectedData` and the row has not already been disabled. Used by
1261
1291
  * the OAuth refresh-failure path to avoid clobbering a peer that rotated the
1262
- * row between our pre-check and the disable.
1292
+ * row between our pre-check and the disable. Returns `false` only when no row
1293
+ * matched the predicate; a failed write throws.
1263
1294
  */
1264
1295
  tryDisableAuthCredentialIfMatches(id: number, expectedData: string, disabledCause: string): boolean;
1296
+ /** Revision-checked disable. Returns `false` only when no row matched; a failed write throws. */
1265
1297
  tryDisableAuthCredentialIfRevision(id: number, expectedRevision: number, disabledCause: string): boolean;
1298
+ /** Soft-deletes every active row of a provider. Throws when the write fails. */
1266
1299
  deleteAuthCredentialsForProvider(provider: string, disabledCause: string): void;
1267
1300
  getCache(key: string, options?: {
1268
1301
  includeExpired?: boolean;
@@ -43,6 +43,7 @@ export * from "./usage/minimax-code";
43
43
  export * from "./usage/openai-codex";
44
44
  export * from "./usage/zai";
45
45
  export * from "./utils/anthropic-auth";
46
+ export * from "./utils/credential-id";
46
47
  export * from "./utils/discovery";
47
48
  export * from "./utils/event-stream";
48
49
  export * from "./utils/fallback-transport";
@@ -188,6 +188,16 @@ export interface ProviderDispatch {
188
188
  readonly headers: Headers;
189
189
  readonly body: string | Uint8Array | undefined;
190
190
  }
191
+ /**
192
+ * API key paired with the stored credential row that supplied it.
193
+ *
194
+ * `credentialId` is the opaque, non-secret row id; it is omitted for
195
+ * external, env, or otherwise unknown keys.
196
+ */
197
+ export interface ResolvedApiKey {
198
+ apiKey: string;
199
+ credentialId?: number;
200
+ }
191
201
  /**
192
202
  * Credential returned by an auth retry resolver.
193
203
  *
@@ -196,8 +206,7 @@ export interface ProviderDispatch {
196
206
  * admitted. Ordinary callers can continue returning a string from
197
207
  * {@link StreamOptions.onAuthError}.
198
208
  */
199
- export interface AuthRetryCredential {
200
- apiKey: string;
209
+ export interface AuthRetryCredential extends ResolvedApiKey {
201
210
  onStreamCreated?: () => void;
202
211
  }
203
212
  export interface StreamOptions {
@@ -226,6 +235,12 @@ export interface StreamOptions {
226
235
  endpointConfiguration?: EndpointConfiguration;
227
236
  signal?: AbortSignal;
228
237
  apiKey?: string;
238
+ /**
239
+ * Stored credential row id that supplied `apiKey`. `streamSimple` records it
240
+ * as {@link AssistantMessage.credentialId} on every emitted message; leave it
241
+ * unset for external, env, or otherwise unknown keys.
242
+ */
243
+ credentialId?: number;
229
244
  /** Disables all transport-level replay; the fallback controller owns retries. */
230
245
  fallbackManaged?: boolean;
231
246
  /** Opaque token returned by beginAttempt for a managed transport invocation. */
@@ -717,6 +732,12 @@ export interface AssistantMessage {
717
732
  ttft?: number;
718
733
  /** Prompt-prefix fingerprint of the request that produced this message. */
719
734
  promptPrefix?: PromptPrefixTelemetry;
735
+ /**
736
+ * Stored credential row id that authenticated the request producing this
737
+ * message. An opaque, non-secret number only; absent for external, env, or
738
+ * unknown keys.
739
+ */
740
+ credentialId?: number;
720
741
  }
721
742
  export interface GoogleGeminiCliDiagnostics {
722
743
  responseAtMs?: number;
@@ -0,0 +1,12 @@
1
+ import type { Message } from "../types";
2
+ /**
3
+ * Drop the local stored-credential row id from assistant messages before a
4
+ * context leaves this process for a remote server (pi-native gateway, proxy).
5
+ *
6
+ * `credentialId` names a row in the local auth store; a remote server
7
+ * authenticates upstream with its own credentials, so the number is
8
+ * meaningless there and must not cross the wire. Returns `messages` itself when
9
+ * no message carries the field; otherwise copies the array and only the
10
+ * messages that carry it.
11
+ */
12
+ export declare function stripCredentialIds(messages: Message[]): Message[];
@@ -32,6 +32,14 @@ export declare class EventStream<T, R = T> implements AsyncIterable<T> {
32
32
  waitForConsumerDrain(signal: AbortSignal): Promise<void>;
33
33
  end(result?: R): void;
34
34
  endWaiting(): void;
35
+ /**
36
+ * Stop every iterator of this stream as if its consumer had returned early,
37
+ * so `onConsumerClose` runs. An iterator parked on the next event wakes now;
38
+ * one that is between events exits before yielding again. A forwarder whose
39
+ * own consumer left calls this to hand the cancellation to its source. The
40
+ * close is permanent: later iterators of the same stream return immediately.
41
+ */
42
+ closeConsumers(): void;
35
43
  fail(err: unknown): void;
36
44
  [Symbol.asyncIterator](): AsyncIterator<T>;
37
45
  result(): Promise<R>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@gajae-code/ai",
4
- "version": "0.22.2",
4
+ "version": "0.22.3",
5
5
  "description": "Unified LLM API with automatic model discovery and provider configuration",
6
6
  "homepage": "https://gajae-code.com",
7
7
  "author": "Yeachan-Heo and Gajae Code Contributors",
@@ -41,8 +41,8 @@
41
41
  "@agentclientprotocol/sdk": "1.3.0",
42
42
  "@anthropic-ai/sdk": "^0.94.0",
43
43
  "@bufbuild/protobuf": "^2.12.0",
44
- "@gajae-code/natives": "0.22.2",
45
- "@gajae-code/utils": "0.22.2",
44
+ "@gajae-code/natives": "0.22.3",
45
+ "@gajae-code/utils": "0.22.3",
46
46
  "openai": "^6.36.0",
47
47
  "partial-json": "^0.1.7",
48
48
  "zod": "4.4.3"
@@ -121,7 +121,15 @@ export class AuthBrokerRefresher {
121
121
  id,
122
122
  error: errorMsg,
123
123
  });
124
- this.#storage.disableCredentialById(id, `auth-broker refresh failed: ${errorMsg}`);
124
+ try {
125
+ this.#storage.disableCredentialById(id, `auth-broker refresh failed: ${errorMsg}`);
126
+ } catch (disableError) {
127
+ // The row is still active on disk; the next sweep retries the refresh and the disable.
128
+ logger.warn("auth-broker could not disable a definitively failed credential", {
129
+ id,
130
+ error: cleanReason(disableError) ?? "Unknown disable failure",
131
+ });
132
+ }
125
133
  } else {
126
134
  logger.debug("auth-broker refresh failed (transient)", { id, error: errorMsg });
127
135
  }
@@ -725,10 +725,19 @@ export function startAuthBroker(opts: AuthBrokerServerOptions): AuthBrokerServer
725
725
  const parsed = await parseBody(req, credentialDisableRequestSchema, { allowEmpty: true });
726
726
  if (!parsed.ok) return parsed.response;
727
727
  const cause = "disabled via auth-broker";
728
- const ok =
729
- parsed.data.expectedRevision === undefined
730
- ? opts.storage.disableCredentialById(id, cause)
731
- : opts.storage.disableCredentialByIdIfRevision(id, parsed.data.expectedRevision, cause);
728
+ let ok: boolean;
729
+ try {
730
+ ok =
731
+ parsed.data.expectedRevision === undefined
732
+ ? opts.storage.disableCredentialById(id, cause)
733
+ : opts.storage.disableCredentialByIdIfRevision(id, parsed.data.expectedRevision, cause);
734
+ } catch (error) {
735
+ // The broker store did not persist the disable; the row is still active,
736
+ // so the client must keep its mirror row instead of treating it as gone.
737
+ const message = cleanReason(error) ?? "Credential disable failed";
738
+ logger.warn("auth-broker disable failed", { id, peer, error: message });
739
+ return json(500, { error: message });
740
+ }
732
741
  if (!ok) {
733
742
  logger.info("auth-broker disable miss", { id, peer });
734
743
  return json(404, { error: `No credential with id=${id}` });
@@ -552,12 +552,34 @@ export interface AuthCredentialStore {
552
552
  targets: readonly CredentialRemovalTarget[],
553
553
  ): AuthCredentialHardRemovalResult;
554
554
  updateAuthCredential(id: number, credential: AuthCredential): void;
555
+ /**
556
+ * Atomically adds a display name to the active OAuth row `id` when it belongs to `organizationId` and has no name.
557
+ * Every other stored field, tokens included, is left as the row currently holds it.
558
+ * Returns the credential as stored after the write, or `undefined` when the condition does not hold.
559
+ * A store with refresh lease hooks but without this writer does not carry a duplicate's name on refresh: the
560
+ * refreshed row stays authoritative and the duplicate is pruned.
561
+ */
562
+ setOAuthOrganizationNameIfUnset?(
563
+ id: number,
564
+ organizationId: string,
565
+ organizationName: string,
566
+ ): AuthCredential | undefined;
567
+ /**
568
+ * Soft-deletes row `id`; a no-op for an already-disabled row. Throws when the write fails. A remote store always
569
+ * throws: it is read-only on the client.
570
+ */
555
571
  deleteAuthCredential(id: number, disabledCause: string): void;
572
+ /**
573
+ * Local stores return `false` only when no active row matched and throw when the write fails. A remote store
574
+ * cannot disable synchronously and always returns `false`; callers reach the broker via `disableAuthCredentialRemote`.
575
+ */
556
576
  tryDisableAuthCredentialIfMatches(id: number, expectedData: string, disabledCause: string): boolean;
577
+ /** Returns `false` only when no active row matched; throws when the write fails. Absent on remote stores. */
557
578
  tryDisableAuthCredentialIfRevision?(id: number, expectedRevision: number, disabledCause: string): boolean;
558
579
  replaceAuthCredentialsForProvider(provider: string, credentials: AuthCredential[]): StoredAuthCredential[];
559
580
  upsertAuthCredentialForProvider(provider: string, credential: AuthCredential): StoredAuthCredential[];
560
581
  upsertAuthCredentialForProviderIfAbsent(provider: string, credential: AuthCredential): AuthCredentialIfAbsentResult;
582
+ /** Soft-deletes every active row of `provider`. Throws when the write fails; a remote store always throws. */
561
583
  deleteAuthCredentialsForProvider(provider: string, disabledCause: string): void;
562
584
  getCache(key: string, options?: { includeExpired?: boolean }): string | null;
563
585
  setCache(key: string, value: string, expiresAtSec: number): void;
@@ -3176,6 +3198,34 @@ export class AuthStorage {
3176
3198
  return deduped.reverse();
3177
3199
  }
3178
3200
 
3201
+ /**
3202
+ * A refresh that establishes a legacy row's organization keeps that row and prunes any other row of the same
3203
+ * identity (see {@link AuthStorage.#pruneDuplicateStoredCredentials}). The pruned row may be a newer login that
3204
+ * carries the organization's display name, which refresh responses do not always return (OpenAI Codex looks the
3205
+ * workspace name up only at login). Carry that name over so the surviving row keeps its label and stays
3206
+ * selectable by `org:<name>`.
3207
+ */
3208
+ #withDuplicateOrganizationName<T extends AuthCredential>(
3209
+ provider: string,
3210
+ entries: readonly StoredCredential[],
3211
+ targetId: number,
3212
+ credential: T,
3213
+ ): T {
3214
+ if (credential.type !== "oauth" || credential.organizationName?.trim() || !credential.organizationId?.trim()) {
3215
+ return credential;
3216
+ }
3217
+ const identityKey = this.#resolveOAuthDedupeIdentityKey(provider, credential);
3218
+ if (!identityKey) return credential;
3219
+ for (const entry of entries) {
3220
+ if (entry.id === targetId || entry.credential.type !== "oauth") continue;
3221
+ const organizationName = entry.credential.organizationName?.trim();
3222
+ if (!organizationName) continue;
3223
+ if (this.#resolveOAuthDedupeIdentityKey(provider, entry.credential) !== identityKey) continue;
3224
+ return { ...credential, organizationName };
3225
+ }
3226
+ return credential;
3227
+ }
3228
+
3179
3229
  #pruneDuplicateStoredCredentials(
3180
3230
  provider: string,
3181
3231
  entries: StoredCredential[],
@@ -3201,14 +3251,31 @@ export class AuthStorage {
3201
3251
  if (identityKey && !selectedIds.has(entry.id)) removed.push(entry);
3202
3252
  else kept.push(entry);
3203
3253
  }
3204
- if (removed.length > 0) {
3205
- for (const entry of removed) {
3254
+ if (removed.length === 0) return kept;
3255
+ // A remote store's snapshot is the broker's truth and its synchronous delete can only throw: the broker owns
3256
+ // deduplication, so this client keeps the rows as served instead of failing (and warning) on every reload.
3257
+ if (this.#store.disableAuthCredentialRemote) return entries;
3258
+ // A duplicate whose delete failed is still active on disk, so it stays in memory too: this process never
3259
+ // publishes a pruned view that a reload would contradict.
3260
+ const stillActive = new Set<number>();
3261
+ for (const entry of removed) {
3262
+ try {
3206
3263
  this.#store.deleteAuthCredential(entry.id, "deduplicated duplicate credential");
3264
+ } catch (error) {
3265
+ stillActive.add(entry.id);
3266
+ logger.warn("Could not retire a deduplicated credential; keeping it", {
3267
+ provider,
3268
+ credentialId: entry.id,
3269
+ error: String(error),
3270
+ });
3207
3271
  }
3208
- this.#clearSelectorsForRemovedCredential(provider, new Set(removed.map(entry => entry.id)), entries);
3209
- this.#resetProviderAssignments(provider);
3210
3272
  }
3211
- return kept;
3273
+ const pruned = removed.filter(entry => !stillActive.has(entry.id));
3274
+ if (pruned.length === 0) return entries;
3275
+ const prunedIds = new Set(pruned.map(entry => entry.id));
3276
+ this.#clearSelectorsForRemovedCredential(provider, prunedIds, entries);
3277
+ this.#resetProviderAssignments(provider);
3278
+ return stillActive.size > 0 ? entries.filter(entry => !prunedIds.has(entry.id)) : kept;
3212
3279
  }
3213
3280
 
3214
3281
  /** Returns all credentials for a provider as an array */
@@ -3792,25 +3859,49 @@ export class AuthStorage {
3792
3859
  }
3793
3860
  }
3794
3861
 
3795
- /** Updates a credential at index after OAuth token refresh. */
3796
- #replaceCredentialAt(
3862
+ /**
3863
+ * Updates a credential at index after OAuth token refresh. Returns the credential actually stored, which may
3864
+ * carry an organization name over from a pruned duplicate; callers that compare against or hand out the
3865
+ * refreshed credential must use the returned value.
3866
+ */
3867
+ #replaceCredentialAt<T extends AuthCredential>(
3797
3868
  provider: string,
3798
3869
  index: number,
3799
- credential: AuthCredential,
3870
+ credential: T,
3800
3871
  persist = true,
3801
3872
  expectedId?: number,
3802
- ): void {
3873
+ ): T {
3803
3874
  const entries = this.#getStoredCredentials(provider);
3804
- if (index < 0 || index >= entries.length) return;
3875
+ if (index < 0 || index >= entries.length) return credential;
3805
3876
  const target = entries[index];
3806
3877
  if (expectedId !== undefined && target.id !== expectedId) {
3807
3878
  throw new Error("Credential authority changed during refresh");
3808
3879
  }
3809
- if (persist && !this.#store.refreshSnapshot) this.#store.updateAuthCredential(target.id, credential);
3880
+ let named = this.#withDuplicateOrganizationName(provider, entries, target.id, credential);
3881
+ let pruneDuplicates = true;
3882
+ if (!this.#store.refreshSnapshot) {
3883
+ if (persist) {
3884
+ this.#store.updateAuthCredential(target.id, named);
3885
+ } else if (named !== credential && named.type === "oauth" && named.organizationId && named.organizationName) {
3886
+ const carried = this.#persistCarriedOrganizationName(
3887
+ provider,
3888
+ target.id,
3889
+ credential,
3890
+ named.organizationId,
3891
+ named.organizationName,
3892
+ );
3893
+ named = carried.credential;
3894
+ pruneDuplicates = carried.pruneDuplicates;
3895
+ }
3896
+ }
3897
+ credential = named;
3810
3898
  const updated = [...entries];
3811
3899
  updated[index] = { id: target.id, credential };
3812
3900
  const configurationGeneration = this.#getProviderConfigurationGeneration(provider);
3813
- this.#setStoredCredentials(provider, this.#pruneDuplicateStoredCredentials(provider, updated, target.id));
3901
+ this.#setStoredCredentials(
3902
+ provider,
3903
+ pruneDuplicates ? this.#pruneDuplicateStoredCredentials(provider, updated, target.id) : updated,
3904
+ );
3814
3905
  // Callers use the refresh generation to discount configuration bumps caused by a refresh, so it only
3815
3906
  // advances when this refresh bumped configuration; token rotation for a known account does not.
3816
3907
  if (
@@ -3828,6 +3919,62 @@ export class AuthStorage {
3828
3919
  this.getProviderOAuthRefreshGeneration(storageProvider) + 1,
3829
3920
  );
3830
3921
  }
3922
+ return credential;
3923
+ }
3924
+
3925
+ /**
3926
+ * Adds a name carried over from a duplicate row to a row whose refresh lease already persisted the tokens. A peer
3927
+ * may have rotated those tokens since, so only the name is written, conditionally on the row as it is now.
3928
+ *
3929
+ * Returns the credential to cache and return to the refresh caller, and whether the duplicate rows of its identity
3930
+ * may be pruned. Whenever the row could be read, the credential is the row as stored, so a peer's newer tokens are
3931
+ * never replaced by this refresh's snapshot:
3932
+ * - written: the row as stored with the carried name, prune.
3933
+ * - condition lost because a peer named the row first or changed its workspace: the row as stored now, prune.
3934
+ * - condition lost because the row is no longer active: the refreshed credential, and keep the duplicate, since
3935
+ * pruning it would leave no active row for the identity.
3936
+ * - store has no name-only writer, or the write failed: the refreshed credential without the carried name, prune.
3937
+ * The row holding the lease-committed tokens stays authoritative: a kept duplicate would win the next reload's
3938
+ * dedupe (it keeps the later row) with its older, possibly rotated-out tokens. The name is then lost as it was
3939
+ * before names were carried, and the refresh itself succeeds.
3940
+ * - condition lost and the row cannot be re-read: the refreshed credential, and keep the duplicate, since the row
3941
+ * may no longer be active.
3942
+ */
3943
+ #persistCarriedOrganizationName<T extends AuthCredential>(
3944
+ provider: string,
3945
+ id: number,
3946
+ credential: T,
3947
+ organizationId: string,
3948
+ carriedName: string,
3949
+ ): { credential: T; pruneDuplicates: boolean } {
3950
+ if (!this.#store.setOAuthOrganizationNameIfUnset) return { credential, pruneDuplicates: true };
3951
+ let written: AuthCredential | undefined;
3952
+ try {
3953
+ written = this.#store.setOAuthOrganizationNameIfUnset(id, organizationId, carriedName);
3954
+ } catch (error) {
3955
+ logger.warn("OAuth refresh could not persist the workspace name carried from a duplicate credential", {
3956
+ provider,
3957
+ credentialId: id,
3958
+ error: String(error),
3959
+ });
3960
+ return { credential, pruneDuplicates: true };
3961
+ }
3962
+ // The writer only updates an active OAuth row, the same row and credential type as `credential`.
3963
+ if (written) return { credential: written as T, pruneDuplicates: true };
3964
+ try {
3965
+ const current = this.#store.listAuthCredentials(provider).find(entry => entry.id === id)?.credential;
3966
+ if (current?.type !== credential.type) return { credential, pruneDuplicates: false };
3967
+ return { credential: current as T, pruneDuplicates: true };
3968
+ } catch (error) {
3969
+ // The conditional write lost and the row cannot be read back, so it may no longer be active: keep the
3970
+ // duplicate rather than risk leaving the identity without an active row.
3971
+ logger.warn("OAuth refresh could not re-read a credential after its workspace name write lost", {
3972
+ provider,
3973
+ credentialId: id,
3974
+ error: String(error),
3975
+ });
3976
+ return { credential, pruneDuplicates: false };
3977
+ }
3831
3978
  }
3832
3979
 
3833
3980
  /**
@@ -3876,7 +4023,8 @@ export class AuthStorage {
3876
4023
  /**
3877
4024
  * Soft-deletes a row by id, bypassing the data-equality CAS. Only safe when the
3878
4025
  * caller has confirmed the row still holds the credential it attempted to
3879
- * refresh, so no peer rotation can be clobbered.
4026
+ * refresh, so no peer rotation can be clobbered. The store write runs first:
4027
+ * when it throws, memory, selectors, and listeners are left untouched.
3880
4028
  */
3881
4029
  #disableCredentialById(provider: string, credentialId: number, disabledCause: string): void {
3882
4030
  this.#store.deleteAuthCredential(credentialId, disabledCause);
@@ -4112,6 +4260,7 @@ export class AuthStorage {
4112
4260
 
4113
4261
  /**
4114
4262
  * Remove credential for a provider.
4263
+ * Throws when the store write fails; memory is cleared only after it succeeds.
4115
4264
  */
4116
4265
  async remove(provider: string): Promise<void> {
4117
4266
  const storageProvider = resolveOAuthStorageProvider(provider);
@@ -4157,6 +4306,7 @@ export class AuthStorage {
4157
4306
  return false;
4158
4307
  }
4159
4308
 
4309
+ /** Returns `false` for a lost revision check or an unknown row; throws when the store write fails. */
4160
4310
  disableCredentialByIdIfRevision(id: number, expectedRevision: number, disabledCause: string): boolean {
4161
4311
  const cause = normalizeDisabledCause(disabledCause);
4162
4312
  if (this.#store.tryDisableAuthCredentialIfRevision?.(id, expectedRevision, cause) !== true) return false;
@@ -6640,8 +6790,7 @@ export class AuthStorage {
6640
6790
  type: "oauth",
6641
6791
  };
6642
6792
  if (!this.#reconcileOAuthCredentialSelection(provider, candidate.selection)) return;
6643
- candidate.selection.credential = updated;
6644
- this.#replaceCredentialAt(
6793
+ candidate.selection.credential = this.#replaceCredentialAt(
6645
6794
  provider,
6646
6795
  candidate.selection.index,
6647
6796
  updated,
@@ -7147,7 +7296,7 @@ export class AuthStorage {
7147
7296
  result = await getOAuthApiKey(provider as OAuthProvider, oauthCreds);
7148
7297
  }
7149
7298
  if (!result) return undefined;
7150
- const updated: OAuthCredential = {
7299
+ const refreshedCredential: OAuthCredential = {
7151
7300
  type: "oauth",
7152
7301
  access: result.newCredentials.access,
7153
7302
  refresh: result.newCredentials.refresh,
@@ -7161,10 +7310,10 @@ export class AuthStorage {
7161
7310
  organizationName: result.newCredentials.organizationName ?? selection.credential.organizationName,
7162
7311
  mcpBinding: refreshedAuthority.mcpBinding,
7163
7312
  };
7164
- this.#replaceCredentialAt(
7313
+ const updated = this.#replaceCredentialAt(
7165
7314
  provider,
7166
7315
  selection.index,
7167
- updated,
7316
+ refreshedCredential,
7168
7317
  !refreshedAuthority.persistedByLease,
7169
7318
  selectionCredentialId,
7170
7319
  );
@@ -7192,8 +7341,32 @@ export class AuthStorage {
7192
7341
  }
7193
7342
  if (!this.#reconcileOAuthCredentialSelection(provider, selection)) return undefined;
7194
7343
  if (!authCredentialEquals(selection.credential, updated)) return undefined;
7344
+ // A peer may have rotated the row after this refresh's lease committed; `updated` is then the stored row
7345
+ // and the key must come from its tokens, not from this refresh's snapshot. A stored row that is already
7346
+ // expired, or whose key cannot be derived, is left to the next resolution, which refreshes it normally;
7347
+ // its errors must not reach the refresh-failure classification below.
7348
+ let apiKey = result.apiKey;
7349
+ if (updated.access !== refreshedCredential.access) {
7350
+ if (Date.now() >= updated.expires) return undefined;
7351
+ try {
7352
+ if (customProvider) {
7353
+ apiKey = customProvider.getApiKey ? customProvider.getApiKey(updated) : updated.access;
7354
+ } else {
7355
+ const current = await getOAuthApiKey(provider as OAuthProvider, { [provider]: updated });
7356
+ if (!current || current.newCredentials.access !== updated.access) return undefined;
7357
+ apiKey = current.apiKey;
7358
+ }
7359
+ } catch (error) {
7360
+ logger.warn("OAuth request could not derive a key from a credential a peer rotated", {
7361
+ provider,
7362
+ credentialId: selection.id,
7363
+ error: String(error),
7364
+ });
7365
+ return undefined;
7366
+ }
7367
+ }
7195
7368
  this.#recordSessionCredential(provider, sessionId, "oauth", selection.index);
7196
- return { apiKey: result.apiKey, credential: updated, credentialRowId: selection.id };
7369
+ return { apiKey, credential: updated, credentialRowId: selection.id };
7197
7370
  } catch (error) {
7198
7371
  if (options?.signal?.aborted) throw error;
7199
7372
  if (isSqliteError(error)) throw error;
@@ -7272,13 +7445,31 @@ export class AuthStorage {
7272
7445
  // Use a CAS-style disable conditioned on the row still containing the stale credential
7273
7446
  // we tried to refresh, so a peer rotation that lands between the pre-check above and
7274
7447
  // this disable doesn't soft-delete the freshly-rotated row.
7275
- const disabled = this.#tryDisableCredentialAtIfMatches(
7276
- provider,
7277
- selection.index,
7278
- selection.credential,
7279
- `oauth refresh failed: ${errorMsg}`,
7280
- attemptedCredentialId,
7281
- );
7448
+ let disabled: boolean;
7449
+ try {
7450
+ disabled = this.#tryDisableCredentialAtIfMatches(
7451
+ provider,
7452
+ selection.index,
7453
+ selection.credential,
7454
+ `oauth refresh failed: ${errorMsg}`,
7455
+ attemptedCredentialId,
7456
+ );
7457
+ } catch (disableError) {
7458
+ // A failed store write is not a lost CAS: the row is still active on disk,
7459
+ // so keep it in memory and surface the original authentication failure.
7460
+ logger.warn("OAuth refresh disable failed in the store", {
7461
+ provider,
7462
+ credentialId: attemptedCredentialId,
7463
+ error: String(disableError),
7464
+ });
7465
+ if (sessionSelector && sessionId) {
7466
+ this.markSessionCredentialUnavailable(sessionId, provider, sessionSelector);
7467
+ }
7468
+ // Keep other sessions in this process off the revoked credential until a
7469
+ // later disable succeeds.
7470
+ this.#markCredentialBlocked(providerKey, selection.index, Date.now() + 5 * 60 * 1000);
7471
+ throw error;
7472
+ }
7282
7473
  if (sessionSelector && sessionId) {
7283
7474
  this.markSessionCredentialUnavailable(sessionId, provider, sessionSelector);
7284
7475
  }
@@ -7333,7 +7524,19 @@ export class AuthStorage {
7333
7524
  throw error;
7334
7525
  }
7335
7526
  } else {
7336
- this.#disableCredentialById(provider, attemptedCredentialId, disabledCause);
7527
+ try {
7528
+ this.#disableCredentialById(provider, attemptedCredentialId, disabledCause);
7529
+ } catch (disableError) {
7530
+ // Same contract as the remote branch: the store write failed, the row
7531
+ // stays active and in memory, and the original failure is reported.
7532
+ logger.warn("OAuth refresh disable by id failed in the store", {
7533
+ provider,
7534
+ credentialId: attemptedCredentialId,
7535
+ error: String(disableError),
7536
+ });
7537
+ this.#markCredentialBlocked(providerKey, selection.index, Date.now() + 5 * 60 * 1000);
7538
+ throw error;
7539
+ }
7337
7540
  }
7338
7541
  } else {
7339
7542
  logger.debug("OAuth refresh disable lost CAS; reloading after peer rotation", {
@@ -7982,13 +8185,13 @@ export class AuthStorage {
7982
8185
  organizationName: refreshed.organizationName ?? target.credential.organizationName,
7983
8186
  mcpBinding: refreshed.mcpBinding,
7984
8187
  };
7985
- this.#replaceCredentialAt(provider, index, updated, !refreshed.persistedByLease, id);
8188
+ const stored = this.#replaceCredentialAt(provider, index, updated, !refreshed.persistedByLease, id);
7986
8189
  const persisted = this.#store.listAuthCredentials(provider).find(entry => entry.id === id);
7987
8190
  return {
7988
8191
  id,
7989
8192
  provider,
7990
- credential: { ...updated, refresh: REMOTE_REFRESH_SENTINEL },
7991
- identityKey: resolveCredentialIdentityKey(provider, updated),
8193
+ credential: { ...stored, refresh: REMOTE_REFRESH_SENTINEL },
8194
+ identityKey: resolveCredentialIdentityKey(provider, stored),
7992
8195
  ...(persisted?.revision === undefined ? {} : { revision: persisted.revision }),
7993
8196
  };
7994
8197
  }
@@ -7999,6 +8202,9 @@ export class AuthStorage {
7999
8202
  * Disable the credential with the given id and emit a
8000
8203
  * {@link CredentialDisabledEvent}. Used by the auth-broker server to honour
8001
8204
  * `POST /v1/credential/:id/disable`. Returns `false` when no such row exists.
8205
+ * Throws when the store write fails; memory, selectors, and listeners are
8206
+ * updated only after it succeeds. A row a peer already disabled on disk is
8207
+ * left as the peer wrote it and is dropped from memory (returns `true`).
8002
8208
  */
8003
8209
  disableCredentialById(id: number, disabledCause: string): boolean {
8004
8210
  const cause = normalizeDisabledCause(disabledCause);
@@ -8362,7 +8568,7 @@ export class SqliteAuthCredentialStore implements AuthCredentialStore {
8362
8568
  `UPDATE auth_credentials SET credential_type = ?, data = ?, identity_key = ?, revision = revision + 1, updated_at = ${SQLITE_NOW_EPOCH} WHERE id = ?`,
8363
8569
  );
8364
8570
  this.#deleteStmt = this.#prepareOwnedStatement(
8365
- `UPDATE auth_credentials SET disabled_cause = ?, revision = revision + 1, updated_at = ${SQLITE_NOW_EPOCH} WHERE id = ?`,
8571
+ `UPDATE auth_credentials SET disabled_cause = ?, revision = revision + 1, updated_at = ${SQLITE_NOW_EPOCH} WHERE id = ? AND disabled_cause IS NULL`,
8366
8572
  );
8367
8573
  this.#deleteIfMatchesStmt = this.#prepareOwnedStatement(
8368
8574
  `UPDATE auth_credentials SET disabled_cause = ?, revision = revision + 1, updated_at = ${SQLITE_NOW_EPOCH} WHERE id = ? AND data = ? AND disabled_cause IS NULL`,
@@ -9113,48 +9319,69 @@ export class SqliteAuthCredentialStore implements AuthCredentialStore {
9113
9319
  }
9114
9320
  }
9115
9321
 
9322
+ setOAuthOrganizationNameIfUnset(
9323
+ id: number,
9324
+ organizationId: string,
9325
+ organizationName: string,
9326
+ ): AuthCredential | undefined {
9327
+ const update = this.#db.transaction(() => {
9328
+ const row = this.#withStatement(
9329
+ "SELECT id, provider, credential_type, data, disabled_cause, identity_key, revision FROM auth_credentials WHERE id = ? AND disabled_cause IS NULL",
9330
+ statement => statement.get(id) as AuthRow | undefined,
9331
+ );
9332
+ if (!row) return undefined;
9333
+ const credential = deserializeCredential(row);
9334
+ if (
9335
+ credential?.type !== "oauth" ||
9336
+ credential.organizationId !== organizationId ||
9337
+ credential.organizationName?.trim()
9338
+ ) {
9339
+ return undefined;
9340
+ }
9341
+ const named: AuthCredential = { ...credential, organizationName };
9342
+ const serialized = serializeCredential(row.provider, named);
9343
+ if (!serialized) return undefined;
9344
+ this.#updateStmt.run(serialized.credentialType, serialized.data, serialized.identityKey, id);
9345
+ return named;
9346
+ });
9347
+ return update.immediate();
9348
+ }
9349
+
9350
+ /**
9351
+ * Soft-deletes one row. Throws when the write fails, so no caller treats a row
9352
+ * that is still active on disk as disabled. A row that is already disabled is
9353
+ * left unchanged (it keeps its first `disabled_cause` and revision), and the
9354
+ * call still succeeds because the row is not active.
9355
+ */
9116
9356
  deleteAuthCredential(id: number, disabledCause: string): void {
9117
- try {
9118
- this.#deleteStmt.run(normalizeDisabledCause(disabledCause), id);
9119
- } catch {
9120
- // Ignore delete failures
9121
- }
9357
+ this.#deleteStmt.run(normalizeDisabledCause(disabledCause), id);
9122
9358
  }
9123
9359
 
9124
9360
  /**
9125
9361
  * CAS-style disable: only soft-deletes the row when its `data` column still
9126
9362
  * matches `expectedData` and the row has not already been disabled. Used by
9127
9363
  * the OAuth refresh-failure path to avoid clobbering a peer that rotated the
9128
- * row between our pre-check and the disable.
9364
+ * row between our pre-check and the disable. Returns `false` only when no row
9365
+ * matched the predicate; a failed write throws.
9129
9366
  */
9130
9367
  tryDisableAuthCredentialIfMatches(id: number, expectedData: string, disabledCause: string): boolean {
9131
- try {
9132
- const result = this.#deleteIfMatchesStmt.run(normalizeDisabledCause(disabledCause), id, expectedData) as {
9133
- changes: number;
9134
- };
9135
- return result.changes === 1;
9136
- } catch {
9137
- return false;
9138
- }
9368
+ const result = this.#deleteIfMatchesStmt.run(normalizeDisabledCause(disabledCause), id, expectedData) as {
9369
+ changes: number;
9370
+ };
9371
+ return result.changes === 1;
9139
9372
  }
9140
9373
 
9374
+ /** Revision-checked disable. Returns `false` only when no row matched; a failed write throws. */
9141
9375
  tryDisableAuthCredentialIfRevision(id: number, expectedRevision: number, disabledCause: string): boolean {
9142
- try {
9143
- const result = this.#deleteIfRevisionStmt.run(normalizeDisabledCause(disabledCause), id, expectedRevision) as {
9144
- changes: number;
9145
- };
9146
- return result.changes === 1;
9147
- } catch {
9148
- return false;
9149
- }
9376
+ const result = this.#deleteIfRevisionStmt.run(normalizeDisabledCause(disabledCause), id, expectedRevision) as {
9377
+ changes: number;
9378
+ };
9379
+ return result.changes === 1;
9150
9380
  }
9151
9381
 
9382
+ /** Soft-deletes every active row of a provider. Throws when the write fails. */
9152
9383
  deleteAuthCredentialsForProvider(provider: string, disabledCause: string): void {
9153
- try {
9154
- this.#deleteByProviderStmt.run(normalizeDisabledCause(disabledCause), provider);
9155
- } catch {
9156
- // Ignore delete failures
9157
- }
9384
+ this.#deleteByProviderStmt.run(normalizeDisabledCause(disabledCause), provider);
9158
9385
  }
9159
9386
 
9160
9387
  getCache(key: string, options?: { includeExpired?: boolean }): string | null {
package/src/index.ts CHANGED
@@ -43,6 +43,7 @@ export * from "./usage/minimax-code";
43
43
  export * from "./usage/openai-codex";
44
44
  export * from "./usage/zai";
45
45
  export * from "./utils/anthropic-auth";
46
+ export * from "./utils/credential-id";
46
47
  export * from "./utils/discovery";
47
48
  export * from "./utils/event-stream";
48
49
  export * from "./utils/fallback-transport";
@@ -1606,10 +1606,16 @@ function isAnthropicUsageExhaustionResponse(
1606
1606
  const message = getStringProperty(error, "message") ?? getStringProperty(parsed, "message") ?? bodyText;
1607
1607
  return (
1608
1608
  /rate_limit_error/i.test(type ?? "") &&
1609
- (/request would exceed your account.?s rate limit/i.test(message) || /out_of_credits/i.test(message))
1609
+ (/request would exceed your account.?s rate limit/i.test(message) ||
1610
+ /out_of_credits/i.test(message) ||
1611
+ // Per-account model gating ("Usage credits are required for this model."):
1612
+ // the same credential never succeeds, so surface it for account rotation.
1613
+ /credits_required|usage credits are required/i.test(bodyText))
1610
1614
  );
1611
1615
  } catch {
1612
- return /request would exceed your account.?s rate limit|out_of_credits/i.test(bodyText);
1616
+ return /request would exceed your account.?s rate limit|out_of_credits|credits_required|usage credits are required/i.test(
1617
+ bodyText,
1618
+ );
1613
1619
  }
1614
1620
  }
1615
1621
 
@@ -25,6 +25,7 @@ import type {
25
25
  Model,
26
26
  SimpleStreamOptions,
27
27
  } from "../types";
28
+ import { stripCredentialIds } from "../utils/credential-id";
28
29
  import { AssistantMessageEventStream } from "../utils/event-stream";
29
30
 
30
31
  /**
@@ -37,6 +38,8 @@ import { AssistantMessageEventStream } from "../utils/event-stream";
37
38
  const NON_WIRE_KEYS = new Set<keyof SimpleStreamOptions>([
38
39
  "signal",
39
40
  "apiKey",
41
+ // Local stored-row id; the gateway authenticates upstream with its own rows.
42
+ "credentialId",
40
43
  "onStreamCreated",
41
44
  "fetch",
42
45
  "onPayload",
@@ -56,11 +59,18 @@ const NON_WIRE_KEYS = new Set<keyof SimpleStreamOptions>([
56
59
  * `JSON.stringify` throw outright, and the rest is dead weight the gateway
57
60
  * re-derives from its own tool registry. Only the protocol-meaningful,
58
61
  * JSON-safe `Tool` fields cross the wire.
62
+ *
63
+ * Prior assistant messages lose their local `credentialId`: the gateway
64
+ * authenticates upstream with its own rows, so the local row id never leaves.
59
65
  */
60
66
  function buildWireContext(context: Context): Context {
61
- if (!context.tools || context.tools.length === 0) return context;
67
+ const messages = stripCredentialIds(context.messages);
68
+ if (!context.tools || context.tools.length === 0) {
69
+ return messages === context.messages ? context : { ...context, messages };
70
+ }
62
71
  return {
63
72
  ...context,
73
+ messages,
64
74
  tools: context.tools.map(tool => ({
65
75
  name: tool.name,
66
76
  description: tool.description,
@@ -95,8 +95,10 @@ export function calculateRateLimitBackoffMs(reason: RateLimitReason): number {
95
95
  /** Detect usage/quota limit errors in error messages (persistent, requires credential switch). */
96
96
  // ZAI reports durable token exhaustion as "[1310][Weekly/Monthly Limit Exhausted...]".
97
97
  // Keep this explicit so generic "rate limit exhausted, retry..." throttles remain retryable.
98
+ // Anthropic gates some models per account with a 429 `credits_required` ("Usage credits are
99
+ // required for this model."); retrying the same account never succeeds, another account can.
98
100
  const USAGE_LIMIT_PATTERN =
99
- /usage.?limit|usage_limit_reached|usage_not_included|limit_reached|model.?limit|model_limit_reached|message.?limit|message_limit_reached|limit for this model|weekly\/monthly\s+limit\s+exhausted|quota.?exceeded|out_of_credits|request would exceed your account.?s rate limit|resource has been exhausted[^\n]*(?:quota|limit)/i;
101
+ /usage.?limit|usage_limit_reached|usage_not_included|limit_reached|model.?limit|model_limit_reached|message.?limit|message_limit_reached|limit for this model|weekly\/monthly\s+limit\s+exhausted|quota.?exceeded|out_of_credits|credits_required|usage credits are required|request would exceed your account.?s rate limit|resource has been exhausted[^\n]*(?:quota|limit)/i;
100
102
  export function isUsageLimitError(errorMessage: string): boolean {
101
103
  return USAGE_LIMIT_PATTERN.test(errorMessage);
102
104
  }
package/src/stream.ts CHANGED
@@ -417,7 +417,8 @@ function pipeAssistantStream(
417
417
  inner: AssistantMessageEventStream,
418
418
  signal?: AbortSignal,
419
419
  onStreamCreated?: () => void,
420
- ): void {
420
+ ): () => void {
421
+ const iteration = closableIteration(inner);
421
422
  void (async () => {
422
423
  try {
423
424
  let admitted = false;
@@ -426,7 +427,8 @@ function pipeAssistantStream(
426
427
  admitted = true;
427
428
  onStreamCreated?.();
428
429
  };
429
- for await (const event of inner) {
430
+ for await (const event of iteration.events) {
431
+ if (iteration.isClosed()) break;
430
432
  if (event.type !== "start") markAdmission();
431
433
  outer.push(event);
432
434
  // The inner provider stream owns abort semantics (it receives the
@@ -438,11 +440,42 @@ function pipeAssistantStream(
438
440
  return;
439
441
  }
440
442
  }
443
+ // A closed consumer still gets a settled result: the provider ends
444
+ // its stream once its cleanup runs, exactly as without the close.
445
+ if (iteration.isClosed()) markAdmission();
441
446
  if (!outer.done) outer.end(await inner.result());
442
447
  } catch (error) {
443
448
  outer.fail(error);
444
449
  }
445
450
  })();
451
+ return iteration.close;
452
+ }
453
+
454
+ interface ClosableIteration {
455
+ events: AssistantMessageEventStream;
456
+ isClosed(): boolean;
457
+ close(): void;
458
+ }
459
+
460
+ /**
461
+ * Iterate a provider stream on behalf of an outer stream's consumer.
462
+ *
463
+ * `close()` stops the iteration even while it is parked waiting for the next
464
+ * event and runs the inner stream's own `onConsumerClose` cleanup. Aborting the
465
+ * request signal alone never reaches a provider that cleans up only through
466
+ * that hook.
467
+ */
468
+ function closableIteration(inner: AssistantMessageEventStream): ClosableIteration {
469
+ let closed = false;
470
+ return {
471
+ events: inner,
472
+ isClosed: () => closed,
473
+ close: () => {
474
+ if (closed) return;
475
+ closed = true;
476
+ inner.closeConsumers();
477
+ },
478
+ };
446
479
  }
447
480
 
448
481
  export function streamFromLazyImport(
@@ -755,13 +788,18 @@ export function streamSimple<TApi extends Api>(
755
788
  : undefined;
756
789
  if (retryApiKey) {
757
790
  const consumerAbortController = new AbortController();
758
- const outer = new AssistantMessageEventStream(() => consumerAbortController.abort());
791
+ let closeActiveAttempt: (() => void) | undefined;
792
+ const outer = new AssistantMessageEventStream(() => {
793
+ consumerAbortController.abort();
794
+ closeActiveAttempt?.();
795
+ });
759
796
  const requestSignal = options?.signal
760
797
  ? AbortSignal.any([options.signal, consumerAbortController.signal])
761
798
  : consumerAbortController.signal;
762
799
  const onAuthError = options!.onAuthError!;
763
800
  const runAttempt = async (
764
801
  apiKey: string,
802
+ credentialId: number | undefined,
765
803
  captureAuthFailure: boolean,
766
804
  onStreamCreated?: () => void,
767
805
  ): Promise<AuthRetryFailure | undefined> => {
@@ -782,11 +820,15 @@ export function streamSimple<TApi extends Api>(
782
820
  const inner = streamSimple(model, context, {
783
821
  ...options,
784
822
  apiKey,
823
+ credentialId,
785
824
  onAuthError: undefined,
786
825
  onStreamCreated: markAdmission,
787
826
  signal: requestSignal,
788
827
  });
789
- for await (const event of inner) {
828
+ const iteration = closableIteration(inner);
829
+ closeActiveAttempt = iteration.close;
830
+ for await (const event of iteration.events) {
831
+ if (iteration.isClosed()) break;
790
832
  if (!emittedReplayUnsafeEvent && event.type === "start") {
791
833
  bufferedEvents.push(event);
792
834
  continue;
@@ -838,7 +880,10 @@ export function streamSimple<TApi extends Api>(
838
880
  };
839
881
 
840
882
  void (async () => {
841
- const failure = await runAttempt(retryApiKey, true, options?.onStreamCreated);
883
+ // The caller's credential id describes `options.apiKey` only; an env
884
+ // fallback key is never a stored row.
885
+ const initialCredentialId = options?.apiKey === retryApiKey ? options?.credentialId : undefined;
886
+ const failure = await runAttempt(retryApiKey, initialCredentialId, true, options?.onStreamCreated);
842
887
  if (!failure) return;
843
888
  let nextCredential: string | AuthRetryCredential | undefined;
844
889
  try {
@@ -853,11 +898,121 @@ export function streamSimple<TApi extends Api>(
853
898
  emitFailure(failure);
854
899
  return;
855
900
  }
856
- await runAttempt(retryCredential.apiKey, false, retryCredential.onStreamCreated);
901
+ await runAttempt(retryCredential.apiKey, retryCredential.credentialId, false, retryCredential.onStreamCreated);
857
902
  })();
858
903
  return outer;
859
904
  }
860
905
 
906
+ const credentialId = attributableCredentialId(model, options);
907
+ if (credentialId === undefined) return dispatchStreamSimple(model, context, options);
908
+ return streamWithCredentialAttribution(model, context, options ?? {}, credentialId);
909
+ }
910
+
911
+ /**
912
+ * Stored credential row to record on this request's messages, if any.
913
+ *
914
+ * The id only describes `options.apiKey`: without that key the request falls
915
+ * back to env/ADC credentials, and a pi-native gateway bearer authenticates to
916
+ * the gateway rather than to the upstream account that serves the turn.
917
+ */
918
+ function attributableCredentialId(model: Model<Api>, options: SimpleStreamOptions | undefined): number | undefined {
919
+ const credentialId = options?.credentialId;
920
+ if (credentialId === undefined || !options?.apiKey || model.transport === "pi-native") return undefined;
921
+ return Number.isSafeInteger(credentialId) ? credentialId : undefined;
922
+ }
923
+
924
+ /** Best-effort: attribution must never fail a request whose message object rejects writes. */
925
+ function setCredentialId(message: AssistantMessage, credentialId: number): void {
926
+ try {
927
+ Reflect.set(message, "credentialId", credentialId);
928
+ } catch {
929
+ // Frozen or hostile provider object; leave it unattributed.
930
+ }
931
+ }
932
+
933
+ function stampCredentialId(event: AssistantMessageEvent, credentialId: number): void {
934
+ if (event.type === "done") setCredentialId(event.message, credentialId);
935
+ else if (event.type === "error") {
936
+ setCredentialId(event.error, credentialId);
937
+ if (event.partial && event.partial !== event.error) setCredentialId(event.partial, credentialId);
938
+ } else if ("partial" in event) setCredentialId(event.partial, credentialId);
939
+ }
940
+
941
+ /**
942
+ * Whether a terminal message carries facts only a provider response can supply:
943
+ * an HTTP status, or a diagnostic minted from structured provider metadata. A
944
+ * transport exception, a local timeout, or an abort before any response has
945
+ * none of these.
946
+ */
947
+ function carriesProviderResponse(message: AssistantMessage): boolean {
948
+ if (message.stopReason !== "error" && message.stopReason !== "aborted") return true;
949
+ return (
950
+ message.errorStatus !== undefined ||
951
+ message.transportFailure?.status !== undefined ||
952
+ message.providerDiagnostic !== undefined
953
+ );
954
+ }
955
+
956
+ /**
957
+ * Whether this event proves the provider answered the request. `start` does
958
+ * not: providers emit it before the request is sent.
959
+ */
960
+ function isProviderResponseEvidence(event: AssistantMessageEvent): boolean {
961
+ if (event.type === "start") return false;
962
+ if (event.type === "error") return carriesProviderResponse(event.error);
963
+ return true;
964
+ }
965
+
966
+ /**
967
+ * Dispatch one request and record its stored credential row on every message
968
+ * the provider's response produced (partials, the terminal message, and the
969
+ * result), so the persisted turn names the account that served it. Until the
970
+ * provider has answered, nothing is stamped: a failure before any response
971
+ * stays unattributed, while a response-backed error (401, 429) and anything
972
+ * after the first streamed event keep the row.
973
+ */
974
+ function streamWithCredentialAttribution<TApi extends Api>(
975
+ model: Model<TApi>,
976
+ context: Context,
977
+ options: SimpleStreamOptions,
978
+ credentialId: number,
979
+ ): AssistantMessageEventStream {
980
+ const consumerAbortController = new AbortController();
981
+ const signal = options.signal
982
+ ? AbortSignal.any([options.signal, consumerAbortController.signal])
983
+ : consumerAbortController.signal;
984
+ const inner = dispatchStreamSimple(model, context, { ...options, signal });
985
+ const iteration = closableIteration(inner);
986
+ const outer = new AssistantMessageEventStream(() => {
987
+ consumerAbortController.abort();
988
+ iteration.close();
989
+ });
990
+ void (async () => {
991
+ let responded = false;
992
+ try {
993
+ for await (const event of iteration.events) {
994
+ if (iteration.isClosed()) break;
995
+ responded ||= isProviderResponseEvidence(event);
996
+ if (responded) stampCredentialId(event, credentialId);
997
+ outer.push(event);
998
+ if (outer.done) return;
999
+ }
1000
+ if (outer.done) return;
1001
+ const result = await inner.result();
1002
+ if (responded || carriesProviderResponse(result)) setCredentialId(result, credentialId);
1003
+ outer.end(result);
1004
+ } catch (error) {
1005
+ outer.fail(error);
1006
+ }
1007
+ })();
1008
+ return outer;
1009
+ }
1010
+
1011
+ function dispatchStreamSimple<TApi extends Api>(
1012
+ model: Model<TApi>,
1013
+ context: Context,
1014
+ options?: SimpleStreamOptions,
1015
+ ): AssistantMessageEventStream {
861
1016
  // Pi-native transport short-circuits the per-provider dispatch entirely:
862
1017
  // the gateway resolves provider + credential server-side, so we don't
863
1018
  // need an `apiKey` from `getEnvApiKey` here — `options.apiKey` carries
@@ -884,8 +1039,11 @@ export function streamSimple<TApi extends Api>(
884
1039
  maxTokens: resolvedRequestMaxTokens,
885
1040
  });
886
1041
  if (!options?.onStreamCreated) return events;
887
- const forwarded = new AssistantMessageEventStream();
888
- pipeAssistantStream(forwarded, events, options.signal, options.onStreamCreated);
1042
+ // The provider stream may clean up only through its own consumer-close
1043
+ // hook, so the forwarder hands an early close through to it.
1044
+ let closeEvents: (() => void) | undefined;
1045
+ const forwarded = new AssistantMessageEventStream(() => closeEvents?.());
1046
+ closeEvents = pipeAssistantStream(forwarded, events, options.signal, options.onStreamCreated);
889
1047
  return forwarded;
890
1048
  }
891
1049
  if (options?.customApiRegistry !== undefined && !isBuiltInApi(model.api)) {
package/src/types.d.ts CHANGED
@@ -188,6 +188,16 @@ export interface ProviderDispatch {
188
188
  readonly headers: Headers;
189
189
  readonly body: string | Uint8Array | undefined;
190
190
  }
191
+ /**
192
+ * API key paired with the stored credential row that supplied it.
193
+ *
194
+ * `credentialId` is the opaque, non-secret row id; it is omitted for
195
+ * external, env, or otherwise unknown keys.
196
+ */
197
+ export interface ResolvedApiKey {
198
+ apiKey: string;
199
+ credentialId?: number;
200
+ }
191
201
  /**
192
202
  * Credential returned by an auth retry resolver.
193
203
  *
@@ -196,8 +206,7 @@ export interface ProviderDispatch {
196
206
  * admitted. Ordinary callers can continue returning a string from
197
207
  * {@link StreamOptions.onAuthError}.
198
208
  */
199
- export interface AuthRetryCredential {
200
- apiKey: string;
209
+ export interface AuthRetryCredential extends ResolvedApiKey {
201
210
  onStreamCreated?: () => void;
202
211
  }
203
212
  export interface StreamOptions {
@@ -226,6 +235,12 @@ export interface StreamOptions {
226
235
  endpointConfiguration?: EndpointConfiguration;
227
236
  signal?: AbortSignal;
228
237
  apiKey?: string;
238
+ /**
239
+ * Stored credential row id that supplied `apiKey`. `streamSimple` records it
240
+ * as {@link AssistantMessage.credentialId} on every emitted message; leave it
241
+ * unset for external, env, or otherwise unknown keys.
242
+ */
243
+ credentialId?: number;
229
244
  /** Disables all transport-level replay; the fallback controller owns retries. */
230
245
  fallbackManaged?: boolean;
231
246
  /** Opaque token returned by beginAttempt for a managed transport invocation. */
@@ -717,6 +732,12 @@ export interface AssistantMessage {
717
732
  ttft?: number;
718
733
  /** Prompt-prefix fingerprint of the request that produced this message. */
719
734
  promptPrefix?: PromptPrefixTelemetry;
735
+ /**
736
+ * Stored credential row id that authenticated the request producing this
737
+ * message. An opaque, non-secret number only; absent for external, env, or
738
+ * unknown keys.
739
+ */
740
+ credentialId?: number;
720
741
  }
721
742
  export interface GoogleGeminiCliDiagnostics {
722
743
  responseAtMs?: number;
package/src/types.ts CHANGED
@@ -416,6 +416,17 @@ export interface ProviderDispatch {
416
416
  readonly body: string | Uint8Array | undefined;
417
417
  }
418
418
 
419
+ /**
420
+ * API key paired with the stored credential row that supplied it.
421
+ *
422
+ * `credentialId` is the opaque, non-secret row id; it is omitted for
423
+ * external, env, or otherwise unknown keys.
424
+ */
425
+ export interface ResolvedApiKey {
426
+ apiKey: string;
427
+ credentialId?: number;
428
+ }
429
+
419
430
  /**
420
431
  * Credential returned by an auth retry resolver.
421
432
  *
@@ -424,8 +435,7 @@ export interface ProviderDispatch {
424
435
  * admitted. Ordinary callers can continue returning a string from
425
436
  * {@link StreamOptions.onAuthError}.
426
437
  */
427
- export interface AuthRetryCredential {
428
- apiKey: string;
438
+ export interface AuthRetryCredential extends ResolvedApiKey {
429
439
  onStreamCreated?: () => void;
430
440
  }
431
441
 
@@ -455,6 +465,12 @@ export interface StreamOptions {
455
465
  endpointConfiguration?: EndpointConfiguration;
456
466
  signal?: AbortSignal;
457
467
  apiKey?: string;
468
+ /**
469
+ * Stored credential row id that supplied `apiKey`. `streamSimple` records it
470
+ * as {@link AssistantMessage.credentialId} on every emitted message; leave it
471
+ * unset for external, env, or otherwise unknown keys.
472
+ */
473
+ credentialId?: number;
458
474
  /** Disables all transport-level replay; the fallback controller owns retries. */
459
475
  fallbackManaged?: boolean;
460
476
  /** Opaque token returned by beginAttempt for a managed transport invocation. */
@@ -989,6 +1005,12 @@ export interface AssistantMessage {
989
1005
  ttft?: number; // Time to first token in milliseconds
990
1006
  /** Prompt-prefix fingerprint of the request that produced this message. */
991
1007
  promptPrefix?: PromptPrefixTelemetry;
1008
+ /**
1009
+ * Stored credential row id that authenticated the request producing this
1010
+ * message. An opaque, non-secret number only; absent for external, env, or
1011
+ * unknown keys.
1012
+ */
1013
+ credentialId?: number;
992
1014
  }
993
1015
 
994
1016
  export interface GoogleGeminiCliDiagnostics {
@@ -0,0 +1,12 @@
1
+ import type { Message } from "../types";
2
+ /**
3
+ * Drop the local stored-credential row id from assistant messages before a
4
+ * context leaves this process for a remote server (pi-native gateway, proxy).
5
+ *
6
+ * `credentialId` names a row in the local auth store; a remote server
7
+ * authenticates upstream with its own credentials, so the number is
8
+ * meaningless there and must not cross the wire. Returns `messages` itself when
9
+ * no message carries the field; otherwise copies the array and only the
10
+ * messages that carry it.
11
+ */
12
+ export declare function stripCredentialIds(messages: Message[]): Message[];
@@ -0,0 +1,23 @@
1
+ import type { Message } from "../types";
2
+
3
+ /**
4
+ * Drop the local stored-credential row id from assistant messages before a
5
+ * context leaves this process for a remote server (pi-native gateway, proxy).
6
+ *
7
+ * `credentialId` names a row in the local auth store; a remote server
8
+ * authenticates upstream with its own credentials, so the number is
9
+ * meaningless there and must not cross the wire. Returns `messages` itself when
10
+ * no message carries the field; otherwise copies the array and only the
11
+ * messages that carry it.
12
+ */
13
+ export function stripCredentialIds(messages: Message[]): Message[] {
14
+ let stripped: Message[] | undefined;
15
+ for (let index = 0; index < messages.length; index++) {
16
+ const message = messages[index];
17
+ if (message.role !== "assistant" || !Object.hasOwn(message, "credentialId")) continue;
18
+ stripped ??= messages.slice();
19
+ const { credentialId: _credentialId, ...rest } = message;
20
+ stripped[index] = rest;
21
+ }
22
+ return stripped ?? messages;
23
+ }
@@ -32,6 +32,14 @@ export declare class EventStream<T, R = T> implements AsyncIterable<T> {
32
32
  waitForConsumerDrain(signal: AbortSignal): Promise<void>;
33
33
  end(result?: R): void;
34
34
  endWaiting(): void;
35
+ /**
36
+ * Stop every iterator of this stream as if its consumer had returned early,
37
+ * so `onConsumerClose` runs. An iterator parked on the next event wakes now;
38
+ * one that is between events exits before yielding again. A forwarder whose
39
+ * own consumer left calls this to hand the cancellation to its source. The
40
+ * close is permanent: later iterators of the same stream return immediately.
41
+ */
42
+ closeConsumers(): void;
35
43
  fail(err: unknown): void;
36
44
  [Symbol.asyncIterator](): AsyncIterator<T>;
37
45
  result(): Promise<R>;
@@ -29,6 +29,7 @@ export class EventStream<T, R = T> implements AsyncIterable<T> {
29
29
  #activeConsumerCount = 0;
30
30
  done = false;
31
31
  #failed = false;
32
+ #consumersClosed = false;
32
33
  #error: unknown = undefined;
33
34
  finalResultPromise: Promise<R>;
34
35
  resolveFinalResult!: (result: R) => void;
@@ -206,6 +207,18 @@ export class EventStream<T, R = T> implements AsyncIterable<T> {
206
207
  }
207
208
  }
208
209
 
210
+ /**
211
+ * Stop every iterator of this stream as if its consumer had returned early,
212
+ * so `onConsumerClose` runs. An iterator parked on the next event wakes now;
213
+ * one that is between events exits before yielding again. A forwarder whose
214
+ * own consumer left calls this to hand the cancellation to its source. The
215
+ * close is permanent: later iterators of the same stream return immediately.
216
+ */
217
+ closeConsumers(): void {
218
+ this.#consumersClosed = true;
219
+ this.endWaiting();
220
+ }
221
+
209
222
  fail(err: unknown): void {
210
223
  if (this.done) return;
211
224
  this.done = true;
@@ -224,6 +237,7 @@ export class EventStream<T, R = T> implements AsyncIterable<T> {
224
237
  this.#activeConsumerCount += 1;
225
238
  try {
226
239
  while (true) {
240
+ if (this.#consumersClosed) return;
227
241
  const node = this.#dequeueEvent();
228
242
  if (node !== undefined) {
229
243
  yield node.event;