@earendil-works/pi-ai 1.4.0 → 1.5.1

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 (318) hide show
  1. package/README.md +58 -39
  2. package/dist/api/anthropic-messages.d.ts.map +1 -1
  3. package/dist/api/anthropic-messages.js +282 -87
  4. package/dist/api/anthropic-messages.js.map +1 -1
  5. package/dist/api/azure-openai-responses.d.ts.map +1 -1
  6. package/dist/api/azure-openai-responses.js +1 -7
  7. package/dist/api/azure-openai-responses.js.map +1 -1
  8. package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
  9. package/dist/api/bedrock-converse-stream.js +127 -103
  10. package/dist/api/bedrock-converse-stream.js.map +1 -1
  11. package/dist/api/bedrock-converse-stream.lazy.d.ts +7 -0
  12. package/dist/api/bedrock-converse-stream.lazy.d.ts.map +1 -1
  13. package/dist/api/bedrock-converse-stream.lazy.js +18 -5
  14. package/dist/api/bedrock-converse-stream.lazy.js.map +1 -1
  15. package/dist/api/constrained-sampling.d.ts +13 -1
  16. package/dist/api/constrained-sampling.d.ts.map +1 -1
  17. package/dist/api/constrained-sampling.js +38 -18
  18. package/dist/api/constrained-sampling.js.map +1 -1
  19. package/dist/api/google-generative-ai.d.ts.map +1 -1
  20. package/dist/api/google-generative-ai.js +0 -6
  21. package/dist/api/google-generative-ai.js.map +1 -1
  22. package/dist/api/google-shared.d.ts +2 -1
  23. package/dist/api/google-shared.d.ts.map +1 -1
  24. package/dist/api/google-shared.js +57 -2
  25. package/dist/api/google-shared.js.map +1 -1
  26. package/dist/api/google-vertex.d.ts.map +1 -1
  27. package/dist/api/google-vertex.js +0 -6
  28. package/dist/api/google-vertex.js.map +1 -1
  29. package/dist/api/lazy.d.ts +1 -1
  30. package/dist/api/lazy.d.ts.map +1 -1
  31. package/dist/api/lazy.js +9 -8
  32. package/dist/api/lazy.js.map +1 -1
  33. package/dist/api/mistral-conversations.d.ts.map +1 -1
  34. package/dist/api/mistral-conversations.js +17 -44
  35. package/dist/api/mistral-conversations.js.map +1 -1
  36. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  37. package/dist/api/openai-codex-responses.js +7 -8
  38. package/dist/api/openai-codex-responses.js.map +1 -1
  39. package/dist/api/openai-completions.d.ts +2 -1
  40. package/dist/api/openai-completions.d.ts.map +1 -1
  41. package/dist/api/openai-completions.js +55 -59
  42. package/dist/api/openai-completions.js.map +1 -1
  43. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  44. package/dist/api/openai-responses-shared.js +58 -57
  45. package/dist/api/openai-responses-shared.js.map +1 -1
  46. package/dist/api/openai-responses.d.ts.map +1 -1
  47. package/dist/api/openai-responses.js +4 -8
  48. package/dist/api/openai-responses.js.map +1 -1
  49. package/dist/api/openrouter-images.js +1 -0
  50. package/dist/api/openrouter-images.js.map +1 -1
  51. package/dist/api/pi-messages.d.ts +2 -0
  52. package/dist/api/pi-messages.d.ts.map +1 -1
  53. package/dist/api/pi-messages.js +24 -9
  54. package/dist/api/pi-messages.js.map +1 -1
  55. package/dist/api/simple-options.d.ts +1 -0
  56. package/dist/api/simple-options.d.ts.map +1 -1
  57. package/dist/api/simple-options.js +16 -2
  58. package/dist/api/simple-options.js.map +1 -1
  59. package/dist/api/strict-tool-limits.d.ts +13 -0
  60. package/dist/api/strict-tool-limits.d.ts.map +1 -0
  61. package/dist/api/strict-tool-limits.js +50 -0
  62. package/dist/api/strict-tool-limits.js.map +1 -0
  63. package/dist/auth/oauth/github-copilot.d.ts.map +1 -1
  64. package/dist/auth/oauth/github-copilot.js +4 -11
  65. package/dist/auth/oauth/github-copilot.js.map +1 -1
  66. package/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
  67. package/dist/auth/oauth/kimi-coding.js +4 -22
  68. package/dist/auth/oauth/kimi-coding.js.map +1 -1
  69. package/dist/auth/oauth/load.d.ts.map +1 -1
  70. package/dist/auth/oauth/load.js +5 -2
  71. package/dist/auth/oauth/load.js.map +1 -1
  72. package/dist/auth/oauth/meta.d.ts.map +1 -1
  73. package/dist/auth/oauth/meta.js +1 -14
  74. package/dist/auth/oauth/meta.js.map +1 -1
  75. package/dist/auth/oauth/radius.d.ts.map +1 -1
  76. package/dist/auth/oauth/radius.js +9 -3
  77. package/dist/auth/oauth/radius.js.map +1 -1
  78. package/dist/auth/oauth/trusted-url.d.ts +7 -0
  79. package/dist/auth/oauth/trusted-url.d.ts.map +1 -0
  80. package/dist/auth/oauth/trusted-url.js +12 -0
  81. package/dist/auth/oauth/trusted-url.js.map +1 -0
  82. package/dist/auth/types.d.ts +4 -0
  83. package/dist/auth/types.d.ts.map +1 -1
  84. package/dist/auth/types.js.map +1 -1
  85. package/dist/cache-warming.d.ts +53 -0
  86. package/dist/cache-warming.d.ts.map +1 -0
  87. package/dist/cache-warming.js +82 -0
  88. package/dist/cache-warming.js.map +1 -0
  89. package/dist/cli.js +6 -2
  90. package/dist/cli.js.map +1 -1
  91. package/dist/compat/extension-oauth-types.d.ts +4 -0
  92. package/dist/compat/extension-oauth-types.d.ts.map +1 -1
  93. package/dist/compat/extension-oauth-types.js.map +1 -1
  94. package/dist/env-api-keys.d.ts.map +1 -1
  95. package/dist/env-api-keys.js +1 -0
  96. package/dist/env-api-keys.js.map +1 -1
  97. package/dist/index.d.ts +3 -3
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +3 -2
  100. package/dist/index.js.map +1 -1
  101. package/dist/lazy-bedrock-provider.d.ts +10 -0
  102. package/dist/lazy-bedrock-provider.d.ts.map +1 -0
  103. package/dist/lazy-bedrock-provider.js +13 -0
  104. package/dist/lazy-bedrock-provider.js.map +1 -0
  105. package/dist/lazy-oauth.d.ts +10 -0
  106. package/dist/lazy-oauth.d.ts.map +1 -0
  107. package/dist/lazy-oauth.js +23 -0
  108. package/dist/lazy-oauth.js.map +1 -0
  109. package/dist/models.d.ts +7 -0
  110. package/dist/models.d.ts.map +1 -1
  111. package/dist/models.generated.d.ts +4 -0
  112. package/dist/models.generated.d.ts.map +1 -1
  113. package/dist/models.generated.js +5 -1
  114. package/dist/models.generated.js.map +1 -1
  115. package/dist/models.js +20 -11
  116. package/dist/models.js.map +1 -1
  117. package/dist/providers/all.d.ts.map +1 -1
  118. package/dist/providers/all.js +2 -0
  119. package/dist/providers/all.js.map +1 -1
  120. package/dist/providers/amazon-bedrock.models.js +1 -1
  121. package/dist/providers/amazon-bedrock.models.js.map +1 -1
  122. package/dist/providers/ant-ling.models.js +1 -1
  123. package/dist/providers/ant-ling.models.js.map +1 -1
  124. package/dist/providers/anthropic.models.js +1 -1
  125. package/dist/providers/anthropic.models.js.map +1 -1
  126. package/dist/providers/azure.models.js +1 -1
  127. package/dist/providers/azure.models.js.map +1 -1
  128. package/dist/providers/baseten.models.js +1 -1
  129. package/dist/providers/baseten.models.js.map +1 -1
  130. package/dist/providers/cerebras.models.js +1 -1
  131. package/dist/providers/cerebras.models.js.map +1 -1
  132. package/dist/providers/cloudflare-ai-gateway.models.js +1 -1
  133. package/dist/providers/cloudflare-ai-gateway.models.js.map +1 -1
  134. package/dist/providers/cloudflare-workers-ai.models.js +1 -1
  135. package/dist/providers/cloudflare-workers-ai.models.js.map +1 -1
  136. package/dist/providers/compat-schema.d.ts +444 -456
  137. package/dist/providers/compat-schema.d.ts.map +1 -1
  138. package/dist/providers/compat-schema.js +166 -112
  139. package/dist/providers/compat-schema.js.map +1 -1
  140. package/dist/providers/data/.manifest.json +1 -1
  141. package/dist/providers/data/amazon-bedrock.json +1 -1
  142. package/dist/providers/data/anthropic.json +1 -1
  143. package/dist/providers/data/azure.json +1 -1
  144. package/dist/providers/data/baseten.json +1 -1
  145. package/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  146. package/dist/providers/data/cloudflare-workers-ai.json +1 -1
  147. package/dist/providers/data/fireworks.json +1 -1
  148. package/dist/providers/data/github-copilot.json +1 -1
  149. package/dist/providers/data/google-vertex.json +1 -1
  150. package/dist/providers/data/google.json +1 -1
  151. package/dist/providers/data/huggingface.json +1 -1
  152. package/dist/providers/data/kimi-coding.json +1 -1
  153. package/dist/providers/data/mistral.json +1 -1
  154. package/dist/providers/data/moonshotai-cn.json +1 -1
  155. package/dist/providers/data/moonshotai.json +1 -1
  156. package/dist/providers/data/nvidia.json +1 -1
  157. package/dist/providers/data/openai-codex.json +1 -1
  158. package/dist/providers/data/openai.json +1 -1
  159. package/dist/providers/data/opencode-go.json +1 -1
  160. package/dist/providers/data/opencode.json +1 -1
  161. package/dist/providers/data/openrouter.json +1 -1
  162. package/dist/providers/data/qwen-token-plan-cn.json +1 -1
  163. package/dist/providers/data/qwen-token-plan-individual-cn.json +1 -0
  164. package/dist/providers/data/qwen-token-plan-individual.json +1 -1
  165. package/dist/providers/data/qwen-token-plan.json +1 -1
  166. package/dist/providers/data/radius.json +1 -1
  167. package/dist/providers/data/together.json +1 -1
  168. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  169. package/dist/providers/data/xai.json +1 -1
  170. package/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
  171. package/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
  172. package/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
  173. package/dist/providers/data/xiaomi.json +1 -1
  174. package/dist/providers/data/zai-coding-cn.json +1 -1
  175. package/dist/providers/data/zai.json +1 -1
  176. package/dist/providers/deepseek.models.js +1 -1
  177. package/dist/providers/deepseek.models.js.map +1 -1
  178. package/dist/providers/faux.d.ts.map +1 -1
  179. package/dist/providers/faux.js +7 -2
  180. package/dist/providers/faux.js.map +1 -1
  181. package/dist/providers/fireworks.models.js +1 -1
  182. package/dist/providers/fireworks.models.js.map +1 -1
  183. package/dist/providers/github-copilot.d.ts +3 -1
  184. package/dist/providers/github-copilot.d.ts.map +1 -1
  185. package/dist/providers/github-copilot.js +13 -2
  186. package/dist/providers/github-copilot.js.map +1 -1
  187. package/dist/providers/github-copilot.models.js +1 -1
  188. package/dist/providers/github-copilot.models.js.map +1 -1
  189. package/dist/providers/google-vertex.models.js +1 -1
  190. package/dist/providers/google-vertex.models.js.map +1 -1
  191. package/dist/providers/google.models.js +1 -1
  192. package/dist/providers/google.models.js.map +1 -1
  193. package/dist/providers/groq.models.js +1 -1
  194. package/dist/providers/groq.models.js.map +1 -1
  195. package/dist/providers/huggingface.models.js +1 -1
  196. package/dist/providers/huggingface.models.js.map +1 -1
  197. package/dist/providers/kimi-coding.models.js +1 -1
  198. package/dist/providers/kimi-coding.models.js.map +1 -1
  199. package/dist/providers/meta.models.js +1 -1
  200. package/dist/providers/meta.models.js.map +1 -1
  201. package/dist/providers/minimax-cn.models.js +1 -1
  202. package/dist/providers/minimax-cn.models.js.map +1 -1
  203. package/dist/providers/minimax.models.js +1 -1
  204. package/dist/providers/minimax.models.js.map +1 -1
  205. package/dist/providers/mistral.models.js +1 -1
  206. package/dist/providers/mistral.models.js.map +1 -1
  207. package/dist/providers/model-schema.d.ts +65 -65
  208. package/dist/providers/model-schema.d.ts.map +1 -1
  209. package/dist/providers/model-schema.js +41 -30
  210. package/dist/providers/model-schema.js.map +1 -1
  211. package/dist/providers/moonshotai-cn.models.js +1 -1
  212. package/dist/providers/moonshotai-cn.models.js.map +1 -1
  213. package/dist/providers/moonshotai.models.js +1 -1
  214. package/dist/providers/moonshotai.models.js.map +1 -1
  215. package/dist/providers/nvidia.models.js +1 -1
  216. package/dist/providers/nvidia.models.js.map +1 -1
  217. package/dist/providers/openai-codex.js +1 -1
  218. package/dist/providers/openai-codex.js.map +1 -1
  219. package/dist/providers/openai-codex.models.js +1 -1
  220. package/dist/providers/openai-codex.models.js.map +1 -1
  221. package/dist/providers/openai.models.js +1 -1
  222. package/dist/providers/openai.models.js.map +1 -1
  223. package/dist/providers/opencode-go.models.js +1 -1
  224. package/dist/providers/opencode-go.models.js.map +1 -1
  225. package/dist/providers/opencode.js +1 -1
  226. package/dist/providers/opencode.js.map +1 -1
  227. package/dist/providers/opencode.models.js +1 -1
  228. package/dist/providers/opencode.models.js.map +1 -1
  229. package/dist/providers/openrouter.models.js +1 -1
  230. package/dist/providers/openrouter.models.js.map +1 -1
  231. package/dist/providers/qwen-token-plan-cn.models.js +1 -1
  232. package/dist/providers/qwen-token-plan-cn.models.js.map +1 -1
  233. package/dist/providers/qwen-token-plan-individual-cn.d.ts +3 -0
  234. package/dist/providers/qwen-token-plan-individual-cn.d.ts.map +1 -0
  235. package/dist/providers/qwen-token-plan-individual-cn.js +15 -0
  236. package/dist/providers/qwen-token-plan-individual-cn.js.map +1 -0
  237. package/dist/providers/qwen-token-plan-individual-cn.models.d.ts +6 -0
  238. package/dist/providers/qwen-token-plan-individual-cn.models.d.ts.map +1 -0
  239. package/dist/providers/qwen-token-plan-individual-cn.models.js +8 -0
  240. package/dist/providers/qwen-token-plan-individual-cn.models.js.map +1 -0
  241. package/dist/providers/qwen-token-plan-individual.models.js +1 -1
  242. package/dist/providers/qwen-token-plan-individual.models.js.map +1 -1
  243. package/dist/providers/qwen-token-plan.models.js +1 -1
  244. package/dist/providers/qwen-token-plan.models.js.map +1 -1
  245. package/dist/providers/radius-config.d.ts.map +1 -1
  246. package/dist/providers/radius-config.js +2 -1
  247. package/dist/providers/radius-config.js.map +1 -1
  248. package/dist/providers/radius.models.js +1 -1
  249. package/dist/providers/radius.models.js.map +1 -1
  250. package/dist/providers/schema-builders.d.ts +10 -0
  251. package/dist/providers/schema-builders.d.ts.map +1 -0
  252. package/dist/providers/schema-builders.js +18 -0
  253. package/dist/providers/schema-builders.js.map +1 -0
  254. package/dist/providers/together.models.js +1 -1
  255. package/dist/providers/together.models.js.map +1 -1
  256. package/dist/providers/typesafe.models.js +1 -1
  257. package/dist/providers/typesafe.models.js.map +1 -1
  258. package/dist/providers/vercel-ai-gateway.models.js +1 -1
  259. package/dist/providers/vercel-ai-gateway.models.js.map +1 -1
  260. package/dist/providers/xai.models.js +1 -1
  261. package/dist/providers/xai.models.js.map +1 -1
  262. package/dist/providers/xiaomi-token-plan-ams.models.js +1 -1
  263. package/dist/providers/xiaomi-token-plan-ams.models.js.map +1 -1
  264. package/dist/providers/xiaomi-token-plan-cn.models.js +1 -1
  265. package/dist/providers/xiaomi-token-plan-cn.models.js.map +1 -1
  266. package/dist/providers/xiaomi-token-plan-sgp.models.js +1 -1
  267. package/dist/providers/xiaomi-token-plan-sgp.models.js.map +1 -1
  268. package/dist/providers/xiaomi.models.js +1 -1
  269. package/dist/providers/xiaomi.models.js.map +1 -1
  270. package/dist/providers/zai-coding-cn.models.js +1 -1
  271. package/dist/providers/zai-coding-cn.models.js.map +1 -1
  272. package/dist/providers/zai.models.js +1 -1
  273. package/dist/providers/zai.models.js.map +1 -1
  274. package/dist/telemetry.d.ts.map +1 -1
  275. package/dist/telemetry.js +2 -1
  276. package/dist/telemetry.js.map +1 -1
  277. package/dist/types.d.ts +20 -3
  278. package/dist/types.d.ts.map +1 -1
  279. package/dist/types.js.map +1 -1
  280. package/dist/utils/error-body.d.ts +8 -0
  281. package/dist/utils/error-body.d.ts.map +1 -1
  282. package/dist/utils/error-body.js +30 -2
  283. package/dist/utils/error-body.js.map +1 -1
  284. package/dist/utils/openrouter-cost.d.ts +24 -0
  285. package/dist/utils/openrouter-cost.d.ts.map +1 -0
  286. package/dist/utils/openrouter-cost.js +34 -0
  287. package/dist/utils/openrouter-cost.js.map +1 -0
  288. package/dist/utils/overflow.d.ts.map +1 -1
  289. package/dist/utils/overflow.js +2 -0
  290. package/dist/utils/overflow.js.map +1 -1
  291. package/dist/utils/retry.d.ts.map +1 -1
  292. package/dist/utils/retry.js +6 -0
  293. package/dist/utils/retry.js.map +1 -1
  294. package/dist/utils/streaming-json.d.ts +84 -0
  295. package/dist/utils/streaming-json.d.ts.map +1 -0
  296. package/dist/utils/streaming-json.js +513 -0
  297. package/dist/utils/streaming-json.js.map +1 -0
  298. package/dist/utils/{typebox-helpers.d.ts → string-enum.d.ts} +5 -5
  299. package/dist/utils/string-enum.d.ts.map +1 -0
  300. package/dist/utils/{typebox-helpers.js → string-enum.js} +5 -6
  301. package/dist/utils/string-enum.js.map +1 -0
  302. package/dist/utils/text.d.ts +7 -0
  303. package/dist/utils/text.d.ts.map +1 -1
  304. package/dist/utils/text.js +9 -0
  305. package/dist/utils/text.js.map +1 -1
  306. package/dist/utils/transcript.d.ts +1 -1
  307. package/dist/utils/transcript.js +1 -1
  308. package/dist/utils/transcript.js.map +1 -1
  309. package/dist/utils/validation.d.ts +5 -3
  310. package/dist/utils/validation.d.ts.map +1 -1
  311. package/dist/utils/validation.js +27 -277
  312. package/dist/utils/validation.js.map +1 -1
  313. package/dist/utils/version.d.ts +1 -1
  314. package/dist/utils/version.js +1 -1
  315. package/dist/utils/version.js.map +1 -1
  316. package/package.json +19 -10
  317. package/dist/utils/typebox-helpers.d.ts.map +0 -1
  318. package/dist/utils/typebox-helpers.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,sBAAsB,GAItB,MAAM,8BAA8B,CAAC;AAItC,MAAM,QAAQ,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,sBAAsB,EAAE,QAAQ,EAAE,IAAI,EAAW,CAAC;AAClG,MAAM,KAAK,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,6BAA6B,EAAE,QAAQ,EAAE,IAAI,EAAW,CAAC;AACtG,MAAM,IAAI,GAAG;IACZ,IAAI,EAAE,QAAQ;IACd,WAAW,EAAE,yBAAyB;IACtC,MAAM,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC;CACvE,CAAC;AACX,MAAM,OAAO,GAAG;IACf,WAAW,EAAE,yEAAyE;IACtF,OAAO,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE;IACxB,eAAe,EAAE;QAChB,QAAQ;QACR,GAAG,EAAE,EAAE,I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;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\tcreateTypedMetrics,\n\tcreateTypedSpanStarter,\n\tdefineTelemetrySchema,\n\tNOOP_TELEMETRY_CONTEXT,\n\tNOOP_TELEMETRY_METRICS,\n\ttype SchemaTelemetrySpan,\n\ttype TelemetryMetrics,\n\ttype TelemetrySpan,\n} from \"@earendil-works/pi-telemetry\";\nimport type { LazyStreamObserver } from \"./api/lazy.ts\";\nimport type { Api, Model } from \"./types.ts\";\n\nconst provider = { type: \"string\", description: \"Provider identifier.\", required: true } as const;\nconst model = { type: \"string\", description: \"Requested model identifier.\", required: true } as const;\nconst stop = {\n\ttype: \"string\",\n\tdescription: \"Normalized stop reason.\",\n\tvalues: [\"pending\", \"stop\", \"length\", \"toolUse\", \"error\", \"aborted\", \"deferred\"],\n} as const;\nconst request = {\n\tdescription: \"One logical model request, including authentication and provider setup.\",\n\tparents: { kind: \"any\" },\n\tstartAttributes: {\n\t\tprovider,\n\t\tapi: { type: \"string\", description: \"API identifier.\", required: true },\n\t\tmodel,\n\t\treasoning: { type: \"string\", description: \"Scalar requested reasoning level.\", required: false },\n\t},\n\tendAttributes: {\n\t\tstop,\n\t\t\"usage.input\": { type: \"number\", description: \"Uncached input tokens.\" },\n\t\t\"usage.output\": { type: \"number\", description: \"Output tokens.\" },\n\t\t\"usage.cache_read\": { type: \"number\", description: \"Cache-read tokens.\" },\n\t\t\"usage.cache_write\": { type: \"number\", description: \"Cache-write tokens.\" },\n\t\t\"cost.total\": { type: \"number\", description: \"Total request cost in USD.\" },\n\t\t\"response.id\": { type: \"string\", description: \"Provider response identifier.\", cardinality: \"high\" },\n\t},\n\tevents: {\n\t\t\"pi.ai.first_chunk\": { description: \"First normalized stream event delivered.\", attributes: {} },\n\t\t\"pi.ai.block\": {\n\t\t\tdescription: \"A completed content block; content is never recorded.\",\n\t\t\tattributes: {\n\t\t\t\ttype: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"Block kind.\",\n\t\t\t\t\tvalues: [\"text\", \"thinking\", \"tool_call\"],\n\t\t\t\t\trequired: true,\n\t\t\t\t},\n\t\t\t\tindex: { type: \"number\", description: \"Content block index.\", required: true },\n\t\t\t\tchars: { type: \"number\", description: \"UTF-16 character count.\", required: true },\n\t\t\t\ttool: { type: \"string\", description: \"Tool name, for tool-call blocks only.\", required: false },\n\t\t\t},\n\t\t},\n\t},\n\tstatus: {\n\t\tdefault: \"ok\",\n\t\terrorWhen: \"Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok.\",\n\t},\n} as const;\n\n/** Pi-owned request metadata, bounded error status, events, and low-cardinality metrics. */\nexport const AI_TELEMETRY_SCHEMA = defineTelemetrySchema({\n\tversion: 1,\n\tspans: {\n\t\t\"pi.ai.request\": request,\n\t\t\"pi.ai.poll\": { ...request, description: \"One deferred-response poll, not the deferred request's lifetime.\" },\n\t},\n\tmetrics: {\n\t\t\"pi.ai.request.duration\": {\n\t\t\tkind: \"histogram\",\n\t\t\tdescription: \"Logical request or poll duration.\",\n\t\t\tunit: \"ms\",\n\t\t\tattributes: { provider, model, stop: { ...stop, required: true } },\n\t\t},\n\t\t\"pi.ai.first_chunk.duration\": {\n\t\t\tkind: \"histogram\",\n\t\t\tdescription: \"Time to the first normalized stream event.\",\n\t\t\tunit: \"ms\",\n\t\t\tattributes: { provider, model },\n\t\t},\n\t\t\"pi.ai.tokens\": {\n\t\t\tkind: \"counter\",\n\t\t\tdescription: \"Reported model token usage; pending and deferred polls are excluded.\",\n\t\t\tunit: \"token\",\n\t\t\tattributes: {\n\t\t\t\tprovider,\n\t\t\t\tmodel,\n\t\t\t\tkind: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"Token usage category.\",\n\t\t\t\t\tvalues: [\"input\", \"output\", \"cache_read\", \"cache_write\"],\n\t\t\t\t\trequired: true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"pi.ai.cost\": {\n\t\t\tkind: \"counter\",\n\t\t\tdescription: \"Reported model cost; pending and deferred polls are excluded.\",\n\t\t\tunit: \"USD\",\n\t\t\tattributes: { provider, model },\n\t\t},\n\t},\n});\n\ntype RequestSpan = SchemaTelemetrySpan<typeof AI_TELEMETRY_SCHEMA, \"pi.ai.request\">;\n\nfunction createInstruments(adapter: TelemetryMetrics) {\n\tconst metrics = createTypedMetrics(adapter, [AI_TELEMETRY_SCHEMA]);\n\treturn {\n\t\trequestDuration: metrics.histogram(\"pi.ai.request.duration\"),\n\t\tfirstChunkDuration: metrics.histogram(\"pi.ai.first_chunk.duration\"),\n\t\ttokens: metrics.counter(\"pi.ai.tokens\"),\n\t\tcost: metrics.counter(\"pi.ai.cost\"),\n\t};\n}\n\nconst instrumentCache = new WeakMap<TelemetryMetrics, ReturnType<typeof createInstruments>>();\n\nexport function observeModelRequest(\n\trequestedModel: Model<Api>,\n\toptions: { telemetry?: TelemetrySpan; reasoning?: unknown } | undefined,\n\tpoll: boolean,\n): LazyStreamObserver {\n\tconst started = performance.now();\n\tconst attributes = { provider: requestedModel.provider, model: requestedModel.id };\n\tconst adapter = options?.telemetry?.metrics ?? NOOP_TELEMETRY_METRICS;\n\tlet instruments = instrumentCache.get(adapter);\n\tif (!instruments) {\n\t\tinstruments = createInstruments(adapter);\n\t\tinstrumentCache.set(adapter, instruments);\n\t}\n\tconst { requestDuration, firstChunkDuration, tokens, cost } = instruments;\n\tlet span!: RequestSpan;\n\tlet finish!: () => void;\n\tlet first = true;\n\tconst toolChars = new Map<number, number>();\n\tconst finished = new Promise<void>((resolve) => {\n\t\tfinish = resolve;\n\t});\n\tconst run = (activeSpan: RequestSpan): Promise<void> => {\n\t\tspan = activeSpan;\n\t\treturn finished;\n\t};\n\tconst startAttributes = {\n\t\t...attributes,\n\t\tapi: requestedModel.api,\n\t\t...(typeof options?.reasoning === \"string\" ? { reasoning: options.reasoning } : {}),\n\t};\n\tconst start = createTypedSpanStarter(options?.telemetry ?? NOOP_TELEMETRY_CONTEXT, [AI_TELEMETRY_SCHEMA]);\n\tif (poll) void start(\"pi.ai.poll\", startAttributes, run);\n\telse void start(\"pi.ai.request\", startAttributes, run);\n\n\treturn {\n\t\tonEvent(event) {\n\t\t\tif (first) {\n\t\t\t\tfirst = false;\n\t\t\t\tspan.addEvent(\"pi.ai.first_chunk\");\n\t\t\t\tfirstChunkDuration.record(performance.now() - started, attributes, span);\n\t\t\t}\n\t\t\tif (event.type === \"toolcall_delta\") {\n\t\t\t\ttoolChars.set(event.contentIndex, (toolChars.get(event.contentIndex) ?? 0) + event.delta.length);\n\t\t\t} else if (event.type === \"text_end\" || event.type === \"thinking_end\") {\n\t\t\t\tspan.addEvent(\"pi.ai.block\", {\n\t\t\t\t\ttype: event.type === \"text_end\" ? \"text\" : \"thinking\",\n\t\t\t\t\tindex: event.contentIndex,\n\t\t\t\t\tchars: event.content.length,\n\t\t\t\t});\n\t\t\t} else if (event.type === \"toolcall_end\") {\n\t\t\t\tconst chars = toolChars.get(event.contentIndex) ?? 0;\n\t\t\t\ttoolChars.delete(event.contentIndex);\n\t\t\t\tspan.addEvent(\"pi.ai.block\", {\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tindex: event.contentIndex,\n\t\t\t\t\tchars,\n\t\t\t\t\ttool: event.toolCall.name,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\tonResult(message) {\n\t\t\tif (message) {\n\t\t\t\tspan.setAttributes({\n\t\t\t\t\tstop: message.stopReason,\n\t\t\t\t\t\"usage.input\": message.usage.input,\n\t\t\t\t\t\"usage.output\": message.usage.output,\n\t\t\t\t\t\"usage.cache_read\": message.usage.cacheRead,\n\t\t\t\t\t\"usage.cache_write\": message.usage.cacheWrite,\n\t\t\t\t\t\"cost.total\": message.usage.cost.total,\n\t\t\t\t\t\"response.id\": message.responseId,\n\t\t\t\t});\n\t\t\t\tif (message.stopReason === \"error\") {\n\t\t\t\t\tspan.setStatus({\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\terror: { name: \"provider_error\", message: message.errorMessage?.slice(0, 500) ?? \"\" },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\trequestDuration.record(performance.now() - started, { ...attributes, stop: message.stopReason }, span);\n\t\t\t\tif (!poll || (message.stopReason !== \"pending\" && message.stopReason !== \"deferred\")) {\n\t\t\t\t\ttokens.add(message.usage.input, { ...attributes, kind: \"input\" });\n\t\t\t\t\ttokens.add(message.usage.output, { ...attributes, kind: \"output\" });\n\t\t\t\t\ttokens.add(message.usage.cacheRead, { ...attributes, kind: \"cache_read\" });\n\t\t\t\t\ttokens.add(message.usage.cacheWrite, { ...attributes, kind: \"cache_write\" });\n\t\t\t\t\tcost.add(message.usage.cost.total, attributes);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinish();\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,kBAAkB,EAClB,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,sBAAsB,GAItB,MAAM,8BAA8B,CAAC;AAGtC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,MAAM,QAAQ,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,sBAAsB,EAAE,QAAQ,EAAE,IAAI,EAAW,CAAC;AAClG,MAAM,KAAK,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,6BAA6B,EAAE,QAAQ,EAAE,IAAI,EAAW,CAAC;AACtG,MAAM,IAAI,GAAG;IACZ,IAAI,EAAE,QAAQ;IACd,WAAW,EAAE,yBAAyB;IACtC,MAAM,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC;CACvE,CAAC;AACX,MAAM,OAAO,GAAG;IACf,WAAW,EAAE,yEAAyE;IACtF,OAAO,EAAE,EAAE,IAAI,EAAE,KAAK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,CAAC;gBAChD,CAAC;YACF,CAAC;YACD,MAAM,EAAE,CAAC;QACV,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import {\n\tcreateTypedMetrics,\n\tcreateTypedSpanStarter,\n\tdefineTelemetrySchema,\n\tNOOP_TELEMETRY_CONTEXT,\n\tNOOP_TELEMETRY_METRICS,\n\ttype SchemaTelemetrySpan,\n\ttype TelemetryMetrics,\n\ttype TelemetrySpan,\n} from \"@earendil-works/pi-telemetry\";\nimport type { LazyStreamObserver } from \"./api/lazy.ts\";\nimport type { Api, Model } from \"./types.ts\";\nimport { ownedSlice } from \"./utils/text.ts\";\n\nconst provider = { type: \"string\", description: \"Provider identifier.\", required: true } as const;\nconst model = { type: \"string\", description: \"Requested model identifier.\", required: true } as const;\nconst stop = {\n\ttype: \"string\",\n\tdescription: \"Normalized stop reason.\",\n\tvalues: [\"pending\", \"stop\", \"length\", \"toolUse\", \"error\", \"aborted\", \"deferred\"],\n} as const;\nconst request = {\n\tdescription: \"One logical model request, including authentication and provider setup.\",\n\tparents: { kind: \"any\" },\n\tstartAttributes: {\n\t\tprovider,\n\t\tapi: { type: \"string\", description: \"API identifier.\", required: true },\n\t\tmodel,\n\t\treasoning: { type: \"string\", description: \"Scalar requested reasoning level.\", required: false },\n\t},\n\tendAttributes: {\n\t\tstop,\n\t\t\"usage.input\": { type: \"number\", description: \"Uncached input tokens.\" },\n\t\t\"usage.output\": { type: \"number\", description: \"Output tokens.\" },\n\t\t\"usage.cache_read\": { type: \"number\", description: \"Cache-read tokens.\" },\n\t\t\"usage.cache_write\": { type: \"number\", description: \"Cache-write tokens.\" },\n\t\t\"cost.total\": { type: \"number\", description: \"Total request cost in USD.\" },\n\t\t\"response.id\": { type: \"string\", description: \"Provider response identifier.\", cardinality: \"high\" },\n\t},\n\tevents: {\n\t\t\"pi.ai.first_chunk\": { description: \"First normalized stream event delivered.\", attributes: {} },\n\t\t\"pi.ai.block\": {\n\t\t\tdescription: \"A completed content block; content is never recorded.\",\n\t\t\tattributes: {\n\t\t\t\ttype: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"Block kind.\",\n\t\t\t\t\tvalues: [\"text\", \"thinking\", \"tool_call\"],\n\t\t\t\t\trequired: true,\n\t\t\t\t},\n\t\t\t\tindex: { type: \"number\", description: \"Content block index.\", required: true },\n\t\t\t\tchars: { type: \"number\", description: \"UTF-16 character count.\", required: true },\n\t\t\t\ttool: { type: \"string\", description: \"Tool name, for tool-call blocks only.\", required: false },\n\t\t\t},\n\t\t},\n\t},\n\tstatus: {\n\t\tdefault: \"ok\",\n\t\terrorWhen: \"Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok.\",\n\t},\n} as const;\n\n/** Pi-owned request metadata, bounded error status, events, and low-cardinality metrics. */\nexport const AI_TELEMETRY_SCHEMA = defineTelemetrySchema({\n\tversion: 1,\n\tspans: {\n\t\t\"pi.ai.request\": request,\n\t\t\"pi.ai.poll\": { ...request, description: \"One deferred-response poll, not the deferred request's lifetime.\" },\n\t},\n\tmetrics: {\n\t\t\"pi.ai.request.duration\": {\n\t\t\tkind: \"histogram\",\n\t\t\tdescription: \"Logical request or poll duration.\",\n\t\t\tunit: \"ms\",\n\t\t\tattributes: { provider, model, stop: { ...stop, required: true } },\n\t\t},\n\t\t\"pi.ai.first_chunk.duration\": {\n\t\t\tkind: \"histogram\",\n\t\t\tdescription: \"Time to the first normalized stream event.\",\n\t\t\tunit: \"ms\",\n\t\t\tattributes: { provider, model },\n\t\t},\n\t\t\"pi.ai.tokens\": {\n\t\t\tkind: \"counter\",\n\t\t\tdescription: \"Reported model token usage; pending and deferred polls are excluded.\",\n\t\t\tunit: \"token\",\n\t\t\tattributes: {\n\t\t\t\tprovider,\n\t\t\t\tmodel,\n\t\t\t\tkind: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescription: \"Token usage category.\",\n\t\t\t\t\tvalues: [\"input\", \"output\", \"cache_read\", \"cache_write\"],\n\t\t\t\t\trequired: true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"pi.ai.cost\": {\n\t\t\tkind: \"counter\",\n\t\t\tdescription: \"Reported model cost; pending and deferred polls are excluded.\",\n\t\t\tunit: \"USD\",\n\t\t\tattributes: { provider, model },\n\t\t},\n\t},\n});\n\ntype RequestSpan = SchemaTelemetrySpan<typeof AI_TELEMETRY_SCHEMA, \"pi.ai.request\">;\n\nfunction createInstruments(adapter: TelemetryMetrics) {\n\tconst metrics = createTypedMetrics(adapter, [AI_TELEMETRY_SCHEMA]);\n\treturn {\n\t\trequestDuration: metrics.histogram(\"pi.ai.request.duration\"),\n\t\tfirstChunkDuration: metrics.histogram(\"pi.ai.first_chunk.duration\"),\n\t\ttokens: metrics.counter(\"pi.ai.tokens\"),\n\t\tcost: metrics.counter(\"pi.ai.cost\"),\n\t};\n}\n\nconst instrumentCache = new WeakMap<TelemetryMetrics, ReturnType<typeof createInstruments>>();\n\nexport function observeModelRequest(\n\trequestedModel: Model<Api>,\n\toptions: { telemetry?: TelemetrySpan; reasoning?: unknown } | undefined,\n\tpoll: boolean,\n): LazyStreamObserver {\n\tconst started = performance.now();\n\tconst attributes = { provider: requestedModel.provider, model: requestedModel.id };\n\tconst adapter = options?.telemetry?.metrics ?? NOOP_TELEMETRY_METRICS;\n\tlet instruments = instrumentCache.get(adapter);\n\tif (!instruments) {\n\t\tinstruments = createInstruments(adapter);\n\t\tinstrumentCache.set(adapter, instruments);\n\t}\n\tconst { requestDuration, firstChunkDuration, tokens, cost } = instruments;\n\tlet span!: RequestSpan;\n\tlet finish!: () => void;\n\tlet first = true;\n\tconst toolChars = new Map<number, number>();\n\tconst finished = new Promise<void>((resolve) => {\n\t\tfinish = resolve;\n\t});\n\tconst run = (activeSpan: RequestSpan): Promise<void> => {\n\t\tspan = activeSpan;\n\t\treturn finished;\n\t};\n\tconst startAttributes = {\n\t\t...attributes,\n\t\tapi: requestedModel.api,\n\t\t...(typeof options?.reasoning === \"string\" ? { reasoning: options.reasoning } : {}),\n\t};\n\tconst start = createTypedSpanStarter(options?.telemetry ?? NOOP_TELEMETRY_CONTEXT, [AI_TELEMETRY_SCHEMA]);\n\tif (poll) void start(\"pi.ai.poll\", startAttributes, run);\n\telse void start(\"pi.ai.request\", startAttributes, run);\n\n\treturn {\n\t\tonEvent(event) {\n\t\t\tif (first) {\n\t\t\t\tfirst = false;\n\t\t\t\tspan.addEvent(\"pi.ai.first_chunk\");\n\t\t\t\tfirstChunkDuration.record(performance.now() - started, attributes, span);\n\t\t\t}\n\t\t\tif (event.type === \"toolcall_delta\") {\n\t\t\t\ttoolChars.set(event.contentIndex, (toolChars.get(event.contentIndex) ?? 0) + event.delta.length);\n\t\t\t} else if (event.type === \"text_end\" || event.type === \"thinking_end\") {\n\t\t\t\tspan.addEvent(\"pi.ai.block\", {\n\t\t\t\t\ttype: event.type === \"text_end\" ? \"text\" : \"thinking\",\n\t\t\t\t\tindex: event.contentIndex,\n\t\t\t\t\tchars: event.content.length,\n\t\t\t\t});\n\t\t\t} else if (event.type === \"toolcall_end\") {\n\t\t\t\tconst chars = toolChars.get(event.contentIndex) ?? 0;\n\t\t\t\ttoolChars.delete(event.contentIndex);\n\t\t\t\tspan.addEvent(\"pi.ai.block\", {\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tindex: event.contentIndex,\n\t\t\t\t\tchars,\n\t\t\t\t\ttool: event.toolCall.name,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\tonResult(message) {\n\t\t\tif (message) {\n\t\t\t\tspan.setAttributes({\n\t\t\t\t\tstop: message.stopReason,\n\t\t\t\t\t\"usage.input\": message.usage.input,\n\t\t\t\t\t\"usage.output\": message.usage.output,\n\t\t\t\t\t\"usage.cache_read\": message.usage.cacheRead,\n\t\t\t\t\t\"usage.cache_write\": message.usage.cacheWrite,\n\t\t\t\t\t\"cost.total\": message.usage.cost.total,\n\t\t\t\t\t\"response.id\": message.responseId,\n\t\t\t\t});\n\t\t\t\tif (message.stopReason === \"error\") {\n\t\t\t\t\tspan.setStatus({\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\terror: { name: \"provider_error\", message: ownedSlice(message.errorMessage ?? \"\", 0, 500) },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\trequestDuration.record(performance.now() - started, { ...attributes, stop: message.stopReason }, span);\n\t\t\t\tif (!poll || (message.stopReason !== \"pending\" && message.stopReason !== \"deferred\")) {\n\t\t\t\t\ttokens.add(message.usage.input, { ...attributes, kind: \"input\" });\n\t\t\t\t\ttokens.add(message.usage.output, { ...attributes, kind: \"output\" });\n\t\t\t\t\ttokens.add(message.usage.cacheRead, { ...attributes, kind: \"cache_read\" });\n\t\t\t\t\ttokens.add(message.usage.cacheWrite, { ...attributes, kind: \"cache_write\" });\n\t\t\t\t\tcost.add(message.usage.cost.total, attributes);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinish();\n\t\t},\n\t};\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -23,7 +23,7 @@ export type KnownImageApi = "openrouter-images";
