apex-code 0.0.1-alpha.0 → 0.0.1-alpha.2

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 (426) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +66 -681
  3. package/dist/cli/args.d.ts +5 -0
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +45 -6
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/cli/auth-command.d.ts.map +1 -1
  8. package/dist/cli/auth-command.js +3 -3
  9. package/dist/cli/auth-command.js.map +1 -1
  10. package/dist/cli/cost-command.d.ts +19 -0
  11. package/dist/cli/cost-command.d.ts.map +1 -0
  12. package/dist/cli/cost-command.js +107 -0
  13. package/dist/cli/cost-command.js.map +1 -0
  14. package/dist/cli/startup-ui.d.ts +1 -1
  15. package/dist/cli/startup-ui.d.ts.map +1 -1
  16. package/dist/cli/startup-ui.js +1 -2
  17. package/dist/cli/startup-ui.js.map +1 -1
  18. package/dist/cli.d.ts.map +1 -1
  19. package/dist/cli.js +45 -16
  20. package/dist/cli.js.map +1 -1
  21. package/dist/config.d.ts +2 -2
  22. package/dist/config.d.ts.map +1 -1
  23. package/dist/config.js +14 -7
  24. package/dist/config.js.map +1 -1
  25. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  26. package/dist/core/agent-session-runtime.js +2 -0
  27. package/dist/core/agent-session-runtime.js.map +1 -1
  28. package/dist/core/agent-session-services.d.ts +9 -0
  29. package/dist/core/agent-session-services.d.ts.map +1 -1
  30. package/dist/core/agent-session-services.js +30 -4
  31. package/dist/core/agent-session-services.js.map +1 -1
  32. package/dist/core/agent-session.d.ts +46 -0
  33. package/dist/core/agent-session.d.ts.map +1 -1
  34. package/dist/core/agent-session.js +137 -19
  35. package/dist/core/agent-session.js.map +1 -1
  36. package/dist/core/auth-storage.d.ts.map +1 -1
  37. package/dist/core/auth-storage.js +6 -6
  38. package/dist/core/auth-storage.js.map +1 -1
  39. package/dist/core/bash-executor.d.ts.map +1 -1
  40. package/dist/core/bash-executor.js +1 -1
  41. package/dist/core/bash-executor.js.map +1 -1
  42. package/dist/core/context/deferred-schemas.d.ts +92 -0
  43. package/dist/core/context/deferred-schemas.d.ts.map +1 -0
  44. package/dist/core/context/deferred-schemas.js +74 -0
  45. package/dist/core/context/deferred-schemas.js.map +1 -0
  46. package/dist/core/context/eviction.d.ts +47 -0
  47. package/dist/core/context/eviction.d.ts.map +1 -0
  48. package/dist/core/context/eviction.js +83 -0
  49. package/dist/core/context/eviction.js.map +1 -0
  50. package/dist/core/context/pipeline.d.ts +90 -0
  51. package/dist/core/context/pipeline.d.ts.map +1 -0
  52. package/dist/core/context/pipeline.js +109 -0
  53. package/dist/core/context/pipeline.js.map +1 -0
  54. package/dist/core/credential-failover.d.ts +30 -0
  55. package/dist/core/credential-failover.d.ts.map +1 -0
  56. package/dist/core/credential-failover.js +46 -0
  57. package/dist/core/credential-failover.js.map +1 -0
  58. package/dist/core/credential-pool.d.ts +60 -0
  59. package/dist/core/credential-pool.d.ts.map +1 -0
  60. package/dist/core/credential-pool.js +84 -0
  61. package/dist/core/credential-pool.js.map +1 -0
  62. package/dist/core/delegation/agents.d.ts +15 -0
  63. package/dist/core/delegation/agents.d.ts.map +1 -0
  64. package/dist/core/delegation/agents.js +55 -0
  65. package/dist/core/delegation/agents.js.map +1 -0
  66. package/dist/core/delegation/ceiling.d.ts +29 -0
  67. package/dist/core/delegation/ceiling.d.ts.map +1 -0
  68. package/dist/core/delegation/ceiling.js +34 -0
  69. package/dist/core/delegation/ceiling.js.map +1 -0
  70. package/dist/core/delegation/runtime.d.ts +94 -0
  71. package/dist/core/delegation/runtime.d.ts.map +1 -0
  72. package/dist/core/delegation/runtime.js +117 -0
  73. package/dist/core/delegation/runtime.js.map +1 -0
  74. package/dist/core/durable-state/daemon.d.ts +37 -0
  75. package/dist/core/durable-state/daemon.d.ts.map +1 -0
  76. package/dist/core/durable-state/daemon.js +62 -0
  77. package/dist/core/durable-state/daemon.js.map +1 -0
  78. package/dist/core/durable-state/provenance.d.ts +7 -0
  79. package/dist/core/durable-state/provenance.d.ts.map +1 -0
  80. package/dist/core/durable-state/provenance.js +24 -0
  81. package/dist/core/durable-state/provenance.js.map +1 -0
  82. package/dist/core/durable-state/sqlite.d.ts +84 -0
  83. package/dist/core/durable-state/sqlite.d.ts.map +1 -0
  84. package/dist/core/durable-state/sqlite.js +331 -0
  85. package/dist/core/durable-state/sqlite.js.map +1 -0
  86. package/dist/core/environment.d.ts +12 -0
  87. package/dist/core/environment.d.ts.map +1 -0
  88. package/dist/core/environment.js +69 -0
  89. package/dist/core/environment.js.map +1 -0
  90. package/dist/core/evidence-policy.d.ts +17 -0
  91. package/dist/core/evidence-policy.d.ts.map +1 -0
  92. package/dist/core/evidence-policy.js +25 -0
  93. package/dist/core/evidence-policy.js.map +1 -0
  94. package/dist/core/evidence.d.ts +16 -0
  95. package/dist/core/evidence.d.ts.map +1 -0
  96. package/dist/core/evidence.js +51 -0
  97. package/dist/core/evidence.js.map +1 -0
  98. package/dist/core/experimental.d.ts.map +1 -1
  99. package/dist/core/experimental.js +2 -1
  100. package/dist/core/experimental.js.map +1 -1
  101. package/dist/core/extensions/types.d.ts +2 -0
  102. package/dist/core/extensions/types.d.ts.map +1 -1
  103. package/dist/core/extensions/types.js.map +1 -1
  104. package/dist/core/index.d.ts +1 -0
  105. package/dist/core/index.d.ts.map +1 -1
  106. package/dist/core/index.js +1 -0
  107. package/dist/core/index.js.map +1 -1
  108. package/dist/core/model-config.d.ts +8 -0
  109. package/dist/core/model-config.d.ts.map +1 -1
  110. package/dist/core/model-config.js +21 -5
  111. package/dist/core/model-config.js.map +1 -1
  112. package/dist/core/model-resolver.d.ts +20 -0
  113. package/dist/core/model-resolver.d.ts.map +1 -1
  114. package/dist/core/model-resolver.js +59 -0
  115. package/dist/core/model-resolver.js.map +1 -1
  116. package/dist/core/model-runtime.d.ts +73 -0
  117. package/dist/core/model-runtime.d.ts.map +1 -1
  118. package/dist/core/model-runtime.js +225 -8
  119. package/dist/core/model-runtime.js.map +1 -1
  120. package/dist/core/observability/aggregate.d.ts +21 -0
  121. package/dist/core/observability/aggregate.d.ts.map +1 -0
  122. package/dist/core/observability/aggregate.js +36 -0
  123. package/dist/core/observability/aggregate.js.map +1 -0
  124. package/dist/core/observability/otlp.d.ts +66 -0
  125. package/dist/core/observability/otlp.d.ts.map +1 -0
  126. package/dist/core/observability/otlp.js +95 -0
  127. package/dist/core/observability/otlp.js.map +1 -0
  128. package/dist/core/package-manager.d.ts.map +1 -1
  129. package/dist/core/package-manager.js +3 -2
  130. package/dist/core/package-manager.js.map +1 -1
  131. package/dist/core/permissions/gate.d.ts +35 -0
  132. package/dist/core/permissions/gate.d.ts.map +1 -0
  133. package/dist/core/permissions/gate.js +72 -0
  134. package/dist/core/permissions/gate.js.map +1 -0
  135. package/dist/core/permissions/modes.d.ts +18 -0
  136. package/dist/core/permissions/modes.d.ts.map +1 -0
  137. package/dist/core/permissions/modes.js +57 -0
  138. package/dist/core/permissions/modes.js.map +1 -0
  139. package/dist/core/permissions/responder.d.ts +30 -0
  140. package/dist/core/permissions/responder.d.ts.map +1 -0
  141. package/dist/core/permissions/responder.js +32 -0
  142. package/dist/core/permissions/responder.js.map +1 -0
  143. package/dist/core/permissions/rules.d.ts +34 -0
  144. package/dist/core/permissions/rules.d.ts.map +1 -0
  145. package/dist/core/permissions/rules.js +74 -0
  146. package/dist/core/permissions/rules.js.map +1 -0
  147. package/dist/core/permissions/startup.d.ts +33 -0
  148. package/dist/core/permissions/startup.d.ts.map +1 -0
  149. package/dist/core/permissions/startup.js +55 -0
  150. package/dist/core/permissions/startup.js.map +1 -0
  151. package/dist/core/permissions/store.d.ts +114 -0
  152. package/dist/core/permissions/store.d.ts.map +1 -0
  153. package/dist/core/permissions/store.js +229 -0
  154. package/dist/core/permissions/store.js.map +1 -0
  155. package/dist/core/project-trust.d.ts.map +1 -1
  156. package/dist/core/project-trust.js +1 -1
  157. package/dist/core/project-trust.js.map +1 -1
  158. package/dist/core/provider-attribution.d.ts.map +1 -1
  159. package/dist/core/provider-attribution.js +6 -7
  160. package/dist/core/provider-attribution.js.map +1 -1
  161. package/dist/core/remote-catalog-provider.d.ts +2 -2
  162. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  163. package/dist/core/remote-catalog-provider.js +20 -16
  164. package/dist/core/remote-catalog-provider.js.map +1 -1
  165. package/dist/core/sandbox/child-entry.d.ts +2 -0
  166. package/dist/core/sandbox/child-entry.d.ts.map +1 -0
  167. package/dist/core/sandbox/child-entry.js +11 -0
  168. package/dist/core/sandbox/child-entry.js.map +1 -0
  169. package/dist/core/sandbox/cli-launch.d.ts +27 -0
  170. package/dist/core/sandbox/cli-launch.d.ts.map +1 -0
  171. package/dist/core/sandbox/cli-launch.js +133 -0
  172. package/dist/core/sandbox/cli-launch.js.map +1 -0
  173. package/dist/core/sandbox/cli-supervisor.d.ts +25 -0
  174. package/dist/core/sandbox/cli-supervisor.d.ts.map +1 -0
  175. package/dist/core/sandbox/cli-supervisor.js +57 -0
  176. package/dist/core/sandbox/cli-supervisor.js.map +1 -0
  177. package/dist/core/sandbox/linux-backend.d.ts +18 -0
  178. package/dist/core/sandbox/linux-backend.d.ts.map +1 -0
  179. package/dist/core/sandbox/linux-backend.js +186 -0
  180. package/dist/core/sandbox/linux-backend.js.map +1 -0
  181. package/dist/core/sandbox/macos-backend.d.ts +18 -0
  182. package/dist/core/sandbox/macos-backend.d.ts.map +1 -0
  183. package/dist/core/sandbox/macos-backend.js +195 -0
  184. package/dist/core/sandbox/macos-backend.js.map +1 -0
  185. package/dist/core/sandbox/network-proxy.d.ts +19 -0
  186. package/dist/core/sandbox/network-proxy.d.ts.map +1 -0
  187. package/dist/core/sandbox/network-proxy.js +79 -0
  188. package/dist/core/sandbox/network-proxy.js.map +1 -0
  189. package/dist/core/sandbox/policy.d.ts +32 -0
  190. package/dist/core/sandbox/policy.d.ts.map +1 -0
  191. package/dist/core/sandbox/policy.js +38 -0
  192. package/dist/core/sandbox/policy.js.map +1 -0
  193. package/dist/core/sandbox/supervisor.d.ts +31 -0
  194. package/dist/core/sandbox/supervisor.d.ts.map +1 -0
  195. package/dist/core/sandbox/supervisor.js +18 -0
  196. package/dist/core/sandbox/supervisor.js.map +1 -0
  197. package/dist/core/sandbox/violations.d.ts +23 -0
  198. package/dist/core/sandbox/violations.d.ts.map +1 -0
  199. package/dist/core/sandbox/violations.js +30 -0
  200. package/dist/core/sandbox/violations.js.map +1 -0
  201. package/dist/core/sdk.d.ts +20 -36
  202. package/dist/core/sdk.d.ts.map +1 -1
  203. package/dist/core/sdk.js +129 -2
  204. package/dist/core/sdk.js.map +1 -1
  205. package/dist/core/session-manager.d.ts +41 -2
  206. package/dist/core/session-manager.d.ts.map +1 -1
  207. package/dist/core/session-manager.js +57 -0
  208. package/dist/core/session-manager.js.map +1 -1
  209. package/dist/core/session-share.d.ts +16 -0
  210. package/dist/core/session-share.d.ts.map +1 -0
  211. package/dist/core/session-share.js +22 -0
  212. package/dist/core/session-share.js.map +1 -0
  213. package/dist/core/settings-manager.d.ts +38 -9
  214. package/dist/core/settings-manager.d.ts.map +1 -1
  215. package/dist/core/settings-manager.js +39 -24
  216. package/dist/core/settings-manager.js.map +1 -1
  217. package/dist/core/system-prompt.d.ts.map +1 -1
  218. package/dist/core/system-prompt.js +5 -5
  219. package/dist/core/system-prompt.js.map +1 -1
  220. package/dist/core/timings.d.ts +1 -1
  221. package/dist/core/timings.d.ts.map +1 -1
  222. package/dist/core/timings.js +3 -2
  223. package/dist/core/timings.js.map +1 -1
  224. package/dist/core/tools/ask-user.d.ts +25 -0
  225. package/dist/core/tools/ask-user.d.ts.map +1 -0
  226. package/dist/core/tools/ask-user.js +49 -0
  227. package/dist/core/tools/ask-user.js.map +1 -0
  228. package/dist/core/tools/bash-command-segments.d.ts +22 -0
  229. package/dist/core/tools/bash-command-segments.d.ts.map +1 -0
  230. package/dist/core/tools/bash-command-segments.js +128 -0
  231. package/dist/core/tools/bash-command-segments.js.map +1 -0
  232. package/dist/core/tools/bash.d.ts +26 -3
  233. package/dist/core/tools/bash.d.ts.map +1 -1
  234. package/dist/core/tools/bash.js +105 -16
  235. package/dist/core/tools/bash.js.map +1 -1
  236. package/dist/core/tools/contract.d.ts +156 -0
  237. package/dist/core/tools/contract.d.ts.map +1 -0
  238. package/dist/core/tools/contract.js +48 -0
  239. package/dist/core/tools/contract.js.map +1 -0
  240. package/dist/core/tools/delegate.d.ts +38 -0
  241. package/dist/core/tools/delegate.d.ts.map +1 -0
  242. package/dist/core/tools/delegate.js +66 -0
  243. package/dist/core/tools/delegate.js.map +1 -0
  244. package/dist/core/tools/edit.d.ts +2 -2
  245. package/dist/core/tools/edit.d.ts.map +1 -1
  246. package/dist/core/tools/edit.js +24 -0
  247. package/dist/core/tools/edit.js.map +1 -1
  248. package/dist/core/tools/find.d.ts +2 -2
  249. package/dist/core/tools/find.d.ts.map +1 -1
  250. package/dist/core/tools/find.js +12 -0
  251. package/dist/core/tools/find.js.map +1 -1
  252. package/dist/core/tools/grep.d.ts +2 -2
  253. package/dist/core/tools/grep.d.ts.map +1 -1
  254. package/dist/core/tools/grep.js +12 -0
  255. package/dist/core/tools/grep.js.map +1 -1
  256. package/dist/core/tools/index.d.ts +29 -4
  257. package/dist/core/tools/index.d.ts.map +1 -1
  258. package/dist/core/tools/index.js +118 -2
  259. package/dist/core/tools/index.js.map +1 -1
  260. package/dist/core/tools/ls.d.ts +2 -2
  261. package/dist/core/tools/ls.d.ts.map +1 -1
  262. package/dist/core/tools/ls.js +12 -0
  263. package/dist/core/tools/ls.js.map +1 -1
  264. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  265. package/dist/core/tools/output-accumulator.js +1 -1
  266. package/dist/core/tools/output-accumulator.js.map +1 -1
  267. package/dist/core/tools/path-permission.d.ts +18 -0
  268. package/dist/core/tools/path-permission.d.ts.map +1 -0
  269. package/dist/core/tools/path-permission.js +28 -0
  270. package/dist/core/tools/path-permission.js.map +1 -0
  271. package/dist/core/tools/plan-present.d.ts +27 -0
  272. package/dist/core/tools/plan-present.d.ts.map +1 -0
  273. package/dist/core/tools/plan-present.js +55 -0
  274. package/dist/core/tools/plan-present.js.map +1 -0
  275. package/dist/core/tools/read.d.ts +2 -2
  276. package/dist/core/tools/read.d.ts.map +1 -1
  277. package/dist/core/tools/read.js +12 -0
  278. package/dist/core/tools/read.js.map +1 -1
  279. package/dist/core/tools/test.d.ts +34 -0
  280. package/dist/core/tools/test.d.ts.map +1 -0
  281. package/dist/core/tools/test.js +75 -0
  282. package/dist/core/tools/test.js.map +1 -0
  283. package/dist/core/tools/todo-write.d.ts +31 -0
  284. package/dist/core/tools/todo-write.d.ts.map +1 -0
  285. package/dist/core/tools/todo-write.js +51 -0
  286. package/dist/core/tools/todo-write.js.map +1 -0
  287. package/dist/core/tools/tool-definition-wrapper.d.ts +13 -2
  288. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  289. package/dist/core/tools/tool-definition-wrapper.js +11 -1
  290. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  291. package/dist/core/tools/tool-schema.d.ts +22 -0
  292. package/dist/core/tools/tool-schema.d.ts.map +1 -0
  293. package/dist/core/tools/tool-schema.js +45 -0
  294. package/dist/core/tools/tool-schema.js.map +1 -0
  295. package/dist/core/tools/web-fetch.d.ts +26 -0
  296. package/dist/core/tools/web-fetch.d.ts.map +1 -0
  297. package/dist/core/tools/web-fetch.js +62 -0
  298. package/dist/core/tools/web-fetch.js.map +1 -0
  299. package/dist/core/tools/web-search.d.ts +26 -0
  300. package/dist/core/tools/web-search.d.ts.map +1 -0
  301. package/dist/core/tools/web-search.js +53 -0
  302. package/dist/core/tools/web-search.js.map +1 -0
  303. package/dist/core/tools/write.d.ts +6 -2
  304. package/dist/core/tools/write.d.ts.map +1 -1
  305. package/dist/core/tools/write.js +32 -1
  306. package/dist/core/tools/write.js.map +1 -1
  307. package/dist/core/usage-performance-store.d.ts +56 -0
  308. package/dist/core/usage-performance-store.d.ts.map +1 -0
  309. package/dist/core/usage-performance-store.js +85 -0
  310. package/dist/core/usage-performance-store.js.map +1 -0
  311. package/dist/index.d.ts +1 -0
  312. package/dist/index.d.ts.map +1 -1
  313. package/dist/index.js +1 -0
  314. package/dist/index.js.map +1 -1
  315. package/dist/main.d.ts.map +1 -1
  316. package/dist/main.js +48 -6
  317. package/dist/main.js.map +1 -1
  318. package/dist/migrations.d.ts.map +1 -1
  319. package/dist/migrations.js +2 -2
  320. package/dist/migrations.js.map +1 -1
  321. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  322. package/dist/modes/interactive/components/config-selector.js +9 -6
  323. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  324. package/dist/modes/interactive/components/first-time-setup.d.ts +1 -4
  325. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  326. package/dist/modes/interactive/components/first-time-setup.js +11 -39
  327. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  328. package/dist/modes/interactive/components/footer.d.ts +8 -1
  329. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  330. package/dist/modes/interactive/components/footer.js +49 -20
  331. package/dist/modes/interactive/components/footer.js.map +1 -1
  332. package/dist/modes/interactive/components/settings-selector.d.ts +2 -2
  333. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  334. package/dist/modes/interactive/components/settings-selector.js +6 -6
  335. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  336. package/dist/modes/interactive/components/tool-execution.d.ts +2 -1
  337. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  338. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  339. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  340. package/dist/modes/interactive/external-editor.js +58 -9
  341. package/dist/modes/interactive/external-editor.js.map +1 -1
  342. package/dist/modes/interactive/interactive-mode.d.ts +2 -3
  343. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  344. package/dist/modes/interactive/interactive-mode.js +92 -104
  345. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  346. package/dist/modes/interactive/theme/theme-schema.json +2 -2
  347. package/dist/package-manager-cli.d.ts.map +1 -1
  348. package/dist/package-manager-cli.js +15 -10
  349. package/dist/package-manager-cli.js.map +1 -1
  350. package/dist/rpc-entry.d.ts.map +1 -1
  351. package/dist/rpc-entry.js +2 -1
  352. package/dist/rpc-entry.js.map +1 -1
  353. package/dist/server/create-harness.d.ts +1 -1
  354. package/dist/server/create-harness.d.ts.map +1 -1
  355. package/dist/server/create-harness.js +6 -5
  356. package/dist/server/create-harness.js.map +1 -1
  357. package/dist/testing/replay/metrics.d.ts +24 -0
  358. package/dist/testing/replay/metrics.d.ts.map +1 -0
  359. package/dist/testing/replay/metrics.js +35 -0
  360. package/dist/testing/replay/metrics.js.map +1 -0
  361. package/dist/testing/replay/recorded-provider.d.ts +10 -0
  362. package/dist/testing/replay/recorded-provider.d.ts.map +1 -0
  363. package/dist/testing/replay/recorded-provider.js +108 -0
  364. package/dist/testing/replay/recorded-provider.js.map +1 -0
  365. package/dist/testing/replay/runner.d.ts +56 -0
  366. package/dist/testing/replay/runner.d.ts.map +1 -0
  367. package/dist/testing/replay/runner.js +406 -0
  368. package/dist/testing/replay/runner.js.map +1 -0
  369. package/dist/utils/apex-code-user-agent.d.ts +2 -0
  370. package/dist/utils/apex-code-user-agent.d.ts.map +1 -0
  371. package/dist/utils/apex-code-user-agent.js +5 -0
  372. package/dist/utils/apex-code-user-agent.js.map +1 -0
  373. package/dist/utils/clipboard-image.d.ts.map +1 -1
  374. package/dist/utils/clipboard-image.js +1 -1
  375. package/dist/utils/clipboard-image.js.map +1 -1
  376. package/dist/utils/tools-manager.d.ts +32 -0
  377. package/dist/utils/tools-manager.d.ts.map +1 -1
  378. package/dist/utils/tools-manager.js +198 -100
  379. package/dist/utils/tools-manager.js.map +1 -1
  380. package/dist/utils/version-check.d.ts +5 -5
  381. package/dist/utils/version-check.d.ts.map +1 -1
  382. package/dist/utils/version-check.js +23 -14
  383. package/dist/utils/version-check.js.map +1 -1
  384. package/dist/utils/windows-self-update.d.ts.map +1 -1
  385. package/dist/utils/windows-self-update.js +1 -1
  386. package/dist/utils/windows-self-update.js.map +1 -1
  387. package/docs/compaction.md +21 -21
  388. package/docs/containerization.md +24 -21
  389. package/docs/custom-provider.md +9 -9
  390. package/docs/development.md +11 -11
  391. package/docs/environment-variables.md +36 -77
  392. package/docs/extensions.md +47 -47
  393. package/docs/index.md +12 -24
  394. package/docs/json.md +6 -6
  395. package/docs/keybindings.md +3 -3
  396. package/docs/llama-cpp.md +7 -7
  397. package/docs/models.md +11 -11
  398. package/docs/packages.md +46 -42
  399. package/docs/prompt-templates.md +3 -3
  400. package/docs/providers.md +10 -10
  401. package/docs/quickstart.md +49 -32
  402. package/docs/rpc.md +11 -11
  403. package/docs/sdk.md +4 -4
  404. package/docs/security.md +18 -18
  405. package/docs/session-format.md +9 -9
  406. package/docs/sessions.md +13 -13
  407. package/docs/settings.md +10 -14
  408. package/docs/shell-aliases.md +1 -1
  409. package/docs/skills.md +8 -8
  410. package/docs/terminal-setup.md +12 -12
  411. package/docs/termux.md +4 -4
  412. package/docs/themes.md +8 -8
  413. package/docs/tmux.md +4 -4
  414. package/docs/tui.md +3 -3
  415. package/docs/usage.md +54 -51
  416. package/docs/windows.md +1 -1
  417. package/npm-shrinkwrap.json +5 -5
  418. package/package.json +2 -3
  419. package/dist/core/telemetry.d.ts +0 -3
  420. package/dist/core/telemetry.d.ts.map +0 -1
  421. package/dist/core/telemetry.js +0 -9
  422. package/dist/core/telemetry.js.map +0 -1
  423. package/dist/utils/pi-user-agent.d.ts +0 -2
  424. package/dist/utils/pi-user-agent.d.ts.map +0 -1
  425. package/dist/utils/pi-user-agent.js +0 -5
  426. package/dist/utils/pi-user-agent.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"model-resolver.js","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"m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AAI,CAAC,aAAa,EAAE,CAAC;YACpB,aAAa,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;QACpC,CAAC;QAED,IAAI,mBAAmB,EAAE,CAAC;YACzB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,oBAAoB,aAAa,CAAC,QAAQ,IAAI,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QAC1F,CAAC;QAED,OAAO;YACN,KAAK,EAAE,aAAa;YACpB,eAAe,EAAE,2BAA2B,aAAa,IAAI,YAAY,KAAK,MAAM,YAAY,aAAa,CAAC,QAAQ,IAAI,aAAa,CAAC,EAAE,GAAG;SAC7I,CAAC;IACH,CAAC;IAED,sBAAsB;IACtB,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;AAAA,CACxD","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nimport {\n\ttype Api,\n\ttype AuthOperationOptions,\n\ttype KnownProvider,\n\ttype Model,\n\tmodelsAreEqual,\n} from \"@earendil-works/pi-ai\";\nimport type { ThinkingLevel } from \"apex-code-agent-core\";\nimport chalk from \"chalk\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\n\n/** Default model IDs for each known provider */\nexport const defaultModelPerProvider: Record<KnownProvider, string> = {\n\t\"amazon-bedrock\": \"us.anthropic.claude-opus-4-6-v1\",\n\t\"ant-ling\": \"Ring-2.6-1T\",\n\tanthropic: \"claude-opus-4-8\",\n\topenai: \"gpt-5.5\",\n\t\"azure-openai-responses\": \"gpt-5.4\",\n\t\"openai-codex\": \"gpt-5.5\",\n\tradius: \"auto\",\n\tnvidia: \"nvidia/nemotron-3-super-120b-a12b\",\n\tdeepseek: \"deepseek-v4-pro\",\n\tgoogle: \"gemini-3.1-pro-preview\",\n\t\"google-vertex\": \"gemini-3.1-pro-preview\",\n\t\"github-copilot\": \"gpt-5.4\",\n\topenrouter: \"moonshotai/kimi-k2.6\",\n\t\"vercel-ai-gateway\": \"zai/glm-5.1\",\n\txai: \"grok-4.5\",\n\tgroq: \"openai/gpt-oss-120b\",\n\tcerebras: \"zai-glm-4.7\",\n\tzai: \"glm-5.1\",\n\t\"zai-coding-cn\": \"glm-5.1\",\n\tmistral: \"devstral-medium-latest\",\n\tminimax: \"MiniMax-M2.7\",\n\t\"minimax-cn\": \"MiniMax-M2.7\",\n\tmoonshotai: \"kimi-k2.6\",\n\t\"moonshotai-cn\": \"kimi-k2.6\",\n\thuggingface: \"moonshotai/Kimi-K2.6\",\n\tfireworks: \"accounts/fireworks/models/kimi-k2p6\",\n\ttogether: \"moonshotai/Kimi-K2.6\",\n\tbaseten: \"zai-org/GLM-5.2\",\n\topencode: \"kimi-k2.6\",\n\t\"opencode-go\": \"kimi-k2.6\",\n\t\"kimi-coding\": \"kimi-for-coding\",\n\t\"cloudflare-workers-ai\": \"@cf/moonshotai/kimi-k2.6\",\n\t\"cloudflare-ai-gateway\": \"workers-ai/@cf/moonshotai/kimi-k2.6\",\n\t\"qwen-token-plan\": \"qwen3.7-max\",\n\t\"qwen-token-plan-cn\": \"qwen3.7-max\",\n\t\"qwen-token-plan-individual\": \"qwen3.8-max\",\n\txiaomi: \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-cn\": \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-ams\": \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-sgp\": \"mimo-v2.5-pro\",\n};\n\nexport interface ScopedModel {\n\tmodel: Model<Api>;\n\t/** Thinking level if explicitly specified in pattern (e.g., \"model:high\"), undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/**\n * Helper to check if a model ID looks like an alias (no date suffix)\n * Dates are typically in format: -20241022 or -20250929\n */\nfunction isAlias(id: string): boolean {\n\t// Check if ID ends with -latest\n\tif (id.endsWith(\"-latest\")) return true;\n\n\t// Check if ID ends with a date pattern (-YYYYMMDD)\n\tconst datePattern = /-\\d{8}$/;\n\treturn !datePattern.test(id);\n}\n\n/**\n * Find an exact model reference match.\n * Supports either a bare model id or a canonical provider/modelId reference.\n * When matching by bare id, ambiguous matches across providers are rejected.\n */\nexport function findExactModelReferenceMatch(\n\tmodelReference: string,\n\tavailableModels: Model<Api>[],\n): Model<Api> | undefined {\n\tconst trimmedReference = modelReference.trim();\n\tif (!trimmedReference) {\n\t\treturn undefined;\n\t}\n\n\tconst normalizedReference = trimmedReference.toLowerCase();\n\n\tconst canonicalMatches = availableModels.filter(\n\t\t(model) => `${model.provider}/${model.id}`.toLowerCase() === normalizedReference,\n\t);\n\tif (canonicalMatches.length === 1) {\n\t\treturn canonicalMatches[0];\n\t}\n\tif (canonicalMatches.length > 1) {\n\t\treturn undefined;\n\t}\n\n\tconst slashIndex = trimmedReference.indexOf(\"/\");\n\tif (slashIndex !== -1) {\n\t\tconst provider = trimmedReference.substring(0, slashIndex).trim();\n\t\tconst modelId = trimmedReference.substring(slashIndex + 1).trim();\n\t\tif (provider && modelId) {\n\t\t\tconst providerMatches = availableModels.filter(\n\t\t\t\t(model) =>\n\t\t\t\t\tmodel.provider.toLowerCase() === provider.toLowerCase() &&\n\t\t\t\t\tmodel.id.toLowerCase() === modelId.toLowerCase(),\n\t\t\t);\n\t\t\tif (providerMatches.length === 1) {\n\t\t\t\treturn providerMatches[0];\n\t\t\t}\n\t\t\tif (providerMatches.length > 1) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst idMatches = availableModels.filter((model) => model.id.toLowerCase() === normalizedReference);\n\treturn idMatches.length === 1 ? idMatches[0] : undefined;\n}\n\n/**\n * Try to match a pattern to a model from the available models list.\n * Returns the matched model or undefined if no match found.\n */\nfunction tryMatchModel(modelPattern: string, availableModels: Model<Api>[]): Model<Api> | undefined {\n\tconst exactMatch = findExactModelReferenceMatch(modelPattern, availableModels);\n\tif (exactMatch) {\n\t\treturn exactMatch;\n\t}\n\n\t// No exact match - fall back to partial matching\n\tconst matches = availableModels.filter(\n\t\t(m) =>\n\t\t\tm.id.toLowerCase().includes(modelPattern.toLowerCase()) ||\n\t\t\tm.name?.toLowerCase().includes(modelPattern.toLowerCase()),\n\t);\n\n\tif (matches.length === 0) {\n\t\treturn undefined;\n\t}\n\n\t// Separate into aliases and dated versions\n\tconst aliases = matches.filter((m) => isAlias(m.id));\n\tconst datedVersions = matches.filter((m) => !isAlias(m.id));\n\n\tif (aliases.length > 0) {\n\t\t// Prefer alias - if multiple aliases, pick the one that sorts highest\n\t\taliases.sort((a, b) => b.id.localeCompare(a.id));\n\t\treturn aliases[0];\n\t} else {\n\t\t// No alias found, pick latest dated version\n\t\tdatedVersions.sort((a, b) => b.id.localeCompare(a.id));\n\t\treturn datedVersions[0];\n\t}\n}\n\nexport interface ParsedModelResult {\n\tmodel: Model<Api> | undefined;\n\t/** Thinking level if explicitly specified in pattern, undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n}\n\nfunction buildFallbackModel(provider: string, modelId: string, availableModels: Model<Api>[]): Model<Api> | undefined {\n\tconst providerModels = availableModels.filter((m) => m.provider === provider);\n\tif (providerModels.length === 0) return undefined;\n\n\tconst defaultId = defaultModelPerProvider[provider as KnownProvider];\n\tconst baseModel = defaultId\n\t\t? (providerModels.find((m) => m.id === defaultId) ?? providerModels[0])\n\t\t: providerModels[0];\n\n\treturn {\n\t\t...baseModel,\n\t\tid: modelId,\n\t\tname: modelId,\n\t};\n}\n\n/**\n * Parse a pattern to extract model and thinking level.\n * Handles models with colons in their IDs (e.g., OpenRouter's :exacto suffix).\n *\n * Algorithm:\n * 1. Try to match full pattern as a model\n * 2. If found, return it with \"off\" thinking level\n * 3. If not found and has colons, split on last colon:\n * - If suffix is valid thinking level, use it and recurse on prefix\n * - If suffix is invalid, warn and recurse on prefix with \"off\"\n *\n * @internal Exported for testing\n */\nexport function parseModelPattern(\n\tpattern: string,\n\tavailableModels: Model<Api>[],\n\toptions?: { allowInvalidThinkingLevelFallback?: boolean },\n): ParsedModelResult {\n\t// Try exact match first\n\tconst exactMatch = tryMatchModel(pattern, availableModels);\n\tif (exactMatch) {\n\t\treturn { model: exactMatch, thinkingLevel: undefined, warning: undefined };\n\t}\n\n\t// No match - try splitting on last colon if present\n\tconst lastColonIndex = pattern.lastIndexOf(\":\");\n\tif (lastColonIndex === -1) {\n\t\t// No colons, pattern simply doesn't match any model\n\t\treturn { model: undefined, thinkingLevel: undefined, warning: undefined };\n\t}\n\n\tconst prefix = pattern.substring(0, lastColonIndex);\n\tconst suffix = pattern.substring(lastColonIndex + 1);\n\n\tif (isValidThinkingLevel(suffix)) {\n\t\t// Valid thinking level - recurse on prefix and use this level\n\t\tconst result = parseModelPattern(prefix, availableModels, options);\n\t\tif (result.model) {\n\t\t\t// Only use this thinking level if no warning from inner recursion\n\t\t\treturn {\n\t\t\t\tmodel: result.model,\n\t\t\t\tthinkingLevel: result.warning ? undefined : suffix,\n\t\t\t\twarning: result.warning,\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t} else {\n\t\t// Invalid suffix\n\t\tconst allowFallback = options?.allowInvalidThinkingLevelFallback ?? true;\n\t\tif (!allowFallback) {\n\t\t\t// In strict mode (CLI --model parsing), treat it as part of the model id and fail.\n\t\t\t// This avoids accidentally resolving to a different model.\n\t\t\treturn { model: undefined, thinkingLevel: undefined, warning: undefined };\n\t\t}\n\n\t\t// Scope mode: recurse on prefix and warn\n\t\tconst result = parseModelPattern(prefix, availableModels, options);\n\t\tif (result.model) {\n\t\t\treturn {\n\t\t\t\tmodel: result.model,\n\t\t\t\tthinkingLevel: undefined,\n\t\t\t\twarning: `Invalid thinking level \"${suffix}\" in pattern \"${pattern}\". Using default instead.`,\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Resolve model patterns to actual Model objects with optional thinking levels\n * Format: \"pattern:level\" where :level is optional\n * For each pattern, finds all matching models and picks the best version:\n * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)\n * 2. If no alias, pick the latest dated version\n *\n * Supports models with colons in their IDs (e.g., OpenRouter's model:exacto).\n * The algorithm tries to match the full pattern first, then progressively\n * strips colon-suffixes to find a match.\n */\nexport interface ModelScopeDiagnostic {\n\ttype: \"warning\";\n\tcode: \"no-match\" | \"invalid-thinking-level\";\n\tmessage: string;\n\tpattern: string;\n}\n\nexport interface ResolveModelScopeResult {\n\tscopedModels: ScopedModel[];\n\tdiagnostics: ModelScopeDiagnostic[];\n}\n\nexport function resolveModelScopeFromModels(\n\tpatterns: string[],\n\tmodels: readonly Model<Api>[],\n): ResolveModelScopeResult {\n\tconst availableModels = [...models];\n\tconst scopedModels: ScopedModel[] = [];\n\tconst diagnostics: ModelScopeDiagnostic[] = [];\n\n\tfor (const pattern of patterns) {\n\t\t// Check if pattern contains glob characters\n\t\tif (pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\")) {\n\t\t\t// Extract optional thinking level suffix (e.g., \"provider/*:high\")\n\t\t\tconst colonIdx = pattern.lastIndexOf(\":\");\n\t\t\tlet globPattern = pattern;\n\t\t\tlet thinkingLevel: ThinkingLevel | undefined;\n\n\t\t\tif (colonIdx !== -1) {\n\t\t\t\tconst suffix = pattern.substring(colonIdx + 1);\n\t\t\t\tif (isValidThinkingLevel(suffix)) {\n\t\t\t\t\tthinkingLevel = suffix;\n\t\t\t\t\tglobPattern = pattern.substring(0, colonIdx);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst exactMatch = findExactModelReferenceMatch(globPattern, availableModels);\n\t\t\tif (exactMatch) {\n\t\t\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, exactMatch))) {\n\t\t\t\t\tscopedModels.push({ model: exactMatch, thinkingLevel });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Match against \"provider/modelId\" format OR just model ID\n\t\t\t// This allows \"*sonnet*\" to match without requiring \"anthropic/*sonnet*\"\n\t\t\tconst matchingModels = availableModels.filter((m) => {\n\t\t\t\tconst fullId = `${m.provider}/${m.id}`;\n\t\t\t\treturn minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true });\n\t\t\t});\n\n\t\t\tif (matchingModels.length === 0) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"no-match\",\n\t\t\t\t\tmessage: `No models match pattern \"${pattern}\"`,\n\t\t\t\t\tpattern,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const model of matchingModels) {\n\t\t\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n\t\t\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels);\n\n\t\tif (warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", code: \"invalid-thinking-level\", message: warning, pattern });\n\t\t}\n\n\t\tif (!model) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"no-match\",\n\t\t\t\tmessage: `No models match pattern \"${pattern}\"`,\n\t\t\t\tpattern,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Avoid duplicates\n\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t}\n\t}\n\n\treturn { scopedModels, diagnostics };\n}\n\nexport async function resolveModelScopeWithDiagnostics(\n\tpatterns: string[],\n\tmodelRuntime: ModelRuntime,\n\toptions?: AuthOperationOptions,\n): Promise<ResolveModelScopeResult> {\n\treturn resolveModelScopeFromModels(patterns, await modelRuntime.getAvailable(undefined, options));\n}\n\nexport async function resolveModelScope(\n\tpatterns: string[],\n\tmodelRuntime: ModelRuntime,\n\toptions?: AuthOperationOptions,\n): Promise<ScopedModel[]> {\n\tconst { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRuntime, options);\n\tfor (const diagnostic of diagnostics) {\n\t\tconsole.warn(chalk.yellow(`Warning: ${diagnostic.message}`));\n\t}\n\treturn scopedModels;\n}\n\nexport interface ResolveCliModelResult {\n\tmodel: Model<Api> | undefined;\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n\t/**\n\t * Error message suitable for CLI display.\n\t * When set, model will be undefined.\n\t */\n\terror: string | undefined;\n}\n\n/**\n * Resolve a single model from CLI flags.\n *\n * Supports:\n * - --provider <provider> --model <pattern>\n * - --model <provider>/<pattern>\n * - Fuzzy matching (same rules as model scoping: exact id, then partial id/name)\n *\n * Note: This does not apply the thinking level by itself, but it may *parse* and\n * return a thinking level from \"<pattern>:<thinking>\" so the caller can apply it.\n */\nexport function resolveCliModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tcliThinking?: ThinkingLevel;\n\tmodelRuntime: ModelRuntime;\n}): ResolveCliModelResult {\n\tconst { cliProvider, cliModel, cliThinking, modelRuntime } = options;\n\n\tif (!cliModel) {\n\t\treturn { model: undefined, warning: undefined, error: undefined };\n\t}\n\n\t// Important: use *all* models here, not just models with pre-configured auth.\n\t// This allows \"--api-key\" to be used for first-time setup.\n\tconst availableModels = [...modelRuntime.getModels()];\n\tif (availableModels.length === 0) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: \"No models available. Check your installation or add models to models.json.\",\n\t\t};\n\t}\n\n\t// Build canonical provider lookup (case-insensitive)\n\tconst providerMap = new Map<string, string>();\n\tfor (const m of availableModels) {\n\t\tproviderMap.set(m.provider.toLowerCase(), m.provider);\n\t}\n\n\tlet provider = cliProvider ? providerMap.get(cliProvider.toLowerCase()) : undefined;\n\tif (cliProvider && !provider) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Unknown provider \"${cliProvider}\". Use --list-models to see available providers/models.`,\n\t\t};\n\t}\n\n\t// If no explicit --provider, try to interpret \"provider/model\" format first.\n\t// When the prefix before the first slash matches a known provider, prefer that\n\t// interpretation over matching models whose IDs literally contain slashes\n\t// (e.g. \"zai/glm-5\" should resolve to provider=zai, model=glm-5, not to a\n\t// vercel-ai-gateway model with id \"zai/glm-5\").\n\tlet pattern = cliModel;\n\tlet inferredProvider = false;\n\n\tif (!provider) {\n\t\tconst slashIndex = cliModel.indexOf(\"/\");\n\t\tif (slashIndex !== -1) {\n\t\t\tconst maybeProvider = cliModel.substring(0, slashIndex);\n\t\t\tconst canonical = providerMap.get(maybeProvider.toLowerCase());\n\t\t\tif (canonical) {\n\t\t\t\tprovider = canonical;\n\t\t\t\tpattern = cliModel.substring(slashIndex + 1);\n\t\t\t\tinferredProvider = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// If no provider was inferred from the slash, try exact matches without provider inference.\n\t// This handles models whose IDs naturally contain slashes (e.g. OpenRouter-style IDs).\n\t// Bare exact IDs can exist in multiple providers, so do not choose by catalog order.\n\t// Prefer the sole authenticated provider when there is one; otherwise require an\n\t// explicit provider to avoid silently selecting an unusable provider.\n\tif (!provider) {\n\t\tconst lower = cliModel.toLowerCase();\n\t\tconst exactMatches = availableModels.filter(\n\t\t\t(m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower,\n\t\t);\n\t\tif (exactMatches.length === 1) {\n\t\t\treturn { model: exactMatches[0], warning: undefined, thinkingLevel: undefined, error: undefined };\n\t\t}\n\t\tif (exactMatches.length > 1) {\n\t\t\tconst authenticatedExactMatches = exactMatches.filter((m) => modelRuntime.hasConfiguredAuth(m.provider));\n\t\t\tif (authenticatedExactMatches.length === 1) {\n\t\t\t\treturn {\n\t\t\t\t\tmodel: authenticatedExactMatches[0],\n\t\t\t\t\twarning: undefined,\n\t\t\t\t\tthinkingLevel: undefined,\n\t\t\t\t\terror: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst matches = exactMatches\n\t\t\t\t.map((m) => `${m.provider}/${m.id}`)\n\t\t\t\t.sort((a, b) => a.localeCompare(b))\n\t\t\t\t.join(\", \");\n\t\t\tconst authHint =\n\t\t\t\tauthenticatedExactMatches.length === 0\n\t\t\t\t\t? \"No matching provider is authenticated.\"\n\t\t\t\t\t: \"More than one matching provider is authenticated.\";\n\t\t\treturn {\n\t\t\t\tmodel: undefined,\n\t\t\t\twarning: undefined,\n\t\t\t\tthinkingLevel: undefined,\n\t\t\t\terror: `Model \"${cliModel}\" is ambiguous across providers: ${matches}. ${authHint} Use --provider or provider/model.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (cliProvider && provider) {\n\t\t// If both were provided, tolerate --model <provider>/<pattern> by stripping the provider prefix\n\t\tconst prefix = `${provider}/`;\n\t\tif (cliModel.toLowerCase().startsWith(prefix.toLowerCase())) {\n\t\t\tpattern = cliModel.substring(prefix.length);\n\t\t}\n\t}\n\n\tconst candidates = provider ? availableModels.filter((m) => m.provider === provider) : availableModels;\n\tconst { model, thinkingLevel, warning } = parseModelPattern(pattern, candidates, {\n\t\tallowInvalidThinkingLevelFallback: false,\n\t});\n\n\tif (model) {\n\t\t// If provider inference matched an unauthenticated provider/model pair, prefer\n\t\t// one exact raw model-id match that is authenticated. This keeps\n\t\t// \"provider/model\" syntax preferred when usable, but handles models whose\n\t\t// literal id starts with a known provider name (for example\n\t\t// commandcode model id \"xiaomi/mimo-v2.5-pro\").\n\t\tif (inferredProvider) {\n\t\t\tconst rawExactMatches = availableModels.filter(\n\t\t\t\t(m) => m.id.toLowerCase() === cliModel.toLowerCase() && !modelsAreEqual(m, model),\n\t\t\t);\n\t\t\tif (rawExactMatches.length > 0 && !modelRuntime.hasConfiguredAuth(model.provider)) {\n\t\t\t\tconst authenticatedRawMatches = rawExactMatches.filter((m) => modelRuntime.hasConfiguredAuth(m.provider));\n\t\t\t\tif (authenticatedRawMatches.length === 1) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmodel: authenticatedRawMatches[0],\n\t\t\t\t\t\tthinkingLevel: undefined,\n\t\t\t\t\t\twarning: undefined,\n\t\t\t\t\t\terror: undefined,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { model, thinkingLevel, warning, error: undefined };\n\t}\n\n\t// If we inferred a provider from the slash but found no match within that provider,\n\t// fall back to matching the full input as a raw model id across all models.\n\t// This handles OpenRouter-style IDs like \"openai/gpt-4o:extended\" where \"openai\"\n\t// looks like a provider but the full string is actually a model id on openrouter.\n\tif (inferredProvider) {\n\t\tconst lower = cliModel.toLowerCase();\n\t\tconst exact = availableModels.find(\n\t\t\t(m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower,\n\t\t);\n\t\tif (exact) {\n\t\t\treturn { model: exact, warning: undefined, thinkingLevel: undefined, error: undefined };\n\t\t}\n\t\t// Also try parseModelPattern on the full input against all models\n\t\tconst fallback = parseModelPattern(cliModel, availableModels, {\n\t\t\tallowInvalidThinkingLevelFallback: false,\n\t\t});\n\t\tif (fallback.model) {\n\t\t\treturn {\n\t\t\t\tmodel: fallback.model,\n\t\t\t\tthinkingLevel: fallback.thinkingLevel,\n\t\t\t\twarning: fallback.warning,\n\t\t\t\terror: undefined,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (provider) {\n\t\t// Parse thinking level suffix from the pattern before building the fallback model,\n\t\t// but only when --thinking is not explicitly provided.\n\t\t// e.g. \"zai-org/GLM-5.1-FP8:high\" → modelId=\"zai-org/GLM-5.1-FP8\", fallbackThinking=\"high\"\n\t\tlet fallbackPattern = pattern;\n\t\tlet fallbackThinking: ThinkingLevel | undefined;\n\t\tif (!cliThinking) {\n\t\t\tconst lastColon = pattern.lastIndexOf(\":\");\n\t\t\tif (lastColon !== -1) {\n\t\t\t\tconst suffix = pattern.substring(lastColon + 1);\n\t\t\t\tif (isValidThinkingLevel(suffix)) {\n\t\t\t\t\tfallbackPattern = pattern.substring(0, lastColon);\n\t\t\t\t\tfallbackThinking = suffix;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst fallbackModel = buildFallbackModel(provider, fallbackPattern, availableModels);\n\t\tif (fallbackModel) {\n\t\t\tconst requestedThinking = cliThinking ?? fallbackThinking;\n\t\t\tconst model =\n\t\t\t\trequestedThinking && requestedThinking !== \"off\" ? { ...fallbackModel, reasoning: true } : fallbackModel;\n\t\t\tconst fallbackWarning = warning\n\t\t\t\t? `${warning} Model \"${fallbackPattern}\" not found for provider \"${provider}\". Using custom model id.`\n\t\t\t\t: `Model \"${fallbackPattern}\" not found for provider \"${provider}\". Using custom model id.`;\n\t\t\treturn { model, thinkingLevel: fallbackThinking, warning: fallbackWarning, error: undefined };\n\t\t}\n\t}\n\n\tconst display = provider ? `${provider}/${pattern}` : cliModel;\n\treturn {\n\t\tmodel: undefined,\n\t\tthinkingLevel: undefined,\n\t\twarning,\n\t\terror: `Model \"${display}\" not found. Use --list-models to see available models.`,\n\t};\n}\n\nexport interface InitialModelResult {\n\tmodel: Model<Api> | undefined;\n\tthinkingLevel: ThinkingLevel;\n\tfallbackMessage: string | undefined;\n}\n\n/**\n * Find the initial model to use based on priority:\n * 1. CLI args (provider + model)\n * 2. First model from scoped models (if not continuing/resuming)\n * 3. Restored from session (if continuing/resuming)\n * 4. Saved default from settings\n * 5. First available model with valid API key\n */\nexport async function findInitialModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tscopedModels: ScopedModel[];\n\tisContinuing: boolean;\n\tdefaultProvider?: string;\n\tdefaultModelId?: string;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\tmodelRuntime: ModelRuntime;\n}): Promise<InitialModelResult> {\n\tconst {\n\t\tcliProvider,\n\t\tcliModel,\n\t\tscopedModels,\n\t\tisContinuing,\n\t\tdefaultProvider,\n\t\tdefaultModelId,\n\t\tdefaultThinkingLevel,\n\t\tmodelRuntime,\n\t} = options;\n\n\tlet model: Model<Api> | undefined;\n\tlet thinkingLevel: ThinkingLevel = DEFAULT_THINKING_LEVEL;\n\n\t// 1. CLI args take priority\n\tif (cliProvider && cliModel) {\n\t\tconst resolved = resolveCliModel({\n\t\t\tcliProvider,\n\t\t\tcliModel,\n\t\t\tmodelRuntime,\n\t\t});\n\t\tif (resolved.error) {\n\t\t\tconsole.error(chalk.red(resolved.error));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tif (resolved.model) {\n\t\t\treturn { model: resolved.model, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 2. Use first model from scoped models (skip if continuing/resuming)\n\tif (scopedModels.length > 0 && !isContinuing) {\n\t\treturn {\n\t\t\tmodel: scopedModels[0].model,\n\t\t\tthinkingLevel: scopedModels[0].thinkingLevel ?? defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t\tfallbackMessage: undefined,\n\t\t};\n\t}\n\n\t// 3. Try saved default from settings if auth is configured.\n\tif (defaultProvider && defaultModelId) {\n\t\tconst found = modelRuntime.getModel(defaultProvider, defaultModelId);\n\t\tif (found && modelRuntime.hasConfiguredAuth(found.provider)) {\n\t\t\tmodel = found;\n\t\t\tif (defaultThinkingLevel) {\n\t\t\t\tthinkingLevel = defaultThinkingLevel;\n\t\t\t}\n\t\t\treturn { model, thinkingLevel, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 4. Try first available model with valid API key\n\tconst availableModels = [...modelRuntime.getAvailableSnapshot()];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\treturn { model: match, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\treturn { model: availableModels[0], thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t}\n\n\t// 5. No model found\n\treturn { model: undefined, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n}\n\n/**\n * Restore model from session, with fallback to available models\n */\nexport async function restoreModelFromSession(\n\tsavedProvider: string,\n\tsavedModelId: string,\n\tcurrentModel: Model<Api> | undefined,\n\tshouldPrintMessages: boolean,\n\tmodelRuntime: ModelRuntime,\n): Promise<{ model: Model<Api> | undefined; fallbackMessage: string | undefined }> {\n\tconst restoredModel = modelRuntime.getModel(savedProvider, savedModelId);\n\n\t// Check if restored model exists and still has auth configured\n\tconst hasConfiguredAuth = restoredModel ? modelRuntime.hasConfiguredAuth(restoredModel.provider) : false;\n\n\tif (restoredModel && hasConfiguredAuth) {\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Restored model: ${savedProvider}/${savedModelId}`));\n\t\t}\n\t\treturn { model: restoredModel, fallbackMessage: undefined };\n\t}\n\n\t// Model not found or no API key - fall back\n\tconst reason = !restoredModel ? \"model no longer exists\" : \"no auth configured\";\n\n\tif (shouldPrintMessages) {\n\t\tconsole.error(chalk.yellow(`Warning: Could not restore model ${savedProvider}/${savedModelId} (${reason}).`));\n\t}\n\n\t// If we already have a model, use it as fallback\n\tif (currentModel) {\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Falling back to: ${currentModel.provider}/${currentModel.id}`));\n\t\t}\n\t\treturn {\n\t\t\tmodel: currentModel,\n\t\t\tfallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${currentModel.provider}/${currentModel.id}.`,\n\t\t};\n\t}\n\n\t// Try to find any available model\n\tconst availableModels = [...modelRuntime.getAvailableSnapshot()];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tlet fallbackModel: Model<Api> | undefined;\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\tfallbackModel = match;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\tif (!fallbackModel) {\n\t\t\tfallbackModel = availableModels[0];\n\t\t}\n\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Falling back to: ${fallbackModel.provider}/${fallbackModel.id}`));\n\t\t}\n\n\t\treturn {\n\t\t\tmodel: fallbackModel,\n\t\t\tfallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${fallbackModel.provider}/${fallbackModel.id}.`,\n\t\t};\n\t}\n\n\t// No models available\n\treturn { model: undefined, fallbackMessage: undefined };\n}\n"]}
