@aryee337/aery-ai 0.2.28 → 0.2.29

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 (417) hide show
  1. package/CHANGELOG.md +2914 -0
  2. package/README.md +614 -813
  3. package/package.json +140 -105
  4. package/src/api-registry.ts +96 -0
  5. package/src/auth-broker/client.ts +358 -0
  6. package/src/auth-broker/index.ts +5 -0
  7. package/src/auth-broker/refresher.ts +117 -0
  8. package/src/auth-broker/remote-store.ts +623 -0
  9. package/src/auth-broker/server.ts +644 -0
  10. package/src/auth-broker/types.ts +127 -0
  11. package/src/auth-broker/wire-schemas.ts +200 -0
  12. package/src/auth-gateway/http.ts +194 -0
  13. package/src/auth-gateway/index.ts +3 -0
  14. package/src/auth-gateway/server.ts +818 -0
  15. package/src/auth-gateway/types.ts +143 -0
  16. package/src/auth-storage.ts +4422 -0
  17. package/src/index.ts +54 -0
  18. package/src/model-cache.ts +129 -0
  19. package/src/model-manager.ts +469 -0
  20. package/src/model-thinking.ts +782 -0
  21. package/src/models.json +83530 -0
  22. package/src/models.json.d.ts +9 -0
  23. package/src/models.ts +56 -0
  24. package/src/prompts/turn-aborted-guidance.md +4 -0
  25. package/src/provider-details.ts +90 -0
  26. package/src/provider-models/bundled-references.ts +38 -0
  27. package/src/provider-models/descriptors.ts +355 -0
  28. package/src/provider-models/google.ts +88 -0
  29. package/src/provider-models/index.ts +5 -0
  30. package/src/provider-models/ollama.ts +153 -0
  31. package/src/provider-models/openai-compat.ts +2817 -0
  32. package/src/provider-models/special.ts +67 -0
  33. package/src/providers/aery-native-client.ts +228 -0
  34. package/src/providers/aery-native-server.ts +212 -0
  35. package/src/providers/amazon-bedrock.ts +873 -0
  36. package/src/providers/anthropic-client.ts +318 -0
  37. package/src/providers/anthropic-messages-server-schema.ts +243 -0
  38. package/src/providers/anthropic-messages-server.ts +683 -0
  39. package/src/providers/anthropic-wire.ts +268 -0
  40. package/src/providers/anthropic.ts +3094 -0
  41. package/src/providers/aws-credentials.ts +501 -0
  42. package/src/providers/aws-eventstream.ts +185 -0
  43. package/src/providers/aws-sigv4.ts +218 -0
  44. package/src/providers/azure-openai-responses.ts +361 -0
  45. package/src/providers/cursor/gen/agent_pb.ts +15274 -0
  46. package/src/providers/cursor/proto/agent.proto +3526 -0
  47. package/src/providers/cursor/proto/buf.gen.yaml +6 -0
  48. package/src/providers/cursor/proto/buf.yaml +17 -0
  49. package/src/providers/cursor.ts +2621 -0
  50. package/src/providers/error-message.ts +21 -0
  51. package/src/providers/github-copilot-headers.ts +140 -0
  52. package/src/providers/gitlab-duo.ts +372 -0
  53. package/src/providers/google-auth.ts +252 -0
  54. package/src/providers/google-gemini-cli.ts +809 -0
  55. package/src/providers/google-gemini-headers.ts +41 -0
  56. package/src/providers/google-shared.ts +917 -0
  57. package/src/providers/google-types.ts +167 -0
  58. package/src/providers/google-vertex.ts +91 -0
  59. package/src/providers/google.ts +41 -0
  60. package/src/providers/grammar.ts +70 -0
  61. package/src/providers/kimi.ts +52 -0
  62. package/src/providers/mock.ts +496 -0
  63. package/src/providers/ollama.ts +644 -0
  64. package/src/providers/openai-anthropic-shim.ts +138 -0
  65. package/src/providers/openai-chat-server-schema.ts +252 -0
  66. package/src/providers/openai-chat-server.ts +647 -0
  67. package/src/providers/openai-codex/constants.ts +43 -0
  68. package/src/providers/openai-codex/request-transformer.ts +161 -0
  69. package/src/providers/openai-codex/response-handler.ts +81 -0
  70. package/src/providers/openai-codex-responses.ts +3018 -0
  71. package/src/providers/openai-completions-compat.ts +300 -0
  72. package/src/providers/openai-completions.ts +1979 -0
  73. package/src/providers/openai-responses-server-schema.ts +290 -0
  74. package/src/providers/openai-responses-server.ts +1183 -0
  75. package/src/providers/openai-responses-shared.ts +873 -0
  76. package/src/providers/openai-responses.ts +679 -0
  77. package/src/providers/register-builtins.ts +436 -0
  78. package/src/providers/synthetic.ts +50 -0
  79. package/src/providers/transform-messages.ts +382 -0
  80. package/src/providers/vision-guard.ts +31 -0
  81. package/src/providers/xai-responses.ts +82 -0
  82. package/src/rate-limit-utils.ts +84 -0
  83. package/src/stream.ts +1065 -0
  84. package/src/types.ts +944 -0
  85. package/src/usage/claude.ts +482 -0
  86. package/src/usage/gemini.ts +250 -0
  87. package/src/usage/github-copilot.ts +421 -0
  88. package/src/usage/google-antigravity.ts +201 -0
  89. package/src/usage/kimi.ts +271 -0
  90. package/src/usage/minimax-code.ts +31 -0
  91. package/src/usage/openai-codex.ts +503 -0
  92. package/src/usage/shared.ts +10 -0
  93. package/src/usage/zai.ts +247 -0
  94. package/src/usage.ts +185 -0
  95. package/src/utils/abort.ts +51 -0
  96. package/src/utils/abortable-iterator.ts +69 -0
  97. package/src/utils/anthropic-auth.ts +93 -0
  98. package/src/utils/discovery/antigravity.ts +261 -0
  99. package/src/utils/discovery/codex.ts +371 -0
  100. package/src/utils/discovery/cursor.ts +306 -0
  101. package/src/utils/discovery/gemini.ts +248 -0
  102. package/src/utils/discovery/index.ts +4 -0
  103. package/src/utils/discovery/openai-compatible.ts +224 -0
  104. package/src/utils/event-stream.ts +142 -0
  105. package/src/utils/fireworks-model-id.ts +30 -0
  106. package/src/utils/foundry.ts +8 -0
  107. package/src/utils/http-inspector.ts +176 -0
  108. package/src/utils/idle-iterator.ts +267 -0
  109. package/src/utils/json-parse.ts +182 -0
  110. package/src/utils/oauth/__tests__/xai-oauth.test.ts +107 -0
  111. package/src/utils/oauth/alibaba-coding-plan.ts +59 -0
  112. package/src/utils/oauth/anthropic.ts +273 -0
  113. package/src/utils/oauth/api-key-login.ts +87 -0
  114. package/src/utils/oauth/api-key-validation.ts +92 -0
  115. package/src/utils/oauth/callback-server.ts +276 -0
  116. package/src/utils/oauth/cerebras.ts +16 -0
  117. package/src/utils/oauth/cloudflare-ai-gateway.ts +48 -0
  118. package/src/utils/oauth/cursor.ts +157 -0
  119. package/src/utils/oauth/deepseek.ts +53 -0
  120. package/src/utils/oauth/firepass.ts +24 -0
  121. package/src/utils/oauth/fireworks.ts +15 -0
  122. package/src/utils/oauth/github-copilot.ts +362 -0
  123. package/src/utils/oauth/gitlab-duo.ts +123 -0
  124. package/src/utils/oauth/google-antigravity.ts +200 -0
  125. package/src/utils/oauth/google-gemini-cli.ts +256 -0
  126. package/src/utils/oauth/google-oauth-shared.ts +110 -0
  127. package/src/utils/oauth/huggingface.ts +62 -0
  128. package/src/utils/oauth/index.ts +484 -0
  129. package/src/utils/oauth/kagi.ts +47 -0
  130. package/src/utils/oauth/kilo.ts +87 -0
  131. package/src/utils/oauth/kimi.ts +254 -0
  132. package/src/utils/oauth/litellm.ts +47 -0
  133. package/src/utils/oauth/lm-studio.ts +38 -0
  134. package/src/utils/oauth/minimax-code.ts +78 -0
  135. package/src/utils/oauth/moonshot.ts +23 -0
  136. package/src/utils/oauth/nanogpt.ts +15 -0
  137. package/src/utils/oauth/nvidia.ts +70 -0
  138. package/src/utils/oauth/oauth.html +203 -0
  139. package/src/utils/oauth/ollama-cloud.ts +28 -0
  140. package/src/utils/oauth/ollama.ts +47 -0
  141. package/src/utils/oauth/openai-codex.ts +299 -0
  142. package/src/utils/oauth/opencode.ts +49 -0
  143. package/src/utils/oauth/openrouter.ts +20 -0
  144. package/src/utils/oauth/parallel.ts +46 -0
  145. package/src/utils/oauth/perplexity.ts +206 -0
  146. package/src/utils/oauth/pkce.ts +18 -0
  147. package/src/utils/oauth/qianfan.ts +58 -0
  148. package/src/utils/oauth/qwen-portal.ts +60 -0
  149. package/src/utils/oauth/synthetic.ts +15 -0
  150. package/src/utils/oauth/tavily.ts +46 -0
  151. package/src/utils/oauth/together.ts +16 -0
  152. package/src/utils/oauth/types.ts +99 -0
  153. package/src/utils/oauth/venice.ts +59 -0
  154. package/src/utils/oauth/vercel-ai-gateway.ts +47 -0
  155. package/src/utils/oauth/vllm.ts +40 -0
  156. package/src/utils/oauth/wafer.ts +50 -0
  157. package/src/utils/oauth/xai-oauth.ts +342 -0
  158. package/src/utils/oauth/xiaomi.ts +139 -0
  159. package/src/utils/oauth/zai.ts +60 -0
  160. package/src/utils/oauth/zenmux.ts +15 -0
  161. package/src/utils/oauth/zhipu.ts +60 -0
  162. package/src/utils/overflow.ts +137 -0
  163. package/src/utils/parse-bind.ts +54 -0
  164. package/src/utils/provider-response.ts +30 -0
  165. package/src/utils/request-debug.ts +336 -0
  166. package/src/utils/retry-after.ts +110 -0
  167. package/src/utils/retry.ts +54 -0
  168. package/src/utils/schema/CONSTRAINTS.md +164 -0
  169. package/src/utils/schema/adapt.ts +36 -0
  170. package/src/utils/schema/compatibility.ts +435 -0
  171. package/src/utils/schema/dereference.ts +98 -0
  172. package/src/utils/schema/draft.ts +341 -0
  173. package/src/utils/schema/equality.ts +97 -0
  174. package/src/utils/schema/fields.ts +191 -0
  175. package/src/utils/schema/index.ts +13 -0
  176. package/src/utils/schema/json-schema-validator.ts +577 -0
  177. package/src/utils/schema/meta-validator.ts +167 -0
  178. package/src/utils/schema/normalize.ts +1588 -0
  179. package/src/utils/schema/spill.ts +43 -0
  180. package/src/utils/schema/stamps.ts +97 -0
  181. package/src/utils/schema/types.ts +10 -0
  182. package/src/utils/schema/wire.ts +293 -0
  183. package/src/utils/schema/zod-decontaminate.ts +331 -0
  184. package/src/utils/sdk-stream-timeout.ts +43 -0
  185. package/src/utils/sse-debug.ts +289 -0
  186. package/src/utils/stream-markup-healing.ts +612 -0
  187. package/src/utils/tool-choice.ts +99 -0
  188. package/src/utils/validation.ts +1024 -0
  189. package/src/utils.ts +166 -0
  190. package/dist/api-registry.d.ts +0 -20
  191. package/dist/api-registry.d.ts.map +0 -1
  192. package/dist/api-registry.js +0 -44
  193. package/dist/api-registry.js.map +0 -1
  194. package/dist/bedrock-provider.d.ts +0 -5
  195. package/dist/bedrock-provider.d.ts.map +0 -1
  196. package/dist/bedrock-provider.js +0 -6
  197. package/dist/bedrock-provider.js.map +0 -1
  198. package/dist/cli.d.ts +0 -3
  199. package/dist/cli.d.ts.map +0 -1
  200. package/dist/cli.js +0 -130
  201. package/dist/cli.js.map +0 -1
  202. package/dist/env-api-keys.d.ts +0 -18
  203. package/dist/env-api-keys.d.ts.map +0 -1
  204. package/dist/env-api-keys.js +0 -178
  205. package/dist/env-api-keys.js.map +0 -1
  206. package/dist/image-models.d.ts +0 -10
  207. package/dist/image-models.d.ts.map +0 -1
  208. package/dist/image-models.generated.d.ts +0 -440
  209. package/dist/image-models.generated.d.ts.map +0 -1
  210. package/dist/image-models.generated.js +0 -442
  211. package/dist/image-models.generated.js.map +0 -1
  212. package/dist/image-models.js +0 -23
  213. package/dist/image-models.js.map +0 -1
  214. package/dist/images-api-registry.d.ts +0 -14
  215. package/dist/images-api-registry.d.ts.map +0 -1
  216. package/dist/images-api-registry.js +0 -22
  217. package/dist/images-api-registry.js.map +0 -1
  218. package/dist/images.d.ts +0 -4
  219. package/dist/images.d.ts.map +0 -1
  220. package/dist/images.js +0 -14
  221. package/dist/images.js.map +0 -1
  222. package/dist/index.d.ts +0 -32
  223. package/dist/index.d.ts.map +0 -1
  224. package/dist/index.js +0 -20
  225. package/dist/index.js.map +0 -1
  226. package/dist/models.d.ts +0 -18
  227. package/dist/models.d.ts.map +0 -1
  228. package/dist/models.generated.d.ts +0 -17707
  229. package/dist/models.generated.d.ts.map +0 -1
  230. package/dist/models.generated.js +0 -16561
  231. package/dist/models.generated.js.map +0 -1
  232. package/dist/models.js +0 -71
  233. package/dist/models.js.map +0 -1
  234. package/dist/oauth.d.ts +0 -2
  235. package/dist/oauth.d.ts.map +0 -1
  236. package/dist/oauth.js +0 -2
  237. package/dist/oauth.js.map +0 -1
  238. package/dist/providers/aery-error-formatting.d.ts +0 -13
  239. package/dist/providers/aery-error-formatting.d.ts.map +0 -1
  240. package/dist/providers/aery-error-formatting.js +0 -112
  241. package/dist/providers/aery-error-formatting.js.map +0 -1
  242. package/dist/providers/amazon-bedrock.d.ts +0 -38
  243. package/dist/providers/amazon-bedrock.d.ts.map +0 -1
  244. package/dist/providers/amazon-bedrock.js +0 -763
  245. package/dist/providers/amazon-bedrock.js.map +0 -1
  246. package/dist/providers/anthropic.d.ts +0 -71
  247. package/dist/providers/anthropic.d.ts.map +0 -1
  248. package/dist/providers/anthropic.js +0 -949
  249. package/dist/providers/anthropic.js.map +0 -1
  250. package/dist/providers/azure-openai-responses.d.ts +0 -15
  251. package/dist/providers/azure-openai-responses.d.ts.map +0 -1
  252. package/dist/providers/azure-openai-responses.js +0 -225
  253. package/dist/providers/azure-openai-responses.js.map +0 -1
  254. package/dist/providers/cloudflare.d.ts +0 -13
  255. package/dist/providers/cloudflare.d.ts.map +0 -1
  256. package/dist/providers/cloudflare.js +0 -26
  257. package/dist/providers/cloudflare.js.map +0 -1
  258. package/dist/providers/faux.d.ts +0 -56
  259. package/dist/providers/faux.d.ts.map +0 -1
  260. package/dist/providers/faux.js +0 -368
  261. package/dist/providers/faux.js.map +0 -1
  262. package/dist/providers/github-copilot-headers.d.ts +0 -8
  263. package/dist/providers/github-copilot-headers.d.ts.map +0 -1
  264. package/dist/providers/github-copilot-headers.js +0 -29
  265. package/dist/providers/github-copilot-headers.js.map +0 -1
  266. package/dist/providers/google-gemini-cli.d.ts +0 -74
  267. package/dist/providers/google-gemini-cli.d.ts.map +0 -1
  268. package/dist/providers/google-gemini-cli.js +0 -779
  269. package/dist/providers/google-gemini-cli.js.map +0 -1
  270. package/dist/providers/google-shared.d.ts +0 -70
  271. package/dist/providers/google-shared.d.ts.map +0 -1
  272. package/dist/providers/google-shared.js +0 -329
  273. package/dist/providers/google-shared.js.map +0 -1
  274. package/dist/providers/google-vertex.d.ts +0 -15
  275. package/dist/providers/google-vertex.d.ts.map +0 -1
  276. package/dist/providers/google-vertex.js +0 -442
  277. package/dist/providers/google-vertex.js.map +0 -1
  278. package/dist/providers/google.d.ts +0 -13
  279. package/dist/providers/google.d.ts.map +0 -1
  280. package/dist/providers/google.js +0 -400
  281. package/dist/providers/google.js.map +0 -1
  282. package/dist/providers/images/openrouter.d.ts +0 -3
  283. package/dist/providers/images/openrouter.d.ts.map +0 -1
  284. package/dist/providers/images/openrouter.js +0 -129
  285. package/dist/providers/images/openrouter.js.map +0 -1
  286. package/dist/providers/images/register-builtins.d.ts +0 -4
  287. package/dist/providers/images/register-builtins.d.ts.map +0 -1
  288. package/dist/providers/images/register-builtins.js +0 -34
  289. package/dist/providers/images/register-builtins.js.map +0 -1
  290. package/dist/providers/mistral.d.ts +0 -25
  291. package/dist/providers/mistral.d.ts.map +0 -1
  292. package/dist/providers/mistral.js +0 -535
  293. package/dist/providers/mistral.js.map +0 -1
  294. package/dist/providers/openai-codex-responses.d.ts +0 -30
  295. package/dist/providers/openai-codex-responses.d.ts.map +0 -1
  296. package/dist/providers/openai-codex-responses.js +0 -1090
  297. package/dist/providers/openai-codex-responses.js.map +0 -1
  298. package/dist/providers/openai-completions.d.ts +0 -19
  299. package/dist/providers/openai-completions.d.ts.map +0 -1
  300. package/dist/providers/openai-completions.js +0 -950
  301. package/dist/providers/openai-completions.js.map +0 -1
  302. package/dist/providers/openai-prompt-cache.d.ts +0 -3
  303. package/dist/providers/openai-prompt-cache.d.ts.map +0 -1
  304. package/dist/providers/openai-prompt-cache.js +0 -10
  305. package/dist/providers/openai-prompt-cache.js.map +0 -1
  306. package/dist/providers/openai-responses-shared.d.ts +0 -18
  307. package/dist/providers/openai-responses-shared.d.ts.map +0 -1
  308. package/dist/providers/openai-responses-shared.js +0 -492
  309. package/dist/providers/openai-responses-shared.js.map +0 -1
  310. package/dist/providers/openai-responses.d.ts +0 -13
  311. package/dist/providers/openai-responses.d.ts.map +0 -1
  312. package/dist/providers/openai-responses.js +0 -237
  313. package/dist/providers/openai-responses.js.map +0 -1
  314. package/dist/providers/register-builtins.d.ts +0 -38
  315. package/dist/providers/register-builtins.d.ts.map +0 -1
  316. package/dist/providers/register-builtins.js +0 -278
  317. package/dist/providers/register-builtins.js.map +0 -1
  318. package/dist/providers/simple-options.d.ts +0 -8
  319. package/dist/providers/simple-options.d.ts.map +0 -1
  320. package/dist/providers/simple-options.js +0 -41
  321. package/dist/providers/simple-options.js.map +0 -1
  322. package/dist/providers/transform-messages.d.ts +0 -8
  323. package/dist/providers/transform-messages.d.ts.map +0 -1
  324. package/dist/providers/transform-messages.js +0 -184
  325. package/dist/providers/transform-messages.js.map +0 -1
  326. package/dist/session-resources.d.ts +0 -4
  327. package/dist/session-resources.d.ts.map +0 -1
  328. package/dist/session-resources.js +0 -22
  329. package/dist/session-resources.js.map +0 -1
  330. package/dist/stream.d.ts +0 -8
  331. package/dist/stream.d.ts.map +0 -1
  332. package/dist/stream.js +0 -27
  333. package/dist/stream.js.map +0 -1
  334. package/dist/types.d.ts +0 -498
  335. package/dist/types.d.ts.map +0 -1
  336. package/dist/types.js +0 -2
  337. package/dist/types.js.map +0 -1
  338. package/dist/utils/diagnostics.d.ts +0 -19
  339. package/dist/utils/diagnostics.d.ts.map +0 -1
  340. package/dist/utils/diagnostics.js +0 -25
  341. package/dist/utils/diagnostics.js.map +0 -1
  342. package/dist/utils/event-stream.d.ts +0 -21
  343. package/dist/utils/event-stream.d.ts.map +0 -1
  344. package/dist/utils/event-stream.js +0 -81
  345. package/dist/utils/event-stream.js.map +0 -1
  346. package/dist/utils/hash.d.ts +0 -3
  347. package/dist/utils/hash.d.ts.map +0 -1
  348. package/dist/utils/hash.js +0 -14
  349. package/dist/utils/hash.js.map +0 -1
  350. package/dist/utils/headers.d.ts +0 -2
  351. package/dist/utils/headers.d.ts.map +0 -1
  352. package/dist/utils/headers.js +0 -8
  353. package/dist/utils/headers.js.map +0 -1
  354. package/dist/utils/json-parse.d.ts +0 -16
  355. package/dist/utils/json-parse.d.ts.map +0 -1
  356. package/dist/utils/json-parse.js +0 -113
  357. package/dist/utils/json-parse.js.map +0 -1
  358. package/dist/utils/node-http-proxy.d.ts +0 -10
  359. package/dist/utils/node-http-proxy.d.ts.map +0 -1
  360. package/dist/utils/node-http-proxy.js +0 -97
  361. package/dist/utils/node-http-proxy.js.map +0 -1
  362. package/dist/utils/oauth/anthropic.d.ts +0 -25
  363. package/dist/utils/oauth/anthropic.d.ts.map +0 -1
  364. package/dist/utils/oauth/anthropic.js +0 -335
  365. package/dist/utils/oauth/anthropic.js.map +0 -1
  366. package/dist/utils/oauth/device-code.d.ts +0 -19
  367. package/dist/utils/oauth/device-code.d.ts.map +0 -1
  368. package/dist/utils/oauth/device-code.js +0 -55
  369. package/dist/utils/oauth/device-code.js.map +0 -1
  370. package/dist/utils/oauth/github-copilot.d.ts +0 -30
  371. package/dist/utils/oauth/github-copilot.d.ts.map +0 -1
  372. package/dist/utils/oauth/github-copilot.js +0 -268
  373. package/dist/utils/oauth/github-copilot.js.map +0 -1
  374. package/dist/utils/oauth/google-antigravity.d.ts +0 -26
  375. package/dist/utils/oauth/google-antigravity.d.ts.map +0 -1
  376. package/dist/utils/oauth/google-antigravity.js +0 -377
  377. package/dist/utils/oauth/google-antigravity.js.map +0 -1
  378. package/dist/utils/oauth/google-gemini-cli.d.ts +0 -26
  379. package/dist/utils/oauth/google-gemini-cli.d.ts.map +0 -1
  380. package/dist/utils/oauth/google-gemini-cli.js +0 -482
  381. package/dist/utils/oauth/google-gemini-cli.js.map +0 -1
  382. package/dist/utils/oauth/index.d.ts +0 -63
  383. package/dist/utils/oauth/index.d.ts.map +0 -1
  384. package/dist/utils/oauth/index.js +0 -131
  385. package/dist/utils/oauth/index.js.map +0 -1
  386. package/dist/utils/oauth/oauth-page.d.ts +0 -3
  387. package/dist/utils/oauth/oauth-page.d.ts.map +0 -1
  388. package/dist/utils/oauth/oauth-page.js +0 -105
  389. package/dist/utils/oauth/oauth-page.js.map +0 -1
  390. package/dist/utils/oauth/openai-codex.d.ts +0 -34
  391. package/dist/utils/oauth/openai-codex.d.ts.map +0 -1
  392. package/dist/utils/oauth/openai-codex.js +0 -385
  393. package/dist/utils/oauth/openai-codex.js.map +0 -1
  394. package/dist/utils/oauth/pkce.d.ts +0 -13
  395. package/dist/utils/oauth/pkce.d.ts.map +0 -1
  396. package/dist/utils/oauth/pkce.js +0 -31
  397. package/dist/utils/oauth/pkce.js.map +0 -1
  398. package/dist/utils/oauth/types.d.ts +0 -64
  399. package/dist/utils/oauth/types.d.ts.map +0 -1
  400. package/dist/utils/oauth/types.js +0 -2
  401. package/dist/utils/oauth/types.js.map +0 -1
  402. package/dist/utils/overflow.d.ts +0 -56
  403. package/dist/utils/overflow.d.ts.map +0 -1
  404. package/dist/utils/overflow.js +0 -151
  405. package/dist/utils/overflow.js.map +0 -1
  406. package/dist/utils/sanitize-unicode.d.ts +0 -22
  407. package/dist/utils/sanitize-unicode.d.ts.map +0 -1
  408. package/dist/utils/sanitize-unicode.js +0 -26
  409. package/dist/utils/sanitize-unicode.js.map +0 -1
  410. package/dist/utils/typebox-helpers.d.ts +0 -17
  411. package/dist/utils/typebox-helpers.d.ts.map +0 -1
  412. package/dist/utils/typebox-helpers.js +0 -21
  413. package/dist/utils/typebox-helpers.js.map +0 -1
  414. package/dist/utils/validation.d.ts +0 -18
  415. package/dist/utils/validation.d.ts.map +0 -1
  416. package/dist/utils/validation.js +0 -281
  417. package/dist/utils/validation.js.map +0 -1
