@fractaal/pi-ai 0.86.9 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (411) hide show
  1. package/README.md +154 -78
  2. package/dist/api/anthropic-messages.d.ts.map +1 -1
  3. package/dist/api/anthropic-messages.js +380 -144
  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 +9 -11
  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 +184 -121
  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/classifier-shared.d.ts +21 -0
  16. package/dist/api/classifier-shared.d.ts.map +1 -0
  17. package/dist/api/classifier-shared.js +99 -0
  18. package/dist/api/classifier-shared.js.map +1 -0
  19. package/dist/api/cloudflare-workers-ai-system-one.d.ts.map +1 -1
  20. package/dist/api/cloudflare-workers-ai-system-one.js +10 -1
  21. package/dist/api/cloudflare-workers-ai-system-one.js.map +1 -1
  22. package/dist/api/constrained-sampling.d.ts +15 -1
  23. package/dist/api/constrained-sampling.d.ts.map +1 -1
  24. package/dist/api/constrained-sampling.js +51 -18
  25. package/dist/api/constrained-sampling.js.map +1 -1
  26. package/dist/api/google-generative-ai.d.ts.map +1 -1
  27. package/dist/api/google-generative-ai.js +4 -10
  28. package/dist/api/google-generative-ai.js.map +1 -1
  29. package/dist/api/google-shared.d.ts +2 -1
  30. package/dist/api/google-shared.d.ts.map +1 -1
  31. package/dist/api/google-shared.js +60 -3
  32. package/dist/api/google-shared.js.map +1 -1
  33. package/dist/api/google-vertex.d.ts.map +1 -1
  34. package/dist/api/google-vertex.js +9 -15
  35. package/dist/api/google-vertex.js.map +1 -1
  36. package/dist/api/lazy.d.ts +7 -2
  37. package/dist/api/lazy.d.ts.map +1 -1
  38. package/dist/api/lazy.js +33 -12
  39. package/dist/api/lazy.js.map +1 -1
  40. package/dist/api/llama-cpp-classify.d.ts.map +1 -1
  41. package/dist/api/llama-cpp-classify.js +4 -1
  42. package/dist/api/llama-cpp-classify.js.map +1 -1
  43. package/dist/api/mistral-conversations.d.ts.map +1 -1
  44. package/dist/api/mistral-conversations.js +50 -60
  45. package/dist/api/mistral-conversations.js.map +1 -1
  46. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  47. package/dist/api/openai-codex-responses.js +30 -17
  48. package/dist/api/openai-codex-responses.js.map +1 -1
  49. package/dist/api/openai-completions.d.ts +2 -1
  50. package/dist/api/openai-completions.d.ts.map +1 -1
  51. package/dist/api/openai-completions.js +93 -90
  52. package/dist/api/openai-completions.js.map +1 -1
  53. package/dist/api/openai-decisions.d.ts +4 -0
  54. package/dist/api/openai-decisions.d.ts.map +1 -0
  55. package/dist/api/openai-decisions.js +162 -0
  56. package/dist/api/openai-decisions.js.map +1 -0
  57. package/dist/api/openai-decisions.lazy.d.ts +3 -0
  58. package/dist/api/openai-decisions.lazy.d.ts.map +1 -0
  59. package/dist/api/openai-decisions.lazy.js +4 -0
  60. package/dist/api/openai-decisions.lazy.js.map +1 -0
  61. package/dist/api/openai-responses-shared.d.ts +26 -0
  62. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  63. package/dist/api/openai-responses-shared.js +132 -66
  64. package/dist/api/openai-responses-shared.js.map +1 -1
  65. package/dist/api/openai-responses.d.ts.map +1 -1
  66. package/dist/api/openai-responses.js +42 -21
  67. package/dist/api/openai-responses.js.map +1 -1
  68. package/dist/api/openrouter-images.d.ts.map +1 -1
  69. package/dist/api/openrouter-images.js +5 -3
  70. package/dist/api/openrouter-images.js.map +1 -1
  71. package/dist/api/pi-messages.d.ts +2 -0
  72. package/dist/api/pi-messages.d.ts.map +1 -1
  73. package/dist/api/pi-messages.js +27 -12
  74. package/dist/api/pi-messages.js.map +1 -1
  75. package/dist/api/simple-options.d.ts +1 -0
  76. package/dist/api/simple-options.d.ts.map +1 -1
  77. package/dist/api/simple-options.js +18 -3
  78. package/dist/api/simple-options.js.map +1 -1
  79. package/dist/api/system-one-shared.d.ts +29 -3
  80. package/dist/api/system-one-shared.d.ts.map +1 -1
  81. package/dist/api/system-one-shared.js +54 -86
  82. package/dist/api/system-one-shared.js.map +1 -1
  83. package/dist/api/transform-messages.d.ts +16 -1
  84. package/dist/api/transform-messages.d.ts.map +1 -1
  85. package/dist/api/transform-messages.js +28 -15
  86. package/dist/api/transform-messages.js.map +1 -1
  87. package/dist/api/typesafe-system-one.d.ts.map +1 -1
  88. package/dist/api/typesafe-system-one.js +12 -1
  89. package/dist/api/typesafe-system-one.js.map +1 -1
  90. package/dist/auth/oauth/anthropic.d.ts.map +1 -1
  91. package/dist/auth/oauth/anthropic.js +14 -6
  92. package/dist/auth/oauth/anthropic.js.map +1 -1
  93. package/dist/auth/oauth/github-copilot.d.ts.map +1 -1
  94. package/dist/auth/oauth/github-copilot.js +4 -11
  95. package/dist/auth/oauth/github-copilot.js.map +1 -1
  96. package/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
  97. package/dist/auth/oauth/kimi-coding.js +4 -22
  98. package/dist/auth/oauth/kimi-coding.js.map +1 -1
  99. package/dist/auth/oauth/load.d.ts.map +1 -1
  100. package/dist/auth/oauth/load.js +5 -2
  101. package/dist/auth/oauth/load.js.map +1 -1
  102. package/dist/auth/oauth/meta.d.ts.map +1 -1
  103. package/dist/auth/oauth/meta.js +1 -14
  104. package/dist/auth/oauth/meta.js.map +1 -1
  105. package/dist/auth/oauth/openai-chatgpt.js +1 -1
  106. package/dist/auth/oauth/openai-chatgpt.js.map +1 -1
  107. package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
  108. package/dist/auth/oauth/openai-codex.js +4 -4
  109. package/dist/auth/oauth/openai-codex.js.map +1 -1
  110. package/dist/auth/oauth/radius.d.ts.map +1 -1
  111. package/dist/auth/oauth/radius.js +9 -3
  112. package/dist/auth/oauth/radius.js.map +1 -1
  113. package/dist/auth/oauth/trusted-url.d.ts +7 -0
  114. package/dist/auth/oauth/trusted-url.d.ts.map +1 -0
  115. package/dist/auth/oauth/trusted-url.js +12 -0
  116. package/dist/auth/oauth/trusted-url.js.map +1 -0
  117. package/dist/auth/types.d.ts +9 -0
  118. package/dist/auth/types.d.ts.map +1 -1
  119. package/dist/auth/types.js.map +1 -1
  120. package/dist/cli.js +6 -2
  121. package/dist/cli.js.map +1 -1
  122. package/dist/compat/extension-oauth-types.d.ts +4 -0
  123. package/dist/compat/extension-oauth-types.d.ts.map +1 -1
  124. package/dist/compat/extension-oauth-types.js.map +1 -1
  125. package/dist/env-api-keys.d.ts.map +1 -1
  126. package/dist/env-api-keys.js +1 -0
  127. package/dist/env-api-keys.js.map +1 -1
  128. package/dist/index.d.ts +4 -4
  129. package/dist/index.d.ts.map +1 -1
  130. package/dist/index.js +4 -3
  131. package/dist/index.js.map +1 -1
  132. package/dist/lazy-bedrock-provider.d.ts +10 -0
  133. package/dist/lazy-bedrock-provider.d.ts.map +1 -0
  134. package/dist/lazy-bedrock-provider.js +13 -0
  135. package/dist/lazy-bedrock-provider.js.map +1 -0
  136. package/dist/lazy-oauth.d.ts +10 -0
  137. package/dist/lazy-oauth.d.ts.map +1 -0
  138. package/dist/lazy-oauth.js +23 -0
  139. package/dist/lazy-oauth.js.map +1 -0
  140. package/dist/models.d.ts +9 -0
  141. package/dist/models.d.ts.map +1 -1
  142. package/dist/models.generated.d.ts +4 -0
  143. package/dist/models.generated.d.ts.map +1 -1
  144. package/dist/models.generated.js +5 -1
  145. package/dist/models.generated.js.map +1 -1
  146. package/dist/models.js +28 -12
  147. package/dist/models.js.map +1 -1
  148. package/dist/providers/all.d.ts.map +1 -1
  149. package/dist/providers/all.js +2 -0
  150. package/dist/providers/all.js.map +1 -1
  151. package/dist/providers/amazon-bedrock.models.js +1 -1
  152. package/dist/providers/amazon-bedrock.models.js.map +1 -1
  153. package/dist/providers/ant-ling.models.js +1 -1
  154. package/dist/providers/ant-ling.models.js.map +1 -1
  155. package/dist/providers/anthropic.models.js +1 -1
  156. package/dist/providers/anthropic.models.js.map +1 -1
  157. package/dist/providers/azure.models.js +1 -1
  158. package/dist/providers/azure.models.js.map +1 -1
  159. package/dist/providers/baseten.models.js +1 -1
  160. package/dist/providers/baseten.models.js.map +1 -1
  161. package/dist/providers/cerebras.models.js +1 -1
  162. package/dist/providers/cerebras.models.js.map +1 -1
  163. package/dist/providers/cloudflare-ai-gateway.models.js +1 -1
  164. package/dist/providers/cloudflare-ai-gateway.models.js.map +1 -1
  165. package/dist/providers/cloudflare-workers-ai.models.js +1 -1
  166. package/dist/providers/cloudflare-workers-ai.models.js.map +1 -1
  167. package/dist/providers/compat-schema.d.ts +494 -0
  168. package/dist/providers/compat-schema.d.ts.map +1 -0
  169. package/dist/providers/compat-schema.js +447 -0
  170. package/dist/providers/compat-schema.js.map +1 -0
  171. package/dist/providers/data/.manifest.json +1 -1
  172. package/dist/providers/data/amazon-bedrock.json +1 -1
  173. package/dist/providers/data/anthropic.json +1 -1
  174. package/dist/providers/data/azure.json +1 -1
  175. package/dist/providers/data/baseten.json +1 -1
  176. package/dist/providers/data/cerebras.json +1 -1
  177. package/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  178. package/dist/providers/data/cloudflare-workers-ai.json +1 -1
  179. package/dist/providers/data/fireworks.json +1 -1
  180. package/dist/providers/data/github-copilot.json +1 -1
  181. package/dist/providers/data/google-vertex.json +1 -1
  182. package/dist/providers/data/google.json +1 -1
  183. package/dist/providers/data/groq.json +1 -1
  184. package/dist/providers/data/huggingface.json +1 -1
  185. package/dist/providers/data/kimi-coding.json +1 -1
  186. package/dist/providers/data/meta.json +1 -1
  187. package/dist/providers/data/minimax-cn.json +1 -1
  188. package/dist/providers/data/minimax.json +1 -1
  189. package/dist/providers/data/mistral.json +1 -1
  190. package/dist/providers/data/moonshotai-cn.json +1 -1
  191. package/dist/providers/data/moonshotai.json +1 -1
  192. package/dist/providers/data/nvidia.json +1 -1
  193. package/dist/providers/data/openai-codex.json +1 -1
  194. package/dist/providers/data/openai.json +1 -1
  195. package/dist/providers/data/opencode-go.json +1 -1
  196. package/dist/providers/data/opencode.json +1 -1
  197. package/dist/providers/data/openrouter.json +1 -1
  198. package/dist/providers/data/qwen-token-plan-cn.json +1 -1
  199. package/dist/providers/data/qwen-token-plan-individual-cn.json +1 -0
  200. package/dist/providers/data/qwen-token-plan-individual.json +1 -1
  201. package/dist/providers/data/qwen-token-plan.json +1 -1
  202. package/dist/providers/data/radius.json +1 -1
  203. package/dist/providers/data/together.json +1 -1
  204. package/dist/providers/data/typesafe.json +1 -1
  205. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  206. package/dist/providers/data/xai.json +1 -1
  207. package/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
  208. package/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
  209. package/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
  210. package/dist/providers/data/xiaomi.json +1 -1
  211. package/dist/providers/data/zai-coding-cn.json +1 -1
  212. package/dist/providers/data/zai.json +1 -1
  213. package/dist/providers/deepseek.models.js +1 -1
  214. package/dist/providers/deepseek.models.js.map +1 -1
  215. package/dist/providers/faux.d.ts.map +1 -1
  216. package/dist/providers/faux.js +31 -9
  217. package/dist/providers/faux.js.map +1 -1
  218. package/dist/providers/fireworks.models.js +1 -1
  219. package/dist/providers/fireworks.models.js.map +1 -1
  220. package/dist/providers/github-copilot.d.ts +3 -1
  221. package/dist/providers/github-copilot.d.ts.map +1 -1
  222. package/dist/providers/github-copilot.js +13 -2
  223. package/dist/providers/github-copilot.js.map +1 -1
  224. package/dist/providers/github-copilot.models.js +1 -1
  225. package/dist/providers/github-copilot.models.js.map +1 -1
  226. package/dist/providers/google-vertex.models.js +1 -1
  227. package/dist/providers/google-vertex.models.js.map +1 -1
  228. package/dist/providers/google.models.js +1 -1
  229. package/dist/providers/google.models.js.map +1 -1
  230. package/dist/providers/groq.models.js +1 -1
  231. package/dist/providers/groq.models.js.map +1 -1
  232. package/dist/providers/huggingface.models.js +1 -1
  233. package/dist/providers/huggingface.models.js.map +1 -1
  234. package/dist/providers/kimi-coding.d.ts +1 -1
  235. package/dist/providers/kimi-coding.js +3 -3
  236. package/dist/providers/kimi-coding.js.map +1 -1
  237. package/dist/providers/kimi-coding.models.js +1 -1
  238. package/dist/providers/kimi-coding.models.js.map +1 -1
  239. package/dist/providers/meta.models.js +1 -1
  240. package/dist/providers/meta.models.js.map +1 -1
  241. package/dist/providers/minimax-cn.models.js +1 -1
  242. package/dist/providers/minimax-cn.models.js.map +1 -1
  243. package/dist/providers/minimax.models.js +1 -1
  244. package/dist/providers/minimax.models.js.map +1 -1
  245. package/dist/providers/mistral.models.js +1 -1
  246. package/dist/providers/mistral.models.js.map +1 -1
  247. package/dist/providers/model-schema.d.ts +91 -0
  248. package/dist/providers/model-schema.d.ts.map +1 -0
  249. package/dist/providers/model-schema.js +68 -0
  250. package/dist/providers/model-schema.js.map +1 -0
  251. package/dist/providers/moonshotai-cn.models.js +1 -1
  252. package/dist/providers/moonshotai-cn.models.js.map +1 -1
  253. package/dist/providers/moonshotai.models.js +1 -1
  254. package/dist/providers/moonshotai.models.js.map +1 -1
  255. package/dist/providers/nvidia.models.js +1 -1
  256. package/dist/providers/nvidia.models.js.map +1 -1
  257. package/dist/providers/openai-codex-catalog.d.ts.map +1 -1
  258. package/dist/providers/openai-codex-catalog.js +44 -44
  259. package/dist/providers/openai-codex-catalog.js.map +1 -1
  260. package/dist/providers/openai-codex.models.js +1 -1
  261. package/dist/providers/openai-codex.models.js.map +1 -1
  262. package/dist/providers/openai.d.ts.map +1 -1
  263. package/dist/providers/openai.js +12 -3
  264. package/dist/providers/openai.js.map +1 -1
  265. package/dist/providers/openai.models.js +1 -1
  266. package/dist/providers/openai.models.js.map +1 -1
  267. package/dist/providers/opencode-go.d.ts +3 -1
  268. package/dist/providers/opencode-go.d.ts.map +1 -1
  269. package/dist/providers/opencode-go.js +2 -0
  270. package/dist/providers/opencode-go.js.map +1 -1
  271. package/dist/providers/opencode-go.models.js +1 -1
  272. package/dist/providers/opencode-go.models.js.map +1 -1
  273. package/dist/providers/opencode.js +1 -1
  274. package/dist/providers/opencode.js.map +1 -1
  275. package/dist/providers/opencode.models.js +1 -1
  276. package/dist/providers/opencode.models.js.map +1 -1
  277. package/dist/providers/openrouter-api.d.ts +40 -0
  278. package/dist/providers/openrouter-api.d.ts.map +1 -0
  279. package/dist/providers/openrouter-api.js +41 -0
  280. package/dist/providers/openrouter-api.js.map +1 -0
  281. package/dist/providers/openrouter.d.ts +11 -1
  282. package/dist/providers/openrouter.d.ts.map +1 -1
  283. package/dist/providers/openrouter.js +52 -1
  284. package/dist/providers/openrouter.js.map +1 -1
  285. package/dist/providers/openrouter.models.js +1 -1
  286. package/dist/providers/openrouter.models.js.map +1 -1
  287. package/dist/providers/qwen-token-plan-cn.models.js +1 -1
  288. package/dist/providers/qwen-token-plan-cn.models.js.map +1 -1
  289. package/dist/providers/qwen-token-plan-individual-cn.d.ts +3 -0
  290. package/dist/providers/qwen-token-plan-individual-cn.d.ts.map +1 -0
  291. package/dist/providers/qwen-token-plan-individual-cn.js +15 -0
  292. package/dist/providers/qwen-token-plan-individual-cn.js.map +1 -0
  293. package/dist/providers/qwen-token-plan-individual-cn.models.d.ts +6 -0
  294. package/dist/providers/qwen-token-plan-individual-cn.models.d.ts.map +1 -0
  295. package/dist/providers/qwen-token-plan-individual-cn.models.js +8 -0
  296. package/dist/providers/qwen-token-plan-individual-cn.models.js.map +1 -0
  297. package/dist/providers/qwen-token-plan-individual.models.js +1 -1
  298. package/dist/providers/qwen-token-plan-individual.models.js.map +1 -1
  299. package/dist/providers/qwen-token-plan.models.js +1 -1
  300. package/dist/providers/qwen-token-plan.models.js.map +1 -1
  301. package/dist/providers/radius-config.d.ts.map +1 -1
  302. package/dist/providers/radius-config.js +2 -1
  303. package/dist/providers/radius-config.js.map +1 -1
  304. package/dist/providers/radius.d.ts.map +1 -1
  305. package/dist/providers/radius.js +4 -12
  306. package/dist/providers/radius.js.map +1 -1
  307. package/dist/providers/radius.models.js +1 -1
  308. package/dist/providers/radius.models.js.map +1 -1
  309. package/dist/providers/schema-builders.d.ts +10 -0
  310. package/dist/providers/schema-builders.d.ts.map +1 -0
  311. package/dist/providers/schema-builders.js +18 -0
  312. package/dist/providers/schema-builders.js.map +1 -0
  313. package/dist/providers/together.models.js +1 -1
  314. package/dist/providers/together.models.js.map +1 -1
  315. package/dist/providers/typesafe.models.js +1 -1
  316. package/dist/providers/typesafe.models.js.map +1 -1
  317. package/dist/providers/vercel-ai-gateway.models.js +1 -1
  318. package/dist/providers/vercel-ai-gateway.models.js.map +1 -1
  319. package/dist/providers/xai.models.js +1 -1
  320. package/dist/providers/xai.models.js.map +1 -1
  321. package/dist/providers/xiaomi-token-plan-ams.models.js +1 -1
  322. package/dist/providers/xiaomi-token-plan-ams.models.js.map +1 -1
  323. package/dist/providers/xiaomi-token-plan-cn.models.js +1 -1
  324. package/dist/providers/xiaomi-token-plan-cn.models.js.map +1 -1
  325. package/dist/providers/xiaomi-token-plan-sgp.models.js +1 -1
  326. package/dist/providers/xiaomi-token-plan-sgp.models.js.map +1 -1
  327. package/dist/providers/xiaomi.models.js +1 -1
  328. package/dist/providers/xiaomi.models.js.map +1 -1
  329. package/dist/providers/zai-coding-cn.models.js +1 -1
  330. package/dist/providers/zai-coding-cn.models.js.map +1 -1
  331. package/dist/providers/zai.models.js +1 -1
  332. package/dist/providers/zai.models.js.map +1 -1
  333. package/dist/telemetry.d.ts +288 -0
  334. package/dist/telemetry.d.ts.map +1 -0
  335. package/dist/telemetry.js +192 -0
  336. package/dist/telemetry.js.map +1 -0
  337. package/dist/types.d.ts +57 -310
  338. package/dist/types.d.ts.map +1 -1
  339. package/dist/types.js.map +1 -1
  340. package/dist/utils/error-body.d.ts +8 -0
  341. package/dist/utils/error-body.d.ts.map +1 -1
  342. package/dist/utils/error-body.js +30 -2
  343. package/dist/utils/error-body.js.map +1 -1
  344. package/dist/utils/estimate.js +1 -1
  345. package/dist/utils/estimate.js.map +1 -1
  346. package/dist/utils/event-stream.d.ts +10 -1
  347. package/dist/utils/event-stream.d.ts.map +1 -1
  348. package/dist/utils/event-stream.js +25 -0
  349. package/dist/utils/event-stream.js.map +1 -1
  350. package/dist/utils/identity.d.ts +65 -0
  351. package/dist/utils/identity.d.ts.map +1 -0
  352. package/dist/utils/identity.js +141 -0
  353. package/dist/utils/identity.js.map +1 -0
  354. package/dist/utils/json-parse.d.ts +10 -0
  355. package/dist/utils/json-parse.d.ts.map +1 -1
  356. package/dist/utils/json-parse.js +26 -1
  357. package/dist/utils/json-parse.js.map +1 -1
  358. package/dist/utils/model-operations.d.ts +3 -1
  359. package/dist/utils/model-operations.d.ts.map +1 -1
  360. package/dist/utils/model-operations.js +6 -0
  361. package/dist/utils/model-operations.js.map +1 -1
  362. package/dist/utils/openrouter-cost.d.ts +24 -0
  363. package/dist/utils/openrouter-cost.d.ts.map +1 -0
  364. package/dist/utils/openrouter-cost.js +34 -0
  365. package/dist/utils/openrouter-cost.js.map +1 -0
  366. package/dist/utils/overflow.d.ts +1 -0
  367. package/dist/utils/overflow.d.ts.map +1 -1
  368. package/dist/utils/overflow.js +8 -1
  369. package/dist/utils/overflow.js.map +1 -1
  370. package/dist/utils/provider-retry.d.ts +2 -0
  371. package/dist/utils/provider-retry.d.ts.map +1 -1
  372. package/dist/utils/provider-retry.js +2 -0
  373. package/dist/utils/provider-retry.js.map +1 -1
  374. package/dist/utils/retry.d.ts.map +1 -1
  375. package/dist/utils/retry.js +29 -10
  376. package/dist/utils/retry.js.map +1 -1
  377. package/dist/utils/streaming-json.d.ts +84 -0
  378. package/dist/utils/streaming-json.d.ts.map +1 -0
  379. package/dist/utils/streaming-json.js +513 -0
  380. package/dist/utils/streaming-json.js.map +1 -0
  381. package/dist/utils/{typebox-helpers.d.ts → string-enum.d.ts} +5 -5
  382. package/dist/utils/string-enum.d.ts.map +1 -0
  383. package/dist/utils/{typebox-helpers.js → string-enum.js} +5 -6
  384. package/dist/utils/string-enum.js.map +1 -0
  385. package/dist/utils/text.d.ts +7 -0
  386. package/dist/utils/text.d.ts.map +1 -1
  387. package/dist/utils/text.js +9 -0
  388. package/dist/utils/text.js.map +1 -1
  389. package/dist/utils/transcript.d.ts +23 -9
  390. package/dist/utils/transcript.d.ts.map +1 -1
  391. package/dist/utils/transcript.js +30 -19
  392. package/dist/utils/transcript.js.map +1 -1
  393. package/dist/utils/validation.d.ts +5 -3
  394. package/dist/utils/validation.d.ts.map +1 -1
  395. package/dist/utils/validation.js +27 -445
  396. package/dist/utils/validation.js.map +1 -1
  397. package/dist/utils/version.d.ts +2 -0
  398. package/dist/utils/version.d.ts.map +1 -0
  399. package/dist/utils/version.js +3 -0
  400. package/dist/utils/version.js.map +1 -0
  401. package/package.json +19 -10
  402. package/dist/utils/assistant-message-frame.d.ts +0 -77
  403. package/dist/utils/assistant-message-frame.d.ts.map +0 -1
  404. package/dist/utils/assistant-message-frame.js +0 -425
  405. package/dist/utils/assistant-message-frame.js.map +0 -1
  406. package/dist/utils/pi-user-agent.d.ts +0 -2
  407. package/dist/utils/pi-user-agent.d.ts.map +0 -1
  408. package/dist/utils/pi-user-agent.js +0 -12
  409. package/dist/utils/pi-user-agent.js.map +0 -1
  410. package/dist/utils/typebox-helpers.d.ts.map +0 -1
  411. package/dist/utils/typebox-helpers.js.map +0 -1