1
+ {"version":3,"file":"model-resolver.js","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAKN,cAAc,GACd,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAGvD,gDAAgD;AAChD,MAAM,CAAC,MAAM,uBAAuB,GAAkC;IACrE,gBAAgB,EAAE,iCAAiC;IACnD,UAAU,EAAE,aAAa;IACzB,SAAS,EAAE,iBAAiB;IAC5B,MAAM,EAAE,SAAS;IACjB,wBAAwB,EAAE,SAAS;IACnC,cAAc,EAAE,SAAS;IACzB,MAAM,EAAE,MAAM;IACd,MAAM,EAAE,mCAAmC;IAC3C,QAAQ,EAAE,iBAAiB;IAC3B,MAAM,EAAE,wBAAwB;IAChC,eAAe,EAAE,wBAAwB;I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AC,CAAC;QACpC,CAAC;QAED,IAAI,mBAAmB,EAAE,CAAC;YACzB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,oBAAoB,aAAa,CAAC,QAAQ,IAAI,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QAC1F,CAAC;QAED,OAAO;YACN,KAAK,EAAE,aAAa;YACpB,eAAe,EAAE,2BAA2B,aAAa,IAAI,YAAY,KAAK,MAAM,YAAY,aAAa,CAAC,QAAQ,IAAI,aAAa,CAAC,EAAE,GAAG;SAC7I,CAAC;IACH,CAAC;IAED,sBAAsB;IACtB,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;AAAA,CACxD","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nimport {\n\ttype Api,\n\ttype AuthOperationOptions,\n\ttype KnownProvider,\n\ttype Model,\n\tmodelsAreEqual,\n} from \"@earendil-works/pi-ai\";\nimport type { ThinkingLevel } from \"apex-code-agent-core\";\nimport chalk from \"chalk\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\n\n/** Default model IDs for each known provider */\nexport const defaultModelPerProvider: Record<KnownProvider, string> = {\n\t\"amazon-bedrock\": \"us.anthropic.claude-opus-4-6-v1\",\n\t\"ant-ling\": \"Ring-2.6-1T\",\n\tanthropic: \"claude-opus-4-8\",\n\topenai: \"gpt-5.5\",\n\t\"azure-openai-responses\": \"gpt-5.4\",\n\t\"openai-codex\": \"gpt-5.5\",\n\tradius: \"auto\",\n\tnvidia: \"nvidia/nemotron-3-super-120b-a12b\",\n\tdeepseek: \"deepseek-v4-pro\",\n\tgoogle: \"gemini-3.1-pro-preview\",\n\t\"google-vertex\": \"gemini-3.1-pro-preview\",\n\t\"github-copilot\": \"gpt-5.4\",\n\topenrouter: \"moonshotai/kimi-k2.6\",\n\t\"vercel-ai-gateway\": \"zai/glm-5.1\",\n\txai: \"grok-4.5\",\n\tgroq: \"openai/gpt-oss-120b\",\n\tcerebras: \"zai-glm-4.7\",\n\tzai: \"glm-5.1\",\n\t\"zai-coding-cn\": \"glm-5.1\",\n\tmistral: \"devstral-medium-latest\",\n\tminimax: \"MiniMax-M2.7\",\n\t\"minimax-cn\": \"MiniMax-M2.7\",\n\tmoonshotai: \"kimi-k2.6\",\n\t\"moonshotai-cn\": \"kimi-k2.6\",\n\thuggingface: \"moonshotai/Kimi-K2.6\",\n\tfireworks: \"accounts/fireworks/models/kimi-k2p6\",\n\ttogether: \"moonshotai/Kimi-K2.6\",\n\tbaseten: \"zai-org/GLM-5.2\",\n\topencode: \"kimi-k2.6\",\n\t\"opencode-go\": \"kimi-k2.6\",\n\t\"kimi-coding\": \"kimi-for-coding\",\n\t\"cloudflare-workers-ai\": \"@cf/moonshotai/kimi-k2.6\",\n\t\"cloudflare-ai-gateway\": \"workers-ai/@cf/moonshotai/kimi-k2.6\",\n\t\"qwen-token-plan\": \"qwen3.7-max\",\n\t\"qwen-token-plan-cn\": \"qwen3.7-max\",\n\t\"qwen-token-plan-individual\": \"qwen3.8-max\",\n\txiaomi: \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-cn\": \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-ams\": \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-sgp\": \"mimo-v2.5-pro\",\n};\n\nexport interface ScopedModel {\n\tmodel: Model<Api>;\n\t/** Thinking level if explicitly specified in pattern (e.g., \"model:high\"), undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/**\n * Helper to check if a model ID looks like an alias (no date suffix)\n * Dates are typically in format: -20241022 or -20250929\n */\nfunction isAlias(id: string): boolean {\n\t// Check if ID ends with -latest\n\tif (id.endsWith(\"-latest\")) return true;\n\n\t// Check if ID ends with a date pattern (-YYYYMMDD)\n\tconst datePattern = /-\\d{8}$/;\n\treturn !datePattern.test(id);\n}\n\n/**\n * Find an exact model reference match.\n * Supports either a bare model id or a canonical provider/modelId reference.\n * When matching by bare id, ambiguous matches across providers are rejected.\n */\nexport function findExactModelReferenceMatch(\n\tmodelReference: string,\n\tavailableModels: Model<Api>[],\n): Model<Api> | undefined {\n\tconst trimmedReference = modelReference.trim();\n\tif (!trimmedReference) {\n\t\treturn undefined;\n\t}\n\n\tconst normalizedReference = trimmedReference.toLowerCase();\n\n\tconst canonicalMatches = availableModels.filter(\n\t\t(model) => `${model.provider}/${model.id}`.toLowerCase() === normalizedReference,\n\t);\n\tif (canonicalMatches.length === 1) {\n\t\treturn canonicalMatches[0];\n\t}\n\tif (canonicalMatches.length > 1) {\n\t\treturn undefined;\n\t}\n\n\tconst slashIndex = trimmedReference.indexOf(\"/\");\n\tif (slashIndex !== -1) {\n\t\tconst provider = trimmedReference.substring(0, slashIndex).trim();\n\t\tconst modelId = trimmedReference.substring(slashIndex + 1).trim();\n\t\tif (provider && modelId) {\n\t\t\tconst providerMatches = availableModels.filter(\n\t\t\t\t(model) =>\n\t\t\t\t\tmodel.provider.toLowerCase() === provider.toLowerCase() &&\n\t\t\t\t\tmodel.id.toLowerCase() === modelId.toLowerCase(),\n\t\t\t);\n\t\t\tif (providerMatches.length === 1) {\n\t\t\t\treturn providerMatches[0];\n\t\t\t}\n\t\t\tif (providerMatches.length > 1) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst idMatches = availableModels.filter((model) => model.id.toLowerCase() === normalizedReference);\n\treturn idMatches.length === 1 ? idMatches[0] : undefined;\n}\n\n/**\n * Try to match a pattern to a model from the available models list.\n * Returns the matched model or undefined if no match found.\n */\nfunction tryMatchModel(modelPattern: string, availableModels: Model<Api>[]): Model<Api> | undefined {\n\tconst exactMatch = findExactModelReferenceMatch(modelPattern, availableModels);\n\tif (exactMatch) {\n\t\treturn exactMatch;\n\t}\n\n\t// No exact match - fall back to partial matching\n\tconst matches = availableModels.filter(\n\t\t(m) =>\n\t\t\tm.id.toLowerCase().includes(modelPattern.toLowerCase()) ||\n\t\t\tm.name?.toLowerCase().includes(modelPattern.toLowerCase()),\n\t);\n\n\tif (matches.length === 0) {\n\t\treturn undefined;\n\t}\n\n\t// Separate into aliases and dated versions\n\tconst aliases = matches.filter((m) => isAlias(m.id));\n\tconst datedVersions = matches.filter((m) => !isAlias(m.id));\n\n\tif (aliases.length > 0) {\n\t\t// Prefer alias - if multiple aliases, pick the one that sorts highest\n\t\taliases.sort((a, b) => b.id.localeCompare(a.id));\n\t\treturn aliases[0];\n\t} else {\n\t\t// No alias found, pick latest dated version\n\t\tdatedVersions.sort((a, b) => b.id.localeCompare(a.id));\n\t\treturn datedVersions[0];\n\t}\n}\n\nexport interface ParsedModelResult {\n\tmodel: Model<Api> | undefined;\n\t/** Thinking level if explicitly specified in pattern, undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n}\n\nfunction buildFallbackModel(provider: string, modelId: string, availableModels: Model<Api>[]): Model<Api> | undefined {\n\tconst providerModels = availableModels.filter((m) => m.provider === provider);\n\tif (providerModels.length === 0) return undefined;\n\n\tconst defaultId = defaultModelPerProvider[provider as KnownProvider];\n\tconst baseModel = defaultId\n\t\t? (providerModels.find((m) => m.id === defaultId) ?? providerModels[0])\n\t\t: providerModels[0];\n\n\treturn {\n\t\t...baseModel,\n\t\tid: modelId,\n\t\tname: modelId,\n\t};\n}\n\n/**\n * Parse a pattern to extract model and thinking level.\n * Handles models with colons in their IDs (e.g., OpenRouter's :exacto suffix).\n *\n * Algorithm:\n * 1. Try to match full pattern as a model\n * 2. If found, return it with \"off\" thinking level\n * 3. If not found and has colons, split on last colon:\n * - If suffix is valid thinking level, use it and recurse on prefix\n * - If suffix is invalid, warn and recurse on prefix with \"off\"\n *\n * @internal Exported for testing\n */\nexport function parseModelPattern(\n\tpattern: string,\n\tavailableModels: Model<Api>[],\n\toptions?: { allowInvalidThinkingLevelFallback?: boolean },\n): ParsedModelResult {\n\t// Try exact match first\n\tconst exactMatch = tryMatchModel(pattern, availableModels);\n\tif (exactMatch) {\n\t\treturn { model: exactMatch, thinkingLevel: undefined, warning: undefined };\n\t}\n\n\t// No match - try splitting on last colon if present\n\tconst lastColonIndex = pattern.lastIndexOf(\":\");\n\tif (lastColonIndex === -1) {\n\t\t// No colons, pattern simply doesn't match any model\n\t\treturn { model: undefined, thinkingLevel: undefined, warning: undefined };\n\t}\n\n\tconst prefix = pattern.substring(0, lastColonIndex);\n\tconst suffix = pattern.substring(lastColonIndex + 1);\n\n\tif (isValidThinkingLevel(suffix)) {\n\t\t// Valid thinking level - recurse on prefix and use this level\n\t\tconst result = parseModelPattern(prefix, availableModels, options);\n\t\tif (result.model) {\n\t\t\t// Only use this thinking level if no warning from inner recursion\n\t\t\treturn {\n\t\t\t\tmodel: result.model,\n\t\t\t\tthinkingLevel: result.warning ? undefined : suffix,\n\t\t\t\twarning: result.warning,\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t} else {\n\t\t// Invalid suffix\n\t\tconst allowFallback = options?.allowInvalidThinkingLevelFallback ?? true;\n\t\tif (!allowFallback) {\n\t\t\t// In strict mode (CLI --model parsing), treat it as part of the model id and fail.\n\t\t\t// This avoids accidentally resolving to a different model.\n\t\t\treturn { model: undefined, thinkingLevel: undefined, warning: undefined };\n\t\t}\n\n\t\t// Scope mode: recurse on prefix and warn\n\t\tconst result = parseModelPattern(prefix, availableModels, options);\n\t\tif (result.model) {\n\t\t\treturn {\n\t\t\t\tmodel: result.model,\n\t\t\t\tthinkingLevel: undefined,\n\t\t\t\twarning: `Invalid thinking level \"${suffix}\" in pattern \"${pattern}\". Using default instead.`,\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Resolve model patterns to actual Model objects with optional thinking levels\n * Format: \"pattern:level\" where :level is optional\n * For each pattern, finds all matching models and picks the best version:\n * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)\n * 2. If no alias, pick the latest dated version\n *\n * Supports models with colons in their IDs (e.g., OpenRouter's model:exacto).\n * The algorithm tries to match the full pattern first, then progressively\n * strips colon-suffixes to find a match.\n */\nexport interface ModelScopeDiagnostic {\n\ttype: \"warning\";\n\tcode: \"no-match\" | \"invalid-thinking-level\";\n\tmessage: string;\n\tpattern: string;\n}\n\nexport interface ResolveModelScopeResult {\n\tscopedModels: ScopedModel[];\n\tdiagnostics: ModelScopeDiagnostic[];\n}\n\nexport function resolveModelScopeFromModels(\n\tpatterns: string[],\n\tmodels: readonly Model<Api>[],\n): ResolveModelScopeResult {\n\tconst availableModels = [...models];\n\tconst scopedModels: ScopedModel[] = [];\n\tconst diagnostics: ModelScopeDiagnostic[] = [];\n\n\tfor (const pattern of patterns) {\n\t\t// Check if pattern contains glob characters\n\t\tif (pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\")) {\n\t\t\t// Extract optional thinking level suffix (e.g., \"provider/*:high\")\n\t\t\tconst colonIdx = pattern.lastIndexOf(\":\");\n\t\t\tlet globPattern = pattern;\n\t\t\tlet thinkingLevel: ThinkingLevel | undefined;\n\n\t\t\tif (colonIdx !== -1) {\n\t\t\t\tconst suffix = pattern.substring(colonIdx + 1);\n\t\t\t\tif (isValidThinkingLevel(suffix)) {\n\t\t\t\t\tthinkingLevel = suffix;\n\t\t\t\t\tglobPattern = pattern.substring(0, colonIdx);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst exactMatch = findExactModelReferenceMatch(globPattern, availableModels);\n\t\t\tif (exactMatch) {\n\t\t\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, exactMatch))) {\n\t\t\t\t\tscopedModels.push({ model: exactMatch, thinkingLevel });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Match against \"provider/modelId\" format OR just model ID\n\t\t\t// This allows \"*sonnet*\" to match without requiring \"anthropic/*sonnet*\"\n\t\t\tconst matchingModels = availableModels.filter((m) => {\n\t\t\t\tconst fullId = `${m.provider}/${m.id}`;\n\t\t\t\treturn minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true });\n\t\t\t});\n\n\t\t\tif (matchingModels.length === 0) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"no-match\",\n\t\t\t\t\tmessage: `No models match pattern \"${pattern}\"`,\n\t\t\t\t\tpattern,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const model of matchingModels) {\n\t\t\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n\t\t\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels);\n\n\t\tif (warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", code: \"invalid-thinking-level\", message: warning, pattern });\n\t\t}\n\n\t\tif (!model) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"no-match\",\n\t\t\t\tmessage: `No models match pattern \"${pattern}\"`,\n\t\t\t\tpattern,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Avoid duplicates\n\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t}\n\t}\n\n\treturn { scopedModels, diagnostics };\n}\n\nexport async function resolveModelScopeWithDiagnostics(\n\tpatterns: string[],\n\tmodelRuntime: ModelRuntime,\n\toptions?: AuthOperationOptions,\n): Promise<ResolveModelScopeResult> {\n\treturn resolveModelScopeFromModels(patterns, await modelRuntime.getAvailable(undefined, options));\n}\n\nexport async function resolveModelScope(\n\tpatterns: string[],\n\tmodelRuntime: ModelRuntime,\n\toptions?: AuthOperationOptions,\n): Promise<ScopedModel[]> {\n\tconst { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRuntime, options);\n\tfor (const diagnostic of diagnostics) {\n\t\tconsole.warn(chalk.yellow(`Warning: ${diagnostic.message}`));\n\t}\n\treturn scopedModels;\n}\n\nexport interface ResolveCliModelResult {\n\tmodel: Model<Api> | undefined;\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n\t/**\n\t * Error message suitable for CLI display.\n\t * When set, model will be undefined.\n\t */\n\terror: string | undefined;\n}\n\n/**\n * Resolve a single model from CLI flags.\n *\n * Supports:\n * - --provider <provider> --model <pattern>\n * - --model <provider>/<pattern>\n * - Fuzzy matching (same rules as model scoping: exact id, then partial id/name)\n *\n * Note: This does not apply the thinking level by itself, but it may *parse* and\n * return a thinking level from \"<pattern>:<thinking>\" so the caller can apply it.\n */\nexport function resolveCliModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tcliThinking?: ThinkingLevel;\n\tmodelRuntime: ModelRuntime;\n}): ResolveCliModelResult {\n\tconst { cliProvider, cliModel, cliThinking, modelRuntime } = options;\n\n\tif (!cliModel) {\n\t\treturn { model: undefined, warning: undefined, error: undefined };\n\t}\n\n\t// Important: use *all* models here, not just models with pre-configured auth.\n\t// This allows \"--api-key\" to be used for first-time setup.\n\tconst availableModels = [...modelRuntime.getModels()];\n\tif (availableModels.length === 0) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: \"No models available. Check your installation or add models to models.json.\",\n\t\t};\n\t}\n\n\t// Build canonical provider lookup (case-insensitive)\n\tconst providerMap = new Map<string, string>();\n\tfor (const m of availableModels) {\n\t\tproviderMap.set(m.provider.toLowerCase(), m.provider);\n\t}\n\n\tlet provider = cliProvider ? providerMap.get(cliProvider.toLowerCase()) : undefined;\n\tif (cliProvider && !provider) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Unknown provider \"${cliProvider}\". Use --list-models to see available providers/models.`,\n\t\t};\n\t}\n\n\t// If no explicit --provider, try to interpret \"provider/model\" format first.\n\t// When the prefix before the first slash matches a known provider, prefer that\n\t// interpretation over matching models whose IDs literally contain slashes\n\t// (e.g. \"zai/glm-5\" should resolve to provider=zai, model=glm-5, not to a\n\t// vercel-ai-gateway model with id \"zai/glm-5\").\n\tlet pattern = cliModel;\n\tlet inferredProvider = false;\n\n\tif (!provider) {\n\t\tconst slashIndex = cliModel.indexOf(\"/\");\n\t\tif (slashIndex !== -1) {\n\t\t\tconst maybeProvider = cliModel.substring(0, slashIndex);\n\t\t\tconst canonical = providerMap.get(maybeProvider.toLowerCase());\n\t\t\tif (canonical) {\n\t\t\t\tprovider = canonical;\n\t\t\t\tpattern = cliModel.substring(slashIndex + 1);\n\t\t\t\tinferredProvider = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// If no provider was inferred from the slash, try exact matches without provider inference.\n\t// This handles models whose IDs naturally contain slashes (e.g. OpenRouter-style IDs).\n\t// Bare exact IDs can exist in multiple providers, so do not choose by catalog order.\n\t// Prefer the sole authenticated provider when there is one; otherwise require an\n\t// explicit provider to avoid silently selecting an unusable provider.\n\tif (!provider) {\n\t\tconst lower = cliModel.toLowerCase();\n\t\tconst exactMatches = availableModels.filter(\n\t\t\t(m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower,\n\t\t);\n\t\tif (exactMatches.length === 1) {\n\t\t\treturn { model: exactMatches[0], warning: undefined, thinkingLevel: undefined, error: undefined };\n\t\t}\n\t\tif (exactMatches.length > 1) {\n\t\t\tconst authenticatedExactMatches = exactMatches.filter((m) => modelRuntime.hasConfiguredAuth(m.provider));\n\t\t\tif (authenticatedExactMatches.length === 1) {\n\t\t\t\treturn {\n\t\t\t\t\tmodel: authenticatedExactMatches[0],\n\t\t\t\t\twarning: undefined,\n\t\t\t\t\tthinkingLevel: undefined,\n\t\t\t\t\terror: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst matches = exactMatches\n\t\t\t\t.map((m) => `${m.provider}/${m.id}`)\n\t\t\t\t.sort((a, b) => a.localeCompare(b))\n\t\t\t\t.join(\", \");\n\t\t\tconst authHint =\n\t\t\t\tauthenticatedExactMatches.length === 0\n\t\t\t\t\t? \"No matching provider is authenticated.\"\n\t\t\t\t\t: \"More than one matching provider is authenticated.\";\n\t\t\treturn {\n\t\t\t\tmodel: undefined,\n\t\t\t\twarning: undefined,\n\t\t\t\tthinkingLevel: undefined,\n\t\t\t\terror: `Model \"${cliModel}\" is ambiguous across providers: ${matches}. ${authHint} Use --provider or provider/model.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (cliProvider && provider) {\n\t\t// If both were provided, tolerate --model <provider>/<pattern> by stripping the provider prefix\n\t\tconst prefix = `${provider}/`;\n\t\tif (cliModel.toLowerCase().startsWith(prefix.toLowerCase())) {\n\t\t\tpattern = cliModel.substring(prefix.length);\n\t\t}\n\t}\n\n\tconst candidates = provider ? availableModels.filter((m) => m.provider === provider) : availableModels;\n\tconst { model, thinkingLevel, warning } = parseModelPattern(pattern, candidates, {\n\t\tallowInvalidThinkingLevelFallback: false,\n\t});\n\n\tif (model) {\n\t\t// If provider inference matched an unauthenticated provider/model pair, prefer\n\t\t// one exact raw model-id match that is authenticated. This keeps\n\t\t// \"provider/model\" syntax preferred when usable, but handles models whose\n\t\t// literal id starts with a known provider name (for example\n\t\t// commandcode model id \"xiaomi/mimo-v2.5-pro\").\n\t\tif (inferredProvider) {\n\t\t\tconst rawExactMatches = availableModels.filter(\n\t\t\t\t(m) => m.id.toLowerCase() === cliModel.toLowerCase() && !modelsAreEqual(m, model),\n\t\t\t);\n\t\t\tif (rawExactMatches.length > 0 && !modelRuntime.hasConfiguredAuth(model.provider)) {\n\t\t\t\tconst authenticatedRawMatches = rawExactMatches.filter((m) => modelRuntime.hasConfiguredAuth(m.provider));\n\t\t\t\tif (authenticatedRawMatches.length === 1) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmodel: authenticatedRawMatches[0],\n\t\t\t\t\t\tthinkingLevel: undefined,\n\t\t\t\t\t\twarning: undefined,\n\t\t\t\t\t\terror: undefined,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { model, thinkingLevel, warning, error: undefined };\n\t}\n\n\t// If we inferred a provider from the slash but found no match within that provider,\n\t// fall back to matching the full input as a raw model id across all models.\n\t// This handles OpenRouter-style IDs like \"openai/gpt-4o:extended\" where \"openai\"\n\t// looks like a provider but the full string is actually a model id on openrouter.\n\tif (inferredProvider) {\n\t\tconst lower = cliModel.toLowerCase();\n\t\tconst exact = availableModels.find(\n\t\t\t(m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower,\n\t\t);\n\t\tif (exact) {\n\t\t\treturn { model: exact, warning: undefined, thinkingLevel: undefined, error: undefined };\n\t\t}\n\t\t// Also try parseModelPattern on the full input against all models\n\t\tconst fallback = parseModelPattern(cliModel, availableModels, {\n\t\t\tallowInvalidThinkingLevelFallback: false,\n\t\t});\n\t\tif (fallback.model) {\n\t\t\treturn {\n\t\t\t\tmodel: fallback.model,\n\t\t\t\tthinkingLevel: fallback.thinkingLevel,\n\t\t\t\twarning: fallback.warning,\n\t\t\t\terror: undefined,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (provider) {\n\t\t// Parse thinking level suffix from the pattern before building the fallback model,\n\t\t// but only when --thinking is not explicitly provided.\n\t\t// e.g. \"zai-org/GLM-5.1-FP8:high\" → modelId=\"zai-org/GLM-5.1-FP8\", fallbackThinking=\"high\"\n\t\tlet fallbackPattern = pattern;\n\t\tlet fallbackThinking: ThinkingLevel | undefined;\n\t\tif (!cliThinking) {\n\t\t\tconst lastColon = pattern.lastIndexOf(\":\");\n\t\t\tif (lastColon !== -1) {\n\t\t\t\tconst suffix = pattern.substring(lastColon + 1);\n\t\t\t\tif (isValidThinkingLevel(suffix)) {\n\t\t\t\t\tfallbackPattern = pattern.substring(0, lastColon);\n\t\t\t\t\tfallbackThinking = suffix;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst fallbackModel = buildFallbackModel(provider, fallbackPattern, availableModels);\n\t\tif (fallbackModel) {\n\t\t\tconst requestedThinking = cliThinking ?? fallbackThinking;\n\t\t\tconst model =\n\t\t\t\trequestedThinking && requestedThinking !== \"off\" ? { ...fallbackModel, reasoning: true } : fallbackModel;\n\t\t\tconst fallbackWarning = warning\n\t\t\t\t? `${warning} Model \"${fallbackPattern}\" not found for provider \"${provider}\". Using custom model id.`\n\t\t\t\t: `Model \"${fallbackPattern}\" not found for provider \"${provider}\". Using custom model id.`;\n\t\t\treturn { model, thinkingLevel: fallbackThinking, warning: fallbackWarning, error: undefined };\n\t\t}\n\t}\n\n\tconst display = provider ? `${provider}/${pattern}` : cliModel;\n\treturn {\n\t\tmodel: undefined,\n\t\tthinkingLevel: undefined,\n\t\twarning,\n\t\terror: `Model \"${display}\" not found. Use --list-models to see available models.`,\n\t};\n}\n\nexport interface InitialModelResult {\n\tmodel: Model<Api> | undefined;\n\tthinkingLevel: ThinkingLevel;\n\tfallbackMessage: string | undefined;\n}\n\n/**\n * Find the initial model to use based on priority:\n * 1. CLI args (provider + model)\n * 2. First model from scoped models (if not continuing/resuming)\n * 3. Restored from session (if continuing/resuming)\n * 4. Saved default from settings\n * 5. First available model with valid API key\n */\nexport async function findInitialModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tscopedModels: ScopedModel[];\n\tisContinuing: boolean;\n\tdefaultProvider?: string;\n\tdefaultModelId?: string;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\tmodelRuntime: ModelRuntime;\n}): Promise<InitialModelResult> {\n\tconst {\n\t\tcliProvider,\n\t\tcliModel,\n\t\tscopedModels,\n\t\tisContinuing,\n\t\tdefaultProvider,\n\t\tdefaultModelId,\n\t\tdefaultThinkingLevel,\n\t\tmodelRuntime,\n\t} = options;\n\n\tlet model: Model<Api> | undefined;\n\tlet thinkingLevel: ThinkingLevel = DEFAULT_THINKING_LEVEL;\n\n\t// 1. CLI args take priority\n\tif (cliProvider && cliModel) {\n\t\tconst resolved = resolveCliModel({\n\t\t\tcliProvider,\n\t\t\tcliModel,\n\t\t\tmodelRuntime,\n\t\t});\n\t\tif (resolved.error) {\n\t\t\tconsole.error(chalk.red(resolved.error));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tif (resolved.model) {\n\t\t\treturn { model: resolved.model, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 2. Use first model from scoped models (skip if continuing/resuming)\n\tif (scopedModels.length > 0 && !isContinuing) {\n\t\treturn {\n\t\t\tmodel: scopedModels[0].model,\n\t\t\tthinkingLevel: scopedModels[0].thinkingLevel ?? defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t\tfallbackMessage: undefined,\n\t\t};\n\t}\n\n\t// 3. Try saved default from settings if auth is configured.\n\tif (defaultProvider && defaultModelId) {\n\t\tconst found = modelRuntime.getModel(defaultProvider, defaultModelId);\n\t\tif (found && modelRuntime.hasConfiguredAuth(found.provider)) {\n\t\t\tmodel = found;\n\t\t\tif (defaultThinkingLevel) {\n\t\t\t\tthinkingLevel = defaultThinkingLevel;\n\t\t\t}\n\t\t\treturn { model, thinkingLevel, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 4. Try first available model with valid API key\n\tconst availableModels = [...modelRuntime.getAvailableSnapshot()];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\treturn { model: match, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\treturn { model: availableModels[0], thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t}\n\n\t// 5. No model found\n\treturn { model: undefined, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n}\n\nexport interface RoleResolutionDiagnostic {\n\ttype: \"warning\";\n\tcode: \"empty-chain\" | \"unknown-model\" | \"duplicate-candidate\";\n\troleName: string;\n\treference?: string;\n\tmessage: string;\n}\n\nexport interface RoleResolutionResult {\n\t/** Successfully resolved roles only; a role with any invalid reference is omitted entirely. */\n\troles: ReadonlyMap<string, Model<Api>[]>;\n\tdiagnostics: RoleResolutionDiagnostic[];\n}\n\n/**\n * Resolve additive role configuration (role name -> ordered \"provider/modelId\"\n * references) against the runtime's known models. Pure and credential-blind: it\n * never resolves auth and never mutates configuration. A role with an empty chain,\n * an unknown model reference, or a duplicate candidate is rejected in full — never\n * partially resolved or silently cast — with a diagnostic explaining why.\n */\nexport function resolveModelRoles(\n\troles: ReadonlyMap<string, readonly string[]> | undefined,\n\tavailableModels: readonly Model<Api>[],\n): RoleResolutionResult {\n\tconst resolvedRoles = new Map<string, Model<Api>[]>();\n\tconst diagnostics: RoleResolutionDiagnostic[] = [];\n\tif (!roles) return { roles: resolvedRoles, diagnostics };\n\n\tconst models = [...availableModels];\n\tfor (const [roleName, references] of roles) {\n\t\tif (references.length === 0) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"empty-chain\",\n\t\t\t\troleName,\n\t\t\t\tmessage: `Role \"${roleName}\" has no model candidates.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst candidates: Model<Api>[] = [];\n\t\tconst seenKeys = new Set<string>();\n\t\tlet valid = true;\n\t\tfor (const reference of references) {\n\t\t\tconst match = findExactModelReferenceMatch(reference, models);\n\t\t\tif (!match) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"unknown-model\",\n\t\t\t\t\troleName,\n\t\t\t\t\treference,\n\t\t\t\t\tmessage: `Role \"${roleName}\" references unknown model \"${reference}\".`,\n\t\t\t\t});\n\t\t\t\tvalid = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst key = `${match.provider}/${match.id}`;\n\t\t\tif (seenKeys.has(key)) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"duplicate-candidate\",\n\t\t\t\t\troleName,\n\t\t\t\t\treference,\n\t\t\t\t\tmessage: `Role \"${roleName}\" lists model \"${key}\" more than once.`,\n\t\t\t\t});\n\t\t\t\tvalid = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenKeys.add(key);\n\t\t\tcandidates.push(match);\n\t\t}\n\t\tif (valid) resolvedRoles.set(roleName, candidates);\n\t}\n\treturn { roles: resolvedRoles, diagnostics };\n}\n\n/**\n * Restore model from session, with fallback to available models\n */\nexport async function restoreModelFromSession(\n\tsavedProvider: string,\n\tsavedModelId: string,\n\tcurrentModel: Model<Api> | undefined,\n\tshouldPrintMessages: boolean,\n\tmodelRuntime: ModelRuntime,\n): Promise<{ model: Model<Api> | undefined; fallbackMessage: string | undefined }> {\n\tconst restoredModel = modelRuntime.getModel(savedProvider, savedModelId);\n\n\t// Check if restored model exists and still has auth configured\n\tconst hasConfiguredAuth = restoredModel ? modelRuntime.hasConfiguredAuth(restoredModel.provider) : false;\n\n\tif (restoredModel && hasConfiguredAuth) {\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Restored model: ${savedProvider}/${savedModelId}`));\n\t\t}\n\t\treturn { model: restoredModel, fallbackMessage: undefined };\n\t}\n\n\t// Model not found or no API key - fall back\n\tconst reason = !restoredModel ? \"model no longer exists\" : \"no auth configured\";\n\n\tif (shouldPrintMessages) {\n\t\tconsole.error(chalk.yellow(`Warning: Could not restore model ${savedProvider}/${savedModelId} (${reason}).`));\n\t}\n\n\t// If we already have a model, use it as fallback\n\tif (currentModel) {\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Falling back to: ${currentModel.provider}/${currentModel.id}`));\n\t\t}\n\t\treturn {\n\t\t\tmodel: currentModel,\n\t\t\tfallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${currentModel.provider}/${currentModel.id}.`,\n\t\t};\n\t}\n\n\t// Try to find any available model\n\tconst availableModels = [...modelRuntime.getAvailableSnapshot()];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tlet fallbackModel: Model<Api> | undefined;\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\tfallbackModel = match;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\tif (!fallbackModel) {\n\t\t\tfallbackModel = availableModels[0];\n\t\t}\n\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Falling back to: ${fallbackModel.provider}/${fallbackModel.id}`));\n\t\t}\n\n\t\treturn {\n\t\t\tmodel: fallbackModel,\n\t\t\tfallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${fallbackModel.provider}/${fallbackModel.id}.`,\n\t\t};\n\t}\n\n\t// No models available\n\treturn { model: undefined, fallbackMessage: undefined };\n}\n"]}
@@ -1,5 +1,9 @@
1
1
  import { type Api, type AssistantMessage, type AssistantMessageEventStream, type AuthCheck, type AuthInteraction, type AuthOperationOptions, type AuthResult, type AuthType, type Context, type Credential, type CredentialInfo, type CredentialStore, type DeferredHandle, type Model, type Models, type ModelsApiStreamOptions, type ModelsDeferredCancelOptions, type ModelsDeferredFetchOptions, type ModelsRefreshOptions, type ModelsRefreshResult, type ModelsSimpleStreamOptions, type ModelsStore, type Provider } from "@earendil-works/pi-ai";