23
23
  export type ImageApi = KnownImageApi | (string & {});
24
24
  export type KnownClassifierApi = "typesafe-system-one" | "cloudflare-workers-ai-system-one" | "llama-cpp-classify" | "openai-decisions";
25
25
  export type ClassifierApi = KnownClassifierApi | (string & {});
26
- export type KnownProvider = "amazon-bedrock" | "ant-ling" | "anthropic" | "google" | "google-vertex" | "openai" | "azure" | "openai-codex" | "radius" | "typesafe" | "nvidia" | "deepseek" | "github-copilot" | "xai" | "groq" | "cerebras" | "openrouter" | "vercel-ai-gateway" | "zai" | "zai-coding-cn" | "mistral" | "minimax" | "minimax-cn" | "moonshotai" | "moonshotai-cn" | "huggingface" | "fireworks" | "together" | "baseten" | "opencode" | "opencode-go" | "kimi-coding" | "meta" | "cloudflare-workers-ai" | "cloudflare-ai-gateway" | "qwen-token-plan" | "qwen-token-plan-cn" | "qwen-token-plan-individual" | "xiaomi" | "xiaomi-token-plan-cn" | "xiaomi-token-plan-ams" | "xiaomi-token-plan-sgp";
26
+ export type KnownProvider = "amazon-bedrock" | "ant-ling" | "anthropic" | "google" | "google-vertex" | "openai" | "azure" | "openai-codex" | "radius" | "typesafe" | "nvidia" | "deepseek" | "github-copilot" | "xai" | "groq" | "cerebras" | "openrouter" | "vercel-ai-gateway" | "zai" | "zai-coding-cn" | "mistral" | "minimax" | "minimax-cn" | "moonshotai" | "moonshotai-cn" | "huggingface" | "fireworks" | "together" | "baseten" | "opencode" | "opencode-go" | "kimi-coding" | "meta" | "cloudflare-workers-ai" | "cloudflare-ai-gateway" | "qwen-token-plan" | "qwen-token-plan-cn" | "qwen-token-plan-individual" | "qwen-token-plan-individual-cn" | "xiaomi" | "xiaomi-token-plan-cn" | "xiaomi-token-plan-ams" | "xiaomi-token-plan-sgp";
27
27
  export type ProviderId = KnownProvider | string;
