apex-code 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (573) hide show
  1. package/CHANGELOG.md +280 -6
  2. package/README.md +624 -0
  3. package/dist/bun/cli.d.ts +3 -1
  4. package/dist/bun/cli.d.ts.map +1 -1
  5. package/dist/bun/cli.js +3 -9
  6. package/dist/bun/cli.js.map +1 -1
  7. package/dist/bun/runtime-setup.d.ts +2 -0
  8. package/dist/bun/runtime-setup.d.ts.map +1 -0
  9. package/dist/bun/runtime-setup.js +9 -0
  10. package/dist/bun/runtime-setup.js.map +1 -0
  11. package/dist/bun/sandbox-env-setup.d.ts +2 -0
  12. package/dist/bun/sandbox-env-setup.d.ts.map +1 -0
  13. package/dist/bun/sandbox-env-setup.js +4 -0
  14. package/dist/bun/sandbox-env-setup.js.map +1 -0
  15. package/dist/cli/args.d.ts.map +1 -1
  16. package/dist/cli/args.js +16 -5
  17. package/dist/cli/args.js.map +1 -1
  18. package/dist/cli/config-selector.d.ts.map +1 -1
  19. package/dist/cli/config-selector.js +2 -1
  20. package/dist/cli/config-selector.js.map +1 -1
  21. package/dist/cli/file-processor.d.ts +1 -1
  22. package/dist/cli/file-processor.d.ts.map +1 -1
  23. package/dist/cli/file-processor.js.map +1 -1
  24. package/dist/cli/session-picker.d.ts +1 -1
  25. package/dist/cli/session-picker.d.ts.map +1 -1
  26. package/dist/cli/session-picker.js.map +1 -1
  27. package/dist/cli/setup.d.ts +2 -0
  28. package/dist/cli/setup.d.ts.map +1 -0
  29. package/dist/cli/setup.js +13 -0
  30. package/dist/cli/setup.js.map +1 -0
  31. package/dist/config.d.ts +1 -0
  32. package/dist/config.d.ts.map +1 -1
  33. package/dist/config.js +1 -0
  34. package/dist/config.js.map +1 -1
  35. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  36. package/dist/core/agent-session-runtime.js +16 -8
  37. package/dist/core/agent-session-runtime.js.map +1 -1
  38. package/dist/core/agent-session.d.ts +85 -15
  39. package/dist/core/agent-session.d.ts.map +1 -1
  40. package/dist/core/agent-session.js +685 -266
  41. package/dist/core/agent-session.js.map +1 -1
  42. package/dist/core/auth-storage.d.ts +4 -0
  43. package/dist/core/auth-storage.d.ts.map +1 -1
  44. package/dist/core/auth-storage.js +55 -0
  45. package/dist/core/auth-storage.js.map +1 -1
  46. package/dist/core/bug-report.d.ts +176 -0
  47. package/dist/core/bug-report.d.ts.map +1 -0
  48. package/dist/core/bug-report.js +291 -0
  49. package/dist/core/bug-report.js.map +1 -0
  50. package/dist/core/cache-stats.d.ts.map +1 -1
  51. package/dist/core/cache-stats.js +12 -1
  52. package/dist/core/cache-stats.js.map +1 -1
  53. package/dist/core/cache-warmer.d.ts +103 -0
  54. package/dist/core/cache-warmer.d.ts.map +1 -0
  55. package/dist/core/cache-warmer.js +356 -0
  56. package/dist/core/cache-warmer.js.map +1 -0
  57. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  58. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  59. package/dist/core/compaction/branch-summarization.js +4 -3
  60. package/dist/core/compaction/branch-summarization.js.map +1 -1
  61. package/dist/core/compaction/compaction.d.ts +5 -3
  62. package/dist/core/compaction/compaction.d.ts.map +1 -1
  63. package/dist/core/compaction/compaction.js +163 -66
  64. package/dist/core/compaction/compaction.js.map +1 -1
  65. package/dist/core/context/pipeline.d.ts +8 -8
  66. package/dist/core/context/pipeline.d.ts.map +1 -1
  67. package/dist/core/context/pipeline.js +21 -12
  68. package/dist/core/context/pipeline.js.map +1 -1
  69. package/dist/core/crash-log.d.ts +27 -0
  70. package/dist/core/crash-log.d.ts.map +1 -0
  71. package/dist/core/crash-log.js +139 -0
  72. package/dist/core/crash-log.js.map +1 -0
  73. package/dist/core/export-html/template.js +6 -1
  74. package/dist/core/extensions/index.d.ts +1 -1
  75. package/dist/core/extensions/index.d.ts.map +1 -1
  76. package/dist/core/extensions/index.js.map +1 -1
  77. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  78. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  79. package/dist/core/extensions/jiti-loader.js +4 -0
  80. package/dist/core/extensions/jiti-loader.js.map +1 -0
  81. package/dist/core/extensions/jiti-static-loader.d.ts +2 -0
  82. package/dist/core/extensions/jiti-static-loader.d.ts.map +1 -0
  83. package/dist/core/extensions/jiti-static-loader.js +4 -0
  84. package/dist/core/extensions/jiti-static-loader.js.map +1 -0
  85. package/dist/core/extensions/loader.d.ts.map +1 -1
  86. package/dist/core/extensions/loader.js +40 -59
  87. package/dist/core/extensions/loader.js.map +1 -1
  88. package/dist/core/extensions/runner.d.ts +24 -8
  89. package/dist/core/extensions/runner.d.ts.map +1 -1
  90. package/dist/core/extensions/runner.js +195 -72
  91. package/dist/core/extensions/runner.js.map +1 -1
  92. package/dist/core/extensions/types.d.ts +142 -55
  93. package/dist/core/extensions/types.d.ts.map +1 -1
  94. package/dist/core/extensions/types.js.map +1 -1
  95. package/dist/core/extensions/virtual-modules.d.ts +3 -0
  96. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  97. package/dist/core/extensions/virtual-modules.js +41 -0
  98. package/dist/core/extensions/virtual-modules.js.map +1 -0
  99. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  100. package/dist/core/extensions/wrapper.js +1 -20
  101. package/dist/core/extensions/wrapper.js.map +1 -1
  102. package/dist/core/http-dispatcher.d.ts.map +1 -1
  103. package/dist/core/http-dispatcher.js +2 -0
  104. package/dist/core/http-dispatcher.js.map +1 -1
  105. package/dist/core/index.d.ts +2 -1
  106. package/dist/core/index.d.ts.map +1 -1
  107. package/dist/core/index.js.map +1 -1
  108. package/dist/core/keybindings.d.ts +6 -1
  109. package/dist/core/keybindings.d.ts.map +1 -1
  110. package/dist/core/keybindings.js +5 -1
  111. package/dist/core/keybindings.js.map +1 -1
  112. package/dist/core/messages.d.ts +1 -1
  113. package/dist/core/messages.d.ts.map +1 -1
  114. package/dist/core/messages.js +1 -0
  115. package/dist/core/messages.js.map +1 -1
  116. package/dist/core/model-config.d.ts +168 -20
  117. package/dist/core/model-config.d.ts.map +1 -1
  118. package/dist/core/model-config.js +44 -18
  119. package/dist/core/model-config.js.map +1 -1
  120. package/dist/core/model-registry.d.ts +5 -1
  121. package/dist/core/model-registry.d.ts.map +1 -1
  122. package/dist/core/model-registry.js +8 -0
  123. package/dist/core/model-registry.js.map +1 -1
  124. package/dist/core/model-resolver.d.ts.map +1 -1
  125. package/dist/core/model-resolver.js +4 -3
  126. package/dist/core/model-resolver.js.map +1 -1
  127. package/dist/core/model-runtime.d.ts +1 -0
  128. package/dist/core/model-runtime.d.ts.map +1 -1
  129. package/dist/core/model-runtime.js +12 -6
  130. package/dist/core/model-runtime.js.map +1 -1
  131. package/dist/core/permissions/store.d.ts.map +1 -1
  132. package/dist/core/permissions/store.js +11 -8
  133. package/dist/core/permissions/store.js.map +1 -1
  134. package/dist/core/prompt-templates.d.ts +6 -1
  135. package/dist/core/prompt-templates.d.ts.map +1 -1
  136. package/dist/core/prompt-templates.js +61 -35
  137. package/dist/core/prompt-templates.js.map +1 -1
  138. package/dist/core/provider-composer.d.ts +4 -2
  139. package/dist/core/provider-composer.d.ts.map +1 -1
  140. package/dist/core/provider-composer.js +29 -2
  141. package/dist/core/provider-composer.js.map +1 -1
  142. package/dist/core/radius.d.ts +3 -0
  143. package/dist/core/radius.d.ts.map +1 -1
  144. package/dist/core/radius.js +6 -0
  145. package/dist/core/radius.js.map +1 -1
  146. package/dist/core/resource-loader.d.ts.map +1 -1
  147. package/dist/core/resource-loader.js +6 -2
  148. package/dist/core/resource-loader.js.map +1 -1
  149. package/dist/core/sdk.d.ts.map +1 -1
  150. package/dist/core/sdk.js +63 -42
  151. package/dist/core/sdk.js.map +1 -1
  152. package/dist/core/session-export.d.ts +6 -2
  153. package/dist/core/session-export.d.ts.map +1 -1
  154. package/dist/core/session-export.js +14 -13
  155. package/dist/core/session-export.js.map +1 -1
  156. package/dist/core/session-manager.d.ts +66 -15
  157. package/dist/core/session-manager.d.ts.map +1 -1
  158. package/dist/core/session-manager.js +295 -115
  159. package/dist/core/session-manager.js.map +1 -1
  160. package/dist/core/settings-manager.d.ts +27 -4
  161. package/dist/core/settings-manager.d.ts.map +1 -1
  162. package/dist/core/settings-manager.js +56 -8
  163. package/dist/core/settings-manager.js.map +1 -1
  164. package/dist/core/skills.d.ts +1 -1
  165. package/dist/core/skills.d.ts.map +1 -1
  166. package/dist/core/skills.js +5 -4
  167. package/dist/core/skills.js.map +1 -1
  168. package/dist/core/slash-commands.d.ts.map +1 -1
  169. package/dist/core/slash-commands.js +1 -0
  170. package/dist/core/slash-commands.js.map +1 -1
  171. package/dist/core/system-prompt.d.ts +49 -6
  172. package/dist/core/system-prompt.d.ts.map +1 -1
  173. package/dist/core/system-prompt.js +140 -79
  174. package/dist/core/system-prompt.js.map +1 -1
  175. package/dist/core/tools/bash.d.ts +9 -15
  176. package/dist/core/tools/bash.d.ts.map +1 -1
  177. package/dist/core/tools/bash.js +20 -137
  178. package/dist/core/tools/bash.js.map +1 -1
  179. package/dist/core/tools/delegate.d.ts.map +1 -1
  180. package/dist/core/tools/delegate.js +2 -2
  181. package/dist/core/tools/delegate.js.map +1 -1
  182. package/dist/core/tools/edit.d.ts +1 -12
  183. package/dist/core/tools/edit.d.ts.map +1 -1
  184. package/dist/core/tools/edit.js +6 -204
  185. package/dist/core/tools/edit.js.map +1 -1
  186. package/dist/core/tools/find.d.ts.map +1 -1
  187. package/dist/core/tools/find.js +4 -55
  188. package/dist/core/tools/find.js.map +1 -1
  189. package/dist/core/tools/grep.d.ts.map +1 -1
  190. package/dist/core/tools/grep.js +4 -60
  191. package/dist/core/tools/grep.js.map +1 -1
  192. package/dist/core/tools/ls.d.ts.map +1 -1
  193. package/dist/core/tools/ls.js +4 -49
  194. package/dist/core/tools/ls.js.map +1 -1
  195. package/dist/core/tools/read.d.ts +4 -1
  196. package/dist/core/tools/read.d.ts.map +1 -1
  197. package/dist/core/tools/read.js +10 -122
  198. package/dist/core/tools/read.js.map +1 -1
  199. package/dist/core/tools/renderers/bash.d.ts +18 -0
  200. package/dist/core/tools/renderers/bash.d.ts.map +1 -0
  201. package/dist/core/tools/renderers/bash.js +126 -0
  202. package/dist/core/tools/renderers/bash.js.map +1 -0
  203. package/dist/core/tools/renderers/edit.d.ts +23 -0
  204. package/dist/core/tools/renderers/edit.d.ts.map +1 -0
  205. package/dist/core/tools/renderers/edit.js +207 -0
  206. package/dist/core/tools/renderers/edit.js.map +1 -0
  207. package/dist/core/tools/renderers/find.d.ts +10 -0
  208. package/dist/core/tools/renderers/find.d.ts.map +1 -0
  209. package/dist/core/tools/renderers/find.js +64 -0
  210. package/dist/core/tools/renderers/find.js.map +1 -0
  211. package/dist/core/tools/renderers/grep.d.ts +10 -0
  212. package/dist/core/tools/renderers/grep.d.ts.map +1 -0
  213. package/dist/core/tools/renderers/grep.js +69 -0
  214. package/dist/core/tools/renderers/grep.js.map +1 -0
  215. package/dist/core/tools/renderers/index.d.ts +34 -0
  216. package/dist/core/tools/renderers/index.d.ts.map +1 -0
  217. package/dist/core/tools/renderers/index.js +47 -0
  218. package/dist/core/tools/renderers/index.js.map +1 -0
  219. package/dist/core/tools/renderers/ls.d.ts +10 -0
  220. package/dist/core/tools/renderers/ls.d.ts.map +1 -0
  221. package/dist/core/tools/renderers/ls.js +58 -0
  222. package/dist/core/tools/renderers/ls.js.map +1 -0
  223. package/dist/core/tools/renderers/read.d.ts +11 -0
  224. package/dist/core/tools/renderers/read.d.ts.map +1 -0
  225. package/dist/core/tools/renderers/read.js +132 -0
  226. package/dist/core/tools/renderers/read.js.map +1 -0
  227. package/dist/core/tools/renderers/write.d.ts +10 -0
  228. package/dist/core/tools/renderers/write.d.ts.map +1 -0
  229. package/dist/core/tools/renderers/write.js +152 -0
  230. package/dist/core/tools/renderers/write.js.map +1 -0
  231. package/dist/core/tools/write.d.ts.map +1 -1
  232. package/dist/core/tools/write.js +6 -147
  233. package/dist/core/tools/write.js.map +1 -1
  234. package/dist/core/usage-totals.d.ts +1 -1
  235. package/dist/core/usage-totals.d.ts.map +1 -1
  236. package/dist/core/usage-totals.js +5 -1
  237. package/dist/core/usage-totals.js.map +1 -1
  238. package/dist/extensions/llama/client.d.ts +2 -0
  239. package/dist/extensions/llama/client.d.ts.map +1 -1
  240. package/dist/extensions/llama/client.js +7 -3
  241. package/dist/extensions/llama/client.js.map +1 -1
  242. package/dist/extensions/llama/provider.d.ts.map +1 -1
  243. package/dist/extensions/llama/provider.js +20 -5
  244. package/dist/extensions/llama/provider.js.map +1 -1
  245. package/dist/extensions/llama/ui.d.ts.map +1 -1
  246. package/dist/extensions/llama/ui.js +3 -2
  247. package/dist/extensions/llama/ui.js.map +1 -1
  248. package/dist/index.d.ts +5 -4
  249. package/dist/index.d.ts.map +1 -1
  250. package/dist/index.js +1 -1
  251. package/dist/index.js.map +1 -1
  252. package/dist/main.d.ts.map +1 -1
  253. package/dist/main.js +21 -13
  254. package/dist/main.js.map +1 -1
  255. package/dist/modes/interactive/bug-report.d.ts +16 -0
  256. package/dist/modes/interactive/bug-report.d.ts.map +1 -0
  257. package/dist/modes/interactive/bug-report.js +167 -0
  258. package/dist/modes/interactive/bug-report.js.map +1 -0
  259. package/dist/modes/interactive/chat-viewport.d.ts +20 -0
  260. package/dist/modes/interactive/chat-viewport.d.ts.map +1 -0
  261. package/dist/modes/interactive/chat-viewport.js +28 -0
  262. package/dist/modes/interactive/chat-viewport.js.map +1 -0
  263. package/dist/modes/interactive/components/assistant-message.d.ts +7 -0
  264. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  265. package/dist/modes/interactive/components/assistant-message.js +63 -27
  266. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  267. package/dist/modes/interactive/components/autocomplete-source.d.ts +8 -0
  268. package/dist/modes/interactive/components/autocomplete-source.d.ts.map +1 -0
  269. package/dist/modes/interactive/components/autocomplete-source.js +23 -0
  270. package/dist/modes/interactive/components/autocomplete-source.js.map +1 -0
  271. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  272. package/dist/modes/interactive/components/bash-execution.js +6 -4
  273. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  274. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  275. package/dist/modes/interactive/components/bordered-loader.js +1 -1
  276. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  277. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  278. package/dist/modes/interactive/components/branch-summary-message.js +12 -5
  279. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  280. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  281. package/dist/modes/interactive/components/compaction-summary-message.js +12 -5
  282. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  283. package/dist/modes/interactive/components/composer-dock.d.ts +12 -0
  284. package/dist/modes/interactive/components/composer-dock.d.ts.map +1 -0
  285. package/dist/modes/interactive/components/composer-dock.js +24 -0
  286. package/dist/modes/interactive/components/composer-dock.js.map +1 -0
  287. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  288. package/dist/modes/interactive/components/config-selector.js +11 -9
  289. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  290. package/dist/modes/interactive/components/custom-editor.d.ts +12 -0
  291. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  292. package/dist/modes/interactive/components/custom-editor.js +38 -0
  293. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  294. package/dist/modes/interactive/components/error-summary.d.ts +11 -0
  295. package/dist/modes/interactive/components/error-summary.d.ts.map +1 -0
  296. package/dist/modes/interactive/components/error-summary.js +31 -0
  297. package/dist/modes/interactive/components/error-summary.js.map +1 -0
  298. package/dist/modes/interactive/components/extension-editor.d.ts +4 -1
  299. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  300. package/dist/modes/interactive/components/extension-editor.js +15 -10
  301. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  302. package/dist/modes/interactive/components/extension-input.d.ts +2 -0
  303. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  304. package/dist/modes/interactive/components/extension-input.js +15 -5
  305. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  306. package/dist/modes/interactive/components/extension-selector.d.ts +2 -0
  307. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  308. package/dist/modes/interactive/components/extension-selector.js +15 -10
  309. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  310. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  311. package/dist/modes/interactive/components/first-time-setup.js +6 -6
  312. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  313. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  314. package/dist/modes/interactive/components/footer.js +12 -4
  315. package/dist/modes/interactive/components/footer.js.map +1 -1
  316. package/dist/modes/interactive/components/index.d.ts +1 -1
  317. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  318. package/dist/modes/interactive/components/index.js.map +1 -1
  319. package/dist/modes/interactive/components/keybinding-hints.d.ts +21 -0
  320. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  321. package/dist/modes/interactive/components/keybinding-hints.js +34 -0
  322. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  323. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  324. package/dist/modes/interactive/components/login-dialog.js +27 -23
  325. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  326. package/dist/modes/interactive/components/model-selector.d.ts +1 -1
  327. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  328. package/dist/modes/interactive/components/model-selector.js +16 -20
  329. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  330. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  331. package/dist/modes/interactive/components/oauth-selector.js +7 -6
  332. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  333. package/dist/modes/interactive/components/permission-preview.d.ts.map +1 -1
  334. package/dist/modes/interactive/components/permission-preview.js +3 -3
  335. package/dist/modes/interactive/components/permission-preview.js.map +1 -1
  336. package/dist/modes/interactive/components/prompt-input.d.ts +12 -0
  337. package/dist/modes/interactive/components/prompt-input.d.ts.map +1 -0
  338. package/dist/modes/interactive/components/prompt-input.js +18 -0
  339. package/dist/modes/interactive/components/prompt-input.js.map +1 -0
  340. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -1
  341. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  342. package/dist/modes/interactive/components/scoped-models-selector.js +17 -18
  343. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  344. package/dist/modes/interactive/components/session-selector.d.ts +5 -5
  345. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  346. package/dist/modes/interactive/components/session-selector.js +100 -67
  347. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  348. package/dist/modes/interactive/components/settings-selector.d.ts +5 -1
  349. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  350. package/dist/modes/interactive/components/settings-selector.js +74 -16
  351. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  352. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  353. package/dist/modes/interactive/components/settings-submenu.js +8 -6
  354. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  355. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  356. package/dist/modes/interactive/components/skill-invocation-message.js +11 -4
  357. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  358. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  359. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  360. package/dist/modes/interactive/components/status-indicator.js +10 -3
  361. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  362. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  363. package/dist/modes/interactive/components/thinking-selector.js +14 -9
  364. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  365. package/dist/modes/interactive/components/tool-execution.d.ts +28 -16
  366. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  367. package/dist/modes/interactive/components/tool-execution.js +73 -80
  368. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  369. package/dist/modes/interactive/components/tool-panel.d.ts.map +1 -1
  370. package/dist/modes/interactive/components/tool-panel.js +7 -2
  371. package/dist/modes/interactive/components/tool-panel.js.map +1 -1
  372. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  373. package/dist/modes/interactive/components/tree-selector.js +18 -5
  374. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  375. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
  376. package/dist/modes/interactive/components/trust-selector.js +12 -12
  377. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  378. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  379. package/dist/modes/interactive/components/user-message-selector.js +2 -2
  380. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  381. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  382. package/dist/modes/interactive/components/user-message.js +6 -3
  383. package/dist/modes/interactive/components/user-message.js.map +1 -1
  384. package/dist/modes/interactive/interactive-mode.d.ts +50 -31
  385. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  386. package/dist/modes/interactive/interactive-mode.js +494 -229
  387. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  388. package/dist/modes/interactive/theme/dark.json +2 -1
  389. package/dist/modes/interactive/theme/light.json +2 -1
  390. package/dist/modes/interactive/theme/theme-controller.d.ts +1 -0
  391. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  392. package/dist/modes/interactive/theme/theme-controller.js +5 -0
  393. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  394. package/dist/modes/interactive/theme/theme-json.d.ts +84 -0
  395. package/dist/modes/interactive/theme/theme-json.d.ts.map +1 -0
  396. package/dist/modes/interactive/theme/theme-json.js +130 -0
  397. package/dist/modes/interactive/theme/theme-json.js.map +1 -0
  398. package/dist/modes/interactive/theme/theme-schema.json +6 -2
  399. package/dist/modes/interactive/theme/theme.d.ts +14 -5
  400. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  401. package/dist/modes/interactive/theme/theme.js +18 -119
  402. package/dist/modes/interactive/theme/theme.js.map +1 -1
  403. package/dist/modes/interactive/tui-renderer.d.ts +21 -0
  404. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -0
  405. package/dist/modes/interactive/tui-renderer.js +66 -0
  406. package/dist/modes/interactive/tui-renderer.js.map +1 -0
  407. package/dist/modes/print-mode.d.ts.map +1 -1
  408. package/dist/modes/print-mode.js +49 -23
  409. package/dist/modes/print-mode.js.map +1 -1
  410. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  411. package/dist/modes/rpc/rpc-mode.js +2 -2
  412. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  413. package/dist/testing/replay/recorded-provider.d.ts +2 -2
  414. package/dist/testing/replay/recorded-provider.d.ts.map +1 -1
  415. package/dist/testing/replay/recorded-provider.js +2 -5
  416. package/dist/testing/replay/recorded-provider.js.map +1 -1
  417. package/dist/testing/replay/runner.d.ts.map +1 -1
  418. package/dist/testing/replay/runner.js +0 -1
  419. package/dist/testing/replay/runner.js.map +1 -1
  420. package/dist/utils/clipboard-command.d.ts +7 -0
  421. package/dist/utils/clipboard-command.d.ts.map +1 -0
  422. package/dist/utils/clipboard-command.js +45 -0
  423. package/dist/utils/clipboard-command.js.map +1 -0
  424. package/dist/utils/clipboard-image.d.ts.map +1 -1
  425. package/dist/utils/clipboard-image.js +53 -81
  426. package/dist/utils/clipboard-image.js.map +1 -1
  427. package/dist/utils/clipboard.d.ts.map +1 -1
  428. package/dist/utils/clipboard.js +111 -121
  429. package/dist/utils/clipboard.js.map +1 -1
  430. package/dist/utils/exif-orientation.d.ts.map +1 -1
  431. package/dist/utils/exif-orientation.js +2 -3
  432. package/dist/utils/exif-orientation.js.map +1 -1
  433. package/dist/utils/mime.d.ts.map +1 -1
  434. package/dist/utils/mime.js +1 -1
  435. package/dist/utils/mime.js.map +1 -1
  436. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  437. package/dist/utils/syntax-highlight.js +21 -21
  438. package/dist/utils/syntax-highlight.js.map +1 -1
  439. package/dist/utils/tool-result-images.d.ts +3 -1
  440. package/dist/utils/tool-result-images.d.ts.map +1 -1
  441. package/dist/utils/tool-result-images.js +4 -1
  442. package/dist/utils/tool-result-images.js.map +1 -1
  443. package/dist/utils/tools-manager.d.ts.map +1 -1
  444. package/dist/utils/tools-manager.js +11 -2
  445. package/dist/utils/tools-manager.js.map +1 -1
  446. package/dist/utils/wsl.d.ts +3 -0
  447. package/dist/utils/wsl.d.ts.map +1 -0
  448. package/dist/utils/wsl.js +15 -0
  449. package/dist/utils/wsl.js.map +1 -0
  450. package/dist/utils/zip.d.ts +7 -0
  451. package/dist/utils/zip.d.ts.map +1 -0
  452. package/dist/utils/zip.js +60 -0
  453. package/dist/utils/zip.js.map +1 -0
  454. package/docs/cli-integration.md +107 -0
  455. package/docs/cli.md +269 -0
  456. package/docs/compaction.md +73 -24
  457. package/docs/configuration.md +45 -0
  458. package/docs/containerization.md +22 -21
  459. package/docs/custom-provider.md +21 -12
  460. package/docs/development.md +19 -0
  461. package/docs/docs.json +139 -95
  462. package/docs/extensions.md +243 -371
  463. package/docs/how-pi-works.md +49 -0
  464. package/docs/images/interactive-mode.png +0 -0
  465. package/docs/index.md +3 -3
  466. package/docs/json.md +43 -3
  467. package/docs/keybindings.md +57 -54
  468. package/docs/llama-cpp.md +2 -2
  469. package/docs/message-types.md +261 -0
  470. package/docs/models.md +103 -49
  471. package/docs/packages.md +49 -47
  472. package/docs/prompt-templates.md +29 -56
  473. package/docs/providers.md +91 -139
  474. package/docs/quickstart.md +42 -14
  475. package/docs/rpc-commands.md +854 -0
  476. package/docs/rpc-extension-ui.md +200 -0
  477. package/docs/rpc.md +121 -223
  478. package/docs/sdk.md +99 -124
  479. package/docs/security.md +7 -7
  480. package/docs/session-format.md +85 -82
  481. package/docs/sessions.md +41 -57
  482. package/docs/settings.md +95 -88
  483. package/docs/shell-aliases.md +68 -3
  484. package/docs/skills.md +62 -49
  485. package/docs/slash-commands.md +60 -0
  486. package/docs/terminal-setup.md +86 -55
  487. package/docs/termux.md +65 -75
  488. package/docs/themes.md +64 -86
  489. package/docs/tmux.md +29 -7
  490. package/docs/tui.md +67 -122
  491. package/docs/usage.md +31 -42
  492. package/docs/windows.md +41 -13
  493. package/examples/README.md +16 -2
  494. package/examples/extensions/README.md +0 -1
  495. package/examples/extensions/custom-provider-anthropic/index.ts +18 -12
  496. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  497. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  498. package/examples/extensions/custom-provider-gitlab-duo/index.ts +2 -2
  499. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  500. package/examples/extensions/dynamic-resources/dynamic.json +2 -0
  501. package/examples/extensions/gondolin/package-lock.json +2 -2
  502. package/examples/extensions/gondolin/package.json +1 -1
  503. package/examples/extensions/prompt-customizer.ts +19 -67
  504. package/examples/extensions/sandbox/package-lock.json +2 -2
  505. package/examples/extensions/sandbox/package.json +1 -1
  506. package/examples/extensions/with-deps/package-lock.json +2 -2
  507. package/examples/extensions/with-deps/package.json +1 -1
  508. package/examples/plugins/pi-example-plugin/README.md +38 -0
  509. package/examples/plugins/pi-example-plugin/package.json +10 -0
  510. package/examples/plugins/pi-example-plugin/src/contract.ts +13 -0
  511. package/examples/plugins/pi-example-plugin/src/session.ts +24 -0
  512. package/examples/plugins/pi-example-plugin/src/tui.ts +31 -0
  513. package/examples/rpc-client.ts +35 -0
  514. package/examples/rpc-extension-ui.ts +25 -5
  515. package/examples/sdk/README.md +1 -1
  516. package/npm-shrinkwrap.json +861 -513
  517. package/package.json +27 -18
  518. package/dist/bun/register-bedrock.d.ts +0 -2
  519. package/dist/bun/register-bedrock.d.ts.map +0 -1
  520. package/dist/bun/register-bedrock.js +0 -4
  521. package/dist/bun/register-bedrock.js.map +0 -1
  522. package/dist/cli/experimental/auth.d.ts +0 -16
  523. package/dist/cli/experimental/auth.d.ts.map +0 -1
  524. package/dist/cli/experimental/auth.js +0 -13
  525. package/dist/cli/experimental/auth.js.map +0 -1
  526. package/dist/cli/experimental/cli.d.ts +0 -6
  527. package/dist/cli/experimental/cli.d.ts.map +0 -1
  528. package/dist/cli/experimental/cli.js +0 -5
  529. package/dist/cli/experimental/cli.js.map +0 -1
  530. package/dist/cli/experimental/command-options.d.ts +0 -17
  531. package/dist/cli/experimental/command-options.d.ts.map +0 -1
  532. package/dist/cli/experimental/command-options.js +0 -35
  533. package/dist/cli/experimental/command-options.js.map +0 -1
  534. package/dist/cli/experimental/command.d.ts +0 -63
  535. package/dist/cli/experimental/command.d.ts.map +0 -1
  536. package/dist/cli/experimental/command.js +0 -130
  537. package/dist/cli/experimental/command.js.map +0 -1
  538. package/dist/cli/experimental/commands/client.d.ts +0 -13
  539. package/dist/cli/experimental/commands/client.d.ts.map +0 -1
  540. package/dist/cli/experimental/commands/client.js +0 -25
  541. package/dist/cli/experimental/commands/client.js.map +0 -1
  542. package/dist/cli/experimental/commands/pi.d.ts +0 -15
  543. package/dist/cli/experimental/commands/pi.d.ts.map +0 -1
  544. package/dist/cli/experimental/commands/pi.js +0 -28
  545. package/dist/cli/experimental/commands/pi.js.map +0 -1
  546. package/dist/cli/experimental/commands/server.d.ts +0 -13
  547. package/dist/cli/experimental/commands/server.d.ts.map +0 -1
  548. package/dist/cli/experimental/commands/server.js +0 -25
  549. package/dist/cli/experimental/commands/server.js.map +0 -1
  550. package/dist/cli/experimental/transport-address.d.ts +0 -10
  551. package/dist/cli/experimental/transport-address.d.ts.map +0 -1
  552. package/dist/cli/experimental/transport-address.js +0 -38
  553. package/dist/cli/experimental/transport-address.js.map +0 -1
  554. package/dist/client/index.d.ts +0 -3
  555. package/dist/client/index.d.ts.map +0 -1
  556. package/dist/client/index.js +0 -3
  557. package/dist/client/index.js.map +0 -1
  558. package/dist/client/remote-session.d.ts +0 -53
  559. package/dist/client/remote-session.d.ts.map +0 -1
  560. package/dist/client/remote-session.js +0 -340
  561. package/dist/client/remote-session.js.map +0 -1
  562. package/dist/client/transcript.d.ts +0 -12
  563. package/dist/client/transcript.d.ts.map +0 -1
  564. package/dist/client/transcript.js +0 -98
  565. package/dist/client/transcript.js.map +0 -1
  566. package/dist/modes/interactive/components/message-spine.d.ts +0 -14
  567. package/dist/modes/interactive/components/message-spine.d.ts.map +0 -1
  568. package/dist/modes/interactive/components/message-spine.js +0 -19
  569. package/dist/modes/interactive/components/message-spine.js.map +0 -1
  570. package/dist/utils/clipboard-native.d.ts +0 -11
  571. package/dist/utils/clipboard-native.d.ts.map +0 -1
  572. package/dist/utils/clipboard-native.js +0 -20
  573. package/dist/utils/clipboard-native.js.map +0 -1
