@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
package/README.md ADDED
@@ -0,0 +1,1194 @@
1
+ # @vib-rato/ai
2
+
3
+ Unified LLM API with automatic model discovery, provider configuration, token and cost tracking, and simple context persistence and hand-off to other models mid-session.
4
+
5
+ **Note**: This library only includes models that support tool calling (function calling), as this is essential for agentic workflows.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Supported Providers](#supported-providers)
10
+ - [Installation](#installation)
11
+ - [Quick Start](#quick-start)
12
+ - [Tools](#tools)
13
+ - [Defining Tools](#defining-tools)
14
+ - [Handling Tool Calls](#handling-tool-calls)
15
+ - [Streaming Tool Calls with Partial JSON](#streaming-tool-calls-with-partial-json)
16
+ - [Validating Tool Arguments](#validating-tool-arguments)
17
+ - [Complete Event Reference](#complete-event-reference)
18
+ - [Image Input](#image-input)
19
+ - [Thinking/Reasoning](#thinkingreasoning)
20
+ - [Unified Interface](#unified-interface-streamsimplecompletesimple)
21
+ - [Provider-Specific Options](#provider-specific-options-streamcomplete)
22
+ - [Streaming Thinking Content](#streaming-thinking-content)
23
+ - [Stop Reasons](#stop-reasons)
24
+ - [Error Handling](#error-handling)
25
+ - [Aborting Requests](#aborting-requests)
26
+ - [Continuing After Abort](#continuing-after-abort)
27
+ - [APIs, Models, and Providers](#apis-models-and-providers)
28
+ - [Providers and Models](#providers-and-models)
29
+ - [Querying Providers and Models](#querying-providers-and-models)
30
+ - [Custom Models](#custom-models)
31
+ - [OpenAI Compatibility Settings](#openai-compatibility-settings)
32
+ - [Type Safety](#type-safety)
33
+ - [Cross-Provider Handoffs](#cross-provider-handoffs)
34
+ - [Context Serialization](#context-serialization)
35
+ - [Browser Usage](#browser-usage)
36
+ - [Environment Variables](#environment-variables-nodejs-only)
37
+ - [Checking Environment Variables](#checking-environment-variables)
38
+ - [OAuth Providers](#oauth-providers)
39
+ - [Vertex AI (ADC)](#vertex-ai-adc)
40
+ - [CLI Login](#cli-login)
41
+ - [Programmatic OAuth](#programmatic-oauth)
42
+ - [Login Flow Example](#login-flow-example)
43
+ - [Using OAuth Tokens](#using-oauth-tokens)
44
+ - [Provider Notes](#provider-notes)
45
+ - [License](#license)
46
+
47
+ ## Supported Providers
48
+
49
+ - **OpenAI**
50
+ - **OpenAI code provider** (ChatGPT Plus/Pro subscription, requires OAuth, see below)
51
+ - **Anthropic**
52
+ - **Google**
53
+ - **Vertex AI** (Gemini via Vertex AI)
54
+ - **Mistral**
55
+ - **Groq**
56
+ - **Cerebras**
57
+ - **Together**
58
+ - **Moonshot** (requires `MOONSHOT_API_KEY`)
59
+ - **Qianfan** (requires `QIANFAN_API_KEY`)
60
+ - **NVIDIA** (requires `NVIDIA_API_KEY`)
61
+ - **NanoGPT** (requires `NANO_GPT_API_KEY`)
62
+ - **Hugging Face Inference**
63
+ - **xAI**
64
+ - **Venice** (requires `VENICE_API_KEY`)
65
+ - **OpenRouter**
66
+ - **Kilo Gateway** (supports OAuth `/login kilo` or `KILO_API_KEY`)
67
+ - **LiteLLM** (requires `LITELLM_API_KEY`)
68
+ - **zAI** (requires `ZAI_API_KEY`)
69
+ - **MiniMax Coding Plan** (requires `MINIMAX_CODE_API_KEY` or `MINIMAX_CODE_CN_API_KEY`)
70
+ - **Xiaomi MiMo** (requires `XIAOMI_API_KEY`)
71
+ - **ZenMux** (requires `ZENMUX_API_KEY`)
72
+ - **OpenGateway by Sionic AI** (requires `OPENGATEWAY_API_KEY`)
73
+ - **BizRouter** (requires `BIZROUTER_API_KEY`)
74
+ - **Mara Cloud** (requires `MARA_API_KEY`)
75
+ - **Qwen Portal** (supports `QWEN_OAUTH_TOKEN` or `QWEN_PORTAL_API_KEY`)
76
+ - **Cloudflare AI Gateway** (requires `CLOUDFLARE_AI_GATEWAY_API_KEY` and provider-specific gateway base URL)
77
+ - **Ollama** (local OpenAI-compatible runtime; optional `OLLAMA_API_KEY`)
78
+ - **Ollama Cloud** (hosted native Ollama API; requires `OLLAMA_CLOUD_API_KEY`)
79
+ - **llama.cpp** (local OpenAI and Anthropic compatible inference server)
80
+ - **vLLM** (OpenAI-compatible server; `VLLM_API_KEY` for secured deployments)
81
+ - **GitHub Copilot** (requires OAuth, see below)
82
+ - **Google Gemini CLI** (requires OAuth, see below)
83
+ - **Antigravity** (requires OAuth, see below)
84
+ - **Any OpenAI-compatible API**: LM Studio, custom proxies, etc.
85
+
86
+ ## Installation
87
+
88
+ ```bash
89
+ npm install @vib-rato/ai
90
+ ```
91
+
92
+ ## Quick Start
93
+
94
+ ```typescript
95
+ import { z, getModel, stream, complete, Context, Tool } from "@vib-rato/ai";
96
+
97
+ // Fully typed with auto-complete support for both providers and models
98
+ const model = getModel("openai", "gpt-4o-mini");
99
+
100
+ // Define tools with Zod schemas for type safety and validation
101
+ const tools: Tool[] = [
102
+ {
103
+ name: "get_time",
104
+ description: "Get the current time",
105
+ parameters: z.object({
106
+ timezone: z
107
+ .string()
108
+ .optional()
109
+ .describe("Optional timezone (e.g., America/New_York)"),
110
+ }),
111
+ },
112
+ ];
113
+
114
+ // Build a conversation context (easily serializable and transferable between models)
115
+ const context: Context = {
116
+ systemPrompt: ["You are a helpful assistant."],
117
+ messages: [{ role: "user", content: "What time is it?" }],
118
+ tools,
119
+ };
120
+
121
+ // Option 1: Streaming with all event types
122
+ const s = stream(model, context);
123
+
124
+ for await (const event of s) {
125
+ switch (event.type) {
126
+ case "start":
127
+ console.log(`Starting with ${event.partial.model}`);
128
+ break;
129
+ case "text_start":
130
+ console.log("\n[Text started]");
131
+ break;
132
+ case "text_delta":
133
+ process.stdout.write(event.delta);
134
+ break;
135
+ case "text_end":
136
+ console.log("\n[Text ended]");
137
+ break;
138
+ case "thinking_start":
139
+ console.log("[Model is thinking...]");
140
+ break;
141
+ case "thinking_delta":
142
+ process.stdout.write(event.delta);
143
+ break;
144
+ case "thinking_end":
145
+ console.log("[Thinking complete]");
146
+ break;
147
+ case "toolcall_start":
148
+ console.log(`\n[Tool call started: index ${event.contentIndex}]`);
149
+ break;
150
+ case "toolcall_delta":
151
+ // Partial tool arguments are being streamed
152
+ const partialCall = event.partial.content[event.contentIndex];
153
+ if (partialCall.type === "toolCall") {
154
+ console.log(`[Streaming args for ${partialCall.name}]`);
155
+ }
156
+ break;
157
+ case "toolcall_end":
158
+ console.log(`\nTool called: ${event.toolCall.name}`);
159
+ console.log(`Arguments: ${JSON.stringify(event.toolCall.arguments)}`);
160
+ break;
161
+ case "done":
162
+ console.log(`\nFinished: ${event.reason}`);
163
+ break;
164
+ case "error":
165
+ console.error(`Error: ${event.error}`);
166
+ break;
167
+ }
168
+ }
169
+
170
+ // Get the final message after streaming, add it to the context
171
+ const finalMessage = await s.result();
172
+ context.messages.push(finalMessage);
173
+
174
+ // Handle tool calls if any
175
+ const toolCalls = finalMessage.content.filter((b) => b.type === "toolCall");
176
+ for (const call of toolCalls) {
177
+ // Execute the tool
178
+ const result =
179
+ call.name === "get_time"
180
+ ? new Date().toLocaleString("en-US", {
181
+ timeZone: call.arguments.timezone || "UTC",
182
+ dateStyle: "full",
183
+ timeStyle: "long",
184
+ })
185
+ : "Unknown tool";
186
+
187
+ // Add tool result to context (supports text and images)
188
+ context.messages.push({
189
+ role: "toolResult",
190
+ toolCallId: call.id,
191
+ toolName: call.name,
192
+ content: [{ type: "text", text: result }],
193
+ isError: false,
194
+ timestamp: Date.now(),
195
+ });
196
+ }
197
+
198
+ // Continue if there were tool calls
199
+ if (toolCalls.length > 0) {
200
+ const continuation = await complete(model, context);
201
+ context.messages.push(continuation);
202
+ console.log("After tool execution:", continuation.content);
203
+ }
204
+
205
+ console.log(`Total tokens: ${finalMessage.usage.input} in, ${finalMessage.usage.output} out`);
206
+ console.log(`Cost: $${finalMessage.usage.cost.total.toFixed(4)}`);
207
+
208
+ // Option 2: Get complete response without streaming
209
+ const response = await complete(model, context);
210
+
211
+ for (const block of response.content) {
212
+ if (block.type === "text") {
213
+ console.log(block.text);
214
+ } else if (block.type === "toolCall") {
215
+ console.log(`Tool: ${block.name}(${JSON.stringify(block.arguments)})`);
216
+ }
217
+ }
218
+ ```
219
+
220
+ ## Tools
221
+
222
+ Tools enable LLMs to interact with external systems. This library uses **Zod** schemas for type-safe tool definitions with automatic validation. Schemas are converted to JSON Schema for providers as needed.
223
+
224
+ ### Defining Tools
225
+
226
+ ```typescript
227
+ import { z, Tool } from "@vib-rato/ai";
228
+
229
+ // Define tool parameters with Zod
230
+ const weatherTool: Tool = {
231
+ name: "get_weather",
232
+ description: "Get current weather for a location",
233
+ parameters: z.object({
234
+ location: z.string().describe("City name or coordinates"),
235
+ units: z.enum(["celsius", "fahrenheit"]).default("celsius"),
236
+ }),
237
+ };
238
+
239
+ const bookMeetingTool: Tool = {
240
+ name: "book_meeting",
241
+ description: "Schedule a meeting",
242
+ parameters: z.object({
243
+ title: z.string().min(1),
244
+ startTime: z.string().describe("ISO 8601 date-time"),
245
+ endTime: z.string().describe("ISO 8601 date-time"),
246
+ attendees: z.array(z.email()).min(1),
247
+ }),
248
+ };
249
+ ```
250
+
251
+ ### Handling Tool Calls
252
+
253
+ Tool results use content blocks and can include both text and images:
254
+
255
+ ```typescript
256
+ import * as fs from "node:fs";
257
+
258
+ const context: Context = {
259
+ messages: [{ role: "user", content: "What is the weather in London?" }],
260
+ tools: [weatherTool],
261
+ };
262
+
263
+ const response = await complete(model, context);
264
+
265
+ // Check for tool calls in the response
266
+ for (const block of response.content) {
267
+ if (block.type === "toolCall") {
268
+ // Execute your tool with the arguments
269
+ // See "Validating Tool Arguments" section for validation
270
+ const result = await executeWeatherApi(block.arguments);
271
+
272
+ // Add tool result with text content
273
+ context.messages.push({
274
+ role: "toolResult",
275
+ toolCallId: block.id,
276
+ toolName: block.name,
277
+ content: [{ type: "text", text: JSON.stringify(result) }],
278
+ isError: false,
279
+ timestamp: Date.now(),
280
+ });
281
+ }
282
+ }
283
+
284
+ // Tool results can also include images (for vision-capable models)
285
+ const imageBuffer = fs.readFileSync("chart.png");
286
+ context.messages.push({
287
+ role: "toolResult",
288
+ toolCallId: "tool_xyz",
289
+ toolName: "generate_chart",
290
+ content: [
291
+ { type: "text", text: "Generated chart showing temperature trends" },
292
+ { type: "image", data: imageBuffer.toBase64(), mimeType: "image/png" },
293
+ ],
294
+ isError: false,
295
+ timestamp: Date.now(),
296
+ });
297
+ ```
298
+
299
+ ### Streaming Tool Calls with Partial JSON
300
+
301
+ During streaming, tool call arguments are progressively parsed as they arrive. This enables real-time UI updates before the complete arguments are available:
302
+
303
+ ```typescript
304
+ const s = stream(model, context);
305
+
306
+ for await (const event of s) {
307
+ if (event.type === "toolcall_delta") {
308
+ const toolCall = event.partial.content[event.contentIndex];
309
+
310
+ // toolCall.arguments contains partially parsed JSON during streaming
311
+ // This allows for progressive UI updates
312
+ if (toolCall.type === "toolCall" && toolCall.arguments) {
313
+ // BE DEFENSIVE: arguments may be incomplete
314
+ // Example: Show file path being written even before content is complete
315
+ if (toolCall.name === "write_file" && toolCall.arguments.path) {
316
+ console.log(`Writing to: ${toolCall.arguments.path}`);
317
+
318
+ // Content might be partial or missing
319
+ if (toolCall.arguments.content) {
320
+ console.log(`Content preview: ${toolCall.arguments.content.substring(0, 100)}...`);
321
+ }
322
+ }
323
+ }
324
+ }
325
+
326
+ if (event.type === "toolcall_end") {
327
+ // Here toolCall.arguments is complete (but not yet validated)
328
+ const toolCall = event.toolCall;
329
+ console.log(`Tool completed: ${toolCall.name}`, toolCall.arguments);
330
+ }
331
+ }
332
+ ```
333
+
334
+ **Important notes about partial tool arguments:**
335
+
336
+ - During `toolcall_delta` events, `arguments` contains the best-effort parse of partial JSON
337
+ - Fields may be missing or incomplete - always check for existence before use
338
+ - String values may be truncated mid-word
339
+ - Arrays may be incomplete
340
+ - Nested objects may be partially populated
341
+ - At minimum, `arguments` will be an empty object `{}`, never `undefined`
342
+ - The Google provider does not support function call streaming. Instead, you will receive a single `toolcall_delta` event with the full arguments.
343
+
344
+ ### Validating Tool Arguments
345
+
346
+ When using `agentLoop`, tool arguments are automatically validated against your Zod parameter schemas before execution. If validation fails, the error is returned to the model as a tool result, allowing it to retry.
347
+
348
+ When implementing your own tool execution loop with `stream()` or `complete()`, use `validateToolCall` to validate arguments before passing them to your tools:
349
+
350
+ ```typescript
351
+ import { stream, validateToolCall, Tool } from "@vib-rato/ai";
352
+
353
+ const tools: Tool[] = [weatherTool, calculatorTool];
354
+ const s = stream(model, { messages, tools });
355
+
356
+ for await (const event of s) {
357
+ if (event.type === "toolcall_end") {
358
+ const toolCall = event.toolCall;
359
+
360
+ try {
361
+ // Validate arguments against the tool's schema (throws on invalid args)
362
+ const validatedArgs = validateToolCall(tools, toolCall);
363
+ const result = await executeMyTool(toolCall.name, validatedArgs);
364
+ // ... add tool result to context
365
+ } catch (error) {
366
+ // Validation failed - return error as tool result so model can retry
367
+ context.messages.push({
368
+ role: "toolResult",
369
+ toolCallId: toolCall.id,
370
+ toolName: toolCall.name,
371
+ content: [{ type: "text", text: error.message }],
372
+ isError: true,
373
+ timestamp: Date.now(),
374
+ });
375
+ }
376
+ }
377
+ }
378
+ ```
379
+
380
+ ### Complete Event Reference
381
+
382
+ All streaming events emitted during assistant message generation:
383
+
384
+ | Event Type | Description | Key Properties |
385
+ | ---------------- | ------------------------ | ------------------------------------------------------------------------------------------- |
386
+ | `start` | Stream begins | `partial`: Initial assistant message structure |
387
+ | `text_start` | Text block starts | `contentIndex`: Position in content array |
388
+ | `text_delta` | Text chunk received | `delta`: New text, `contentIndex`: Position |
389
+ | `text_end` | Text block complete | `content`: Full text, `contentIndex`: Position |
390
+ | `thinking_start` | Thinking block starts | `contentIndex`: Position in content array |
391
+ | `thinking_delta` | Thinking chunk received | `delta`: New text, `contentIndex`: Position |
392
+ | `thinking_end` | Thinking block complete | `content`: Full thinking, `contentIndex`: Position |
393
+ | `toolcall_start` | Tool call begins | `contentIndex`: Position in content array |
394
+ | `toolcall_delta` | Tool arguments streaming | `delta`: JSON chunk, `partial.content[contentIndex].arguments`: Partial parsed args |
395
+ | `toolcall_end` | Tool call complete | `toolCall`: Complete validated tool call with `id`, `name`, `arguments` |
396
+ | `done` | Stream complete | `reason`: Stop reason ("stop", "length", "toolUse"), `message`: Final assistant message |
397
+ | `error` | Error occurred | `reason`: Error type ("error" or "aborted"), `error`: AssistantMessage with partial content |
398
+
399
+ ## Image Input
400
+
401
+ Models with vision capabilities can process images. You can check if a model supports images via the `input` property. If you pass images to a non-vision model, they are silently ignored.
402
+
403
+ ```typescript
404
+ import * as fs from "node:fs";
405
+ import { getModel, complete } from "@vib-rato/ai";
406
+
407
+ const model = getModel("openai", "gpt-4o-mini");
408
+
409
+ // Check if model supports images
410
+ if (model.input.includes("image")) {
411
+ console.log("Model supports vision");
412
+ }
413
+
414
+ const imageBuffer = fs.readFileSync("image.png");
415
+ const base64Image = imageBuffer.toBase64();
416
+
417
+ const response = await complete(model, {
418
+ messages: [
419
+ {
420
+ role: "user",
421
+ content: [
422
+ { type: "text", text: "What is in this image?" },
423
+ { type: "image", data: base64Image, mimeType: "image/png" },
424
+ ],
425
+ },
426
+ ],
427
+ });
428
+
429
+ // Access the response
430
+ for (const block of response.content) {
431
+ if (block.type === "text") {
432
+ console.log(block.text);
433
+ }
434
+ }
435
+ ```
436
+
437
+ ## Thinking/Reasoning
438
+
439
+ Many models support thinking/reasoning capabilities where they can show their internal thought process. You can check if a model supports reasoning via the `reasoning` property. If you pass reasoning options to a non-reasoning model, they are silently ignored.
440
+
441
+ ### Unified Interface (streamSimple/completeSimple)
442
+
443
+ ```typescript
444
+ import { getModel, streamSimple, completeSimple } from "@vib-rato/ai";
445
+
446
+ // Many models across providers support thinking/reasoning
447
+ const model = getModel("anthropic", "anthropic-model-sonnet-4-20250514");
448
+ // or getModel('openai', 'gpt-5-mini');
449
+ // or getModel('google', 'gemini-2.5-flash');
450
+ // or getModel('xai', 'grok-code-fast-1');
451
+ // or getModel('groq', 'openai/gpt-oss-20b');
452
+ // or getModel('cerebras', 'gpt-oss-120b');
453
+ // or getModel('openrouter', 'z-ai/glm-4.5v');
454
+
455
+ // Check if model supports reasoning
456
+ if (model.reasoning) {
457
+ console.log("Model supports reasoning/thinking");
458
+ }
459
+
460
+ // Use the simplified reasoning option
461
+ const response = await completeSimple(
462
+ model,
463
+ {
464
+ messages: [{ role: "user", content: "Solve: 2x + 5 = 13" }],
465
+ },
466
+ {
467
+ reasoning: "medium", // 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' (xhigh maps to high on non-OpenAI providers)
468
+ }
469
+ );
470
+
471
+ // Access thinking and text blocks
472
+ for (const block of response.content) {
473
+ if (block.type === "thinking") {
474
+ console.log("Thinking:", block.thinking);
475
+ } else if (block.type === "text") {
476
+ console.log("Response:", block.text);
477
+ }
478
+ }
479
+ ```
480
+
481
+ ### Provider-Specific Options (stream/complete)
482
+
483
+ For fine-grained control, use the provider-specific options:
484
+
485
+ ```typescript
486
+ import { getModel, complete } from "@vib-rato/ai";
487
+
488
+ // OpenAI Reasoning (o1, o3, gpt-5)
489
+ const openaiModel = getModel("openai", "gpt-5-mini");
490
+ await complete(openaiModel, context, {
491
+ reasoningEffort: "medium",
492
+ reasoningSummary: "detailed", // OpenAI Responses API only
493
+ });
494
+
495
+ // Anthropic Thinking (Anthropic model Sonnet 4)
496
+ const anthropicModel = getModel("anthropic", "anthropic-model-sonnet-4-20250514");
497
+ await complete(anthropicModel, context, {
498
+ thinkingEnabled: true,
499
+ thinkingBudgetTokens: 8192, // Optional token limit
500
+ });
501
+
502
+ // Google Gemini Thinking
503
+ const googleModel = getModel("google", "gemini-2.5-flash");
504
+ await complete(googleModel, context, {
505
+ thinking: {
506
+ enabled: true,
507
+ budgetTokens: 8192, // -1 for dynamic, 0 to disable
508
+ },
509
+ });
510
+ ```
511
+
512
+ ### Streaming Thinking Content
513
+
514
+ When streaming, thinking content is delivered through specific events:
515
+
516
+ ```typescript
517
+ const s = streamSimple(model, context, { reasoning: "high" });
518
+
519
+ for await (const event of s) {
520
+ switch (event.type) {
521
+ case "thinking_start":
522
+ console.log("[Model started thinking]");
523
+ break;
524
+ case "thinking_delta":
525
+ process.stdout.write(event.delta); // Stream thinking content
526
+ break;
527
+ case "thinking_end":
528
+ console.log("\n[Thinking complete]");
529
+ break;
530
+ }
531
+ }
532
+ ```
533
+
534
+ ## Stop Reasons
535
+
536
+ Every `AssistantMessage` includes a `stopReason` field that indicates how the generation ended:
537
+
538
+ - `"stop"` - Normal completion, the model finished its response
539
+ - `"length"` - Output hit the maximum token limit
540
+ - `"toolUse"` - Model is calling tools and expects tool results
541
+ - `"error"` - An error occurred during generation
542
+ - `"aborted"` - Request was cancelled via abort signal
543
+
544
+ ## Error Handling
545
+
546
+ When a request ends with an error (including aborts and tool call validation errors), the streaming API emits an error event:
547
+
548
+ ```typescript
549
+ // In streaming
550
+ for await (const event of stream) {
551
+ if (event.type === "error") {
552
+ // event.reason is either "error" or "aborted"
553
+ // event.error is the AssistantMessage with partial content
554
+ console.error(`Error (${event.reason}):`, event.error.errorMessage);
555
+ console.log("Partial content:", event.error.content);
556
+ }
557
+ }
558
+
559
+ // The final message will have the error details
560
+ const message = await stream.result();
561
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
562
+ console.error("Request failed:", message.errorMessage);
563
+ // message.content contains any partial content received before the error
564
+ // message.usage contains partial token counts and costs
565
+ }
566
+ ```
567
+
568
+ ### Aborting Requests
569
+
570
+ The abort signal allows you to cancel in-progress requests. Aborted requests have `stopReason === 'aborted'`:
571
+
572
+ ```typescript
573
+ import { getModel, stream } from "@vib-rato/ai";
574
+
575
+ const model = getModel("openai", "gpt-4o-mini");
576
+
577
+ // Abort after 2 seconds
578
+ const signal = AbortSignal.timeout(2000);
579
+
580
+ const s = stream(
581
+ model,
582
+ {
583
+ messages: [{ role: "user", content: "Write a long story" }],
584
+ },
585
+ {
586
+ signal,
587
+ }
588
+ );
589
+
590
+ for await (const event of s) {
591
+ if (event.type === "text_delta") {
592
+ process.stdout.write(event.delta);
593
+ } else if (event.type === "error") {
594
+ // event.reason tells you if it was "error" or "aborted"
595
+ console.log(`${event.reason === "aborted" ? "Aborted" : "Error"}:`, event.error.errorMessage);
596
+ }
597
+ }
598
+
599
+ // Get results (may be partial if aborted)
600
+ const response = await s.result();
601
+ if (response.stopReason === "aborted") {
602
+ console.log("Request was aborted:", response.errorMessage);
603
+ console.log("Partial content received:", response.content);
604
+ console.log("Tokens used:", response.usage);
605
+ }
606
+ ```
607
+
608
+ ### Continuing After Abort
609
+
610
+ Aborted messages can be added to the conversation context and continued in subsequent requests:
611
+
612
+ ```typescript
613
+ const context = {
614
+ messages: [{ role: "user", content: "Explain quantum computing in detail" }],
615
+ };
616
+
617
+ // First request gets aborted after 2 seconds
618
+ const controller1 = new AbortController();
619
+ setTimeout(() => controller1.abort(), 2000);
620
+
621
+ const partial = await complete(model, context, { signal: controller1.signal });
622
+
623
+ // Add the partial response to context
624
+ context.messages.push(partial);
625
+ context.messages.push({ role: "user", content: "Please continue" });
626
+
627
+ // Continue the conversation
628
+ const continuation = await complete(model, context);
629
+ ```
630
+
631
+ ### Common Stream Options
632
+
633
+ All providers accept the base `StreamOptions` (in addition to provider-specific options):
634
+
635
+ - `apiKey`: Override the provider API key
636
+ - `headers`: Extra request headers merged on top of model-defined headers
637
+ - `sessionId`: Provider-specific session identifier (prompt caching/routing)
638
+ - `signal`: Abort in-flight requests
639
+ - `onPayload`: Callback invoked with the provider request payload just before sending
640
+
641
+ Example:
642
+
643
+ ```typescript
644
+ const response = await complete(model, context, {
645
+ apiKey: "sk-live",
646
+ headers: { "X-Debug-Trace": "true" },
647
+ onPayload: (payload) => {
648
+ console.log("request payload", payload);
649
+ },
650
+ });
651
+ ```
652
+
653
+ ## APIs, Models, and Providers
654
+
655
+ The library implements 4 API interfaces, each with its own streaming function and options:
656
+
657
+ - **`anthropic-messages`**: Anthropic's Messages API (`streamAnthropic`, `AnthropicOptions`)
658
+ - **`google-generative-ai`**: Google's Generative AI API (`streamGoogle`, `GoogleOptions`)
659
+ - **`openai-completions`**: OpenAI's Chat Completions API (`streamOpenAICompletions`, `OpenAICompletionsOptions`)
660
+ - **`openai-responses`**: OpenAI's Responses API (`streamOpenAIResponses`, `OpenAIResponsesOptions`)
661
+
662
+ ### Providers and Models
663
+
664
+ A **provider** offers models through a specific API. For example:
665
+
666
+ - **Anthropic** models use the `anthropic-messages` API
667
+ - **Google** models use the `google-generative-ai` API
668
+ - **OpenAI** models use the `openai-responses` API
669
+ - **Mistral, xAI, Cerebras, Groq, etc.** models use the `openai-completions` API (OpenAI-compatible)
670
+
671
+ ### Querying Providers and Models
672
+
673
+ ```typescript
674
+ import { getProviders, getModels, getModel } from "@vib-rato/ai";
675
+
676
+ // Get all available providers
677
+ const providers = getProviders();
678
+ console.log(providers); // ['openai', 'anthropic', 'google', 'xai', 'groq', ...]
679
+
680
+ // Get all models from a provider (fully typed)
681
+ const anthropicModels = getModels("anthropic");
682
+ for (const model of anthropicModels) {
683
+ console.log(`${model.id}: ${model.name}`);
684
+ console.log(` API: ${model.api}`); // 'anthropic-messages'
685
+ console.log(` Context: ${model.contextWindow} tokens`);
686
+ console.log(` Vision: ${model.input.includes("image")}`);
687
+ console.log(` Reasoning: ${model.reasoning}`);
688
+ }
689
+
690
+ // Get a specific model (both provider and model ID are auto-completed in IDEs)
691
+ const model = getModel("openai", "gpt-4o-mini");
692
+ console.log(`Using ${model.name} via ${model.api} API`);
693
+ ```
694
+
695
+ ### Custom Models
696
+
697
+ You can create custom models for local inference servers or custom endpoints.
698
+
699
+ For local Ollama, `OLLAMA_API_KEY` is optional and mainly needed for authenticated/self-hosted gateways. `ollama` remains the local OpenAI-compatible runtime integration.
700
+
701
+ ```typescript
702
+ import { Model, stream } from "@vib-rato/ai";
703
+
704
+ // Example: local Ollama using the OpenAI-compatible API
705
+ const ollamaModel: Model<"openai-completions"> = {
706
+ id: "llama-3.1-8b",
707
+ name: "Llama 3.1 8B (Ollama)",
708
+ api: "openai-completions",
709
+ provider: "ollama",
710
+ baseUrl: "http://localhost:11434/v1",
711
+ reasoning: false,
712
+ input: ["text"],
713
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
714
+ contextWindow: 128000,
715
+ maxTokens: 32000,
716
+ };
717
+
718
+ const localResponse = await stream(ollamaModel, context, {
719
+ apiKey: process.env.OLLAMA_API_KEY, // Optional; local Ollama usually runs without auth
720
+ });
721
+
722
+ // Example: Ollama Cloud using the native /api/chat transport
723
+ const ollamaCloudModel: Model<"ollama-chat"> = {
724
+ id: "gpt-oss:120b",
725
+ name: "GPT OSS 120B (Ollama Cloud)",
726
+ api: "ollama-chat",
727
+ provider: "ollama-cloud",
728
+ baseUrl: "https://ollama.com",
729
+ reasoning: true,
730
+ input: ["text", "image"],
731
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
732
+ contextWindow: 262144,
733
+ maxTokens: 8192,
734
+ };
735
+
736
+ const cloudResponse = await stream(ollamaCloudModel, context, {
737
+ apiKey: process.env.OLLAMA_CLOUD_API_KEY,
738
+ });
739
+
740
+ // Example: LiteLLM proxy with explicit compat settings
741
+ const litellmModel: Model<"openai-completions"> = {
742
+ id: "gpt-4o",
743
+ name: "GPT-4o (via LiteLLM)",
744
+ api: "openai-completions",
745
+ provider: "litellm",
746
+ baseUrl: "http://localhost:4000/v1",
747
+ reasoning: false,
748
+ input: ["text", "image"],
749
+ cost: { input: 2.5, output: 10, cacheRead: 0, cacheWrite: 0 },
750
+ contextWindow: 128000,
751
+ maxTokens: 16384,
752
+ compat: {
753
+ supportsStore: false, // LiteLLM doesn't support the store field
754
+ },
755
+ };
756
+
757
+ // Example: Custom endpoint with headers (bypassing Cloudflare bot detection)
758
+ const proxyModel: Model<"anthropic-messages"> = {
759
+ id: "anthropic-model-sonnet-4",
760
+ name: "Anthropic model Sonnet 4 (Proxied)",
761
+ api: "anthropic-messages",
762
+ provider: "custom-proxy",
763
+ baseUrl: "https://proxy.example.com/v1",
764
+ reasoning: true,
765
+ input: ["text", "image"],
766
+ cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
767
+ contextWindow: 200000,
768
+ maxTokens: 8192,
769
+ headers: {
770
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
771
+ "X-Custom-Auth": "bearer-token-here",
772
+ },
773
+ };
774
+ ```
775
+
776
+ ### OpenAI Compatibility Settings
777
+
778
+ The `openai-completions` API is implemented by many providers with minor differences. By default, the library auto-detects compatibility settings based on `baseUrl` for known providers (Cerebras, xAI, Mistral, Chutes, etc.). For custom proxies or unknown endpoints, you can override these settings via the `compat` field:
779
+
780
+ ```typescript
781
+ interface OpenAICompat {
782
+ supportsStore?: boolean; // Whether provider supports the `store` field (default: true)
783
+ supportsDeveloperRole?: boolean; // Whether provider supports `developer` role vs `system` (default: true)
784
+ sendSessionHeaders?: boolean; // Forward the session id as `session_id`/`x-session-id` headers for relay session-affinity & prompt-cache reuse (default: false)
785
+ supportsResponsesSessionAffinity?: boolean; // Opt in to session-affinity headers for custom openai-responses relays; canonical OpenAI routing is automatic (default: false)
786
+ supportsReasoningEffort?: boolean; // Whether provider supports `reasoning_effort` (default: true)
787
+ maxTokensField?: "max_completion_tokens" | "max_tokens"; // Which field name to use (default: max_completion_tokens)
788
+ extraBody?: Record<string, unknown>; // Extra request-body fields for custom proxy routing or provider-specific options
789
+ }
790
+ ```
791
+
792
+ If `compat` is not set, the library falls back to URL-based detection. If `compat` is partially set, unspecified fields use the detected defaults. This is useful for:
793
+
794
+ - **LiteLLM proxies**: May not support `store` field
795
+ - **Custom inference servers**: May use non-standard field names
796
+ - **Self-hosted endpoints**: May have different feature support
797
+
798
+ ### Type Safety
799
+
800
+ Models are typed by their API, ensuring type-safe options:
801
+
802
+ ```typescript
803
+ // TypeScript knows this is an Anthropic model
804
+ const anthropic-model = getModel("anthropic", "anthropic-model-sonnet-4-20250514");
805
+
806
+ // So these options are type-checked for AnthropicOptions
807
+ await stream(anthropic-model, context, {
808
+ thinkingEnabled: true, // ✓ Valid for anthropic-messages
809
+ thinkingBudgetTokens: 2048, // ✓ Valid for anthropic-messages
810
+ // reasoningEffort: 'high' // ✗ TypeScript error: not valid for anthropic-messages
811
+ });
812
+ ```
813
+
814
+ ## Cross-Provider Handoffs
815
+
816
+ The library supports seamless handoffs between different LLM providers within the same conversation. This allows you to switch models mid-conversation while preserving context, including thinking blocks, tool calls, and tool results.
817
+
818
+ ### How It Works
819
+
820
+ When messages from one provider are sent to a different provider, the library automatically transforms them for compatibility:
821
+
822
+ - **User and tool result messages** are passed through unchanged
823
+ - **Assistant messages from the same provider/API** are preserved as-is
824
+ - **Assistant messages from different providers** have their thinking blocks converted to text with `<thinking>` tags
825
+ - **Tool calls and regular text** are preserved unchanged
826
+
827
+ ### Example: Multi-Provider Conversation
828
+
829
+ ```typescript
830
+ import { getModel, complete, Context } from "@vib-rato/ai";
831
+
832
+ // Start with Anthropic model
833
+ const anthropic-model = getModel("anthropic", "anthropic-model-sonnet-4-20250514");
834
+ const context: Context = {
835
+ messages: [],
836
+ };
837
+
838
+ context.messages.push({ role: "user", content: "What is 25 * 18?" });
839
+ const anthropic-modelResponse = await complete(anthropic-model, context, {
840
+ thinkingEnabled: true,
841
+ });
842
+ context.messages.push(anthropic-modelResponse);
843
+
844
+ // Switch to GPT-5 - it will see Anthropic model's thinking as <thinking> tagged text
845
+ const gpt5 = getModel("openai", "gpt-5-mini");
846
+ context.messages.push({ role: "user", content: "Is that calculation correct?" });
847
+ const gptResponse = await complete(gpt5, context);
848
+ context.messages.push(gptResponse);
849
+
850
+ // Switch to Gemini
851
+ const gemini = getModel("google", "gemini-2.5-flash");
852
+ context.messages.push({ role: "user", content: "What was the original question?" });
853
+ const geminiResponse = await complete(gemini, context);
854
+ ```
855
+
856
+ ### Provider Compatibility
857
+
858
+ All providers can handle messages from other providers, including:
859
+
860
+ - Text content
861
+ - Tool calls and tool results (including images in tool results)
862
+ - Thinking/reasoning blocks (transformed to tagged text for cross-provider compatibility)
863
+ - Aborted messages with partial content
864
+
865
+ This enables flexible workflows where you can:
866
+
867
+ - Start with a fast model for initial responses
868
+ - Switch to a more capable model for complex reasoning
869
+ - Use specialized models for specific tasks
870
+ - Maintain conversation continuity across provider outages
871
+
872
+ ## Context Serialization
873
+
874
+ The `Context` object can be easily serialized and deserialized using standard JSON methods, making it simple to persist conversations, implement chat history, or transfer contexts between services:
875
+
876
+ ```typescript
877
+ import { Context, getModel, complete } from "@vib-rato/ai";
878
+
879
+ // Create and use a context
880
+ const context: Context = {
881
+ systemPrompt: ["You are a helpful assistant."],
882
+ messages: [{ role: "user", content: "What is TypeScript?" }],
883
+ };
884
+
885
+ const model = getModel("openai", "gpt-4o-mini");
886
+ const response = await complete(model, context);
887
+ context.messages.push(response);
888
+
889
+ // Serialize the entire context
890
+ const serialized = JSON.stringify(context);
891
+ console.log("Serialized context size:", serialized.length, "bytes");
892
+
893
+ // Save to database, localStorage, file, etc.
894
+ localStorage.setItem("conversation", serialized);
895
+
896
+ // Later: deserialize and continue the conversation
897
+ const restored: Context = JSON.parse(localStorage.getItem("conversation")!);
898
+ restored.messages.push({ role: "user", content: "Tell me more about its type system" });
899
+
900
+ // Continue with any model
901
+ const newModel = getModel("anthropic", "anthropic-model-haiku-4-5-20251001");
902
+ const continuation = await complete(newModel, restored);
903
+ ```
904
+
905
+ > **Note**: If the context contains images (encoded as base64 as shown in the Image Input section), those will also be serialized.
906
+
907
+ ## Browser Usage
908
+
909
+ The library supports browser environments. You must pass the API key explicitly since environment variables are not available in browsers:
910
+
911
+ ```typescript
912
+ import { getModel, complete } from "@vib-rato/ai";
913
+
914
+ // API key must be passed explicitly in browser
915
+ const model = getModel("anthropic", "anthropic-model-haiku-4-5-20251001");
916
+
917
+ const response = await complete(
918
+ model,
919
+ {
920
+ messages: [{ role: "user", content: "Hello!" }],
921
+ },
922
+ {
923
+ apiKey: "your-api-key",
924
+ }
925
+ );
926
+ ```
927
+
928
+ > **Security Warning**: Exposing API keys in frontend code is dangerous. Anyone can extract and abuse your keys. Only use this approach for internal tools or demos. For production applications, use a backend proxy that keeps your API keys secure.
929
+
930
+ ### Environment Variables (Node.js only)
931
+
932
+ In Node.js environments, you can set environment variables to avoid passing API keys:
933
+
934
+ | Provider | Environment Variable(s) |
935
+ | -------------- | ---------------------------------------------------------------------------- |
936
+ | OpenAI | `OPENAI_API_KEY` |
937
+ | Anthropic | `ANTHROPIC_API_KEY` or `ANTHROPIC_OAUTH_TOKEN` (or `ANTHROPIC_FOUNDRY_API_KEY` when `ANTHROPIC_MODEL_CODE_USE_FOUNDRY=true`) |
938
+ | Google | `GEMINI_API_KEY` |
939
+ | Vertex AI | `GOOGLE_CLOUD_PROJECT` (or `GCLOUD_PROJECT`) + `GOOGLE_CLOUD_LOCATION` + ADC |
940
+ | Mistral | `MISTRAL_API_KEY` |
941
+ | Groq | `GROQ_API_KEY` |
942
+ | Cerebras | `CEREBRAS_API_KEY` |
943
+ | Together | `TOGETHER_API_KEY` |
944
+ | Qianfan | `QIANFAN_API_KEY` |
945
+ | Hugging Face | `HUGGINGFACE_HUB_TOKEN` or `HF_TOKEN` |
946
+ | Synthetic | `SYNTHETIC_API_KEY` |
947
+ | NVIDIA | `NVIDIA_API_KEY` |
948
+ | NanoGPT | `NANO_GPT_API_KEY` |
949
+ | Venice | `VENICE_API_KEY` |
950
+ | Moonshot | `MOONSHOT_API_KEY` |
951
+ | xAI | `XAI_API_KEY` |
952
+ | OpenRouter | `OPENROUTER_API_KEY` |
953
+ | LiteLLM | `LITELLM_API_KEY` |
954
+ | Ollama | `OLLAMA_API_KEY` (optional for local deployments) |
955
+ | Ollama Cloud | `OLLAMA_CLOUD_API_KEY` |
956
+ | Qwen Portal | `QWEN_OAUTH_TOKEN` or `QWEN_PORTAL_API_KEY` |
957
+ | zAI | `ZAI_API_KEY` |
958
+ | MiniMax Code | `MINIMAX_CODE_API_KEY` (international) or `MINIMAX_CODE_CN_API_KEY` (China) |
959
+ | Xiaomi MiMo | `XIAOMI_API_KEY` |
960
+ | ZenMux | `ZENMUX_API_KEY` |
961
+ | OpenGateway | `OPENGATEWAY_API_KEY` |
962
+ | BizRouter | `BIZROUTER_API_KEY` |
963
+ | Mara Cloud | `MARA_API_KEY` |
964
+ | vLLM | `VLLM_API_KEY` |
965
+ | Cloudflare AI Gateway | `CLOUDFLARE_AI_GATEWAY_API_KEY` |
966
+ | GitHub Copilot | `COPILOT_GITHUB_TOKEN` or `GH_TOKEN` or `GITHUB_TOKEN` |
967
+
968
+ For Cloudflare AI Gateway models, use provider base URL format
969
+ `https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/anthropic`.
970
+
971
+ For Anthropic Foundry routing, set `ANTHROPIC_MODEL_CODE_USE_FOUNDRY=true` plus:
972
+ `FOUNDRY_BASE_URL`, `ANTHROPIC_FOUNDRY_API_KEY`, optional `ANTHROPIC_CUSTOM_HEADERS`,
973
+ and optional mTLS material (`ANTHROPIC_MODEL_CODE_CLIENT_CERT`, `ANTHROPIC_MODEL_CODE_CLIENT_KEY`, `NODE_EXTRA_CA_CERTS`).
974
+
975
+ Provider endpoint defaults for the current OpenAI-compatible integrations:
976
+
977
+ - Together: `https://api.together.xyz/v1`
978
+ - Moonshot: `https://api.moonshot.ai/v1`
979
+ - Qianfan: `https://qianfan.baidubce.com/v2`
980
+ - NVIDIA: `https://integrate.api.nvidia.com/v1`
981
+ - NanoGPT: `https://nano-gpt.com/api/v1`
982
+ - Hugging Face Inference: `https://router.huggingface.co/v1`
983
+ - Venice: `https://api.venice.ai/api/v1`
984
+ - Xiaomi MiMo: `https://api.xiaomimimo.com/anthropic`
985
+ - ZenMux (OpenAI): `https://zenmux.ai/api/v1`
986
+ - ZenMux (Anthropic models): `https://zenmux.ai/api/anthropic`
987
+ - OpenGateway by Sionic AI: `https://apis.opengateway.ai/v1`
988
+ - BizRouter: `https://api.bizrouter.ai/v1`
989
+ - Mara Cloud: `https://api.cloud.mara.com/v1`
990
+ - vLLM: `http://127.0.0.1:8000/v1`
991
+ - Ollama: local OpenAI-compatible runtime (`http://127.0.0.1:11434/v1`)
992
+ - Ollama Cloud: native Ollama API host (`https://ollama.com/api`, configured here as base URL `https://ollama.com`)
993
+ - LiteLLM: `http://localhost:4000/v1`
994
+ - Cloudflare AI Gateway: `https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/anthropic`
995
+ - Qwen Portal: `https://portal.qwen.ai/v1`
996
+ When set, the library automatically uses these keys:
997
+
998
+ ```typescript
999
+ // Uses OPENAI_API_KEY from environment
1000
+ const model = getModel("openai", "gpt-4o-mini");
1001
+ const response = await complete(model, context);
1002
+
1003
+ // Or override with explicit key
1004
+ const response = await complete(model, context, {
1005
+ apiKey: "sk-different-key",
1006
+ });
1007
+ ```
1008
+
1009
+ ### Checking Environment Variables
1010
+
1011
+ ```typescript
1012
+ import { getEnvApiKey } from "@vib-rato/ai";
1013
+
1014
+ // Check if an API key is set in environment variables
1015
+ const key = getEnvApiKey("openai"); // checks OPENAI_API_KEY
1016
+ ```
1017
+
1018
+ ## OAuth Providers
1019
+
1020
+ Several providers support OAuth authentication (some also support static API keys):
1021
+
1022
+ - **Anthropic** (Anthropic model Pro/Max subscription)
1023
+ - **OpenAI code provider** (ChatGPT Plus/Pro subscription, access to GPT-5.x OpenAI code models)
1024
+ - **GitHub Copilot** (Copilot subscription)
1025
+ - **Google Gemini CLI** (Gemini 2.0/2.5 via Google Cloud Code Assist; free tier or paid subscription)
1026
+ - **Antigravity** (Free Gemini 3, Anthropic model, GPT-OSS via Google Cloud)
1027
+ - **Qwen Portal** (Qwen OAuth token or API key)
1028
+ - **xAI** (Grok OAuth login via xAI account)
1029
+
1030
+ For paid Cloud Code Assist subscriptions, set `GOOGLE_CLOUD_PROJECT` or `GOOGLE_CLOUD_PROJECT_ID` to your project ID.
1031
+
1032
+ ### Vertex AI (ADC)
1033
+
1034
+ Vertex AI models use Application Default Credentials (ADC):
1035
+
1036
+ - **Local development**: Run `gcloud auth application-default login`
1037
+ - **CI/Production**: Set `GOOGLE_APPLICATION_CREDENTIALS` to point to a service account JSON key file
1038
+
1039
+ Also set `GOOGLE_CLOUD_PROJECT` (or `GCLOUD_PROJECT`) and `GOOGLE_CLOUD_LOCATION`. You can also pass `project`/`location` in the call options.
1040
+
1041
+ Example:
1042
+
1043
+ ```bash
1044
+ # Local (uses your user credentials)
1045
+ gcloud auth application-default login
1046
+ export GOOGLE_CLOUD_PROJECT="my-project"
1047
+ export GOOGLE_CLOUD_LOCATION="us-central1"
1048
+
1049
+ # CI/Production (service account key file)
1050
+ export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
1051
+ ```
1052
+
1053
+ ```typescript
1054
+ import { getModel, complete } from "@vib-rato/ai";
1055
+
1056
+ (async () => {
1057
+ const model = getModel("google-vertex", "gemini-2.5-flash");
1058
+ const response = await complete(model, {
1059
+ messages: [{ role: "user", content: "Hello from Vertex AI" }],
1060
+ });
1061
+
1062
+ for (const block of response.content) {
1063
+ if (block.type === "text") console.log(block.text);
1064
+ }
1065
+ })().catch(console.error);
1066
+ ```
1067
+
1068
+ Official docs: [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials)
1069
+
1070
+ ### CLI Login
1071
+
1072
+ The quickest way to authenticate:
1073
+
1074
+ ```bash
1075
+ bunx @vib-rato/ai login # interactive provider selection
1076
+ bunx @vib-rato/ai login anthropic # login to specific provider
1077
+ bunx @vib-rato/ai login vllm # store vLLM API key (local no-auth servers are discovered automatically)
1078
+ bunx @vib-rato/ai login xai # sign in with xAI/Grok OAuth
1079
+ bunx @vib-rato/ai list # list available providers
1080
+ ```
1081
+
1082
+ Credentials are saved to `agent.db` in the agent directory. `/login qianfan` opens the Qianfan console and stores the pasted API key; `/login xai` opens xAI/Grok OAuth login and stores refreshable OAuth credentials.
1083
+
1084
+ `login` supports OAuth providers (Anthropic, OpenAI code provider, GitHub Copilot, Gemini CLI, Antigravity, xAI) and API-key onboarding flows.
1085
+
1086
+ For the current API-key onboarding flows, the library covers Together, Moonshot, Qianfan, NVIDIA, NanoGPT, Hugging Face, Venice, Xiaomi, vLLM, LiteLLM, Cloudflare AI Gateway, Qwen Portal, and Ollama Cloud. Ollama remains the local runtime integration; set `OLLAMA_API_KEY` only when your local or self-hosted deployment enforces bearer auth.
1087
+
1088
+ ### Programmatic OAuth
1089
+
1090
+ The library provides login and token refresh functions. Credential storage is the caller's responsibility.
1091
+
1092
+ ```typescript
1093
+ import {
1094
+ // Login functions (return credentials, do not store)
1095
+ loginAnthropic,
1096
+ loginOpenAIOpenAI code,
1097
+ loginGitHubCopilot,
1098
+ loginGeminiCli,
1099
+ loginAntigravity,
1100
+ loginCloudflareAiGateway,
1101
+ loginHuggingface,
1102
+ loginLiteLLM,
1103
+ loginMoonshot,
1104
+ loginNvidia,
1105
+ loginNanoGPT,
1106
+ loginQianfan,
1107
+ loginQwenPortal,
1108
+ loginTogether,
1109
+ loginVenice,
1110
+ loginVllm,
1111
+ loginXiaomi,
1112
+
1113
+ // Token management
1114
+ refreshOAuthToken, // (provider, credentials) => new credentials
1115
+ getOAuthApiKey, // (provider, credentialsMap) => { newCredentials, apiKey } | null
1116
+
1117
+ // Types
1118
+ type OAuthProvider, // includes 'anthropic', 'openai-code', 'github-copilot', 'google-gemini-cli', 'google-antigravity', 'together', 'moonshot', 'qianfan', 'nvidia', 'nanogpt', 'huggingface', 'venice', 'xiaomi', 'vllm', 'litellm', 'cloudflare-ai-gateway', 'qwen-portal', ...
1119
+ type OAuthCredentials,
1120
+ } from "@vib-rato/ai";
1121
+ ```
1122
+
1123
+ `loginOpenAIOpenAI code` accepts an optional `originator` value used in the OAuth flow:
1124
+
1125
+ ```typescript
1126
+ await loginOpenAIOpenAI code({
1127
+ onAuth: ({ url }) => console.log(url),
1128
+ originator: "my-cli",
1129
+ });
1130
+ ```
1131
+
1132
+ ### Login Flow Example
1133
+
1134
+ ```typescript
1135
+ import { loginGitHubCopilot } from "@vib-rato/ai";
1136
+ import * as fs from "node:fs";
1137
+
1138
+ const credentials = await loginGitHubCopilot({
1139
+ onAuth: (url, instructions) => {
1140
+ console.log(`Open: ${url}`);
1141
+ if (instructions) console.log(instructions);
1142
+ },
1143
+ onPrompt: async (prompt) => {
1144
+ return await getUserInput(prompt.message);
1145
+ },
1146
+ onProgress: (message) => console.log(message),
1147
+ });
1148
+
1149
+ // Store credentials yourself
1150
+ const auth = { "github-copilot": { type: "oauth", ...credentials } };
1151
+ fs.writeFileSync("credentials.json", JSON.stringify(auth, null, 2));
1152
+ ```
1153
+
1154
+ ### Using OAuth Tokens
1155
+
1156
+ Use `getOAuthApiKey()` to get an API key, automatically refreshing if expired:
1157
+
1158
+ ```typescript
1159
+ import { getModel, complete, getOAuthApiKey } from "@vib-rato/ai";
1160
+ import * as fs from "node:fs";
1161
+
1162
+ // Load your stored credentials
1163
+ const auth = JSON.parse(fs.readFileSync("credentials.json", "utf-8"));
1164
+
1165
+ // Get API key (refreshes if expired)
1166
+ const result = await getOAuthApiKey("github-copilot", auth);
1167
+ if (!result) throw new Error("Not logged in");
1168
+
1169
+ // Save refreshed credentials
1170
+ auth["github-copilot"] = { type: "oauth", ...result.newCredentials };
1171
+ fs.writeFileSync("credentials.json", JSON.stringify(auth, null, 2));
1172
+
1173
+ // Use the API key
1174
+ const model = getModel("github-copilot", "gpt-4o");
1175
+ const response = await complete(
1176
+ model,
1177
+ {
1178
+ messages: [{ role: "user", content: "Hello!" }],
1179
+ },
1180
+ { apiKey: result.apiKey }
1181
+ );
1182
+ ```
1183
+
1184
+ ### Provider Notes
1185
+
1186
+ **OpenAI code provider**: Requires a ChatGPT Plus or Pro subscription. Provides access to GPT-5.x OpenAI code models with extended context windows and reasoning capabilities. The library automatically handles session-based prompt caching when `sessionId` is provided in stream options.
1187
+
1188
+ **GitHub Copilot**: If you get "The requested model is not supported" error, enable the model manually in VS Code: open Copilot Chat, click the model selector, select the model (warning icon), and click "Enable".
1189
+
1190
+ **Google Gemini CLI / Antigravity**: These use Google Cloud OAuth. The `apiKey` returned by `getOAuthApiKey()` is a JSON string containing both the token and project ID, which the library handles automatically.
1191
+
1192
+ ## License
1193
+
1194
+ MIT