28
28
  export type ToolChoice = "auto" | "none";
29
29
  export type SamplingParams = Record<string, unknown>;
@@ -142,6 +142,13 @@ export interface StreamOptions extends ProviderRequestOptions<Model<Api>> {
142
142
  * session-aware features. Ignored by providers that don't support it.
143
143
  */
144
144
  sessionId?: string;
145
+ /**
146
+ * Do not use or record server-side continuation state for this request (for example
147
+ * Anthropic message threads). Set this for replays such as cache warming, which must not
148
+ * replace the state of the real conversation. Providers that do not keep continuation
149
+ * state ignore it.
150
+ */
151
+ disableContinuation?: boolean;
145
152
  /**
146
153
  * WebSocket connect timeout in milliseconds for providers that support
147
154
  * WebSocket transports. This covers the connection/open handshake only;
@@ -297,11 +304,18 @@ export interface Usage {
297
304
  reasoning?: number;
298
305
  totalTokens: number;
299
306
  cost: {
307
+ /** Catalog-derived input cost. */
300
308
  input: number;
309
+ /** Catalog-derived output cost. */
301
310
  output: number;
311
+ /** Catalog-derived cache-read cost. */
302
312
  cacheRead: number;
313
+ /** Catalog-derived cache-write cost. */
303
314
  cacheWrite: number;
315
+ /** Best available total: provider-reported billed cost when supported, otherwise the catalog estimate. */
304
316
  total: number;
317
+ /** True when `total` is the billed cost reported by the provider. False when it is a catalog estimate; absent also means false. */
318
+ totalFromProvider?: boolean;
305
319
  };
306
320
  }
307
321
  export type StopReason = "pending" | "stop" | "length" | "toolUse" | "error" | "aborted" | "deferred";
@@ -507,7 +521,6 @@ export interface ClassifierResult {
507
521
  errorMessage?: string;
508
522
  timestamp: number;
509
523
  }
510
- import type { TSchema } from "typebox";
511
524
  /** OpenAI grammar variants for constrained sampling. */
512
525
  export type GrammarFormat = "openai_lark" | "openai_regex";
513
526
  export type GrammarVariants = Partial<Record<GrammarFormat, string>>;
@@ -525,7 +538,11 @@ export type ConstrainedSamplingConfig = {
525
538
  type: "grammar";
526
539
  variants: GrammarVariants;
527
540
  };