@@ -1,429 +1,30 @@
1
- import { Compile } from "typebox/compile";
2
- import { Settings } from "typebox/system";
3
- import { Value } from "typebox/value";
1
+ import { compile } from "@earendil-works/pi-schema";
2
+ import { formats } from "@earendil-works/pi-schema/formats";
3
+ // One compiled validator per schema object: tool schemas are long-lived, so the WeakMap drops entries with their tools.
4
4
  const validatorCache = new WeakMap();
5
- const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
6
- function getSchemaTypes(schema) {
7
- if (typeof schema.type === "string") {
8
- return [schema.type];
9
- }
10
- if (Array.isArray(schema.type)) {
11
- return schema.type.filter((type) => typeof type === "string");
12
- }
13
- return [];
14
- }
15
- function matchesJsonType(value, type) {
16
- switch (type) {
17
- case "number":
18
- return typeof value === "number";
19
- case "integer":
20
- return typeof value === "number" && Number.isInteger(value);
21
- case "boolean":
22
- return typeof value === "boolean";
23
- case "string":
24
- return typeof value === "string";
25
- case "null":
26
- return value === null;
27
- case "array":
28
- return Array.isArray(value);
29
- case "object":
30
- return typeof value === "object" && value !== null && !Array.isArray(value);
31
- default:
32
- return false;
33
- }
34
- }
35
- function getSubSchemaValidator(schema) {
36
- try {
37
- return getValidator(schema);
38
- }
39
- catch {
40
- return undefined;
41
- }
42
- }
43
- function coercePrimitiveByType(value, type) {
44
- switch (type) {
45
- case "number": {
46
- if (value === null) {
47
- return 0;
48
- }
49
- if (typeof value === "string" && value.trim() !== "") {
50
- const parsed = Number(value);
51
- if (Number.isFinite(parsed)) {
52
- return parsed;
53
- }
54
- }
55
- if (typeof value === "boolean") {
56
- return value ? 1 : 0;
57
- }
58
- return value;
59
- }
60
- case "integer": {
61
- if (value === null) {
62
- return 0;
63
- }
64
- if (typeof value === "string" && value.trim() !== "") {
65
- const parsed = Number(value);
66
- if (Number.isInteger(parsed)) {
67
- return parsed;
68
- }
69
- }
70
- if (typeof value === "boolean") {
71
- return value ? 1 : 0;
72
- }
73
- return value;
74
- }
75
- case "boolean": {
76
- if (value === null) {
77
- return false;
78
- }
79
- if (typeof value === "string") {
80
- if (value === "true") {
81
- return true;
82
- }
83
- if (value === "false") {
84
- return false;
85
- }
86
- }
87
- if (typeof value === "number") {
88
- if (value === 1) {
89
- return true;
90
- }
91
- if (value === 0) {
92
- return false;
93
- }
94
- }
95
- return value;
96
- }
97
- case "string": {
98
- if (value === null) {
99
- return "";
100
- }
101
- if (typeof value === "number" || typeof value === "boolean") {
102
- return String(value);
103
- }
104
- return value;
105
- }
106
- case "null": {
107
- if (value === "" || value === 0 || value === false) {
108
- return null;
109
- }
110
- return value;
111
- }
112
- default:
113
- return value;
114
- }
115
- }
116
- function applySchemaObjectCoercion(value, schema) {
117
- const properties = schema.properties;
118
- const definedKeys = new Set(properties ? Object.keys(properties) : []);
119
- if (properties) {
120
- for (const [key, propertySchema] of Object.entries(properties)) {
121
- if (!(key in value)) {
122
- continue;
123
- }
124
- value[key] = coerceWithJsonSchema(value[key], propertySchema);
125
- }
126
- }
127
- if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
128
- for (const [key, propertyValue] of Object.entries(value)) {
129
- if (definedKeys.has(key)) {
130
- continue;
131
- }
132
- value[key] = coerceWithJsonSchema(propertyValue, schema.additionalProperties);
133
- }
134
- }
135
- }
136
- function applySchemaArrayCoercion(value, schema) {
137
- if (Array.isArray(schema.items)) {
138
- for (let index = 0; index < value.length; index++) {
139
- const itemSchema = schema.items[index];
140
- if (!itemSchema) {
141
- continue;
142
- }
143
- value[index] = coerceWithJsonSchema(value[index], itemSchema);
144
- }
145
- return;
146
- }
147
- if (schema.items && typeof schema.items === "object") {
148
- for (let index = 0; index < value.length; index++) {
149
- value[index] = coerceWithJsonSchema(value[index], schema.items);
150
- }
151
- }
152
- }
153
- function coerceWithUnionSchema(value, schemas) {
154
- for (const schema of schemas) {
155
- const validator = getSubSchemaValidator(schema);
156
- if (validator?.Check(value)) {
157
- return value;
158
- }
159
- }
160
- for (const schema of schemas) {
161
- const candidate = structuredClone(value);
162
- const coerced = coerceWithJsonSchema(candidate, schema);
163
- const validator = getSubSchemaValidator(schema);
164
- if (validator?.Check(coerced)) {
165
- return coerced;
166
- }
167
- }
168
- return value;
169
- }
170
- function coerceWithJsonSchema(value, schema) {
171
- let nextValue = value;
172
- if (Array.isArray(schema.allOf)) {
173
- for (const nested of schema.allOf) {
174
- nextValue = coerceWithJsonSchema(nextValue, nested);
175
- }
176
- }
177
- if (Array.isArray(schema.anyOf)) {
178
- nextValue = coerceWithUnionSchema(nextValue, schema.anyOf);
179
- }
180
- if (Array.isArray(schema.oneOf)) {
181
- nextValue = coerceWithUnionSchema(nextValue, schema.oneOf);
182
- }
183
- const schemaTypes = getSchemaTypes(schema);
184
- const matchesUnionMember = schemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType));
185
- if (schemaTypes.length > 0 && !matchesUnionMember) {
186
- for (const schemaType of schemaTypes) {
187
- const candidate = coercePrimitiveByType(nextValue, schemaType);
188
- if (candidate !== nextValue) {
189
- nextValue = candidate;
190
- break;
191
- }
192
- }
193
- }
194
- if (schemaTypes.includes("object") &&
195
- typeof nextValue === "object" &&
196
- nextValue !== null &&
197
- !Array.isArray(nextValue)) {
198
- applySchemaObjectCoercion(nextValue, schema);
199
- }
200
- if (schemaTypes.includes("array") && Array.isArray(nextValue)) {
201
- applySchemaArrayCoercion(nextValue, schema);
202
- }
203
- return nextValue;
204
- }
205
- function normalizeOptionalNulls(value, schema) {
206
- if (Array.isArray(value)) {
207
- if (Array.isArray(schema.items)) {
208
- for (let index = 0; index < value.length; index++) {
209
- const itemSchema = schema.items[index];
210
- if (itemSchema)
211
- normalizeOptionalNulls(value[index], itemSchema);
212
- }
213
- }
214
- else if (schema.items) {
215
- for (const item of value)
216
- normalizeOptionalNulls(item, schema.items);
217
- }
218
- return;
219
- }
220
- if (typeof value !== "object" || value === null || !schema.properties)
221
- return;
222
- const object = value;
223
- const required = new Set(schema.required ?? []);
224
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
225
- if (!(key in object))
226
- continue;
227
- if (object[key] === null &&
228
- !required.has(key) &&
229
- typeof propertySchema.$ref !== "string" &&
230
- getSubSchemaValidator(propertySchema)?.Check(null) === false) {
231
- delete object[key];
232
- }
233
- else {
234
- normalizeOptionalNulls(object[key], propertySchema);
235
- }
236
- }
237
- }
238
5
  function getValidator(schema) {
239
- const key = schema;
240
- const cached = validatorCache.get(key);
6
+ const cached = validatorCache.get(schema);
241
7
  if (cached) {
242
8
  return cached;
243
9
  }
244
- const validator = Compile(schema);
245
- validatorCache.set(key, validator);
10
+ // A $ref that names nothing (a dangling definition in an MCP server's schema) rejects only values at its place,
11
+ // instead of making every call of the tool fail.
12
+ const validator = compile(schema, { formats, coerce: true, unresolvedRefs: "reject" });
13
+ validatorCache.set(schema, validator);
246
14
  return validator;
247
15
  }
