@sayknow-cli/ai 0.3.5 → 0.3.6

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