@vib-rato/ai 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (525) hide show
  1. package/CHANGELOG.md +3354 -0
  2. package/README.md +1194 -0
  3. package/dist/types/adapter-internals/provider-safety-stop.d.ts +45 -0
  4. package/dist/types/api-registry.d.ts +30 -0
  5. package/dist/types/auth-broker/client.d.ts +80 -0
  6. package/dist/types/auth-broker/index.d.ts +5 -0
  7. package/dist/types/auth-broker/redact.d.ts +7 -0
  8. package/dist/types/auth-broker/refresher.d.ts +25 -0
  9. package/dist/types/auth-broker/remote-store.d.ts +153 -0
  10. package/dist/types/auth-broker/server.d.ts +32 -0
  11. package/dist/types/auth-broker/types.d.ts +132 -0
  12. package/dist/types/auth-broker/wire-schemas.d.ts +555 -0
  13. package/dist/types/auth-gateway/http.d.ts +40 -0
  14. package/dist/types/auth-gateway/index.d.ts +3 -0
  15. package/dist/types/auth-gateway/server.d.ts +70 -0
  16. package/dist/types/auth-gateway/types.d.ts +129 -0
  17. package/dist/types/auth-storage.d.ts +1074 -0
  18. package/dist/types/cli.d.ts +2 -0
  19. package/dist/types/codex-tools.d.ts +4 -0
  20. package/dist/types/context-cap-policy.d.ts +68 -0
  21. package/dist/types/core.d.ts +35 -0
  22. package/dist/types/index.d.ts +55 -0
  23. package/dist/types/model-cache.d.ts +24 -0
  24. package/dist/types/model-manager.d.ts +77 -0
  25. package/dist/types/model-pricing.d.ts +3 -0
  26. package/dist/types/model-retirements.d.ts +6 -0
  27. package/dist/types/model-thinking.d.ts +100 -0
  28. package/dist/types/models.d.ts +21 -0
  29. package/dist/types/openai-completions-compat.d.ts +34 -0
  30. package/dist/types/provider-details.d.ts +24 -0
  31. package/dist/types/provider-models/bundled-references.d.ts +4 -0
  32. package/dist/types/provider-models/descriptors.d.ts +48 -0
  33. package/dist/types/provider-models/google.d.ts +20 -0
  34. package/dist/types/provider-models/index.d.ts +5 -0
  35. package/dist/types/provider-models/ollama.d.ts +7 -0
  36. package/dist/types/provider-models/openai-compat.d.ts +293 -0
  37. package/dist/types/provider-models/special.d.ts +29 -0
  38. package/dist/types/providers/amazon-bedrock.d.ts +60 -0
  39. package/dist/types/providers/anthropic-messages-server-schema.d.ts +450 -0
  40. package/dist/types/providers/anthropic-messages-server.d.ts +17 -0
  41. package/dist/types/providers/anthropic.d.ts +280 -0
  42. package/dist/types/providers/aws-credential-config.d.ts +19 -0
  43. package/dist/types/providers/aws-credentials.d.ts +43 -0
  44. package/dist/types/providers/aws-eventstream.d.ts +38 -0
  45. package/dist/types/providers/aws-sigv4.d.ts +55 -0
  46. package/dist/types/providers/azure-openai-responses.d.ts +22 -0
  47. package/dist/types/providers/composer-discipline.d.ts +32 -0
  48. package/dist/types/providers/cursor/client-version.d.ts +10 -0
  49. package/dist/types/providers/cursor/exec-modern.d.ts +98 -0
  50. package/dist/types/providers/cursor/gen/agent_pb.d.ts +16769 -0
  51. package/dist/types/providers/cursor-pi-args.d.ts +119 -0
  52. package/dist/types/providers/cursor.d.ts +72 -0
  53. package/dist/types/providers/dashscope-token-plan-headers.d.ts +57 -0
  54. package/dist/types/providers/error-message.d.ts +27 -0
  55. package/dist/types/providers/github-copilot-headers.d.ts +40 -0
  56. package/dist/types/providers/gitlab-duo.d.ts +27 -0
  57. package/dist/types/providers/google-auth.d.ts +26 -0
  58. package/dist/types/providers/google-gemini-cli.d.ts +75 -0
  59. package/dist/types/providers/google-gemini-headers.d.ts +43 -0
  60. package/dist/types/providers/google-shared.d.ts +183 -0
  61. package/dist/types/providers/google-types.d.ts +138 -0
  62. package/dist/types/providers/google-vertex.d.ts +11 -0
  63. package/dist/types/providers/google.d.ts +4 -0
  64. package/dist/types/providers/grammar.d.ts +1 -0
  65. package/dist/types/providers/kimi.d.ts +27 -0
  66. package/dist/types/providers/kiro-api-key.d.ts +50 -0
  67. package/dist/types/providers/kiro-codewhisperer.d.ts +11 -0
  68. package/dist/types/providers/mock.d.ts +189 -0
  69. package/dist/types/providers/ollama.d.ts +41 -0
  70. package/dist/types/providers/openai-anthropic-shim.d.ts +31 -0
  71. package/dist/types/providers/openai-bounded-rate-limits.d.ts +3 -0
  72. package/dist/types/providers/openai-chat-server-schema.d.ts +1733 -0
  73. package/dist/types/providers/openai-chat-server.d.ts +16 -0
  74. package/dist/types/providers/openai-codex/constants.d.ts +26 -0
  75. package/dist/types/providers/openai-codex/request-transformer.d.ts +50 -0
  76. package/dist/types/providers/openai-codex/response-handler.d.ts +18 -0
  77. package/dist/types/providers/openai-codex-responses.d.ts +71 -0
  78. package/dist/types/providers/openai-completions-compat.d.ts +6 -0
  79. package/dist/types/providers/openai-completions.d.ts +35 -0
  80. package/dist/types/providers/openai-opencodex-responses.d.ts +10 -0
  81. package/dist/types/providers/openai-request-transform.d.ts +4 -0
  82. package/dist/types/providers/openai-responses-server-schema.d.ts +392 -0
  83. package/dist/types/providers/openai-responses-server.d.ts +17 -0
  84. package/dist/types/providers/openai-responses-shared.d.ts +106 -0
  85. package/dist/types/providers/openai-responses.d.ts +37 -0
  86. package/dist/types/providers/pi-native-client.d.ts +29 -0
  87. package/dist/types/providers/pi-native-server.d.ts +60 -0
  88. package/dist/types/providers/register-builtins.d.ts +59 -0
  89. package/dist/types/providers/synthetic.d.ts +26 -0
  90. package/dist/types/providers/transform-messages.d.ts +33 -0
  91. package/dist/types/providers/vision-guard.d.ts +8 -0
  92. package/dist/types/rate-limit-utils.d.ts +19 -0
  93. package/dist/types/stream.d.ts +45 -0
  94. package/dist/types/types.d.ts +1073 -0
  95. package/dist/types/usage/claude.d.ts +3 -0
  96. package/dist/types/usage/gemini.d.ts +2 -0
  97. package/dist/types/usage/github-copilot.d.ts +7 -0
  98. package/dist/types/usage/google-antigravity.d.ts +2 -0
  99. package/dist/types/usage/grok-cli.d.ts +17 -0
  100. package/dist/types/usage/kimi.d.ts +4 -0
  101. package/dist/types/usage/minimax-code.d.ts +2 -0
  102. package/dist/types/usage/openai-codex.d.ts +3 -0
  103. package/dist/types/usage/shared.d.ts +1 -0
  104. package/dist/types/usage/zai.d.ts +2 -0
  105. package/dist/types/usage.d.ts +264 -0
  106. package/dist/types/utils/abort.d.ts +19 -0
  107. package/dist/types/utils/anthropic-auth.d.ts +39 -0
  108. package/dist/types/utils/block-symbols.d.ts +6 -0
  109. package/dist/types/utils/discovery/antigravity.d.ts +67 -0
  110. package/dist/types/utils/discovery/codex.d.ts +38 -0
  111. package/dist/types/utils/discovery/cursor.d.ts +49 -0
  112. package/dist/types/utils/discovery/gemini.d.ts +25 -0
  113. package/dist/types/utils/discovery/index.d.ts +4 -0
  114. package/dist/types/utils/discovery/openai-compatible.d.ts +81 -0
  115. package/dist/types/utils/event-stream.d.ts +41 -0
  116. package/dist/types/utils/fallback-transport.d.ts +110 -0
  117. package/dist/types/utils/fireworks-model-id.d.ts +10 -0
  118. package/dist/types/utils/foundry.d.ts +11 -0
  119. package/dist/types/utils/h2-fetch.d.ts +22 -0
  120. package/dist/types/utils/http-inspector.d.ts +59 -0
  121. package/dist/types/utils/idle-iterator.d.ts +122 -0
  122. package/dist/types/utils/json-parse.d.ts +98 -0
  123. package/dist/types/utils/oauth/alibaba-token-plan.d.ts +19 -0
  124. package/dist/types/utils/oauth/anthropic.d.ts +41 -0
  125. package/dist/types/utils/oauth/api-key-login.d.ts +38 -0
  126. package/dist/types/utils/oauth/api-key-validation.d.ts +39 -0
  127. package/dist/types/utils/oauth/bizrouter.d.ts +1 -0
  128. package/dist/types/utils/oauth/callback-server.d.ts +80 -0
  129. package/dist/types/utils/oauth/cerebras.d.ts +1 -0
  130. package/dist/types/utils/oauth/cloudflare-ai-gateway.d.ts +18 -0
  131. package/dist/types/utils/oauth/commandcode.d.ts +1 -0
  132. package/dist/types/utils/oauth/cursor.d.ts +15 -0
  133. package/dist/types/utils/oauth/deepinfra.d.ts +1 -0
  134. package/dist/types/utils/oauth/deepseek.d.ts +10 -0
  135. package/dist/types/utils/oauth/firepass.d.ts +1 -0
  136. package/dist/types/utils/oauth/fireworks.d.ts +1 -0
  137. package/dist/types/utils/oauth/fugu.d.ts +1 -0
  138. package/dist/types/utils/oauth/github-copilot.d.ts +38 -0
  139. package/dist/types/utils/oauth/gitlab-duo.d.ts +3 -0
  140. package/dist/types/utils/oauth/glm-zcode.d.ts +71 -0
  141. package/dist/types/utils/oauth/google-antigravity.d.ts +11 -0
  142. package/dist/types/utils/oauth/google-gemini-cli.d.ts +10 -0
  143. package/dist/types/utils/oauth/google-oauth-shared.d.ts +28 -0
  144. package/dist/types/utils/oauth/huggingface.d.ts +19 -0
  145. package/dist/types/utils/oauth/index.d.ts +39 -0
  146. package/dist/types/utils/oauth/kagi.d.ts +17 -0
  147. package/dist/types/utils/oauth/kilo.d.ts +5 -0
  148. package/dist/types/utils/oauth/kimi.d.ts +17 -0
  149. package/dist/types/utils/oauth/kiro.d.ts +71 -0
  150. package/dist/types/utils/oauth/litellm.d.ts +18 -0
  151. package/dist/types/utils/oauth/lm-studio.d.ts +17 -0
  152. package/dist/types/utils/oauth/mara.d.ts +1 -0
  153. package/dist/types/utils/oauth/minimax-code.d.ts +28 -0
  154. package/dist/types/utils/oauth/moonshot.d.ts +1 -0
  155. package/dist/types/utils/oauth/nanogpt.d.ts +1 -0
  156. package/dist/types/utils/oauth/nvidia.d.ts +18 -0
  157. package/dist/types/utils/oauth/ollama-cloud.d.ts +2 -0
  158. package/dist/types/utils/oauth/ollama.d.ts +18 -0
  159. package/dist/types/utils/oauth/openai-codex.d.ts +21 -0
  160. package/dist/types/utils/oauth/opencode.d.ts +18 -0
  161. package/dist/types/utils/oauth/opengateway.d.ts +1 -0
  162. package/dist/types/utils/oauth/openrouter.d.ts +1 -0
  163. package/dist/types/utils/oauth/parallel.d.ts +17 -0
  164. package/dist/types/utils/oauth/perplexity.d.ts +4 -0
  165. package/dist/types/utils/oauth/pkce.d.ts +8 -0
  166. package/dist/types/utils/oauth/qianfan.d.ts +17 -0
  167. package/dist/types/utils/oauth/qwen-portal.d.ts +19 -0
  168. package/dist/types/utils/oauth/sglang.d.ts +16 -0
  169. package/dist/types/utils/oauth/synthetic.d.ts +1 -0
  170. package/dist/types/utils/oauth/tavily.d.ts +17 -0
  171. package/dist/types/utils/oauth/together.d.ts +1 -0
  172. package/dist/types/utils/oauth/types.d.ts +56 -0
  173. package/dist/types/utils/oauth/venice.d.ts +18 -0
  174. package/dist/types/utils/oauth/vercel-ai-gateway.d.ts +18 -0
  175. package/dist/types/utils/oauth/vllm.d.ts +16 -0
  176. package/dist/types/utils/oauth/xai.d.ts +30 -0
  177. package/dist/types/utils/oauth/xiaomi.d.ts +25 -0
  178. package/dist/types/utils/oauth/zai.d.ts +18 -0
  179. package/dist/types/utils/oauth/zenmux.d.ts +1 -0
  180. package/dist/types/utils/overflow.d.ts +14 -0
  181. package/dist/types/utils/parse-bind.d.ts +26 -0
  182. package/dist/types/utils/provider-response.d.ts +6 -0
  183. package/dist/types/utils/provider-safety-stop.d.ts +8 -0
  184. package/dist/types/utils/proxy.d.ts +7 -0
  185. package/dist/types/utils/retry-after.d.ts +3 -0
  186. package/dist/types/utils/retry-budget.d.ts +1 -0
  187. package/dist/types/utils/retry.d.ts +29 -0
  188. package/dist/types/utils/schema/adapt.d.ts +24 -0
  189. package/dist/types/utils/schema/compatibility.d.ts +30 -0
  190. package/dist/types/utils/schema/dereference.d.ts +11 -0
  191. package/dist/types/utils/schema/draft.d.ts +10 -0
  192. package/dist/types/utils/schema/equality.d.ts +4 -0
  193. package/dist/types/utils/schema/fields.d.ts +49 -0
  194. package/dist/types/utils/schema/index.d.ts +14 -0
  195. package/dist/types/utils/schema/json-schema-validator.d.ts +12 -0
  196. package/dist/types/utils/schema/meta-validator.d.ts +2 -0
  197. package/dist/types/utils/schema/normalize.d.ts +93 -0
  198. package/dist/types/utils/schema/root-combinator.d.ts +12 -0
  199. package/dist/types/utils/schema/spill.d.ts +8 -0
  200. package/dist/types/utils/schema/stamps.d.ts +25 -0
  201. package/dist/types/utils/schema/types.d.ts +4 -0
  202. package/dist/types/utils/schema/wire.d.ts +54 -0
  203. package/dist/types/utils/schema/zod-decontaminate.d.ts +31 -0
  204. package/dist/types/utils/sse-debug.d.ts +10 -0
  205. package/dist/types/utils/tool-call-healing.d.ts +80 -0
  206. package/dist/types/utils/tool-choice-capability.d.ts +57 -0
  207. package/dist/types/utils/tool-choice.d.ts +50 -0
  208. package/dist/types/utils/validation.d.ts +17 -0
  209. package/dist/types/utils.d.ts +117 -0
  210. package/package.json +152 -0
  211. package/src/adapter-internals/provider-safety-stop.d.ts +45 -0
  212. package/src/adapter-internals/provider-safety-stop.ts +156 -0
  213. package/src/api-registry.d.ts +30 -0
  214. package/src/api-registry.ts +96 -0
  215. package/src/auth-broker/client.ts +444 -0
  216. package/src/auth-broker/index.ts +5 -0
  217. package/src/auth-broker/redact.ts +39 -0
  218. package/src/auth-broker/refresher.ts +130 -0
  219. package/src/auth-broker/remote-store.ts +1576 -0
  220. package/src/auth-broker/server.ts +764 -0
  221. package/src/auth-broker/types.ts +164 -0
  222. package/src/auth-broker/wire-schemas.ts +261 -0
  223. package/src/auth-gateway/http.ts +198 -0
  224. package/src/auth-gateway/index.ts +3 -0
  225. package/src/auth-gateway/server.ts +1315 -0
  226. package/src/auth-gateway/types.ts +160 -0
  227. package/src/auth-storage.ts +7312 -0
  228. package/src/cli.ts +269 -0
  229. package/src/codex-tools.d.ts +4 -0
  230. package/src/codex-tools.ts +24 -0
  231. package/src/context-cap-policy.d.ts +68 -0
  232. package/src/context-cap-policy.ts +123 -0
  233. package/src/core.ts +44 -0
  234. package/src/index.ts +61 -0
  235. package/src/model-cache.ts +236 -0
  236. package/src/model-manager.ts +744 -0
  237. package/src/model-pricing.d.ts +3 -0
  238. package/src/model-pricing.ts +68 -0
  239. package/src/model-retirements.d.ts +6 -0
  240. package/src/model-retirements.ts +19 -0
  241. package/src/model-thinking.d.ts +100 -0
  242. package/src/model-thinking.ts +1054 -0
  243. package/src/models.d.ts +21 -0
  244. package/src/models.json +94672 -0
  245. package/src/models.json.d.ts +9 -0
  246. package/src/models.ts +126 -0
  247. package/src/openai-completions-compat.d.ts +34 -0
  248. package/src/openai-completions-compat.ts +383 -0
  249. package/src/prompts/composer-bash-policy-recovery.md +1 -0
  250. package/src/prompts/cursor-composer-bash-policy-recovery.md +1 -0
  251. package/src/prompts/cursor-composer-edit-discipline.md +7 -0
  252. package/src/prompts/turn-aborted-guidance.md +4 -0
  253. package/src/provider-details.ts +90 -0
  254. package/src/provider-models/bundled-references.ts +38 -0
  255. package/src/provider-models/descriptors.ts +392 -0
  256. package/src/provider-models/google.ts +92 -0
  257. package/src/provider-models/index.ts +5 -0
  258. package/src/provider-models/ollama.ts +159 -0
  259. package/src/provider-models/openai-compat.ts +2920 -0
  260. package/src/provider-models/special.ts +185 -0
  261. package/src/providers/amazon-bedrock.d.ts +60 -0
  262. package/src/providers/amazon-bedrock.ts +939 -0
  263. package/src/providers/anthropic-messages-server-schema.ts +229 -0
  264. package/src/providers/anthropic-messages-server.ts +839 -0
  265. package/src/providers/anthropic.d.ts +280 -0
  266. package/src/providers/anthropic.ts +4421 -0
  267. package/src/providers/aws-credential-config.d.ts +19 -0
  268. package/src/providers/aws-credential-config.ts +179 -0
  269. package/src/providers/aws-credentials.d.ts +43 -0
  270. package/src/providers/aws-credentials.ts +457 -0
  271. package/src/providers/aws-eventstream.d.ts +38 -0
  272. package/src/providers/aws-eventstream.ts +185 -0
  273. package/src/providers/aws-sigv4.d.ts +55 -0
  274. package/src/providers/aws-sigv4.ts +218 -0
  275. package/src/providers/azure-openai-responses.d.ts +22 -0
  276. package/src/providers/azure-openai-responses.ts +447 -0
  277. package/src/providers/composer-discipline.d.ts +32 -0
  278. package/src/providers/composer-discipline.ts +95 -0
  279. package/src/providers/cursor/client-version.d.ts +10 -0
  280. package/src/providers/cursor/client-version.ts +10 -0
  281. package/src/providers/cursor/exec-modern.d.ts +98 -0
  282. package/src/providers/cursor/exec-modern.ts +497 -0
  283. package/src/providers/cursor/gen/agent_pb.d.ts +16769 -0
  284. package/src/providers/cursor/gen/agent_pb.ts +19780 -0
  285. package/src/providers/cursor/proto/agent.proto +4533 -0
  286. package/src/providers/cursor/proto/buf.gen.yaml +6 -0
  287. package/src/providers/cursor/proto/buf.yaml +17 -0
  288. package/src/providers/cursor-pi-args.d.ts +119 -0
  289. package/src/providers/cursor-pi-args.ts +187 -0
  290. package/src/providers/cursor.d.ts +72 -0
  291. package/src/providers/cursor.ts +3396 -0
  292. package/src/providers/dashscope-token-plan-headers.d.ts +57 -0
  293. package/src/providers/dashscope-token-plan-headers.ts +84 -0
  294. package/src/providers/error-message.d.ts +27 -0
  295. package/src/providers/error-message.ts +21 -0
  296. package/src/providers/github-copilot-headers.d.ts +40 -0
  297. package/src/providers/github-copilot-headers.ts +140 -0
  298. package/src/providers/gitlab-duo.d.ts +27 -0
  299. package/src/providers/gitlab-duo.ts +393 -0
  300. package/src/providers/google-auth.d.ts +26 -0
  301. package/src/providers/google-auth.ts +262 -0
  302. package/src/providers/google-gemini-cli.d.ts +75 -0
  303. package/src/providers/google-gemini-cli.ts +969 -0
  304. package/src/providers/google-gemini-headers.d.ts +43 -0
  305. package/src/providers/google-gemini-headers.ts +100 -0
  306. package/src/providers/google-shared.d.ts +183 -0
  307. package/src/providers/google-shared.ts +1105 -0
  308. package/src/providers/google-types.d.ts +138 -0
  309. package/src/providers/google-types.ts +167 -0
  310. package/src/providers/google-vertex.d.ts +11 -0
  311. package/src/providers/google-vertex.ts +124 -0
  312. package/src/providers/google.d.ts +4 -0
  313. package/src/providers/google.ts +41 -0
  314. package/src/providers/grammar.d.ts +1 -0
  315. package/src/providers/grammar.ts +70 -0
  316. package/src/providers/kimi.d.ts +27 -0
  317. package/src/providers/kimi.ts +52 -0
  318. package/src/providers/kiro-api-key.d.ts +50 -0
  319. package/src/providers/kiro-api-key.ts +786 -0
  320. package/src/providers/kiro-codewhisperer.d.ts +11 -0
  321. package/src/providers/kiro-codewhisperer.ts +600 -0
  322. package/src/providers/mock.ts +526 -0
  323. package/src/providers/ollama.d.ts +41 -0
  324. package/src/providers/ollama.ts +645 -0
  325. package/src/providers/openai-anthropic-shim.d.ts +31 -0
  326. package/src/providers/openai-anthropic-shim.ts +156 -0
  327. package/src/providers/openai-bounded-rate-limits.d.ts +3 -0
  328. package/src/providers/openai-bounded-rate-limits.ts +57 -0
  329. package/src/providers/openai-chat-server-schema.ts +254 -0
  330. package/src/providers/openai-chat-server.ts +724 -0
  331. package/src/providers/openai-codex/constants.d.ts +26 -0
  332. package/src/providers/openai-codex/constants.ts +43 -0
  333. package/src/providers/openai-codex/request-transformer.d.ts +50 -0
  334. package/src/providers/openai-codex/request-transformer.ts +219 -0
  335. package/src/providers/openai-codex/response-handler.d.ts +18 -0
  336. package/src/providers/openai-codex/response-handler.ts +111 -0
  337. package/src/providers/openai-codex-responses.d.ts +71 -0
  338. package/src/providers/openai-codex-responses.ts +3288 -0
  339. package/src/providers/openai-completions-compat.d.ts +6 -0
  340. package/src/providers/openai-completions-compat.ts +6 -0
  341. package/src/providers/openai-completions.d.ts +35 -0
  342. package/src/providers/openai-completions.ts +2294 -0
  343. package/src/providers/openai-opencodex-responses.ts +174 -0
  344. package/src/providers/openai-request-transform.d.ts +4 -0
  345. package/src/providers/openai-request-transform.ts +136 -0
  346. package/src/providers/openai-responses-server-schema.ts +290 -0
  347. package/src/providers/openai-responses-server.ts +1268 -0
  348. package/src/providers/openai-responses-shared.d.ts +106 -0
  349. package/src/providers/openai-responses-shared.ts +1253 -0
  350. package/src/providers/openai-responses.d.ts +37 -0
  351. package/src/providers/openai-responses.ts +989 -0
  352. package/src/providers/pi-native-client.d.ts +29 -0
  353. package/src/providers/pi-native-client.ts +243 -0
  354. package/src/providers/pi-native-server.ts +488 -0
  355. package/src/providers/register-builtins.d.ts +59 -0
  356. package/src/providers/register-builtins.ts +544 -0
  357. package/src/providers/synthetic.d.ts +26 -0
  358. package/src/providers/synthetic.ts +50 -0
  359. package/src/providers/transform-messages.d.ts +33 -0
  360. package/src/providers/transform-messages.ts +408 -0
  361. package/src/providers/vision-guard.d.ts +8 -0
  362. package/src/providers/vision-guard.ts +31 -0
  363. package/src/rate-limit-utils.d.ts +19 -0
  364. package/src/rate-limit-utils.ts +102 -0
  365. package/src/stream.d.ts +45 -0
  366. package/src/stream.ts +1306 -0
  367. package/src/types.d.ts +1073 -0
  368. package/src/types.ts +1305 -0
  369. package/src/usage/claude.ts +449 -0
  370. package/src/usage/gemini.ts +250 -0
  371. package/src/usage/github-copilot.ts +421 -0
  372. package/src/usage/google-antigravity.ts +201 -0
  373. package/src/usage/grok-cli.ts +259 -0
  374. package/src/usage/kimi.ts +285 -0
  375. package/src/usage/minimax-code.ts +31 -0
  376. package/src/usage/openai-codex.ts +503 -0
  377. package/src/usage/shared.ts +10 -0
  378. package/src/usage/zai.ts +247 -0
  379. package/src/usage.ts +190 -0
  380. package/src/utils/abort.d.ts +19 -0
  381. package/src/utils/abort.ts +51 -0
  382. package/src/utils/anthropic-auth.ts +95 -0
  383. package/src/utils/block-symbols.d.ts +6 -0
  384. package/src/utils/block-symbols.ts +11 -0
  385. package/src/utils/discovery/antigravity.ts +275 -0
  386. package/src/utils/discovery/codex.ts +362 -0
  387. package/src/utils/discovery/cursor.ts +388 -0
  388. package/src/utils/discovery/gemini.ts +248 -0
  389. package/src/utils/discovery/index.ts +4 -0
  390. package/src/utils/discovery/openai-compatible.ts +379 -0
  391. package/src/utils/event-stream.d.ts +41 -0
  392. package/src/utils/event-stream.ts +269 -0
  393. package/src/utils/fallback-transport.d.ts +110 -0
  394. package/src/utils/fallback-transport.ts +411 -0
  395. package/src/utils/fireworks-model-id.d.ts +10 -0
  396. package/src/utils/fireworks-model-id.ts +30 -0
  397. package/src/utils/foundry.d.ts +11 -0
  398. package/src/utils/foundry.ts +18 -0
  399. package/src/utils/h2-fetch.ts +60 -0
  400. package/src/utils/http-inspector.d.ts +59 -0
  401. package/src/utils/http-inspector.ts +380 -0
  402. package/src/utils/idle-iterator.d.ts +122 -0
  403. package/src/utils/idle-iterator.ts +410 -0
  404. package/src/utils/json-parse.d.ts +98 -0
  405. package/src/utils/json-parse.ts +607 -0
  406. package/src/utils/oauth/alibaba-token-plan.ts +60 -0
  407. package/src/utils/oauth/anthropic.ts +233 -0
  408. package/src/utils/oauth/api-key-login.ts +98 -0
  409. package/src/utils/oauth/api-key-validation.ts +344 -0
  410. package/src/utils/oauth/bizrouter.ts +15 -0
  411. package/src/utils/oauth/callback-server.d.ts +80 -0
  412. package/src/utils/oauth/callback-server.ts +359 -0
  413. package/src/utils/oauth/cerebras.ts +16 -0
  414. package/src/utils/oauth/cloudflare-ai-gateway.ts +48 -0
  415. package/src/utils/oauth/commandcode.ts +17 -0
  416. package/src/utils/oauth/cursor.ts +157 -0
  417. package/src/utils/oauth/deepinfra.ts +15 -0
  418. package/src/utils/oauth/deepseek.ts +53 -0
  419. package/src/utils/oauth/firepass.ts +24 -0
  420. package/src/utils/oauth/fireworks.ts +15 -0
  421. package/src/utils/oauth/fugu.ts +15 -0
  422. package/src/utils/oauth/github-copilot.d.ts +38 -0
  423. package/src/utils/oauth/github-copilot.ts +362 -0
  424. package/src/utils/oauth/gitlab-duo.ts +123 -0
  425. package/src/utils/oauth/glm-zcode.d.ts +71 -0
  426. package/src/utils/oauth/glm-zcode.ts +433 -0
  427. package/src/utils/oauth/google-antigravity.ts +200 -0
  428. package/src/utils/oauth/google-gemini-cli.ts +256 -0
  429. package/src/utils/oauth/google-oauth-shared.ts +110 -0
  430. package/src/utils/oauth/huggingface.ts +62 -0
  431. package/src/utils/oauth/index.ts +558 -0
  432. package/src/utils/oauth/kagi.ts +47 -0
  433. package/src/utils/oauth/kilo.ts +87 -0
  434. package/src/utils/oauth/kimi.d.ts +17 -0
  435. package/src/utils/oauth/kimi.ts +275 -0
  436. package/src/utils/oauth/kiro.ts +448 -0
  437. package/src/utils/oauth/litellm.ts +47 -0
  438. package/src/utils/oauth/lm-studio.ts +38 -0
  439. package/src/utils/oauth/mara.ts +16 -0
  440. package/src/utils/oauth/minimax-code.ts +78 -0
  441. package/src/utils/oauth/moonshot.ts +16 -0
  442. package/src/utils/oauth/nanogpt.ts +15 -0
  443. package/src/utils/oauth/nvidia.ts +70 -0
  444. package/src/utils/oauth/oauth.html +199 -0
  445. package/src/utils/oauth/ollama-cloud.ts +28 -0
  446. package/src/utils/oauth/ollama.ts +47 -0
  447. package/src/utils/oauth/openai-codex.ts +299 -0
  448. package/src/utils/oauth/opencode.ts +49 -0
  449. package/src/utils/oauth/opengateway.ts +15 -0
  450. package/src/utils/oauth/openrouter.ts +16 -0
  451. package/src/utils/oauth/parallel.ts +46 -0
  452. package/src/utils/oauth/perplexity.ts +225 -0
  453. package/src/utils/oauth/pkce.ts +18 -0
  454. package/src/utils/oauth/qianfan.ts +58 -0
  455. package/src/utils/oauth/qwen-portal.ts +60 -0
  456. package/src/utils/oauth/sglang.ts +42 -0
  457. package/src/utils/oauth/synthetic.ts +15 -0
  458. package/src/utils/oauth/tavily.ts +46 -0
  459. package/src/utils/oauth/together.ts +16 -0
  460. package/src/utils/oauth/types.d.ts +56 -0
  461. package/src/utils/oauth/types.ts +122 -0
  462. package/src/utils/oauth/venice.ts +59 -0
  463. package/src/utils/oauth/vercel-ai-gateway.ts +47 -0
  464. package/src/utils/oauth/vllm.ts +42 -0
  465. package/src/utils/oauth/xai.ts +246 -0
  466. package/src/utils/oauth/xiaomi.ts +199 -0
  467. package/src/utils/oauth/zai.ts +60 -0
  468. package/src/utils/oauth/zenmux.ts +15 -0
  469. package/src/utils/overflow.ts +275 -0
  470. package/src/utils/parse-bind.ts +81 -0
  471. package/src/utils/provider-response.d.ts +6 -0
  472. package/src/utils/provider-response.ts +30 -0
  473. package/src/utils/provider-safety-stop.ts +8 -0
  474. package/src/utils/proxy.d.ts +7 -0
  475. package/src/utils/proxy.ts +652 -0
  476. package/src/utils/retry-after.d.ts +3 -0
  477. package/src/utils/retry-after.ts +110 -0
  478. package/src/utils/retry-budget.d.ts +1 -0
  479. package/src/utils/retry-budget.ts +4 -0
  480. package/src/utils/retry.d.ts +29 -0
  481. package/src/utils/retry.ts +67 -0
  482. package/src/utils/schema/CONSTRAINTS.md +164 -0
  483. package/src/utils/schema/adapt.d.ts +24 -0
  484. package/src/utils/schema/adapt.ts +36 -0
  485. package/src/utils/schema/compatibility.d.ts +30 -0
  486. package/src/utils/schema/compatibility.ts +435 -0
  487. package/src/utils/schema/dereference.d.ts +11 -0
  488. package/src/utils/schema/dereference.ts +98 -0
  489. package/src/utils/schema/draft.d.ts +10 -0
  490. package/src/utils/schema/draft.ts +341 -0
  491. package/src/utils/schema/equality.d.ts +4 -0
  492. package/src/utils/schema/equality.ts +97 -0
  493. package/src/utils/schema/fields.d.ts +49 -0
  494. package/src/utils/schema/fields.ts +190 -0
  495. package/src/utils/schema/index.d.ts +14 -0
  496. package/src/utils/schema/index.ts +14 -0
  497. package/src/utils/schema/json-schema-validator.d.ts +12 -0
  498. package/src/utils/schema/json-schema-validator.ts +577 -0
  499. package/src/utils/schema/meta-validator.d.ts +2 -0
  500. package/src/utils/schema/meta-validator.ts +167 -0
  501. package/src/utils/schema/normalize.d.ts +93 -0
  502. package/src/utils/schema/normalize.ts +1588 -0
  503. package/src/utils/schema/root-combinator.d.ts +12 -0
  504. package/src/utils/schema/root-combinator.ts +143 -0
  505. package/src/utils/schema/spill.d.ts +8 -0
  506. package/src/utils/schema/spill.ts +43 -0
  507. package/src/utils/schema/stamps.d.ts +25 -0
  508. package/src/utils/schema/stamps.ts +97 -0
  509. package/src/utils/schema/types.d.ts +4 -0
  510. package/src/utils/schema/types.ts +11 -0
  511. package/src/utils/schema/wire.d.ts +54 -0
  512. package/src/utils/schema/wire.ts +213 -0
  513. package/src/utils/schema/zod-decontaminate.d.ts +31 -0
  514. package/src/utils/schema/zod-decontaminate.ts +331 -0
  515. package/src/utils/sse-debug.d.ts +10 -0
  516. package/src/utils/sse-debug.ts +289 -0
  517. package/src/utils/tool-call-healing.d.ts +80 -0
  518. package/src/utils/tool-call-healing.ts +298 -0
  519. package/src/utils/tool-choice-capability.d.ts +57 -0
  520. package/src/utils/tool-choice-capability.ts +633 -0
  521. package/src/utils/tool-choice.d.ts +50 -0
  522. package/src/utils/tool-choice.ts +99 -0
  523. package/src/utils/validation.ts +1080 -0
  524. package/src/utils.d.ts +117 -0
  525. package/src/utils.ts +523 -0