528
- export interface Tool<TParameters extends TSchema = TSchema> {
541
+ /**
542
+ * A tool the model may call. `parameters` is the JSON Schema of its arguments: pi-schema's builders (which also type
543
+ * the arguments, see `Static` in `@earendil-works/pi-schema`), TypeBox schemas, or any JSON Schema object.
544
+ */
545
+ export interface Tool<TParameters extends object = object> {
529
546
  name: string;
530
547
  description: string;
531
548
  parameters: TParameters;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM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AI,SAAS,uBAAuB,GACnC,0BAA0B,GAC1B,KAAK,CAAC;CACb;AAED,mEAAmE;AACnE,MAAM,WAAW,UAAU,CAAC,IAAI,SAAS,QAAQ,CAAE,SAAQ,SAAS,CAAC,IAAI,CAAC;IACzE,IAAI,EAAE,OAAO,CAAC;IACd,0GAA0G;IAC1G,MAAM,EAAE,CAAC,MAAM,GAAG,OAAO,CAAC,EAAE,CAAC;CAC7B;AAED,kEAAkE;AAClE,MAAM,WAAW,eAAe,CAAC,IAAI,SAAS,aAAa,CAAE,SAAQ,SAAS,CAAC,IAAI,CAAC;IACnF,IAAI,EAAE,YAAY,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,6GAA6G;IAC7G,MAAM,CAAC,EAAE,IAAI,SAAS,qBAAqB,GAAG,kCAAkC,GAAG,eAAe,GAAG,KAAK,CAAC;CAC3G;AAED,uCAAuC;AACvC,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IACjB,KAAK,EAAE,UAAU,CAAC,QAAQ,CAAC,CAAC;IAC5B,UAAU,EAAE,eAAe,CAAC,aAAa,CAAC,CAAC;CAC3C;AAED,gFAAgF;AAChF,MAAM,MAAM,SAAS,GAAG,MAAM,YAAY,CAAC;AAE3C,iEAAiE;AACjE,MAAM,MAAM,QAAQ,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TelemetrySpan } from \"@earendil-works/pi-telemetry\";\nimport type { AnthropicOptions } from \"./api/anthropic-messages.ts\";\nimport type { AzureOpenAIResponsesOptions } from \"./api/azure-openai-responses.ts\";\nimport type { BedrockOptions } from \"./api/bedrock-converse-stream.ts\";\nimport type { GoogleOptions } from \"./api/google-generative-ai.ts\";\nimport type { GoogleVertexOptions } from \"./api/google-vertex.ts\";\nimport type { MistralOptions } from \"./api/mistral-conversations.ts\";\nimport type { OpenAICodexResponsesOptions } from \"./api/openai-codex-responses.ts\";\nimport type { OpenAICompletionsOptions } from \"./api/openai-completions.ts\";\nimport type { OpenAIResponsesOptions } from \"./api/openai-responses.ts\";\nimport type { PiMessagesOptions } from \"./api/pi-messages.ts\";\nimport type {\n\tAnthropicMessagesCompat,\n\tBedrockCompat,\n\tMistralConversationsCompat,\n\tOpenAICompletionsCompat,\n\tOpenAIResponsesCompat,\n\tSystemOneCompat,\n} from \"./providers/compat-schema.ts\";\nimport type {\n\tCacheRetention,\n\tModelCost,\n\tModelInputLimits,\n\tModelInputModality,\n\tModelPromptCache,\n\tModelThinkingLevel,\n\tThinkingLevel,\n\tThinkingLevelMap,\n} from \"./providers/model-schema.ts\";\nimport type { AssistantMessageDiagnostic } from \"./utils/diagnostics.ts\";\nimport type { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\nimport type { ClientIdentity } from \"./utils/identity.ts\";\n\nexport type {\n\tAnthropicAllowedFallbackModel,\n\tAnthropicMessagesCompat,\n\tBedrockCompat,\n\tChatTemplateKwargValue,\n\tMistralConversationsCompat,\n\tOpenAICompletionsCompat,\n\tOpenAIResponsesCompat,\n\tOpenRouterRouting,\n\tSessionAffinityFormat,\n\tSystemOneCompat,\n\tThinkingTokenBudgetField,\n\tVercelGatewayRouting,\n} from \"./providers/compat-schema.ts\";\nexport type {\n\tCacheRetention,\n\tModelCost,\n\tModelCostRates,\n\tModelCostTier,\n\tModelImageInputLimits,\n\tModelImageResizeOptions,\n\tModelInputLimits,\n\tModelInputModality,\n\tModelPromptCache,\n\tModelThinkingLevel,\n\tThinkingLevel,\n\tThinkingLevelMap,\n} from \"./providers/model-schema.ts\";\nexport type { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\n\nexport type KnownApi =\n\t| \"openai-completions\"\n\t| \"mistral-conversations\"\n\t| \"openai-responses\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex-responses\"\n\t| \"anthropic-messages\"\n\t| \"bedrock-converse-stream\"\n\t| \"google-generative-ai\"\n\t| \"google-vertex\"\n\t| \"pi-messages\";\n\nexport type Api = KnownApi | (string & {});\n\nexport type KnownImageApi = \"openrouter-images\";\n\nexport type ImageApi = KnownImageApi | (string & {});\n\nexport type KnownClassifierApi =\n\t| \"typesafe-system-one\"\n\t| \"cloudflare-workers-ai-system-one\"\n\t| \"llama-cpp-classify\"\n\t| \"openai-decisions\";\n\nexport type ClassifierApi = KnownClassifierApi | (string & {});\n\nexport type KnownProvider =\n\t| \"amazon-bedrock\"\n\t| \"ant-ling\"\n\t| \"anthropic\"\n\t| \"google\"\n\t| \"google-vertex\"\n\t| \"openai\"\n\t| \"azure\"\n\t| \"openai-codex\"\n\t| \"radius\"\n\t| \"typesafe\"\n\t| \"nvidia\"\n\t| \"deepseek\"\n\t| \"github-copilot\"\n\t| \"xai\"\n\t| \"groq\"\n\t| \"cerebras\"\n\t| \"openrouter\"\n\t| \"vercel-ai-gateway\"\n\t| \"zai\"\n\t| \"zai-coding-cn\"\n\t| \"mistral\"\n\t| \"minimax\"\n\t| \"minimax-cn\"\n\t| \"moonshotai\"\n\t| \"moonshotai-cn\"\n\t| \"huggingface\"\n\t| \"fireworks\"\n\t| \"together\"\n\t| \"baseten\"\n\t| \"opencode\"\n\t| \"opencode-go\"\n\t| \"kimi-coding\"\n\t| \"meta\"\n\t| \"cloudflare-workers-ai\"\n\t| \"cloudflare-ai-gateway\"\n\t| \"qwen-token-plan\"\n\t| \"qwen-token-plan-cn\"\n\t| \"qwen-token-plan-individual\"\n\t| \"xiaomi\"\n\t| \"xiaomi-token-plan-cn\"\n\t| \"xiaomi-token-plan-ams\"\n\t| \"xiaomi-token-plan-sgp\";\nexport type ProviderId = KnownProvider | string;\n\nexport type ToolChoice = \"auto\" | \"none\";\nexport type SamplingParams = Record<string, unknown>;\nexport type SamplingParamsByThinkingLevel = Partial<Record<ModelThinkingLevel, SamplingParams>>;\n/** Token budgets for each thinking level (token-based providers only) */\nexport interface ThinkingBudgets {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\n// Base options all providers share\nexport type Transport = \"sse\" | \"websocket\" | \"websocket-cached\" | \"auto\";\n\n/** Provider-scoped environment overrides. Values take precedence over process.env. */\nexport type ProviderEnv = Record<string, string>;\nexport type ProviderHeaders = Record<string, string | null>;\nexport type FetchFunction = typeof globalThis.fetch;\n\nexport interface ProviderResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Authentication, HTTP transport, and lifecycle callbacks shared by provider requests. */\nexport interface ProviderRequestOptions<TModel = Model<Api>> {\n\tsignal?: AbortSignal;\n\t/** Explicit parent span for telemetry produced by this logical request. */\n\ttelemetry?: TelemetrySpan;\n\tapiKey?: string;\n\t/**\n\t * Optional fetch implementation for provider HTTP requests.\n\t * Defaults to `globalThis.fetch`. Provider adapters that cannot inject a custom implementation may reject it.\n\t * This does not affect WebSocket transports.\n\t */\n\tfetch?: FetchFunction;\n\t/**\n\t * Provider-scoped environment values. These take precedence over process.env for\n\t * provider configuration such as regional settings, endpoint placeholders, and\n\t * proxy variables.\n\t */\n\tenv?: ProviderEnv;\n\t/**\n\t * Optional callback for inspecting or replacing provider payloads before sending.\n\t * Return undefined to keep the payload unchanged.\n\t */\n\tonPayload?: (payload: unknown, model: TModel) => unknown | undefined | Promise<unknown | undefined>;\n\t/**\n\t * Optional callback invoked after an HTTP response is received.\n\t */\n\tonResponse?: (response: ProviderResponse, model: TModel) => void | Promise<void>;\n\t/**\n\t * Optional custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; caller values override default headers.\n\t * On AWS Bedrock these are injected via a Smithy `build`-step middleware so\n\t * they are covered by SigV4 signing; reserved headers (`x-amz-*`,\n\t * `authorization`, `host`) are silently ignored to preserve SigV4 / bearer auth.\n\t * A null value suppresses a provider/API default header with the same name.\n\t */\n\theaders?: ProviderHeaders;\n\t/**\n\t * How the request identifies the calling app: `User-Agent` and provider attribution headers.\n\t * Absent fields use pi-ai's defaults: a detailed `User-Agent` and no attribution.\n\t */\n\tidentity?: ClientIdentity;\n\t/**\n\t * HTTP request timeout in milliseconds for providers/SDKs that support it.\n\t * For example, OpenAI and Anthropic SDK clients default to 10 minutes.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum retry attempts for providers/SDKs that support client-side retries.\n\t * For example, OpenAI and Anthropic SDK clients default to 2.\n\t */\n\tmaxRetries?: number;\n\t/**\n\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t * If the server's requested delay exceeds this value, the request fails immediately\n\t * with an error containing the requested delay, allowing higher-level retry logic\n\t * to handle it with user visibility.\n\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t */\n\tmaxRetryDelayMs?: number;\n}\n\nexport interface StreamOptions extends ProviderRequestOptions<Model<Api>> {\n\t/**\n\t * Optional callback invoked after an HTTP response is received and before\n\t * its body stream is consumed.\n\t */\n\tonResponse?: (response: ProviderResponse, model: Model<Api>) => void | Promise<void>;\n\t/**\n\t * Optional observer for each parsed provider stream event before Pi normalization.\n\t * Event data is adapter-owned and must be treated as read-only.\n\t * Adapter support is explicit; unsupported adapters do not invoke it.\n\t */\n\tonProviderStreamEvent?: (data: unknown, model: Model<Api>) => void | Promise<void>;\n\ttemperature?: number;\n\t/**\n\t * Arbitrary sampling parameters merged into the request body as-is, after the named request\n\t * fields, so keys here override them. Lets custom OpenAI-compatible servers (llama.cpp, vLLM,\n\t * SGLang, ...) receive parameters pi does not model, e.g. `top_p`, `top_k`, `min_p`,\n\t * `repetition_penalty`. Merged over `Model.samplingParams` per key. Only applied by\n\t * OpenAI-compatible adapters (completions, responses, Azure responses); other APIs ignore it.\n\t */\n\tsamplingParams?: SamplingParams;\n\tmaxTokens?: number;\n\t/**\n\t * Preferred transport for providers that support multiple transports.\n\t * Providers that do not support this option ignore it.\n\t */\n\ttransport?: Transport;\n\t/**\n\t * Prompt cache retention preference. Providers map this to their supported values.\n\t * Default: \"short\".\n\t */\n\tcacheRetention?: CacheRetention;\n\t/**\n\t * Optional session identifier for providers that support session-based caching.\n\t * Providers can use this to enable prompt caching, request routing, or other\n\t * session-aware features. Ignored by providers that don't support it.\n\t */\n\tsessionId?: string;\n\t/**\n\t * WebSocket connect timeout in milliseconds for providers that support\n\t * WebSocket transports. This covers the connection/open handshake only;\n\t * stream idleness after connection uses timeoutMs.\n\t */\n\twebsocketConnectTimeoutMs?: number;\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t * For example, Anthropic uses `user_id` for abuse tracking and rate limiting.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderStreamOptions = StreamOptions & Record<string, unknown>;\n\nexport interface DeferredFetchOptions extends ProviderRequestOptions<Model<Api>> {\n\t/**\n\t * Maximum provider long-poll duration in milliseconds.\n\t * Defaults to 0, which performs one status check.\n\t */\n\twait?: number;\n}\n\n/** Request options for best-effort deferred-response cancellation. */\nexport type DeferredCancelOptions = ProviderRequestOptions<Model<Api>>;\n\n/**\n * Maps known APIs to their full provider-specific stream option types.\n * Type-only imports from API implementation modules are erased at emit, so\n * this is tree-shake safe.\n */\nexport interface ApiOptionsMap {\n\t\"anthropic-messages\": AnthropicOptions;\n\t\"openai-completions\": OpenAICompletionsOptions;\n\t\"openai-responses\": OpenAIResponsesOptions;\n\t\"openai-codex-responses\": OpenAICodexResponsesOptions;\n\t\"azure-openai-responses\": AzureOpenAIResponsesOptions;\n\t\"google-generative-ai\": GoogleOptions;\n\t\"google-vertex\": GoogleVertexOptions;\n\t\"mistral-conversations\": MistralOptions;\n\t\"bedrock-converse-stream\": BedrockOptions;\n\t\"pi-messages\": PiMessagesOptions;\n}\n\n/**\n * Full stream options for an API. Known APIs resolve to their concrete option\n * type; custom API strings fall back to the generic shape.\n */\nexport type ApiStreamOptions<TApi extends Api> = TApi extends keyof ApiOptionsMap\n\t? ApiOptionsMap[TApi]\n\t: StreamOptions & Record<string, unknown>;\n\n/**\n * The uniform stream contract of an API implementation module: every module\n * under `src/api/` exports `stream` and `streamSimple`; capable modules may also\n * export deferred-response methods. Lazy wrappers (`lazyApi()`) and provider\n * factories pass these around as values. This is the untyped dispatch shape;\n * per-API option typing lives on the implementation modules themselves and on\n * `Provider.stream()` via `ApiStreamOptions`.\n */\nexport interface ProviderStreams {\n\tstream(model: Model<Api>, context: TranscriptContext, options?: StreamOptions): AssistantMessageEventStream;\n\tstreamSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: SimpleStreamOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred?(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: DeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tcancelDeferred?(model: Model<Api>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;\n}\n\n/**\n * The uniform contract of an image-generation API implementation module:\n * every image API module under `src/api/` exports exactly `generateImages`,\n * so the module itself satisfies this interface. Lazy wrappers and\n * `createProvider({ images })` pass these around as values.\n */\nexport interface ProviderImages {\n\tgenerateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ImagesOptions,\n\t): Promise<AssistantImages>;\n}\n\n/** The uniform contract implemented by classifier API modules. */\nexport interface ProviderClassifier {\n\tclassify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\nexport interface ClassifierOptions extends ProviderRequestOptions<ClassifierModel<ClassifierApi>> {\n\t/**\n\t * Divides the answer logits by this value before they are normalized into probabilities.\n\t * Values above 1 soften the distribution; values below 1 sharpen it. Must be positive.\n\t * APIs that cannot apply it ignore it.\n\t */\n\ttemperature?: number;\n}\n\nexport interface ImagesOptions extends ProviderRequestOptions<ImageModel<ImageApi>> {\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderImagesOptions = ImagesOptions & Record<string, unknown>;\n\n// Unified options with reasoning passed to streamSimple() and completeSimple()\nexport interface SimpleStreamOptions extends StreamOptions {\n\t/** Provider-neutral tool selection for simple requests. When omitted, adapters use provider-specific behavior. */\n\ttoolChoice?: ToolChoice;\n\treasoning?: ThinkingLevel;\n\t/** Ask a capable provider to return a durable handle and continue the request asynchronously. */\n\tdeferred?: boolean | { window?: \"15m\" | \"1h\" | \"24h\" };\n\t/** Custom token budgets for thinking levels (token-based providers only) */\n\tthinkingBudgets?: ThinkingBudgets;\n}\n\n// Generic StreamFunction with typed options.\n//\n// Contract:\n// - Receives a normalized transcript: the system prompt and tools live in the\n// leading system message, never on the context itself.\n// - Must return an AssistantMessageEventStream.\n// - Direct streamSimple() calls may throw synchronously when request auth is\n// missing. Once a stream is returned, request/model/runtime failures should\n// be encoded in that stream.\n// - Error termination must produce an AssistantMessage with stopReason\n// \"error\" or \"aborted\" and errorMessage, emitted via the stream protocol.\nexport type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (\n\tmodel: Model<TApi>,\n\tcontext: TranscriptContext,\n\toptions?: TOptions,\n) => AssistantMessageEventStream;\n\nexport type ImagesFunction<TOptions extends ImagesOptions = ImagesOptions> = (\n\tmodel: ImageModel<ImageApi>,\n\tcontext: ImagesContext,\n\toptions?: TOptions,\n) => Promise<AssistantImages>;\n\nexport type ClassifierFunction<TOptions extends ClassifierOptions = ClassifierOptions> = (\n\tmodel: ClassifierModel<ClassifierApi>,\n\tcontext: ClassifierContext,\n\toptions?: TOptions,\n) => Promise<ClassifierResult>;\n\nexport interface TextSignatureV1 {\n\tv: 1;\n\tid: string;\n\tphase?: \"commentary\" | \"final_answer\";\n}\n\nexport interface TextContent {\n\ttype: \"text\";\n\ttext: string;\n\ttextSignature?: string; // e.g., for OpenAI responses, message metadata (legacy id string or TextSignatureV1 JSON)\n}\n\nexport interface ThinkingContent {\n\ttype: \"thinking\";\n\tthinking: string;\n\tthinkingSignature?: string; // Provider-specific opaque or serialized reasoning replay data\n\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t * to the API for multi-turn continuity. */\n\tredacted?: boolean;\n}\n\nexport interface ImageContent {\n\ttype: \"image\";\n\tdata: string; // base64 encoded image data\n\tmimeType: string; // e.g., \"image/jpeg\", \"image/png\"\n}\n\nexport interface ToolCall {\n\ttype: \"toolCall\";\n\tid: string;\n\tname: string;\n\targuments: JsonObject;\n\tthoughtSignature?: string; // Google-specific: opaque signature for reusing thought context\n\t/** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */\n\tnamespace?: string;\n\t/**\n\t * Set when the model's complete arguments text was not a valid JSON object. `arguments` is then `{}`.\n\t * Describes the problem and includes the text the model sent; tool argument validation fails with it.\n\t */\n\targumentsError?: string;\n}\n\nexport interface Usage {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\t/** Subset of `cacheWrite` written with 1h retention. Only Anthropic reports this split. */\n\tcacheWrite1h?: number;\n\t/**\n\t * Reasoning/thinking tokens, when the provider reports them. This is a subset of\n\t * `output`: `output` already includes these tokens. Set to a number (possibly 0) by\n\t * providers that expose a reasoning breakdown; left undefined by providers that don't.\n\t */\n\treasoning?: number;\n\ttotalTokens: number;\n\tcost: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n}\n\nexport type StopReason = \"pending\" | \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\" | \"deferred\";\n\nexport type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject;\nexport type JsonObject = { [key: string]: JsonValue };\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype IsExactlyJsonValue<T> = [T] extends [JsonValue] ? ([JsonValue] extends [T] ? true : false) : false;\ntype IsJsonProperty<T> = IsAny<T> extends true\n\t? false\n\t: unknown extends T\n\t\t? false\n\t\t: [Exclude<T, undefined>] extends [never]\n\t\t\t? true\n\t\t\t: IsJsonCompatible<Exclude<T, undefined>>;\ntype InvalidJsonKeys<T extends object> = {\n\t[TKey in keyof T]-?: TKey extends string | number ? (IsJsonProperty<T[TKey]> extends true ? never : TKey) : TKey;\n}[keyof T];\ntype IsJsonCompatible<T> = IsAny<T> extends true\n\t? false\n\t: unknown extends T\n\t\t? false\n\t\t: IsExactlyJsonValue<T> extends true\n\t\t\t? true\n\t\t\t: T extends null | boolean | number | string\n\t\t\t\t? true\n\t\t\t\t: T extends undefined\n\t\t\t\t\t? false\n\t\t\t\t\t: T extends readonly (infer TItem)[]\n\t\t\t\t\t\t? IsJsonCompatible<TItem>\n\t\t\t\t\t\t: T extends (...args: never[]) => unknown\n\t\t\t\t\t\t\t? false\n\t\t\t\t\t\t\t: T extends object\n\t\t\t\t\t\t\t\t? [InvalidJsonKeys<T>] extends [never]\n\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t: false\n\t\t\t\t\t\t\t\t: false;\n\n/** The JSON representation of a typed in-memory value. Optional object properties remain optional. */\nexport type JsonRepresentation<T> = IsAny<T> extends true\n\t? JsonValue\n\t: unknown extends T\n\t\t? JsonValue\n\t\t: [T] extends [JsonValue]\n\t\t\t? T\n\t\t\t: T extends readonly unknown[]\n\t\t\t\t? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }\n\t\t\t\t: T extends object\n\t\t\t\t\t? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }\n\t\t\t\t\t: never;\n\nexport interface DeferredHandle {\n\tprovider: string;\n\tmodelId: string;\n\tapi: string;\n\t/** Provider token, such as a response id or batch id plus row id. */\n\tid: string;\n\texpiresAt?: number;\n\tpollAfterMs?: number;\n\t/** Provider conversion data required to reconstruct the final assistant message. */\n\tdata?: JsonValue;\n}\n\n/**\n * System instructions and tool declarations at one point in the transcript.\n *\n * The leading system message is the system prompt. Later system messages change it:\n * `content` adds instructions from that point on, `sections` replace or remove named\n * prompt sections, and `toolsAdded`/`toolsRemoved` change the tool set. Replaying\n * every system message in order yields the current prompt and tools. Providers that\n * accept system messages mid-conversation send each one in place; other providers\n * rebuild the leading system message from the replayed state.\n */\nexport interface SystemMessage {\n\trole: \"system\";\n\t/** Instruction text. On the leading message this is the base prompt; later, additional instructions. */\n\tcontent: string | TextContent[];\n\t/**\n\t * Named, ordered prompt sections rendered verbatim after `content`. The leading message\n\t * declares them; later messages replace sections by name, and `null` removes one. Keep\n\t * each section self-delimiting (a tag, a heading) so the model can relate an update to\n\t * the original. Avoid integer-like names; JSON objects reorder those.\n\t */\n\tsections?: Record<string, string | null>;\n\t/** Complete definitions of tools that become available at this point. */\n\ttoolsAdded?: Tool[];\n\t/** Tools that stop being available at this point. */\n\ttoolsRemoved?: ToolReference[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface UserMessage {\n\trole: \"user\";\n\tcontent: string | (TextContent | ImageContent)[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface AssistantMessage {\n\trole: \"assistant\";\n\tcontent: (TextContent | ThinkingContent | ToolCall)[];\n\tapi: Api;\n\tprovider: ProviderId;\n\tmodel: string;\n\tresponseModel?: string; // Concrete model reported by the provider when different from the requested `model`\n\tresponseId?: string; // Provider-specific response/message identifier when the upstream API exposes one\n\t/** Exact provider-native effort level used for this response. Absent for legacy or unmanaged responses. */\n\tproviderThinkingLevel?: string;\n\t/** Pi thinking level the agent loop requested for this response. Absent outside the agent loop and for legacy responses. */\n\tthinkingLevel?: ModelThinkingLevel;\n\tdiagnostics?: AssistantMessageDiagnostic[]; // Redacted provider/runtime diagnostics for failures and recoveries.\n\tusage: Usage;\n\tstopReason: StopReason;\n\tdeferred?: DeferredHandle;\n\terrorMessage?: string;\n\trawStopReason?: string;\n\t/**\n\t * Provider indication of whether the model explicitly ended its turn.\n\t * Preserved for debugging and does not currently affect agent control flow.\n\t */\n\tendTurn?: boolean;\n\t/** Unix timestamp in milliseconds when the request started. */\n\ttimestamp: number;\n\t/**\n\t * Milliseconds from `timestamp` until the response ended, measured with a monotonic clock. Set by\n\t * `AssistantMessageEventStream` on the final message of a response it saw start; absent for legacy messages and\n\t * for deferred results fetched later.\n\t */\n\tdurationMs?: number;\n}\n\n/** A tool call that another tool made while it ran, for example from a codemode script. */\nexport interface NestedToolCallRecord {\n\tid: string;\n\tname: string;\n\t/** Omitted when over the size limits; `argumentsBytes` then gives their size. */\n\targuments?: JsonObject;\n\t/** UTF-8 size of the arguments as JSON, set when `arguments` is omitted. */\n\targumentsBytes?: number;\n\t/** `unfinished`: the call was still running when the calling tool finished. */\n\tstatus: \"ok\" | \"error\" | \"unfinished\";\n\tdurationMs?: number;\n\t/** Error text, truncated. */\n\terror?: string;\n}\n\n/** Bounded record of the nested calls a tool made. Results are not recorded. */\nexport interface NestedToolCalls {\n\tcalls: NestedToolCallRecord[];\n\t/** False when calls were dropped, arguments omitted, or calls had not finished. */\n\tcomplete: boolean;\n}\n\nexport type ToolResultMessage<TDetails = JsonValue> = IsJsonCompatible<TDetails> extends true\n\t? {\n\t\t\trole: \"toolResult\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tcontent: (TextContent | ImageContent)[]; // Supports text and images\n\t\t\tdetails?: JsonRepresentation<TDetails>;\n\t\t\t/** Usage from the tool execution itself, if available. Not part of main LLM context accounting. */\n\t\t\tusage?: Usage;\n\t\t\t/** Calls this tool made to other tools. Kept for the session record; not sent to the model. */\n\t\t\tnestedCalls?: NestedToolCalls;\n\t\t\tisError: boolean;\n\t\t\t/** Unix timestamp in milliseconds when the result was created. */\n\t\t\ttimestamp: number;\n\t\t\t/** Milliseconds the tool's execution took, measured with a monotonic clock. Absent for legacy results. */\n\t\t\tdurationMs?: number;\n\t\t}\n\t: never;\n\nexport type Message = SystemMessage | UserMessage | AssistantMessage | ToolResultMessage;\n\nexport type ImagesInputContent = TextContent | ImageContent;\nexport type ImagesOutputContent = TextContent | ImageContent;\n\nexport interface ImagesContext {\n\tinput: ImagesInputContent[];\n}\n\nexport type ImagesStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface AssistantImages {\n\tapi: ImageApi;\n\tprovider: ProviderId;\n\tmodel: string;\n\toutput: ImagesOutputContent[];\n\tresponseId?: string;\n\tusage?: Usage;\n\tstopReason: ImagesStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface ClassifierChoiceQuestion {\n\ttype: \"choice\";\n\tinstructions: string;\n\tcriteria: Record<string, string>;\n}\n\nexport interface ClassifierScoreQuestion {\n\ttype: \"score\";\n\tinstructions: string;\n\tcriteria: string[];\n}\n\nexport interface ClassifierBoolQuestion {\n\ttype: \"bool\";\n\tinstructions: string;\n\tcriteria: { true: string; false: string };\n}\n\nexport type ClassifierQuestion = ClassifierChoiceQuestion | ClassifierScoreQuestion | ClassifierBoolQuestion;\n\nexport interface ClassifierContext {\n\tstate: JsonObject;\n\t/**\n\t * Images judged together with `state`. Only models whose `input` includes `\"image\"` accept them;\n\t * other models return an error result.\n\t */\n\timages?: ImageContent[];\n\tquestions: Record<string, ClassifierQuestion>;\n}\n\nexport interface ClassifierChoiceAnswer {\n\ttype: \"choice\";\n\tchoice: string;\n\tprobabilities: Record<string, number>;\n\tconfidence: number;\n}\n\nexport interface ClassifierScoreAnswer {\n\ttype: \"score\";\n\tscore: number;\n\tconfidence: number;\n}\n\nexport interface ClassifierBoolAnswer {\n\ttype: \"bool\";\n\tprobability: number;\n}\n\nexport type ClassifierAnswer = ClassifierChoiceAnswer | ClassifierScoreAnswer | ClassifierBoolAnswer;\nexport type ClassifierStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface ClassifierResult {\n\tapi: ClassifierApi;\n\tprovider: ProviderId;\n\tmodel: string;\n\tanswers: Record<string, ClassifierAnswer>;\n\t/** Token usage and its cost at the model's catalog price, when the service reports token counts. */\n\tusage?: Usage;\n\tstopReason: ClassifierStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nimport type { TSchema } from \"typebox\";\n\n/** OpenAI grammar variants for constrained sampling. */\nexport type GrammarFormat = \"openai_lark\" | \"openai_regex\";\n\nexport type GrammarVariants = Partial<Record<GrammarFormat, string>>;\n\n/**\n * Optional provider-side constrained sampling configs for a tool.\n *\n * The `json_schema` value roughly maps to the concept of `strict` in APIs which is\n * implemented as json-schema constrained sampling by APIs. Grammar variants let\n * callers provide provider-specific encodings of the same intended language.\n */\nexport type ConstrainedSamplingConfig =\n\t| {\n\t\t\ttype: \"json_schema\";\n\t\t\tstrict: \"prefer\" | \"require\";\n\t }\n\t| {\n\t\t\ttype: \"grammar\";\n\t\t\tvariants: GrammarVariants;\n\t };\n\nexport interface Tool<TParameters extends TSchema = TSchema> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n\tconstrainedSampling?: false | ConstrainedSamplingConfig;\n}\n\nexport interface ToolReference {\n\tname: string;\n}\n\n/**\n * Request input accepted by the public stream entry points (`Models.stream()`,\n * `streamSimple()`, ...). `systemPrompt` and `tools` are shorthand for a leading\n * system message; `normalizeContext()` folds them into one before the request\n * reaches a provider.\n */\nexport interface Context {\n\tsystemPrompt?: string;\n\tmessages: Message[];\n\ttools?: Tool[];\n}\n\ndeclare const transcriptContextBrand: unique symbol;\n\n/**\n * Normalized request context passed to providers and API implementations. The\n * prompt and tool declarations are carried by the transcript's system messages.\n * Only `normalizeContext()` produces this type, so a raw `Context` cannot reach\n * provider code by accident.\n */\nexport type TranscriptContext = {\n\tmessages: Message[];\n\treadonly [transcriptContextBrand]: true;\n};\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Successful streams emit `start` before partial updates and terminate with\n * `done`. A stream may terminate directly with `error` when request setup fails\n * before generation starts; after `start`, failures also terminate with `error`.\n * Direct `streamSimple()` calls throw synchronously when request auth is missing.\n * Updates and `done` must never appear before `start`.\n *\n * `partial` is the shared live response-so-far helper, not an event-time\n * snapshot. Text and thinking blocks are empty when their `*_start` event is\n * emitted and grow only through their corresponding `*_delta` events until the\n * authoritative `*_end`. Redacted thinking may be complete at start and emit no\n * deltas. Tool-call arguments at `toolcall_start` are provider-specific;\n * `toolcall_delta` carries subsequent JSON updates.\n */\nexport type AssistantMessageEvent =\n\t| { type: \"start\"; partial: AssistantMessage }\n\t| { type: \"text_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"text_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"thinking_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"thinking_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"toolcall_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"toolcall_end\"; contentIndex: number; toolCall: ToolCall; partial: AssistantMessage }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\" | \"deferred\">;\n\t\t\tmessage: AssistantMessage;\n\t }\n\t| { type: \"error\"; reason: Extract<StopReason, \"aborted\" | \"error\">; error: AssistantMessage };\n\n/** Fields shared by every catalog entry, regardless of what you can do with it. */\nexport interface BaseModel<TApi extends string> {\n\tid: string;\n\tname: string;\n\tapi: TApi;\n\tprovider: ProviderId;\n\tbaseUrl: string;\n\tinput: ModelInputModality[];\n\t/** Provider input limits and cache-safe preprocessing metadata. */\n\tinputLimits?: ModelInputLimits;\n\tcost: ModelCost;\n\theaders?: Record<string, string>;\n}\n\n/** Chat model: usable with `stream()` and friends. */\nexport interface Model<TApi extends Api> extends BaseModel<TApi> {\n\t/**\n\t * Optional: chat is the default model type, so models without `type` are chat\n\t * models. Narrow mixed model lists with `isModelType()` instead of comparing\n\t * `type` directly.\n\t */\n\ttype?: \"chat\";\n\treasoning: boolean;\n\t/**\n\t * Maps pi thinking levels to provider/model-specific values.\n\t * Missing keys use provider defaults. null marks a level as unsupported.\n\t */\n\tthinkingLevelMap?: ThinkingLevelMap;\n\t/** Prompt cache lifetimes per retention tier. Unset when the provider's cache behavior is unknown. */\n\tpromptCache?: ModelPromptCache;\n\tcontextWindow: number;\n\tmaxTokens: number;\n\t/** Default sampling parameters for this model. See {@link StreamOptions.samplingParams}; per-request keys override these. */\n\tsamplingParams?: SamplingParams;\n\t/** Sampling parameter overrides selected by the effective pi thinking level. */\n\tsamplingParamsByThinkingLevel?: SamplingParamsByThinkingLevel;\n\t/** Compatibility overrides for OpenAI-compatible APIs. If not set, auto-detected from baseUrl. */\n\tcompat?: TApi extends \"openai-completions\"\n\t\t? OpenAICompletionsCompat\n\t\t: TApi extends \"openai-responses\" | \"azure-openai-responses\" | \"openai-codex-responses\"\n\t\t\t? OpenAIResponsesCompat\n\t\t\t: TApi extends \"anthropic-messages\"\n\t\t\t\t? AnthropicMessagesCompat\n\t\t\t\t: TApi extends \"bedrock-converse-stream\"\n\t\t\t\t\t? BedrockCompat\n\t\t\t\t\t: TApi extends \"mistral-conversations\"\n\t\t\t\t\t\t? MistralConversationsCompat\n\t\t\t\t\t\t: never;\n}\n\n/** Image-generation model: usable with `generateImages()` only. */\nexport interface ImageModel<TApi extends ImageApi> extends BaseModel<TApi> {\n\ttype: \"image\";\n\t/** Output modalities. Always includes `\"image\"`; `\"text\"` means the model can also return text blocks. */\n\toutput: (\"text\" | \"image\")[];\n}\n\n/** Structured classifier model: usable with `classify()` only. */\nexport interface ClassifierModel<TApi extends ClassifierApi> extends BaseModel<TApi> {\n\ttype: \"classifier\";\n\tcontextWindow: number;\n\t/** Compatibility overrides for System One APIs. If not set, auto-detected from provider, baseUrl, and id. */\n\tcompat?: TApi extends \"typesafe-system-one\" | \"cloudflare-workers-ai-system-one\" ? SystemOneCompat : never;\n}\n\n/** Model shape for each model type. */\nexport interface ModelTypeMap {\n\tchat: Model<Api>;\n\timage: ImageModel<ImageApi>;\n\tclassifier: ClassifierModel<ClassifierApi>;\n}\n\n/** What a catalog entry is for. Decides which `Models` operation accepts it. */\nexport type ModelType = keyof ModelTypeMap;\n\n/** Anything a provider can list. Narrow with `isModelType()`. */\nexport type AnyModel = ModelTypeMap[ModelType];\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TelemetrySpan } from \"@earendil-works/pi-telemetry\";\nimport type { AnthropicOptions } from \"./api/anthropic-messages.ts\";\nimport type { AzureOpenAIResponsesOptions } from \"./api/azure-openai-responses.ts\";\nimport type { BedrockOptions } from \"./api/bedrock-converse-stream.ts\";\nimport type { GoogleOptions } from \"./api/google-generative-ai.ts\";\nimport type { GoogleVertexOptions } from \"./api/google-vertex.ts\";\nimport type { MistralOptions } from \"./api/mistral-conversations.ts\";\nimport type { OpenAICodexResponsesOptions } from \"./api/openai-codex-responses.ts\";\nimport type { OpenAICompletionsOptions } from \"./api/openai-completions.ts\";\nimport type { OpenAIResponsesOptions } from \"./api/openai-responses.ts\";\nimport type { PiMessagesOptions } from \"./api/pi-messages.ts\";\nimport type {\n\tAnthropicMessagesCompat,\n\tBedrockCompat,\n\tMistralConversationsCompat,\n\tOpenAICompletionsCompat,\n\tOpenAIResponsesCompat,\n\tSystemOneCompat,\n} from \"./providers/compat-schema.ts\";\nimport type {\n\tCacheRetention,\n\tModelCost,\n\tModelInputLimits,\n\tModelInputModality,\n\tModelPromptCache,\n\tModelThinkingLevel,\n\tThinkingLevel,\n\tThinkingLevelMap,\n} from \"./providers/model-schema.ts\";\nimport type { AssistantMessageDiagnostic } from \"./utils/diagnostics.ts\";\nimport type { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\nimport type { ClientIdentity } from \"./utils/identity.ts\";\n\nexport type {\n\tAnthropicAllowedFallbackModel,\n\tAnthropicMessagesCompat,\n\tBedrockCompat,\n\tChatTemplateKwargValue,\n\tMistralConversationsCompat,\n\tOpenAICompletionsCompat,\n\tOpenAIResponsesCompat,\n\tOpenRouterRouting,\n\tSessionAffinityFormat,\n\tSystemOneCompat,\n\tThinkingTokenBudgetField,\n\tVercelGatewayRouting,\n} from \"./providers/compat-schema.ts\";\nexport type {\n\tCacheRetention,\n\tModelCost,\n\tModelCostRates,\n\tModelCostTier,\n\tModelImageInputLimits,\n\tModelImageResizeOptions,\n\tModelInputLimits,\n\tModelInputModality,\n\tModelPromptCache,\n\tModelThinkingLevel,\n\tThinkingLevel,\n\tThinkingLevelMap,\n} from \"./providers/model-schema.ts\";\nexport type { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\n\nexport type KnownApi =\n\t| \"openai-completions\"\n\t| \"mistral-conversations\"\n\t| \"openai-responses\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex-responses\"\n\t| \"anthropic-messages\"\n\t| \"bedrock-converse-stream\"\n\t| \"google-generative-ai\"\n\t| \"google-vertex\"\n\t| \"pi-messages\";\n\nexport type Api = KnownApi | (string & {});\n\nexport type KnownImageApi = \"openrouter-images\";\n\nexport type ImageApi = KnownImageApi | (string & {});\n\nexport type KnownClassifierApi =\n\t| \"typesafe-system-one\"\n\t| \"cloudflare-workers-ai-system-one\"\n\t| \"llama-cpp-classify\"\n\t| \"openai-decisions\";\n\nexport type ClassifierApi = KnownClassifierApi | (string & {});\n\nexport type KnownProvider =\n\t| \"amazon-bedrock\"\n\t| \"ant-ling\"\n\t| \"anthropic\"\n\t| \"google\"\n\t| \"google-vertex\"\n\t| \"openai\"\n\t| \"azure\"\n\t| \"openai-codex\"\n\t| \"radius\"\n\t| \"typesafe\"\n\t| \"nvidia\"\n\t| \"deepseek\"\n\t| \"github-copilot\"\n\t| \"xai\"\n\t| \"groq\"\n\t| \"cerebras\"\n\t| \"openrouter\"\n\t| \"vercel-ai-gateway\"\n\t| \"zai\"\n\t| \"zai-coding-cn\"\n\t| \"mistral\"\n\t| \"minimax\"\n\t| \"minimax-cn\"\n\t| \"moonshotai\"\n\t| \"moonshotai-cn\"\n\t| \"huggingface\"\n\t| \"fireworks\"\n\t| \"together\"\n\t| \"baseten\"\n\t| \"opencode\"\n\t| \"opencode-go\"\n\t| \"kimi-coding\"\n\t| \"meta\"\n\t| \"cloudflare-workers-ai\"\n\t| \"cloudflare-ai-gateway\"\n\t| \"qwen-token-plan\"\n\t| \"qwen-token-plan-cn\"\n\t| \"qwen-token-plan-individual\"\n\t| \"qwen-token-plan-individual-cn\"\n\t| \"xiaomi\"\n\t| \"xiaomi-token-plan-cn\"\n\t| \"xiaomi-token-plan-ams\"\n\t| \"xiaomi-token-plan-sgp\";\nexport type ProviderId = KnownProvider | string;\n\nexport type ToolChoice = \"auto\" | \"none\";\nexport type SamplingParams = Record<string, unknown>;\nexport type SamplingParamsByThinkingLevel = Partial<Record<ModelThinkingLevel, SamplingParams>>;\n/** Token budgets for each thinking level (token-based providers only) */\nexport interface ThinkingBudgets {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\n// Base options all providers share\nexport type Transport = \"sse\" | \"websocket\" | \"websocket-cached\" | \"auto\";\n\n/** Provider-scoped environment overrides. Values take precedence over process.env. */\nexport type ProviderEnv = Record<string, string>;\nexport type ProviderHeaders = Record<string, string | null>;\nexport type FetchFunction = typeof globalThis.fetch;\n\nexport interface ProviderResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Authentication, HTTP transport, and lifecycle callbacks shared by provider requests. */\nexport interface ProviderRequestOptions<TModel = Model<Api>> {\n\tsignal?: AbortSignal;\n\t/** Explicit parent span for telemetry produced by this logical request. */\n\ttelemetry?: TelemetrySpan;\n\tapiKey?: string;\n\t/**\n\t * Optional fetch implementation for provider HTTP requests.\n\t * Defaults to `globalThis.fetch`. Provider adapters that cannot inject a custom implementation may reject it.\n\t * This does not affect WebSocket transports.\n\t */\n\tfetch?: FetchFunction;\n\t/**\n\t * Provider-scoped environment values. These take precedence over process.env for\n\t * provider configuration such as regional settings, endpoint placeholders, and\n\t * proxy variables.\n\t */\n\tenv?: ProviderEnv;\n\t/**\n\t * Optional callback for inspecting or replacing provider payloads before sending.\n\t * Return undefined to keep the payload unchanged.\n\t */\n\tonPayload?: (payload: unknown, model: TModel) => unknown | undefined | Promise<unknown | undefined>;\n\t/**\n\t * Optional callback invoked after an HTTP response is received.\n\t */\n\tonResponse?: (response: ProviderResponse, model: TModel) => void | Promise<void>;\n\t/**\n\t * Optional custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; caller values override default headers.\n\t * On AWS Bedrock these are injected via a Smithy `build`-step middleware so\n\t * they are covered by SigV4 signing; reserved headers (`x-amz-*`,\n\t * `authorization`, `host`) are silently ignored to preserve SigV4 / bearer auth.\n\t * A null value suppresses a provider/API default header with the same name.\n\t */\n\theaders?: ProviderHeaders;\n\t/**\n\t * How the request identifies the calling app: `User-Agent` and provider attribution headers.\n\t * Absent fields use pi-ai's defaults: a detailed `User-Agent` and no attribution.\n\t */\n\tidentity?: ClientIdentity;\n\t/**\n\t * HTTP request timeout in milliseconds for providers/SDKs that support it.\n\t * For example, OpenAI and Anthropic SDK clients default to 10 minutes.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum retry attempts for providers/SDKs that support client-side retries.\n\t * For example, OpenAI and Anthropic SDK clients default to 2.\n\t */\n\tmaxRetries?: number;\n\t/**\n\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t * If the server's requested delay exceeds this value, the request fails immediately\n\t * with an error containing the requested delay, allowing higher-level retry logic\n\t * to handle it with user visibility.\n\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t */\n\tmaxRetryDelayMs?: number;\n}\n\nexport interface StreamOptions extends ProviderRequestOptions<Model<Api>> {\n\t/**\n\t * Optional callback invoked after an HTTP response is received and before\n\t * its body stream is consumed.\n\t */\n\tonResponse?: (response: ProviderResponse, model: Model<Api>) => void | Promise<void>;\n\t/**\n\t * Optional observer for each parsed provider stream event before Pi normalization.\n\t * Event data is adapter-owned and must be treated as read-only.\n\t * Adapter support is explicit; unsupported adapters do not invoke it.\n\t */\n\tonProviderStreamEvent?: (data: unknown, model: Model<Api>) => void | Promise<void>;\n\ttemperature?: number;\n\t/**\n\t * Arbitrary sampling parameters merged into the request body as-is, after the named request\n\t * fields, so keys here override them. Lets custom OpenAI-compatible servers (llama.cpp, vLLM,\n\t * SGLang, ...) receive parameters pi does not model, e.g. `top_p`, `top_k`, `min_p`,\n\t * `repetition_penalty`. Merged over `Model.samplingParams` per key. Only applied by\n\t * OpenAI-compatible adapters (completions, responses, Azure responses); other APIs ignore it.\n\t */\n\tsamplingParams?: SamplingParams;\n\tmaxTokens?: number;\n\t/**\n\t * Preferred transport for providers that support multiple transports.\n\t * Providers that do not support this option ignore it.\n\t */\n\ttransport?: Transport;\n\t/**\n\t * Prompt cache retention preference. Providers map this to their supported values.\n\t * Default: \"short\".\n\t */\n\tcacheRetention?: CacheRetention;\n\t/**\n\t * Optional session identifier for providers that support session-based caching.\n\t * Providers can use this to enable prompt caching, request routing, or other\n\t * session-aware features. Ignored by providers that don't support it.\n\t */\n\tsessionId?: string;\n\t/**\n\t * Do not use or record server-side continuation state for this request (for example\n\t * Anthropic message threads). Set this for replays such as cache warming, which must not\n\t * replace the state of the real conversation. Providers that do not keep continuation\n\t * state ignore it.\n\t */\n\tdisableContinuation?: boolean;\n\t/**\n\t * WebSocket connect timeout in milliseconds for providers that support\n\t * WebSocket transports. This covers the connection/open handshake only;\n\t * stream idleness after connection uses timeoutMs.\n\t */\n\twebsocketConnectTimeoutMs?: number;\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t * For example, Anthropic uses `user_id` for abuse tracking and rate limiting.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderStreamOptions = StreamOptions & Record<string, unknown>;\n\nexport interface DeferredFetchOptions extends ProviderRequestOptions<Model<Api>> {\n\t/**\n\t * Maximum provider long-poll duration in milliseconds.\n\t * Defaults to 0, which performs one status check.\n\t */\n\twait?: number;\n}\n\n/** Request options for best-effort deferred-response cancellation. */\nexport type DeferredCancelOptions = ProviderRequestOptions<Model<Api>>;\n\n/**\n * Maps known APIs to their full provider-specific stream option types.\n * Type-only imports from API implementation modules are erased at emit, so\n * this is tree-shake safe.\n */\nexport interface ApiOptionsMap {\n\t\"anthropic-messages\": AnthropicOptions;\n\t\"openai-completions\": OpenAICompletionsOptions;\n\t\"openai-responses\": OpenAIResponsesOptions;\n\t\"openai-codex-responses\": OpenAICodexResponsesOptions;\n\t\"azure-openai-responses\": AzureOpenAIResponsesOptions;\n\t\"google-generative-ai\": GoogleOptions;\n\t\"google-vertex\": GoogleVertexOptions;\n\t\"mistral-conversations\": MistralOptions;\n\t\"bedrock-converse-stream\": BedrockOptions;\n\t\"pi-messages\": PiMessagesOptions;\n}\n\n/**\n * Full stream options for an API. Known APIs resolve to their concrete option\n * type; custom API strings fall back to the generic shape.\n */\nexport type ApiStreamOptions<TApi extends Api> = TApi extends keyof ApiOptionsMap\n\t? ApiOptionsMap[TApi]\n\t: StreamOptions & Record<string, unknown>;\n\n/**\n * The uniform stream contract of an API implementation module: every module\n * under `src/api/` exports `stream` and `streamSimple`; capable modules may also\n * export deferred-response methods. Lazy wrappers (`lazyApi()`) and provider\n * factories pass these around as values. This is the untyped dispatch shape;\n * per-API option typing lives on the implementation modules themselves and on\n * `Provider.stream()` via `ApiStreamOptions`.\n */\nexport interface ProviderStreams {\n\tstream(model: Model<Api>, context: TranscriptContext, options?: StreamOptions): AssistantMessageEventStream;\n\tstreamSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: SimpleStreamOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred?(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: DeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tcancelDeferred?(model: Model<Api>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;\n}\n\n/**\n * The uniform contract of an image-generation API implementation module:\n * every image API module under `src/api/` exports exactly `generateImages`,\n * so the module itself satisfies this interface. Lazy wrappers and\n * `createProvider({ images })` pass these around as values.\n */\nexport interface ProviderImages {\n\tgenerateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ImagesOptions,\n\t): Promise<AssistantImages>;\n}\n\n/** The uniform contract implemented by classifier API modules. */\nexport interface ProviderClassifier {\n\tclassify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\nexport interface ClassifierOptions extends ProviderRequestOptions<ClassifierModel<ClassifierApi>> {\n\t/**\n\t * Divides the answer logits by this value before they are normalized into probabilities.\n\t * Values above 1 soften the distribution; values below 1 sharpen it. Must be positive.\n\t * APIs that cannot apply it ignore it.\n\t */\n\ttemperature?: number;\n}\n\nexport interface ImagesOptions extends ProviderRequestOptions<ImageModel<ImageApi>> {\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderImagesOptions = ImagesOptions & Record<string, unknown>;\n\n// Unified options with reasoning passed to streamSimple() and completeSimple()\nexport interface SimpleStreamOptions extends StreamOptions {\n\t/** Provider-neutral tool selection for simple requests. When omitted, adapters use provider-specific behavior. */\n\ttoolChoice?: ToolChoice;\n\treasoning?: ThinkingLevel;\n\t/** Ask a capable provider to return a durable handle and continue the request asynchronously. */\n\tdeferred?: boolean | { window?: \"15m\" | \"1h\" | \"24h\" };\n\t/** Custom token budgets for thinking levels (token-based providers only) */\n\tthinkingBudgets?: ThinkingBudgets;\n}\n\n// Generic StreamFunction with typed options.\n//\n// Contract:\n// - Receives a normalized transcript: the system prompt and tools live in the\n// leading system message, never on the context itself.\n// - Must return an AssistantMessageEventStream.\n// - Direct streamSimple() calls may throw synchronously when request auth is\n// missing. Once a stream is returned, request/model/runtime failures should\n// be encoded in that stream.\n// - Error termination must produce an AssistantMessage with stopReason\n// \"error\" or \"aborted\" and errorMessage, emitted via the stream protocol.\nexport type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (\n\tmodel: Model<TApi>,\n\tcontext: TranscriptContext,\n\toptions?: TOptions,\n) => AssistantMessageEventStream;\n\nexport type ImagesFunction<TOptions extends ImagesOptions = ImagesOptions> = (\n\tmodel: ImageModel<ImageApi>,\n\tcontext: ImagesContext,\n\toptions?: TOptions,\n) => Promise<AssistantImages>;\n\nexport type ClassifierFunction<TOptions extends ClassifierOptions = ClassifierOptions> = (\n\tmodel: ClassifierModel<ClassifierApi>,\n\tcontext: ClassifierContext,\n\toptions?: TOptions,\n) => Promise<ClassifierResult>;\n\nexport interface TextSignatureV1 {\n\tv: 1;\n\tid: string;\n\tphase?: \"commentary\" | \"final_answer\";\n}\n\nexport interface TextContent {\n\ttype: \"text\";\n\ttext: string;\n\ttextSignature?: string; // e.g., for OpenAI responses, message metadata (legacy id string or TextSignatureV1 JSON)\n}\n\nexport interface ThinkingContent {\n\ttype: \"thinking\";\n\tthinking: string;\n\tthinkingSignature?: string; // Provider-specific opaque or serialized reasoning replay data\n\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t * to the API for multi-turn continuity. */\n\tredacted?: boolean;\n}\n\nexport interface ImageContent {\n\ttype: \"image\";\n\tdata: string; // base64 encoded image data\n\tmimeType: string; // e.g., \"image/jpeg\", \"image/png\"\n}\n\nexport interface ToolCall {\n\ttype: \"toolCall\";\n\tid: string;\n\tname: string;\n\targuments: JsonObject;\n\tthoughtSignature?: string; // Google-specific: opaque signature for reusing thought context\n\t/** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */\n\tnamespace?: string;\n\t/**\n\t * Set when the model's complete arguments text was not a valid JSON object. `arguments` is then `{}`.\n\t * Describes the problem and includes the text the model sent; tool argument validation fails with it.\n\t */\n\targumentsError?: string;\n}\n\nexport interface Usage {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\t/** Subset of `cacheWrite` written with 1h retention. Only Anthropic reports this split. */\n\tcacheWrite1h?: number;\n\t/**\n\t * Reasoning/thinking tokens, when the provider reports them. This is a subset of\n\t * `output`: `output` already includes these tokens. Set to a number (possibly 0) by\n\t * providers that expose a reasoning breakdown; left undefined by providers that don't.\n\t */\n\treasoning?: number;\n\ttotalTokens: number;\n\tcost: {\n\t\t/** Catalog-derived input cost. */\n\t\tinput: number;\n\t\t/** Catalog-derived output cost. */\n\t\toutput: number;\n\t\t/** Catalog-derived cache-read cost. */\n\t\tcacheRead: number;\n\t\t/** Catalog-derived cache-write cost. */\n\t\tcacheWrite: number;\n\t\t/** Best available total: provider-reported billed cost when supported, otherwise the catalog estimate. */\n\t\ttotal: number;\n\t\t/** True when `total` is the billed cost reported by the provider. False when it is a catalog estimate; absent also means false. */\n\t\ttotalFromProvider?: boolean;\n\t};\n}\n\nexport type StopReason = \"pending\" | \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\" | \"deferred\";\n\nexport type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject;\nexport type JsonObject = { [key: string]: JsonValue };\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype IsExactlyJsonValue<T> = [T] extends [JsonValue] ? ([JsonValue] extends [T] ? true : false) : false;\ntype IsJsonProperty<T> = IsAny<T> extends true\n\t? false\n\t: unknown extends T\n\t\t? false\n\t\t: [Exclude<T, undefined>] extends [never]\n\t\t\t? true\n\t\t\t: IsJsonCompatible<Exclude<T, undefined>>;\ntype InvalidJsonKeys<T extends object> = {\n\t[TKey in keyof T]-?: TKey extends string | number ? (IsJsonProperty<T[TKey]> extends true ? never : TKey) : TKey;\n}[keyof T];\ntype IsJsonCompatible<T> = IsAny<T> extends true\n\t? false\n\t: unknown extends T\n\t\t? false\n\t\t: IsExactlyJsonValue<T> extends true\n\t\t\t? true\n\t\t\t: T extends null | boolean | number | string\n\t\t\t\t? true\n\t\t\t\t: T extends undefined\n\t\t\t\t\t? false\n\t\t\t\t\t: T extends readonly (infer TItem)[]\n\t\t\t\t\t\t? IsJsonCompatible<TItem>\n\t\t\t\t\t\t: T extends (...args: never[]) => unknown\n\t\t\t\t\t\t\t? false\n\t\t\t\t\t\t\t: T extends object\n\t\t\t\t\t\t\t\t? [InvalidJsonKeys<T>] extends [never]\n\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t: false\n\t\t\t\t\t\t\t\t: false;\n\n/** The JSON representation of a typed in-memory value. Optional object properties remain optional. */\nexport type JsonRepresentation<T> = IsAny<T> extends true\n\t? JsonValue\n\t: unknown extends T\n\t\t? JsonValue\n\t\t: [T] extends [JsonValue]\n\t\t\t? T\n\t\t\t: T extends readonly unknown[]\n\t\t\t\t? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }\n\t\t\t\t: T extends object\n\t\t\t\t\t? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }\n\t\t\t\t\t: never;\n\nexport interface DeferredHandle {\n\tprovider: string;\n\tmodelId: string;\n\tapi: string;\n\t/** Provider token, such as a response id or batch id plus row id. */\n\tid: string;\n\texpiresAt?: number;\n\tpollAfterMs?: number;\n\t/** Provider conversion data required to reconstruct the final assistant message. */\n\tdata?: JsonValue;\n}\n\n/**\n * System instructions and tool declarations at one point in the transcript.\n *\n * The leading system message is the system prompt. Later system messages change it:\n * `content` adds instructions from that point on, `sections` replace or remove named\n * prompt sections, and `toolsAdded`/`toolsRemoved` change the tool set. Replaying\n * every system message in order yields the current prompt and tools. Providers that\n * accept system messages mid-conversation send each one in place; other providers\n * rebuild the leading system message from the replayed state.\n */\nexport interface SystemMessage {\n\trole: \"system\";\n\t/** Instruction text. On the leading message this is the base prompt; later, additional instructions. */\n\tcontent: string | TextContent[];\n\t/**\n\t * Named, ordered prompt sections rendered verbatim after `content`. The leading message\n\t * declares them; later messages replace sections by name, and `null` removes one. Keep\n\t * each section self-delimiting (a tag, a heading) so the model can relate an update to\n\t * the original. Avoid integer-like names; JSON objects reorder those.\n\t */\n\tsections?: Record<string, string | null>;\n\t/** Complete definitions of tools that become available at this point. */\n\ttoolsAdded?: Tool[];\n\t/** Tools that stop being available at this point. */\n\ttoolsRemoved?: ToolReference[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface UserMessage {\n\trole: \"user\";\n\tcontent: string | (TextContent | ImageContent)[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface AssistantMessage {\n\trole: \"assistant\";\n\tcontent: (TextContent | ThinkingContent | ToolCall)[];\n\tapi: Api;\n\tprovider: ProviderId;\n\tmodel: string;\n\tresponseModel?: string; // Concrete model reported by the provider, when reported. May equal the requested `model`\n\tresponseId?: string; // Provider-specific response/message identifier when the upstream API exposes one\n\t/** Exact provider-native effort level used for this response. Absent for legacy or unmanaged responses. */\n\tproviderThinkingLevel?: string;\n\t/** Pi thinking level the agent loop requested for this response. Absent outside the agent loop and for legacy responses. */\n\tthinkingLevel?: ModelThinkingLevel;\n\tdiagnostics?: AssistantMessageDiagnostic[]; // Redacted provider/runtime diagnostics for failures and recoveries.\n\tusage: Usage;\n\tstopReason: StopReason;\n\tdeferred?: DeferredHandle;\n\terrorMessage?: string;\n\trawStopReason?: string;\n\t/**\n\t * Provider indication of whether the model explicitly ended its turn.\n\t * Preserved for debugging and does not currently affect agent control flow.\n\t */\n\tendTurn?: boolean;\n\t/** Unix timestamp in milliseconds when the request started. */\n\ttimestamp: number;\n\t/**\n\t * Milliseconds from `timestamp` until the response ended, measured with a monotonic clock. Set by\n\t * `AssistantMessageEventStream` on the final message of a response it saw start; absent for legacy messages and\n\t * for deferred results fetched later.\n\t */\n\tdurationMs?: number;\n}\n\n/** A tool call that another tool made while it ran, for example from a codemode script. */\nexport interface NestedToolCallRecord {\n\tid: string;\n\tname: string;\n\t/** Omitted when over the size limits; `argumentsBytes` then gives their size. */\n\targuments?: JsonObject;\n\t/** UTF-8 size of the arguments as JSON, set when `arguments` is omitted. */\n\targumentsBytes?: number;\n\t/** `unfinished`: the call was still running when the calling tool finished. */\n\tstatus: \"ok\" | \"error\" | \"unfinished\";\n\tdurationMs?: number;\n\t/** Error text, truncated. */\n\terror?: string;\n}\n\n/** Bounded record of the nested calls a tool made. Results are not recorded. */\nexport interface NestedToolCalls {\n\tcalls: NestedToolCallRecord[];\n\t/** False when calls were dropped, arguments omitted, or calls had not finished. */\n\tcomplete: boolean;\n}\n\nexport type ToolResultMessage<TDetails = JsonValue> = IsJsonCompatible<TDetails> extends true\n\t? {\n\t\t\trole: \"toolResult\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tcontent: (TextContent | ImageContent)[]; // Supports text and images\n\t\t\tdetails?: JsonRepresentation<TDetails>;\n\t\t\t/** Usage from the tool execution itself, if available. Not part of main LLM context accounting. */\n\t\t\tusage?: Usage;\n\t\t\t/** Calls this tool made to other tools. Kept for the session record; not sent to the model. */\n\t\t\tnestedCalls?: NestedToolCalls;\n\t\t\tisError: boolean;\n\t\t\t/** Unix timestamp in milliseconds when the result was created. */\n\t\t\ttimestamp: number;\n\t\t\t/** Milliseconds the tool's execution took, measured with a monotonic clock. Absent for legacy results. */\n\t\t\tdurationMs?: number;\n\t\t}\n\t: never;\n\nexport type Message = SystemMessage | UserMessage | AssistantMessage | ToolResultMessage;\n\nexport type ImagesInputContent = TextContent | ImageContent;\nexport type ImagesOutputContent = TextContent | ImageContent;\n\nexport interface ImagesContext {\n\tinput: ImagesInputContent[];\n}\n\nexport type ImagesStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface AssistantImages {\n\tapi: ImageApi;\n\tprovider: ProviderId;\n\tmodel: string;\n\toutput: ImagesOutputContent[];\n\tresponseId?: string;\n\tusage?: Usage;\n\tstopReason: ImagesStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface ClassifierChoiceQuestion {\n\ttype: \"choice\";\n\tinstructions: string;\n\tcriteria: Record<string, string>;\n}\n\nexport interface ClassifierScoreQuestion {\n\ttype: \"score\";\n\tinstructions: string;\n\tcriteria: string[];\n}\n\nexport interface ClassifierBoolQuestion {\n\ttype: \"bool\";\n\tinstructions: string;\n\tcriteria: { true: string; false: string };\n}\n\nexport type ClassifierQuestion = ClassifierChoiceQuestion | ClassifierScoreQuestion | ClassifierBoolQuestion;\n\nexport interface ClassifierContext {\n\tstate: JsonObject;\n\t/**\n\t * Images judged together with `state`. Only models whose `input` includes `\"image\"` accept them;\n\t * other models return an error result.\n\t */\n\timages?: ImageContent[];\n\tquestions: Record<string, ClassifierQuestion>;\n}\n\nexport interface ClassifierChoiceAnswer {\n\ttype: \"choice\";\n\tchoice: string;\n\tprobabilities: Record<string, number>;\n\tconfidence: number;\n}\n\nexport interface ClassifierScoreAnswer {\n\ttype: \"score\";\n\tscore: number;\n\tconfidence: number;\n}\n\nexport interface ClassifierBoolAnswer {\n\ttype: \"bool\";\n\tprobability: number;\n}\n\nexport type ClassifierAnswer = ClassifierChoiceAnswer | ClassifierScoreAnswer | ClassifierBoolAnswer;\nexport type ClassifierStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface ClassifierResult {\n\tapi: ClassifierApi;\n\tprovider: ProviderId;\n\tmodel: string;\n\tanswers: Record<string, ClassifierAnswer>;\n\t/** Token usage and its cost at the model's catalog price, when the service reports token counts. */\n\tusage?: Usage;\n\tstopReason: ClassifierStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\n/** OpenAI grammar variants for constrained sampling. */\nexport type GrammarFormat = \"openai_lark\" | \"openai_regex\";\n\nexport type GrammarVariants = Partial<Record<GrammarFormat, string>>;\n\n/**\n * Optional provider-side constrained sampling configs for a tool.\n *\n * The `json_schema` value roughly maps to the concept of `strict` in APIs which is\n * implemented as json-schema constrained sampling by APIs. Grammar variants let\n * callers provide provider-specific encodings of the same intended language.\n */\nexport type ConstrainedSamplingConfig =\n\t| {\n\t\t\ttype: \"json_schema\";\n\t\t\tstrict: \"prefer\" | \"require\";\n\t }\n\t| {\n\t\t\ttype: \"grammar\";\n\t\t\tvariants: GrammarVariants;\n\t };\n\n/**\n * A tool the model may call. `parameters` is the JSON Schema of its arguments: pi-schema's builders (which also type\n * the arguments, see `Static` in `@earendil-works/pi-schema`), TypeBox schemas, or any JSON Schema object.\n */\nexport interface Tool<TParameters extends object = object> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n\tconstrainedSampling?: false | ConstrainedSamplingConfig;\n}\n\nexport interface ToolReference {\n\tname: string;\n}\n\n/**\n * Request input accepted by the public stream entry points (`Models.stream()`,\n * `streamSimple()`, ...). `systemPrompt` and `tools` are shorthand for a leading\n * system message; `normalizeContext()` folds them into one before the request\n * reaches a provider.\n */\nexport interface Context {\n\tsystemPrompt?: string;\n\tmessages: Message[];\n\ttools?: Tool[];\n}\n\ndeclare const transcriptContextBrand: unique symbol;\n\n/**\n * Normalized request context passed to providers and API implementations. The\n * prompt and tool declarations are carried by the transcript's system messages.\n * Only `normalizeContext()` produces this type, so a raw `Context` cannot reach\n * provider code by accident.\n */\nexport type TranscriptContext = {\n\tmessages: Message[];\n\treadonly [transcriptContextBrand]: true;\n};\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Successful streams emit `start` before partial updates and terminate with\n * `done`. A stream may terminate directly with `error` when request setup fails\n * before generation starts; after `start`, failures also terminate with `error`.\n * Direct `streamSimple()` calls throw synchronously when request auth is missing.\n * Updates and `done` must never appear before `start`.\n *\n * `partial` is the shared live response-so-far helper, not an event-time\n * snapshot. Text and thinking blocks are empty when their `*_start` event is\n * emitted and grow only through their corresponding `*_delta` events until the\n * authoritative `*_end`. Redacted thinking may be complete at start and emit no\n * deltas. Tool-call arguments at `toolcall_start` are provider-specific;\n * `toolcall_delta` carries subsequent JSON updates.\n */\nexport type AssistantMessageEvent =\n\t| { type: \"start\"; partial: AssistantMessage }\n\t| { type: \"text_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"text_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"thinking_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"thinking_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"toolcall_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"toolcall_end\"; contentIndex: number; toolCall: ToolCall; partial: AssistantMessage }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\" | \"deferred\">;\n\t\t\tmessage: AssistantMessage;\n\t }\n\t| { type: \"error\"; reason: Extract<StopReason, \"aborted\" | \"error\">; error: AssistantMessage };\n\n/** Fields shared by every catalog entry, regardless of what you can do with it. */\nexport interface BaseModel<TApi extends string> {\n\tid: string;\n\tname: string;\n\tapi: TApi;\n\tprovider: ProviderId;\n\tbaseUrl: string;\n\tinput: ModelInputModality[];\n\t/** Provider input limits and cache-safe preprocessing metadata. */\n\tinputLimits?: ModelInputLimits;\n\tcost: ModelCost;\n\theaders?: Record<string, string>;\n}\n\n/** Chat model: usable with `stream()` and friends. */\nexport interface Model<TApi extends Api> extends BaseModel<TApi> {\n\t/**\n\t * Optional: chat is the default model type, so models without `type` are chat\n\t * models. Narrow mixed model lists with `isModelType()` instead of comparing\n\t * `type` directly.\n\t */\n\ttype?: \"chat\";\n\treasoning: boolean;\n\t/**\n\t * Maps pi thinking levels to provider/model-specific values.\n\t * Missing keys use provider defaults. null marks a level as unsupported.\n\t */\n\tthinkingLevelMap?: ThinkingLevelMap;\n\t/** Prompt cache lifetimes per retention tier. Unset when the provider's cache behavior is unknown. */\n\tpromptCache?: ModelPromptCache;\n\tcontextWindow: number;\n\tmaxTokens: number;\n\t/** Default sampling parameters for this model. See {@link StreamOptions.samplingParams}; per-request keys override these. */\n\tsamplingParams?: SamplingParams;\n\t/** Sampling parameter overrides selected by the effective pi thinking level. */\n\tsamplingParamsByThinkingLevel?: SamplingParamsByThinkingLevel;\n\t/** Compatibility overrides for OpenAI-compatible APIs. If not set, auto-detected from baseUrl. */\n\tcompat?: TApi extends \"openai-completions\"\n\t\t? OpenAICompletionsCompat\n\t\t: TApi extends \"openai-responses\" | \"azure-openai-responses\" | \"openai-codex-responses\"\n\t\t\t? OpenAIResponsesCompat\n\t\t\t: TApi extends \"anthropic-messages\"\n\t\t\t\t? AnthropicMessagesCompat\n\t\t\t\t: TApi extends \"bedrock-converse-stream\"\n\t\t\t\t\t? BedrockCompat\n\t\t\t\t\t: TApi extends \"mistral-conversations\"\n\t\t\t\t\t\t? MistralConversationsCompat\n\t\t\t\t\t\t: never;\n}\n\n/** Image-generation model: usable with `generateImages()` only. */\nexport interface ImageModel<TApi extends ImageApi> extends BaseModel<TApi> {\n\ttype: \"image\";\n\t/** Output modalities. Always includes `\"image\"`; `\"text\"` means the model can also return text blocks. */\n\toutput: (\"text\" | \"image\")[];\n}\n\n/** Structured classifier model: usable with `classify()` only. */\nexport interface ClassifierModel<TApi extends ClassifierApi> extends BaseModel<TApi> {\n\ttype: \"classifier\";\n\tcontextWindow: number;\n\t/** Compatibility overrides for System One APIs. If not set, auto-detected from provider, baseUrl, and id. */\n\tcompat?: TApi extends \"typesafe-system-one\" | \"cloudflare-workers-ai-system-one\" ? SystemOneCompat : never;\n}\n\n/** Model shape for each model type. */\nexport interface ModelTypeMap {\n\tchat: Model<Api>;\n\timage: ImageModel<ImageApi>;\n\tclassifier: ClassifierModel<ClassifierApi>;\n}\n\n/** What a catalog entry is for. Decides which `Models` operation accepts it. */\nexport type ModelType = keyof ModelTypeMap;\n\n/** Anything a provider can list. Narrow with `isModelType()`. */\nexport type AnyModel = ModelTypeMap[ModelType];\n"]}