248
- const dereferencedSchemaCache = new WeakMap();
249
- function decodePointerSegments(pointer) {
16
+ /** A pi-schema error path (a JSON Pointer) as the dotted path the model sees: `/edits/0/oldText` -> `edits.0.oldText`. */
17
+ function formatValidationPath(pointer) {
18
+ if (pointer === "")
19
+ return "root";
250
20
  return pointer
251
- .split("/")
252
21
  .slice(1)
253
- .map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
254
- }
255
- function resolvePointer(root, pointer) {
256
- if (pointer !== "#" && !pointer.startsWith("#/"))
257
- return undefined;
258
- let node = root;
259
- for (const segment of decodePointerSegments(pointer.slice(1))) {
260
- if (typeof node !== "object" || node === null)
261
- return undefined;
262
- node = node[segment];
263
- }
264
- return node;
265
- }
266
- /**
267
- * Inlines local `$ref`s so that every error's schema path points into the tool schema itself. TypeBox reports
268
- * errors inside a referenced schema relative to the reference target, which hides which union branch they
269
- * belong to. Recursive references are left in place.
270
- */
271
- function dereferenceSchema(schema) {
272
- const cached = dereferencedSchemaCache.get(schema);
273
- if (cached)
274
- return cached;
275
- const visit = (node, activeRefs) => {
276
- if (Array.isArray(node))
277
- return node.map((item) => visit(item, activeRefs));
278
- if (typeof node !== "object" || node === null)
279
- return node;
280
- const { $ref: ref, ...rest } = node;
281
- const target = typeof ref === "string" && !activeRefs.has(ref) ? resolvePointer(schema, ref) : undefined;
282
- const entries = Object.entries(rest).map(([key, value]) => [key, visit(value, activeRefs)]);
283
- if (target === undefined)
284
- return Object.fromEntries(ref === undefined ? entries : [["$ref", ref], ...entries]);
285
- const resolved = visit(target, new Set([...activeRefs, ref]));
286
- return entries.length === 0 ? resolved : { ...resolved, ...Object.fromEntries(entries) };
287
- };
288
- const dereferenced = (JSON.stringify(schema).includes('"$ref"') ? visit(schema, new Set()) : schema);
289
- dereferencedSchemaCache.set(schema, dereferenced);
290
- return dereferenced;
291
- }
292
- // TypeBox stops collecting errors at Settings.maxErrors (8 by default). A union reports every branch in order,
293
- // so the cap could hide the only branch the arguments were meant for.
294
- function collectErrors(validator, value) {
295
- const { maxErrors } = Settings.Get();
296
- Settings.Set({ maxErrors: Number.POSITIVE_INFINITY });
297
- try {
298
- return validator.Errors(value);
299
- }
300
- finally {
301
- Settings.Set({ maxErrors });
302
- }
303
- }
304
- /**
305
- * A failed union reports the errors of every branch. When branches are told apart by a constant property, such
306
- * as `operation: "save_product"`, keep only the errors of the branches the arguments selected. When no branch
307
- * matches, report the allowed constants instead of every branch's shape.
308
- */
309
- function narrowUnionErrors(errors) {
310
- let result = errors;
311
- const unions = errors
312
- .filter((error) => error.keyword === "anyOf" || error.keyword === "oneOf")
313
- .sort((left, right) => left.schemaPath.length - right.schemaPath.length);
314
- for (const union of unions) {
315
- if (!result.includes(union))
316
- continue;
317
- const prefix = `${union.schemaPath}/${union.keyword}/`;
318
- const branchOf = (error) => error.schemaPath.startsWith(prefix) ? error.schemaPath.slice(prefix.length).split("/")[0] : undefined;
319
- const discriminatorErrors = result.filter((error) => (error.keyword === "const" || error.keyword === "enum") &&
320
- error.schemaPath.startsWith(prefix) &&
321
- /^\d+\/properties\/[^/]+$/.test(error.schemaPath.slice(prefix.length)));
322
- if (discriminatorErrors.length === 0)
323
- continue;
324
- const branches = new Set(result.map(branchOf).filter((branch) => branch !== undefined));
325
- const rejected = new Set(discriminatorErrors.map(branchOf));
326
- if (rejected.size < branches.size) {
327
- result = result.filter((error) => error !== union && !rejected.has(branchOf(error)));
328
- continue;
329
- }
330
- const discriminatorPaths = new Set(discriminatorErrors.map((error) => error.instancePath));
331
- if (discriminatorPaths.size !== 1)
332
- continue;
333
- const allowedValues = discriminatorErrors.flatMap((error) => error.keyword === "const"
334
- ? [error.params.allowedValue]
335
- : error.params.allowedValues);
336
- const replacement = {
337
- keyword: "enum",
338
- schemaPath: union.schemaPath,
339
- instancePath: discriminatorErrors[0].instancePath,
340
- params: { allowedValues },
341
- message: "",
342
- };
343
- result = result.flatMap((error) => error === union ? [replacement] : branchOf(error) === undefined ? [error] : []);
344
- }
345
- return result;
346
- }
347
- function valueAtPointer(value, pointer) {
348
- let node = value;
349
- for (const segment of decodePointerSegments(pointer)) {
350
- if (typeof node !== "object" || node === null)
351
- return undefined;
352
- node = node[segment];
353
- }
354
- return node;
355
- }
356
- function quoteList(values) {
357
- return values.map((value) => JSON.stringify(value)).join(", ");
358
- }
359
- function describeError(error) {
360
- switch (error.keyword) {
361
- case "required": {
362
- const missing = error.params.requiredProperties;
363
- return `missing required ${missing.length === 1 ? "property" : "properties"} ${quoteList(missing)}`;
364
- }
365
- case "const":
366
- return `must be ${JSON.stringify(error.params.allowedValue)}`;
367
- case "enum":
368
- return `must be one of ${quoteList(error.params.allowedValues)}`;
369
- default:
370
- return error.message;
371
- }
372
- }
373
- /** Explains why `value` fails `schema`, with each issue located at the argument it concerns. */
374
- function explainValidationFailure(schema, value, basePath) {
375
- const validator = getSubSchemaValidator(schema);
376
- if (!validator)
377
- return [];
378
- const issues = [];
379
- const errors = narrowUnionErrors(collectErrors(validator, value));
380
- // Each key an additionalProperties error lists is explained below, so skip TypeBox's per-key errors for them.
381
- const additionalPropertiesPaths = errors
382
- .filter((error) => error.keyword === "additionalProperties")
383
- .map((error) => `${error.schemaPath}/additionalProperties`);
384
- for (const error of errors) {
385
- if (additionalPropertiesPaths.some((path) => error.schemaPath === path || error.schemaPath.startsWith(`${path}/`))) {
386
- continue;
387
- }
388
- const instancePath = `${basePath}${error.instancePath}`;
389
- if (error.keyword !== "additionalProperties") {
390
- issues.push({ instancePath, message: describeError(error) });
391
- continue;
392
- }
393
- const keys = error.params.additionalProperties;
394
- const valueSchema = resolvePointer(schema, error.schemaPath)
395
- ?.additionalProperties;
396
- if (typeof valueSchema !== "object") {
397
- issues.push({
398
- instancePath,
399
- message: `unexpected ${keys.length === 1 ? "property" : "properties"} ${quoteList(keys)}`,
400
- });
401
- continue;
402
- }
403
- // TypeBox names a map entry whose value is invalid as if the key itself were not allowed; explain the value.
404
- for (const key of keys) {
405
- const segment = `/${key.replace(/~/g, "~0").replace(/\//g, "~1")}`;
406
- const entryValue = valueAtPointer(value, `${error.instancePath}${segment}`);
407
- const entryIssues = explainValidationFailure(valueSchema, entryValue, `${instancePath}${segment}`);
408
- issues.push(...(entryIssues.length > 0
409
- ? entryIssues
410
- : [{ instancePath: `${instancePath}${segment}`, message: "is invalid" }]));
411
- }
412
- }
413
- const seen = new Set();
414
- return issues.filter((issue) => {
415
- const key = `${issue.instancePath}\0${issue.message}`;
416
- if (seen.has(key))
417
- return false;
418
- seen.add(key);
419
- return true;
420
- });
421
- }
422
- function formatIssuePath(instancePath) {
423
- return decodePointerSegments(instancePath).join(".") || "root";
22
+ .split("/")
23
+ .map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"))
24
+ .join(".");
424
25
  }
425
26
  /**
426
- * Finds a tool by name and validates the tool call arguments against its TypeBox schema
27
+ * Finds a tool by name and validates the tool call arguments against its JSON Schema
427
28
  * @param tools Array of tool definitions
428
29
  * @param toolCall The tool call from the LLM
429
30
  * @returns The validated arguments
@@ -437,43 +38,24 @@ export function validateToolCall(tools, toolCall) {
437
38
  return validateToolArguments(tool, toolCall);
438
39
  }
439
40
  /**
440
- * Validates tool call arguments against the tool's TypeBox schema
441
- * @param tool The tool definition with TypeBox schema
41
+ * Validates tool call arguments against the tool's JSON Schema (any JSON Schema: pi-schema's builders, TypeBox, plain
42
+ * objects). The arguments are coerced first (pi-schema's `parse()`): models often send `"42"` for a number, a single
43
+ * value for an array, or `null` for an omitted optional property.
44
+ * @param tool The tool definition with its JSON Schema
442
45
  * @param toolCall The tool call from the LLM
443
46
  * @returns The validated (and potentially coerced) arguments
444
47
  * @throws Error with formatted message if validation fails
445
48
  */
446
49
  export function validateToolArguments(tool, toolCall) {
447
- const args = structuredClone(toolCall.arguments);
448
- normalizeOptionalNulls(args, tool.parameters);
449
- Value.Convert(tool.parameters, args);
450
- const validator = getValidator(tool.parameters);
451
- if (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) {
452
- const coerced = coerceWithJsonSchema(args, tool.parameters);
453
- if (coerced !== args) {
454
- if (typeof args === "object" && args !== null && typeof coerced === "object" && coerced !== null) {
455
- for (const key of Object.keys(args)) {
456
- delete args[key];
457
- }
458
- Object.assign(args, coerced);
459
- }
460
- else {
461
- return validator.Check(coerced) ? coerced : args;
462
- }
463
- }
50
+ if (toolCall.argumentsError) {
51
+ throw new Error(`Invalid arguments for tool "${toolCall.name}": ${toolCall.argumentsError}`);
464
52
  }
465
- if (validator.Check(args)) {
466
- return args;
53
+ // A copy, so tools that modify their arguments never modify the tool call in the transcript.
54
+ const result = getValidator(tool.parameters).parse(structuredClone(toolCall.arguments));
55
+ if (result.ok) {
56
+ return result.value;
467
57
  }
468
- const explained = explainValidationFailure(dereferenceSchema(tool.parameters), args, "");
469
- const issues = explained.length > 0
470
- ? explained
471
- : collectErrors(validator, args).map((error) => ({
472
- instancePath: error.instancePath,
473
- message: describeError(error),
474
- }));
475
- const errors = issues.map((issue) => ` - ${formatIssuePath(issue.instancePath)}: ${issue.message}`).join("\n") ||
476
- "Unknown validation error";
58
+ const errors = result.errors.map((error) => ` - ${formatValidationPath(error.path)}: ${error.message}`).join("\n");
477
59
  const errorMessage = `Validation failed for tool "${toolCall.name}":\n${errors}\n\nReceived arguments:\n${JSON.stringify(toolCall.arguments, null, 2)}`;
478
60
  throw new Error(errorMessage);
479
61
  }
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,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CAAC,IAAI,CAAC;QAChG,0BAA0B,CAAC;IAE5B,MAAM,YAAY,GAAG,+BAA+B,QAAQ,CAAC,IAAI,OAAO,MAAM,4BAA4B,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;IAExJ,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import { Compile } from \"typebox/compile\";\nimport type { TLocalizedValidationError } from \"typebox/error\";\nimport { Settings } from \"typebox/system\";\nimport { Value } from \"typebox/value\";\nimport type { Tool, ToolCall } from \"../types.ts\";\n\nconst validatorCache = new WeakMap<object, ReturnType<typeof Compile>>();\nconst TYPEBOX_KIND = Symbol.for(\"TypeBox.Kind\");\n\ninterface JsonSchemaObject {\n\ttype?: string | string[];\n\tproperties?: Record<string, JsonSchemaObject>;\n\trequired?: string[];\n\titems?: JsonSchemaObject | JsonSchemaObject[];\n\tadditionalProperties?: boolean | JsonSchemaObject;\n\tallOf?: JsonSchemaObject[];\n\tanyOf?: JsonSchemaObject[];\n\toneOf?: JsonSchemaObject[];\n}\n\nfunction getSchemaTypes(schema: JsonSchemaObject): string[] {\n\tif (typeof schema.type === \"string\") {\n\t\treturn [schema.type];\n\t}\n\tif (Array.isArray(schema.type)) {\n\t\treturn schema.type.filter((type): type is string => typeof type === \"string\");\n\t}\n\treturn [];\n}\n\nfunction matchesJsonType(value: unknown, type: string): boolean {\n\tswitch (type) {\n\t\tcase \"number\":\n\t\t\treturn typeof value === \"number\";\n\t\tcase \"integer\":\n\t\t\treturn typeof value === \"number\" && Number.isInteger(value);\n\t\tcase \"boolean\":\n\t\t\treturn typeof value === \"boolean\";\n\t\tcase \"string\":\n\t\t\treturn typeof value === \"string\";\n\t\tcase \"null\":\n\t\t\treturn value === null;\n\t\tcase \"array\":\n\t\t\treturn Array.isArray(value);\n\t\tcase \"object\":\n\t\t\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction getSubSchemaValidator(schema: JsonSchemaObject): ReturnType<typeof Compile> | undefined {\n\ttry {\n\t\treturn getValidator(schema as Tool[\"parameters\"]);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction coercePrimitiveByType(value: unknown, type: string): unknown {\n\tswitch (type) {\n\t\tcase \"number\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (typeof value === \"string\" && value.trim() !== \"\") {\n\t\t\t\tconst parsed = Number(value);\n\t\t\t\tif (Number.isFinite(parsed)) {\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"boolean\") {\n\t\t\t\treturn value ? 1 : 0;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"integer\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (typeof value === \"string\" && value.trim() !== \"\") {\n\t\t\t\tconst parsed = Number(value);\n\t\t\t\tif (Number.isInteger(parsed)) {\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"boolean\") {\n\t\t\t\treturn value ? 1 : 0;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"boolean\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (typeof value === \"string\") {\n\t\t\t\tif (value === \"true\") {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (value === \"false\") {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"number\") {\n\t\t\t\tif (value === 1) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"string\": {\n\t\t\tif (value === null) {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\tif (typeof value === \"number\" || typeof value === \"boolean\") {\n\t\t\t\treturn String(value);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase \"null\": {\n\t\t\tif (value === \"\" || value === 0 || value === false) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tdefault:\n\t\t\treturn value;\n\t}\n}\n\nfunction applySchemaObjectCoercion(value: Record<string, unknown>, schema: JsonSchemaObject): void {\n\tconst properties = schema.properties;\n\tconst definedKeys = new Set<string>(properties ? Object.keys(properties) : []);\n\n\tif (properties) {\n\t\tfor (const [key, propertySchema] of Object.entries(properties)) {\n\t\t\tif (!(key in value)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue[key] = coerceWithJsonSchema(value[key], propertySchema);\n\t\t}\n\t}\n\n\tif (schema.additionalProperties && typeof schema.additionalProperties === \"object\") {\n\t\tfor (const [key, propertyValue] of Object.entries(value)) {\n\t\t\tif (definedKeys.has(key)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue[key] = coerceWithJsonSchema(propertyValue, schema.additionalProperties);\n\t\t}\n\t}\n}\n\nfunction applySchemaArrayCoercion(value: unknown[], schema: JsonSchemaObject): void {\n\tif (Array.isArray(schema.items)) {\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tconst itemSchema = schema.items[index];\n\t\t\tif (!itemSchema) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalue[index] = coerceWithJsonSchema(value[index], itemSchema);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (schema.items && typeof schema.items === \"object\") {\n\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\tvalue[index] = coerceWithJsonSchema(value[index], schema.items);\n\t\t}\n\t}\n}\n\nfunction coerceWithUnionSchema(value: unknown, schemas: JsonSchemaObject[]): unknown {\n\tfor (const schema of schemas) {\n\t\tconst validator = getSubSchemaValidator(schema);\n\t\tif (validator?.Check(value)) {\n\t\t\treturn value;\n\t\t}\n\t}\n\n\tfor (const schema of schemas) {\n\t\tconst candidate = structuredClone(value);\n\t\tconst coerced = coerceWithJsonSchema(candidate, schema);\n\t\tconst validator = getSubSchemaValidator(schema);\n\t\tif (validator?.Check(coerced)) {\n\t\t\treturn coerced;\n\t\t}\n\t}\n\treturn value;\n}\n\nfunction coerceWithJsonSchema(value: unknown, schema: JsonSchemaObject): unknown {\n\tlet nextValue = value;\n\n\tif (Array.isArray(schema.allOf)) {\n\t\tfor (const nested of schema.allOf) {\n\t\t\tnextValue = coerceWithJsonSchema(nextValue, nested);\n\t\t}\n\t}\n\n\tif (Array.isArray(schema.anyOf)) {\n\t\tnextValue = coerceWithUnionSchema(nextValue, schema.anyOf);\n\t}\n\n\tif (Array.isArray(schema.oneOf)) {\n\t\tnextValue = coerceWithUnionSchema(nextValue, schema.oneOf);\n\t}\n\n\tconst schemaTypes = getSchemaTypes(schema);\n\tconst matchesUnionMember =\n\t\tschemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType));\n\tif (schemaTypes.length > 0 && !matchesUnionMember) {\n\t\tfor (const schemaType of schemaTypes) {\n\t\t\tconst candidate = coercePrimitiveByType(nextValue, schemaType);\n\t\t\tif (candidate !== nextValue) {\n\t\t\t\tnextValue = candidate;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (\n\t\tschemaTypes.includes(\"object\") &&\n\t\ttypeof nextValue === \"object\" &&\n\t\tnextValue !== null &&\n\t\t!Array.isArray(nextValue)\n\t) {\n\t\tapplySchemaObjectCoercion(nextValue as Record<string, unknown>, schema);\n\t}\n\n\tif (schemaTypes.includes(\"array\") && Array.isArray(nextValue)) {\n\t\tapplySchemaArrayCoercion(nextValue, schema);\n\t}\n\n\treturn nextValue;\n}\n\nfunction normalizeOptionalNulls(value: unknown, schema: JsonSchemaObject): void {\n\tif (Array.isArray(value)) {\n\t\tif (Array.isArray(schema.items)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tconst itemSchema = schema.items[index];\n\t\t\t\tif (itemSchema) normalizeOptionalNulls(value[index], itemSchema);\n\t\t\t}\n\t\t} else if (schema.items) {\n\t\t\tfor (const item of value) normalizeOptionalNulls(item, schema.items);\n\t\t}\n\t\treturn;\n\t}\n\tif (typeof value !== \"object\" || value === null || !schema.properties) return;\n\n\tconst object = value as Record<string, unknown>;\n\tconst required = new Set(schema.required ?? []);\n\tfor (const [key, propertySchema] of Object.entries(schema.properties)) {\n\t\tif (!(key in object)) continue;\n\t\tif (\n\t\t\tobject[key] === null &&\n\t\t\t!required.has(key) &&\n\t\t\ttypeof (propertySchema as { $ref?: unknown }).$ref !== \"string\" &&\n\t\t\tgetSubSchemaValidator(propertySchema)?.Check(null) === false\n\t\t) {\n\t\t\tdelete object[key];\n\t\t} else {\n\t\t\tnormalizeOptionalNulls(object[key], propertySchema);\n\t\t}\n\t}\n}\n\nfunction getValidator(schema: Tool[\"parameters\"]): ReturnType<typeof Compile> {\n\tconst key = schema as object;\n\tconst cached = validatorCache.get(key);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\tconst validator = Compile(schema);\n\tvalidatorCache.set(key, validator);\n\treturn validator;\n}\n\ninterface ValidationIssue {\n\tinstancePath: string;\n\tmessage: string;\n}\n\nconst dereferencedSchemaCache = new WeakMap<object, JsonSchemaObject>();\n\nfunction decodePointerSegments(pointer: string): string[] {\n\treturn pointer\n\t\t.split(\"/\")\n\t\t.slice(1)\n\t\t.map((segment) => segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n}\n\nfunction resolvePointer(root: unknown, pointer: string): unknown {\n\tif (pointer !== \"#\" && !pointer.startsWith(\"#/\")) return undefined;\n\tlet node = root;\n\tfor (const segment of decodePointerSegments(pointer.slice(1))) {\n\t\tif (typeof node !== \"object\" || node === null) return undefined;\n\t\tnode = (node as Record<string, unknown>)[segment];\n\t}\n\treturn node;\n}\n\n/**\n * Inlines local `$ref`s so that every error's schema path points into the tool schema itself. TypeBox reports\n * errors inside a referenced schema relative to the reference target, which hides which union branch they\n * belong to. Recursive references are left in place.\n */\nfunction dereferenceSchema(schema: Tool[\"parameters\"]): JsonSchemaObject {\n\tconst cached = dereferencedSchemaCache.get(schema);\n\tif (cached) return cached;\n\tconst visit = (node: unknown, activeRefs: ReadonlySet<string>): unknown => {\n\t\tif (Array.isArray(node)) return node.map((item) => visit(item, activeRefs));\n\t\tif (typeof node !== \"object\" || node === null) return node;\n\t\tconst { $ref: ref, ...rest } = node as Record<string, unknown>;\n\t\tconst target = typeof ref === \"string\" && !activeRefs.has(ref) ? resolvePointer(schema, ref) : undefined;\n\t\tconst entries = Object.entries(rest).map(([key, value]) => [key, visit(value, activeRefs)]);\n\t\tif (target === undefined) return Object.fromEntries(ref === undefined ? entries : [[\"$ref\", ref], ...entries]);\n\t\tconst resolved = visit(target, new Set([...activeRefs, ref as string]));\n\t\treturn entries.length === 0 ? resolved : { ...(resolved as object), ...Object.fromEntries(entries) };\n\t};\n\tconst dereferenced = (\n\t\tJSON.stringify(schema).includes('\"$ref\"') ? visit(schema, new Set()) : schema\n\t) as JsonSchemaObject;\n\tdereferencedSchemaCache.set(schema, dereferenced);\n\treturn dereferenced;\n}\n\n// TypeBox stops collecting errors at Settings.maxErrors (8 by default). A union reports every branch in order,\n// so the cap could hide the only branch the arguments were meant for.\nfunction collectErrors(validator: ReturnType<typeof Compile>, value: unknown): TLocalizedValidationError[] {\n\tconst { maxErrors } = Settings.Get();\n\tSettings.Set({ maxErrors: Number.POSITIVE_INFINITY });\n\ttry {\n\t\treturn validator.Errors(value);\n\t} finally {\n\t\tSettings.Set({ maxErrors });\n\t}\n}\n\n/**\n * A failed union reports the errors of every branch. When branches are told apart by a constant property, such\n * as `operation: \"save_product\"`, keep only the errors of the branches the arguments selected. When no branch\n * matches, report the allowed constants instead of every branch's shape.\n */\nfunction narrowUnionErrors(errors: TLocalizedValidationError[]): TLocalizedValidationError[] {\n\tlet result = errors;\n\tconst unions = errors\n\t\t.filter((error) => error.keyword === \"anyOf\" || error.keyword === \"oneOf\")\n\t\t.sort((left, right) => left.schemaPath.length - right.schemaPath.length);\n\tfor (const union of unions) {\n\t\tif (!result.includes(union)) continue;\n\t\tconst prefix = `${union.schemaPath}/${union.keyword}/`;\n\t\tconst branchOf = (error: TLocalizedValidationError) =>\n\t\t\terror.schemaPath.startsWith(prefix) ? error.schemaPath.slice(prefix.length).split(\"/\")[0] : undefined;\n\t\tconst discriminatorErrors = result.filter(\n\t\t\t(error) =>\n\t\t\t\t(error.keyword === \"const\" || error.keyword === \"enum\") &&\n\t\t\t\terror.schemaPath.startsWith(prefix) &&\n\t\t\t\t/^\\d+\\/properties\\/[^/]+$/.test(error.schemaPath.slice(prefix.length)),\n\t\t);\n\t\tif (discriminatorErrors.length === 0) continue;\n\t\tconst branches = new Set(result.map(branchOf).filter((branch) => branch !== undefined));\n\t\tconst rejected = new Set(discriminatorErrors.map(branchOf));\n\t\tif (rejected.size < branches.size) {\n\t\t\tresult = result.filter((error) => error !== union && !rejected.has(branchOf(error)));\n\t\t\tcontinue;\n\t\t}\n\t\tconst discriminatorPaths = new Set(discriminatorErrors.map((error) => error.instancePath));\n\t\tif (discriminatorPaths.size !== 1) continue;\n\t\tconst allowedValues = discriminatorErrors.flatMap((error) =>\n\t\t\terror.keyword === \"const\"\n\t\t\t\t? [error.params.allowedValue]\n\t\t\t\t: (error.params as { allowedValues: unknown[] }).allowedValues,\n\t\t);\n\t\tconst replacement = {\n\t\t\tkeyword: \"enum\",\n\t\t\tschemaPath: union.schemaPath,\n\t\t\tinstancePath: discriminatorErrors[0].instancePath,\n\t\t\tparams: { allowedValues },\n\t\t\tmessage: \"\",\n\t\t} as TLocalizedValidationError;\n\t\tresult = result.flatMap((error) =>\n\t\t\terror === union ? [replacement] : branchOf(error) === undefined ? [error] : [],\n\t\t);\n\t}\n\treturn result;\n}\n\nfunction valueAtPointer(value: unknown, pointer: string): unknown {\n\tlet node = value;\n\tfor (const segment of decodePointerSegments(pointer)) {\n\t\tif (typeof node !== \"object\" || node === null) return undefined;\n\t\tnode = (node as Record<string, unknown>)[segment];\n\t}\n\treturn node;\n}\n\nfunction quoteList(values: unknown[]): string {\n\treturn values.map((value) => JSON.stringify(value)).join(\", \");\n}\n\nfunction describeError(error: TLocalizedValidationError): string {\n\tswitch (error.keyword) {\n\t\tcase \"required\": {\n\t\t\tconst missing = error.params.requiredProperties;\n\t\t\treturn `missing required ${missing.length === 1 ? \"property\" : \"properties\"} ${quoteList(missing)}`;\n\t\t}\n\t\tcase \"const\":\n\t\t\treturn `must be ${JSON.stringify(error.params.allowedValue)}`;\n\t\tcase \"enum\":\n\t\t\treturn `must be one of ${quoteList(error.params.allowedValues)}`;\n\t\tdefault:\n\t\t\treturn error.message;\n\t}\n}\n\n/** Explains why `value` fails `schema`, with each issue located at the argument it concerns. */\nfunction explainValidationFailure(schema: JsonSchemaObject, value: unknown, basePath: string): ValidationIssue[] {\n\tconst validator = getSubSchemaValidator(schema);\n\tif (!validator) return [];\n\tconst issues: ValidationIssue[] = [];\n\tconst errors = narrowUnionErrors(collectErrors(validator, value));\n\t// Each key an additionalProperties error lists is explained below, so skip TypeBox's per-key errors for them.\n\tconst additionalPropertiesPaths = errors\n\t\t.filter((error) => error.keyword === \"additionalProperties\")\n\t\t.map((error) => `${error.schemaPath}/additionalProperties`);\n\tfor (const error of errors) {\n\t\tif (\n\t\t\tadditionalPropertiesPaths.some((path) => error.schemaPath === path || error.schemaPath.startsWith(`${path}/`))\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst instancePath = `${basePath}${error.instancePath}`;\n\t\tif (error.keyword !== \"additionalProperties\") {\n\t\t\tissues.push({ instancePath, message: describeError(error) });\n\t\t\tcontinue;\n\t\t}\n\t\tconst keys = error.params.additionalProperties;\n\t\tconst valueSchema = (resolvePointer(schema, error.schemaPath) as JsonSchemaObject | undefined)\n\t\t\t?.additionalProperties;\n\t\tif (typeof valueSchema !== \"object\") {\n\t\t\tissues.push({\n\t\t\t\tinstancePath,\n\t\t\t\tmessage: `unexpected ${keys.length === 1 ? \"property\" : \"properties\"} ${quoteList(keys)}`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\t// TypeBox names a map entry whose value is invalid as if the key itself were not allowed; explain the value.\n\t\tfor (const key of keys) {\n\t\t\tconst segment = `/${key.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")}`;\n\t\t\tconst entryValue = valueAtPointer(value, `${error.instancePath}${segment}`);\n\t\t\tconst entryIssues = explainValidationFailure(valueSchema, entryValue, `${instancePath}${segment}`);\n\t\t\tissues.push(\n\t\t\t\t...(entryIssues.length > 0\n\t\t\t\t\t? entryIssues\n\t\t\t\t\t: [{ instancePath: `${instancePath}${segment}`, message: \"is invalid\" }]),\n\t\t\t);\n\t\t}\n\t}\n\tconst seen = new Set<string>();\n\treturn issues.filter((issue) => {\n\t\tconst key = `${issue.instancePath}\\0${issue.message}`;\n\t\tif (seen.has(key)) return false;\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n}\n\nfunction formatIssuePath(instancePath: string): string {\n\treturn decodePointerSegments(instancePath).join(\".\") || \"root\";\n}\n\n/**\n * Finds a tool by name and validates the tool call arguments against its TypeBox schema\n * @param tools Array of tool definitions\n * @param toolCall The tool call from the LLM\n * @returns The validated arguments\n * @throws Error if tool is not found or validation fails\n */\nexport function validateToolCall(tools: Tool[], toolCall: ToolCall): any {\n\tconst tool = tools.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\tthrow new Error(`Tool \"${toolCall.name}\" not found`);\n\t}\n\treturn validateToolArguments(tool, toolCall);\n}\n\n/**\n * Validates tool call arguments against the tool's TypeBox schema\n * @param tool The tool definition with TypeBox schema\n * @param toolCall The tool call from the LLM\n * @returns The validated (and potentially coerced) arguments\n * @throws Error with formatted message if validation fails\n */\nexport function validateToolArguments(tool: Tool, toolCall: ToolCall): any {\n\tconst args = structuredClone(toolCall.arguments);\n\tnormalizeOptionalNulls(args, tool.parameters as JsonSchemaObject);\n\tValue.Convert(tool.parameters, args);\n\n\tconst validator = getValidator(tool.parameters);\n\tif (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) {\n\t\tconst coerced = coerceWithJsonSchema(args, tool.parameters as JsonSchemaObject);\n\t\tif (coerced !== args) {\n\t\t\tif (typeof args === \"object\" && args !== null && typeof coerced === \"object\" && coerced !== null) {\n\t\t\t\tfor (const key of Object.keys(args)) {\n\t\t\t\t\tdelete args[key];\n\t\t\t\t}\n\t\t\t\tObject.assign(args, coerced);\n\t\t\t} else {\n\t\t\t\treturn validator.Check(coerced) ? coerced : args;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (validator.Check(args)) {\n\t\treturn args;\n\t}\n\n\tconst explained = explainValidationFailure(dereferenceSchema(tool.parameters), args, \"\");\n\tconst issues =\n\t\texplained.length > 0\n\t\t\t? explained\n\t\t\t: collectErrors(validator, args).map((error) => ({\n\t\t\t\t\tinstancePath: error.instancePath,\n\t\t\t\t\tmessage: describeError(error),\n\t\t\t\t}));\n\tconst errors =\n\t\tissues.map((issue) => ` - ${formatIssuePath(issue.instancePath)}: ${issue.message}`).join(\"\\n\") ||\n\t\t\"Unknown validation error\";\n\n\tconst errorMessage = `Validation failed for tool \"${toolCall.name}\":\\n${errors}\\n\\nReceived arguments:\\n${JSON.stringify(toolCall.arguments, null, 2)}`;\n\n\tthrow new Error(errorMessage);\n}\n"]}
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,OAAO,EAAE,MAAM,2BAA2B,CAAC;AAC5E,OAAO,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAG5D,wHAAwH;AACxH,MAAM,cAAc,GAAG,IAAI,OAAO,EAA6B,CAAC;AAEhE,SAAS,YAAY,CAAC,MAA0B;IAC/C,MAAM,MAAM,GAAG,cAAc,CAAC,GAAG,CAAC,MAAM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AC,+BAA+B,QAAQ,CAAC,IAAI,MAAM,QAAQ,CAAC,cAAc,EAAE,CAAC,CAAC;IAC9F,CAAC;IACD,6FAA6F;IAC7F,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC;IACxF,IAAI,MAAM,CAAC,EAAE,EAAE,CAAC;QACf,OAAO,MAAM,CAAC,KAAK,CAAC;IACrB,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,oBAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAEpH,MAAM,YAAY,GAAG,+BAA+B,QAAQ,CAAC,IAAI,OAAO,MAAM,4BAA4B,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;IAExJ,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import { type CoercingValidator, compile } from \"@earendil-works/pi-schema\";\nimport { formats } from \"@earendil-works/pi-schema/formats\";\nimport type { Tool, ToolCall } from \"../types.ts\";\n\n// One compiled validator per schema object: tool schemas are long-lived, so the WeakMap drops entries with their tools.\nconst validatorCache = new WeakMap<object, CoercingValidator>();\n\nfunction getValidator(schema: Tool[\"parameters\"]): CoercingValidator {\n\tconst cached = validatorCache.get(schema);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\t// A $ref that names nothing (a dangling definition in an MCP server's schema) rejects only values at its place,\n\t// instead of making every call of the tool fail.\n\tconst validator = compile(schema, { formats, coerce: true, unresolvedRefs: \"reject\" });\n\tvalidatorCache.set(schema, validator);\n\treturn validator;\n}\n\n/** A pi-schema error path (a JSON Pointer) as the dotted path the model sees: `/edits/0/oldText` -> `edits.0.oldText`. */\nfunction formatValidationPath(pointer: string): string {\n\tif (pointer === \"\") return \"root\";\n\treturn pointer\n\t\t.slice(1)\n\t\t.split(\"/\")\n\t\t.map((segment) => segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\"))\n\t\t.join(\".\");\n}\n\n/**\n * Finds a tool by name and validates the tool call arguments against its JSON Schema\n * @param tools Array of tool definitions\n * @param toolCall The tool call from the LLM\n * @returns The validated arguments\n * @throws Error if tool is not found or validation fails\n */\nexport function validateToolCall(tools: Tool[], toolCall: ToolCall): any {\n\tconst tool = tools.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\tthrow new Error(`Tool \"${toolCall.name}\" not found`);\n\t}\n\treturn validateToolArguments(tool, toolCall);\n}\n\n/**\n * Validates tool call arguments against the tool's JSON Schema (any JSON Schema: pi-schema's builders, TypeBox, plain\n * objects). The arguments are coerced first (pi-schema's `parse()`): models often send `\"42\"` for a number, a single\n * value for an array, or `null` for an omitted optional property.\n * @param tool The tool definition with its JSON Schema\n * @param toolCall The tool call from the LLM\n * @returns The validated (and potentially coerced) arguments\n * @throws Error with formatted message if validation fails\n */\nexport function validateToolArguments(tool: Tool, toolCall: ToolCall): any {\n\tif (toolCall.argumentsError) {\n\t\tthrow new Error(`Invalid arguments for tool \"${toolCall.name}\": ${toolCall.argumentsError}`);\n\t}\n\t// A copy, so tools that modify their arguments never modify the tool call in the transcript.\n\tconst result = getValidator(tool.parameters).parse(structuredClone(toolCall.arguments));\n\tif (result.ok) {\n\t\treturn result.value;\n\t}\n\n\tconst errors = result.errors.map((error) => ` - ${formatValidationPath(error.path)}: ${error.message}`).join(\"\\n\");\n\n\tconst errorMessage = `Validation failed for tool \"${toolCall.name}\":\\n${errors}\\n\\nReceived arguments:\\n${JSON.stringify(toolCall.arguments, null, 2)}`;\n\n\tthrow new Error(errorMessage);\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare const PI_AI_VERSION = "1.6.0";
2
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/utils/version.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,aAAa,UAAU,CAAC"}
@@ -0,0 +1,3 @@
1
+ // The @earendil-works/pi-ai package version. scripts/sync-versions.js keeps it in sync with package.json.
2
+ export const PI_AI_VERSION = "1.6.0";
3
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/utils/version.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,MAAM,CAAC,MAAM,aAAa,GAAG,OAAO,CAAC","sourcesContent":["// The @earendil-works/pi-ai package version. scripts/sync-versions.js keeps it in sync with package.json.\nexport const PI_AI_VERSION = \"1.6.0\";\n"]}