@@ -0,0 +1,1074 @@
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, OAuthLoginOptions, OAuthProviderId } from "./utils/oauth/types";
14
+ export type ApiKeyCredential = {
15
+ type: "api_key";
16
+ key: string;
17
+ };
18
+ /**
19
+ * Extracts the bearer token from the structured API-key form used by OAuth
20
+ * providers that need to carry token metadata alongside the access token.
21
+ */
22
+ export declare function extractStructuredApiKeyToken(apiKey: string): string | undefined;
23
+ export interface MCPOAuthBinding {
24
+ /** Exact HTTP(S) origin of the MCP resource endpoint. */
25
+ resourceOrigin: string;
26
+ /** Exact canonical HTTP(S) token endpoint used to create and refresh the credential. */
27
+ tokenEndpoint: string;
28
+ }
29
+ export declare function resolveMCPOAuthResourceOrigin(value: string): string | undefined;
30
+ export declare function resolveMCPOAuthTokenEndpoint(value: string): string | undefined;
31
+ export declare function isCanonicalMCPOAuthBinding(binding: MCPOAuthBinding): boolean;
32
+ export declare function assertCanonicalMCPOAuthBinding(binding: MCPOAuthBinding | undefined): asserts binding is MCPOAuthBinding;
33
+ export type OAuthCredential = {
34
+ type: "oauth";
35
+ /** Present only for credentials created by runtime MCP OAuth. */
36
+ mcpBinding?: MCPOAuthBinding;
37
+ } & OAuthCredentials;
38
+ export type AuthCredential = ApiKeyCredential | OAuthCredential;
39
+ export interface MCPOAuthRefreshClient {
40
+ clientId?: string;
41
+ clientSecret?: string;
42
+ }
43
+ export type AuthCredentialEntry = AuthCredential | AuthCredential[];
44
+ export type AuthStorageData = Record<string, AuthCredentialEntry>;
45
+ /**
46
+ * Serialized representation of AuthStorage for passing to subagent workers.
47
+ * Contains only the essential credential data, not runtime state.
48
+ */
49
+ export interface SerializedAuthStorage {
50
+ credentials: Record<string, Array<{
51
+ id: number;
52
+ type: "api_key" | "oauth";
53
+ data: Record<string, unknown>;
54
+ }>>;
55
+ runtimeOverrides?: Record<string, string>;
56
+ dbPath?: string;
57
+ }
58
+ /**
59
+ * Auth credential with database row ID for updates/deletes.
60
+ * Wraps AuthCredential with storage metadata.
61
+ */
62
+ export interface StoredAuthCredential {
63
+ id: number;
64
+ provider: string;
65
+ credential: AuthCredential;
66
+ disabledCause: string | null;
67
+ /** Monotonic local row revision used by optimistic hard-removal actions. */
68
+ revision?: number;
69
+ }
70
+ /**
71
+ * Payload-free inventory projection used by account-management and presentation
72
+ * surfaces. This deliberately has no credential/token fields; `listAuthCredentials`
73
+ * remains the active full-fidelity selection contract.
74
+ */
75
+ export interface CredentialInventoryRecord {
76
+ id: number;
77
+ provider: string;
78
+ credentialKind: "oauth" | "api_key";
79
+ identityLabel: string | null;
80
+ accountId?: string;
81
+ email?: string;
82
+ projectId?: string;
83
+ disabled: boolean;
84
+ disabledCause: string | null;
85
+ }
86
+ /** Safe usage observation supplied by a remote store's presentation cache. */
87
+ export interface CachedUsagePresentation {
88
+ credentialId: number;
89
+ provider: string;
90
+ inventoryGeneration: number;
91
+ identityDigest: string;
92
+ usage: SafeUsageReport;
93
+ fetchedAt: number;
94
+ freshUntil: number;
95
+ retainUntil: number;
96
+ }
97
+ /** Opaque local action target for an all-or-nothing OAuth hard removal. */
98
+ export interface CredentialRemovalTarget {
99
+ id: number;
100
+ provider: string;
101
+ expectedRevision: number;
102
+ }
103
+ export type AuthCredentialHardRemovalResult = {
104
+ kind: "removed";
105
+ ids: readonly number[];
106
+ } | {
107
+ kind: "conflict";
108
+ currentIds: readonly number[];
109
+ };
110
+ /** Usage report projection safe to cross a presentation boundary. */
111
+ export type SafeUsageReport = Omit<UsageReport, "raw">;
112
+ export type CachedUsageFreshness = "fresh" | "stale-last-good";
113
+ export interface CachedUsageReport {
114
+ report: SafeUsageReport;
115
+ fetchedAt: number;
116
+ freshUntil: number;
117
+ retainUntil: number;
118
+ freshness: CachedUsageFreshness;
119
+ }
120
+ export type CachedCredentialHealthStatus = "ok" | "failed" | "unverifiable" | "unknown";
121
+ export interface CachedCredentialHealth {
122
+ status: CachedCredentialHealthStatus;
123
+ reason: string | null;
124
+ checkedAt?: number;
125
+ retainUntil?: number;
126
+ }
127
+ /** Safe result from an explicit API-key probe whose key bytes are invocation-only. */
128
+ export interface ApiKeyCredentialCheckResult {
129
+ provider: string;
130
+ type: "api_key";
131
+ ok: boolean | null;
132
+ reason?: string;
133
+ report?: SafeUsageReport;
134
+ }
135
+ /** Typed failure raised when an OAuth-only selector cannot be applied. */
136
+ export type OAuthCredentialSelectorFailureReason = "api-key-row" | "api-key-provider" | "override-active" | "not-found" | "disabled" | "ambiguous" | "gateway-managed";
137
+ export declare class OAuthCredentialSelectorError extends Error {
138
+ readonly reason: OAuthCredentialSelectorFailureReason;
139
+ readonly provider: string;
140
+ readonly selector: AuthCredentialSelector;
141
+ readonly candidateIds: readonly number[];
142
+ constructor(reason: OAuthCredentialSelectorFailureReason, provider: string, selector: AuthCredentialSelector, message: string, candidateIds?: readonly number[]);
143
+ }
144
+ export interface OAuthPinTarget {
145
+ credentialId: number;
146
+ canonicalSelector: AuthCredentialSelector;
147
+ }
148
+ /**
149
+ * Per-credential health record returned by {@link AuthStorage.checkCredentials}.
150
+ *
151
+ * Use this to identify which credential in a multi-account pool is causing
152
+ * auth errors. `ok` is tri-state:
153
+ *
154
+ * - `true` — credential authenticated against the provider's auth-verifying
155
+ * probe (today: the usage endpoint). For OAuth this also exercises refresh
156
+ * when the access token was expired.
157
+ * - `false` — the probe rejected the credential (401/403/refresh failure/etc).
158
+ * `reason` carries the upstream error string.
159
+ * - `null` — no probe is configured for this provider (or the configured
160
+ * probe doesn't support this credential type). The credential's auth
161
+ * status is unverifiable from here.
162
+ */
163
+ export interface CredentialHealthResult {
164
+ /** Database row id (matches {@link StoredAuthCredential.id}). */
165
+ id: number;
166
+ provider: string;
167
+ type: AuthCredential["type"];
168
+ /** OAuth email if known on the stored credential or surfaced by the probe. */
169
+ email?: string;
170
+ /** OAuth account id / org id if known. */
171
+ accountId?: string;
172
+ /** `true` when the refresh token lives on a remote broker (sentinel was present). */
173
+ remoteRefresh?: true;
174
+ ok: boolean | null;
175
+ /** Failure / unverifiable reason; absent when `ok === true`. */
176
+ reason?: string;
177
+ report?: SafeUsageReport;
178
+ }
179
+ export interface CheckCredentialsOptions {
180
+ signal?: AbortSignal;
181
+ provider?: string;
182
+ /** Per-credential probe timeout (ms). Defaults to the configured usage request timeout. */
183
+ timeoutMs?: number;
184
+ /** Provider → base URL override, same shape as {@link AuthStorage.fetchUsageReports}. */
185
+ baseUrlResolver?: (provider: Provider) => string | undefined;
186
+ }
187
+ /** Options for the explicit, invocation-only API-key probe. */
188
+ export interface ApiKeyCredentialCheckOptions {
189
+ signal?: AbortSignal;
190
+ timeoutMs?: number;
191
+ baseUrl?: string;
192
+ }
193
+ /**
194
+ * Sentinel value placed in OAuth `refresh` fields when a credential is shared
195
+ * via {@link AuthStorage.exportSnapshot}. Refresh tokens never leave the broker;
196
+ * clients must call back to refresh.
197
+ */
198
+ export declare const REMOTE_REFRESH_SENTINEL: "__remote__";
199
+ export type RemoteRefreshSentinel = typeof REMOTE_REFRESH_SENTINEL;
200
+ /** OAuth credential with refresh token replaced by the broker sentinel. */
201
+ export type RemoteOAuthCredential = Omit<OAuthCredential, "refresh"> & {
202
+ refresh: RemoteRefreshSentinel;
203
+ };
204
+ /** Discriminated credential payload as published by the broker. */
205
+ export type SnapshotCredential = ApiKeyCredential | RemoteOAuthCredential;
206
+ export interface AuthCredentialSnapshotEntry {
207
+ id: number;
208
+ provider: string;
209
+ credential: SnapshotCredential;
210
+ identityKey: string | null;
211
+ revision?: number;
212
+ }
213
+ export type AuthCredentialIfAbsentReason = "inserted" | "updated-existing" | "skipped-existing" | "skipped-existing-runtime" | "skipped-existing-config" | "skipped-existing-env" | "skipped-existing-fallback" | "skipped-invalid";
214
+ export interface AuthCredentialIfAbsentResult {
215
+ inserted: boolean;
216
+ reason: AuthCredentialIfAbsentReason;
217
+ provider: string;
218
+ entries: StoredAuthCredential[];
219
+ }
220
+ export interface AuthCredentialIfAbsentSnapshotResult {
221
+ inserted: boolean;
222
+ reason: AuthCredentialIfAbsentReason;
223
+ provider: string;
224
+ entries: AuthCredentialSnapshotEntry[];
225
+ }
226
+ /**
227
+ * Wire-shaped snapshot exported by {@link AuthStorage.exportSnapshot} and
228
+ * served by the auth-broker server on `GET /v1/snapshot`.
229
+ */
230
+ export interface AuthCredentialSnapshot {
231
+ generation: number;
232
+ generatedAt: number;
233
+ credentials: AuthCredentialSnapshotEntry[];
234
+ }
235
+ /**
236
+ * Persistence abstraction consumed by {@link AuthStorage}.
237
+ *
238
+ * Concrete implementations:
239
+ * - {@link SqliteAuthCredentialStore} — local SQLite-backed store (default).
240
+ * - `RemoteAuthCredentialStore` from `./auth-broker` — client-side snapshot of
241
+ * a remote broker; mutating methods (`replace*`, `upsert*`, `delete*ForProvider`)
242
+ * throw because login flows route through the broker, not the client.
243
+ */
244
+ export type OAuthRefreshLease = {
245
+ credentialId: number;
246
+ owner: string;
247
+ tokenFingerprint: string;
248
+ };
249
+ export type OAuthRefreshLeaseClaim = {
250
+ kind: "claimed";
251
+ credential: OAuthCredential;
252
+ lease: OAuthRefreshLease;
253
+ } | {
254
+ kind: "adopted";
255
+ credential: OAuthCredential;
256
+ } | {
257
+ kind: "busy";
258
+ expiresAt: number;
259
+ } | {
260
+ kind: "missing";
261
+ };
262
+ /**
263
+ * Store-owned ticket that orders a provider admission against remote
264
+ * credential snapshot application. The ticket is intentionally released at
265
+ * provider admission, not response completion.
266
+ */
267
+ export interface CredentialDispatchTicket {
268
+ release(): void;
269
+ }
270
+ export interface AuthCredentialStore {
271
+ close(): void;
272
+ refreshSnapshot?(signal?: AbortSignal): Promise<unknown>;
273
+ onSnapshotChanged?(listener: () => void): () => void;
274
+ /** Order provider admission with remote snapshot authority application. */
275
+ acquireCredentialDispatchTicket?(provider: Provider, signal?: AbortSignal): Promise<CredentialDispatchTicket>;
276
+ listAuthCredentials(provider?: string): StoredAuthCredential[];
277
+ /** Payload-free account inventory; active and soft-disabled rows are included. */
278
+ listCredentialInventory?(provider?: string): CredentialInventoryRecord[];
279
+ /** Local opaque removal targets; remote stores may omit this capability. */
280
+ listCredentialRemovalTargets?(provider?: string): CredentialRemovalTarget[];
281
+ /** Transactional local hard removal; remote stores must reject this capability. */
282
+ removeAuthCredentialsHard?(provider: string, targets: readonly CredentialRemovalTarget[]): AuthCredentialHardRemovalResult;
283
+ updateAuthCredential(id: number, credential: AuthCredential): void;
284
+ deleteAuthCredential(id: number, disabledCause: string): void;
285
+ tryDisableAuthCredentialIfMatches(id: number, expectedData: string, disabledCause: string): boolean;
286
+ tryDisableAuthCredentialIfRevision?(id: number, expectedRevision: number, disabledCause: string): boolean;
287
+ replaceAuthCredentialsForProvider(provider: string, credentials: AuthCredential[]): StoredAuthCredential[];
288
+ upsertAuthCredentialForProvider(provider: string, credential: AuthCredential): StoredAuthCredential[];
289
+ upsertAuthCredentialForProviderIfAbsent(provider: string, credential: AuthCredential): AuthCredentialIfAbsentResult;
290
+ deleteAuthCredentialsForProvider(provider: string, disabledCause: string): void;
291
+ getCache(key: string, options?: {
292
+ includeExpired?: boolean;
293
+ }): string | null;
294
+ setCache(key: string, value: string, expiresAtSec: number): void;
295
+ /** Atomically allocate a durable sequence for broker restart epochs. */
296
+ allocateMonotonicSequence(key: string, expiresAtSec: number): number;
297
+ deleteCachePrefix?(prefix: string): void;
298
+ cleanExpiredCache(): void;
299
+ /**
300
+ * Optional store-supplied OAuth refresh. When present, `AuthStorage` uses
301
+ * it before the per-provider local refresh path. `RemoteAuthCredentialStore`
302
+ * implements this against the broker; SQLite stores leave it undefined.
303
+ *
304
+ * Precedence: `AuthStorageOptions.refreshOAuthCredential` > this hook > local.
305
+ *
306
+ * `signal` propagates the agent's cancel (ESC, request abort, …) all the
307
+ * way to the broker fetch so a hung connection can't strand the caller
308
+ * for `timeoutMs * (maxRetries + 1)`.
309
+ */
310
+ refreshOAuthCredential?(provider: Provider, credentialId: number, credential: OAuthCredential, signal?: AbortSignal): Promise<OAuthCredentials>;
311
+ /** Broker-backed MCP refresh using the broker's stored token endpoint and refresh secret. */
312
+ refreshMCPOAuthCredential?(credentialId: number, credential: OAuthCredential, client: MCPOAuthRefreshClient, signal?: AbortSignal): Promise<OAuthCredential>;
313
+ /**
314
+ * Atomically adopts a fresh row or claims the current refresh token for one
315
+ * local provider dial. SQLite-backed stores use this to prevent another
316
+ * process from replaying a rotating refresh token between a pre-read and
317
+ * the provider request.
318
+ */
319
+ claimOAuthRefreshLease?(credentialId: number, expectedRefresh: string, force: boolean, owner: string, nowMs: number, leaseMs: number): OAuthRefreshLeaseClaim;
320
+ /** Atomically persists a successful claimed refresh and releases its lease. */
321
+ completeOAuthRefreshLease?(lease: OAuthRefreshLease, credential: OAuthCredential): boolean;
322
+ /** Releases an uncompleted refresh lease owned by this process. */
323
+ releaseOAuthRefreshLease?(lease: OAuthRefreshLease): void;
324
+ /**
325
+ * Optional async pre-read hook invoked after AuthStorage selects a stored
326
+ * credential but before it returns that credential for an outbound request.
327
+ * Remote broker stores use this to wait out imminent rotations and refresh
328
+ * their local snapshot before the caller sees a stale access token.
329
+ */
330
+ prepareForRequest?(credentialId: number, opts?: {
331
+ signal?: AbortSignal;
332
+ }): Promise<boolean | undefined>;
333
+ /**
334
+ * Optional store-supplied aggregate usage fetch. When present, `AuthStorage`
335
+ * routes `fetchUsageReports()` here instead of fanning out per-credential.
336
+ * `RemoteAuthCredentialStore` proxies to the broker (whose datacenter IP
337
+ * isn't rate-limited like a heavy residential client).
338
+ *
339
+ * Precedence: `AuthStorageOptions.fetchUsageReports` > this hook > local fan-out.
340
+ *
341
+ * `signal` propagates the agent's cancel down to the broker fetch.
342
+ */
343
+ fetchUsageReports?(signal?: AbortSignal): Promise<UsageReport[] | null>;
344
+ fetchUsageReportsForProvider?(provider: Provider, signal?: AbortSignal): Promise<UsageReport[] | null>;
345
+ /** Synchronous, zero-network usage presentation peek. */
346
+ peekCachedUsagePresentation?(provider: Provider, credentialId: number): CachedUsagePresentation | undefined;
347
+ /** Record a safe usage observation after an explicit fetch/check. */
348
+ recordUsagePresentation?(observation: CachedUsagePresentation): void;
349
+ /** Read a safe, durable health observation for one credential row. */
350
+ peekCachedCredentialHealth?(provider: Provider, credentialId: number): CachedCredentialHealth | undefined;
351
+ /** Persist a safe health observation for one credential row. */
352
+ recordCredentialHealth?(provider: Provider, credentialId: number, health: CachedCredentialHealth): void;
353
+ /** Persist a safe usage observation without exposing credential payloads. */
354
+ recordCredentialUsage?(provider: Provider, credentialId: number, report: SafeUsageReport): void;
355
+ /**
356
+ * Optional readiness hook for stores that must hydrate payload-free metadata
357
+ * before one-shot inventory consumers read their first snapshot.
358
+ */
359
+ waitForReady?(): Promise<void>;
360
+ /**
361
+ * Optional store-supplied per-credential usage report lookup. When present,
362
+ * `AuthStorage` consults this before its own per-credential upstream fetch
363
+ * (`#getUsageReport`). `RemoteAuthCredentialStore` implements this against
364
+ * the broker's aggregate `/v1/usage` (one coalesced round-trip shared across
365
+ * all callers) so multi-credential ranking on the client never hits the
366
+ * upstream provider's rate-limited usage endpoint from the laptop IP.
367
+ *
368
+ * Returning `null` is authoritative — `AuthStorage` does NOT fall back to
369
+ * the local fetch path. The store hook owns the decision, since falling
370
+ * back would re-introduce the per-IP rate-limit problem the broker exists
371
+ * to avoid.
372
+ *
373
+ * `signal` propagates the agent's cancel down to the broker fetch.
374
+ */
375
+ getUsageReport?(provider: Provider, credential: OAuthCredential, signal?: AbortSignal): Promise<UsageReport | null>;
376
+ /**
377
+ * Optional store hook to invalidate a specific credential after the upstream
378
+ * provider returned 401 on a supposedly-fresh key. Remote stores force the
379
+ * broker to re-issue the row; local stores can leave it undefined and let
380
+ * {@link AuthStorage.invalidateCredentialMatching} fall back to `reload()`.
381
+ */
382
+ markCredentialSuspect?(credentialId: number, opts?: {
383
+ signal?: AbortSignal;
384
+ }): Promise<void>;
385
+ /**
386
+ * Optional async write hook to disable one credential through an authoritative
387
+ * remote store. Remote clients MUST use this hook instead of the synchronous
388
+ * local delete methods when an OAuth refresh fails definitively.
389
+ *
390
+ * Returns `false` when the row is already absent (for example, a peer
391
+ * disabled it first). Implementations MUST NOT treat a failed remote write as
392
+ * a successful local deletion.
393
+ */
394
+ disableAuthCredentialRemote?(credentialId: number, disabledCause: string, signal?: AbortSignal, expectedRevision?: number): Promise<boolean>;
395
+ /**
396
+ * Optional async write hook for upserting a single credential. When present,
397
+ * `AuthStorage.#upsertOAuthCredential` routes through this instead of the
398
+ * sync `upsertAuthCredentialForProvider`. `RemoteAuthCredentialStore` uses
399
+ * it to send the upsert to the broker via `POST /v1/credential`.
400
+ *
401
+ * Implementations MUST update the in-memory snapshot before returning so the
402
+ * post-write read path is consistent.
403
+ */
404
+ upsertAuthCredentialRemote?(provider: string, credential: AuthCredential): Promise<StoredAuthCredential[]>;
405
+ upsertAuthCredentialRemoteIfAbsent?(provider: string, credential: AuthCredential): Promise<AuthCredentialIfAbsentResult>;
406
+ /**
407
+ * Optional async write hook for replace-all semantics (e.g. API-key login
408
+ * overwriting any previous keys for the same provider). When present,
409
+ * `AuthStorage.set` routes through this instead of the sync
410
+ * `replaceAuthCredentialsForProvider`.
411
+ */
412
+ replaceAuthCredentialsRemote?(provider: string, credentials: AuthCredential[]): Promise<StoredAuthCredential[]>;
413
+ /**
414
+ * Optional async write hook for clearing every credential for a provider
415
+ * (logout or a provider-wide invalidation). Remote stores must perform this
416
+ * through their authoritative broker rather than mutating the client cache.
417
+ */
418
+ deleteAuthCredentialsRemote?(provider: string, disabledCause: string): Promise<void>;
419
+ }
420
+ /**
421
+ * Event payload describing a credential that was just soft-disabled.
422
+ *
423
+ * Today the only call site is OAuth refresh failures with a definitive cause
424
+ * (`invalid_grant`, `401/403` not from a network blip, etc.) — the
425
+ * disabled_cause string is the verbatim error captured for forensics.
426
+ *
427
+ * Subscribers can use this to surface a notification, banner, or auto-launch
428
+ * a re-login flow instead of letting the credential silently disappear.
429
+ */
430
+ export interface CredentialDisabledEvent {
431
+ provider: string;
432
+ disabledCause: string;
433
+ }
434
+ /**
435
+ * How {@link AuthStorage} orders multiple healthy OAuth credentials of the same
436
+ * provider:type pool when selecting one for a (new) session.
437
+ *
438
+ * - `balanced` (default): prefer the least-used / lowest-drain-rate account.
439
+ * Spreads load across accounts and keeps burst headroom on every account.
440
+ * - `earliest-reset`: prefer the non-blocked account whose usage window resets
441
+ * soonest (earliest-expiry-first). Tumbling-window quota is perishable —
442
+ * unused quota is lost at reset — so draining the soonest-to-reset account
443
+ * first minimizes wasted quota. Drain/used metrics remain tiebreakers.
444
+ *
445
+ * Only affects ranking, which the `shouldRank` guard already limits to session
446
+ * start (or when the session's preferred credential is blocked), so this never
447
+ * thrashes accounts mid-session / cold-starts the server-side prompt cache.
448
+ */
449
+ export type CredentialRankingMode = "balanced" | "earliest-reset";
450
+ export type AuthStorageOptions = {
451
+ usageProviderResolver?: (provider: Provider) => UsageProvider | undefined;
452
+ rankingStrategyResolver?: (provider: Provider) => CredentialRankingStrategy | undefined;
453
+ credentialRankingMode?: CredentialRankingMode;
454
+ usageFetch?: typeof fetch;
455
+ usageRequestTimeoutMs?: number;
456
+ usageLogger?: UsageLogger;
457
+ /**
458
+ * Resolve a config value (API key, header value, etc.) to an actual value.
459
+ * - coding-agent injects its resolveConfigValue (supports "!command" syntax via pi-natives)
460
+ * - Default: checks environment variable first, then treats as literal
461
+ * `cacheScope` changes whenever the provider credential configuration changes.
462
+ */
463
+ configValueResolver?: (config: string, cacheScope?: string) => Promise<string | undefined>;
464
+ /**
465
+ * Optional callback fired when AuthStorage automatically disables a
466
+ * credential because something detected it as no longer usable — today
467
+ * that's the OAuth refresh-failure path in `getApiKey`. NOT fired for
468
+ * user-initiated `remove()` (the user already knows) or dedup of
469
+ * duplicate credentials (uninteresting hygiene).
470
+ */
471
+ onCredentialDisabled?: (event: CredentialDisabledEvent) => void | Promise<void>;
472
+ /**
473
+ * Override OAuth refresh. When set, `AuthStorage` calls this instead of the
474
+ * per-provider local refresh function. Receives the credential id so the
475
+ * implementation can address remote credentials.
476
+ *
477
+ * Must return updated {@link OAuthCredentials} with at least `access` and
478
+ * `expires`. `refresh` may be an opaque sentinel (e.g. `"__remote__"`) when
479
+ * the actual refresh token never leaves the broker.
480
+ */
481
+ refreshOAuthCredential?: (provider: Provider, credentialId: number, credential: OAuthCredential, signal?: AbortSignal) => Promise<OAuthCredentials>;
482
+ /**
483
+ * Human-readable description of the credential store backing this
484
+ * AuthStorage instance. Surfaced through {@link AuthStorage.describeCredentialSource}
485
+ * so the TUI can show where a token came from (broker URL or local SQLite path).
486
+ *
487
+ * Examples:
488
+ * - `"local ~/.vib/agent/agent.db"`
489
+ * - `"broker http://can.internal:8765"`
490
+ */
491
+ sourceLabel?: string;
492
+ /**
493
+ * Override `fetchUsageReports`. When set, `AuthStorage.fetchUsageReports`
494
+ * calls this instead of fanning out per-credential. The primary use case is
495
+ * routing through a broker that egresses from a less-throttled IP — e.g. a
496
+ * residential laptop trips Anthropic's per-IP rate limit on the usage
497
+ * endpoint and drops 2-of-5 credentials, while the VPS broker gets all 5.
498
+ *
499
+ * Implementations may return null when no usage data is available; the
500
+ * AuthStorage caller surfaces that to its own consumer unchanged.
501
+ */
502
+ fetchUsageReports?: (signal?: AbortSignal) => Promise<UsageReport[] | null>;
503
+ fetchUsageReportsForProvider?: (provider: Provider, signal?: AbortSignal) => Promise<UsageReport[] | null>;
504
+ };
505
+ export type AuthApiKeyOptions = {
506
+ baseUrl?: string;
507
+ modelId?: string;
508
+ /** Select config registrations owned by one caller (for example a ModelRegistry). */
509
+ owner?: object;
510
+ /**
511
+ * Caller's cancel signal. Threaded into any broker-bound OAuth refresh so
512
+ * `ESC` / request abort actually kills a hung broker fetch instead of
513
+ * stranding the caller for `timeoutMs * (maxRetries + 1)`.
514
+ */
515
+ signal?: AbortSignal;
516
+ /** Pin selection to one stored credential instead of using round-robin/ranking. */
517
+ credentialSelector?: AuthCredentialSelector;
518
+ /** Prefer one stored OAuth credential while preserving quota-triggered fallback. */
519
+ preferredCredentialSelector?: AuthCredentialSelector;
520
+ };
521
+ export type AuthCredentialSelectorKind = "id" | "email" | "account" | "project";
522
+ export interface AuthCredentialSelector {
523
+ kind: AuthCredentialSelectorKind;
524
+ value: string;
525
+ }
526
+ /**
527
+ * Refreshed OAuth access plus identity metadata returned by
528
+ * {@link AuthStorage.getOAuthAccess}. Callers that authenticate via a bearer
529
+ * AND need the credential's identity (OpenAI code backend `chatgpt-account-id`, Google
530
+ * `projectId`, GitHub `enterpriseUrl`) consume this shape directly; the
531
+ * refresh slot is deliberately omitted because rotating refresh tokens never
532
+ * leave {@link AuthStorage}.
533
+ */
534
+ export interface OAuthAccess {
535
+ accessToken: string;
536
+ accountId?: string;
537
+ email?: string;
538
+ projectId?: string;
539
+ enterpriseUrl?: string;
540
+ }
541
+ export interface InvalidateCredentialMatchingOptions {
542
+ signal?: AbortSignal;
543
+ sessionId?: string;
544
+ owner?: object;
545
+ }
546
+ /** Read optional broker error detail without allowing hostile objects to escape classification. */
547
+ /** @internal Tested directly because hostile accessors must preserve the original error identity. */
548
+ export declare function readBrokerErrorBody(error: unknown): string | undefined;
549
+ /**
550
+ * Credential storage backed by an AuthCredentialStore.
551
+ * Reads from storage on reload(), manages round-robin credential selection,
552
+ * usage limit tracking, and OAuth token refresh.
553
+ */
554
+ export declare class AuthStorage {
555
+ #private;
556
+ constructor(store: AuthCredentialStore, options?: AuthStorageOptions);
557
+ /**
558
+ * Create an AuthStorage instance backed by a AuthCredentialStore.
559
+ * Convenience factory for standalone use (e.g., pi-ai CLI).
560
+ * @param dbPath - Path to SQLite database
561
+ */
562
+ static create(dbPath: string, options?: AuthStorageOptions): Promise<AuthStorage>;
563
+ /**
564
+ * Close the underlying credential store.
565
+ *
566
+ * After calling this, the instance must not be reused.
567
+ */
568
+ close(): void;
569
+ getGeneration(): number;
570
+ getCache(key: string, options?: {
571
+ includeExpired?: boolean;
572
+ }): string | null;
573
+ setCache(key: string, value: string, expiresAtSec: number): void;
574
+ allocateMonotonicSequence(key: string, expiresAtSec: number): number;
575
+ getProviderConfigurationGeneration(provider: string): number;
576
+ getProviderOAuthRefreshGeneration(provider: string): number;
577
+ getProviderEvidenceGeneration(provider: string, resolvedApiKey?: string, owner?: object): string;
578
+ onGenerationChanged(listener: (generation: number) => void): () => void;
579
+ offGenerationChanged(listener: (generation: number) => void): void;
580
+ /**
581
+ * Subscribe to {@link CredentialDisabledEvent}s. Multiple subscribers are supported and
582
+ * each fires for every disable event; subscribers are invoked in registration order with
583
+ * exceptions and async rejections isolated per-listener so a misbehaving subscriber
584
+ * cannot break the disable path or starve the rest of the chain.
585
+ *
586
+ * If `credential_disabled` events were emitted while no listener was subscribed, they are
587
+ * replayed (in insertion order) to the listener that triggers the empty→non-empty
588
+ * transition. The drain is one-shot — listeners that subscribe after that no longer see
589
+ * past events.
590
+ *
591
+ * Returns an unsubscribe function. The function is idempotent: calling it more than once
592
+ * is a no-op. After every subscriber has unsubscribed, subsequent disable events buffer
593
+ * again until the next subscribe.
594
+ *
595
+ * @param listener Callback invoked with each disable event. May be sync or async.
596
+ * @returns A function that removes this listener from the subscriber set.
597
+ */
598
+ onCredentialDisabled(listener: (event: CredentialDisabledEvent) => void | Promise<void>): () => void;
599
+ /**
600
+ * Set a runtime API key override (not persisted to disk).
601
+ * Used for CLI --api-key flag.
602
+ */
603
+ setRuntimeApiKey(provider: string, apiKey: string): void;
604
+ /**
605
+ * Pin credential selection for a provider (not persisted to disk).
606
+ * Used for CLI --credential.
607
+ */
608
+ setRuntimeCredentialSelector(provider: string, selector: AuthCredentialSelector): void;
609
+ /** Acquire a reference-counted credential scope for a session or shared subagent scope. */
610
+ acquireCredentialScope(scopeId: string): void;
611
+ /** Whether a credential scope already has at least one live owner. */
612
+ hasCredentialScopeLease(scopeId: string): boolean;
613
+ /** Release one credential-scope lease; final release clears only that scope's derived state. */
614
+ releaseCredentialScope(scopeId: string): void;
615
+ /**
616
+ * Set the selector derived from a durable session pin or a session seed.
617
+ * `owner` scopes config-override validation to one ModelRegistry; omitted
618
+ * owners retain process-wide caller semantics.
619
+ */
620
+ setSessionCredentialSelector(scopeId: string, provider: string, selector: AuthCredentialSelector, owner?: object): void;
621
+ /** Explicitly mask persistent/process-global selection and return the provider to AUTO for one scope. */
622
+ setSessionCredentialAuto(provider: string, scopeId: string): void;
623
+ /** Clear a scope's explicit selector and AUTO mask, restoring normal precedence. */
624
+ clearSessionCredentialSelector(provider: string, scopeId: string): void;
625
+ /** Whether the effective selection for a scope is explicitly pinned (AUTO masks are not pins). */
626
+ hasSessionCredentialSelector(provider: string, scopeId?: string): boolean;
627
+ /** Whether this scope explicitly masks provider pins and uses AUTO ranking. */
628
+ hasSessionCredentialAuto(provider: string, scopeId?: string): boolean;
629
+ /** Resolve the effective selector precedence for a provider/scope. */
630
+ resolveEffectiveCredentialSelector(provider: string, scopeId?: string, explicitSelector?: AuthCredentialSelector): AuthCredentialSelector | undefined;
631
+ /** @internal Return cache provenance for an exact stored literal API-key row without resolving its value. */
632
+ getStoredLiteralApiKeyEvidenceGeneration(provider: string, selector: AuthCredentialSelector, owner?: object): string | undefined;
633
+ /**
634
+ * Validate and canonicalize an OAuth-only selector for account pinning.
635
+ * `owner` scopes config-override checks to one ModelRegistry; omitted owners
636
+ * retain process-wide caller semantics.
637
+ */
638
+ resolveOAuthPinTarget(provider: string, selector: AuthCredentialSelector, owner?: object): OAuthPinTarget;
639
+ /** Return all local inventory rows, including soft-disabled metadata, without payloads. */
640
+ listCredentialInventory(provider?: string): CredentialInventoryRecord[];
641
+ /** Return local credential hard-removal action targets, including disabled rows. */
642
+ listCredentialRemovalTargets(provider?: string): CredentialRemovalTarget[];
643
+ /** Remove selected local credential rows atomically; conflict leaves all rows intact. */
644
+ removeAuthCredentialsHard(provider: string, targets: readonly CredentialRemovalTarget[]): AuthCredentialHardRemovalResult;
645
+ /**
646
+ * Remove a runtime credential selector.
647
+ */
648
+ removeRuntimeCredentialSelector(provider: string): void;
649
+ /** Whether a provider currently has a soft runtime credential preference. */
650
+ hasRuntimePreferredCredentialSelector(provider: string): boolean;
651
+ /** Resolve an unqualified preferred selector to the single active OAuth provider it matches. */
652
+ resolveRuntimePreferredCredentialSelectorProvider(selector: AuthCredentialSelector): string;
653
+ /**
654
+ * Prefer one stored OAuth credential for a provider while retaining quota
655
+ * fallback to the rest of the pool (not persisted to disk). Used for CLI
656
+ * `--prefer-credential`. Unlike {@link setRuntimeCredentialSelector}, a
657
+ * quota/rate-limit failure on the preferred row still rotates to another
658
+ * active credential instead of failing the session.
659
+ */
660
+ setRuntimePreferredCredentialSelector(provider: string, selector: AuthCredentialSelector): void;
661
+ /**
662
+ * Remove a runtime preferred credential selector.
663
+ */
664
+ removeRuntimePreferredCredentialSelector(provider: string): void;
665
+ /**
666
+ * Remove a runtime API key override.
667
+ */
668
+ removeRuntimeApiKey(provider: string): void;
669
+ /** Whether a provider is currently authenticated by a runtime API-key override. */
670
+ hasRuntimeApiKey(provider: string): boolean;
671
+ /** Whether a provider is currently authenticated by a config API-key override. */
672
+ hasConfigApiKey(provider: string, owner?: object): boolean;
673
+ /**
674
+ * Whether credential selection for a provider is pinned to one stored row by
675
+ * a runtime selector (`--credential`).
676
+ *
677
+ * Distinct from {@link AuthStorage.hasRuntimeApiKey}: that reports the
678
+ * `--api-key` override, which lives in a different map and is mutually
679
+ * exclusive with a selector. Callers that must not rotate away from a pinned
680
+ * credential have to consult BOTH.
681
+ */
682
+ hasRuntimeCredentialSelector(provider: string): boolean;
683
+ /** Whether the effective selector for a session scope is pinned. */
684
+ hasEffectiveCredentialSelector(provider: string, sessionId?: string): boolean;
685
+ /**
686
+ * Opaque stored row id of the credential this session is currently using.
687
+ *
688
+ * Deliberately non-identifying: the persisted primary key, never an email,
689
+ * account id, project id, or key material. Callers that need to correlate a
690
+ * credential across a session boundary use this instead of projecting
691
+ * personal metadata.
692
+ *
693
+ * Returns `undefined` when the session has not been routed to a stored
694
+ * credential yet, or when it authenticated through an env key or fallback
695
+ * resolver rather than a stored row.
696
+ */
697
+ getSessionCredentialRowId(provider: string, sessionId?: string): number | undefined;
698
+ /**
699
+ * Force a running session's OAuth credential for a provider to a specific
700
+ * stored row, independent of quota/rate-limit state. Used for a mid-session
701
+ * `/credential <selector>` switch that has nothing to do with exhaustion —
702
+ * the user just wants a different account for the rest of the session.
703
+ *
704
+ * This mutates ONLY the session-scoped sticky pointer
705
+ * ({@link AuthStorage.#recordSessionCredential}), never a provider-wide
706
+ * runtime override, so it cannot bleed into other sessions in the same
707
+ * process whose credential identity differs. The sticky pointer is keyed by
708
+ * `sessionId`, and subagents/team workers inherit their parent's
709
+ * `credentialSessionId` by design so they keep using the same account as
710
+ * the parent — a switch therefore applies to the whole session family
711
+ * sharing that identity, not to unrelated sessions.
712
+ *
713
+ * Fails closed rather than silently no-op when a stronger override already
714
+ * decides this provider's credential every call: a hard pin
715
+ * ({@link AuthStorage.setRuntimeCredentialSelector}, `--credential`), a
716
+ * runtime API-key override (`--api-key`), or a config-sourced API key
717
+ * (`models.yml` `apiKey`) would each re-decide the credential on the very
718
+ * next {@link AuthStorage.getApiKey} call and make this switch appear to
719
+ * silently do nothing. `owner` scopes the config-override check to one
720
+ * ModelRegistry; omitted owners retain process-wide caller semantics.
721
+ *
722
+ * Deliberately does not touch credential-blocked state: if the target row
723
+ * is still backoff-blocked from a prior quota failure, the existing
724
+ * `#resolveOAuthSelection` ranking safely ignores this sticky pointer and
725
+ * falls back to a usable account instead of re-issuing a request that would
726
+ * just draw another 429/quota error.
727
+ */
728
+ switchSessionCredential(provider: string, sessionId: string, selector: AuthCredentialSelector, owner?: object): void;
729
+ /**
730
+ * Register a per-provider API key sourced from user configuration
731
+ * (e.g. `models.yml` `providers.<name>.apiKey`). Higher priority than
732
+ * stored credentials and OAuth tokens — when the user pins a key in
733
+ * config, that key is what authenticates outbound requests, regardless
734
+ * of whatever the broker happens to have loaded for that provider.
735
+ *
736
+ * Lower priority than {@link setRuntimeApiKey} so a CLI `--api-key`
737
+ * still wins for the duration of a single invocation.
738
+ *
739
+ * `options.owner` scopes the override to one registry or other caller. The
740
+ * unscoped form is process-wide and is retained for standalone callers.
741
+ *
742
+ * `options.envSourced` marks the value as resolved from a models.yml
743
+ * `apiKeyEnv` indirection. Unlike a literal pin, an env pointer only says
744
+ * where to look for a key; when the user has since run `auth login`, the
745
+ * stored api_key credential is the fresher, actively-managed secret and
746
+ * wins over the indirection (stored OAuth credentials still yield, so a
747
+ * custom-endpoint bearer is never replaced by an upstream OAuth token).
748
+ */
749
+ setConfigApiKey(provider: string, apiKey: string, options?: {
750
+ envSourced?: boolean;
751
+ owner?: object;
752
+ }): void;
753
+ /**
754
+ * Remove a single config-sourced API key override.
755
+ */
756
+ removeConfigApiKey(provider: string, owner?: object): void;
757
+ /**
758
+ * Drop config-sourced API keys. An owner removes only its own registrations;
759
+ * the unscoped form remains an explicit global reset for callers that own the
760
+ * entire AuthStorage instance.
761
+ */
762
+ clearConfigApiKeys(owner?: object): void;
763
+ /**
764
+ * Set a fallback resolver for API keys not found in storage or env vars.
765
+ * Used for custom provider keys from models.json.
766
+ */
767
+ setFallbackResolver(resolver: (provider: string) => string | undefined, owner?: object): () => void;
768
+ /**
769
+ * Reload credentials from storage.
770
+ */
771
+ reload(): Promise<void>;
772
+ /**
773
+ * Acquire a store-owned provider-admission ticket when the backing store
774
+ * provides one (for example, a remote broker snapshot store). Local stores
775
+ * need no additional ordering and return `undefined`.
776
+ */
777
+ acquireCredentialDispatchTicket(provider: Provider, signal?: AbortSignal): Promise<CredentialDispatchTicket | undefined>;
778
+ /** Returns the credential type selected for a provider/session, if one has been recorded. */
779
+ getSessionCredentialType(provider: string, sessionId?: string): AuthCredential["type"] | undefined;
780
+ /**
781
+ * Get credential for a provider (first entry if multiple).
782
+ */
783
+ get(provider: string): AuthCredential | undefined;
784
+ /**
785
+ * Set credential for a provider.
786
+ */
787
+ set(provider: string, credential: AuthCredentialEntry): Promise<void>;
788
+ importCredentialIfAbsent(provider: string, credential: AuthCredential, owner?: object): Promise<AuthCredentialIfAbsentSnapshotResult>;
789
+ /**
790
+ * Remove credential for a provider.
791
+ */
792
+ remove(provider: string): Promise<void>;
793
+ /**
794
+ * List all providers with credentials.
795
+ */
796
+ list(): string[];
797
+ /**
798
+ * Check if credentials exist for a provider in storage.
799
+ */
800
+ has(provider: string): boolean;
801
+ disableCredentialByIdIfRevision(id: number, expectedRevision: number, disabledCause: string): boolean;
802
+ hasAuth(provider: string, sessionId?: string, options?: Pick<AuthApiKeyOptions, "owner">): boolean;
803
+ /**
804
+ * Credential type that a provider/session will dispatch first without performing I/O.
805
+ * Mirrors getApiKey selector validation, overrides, session OAuth stickiness,
806
+ * cached command-key usability, OAuth retry, and environment fallback order.
807
+ */
808
+ getEffectiveCredentialType(provider: string, sessionId?: string, options?: Pick<AuthApiKeyOptions, "owner">): AuthCredential["type"] | undefined;
809
+ /**
810
+ * Check whether configured auth is currently usable without resolving credentials.
811
+ */
812
+ hasUsableAuth(provider: string, options?: Pick<AuthApiKeyOptions, "owner">): boolean;
813
+ /**
814
+ * Check if OAuth credentials are configured for a provider.
815
+ */
816
+ hasOAuth(provider: string): boolean;
817
+ /**
818
+ * Get OAuth credentials for a provider.
819
+ */
820
+ getOAuthCredential(provider: string, sessionId?: string, options?: Pick<AuthApiKeyOptions, "owner">): OAuthCredential | undefined;
821
+ /**
822
+ * Get the OAuth `accountId` for a provider, preferring the credential that is
823
+ * session-sticky for `sessionId` when multiple OAuth credentials are configured.
824
+ * Falls back to the first OAuth credential when no session preference exists (e.g.
825
+ * first call before any `getApiKey` has been issued, or single-credential setups).
826
+ * Returns `undefined` when no OAuth credential carries an `accountId`.
827
+ */
828
+ getOAuthAccountId(provider: string, sessionId?: string, options?: Pick<AuthApiKeyOptions, "owner">): string | undefined;
829
+ /**
830
+ * Get all credentials.
831
+ */
832
+ getAll(): AuthStorageData;
833
+ /**
834
+ * Login to an OAuth provider.
835
+ */
836
+ login(provider: OAuthProviderId, ctrl: OAuthController & {
837
+ /** onAuth is required by auth-storage but optional in OAuthController */
838
+ onAuth: (info: {
839
+ url: string;
840
+ instructions?: string;
841
+ }) => void;
842
+ /** onPrompt is required for some providers (github-copilot, OpenAI code provider) */
843
+ onPrompt: (prompt: {
844
+ message: string;
845
+ placeholder?: string;
846
+ }) => Promise<string>;
847
+ }, options?: OAuthLoginOptions): Promise<void>;
848
+ /**
849
+ * Logout from a provider.
850
+ */
851
+ logout(provider: string): Promise<void>;
852
+ fetchUsageReports(options?: {
853
+ provider?: Provider;
854
+ baseUrlResolver?: (provider: Provider) => string | undefined;
855
+ /** Caller's cancel signal; only rejects this caller, never the shared upstream fetch. */
856
+ signal?: AbortSignal;
857
+ /** Disable provider/account/error logging for secret-safe control surfaces. */
858
+ logDetails?: boolean;
859
+ }): Promise<UsageReport[] | null>;
860
+ /**
861
+ * Probe each stored credential against its provider's auth-verifying usage
862
+ * endpoint and report per-credential auth health.
863
+ *
864
+ * Surfaces the identity of failing credentials so callers running a
865
+ * multi-account pool (e.g. a broker-backed auth-gateway) can tell which
866
+ * row is producing 401s. The probe mirrors the per-credential fan-out
867
+ * inside {@link AuthStorage.fetchUsageReports} (OAuth refresh-on-expiry,
868
+ * then `UsageProvider.fetchUsage`) but does NOT swallow errors — every
869
+ * credential gets either `ok: true`, `ok: false` with `reason`, or
870
+ * `ok: null` when no probe is configured for the provider.
871
+ *
872
+ * Iterates sequentially to avoid synchronized N-account fan-out that
873
+ * upstream `/usage` rate limiters (per source IP) treat as a burst.
874
+ *
875
+ * Only inspects active rows from {@link AuthCredentialStore.listAuthCredentials};
876
+ * soft-disabled rows are already known-bad and don't need a network probe.
877
+ * Environment-variable API keys are not enumerated — the caller's intent
878
+ * here is "which of my stored credentials is broken".
879
+ */
880
+ /** Return a safe cache-only usage observation. */
881
+ getCachedUsageReport(provider: Provider, credentialId: number, baseUrl?: string): CachedUsageReport | undefined;
882
+ /** Cache-only health observation; unknown means no retained explicit check. */
883
+ getCachedCredentialHealth(credentialId: number): CachedCredentialHealth;
884
+ peekCachedCredentialHealthForSource(provider: string, source: "env" | "config" | "runtime"): CachedCredentialHealth;
885
+ recordCredentialHealthForSource(provider: string, source: "env" | "config" | "runtime", health: CachedCredentialHealth): void;
886
+ /** Explicit API-key probe; key bytes are not retained in the returned result. */
887
+ checkApiKeyCredential(provider: Provider, apiKey: string, options?: ApiKeyCredentialCheckOptions): Promise<ApiKeyCredentialCheckResult>;
888
+ checkCredentials(options?: CheckCredentialsOptions): Promise<CredentialHealthResult[]>;
889
+ /**
890
+ * Marks the current session's credential as temporarily blocked due to usage limits.
891
+ * Uses usage reports to determine accurate reset time when available.
892
+ * Returns true if a credential was blocked, enabling automatic fallback to the next credential.
893
+ */
894
+ markUsageLimitReached(provider: string, sessionId: string | undefined, options?: {
895
+ retryAfterMs?: number;
896
+ baseUrl?: string;
897
+ signal?: AbortSignal;
898
+ owner?: object;
899
+ }): Promise<boolean>;
900
+ /**
901
+ * Earliest instant at which any currently blocked stored credential for this
902
+ * provider becomes usable again. Undefined when nothing is blocked.
903
+ * When `sessionId` is provided, only the session's active credential type is
904
+ * considered — API-key and OAuth backoff pools are independent.
905
+ * Informational only: callers must not treat this as authorization to wait.
906
+ */
907
+ getEarliestUnblockAt(provider: string, sessionId?: string): number | undefined;
908
+ /**
909
+ * Peek at API key for a provider without refreshing OAuth tokens.
910
+ * Used for model discovery where we only need to know if credentials exist
911
+ * and get a best-effort token. For GitHub Copilot we preserve enterprise
912
+ * routing metadata so discovery can hit the correct host.
913
+ */
914
+ peekApiKey(provider: string, options?: Pick<AuthApiKeyOptions, "owner">): Promise<string | undefined>;
915
+ /**
916
+ * Get API key for a provider.
917
+ * Priority:
918
+ * 1. Runtime override (CLI --api-key)
919
+ * 2. Config override (models.yml `providers.<name>.apiKey` literal pin)
920
+ * 3. Stored api_key credential from `auth login`, when the config override
921
+ * is only an `apiKeyEnv` indirection
922
+ * 4. Config override sourced from models.yml `providers.<name>.apiKeyEnv`
923
+ * 5. Session-selected OAuth credential, when present
924
+ * 6. Usable or unresolved API key from storage
925
+ * 7. OAuth token from storage (auto-refreshed)
926
+ * 8. Previously unusable command-backed API key retry
927
+ * 9. Environment variable
928
+ * 10. Fallback resolver (models.yml custom providers, last-resort)
929
+ */
930
+ getApiKey(provider: string, sessionId?: string, options?: AuthApiKeyOptions): Promise<string | undefined>;
931
+ /**
932
+ * Resolve the OAuth credential for `provider`, refreshing through the same
933
+ * pipeline as {@link AuthStorage.getApiKey} but returning the refreshed
934
+ * {@link OAuthAccess} (raw access token + identity metadata) instead of
935
+ * the API-key bytes.
936
+ *
937
+ * Use this when the caller needs to inject identity headers alongside the
938
+ * bearer (OpenAI code backend `chatgpt-account-id`, Google `project`, GitHub
939
+ * `enterpriseUrl`). For pure "give me the bytes for `Authorization`"
940
+ * scenarios, prefer {@link AuthStorage.getApiKey}.
941
+ *
942
+ * Returns `undefined` when no OAuth credential is available, the
943
+ * credential fails to refresh, or runtime/config overrides have replaced
944
+ * OAuth with an explicit API key.
945
+ */
946
+ getOAuthAccess(provider: string, sessionId?: string, options?: AuthApiKeyOptions): Promise<OAuthAccess | undefined>;
947
+ invalidateCredentialMatching(provider: string, apiKey: string, options?: InvalidateCredentialMatchingOptions): Promise<boolean>;
948
+ invalidateCredentialMatching(provider: string, apiKey: string, signal?: AbortSignal): Promise<boolean>;
949
+ /**
950
+ * Build a redacted snapshot of all loaded credentials for the auth-broker
951
+ * wire. OAuth refresh tokens are replaced with {@link REMOTE_REFRESH_SENTINEL}
952
+ * so clients never see the actual refresh token.
953
+ *
954
+ * Callers must {@link AuthStorage.reload} first when serving a stale snapshot
955
+ * (the broker server's HTTP handler does this).
956
+ */
957
+ exportSnapshot(): AuthCredentialSnapshot;
958
+ /**
959
+ * Refresh the OAuth credential with the given id through a per-credential
960
+ * single-flight. Concurrent callers for the same row await the same upstream
961
+ * refresh attempt, which is required for providers that rotate refresh tokens
962
+ * on every successful refresh.
963
+ */
964
+ refreshCredentialById(id: number, signal?: AbortSignal, mcpClient?: MCPOAuthRefreshClient): Promise<AuthCredentialSnapshotEntry>;
965
+ /**
966
+ * Force-refresh the OAuth credential with the given id, bypassing the
967
+ * not-yet-expired guard. Used by the auth-broker server to honour
968
+ * `POST /v1/credential/:id/refresh`.
969
+ *
970
+ * Returns the redacted snapshot entry for the refreshed row.
971
+ * Throws when no OAuth credential with that id is loaded.
972
+ */
973
+ forceRefreshCredentialById(id: number, signal?: AbortSignal): Promise<AuthCredentialSnapshotEntry>;
974
+ /** Force-refresh the first OAuth credential stored for a provider. */
975
+ forceRefreshOAuthCredential(provider: string, expected: OAuthCredential, client?: MCPOAuthRefreshClient, signal?: AbortSignal): Promise<OAuthCredential>;
976
+ /**
977
+ * Disable the credential with the given id and emit a
978
+ * {@link CredentialDisabledEvent}. Used by the auth-broker server to honour
979
+ * `POST /v1/credential/:id/disable`. Returns `false` when no such row exists.
980
+ */
981
+ disableCredentialById(id: number, disabledCause: string): boolean;
982
+ /**
983
+ * Upsert a credential into the underlying store, refresh the in-memory
984
+ * snapshot, and return the redacted snapshot entries for the provider.
985
+ *
986
+ * Used by the auth-broker server to honour `POST /v1/credential`. The
987
+ * persistence layer (`SqliteAuthCredentialStore.upsertAuthCredentialForProvider`)
988
+ * does identity-key matching, so re-uploading the same email/account replaces
989
+ * the existing row instead of inserting a duplicate.
990
+ */
991
+ upsertCredential(provider: string, credential: AuthCredential): AuthCredentialSnapshotEntry[];
992
+ /**
993
+ * Describe where the active credential for a provider came from.
994
+ *
995
+ * Surfaces four layers, highest precedence first:
996
+ * 1. Runtime override (`--api-key`).
997
+ * 2. Config override (`models.yml` `providers.<name>.apiKey` literal pin,
998
+ * or an `apiKeyEnv` indirection when no stored api_key credential
999
+ * outranks it).
1000
+ * 3. Stored credential (the one this session is currently sticky to, or the
1001
+ * one round-robin would pick next when no session id is supplied).
1002
+ * 4. Env var / fallback resolver — when no stored credential exists.
1003
+ *
1004
+ * The string is purely informational; consumers must not parse it.
1005
+ */
1006
+ describeCredentialSource(provider: string, sessionId?: string, options?: Pick<AuthApiKeyOptions, "owner">): string | undefined;
1007
+ }
1008
+ /**
1009
+ * Default SQLite-backed implementation of {@link AuthCredentialStore}.
1010
+ *
1011
+ * Used by the pi-ai CLI and as the default store for `AuthStorage.create()`.
1012
+ * Also exposes convenience methods (`saveOAuth`, `getOAuth`, `saveApiKey`,
1013
+ * `getApiKey`, `listProviders`, `deleteProvider`) that callers can use directly
1014
+ * without going through `AuthStorage`.
1015
+ */
1016
+ export declare class SqliteAuthCredentialStore implements AuthCredentialStore {
1017
+ #private;
1018
+ constructor(db: Database);
1019
+ static open(dbPath?: string): Promise<SqliteAuthCredentialStore>;
1020
+ listAuthCredentials(provider?: string): StoredAuthCredential[];
1021
+ listCredentialInventory(provider?: string): CredentialInventoryRecord[];
1022
+ listCredentialRemovalTargets(provider?: string): CredentialRemovalTarget[];
1023
+ removeAuthCredentialsHard(provider: string, targets: readonly CredentialRemovalTarget[]): AuthCredentialHardRemovalResult;
1024
+ claimOAuthRefreshLease(credentialId: number, expectedRefresh: string, force: boolean, owner: string, nowMs: number, leaseMs: number): OAuthRefreshLeaseClaim;
1025
+ completeOAuthRefreshLease(lease: OAuthRefreshLease, credential: OAuthCredential): boolean;
1026
+ releaseOAuthRefreshLease(lease: OAuthRefreshLease): void;
1027
+ replaceAuthCredentialsForProvider(provider: string, credentials: AuthCredential[]): StoredAuthCredential[];
1028
+ upsertAuthCredentialForProvider(provider: string, credential: AuthCredential): StoredAuthCredential[];
1029
+ upsertAuthCredentialForProviderIfAbsent(provider: string, credential: AuthCredential): AuthCredentialIfAbsentResult;
1030
+ updateAuthCredential(id: number, credential: AuthCredential): void;
1031
+ deleteAuthCredential(id: number, disabledCause: string): void;
1032
+ /**
1033
+ * CAS-style disable: only soft-deletes the row when its `data` column still
1034
+ * matches `expectedData` and the row has not already been disabled. Used by
1035
+ * the OAuth refresh-failure path to avoid clobbering a peer that rotated the
1036
+ * row between our pre-check and the disable.
1037
+ */
1038
+ tryDisableAuthCredentialIfMatches(id: number, expectedData: string, disabledCause: string): boolean;
1039
+ tryDisableAuthCredentialIfRevision(id: number, expectedRevision: number, disabledCause: string): boolean;
1040
+ deleteAuthCredentialsForProvider(provider: string, disabledCause: string): void;
1041
+ getCache(key: string, options?: {
1042
+ includeExpired?: boolean;
1043
+ }): string | null;
1044
+ setCache(key: string, value: string, expiresAtSec: number): void;
1045
+ allocateMonotonicSequence(key: string, expiresAtSec: number): number;
1046
+ deleteCachePrefix(prefix: string): void;
1047
+ cleanExpiredCache(): void;
1048
+ /**
1049
+ * Save OAuth credentials for a provider.
1050
+ * Preserves unrelated identities and replaces only the matching credential.
1051
+ */
1052
+ saveOAuth(provider: string, credentials: OAuthCredentials): void;
1053
+ /**
1054
+ * Get OAuth credentials for a provider.
1055
+ */
1056
+ getOAuth(provider: string): OAuthCredentials | null;
1057
+ /**
1058
+ * Save API key for a provider (replaces existing).
1059
+ */
1060
+ saveApiKey(provider: string, apiKey: string): void;
1061
+ /**
1062
+ * Get API key for a provider.
1063
+ */
1064
+ getApiKey(provider: string): string | null;
1065
+ /**
1066
+ * List all providers with credentials.
1067
+ */
1068
+ listProviders(): string[];
1069
+ /**
1070
+ * Delete all credentials for a provider.
1071
+ */
1072
+ deleteProvider(provider: string): void;
1073
+ close(): void;
1074
+ }