apex-code 0.0.1-alpha.1 → 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,11 +1,15 @@
1
1
  import { dirname, join } from "node:path";
2
- import { createModels, lazyStream, ModelsError, } from "@earendil-works/pi-ai";
2
+ import { createAssistantMessageEventStream, createModels, lazyStream, ModelsError, } from "@earendil-works/pi-ai";
3
3
  import * as builtinProviderCatalog from "@earendil-works/pi-ai/providers/all";
4
4
  import { getAgentDir } from "../config.js";
5
5
  import { operationSignal, raceWithAbortSignal } from "../utils/abort.js";
6
6
  import { AuthStorage as DefaultAuthStorage } from "./auth-storage.js";
7
+ import { classifyCredentialFailure, drainAttempt, replayAttempt, } from "./credential-failover.js";
8
+ import { getApexEnvironment } from "./environment.js";
7
9
  import { ModelConfig } from "./model-config.js";
10
+ import { resolveModelRoles } from "./model-resolver.js";
8
11
  import { FileModelsStore, InMemoryCodingAgentModelsStore } from "./models-store.js";
12
+ import { exportUsageSampleSpan } from "./observability/otlp.js";
9
13
  import { composeModelProvider, configuredRequestAuthStatus, resolveCompatibilityRequestConfig, resolveConfiguredModelHeaders, validateExtensionProvider, } from "./provider-composer.js";
10
14
  import { withRemoteCatalog } from "./remote-catalog-provider.js";
11
15
  import { RuntimeCredentials } from "./runtime-credentials.js";
@@ -60,11 +64,21 @@ export class ModelRuntime {
60
64
  providerAvailabilitySeq = new Map();
61
65
  availabilityError;
62
66
  credentialOperations = new Map();
63
- constructor(credentials, config, modelsPath, modelsStore, providers, modelNetworkEnabled) {
67
+ credentialPool;
68
+ resolveCredentialPoolAuth;
69
+ usagePerformanceStore;
70
+ performanceClock;
71
+ otlpExportConfig;
72
+ constructor(credentials, config, modelsPath, modelsStore, providers, modelNetworkEnabled, credentialPool, resolveCredentialPoolAuth, usagePerformanceStore, performanceClock, otlpExportConfig) {
64
73
  this.credentials = credentials;
65
74
  this.config = config;
66
75
  this.modelsPath = modelsPath;
67
76
  this.modelNetworkEnabled = modelNetworkEnabled;
77
+ this.credentialPool = credentialPool;
78
+ this.resolveCredentialPoolAuth = resolveCredentialPoolAuth;
79
+ this.usagePerformanceStore = usagePerformanceStore;
80
+ this.performanceClock = performanceClock ?? (() => performance.now());
81
+ this.otlpExportConfig = otlpExportConfig;
68
82
  this.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));
69
83
  for (const [providerId, provider] of this.defaultBuiltins)
70
84
  this.builtins.set(providerId, provider);
@@ -80,12 +94,13 @@ export class ModelRuntime {
80
94
  ? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), "models-store.json"))
81
95
  : new InMemoryCodingAgentModelsStore());
82
96
  const builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();
97
+ const catalogBaseUrl = (options.catalogBaseUrl ?? getApexEnvironment("APEX_CODE_MODEL_CATALOG_URL"))?.trim();
83
98
  const providers = builtinProviderCatalog
84
99
  .builtinProviders()
85
- .map((provider) => provider.id === "radius"
100
+ .map((provider) => provider.id === "radius" || !catalogBaseUrl
86
101
  ? provider
87
- : withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt));
88
- const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers, process.env.PI_OFFLINE === undefined);
102
+ : withRemoteCatalog(provider, catalogBaseUrl, builtinModelDataGeneratedAt));
103
+ const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers, getApexEnvironment("APEX_CODE_OFFLINE") === undefined, options.credentialPool, options.resolveCredentialPoolAuth, options.usagePerformanceStore, options.performanceClock, options.otlpExportConfig);
89
104
  runtime.configureRadiusProviders();
90
105
  runtime.rebuildProviders();
91
106
  const refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;
