@sayknow-cli/ai 0.4.2 → 0.4.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.
Files changed (186) hide show
  1. package/dist/types/api-registry.d.ts +30 -0
  2. package/dist/types/auth-broker/client.d.ts +67 -0
  3. package/dist/types/auth-broker/index.d.ts +5 -0
  4. package/dist/types/auth-broker/refresher.d.ts +25 -0
  5. package/dist/types/auth-broker/remote-store.d.ts +99 -0
  6. package/dist/types/auth-broker/server.d.ts +32 -0
  7. package/dist/types/auth-broker/types.d.ts +110 -0
  8. package/dist/types/auth-broker/wire-schemas.d.ts +443 -0
  9. package/dist/types/auth-gateway/http.d.ts +40 -0
  10. package/dist/types/auth-gateway/index.d.ts +3 -0
  11. package/dist/types/auth-gateway/server.d.ts +36 -0
  12. package/dist/types/auth-gateway/types.d.ts +115 -0
  13. package/dist/types/auth-storage.d.ts +699 -0
  14. package/dist/types/cli.d.ts +2 -0
  15. package/dist/types/context-cap-policy.d.ts +10 -0
  16. package/dist/types/index.d.ts +53 -0
  17. package/dist/types/model-cache.d.ts +19 -0
  18. package/dist/types/model-manager.d.ts +64 -0
  19. package/dist/types/model-retirements.d.ts +6 -0
  20. package/dist/types/model-thinking.d.ts +74 -0
  21. package/dist/types/models.d.ts +21 -0
  22. package/dist/types/provider-details.d.ts +24 -0
  23. package/dist/types/provider-models/bundled-references.d.ts +4 -0
  24. package/dist/types/provider-models/descriptors.d.ts +48 -0
  25. package/dist/types/provider-models/google.d.ts +20 -0
  26. package/dist/types/provider-models/index.d.ts +5 -0
  27. package/dist/types/provider-models/ollama.d.ts +7 -0
  28. package/dist/types/provider-models/openai-compat.d.ts +256 -0
  29. package/dist/types/provider-models/special.d.ts +19 -0
  30. package/dist/types/providers/amazon-bedrock.d.ts +60 -0
  31. package/dist/types/providers/anthropic-messages-server-schema.d.ts +450 -0
  32. package/dist/types/providers/anthropic-messages-server.d.ts +17 -0
  33. package/dist/types/providers/anthropic.d.ts +209 -0
  34. package/dist/types/providers/aws-credential-config.d.ts +19 -0
  35. package/dist/types/providers/aws-credentials.d.ts +43 -0
  36. package/dist/types/providers/aws-eventstream.d.ts +38 -0
  37. package/dist/types/providers/aws-sigv4.d.ts +55 -0
  38. package/dist/types/providers/azure-openai-responses.d.ts +15 -0
  39. package/dist/types/providers/composer-discipline.d.ts +26 -0
  40. package/dist/types/providers/cursor/client-version.d.ts +10 -0
  41. package/dist/types/providers/cursor/gen/agent_pb.d.ts +13022 -0
  42. package/dist/types/providers/cursor.d.ts +45 -0
  43. package/dist/types/providers/error-message.d.ts +27 -0
  44. package/dist/types/providers/github-copilot-headers.d.ts +40 -0
  45. package/dist/types/providers/gitlab-duo.d.ts +27 -0
  46. package/dist/types/providers/google-auth.d.ts +24 -0
  47. package/dist/types/providers/google-gemini-cli.d.ts +75 -0
  48. package/dist/types/providers/google-gemini-headers.d.ts +43 -0
  49. package/dist/types/providers/google-shared.d.ts +179 -0
  50. package/dist/types/providers/google-types.d.ts +138 -0
  51. package/dist/types/providers/google-vertex.d.ts +7 -0
  52. package/dist/types/providers/google.d.ts +4 -0
  53. package/dist/types/providers/grammar.d.ts +1 -0
  54. package/dist/types/providers/kimi.d.ts +27 -0
  55. package/dist/types/providers/mock.d.ts +177 -0
  56. package/dist/types/providers/ollama.d.ts +41 -0
  57. package/dist/types/providers/openai-anthropic-shim.d.ts +31 -0
  58. package/dist/types/providers/openai-bounded-rate-limits.d.ts +3 -0
  59. package/dist/types/providers/openai-chat-server-schema.d.ts +815 -0
  60. package/dist/types/providers/openai-chat-server.d.ts +16 -0
  61. package/dist/types/providers/openai-codex/constants.d.ts +26 -0
  62. package/dist/types/providers/openai-codex/request-transformer.d.ts +50 -0
  63. package/dist/types/providers/openai-codex/response-handler.d.ts +18 -0
  64. package/dist/types/providers/openai-codex-responses.d.ts +68 -0
  65. package/dist/types/providers/openai-completions-compat.d.ts +27 -0
  66. package/dist/types/providers/openai-completions.d.ts +33 -0
  67. package/dist/types/providers/openai-request-transform.d.ts +4 -0
  68. package/dist/types/providers/openai-responses-server-schema.d.ts +392 -0
  69. package/dist/types/providers/openai-responses-server.d.ts +17 -0
  70. package/dist/types/providers/openai-responses-shared.d.ts +104 -0
  71. package/dist/types/providers/openai-responses.d.ts +32 -0
  72. package/dist/types/providers/pi-native-client.d.ts +13 -0
  73. package/dist/types/providers/pi-native-server.d.ts +60 -0
  74. package/dist/types/providers/register-builtins.d.ts +31 -0
  75. package/dist/types/providers/synthetic.d.ts +26 -0
  76. package/dist/types/providers/transform-messages.d.ts +14 -0
  77. package/dist/types/providers/vision-guard.d.ts +8 -0
  78. package/dist/types/rate-limit-utils.d.ts +19 -0
  79. package/dist/types/stream.d.ts +43 -0
  80. package/dist/types/types.d.ts +882 -0
  81. package/dist/types/usage/claude.d.ts +3 -0
  82. package/dist/types/usage/gemini.d.ts +2 -0
  83. package/dist/types/usage/github-copilot.d.ts +7 -0
  84. package/dist/types/usage/google-antigravity.d.ts +2 -0
  85. package/dist/types/usage/grok-cli.d.ts +10 -0
  86. package/dist/types/usage/kimi.d.ts +2 -0
  87. package/dist/types/usage/minimax-code.d.ts +2 -0
  88. package/dist/types/usage/openai-codex.d.ts +3 -0
  89. package/dist/types/usage/shared.d.ts +1 -0
  90. package/dist/types/usage/zai.d.ts +2 -0
  91. package/dist/types/usage.d.ts +258 -0
  92. package/dist/types/utils/abort.d.ts +19 -0
  93. package/dist/types/utils/anthropic-auth.d.ts +31 -0
  94. package/dist/types/utils/discovery/antigravity.d.ts +67 -0
  95. package/dist/types/utils/discovery/codex.d.ts +38 -0
  96. package/dist/types/utils/discovery/cursor.d.ts +23 -0
  97. package/dist/types/utils/discovery/gemini.d.ts +25 -0
  98. package/dist/types/utils/discovery/index.d.ts +4 -0
  99. package/dist/types/utils/discovery/openai-compatible.d.ts +74 -0
  100. package/dist/types/utils/event-stream.d.ts +39 -0
  101. package/dist/types/utils/fallback-transport.d.ts +66 -0
  102. package/dist/types/utils/fireworks-model-id.d.ts +10 -0
  103. package/dist/types/utils/foundry.d.ts +1 -0
  104. package/dist/types/utils/h2-fetch.d.ts +22 -0
  105. package/dist/types/utils/http-inspector.d.ts +35 -0
  106. package/dist/types/utils/idle-iterator.d.ts +67 -0
  107. package/dist/types/utils/json-parse.d.ts +18 -0
  108. package/dist/types/utils/oauth/alibaba-coding-plan.d.ts +18 -0
  109. package/dist/types/utils/oauth/anthropic.d.ts +22 -0
  110. package/dist/types/utils/oauth/api-key-login.d.ts +35 -0
  111. package/dist/types/utils/oauth/api-key-validation.d.ts +27 -0
  112. package/dist/types/utils/oauth/callback-server.d.ts +60 -0
  113. package/dist/types/utils/oauth/cerebras.d.ts +1 -0
  114. package/dist/types/utils/oauth/cloudflare-ai-gateway.d.ts +18 -0
  115. package/dist/types/utils/oauth/cursor.d.ts +15 -0
  116. package/dist/types/utils/oauth/deepinfra.d.ts +1 -0
  117. package/dist/types/utils/oauth/deepseek.d.ts +10 -0
  118. package/dist/types/utils/oauth/firepass.d.ts +1 -0
  119. package/dist/types/utils/oauth/fireworks.d.ts +1 -0
  120. package/dist/types/utils/oauth/fugu.d.ts +1 -0
  121. package/dist/types/utils/oauth/github-copilot.d.ts +38 -0
  122. package/dist/types/utils/oauth/gitlab-duo.d.ts +3 -0
  123. package/dist/types/utils/oauth/glm-zcode.d.ts +71 -0
  124. package/dist/types/utils/oauth/google-antigravity.d.ts +11 -0
  125. package/dist/types/utils/oauth/google-gemini-cli.d.ts +10 -0
  126. package/dist/types/utils/oauth/google-oauth-shared.d.ts +28 -0
  127. package/dist/types/utils/oauth/huggingface.d.ts +19 -0
  128. package/dist/types/utils/oauth/index.d.ts +39 -0
  129. package/dist/types/utils/oauth/kagi.d.ts +17 -0
  130. package/dist/types/utils/oauth/kilo.d.ts +5 -0
  131. package/dist/types/utils/oauth/kimi.d.ts +21 -0
  132. package/dist/types/utils/oauth/litellm.d.ts +18 -0
  133. package/dist/types/utils/oauth/lm-studio.d.ts +17 -0
  134. package/dist/types/utils/oauth/minimax-code.d.ts +28 -0
  135. package/dist/types/utils/oauth/moonshot.d.ts +1 -0
  136. package/dist/types/utils/oauth/nanogpt.d.ts +1 -0
  137. package/dist/types/utils/oauth/nvidia.d.ts +18 -0
  138. package/dist/types/utils/oauth/ollama-cloud.d.ts +2 -0
  139. package/dist/types/utils/oauth/ollama.d.ts +18 -0
  140. package/dist/types/utils/oauth/openai-codex.d.ts +21 -0
  141. package/dist/types/utils/oauth/opencode.d.ts +18 -0
  142. package/dist/types/utils/oauth/parallel.d.ts +17 -0
  143. package/dist/types/utils/oauth/perplexity.d.ts +9 -0
  144. package/dist/types/utils/oauth/pkce.d.ts +8 -0
  145. package/dist/types/utils/oauth/qianfan.d.ts +17 -0
  146. package/dist/types/utils/oauth/qwen-portal.d.ts +19 -0
  147. package/dist/types/utils/oauth/synthetic.d.ts +1 -0
  148. package/dist/types/utils/oauth/tavily.d.ts +17 -0
  149. package/dist/types/utils/oauth/together.d.ts +1 -0
  150. package/dist/types/utils/oauth/types.d.ts +45 -0
  151. package/dist/types/utils/oauth/venice.d.ts +18 -0
  152. package/dist/types/utils/oauth/vercel-ai-gateway.d.ts +18 -0
  153. package/dist/types/utils/oauth/vllm.d.ts +16 -0
  154. package/dist/types/utils/oauth/xai.d.ts +30 -0
  155. package/dist/types/utils/oauth/xiaomi.d.ts +25 -0
  156. package/dist/types/utils/oauth/zai.d.ts +18 -0
  157. package/dist/types/utils/oauth/zenmux.d.ts +1 -0
  158. package/dist/types/utils/overflow.d.ts +14 -0
  159. package/dist/types/utils/parse-bind.d.ts +23 -0
  160. package/dist/types/utils/provider-response.d.ts +3 -0
  161. package/dist/types/utils/retry-after.d.ts +3 -0
  162. package/dist/types/utils/retry-budget.d.ts +1 -0
  163. package/dist/types/utils/retry.d.ts +27 -0
  164. package/dist/types/utils/schema/adapt.d.ts +24 -0
  165. package/dist/types/utils/schema/compatibility.d.ts +30 -0
  166. package/dist/types/utils/schema/dereference.d.ts +11 -0
  167. package/dist/types/utils/schema/draft.d.ts +10 -0
  168. package/dist/types/utils/schema/equality.d.ts +4 -0
  169. package/dist/types/utils/schema/fields.d.ts +49 -0
  170. package/dist/types/utils/schema/index.d.ts +14 -0
  171. package/dist/types/utils/schema/json-schema-validator.d.ts +12 -0
  172. package/dist/types/utils/schema/meta-validator.d.ts +2 -0
  173. package/dist/types/utils/schema/normalize.d.ts +93 -0
  174. package/dist/types/utils/schema/root-combinator.d.ts +12 -0
  175. package/dist/types/utils/schema/spill.d.ts +8 -0
  176. package/dist/types/utils/schema/stamps.d.ts +25 -0
  177. package/dist/types/utils/schema/types.d.ts +4 -0
  178. package/dist/types/utils/schema/wire.d.ts +54 -0
  179. package/dist/types/utils/schema/zod-decontaminate.d.ts +31 -0
  180. package/dist/types/utils/sse-debug.d.ts +10 -0
  181. package/dist/types/utils/tool-call-healing.d.ts +71 -0
  182. package/dist/types/utils/tool-choice-capability.d.ts +41 -0
  183. package/dist/types/utils/tool-choice.d.ts +50 -0
  184. package/dist/types/utils/validation.d.ts +17 -0
  185. package/dist/types/utils.d.ts +89 -0
  186. package/package.json +25 -24