@@ -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,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,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AK,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"]}
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,EAOX,gBAAgB,GAOhB,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,E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AE,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\tnormalizeContext,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype ProviderRequestOptions,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n\ttype TranscriptContext,\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\tconst transcript = normalizeContext(context);\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\ttranscript,\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\tconst transcript = normalizeContext(context);\n\t\treturn lazyStream(model, () => this.attemptModel(model, transcript, 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: TranscriptContext,\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 transcript = normalizeContext(context);\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, transcript, 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: TranscriptContext,\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\tstreamDeferred(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: ModelsDeferredFetchOptions,\n\t): AssistantMessageEventStream {\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});\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 this.streamDeferred(model, handle, options).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 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/core/permissions/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAMH,OAAO,EAAE,KAAK,kBAAkB,EAA0B,MAAM,oBAAoB,CAAC;AAOrF,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnE,eAAO,MAAM,gBAAgB,6EAA8E,CAAC;AAC5G,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/D;;mDAEmD;AACnD,eAAO,MAAM,2BAA2B,6DAA8D,CAAC;AACvG,MAAM,MAAM,wBAAwB,GAAG,CAAC,OAAO,2BAA2B,CAAC,CAAC,MAAM,CAAC,CAAC;AAEpF,QAAA,MAAM,mBAAmB,uCAAwC,CAAC;AAClE,KAAK,gBAAgB,GAAG,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;AAK7D,kGAAgG;AAChG,MAAM,MAAM,oBAAoB,GAAG,IAAI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C,QAAQ,CAAC,YAAY,CAAsD;IAEnF,YAAY,OAAO,EAAE,iCAAiC,EAErD;IAEK,QAAQ,IAAI,OAAO,CAAC,uBAAuB,CAAC,CAWjD;IAEK,KAAK,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAenD;CACD","sourcesContent":["/**\n * Persistence for the permission rule model (ADR 0004). Four of the eight sources\n * are file-backed (policy, local, project, user); the other four are runtime-only\n * (flag, cliArg — parsed once from argv, not stored here; command, session — held\n * in memory for the life of the process). `session`-source updates are never\n * written to disk: \"allow for this session\" dies with the session by design.\n *\n * Reuses the locked-JSON-file backend already proven for Phase 1's operational\n * state (FileAuthStorageBackend) rather than widening `SettingsScope`, which only\n * covers two of these four file-backed sources and represents a different, larger\n * settings domain.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../../config.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { type AuthStorageBackend, FileAuthStorageBackend } from \"../auth-storage.ts\";\nimport {\n\tPROJECT_LOCAL_PERMISSIONS_FILE,\n\tPROJECT_PERMISSIONS_FILE,\n\tprojectResourcePathByName,\n} from \"../project-resources.ts\";\nimport type { PermissionBehavior } from \"../tools/contract.ts\";\nimport type { PermissionRule, PermissionSource } from \"./rules.ts\";\n\nexport const PERMISSION_MODES = [\"default\", \"plan\", \"acceptEdits\", \"bypassPermissions\", \"dontAsk\"] as const;\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\n/** Sources a PermissionUpdate may target. Excludes `policy` (administrator-managed,\n * never user-writable) and `flag`/`cliArg` (parsed once from argv at startup, not\n * something this store updates after the fact). */\nexport const WRITABLE_PERMISSION_SOURCES = [\"local\", \"project\", \"user\", \"command\", \"session\"] as const;\nexport type WritablePermissionSource = (typeof WRITABLE_PERMISSION_SOURCES)[number];\n\nconst FILE_BACKED_SOURCES = [\"local\", \"project\", \"user\"] as const;\ntype FileBackedSource = (typeof FILE_BACKED_SOURCES)[number];\n\nconst RUNTIME_SOURCES = [\"command\", \"session\"] as const;\ntype RuntimeSource = (typeof RUNTIME_SOURCES)[number];\n\n/** A rule as persisted: `source` is never stored — it is implied by which file it came from. */\nexport type StoredPermissionRule = Omit<PermissionRule, \"source\">;\n\nexport interface RuleMatcher {\n\ttoolName: string;\n\truleContent?: string;\n}\n\nexport type PermissionUpdate =\n\t| { type: \"addRules\"; destination: WritablePermissionSource; rules: readonly StoredPermissionRule[] }\n\t| { type: \"replaceRules\"; destination: WritablePermissionSource; rules: readonly StoredPermissionRule[] }\n\t| { type: \"removeRules\"; destination: WritablePermissionSource; matching: readonly RuleMatcher[] }\n\t| { type: \"setMode\"; destination: WritablePermissionSource; mode: PermissionMode };\n\nexport interface PermissionStoreError {\n\tsource: PermissionSource;\n\terror: Error;\n}\n\nexport interface PermissionStoreSnapshot {\n\trules: readonly PermissionRule[];\n\tmodesBySource: ReadonlyMap<WritablePermissionSource, PermissionMode>;\n\terrors: readonly PermissionStoreError[];\n}\n\nexport interface PermissionRuleStore {\n\tsnapshot(): Promise<PermissionStoreSnapshot>;\n\tapply(update: PermissionUpdate): Promise<void>;\n}\n\nconst STORE_VERSION = 1;\n\ninterface StoredPermissionScope {\n\tversion: number;\n\trules: StoredPermissionRule[];\n\tmode?: PermissionMode;\n}\n\nfunction emptyScope(): StoredPermissionScope {\n\treturn { version: STORE_VERSION, rules: [] };\n}\n\n/**\n * Whether a permission file's contents grant anything. The trust classifier asks this\n * so a `{}` file does not raise a prompt that carries no decision. Unparseable content\n * counts as granting: a malformed or hostile file must prompt rather than pass.\n */\nexport function permissionContentConfersAuthority(content: string | undefined): boolean {\n\tlet scope: StoredPermissionScope;\n\ttry {\n\t\tscope = parseScope(content);\n\t} catch {\n\t\treturn true;\n\t}\n\treturn scope.rules.length > 0 || scope.mode !== undefined;\n}\n\nfunction isPermissionBehavior(value: unknown): value is PermissionBehavior {\n\treturn value === \"allow\" || value === \"deny\" || value === \"ask\";\n}\n\nfunction parseScope(content: string | undefined): StoredPermissionScope {\n\tif (!content) return emptyScope();\n\tconst parsed = JSON.parse(content);\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(\"Invalid permission rules file: unexpected shape\");\n\t}\n\t// FileAuthStorageBackend (shared with auth.json) seeds a freshly created file\n\t// with the literal text \"{}\". Treat a content-free object as \"nothing written\n\t// yet\" rather than malformed; a real malformed file has some recognizable but\n\t// wrong-shaped field, caught below.\n\tif (!(\"version\" in parsed) && !(\"rules\" in parsed) && !(\"mode\" in parsed)) {\n\t\treturn emptyScope();\n\t}\n\tif (\n\t\tparsed.version !== STORE_VERSION ||\n\t\t(parsed.mode !== undefined && !(PERMISSION_MODES as readonly string[]).includes(parsed.mode)) ||\n\t\t!Array.isArray(parsed.rules) ||\n\t\t!parsed.rules.every(\n\t\t\t(rule: unknown) =>\n\t\t\t\ttypeof rule === \"object\" &&\n\t\t\t\trule !== null &&\n\t\t\t\ttypeof (rule as StoredPermissionRule).toolName === \"string\" &&\n\t\t\t\tisPermissionBehavior((rule as StoredPermissionRule).behavior) &&\n\t\t\t\t((rule as StoredPermissionRule).ruleContent === undefined ||\n\t\t\t\t\ttypeof (rule as StoredPermissionRule).ruleContent === \"string\"),\n\t\t)\n\t) {\n\t\tthrow new Error(\"Invalid permission rules file: unexpected shape\");\n\t}\n\treturn parsed as StoredPermissionScope;\n}\n\nfunction applyToScope(scope: StoredPermissionScope, update: PermissionUpdate): StoredPermissionScope {\n\tswitch (update.type) {\n\t\tcase \"addRules\":\n\t\t\treturn { ...scope, rules: [...scope.rules, ...update.rules] };\n\t\tcase \"replaceRules\":\n\t\t\treturn { ...scope, rules: [...update.rules] };\n\t\tcase \"removeRules\":\n\t\t\treturn {\n\t\t\t\t...scope,\n\t\t\t\trules: scope.rules.filter(\n\t\t\t\t\t(rule) =>\n\t\t\t\t\t\t!update.matching.some((m) => m.toolName === rule.toolName && m.ruleContent === rule.ruleContent),\n\t\t\t\t),\n\t\t\t};\n\t\tcase \"setMode\":\n\t\t\treturn { ...scope, mode: update.mode };\n\t}\n}\n\nfunction defaultPolicyPath(): string {\n\tif (process.env.APEX_CODE_POLICY_PATH) return process.env.APEX_CODE_POLICY_PATH;\n\treturn process.platform === \"win32\"\n\t\t? join(process.env.ProgramData ?? \"C:\\\\ProgramData\", \"apex-code\", \"policy.json\")\n\t\t: \"/etc/apex-code/policy.json\";\n}\n\nexport interface CreateFilePermissionRuleStoreOptions {\n\tcwd: string;\n\tagentDir?: string;\n\t/** Overrides the managed policy file path. Defaults to $APEX_CODE_POLICY_PATH, else an OS-specific system location. */\n\tpolicyPath?: string;\n\t/** Test seam: inject backends for the three writable file-backed sources instead of touching real files. */\n\tbackends?: Partial<Record<FileBackedSource, AuthStorageBackend>>;\n\t/** Immutable argv layers (`flag` / `cliArg`), validated by the CLI before construction. */\n\tinitialRules?: readonly PermissionRule[];\n\t/**\n\t * Resolved before construction. False excludes both project-controlled scopes.\n\t *\n\t * Required, per ADR 0034. There is no correct default: a caller that has not resolved\n\t * trust cannot be given either answer about an untrusted checkout.\n\t */\n\tprojectTrusted: boolean;\n}\n\n/** File-backed store for policy/local/project/user, in-memory for command/session. */\nexport class FilePermissionRuleStore implements PermissionRuleStore {\n\tprivate readonly backends: Record<FileBackedSource, AuthStorageBackend>;\n\tprivate readonly policyPath: string;\n\tprivate readonly initialRules: readonly PermissionRule[];\n\tprivate readonly runtimeRules: Record<RuntimeSource, StoredPermissionRule[]> = { command: [], session: [] };\n\tprivate readonly runtimeModes: Partial<Record<RuntimeSource, PermissionMode>> = {};\n\tprivate readonly projectTrusted: boolean;\n\tprivate readonly fileScopes: Partial<\n\t\tRecord<FileBackedSource, Promise<{ scope: StoredPermissionScope; error?: Error }>>\n\t> = {};\n\tprivate readonly fileScopeUpdates: Partial<Record<FileBackedSource, Promise<void>>> = {};\n\n\tconstructor(options: CreateFilePermissionRuleStoreOptions) {\n\t\tconst agentDir = options.agentDir ?? getAgentDir();\n\t\tconst cwd = resolvePath(options.cwd);\n\t\tthis.backends = {\n\t\t\tuser: new FileAuthStorageBackend(join(agentDir, \"permissions.json\")),\n\t\t\tproject: new FileAuthStorageBackend(projectResourcePathByName(cwd, PROJECT_PERMISSIONS_FILE)),\n\t\t\tlocal: new FileAuthStorageBackend(projectResourcePathByName(cwd, PROJECT_LOCAL_PERMISSIONS_FILE)),\n\t\t\t...options.backends,\n\t\t};\n\t\tthis.policyPath = options.policyPath ?? defaultPolicyPath();\n\t\tthis.initialRules = options.initialRules ?? [];\n\t\t// A JavaScript caller reaches this with no compiler in between, so the type is not\n\t\t// the whole guard. ADR 0034.\n\t\tif (typeof options.projectTrusted !== \"boolean\") {\n\t\t\tthrow new TypeError(\"FilePermissionRuleStore requires an explicit projectTrusted decision (ADR 0034)\");\n\t\t}\n\t\tthis.projectTrusted = options.projectTrusted;\n\t\tif (!this.projectTrusted) {\n\t\t\tthis.fileScopes.local = Promise.resolve({ scope: emptyScope() });\n\t\t\tthis.fileScopes.project = Promise.resolve({ scope: emptyScope() });\n\t\t}\n\t}\n\n\tprivate capturedFileBackedScope(source: FileBackedSource): Promise<{ scope: StoredPermissionScope; error?: Error }> {\n\t\tconst captured = this.fileScopes[source];\n\t\tif (captured) return captured;\n\t\tconst initial = this.readFileBackedScope(source);\n\t\tthis.fileScopes[source] = initial;\n\t\treturn initial;\n\t}\n\n\tprivate async readFileBackedScope(\n\t\tsource: FileBackedSource,\n\t): Promise<{ scope: StoredPermissionScope; error?: Error }> {\n\t\ttry {\n\t\t\tlet content: string | undefined;\n\t\t\tawait this.backends[source].withLockAsync(async (current) => {\n\t\t\t\tcontent = current;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\treturn { scope: parseScope(content) };\n\t\t} catch (error) {\n\t\t\treturn { scope: emptyScope(), error: error instanceof Error ? error : new Error(String(error)) };\n\t\t}\n\t}\n\n\tprivate async readPolicy(): Promise<{ scope: StoredPermissionScope; error?: Error }> {\n\t\ttry {\n\t\t\tconst content = await readFile(this.policyPath, \"utf-8\");\n\t\t\treturn { scope: parseScope(content) };\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { scope: emptyScope() };\n\t\t\treturn { scope: emptyScope(), error: error instanceof Error ? error : new Error(String(error)) };\n\t\t}\n\t}\n\n\tprivate capturedPolicyAndUser(): Promise<{\n\t\tpolicy: { scope: StoredPermissionScope; error?: Error };\n\t\tuser: { scope: StoredPermissionScope; error?: Error };\n\t}> {\n\t\treturn Promise.all([this.readPolicy(), this.capturedFileBackedScope(\"user\")]).then(([policy, user]) => ({\n\t\t\tpolicy,\n\t\t\tuser,\n\t\t}));\n\t}\n\n\tasync snapshot(): Promise<PermissionStoreSnapshot> {\n\t\t// File-backed authorization is captured once. Direct filesystem writes,\n\t\t// including symlink replacement, cannot widen the current or next gate\n\t\t// decision. Managed policy and runtime scopes remain live.\n\t\tconst [policyAndUser, local, project] = await Promise.all([\n\t\t\tthis.capturedPolicyAndUser(),\n\t\t\tthis.capturedFileBackedScope(\"local\"),\n\t\t\tthis.capturedFileBackedScope(\"project\"),\n\t\t]);\n\t\tconst { policy, user } = policyAndUser;\n\t\tconst errors: PermissionStoreError[] = [];\n\t\tconst withSource = (\n\t\t\tsource: PermissionSource,\n\t\t\tentry: { scope: StoredPermissionScope; error?: Error },\n\t\t): PermissionRule[] => {\n\t\t\tif (entry.error) errors.push({ source, error: entry.error });\n\t\t\treturn entry.scope.rules.map((rule) => ({ ...rule, source }));\n\t\t};\n\n\t\tconst rules: PermissionRule[] = [\n\t\t\t...withSource(\"policy\", policy),\n\t\t\t...this.initialRules,\n\t\t\t...withSource(\"local\", local),\n\t\t\t...withSource(\"project\", project),\n\t\t\t...withSource(\"user\", user),\n\t\t\t...this.runtimeRules.command.map((rule) => ({ ...rule, source: \"command\" as const })),\n\t\t\t...this.runtimeRules.session.map((rule) => ({ ...rule, source: \"session\" as const })),\n\t\t];\n\n\t\tconst modesBySource = new Map<WritablePermissionSource, PermissionMode>();\n\t\tif (local.scope.mode) modesBySource.set(\"local\", local.scope.mode);\n\t\tif (project.scope.mode) modesBySource.set(\"project\", project.scope.mode);\n\t\tif (user.scope.mode) modesBySource.set(\"user\", user.scope.mode);\n\t\tif (this.runtimeModes.command) modesBySource.set(\"command\", this.runtimeModes.command);\n\t\tif (this.runtimeModes.session) modesBySource.set(\"session\", this.runtimeModes.session);\n\n\t\treturn { rules, modesBySource, errors };\n\t}\n\n\tasync apply(update: PermissionUpdate): Promise<void> {\n\t\tif (update.destination === \"command\" || update.destination === \"session\") {\n\t\t\tthis.applyRuntime(update.destination, update);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.projectTrusted && (update.destination === \"local\" || update.destination === \"project\")) {\n\t\t\tthrow new Error(`Cannot update untrusted ${update.destination} permission scope`);\n\t\t}\n\t\tconst destination = update.destination;\n\t\tconst previousUpdate = this.fileScopeUpdates[destination]?.catch(() => undefined) ?? Promise.resolve();\n\t\tconst nextUpdate = previousUpdate.then(async () => {\n\t\t\tconst current = await this.capturedFileBackedScope(destination);\n\t\t\tconst next = applyToScope(current.scope, update);\n\t\t\tawait this.backends[destination].withLockAsync(async () => ({\n\t\t\t\tresult: undefined,\n\t\t\t\tnext: JSON.stringify(next, null, 2),\n\t\t\t}));\n\t\t\tthis.fileScopes[destination] = Promise.resolve({ scope: next });\n\t\t});\n\t\tthis.fileScopeUpdates[destination] = nextUpdate;\n\t\tawait nextUpdate;\n\t}\n\n\tprivate applyRuntime(destination: RuntimeSource, update: PermissionUpdate): void {\n\t\tif (update.type === \"setMode\") {\n\t\t\tthis.runtimeModes[destination] = update.mode;\n\t\t\treturn;\n\t\t}\n\t\tconst current: StoredPermissionScope = { version: STORE_VERSION, rules: this.runtimeRules[destination] };\n\t\tthis.runtimeRules[destination] = applyToScope(current, update).rules;\n\t}\n}\n\nexport interface DerivedPermissionRuleStoreOptions {\n\t/** The parent's live store. Read fresh on every `snapshot()`, never cached, so a\n\t * rule the parent picks up mid-session (e.g. a human's \"always allow\") is visible\n\t * to the child on its very next call. */\n\tparent: PermissionRuleStore;\n}\n\n/**\n * A delegated child's permission store (roadmap Phase 5, ADR 0008). A read-through\n * view over the parent's live snapshot -- including its runtime-only sources\n * (`flag`, `cliArg`, `command`, `session`), which a subprocess-spawned child could\n * never observe -- plus a child-local runtime overlay for the child's own writes.\n *\n * `apply()` never reaches the parent. It writes only into this instance's own\n * overlay, and only for the two runtime-only writable sources (`command`, `session`);\n * a file-backed destination (`local`, `project`, `user`) is rejected outright, not\n * silently redirected -- a delegated child must never be able to persist to the\n * parent's settings files, and \"runtime-only\" is enforced by construction here, not\n * by a convention a future caller could forget. The overlay is discarded with the\n * child: there is no code path from a child's approval back into the parent's store,\n * which is what keeps a child's `persist: true` from widening its parent.\n */\nexport class DerivedPermissionRuleStore implements PermissionRuleStore {\n\tprivate readonly parent: PermissionRuleStore;\n\tprivate readonly overlayRules: Record<RuntimeSource, StoredPermissionRule[]> = { command: [], session: [] };\n\tprivate readonly overlayModes: Partial<Record<RuntimeSource, PermissionMode>> = {};\n\n\tconstructor(options: DerivedPermissionRuleStoreOptions) {\n\t\tthis.parent = options.parent;\n\t}\n\n\tasync snapshot(): Promise<PermissionStoreSnapshot> {\n\t\tconst parentSnapshot = await this.parent.snapshot();\n\t\tconst rules: PermissionRule[] = [\n\t\t\t...parentSnapshot.rules,\n\t\t\t...this.overlayRules.command.map((rule) => ({ ...rule, source: \"command\" as const })),\n\t\t\t...this.overlayRules.session.map((rule) => ({ ...rule, source: \"session\" as const })),\n\t\t];\n\t\tconst modesBySource = new Map(parentSnapshot.modesBySource);\n\t\tif (this.overlayModes.command !== undefined) modesBySource.set(\"command\", this.overlayModes.command);\n\t\tif (this.overlayModes.session !== undefined) modesBySource.set(\"session\", this.overlayModes.session);\n\t\treturn { rules, modesBySource, errors: parentSnapshot.errors };\n\t}\n\n\tasync apply(update: PermissionUpdate): Promise<void> {\n\t\tif (update.destination !== \"command\" && update.destination !== \"session\") {\n\t\t\tthrow new Error(\n\t\t\t\t`A delegated child cannot persist permission rules to \"${update.destination}\" -- only \"command\" and \"session\" are writable from a derived store (ADR 0008).`,\n\t\t\t);\n\t\t}\n\t\tif (update.type === \"setMode\") {\n\t\t\tthis.overlayModes[update.destination] = update.mode;\n\t\t\treturn;\n\t\t}\n\t\tconst current: StoredPermissionScope = {\n\t\t\tversion: STORE_VERSION,\n\t\t\trules: this.overlayRules[update.destination],\n\t\t};\n\t\tthis.overlayRules[update.destination] = applyToScope(current, update).rules;\n\t}\n}\n"]}
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/core/permissions/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAMH,OAAO,EAAE,KAAK,kBAAkB,EAA0B,MAAM,oBAAoB,CAAC;AAOrF,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnE,eAAO,MAAM,gBAAgB,6EAA8E,CAAC;AAC5G,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/D;;mDAEmD;AACnD,eAAO,MAAM,2BAA2B,6DAA8D,CAAC;AACvG,MAAM,MAAM,wBAAwB,GAAG,CAAC,OAAO,2BAA2B,CAAC,CAAC,MAAM,CAAC,CAAC;AAEpF,QAAA,MAAM,mBAAmB,uCAAwC,CAAC;AAClE,KAAK,gBAAgB,GAAG,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;AAK7D,kGAAgG;AAChG,MAAM,MAAM,oBAAoB,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;AAElE,MAAM,WAAW,WAAW;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,MAAM,gBAAgB,GACzB;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,WAAW,EAAE,wBAAwB,CAAC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model (ADR 0004). Four of the eight sources\n * are file-backed (policy, local, project, user); the other four are runtime-only\n * (flag, cliArg — parsed once from argv, not stored here; command, session — held\n * in memory for the life of the process). `session`-source updates are never\n * written to disk: \"allow for this session\" dies with the session by design.\n *\n * Reuses the locked-JSON-file backend already proven for Phase 1's operational\n * state (FileAuthStorageBackend) rather than widening `SettingsScope`, which only\n * covers two of these four file-backed sources and represents a different, larger\n * settings domain.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../../config.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { type AuthStorageBackend, FileAuthStorageBackend } from \"../auth-storage.ts\";\nimport {\n\tPROJECT_LOCAL_PERMISSIONS_FILE,\n\tPROJECT_PERMISSIONS_FILE,\n\tprojectResourcePathByName,\n} from \"../project-resources.ts\";\nimport type { PermissionBehavior } from \"../tools/contract.ts\";\nimport type { PermissionRule, PermissionSource } from \"./rules.ts\";\n\nexport const PERMISSION_MODES = [\"default\", \"plan\", \"acceptEdits\", \"bypassPermissions\", \"dontAsk\"] as const;\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\n/** Sources a PermissionUpdate may target. Excludes `policy` (administrator-managed,\n * never user-writable) and `flag`/`cliArg` (parsed once from argv at startup, not\n * something this store updates after the fact). */\nexport const WRITABLE_PERMISSION_SOURCES = [\"local\", \"project\", \"user\", \"command\", \"session\"] as const;\nexport type WritablePermissionSource = (typeof WRITABLE_PERMISSION_SOURCES)[number];\n\nconst FILE_BACKED_SOURCES = [\"local\", \"project\", \"user\"] as const;\ntype FileBackedSource = (typeof FILE_BACKED_SOURCES)[number];\n\nconst RUNTIME_SOURCES = [\"command\", \"session\"] as const;\ntype RuntimeSource = (typeof RUNTIME_SOURCES)[number];\n\n/** A rule as persisted: `source` is never stored — it is implied by which file it came from. */\nexport type StoredPermissionRule = Omit<PermissionRule, \"source\">;\n\nexport interface RuleMatcher {\n\ttoolName: string;\n\truleContent?: string;\n}\n\nexport type PermissionUpdate =\n\t| { type: \"addRules\"; destination: WritablePermissionSource; rules: readonly StoredPermissionRule[] }\n\t| { type: \"replaceRules\"; destination: WritablePermissionSource; rules: readonly StoredPermissionRule[] }\n\t| { type: \"removeRules\"; destination: WritablePermissionSource; matching: readonly RuleMatcher[] }\n\t| { type: \"setMode\"; destination: WritablePermissionSource; mode: PermissionMode };\n\nexport interface PermissionStoreError {\n\tsource: PermissionSource;\n\terror: Error;\n}\n\nexport interface PermissionStoreSnapshot {\n\trules: readonly PermissionRule[];\n\tmodesBySource: ReadonlyMap<WritablePermissionSource, PermissionMode>;\n\terrors: readonly PermissionStoreError[];\n}\n\nexport interface PermissionRuleStore {\n\tsnapshot(): Promise<PermissionStoreSnapshot>;\n\tapply(update: PermissionUpdate): Promise<void>;\n}\n\nconst STORE_VERSION = 1;\n\ninterface StoredPermissionScope {\n\tversion: number;\n\trules: StoredPermissionRule[];\n\tmode?: PermissionMode;\n}\n\nfunction emptyScope(): StoredPermissionScope {\n\treturn { version: STORE_VERSION, rules: [] };\n}\n\n/**\n * Whether a permission file's contents grant anything. The trust classifier asks this\n * so a `{}` file does not raise a prompt that carries no decision. Unparseable content\n * counts as granting: a malformed or hostile file must prompt rather than pass.\n */\nexport function permissionContentConfersAuthority(content: string | undefined): boolean {\n\tlet scope: StoredPermissionScope;\n\ttry {\n\t\tscope = parseScope(content);\n\t} catch {\n\t\treturn true;\n\t}\n\treturn scope.rules.length > 0 || scope.mode !== undefined;\n}\n\nfunction isPermissionBehavior(value: unknown): value is PermissionBehavior {\n\treturn value === \"allow\" || value === \"deny\" || value === \"ask\";\n}\n\nfunction parseScope(content: string | undefined): StoredPermissionScope {\n\tif (!content) return emptyScope();\n\tconst parsed = JSON.parse(content);\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(\"Invalid permission rules file: unexpected shape\");\n\t}\n\t// FileAuthStorageBackend (shared with auth.json) seeds a freshly created file\n\t// with the literal text \"{}\". Treat a content-free object as \"nothing written\n\t// yet\" rather than malformed; a real malformed file has some recognizable but\n\t// wrong-shaped field, caught below.\n\tif (!(\"version\" in parsed) && !(\"rules\" in parsed) && !(\"mode\" in parsed)) {\n\t\treturn emptyScope();\n\t}\n\tif (\n\t\tparsed.version !== STORE_VERSION ||\n\t\t(parsed.mode !== undefined && !(PERMISSION_MODES as readonly string[]).includes(parsed.mode)) ||\n\t\t!Array.isArray(parsed.rules) ||\n\t\t!parsed.rules.every(\n\t\t\t(rule: unknown) =>\n\t\t\t\ttypeof rule === \"object\" &&\n\t\t\t\trule !== null &&\n\t\t\t\ttypeof (rule as StoredPermissionRule).toolName === \"string\" &&\n\t\t\t\tisPermissionBehavior((rule as StoredPermissionRule).behavior) &&\n\t\t\t\t((rule as StoredPermissionRule).ruleContent === undefined ||\n\t\t\t\t\ttypeof (rule as StoredPermissionRule).ruleContent === \"string\"),\n\t\t)\n\t) {\n\t\tthrow new Error(\"Invalid permission rules file: unexpected shape\");\n\t}\n\treturn parsed as StoredPermissionScope;\n}\n\nfunction applyToScope(scope: StoredPermissionScope, update: PermissionUpdate): StoredPermissionScope {\n\tswitch (update.type) {\n\t\tcase \"addRules\":\n\t\t\treturn { ...scope, rules: [...scope.rules, ...update.rules] };\n\t\tcase \"replaceRules\":\n\t\t\treturn { ...scope, rules: [...update.rules] };\n\t\tcase \"removeRules\":\n\t\t\treturn {\n\t\t\t\t...scope,\n\t\t\t\trules: scope.rules.filter(\n\t\t\t\t\t(rule) =>\n\t\t\t\t\t\t!update.matching.some((m) => m.toolName === rule.toolName && m.ruleContent === rule.ruleContent),\n\t\t\t\t),\n\t\t\t};\n\t\tcase \"setMode\":\n\t\t\treturn { ...scope, mode: update.mode };\n\t}\n}\n\nfunction defaultPolicyPath(): string {\n\tif (process.env.APEX_CODE_POLICY_PATH) return process.env.APEX_CODE_POLICY_PATH;\n\treturn process.platform === \"win32\"\n\t\t? join(process.env.ProgramData ?? \"C:\\\\ProgramData\", \"apex-code\", \"policy.json\")\n\t\t: \"/etc/apex-code/policy.json\";\n}\n\nexport interface CreateFilePermissionRuleStoreOptions {\n\tcwd: string;\n\tagentDir?: string;\n\t/** Overrides the managed policy file path. Defaults to $APEX_CODE_POLICY_PATH, else an OS-specific system location. */\n\tpolicyPath?: string;\n\t/** Test seam: inject backends for the three writable file-backed sources instead of touching real files. */\n\tbackends?: Partial<Record<FileBackedSource, AuthStorageBackend>>;\n\t/** Immutable argv layers (`flag` / `cliArg`), validated by the CLI before construction. */\n\tinitialRules?: readonly PermissionRule[];\n\t/**\n\t * Resolved before construction. False excludes both project-controlled scopes.\n\t *\n\t * Required, per ADR 0034. There is no correct default: a caller that has not resolved\n\t * trust cannot be given either answer about an untrusted checkout.\n\t */\n\tprojectTrusted: boolean;\n}\n\n/** File-backed store for policy/local/project/user, in-memory for command/session. */\nexport class FilePermissionRuleStore implements PermissionRuleStore {\n\tprivate readonly backends: Record<FileBackedSource, AuthStorageBackend>;\n\tprivate readonly policyPath: string;\n\tprivate readonly initialRules: readonly PermissionRule[];\n\tprivate readonly runtimeRules: Record<RuntimeSource, StoredPermissionRule[]> = { command: [], session: [] };\n\tprivate readonly runtimeModes: Partial<Record<RuntimeSource, PermissionMode>> = {};\n\tprivate readonly projectTrusted: boolean;\n\tprivate readonly fileScopes: Partial<\n\t\tRecord<FileBackedSource, Promise<{ scope: StoredPermissionScope; error?: Error }>>\n\t> = {};\n\tprivate readonly fileScopeUpdates: Partial<Record<FileBackedSource, Promise<void>>> = {};\n\n\tconstructor(options: CreateFilePermissionRuleStoreOptions) {\n\t\tconst agentDir = options.agentDir ?? getAgentDir();\n\t\tconst cwd = resolvePath(options.cwd);\n\t\tconst paths: Record<FileBackedSource, string> = {\n\t\t\tuser: join(agentDir, \"permissions.json\"),\n\t\t\tproject: projectResourcePathByName(cwd, PROJECT_PERMISSIONS_FILE),\n\t\t\tlocal: projectResourcePathByName(cwd, PROJECT_LOCAL_PERMISSIONS_FILE),\n\t\t};\n\t\tthis.backends = {\n\t\t\tuser: new FileAuthStorageBackend(paths.user),\n\t\t\tproject: new FileAuthStorageBackend(paths.project),\n\t\t\tlocal: new FileAuthStorageBackend(paths.local),\n\t\t\t...options.backends,\n\t\t};\n\t\tthis.policyPath = options.policyPath ?? defaultPolicyPath();\n\t\tthis.initialRules = options.initialRules ?? [];\n\t\t// A JavaScript caller reaches this with no compiler in between, so the type is not\n\t\t// the whole guard. ADR 0034.\n\t\tif (typeof options.projectTrusted !== \"boolean\") {\n\t\t\tthrow new TypeError(\"FilePermissionRuleStore requires an explicit projectTrusted decision (ADR 0034)\");\n\t\t}\n\t\tthis.projectTrusted = options.projectTrusted;\n\t\tif (!this.projectTrusted) {\n\t\t\tthis.fileScopes.local = Promise.resolve({ scope: emptyScope() });\n\t\t\tthis.fileScopes.project = Promise.resolve({ scope: emptyScope() });\n\t\t}\n\t}\n\n\tprivate capturedFileBackedScope(source: FileBackedSource): Promise<{ scope: StoredPermissionScope; error?: Error }> {\n\t\tconst captured = this.fileScopes[source];\n\t\tif (captured) return captured;\n\t\tconst initial = this.readFileBackedScope(source);\n\t\tthis.fileScopes[source] = initial;\n\t\treturn initial;\n\t}\n\n\tprivate async readFileBackedScope(\n\t\tsource: FileBackedSource,\n\t): Promise<{ scope: StoredPermissionScope; error?: Error }> {\n\t\ttry {\n\t\t\tconst content = await this.backends[source].withReadLockAsync(async (current) => current);\n\t\t\treturn { scope: parseScope(content) };\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException)?.code === \"ENOENT\") return { scope: emptyScope() };\n\t\t\treturn { scope: emptyScope(), error: error instanceof Error ? error : new Error(String(error)) };\n\t\t}\n\t}\n\n\tprivate async readPolicy(): Promise<{ scope: StoredPermissionScope; error?: Error }> {\n\t\ttry {\n\t\t\tconst content = await readFile(this.policyPath, \"utf-8\");\n\t\t\treturn { scope: parseScope(content) };\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { scope: emptyScope() };\n\t\t\treturn { scope: emptyScope(), error: error instanceof Error ? error : new Error(String(error)) };\n\t\t}\n\t}\n\n\tprivate capturedPolicyAndUser(): Promise<{\n\t\tpolicy: { scope: StoredPermissionScope; error?: Error };\n\t\tuser: { scope: StoredPermissionScope; error?: Error };\n\t}> {\n\t\treturn Promise.all([this.readPolicy(), this.capturedFileBackedScope(\"user\")]).then(([policy, user]) => ({\n\t\t\tpolicy,\n\t\t\tuser,\n\t\t}));\n\t}\n\n\tasync snapshot(): Promise<PermissionStoreSnapshot> {\n\t\t// File-backed authorization is captured once. Direct filesystem writes,\n\t\t// including symlink replacement, cannot widen the current or next gate\n\t\t// decision. Managed policy and runtime scopes remain live.\n\t\tconst [policyAndUser, local, project] = await Promise.all([\n\t\t\tthis.capturedPolicyAndUser(),\n\t\t\tthis.capturedFileBackedScope(\"local\"),\n\t\t\tthis.capturedFileBackedScope(\"project\"),\n\t\t]);\n\t\tconst { policy, user } = policyAndUser;\n\t\tconst errors: PermissionStoreError[] = [];\n\t\tconst withSource = (\n\t\t\tsource: PermissionSource,\n\t\t\tentry: { scope: StoredPermissionScope; error?: Error },\n\t\t): PermissionRule[] => {\n\t\t\tif (entry.error) errors.push({ source, error: entry.error });\n\t\t\treturn entry.scope.rules.map((rule) => ({ ...rule, source }));\n\t\t};\n\n\t\tconst rules: PermissionRule[] = [\n\t\t\t...withSource(\"policy\", policy),\n\t\t\t...this.initialRules,\n\t\t\t...withSource(\"local\", local),\n\t\t\t...withSource(\"project\", project),\n\t\t\t...withSource(\"user\", user),\n\t\t\t...this.runtimeRules.command.map((rule) => ({ ...rule, source: \"command\" as const })),\n\t\t\t...this.runtimeRules.session.map((rule) => ({ ...rule, source: \"session\" as const })),\n\t\t];\n\n\t\tconst modesBySource = new Map<WritablePermissionSource, PermissionMode>();\n\t\tif (local.scope.mode) modesBySource.set(\"local\", local.scope.mode);\n\t\tif (project.scope.mode) modesBySource.set(\"project\", project.scope.mode);\n\t\tif (user.scope.mode) modesBySource.set(\"user\", user.scope.mode);\n\t\tif (this.runtimeModes.command) modesBySource.set(\"command\", this.runtimeModes.command);\n\t\tif (this.runtimeModes.session) modesBySource.set(\"session\", this.runtimeModes.session);\n\n\t\treturn { rules, modesBySource, errors };\n\t}\n\n\tasync apply(update: PermissionUpdate): Promise<void> {\n\t\tif (update.destination === \"command\" || update.destination === \"session\") {\n\t\t\tthis.applyRuntime(update.destination, update);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.projectTrusted && (update.destination === \"local\" || update.destination === \"project\")) {\n\t\t\tthrow new Error(`Cannot update untrusted ${update.destination} permission scope`);\n\t\t}\n\t\tconst destination = update.destination;\n\t\tconst previousUpdate = this.fileScopeUpdates[destination]?.catch(() => undefined) ?? Promise.resolve();\n\t\tconst nextUpdate = previousUpdate.then(async () => {\n\t\t\tconst current = await this.capturedFileBackedScope(destination);\n\t\t\tconst next = applyToScope(current.scope, update);\n\t\t\tawait this.backends[destination].withLockAsync(async () => ({\n\t\t\t\tresult: undefined,\n\t\t\t\tnext: JSON.stringify(next, null, 2),\n\t\t\t}));\n\t\t\tthis.fileScopes[destination] = Promise.resolve({ scope: next });\n\t\t});\n\t\tthis.fileScopeUpdates[destination] = nextUpdate;\n\t\tawait nextUpdate;\n\t}\n\n\tprivate applyRuntime(destination: RuntimeSource, update: PermissionUpdate): void {\n\t\tif (update.type === \"setMode\") {\n\t\t\tthis.runtimeModes[destination] = update.mode;\n\t\t\treturn;\n\t\t}\n\t\tconst current: StoredPermissionScope = { version: STORE_VERSION, rules: this.runtimeRules[destination] };\n\t\tthis.runtimeRules[destination] = applyToScope(current, update).rules;\n\t}\n}\n\nexport interface DerivedPermissionRuleStoreOptions {\n\t/** The parent's live store. Read fresh on every `snapshot()`, never cached, so a\n\t * rule the parent picks up mid-session (e.g. a human's \"always allow\") is visible\n\t * to the child on its very next call. */\n\tparent: PermissionRuleStore;\n}\n\n/**\n * A delegated child's permission store (roadmap Phase 5, ADR 0008). A read-through\n * view over the parent's live snapshot -- including its runtime-only sources\n * (`flag`, `cliArg`, `command`, `session`), which a subprocess-spawned child could\n * never observe -- plus a child-local runtime overlay for the child's own writes.\n *\n * `apply()` never reaches the parent. It writes only into this instance's own\n * overlay, and only for the two runtime-only writable sources (`command`, `session`);\n * a file-backed destination (`local`, `project`, `user`) is rejected outright, not\n * silently redirected -- a delegated child must never be able to persist to the\n * parent's settings files, and \"runtime-only\" is enforced by construction here, not\n * by a convention a future caller could forget. The overlay is discarded with the\n * child: there is no code path from a child's approval back into the parent's store,\n * which is what keeps a child's `persist: true` from widening its parent.\n */\nexport class DerivedPermissionRuleStore implements PermissionRuleStore {\n\tprivate readonly parent: PermissionRuleStore;\n\tprivate readonly overlayRules: Record<RuntimeSource, StoredPermissionRule[]> = { command: [], session: [] };\n\tprivate readonly overlayModes: Partial<Record<RuntimeSource, PermissionMode>> = {};\n\n\tconstructor(options: DerivedPermissionRuleStoreOptions) {\n\t\tthis.parent = options.parent;\n\t}\n\n\tasync snapshot(): Promise<PermissionStoreSnapshot> {\n\t\tconst parentSnapshot = await this.parent.snapshot();\n\t\tconst rules: PermissionRule[] = [\n\t\t\t...parentSnapshot.rules,\n\t\t\t...this.overlayRules.command.map((rule) => ({ ...rule, source: \"command\" as const })),\n\t\t\t...this.overlayRules.session.map((rule) => ({ ...rule, source: \"session\" as const })),\n\t\t];\n\t\tconst modesBySource = new Map(parentSnapshot.modesBySource);\n\t\tif (this.overlayModes.command !== undefined) modesBySource.set(\"command\", this.overlayModes.command);\n\t\tif (this.overlayModes.session !== undefined) modesBySource.set(\"session\", this.overlayModes.session);\n\t\treturn { rules, modesBySource, errors: parentSnapshot.errors };\n\t}\n\n\tasync apply(update: PermissionUpdate): Promise<void> {\n\t\tif (update.destination !== \"command\" && update.destination !== \"session\") {\n\t\t\tthrow new Error(\n\t\t\t\t`A delegated child cannot persist permission rules to \"${update.destination}\" -- only \"command\" and \"session\" are writable from a derived store (ADR 0008).`,\n\t\t\t);\n\t\t}\n\t\tif (update.type === \"setMode\") {\n\t\t\tthis.overlayModes[update.destination] = update.mode;\n\t\t\treturn;\n\t\t}\n\t\tconst current: StoredPermissionScope = {\n\t\t\tversion: STORE_VERSION,\n\t\t\trules: this.overlayRules[update.destination],\n\t\t};\n\t\tthis.overlayRules[update.destination] = applyToScope(current, update).rules;\n\t}\n}\n"]}
@@ -107,10 +107,15 @@ export class FilePermissionRuleStore {
107
107
  constructor(options) {
108
108
  const agentDir = options.agentDir ?? getAgentDir();
109
109
  const cwd = resolvePath(options.cwd);
110
+ const paths = {
111
+ user: join(agentDir, "permissions.json"),
112
+ project: projectResourcePathByName(cwd, PROJECT_PERMISSIONS_FILE),
113
+ local: projectResourcePathByName(cwd, PROJECT_LOCAL_PERMISSIONS_FILE),
114
+ };
110
115
  this.backends = {
111
- user: new FileAuthStorageBackend(join(agentDir, "permissions.json")),
112
- project: new FileAuthStorageBackend(projectResourcePathByName(cwd, PROJECT_PERMISSIONS_FILE)),
113
- local: new FileAuthStorageBackend(projectResourcePathByName(cwd, PROJECT_LOCAL_PERMISSIONS_FILE)),
116
+ user: new FileAuthStorageBackend(paths.user),
117
+ project: new FileAuthStorageBackend(paths.project),
118
+ local: new FileAuthStorageBackend(paths.local),
114
119
  ...options.backends,
115
120
  };
116
121
  this.policyPath = options.policyPath ?? defaultPolicyPath();
@@ -136,14 +141,12 @@ export class FilePermissionRuleStore {
136
141
  }
137
142
  async readFileBackedScope(source) {
138
143
  try {
139
- let content;
140
- await this.backends[source].withLockAsync(async (current) => {
141
- content = current;
142
- return { result: undefined };
143
- });
144
+ const content = await this.backends[source].withReadLockAsync(async (current) => current);
144
145
  return { scope: parseScope(content) };
145
146
  }
146
147
  catch (error) {
148
+ if (error?.code === "ENOENT")
149
+ return { scope: emptyScope() };
147
150
  return { scope: emptyScope(), error: error instanceof Error ? error : new Error(String(error)) };
148
151
  }
149
152
  }