@@ -277,6 +292,16 @@ export class ModelRuntime {
277
292
  getModel(providerId, modelId) {
278
293
  return this.models.getModel(providerId, modelId);
279
294
  }
295
+ /**
296
+ * Resolve additive role configuration into ordered model-candidate chains.
297
+ * Credential-blind and side-effect free: it never resolves auth and never
298
+ * writes configuration. Legacy files with no `roles` resolve to an empty map,
299
+ * leaving initial model selection (`findInitialModel`, `resolveCliModel`)
300
+ * behaviorally unchanged.
301
+ */
302
+ resolveModelRoles() {
303
+ return resolveModelRoles(this.config.getRoles(), this.getModels());
304
+ }
280
305
  async checkAuth(providerId, options) {
281
306
  return this.models.checkAuth(providerId, options);
282
307
  }
@@ -459,10 +484,202 @@ export class ModelRuntime {
459
484
  return this.stream(model, context, options).result();
460
485
  }
461
486
  streamSimple(model, context, options) {
462
- return lazyStream(model, async () => {
463
- const prepared = await this.prepareRequest(model, options);
464
- return prepared.provider.streamSimple(prepared.model, context, prepared.options);
487
+ return lazyStream(model, () => this.attemptModel(model, context, options, undefined));
488
+ }
489
+ /** One model attempt: pool-based credential failover when configured, single-credential resolution otherwise. */
490
+ async attemptModel(model, context, options, role) {
491
+ const pool = this.credentialPool;
492
+ if (pool?.snapshot().some((entry) => entry.providerId === model.provider)) {
493
+ return this.streamSimpleWithCredentialFailover(pool, model, context, options, role);
494
+ }
495
+ const prepared = await this.prepareRequest(model, options);
496
+ const attemptStream = prepared.provider.streamSimple(prepared.model, context, prepared.options);
497
+ return this.instrumentAttempt(attemptStream, model, role, undefined);
498
+ }
499
+ /**
500
+ * Wraps a provider attempt stream with usage/latency recording, pass-through
501
+ * (no buffering, so live streaming is unaffected). Recording is triggered by
502
+ * the terminal (done/error) event itself, synchronously before that event is
503
+ * yielded onward. This matters: a consumer's `.result()` promise can resolve
504
+ * the instant the terminal event reaches it — one iteration step before a
505
+ * plain post-loop "the generator finished" check would fire — so recording
506
+ * after the loop exits would race a caller awaiting `.result()` and lose.
507
+ * Relies on every call site fully iterating the returned stream (all current
508
+ * ones do, via drainAttempt or lazyStream's forwardStream).
509
+ */
510
+ /**
511
+ * Durable usage/cost/latency samples this runtime has recorded, if a store was
512
+ * configured. Read-only; callers query it (e.g. `aggregateUsagePerformance`)
513
+ * rather than this class exposing grouped views itself.
514
+ */
515
+ async listUsagePerformanceSamples() {
516
+ return this.usagePerformanceStore ? await this.usagePerformanceStore.list() : [];
517
+ }
518
+ close() {
519
+ this.usagePerformanceStore?.close?.();
520
+ }
521
+ instrumentAttempt(stream, model, role, credentialIdentity) {
522
+ const store = this.usagePerformanceStore;
523
+ const otlpConfig = this.otlpExportConfig;
524
+ if (!store && !otlpConfig)
525
+ return stream;
526
+ const now = this.performanceClock;
527
+ const startedAt = now();
528
+ const self = this;
529
+ return {
530
+ async *[Symbol.asyncIterator]() {
531
+ let firstEventAt;
532
+ for await (const event of stream) {
533
+ if (firstEventAt === undefined)
534
+ firstEventAt = now();
535
+ if (event.type === "done" || event.type === "error") {
536
+ const completedAt = now();
537
+ const message = event.type === "done" ? event.message : event.error;
538
+ const sample = self.buildUsageSample(model, role, credentialIdentity, message, {
539
+ startedAt,
540
+ firstEventAt: firstEventAt ?? completedAt,
541
+ completedAt,
542
+ });
543
+ if (store)
544
+ void store.record(sample).catch(() => { });
545
+ if (otlpConfig)
546
+ void exportUsageSampleSpan(sample, otlpConfig);
547
+ }
548
+ yield event;
549
+ }
550
+ },
551
+ result: () => stream.result(),
552
+ };
553
+ }
554
+ buildUsageSample(model, role, credentialIdentity, message, timing) {
555
+ const outcome = message.stopReason === "aborted" ? "aborted" : message.stopReason === "error" ? "error" : "success";
556
+ const failureKind = outcome === "error" ? classifyCredentialFailure(message) : undefined;
557
+ return {
558
+ timestamp: Date.now(),
559
+ provider: model.provider,
560
+ model: model.id,
561
+ role,
562
+ credentialIdentity,
563
+ outcome,
564
+ failureKind,
565
+ ttftMs: timing.firstEventAt - timing.startedAt,
566
+ generationMs: timing.completedAt - timing.firstEventAt,
567
+ usage: message.usage
568
+ ? {
569
+ input: message.usage.input,
570
+ output: message.usage.output,
571
+ cacheRead: message.usage.cacheRead,
572
+ cacheWrite: message.usage.cacheWrite,
573
+ }
574
+ : undefined,
575
+ cost: message.usage?.cost.total,
576
+ };
577
+ }
578
+ /**
579
+ * Opt-in role-based resolution: attempt each of a role's ordered model
580
+ * candidates in turn, exhausting that candidate's credential pool (Task 1.3)
581
+ * before advancing. A model visits at most once; since each visited model
582
+ * gets its own fresh credential-attempt set, no (credential, model) pair
583
+ * repeats across the whole call. A non-retryable failure on any candidate is
584
+ * terminal for the whole call — model fallback never masks a non-retryable
585
+ * error. Explicit CLI/session model selection is unaffected: callers must
586
+ * opt into this method instead of streamSimple().
587
+ */
588
+ streamSimpleForRole(roleName, context, options) {
589
+ const outer = createAssistantMessageEventStream();
590
+ this.attemptRole(roleName, context, options)
591
+ .then((drained) => {
592
+ for (const event of drained.events)
593
+ outer.push(event);
594
+ outer.end(drained.message);
595
+ })
596
+ .catch((error) => {
597
+ const message = {
598
+ role: "assistant",
599
+ content: [],
600
+ api: "role",
601
+ provider: "role",
602
+ model: roleName,
603
+ usage: {
604
+ input: 0,
605
+ output: 0,
606
+ cacheRead: 0,
607
+ cacheWrite: 0,
608
+ totalTokens: 0,
609
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
610
+ },
611
+ stopReason: "error",
612
+ errorMessage: error instanceof Error ? error.message : String(error),
613
+ timestamp: Date.now(),
614
+ };
615
+ outer.push({ type: "error", reason: "error", error: message });
616
+ outer.end(message);
465
617
  });
618
+ return outer;
619
+ }
620
+ async attemptRole(roleName, context, options) {
621
+ const { roles } = this.resolveModelRoles();
622
+ const candidates = roles.get(roleName);
623
+ if (!candidates || candidates.length === 0) {
624
+ throw new ModelsError("model_source", `Unknown or unresolved role: ${roleName}`);
625
+ }
626
+ let originalFailure;
627
+ for (const candidate of candidates) {
628
+ options?.signal?.throwIfAborted();
629
+ const attemptStream = await this.attemptModel(candidate, context, options, roleName);
630
+ const drained = await drainAttempt(attemptStream);
631
+ if (drained.message.stopReason !== "error")
632
+ return drained;
633
+ if (!originalFailure)
634
+ originalFailure = drained;
635
+ // Non-retryable (or aborted) is terminal for the whole role: model fallback
636
+ // never masks an error rotation itself already declined to retry.
637
+ if (!classifyCredentialFailure(drained.message))
638
+ return drained;
639
+ }
640
+ // originalFailure is always set here: candidates is non-empty, so the loop
641
+ // ran at least once, and every path that returns early also sets it first.
642
+ return originalFailure;
643
+ }
644
+ /**
645
+ * Bounded, pre-completion credential failover: each attempt is fully drained
646
+ * before any event reaches the caller, so a rotated-away attempt is invisible
647
+ * to it. A turn visits each (credential identity, this model) at most once.
648
+ * Only a classified rate-limit/blocked/transient failure advances the chain;
649
+ * on exhaustion the original (first) failure is rethrown, not the last one.
650
+ */
651
+ async streamSimpleWithCredentialFailover(pool, model, context, options, role) {
652
+ const attempted = new Set();
653
+ let originalFailure;
654
+ for (;;) {
655
+ options?.signal?.throwIfAborted();
656
+ const selection = pool.select({ providerId: model.provider, attempted });
657
+ if (!selection) {
658
+ if (originalFailure)
659
+ return originalFailure;
660
+ // Pool configured for this provider but nothing currently eligible
661
+ // (e.g. every entry cooling down): fall back to default auth resolution
662
+ // so the caller still gets a real attempt instead of a silent no-op.
663
+ const prepared = await this.prepareRequest(model, options);
664
+ const fallbackStream = prepared.provider.streamSimple(prepared.model, context, prepared.options);
665
+ return this.instrumentAttempt(fallbackStream, model, role, undefined);
666
+ }
667
+ attempted.add(selection.identity);
668
+ const auth = this.resolveCredentialPoolAuth?.(selection.identity);
669
+ const prepared = await this.prepareRequest(model, {
670
+ ...options,
671
+ apiKey: auth?.apiKey ?? options?.apiKey,
672
+ env: auth?.env ?? options?.env,
673
+ });
674
+ const attemptStream = this.instrumentAttempt(prepared.provider.streamSimple(prepared.model, context, prepared.options), model, role, selection.identity);
675
+ const drained = await drainAttempt(attemptStream);
676
+ const kind = classifyCredentialFailure(drained.message);
677
+ if (!kind)
678
+ return replayAttempt(drained);
679
+ pool.recordFailure({ identity: selection.identity, kind });
680
+ if (!originalFailure)
681
+ originalFailure = replayAttempt(drained);
682
+ }
466
683
  }
467
684
  completeSimple(model, context, options) {
468
685
  return this.streamSimple(model, context, options).result();
@@ -1 +1 @@
1
- {"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAcN,YAAY,EAIZ,UAAU,EAMV,WAAW,GAYX,MAAM,uBAAuB,CAAC;AAC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GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;aACvF,CAAC;QACH,CAAC;QACD,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;IAED,kBAAkB,CAAC,UAAkB,EAAQ;QAC5C,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;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.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAeN,iCAAiC,EACjC,YAAY,EAIZ,UAAU,EAMV,WAAW,GAYX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,sBAAsB,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,WAAW,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EACN,yBAAyB,EAEzB,YAAY,EAEZ,aAAa,GACb,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAA6B,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAyB,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAGN,oBAAoB,EACpB,2BAA2B,EAE3B,iCAAiC,EACjC,6BAA6B,EAC7B,yBAAyB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AA2D9D,qGAAqG;AACrG,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IAC/C,UAAU,CAAS;IACnB,SAAS,CAAqC;IAC9C,UAAU,CAAyB;IAE5C,YACC,UAAkB,EAClB,SAA6C,EAC7C,UAAkC,EAClC,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AS;oBAChE,MAAM,EAAE,qBAAqB;iBAC7B,CAAC,CAAC;YACJ,CAAC;YACD,IAAI,CAAC,QAAQ,GAAG;gBACf,GAAG,IAAI,CAAC,QAAQ;gBAChB,IAAI;gBACJ,mBAAmB;gBACnB,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;aACvF,CAAC;QACH,CAAC;QACD,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;IAED,kBAAkB,CAAC,UAAkB,EAAQ;QAC5C,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;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"]}
@@ -0,0 +1,21 @@
1
+ import type { UsagePerformanceSample } from "../usage-performance-store.ts";
2
+ export type UsageAggregateDimension = "model" | "session" | "role";
3
+ export interface UsageAggregateRow {
4
+ key: string;
5
+ cost: number;
6
+ sampleCount: number;
7
+ ttftMsTotal: number;
8
+ generationMsTotal: number;
9
+ }
10
+ export interface UsageAggregateRange {
11
+ sinceMs?: number;
12
+ untilMs?: number;
13
+ }
14
+ /**
15
+ * Groups durable usage/cost samples by model, session, or role over an optional
16
+ * time range. The one query surface both `apex-code cost` (roadmap Phase 8) and
17
+ * the ledger-vs-`getUsageCostBreakdown` reconciliation gate read, so the two never
18
+ * compute cost through independently-drifting logic.
19
+ */
20
+ export declare function aggregateUsagePerformance(samples: readonly UsagePerformanceSample[], dimension: UsageAggregateDimension, range?: UsageAggregateRange): UsageAggregateRow[];
21
+ //# sourceMappingURL=aggregate.d.ts.map