package/src/types.ts ADDED
@@ -0,0 +1,944 @@
1
+ import type { ZodType, z } from "zod/v4";
2
+ import type { BedrockOptions } from "./providers/amazon-bedrock";
3
+ import type { AnthropicOptions } from "./providers/anthropic";
4
+ import type { AzureOpenAIResponsesOptions } from "./providers/azure-openai-responses";
5
+ import type { CursorOptions } from "./providers/cursor";
6
+ import type {
7
+ DeleteArgs,
8
+ DeleteResult,
9
+ DiagnosticsArgs,
10
+ DiagnosticsResult,
11
+ GrepArgs,
12
+ GrepResult,
13
+ LsArgs,
14
+ LsResult,
15
+ McpResult,
16
+ ReadArgs,
17
+ ReadResult,
18
+ ShellArgs,
19
+ ShellResult,
20
+ WriteArgs,
21
+ WriteResult,
22
+ } from "./providers/cursor/gen/agent_pb";
23
+ import type { GoogleOptions } from "./providers/google";
24
+ import type { GoogleGeminiCliOptions } from "./providers/google-gemini-cli";
25
+ import type { GoogleVertexOptions } from "./providers/google-vertex";
26
+ import type { OllamaChatOptions } from "./providers/ollama";
27
+ import type { OpenAICodexResponsesOptions } from "./providers/openai-codex-responses";
28
+ import type { OpenAICompletionsOptions } from "./providers/openai-completions";
29
+ import type { OpenAIResponsesOptions } from "./providers/openai-responses";
30
+ import type { AssistantMessageEventStream } from "./utils/event-stream";
31
+
32
+ export type { AssistantMessageEventStream } from "./utils/event-stream";
33
+
34
+ export type KnownApi =
35
+ | "openai-completions"
36
+ | "openai-responses"
37
+ | "openai-codex-responses"
38
+ | "azure-openai-responses"
39
+ | "anthropic-messages"
40
+ | "bedrock-converse-stream"
41
+ | "google-generative-ai"
42
+ | "google-gemini-cli"
43
+ | "google-vertex"
44
+ | "ollama-chat"
45
+ | "cursor-agent";
46
+ export type Api = KnownApi | (string & {});
47
+ export interface ApiOptionsMap {
48
+ "anthropic-messages": AnthropicOptions;
49
+ "bedrock-converse-stream": BedrockOptions;
50
+ "openai-completions": OpenAICompletionsOptions;
51
+ "openai-responses": OpenAIResponsesOptions;
52
+ "openai-codex-responses": OpenAICodexResponsesOptions;
53
+ "azure-openai-responses": AzureOpenAIResponsesOptions;
54
+ "google-generative-ai": GoogleOptions;
55
+ "google-gemini-cli": GoogleGeminiCliOptions;
56
+ "google-vertex": GoogleVertexOptions;
57
+ "ollama-chat": OllamaChatOptions;
58
+ "cursor-agent": CursorOptions;
59
+ }
60
+ // Compile-time exhaustiveness check - this will fail if ApiOptionsMap doesn't have all KnownApi keys
61
+ type _CheckExhaustive =
62
+ ApiOptionsMap extends Record<KnownApi, StreamOptions>
63
+ ? Record<KnownApi, StreamOptions> extends ApiOptionsMap
64
+ ? true
65
+ : ["ApiOptionsMap is missing some KnownApi values", Exclude<KnownApi, keyof ApiOptionsMap>]
66
+ : ["ApiOptionsMap doesn't extend Record<KnownApi, StreamOptions>"];
67
+ true satisfies _CheckExhaustive;
68
+ export type OptionsForApi<TApi extends Api> =
69
+ | StreamOptions
70
+ | (TApi extends keyof ApiOptionsMap ? ApiOptionsMap[TApi] : never);
71
+
72
+ /** Canonical thinking transport used by a model. */
73
+ export type ThinkingControlMode =
74
+ | "effort"
75
+ | "budget"
76
+ | "google-level"
77
+ | "anthropic-adaptive"
78
+ | "anthropic-budget-effort";
79
+
80
+ /** Per-model thinking capabilities used to clamp and map user-facing effort levels. */
81
+ export interface ThinkingConfig {
82
+ /** Least intensive supported user-facing effort level. */
83
+ minLevel: Effort;
84
+ /** Most intensive supported user-facing effort level. */
85
+ maxLevel: Effort;
86
+ /**
87
+ * Optional explicit list of supported levels. When present, takes precedence over
88
+ * the `minLevel`..`maxLevel` range — used to encode discrete sets with gaps
89
+ * (e.g. Gemini 3 Pro supports `low` and `high` but not `medium`).
90
+ */
91
+ levels?: readonly Effort[];
92
+ /** Optional default effort applied when this model is selected. Falls back to global default if absent. */
93
+ defaultLevel?: Effort;
94
+ /** Provider-specific transport used to encode the selected effort. */
95
+ mode: ThinkingControlMode;
96
+ }
97
+
98
+ export type KnownProvider =
99
+ | "alibaba-coding-plan"
100
+ | "amazon-bedrock"
101
+ | "anthropic"
102
+ | "google"
103
+ | "google-gemini-cli"
104
+ | "google-antigravity"
105
+ | "google-vertex"
106
+ | "openai"
107
+ | "openai-codex"
108
+ | "kimi-code"
109
+ | "minimax-code"
110
+ | "minimax-code-cn"
111
+ | "github-copilot"
112
+ | "fireworks"
113
+ | "firepass"
114
+ | "gitlab-duo"
115
+ | "cursor"
116
+ | "deepseek"
117
+ | "xai"
118
+ | "xai-oauth"
119
+ | "groq"
120
+ | "cerebras"
121
+ | "openrouter"
122
+ | "kilo"
123
+ | "vercel-ai-gateway"
124
+ | "zai"
125
+ | "zhipu-coding-plan"
126
+ | "mistral"
127
+ | "minimax"
128
+ | "opencode-go"
129
+ | "opencode-zen"
130
+ | "synthetic"
131
+ | "cloudflare-ai-gateway"
132
+ | "huggingface"
133
+ | "litellm"
134
+ | "moonshot"
135
+ | "nvidia"
136
+ | "nanogpt"
137
+ | "ollama"
138
+ | "ollama-cloud"
139
+ | "qianfan"
140
+ | "qwen-portal"
141
+ | "together"
142
+ | "venice"
143
+ | "vllm"
144
+ | "xiaomi"
145
+ | "wafer-pass"
146
+ | "wafer-serverless"
147
+ | "zenmux"
148
+ | "lm-studio";
149
+ export type Provider = KnownProvider | string;
150
+
151
+ import type { Effort } from "./model-thinking";
152
+
153
+ /** Token budgets for each thinking level (token-based providers only) */
154
+ export type ThinkingBudgets = { [key in Effort]?: number };
155
+
156
+ export interface TokenTaskBudget {
157
+ type: "tokens";
158
+ total: number;
159
+ remaining?: number;
160
+ }
161
+
162
+ export type MessageAttribution = "user" | "agent";
163
+
164
+ export type ToolChoice =
165
+ | "auto"
166
+ | "none"
167
+ | "any"
168
+ | "required"
169
+ | { type: "function"; name: string }
170
+ | { type: "function"; function: { name: string } }
171
+ | { type: "tool"; name: string };
172
+
173
+ // Base options all providers share
174
+ export type CacheRetention = "none" | "short" | "long";
175
+
176
+ /**
177
+ * Service tier hint for processing priority / cost control.
178
+ *
179
+ * The unscoped values (`"auto"`, `"default"`, `"flex"`, `"scale"`,
180
+ * `"priority"`) are passed through to providers that understand them
181
+ * (OpenAI's `service_tier` field directly; Anthropic translates
182
+ * `"priority"` into `speed: "fast"` on supported Opus models).
183
+ *
184
+ * The scoped values target a specific provider family and behave as the
185
+ * unscoped value on the matching provider, or `undefined` everywhere else.
186
+ * They let users opt into priority on one family without paying premium
187
+ * costs on the other when switching models mid-session.
188
+ *
189
+ * - `"openai-only"` → `"priority"` on `openai` and `openai-codex`; ignored elsewhere.
190
+ * - `"claude-only"` → `"priority"` on direct `anthropic` (not Bedrock/Vertex Claude).
191
+ */
192
+ export type ServiceTier = "auto" | "default" | "flex" | "scale" | "priority" | "openai-only" | "claude-only";
193
+
194
+ /** Resolved tier — one of the values that providers actually consume on the wire. */
195
+ export type ResolvedServiceTier = Exclude<ServiceTier, "openai-only" | "claude-only">;
196
+
197
+ /**
198
+ * Resolves a possibly scoped `ServiceTier` to the effective tier for the
199
+ * given provider. Scoped values match their target family and otherwise
200
+ * collapse to `undefined`; unscoped values pass through unchanged.
201
+ */
202
+ export function resolveServiceTier(
203
+ serviceTier: ServiceTier | null | undefined,
204
+ provider: Provider | undefined,
205
+ ): ResolvedServiceTier | undefined {
206
+ if (!serviceTier) return undefined;
207
+ switch (serviceTier) {
208
+ case "openai-only":
209
+ return provider === "openai" || provider === "openai-codex" ? "priority" : undefined;
210
+ case "claude-only":
211
+ return provider === "anthropic" ? "priority" : undefined;
212
+ default:
213
+ return serviceTier;
214
+ }
215
+ }
216
+
217
+ /**
218
+ * True when the (possibly scoped) tier should be sent as OpenAI's
219
+ * `service_tier` request field for the given provider. Non-OpenAI
220
+ * providers, unsupported tiers (`"auto"`, `"default"`), and scope
221
+ * mismatches all return false.
222
+ */
223
+ export function shouldSendServiceTier(
224
+ serviceTier: ServiceTier | null | undefined,
225
+ provider: Provider | undefined,
226
+ ): boolean {
227
+ if (provider !== "openai" && provider !== "openai-codex") return false;
228
+ const resolved = resolveServiceTier(serviceTier, provider);
229
+ return resolved === "flex" || resolved === "scale" || resolved === "priority";
230
+ }
231
+
232
+ /**
233
+ * Premium-request weight contributed by sending priority to a provider
234
+ * that supports it. Mirrors GitHub Copilot's `premiumRequests` accounting
235
+ * so the "premium requests" stat aggregates priority traffic across the
236
+ * OpenAI family and Anthropic fast-mode realizations.
237
+ *
238
+ * Returns 1 per resolved priority request, 0 otherwise.
239
+ */
240
+ export function getPriorityPremiumRequests(
241
+ serviceTier: ServiceTier | null | undefined,
242
+ provider: Provider | undefined,
243
+ ): number {
244
+ if (resolveServiceTier(serviceTier, provider) !== "priority") return 0;
245
+ // Only providers that realize `priority` on the wire bill the user.
246
+ // Everywhere else, the field is silently dropped and nothing is charged.
247
+ return provider === "openai" || provider === "openai-codex" || provider === "anthropic" ? 1 : 0;
248
+ }
249
+
250
+ export interface ProviderSessionState {
251
+ close(): void;
252
+ }
253
+
254
+ export interface ProviderResponseMetadata {
255
+ status: number;
256
+ headers: Record<string, string>;
257
+ requestId?: string | null;
258
+ metadata?: Record<string, unknown>;
259
+ }
260
+
261
+ export interface RawSseEvent {
262
+ event: string | null;
263
+ data: string;
264
+ raw: string[];
265
+ }
266
+
267
+ /**
268
+ * `fetch`-compatible function. Accepts any callable matching the standard
269
+ * fetch signature; `preconnect` is optional because non-Bun runtimes (browsers,
270
+ * test mocks) won't expose it.
271
+ */
272
+ export type FetchImpl = ((input: string | URL | Request, init?: RequestInit) => Promise<Response>) & {
273
+ preconnect?: typeof globalThis.fetch.preconnect;
274
+ };
275
+
276
+ export interface StreamOptions {
277
+ temperature?: number;
278
+ topP?: number;
279
+ topK?: number;
280
+ minP?: number;
281
+ presencePenalty?: number;
282
+ repetitionPenalty?: number;
283
+ /**
284
+ * Stop sequences. Anthropic encodes as `stop_sequences` (array, max 4);
285
+ * OpenAI chat-completions encodes as `stop` (string or array of up to 4);
286
+ * OpenAI Responses API has no `stop` field today (silently dropped by the
287
+ * provider when present).
288
+ */
289
+ stopSequences?: string[];
290
+ /**
291
+ * Frequency penalty (OpenAI). Penalizes new tokens based on existing frequency
292
+ * in the text so far. Range -2.0 to 2.0. Parallel to {@link presencePenalty}.
293
+ */
294
+ frequencyPenalty?: number;
295
+ maxTokens?: number;
296
+ signal?: AbortSignal;
297
+ apiKey?: string;
298
+ /**
299
+ * Called when a provider returns 401 before any replay-unsafe assistant
300
+ * event has been emitted. Returning a different key retries the provider
301
+ * request once.
302
+ */
303
+ onAuthError?: (provider: string, apiKey: string, error: unknown) => Promise<string | undefined>;
304
+ cacheRetention?: CacheRetention;
305
+ /**
306
+ * Additional headers to include in provider requests.
307
+ * These are merged on top of model-defined headers.
308
+ */
309
+ headers?: Record<string, string>;
310
+ /**
311
+ * Optional explicit request attribution override for providers that support it.
312
+ */
313
+ initiatorOverride?: MessageAttribution;
314
+ /**
315
+ * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
316
+ * If the server's requested delay exceeds this value, the request fails immediately
317
+ * with an error containing the requested delay, allowing higher-level retry logic
318
+ * to handle it with user visibility.
319
+ * Default: 60000 (60 seconds). Set to 0 to disable the cap.
320
+ */
321
+ maxRetryDelayMs?: number;
322
+ /**
323
+ * Optional metadata to include in API requests.
324
+ * Providers extract the fields they understand and ignore the rest.
325
+ * For example, Anthropic uses `user_id` for abuse tracking and rate limiting.
326
+ */
327
+ metadata?: Record<string, unknown>;
328
+ /**
329
+ * Advisory token budget for a full agentic loop. Anthropic encodes this as
330
+ * `output_config.task_budget` with the `task-budgets-2026-03-13` beta header.
331
+ */
332
+ taskBudget?: TokenTaskBudget;
333
+ /**
334
+ * Optional session identifier for providers that support session-based
335
+ * routing, request affinity, or transport reuse. Providers may also use this
336
+ * as the prompt-cache key when `promptCacheKey` is not set.
337
+ */
338
+ sessionId?: string;
339
+ /**
340
+ * Optional prompt-cache identity. When set, OpenAI Responses-compatible
341
+ * providers use this for `prompt_cache_key` while keeping `sessionId` for
342
+ * provider routing / conversation headers.
343
+ */
344
+ promptCacheKey?: string;
345
+ /**
346
+ * Provider-scoped mutable state store for this agent session.
347
+ * Providers can use this to persist transport/session state between turns.
348
+ */
349
+ providerSessionState?: Map<string, ProviderSessionState>;
350
+ /**
351
+ * Optional callback for inspecting or replacing provider payloads before sending.
352
+ * Return undefined to keep the payload unchanged.
353
+ */
354
+ onPayload?: (payload: unknown, model?: Model<Api>) => unknown | undefined | Promise<unknown | undefined>;
355
+ /**
356
+ * Optional callback for provider response metadata after headers are received.
357
+ */
358
+ onResponse?: (response: ProviderResponseMetadata, model?: Model<Api>) => void | Promise<void>;
359
+ /**
360
+ * Optional callback for raw Server-Sent Events as they arrive from HTTP streaming providers,
361
+ * plus synthesized SSE-shaped frames for the Codex WebSocket transport (one synthetic frame
362
+ * per JSON request/response message). WebSocket frames are tagged with a leading
363
+ * `: ws → <type>` (outbound) or `: ws ← <type>` (inbound) comment line in `RawSseEvent.raw`.
364
+ *
365
+ * Diagnostic only: provider implementations must ignore callback failures and must not
366
+ * let observers alter stream contents.
367
+ */
368
+ onSseEvent?: (event: RawSseEvent, model?: Model<Api>) => void;
369
+ /**
370
+ * Optional override for the first-event watchdog in milliseconds. Built-in
371
+ * providers apply this budget twice when they can: once to the underlying
372
+ * SDK/request while waiting for the HTTP stream object to exist, then again
373
+ * in the iterator while waiting for the first semantic stream event. Set to
374
+ * `0` to disable both layers for this request. After the first semantic
375
+ * event arrives, `streamIdleTimeoutMs` governs inter-event stalls. Falls
376
+ * back to `PI_STREAM_FIRST_EVENT_TIMEOUT_MS` and then to a 100s default.
377
+ * OpenAI-family transports additionally honor
378
+ * `PI_OPENAI_STREAM_FIRST_EVENT_TIMEOUT_MS` as the most-specific override and
379
+ * floor the first-event budget at the resolved idle (per-call
380
+ * `streamIdleTimeoutMs` or `PI_OPENAI_STREAM_IDLE_TIMEOUT_MS`) so slow local
381
+ * OpenAI-compatible servers are not undercut during prompt processing.
382
+ *
383
+ * Iterator-level honored by: every built-in provider (via the lazy-stream
384
+ * forwarder in `register-builtins`). SDK-request honored by:
385
+ * `openai-completions`, `openai-responses`, `azure-openai-responses`,
386
+ * `anthropic-messages`.
387
+ */
388
+ streamFirstEventTimeoutMs?: number;
389
+ /**
390
+ * Optional override for the maximum idle gap between streamed events in
391
+ * milliseconds. Once the first event arrives, this guards against silent
392
+ * mid-stream stalls (broker dies, half-open socket, model produces no real
393
+ * progress for too long). Set to `0` to disable. Falls back to
394
+ * `PI_STREAM_IDLE_TIMEOUT_MS` (alias: `PI_OPENAI_STREAM_IDLE_TIMEOUT_MS`)
395
+ * and then to a 120s default.
396
+ */
397
+ streamIdleTimeoutMs?: number;
398
+ /**
399
+ * Optional retry delay hook for tests and transports that need custom scheduling.
400
+ */
401
+ providerRetryWait?: (delayMs: number, signal?: AbortSignal) => Promise<void>;
402
+ /**
403
+ * Optional `fetch` implementation override. Providers route every HTTP
404
+ * request — direct calls, SDK clients, and retry helpers — through this
405
+ * implementation when set. Defaults to `globalThis.fetch`. Providers that
406
+ * do not use `fetch` (Bedrock's AWS SDK transport, Cursor's HTTP/2
407
+ * channel) silently ignore the override.
408
+ */
409
+ fetch?: FetchImpl;
410
+ /** Cursor exec/MCP tool handlers (cursor-agent only). */
411
+ execHandlers?: CursorExecHandlers;
412
+ }
413
+
414
+ // Unified options with reasoning passed to streamSimple() and completeSimple()
415
+ export interface SimpleStreamOptions extends StreamOptions {
416
+ reasoning?: Effort;
417
+ /**
418
+ * Force-disable reasoning for the request even when the model supports it.
419
+ * Takes precedence over `reasoning`. Useful for fast utility calls
420
+ * (e.g. title generation) where the model would otherwise burn the entire
421
+ * output budget on internal thinking. Provider support is format-specific:
422
+ * some transports can disable reasoning directly, while generic
423
+ * effort-based OpenAI-compatible endpoints use the lowest supported effort.
424
+ */
425
+ disableReasoning?: boolean;
426
+ /**
427
+ * If true, request that the provider omit thinking/reasoning summaries
428
+ * from the response (e.g. Anthropic `thinking.display = "omitted"`,
429
+ * OpenAI Responses `reasoning.summary` left unset). The model still
430
+ * reasons internally; only the human-readable summary stream is dropped.
431
+ * Useful when the UI hides thinking blocks anyway and the summary is wasted bandwidth.
432
+ */
433
+ hideThinkingSummary?: boolean;
434
+ /** Custom token budgets for thinking levels (token-based providers only) */
435
+ thinkingBudgets?: ThinkingBudgets;
436
+ /** Cursor exec handlers for local tool execution */
437
+ cursorExecHandlers?: CursorExecHandlers;
438
+ /** Hook to handle tool results from Cursor exec */
439
+ cursorOnToolResult?: CursorToolResultHandler;
440
+ /** Optional tool choice override for compatible providers */
441
+ toolChoice?: ToolChoice;
442
+ /** OpenAI service tier for processing priority/cost control. Ignored by non-OpenAI providers. */
443
+ serviceTier?: ServiceTier;
444
+ /** API format for Kimi Code provider: "openai" or "anthropic" (default: "anthropic") */
445
+ kimiApiFormat?: "openai" | "anthropic";
446
+ /** API format for Synthetic provider: "openai" or "anthropic" (default: "openai") */
447
+ syntheticApiFormat?: "openai" | "anthropic";
448
+ /** Hint that websocket transport should be preferred when supported by the provider implementation. */
449
+ preferWebsockets?: boolean;
450
+ /**
451
+ * OpenRouter routing-variant suffix automatically appended to model IDs when
452
+ * the request targets OpenRouter (`model.provider === "openrouter"`). Common
453
+ * values: `"nitro"` (throughput), `"floor"` (cheapest), `"online"` (web
454
+ * search plugin), `"exacto"` (cherry-picked high-quality providers, only
455
+ * defined for some models). Ignored when the resolved model id already
456
+ * contains a `:<variant>` suffix (e.g. the user typed `:nitro` explicitly
457
+ * or the catalog entry already names the variant).
458
+ */
459
+ openrouterVariant?: string;
460
+ }
461
+
462
+ // Generic StreamFunction with typed options
463
+ export type StreamFunction<TApi extends Api> = (
464
+ model: Model<TApi>,
465
+ context: Context,
466
+ options: OptionsForApi<TApi>,
467
+ ) => AssistantMessageEventStream;
468
+
469
+ export interface TextSignatureV1 {
470
+ v: 1;
471
+ id: string;
472
+ phase?: "commentary" | "final_answer";
473
+ }
474
+
475
+ export interface TextContent {
476
+ type: "text";
477
+ text: string;
478
+ textSignature?: string; // e.g., for OpenAI responses, message metadata (legacy id string or TextSignatureV1 JSON)
479
+ }
480
+
481
+ export interface ThinkingContent {
482
+ type: "thinking";
483
+ thinking: string;
484
+ thinkingSignature?: string; // e.g., for OpenAI responses, the reasoning item ID
485
+ itemId?: string; // item.id from output_item.added, used to match output_item.done
486
+ }
487
+
488
+ export interface RedactedThinkingContent {
489
+ type: "redactedThinking";
490
+ data: string;
491
+ }
492
+
493
+ export interface ImageContent {
494
+ type: "image";
495
+ data: string; // base64 encoded image data
496
+ mimeType: string; // e.g., "image/jpeg", "image/png"
497
+ }
498
+
499
+ export interface ToolCall {
500
+ type: "toolCall";
501
+ id: string;
502
+ name: string;
503
+ arguments: Record<string, any>;
504
+ thoughtSignature?: string; // Google-specific: opaque signature for reusing thought context
505
+ intent?: string; // Harness-level intent metadata extracted from traced tool arguments
506
+ /**
507
+ * Original wire-level name when the tool was invoked via OpenAI's custom-tool
508
+ * mechanism (e.g., `apply_patch`). Set by `openai-responses` on receive so
509
+ * the history-replay path can re-emit the call as `custom_tool_call` with
510
+ * its paired tool-result as `custom_tool_call_output`. Absent for regular
511
+ * JSON function tools.
512
+ */
513
+ customWireName?: string;
514
+ }
515
+
516
+ export interface Usage {
517
+ /** Non-cached input tokens (matches the bucket the provider bills as new input). */
518
+ input: number;
519
+ /** Total output tokens for the turn, including thinking, assistant text, and tool-call argument tokens. */
520
+ output: number;
521
+ /** Tokens read from the prompt cache. */
522
+ cacheRead: number;
523
+ /** Tokens written to the prompt cache (cache creation). */
524
+ cacheWrite: number;
525
+ /** Sum of input + output + cacheRead + cacheWrite. */
526
+ totalTokens: number;
527
+ /** Copilot premium-request counter, when applicable. */
528
+ premiumRequests?: number;
529
+ /**
530
+ * Reasoning/thinking tokens included in `output`, when the provider reports them
531
+ * (OpenAI `output_tokens_details.reasoning_tokens`, Google `thoughtsTokenCount`).
532
+ * Always a subset of `output` — non-reasoning output is `output - reasoningTokens`.
533
+ *
534
+ * Providers that don't expose this leave it undefined rather than guessing;
535
+ * `undefined` means unknown, NOT zero.
536
+ */
537
+ reasoningTokens?: number;
538
+ /**
539
+ * Cache-write TTL breakdown (Anthropic only). When set, the components sum to
540
+ * `cacheWrite`. Absent providers do not populate this.
541
+ */
542
+ cttl?: {
543
+ ephemeral5m?: number;
544
+ ephemeral1h?: number;
545
+ };
546
+ /**
547
+ * Server-side tool invocations made during this turn (Anthropic web_search /
548
+ * web_fetch, OpenAI built-in tools when reported). Counts requests, not tokens.
549
+ */
550
+ server?: {
551
+ webSearch?: number;
552
+ webFetch?: number;
553
+ };
554
+ cost: {
555
+ input: number;
556
+ output: number;
557
+ cacheRead: number;
558
+ cacheWrite: number;
559
+ total: number;
560
+ };
561
+ }
562
+
563
+ export type StopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
564
+
565
+ export interface OpenAIResponsesHistoryPayload {
566
+ type: "openaiResponsesHistory";
567
+ provider?: string;
568
+ dt?: boolean;
569
+ items: Array<Record<string, unknown>>;
570
+ }
571
+
572
+ export type ProviderPayload = OpenAIResponsesHistoryPayload;
573
+
574
+ export interface UserMessage {
575
+ role: "user";
576
+ content: string | (TextContent | ImageContent)[];
577
+ /** True if the message was injected by the system (e.g., auto-continue). */
578
+ synthetic?: boolean;
579
+ /** Who initiated this message for billing/attribution semantics. */
580
+ attribution?: MessageAttribution;
581
+ /** Provider-specific opaque payload used to reconstruct transport-native history. */
582
+ providerPayload?: ProviderPayload;
583
+ timestamp: number; // Unix timestamp in milliseconds
584
+ }
585
+
586
+ export interface DeveloperMessage {
587
+ role: "developer";
588
+ content: string | (TextContent | ImageContent)[];
589
+ /** Who initiated this message for billing/attribution semantics. */
590
+ attribution?: MessageAttribution;
591
+ /** Provider-specific opaque payload used to reconstruct transport-native history. */
592
+ providerPayload?: ProviderPayload;
593
+ timestamp: number; // Unix timestamp in milliseconds
594
+ }
595
+
596
+ export interface AssistantMessage {
597
+ role: "assistant";
598
+ content: (TextContent | ThinkingContent | RedactedThinkingContent | ToolCall)[];
599
+ api: Api;
600
+ provider: Provider;
601
+ model: string;
602
+ responseId?: string; // Provider-specific response/message identifier when the upstream API exposes one
603
+ usage: Usage;
604
+ stopReason: StopReason;
605
+ errorMessage?: string;
606
+ /** HTTP status surfaced by the provider when the request failed. Populated by every provider's catch block alongside `errorMessage` so consumers (auth retry, telemetry, UI) can branch without regex-scraping the message. */
607
+ errorStatus?: number;
608
+ /**
609
+ * Stable identifiers for request features the provider silently dropped
610
+ * during this turn (e.g. `"priority"`). Set when a server-side rejection
611
+ * triggered an in-provider fallback retry that succeeded without the
612
+ * feature. Callers can use this to sync user-facing toggles back to the
613
+ * server's actual state.
614
+ */
615
+ disabledFeatures?: string[];
616
+ /** Provider-specific opaque payload used to reconstruct transport-native history. */
617
+ providerPayload?: ProviderPayload;
618
+ timestamp: number; // Unix timestamp in milliseconds
619
+ duration?: number; // Request duration in milliseconds
620
+ ttft?: number; // Time to first token in milliseconds
621
+ }
622
+
623
+ export interface ToolResultMessage<TDetails = any> {
624
+ role: "toolResult";
625
+ toolCallId: string;
626
+ toolName: string;
627
+ content: (TextContent | ImageContent)[]; // Supports text and images
628
+ details?: TDetails;
629
+ isError: boolean;
630
+ /** Who initiated this message for billing/attribution semantics. */
631
+ attribution?: MessageAttribution;
632
+ /** Timestamp when output was pruned (ms since epoch). Undefined if unpruned. */
633
+ prunedAt?: number;
634
+ timestamp: number; // Unix timestamp in milliseconds
635
+ }
636
+
637
+ export type Message = UserMessage | DeveloperMessage | AssistantMessage | ToolResultMessage;
638
+
639
+ export type CursorExecHandlerResult<T> = { result: T; toolResult?: ToolResultMessage } | T | ToolResultMessage;
640
+
641
+ export type CursorToolResultHandler = (
642
+ result: ToolResultMessage,
643
+ ) => ToolResultMessage | undefined | Promise<ToolResultMessage | undefined>;
644
+
645
+ export interface CursorMcpCall {
646
+ name: string;
647
+ providerIdentifier: string;
648
+ toolName: string;
649
+ toolCallId: string;
650
+ args: Record<string, unknown>;
651
+ rawArgs: Record<string, Uint8Array>;
652
+ }
653
+
654
+ export interface CursorShellStreamCallbacks {
655
+ onStdout(data: string): void;
656
+ onStderr(data: string): void;
657
+ }
658
+
659
+ export interface CursorExecHandlers {
660
+ read?: (args: ReadArgs) => Promise<CursorExecHandlerResult<ReadResult>>;
661
+ ls?: (args: LsArgs) => Promise<CursorExecHandlerResult<LsResult>>;
662
+ grep?: (args: GrepArgs) => Promise<CursorExecHandlerResult<GrepResult>>;
663
+ write?: (args: WriteArgs) => Promise<CursorExecHandlerResult<WriteResult>>;
664
+ delete?: (args: DeleteArgs) => Promise<CursorExecHandlerResult<DeleteResult>>;
665
+ shell?: (args: ShellArgs) => Promise<CursorExecHandlerResult<ShellResult>>;
666
+ shellStream?: (
667
+ args: ShellArgs,
668
+ callbacks: CursorShellStreamCallbacks,
669
+ ) => Promise<CursorExecHandlerResult<ShellResult>>;
670
+ diagnostics?: (args: DiagnosticsArgs) => Promise<CursorExecHandlerResult<DiagnosticsResult>>;
671
+ mcp?: (call: CursorMcpCall) => Promise<CursorExecHandlerResult<McpResult>>;
672
+ onToolResult?: CursorToolResultHandler;
673
+ }
674
+
675
+ /**
676
+ * Plain JSON Schema document used by extension-authored tools (legacy TypeBox
677
+ * emits this shape). Distinguished from Zod at runtime via {@link isZodSchema}.
678
+ */
679
+ export type TJsonSchema = Record<string, unknown>;
680
+
681
+ /**
682
+ * Schema type accepted by the {@link Tool} interface.
683
+ *
684
+ * Canonical authoring uses Zod. Extension compat may supply a JSON Schema
685
+ * object (including TypeBox static schema objects).
686
+ */
687
+ export type TSchema = ZodType | TJsonSchema;
688
+
689
+ /** Resolve parameter types for tool execution / handlers. */
690
+ export type Static<S> = S extends ZodType ? z.infer<S> : S extends { static: infer T } ? T : unknown;
691
+
692
+ export interface Tool<TParameters extends TSchema = TSchema> {
693
+ name: string;
694
+ description: string;
695
+ parameters: TParameters;
696
+ /** If true, tool is strictly typed and validated against the parameters schema before execution */
697
+ strict?: boolean;
698
+ /**
699
+ * Optional grammar constraint for OpenAI custom-tool emission.
700
+ * When set, providers that support grammar-constrained tools (currently only
701
+ * `openai-responses` against models with the right capability flag) may emit
702
+ * this tool as `{type: "custom", format: {type: "grammar", …}}` instead of a
703
+ * JSON function tool. Other providers ignore the field.
704
+ */
705
+ customFormat?: { syntax: "lark" | "regex"; definition: string };
706
+ /**
707
+ * Optional wire-level name used when this tool is emitted as a custom tool
708
+ * (e.g. OpenAI's `{type: "custom"}` shape). Models trained on specific tool
709
+ * names — like GPT-5 on `apply_patch` — need to see that exact name on the
710
+ * wire, but it may differ from the harness-internal `name`. The agent-loop
711
+ * dispatcher matches both `name` and `customWireName` so returned tool
712
+ * calls route correctly. Absent for regular JSON function tools.
713
+ */
714
+ customWireName?: string;
715
+ }
716
+
717
+ export interface Context {
718
+ systemPrompt?: string[];
719
+ messages: Message[];
720
+ tools?: Tool[];
721
+ }
722
+
723
+ export type AssistantMessageEvent =
724
+ | { type: "start"; contentIndex?: undefined; partial: AssistantMessage }
725
+ | { type: "text_start"; contentIndex: number; partial: AssistantMessage }
726
+ | { type: "text_delta"; contentIndex: number; delta: string; partial: AssistantMessage }
727
+ | { type: "text_end"; contentIndex: number; content: string; partial: AssistantMessage }
728
+ | { type: "thinking_start"; contentIndex: number; partial: AssistantMessage }
729
+ | { type: "thinking_delta"; contentIndex: number; delta: string; partial: AssistantMessage }
730
+ | { type: "thinking_end"; contentIndex: number; content: string; partial: AssistantMessage }
731
+ | { type: "toolcall_start"; contentIndex: number; partial: AssistantMessage }
732
+ | { type: "toolcall_delta"; contentIndex: number; delta: string; partial: AssistantMessage }
733
+ | { type: "toolcall_end"; contentIndex: number; toolCall: ToolCall; partial: AssistantMessage }
734
+ | {
735
+ type: "done";
736
+ contentIndex?: undefined;
737
+ reason: Extract<StopReason, "stop" | "length" | "toolUse">;
738
+ message: AssistantMessage;
739
+ }
740
+ | {
741
+ type: "error";
742
+ contentIndex?: undefined;
743
+ reason: Extract<StopReason, "aborted" | "error">;
744
+ error: AssistantMessage;
745
+ };
746
+
747
+ /**
748
+ * Compatibility settings for openai-completions API.
749
+ * Use this to override URL-based auto-detection for custom providers.
750
+ */
751
+ export interface OpenAICompat {
752
+ /** Whether the provider supports the `store` field. Default: auto-detected from URL. */
753
+ supportsStore?: boolean;
754
+ /** Whether the provider supports the `developer` role (vs `system`). Default: auto-detected from URL. */
755
+ supportsDeveloperRole?: boolean;
756
+ /**
757
+ * Whether the provider's chat-completions endpoint accepts multiple
758
+ * leading `system`/`developer` messages. When false, ordered system
759
+ * prompts are coalesced into a single message joined by `\n\n` so
760
+ * strict chat templates (e.g. Qwen-served via vLLM, MiniMax) accept
761
+ * the request. Default: detected per provider/baseUrl. Canonical
762
+ * OpenAI/Azure/OpenRouter/Cerebras/Together/Fireworks/Groq/DeepSeek/
763
+ * Mistral/xAI/Z.ai/GitHub Copilot/Zenmux are treated as `true`;
764
+ * unknown or strict-template hosts default to `false`. Setting this
765
+ * to `true` preserves separate blocks, which is preferred for
766
+ * KV-cache reuse when the trailing prompt changes between calls.
767
+ */
768
+ supportsMultipleSystemMessages?: boolean;
769
+ /** Whether the provider supports `reasoning_effort`. Default: auto-detected from URL. */
770
+ supportsReasoningEffort?: boolean;
771
+ /** Optional mapping from aery-ai reasoning levels to provider/model-specific `reasoning_effort` values. */
772
+ reasoningEffortMap?: Partial<Record<Effort, string>>;
773
+ /** Whether the provider supports `stream_options: { include_usage: true }` for token usage in streaming responses. Default: true. */
774
+ supportsUsageInStreaming?: boolean;
775
+ /** Which field to use for max tokens. Default: auto-detected from URL. */
776
+ maxTokensField?: "max_completion_tokens" | "max_tokens";
777
+ /** Whether tool results require the `name` field. Default: auto-detected from URL. */
778
+ requiresToolResultName?: boolean;
779
+ /** Whether a user message after tool results requires an assistant message in between. Default: auto-detected from URL. */
780
+ requiresAssistantAfterToolResult?: boolean;
781
+ /** Whether thinking blocks must be converted to text blocks with <thinking> delimiters. Default: auto-detected from URL. */
782
+ requiresThinkingAsText?: boolean;
783
+ /** Whether tool call IDs must be normalized to Mistral format (exactly 9 alphanumeric chars). Default: auto-detected from URL. */
784
+ requiresMistralToolIds?: boolean;
785
+ /** Format for reasoning/thinking parameter. "openai" uses reasoning_effort, "openrouter" uses reasoning: { effort }, "zai" uses thinking: { type: "enabled" | "disabled" } (also used by Moonshot Kimi), "qwen" uses top-level enable_thinking, and "qwen-chat-template" uses chat_template_kwargs.enable_thinking. Default: "openai". */
786
+ thinkingFormat?: "openai" | "openrouter" | "zai" | "qwen" | "qwen-chat-template";
787
+ /** Which reasoning content field to emit on assistant messages. Default: auto-detected. */
788
+ reasoningContentField?: "reasoning_content" | "reasoning" | "reasoning_text";
789
+ /** Whether assistant tool-call messages must include reasoning content. Default: false. */
790
+ requiresReasoningContentForToolCalls?: boolean;
791
+ /** Whether the provider accepts a synthetic placeholder (e.g. ".") for missing reasoning_content on tool-call turns. Default: true. Set to false for providers like DeepSeek that validate the exact reasoning_content value. */
792
+ allowsSyntheticReasoningContentForToolCalls?: boolean;
793
+ /** Whether assistant tool-call messages must include non-empty content. Default: false. */
794
+ requiresAssistantContentForToolCalls?: boolean;
795
+ /** Whether the provider supports the `tool_choice` parameter. Default: true. */
796
+ supportsToolChoice?: boolean;
797
+ /**
798
+ * Drop reasoning fields (`reasoning_effort`, OpenRouter `reasoning`) for
799
+ * the request when `tool_choice` forces a tool call. Mirrors the Anthropic
800
+ * `disableThinkingIfToolChoiceForced` rule for backends like Kimi that
801
+ * 400 with `tool_choice 'specified' is incompatible with thinking
802
+ * enabled` whenever both are present. Default: auto-detected (Kimi).
803
+ */
804
+ disableReasoningOnForcedToolChoice?: boolean;
805
+ /**
806
+ * Drop reasoning fields (`reasoning_effort`, OpenRouter `reasoning`) for
807
+ * any request that sends `tool_choice`. Use for providers/models that accept
808
+ * tools and `tool_choice`, but reject `tool_choice` while thinking is enabled.
809
+ * Default: auto-detected (DeepSeek reasoning models).
810
+ */
811
+ disableReasoningOnToolChoice?: boolean;
812
+ /** OpenRouter-specific routing preferences. Only used when baseUrl points to OpenRouter. */
813
+ openRouterRouting?: OpenRouterRouting;
814
+ /** Vercel AI Gateway routing preferences. Only used when baseUrl points to Vercel AI Gateway. */
815
+ vercelGatewayRouting?: VercelGatewayRouting;
816
+ /** Extra fields to include in request body (e.g. gateway routing hints for OpenClaw-style proxies). */
817
+ extraBody?: Record<string, unknown>;
818
+ /** Whether the provider supports the `strict` field in tool definitions. Default: auto-detected per provider/baseUrl (conservative for unknown providers). */
819
+ supportsStrictMode?: boolean;
820
+ /** Whether tool schemas must be sent either all strict or all non-strict. Undefined keeps the existing per-tool mixed behavior. */
821
+ toolStrictMode?: "all_strict" | "none";
822
+ }
823
+
824
+ /**
825
+ * Compatibility settings for anthropic-messages API.
826
+ * Use this to disable features that strict-by-default Anthropic accepts but
827
+ * that proxy gateways (Vertex AI, AWS Bedrock-style fronts, etc.) reject.
828
+ */
829
+ export interface AnthropicCompat {
830
+ /**
831
+ * Drop the top-level `strict: true` field on tool definitions. Vertex AI's
832
+ * Anthropic-compatible endpoint rejects unknown tool fields with
833
+ * `tools.<n>.custom.strict: Extra inputs are not permitted`.
834
+ */
835
+ disableStrictTools?: boolean;
836
+ /**
837
+ * Map adaptive thinking (`thinking: { type: "adaptive" }`) to
838
+ * `{ type: "enabled", budget_tokens }`. Vertex AI rejects the `adaptive`
839
+ * tag with `Input tag 'adaptive' ... does not match any of the expected
840
+ * tags: 'disabled', 'enabled'`.
841
+ */
842
+ disableAdaptiveThinking?: boolean;
843
+ /** Whether tools may include Anthropic's per-tool eager_input_streaming flag. Default: true. */
844
+ supportsEagerToolInputStreaming?: boolean;
845
+ /** Whether long prompt-cache retention (`ttl: "1h"`) is supported. Default: true for canonical Anthropic API. */
846
+ supportsLongCacheRetention?: boolean;
847
+ /**
848
+ * Whether mid-conversation `role: "system"` messages are accepted in the
849
+ * `messages` array (Claude Opus 4.8+ on the first-party Claude API and
850
+ * Claude Platform on AWS). When unset, auto-detected from the model id and
851
+ * base URL. Not available on Bedrock, Vertex AI, or Microsoft Foundry.
852
+ */
853
+ supportsMidConversationSystem?: boolean;
854
+ }
855
+
856
+ /**
857
+ * OpenRouter provider routing preferences.
858
+ * Controls which upstream providers OpenRouter routes requests to.
859
+ * @see https://openrouter.ai/docs/provider-routing
860
+ */
861
+ export interface OpenRouterRouting {
862
+ /** List of provider slugs to exclusively use for this request (e.g., ["amazon-bedrock", "anthropic"]). */
863
+ only?: string[];
864
+ /** List of provider slugs to try in order (e.g., ["anthropic", "openai"]). */
865
+ order?: string[];
866
+ }
867
+
868
+ /**
869
+ * Vercel AI Gateway routing preferences.
870
+ * Controls which upstream providers the gateway routes requests to.
871
+ * @see https://vercel.com/docs/ai-gateway/models-and-providers/provider-options
872
+ */
873
+ export interface VercelGatewayRouting {
874
+ /** List of provider slugs to exclusively use for this request (e.g., ["bedrock", "anthropic"]). */
875
+ only?: string[];
876
+ /** List of provider slugs to try in order (e.g., ["anthropic", "openai"]). */
877
+ order?: string[];
878
+ }
879
+
880
+ // Model interface for the unified model system
881
+ export interface Model<TApi extends Api = any> {
882
+ id: string;
883
+ name: string;
884
+ api: TApi;
885
+ provider: Provider;
886
+ baseUrl: string;
887
+ reasoning: boolean;
888
+ input: ("text" | "image")[];
889
+ cost: {
890
+ input: number; // $/million tokens
891
+ output: number; // $/million tokens
892
+ cacheRead: number; // $/million tokens
893
+ cacheWrite: number; // $/million tokens
894
+ };
895
+ /** Premium Copilot requests charged per user-initiated request (defaults to 1). */
896
+ premiumMultiplier?: number;
897
+ contextWindow: number;
898
+ maxTokens: number;
899
+ headers?: Record<string, string>;
900
+ /**
901
+ * Streaming transport override. When `"aery-native"`, `streamSimple` routes
902
+ * the request to the model's `baseUrl` via the auth-gateway's
903
+ * `POST /v1/aery/stream` endpoint instead of dispatching the per-API
904
+ * provider client. The `baseUrl` must point at an `aery auth-gateway`
905
+ * (or compatible) host; `headers.Authorization` (or `apiKey` resolved by
906
+ * the registry) carries the gateway bearer.
907
+ *
908
+ * Used by containerized aery installs (e.g. robomp slots) to route every
909
+ * LLM call through a sidecar gateway that holds the real provider
910
+ * credentials. The model's other metadata (pricing, context window,
911
+ * thinking config, …) still resolves locally; only the streaming
912
+ * dispatch is redirected.
913
+ */
914
+ transport?: "aery-native";
915
+ /** Hint that websocket transport should be preferred when supported by the provider implementation. */
916
+ preferWebsockets?: boolean;
917
+ /** Preferred model to switch to when context promotion is triggered (model id or provider/id). */
918
+ contextPromotionTarget?: string;
919
+ /** Provider-assigned priority value (lower = higher priority). */
920
+ priority?: number;
921
+ /** Canonical thinking capability metadata for this model. */
922
+ thinking?: ThinkingConfig;
923
+ /** Compatibility overrides per API. If not set, auto-detected from baseUrl. */
924
+ compat?: TApi extends "openai-completions" | "openai-responses"
925
+ ? OpenAICompat
926
+ : TApi extends "anthropic-messages"
927
+ ? AnthropicCompat
928
+ : never;
929
+ /**
930
+ * Which shape to use when exposing the Codex `apply_patch` tool to this model.
931
+ * Generated catalog policy sets `"freeform"` for first-party GPT-5 Responses
932
+ * models that support OpenAI custom tools with a Lark grammar. The freeform
933
+ * variant sends a raw patch string with no JSON envelope.
934
+ * - `"function"` or undefined: JSON function-tool with `{input: string}` (spec §1.2).
935
+ */
936
+ applyPatchToolType?: "freeform" | "function";
937
+ /**
938
+ * Force OAuth-style request shaping for providers whose API key prefix doesn't
939
+ * match an OAuth token (e.g. routing Anthropic traffic through a proxy that
940
+ * expects Claude Code framing). When true, the streaming layer sets
941
+ * `options.isOAuth = true` for the underlying provider call.
942
+ */
943
+ isOAuth?: boolean;
944
+ }