@@ -0,0 +1,699 @@
1
+ /**
2
+ * Credential storage for API keys and OAuth tokens.
3
+ * Handles loading, saving, refreshing credentials, and usage tracking.
4
+ *
5
+ * This module defines:
6
+ * - `AuthCredentialStore` interface: persistence abstraction (SQLite, remote vault, …)
7
+ * - `AuthStorage` class: credential management with round-robin, usage limits, OAuth refresh
8
+ * - `SqliteAuthCredentialStore`: concrete SQLite-backed implementation
9
+ */
10
+ import { Database } from "bun:sqlite";
11
+ import type { Provider } from "./types";
12
+ import type { CredentialRankingStrategy, UsageLogger, UsageProvider, UsageReport } from "./usage";
13
+ import type { OAuthController, OAuthCredentials, OAuthProviderId } from "./utils/oauth/types";
14
+ export type ApiKeyCredential = {
15
+ type: "api_key";
16
+ key: string;
17
+ };
18
+ export type OAuthCredential = {
19
+ type: "oauth";
20
+ } & OAuthCredentials;
21
+ export type AuthCredential = ApiKeyCredential | OAuthCredential;
22
+ export type AuthCredentialEntry = AuthCredential | AuthCredential[];
23
+ export type AuthStorageData = Record<string, AuthCredentialEntry>;
24
+ /**
25
+ * Serialized representation of AuthStorage for passing to subagent workers.
26
+ * Contains only the essential credential data, not runtime state.
27
+ */
28
+ export interface SerializedAuthStorage {
29
+ credentials: Record<string, Array<{
30
+ id: number;
31
+ type: "api_key" | "oauth";
32
+ data: Record<string, unknown>;
33
+ }>>;
34
+ runtimeOverrides?: Record<string, string>;
35
+ dbPath?: string;
36
+ }
37
+ /**
38
+ * Auth credential with database row ID for updates/deletes.
39
+ * Wraps AuthCredential with storage metadata.
40
+ */
41
+ export interface StoredAuthCredential {
42
+ id: number;
43
+ provider: string;
44
+ credential: AuthCredential;
45
+ disabledCause: string | null;
46
+ }
47
+ /**
48
+ * Per-credential health record returned by {@link AuthStorage.checkCredentials}.
49
+ *
50
+ * Use this to identify which credential in a multi-account pool is causing
51
+ * auth errors. `ok` is tri-state:
52
+ *
53
+ * - `true` — credential authenticated against the provider's auth-verifying
54
+ * probe (today: the usage endpoint). For OAuth this also exercises refresh
55
+ * when the access token was expired.
56
+ * - `false` — the probe rejected the credential (401/403/refresh failure/etc).
57
+ * `reason` carries the upstream error string.
58
+ * - `null` — no probe is configured for this provider (or the configured
59
+ * probe doesn't support this credential type). The credential's auth
60
+ * status is unverifiable from here.
61
+ */
62
+ export interface CredentialHealthResult {
63
+ /** Database row id (matches {@link StoredAuthCredential.id}). */
64
+ id: number;
65
+ provider: string;
66
+ type: AuthCredential["type"];
67
+ /** OAuth email if known on the stored credential or surfaced by the probe. */
68
+ email?: string;
69
+ /** OAuth account id / org id if known. */
70
+ accountId?: string;
71
+ /** `true` when the refresh token lives on a remote broker (sentinel was present). */
72
+ remoteRefresh?: true;
73
+ ok: boolean | null;
74
+ /** Failure / unverifiable reason; absent when `ok === true`. */
75
+ reason?: string;
76
+ /** Probe usage report (raw payload stripped) when `ok === true`. */
77
+ report?: Omit<UsageReport, "raw">;
78
+ }
79
+ export interface CheckCredentialsOptions {
80
+ signal?: AbortSignal;
81
+ /** Per-credential probe timeout (ms). Defaults to the configured usage request timeout. */
82
+ timeoutMs?: number;
83
+ /** Provider → base URL override, same shape as {@link AuthStorage.fetchUsageReports}. */
84
+ baseUrlResolver?: (provider: Provider) => string | undefined;
85
+ }
86
+ /**
87
+ * Sentinel value placed in OAuth `refresh` fields when a credential is shared
88
+ * via {@link AuthStorage.exportSnapshot}. Refresh tokens never leave the broker;
89
+ * clients must call back to refresh.
90
+ */
91
+ export declare const REMOTE_REFRESH_SENTINEL: "__remote__";
92
+ export type RemoteRefreshSentinel = typeof REMOTE_REFRESH_SENTINEL;
93
+ /** OAuth credential with refresh token replaced by the broker sentinel. */
94
+ export type RemoteOAuthCredential = Omit<OAuthCredential, "refresh"> & {
95
+ refresh: RemoteRefreshSentinel;
96
+ };
97
+ /** Discriminated credential payload as published by the broker. */
98
+ export type SnapshotCredential = ApiKeyCredential | RemoteOAuthCredential;
99
+ export interface AuthCredentialSnapshotEntry {
100
+ id: number;
101
+ provider: string;
102
+ credential: SnapshotCredential;
103
+ identityKey: string | null;
104
+ }
105
+ export type AuthCredentialIfAbsentReason = "inserted" | "updated-existing" | "skipped-existing" | "skipped-existing-runtime" | "skipped-existing-config" | "skipped-existing-env" | "skipped-existing-fallback" | "skipped-invalid";
106
+ export interface AuthCredentialIfAbsentResult {
107
+ inserted: boolean;
108
+ reason: AuthCredentialIfAbsentReason;
109
+ provider: string;
110
+ entries: StoredAuthCredential[];
111
+ }
112
+ export interface AuthCredentialIfAbsentSnapshotResult {
113
+ inserted: boolean;
114
+ reason: AuthCredentialIfAbsentReason;
115
+ provider: string;
116
+ entries: AuthCredentialSnapshotEntry[];
117
+ }
118
+ /**
119
+ * Wire-shaped snapshot exported by {@link AuthStorage.exportSnapshot} and
120
+ * served by the auth-broker server on `GET /v1/snapshot`.
121
+ */
122
+ export interface AuthCredentialSnapshot {
123
+ generation: number;
124
+ generatedAt: number;
125
+ credentials: AuthCredentialSnapshotEntry[];
126
+ }
127
+ /**
128
+ * Persistence abstraction consumed by {@link AuthStorage}.
129
+ *
130
+ * Concrete implementations:
131
+ * - {@link SqliteAuthCredentialStore} — local SQLite-backed store (default).
132
+ * - `RemoteAuthCredentialStore` from `./auth-broker` — client-side snapshot of
133
+ * a remote broker; mutating methods (`replace*`, `upsert*`, `delete*ForProvider`)
134
+ * throw because login flows route through the broker, not the client.
135
+ */
136
+ export interface AuthCredentialStore {
137
+ close(): void;
138
+ listAuthCredentials(provider?: string): StoredAuthCredential[];
139
+ updateAuthCredential(id: number, credential: AuthCredential): void;
140
+ deleteAuthCredential(id: number, disabledCause: string): void;
141
+ tryDisableAuthCredentialIfMatches(id: number, expectedData: string, disabledCause: string): boolean;
142
+ replaceAuthCredentialsForProvider(provider: string, credentials: AuthCredential[]): StoredAuthCredential[];
143
+ upsertAuthCredentialForProvider(provider: string, credential: AuthCredential): StoredAuthCredential[];
144
+ upsertAuthCredentialForProviderIfAbsent(provider: string, credential: AuthCredential): AuthCredentialIfAbsentResult;
145
+ deleteAuthCredentialsForProvider(provider: string, disabledCause: string): void;
146
+ getCache(key: string, options?: {
147
+ includeExpired?: boolean;
148
+ }): string | null;
149
+ setCache(key: string, value: string, expiresAtSec: number): void;
150
+ deleteCachePrefix?(prefix: string): void;
151
+ cleanExpiredCache(): void;
152
+ /**
153
+ * Optional store-supplied OAuth refresh. When present, `AuthStorage` uses
154
+ * it before the per-provider local refresh path. `RemoteAuthCredentialStore`
155
+ * implements this against the broker; SQLite stores leave it undefined.
156
+ *
157
+ * Precedence: `AuthStorageOptions.refreshOAuthCredential` > this hook > local.
158
+ *
159
+ * `signal` propagates the agent's cancel (ESC, request abort, …) all the
160
+ * way to the broker fetch so a hung connection can't strand the caller
161
+ * for `timeoutMs * (maxRetries + 1)`.
162
+ */
163
+ refreshOAuthCredential?(provider: Provider, credentialId: number, credential: OAuthCredential, signal?: AbortSignal): Promise<OAuthCredentials>;
164
+ /**
165
+ * Optional async pre-read hook invoked after AuthStorage selects a stored
166
+ * credential but before it returns that credential for an outbound request.
167
+ * Remote broker stores use this to wait out imminent rotations and refresh
168
+ * their local snapshot before the caller sees a stale access token.
169
+ */
170
+ prepareForRequest?(credentialId: number, opts?: {
171
+ signal?: AbortSignal;
172
+ }): Promise<boolean | undefined>;
173
+ /**
174
+ * Optional store-supplied aggregate usage fetch. When present, `AuthStorage`
175
+ * routes `fetchUsageReports()` here instead of fanning out per-credential.
176
+ * `RemoteAuthCredentialStore` proxies to the broker (whose datacenter IP
177
+ * isn't rate-limited like a heavy residential client).
178
+ *
179
+ * Precedence: `AuthStorageOptions.fetchUsageReports` > this hook > local fan-out.
180
+ *
181
+ * `signal` propagates the agent's cancel down to the broker fetch.
182
+ */
183
+ fetchUsageReports?(signal?: AbortSignal): Promise<UsageReport[] | null>;
184
+ /**
185
+ * Optional store-supplied per-credential usage report lookup. When present,
186
+ * `AuthStorage` consults this before its own per-credential upstream fetch
187
+ * (`#getUsageReport`). `RemoteAuthCredentialStore` implements this against
188
+ * the broker's aggregate `/v1/usage` (one coalesced round-trip shared across
189
+ * all callers) so multi-credential ranking on the client never hits the
190
+ * upstream provider's rate-limited usage endpoint from the laptop IP.
191
+ *
192
+ * Returning `null` is authoritative — `AuthStorage` does NOT fall back to
193
+ * the local fetch path. The store hook owns the decision, since falling
194
+ * back would re-introduce the per-IP rate-limit problem the broker exists
195
+ * to avoid.
196
+ *
197
+ * `signal` propagates the agent's cancel down to the broker fetch.
198
+ */
199
+ getUsageReport?(provider: Provider, credential: OAuthCredential, signal?: AbortSignal): Promise<UsageReport | null>;
200
+ /**
201
+ * Optional store hook to invalidate a specific credential after the upstream
202
+ * provider returned 401 on a supposedly-fresh key. Remote stores force the
203
+ * broker to re-issue the row; local stores can leave it undefined and let
204
+ * {@link AuthStorage.invalidateCredentialMatching} fall back to `reload()`.
205
+ */
206
+ markCredentialSuspect?(credentialId: number, opts?: {
207
+ signal?: AbortSignal;
208
+ }): Promise<void>;
209
+ /**
210
+ * Optional async write hook for upserting a single credential. When present,
211
+ * `AuthStorage.#upsertOAuthCredential` routes through this instead of the
212
+ * sync `upsertAuthCredentialForProvider`. `RemoteAuthCredentialStore` uses
213
+ * it to send the upsert to the broker via `POST /v1/credential`.
214
+ *
215
+ * Implementations MUST update the in-memory snapshot before returning so the
216
+ * post-write read path is consistent.
217
+ */
218
+ upsertAuthCredentialRemote?(provider: string, credential: AuthCredential): Promise<StoredAuthCredential[]>;
219
+ upsertAuthCredentialRemoteIfAbsent?(provider: string, credential: AuthCredential): Promise<AuthCredentialIfAbsentResult>;
220
+ /**
221
+ * Optional async write hook for replace-all semantics (e.g. API-key login
222
+ * overwriting any previous keys for the same provider). When present,
223
+ * `AuthStorage.set` routes through this instead of the sync
224
+ * `replaceAuthCredentialsForProvider`.
225
+ */
226
+ replaceAuthCredentialsRemote?(provider: string, credentials: AuthCredential[]): Promise<StoredAuthCredential[]>;
227
+ /**
228
+ * Optional async write hook for clearing every credential for a provider
229
+ * (logout). When present, `AuthStorage.remove` routes through this instead
230
+ * of the sync `deleteAuthCredentialsForProvider`.
231
+ */
232
+ deleteAuthCredentialsRemote?(provider: string, disabledCause: string): Promise<void>;
233
+ }
234
+ /**
235
+ * Event payload describing a credential that was just soft-disabled.
236
+ *
237
+ * Today the only call site is OAuth refresh failures with a definitive cause
238
+ * (`invalid_grant`, `401/403` not from a network blip, etc.) — the
239
+ * disabled_cause string is the verbatim error captured for forensics.
240
+ *
241
+ * Subscribers can use this to surface a notification, banner, or auto-launch
242
+ * a re-login flow instead of letting the credential silently disappear.
243
+ */
244
+ export interface CredentialDisabledEvent {
245
+ provider: string;
246
+ disabledCause: string;
247
+ }
248
+ /**
249
+ * How {@link AuthStorage} orders multiple healthy OAuth credentials of the same
250
+ * provider:type pool when selecting one for a (new) session.
251
+ *
252
+ * - `balanced` (default): prefer the least-used / lowest-drain-rate account.
253
+ * Spreads load across accounts and keeps burst headroom on every account.
254
+ * - `earliest-reset`: prefer the non-blocked account whose usage window resets
255
+ * soonest (earliest-expiry-first). Tumbling-window quota is perishable —
256
+ * unused quota is lost at reset — so draining the soonest-to-reset account
257
+ * first minimizes wasted quota. Drain/used metrics remain tiebreakers.
258
+ *
259
+ * Only affects ranking, which the `shouldRank` guard already limits to session
260
+ * start (or when the session's preferred credential is blocked), so this never
261
+ * thrashes accounts mid-session / cold-starts the server-side prompt cache.
262
+ */
263
+ export type CredentialRankingMode = "balanced" | "earliest-reset";
264
+ export type AuthStorageOptions = {
265
+ usageProviderResolver?: (provider: Provider) => UsageProvider | undefined;
266
+ rankingStrategyResolver?: (provider: Provider) => CredentialRankingStrategy | undefined;
267
+ credentialRankingMode?: CredentialRankingMode;
268
+ usageFetch?: typeof fetch;
269
+ usageRequestTimeoutMs?: number;
270
+ usageLogger?: UsageLogger;
271
+ /**
272
+ * Resolve a config value (API key, header value, etc.) to an actual value.
273
+ * - coding-agent injects its resolveConfigValue (supports "!command" syntax via pi-natives)
274
+ * - Default: checks environment variable first, then treats as literal
275
+ */
276
+ configValueResolver?: (config: string) => Promise<string | undefined>;
277
+ /**
278
+ * Optional callback fired when AuthStorage automatically disables a
279
+ * credential because something detected it as no longer usable — today
280
+ * that's the OAuth refresh-failure path in `getApiKey`. NOT fired for
281
+ * user-initiated `remove()` (the user already knows) or dedup of
282
+ * duplicate credentials (uninteresting hygiene).
283
+ */
284
+ onCredentialDisabled?: (event: CredentialDisabledEvent) => void | Promise<void>;
285
+ /**
286
+ * Override OAuth refresh. When set, `AuthStorage` calls this instead of the
287
+ * per-provider local refresh function. Receives the credential id so the
288
+ * implementation can address remote credentials.
289
+ *
290
+ * Must return updated {@link OAuthCredentials} with at least `access` and
291
+ * `expires`. `refresh` may be an opaque sentinel (e.g. `"__remote__"`) when
292
+ * the actual refresh token never leaves the broker.
293
+ */
294
+ refreshOAuthCredential?: (provider: Provider, credentialId: number, credential: OAuthCredential, signal?: AbortSignal) => Promise<OAuthCredentials>;
295
+ /**
296
+ * Human-readable description of the credential store backing this
297
+ * AuthStorage instance. Surfaced through {@link AuthStorage.describeCredentialSource}
298
+ * so the TUI can show where a token came from (broker URL or local SQLite path).
299
+ *
300
+ * Examples:
301
+ * - `"local ~/.skc/agent/agent.db"`
302
+ * - `"broker http://can.internal:8765"`
303
+ */
304
+ sourceLabel?: string;
305
+ /**
306
+ * Override `fetchUsageReports`. When set, `AuthStorage.fetchUsageReports`
307
+ * calls this instead of fanning out per-credential. The primary use case is
308
+ * routing through a broker that egresses from a less-throttled IP — e.g. a
309
+ * residential laptop trips Anthropic's per-IP rate limit on the usage
310
+ * endpoint and drops 2-of-5 credentials, while the VPS broker gets all 5.
311
+ *
312
+ * Implementations may return null when no usage data is available; the
313
+ * AuthStorage caller surfaces that to its own consumer unchanged.
314
+ */
315
+ fetchUsageReports?: (signal?: AbortSignal) => Promise<UsageReport[] | null>;
316
+ };
317
+ type AuthApiKeyOptions = {
318
+ baseUrl?: string;
319
+ modelId?: string;
320
+ /**
321
+ * Caller's cancel signal. Threaded into any broker-bound OAuth refresh so
322
+ * `ESC` / request abort actually kills a hung broker fetch instead of
323
+ * stranding the caller for `timeoutMs * (maxRetries + 1)`.
324
+ */
325
+ signal?: AbortSignal;
326
+ /** Pin selection to one stored credential instead of using round-robin/ranking. */
327
+ credentialSelector?: AuthCredentialSelector;
328
+ };
329
+ export type AuthCredentialSelectorKind = "id" | "email" | "account" | "project";
330
+ export interface AuthCredentialSelector {
331
+ kind: AuthCredentialSelectorKind;
332
+ value: string;
333
+ }
334
+ /**
335
+ * Refreshed OAuth access plus identity metadata returned by
336
+ * {@link AuthStorage.getOAuthAccess}. Callers that authenticate via a bearer
337
+ * AND need the credential's identity (OpenAI code backend `chatgpt-account-id`, Google
338
+ * `projectId`, GitHub `enterpriseUrl`) consume this shape directly; the
339
+ * refresh slot is deliberately omitted because rotating refresh tokens never
340
+ * leave {@link AuthStorage}.
341
+ */
342
+ export interface OAuthAccess {
343
+ accessToken: string;
344
+ accountId?: string;
345
+ email?: string;
346
+ projectId?: string;
347
+ enterpriseUrl?: string;
348
+ }
349
+ export interface InvalidateCredentialMatchingOptions {
350
+ signal?: AbortSignal;
351
+ sessionId?: string;
352
+ }
353
+ /**
354
+ * Credential storage backed by an AuthCredentialStore.
355
+ * Reads from storage on reload(), manages round-robin credential selection,
356
+ * usage limit tracking, and OAuth token refresh.
357
+ */
358
+ export declare class AuthStorage {
359
+ #private;
360
+ constructor(store: AuthCredentialStore, options?: AuthStorageOptions);
361
+ /**
362
+ * Create an AuthStorage instance backed by a AuthCredentialStore.
363
+ * Convenience factory for standalone use (e.g., pi-ai CLI).
364
+ * @param dbPath - Path to SQLite database
365
+ */
366
+ static create(dbPath: string, options?: AuthStorageOptions): Promise<AuthStorage>;
367
+ /**
368
+ * Close the underlying credential store.
369
+ *
370
+ * After calling this, the instance must not be reused.
371
+ */
372
+ close(): void;
373
+ getGeneration(): number;
374
+ onGenerationChanged(listener: (generation: number) => void): () => void;
375
+ offGenerationChanged(listener: (generation: number) => void): void;
376
+ /**
377
+ * Subscribe to {@link CredentialDisabledEvent}s. Multiple subscribers are supported and
378
+ * each fires for every disable event; subscribers are invoked in registration order with
379
+ * exceptions and async rejections isolated per-listener so a misbehaving subscriber
380
+ * cannot break the disable path or starve the rest of the chain.
381
+ *
382
+ * If `credential_disabled` events were emitted while no listener was subscribed, they are
383
+ * replayed (in insertion order) to the listener that triggers the empty→non-empty
384
+ * transition. The drain is one-shot — listeners that subscribe after that no longer see
385
+ * past events.
386
+ *
387
+ * Returns an unsubscribe function. The function is idempotent: calling it more than once
388
+ * is a no-op. After every subscriber has unsubscribed, subsequent disable events buffer
389
+ * again until the next subscribe.
390
+ *
391
+ * @param listener Callback invoked with each disable event. May be sync or async.
392
+ * @returns A function that removes this listener from the subscriber set.
393
+ */
394
+ onCredentialDisabled(listener: (event: CredentialDisabledEvent) => void | Promise<void>): () => void;
395
+ /**
396
+ * Set a runtime API key override (not persisted to disk).
397
+ * Used for CLI --api-key flag.
398
+ */
399
+ setRuntimeApiKey(provider: string, apiKey: string): void;
400
+ /**
401
+ * Pin credential selection for a provider (not persisted to disk).
402
+ * Used for CLI --credential.
403
+ */
404
+ setRuntimeCredentialSelector(provider: string, selector: AuthCredentialSelector): void;
405
+ /**
406
+ * Remove a runtime credential selector.
407
+ */
408
+ removeRuntimeCredentialSelector(provider: string): void;
409
+ /**
410
+ * Remove a runtime API key override.
411
+ */
412
+ removeRuntimeApiKey(provider: string): void;
413
+ /** Whether a provider is currently authenticated by a runtime API-key override. */
414
+ hasRuntimeApiKey(provider: string): boolean;
415
+ /**
416
+ * Register a per-provider API key sourced from user configuration
417
+ * (e.g. `models.yml` `providers.<name>.apiKey`). Higher priority than
418
+ * stored credentials and OAuth tokens — when the user pins a key in
419
+ * config, that key is what authenticates outbound requests, regardless
420
+ * of whatever the broker happens to have loaded for that provider.
421
+ *
422
+ * Lower priority than {@link setRuntimeApiKey} so a CLI `--api-key`
423
+ * still wins for the duration of a single invocation.
424
+ */
425
+ setConfigApiKey(provider: string, apiKey: string): void;
426
+ /**
427
+ * Remove a single config-sourced API key override.
428
+ */
429
+ removeConfigApiKey(provider: string): void;
430
+ /**
431
+ * Drop every config-sourced API key. Called by `ModelRegistry` before
432
+ * re-parsing `models.yml` so removed entries actually disappear.
433
+ */
434
+ clearConfigApiKeys(): void;
435
+ /**
436
+ * Set a fallback resolver for API keys not found in storage or env vars.
437
+ * Used for custom provider keys from models.json.
438
+ */
439
+ setFallbackResolver(resolver: (provider: string) => string | undefined): void;
440
+ /**
441
+ * Reload credentials from storage.
442
+ */
443
+ reload(): Promise<void>;
444
+ /** Returns the credential type selected for a provider/session, if one has been recorded. */
445
+ getSessionCredentialType(provider: string, sessionId?: string): AuthCredential["type"] | undefined;
446
+ /**
447
+ * Get credential for a provider (first entry if multiple).
448
+ */
449
+ get(provider: string): AuthCredential | undefined;
450
+ /**
451
+ * Set credential for a provider.
452
+ */
453
+ set(provider: string, credential: AuthCredentialEntry): Promise<void>;
454
+ importCredentialIfAbsent(provider: string, credential: AuthCredential): Promise<AuthCredentialIfAbsentSnapshotResult>;
455
+ /**
456
+ * Remove credential for a provider.
457
+ */
458
+ remove(provider: string): Promise<void>;
459
+ /**
460
+ * List all providers with credentials.
461
+ */
462
+ list(): string[];
463
+ /**
464
+ * Check if credentials exist for a provider in storage.
465
+ */
466
+ has(provider: string): boolean;
467
+ /**
468
+ * Check if any form of auth is configured for a provider.
469
+ * Unlike getApiKey(), this doesn't refresh OAuth tokens.
470
+ */
471
+ hasAuth(provider: string): boolean;
472
+ /**
473
+ * Check if OAuth credentials are configured for a provider.
474
+ */
475
+ hasOAuth(provider: string): boolean;
476
+ /**
477
+ * Get OAuth credentials for a provider.
478
+ */
479
+ getOAuthCredential(provider: string): OAuthCredential | undefined;
480
+ /**
481
+ * Get the OAuth `accountId` for a provider, preferring the credential that is
482
+ * session-sticky for `sessionId` when multiple OAuth credentials are configured.
483
+ * Falls back to the first OAuth credential when no session preference exists (e.g.
484
+ * first call before any `getApiKey` has been issued, or single-credential setups).
485
+ * Returns `undefined` when no OAuth credential carries an `accountId`.
486
+ */
487
+ getOAuthAccountId(provider: string, sessionId?: string): string | undefined;
488
+ /**
489
+ * Get all credentials.
490
+ */
491
+ getAll(): AuthStorageData;
492
+ /**
493
+ * Login to an OAuth provider.
494
+ */
495
+ login(provider: OAuthProviderId, ctrl: OAuthController & {
496
+ /** onAuth is required by auth-storage but optional in OAuthController */
497
+ onAuth: (info: {
498
+ url: string;
499
+ instructions?: string;
500
+ }) => void;
501
+ /** onPrompt is required for some providers (github-copilot, OpenAI code provider) */
502
+ onPrompt: (prompt: {
503
+ message: string;
504
+ placeholder?: string;
505
+ }) => Promise<string>;
506
+ }): Promise<void>;
507
+ /**
508
+ * Logout from a provider.
509
+ */
510
+ logout(provider: string): Promise<void>;
511
+ fetchUsageReports(options?: {
512
+ baseUrlResolver?: (provider: Provider) => string | undefined;
513
+ /** Caller's cancel signal; only rejects this caller, never the shared upstream fetch. */
514
+ signal?: AbortSignal;
515
+ /** Disable provider/account/error logging for secret-safe control surfaces. */
516
+ logDetails?: boolean;
517
+ }): Promise<UsageReport[] | null>;
518
+ /**
519
+ * Probe each stored credential against its provider's auth-verifying usage
520
+ * endpoint and report per-credential auth health.
521
+ *
522
+ * Surfaces the identity of failing credentials so callers running a
523
+ * multi-account pool (e.g. a broker-backed auth-gateway) can tell which
524
+ * row is producing 401s. The probe mirrors the per-credential fan-out
525
+ * inside {@link AuthStorage.fetchUsageReports} (OAuth refresh-on-expiry,
526
+ * then `UsageProvider.fetchUsage`) but does NOT swallow errors — every
527
+ * credential gets either `ok: true`, `ok: false` with `reason`, or
528
+ * `ok: null` when no probe is configured for the provider.
529
+ *
530
+ * Iterates sequentially to avoid synchronized N-account fan-out that
531
+ * upstream `/usage` rate limiters (per source IP) treat as a burst.
532
+ *
533
+ * Only inspects active rows from {@link AuthCredentialStore.listAuthCredentials};
534
+ * soft-disabled rows are already known-bad and don't need a network probe.
535
+ * Environment-variable API keys are not enumerated — the caller's intent
536
+ * here is "which of my stored credentials is broken".
537
+ */
538
+ checkCredentials(options?: CheckCredentialsOptions): Promise<CredentialHealthResult[]>;
539
+ /**
540
+ * Marks the current session's credential as temporarily blocked due to usage limits.
541
+ * Uses usage reports to determine accurate reset time when available.
542
+ * Returns true if a credential was blocked, enabling automatic fallback to the next credential.
543
+ */
544
+ markUsageLimitReached(provider: string, sessionId: string | undefined, options?: {
545
+ retryAfterMs?: number;
546
+ baseUrl?: string;
547
+ signal?: AbortSignal;
548
+ }): Promise<boolean>;
549
+ /**
550
+ * Peek at API key for a provider without refreshing OAuth tokens.
551
+ * Used for model discovery where we only need to know if credentials exist
552
+ * and get a best-effort token. For GitHub Copilot we preserve enterprise
553
+ * routing metadata so discovery can hit the correct host.
554
+ */
555
+ peekApiKey(provider: string): Promise<string | undefined>;
556
+ /**
557
+ * Get API key for a provider.
558
+ * Priority:
559
+ * 1. Runtime override (CLI --api-key)
560
+ * 2. Config override (models.yml `providers.<name>.apiKey`)
561
+ * 3. API key from storage
562
+ * 4. OAuth token from storage (auto-refreshed)
563
+ * 5. Environment variable
564
+ * 6. Fallback resolver (models.yml custom providers, last-resort)
565
+ */
566
+ getApiKey(provider: string, sessionId?: string, options?: AuthApiKeyOptions): Promise<string | undefined>;
567
+ /**
568
+ * Resolve the OAuth credential for `provider`, refreshing through the same
569
+ * pipeline as {@link AuthStorage.getApiKey} but returning the refreshed
570
+ * {@link OAuthAccess} (raw access token + identity metadata) instead of
571
+ * the API-key bytes.
572
+ *
573
+ * Use this when the caller needs to inject identity headers alongside the
574
+ * bearer (OpenAI code backend `chatgpt-account-id`, Google `project`, GitHub
575
+ * `enterpriseUrl`). For pure "give me the bytes for `Authorization`"
576
+ * scenarios, prefer {@link AuthStorage.getApiKey}.
577
+ *
578
+ * Returns `undefined` when no OAuth credential is available, the
579
+ * credential fails to refresh, or runtime/config overrides have replaced
580
+ * OAuth with an explicit API key.
581
+ */
582
+ getOAuthAccess(provider: string, sessionId?: string, options?: AuthApiKeyOptions): Promise<OAuthAccess | undefined>;
583
+ invalidateCredentialMatching(provider: string, apiKey: string, options?: InvalidateCredentialMatchingOptions): Promise<boolean>;
584
+ invalidateCredentialMatching(provider: string, apiKey: string, signal?: AbortSignal): Promise<boolean>;
585
+ /**
586
+ * Build a redacted snapshot of all loaded credentials for the auth-broker
587
+ * wire. OAuth refresh tokens are replaced with {@link REMOTE_REFRESH_SENTINEL}
588
+ * so clients never see the actual refresh token.
589
+ *
590
+ * Callers must {@link AuthStorage.reload} first when serving a stale snapshot
591
+ * (the broker server's HTTP handler does this).
592
+ */
593
+ exportSnapshot(): AuthCredentialSnapshot;
594
+ /**
595
+ * Refresh the OAuth credential with the given id through a per-credential
596
+ * single-flight. Concurrent callers for the same row await the same upstream
597
+ * refresh attempt, which is required for providers that rotate refresh tokens
598
+ * on every successful refresh.
599
+ */
600
+ refreshCredentialById(id: number, signal?: AbortSignal): Promise<AuthCredentialSnapshotEntry>;
601
+ /**
602
+ * Force-refresh the OAuth credential with the given id, bypassing the
603
+ * not-yet-expired guard. Used by the auth-broker server to honour
604
+ * `POST /v1/credential/:id/refresh`.
605
+ *
606
+ * Returns the redacted snapshot entry for the refreshed row.
607
+ * Throws when no OAuth credential with that id is loaded.
608
+ */
609
+ forceRefreshCredentialById(id: number, signal?: AbortSignal): Promise<AuthCredentialSnapshotEntry>;
610
+ /**
611
+ * Disable the credential with the given id and emit a
612
+ * {@link CredentialDisabledEvent}. Used by the auth-broker server to honour
613
+ * `POST /v1/credential/:id/disable`. Returns `false` when no such row exists.
614
+ */
615
+ disableCredentialById(id: number, disabledCause: string): boolean;
616
+ /**
617
+ * Upsert a credential into the underlying store, refresh the in-memory
618
+ * snapshot, and return the redacted snapshot entries for the provider.
619
+ *
620
+ * Used by the auth-broker server to honour `POST /v1/credential`. The
621
+ * persistence layer (`SqliteAuthCredentialStore.upsertAuthCredentialForProvider`)
622
+ * does identity-key matching, so re-uploading the same email/account replaces
623
+ * the existing row instead of inserting a duplicate.
624
+ */
625
+ upsertCredential(provider: string, credential: AuthCredential): AuthCredentialSnapshotEntry[];
626
+ /**
627
+ * Describe where the active credential for a provider came from.
628
+ *
629
+ * Surfaces four layers, highest precedence first:
630
+ * 1. Runtime override (`--api-key`).
631
+ * 2. Config override (`models.yml` `providers.<name>.apiKey`).
632
+ * 3. Stored credential (the one this session is currently sticky to, or the
633
+ * one round-robin would pick next when no session id is supplied).
634
+ * 4. Env var / fallback resolver — when no stored credential exists.
635
+ *
636
+ * The string is purely informational; consumers must not parse it.
637
+ */
638
+ describeCredentialSource(provider: string, sessionId?: string): string | undefined;
639
+ }
640
+ /**
641
+ * Default SQLite-backed implementation of {@link AuthCredentialStore}.
642
+ *
643
+ * Used by the pi-ai CLI and as the default store for `AuthStorage.create()`.
644
+ * Also exposes convenience methods (`saveOAuth`, `getOAuth`, `saveApiKey`,
645
+ * `getApiKey`, `listProviders`, `deleteProvider`) that callers can use directly
646
+ * without going through `AuthStorage`.
647
+ */
648
+ export declare class SqliteAuthCredentialStore implements AuthCredentialStore {
649
+ #private;
650
+ constructor(db: Database);
651
+ static open(dbPath?: string): Promise<SqliteAuthCredentialStore>;
652
+ listAuthCredentials(provider?: string): StoredAuthCredential[];
653
+ replaceAuthCredentialsForProvider(provider: string, credentials: AuthCredential[]): StoredAuthCredential[];
654
+ upsertAuthCredentialForProvider(provider: string, credential: AuthCredential): StoredAuthCredential[];
655
+ upsertAuthCredentialForProviderIfAbsent(provider: string, credential: AuthCredential): AuthCredentialIfAbsentResult;
656
+ updateAuthCredential(id: number, credential: AuthCredential): void;
657
+ deleteAuthCredential(id: number, disabledCause: string): void;
658
+ /**
659
+ * CAS-style disable: only soft-deletes the row when its `data` column still
660
+ * matches `expectedData` and the row has not already been disabled. Used by
661
+ * the OAuth refresh-failure path to avoid clobbering a peer that rotated the
662
+ * row between our pre-check and the disable.
663
+ */
664
+ tryDisableAuthCredentialIfMatches(id: number, expectedData: string, disabledCause: string): boolean;
665
+ deleteAuthCredentialsForProvider(provider: string, disabledCause: string): void;
666
+ getCache(key: string, options?: {
667
+ includeExpired?: boolean;
668
+ }): string | null;
669
+ setCache(key: string, value: string, expiresAtSec: number): void;
670
+ deleteCachePrefix(prefix: string): void;
671
+ cleanExpiredCache(): void;
672
+ /**
673
+ * Save OAuth credentials for a provider.
674
+ * Preserves unrelated identities and replaces only the matching credential.
675
+ */
676
+ saveOAuth(provider: string, credentials: OAuthCredentials): void;
677
+ /**
678
+ * Get OAuth credentials for a provider.
679
+ */
680
+ getOAuth(provider: string): OAuthCredentials | null;
681
+ /**
682
+ * Save API key for a provider (replaces existing).
683
+ */
684
+ saveApiKey(provider: string, apiKey: string): void;
685
+ /**
686
+ * Get API key for a provider.
687
+ */
688
+ getApiKey(provider: string): string | null;
689
+ /**
690
+ * List all providers with credentials.
691
+ */
692
+ listProviders(): string[];
693
+ /**
694
+ * Delete all credentials for a provider.
695
+ */
696
+ deleteProvider(provider: string): void;
697
+ close(): void;
698
+ }
699
+ export {};