@@ -10,6 +10,14 @@ export interface NormalizedProviderError {
10
10
  messageCarriesBody: boolean;
11
11
  }
12
12
  export declare function normalizeProviderError(error: unknown): NormalizedProviderError;
13
+ /**
14
+ * Connection-level failures carry no status or body, and SDKs replace the
15
+ * reason with a generic message (`openai`: `"Connection error."`). The real
16
+ * reason sits in the `cause` chain, often two levels deep (undici's
17
+ * `"fetch failed"` wraps `connect ECONNREFUSED ...`). Append the deepest
18
+ * cause so callers that surface only the message keep the reason.
19
+ */
20
+ export declare function withCauseDetail(error: Error): string;
13
21
  /**
14
22
  * Compose a display string from a normalized error. When the message already
15
23
  * carries the body (Anthropic / `@google/genai` happy path) or no body/status
@@ -1 +1 @@
1
- {"version":3,"file":"error-body.d.ts","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,MAAM,WAAW,uBAAuB;IACvC,+EAA+E;IAC/E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sEAAsE;IACtE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,8EAA8E;IAC9E,OAAO,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,kBAAkB,EAAE,OAAO,CAAC;CAC5B;AAWD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAgB9E;AAiED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAO1F;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGxE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOxD"}
1
+ {"version":3,"file":"error-body.d.ts","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,MAAM,WAAW,uBAAuB;IACvC,+EAA+E;IAC/E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sEAAsE;IACtE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,8EAA8E;IAC9E,OAAO,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,kBAAkB,EAAE,OAAO,CAAC;CAC5B;AAWD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAiB9E;AAID;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAepD;AAiED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAO1F;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGxE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOxD"}
@@ -12,6 +12,7 @@
12
12
  // composes into its display string. The `messageCarriesBody` flag captures the
13
13
  // Anthropic / `@google/genai` happy path where the SDK already folded the body
14
14
  // into the message, so providers can preserve it without double-printing.
15
+ import { ownedSlice } from "./text.js";
15
16
  export const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;
16
17
  export function normalizeProviderError(error) {
17
18
  if (!(error instanceof Error)) {
@@ -21,13 +22,40 @@ export function normalizeProviderError(error) {
21
22
  const status = extractStatus(sdkError);
22
23
  const body = extractBody(sdkError);
23
24
  const messageCarriesBody = body === undefined || error.message.includes(body);
25
+ const message = status === undefined && body === undefined ? withCauseDetail(error) : error.message;
24
26
  return {
25
27
  status,
26
28
  body,
27
- message: error.message,
29
+ message,
28
30
  messageCarriesBody,
29
31
  };
30
32
  }
33
+ const MAX_CAUSE_DEPTH = 5;
34
+ /**
35
+ * Connection-level failures carry no status or body, and SDKs replace the
36
+ * reason with a generic message (`openai`: `"Connection error."`). The real
37
+ * reason sits in the `cause` chain, often two levels deep (undici's
38
+ * `"fetch failed"` wraps `connect ECONNREFUSED ...`). Append the deepest
39
+ * cause so callers that surface only the message keep the reason.
40
+ */
41
+ export function withCauseDetail(error) {
42
+ let deepest;
43
+ let current = error.cause;
44
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && current instanceof Error; depth++) {
45
+ deepest = current;
46
+ current = current.cause;
47
+ }
48
+ if (!deepest)
49
+ return error.message;
50
+ let detail = (deepest.message || deepest.name).trim();
51
+ const code = deepest.code;
52
+ if ((typeof code === "string" || typeof code === "number") && !detail.includes(String(code))) {
53
+ detail = detail ? `${detail} (${code})` : String(code);
54
+ }
55
+ if (!detail || error.message.includes(detail))
56
+ return error.message;
57
+ return error.message ? `${error.message}: ${detail}` : detail;
58
+ }
31
59
  /**
32
60
  * Probe the HTTP status, first numeric hit wins, in SDK-field order:
33
61
  * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) →
@@ -119,7 +147,7 @@ export function formatProviderError(norm, prefix) {
119
147
  export function truncateErrorText(text, maxChars) {
120
148
  if (text.length <= maxChars)
121
149
  return text;
122
- return `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;
150
+ return `${ownedSlice(text, 0, maxChars)}... [truncated ${text.length - maxChars} chars]`;
123
151
  }
124
152
  export function safeJsonStringify(value) {
125
153
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"error-body.js","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,gFAAgF;AAChF,6EAA6E;AAC7E,6EAA6E;AAC7E,yCAAyC;AACzC,EAAE;AACF,uEAAuE;A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C;IAAC,MAAM,CAAC;QACR,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AACF,CAAC","sourcesContent":["// Shared normalization for provider HTTP error objects.\n//\n// Endpoints behind a proxy / gateway may return a non-2xx response whose body\n// the provider SDK cannot fold into `error.message`. The SDK error object still\n// carries the HTTP status and the raw/parsed body, but under SDK-specific field\n// names. Provider catch blocks that read only `error.message` therefore drop\n// the body and surface opaque messages like `\"403 status code (no body)\"` or\n// collapse to `\"Unknown: UnknownError\"`.\n//\n// `normalizeProviderError` probes the known SDK field shapes (Mistral,\n// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider\n// composes into its display string. The `messageCarriesBody` flag captures the\n// Anthropic / `@google/genai` happy path where the SDK already folded the body\n// into the message, so providers can preserve it without double-printing.\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, already trimmed and truncated to the cap. */\n\tbody?: string;\n\t/** `error.message`, or `safeJsonStringify(error)` for a non-`Error` throw. */\n\tmessage: string;\n\t/** True when `message` already contains the body (no separate body to add). */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) {\n\t\treturn { message: safeJsonStringify(error), messageCarriesBody: false };\n\t}\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\tconst messageCarriesBody = body === undefined || error.message.includes(body);\n\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody,\n\t} satisfies NormalizedProviderError;\n}\n\n/**\n * Probe the HTTP status, first numeric hit wins, in SDK-field order:\n * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) →\n * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock).\n */\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\n/**\n * Probe the raw body reason, first usable hit wins, in SDK-field order:\n * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's\n * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response\n * streams are treated as no body so they do not surface as `\"{}\"` or serialized\n * stream internals. The chosen body is truncated to the cap.\n */\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst bodyText = pickBodyText(error);\n\tif (bodyText === undefined) return undefined;\n\tconst trimmed = bodyText.trim();\n\tif (trimmed.length === 0) return undefined;\n\treturn truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction pickBodyText(error: SdkErrorShape): string | undefined {\n\tif (typeof error.body === \"string\") return error.body;\n\tif (isPlainNonEmptyObject(error.error)) return safeJsonStringify(error.error);\n\tconst responseBody = error.$response?.body;\n\tif (typeof responseBody === \"string\") return responseBody;\n\tif (isReadableStreamLike(responseBody)) return undefined;\n\tif (isPlainNonEmptyObject(responseBody)) return safeJsonStringify(responseBody);\n\treturn undefined;\n}\n\nfunction isReadableStreamLike(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && \"pipe\" in value && typeof value.pipe === \"function\";\n}\n\n/**\n * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class\n * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an\n * HTTP stream/response wrapper object, and stringifying one produced garbage\n * like `{\"_events\":...}` as the \"body\", which then REPLACED `error.message`\n * in the composed display string. `error.message` is where the SDK puts the\n * real deserialized exception text (\"Input is too long...\", schema validation\n * details, ...), so the one useful string was discarded for noise. A class\n * instance yields no body, `messageCarriesBody` stays true, and the real\n * message survives. Complements the `pipe` sniffing above: web\n * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper\n * classes fail the prototype check, while parsed JSON bodies (plain objects\n * by construction) still pass.\n */\nfunction isPlainNonEmptyObject(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return false;\n\treturn Object.keys(value).length > 0;\n}\n\n/**\n * Compose a display string from a normalized error. When the message already\n * carries the body (Anthropic / `@google/genai` happy path) or no body/status\n * was extracted, the message is returned unchanged. Otherwise the status and\n * body are surfaced, with an optional provider prefix.\n *\n * - no prefix: `\"<status>: <body>\"`\n * - prefix: `\"<prefix> (<status>): <body>\"`\n */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n"]}
1
+ {"version":3,"file":"error-body.js","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,gFAAgF;AAChF,6EAA6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C,CAAC;QACzC,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;IAC9D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AACF,CAAC","sourcesContent":["// Shared normalization for provider HTTP error objects.\n//\n// Endpoints behind a proxy / gateway may return a non-2xx response whose body\n// the provider SDK cannot fold into `error.message`. The SDK error object still\n// carries the HTTP status and the raw/parsed body, but under SDK-specific field\n// names. Provider catch blocks that read only `error.message` therefore drop\n// the body and surface opaque messages like `\"403 status code (no body)\"` or\n// collapse to `\"Unknown: UnknownError\"`.\n//\n// `normalizeProviderError` probes the known SDK field shapes (Mistral,\n// `openai`, `@google/genai`, AWS Bedrock) and returns a struct each provider\n// composes into its display string. The `messageCarriesBody` flag captures the\n// Anthropic / `@google/genai` happy path where the SDK already folded the body\n// into the message, so providers can preserve it without double-printing.\n\nimport { ownedSlice } from \"./text.ts\";\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, already trimmed and truncated to the cap. */\n\tbody?: string;\n\t/** `error.message`, or `safeJsonStringify(error)` for a non-`Error` throw. */\n\tmessage: string;\n\t/** True when `message` already contains the body (no separate body to add). */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) {\n\t\treturn { message: safeJsonStringify(error), messageCarriesBody: false };\n\t}\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\tconst messageCarriesBody = body === undefined || error.message.includes(body);\n\tconst message = status === undefined && body === undefined ? withCauseDetail(error) : error.message;\n\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage,\n\t\tmessageCarriesBody,\n\t} satisfies NormalizedProviderError;\n}\n\nconst MAX_CAUSE_DEPTH = 5;\n\n/**\n * Connection-level failures carry no status or body, and SDKs replace the\n * reason with a generic message (`openai`: `\"Connection error.\"`). The real\n * reason sits in the `cause` chain, often two levels deep (undici's\n * `\"fetch failed\"` wraps `connect ECONNREFUSED ...`). Append the deepest\n * cause so callers that surface only the message keep the reason.\n */\nexport function withCauseDetail(error: Error): string {\n\tlet deepest: Error | undefined;\n\tlet current: unknown = error.cause;\n\tfor (let depth = 0; depth < MAX_CAUSE_DEPTH && current instanceof Error; depth++) {\n\t\tdeepest = current;\n\t\tcurrent = current.cause;\n\t}\n\tif (!deepest) return error.message;\n\tlet detail = (deepest.message || deepest.name).trim();\n\tconst code = (deepest as Error & { code?: unknown }).code;\n\tif ((typeof code === \"string\" || typeof code === \"number\") && !detail.includes(String(code))) {\n\t\tdetail = detail ? `${detail} (${code})` : String(code);\n\t}\n\tif (!detail || error.message.includes(detail)) return error.message;\n\treturn error.message ? `${error.message}: ${detail}` : detail;\n}\n\n/**\n * Probe the HTTP status, first numeric hit wins, in SDK-field order:\n * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) →\n * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock).\n */\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\n/**\n * Probe the raw body reason, first usable hit wins, in SDK-field order:\n * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's\n * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response\n * streams are treated as no body so they do not surface as `\"{}\"` or serialized\n * stream internals. The chosen body is truncated to the cap.\n */\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst bodyText = pickBodyText(error);\n\tif (bodyText === undefined) return undefined;\n\tconst trimmed = bodyText.trim();\n\tif (trimmed.length === 0) return undefined;\n\treturn truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction pickBodyText(error: SdkErrorShape): string | undefined {\n\tif (typeof error.body === \"string\") return error.body;\n\tif (isPlainNonEmptyObject(error.error)) return safeJsonStringify(error.error);\n\tconst responseBody = error.$response?.body;\n\tif (typeof responseBody === \"string\") return responseBody;\n\tif (isReadableStreamLike(responseBody)) return undefined;\n\tif (isPlainNonEmptyObject(responseBody)) return safeJsonStringify(responseBody);\n\treturn undefined;\n}\n\nfunction isReadableStreamLike(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && \"pipe\" in value && typeof value.pipe === \"function\";\n}\n\n/**\n * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class\n * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an\n * HTTP stream/response wrapper object, and stringifying one produced garbage\n * like `{\"_events\":...}` as the \"body\", which then REPLACED `error.message`\n * in the composed display string. `error.message` is where the SDK puts the\n * real deserialized exception text (\"Input is too long...\", schema validation\n * details, ...), so the one useful string was discarded for noise. A class\n * instance yields no body, `messageCarriesBody` stays true, and the real\n * message survives. Complements the `pipe` sniffing above: web\n * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper\n * classes fail the prototype check, while parsed JSON bodies (plain objects\n * by construction) still pass.\n */\nfunction isPlainNonEmptyObject(value: unknown): boolean {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return false;\n\treturn Object.keys(value).length > 0;\n}\n\n/**\n * Compose a display string from a normalized error. When the message already\n * carries the body (Anthropic / `@google/genai` happy path) or no body/status\n * was extracted, the message is returned unchanged. Otherwise the status and\n * body are surfaced, with an optional provider prefix.\n *\n * - no prefix: `\"<status>: <body>\"`\n * - prefix: `\"<prefix> (<status>): <body>\"`\n */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${ownedSlice(text, 0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import type { Usage } from "../types.ts";
2
+ export interface OpenRouterUsageAccounting {
3
+ /** Amount charged to the user's OpenRouter account. */
4
+ cost: number | null;
5
+ /** Whether OpenRouter used the user's upstream provider key. */
6
+ is_byok: boolean;
7
+ cost_details: {
8
+ /** Total inference cost billed through the user's upstream provider account, when available. */
9
+ upstream_inference_cost: number | null;
10
+ /** Upstream cost for prompt processing, including any provider-side cache pricing. */
11
+ upstream_inference_prompt_cost: number;
12
+ /** Upstream cost for completion generation. */
13
+ upstream_inference_completions_cost: number;
14
+ /** Metered server-tool cost already included in OpenRouter's charged `cost`. */
15
+ server_tool_cost?: number | null;
16
+ } | null;
17
+ }
18
+ export declare function isOpenRouterModel(model: {
19
+ provider: string;
20
+ baseUrl: string;
21
+ }): boolean;
22
+ /** Replace the catalog total with OpenRouter's billed cost when the response contains complete, valid accounting. */
23
+ export declare function applyOpenRouterReportedCost(usage: Usage, reported: OpenRouterUsageAccounting): void;
24
+ //# sourceMappingURL=openrouter-cost.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openrouter-cost.d.ts","sourceRoot":"","sources":["../../src/utils/openrouter-cost.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,WAAW,yBAAyB;IACzC,uDAAuD;IACvD,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,gEAAgE;IAChE,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,EAAE;QACb,gGAAgG;QAChG,uBAAuB,EAAE,MAAM,GAAG,IAAI,CAAC;QACvC,sFAAsF;QACtF,8BAA8B,EAAE,MAAM,CAAC;QACvC,+CAA+C;QAC/C,mCAAmC,EAAE,MAAM,CAAC;QAC5C,gFAAgF;QAChF,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;KACjC,GAAG,IAAI,CAAC;CACT;AAMD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAEvF;AAED,qHAAqH;AACrH,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,yBAAyB,GAAG,IAAI,CA0BnG"}