@e4779/pi-fabric 0.109.2-fork.23 → 0.116.0-fork.25

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 (346) hide show
  1. package/README.md +3 -1
  2. package/THIRD_PARTY_NOTICES.md +9 -2
  3. package/dist/agents/completion-inbox.d.ts.map +1 -1
  4. package/dist/agents/handoff.d.ts +1 -1
  5. package/dist/agents/handoff.d.ts.map +1 -1
  6. package/dist/agents/manager.d.ts +8 -0
  7. package/dist/agents/manager.d.ts.map +1 -1
  8. package/dist/agents/provider-bridge.d.ts +64 -0
  9. package/dist/agents/provider-bridge.d.ts.map +1 -0
  10. package/dist/agents/provider-bridge.js +117 -0
  11. package/dist/agents/provider-bridge.js.map +7 -0
  12. package/dist/agents/runner-registry.d.ts +3 -0
  13. package/dist/agents/runner-registry.d.ts.map +1 -1
  14. package/dist/agents/trace-context-request.d.ts +4 -0
  15. package/dist/agents/trace-context-request.d.ts.map +1 -0
  16. package/dist/agents/trace-context.d.ts +31 -0
  17. package/dist/agents/trace-context.d.ts.map +1 -0
  18. package/dist/agents/types.d.ts +13 -0
  19. package/dist/agents/types.d.ts.map +1 -1
  20. package/dist/agents.js +7 -7
  21. package/dist/audit/details.d.ts +5 -2
  22. package/dist/audit/details.d.ts.map +1 -1
  23. package/dist/capture/interceptor.d.ts.map +1 -1
  24. package/dist/chunks/{chunk-X2TRSE7D.js → chunk-2YG4ZA2K.js} +2 -2
  25. package/dist/chunks/{chunk-WHBJDTCR.js → chunk-4GGBND7V.js} +37 -10
  26. package/dist/chunks/chunk-4GGBND7V.js.map +7 -0
  27. package/dist/chunks/{chunk-N2VKKA7O.js → chunk-4GNFBZPR.js} +2 -2
  28. package/dist/chunks/{chunk-M5IN6DMF.js → chunk-56RFFBBO.js} +6 -6
  29. package/dist/chunks/{chunk-J2HUD36Z.js → chunk-5X35KXBV.js} +14 -2
  30. package/dist/chunks/{chunk-J2HUD36Z.js.map → chunk-5X35KXBV.js.map} +2 -2
  31. package/dist/chunks/{chunk-DU6ZA44F.js → chunk-6EVAHJAR.js} +5 -5
  32. package/dist/chunks/{chunk-ST36EYHN.js → chunk-6QVQXGMR.js} +1 -1
  33. package/dist/chunks/chunk-6QVQXGMR.js.map +7 -0
  34. package/dist/chunks/chunk-7C5IEIQK.js +157 -0
  35. package/dist/chunks/chunk-7C5IEIQK.js.map +7 -0
  36. package/dist/chunks/{chunk-C7EEG6SM.js → chunk-A5XF3ZPJ.js} +19 -2
  37. package/dist/chunks/chunk-A5XF3ZPJ.js.map +7 -0
  38. package/dist/chunks/{chunk-CZPQTISQ.js → chunk-BQWJ5ZR7.js} +10 -6
  39. package/dist/chunks/chunk-BQWJ5ZR7.js.map +7 -0
  40. package/dist/chunks/{chunk-ABJCSNZO.js → chunk-D3IONBBJ.js} +2 -2
  41. package/dist/chunks/{chunk-7JU7Z4XQ.js → chunk-D3W6CBJZ.js} +2 -2
  42. package/dist/chunks/{chunk-3SHUUBZJ.js → chunk-DONS3EZH.js} +3 -3
  43. package/dist/chunks/{chunk-W5CHVJBR.js → chunk-EQYQICUY.js} +54 -8
  44. package/dist/chunks/chunk-EQYQICUY.js.map +7 -0
  45. package/dist/chunks/{chunk-FB24AOIJ.js → chunk-H3SGA7G7.js} +5 -5
  46. package/dist/chunks/{chunk-ZXKYU6CH.js → chunk-HCNHKJDA.js} +2 -2
  47. package/dist/chunks/{chunk-UXEMIWYI.js → chunk-HITKWKYD.js} +11 -9
  48. package/dist/chunks/chunk-HITKWKYD.js.map +7 -0
  49. package/dist/chunks/{chunk-YYSZBD7S.js → chunk-HQ5YW2OJ.js} +2 -2
  50. package/dist/chunks/{chunk-GC2AUXG6.js → chunk-HZGQ7XYM.js} +2 -2
  51. package/dist/chunks/{chunk-WREA4RNR.js → chunk-I2TK65VR.js} +3 -3
  52. package/dist/chunks/chunk-IQXNJNDI.js +854 -0
  53. package/dist/chunks/chunk-IQXNJNDI.js.map +7 -0
  54. package/dist/chunks/{chunk-DZ4WN5XJ.js → chunk-JV4JR6TT.js} +3 -3
  55. package/dist/chunks/{chunk-3GJJG2FV.js → chunk-KBYSGB7E.js} +2 -2
  56. package/dist/chunks/chunk-KBYSGB7E.js.map +7 -0
  57. package/dist/chunks/{chunk-PF27MQY5.js → chunk-MOJBW5X2.js} +42 -3
  58. package/dist/chunks/chunk-MOJBW5X2.js.map +7 -0
  59. package/dist/chunks/{chunk-YJX27XBO.js → chunk-O7IREHJI.js} +104 -46
  60. package/dist/chunks/chunk-O7IREHJI.js.map +7 -0
  61. package/dist/chunks/{chunk-FRPNQZV2.js → chunk-ODYU3IJU.js} +81 -18
  62. package/dist/chunks/chunk-ODYU3IJU.js.map +7 -0
  63. package/dist/chunks/{chunk-LOLCTWJF.js → chunk-OTHMEDN6.js} +4 -4
  64. package/dist/chunks/{chunk-PXAICAUT.js → chunk-PBDDXBHY.js} +2 -1
  65. package/dist/chunks/chunk-PBDDXBHY.js.map +7 -0
  66. package/dist/chunks/{chunk-M6IRQ3QT.js → chunk-PH4PT6R4.js} +2 -2
  67. package/dist/chunks/{chunk-B54Z662X.js → chunk-PTZ5DKAB.js} +25 -5
  68. package/dist/chunks/chunk-PTZ5DKAB.js.map +7 -0
  69. package/dist/chunks/{chunk-RUO6L7RM.js → chunk-Q2JQ3RYZ.js} +3 -1
  70. package/dist/chunks/chunk-Q2JQ3RYZ.js.map +7 -0
  71. package/dist/chunks/{chunk-WYUV6WL3.js → chunk-QCCPR3U5.js} +4 -4
  72. package/dist/chunks/{chunk-GYPDGW27.js → chunk-QGP7AY2R.js} +4 -2
  73. package/dist/chunks/{chunk-GYPDGW27.js.map → chunk-QGP7AY2R.js.map} +2 -2
  74. package/dist/chunks/{chunk-7XRUMDV7.js → chunk-QQ7D6UAM.js} +2 -2
  75. package/dist/chunks/chunk-QRN433TI.js +19 -0
  76. package/dist/chunks/chunk-QRN433TI.js.map +7 -0
  77. package/dist/chunks/{chunk-PYQM7KPL.js → chunk-R2MMPHR2.js} +2 -2
  78. package/dist/chunks/{chunk-CXTTLBUV.js → chunk-R2XQ6AHT.js} +2 -2
  79. package/dist/chunks/{chunk-DV2JZSCI.js → chunk-SPCJXN4K.js} +14 -4
  80. package/dist/chunks/{chunk-DV2JZSCI.js.map → chunk-SPCJXN4K.js.map} +2 -2
  81. package/dist/chunks/{chunk-T5CU2GPZ.js → chunk-TNPZBMYC.js} +34 -10
  82. package/dist/chunks/chunk-TNPZBMYC.js.map +7 -0
  83. package/dist/chunks/{chunk-5SU3YXBS.js → chunk-UGYCAG6O.js} +1 -1
  84. package/dist/chunks/{chunk-5SU3YXBS.js.map → chunk-UGYCAG6O.js.map} +1 -1
  85. package/dist/chunks/{chunk-X3CHSIL2.js → chunk-V2IV4LYW.js} +3 -3
  86. package/dist/chunks/{chunk-QY7YK7M6.js → chunk-VR2LV4CA.js} +2 -2
  87. package/dist/chunks/chunk-WJJXODAB.js +82 -0
  88. package/dist/chunks/chunk-WJJXODAB.js.map +7 -0
  89. package/dist/chunks/{chunk-S3IRPDSO.js → chunk-WQ6LC2KK.js} +2 -2
  90. package/dist/chunks/{chunk-CYMDX3XP.js → chunk-WTLH5RY4.js} +2 -2
  91. package/dist/chunks/chunk-WTLH5RY4.js.map +7 -0
  92. package/dist/chunks/{chunk-BVJBYFHD.js → chunk-ZPI4QTOX.js} +2 -2
  93. package/dist/chunks/{chunk-3DUKKQHN.js → chunk-ZQMBS5SH.js} +5 -5
  94. package/dist/cli/decisions.js +1 -1
  95. package/dist/cli/mesh.js +2 -2
  96. package/dist/commands/fabric.d.ts +1 -1
  97. package/dist/commands/fabric.d.ts.map +1 -1
  98. package/dist/compaction/hook.d.ts +1 -1
  99. package/dist/compaction/hook.d.ts.map +1 -1
  100. package/dist/compaction/hook.js +6 -6
  101. package/dist/compaction/owner.js +7 -7
  102. package/dist/components/configuration.js +4 -4
  103. package/dist/config.d.ts +2 -0
  104. package/dist/config.d.ts.map +1 -1
  105. package/dist/core/action-registry.d.ts.map +1 -1
  106. package/dist/core/action-registry.js +7 -7
  107. package/dist/core/action-result.d.ts +10 -0
  108. package/dist/core/action-result.d.ts.map +1 -1
  109. package/dist/core/agent-dir.d.ts +1 -0
  110. package/dist/core/agent-dir.d.ts.map +1 -1
  111. package/dist/core/fabric-state-paths.d.ts.map +1 -1
  112. package/dist/core/host-sdk-runtime.d.ts +8 -0
  113. package/dist/core/host-sdk-runtime.d.ts.map +1 -0
  114. package/dist/core/host-sdk.d.ts +28 -0
  115. package/dist/core/host-sdk.d.ts.map +1 -0
  116. package/dist/core/host-sdk.js +11 -0
  117. package/dist/core/host-sdk.js.map +7 -0
  118. package/dist/core/provider-operations.js +1 -1
  119. package/dist/core/provider-operations.js.map +2 -2
  120. package/dist/core/session-context.d.ts +5 -0
  121. package/dist/core/session-context.d.ts.map +1 -1
  122. package/dist/core/shell-inbox.d.ts.map +1 -1
  123. package/dist/core/shell-jobs.d.ts +2 -0
  124. package/dist/core/shell-jobs.d.ts.map +1 -1
  125. package/dist/core/tool-ownership.d.ts.map +1 -1
  126. package/dist/core/tool-result-proxy.d.ts +2 -0
  127. package/dist/core/tool-result-proxy.d.ts.map +1 -1
  128. package/dist/durable/agent.d.ts +6 -0
  129. package/dist/durable/agent.d.ts.map +1 -1
  130. package/dist/durable/worker-host.d.ts.map +1 -1
  131. package/dist/durable/worker-host.js +48 -10
  132. package/dist/durable/worker-host.js.map +2 -2
  133. package/dist/durable.js +2 -2
  134. package/dist/durable.js.map +1 -1
  135. package/dist/entropy/index.js +8 -8
  136. package/dist/extension-bootstrap.js +17 -17
  137. package/dist/fabric-runtime-state.d.ts +2 -0
  138. package/dist/fabric-runtime-state.d.ts.map +1 -1
  139. package/dist/fabric-runtime-state.js +362 -101
  140. package/dist/fabric-runtime-state.js.map +4 -4
  141. package/dist/fabric-state.d.ts +2 -0
  142. package/dist/fabric-state.d.ts.map +1 -1
  143. package/dist/index.js +23 -21
  144. package/dist/index.js.map +1 -1
  145. package/dist/jev/auth.d.ts +2 -0
  146. package/dist/jev/auth.d.ts.map +1 -1
  147. package/dist/jev/client.d.ts.map +1 -1
  148. package/dist/jev/client.js +3 -3
  149. package/dist/jev/config.d.ts +5 -0
  150. package/dist/jev/config.d.ts.map +1 -1
  151. package/dist/jev/decision-profiles.d.ts +8 -0
  152. package/dist/jev/decision-profiles.d.ts.map +1 -0
  153. package/dist/jev/decision-schema.d.ts +35 -0
  154. package/dist/jev/decision-schema.d.ts.map +1 -0
  155. package/dist/jev/decision-types.d.ts +139 -0
  156. package/dist/jev/decision-types.d.ts.map +1 -0
  157. package/dist/jev/decisions.d.ts +27 -0
  158. package/dist/jev/decisions.d.ts.map +1 -0
  159. package/dist/jev/guest-types.d.ts +1 -1
  160. package/dist/jev/guest-types.d.ts.map +1 -1
  161. package/dist/jev/manager.d.ts +7 -0
  162. package/dist/jev/manager.d.ts.map +1 -1
  163. package/dist/jev/model-key.d.ts +3 -2
  164. package/dist/jev/model-key.d.ts.map +1 -1
  165. package/dist/jev/observation.js +7 -7
  166. package/dist/jev/routes.d.ts +11 -1
  167. package/dist/jev/routes.d.ts.map +1 -1
  168. package/dist/jev/types.d.ts +3 -2
  169. package/dist/jev/types.d.ts.map +1 -1
  170. package/dist/jev/validation.d.ts +34 -0
  171. package/dist/jev/validation.d.ts.map +1 -1
  172. package/dist/jev-fabric/resolve.d.ts +4 -0
  173. package/dist/jev-fabric/resolve.d.ts.map +1 -1
  174. package/dist/jev-fabric/resolve.js +1 -0
  175. package/dist/jev-fabric/resolve.js.map +2 -2
  176. package/dist/jev-fabric/serve.d.ts +5 -15
  177. package/dist/jev-fabric/serve.d.ts.map +1 -1
  178. package/dist/jev-fabric/serve.js +87 -56
  179. package/dist/jev-fabric/serve.js.map +2 -2
  180. package/dist/jev.d.ts +6 -2
  181. package/dist/jev.d.ts.map +1 -1
  182. package/dist/jev.js +37 -15
  183. package/dist/memory/digest.js +2 -2
  184. package/dist/memory/discovery.js +6 -6
  185. package/dist/memory/extractive-history.d.ts +3 -0
  186. package/dist/memory/extractive-history.d.ts.map +1 -1
  187. package/dist/memory/extractive-history.js +36 -7
  188. package/dist/memory/extractive-history.js.map +3 -3
  189. package/dist/memory/extractive-index.d.ts.map +1 -1
  190. package/dist/memory/file-worker.js +9 -9
  191. package/dist/memory/normalize.js +5 -5
  192. package/dist/memory/search.js +7 -7
  193. package/dist/memory/worker-provider.js +10 -10
  194. package/dist/memory.js +10 -10
  195. package/dist/native-codemode.d.ts.map +1 -1
  196. package/dist/protocol.d.ts +3 -0
  197. package/dist/protocol.d.ts.map +1 -1
  198. package/dist/protocol.js +3 -1
  199. package/dist/providers/agents-provider.d.ts.map +1 -1
  200. package/dist/providers/captured-tools-provider.d.ts.map +1 -1
  201. package/dist/providers/jev-provider.d.ts +2 -0
  202. package/dist/providers/jev-provider.d.ts.map +1 -1
  203. package/dist/providers/jev-provider.js +12 -12
  204. package/dist/providers/memory-provider.js +9 -9
  205. package/dist/providers/pi-bash-cwd.d.ts +1 -1
  206. package/dist/providers/pi-bash-cwd.d.ts.map +1 -1
  207. package/dist/providers/pi-tools-provider.d.ts.map +1 -1
  208. package/dist/providers/write-preview.d.ts +1 -1
  209. package/dist/providers/write-preview.d.ts.map +1 -1
  210. package/dist/residency/host.js +16 -14
  211. package/dist/residency/pi-entry.js +16 -14
  212. package/dist/residency/pi-entry.js.map +1 -1
  213. package/dist/runners.js +1 -1
  214. package/dist/runtime/core-override-guest-types.js +2 -2
  215. package/dist/runtime/guest-types.d.ts +1 -1
  216. package/dist/runtime/guest-types.d.ts.map +1 -1
  217. package/dist/runtime/guest-types.js +1 -1
  218. package/dist/runtime/monty-runtime.js +3 -3
  219. package/dist/runtime/native-codemode-types.d.ts +1 -1
  220. package/dist/runtime/native-codemode-types.d.ts.map +1 -1
  221. package/dist/runtime/node-process-runtime.js +3 -3
  222. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  223. package/dist/runtime/quickjs-runtime.js +2 -2
  224. package/dist/runtime/typescript-kernel.js +5 -5
  225. package/dist/storage/retention.d.ts.map +1 -1
  226. package/dist/topology/peer-presence.d.ts +56 -0
  227. package/dist/topology/peer-presence.d.ts.map +1 -0
  228. package/dist/type-error-guidance.js +1 -1
  229. package/dist/ui/controller.d.ts.map +1 -1
  230. package/dist/ui/conversation-chrome.js +2 -2
  231. package/dist/ui/conversation-host.js +1 -1
  232. package/dist/ui/conversation-native-reader.js +1 -1
  233. package/dist/ui/conversation.js +6 -6
  234. package/dist/ui/dashboard.js +3 -3
  235. package/dist/ui/settings-decision-profiles.d.ts +24 -0
  236. package/dist/ui/settings-decision-profiles.d.ts.map +1 -0
  237. package/dist/ui/settings-section-context.d.ts +1 -1
  238. package/dist/ui/settings-section-context.d.ts.map +1 -1
  239. package/dist/ui/settings-sections-agents.d.ts.map +1 -1
  240. package/dist/ui/settings-sections-decisions.d.ts +4 -0
  241. package/dist/ui/settings-sections-decisions.d.ts.map +1 -0
  242. package/dist/ui/settings-sections-lifecycle.d.ts.map +1 -1
  243. package/dist/ui/settings-sections.d.ts +1 -1
  244. package/dist/ui/settings-sections.d.ts.map +1 -1
  245. package/dist/ui/settings-submenus.d.ts +3 -1
  246. package/dist/ui/settings-submenus.d.ts.map +1 -1
  247. package/dist/ui/settings-values.d.ts.map +1 -1
  248. package/dist/ui/settings.d.ts.map +1 -1
  249. package/dist/ui/settings.js +224 -45
  250. package/dist/ui/settings.js.map +4 -4
  251. package/dist/verified/generated/authority-kernel.js +2 -2
  252. package/dist/verified/generated/kernel.js +2 -2
  253. package/dist/verified/generated/lifecycle-kernel.js +2 -2
  254. package/dist/verified/generated/manifest.json +7 -7
  255. package/dist/verified/generated/provider-kernel.js +2 -2
  256. package/dist/verified/generated/storage-kernel.js +2 -2
  257. package/dist/worker/options.d.ts.map +1 -1
  258. package/dist/worker/options.js +15 -0
  259. package/dist/worker/options.js.map +2 -2
  260. package/dist/worker.js +11 -1
  261. package/dist/worker.js.map +2 -2
  262. package/docs/agents.md +49 -0
  263. package/docs/architecture.md +1 -1
  264. package/docs/audit-trace.md +3 -1
  265. package/docs/background-tasks.md +4 -0
  266. package/docs/codemode-parity.md +3 -1
  267. package/docs/compaction.md +1 -1
  268. package/docs/configuration.md +91 -8
  269. package/docs/decision-profiles.schema.json +52 -0
  270. package/docs/decision-test-coverage.md +77 -0
  271. package/docs/durable-pi.md +9 -2
  272. package/docs/extractive-history.md +17 -2
  273. package/docs/jev-decisions.md +150 -0
  274. package/docs/jev.md +18 -5
  275. package/docs/prompt-cache.md +1 -1
  276. package/docs/provider-capabilities.md +1 -1
  277. package/docs/providers.md +4 -1
  278. package/docs/verified-kernels.md +1 -1
  279. package/node_modules/pi-coralbricks-provider/LICENSE +21 -0
  280. package/node_modules/pi-coralbricks-provider/README.md +306 -0
  281. package/node_modules/pi-coralbricks-provider/auth.ts +30 -0
  282. package/node_modules/pi-coralbricks-provider/custom-models.json +1 -0
  283. package/node_modules/pi-coralbricks-provider/deprecated-models.json +1 -0
  284. package/node_modules/pi-coralbricks-provider/guard.ts +155 -0
  285. package/node_modules/pi-coralbricks-provider/index.ts +662 -0
  286. package/node_modules/pi-coralbricks-provider/models.json +88 -0
  287. package/node_modules/pi-coralbricks-provider/package.json +74 -0
  288. package/node_modules/pi-coralbricks-provider/park.ts +122 -0
  289. package/node_modules/pi-coralbricks-provider/patch.json +34 -0
  290. package/node_modules/pi-coralbricks-provider/scripts/update-models.js +658 -0
  291. package/node_modules/pi-coralbricks-provider/settings.ts +143 -0
  292. package/node_modules/pi-coralbricks-provider/sync-policy.ts +309 -0
  293. package/package.json +23 -15
  294. package/scripts/test-verified-kernels.mjs +1 -1
  295. package/scripts/verified-kernels.mjs +1 -1
  296. package/skillsets/python/fabric-exec/SKILL.md +1 -1
  297. package/skillsets/python/fabric-exec/references/agents.md +1 -1
  298. package/skillsets/python/fabric-foreman/SKILL.md +1 -1
  299. package/skillsets/python/fabric-jev/SKILL.md +2 -2
  300. package/skillsets/typescript/fabric-exec/SKILL.md +1 -1
  301. package/skillsets/typescript/fabric-exec/references/agents.md +1 -0
  302. package/skillsets/typescript/fabric-foreman/SKILL.md +1 -1
  303. package/skillsets/typescript/fabric-jev/SKILL.md +2 -2
  304. package/dist/chunks/chunk-3GJJG2FV.js.map +0 -7
  305. package/dist/chunks/chunk-B54Z662X.js.map +0 -7
  306. package/dist/chunks/chunk-C7EEG6SM.js.map +0 -7
  307. package/dist/chunks/chunk-CYMDX3XP.js.map +0 -7
  308. package/dist/chunks/chunk-CZPQTISQ.js.map +0 -7
  309. package/dist/chunks/chunk-FRPNQZV2.js.map +0 -7
  310. package/dist/chunks/chunk-IAFI4A2I.js +0 -92
  311. package/dist/chunks/chunk-IAFI4A2I.js.map +0 -7
  312. package/dist/chunks/chunk-LEDY5G2V.js +0 -515
  313. package/dist/chunks/chunk-LEDY5G2V.js.map +0 -7
  314. package/dist/chunks/chunk-PF27MQY5.js.map +0 -7
  315. package/dist/chunks/chunk-PXAICAUT.js.map +0 -7
  316. package/dist/chunks/chunk-RUO6L7RM.js.map +0 -7
  317. package/dist/chunks/chunk-ST36EYHN.js.map +0 -7
  318. package/dist/chunks/chunk-T5CU2GPZ.js.map +0 -7
  319. package/dist/chunks/chunk-UXEMIWYI.js.map +0 -7
  320. package/dist/chunks/chunk-W5CHVJBR.js.map +0 -7
  321. package/dist/chunks/chunk-WHBJDTCR.js.map +0 -7
  322. package/dist/chunks/chunk-YJX27XBO.js.map +0 -7
  323. /package/dist/chunks/{chunk-X2TRSE7D.js.map → chunk-2YG4ZA2K.js.map} +0 -0
  324. /package/dist/chunks/{chunk-N2VKKA7O.js.map → chunk-4GNFBZPR.js.map} +0 -0
  325. /package/dist/chunks/{chunk-M5IN6DMF.js.map → chunk-56RFFBBO.js.map} +0 -0
  326. /package/dist/chunks/{chunk-DU6ZA44F.js.map → chunk-6EVAHJAR.js.map} +0 -0
  327. /package/dist/chunks/{chunk-ABJCSNZO.js.map → chunk-D3IONBBJ.js.map} +0 -0
  328. /package/dist/chunks/{chunk-7JU7Z4XQ.js.map → chunk-D3W6CBJZ.js.map} +0 -0
  329. /package/dist/chunks/{chunk-3SHUUBZJ.js.map → chunk-DONS3EZH.js.map} +0 -0
  330. /package/dist/chunks/{chunk-FB24AOIJ.js.map → chunk-H3SGA7G7.js.map} +0 -0
  331. /package/dist/chunks/{chunk-ZXKYU6CH.js.map → chunk-HCNHKJDA.js.map} +0 -0
  332. /package/dist/chunks/{chunk-YYSZBD7S.js.map → chunk-HQ5YW2OJ.js.map} +0 -0
  333. /package/dist/chunks/{chunk-GC2AUXG6.js.map → chunk-HZGQ7XYM.js.map} +0 -0
  334. /package/dist/chunks/{chunk-WREA4RNR.js.map → chunk-I2TK65VR.js.map} +0 -0
  335. /package/dist/chunks/{chunk-DZ4WN5XJ.js.map → chunk-JV4JR6TT.js.map} +0 -0
  336. /package/dist/chunks/{chunk-LOLCTWJF.js.map → chunk-OTHMEDN6.js.map} +0 -0
  337. /package/dist/chunks/{chunk-M6IRQ3QT.js.map → chunk-PH4PT6R4.js.map} +0 -0
  338. /package/dist/chunks/{chunk-WYUV6WL3.js.map → chunk-QCCPR3U5.js.map} +0 -0
  339. /package/dist/chunks/{chunk-7XRUMDV7.js.map → chunk-QQ7D6UAM.js.map} +0 -0
  340. /package/dist/chunks/{chunk-PYQM7KPL.js.map → chunk-R2MMPHR2.js.map} +0 -0
  341. /package/dist/chunks/{chunk-CXTTLBUV.js.map → chunk-R2XQ6AHT.js.map} +0 -0
  342. /package/dist/chunks/{chunk-X3CHSIL2.js.map → chunk-V2IV4LYW.js.map} +0 -0
  343. /package/dist/chunks/{chunk-QY7YK7M6.js.map → chunk-VR2LV4CA.js.map} +0 -0
  344. /package/dist/chunks/{chunk-S3IRPDSO.js.map → chunk-WQ6LC2KK.js.map} +0 -0
  345. /package/dist/chunks/{chunk-BVJBYFHD.js.map → chunk-ZPI4QTOX.js.map} +0 -0
  346. /package/dist/chunks/{chunk-3DUKKQHN.js.map → chunk-ZQMBS5SH.js.map} +0 -0