2
+ import type { CredentialIdentity, CredentialPool } from "./credential-pool.ts";
3
+ import { type RoleResolutionResult } from "./model-resolver.ts";
4
+ import { type OtlpExportConfig } from "./observability/otlp.ts";
2
5
  import { type AuthStatus, type CompatibilityRequestConfig, type ProviderConfigInput } from "./provider-composer.ts";
6
+ import type { UsagePerformanceSample, UsagePerformanceStore } from "./usage-performance-store.ts";
3
7
  export interface CreateModelRuntimeOptions {
4
8
  /** Credential storage. Defaults to the file at authPath. */
5
9
  credentials?: CredentialStore;
@@ -16,6 +20,28 @@ export interface CreateModelRuntimeOptions {
16
20
  signal?: AbortSignal;
17
21
  /** Skip initial catalog and availability refresh. Static models remain available. */
18
22
  refreshOnCreate?: boolean;
23
+ /**
24
+ * Optional pool for bounded, pre-completion credential failover in streamSimple().
25
+ * Providers with no entries in the pool keep single-credential auth resolution
26
+ * unchanged. Apex owns this pool adjacent to the consumed CredentialStore
27
+ * contract (one credential per provider); it is never itself a CredentialStore.
28
+ */
29
+ credentialPool?: CredentialPool;
30
+ /**
31
+ * Resolves the request-scoped auth override for a credential-pool selection.
32
+ * Required for pool entries to actually authenticate; an identity with no
33
+ * resolver entry falls back to the request's own apiKey/env options.
34
+ */
35
+ resolveCredentialPoolAuth?: (identity: CredentialIdentity) => {
36
+ apiKey?: string;
37
+ env?: Record<string, string>;
38
+ } | undefined;
39
+ /** Optional durable store for non-secret per-request usage/latency samples. Unset records nothing. */
40
+ usagePerformanceStore?: UsagePerformanceStore;
41
+ /** Monotonic clock for usage/latency timing. Defaults to performance.now(); inject a fake in tests. */
42
+ performanceClock?: () => number;
43
+ /** User-directed OTLP export target (roadmap Phase 8, ADR 0012). Unset: no export, no egress. */
44
+ otlpExportConfig?: OtlpExportConfig;
19
45
  }
20
46
  export interface ModelRuntimeAuthOverrides extends AuthOperationOptions {
21
47
  apiKey?: string;
@@ -49,6 +75,11 @@ export declare class ModelRuntime implements Models {
49
75
  private readonly providerAvailabilitySeq;
50
76
  private availabilityError;
51
77
  private readonly credentialOperations;
78
+ private readonly credentialPool;
79
+ private readonly resolveCredentialPoolAuth;
80
+ private readonly usagePerformanceStore;
81
+ private readonly performanceClock;
82
+ private readonly otlpExportConfig;
52
83
  private constructor();
53
84
  static create(options?: CreateModelRuntimeOptions): Promise<ModelRuntime>;
54
85
  private configureRadiusProviders;
@@ -63,6 +94,14 @@ export declare class ModelRuntime implements Models {
63
94
  getProvider(providerId: string): Provider | undefined;
64
95
  getModels(providerId?: string): readonly Model<Api>[];
65
96
  getModel(providerId: string, modelId: string): Model<Api> | undefined;
97
+ /**
98
+ * Resolve additive role configuration into ordered model-candidate chains.
99
+ * Credential-blind and side-effect free: it never resolves auth and never
100
+ * writes configuration. Legacy files with no `roles` resolve to an empty map,
101
+ * leaving initial model selection (`findInitialModel`, `resolveCliModel`)
102
+ * behaviorally unchanged.
103
+ */
104
+ resolveModelRoles(): RoleResolutionResult;
66
105
  checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined>;
67
106
  getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]>;
68
107
  getAvailableSnapshot(): readonly Model<Api>[];
@@ -87,6 +126,40 @@ export declare class ModelRuntime implements Models {
87
126
  stream<TApi extends Api>(model: Model<TApi>, context: Context, options?: ModelsApiStreamOptions<TApi>): AssistantMessageEventStream;
88
127
  complete<TApi extends Api>(model: Model<TApi>, context: Context, options?: ModelsApiStreamOptions<TApi>): Promise<AssistantMessage>;
89
128
  streamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream;
129
+ private attemptModel;
130
+ /**
131
+ * Wraps a provider attempt stream with usage/latency recording, pass-through
132
+ * (no buffering, so live streaming is unaffected). Recording is triggered by
133
+ * the terminal (done/error) event itself, synchronously before that event is
134
+ * yielded onward. This matters: a consumer's `.result()` promise can resolve
135
+ * the instant the terminal event reaches it — one iteration step before a
136
+ * plain post-loop "the generator finished" check would fire — so recording
137
+ * after the loop exits would race a caller awaiting `.result()` and lose.
138
+ * Relies on every call site fully iterating the returned stream (all current
139
+ * ones do, via drainAttempt or lazyStream's forwardStream).
140
+ */
141
+ /**
142
+ * Durable usage/cost/latency samples this runtime has recorded, if a store was
143
+ * configured. Read-only; callers query it (e.g. `aggregateUsagePerformance`)
144
+ * rather than this class exposing grouped views itself.
145
+ */
146
+ listUsagePerformanceSamples(): Promise<readonly UsagePerformanceSample[]>;
147
+ close(): void;
148
+ private instrumentAttempt;
149
+ private buildUsageSample;
150
+ /**
151
+ * Opt-in role-based resolution: attempt each of a role's ordered model
152
+ * candidates in turn, exhausting that candidate's credential pool (Task 1.3)
153
+ * before advancing. A model visits at most once; since each visited model
154
+ * gets its own fresh credential-attempt set, no (credential, model) pair
155
+ * repeats across the whole call. A non-retryable failure on any candidate is
156
+ * terminal for the whole call — model fallback never masks a non-retryable
157
+ * error. Explicit CLI/session model selection is unaffected: callers must
158
+ * opt into this method instead of streamSimple().
159
+ */
160
+ streamSimpleForRole(roleName: string, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream;
161
+ private attemptRole;
162
+ private streamSimpleWithCredentialFailover;
90
163
  completeSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage>;
91
164
  fetchDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredFetchOptions): Promise<AssistantMessage>;
92
165
  cancelDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredCancelOptions): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"model-runtime.d.ts","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,GAAG,EAER,KAAK,gBAAgB,EACrB,KAAK,2BAA2B,EAChC,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,eAAe,EAIpB,KAAK,cAAc,EAEnB,KAAK,KAA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GAAG,CAAC,EACjB,MAAM,EAAE,cAAc,EACtB,OAAO,CAAC,EAAE,0BAA0B,GAClC,OAAO,CAAC,gBAAgB,CAAC,CAQ3B;IAEK,cAAc,CACnB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,MAAM,EAAE,cAAc,EACtB,OAAO,CAAC,EAAE,2BAA2B,GACnC,OAAO,CAAC,IAAI,CAAC,CAMf;IAED,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,eAAe,GAAG,OAAO,CAAC,UAAU,CAAC,CAO3F;IAED,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC,CAM5E;IAEK,OAAO,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAyC9E;IAED,sBAAsB,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAO/C;IAED,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAoCtE;IAED,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAM3C;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthOperationOptions,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype ProviderRequestOptions,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n\t/** Optional caller cancellation for initial cache restoration and availability checks. */\n\tsignal?: AbortSignal;\n\t/** Skip initial catalog and availability refresh. Static models remain available. */\n\trefreshOnCreate?: boolean;\n}\n\nexport interface ModelRuntimeAuthOverrides extends AuthOperationOptions {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nexport type CredentialSynchronizationOperation = \"login\" | \"logout\" | \"setRuntimeApiKey\" | \"removeRuntimeApiKey\";\n\n/** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */\nexport class CredentialSynchronizationError extends Error {\n\treadonly providerId: string;\n\treadonly operation: CredentialSynchronizationOperation;\n\treadonly credential: Credential | undefined;\n\n\tconstructor(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\toptions: ErrorOptions,\n\t) {\n\t\tsuper(`Credential ${operation} committed for ${providerId}, but local synchronization failed`, options);\n\t\tthis.name = \"CredentialSynchronizationError\";\n\t\tthis.providerId = providerId;\n\t\tthis.operation = operation;\n\t\tthis.credential = credential;\n\t}\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefreshSeq = 0;\n\tprivate availabilityErrorSeq = 0;\n\tprivate readonly providerAvailabilitySeq = new Map<string, number>();\n\tprivate availabilityError: string | undefined;\n\tprivate readonly credentialOperations = new Map<string, Promise<unknown>>();\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.id === \"radius\"\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tprocess.env.PI_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller =\n\t\t\trefreshFromNetwork && options.modelRefreshTimeoutMs !== undefined ? new AbortController() : undefined;\n\t\tconst timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs) : undefined;\n\t\tconst signal = controller\n\t\t\t? options.signal\n\t\t\t\t? AbortSignal.any([options.signal, controller.signal])\n\t\t\t\t: controller.signal\n\t\t\t: options.signal;\n\t\ttry {\n\t\t\tif (options.refreshOnCreate !== false) {\n\t\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal });\n\t\t\t}\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(seq: number, errorSeq: number, signal: AbortSignal): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(undefined, { signal }),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id, { signal }),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list({ signal }),\n\t\t]);\n\t\tif (seq !== this.availabilityRefreshSeq) return;\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(signal?: AbortSignal): Promise<void> {\n\t\tconst seq = ++this.availabilityRefreshSeq;\n\t\tfor (const [providerId, providerSeq] of this.providerAvailabilitySeq) {\n\t\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq + 1);\n\t\t}\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\tconst effectiveSignal = operationSignal(signal);\n\t\treturn this.runAvailabilityRefresh(seq, errorSeq, effectiveSignal).catch((error) => {\n\t\t\tif (errorSeq === this.availabilityErrorSeq && !effectiveSignal.aborted) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t}\n\n\tprivate async refreshProviderAvailability(providerId: string, signal: AbortSignal): Promise<void> {\n\t\t// Invalidate any full availability pass that started before this credential change.\n\t\t++this.availabilityRefreshSeq;\n\t\tconst providerSeq = (this.providerAvailabilitySeq.get(providerId) ?? 0) + 1;\n\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq);\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\ttry {\n\t\t\tconst [available, auth, credential] = await Promise.all([\n\t\t\t\tthis.models.getAvailable(providerId, { signal }),\n\t\t\t\tthis.models.checkAuth(providerId, { signal }),\n\t\t\t\tthis.credentials.read(providerId, { signal }),\n\t\t\t]);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (this.providerAvailabilitySeq.get(providerId) !== providerSeq) return;\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders);\n\t\t\tconst storedProviders = new Set(this.snapshot.storedProviders);\n\t\t\tconst authByProvider = new Map(this.snapshot.auth);\n\t\t\tif (auth) {\n\t\t\t\tconfiguredProviders.add(providerId);\n\t\t\t\tauthByProvider.set(providerId, auth);\n\t\t\t} else {\n\t\t\t\tconfiguredProviders.delete(providerId);\n\t\t\t\tauthByProvider.delete(providerId);\n\t\t\t}\n\t\t\tif (credential) storedProviders.add(providerId);\n\t\t\telse storedProviders.delete(providerId);\n\t\t\tconst all = [...this.models.getModels()];\n\t\t\tconst availableById = new Map(\n\t\t\t\t[...this.snapshot.available.filter((model) => model.provider !== providerId), ...available].map((model) => [\n\t\t\t\t\t`${model.provider}\\0${model.id}`,\n\t\t\t\t\tmodel,\n\t\t\t\t]),\n\t\t\t);\n\t\t\tthis.snapshot = {\n\t\t\t\tall,\n\t\t\t\tavailable: all.flatMap((model) => availableById.get(`${model.provider}\\0${model.id}`) ?? []),\n\t\t\t\tconfiguredProviders,\n\t\t\t\tstoredProviders,\n\t\t\t\tauth: authByProvider,\n\t\t\t};\n\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tthis.providerAvailabilitySeq.get(providerId) === providerSeq &&\n\t\t\t\terrorSeq === this.availabilityErrorSeq &&\n\t\t\t\t!signal.aborted\n\t\t\t) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tasync checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId, options);\n\t}\n\n\tasync getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\t\ttry {\n\t\t\t\tconst available = await this.models.getAvailable(providerId, options);\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t\t\treturn available;\n\t\t\t} catch (error) {\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq && !options?.signal?.aborted) {\n\t\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.queueAvailabilityRefresh(options?.signal);\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\tisUsingSubscription(providerId: string): boolean {\n\t\treturn this.isUsingOAuth(providerId) && this.models.getProvider(providerId)?.auth.oauth?.isSubscription === true;\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model<Api>,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate enqueueCredentialOperation<T>(providerId: string, signal: AbortSignal, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.credentialOperations.get(providerId) ?? Promise.resolve();\n\t\tlet markStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkStarted = resolve;\n\t\t});\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\tmarkStarted?.();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = operation.catch(() => {});\n\t\tthis.credentialOperations.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.credentialOperations.get(providerId) === tail) this.credentialOperations.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(started, signal).then(() => operation);\n\t}\n\n\tprivate async synchronizeCredentialState(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.recomposeProvider(providerId);\n\t\t\tconst compositionError = this.compositionErrors.get(providerId);\n\t\t\tif (compositionError) throw new Error(compositionError);\n\t\t\tconst result = await this.models.refresh({ allowNetwork: false, providers: [providerId], signal });\n\t\t\tif (result.aborted) signal.throwIfAborted();\n\t\t\tconst refreshError = result.errors.get(providerId);\n\t\t\tif (refreshError) throw refreshError;\n\t\t\tthis.updateModelSnapshot();\n\t\t\tawait this.refreshProviderAvailability(providerId, signal);\n\t\t} catch (cause) {\n\t\t\tthrow new CredentialSynchronizationError(providerId, operation, credential, { cause });\n\t\t}\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\t\tawait this.synchronizeCredentialState(\n\t\t\t\tproviderId,\n\t\t\t\t\"setRuntimeApiKey\",\n\t\t\t\t{ type: \"api_key\", key: apiKey },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t});\n\t}\n\n\tremoveRuntimeApiKey(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"removeRuntimeApiKey\", undefined, signal);\n\t\t});\n\t}\n\n\tlistCredentials(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list(options);\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest<TOptions extends ProviderRequestOptions & ModelsRequestTransforms>(\n\t\tmodel: Model<Api>,\n\t\toptions: TOptions | undefined,\n\t): Promise<{\n\t\tprovider: Provider;\n\t\tmodel: Model<Api>;\n\t\toptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t}> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...rawProviderOptions } = options ?? {};\n\t\tconst providerOptions = rawProviderOptions as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t} as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions,\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsRequestTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\tcontext,\n\t\t\t\tprepared.options as ApiStreamOptions<TApi>,\n\t\t\t);\n\t\t});\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\treturn prepared.provider.streamSimple(prepared.model, context, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\treturn prepared.provider.fetchDeferred(prepared.model, handle, prepared.options as DeferredFetchOptions);\n\t\t}).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tconst prepared = await this.prepareRequest(model, options);\n\t\tif (!prepared.provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tawait prepared.provider.cancelDeferred(prepared.model, handle, prepared.options as DeferredCancelOptions);\n\t}\n\n\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tconst credential = await this.models.login(providerId, type, { ...interaction, signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"login\", credential, signal);\n\t\t\treturn credential;\n\t\t});\n\t}\n\n\tlogout(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tawait this.models.logout(providerId, { signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"logout\", undefined, signal);\n\t\t});\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tif (options.providers) {\n\t\t\tfor (const providerId of new Set(options.providers)) this.recomposeProvider(providerId);\n\t\t\tthis.updateModelSnapshot();\n\t\t} else {\n\t\t\tthis.rebuildProviders();\n\t\t}\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tconst errors = new Map(result.errors);\n\t\tthis.updateModelSnapshot();\n\t\tif (options.providers) {\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(options.providers)].map(async (providerId) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.refreshProviderAvailability(providerId, operationSignal(options.signal));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!options.signal?.aborted) {\n\t\t\t\t\t\t\terrors.set(providerId, error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.queueAvailabilityRefresh(options.signal);\n\t\t\t} catch {\n\t\t\t\t// Availability errors are recorded by the latest pass; refreshed models remain usable.\n\t\t\t}\n\t\t}\n\t\treturn { aborted: result.aborted || (options.signal?.aborted ?? false), errors };\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
1
+ {"version":3,"file":"model-runtime.d.ts","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,GAAG,EAER,KAAK,gBAAgB,EAErB,KAAK,2BAA2B,EAChC,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,eAAe,EAKpB,KAAK,cAAc,EAEnB,KAAK,KAAK,EACV,KAAK,MAAM,EACX,KAAK,sBAAsB,EAC3B,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAE/B,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EAExB,KAAK,yBAAyB,EAC9B,KAAK,WAAW,EAEhB,KAAK,QAAQ,EAKb,MAAM,uBAAuB,CAAC;AAY/B,OAAO,KAAK,EAAyB,kBAAkB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtG,OAAO,EAAE,KAAK,oBAAoB,EAAqB,MAAM,qBAAqB,CAAC;AAEnF,OAAO,EAAyB,KAAK,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACvF,OAAO,EACN,KAAK,UAAU,EACf,KAAK,0BAA0B,EAG/B,KAAK,mBAAmB,EAIxB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,KAAK,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAUlG,MAAM,WAAW,yBAAyB;IACzC,4DAA4D;IAC5D,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,Q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CAyC9E;IAED,sBAAsB,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAO/C;IAED,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAoCtE;IAED,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAM3C;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthOperationOptions,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateAssistantMessageEventStream,\n\tcreateModels,\n\ttype DeferredCancelOptions,\n\ttype DeferredFetchOptions,\n\ttype DeferredHandle,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\ttype ModelsDeferredCancelOptions,\n\ttype ModelsDeferredFetchOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsRequestTransforms,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype ProviderRequestOptions,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport {\n\tclassifyCredentialFailure,\n\ttype DrainedAttempt,\n\tdrainAttempt,\n\ttype ResultStream,\n\treplayAttempt,\n} from \"./credential-failover.ts\";\nimport type { CredentialFailureKind, CredentialIdentity, CredentialPool } from \"./credential-pool.ts\";\nimport { getApexEnvironment } from \"./environment.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { type RoleResolutionResult, resolveModelRoles } from \"./model-resolver.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport { exportUsageSampleSpan, type OtlpExportConfig } from \"./observability/otlp.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\nimport type { UsagePerformanceSample, UsagePerformanceStore } from \"./usage-performance-store.ts\";\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n\t/** Optional caller cancellation for initial cache restoration and availability checks. */\n\tsignal?: AbortSignal;\n\t/** Skip initial catalog and availability refresh. Static models remain available. */\n\trefreshOnCreate?: boolean;\n\t/**\n\t * Optional pool for bounded, pre-completion credential failover in streamSimple().\n\t * Providers with no entries in the pool keep single-credential auth resolution\n\t * unchanged. Apex owns this pool adjacent to the consumed CredentialStore\n\t * contract (one credential per provider); it is never itself a CredentialStore.\n\t */\n\tcredentialPool?: CredentialPool;\n\t/**\n\t * Resolves the request-scoped auth override for a credential-pool selection.\n\t * Required for pool entries to actually authenticate; an identity with no\n\t * resolver entry falls back to the request's own apiKey/env options.\n\t */\n\tresolveCredentialPoolAuth?: (\n\t\tidentity: CredentialIdentity,\n\t) => { apiKey?: string; env?: Record<string, string> } | undefined;\n\t/** Optional durable store for non-secret per-request usage/latency samples. Unset records nothing. */\n\tusagePerformanceStore?: UsagePerformanceStore;\n\t/** Monotonic clock for usage/latency timing. Defaults to performance.now(); inject a fake in tests. */\n\tperformanceClock?: () => number;\n\t/** User-directed OTLP export target (roadmap Phase 8, ADR 0012). Unset: no export, no egress. */\n\totlpExportConfig?: OtlpExportConfig;\n}\n\nexport interface ModelRuntimeAuthOverrides extends AuthOperationOptions {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nexport type CredentialSynchronizationOperation = \"login\" | \"logout\" | \"setRuntimeApiKey\" | \"removeRuntimeApiKey\";\n\n/** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */\nexport class CredentialSynchronizationError extends Error {\n\treadonly providerId: string;\n\treadonly operation: CredentialSynchronizationOperation;\n\treadonly credential: Credential | undefined;\n\n\tconstructor(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\toptions: ErrorOptions,\n\t) {\n\t\tsuper(`Credential ${operation} committed for ${providerId}, but local synchronization failed`, options);\n\t\tthis.name = \"CredentialSynchronizationError\";\n\t\tthis.providerId = providerId;\n\t\tthis.operation = operation;\n\t\tthis.credential = credential;\n\t}\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefreshSeq = 0;\n\tprivate availabilityErrorSeq = 0;\n\tprivate readonly providerAvailabilitySeq = new Map<string, number>();\n\tprivate availabilityError: string | undefined;\n\tprivate readonly credentialOperations = new Map<string, Promise<unknown>>();\n\tprivate readonly credentialPool: CredentialPool | undefined;\n\tprivate readonly resolveCredentialPoolAuth:\n\t\t| ((identity: CredentialIdentity) => { apiKey?: string; env?: Record<string, string> } | undefined)\n\t\t| undefined;\n\tprivate readonly usagePerformanceStore: UsagePerformanceStore | undefined;\n\tprivate readonly performanceClock: () => number;\n\tprivate readonly otlpExportConfig: OtlpExportConfig | undefined;\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t\tcredentialPool?: CredentialPool,\n\t\tresolveCredentialPoolAuth?: (\n\t\t\tidentity: CredentialIdentity,\n\t\t) => { apiKey?: string; env?: Record<string, string> } | undefined,\n\t\tusagePerformanceStore?: UsagePerformanceStore,\n\t\tperformanceClock?: () => number,\n\t\totlpExportConfig?: OtlpExportConfig,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.credentialPool = credentialPool;\n\t\tthis.resolveCredentialPoolAuth = resolveCredentialPoolAuth;\n\t\tthis.usagePerformanceStore = usagePerformanceStore;\n\t\tthis.performanceClock = performanceClock ?? (() => performance.now());\n\t\tthis.otlpExportConfig = otlpExportConfig;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst catalogBaseUrl = (options.catalogBaseUrl ?? getApexEnvironment(\"APEX_CODE_MODEL_CATALOG_URL\"))?.trim();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.id === \"radius\" || !catalogBaseUrl\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tgetApexEnvironment(\"APEX_CODE_OFFLINE\") === undefined,\n\t\t\toptions.credentialPool,\n\t\t\toptions.resolveCredentialPoolAuth,\n\t\t\toptions.usagePerformanceStore,\n\t\t\toptions.performanceClock,\n\t\t\toptions.otlpExportConfig,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller =\n\t\t\trefreshFromNetwork && options.modelRefreshTimeoutMs !== undefined ? new AbortController() : undefined;\n\t\tconst timeout = controller ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs) : undefined;\n\t\tconst signal = controller\n\t\t\t? options.signal\n\t\t\t\t? AbortSignal.any([options.signal, controller.signal])\n\t\t\t\t: controller.signal\n\t\t\t: options.signal;\n\t\ttry {\n\t\t\tif (options.refreshOnCreate !== false) {\n\t\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal });\n\t\t\t}\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(seq: number, errorSeq: number, signal: AbortSignal): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(undefined, { signal }),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id, { signal }),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list({ signal }),\n\t\t]);\n\t\tif (seq !== this.availabilityRefreshSeq) return;\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(signal?: AbortSignal): Promise<void> {\n\t\tconst seq = ++this.availabilityRefreshSeq;\n\t\tfor (const [providerId, providerSeq] of this.providerAvailabilitySeq) {\n\t\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq + 1);\n\t\t}\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\tconst effectiveSignal = operationSignal(signal);\n\t\treturn this.runAvailabilityRefresh(seq, errorSeq, effectiveSignal).catch((error) => {\n\t\t\tif (errorSeq === this.availabilityErrorSeq && !effectiveSignal.aborted) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t}\n\n\tprivate async refreshProviderAvailability(providerId: string, signal: AbortSignal): Promise<void> {\n\t\t// Invalidate any full availability pass that started before this credential change.\n\t\t++this.availabilityRefreshSeq;\n\t\tconst providerSeq = (this.providerAvailabilitySeq.get(providerId) ?? 0) + 1;\n\t\tthis.providerAvailabilitySeq.set(providerId, providerSeq);\n\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\ttry {\n\t\t\tconst [available, auth, credential] = await Promise.all([\n\t\t\t\tthis.models.getAvailable(providerId, { signal }),\n\t\t\t\tthis.models.checkAuth(providerId, { signal }),\n\t\t\t\tthis.credentials.read(providerId, { signal }),\n\t\t\t]);\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (this.providerAvailabilitySeq.get(providerId) !== providerSeq) return;\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders);\n\t\t\tconst storedProviders = new Set(this.snapshot.storedProviders);\n\t\t\tconst authByProvider = new Map(this.snapshot.auth);\n\t\t\tif (auth) {\n\t\t\t\tconfiguredProviders.add(providerId);\n\t\t\t\tauthByProvider.set(providerId, auth);\n\t\t\t} else {\n\t\t\t\tconfiguredProviders.delete(providerId);\n\t\t\t\tauthByProvider.delete(providerId);\n\t\t\t}\n\t\t\tif (credential) storedProviders.add(providerId);\n\t\t\telse storedProviders.delete(providerId);\n\t\t\tconst all = [...this.models.getModels()];\n\t\t\tconst availableById = new Map(\n\t\t\t\t[...this.snapshot.available.filter((model) => model.provider !== providerId), ...available].map((model) => [\n\t\t\t\t\t`${model.provider}\\0${model.id}`,\n\t\t\t\t\tmodel,\n\t\t\t\t]),\n\t\t\t);\n\t\t\tthis.snapshot = {\n\t\t\t\tall,\n\t\t\t\tavailable: all.flatMap((model) => availableById.get(`${model.provider}\\0${model.id}`) ?? []),\n\t\t\t\tconfiguredProviders,\n\t\t\t\tstoredProviders,\n\t\t\t\tauth: authByProvider,\n\t\t\t};\n\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\tthis.providerAvailabilitySeq.get(providerId) === providerSeq &&\n\t\t\t\terrorSeq === this.availabilityErrorSeq &&\n\t\t\t\t!signal.aborted\n\t\t\t) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\t/**\n\t * Resolve additive role configuration into ordered model-candidate chains.\n\t * Credential-blind and side-effect free: it never resolves auth and never\n\t * writes configuration. Legacy files with no `roles` resolve to an empty map,\n\t * leaving initial model selection (`findInitialModel`, `resolveCliModel`)\n\t * behaviorally unchanged.\n\t */\n\tresolveModelRoles(): RoleResolutionResult {\n\t\treturn resolveModelRoles(this.config.getRoles(), this.getModels());\n\t}\n\n\tasync checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId, options);\n\t}\n\n\tasync getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tconst errorSeq = ++this.availabilityErrorSeq;\n\t\t\ttry {\n\t\t\t\tconst available = await this.models.getAvailable(providerId, options);\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq) this.availabilityError = undefined;\n\t\t\t\treturn available;\n\t\t\t} catch (error) {\n\t\t\t\tif (errorSeq === this.availabilityErrorSeq && !options?.signal?.aborted) {\n\t\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.queueAvailabilityRefresh(options?.signal);\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\tisUsingSubscription(providerId: string): boolean {\n\t\treturn this.isUsingOAuth(providerId) && this.models.getProvider(providerId)?.auth.oauth?.isSubscription === true;\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model<Api>,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate enqueueCredentialOperation<T>(providerId: string, signal: AbortSignal, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.credentialOperations.get(providerId) ?? Promise.resolve();\n\t\tlet markStarted: (() => void) | undefined;\n\t\tconst started = new Promise<void>((resolve) => {\n\t\t\tmarkStarted = resolve;\n\t\t});\n\t\tconst operation = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\tmarkStarted?.();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = operation.catch(() => {});\n\t\tthis.credentialOperations.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.credentialOperations.get(providerId) === tail) this.credentialOperations.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(started, signal).then(() => operation);\n\t}\n\n\tprivate async synchronizeCredentialState(\n\t\tproviderId: string,\n\t\toperation: CredentialSynchronizationOperation,\n\t\tcredential: Credential | undefined,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.recomposeProvider(providerId);\n\t\t\tconst compositionError = this.compositionErrors.get(providerId);\n\t\t\tif (compositionError) throw new Error(compositionError);\n\t\t\tconst result = await this.models.refresh({ allowNetwork: false, providers: [providerId], signal });\n\t\t\tif (result.aborted) signal.throwIfAborted();\n\t\t\tconst refreshError = result.errors.get(providerId);\n\t\t\tif (refreshError) throw refreshError;\n\t\t\tthis.updateModelSnapshot();\n\t\t\tawait this.refreshProviderAvailability(providerId, signal);\n\t\t} catch (cause) {\n\t\t\tthrow new CredentialSynchronizationError(providerId, operation, credential, { cause });\n\t\t}\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\t\tawait this.synchronizeCredentialState(\n\t\t\t\tproviderId,\n\t\t\t\t\"setRuntimeApiKey\",\n\t\t\t\t{ type: \"api_key\", key: apiKey },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t});\n\t}\n\n\tremoveRuntimeApiKey(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\t\tawait this.synchronizeCredentialState(providerId, \"removeRuntimeApiKey\", undefined, signal);\n\t\t});\n\t}\n\n\tlistCredentials(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list(options);\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest<TOptions extends ProviderRequestOptions & ModelsRequestTransforms>(\n\t\tmodel: Model<Api>,\n\t\toptions: TOptions | undefined,\n\t): Promise<{\n\t\tprovider: Provider;\n\t\tmodel: Model<Api>;\n\t\toptions: Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t}> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, {\n\t\t\tapiKey: options?.apiKey,\n\t\t\tenv: options?.env,\n\t\t\tsignal: options?.signal,\n\t\t});\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...rawProviderOptions } = options ?? {};\n\t\tconst providerOptions = rawProviderOptions as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions;\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t} as Omit<TOptions, \"transformHeaders\"> & ProviderRequestOptions,\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsRequestTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\tcontext,\n\t\t\t\tprepared.options as ApiStreamOptions<TApi>,\n\t\t\t);\n\t\t});\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, () => this.attemptModel(model, context, options, undefined));\n\t}\n\n\t/** One model attempt: pool-based credential failover when configured, single-credential resolution otherwise. */\n\tprivate async attemptModel(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: ModelsSimpleStreamOptions | undefined,\n\t\trole: string | undefined,\n\t): Promise<ResultStream> {\n\t\tconst pool = this.credentialPool;\n\t\tif (pool?.snapshot().some((entry) => entry.providerId === model.provider)) {\n\t\t\treturn this.streamSimpleWithCredentialFailover(pool, model, context, options, role);\n\t\t}\n\t\tconst prepared = await this.prepareRequest(model, options);\n\t\tconst attemptStream = prepared.provider.streamSimple(\n\t\t\tprepared.model,\n\t\t\tcontext,\n\t\t\tprepared.options as SimpleStreamOptions,\n\t\t) as ResultStream;\n\t\treturn this.instrumentAttempt(attemptStream, model, role, undefined);\n\t}\n\n\t/**\n\t * Wraps a provider attempt stream with usage/latency recording, pass-through\n\t * (no buffering, so live streaming is unaffected). Recording is triggered by\n\t * the terminal (done/error) event itself, synchronously before that event is\n\t * yielded onward. This matters: a consumer's `.result()` promise can resolve\n\t * the instant the terminal event reaches it — one iteration step before a\n\t * plain post-loop \"the generator finished\" check would fire — so recording\n\t * after the loop exits would race a caller awaiting `.result()` and lose.\n\t * Relies on every call site fully iterating the returned stream (all current\n\t * ones do, via drainAttempt or lazyStream's forwardStream).\n\t */\n\t/**\n\t * Durable usage/cost/latency samples this runtime has recorded, if a store was\n\t * configured. Read-only; callers query it (e.g. `aggregateUsagePerformance`)\n\t * rather than this class exposing grouped views itself.\n\t */\n\tasync listUsagePerformanceSamples(): Promise<readonly UsagePerformanceSample[]> {\n\t\treturn this.usagePerformanceStore ? await this.usagePerformanceStore.list() : [];\n\t}\n\n\tclose(): void {\n\t\tthis.usagePerformanceStore?.close?.();\n\t}\n\n\tprivate instrumentAttempt(\n\t\tstream: ResultStream,\n\t\tmodel: Model<Api>,\n\t\trole: string | undefined,\n\t\tcredentialIdentity: CredentialIdentity | undefined,\n\t): ResultStream {\n\t\tconst store = this.usagePerformanceStore;\n\t\tconst otlpConfig = this.otlpExportConfig;\n\t\tif (!store && !otlpConfig) return stream;\n\t\tconst now = this.performanceClock;\n\t\tconst startedAt = now();\n\t\tconst self = this;\n\t\treturn {\n\t\t\tasync *[Symbol.asyncIterator]() {\n\t\t\t\tlet firstEventAt: number | undefined;\n\t\t\t\tfor await (const event of stream) {\n\t\t\t\t\tif (firstEventAt === undefined) firstEventAt = now();\n\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") {\n\t\t\t\t\t\tconst completedAt = now();\n\t\t\t\t\t\tconst message = event.type === \"done\" ? event.message : event.error;\n\t\t\t\t\t\tconst sample = self.buildUsageSample(model, role, credentialIdentity, message, {\n\t\t\t\t\t\t\tstartedAt,\n\t\t\t\t\t\t\tfirstEventAt: firstEventAt ?? completedAt,\n\t\t\t\t\t\t\tcompletedAt,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (store) void store.record(sample).catch(() => {});\n\t\t\t\t\t\tif (otlpConfig) void exportUsageSampleSpan(sample, otlpConfig);\n\t\t\t\t\t}\n\t\t\t\t\tyield event;\n\t\t\t\t}\n\t\t\t},\n\t\t\tresult: () => stream.result(),\n\t\t};\n\t}\n\n\tprivate buildUsageSample(\n\t\tmodel: Model<Api>,\n\t\trole: string | undefined,\n\t\tcredentialIdentity: CredentialIdentity | undefined,\n\t\tmessage: AssistantMessage,\n\t\ttiming: { startedAt: number; firstEventAt: number; completedAt: number },\n\t): UsagePerformanceSample {\n\t\tconst outcome: UsagePerformanceSample[\"outcome\"] =\n\t\t\tmessage.stopReason === \"aborted\" ? \"aborted\" : message.stopReason === \"error\" ? \"error\" : \"success\";\n\t\tconst failureKind: CredentialFailureKind | undefined =\n\t\t\toutcome === \"error\" ? classifyCredentialFailure(message) : undefined;\n\t\treturn {\n\t\t\ttimestamp: Date.now(),\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\trole,\n\t\t\tcredentialIdentity,\n\t\t\toutcome,\n\t\t\tfailureKind,\n\t\t\tttftMs: timing.firstEventAt - timing.startedAt,\n\t\t\tgenerationMs: timing.completedAt - timing.firstEventAt,\n\t\t\tusage: message.usage\n\t\t\t\t? {\n\t\t\t\t\t\tinput: message.usage.input,\n\t\t\t\t\t\toutput: message.usage.output,\n\t\t\t\t\t\tcacheRead: message.usage.cacheRead,\n\t\t\t\t\t\tcacheWrite: message.usage.cacheWrite,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tcost: message.usage?.cost.total,\n\t\t};\n\t}\n\n\t/**\n\t * Opt-in role-based resolution: attempt each of a role's ordered model\n\t * candidates in turn, exhausting that candidate's credential pool (Task 1.3)\n\t * before advancing. A model visits at most once; since each visited model\n\t * gets its own fresh credential-attempt set, no (credential, model) pair\n\t * repeats across the whole call. A non-retryable failure on any candidate is\n\t * terminal for the whole call — model fallback never masks a non-retryable\n\t * error. Explicit CLI/session model selection is unaffected: callers must\n\t * opt into this method instead of streamSimple().\n\t */\n\tstreamSimpleForRole(\n\t\troleName: string,\n\t\tcontext: Context,\n\t\toptions?: ModelsSimpleStreamOptions,\n\t): AssistantMessageEventStream {\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tthis.attemptRole(roleName, context, options)\n\t\t\t.then((drained) => {\n\t\t\t\tfor (const event of drained.events) outer.push(event);\n\t\t\t\touter.end(drained.message);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tconst message: AssistantMessage = {\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: [],\n\t\t\t\t\tapi: \"role\",\n\t\t\t\t\tprovider: \"role\",\n\t\t\t\t\tmodel: roleName,\n\t\t\t\t\tusage: {\n\t\t\t\t\t\tinput: 0,\n\t\t\t\t\t\toutput: 0,\n\t\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t\t},\n\t\t\t\t\tstopReason: \"error\",\n\t\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t};\n\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\touter.end(message);\n\t\t\t});\n\t\treturn outer;\n\t}\n\n\tprivate async attemptRole(\n\t\troleName: string,\n\t\tcontext: Context,\n\t\toptions: ModelsSimpleStreamOptions | undefined,\n\t): Promise<{ events: readonly AssistantMessageEvent[]; message: AssistantMessage }> {\n\t\tconst { roles } = this.resolveModelRoles();\n\t\tconst candidates = roles.get(roleName);\n\t\tif (!candidates || candidates.length === 0) {\n\t\t\tthrow new ModelsError(\"model_source\", `Unknown or unresolved role: ${roleName}`);\n\t\t}\n\n\t\tlet originalFailure: DrainedAttempt | undefined;\n\t\tfor (const candidate of candidates) {\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst attemptStream = await this.attemptModel(candidate, context, options, roleName);\n\t\t\tconst drained = await drainAttempt(attemptStream);\n\t\t\tif (drained.message.stopReason !== \"error\") return drained;\n\t\t\tif (!originalFailure) originalFailure = drained;\n\t\t\t// Non-retryable (or aborted) is terminal for the whole role: model fallback\n\t\t\t// never masks an error rotation itself already declined to retry.\n\t\t\tif (!classifyCredentialFailure(drained.message)) return drained;\n\t\t}\n\t\t// originalFailure is always set here: candidates is non-empty, so the loop\n\t\t// ran at least once, and every path that returns early also sets it first.\n\t\treturn originalFailure as DrainedAttempt;\n\t}\n\n\t/**\n\t * Bounded, pre-completion credential failover: each attempt is fully drained\n\t * before any event reaches the caller, so a rotated-away attempt is invisible\n\t * to it. A turn visits each (credential identity, this model) at most once.\n\t * Only a classified rate-limit/blocked/transient failure advances the chain;\n\t * on exhaustion the original (first) failure is rethrown, not the last one.\n\t */\n\tprivate async streamSimpleWithCredentialFailover(\n\t\tpool: CredentialPool,\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: ModelsSimpleStreamOptions | undefined,\n\t\trole: string | undefined,\n\t): Promise<ResultStream> {\n\t\tconst attempted = new Set<CredentialIdentity>();\n\t\tlet originalFailure: ResultStream | undefined;\n\n\t\tfor (;;) {\n\t\t\toptions?.signal?.throwIfAborted();\n\t\t\tconst selection = pool.select({ providerId: model.provider, attempted });\n\t\t\tif (!selection) {\n\t\t\t\tif (originalFailure) return originalFailure;\n\t\t\t\t// Pool configured for this provider but nothing currently eligible\n\t\t\t\t// (e.g. every entry cooling down): fall back to default auth resolution\n\t\t\t\t// so the caller still gets a real attempt instead of a silent no-op.\n\t\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\t\tconst fallbackStream = prepared.provider.streamSimple(\n\t\t\t\t\tprepared.model,\n\t\t\t\t\tcontext,\n\t\t\t\t\tprepared.options as SimpleStreamOptions,\n\t\t\t\t) as ResultStream;\n\t\t\t\treturn this.instrumentAttempt(fallbackStream, model, role, undefined);\n\t\t\t}\n\t\t\tattempted.add(selection.identity);\n\n\t\t\tconst auth = this.resolveCredentialPoolAuth?.(selection.identity);\n\t\t\tconst prepared = await this.prepareRequest(model, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth?.apiKey ?? options?.apiKey,\n\t\t\t\tenv: auth?.env ?? options?.env,\n\t\t\t});\n\t\t\tconst attemptStream = this.instrumentAttempt(\n\t\t\t\tprepared.provider.streamSimple(\n\t\t\t\t\tprepared.model,\n\t\t\t\t\tcontext,\n\t\t\t\t\tprepared.options as SimpleStreamOptions,\n\t\t\t\t) as ResultStream,\n\t\t\t\tmodel,\n\t\t\t\trole,\n\t\t\t\tselection.identity,\n\t\t\t);\n\t\t\tconst drained = await drainAttempt(attemptStream);\n\n\t\t\tconst kind = classifyCredentialFailure(drained.message);\n\t\t\tif (!kind) return replayAttempt(drained);\n\n\t\t\tpool.recordFailure({ identity: selection.identity, kind });\n\t\t\tif (!originalFailure) originalFailure = replayAttempt(drained);\n\t\t}\n\t}\n\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tasync fetchDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): Promise<AssistantMessage> {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\tif (!prepared.provider.fetchDeferred) {\n\t\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t\t}\n\t\t\treturn prepared.provider.fetchDeferred(prepared.model, handle, prepared.options as DeferredFetchOptions);\n\t\t}).result();\n\t}\n\n\tasync cancelDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredCancelOptions,\n\t): Promise<void> {\n\t\tconst prepared = await this.prepareRequest(model, options);\n\t\tif (!prepared.provider.cancelDeferred) {\n\t\t\tthrow new ModelsError(\"provider\", `Provider ${model.provider} does not support deferred responses`);\n\t\t}\n\t\tawait prepared.provider.cancelDeferred(prepared.model, handle, prepared.options as DeferredCancelOptions);\n\t}\n\n\tlogin(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst signal = operationSignal(interaction.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tconst credential = await this.models.login(providerId, type, { ...interaction, signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"login\", credential, signal);\n\t\t\treturn credential;\n\t\t});\n\t}\n\n\tlogout(providerId: string, options: AuthOperationOptions = {}): Promise<void> {\n\t\tconst signal = operationSignal(options.signal);\n\t\treturn this.enqueueCredentialOperation(providerId, signal, async () => {\n\t\t\tawait this.models.logout(providerId, { signal });\n\t\t\tawait this.synchronizeCredentialState(providerId, \"logout\", undefined, signal);\n\t\t});\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tif (options.providers) {\n\t\t\tfor (const providerId of new Set(options.providers)) this.recomposeProvider(providerId);\n\t\t\tthis.updateModelSnapshot();\n\t\t} else {\n\t\t\tthis.rebuildProviders();\n\t\t}\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tconst errors = new Map(result.errors);\n\t\tthis.updateModelSnapshot();\n\t\tif (options.providers) {\n\t\t\tawait Promise.all(\n\t\t\t\t[...new Set(options.providers)].map(async (providerId) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.refreshProviderAvailability(providerId, operationSignal(options.signal));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!options.signal?.aborted) {\n\t\t\t\t\t\t\terrors.set(providerId, error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tawait this.queueAvailabilityRefresh(options.signal);\n\t\t\t} catch {\n\t\t\t\t// Availability errors are recorded by the latest pass; refreshed models remain usable.\n\t\t\t}\n\t\t}\n\t\treturn { aborted: result.aborted || (options.signal?.aborted ?? false), errors };\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}