@@ -0,0 +1,658 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Update CoralBricks models from API
4
+ *
5
+ * Fetches models and updates:
6
+ * - models.json: Provider model definitions (enriched with pricing & compat)
7
+ * - README.md: Model table in the Available Models section
8
+ *
9
+ * Sources, in order:
10
+ * 1. Authenticated https://inference.coralbricks.ai/v1/models — the authoritative
11
+ * per-key enabled set, with per-million USD pricing (input_per_m / output_per_m /
12
+ * cached_input_per_m — cached reads are $0), context_length, supports_image_input.
13
+ * 2. Unauthenticated public catalog https://www.coralbricks.ai/api/public/models —
14
+ * same control-plane data without a key (contextWindow like "1M", inputPerM,
15
+ * outputPerM). Used when no key is configured or /v1/models fails.
16
+ *
17
+ * The catalog is a subset: it lists each model's canonical slug, not every
18
+ * variant enabled for a key, so a catalog run only ever adds or keeps models —
19
+ * it never delists one (see keepUnlistedModels).
20
+ *
21
+ * models.json is the source of truth for curated specs — the script preserves
22
+ * existing data and only adds new models with API-derived defaults.
23
+ * Curate models.json manually after new model discovery.
24
+ *
25
+ * patch.json and custom-models.json are applied at runtime by the provider.
26
+ * They are NOT baked into models.json, but ARE used to generate the README table.
27
+ *
28
+ * API key: the stored `coralbricks` credential in ~/.pi/agent/auth.json wins, then
29
+ * the CORALBRICKS_API_KEY environment variable (localterm:
30
+ * `localterm secret set coralbricks_api_key`).
31
+ */
32
+
33
+ import fs from 'fs';
34
+ import os from 'os';
35
+ import { execSync } from 'child_process';
36
+ import path from 'path';
37
+ import { fileURLToPath } from 'url';
38
+
39
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
40
+
41
+ // pi's agent directory: PI_CODING_AGENT_DIR (with ~ expansion) or ~/.pi/agent.
42
+ function piAgentDir() {
43
+ const envDir = process.env.PI_CODING_AGENT_DIR;
44
+ if (envDir) {
45
+ return envDir.startsWith('~/') || envDir === '~'
46
+ ? path.join(os.homedir(), envDir.slice(1))
47
+ : envDir;
48
+ }
49
+ return path.join(os.homedir(), '.pi', 'agent');
50
+ }
51
+
52
+ const AUTH_JSON_PATH = path.join(piAgentDir(), 'auth.json');
53
+
54
+ /**
55
+ * Resolve a configured value using pi's semantics (resolve-config-value.ts in
56
+ * pi-mono): "!command" runs via the shell (10s timeout) and uses trimmed
57
+ * stdout; "$VAR" / "${VAR}" interpolate environment variables ("$$" escapes a
58
+ * literal "$", "$!" a literal "!"); anything else is a literal. Returns
59
+ * undefined when a referenced env var is unset or a command fails.
60
+ */
61
+ function resolveConfigValue(config, env) {
62
+ if (typeof config !== 'string' || config.length === 0) return undefined;
63
+ if (config.startsWith('!')) {
64
+ try {
65
+ const out = execSync(config.slice(1), {
66
+ encoding: 'utf8',
67
+ timeout: 10000,
68
+ stdio: ['ignore', 'pipe', 'ignore'],
69
+ });
70
+ return out.trim() || undefined;
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ }
75
+ const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
76
+ let resolved = '';
77
+ let index = 0;
78
+ while (index < config.length) {
79
+ const dollar = config.indexOf('$', index);
80
+ if (dollar < 0) {
81
+ resolved += config.slice(index);
82
+ break;
83
+ }
84
+ resolved += config.slice(index, dollar);
85
+ const next = config[dollar + 1];
86
+ let name;
87
+ if (next === '$' || next === '!') {
88
+ resolved += next;
89
+ index = dollar + 2;
90
+ continue;
91
+ } else if (next === '{') {
92
+ const end = config.indexOf('}', dollar + 2);
93
+ if (end < 0) {
94
+ resolved += '$';
95
+ index = dollar + 1;
96
+ continue;
97
+ }
98
+ const inner = config.slice(dollar + 2, end);
99
+ if (!ENV_NAME_RE.test(inner)) {
100
+ resolved += config.slice(dollar, end + 1);
101
+ index = end + 1;
102
+ continue;
103
+ }
104
+ name = inner;
105
+ index = end + 1;
106
+ } else {
107
+ const match = config.slice(dollar + 1).match(/^[A-Za-z_][A-Za-z0-9_]*/);
108
+ if (!match) {
109
+ resolved += '$';
110
+ index = dollar + 1;
111
+ continue;
112
+ }
113
+ name = match[0];
114
+ index = dollar + 1 + name.length;
115
+ }
116
+ const value = (env && env[name]) || process.env[name] || undefined;
117
+ if (value === undefined) return undefined;
118
+ resolved += value;
119
+ }
120
+ return resolved;
121
+ }
122
+
123
+ /**
124
+ * The API key, resolved the way pi itself resolves it for this provider: the
125
+ * stored `coralbricks` credential in ~/.pi/agent/auth.json wins, then
126
+ * the CORALBRICKS_API_KEY environment variable.
127
+ */
128
+ function resolveApiKey() {
129
+ try {
130
+ const auth = JSON.parse(fs.readFileSync(AUTH_JSON_PATH, 'utf8'));
131
+ const credential = auth?.coralbricks;
132
+ if (credential && credential.type === 'api_key' && typeof credential.key === 'string') {
133
+ const key = resolveConfigValue(credential.key, credential.env);
134
+ if (key) return key;
135
+ }
136
+ } catch {
137
+ // Missing or unparseable auth.json: fall through to the env var.
138
+ }
139
+ return process.env.CORALBRICKS_API_KEY || undefined;
140
+ }
141
+
142
+ const MODELS_API_URL = 'https://inference.coralbricks.ai/v1/models';
143
+ const CHAT_COMPLETIONS_URL = 'https://inference.coralbricks.ai/v1/chat/completions';
144
+ const PUBLIC_CATALOG_URL = 'https://www.coralbricks.ai/api/public/models';
145
+ const MODELS_JSON_PATH = path.join(__dirname, '..', 'models.json');
146
+ const PATCH_JSON_PATH = path.join(__dirname, '..', 'patch.json');
147
+ const CUSTOM_MODELS_JSON_PATH = path.join(__dirname, '..', 'custom-models.json');
148
+ const README_PATH = path.join(__dirname, '..', 'README.md');
149
+
150
+ // Output-token fallbacks for models whose API rows do not report a limit.
151
+ const DEFAULT_MAX_TOKENS = {}; // per-id output-token fallbacks; empty while every served model reports one
152
+ const FALLBACK_MAX_TOKENS = 32768;
153
+
154
+ // Helpers
155
+
156
+ function loadJson(filePath) {
157
+ try {
158
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
159
+ } catch {
160
+ return {};
161
+ }
162
+ }
163
+
164
+ function saveJson(filePath, data) {
165
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n');
166
+ console.log(`✓ Saved ${path.basename(filePath)}`);
167
+ }
168
+
169
+ // Coral states the cache write ON TOP of input (2026-10-08); pi's cacheWrite is the full
170
+ // price of a written token, input + it. 0 when the row has no cache-write rate.
171
+ function writtenTokenCost(input, cacheWriteOnTop) {
172
+ if (typeof cacheWriteOnTop !== 'number' || !Number.isFinite(cacheWriteOnTop)) return 0;
173
+ return Math.round((input + cacheWriteOnTop) * 1e6) / 1e6;
174
+ }
175
+
176
+ function toNumber(value) {
177
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
178
+ }
179
+
180
+ function generateDisplayName(id) {
181
+ return id
182
+ .split(/[-_/]/)
183
+ .filter(Boolean)
184
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
185
+ .join(' ');
186
+ }
187
+
188
+ /** Parse "1M" / "128K" / "1048576" / 1048576 into a token count. */
189
+ function parseContextWindow(value, fallback = 131072) {
190
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;
191
+ if (typeof value === 'string') {
192
+ const match = value.trim().match(/^([\d.]+)\s*([KkMm])$/);
193
+ if (match) {
194
+ const n = parseFloat(match[1]);
195
+ if (Number.isFinite(n) && n > 0) {
196
+ return Math.round(n * (match[2].toUpperCase() === 'M' ? 1024 * 1024 : 1024));
197
+ }
198
+ }
199
+ const n = parseInt(value, 10);
200
+ if (Number.isFinite(n) && n > 0) return n;
201
+ }
202
+ return fallback;
203
+ }
204
+
205
+ // API fetch
206
+
207
+ async function fetchV1Models(apiKey) {
208
+ console.log(`Fetching models from ${MODELS_API_URL}...`);
209
+ const response = await fetch(MODELS_API_URL, {
210
+ headers: { Authorization: `Bearer ${apiKey}` },
211
+ });
212
+ if (!response.ok) {
213
+ throw new Error(`API error: ${response.status} ${response.statusText}`);
214
+ }
215
+ const data = await response.json();
216
+ const models = data.data || [];
217
+ console.log(`✓ Fetched ${models.length} models from API`);
218
+ return models;
219
+ }
220
+
221
+ async function fetchPublicCatalog() {
222
+ console.log(`Fetching public catalog from ${PUBLIC_CATALOG_URL}...`);
223
+ const response = await fetch(PUBLIC_CATALOG_URL);
224
+ if (!response.ok) {
225
+ throw new Error(`API error: ${response.status} ${response.statusText}`);
226
+ }
227
+ const data = await response.json();
228
+ const models = data.models || [];
229
+ console.log(`✓ Fetched ${models.length} models from public catalog`);
230
+ return models;
231
+ }
232
+
233
+ async function fetchModels(apiKey) {
234
+ if (apiKey) {
235
+ try {
236
+ return { models: await fetchV1Models(apiKey), authoritative: true };
237
+ } catch (error) {
238
+ console.warn(`⚠ /v1/models failed (${error.message}); falling back to public catalog`);
239
+ }
240
+ } else {
241
+ console.warn('⚠ No API key found (no `coralbricks` credential in ' + AUTH_JSON_PATH + ', CORALBRICKS_API_KEY unset); using the public catalog');
242
+ }
243
+ return { models: await fetchPublicCatalog(), authoritative: false };
244
+ }
245
+
246
+ /**
247
+ * The public catalog is a subset of the per-key /v1/models set: it advertises a
248
+ * model's canonical slug, not every variant enabled for the key (the -fp4 twins
249
+ * are listed by /v1/models only). It can vouch for what exists, never for what
250
+ * is gone, so a non-authoritative fetch keeps every already-known model it does
251
+ * not list: a keyless run may discover models, it may not delist them. Returns
252
+ * the ids it kept, in the order they were appended.
253
+ */
254
+ function keepUnlistedModels(models, existingModelsMap, authoritative) {
255
+ if (authoritative) return [];
256
+ const seen = new Set(models.map((m) => m.id));
257
+ const kept = [];
258
+ for (const [id, existing] of Object.entries(existingModelsMap)) {
259
+ if (!seen.has(id)) {
260
+ models.push(existing);
261
+ kept.push(id);
262
+ }
263
+ }
264
+ return kept;
265
+ }
266
+
267
+ // Transform API model → models.json entry
268
+
269
+ function transformApiModel(apiModel, existingModelsMap) {
270
+ const id = apiModel.id;
271
+ const pricing = apiModel.pricing || {};
272
+ const input = apiModel.supports_image_input ? ['text', 'image'] : ['text'];
273
+ const contextWindow = parseContextWindow(apiModel.context_length);
274
+ const maxTokens = DEFAULT_MAX_TOKENS[id] ?? FALLBACK_MAX_TOKENS;
275
+
276
+ // Preserve existing curated data (pricing, reasoning, compat, etc.)
277
+ if (existingModelsMap[id]) {
278
+ const existing = { ...existingModelsMap[id] };
279
+ if (contextWindow) existing.contextWindow = contextWindow;
280
+ if (apiModel.max_output_tokens) existing.maxTokens = apiModel.max_output_tokens;
281
+ if (typeof pricing.input_per_m === 'number') existing.cost.input = pricing.input_per_m;
282
+ if (typeof pricing.output_per_m === 'number') existing.cost.output = pricing.output_per_m;
283
+ existing.cost.cacheRead = toNumber(pricing.cached_input_per_m);
284
+ if (typeof pricing.cache_write_per_m === 'number') {
285
+ existing.cost.cacheWrite = writtenTokenCost(existing.cost.input, pricing.cache_write_per_m);
286
+ }
287
+ existing.input = input;
288
+ return existing;
289
+ }
290
+
291
+ // New model — build from API data + sensible defaults
292
+ return {
293
+ id,
294
+ name: apiModel.name || generateDisplayName(id),
295
+ reasoning: false,
296
+ input,
297
+ cost: {
298
+ input: toNumber(pricing.input_per_m),
299
+ output: toNumber(pricing.output_per_m),
300
+ cacheRead: toNumber(pricing.cached_input_per_m),
301
+ cacheWrite: writtenTokenCost(toNumber(pricing.input_per_m), pricing.cache_write_per_m),
302
+ },
303
+ contextWindow,
304
+ maxTokens,
305
+ compat: {
306
+ supportsDeveloperRole: false,
307
+ supportsStore: false,
308
+ maxTokensField: 'max_tokens',
309
+ },
310
+ };
311
+ }
312
+
313
+ function transformCatalogModel(entry, existingModelsMap) {
314
+ const id = entry.slug;
315
+ const contextWindow = parseContextWindow(entry.contextWindow);
316
+ const maxTokens = DEFAULT_MAX_TOKENS[id] ?? FALLBACK_MAX_TOKENS;
317
+
318
+ if (existingModelsMap[id]) {
319
+ const existing = { ...existingModelsMap[id] };
320
+ if (contextWindow) existing.contextWindow = contextWindow;
321
+ if (typeof entry.inputPerM === 'number') existing.cost.input = entry.inputPerM;
322
+ if (typeof entry.outputPerM === 'number') existing.cost.output = entry.outputPerM;
323
+ if (typeof entry.cacheWritePerM === 'number') {
324
+ existing.cost.cacheWrite = writtenTokenCost(existing.cost.input, entry.cacheWritePerM);
325
+ }
326
+ return existing;
327
+ }
328
+
329
+ return {
330
+ id,
331
+ name: entry.name || generateDisplayName(id),
332
+ reasoning: false,
333
+ input: ['text'],
334
+ cost: {
335
+ input: toNumber(entry.inputPerM),
336
+ output: toNumber(entry.outputPerM),
337
+ cacheRead: 0,
338
+ cacheWrite: writtenTokenCost(toNumber(entry.inputPerM), entry.cacheWritePerM),
339
+ },
340
+ contextWindow,
341
+ maxTokens,
342
+ compat: {
343
+ supportsDeveloperRole: false,
344
+ supportsStore: false,
345
+ maxTokensField: 'max_tokens',
346
+ },
347
+ };
348
+ }
349
+
350
+ // Patch Application (mirrors index.ts)
351
+
352
+ function applyPatch(model, patch) {
353
+ // Deep-copy nested objects: the delete branches below must not mutate the
354
+ // caller's (embedded or cached) source data through shared references.
355
+ const result = {
356
+ ...model,
357
+ cost: { ...model.cost },
358
+ compat: model.compat ? { ...model.compat } : undefined,
359
+ thinkingLevelMap: model.thinkingLevelMap ? { ...model.thinkingLevelMap } : undefined,
360
+ };
361
+ if (patch.name !== undefined) result.name = patch.name;
362
+ if (patch.hidden !== undefined) result.hidden = patch.hidden;
363
+ if (patch.reasoning !== undefined) result.reasoning = patch.reasoning;
364
+ if (patch.input !== undefined) result.input = patch.input;
365
+ if (patch.contextWindow !== undefined) result.contextWindow = patch.contextWindow;
366
+ if (patch.maxTokens !== undefined) result.maxTokens = patch.maxTokens;
367
+ if (patch.thinkingLevelMap !== undefined) result.thinkingLevelMap = patch.thinkingLevelMap;
368
+ if (patch.cost) {
369
+ result.cost = {
370
+ input: patch.cost.input ?? result.cost.input,
371
+ output: patch.cost.output ?? result.cost.output,
372
+ cacheRead: patch.cost.cacheRead ?? result.cost.cacheRead,
373
+ cacheWrite: patch.cost.cacheWrite ?? result.cost.cacheWrite,
374
+ };
375
+ }
376
+ if (patch.compat) {
377
+ result.compat = { ...(result.compat || {}), ...patch.compat };
378
+ }
379
+ if (!result.reasoning && result.compat?.thinkingFormat) {
380
+ delete result.compat.thinkingFormat;
381
+ }
382
+ if (!result.reasoning && result.thinkingLevelMap) {
383
+ delete result.thinkingLevelMap;
384
+ }
385
+ if (result.compat && Object.keys(result.compat).length === 0) {
386
+ delete result.compat;
387
+ }
388
+ return result;
389
+ }
390
+
391
+ /** Full pipeline: base models → patch → custom → result */
392
+ function buildModels(baseModels, customModels, patchData) {
393
+ const modelMap = new Map();
394
+ for (const model of baseModels) {
395
+ modelMap.set(model.id, model);
396
+ }
397
+ for (const [id, patchEntry] of Object.entries(patchData)) {
398
+ const existing = modelMap.get(id);
399
+ if (existing) {
400
+ modelMap.set(id, applyPatch(existing, patchEntry));
401
+ }
402
+ }
403
+ for (const model of customModels) {
404
+ const existing = modelMap.get(model.id);
405
+ const patchEntry = patchData[model.id];
406
+ if (existing && patchEntry) {
407
+ modelMap.set(model.id, applyPatch(model, patchEntry));
408
+ } else if (existing) {
409
+ modelMap.set(model.id, model);
410
+ } else if (patchEntry) {
411
+ modelMap.set(model.id, applyPatch(model, patchEntry));
412
+ } else {
413
+ modelMap.set(model.id, model);
414
+ }
415
+ }
416
+ // Mirrors index.ts buildModels: hidden models are served by Coral but kept out
417
+ // of the catalog the provider offers, so the README table skips them too.
418
+ return Array.from(modelMap.values())
419
+ .filter((m) => !m.hidden)
420
+ .map(({ hidden: _hidden, ...model }) => model);
421
+ }
422
+
423
+ // README generation
424
+
425
+ function formatContext(n) {
426
+ if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
427
+ if (n >= 1000) return `${Math.round(n / 1000)}K`;
428
+ return n.toString();
429
+ }
430
+
431
+ function formatCost(cost) {
432
+ if (cost === 0 || cost === null || cost === undefined) return '—';
433
+ return `$${cost.toFixed(2)}`;
434
+ }
435
+
436
+ function generateReadmeTable(models) {
437
+ const lines = [
438
+ '| Model | Context | Vision | Reasoning | Input $/M | Cache Read $/M | Cache Write $/M | Output $/M |',
439
+ '|-------|---------|--------|-----------|-----------|-----------------|------------------|------------|',
440
+ ];
441
+
442
+ for (const model of models) {
443
+ const context = formatContext(model.contextWindow);
444
+ const vision = model.input.includes('image') ? '✅' : '❌';
445
+ const reasoning = model.reasoning ? '✅' : '❌';
446
+ const inputCost = formatCost(model.cost.input);
447
+ const cacheReadCost = formatCost(model.cost.cacheRead);
448
+ const cacheWriteCost = formatCost(model.cost.cacheWrite);
449
+ const outputCost = formatCost(model.cost.output);
450
+
451
+ lines.push(`| ${model.name} | ${context} | ${vision} | ${reasoning} | ${inputCost} | ${cacheReadCost} | ${cacheWriteCost} | ${outputCost} |`);
452
+ }
453
+
454
+ return lines.join('\n');
455
+ }
456
+
457
+ function updateReadme(models) {
458
+ let readme = fs.readFileSync(README_PATH, 'utf8');
459
+ const newTable = generateReadmeTable(models);
460
+
461
+ const tableRegex = /(## Available Models\n\n)\| Model \|[^\n]+\|\n\|[-| ]+\|(\n\|[^\n]+\|)*\n*/;
462
+
463
+ if (tableRegex.test(readme)) {
464
+ readme = readme.replace(tableRegex, (match, header) => `${header}${newTable}\n\n`);
465
+ fs.writeFileSync(README_PATH, readme);
466
+ console.log('✓ Updated README.md');
467
+ } else {
468
+ console.warn('⚠ Could not find model table in "## Available Models" section');
469
+ }
470
+ }
471
+
472
+ // Grace period for delisted models: update-models.js moves models the API no
473
+ // longer lists into deprecated-models.json (stamped with deprecatedAt) instead
474
+ // of dropping them; the runtime appends them back so sessions and saved model
475
+ // settings keep working, and after 14 days they are evicted permanently.
476
+ //
477
+ // The grace period exists for a model that is still ANSWERING while it leaves
478
+ // the catalog. A retired one is not: Coral answers 404 with
479
+ // `error.code == "model_retired"`, so keeping it registered only offers the
480
+ // user a model that cannot reply, and /model still lists it for two weeks.
481
+ // Each delisted model is probed once, and a retired one is dropped instead of
482
+ // parked. Anything else — an unknown id, a key without access, a network
483
+ // blip — keeps the grace period, because only `model_retired` is a statement
484
+ // that the model is gone for everybody rather than missing for this key.
485
+ const DEPRECATED_MODEL_TTL_MS = 14 * 24 * 60 * 60 * 1000;
486
+ const RETIRED_PROBE_TIMEOUT_MS = 10000;
487
+
488
+ /**
489
+ * Ask the gateway whether a model is retired. Returns true ONLY on an explicit
490
+ * 404 `model_retired`; every other outcome returns false, so a probe that
491
+ * cannot answer never shortens a grace period.
492
+ */
493
+ async function isRetiredUpstream(id, apiKey) {
494
+ if (!apiKey) return false;
495
+ try {
496
+ const response = await fetch(CHAT_COMPLETIONS_URL, {
497
+ method: 'POST',
498
+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
499
+ body: JSON.stringify({ model: id, max_tokens: 1, messages: [{ role: 'user', content: 'ping' }] }),
500
+ signal: AbortSignal.timeout(RETIRED_PROBE_TIMEOUT_MS),
501
+ });
502
+ if (response.status !== 404) return false;
503
+ const body = await response.json();
504
+ return body?.error?.code === 'model_retired';
505
+ } catch {
506
+ return false; // offline, timeout, unparseable body: keep the grace period
507
+ }
508
+ }
509
+
510
+ async function updateDeprecatedModels(modelsJsonPath, newModels, apiKey) {
511
+ const deprecatedPath = path.join(path.dirname(modelsJsonPath), 'deprecated-models.json');
512
+
513
+ let oldModels = [];
514
+ try {
515
+ const parsed = JSON.parse(fs.readFileSync(modelsJsonPath, 'utf8'));
516
+ if (Array.isArray(parsed)) oldModels = parsed;
517
+ } catch { /* first run: no previous models.json */ }
518
+
519
+ let deprecated = {};
520
+ try {
521
+ const parsed = JSON.parse(fs.readFileSync(deprecatedPath, 'utf8'));
522
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) deprecated = parsed;
523
+ } catch { /* no graveyard yet */ }
524
+
525
+ const currentIds = new Set(newModels.map((m) => m.id));
526
+ const now = new Date().toISOString();
527
+ const added = [];
528
+ const resurrected = [];
529
+ const evicted = [];
530
+ const retired = [];
531
+
532
+ const candidates = oldModels.filter((old) => old && old.id && !currentIds.has(old.id) && !deprecated[old.id]);
533
+ // Probe the delisted models plus anything already parked: a model can retire
534
+ // during its own grace period, which is exactly when it starts 404ing.
535
+ const parked = Object.keys(deprecated).filter((id) => !currentIds.has(id));
536
+ const toProbe = [...new Set([...candidates.map((m) => m.id), ...parked])];
537
+ const retiredIds = new Set(
538
+ (await Promise.all(toProbe.map(async (id) => ((await isRetiredUpstream(id, apiKey)) ? id : null))))
539
+ .filter((id) => id !== null)
540
+ );
541
+
542
+ for (const old of candidates) {
543
+ if (retiredIds.has(old.id)) {
544
+ retired.push(old.id);
545
+ continue; // retired upstream: 404s, so a grace period buys nothing
546
+ }
547
+ deprecated[old.id] = { ...old, deprecatedAt: now };
548
+ added.push(old.id);
549
+ }
550
+
551
+ for (const [id, entry] of Object.entries(deprecated)) {
552
+ if (currentIds.has(id)) {
553
+ delete deprecated[id];
554
+ resurrected.push(id);
555
+ continue;
556
+ }
557
+ if (retiredIds.has(id)) {
558
+ delete deprecated[id];
559
+ retired.push(id);
560
+ continue;
561
+ }
562
+ const removedAt = Date.parse(entry && entry.deprecatedAt ? entry.deprecatedAt : '');
563
+ if (Number.isNaN(removedAt) || Date.now() - removedAt > DEPRECATED_MODEL_TTL_MS) {
564
+ delete deprecated[id];
565
+ evicted.push(id);
566
+ }
567
+ }
568
+
569
+ if (added.length > 0 || resurrected.length > 0 || evicted.length > 0 || retired.length > 0) {
570
+ fs.writeFileSync(deprecatedPath, JSON.stringify(deprecated, null, 2) + '\n');
571
+ console.log('Updated deprecated-models.json ' + JSON.stringify({ added, resurrected, evicted, retired }));
572
+ }
573
+ }
574
+
575
+ async function main() {
576
+ try {
577
+ // Regenerate the derived README table from local source data without an API
578
+ // key. This is useful for offline workflows while curating custom models.
579
+ if (process.argv.includes('--readme-only')) {
580
+ const baseModels = loadJson(MODELS_JSON_PATH);
581
+ const patchData = loadJson(PATCH_JSON_PATH);
582
+ const customModels = loadJson(CUSTOM_MODELS_JSON_PATH);
583
+ const readmeBase = Array.isArray(baseModels) ? baseModels : [];
584
+ const readmeModels = buildModels(readmeBase, Array.isArray(customModels) ? customModels : [], patchData);
585
+ readmeModels.sort((a, b) => a.name.localeCompare(b.name));
586
+ updateReadme(readmeModels);
587
+ console.log('✓ Regenerated README.md from local model data');
588
+ return;
589
+ }
590
+
591
+ const apiKey = resolveApiKey();
592
+ const { models: apiModels, authoritative } = await fetchModels(apiKey);
593
+
594
+ // Load existing models.json — source of truth for curated specs
595
+ const existingModels = loadJson(MODELS_JSON_PATH);
596
+ const existingModelsMap = {};
597
+ for (const m of (Array.isArray(existingModels) ? existingModels : [])) {
598
+ existingModelsMap[m.id] = m;
599
+ }
600
+
601
+ // Transform API models, preserving existing data where available
602
+ const isCatalogShape = apiModels.length > 0 && apiModels.every((m) => m && m.slug && m.id === undefined);
603
+ let models = apiModels.map((m) =>
604
+ isCatalogShape ? transformCatalogModel(m, existingModelsMap) : transformApiModel(m, existingModelsMap)
605
+ );
606
+
607
+ // Live API is authoritative — models absent from it are removed (embedded
608
+ // data is already used for enrichment in transformApiModel). A catalog run
609
+ // is not: keep every known model it does not list.
610
+ const kept = keepUnlistedModels(models, existingModelsMap, authoritative);
611
+ if (kept.length > 0) {
612
+ console.warn(`⚠ Public catalog listed ${kept.length} fewer model(s) than models.json; kept: ${kept.join(', ')}`);
613
+ }
614
+
615
+ // Sort by model name
616
+ models.sort((a, b) => a.name.localeCompare(b.name));
617
+
618
+ // Save models.json (pure API output, no patch/custom baked in)
619
+ // Move delisted models to deprecated-models.json BEFORE models.json is overwritten
620
+ await updateDeprecatedModels(MODELS_JSON_PATH, models, apiKey);
621
+ saveJson(MODELS_JSON_PATH, models);
622
+
623
+ // Build the README model list: base → patch → custom. Grace-period models stay
624
+ // servable at runtime (index.ts appends them) but are not listed as available.
625
+ const patchData = loadJson(PATCH_JSON_PATH);
626
+ const customModels = loadJson(CUSTOM_MODELS_JSON_PATH);
627
+ const readmeBase = models;
628
+ const readmeModels = buildModels(readmeBase, Array.isArray(customModels) ? customModels : [], patchData);
629
+ readmeModels.sort((a, b) => a.name.localeCompare(b.name));
630
+
631
+ // Update README
632
+ updateReadme(readmeModels);
633
+
634
+ // Summary
635
+ const newIds = new Set(models.map((m) => m.id));
636
+ const oldIds = new Set(Object.keys(existingModelsMap));
637
+ const added = [...newIds].filter((id) => !oldIds.has(id));
638
+ const removed = [...oldIds].filter((id) => !newIds.has(id));
639
+
640
+ console.log('\n--- Summary ---');
641
+ console.log(`Total models: ${models.length}`);
642
+ console.log(`Reasoning models: ${models.filter((m) => m.reasoning).length}`);
643
+ console.log(`Vision models: ${models.filter((m) => m.input.includes('image')).length}`);
644
+ if (added.length > 0) console.log(`New models: ${added.join(', ')} — curate models.json manually`);
645
+ if (removed.length > 0) console.log(`Removed models: ${removed.join(', ')}`);
646
+ } catch (error) {
647
+ console.error('Error:', error.message);
648
+ process.exit(1);
649
+ }
650
+ }
651
+
652
+ // Run only when invoked as a script, so the deprecation logic below can be
653
+ // imported by tests without kicking off a sync.
654
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))) {
655
+ main();
656
+ }
657
+
658
+ export { isRetiredUpstream, keepUnlistedModels, updateDeprecatedModels };