aicodeman 1.50.0 → 1.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/README.md +17 -10
  2. package/dist/config/attachment-guard.d.ts +5 -1
  3. package/dist/config/attachment-guard.d.ts.map +1 -1
  4. package/dist/config/attachment-guard.js +4 -2
  5. package/dist/config/attachment-guard.js.map +1 -1
  6. package/dist/config/cli-registry/schema.d.ts +2 -0
  7. package/dist/config/cli-registry/schema.d.ts.map +1 -1
  8. package/dist/config/cli-registry/schema.js +11 -0
  9. package/dist/config/cli-registry/schema.js.map +1 -1
  10. package/dist/config/cli-registry/stock.d.ts.map +1 -1
  11. package/dist/config/cli-registry/stock.js +155 -4
  12. package/dist/config/cli-registry/stock.js.map +1 -1
  13. package/dist/config/cli-registry/types.d.ts +33 -2
  14. package/dist/config/cli-registry/types.d.ts.map +1 -1
  15. package/dist/config/file-editing.d.ts +7 -3
  16. package/dist/config/file-editing.d.ts.map +1 -1
  17. package/dist/config/file-editing.js +12 -3
  18. package/dist/config/file-editing.js.map +1 -1
  19. package/dist/config/local-model-catalog.d.ts +95 -20
  20. package/dist/config/local-model-catalog.d.ts.map +1 -1
  21. package/dist/config/local-model-catalog.js +172 -37
  22. package/dist/config/local-model-catalog.js.map +1 -1
  23. package/dist/config-backup.js +1 -1
  24. package/dist/config-backup.js.map +1 -1
  25. package/dist/custom-model-injection.d.ts.map +1 -1
  26. package/dist/custom-model-injection.js +22 -14
  27. package/dist/custom-model-injection.js.map +1 -1
  28. package/dist/hooks-config.d.ts +62 -0
  29. package/dist/hooks-config.d.ts.map +1 -1
  30. package/dist/hooks-config.js +156 -0
  31. package/dist/hooks-config.js.map +1 -1
  32. package/dist/local-model/connect.d.ts +16 -2
  33. package/dist/local-model/connect.d.ts.map +1 -1
  34. package/dist/local-model/connect.js +17 -3
  35. package/dist/local-model/connect.js.map +1 -1
  36. package/dist/local-model/harness-facts.d.ts +8 -4
  37. package/dist/local-model/harness-facts.d.ts.map +1 -1
  38. package/dist/local-model/harness-facts.js +13 -5
  39. package/dist/local-model/harness-facts.js.map +1 -1
  40. package/dist/local-model/install-job.d.ts +208 -28
  41. package/dist/local-model/install-job.d.ts.map +1 -1
  42. package/dist/local-model/install-job.js +856 -94
  43. package/dist/local-model/install-job.js.map +1 -1
  44. package/dist/local-model/recommend.d.ts +11 -5
  45. package/dist/local-model/recommend.d.ts.map +1 -1
  46. package/dist/local-model/recommend.js +11 -5
  47. package/dist/local-model/recommend.js.map +1 -1
  48. package/dist/local-model/runtime.d.ts +12 -0
  49. package/dist/local-model/runtime.d.ts.map +1 -1
  50. package/dist/local-model/runtime.js +42 -0
  51. package/dist/local-model/runtime.js.map +1 -1
  52. package/dist/local-model/state-store.d.ts.map +1 -1
  53. package/dist/local-model/state-store.js +40 -0
  54. package/dist/local-model/state-store.js.map +1 -1
  55. package/dist/mux-interface.d.ts +3 -1
  56. package/dist/mux-interface.d.ts.map +1 -1
  57. package/dist/proc-tree.d.ts +23 -0
  58. package/dist/proc-tree.d.ts.map +1 -1
  59. package/dist/proc-tree.js +28 -0
  60. package/dist/proc-tree.js.map +1 -1
  61. package/dist/session-auto-ops.d.ts +95 -8
  62. package/dist/session-auto-ops.d.ts.map +1 -1
  63. package/dist/session-auto-ops.js +146 -32
  64. package/dist/session-auto-ops.js.map +1 -1
  65. package/dist/session-cli-registry-bridge.d.ts +2 -1
  66. package/dist/session-cli-registry-bridge.d.ts.map +1 -1
  67. package/dist/session-cli-registry-bridge.js.map +1 -1
  68. package/dist/session.d.ts +16 -1
  69. package/dist/session.d.ts.map +1 -1
  70. package/dist/session.js +29 -5
  71. package/dist/session.js.map +1 -1
  72. package/dist/tmux-manager.d.ts +10 -1
  73. package/dist/tmux-manager.d.ts.map +1 -1
  74. package/dist/tmux-manager.js +45 -6
  75. package/dist/tmux-manager.js.map +1 -1
  76. package/dist/tui/tui-app.d.ts.map +1 -1
  77. package/dist/tui/tui-app.js +1 -0
  78. package/dist/tui/tui-app.js.map +1 -1
  79. package/dist/tui/tui-client.d.ts +1 -1
  80. package/dist/tui/tui-client.d.ts.map +1 -1
  81. package/dist/types/common.d.ts +5 -0
  82. package/dist/types/common.d.ts.map +1 -1
  83. package/dist/types/local-model-install.d.ts +202 -15
  84. package/dist/types/local-model-install.d.ts.map +1 -1
  85. package/dist/types/local-model-install.js +21 -4
  86. package/dist/types/local-model-install.js.map +1 -1
  87. package/dist/types/local-model.d.ts +32 -6
  88. package/dist/types/local-model.d.ts.map +1 -1
  89. package/dist/types/local-model.js.map +1 -1
  90. package/dist/types/session.d.ts +26 -4
  91. package/dist/types/session.d.ts.map +1 -1
  92. package/dist/types/session.js +2 -1
  93. package/dist/types/session.js.map +1 -1
  94. package/dist/usage-telemetry.d.ts +3 -0
  95. package/dist/usage-telemetry.d.ts.map +1 -1
  96. package/dist/usage-telemetry.js +4 -0
  97. package/dist/usage-telemetry.js.map +1 -1
  98. package/dist/utils/token-validation.d.ts +3 -3
  99. package/dist/utils/token-validation.d.ts.map +1 -1
  100. package/dist/utils/token-validation.js +3 -3
  101. package/dist/utils/token-validation.js.map +1 -1
  102. package/dist/web/case-state-sync.d.ts +28 -0
  103. package/dist/web/case-state-sync.d.ts.map +1 -0
  104. package/dist/web/case-state-sync.js +41 -0
  105. package/dist/web/case-state-sync.js.map +1 -0
  106. package/dist/web/public/admin-ui.js.gz +0 -0
  107. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  108. package/dist/web/public/{app.8719143d.js → app.bddc2382.js} +9 -7
  109. package/dist/web/public/app.bddc2382.js.br +0 -0
  110. package/dist/web/public/app.bddc2382.js.gz +0 -0
  111. package/dist/web/public/approvals-ui.js.gz +0 -0
  112. package/dist/web/public/constants.782170e1.js.gz +0 -0
  113. package/dist/web/public/cron-ui.js.gz +0 -0
  114. package/dist/web/public/edit-history-ui.js.gz +0 -0
  115. package/dist/web/public/entrance-animations.js.gz +0 -0
  116. package/dist/web/public/foreign-sessions.js.gz +0 -0
  117. package/dist/web/public/git-status-ui.js.gz +0 -0
  118. package/dist/web/public/header-divider.eb2d2463.js.gz +0 -0
  119. package/dist/web/public/home-sessions.js +38 -18
  120. package/dist/web/public/home-sessions.js.br +0 -0
  121. package/dist/web/public/home-sessions.js.gz +0 -0
  122. package/dist/web/public/host-wake-ui.js.gz +0 -0
  123. package/dist/web/public/i18n.2e0cdcee.js +2 -0
  124. package/dist/web/public/i18n.2e0cdcee.js.br +0 -0
  125. package/dist/web/public/i18n.2e0cdcee.js.gz +0 -0
  126. package/dist/web/public/{image-input.a5d0f8f3.js → image-input.b75c41ca.js} +17 -1
  127. package/dist/web/public/image-input.b75c41ca.js.br +0 -0
  128. package/dist/web/public/image-input.b75c41ca.js.gz +0 -0
  129. package/dist/web/public/index.html +39 -15
  130. package/dist/web/public/index.html.br +0 -0
  131. package/dist/web/public/index.html.gz +0 -0
  132. package/dist/web/public/input-cjk.8bc46081.js.gz +0 -0
  133. package/dist/web/public/{keyboard-accessory.b941676c.js → keyboard-accessory.0800fc44.js} +160 -2
  134. package/dist/web/public/keyboard-accessory.0800fc44.js.br +0 -0
  135. package/dist/web/public/keyboard-accessory.0800fc44.js.gz +0 -0
  136. package/dist/web/public/local-model-ui.js +618 -32
  137. package/dist/web/public/local-model-ui.js.br +0 -0
  138. package/dist/web/public/local-model-ui.js.gz +0 -0
  139. package/dist/web/public/mobile-handlers.f7c3f692.js.gz +0 -0
  140. package/dist/web/public/mobile-ime-preview.2dbaf262.js.gz +0 -0
  141. package/dist/web/public/mobile-overview.js +31 -14
  142. package/dist/web/public/mobile-overview.js.br +0 -0
  143. package/dist/web/public/mobile-overview.js.gz +0 -0
  144. package/dist/web/public/mobile.984e9058.css +1 -0
  145. package/dist/web/public/mobile.984e9058.css.br +0 -0
  146. package/dist/web/public/mobile.984e9058.css.gz +0 -0
  147. package/dist/web/public/notification-manager.feb82c04.js.gz +0 -0
  148. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  149. package/dist/web/public/{panels-ui.d3f4f1c4.js → panels-ui.ee2330a4.js} +99 -97
  150. package/dist/web/public/panels-ui.ee2330a4.js.br +0 -0
  151. package/dist/web/public/panels-ui.ee2330a4.js.gz +0 -0
  152. package/dist/web/public/ralph-panel.b350e2ef.js.gz +0 -0
  153. package/dist/web/public/ralph-wizard.b6c0dd19.js.gz +0 -0
  154. package/dist/web/public/readmymind-ui.js.gz +0 -0
  155. package/dist/web/public/reboot-restore-ui.js.gz +0 -0
  156. package/dist/web/public/respawn-ui.304ba0d4.js.gz +0 -0
  157. package/dist/web/public/sanitize-html.e7147e76.js.gz +0 -0
  158. package/dist/web/public/session-lineage.js.gz +0 -0
  159. package/dist/web/public/session-ui.4273cbc5.js +106 -0
  160. package/dist/web/public/session-ui.4273cbc5.js.br +0 -0
  161. package/dist/web/public/session-ui.4273cbc5.js.gz +0 -0
  162. package/dist/web/public/{settings-ui.11da6f15.js → settings-ui.8b37cf07.js} +14 -14
  163. package/dist/web/public/settings-ui.8b37cf07.js.br +0 -0
  164. package/dist/web/public/settings-ui.8b37cf07.js.gz +0 -0
  165. package/dist/web/public/spreadsheet-preview-worker.js.gz +0 -0
  166. package/dist/web/public/spreadsheet-preview.75c751de.js.gz +0 -0
  167. package/dist/web/public/spreadsheet-xlsx-core.js.gz +0 -0
  168. package/dist/web/public/styles.81d95f50.css +1 -0
  169. package/dist/web/public/styles.81d95f50.css.br +0 -0
  170. package/dist/web/public/styles.81d95f50.css.gz +0 -0
  171. package/dist/web/public/subagent-windows.07277a58.js.gz +0 -0
  172. package/dist/web/public/sw.js +2 -2
  173. package/dist/web/public/sw.js.br +0 -0
  174. package/dist/web/public/sw.js.gz +0 -0
  175. package/dist/web/public/tab-layout-browser.2d6189f7.js.gz +0 -0
  176. package/dist/web/public/tab-rail-resize.b5cdceaf.js.gz +0 -0
  177. package/dist/web/public/terminal-keycode229-recovery.98843069.js.gz +0 -0
  178. package/dist/web/public/terminal-split.js.gz +0 -0
  179. package/dist/web/public/terminal-tile.js +1 -1
  180. package/dist/web/public/terminal-tile.js.br +0 -0
  181. package/dist/web/public/terminal-tile.js.gz +0 -0
  182. package/dist/web/public/{terminal-ui.f92eae28.js → terminal-ui.8e4c2017.js} +1 -1
  183. package/dist/web/public/terminal-ui.8e4c2017.js.br +0 -0
  184. package/dist/web/public/terminal-ui.8e4c2017.js.gz +0 -0
  185. package/dist/web/public/tile-grid.js.gz +0 -0
  186. package/dist/web/public/ultracode-panel.js.gz +0 -0
  187. package/dist/web/public/ultracode-windows.js.gz +0 -0
  188. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  189. package/dist/web/public/vendor/exceljs.min.js.gz +0 -0
  190. package/dist/web/public/vendor/fflate.min.js.gz +0 -0
  191. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  192. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  193. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  194. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  195. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  196. package/dist/web/public/vendor/xterm-predictive-echo.276b11d9.js.gz +0 -0
  197. package/dist/web/public/vendor/xterm-zerolag-input.1be42307.js.gz +0 -0
  198. package/dist/web/public/vendor/xterm.css.gz +0 -0
  199. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  200. package/dist/web/public/{voice-input.2342c37b.js → voice-input.d0580528.js} +232 -137
  201. package/dist/web/public/voice-input.d0580528.js.br +0 -0
  202. package/dist/web/public/voice-input.d0580528.js.gz +0 -0
  203. package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
  204. package/dist/web/public/webview-tabs.js.gz +0 -0
  205. package/dist/web/public/whats-new.json +9 -9
  206. package/dist/web/routes/case-routes.d.ts.map +1 -1
  207. package/dist/web/routes/case-routes.js +31 -5
  208. package/dist/web/routes/case-routes.js.map +1 -1
  209. package/dist/web/routes/file-routes.d.ts +4 -2
  210. package/dist/web/routes/file-routes.d.ts.map +1 -1
  211. package/dist/web/routes/file-routes.js +112 -6
  212. package/dist/web/routes/file-routes.js.map +1 -1
  213. package/dist/web/routes/hook-event-routes.d.ts.map +1 -1
  214. package/dist/web/routes/hook-event-routes.js +45 -16
  215. package/dist/web/routes/hook-event-routes.js.map +1 -1
  216. package/dist/web/routes/local-model-routes.d.ts +18 -6
  217. package/dist/web/routes/local-model-routes.d.ts.map +1 -1
  218. package/dist/web/routes/local-model-routes.js +47 -10
  219. package/dist/web/routes/local-model-routes.js.map +1 -1
  220. package/dist/web/routes/session-routes.d.ts.map +1 -1
  221. package/dist/web/routes/session-routes.js +52 -4
  222. package/dist/web/routes/session-routes.js.map +1 -1
  223. package/dist/web/routes/status-telemetry-routes.d.ts.map +1 -1
  224. package/dist/web/routes/status-telemetry-routes.js +6 -0
  225. package/dist/web/routes/status-telemetry-routes.js.map +1 -1
  226. package/dist/web/routes/system-routes.d.ts +2 -2
  227. package/dist/web/routes/system-routes.d.ts.map +1 -1
  228. package/dist/web/routes/system-routes.js +35 -4
  229. package/dist/web/routes/system-routes.js.map +1 -1
  230. package/dist/web/schemas.d.ts +30 -0
  231. package/dist/web/schemas.d.ts.map +1 -1
  232. package/dist/web/schemas.js +56 -4
  233. package/dist/web/schemas.js.map +1 -1
  234. package/dist/web/sensitive-path.d.ts +8 -1
  235. package/dist/web/sensitive-path.d.ts.map +1 -1
  236. package/dist/web/sensitive-path.js +23 -4
  237. package/dist/web/sensitive-path.js.map +1 -1
  238. package/dist/web/server.d.ts.map +1 -1
  239. package/dist/web/server.js +1 -0
  240. package/dist/web/server.js.map +1 -1
  241. package/dist/web/session-wait-registry.d.ts +19 -4
  242. package/dist/web/session-wait-registry.d.ts.map +1 -1
  243. package/dist/web/session-wait-registry.js +26 -5
  244. package/dist/web/session-wait-registry.js.map +1 -1
  245. package/dist/web/voice-stream.d.ts +4 -3
  246. package/dist/web/voice-stream.d.ts.map +1 -1
  247. package/dist/web/voice-stream.js +5 -4
  248. package/dist/web/voice-stream.js.map +1 -1
  249. package/package.json +1 -1
  250. package/skills/codeman/SKILL.md +147 -42
  251. package/skills/codeman/preamble.sh +102 -26
  252. package/skills/codeman/reference/endpoints.md +13 -9
  253. package/skills/codeman/reference/messaging.md +2 -2
  254. package/skills/codeman/reference/recipes.md +2 -2
  255. package/skills/codeman/reference/verbs.md +46 -15
  256. package/dist/web/public/app.8719143d.js.br +0 -0
  257. package/dist/web/public/app.8719143d.js.gz +0 -0
  258. package/dist/web/public/i18n.1e96a258.js +0 -2
  259. package/dist/web/public/i18n.1e96a258.js.br +0 -0
  260. package/dist/web/public/i18n.1e96a258.js.gz +0 -0
  261. package/dist/web/public/image-input.a5d0f8f3.js.br +0 -0
  262. package/dist/web/public/image-input.a5d0f8f3.js.gz +0 -0
  263. package/dist/web/public/keyboard-accessory.b941676c.js.br +0 -0
  264. package/dist/web/public/keyboard-accessory.b941676c.js.gz +0 -0
  265. package/dist/web/public/mobile.4dfd5c55.css +0 -1
  266. package/dist/web/public/mobile.4dfd5c55.css.br +0 -0
  267. package/dist/web/public/mobile.4dfd5c55.css.gz +0 -0
  268. package/dist/web/public/panels-ui.d3f4f1c4.js.br +0 -0
  269. package/dist/web/public/panels-ui.d3f4f1c4.js.gz +0 -0
  270. package/dist/web/public/session-ui.a7c8c095.js +0 -106
  271. package/dist/web/public/session-ui.a7c8c095.js.br +0 -0
  272. package/dist/web/public/session-ui.a7c8c095.js.gz +0 -0
  273. package/dist/web/public/settings-ui.11da6f15.js.br +0 -0
  274. package/dist/web/public/settings-ui.11da6f15.js.gz +0 -0
  275. package/dist/web/public/styles.63382d6e.css +0 -1
  276. package/dist/web/public/styles.63382d6e.css.br +0 -0
  277. package/dist/web/public/styles.63382d6e.css.gz +0 -0
  278. package/dist/web/public/terminal-ui.f92eae28.js.br +0 -0
  279. package/dist/web/public/terminal-ui.f92eae28.js.gz +0 -0
  280. package/dist/web/public/voice-input.2342c37b.js.br +0 -0
  281. package/dist/web/public/voice-input.2342c37b.js.gz +0 -0
@@ -6,6 +6,14 @@
6
6
  * runtime, model, verify, agent, connect; `agent` is left out when the coding agent is
7
7
  * installed). Its state is one of five (`LocalModelInstallState`), stored in the state file.
8
8
  *
9
+ * A LIBRARY with ONE model in use. The store can hold several models; exactly one of them is
10
+ * the model in use: the one the saved endpoint record lists, the runtime is started for and a
11
+ * session may be launched on. `LocalModelStateFile.library` lists every model that passed the
12
+ * check through Codeman. A job makes its model the one in use when it ends: an install (also
13
+ * from `installed`, which adds a model and keeps the earlier ones) or a switch (`use`, the two
14
+ * steps `USE_JOB_STEPS`: nothing is downloaded, the model is loaded and checked again and its
15
+ * digest must still be the stored one).
16
+ *
9
17
  * The state table. "On disk" names what lies under the local model folder; the two writes
10
18
  * outside it belong to the `connect` step.
11
19
  *
@@ -17,12 +25,15 @@
17
25
  * | | the current step has written so far | same step; nothing resumes | the same step | |
18
26
  * | | (see the step table) | without a click | | |
19
27
  * | `paused` | as `installing` at that step, nothing in | stays `paused` | refused (409) | resume, install (another |
20
- * | | flight | | | choice), remove |
28
+ * | | flight | | | choice), use (a checked model), |
29
+ * | | | | | delete a model, remove |
21
30
  * | `failed` | as `installing` at that step, nothing in | stays `failed`, same error | refused (409) | resume (try again), install |
22
- * | | flight | | | (another choice), remove |
31
+ * | | flight | | | (another choice), use, delete a |
32
+ * | | | | | model, remove |
23
33
  * | `installed` | the runtime, the private home, the model | stays `installed`; the | refused (409) | start a session, start or stop |
24
- * | | | runtime is started again | | the runtime, remove |
25
- * | | | when it was not stopped | | |
34
+ * | | in use and every other model of the | runtime is started again | | the runtime, install (add a |
35
+ * | | library | when it was not stopped | | model), use, delete a model, |
36
+ * | | | | | install a coding agent, remove |
26
37
  *
27
38
  * The step table. Every step is IDEMPOTENT, so Resume and "Try again" re-enter the step the
28
39
  * job stopped in; they first make sure the runtime runs when the step needs it.
@@ -62,16 +73,39 @@
62
73
  * `mutateLocalModelState()` and never change the state.
63
74
  * - A job read as `installing` at boot was interrupted by the restart: the service applies
64
75
  * the event `restart` before anything else, so it is `paused` and waits for a click.
65
- * - A new install from `paused` or `failed` REPLACES the job. When it names another model,
66
- * what the old job left of its model is deleted from the store first: the model through the
67
- * runtime when it was downloaded whole, and the partial blobs of a download that was
68
- * interrupted (the runtime knows no model for those, so they are deleted as files).
76
+ * - A new install or a switch from `paused` or `failed` REPLACES the job. When it names another
77
+ * model, what the old job left of its model is deleted from the store first: the model
78
+ * through the runtime when it was downloaded whole, and the partial blobs of a download that
79
+ * was interrupted (the runtime knows no model for those, so they are deleted as files). A
80
+ * model of the library is never deleted that way: it was checked, and it stays until the
81
+ * person deletes it.
82
+ * - Installing another model and switching change which model the runtime holds (it holds
83
+ * one), and often its context. Both are refused (409 `sessions-open`) while live sessions
84
+ * use the endpoint, like Stop: their coding agents were started with the other model's name.
85
+ * - While a job that started from `installed` is not finished (`installing`, `paused`,
86
+ * `failed`), no session is started: the launch check wants the state `installed`. `use` on
87
+ * the earlier model is the way back.
88
+ * - A model is deleted ONLY through the runtime (`deleteModel()`), by a name that is in the
89
+ * server's own listing (the library or the runtime's tags), never by a path. The model of
90
+ * the installation or of the current job is refused (`model-active`): switch first, or
91
+ * Remove. Deleting moves no state: it is not an event of the reducer, and whether a state
92
+ * allows it is the `delete-model` action of its row in `INSTALL_STATE_TABLE`.
69
93
  * - Install is checked before anything is downloaded: admin only in multi-user mode; the
70
94
  * model, the context and the coding agent must be a row the current recommendation offers;
71
95
  * the coding agent must be a harness row of the catalogue; `acknowledgedBytes` must be the
72
96
  * server's own total.
73
97
  * - No CLI id is compared with a literal here: the coding agent is a catalogue row plus a
74
98
  * `HarnessFact`.
99
+ * - The coding agent is chosen PER SESSION. The state file's `cli` is the agent of the job
100
+ * and, once installed, the default one; the view's `harnesses` lists every catalogue harness
101
+ * the model in use can be run with (`buildHarnessRows()`). The launch check
102
+ * (`launchRefusalMessage()`) asks about the endpoint and the model, never about the agent.
103
+ * - Installing one more coding agent beside an installed model (`installAgent()`,
104
+ * `POST /api/local-model/agent`) is NOT a job and not an event of the reducer: the state
105
+ * stays `installed` whatever the installer does, so a failed `npm install` never blocks a
106
+ * session on a model that works. It runs in the background through the same install slot
107
+ * and the same stock command as the `agent` step, one at a time, and what it leaves behind
108
+ * is in memory only (`LocalModelHarnessRow.status` `installing`, or its `error`).
75
109
  *
76
110
  * The service (`createLocalModelService()`), beyond the reducer:
77
111
  * - Verbs run one at a time on one queue, so two installs sent together cannot both find the
@@ -106,12 +140,16 @@
106
140
  * process runs no job, which is what a restart leaves too.
107
141
  * - Stop and "Use another port" are refused (409 `sessions-open`) while live sessions use
108
142
  * the model: their coding agents were given the address when they started.
143
+ * - The view's `library` joins the state file's checked models with what the running runtime
144
+ * lists, and `store` is the disk use of the blob folder. Neither is asked for on every
145
+ * one-second poll: both are cached (`TAGS_RECHECK_MS`, `STORE_RECHECK_MS`), refreshed in the
146
+ * background, and thrown away by every verb and step that changes them.
109
147
  */
110
148
  import { appendAdminAudit } from '../web/admin-audit.js';
111
149
  import { CLI_INSTALL_TIMEOUT_MS, forgetResolvedCli, runInstallCommand, stockInstallCommand, tryBeginCliInstall, } from '../cli-install-runner.js';
112
150
  import { getCli } from '../config/cli-registry/registry.js';
113
151
  import { getDataDir } from '../config/instance.js';
114
- import { getLocalModelCatalog } from '../config/local-model-catalog.js';
152
+ import { getLocalModelCatalog, LOCAL_MODEL_ID_PATTERN } from '../config/local-model-catalog.js';
115
153
  import { readCustomModelHosts } from '../custom-model-hosts.js';
116
154
  import { getErrorMessage, LOCAL_MODEL_ERROR_LABELS, LOCAL_MODEL_ERROR_NEXT, LOCAL_MODEL_INSTALL_LABELS, LOCAL_MODEL_INSTALL_STEPS, } from '../types.js';
117
155
  import { isCliEntryInstalled, probeStockCliAvailability } from '../utils/cli-installed-probes.js';
@@ -120,10 +158,10 @@ import { checkDeveloperTools } from './developer-tools.js';
120
158
  import { formatGb } from './format.js';
121
159
  import { readHardware } from './hardware.js';
122
160
  import { buildHarnessFacts } from './harness-facts.js';
123
- import { deleteModel, getRuntimeVersion, listOpenAiModels, listRunning, pullModel, readModelDigest, verifyModel, } from './ollama-client.js';
161
+ import { deleteModel, getRuntimeVersion, listOpenAiModels, listRunning, listTags, pullModel, readModelDigest, verifyModel, } from './ollama-client.js';
124
162
  import { localModelPaths, runtimeBinaryForVersion } from './paths.js';
125
163
  import { modelFitsBudget, needBytes, recommend } from './recommend.js';
126
- import { chooseRuntimePort, createRuntimeSupervisor, ensureRuntimeInstalled, isRuntimeInstalled, OLLAMA_RUNTIME_PIN, removeLocalModelFiles, removePartialModelBlobs, RUNTIME_PORT_FIRST, } from './runtime.js';
164
+ import { chooseRuntimePort, createRuntimeSupervisor, ensureRuntimeInstalled, isRuntimeInstalled, measureModelStore, OLLAMA_RUNTIME_PIN, removeLocalModelFiles, removePartialModelBlobs, RUNTIME_PORT_FIRST, } from './runtime.js';
127
165
  import { IDLE_LOCAL_MODEL_STATE, mutateLocalModelState, readLocalModelState } from './state-store.js';
128
166
  /** The state table of the file header, as data. */
129
167
  export const INSTALL_STATE_TABLE = {
@@ -133,7 +171,7 @@ export const INSTALL_STATE_TABLE = {
133
171
  restart: 'Nothing happens.',
134
172
  afterCancel: null,
135
173
  cancel: 'Refused: no job is running.',
136
- actions: ['install'],
174
+ actions: ['install', 'remove'],
137
175
  },
138
176
  installing: {
139
177
  onDisk: 'What the finished steps wrote, plus what the current step has written so far (INSTALL_STEP_TABLE). The state file names the model, the coding agent, the context and the step.',
@@ -149,7 +187,7 @@ export const INSTALL_STATE_TABLE = {
149
187
  restart: 'Stays paused.',
150
188
  afterCancel: null,
151
189
  cancel: 'Refused: no job is running.',
152
- actions: ['resume', 'install', 'remove'],
190
+ actions: ['resume', 'install', 'use', 'delete-model', 'remove'],
153
191
  },
154
192
  failed: {
155
193
  onDisk: 'As installing at that step, with nothing in flight.',
@@ -157,15 +195,15 @@ export const INSTALL_STATE_TABLE = {
157
195
  restart: 'Stays failed, with the same error.',
158
196
  afterCancel: null,
159
197
  cancel: 'Refused: no job is running.',
160
- actions: ['resume', 'install', 'remove'],
198
+ actions: ['resume', 'install', 'use', 'delete-model', 'remove'],
161
199
  },
162
200
  installed: {
163
- onDisk: 'The runtime, its private home and the model. The state file holds the port, the pid, the digest, what the runtime loaded and the previous settings flag. Outside the folder: our endpoint record and the settings flag.',
201
+ onDisk: 'The runtime, its private home, the model in use and every other model of the library. The state file holds the port, the pid, the digest, what the runtime loaded, the checked models and the previous settings flag. Outside the folder: our endpoint record and the settings flag.',
164
202
  afterRestart: 'installed',
165
203
  restart: 'Stays installed. The runtime is started again unless the person had stopped it, and the digest is read again: a changed digest or a port taken by another program shows as an error on the view and blocks a session, the state stays installed.',
166
204
  afterCancel: null,
167
205
  cancel: 'Refused: no job is running.',
168
- actions: ['start-session', 'start', 'stop', 'remove'],
206
+ actions: ['start-session', 'start', 'stop', 'install', 'use', 'delete-model', 'install-agent', 'remove'],
169
207
  },
170
208
  };
171
209
  /** The step table of the file header, as data. */
@@ -242,6 +280,9 @@ export const INSTALL_STEP_TABLE = {
242
280
  errors: ['endpoint-id-taken', 'connect-failed', 'internal'],
243
281
  },
244
282
  };
283
+ // ---------- Events and transitions ----------
284
+ /** The steps of a switch to a checked model: it is loaded and checked again, then connected. Nothing is downloaded. */
285
+ export const USE_JOB_STEPS = ['verify', 'connect'];
245
286
  /**
246
287
  * Which state an event leads to, by current state. A pair that is not listed is REFUSED: the
247
288
  * reducer returns the object it was given. One entry needs a word: `step-done` in
@@ -257,10 +298,51 @@ export const INSTALL_TRANSITIONS = {
257
298
  cancel: 'paused',
258
299
  restart: 'paused',
259
300
  },
260
- paused: { resume: 'installing', install: 'installing', remove: 'idle', restart: 'paused' },
261
- failed: { resume: 'installing', install: 'installing', remove: 'idle', restart: 'failed' },
262
- installed: { remove: 'idle', restart: 'installed' },
301
+ paused: { resume: 'installing', install: 'installing', use: 'installing', remove: 'idle', restart: 'paused' },
302
+ failed: { resume: 'installing', install: 'installing', use: 'installing', remove: 'idle', restart: 'failed' },
303
+ installed: { install: 'installing', use: 'installing', remove: 'idle', restart: 'installed' },
263
304
  };
305
+ /**
306
+ * The checked models of a state: its `library`, and for an `installed` state whose model is
307
+ * not in it (a file an earlier build wrote has no list) that model too, first. A model without
308
+ * a stored digest is never one of them: nothing could be compared when it is switched to. Pure.
309
+ */
310
+ export function libraryOf(state) {
311
+ const entries = [...(state.library ?? [])];
312
+ const model = state.model;
313
+ if (state.state === 'installed' && model?.digest && !entries.some((entry) => entry.id === model.id)) {
314
+ entries.unshift({
315
+ id: model.id,
316
+ label: model.label,
317
+ context: model.context,
318
+ digest: model.digest,
319
+ ...(model.pullBytes ? { bytes: model.pullBytes } : {}),
320
+ ...(state.cli ? { cli: state.cli } : {}),
321
+ });
322
+ }
323
+ return entries;
324
+ }
325
+ /** `library` with `entry` in the place of the one with its id, or at the end. Pure. */
326
+ export function upsertLibraryEntry(library, entry) {
327
+ const index = library.findIndex((existing) => existing.id === entry.id);
328
+ if (index === -1)
329
+ return [...library, entry];
330
+ const next = [...library];
331
+ next[index] = entry;
332
+ return next;
333
+ }
334
+ /**
335
+ * The model whose leftovers a new job for `nextId` deletes from the store first: the model of
336
+ * the job it replaces when that is another model, else one that was already waiting to be
337
+ * deleted. Never a model of the library (it was checked and stays until the person deletes
338
+ * it), and never the model that is wanted now. Pure.
339
+ */
340
+ function replacedModelFor(current, nextId, library) {
341
+ const checked = (id) => library.some((entry) => entry.id === id);
342
+ const replaced = current.model && current.model.id !== nextId && !checked(current.model.id) ? current.model.id : undefined;
343
+ const pending = replaced ?? current.replacedModelId;
344
+ return pending !== undefined && pending !== nextId && !checked(pending) ? pending : undefined;
345
+ }
264
346
  /** The steps a job runs, in order: all of `LOCAL_MODEL_INSTALL_STEPS`, without `agent` when the coding agent is installed. Pure. */
265
347
  export function jobSteps(input) {
266
348
  return LOCAL_MODEL_INSTALL_STEPS.filter((step) => step !== 'agent' || !input.agentInstalled);
@@ -270,12 +352,13 @@ const isByteCount = (value) => Number.isSafeInteger(value) && value >= 0;
270
352
  /**
271
353
  * The state file after `event`. Pure: no IO, no clock (`updatedAt` is the state store's
272
354
  * business). Refuses an event the transition table does not list for the current state by
273
- * returning `current` itself. Keeps `runtime` and `connection` across a new install, because
274
- * what they record is still on disk; `remove` drops everything.
355
+ * returning `current` itself. Keeps `runtime`, `connection` and `library` across a new install
356
+ * or a switch, because what they record is still on disk; `remove` drops everything.
275
357
  *
276
358
  * An event that is listed but cannot be applied is refused the same way: an `install` whose
277
- * steps are not a job's, a `progress` that is not two byte counts, a `step-done` on a state
278
- * without a step, and a last `step-done` on a job that has no runtime recorded.
359
+ * steps are not a job's, a `use` of a model that is not in the library or on a state without a
360
+ * runtime, a `progress` that is not two byte counts, a `step-done` on a state without a step,
361
+ * and a last `step-done` on a job that has no runtime recorded.
279
362
  */
280
363
  export function reduceInstallJob(current, event) {
281
364
  if (INSTALL_TRANSITIONS[current.state][event.type] === undefined)
@@ -288,9 +371,10 @@ export function reduceInstallJob(current, event) {
288
371
  steps.some((step) => !LOCAL_MODEL_INSTALL_STEPS.includes(step))) {
289
372
  return current;
290
373
  }
291
- // What the replaced job left of ANOTHER model is deleted before the new one is pulled.
292
- const pending = current.model && current.model.id !== event.model.id ? current.model.id : current.replacedModelId;
293
- const replacedModelId = pending !== undefined && pending !== event.model.id ? pending : undefined;
374
+ // What the replaced job left of ANOTHER model is deleted before the new one is pulled,
375
+ // unless that model is one of the library.
376
+ const library = libraryOf(current);
377
+ const replacedModelId = replacedModelFor(current, event.model.id, library);
294
378
  return {
295
379
  schema: 1,
296
380
  state: 'installing',
@@ -300,6 +384,31 @@ export function reduceInstallJob(current, event) {
300
384
  ...(replacedModelId ? { replacedModelId } : {}),
301
385
  cli: { id: event.cli.id, label: event.cli.label },
302
386
  ...(current.runtime ? { runtime: current.runtime } : {}),
387
+ ...(library.length > 0 ? { library } : {}),
388
+ ...(current.connection ? { connection: current.connection } : {}),
389
+ };
390
+ }
391
+ case 'use': {
392
+ const library = libraryOf(current);
393
+ // Only a checked model can be switched to, and only where a runtime was set up.
394
+ if (!current.runtime || !library.some((entry) => entry.id === event.model.id))
395
+ return current;
396
+ const replacedModelId = replacedModelFor(current, event.model.id, library);
397
+ return {
398
+ schema: 1,
399
+ state: 'installing',
400
+ step: USE_JOB_STEPS[0],
401
+ steps: [...USE_JOB_STEPS],
402
+ model: {
403
+ id: event.model.id,
404
+ label: event.model.label,
405
+ context: event.model.context,
406
+ digest: event.model.digest,
407
+ },
408
+ ...(replacedModelId ? { replacedModelId } : {}),
409
+ cli: { id: event.cli.id, label: event.cli.label },
410
+ runtime: current.runtime,
411
+ library,
303
412
  ...(current.connection ? { connection: current.connection } : {}),
304
413
  };
305
414
  }
@@ -327,6 +436,7 @@ export function reduceInstallJob(current, event) {
327
436
  cli: current.cli,
328
437
  runtime: current.runtime,
329
438
  ...(current.loaded ? { loaded: current.loaded } : {}),
439
+ ...(current.library ? { library: current.library } : {}),
330
440
  ...(current.connection ? { connection: current.connection } : {}),
331
441
  };
332
442
  }
@@ -392,19 +502,183 @@ export function installedBlocker(state, live) {
392
502
  return buildInstallError('model-changed');
393
503
  return undefined;
394
504
  }
395
- /** The actions the server accepts right now: the state row's list narrowed by what is live. Pure. */
396
- export function allowedActions(state, live) {
505
+ /**
506
+ * The models on this Mac, for the view: the checked models of the state file joined with what
507
+ * the running runtime lists. The model in use first, then the other checked models in the
508
+ * order they were checked, then what the runtime lists beside them, by name. Pure.
509
+ *
510
+ * What a row offers:
511
+ * - `use`: a checked model the runtime does not contradict (`ready`), in a state whose row of
512
+ * `INSTALL_STATE_TABLE` lists `use`, unless it is the model of the installation (in use
513
+ * already) or of the stopped job (Resume goes on with that one).
514
+ * - `delete`: any model the running runtime lists, in a state that lists `delete-model`,
515
+ * unless it is the model of the installation or of the current job, and unless its name is
516
+ * not a plain `name:tag` (`LOCAL_MODEL_ID_PATTERN`): the delete route takes no other name.
517
+ * A checked model the runtime no longer lists (`missing`) can be deleted too: that drops
518
+ * its entry.
519
+ */
520
+ export function buildLibraryRows(state, live) {
521
+ if (state.state === 'idle')
522
+ return [];
523
+ const stateActions = INSTALL_STATE_TABLE[state.state].actions;
524
+ const tags = live.running ? live.tags : undefined;
525
+ const jobModelId = state.model?.id;
526
+ const canDelete = (id) => stateActions.includes('delete-model') && tags !== undefined && id !== jobModelId && LOCAL_MODEL_ID_PATTERN.test(id);
527
+ const sized = (bytes) => bytes !== undefined && bytes > 0 ? { sizeBytes: bytes, sizeGb: formatGb(bytes) } : {};
528
+ const rows = [];
529
+ const entries = libraryOf(state);
530
+ for (const entry of entries) {
531
+ const tag = tags?.find((listed) => listed.name === entry.id);
532
+ const active = state.state === 'installed' && entry.id === jobModelId;
533
+ let status = 'ready';
534
+ if (tags !== undefined) {
535
+ if (!tag)
536
+ status = 'missing';
537
+ else if (compareModelDigest(entry.digest, tag.digest) === 'changed')
538
+ status = 'changed';
539
+ }
540
+ // The model in use is compared on its own schedule too: what blocks a session says so here.
541
+ if (active && live.digest === 'changed')
542
+ status = 'changed';
543
+ const actions = [];
544
+ // The model of the installation is in use already, and the model of a stopped job is
545
+ // what Resume goes on with: a switch is offered to every OTHER checked model.
546
+ if (stateActions.includes('use') && status === 'ready' && entry.id !== jobModelId)
547
+ actions.push('use');
548
+ if (canDelete(entry.id))
549
+ actions.push('delete');
550
+ rows.push({
551
+ id: entry.id,
552
+ label: entry.label,
553
+ context: entry.context,
554
+ ...sized(tag && tag.size > 0 ? tag.size : entry.bytes),
555
+ active,
556
+ verified: true,
557
+ status,
558
+ actions,
559
+ });
560
+ }
561
+ rows.sort((a, b) => Number(b.active) - Number(a.active));
562
+ const others = (tags ?? [])
563
+ .filter((listed) => !entries.some((entry) => entry.id === listed.name))
564
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
565
+ for (const listed of others) {
566
+ rows.push({
567
+ id: listed.name,
568
+ label: live.labels?.[listed.name] ?? (listed.name === jobModelId && state.model ? state.model.label : listed.name),
569
+ ...sized(listed.size),
570
+ active: false,
571
+ verified: false,
572
+ status: 'unverified',
573
+ actions: canDelete(listed.name) ? ['delete'] : [],
574
+ });
575
+ }
576
+ return rows;
577
+ }
578
+ /**
579
+ * The coding agents the model in use can be run with: every catalogue harness that is not
580
+ * gated, has a fact, works at the model's context and accepts its name. The default agent
581
+ * first, then the higher catalogue rank. The default is the agent of the installation
582
+ * (`state.cli`) while it can be started, else the first one that can, so a client that names
583
+ * no agent never starts one that is gone. Rows carry no `start-session` action yet: whether a
584
+ * session can be started at all is the view's knowledge (`buildInstallView()`). Empty unless
585
+ * the state is `installed`. Pure, and it compares no CLI id with a literal.
586
+ */
587
+ export function buildHarnessRows(state, catalog, facts, memory = {}) {
588
+ if (state.state !== 'installed' || !state.model)
589
+ return [];
590
+ const model = state.model;
591
+ const ranked = [];
592
+ for (const entry of catalog.harnesses) {
593
+ if (entry.gated)
594
+ continue;
595
+ const fact = facts.find((candidate) => candidate.cli === entry.cli);
596
+ if (!fact || model.context < entry.minContext)
597
+ continue;
598
+ let accepts = false;
599
+ try {
600
+ accepts = fact.acceptsModelId(model.id);
601
+ }
602
+ catch {
603
+ accepts = false;
604
+ }
605
+ if (!accepts)
606
+ continue;
607
+ const installing = !fact.installed && memory.running === entry.cli;
608
+ const status = fact.installed
609
+ ? 'ready'
610
+ : installing
611
+ ? 'installing'
612
+ : fact.installable
613
+ ? 'installable'
614
+ : 'setup-needed';
615
+ const failure = status === 'installable' ? memory.failed?.[entry.cli] : undefined;
616
+ const readyMark = entry.readyMark ?? fact.readyMark;
617
+ ranked.push({
618
+ rank: entry.rank,
619
+ row: {
620
+ cli: entry.cli,
621
+ cliLabel: fact.label,
622
+ default: false,
623
+ status,
624
+ ...((status === 'installable' || status === 'installing') && fact.installCommand !== undefined
625
+ ? { installCommand: fact.installCommand }
626
+ : {}),
627
+ ...(entry.slowFirstTurn ? { slowFirstTurn: true } : {}),
628
+ ...(readyMark !== undefined ? { readyMark } : {}),
629
+ ...(failure
630
+ ? {
631
+ error: {
632
+ message: { text: LOCAL_MODEL_INSTALL_LABELS.errHarnessFailed, vars: { cli: fact.label } },
633
+ ...(failure.detail ? { detail: failure.detail } : {}),
634
+ },
635
+ }
636
+ : {}),
637
+ // One installer at a time: while one runs, no other agent is offered for install.
638
+ actions: status === 'installable' && memory.running === undefined ? ['install'] : [],
639
+ },
640
+ });
641
+ }
642
+ ranked.sort((a, b) => b.rank - a.rank);
643
+ const rows = ranked.map((entry) => entry.row);
644
+ const chosen = state.cli?.id;
645
+ const fallback = rows.find((row) => row.cli === chosen && row.status === 'ready') ??
646
+ rows.find((row) => row.status === 'ready') ??
647
+ rows.find((row) => row.cli === chosen);
648
+ if (!fallback)
649
+ return rows;
650
+ fallback.default = true;
651
+ return [fallback, ...rows.filter((row) => row !== fallback)];
652
+ }
653
+ /**
654
+ * The actions the server accepts right now: the state row's list narrowed by what is live.
655
+ * `rows` is `buildLibraryRows()` of the same two arguments, for a caller that has it. Pure.
656
+ */
657
+ export function allowedActions(state, live, rows = buildLibraryRows(state, live)) {
397
658
  const actions = INSTALL_STATE_TABLE[state.state].actions;
398
- if (state.state !== 'installed')
399
- return [...actions];
400
659
  const blocked = installedBlocker(state, live) !== undefined;
401
660
  return actions.filter((action) => {
661
+ if (action === 'use')
662
+ return rows.some((row) => row.actions.includes('use'));
663
+ if (action === 'delete-model')
664
+ return rows.some((row) => row.actions.includes('delete'));
665
+ if (action === 'install-agent')
666
+ return (live.harnesses ?? []).some((row) => row.actions.includes('install'));
667
+ // From idle a Remove only clears what an earlier one kept: offered while there is something.
668
+ if (state.state === 'idle')
669
+ return action !== 'remove' || (live.storeBytes ?? 0) > 0;
670
+ if (state.state !== 'installed')
671
+ return true;
402
672
  if (action === 'start')
403
673
  return !live.running;
404
674
  if (action === 'stop')
405
675
  return live.running;
406
- if (action === 'start-session')
407
- return live.running && !blocked;
676
+ if (action === 'start-session') {
677
+ // With the agents known, a session needs one that can be started. Unknown (the registry
678
+ // could not be read) is not "none": the launch itself says what is missing then.
679
+ const anAgent = live.harnesses === undefined || live.harnesses.some((row) => row.status === 'ready');
680
+ return live.running && !blocked && anAgent;
681
+ }
408
682
  return true;
409
683
  });
410
684
  }
@@ -428,6 +702,7 @@ function buildProgress(progress, bytesPerSecond) {
428
702
  /** The `install` object of the GET. Pure: every size text comes from `formatGb()`, every sentence from `LOCAL_MODEL_INSTALL_LABELS`. */
429
703
  export function buildInstallView(state, live) {
430
704
  const runtimeDownload = live.runtimeInstalled ? 0 : live.pin.bytes;
705
+ const library = buildLibraryRows(state, live);
431
706
  const view = {
432
707
  state: state.state,
433
708
  running: live.running,
@@ -440,7 +715,10 @@ export function buildInstallView(state, live) {
440
715
  unpackedGb: formatGb(live.pin.unpackedBytes),
441
716
  },
442
717
  folder: live.folder,
443
- actions: allowedActions(state, live),
718
+ library,
719
+ ...(live.storeBytes !== undefined ? { store: { bytes: live.storeBytes, gb: formatGb(live.storeBytes) } } : {}),
720
+ harnesses: [],
721
+ actions: allowedActions(state, live, library),
444
722
  };
445
723
  if (state.state === 'idle')
446
724
  return view;
@@ -468,6 +746,16 @@ export function buildInstallView(state, live) {
468
746
  const blocker = installedBlocker(state, live);
469
747
  if (blocker)
470
748
  view.error = blocker;
749
+ // An agent that can be started offers a session exactly when the model does.
750
+ const canStart = view.actions.includes('start-session');
751
+ view.harnesses = (live.harnesses ?? []).map((row) => row.status === 'ready' && canStart ? { ...row, actions: ['start-session', ...row.actions] } : { ...row });
752
+ // The default agent is the one a client that names none starts: never one that is gone
753
+ // while another can be started.
754
+ const preferred = view.harnesses.find((row) => row.default);
755
+ if (preferred) {
756
+ view.cli = preferred.cli;
757
+ view.cliLabel = preferred.cliLabel;
758
+ }
471
759
  return view;
472
760
  }
473
761
  if (state.step)
@@ -489,6 +777,28 @@ export function buildInstallView(state, live) {
489
777
  }
490
778
  return view;
491
779
  }
780
+ /**
781
+ * `recommendation` with every row marked that is a checked model of the library at the row's
782
+ * context (`Candidate.library`): `active` for the model in use, `ready` for one a switch can
783
+ * take. The chooser then says the model is on this Mac and switches without a download. A
784
+ * recommendation with nothing to mark is handed back as it is. Pure.
785
+ */
786
+ export function markLibraryCandidates(recommendation, view) {
787
+ const mark = (candidate) => {
788
+ const row = view.library.find((entry) => entry.verified && entry.id === candidate.modelId && entry.context === candidate.context);
789
+ if (!row)
790
+ return candidate;
791
+ if (row.active)
792
+ return { ...candidate, library: 'active' };
793
+ return row.actions.includes('use') ? { ...candidate, library: 'ready' } : candidate;
794
+ };
795
+ if (view.library.length === 0 || !recommendation.pick)
796
+ return recommendation;
797
+ const pick = mark(recommendation.pick);
798
+ const alternatives = recommendation.alternatives.map(mark);
799
+ const changed = pick !== recommendation.pick || alternatives.some((row, i) => row !== recommendation.alternatives[i]);
800
+ return changed ? { ...recommendation, pick, alternatives } : recommendation;
801
+ }
492
802
  /** A sentence of the install as plain English text, its slots filled. For an API error message and the log. Pure. */
493
803
  export function formatInstallMessage(message) {
494
804
  const vars = message.vars ?? {};
@@ -500,6 +810,12 @@ const PROGRESS_FLUSH_MS = 5_000;
500
810
  const DIGEST_RECHECK_MS = 30_000;
501
811
  /** How long a read of the runtime's listings may take. */
502
812
  const RUNTIME_READ_TIMEOUT_MS = 5_000;
813
+ /** How long the runtime's list of models stays good for the view. Every verb and step that changes the store throws it away. */
814
+ const TAGS_RECHECK_MS = 5_000;
815
+ /** How long a measurement of the model store stays good for the view. */
816
+ const STORE_RECHECK_MS = 30_000;
817
+ /** How long the view waits for the FIRST listing and measurement. Later ones are read in the background. */
818
+ const FIRST_LISTING_WAIT_MS = 300;
503
819
  /** The window a download speed is measured over when the source reports none. */
504
820
  const SPEED_WINDOW_MS = 5_000;
505
821
  /** How much of an installer's output is kept as the error detail. */
@@ -514,6 +830,8 @@ function conflict(reason, extra = {}, vars) {
514
830
  'size-changed': LOCAL_MODEL_INSTALL_LABELS.conflictSizeChanged,
515
831
  'sessions-open': LOCAL_MODEL_INSTALL_LABELS.conflictSessionsOpen,
516
832
  'wrong-state': LOCAL_MODEL_INSTALL_LABELS.conflictWrongState,
833
+ 'model-active': LOCAL_MODEL_INSTALL_LABELS.conflictModelActive,
834
+ 'runtime-not-running': LOCAL_MODEL_INSTALL_LABELS.errRuntimeNotRunning,
517
835
  }[reason];
518
836
  return { ok: false, status: 409, conflict: { reason, message: { text, ...(vars ? { vars } : {}) }, ...extra } };
519
837
  }
@@ -570,6 +888,19 @@ class LocalModelServiceImpl {
570
888
  startFailed;
571
889
  digestStatus;
572
890
  digestCheckedAt = 0;
891
+ /** What the runtime on `port` last listed on disk, and when. Thrown away whenever the store may have changed. */
892
+ tagsCache;
893
+ tagsRefresh;
894
+ /** What the model store last took on disk, and when. */
895
+ storeCache;
896
+ storeRefresh;
897
+ /**
898
+ * The install of one more coding agent beside an installed model, while its installer runs.
899
+ * Not a job: the state file never hears of it, and the state stays `installed`.
900
+ */
901
+ agentInstall;
902
+ /** The agents whose last such install failed, with the end of what the installer printed. Forgotten at a restart. */
903
+ agentFailures = new Map();
573
904
  constructor(deps) {
574
905
  const pin = deps.pin ?? OLLAMA_RUNTIME_PIN;
575
906
  this.deps = {
@@ -590,7 +921,9 @@ class LocalModelServiceImpl {
590
921
  listRunning,
591
922
  getRuntimeVersion,
592
923
  deleteModel,
924
+ listTags,
593
925
  removePartialModelBlobs,
926
+ measureModelStore,
594
927
  checkDeveloperTools: () => checkDeveloperTools(),
595
928
  stockInstallCommand,
596
929
  tryBeginCliInstall,
@@ -656,9 +989,17 @@ class LocalModelServiceImpl {
656
989
  const progress = this.unrecorded?.progress;
657
990
  return progress ? { ...next, progress } : next;
658
991
  }
659
- /** The stored state as a view or a verb must see it: settled, unless a verb is just starting a job. */
992
+ /**
993
+ * The stored state as a view or a verb must see it: settled, unless a verb is just starting a
994
+ * job. A job writes its last state BEFORE it lets go of `this.job`, so when the job ended while
995
+ * this read was out, the read may hold the `installing` from before that write; it is read
996
+ * again rather than settled, or it would show as an interrupted (`paused`) job for a tick.
997
+ */
660
998
  async currentState() {
661
- const state = await this.deps.readState();
999
+ const jobAtRead = this.job;
1000
+ let state = await this.deps.readState();
1001
+ if (jobAtRead && !this.job)
1002
+ state = await this.deps.readState();
662
1003
  return this.jobStarting ? state : this.settled(state);
663
1004
  }
664
1005
  /**
@@ -926,9 +1267,112 @@ class LocalModelServiceImpl {
926
1267
  };
927
1268
  }).catch(() => { });
928
1269
  }
1270
+ // ---------- The library's live half ----------
1271
+ /** The store changed, or may have: the next view reads the runtime's list and the disk again. */
1272
+ forgetStore() {
1273
+ this.tagsCache = undefined;
1274
+ this.storeCache = undefined;
1275
+ }
1276
+ /**
1277
+ * Reads what the running runtime lists on disk. A runtime that does not answer leaves the
1278
+ * last list in place: "it has no models" and "it said nothing" must not look alike, or every
1279
+ * checked model would read as missing for a moment. Never throws.
1280
+ */
1281
+ refreshTags(state) {
1282
+ const port = state.runtime?.port;
1283
+ if (port === undefined || !this.deps.supervisor.status().running) {
1284
+ this.tagsCache = undefined;
1285
+ return Promise.resolve();
1286
+ }
1287
+ this.tagsRefresh ??= (async () => {
1288
+ try {
1289
+ const target = baseUrlOf(port);
1290
+ const version = await this.deps.getRuntimeVersion(target, AbortSignal.timeout(RUNTIME_READ_TIMEOUT_MS));
1291
+ if (version === undefined)
1292
+ return;
1293
+ const tags = await this.deps.listTags(target, AbortSignal.timeout(RUNTIME_READ_TIMEOUT_MS));
1294
+ this.tagsCache = { at: this.deps.now(), port, tags };
1295
+ }
1296
+ catch {
1297
+ /* the last list stays */
1298
+ }
1299
+ finally {
1300
+ this.tagsRefresh = undefined;
1301
+ }
1302
+ })();
1303
+ return this.tagsRefresh;
1304
+ }
1305
+ /** Measures the model store on disk. Never throws. */
1306
+ refreshStore() {
1307
+ this.storeRefresh ??= (async () => {
1308
+ try {
1309
+ const bytes = await this.deps.measureModelStore(this.paths());
1310
+ this.storeCache = { at: this.deps.now(), bytes };
1311
+ }
1312
+ catch {
1313
+ /* the last figure stays */
1314
+ }
1315
+ finally {
1316
+ this.storeRefresh = undefined;
1317
+ }
1318
+ })();
1319
+ return this.storeRefresh;
1320
+ }
1321
+ /**
1322
+ * Keeps the two caches of the view current WITHOUT making the one-second poll wait for the
1323
+ * runtime or the disk: a stale figure is refreshed in the background, and only a figure that
1324
+ * was never read is waited for, briefly.
1325
+ */
1326
+ async freshenListings(state) {
1327
+ const now = this.deps.now();
1328
+ const first = [];
1329
+ if (!this.storeCache || now - this.storeCache.at >= STORE_RECHECK_MS) {
1330
+ const run = this.refreshStore();
1331
+ if (!this.storeCache)
1332
+ first.push(run);
1333
+ }
1334
+ const port = state.runtime?.port;
1335
+ if (port === undefined || !this.deps.supervisor.status().running) {
1336
+ this.tagsCache = undefined;
1337
+ }
1338
+ else if (!this.tagsCache || this.tagsCache.port !== port || now - this.tagsCache.at >= TAGS_RECHECK_MS) {
1339
+ const known = this.tagsCache?.port === port;
1340
+ const run = this.refreshTags(state);
1341
+ if (!known)
1342
+ first.push(run);
1343
+ }
1344
+ if (first.length === 0)
1345
+ return;
1346
+ let timer;
1347
+ const waited = new Promise((resolve) => {
1348
+ timer = setTimeout(resolve, FIRST_LISTING_WAIT_MS);
1349
+ timer.unref();
1350
+ });
1351
+ await Promise.race([Promise.all(first), waited]);
1352
+ clearTimeout(timer);
1353
+ }
929
1354
  // ---------- The view ----------
930
- async liveFacts(state) {
1355
+ /** What `buildHarnessRows()` is told about agent installs: the one that runs, and the ones that failed. */
1356
+ agentMemory() {
1357
+ return {
1358
+ ...(this.agentInstall ? { running: this.agentInstall.cli } : {}),
1359
+ ...(this.agentFailures.size > 0 ? { failed: Object.fromEntries(this.agentFailures) } : {}),
1360
+ };
1361
+ }
1362
+ async liveFacts(state, harnessFacts) {
931
1363
  const status = this.deps.supervisor.status();
1364
+ let harnesses;
1365
+ if (state.state === 'installed') {
1366
+ try {
1367
+ const catalog = this.deps.getCatalog();
1368
+ const facts = harnessFacts ?? (await this.deps.buildHarnessFacts(catalog));
1369
+ harnesses = buildHarnessRows(state, catalog, facts, this.agentMemory());
1370
+ }
1371
+ catch (err) {
1372
+ // Unknown, not "none": the view then lists no agent and still offers a session.
1373
+ console.warn(`[local-model] The coding agents could not be listed: ${getErrorMessage(err)}`);
1374
+ }
1375
+ }
932
1376
  let developerTools = 'unknown';
933
1377
  try {
934
1378
  developerTools = await this.deps.checkDeveloperTools();
@@ -938,16 +1382,19 @@ class LocalModelServiceImpl {
938
1382
  }
939
1383
  let nextModel;
940
1384
  const nextModelId = state.error?.nextModelId;
941
- if (nextModelId) {
942
- try {
943
- const entry = this.deps.getCatalog().models.find((model) => model.id === nextModelId);
944
- if (entry)
945
- nextModel = { modelId: entry.id, modelLabel: entry.label };
946
- }
947
- catch {
948
- /* no model is offered then */
949
- }
1385
+ let labels;
1386
+ try {
1387
+ const models = this.deps.getCatalog().models;
1388
+ const entry = nextModelId ? models.find((model) => model.id === nextModelId) : undefined;
1389
+ if (entry)
1390
+ nextModel = { modelId: entry.id, modelLabel: entry.label };
1391
+ labels = Object.fromEntries(models.map((model) => [model.id, model.label]));
1392
+ }
1393
+ catch {
1394
+ /* no model is offered then, and a model the state file does not know keeps its name */
950
1395
  }
1396
+ const port = state.runtime?.port;
1397
+ const tags = status.running && port !== undefined && this.tagsCache?.port === port ? this.tagsCache.tags : undefined;
951
1398
  return {
952
1399
  running: status.running,
953
1400
  gaveUp: status.gaveUp,
@@ -960,9 +1407,13 @@ class LocalModelServiceImpl {
960
1407
  ...(nextModel ? { nextModel } : {}),
961
1408
  pin: this.deps.pin,
962
1409
  folder: this.paths().root,
1410
+ ...(tags ? { tags } : {}),
1411
+ ...(this.storeCache ? { storeBytes: this.storeCache.bytes } : {}),
1412
+ ...(labels ? { labels } : {}),
1413
+ ...(harnesses ? { harnesses } : {}),
963
1414
  };
964
1415
  }
965
- async view() {
1416
+ async view(options = {}) {
966
1417
  try {
967
1418
  await this.recovered();
968
1419
  let state = await this.currentState();
@@ -982,7 +1433,8 @@ class LocalModelServiceImpl {
982
1433
  this.digestCheckedAt = this.deps.now();
983
1434
  void this.refreshDigest(state).catch(() => { });
984
1435
  }
985
- return buildInstallView(state, await this.liveFacts(state));
1436
+ await this.freshenListings(state);
1437
+ return buildInstallView(state, await this.liveFacts(state, options.harnessFacts));
986
1438
  }
987
1439
  catch (err) {
988
1440
  console.warn(`[local-model] Could not build the install view: ${getErrorMessage(err)}`);
@@ -1021,7 +1473,11 @@ class LocalModelServiceImpl {
1021
1473
  if (state.connection?.endpointId !== endpointId)
1022
1474
  return undefined;
1023
1475
  const status = this.deps.supervisor.status();
1024
- if (state.state !== 'installed' || !state.runtime || !state.model || !status.running) {
1476
+ // A job that changes the model in use runs or stopped: the record may still name the
1477
+ // earlier model, and nothing is started on it until a job ended `installed` again.
1478
+ if (state.state !== 'installed')
1479
+ return buildInstallError('job-unfinished');
1480
+ if (!state.runtime || !state.model || !status.running) {
1025
1481
  if (this.portInUse)
1026
1482
  return buildInstallError('port-in-use', { vars: this.errorVars('port-in-use', state) });
1027
1483
  if (status.gaveUp)
@@ -1077,14 +1533,22 @@ class LocalModelServiceImpl {
1077
1533
  async answer() {
1078
1534
  return { ok: true, view: await this.view() };
1079
1535
  }
1080
- install(request, actor) {
1536
+ install(request, actor, liveSessionNames = []) {
1081
1537
  return this.exclusive(async () => {
1082
1538
  await this.settle();
1083
1539
  const state = await this.currentState();
1084
1540
  if (state.state === 'installing')
1085
1541
  return conflict('job-running');
1086
- if (state.state === 'installed')
1542
+ // The model in use at the context it runs with: there is nothing to install.
1543
+ if (state.state === 'installed' &&
1544
+ state.model?.id === request.modelId &&
1545
+ state.model.context === request.context) {
1087
1546
  return conflict('already-installed');
1547
+ }
1548
+ // Another model takes the runtime (it holds one) and often restarts it for its context.
1549
+ const open = this.sessionsOpen(state, liveSessionNames);
1550
+ if (open)
1551
+ return open;
1088
1552
  // Everything below is checked against what the server itself offers right now, before
1089
1553
  // anything is downloaded.
1090
1554
  const hw = await this.deps.readHardware();
@@ -1133,6 +1597,8 @@ class LocalModelServiceImpl {
1133
1597
  });
1134
1598
  if (refused)
1135
1599
  return refused;
1600
+ await this.undoStop();
1601
+ this.forgetStore();
1136
1602
  void this.deps
1137
1603
  .audit({
1138
1604
  admin: actor.username,
@@ -1145,8 +1611,204 @@ class LocalModelServiceImpl {
1145
1611
  return this.answer();
1146
1612
  });
1147
1613
  }
1614
+ use(request, actor, liveSessionNames = []) {
1615
+ return this.exclusive(async () => {
1616
+ await this.settle();
1617
+ const state = await this.currentState();
1618
+ if (state.state === 'installing')
1619
+ return conflict('job-running');
1620
+ if (INSTALL_TRANSITIONS[state.state].use === undefined)
1621
+ return conflict('wrong-state');
1622
+ const entry = libraryOf(state).find((candidate) => candidate.id === request.modelId);
1623
+ if (!entry) {
1624
+ return { ok: false, status: 400, message: { text: LOCAL_MODEL_INSTALL_LABELS.refusedNotInLibrary } };
1625
+ }
1626
+ if (state.state === 'installed' && state.model?.id === entry.id)
1627
+ return conflict('already-installed');
1628
+ const open = this.sessionsOpen(state, liveSessionNames);
1629
+ if (open)
1630
+ return open;
1631
+ // The coding agent of the switch, which becomes the default one: the one this model was
1632
+ // checked with, else the one of the state, whichever is on this Mac now. A job that
1633
+ // stopped while it installed another agent leaves the state naming one that may not be
1634
+ // there. With neither, any agent the model can be run with that is on this Mac: the
1635
+ // agent is chosen per session, so a switch is not refused for one that was uninstalled.
1636
+ const agents = [entry.cli, state.cli].filter((cli, index, all) => cli !== undefined && all.findIndex((other) => other?.id === cli.id) === index);
1637
+ let cli;
1638
+ for (const agent of agents) {
1639
+ if (await this.deps.recheckCliInstalled(agent.id).catch(() => false)) {
1640
+ cli = agent;
1641
+ break;
1642
+ }
1643
+ }
1644
+ if (!cli) {
1645
+ try {
1646
+ const catalog = this.deps.getCatalog();
1647
+ const afterSwitch = {
1648
+ schema: 1,
1649
+ state: 'installed',
1650
+ model: { id: entry.id, label: entry.label, context: entry.context },
1651
+ };
1652
+ const ready = buildHarnessRows(afterSwitch, catalog, await this.deps.buildHarnessFacts(catalog)).find((row) => row.status === 'ready');
1653
+ if (ready)
1654
+ cli = { id: ready.cli, label: ready.cliLabel };
1655
+ }
1656
+ catch {
1657
+ /* no other agent is known then, and the switch is refused below */
1658
+ }
1659
+ }
1660
+ if (!cli) {
1661
+ return {
1662
+ ok: false,
1663
+ status: 400,
1664
+ message: { text: LOCAL_MODEL_INSTALL_LABELS.refusedAgentMissing, vars: { cli: agents[0]?.label ?? '' } },
1665
+ };
1666
+ }
1667
+ const refused = await this.beginJob(actor, {
1668
+ type: 'use',
1669
+ model: { id: entry.id, label: entry.label, context: entry.context, digest: entry.digest },
1670
+ cli,
1671
+ });
1672
+ if (refused)
1673
+ return refused;
1674
+ await this.undoStop();
1675
+ this.forgetStore();
1676
+ void this.deps
1677
+ .audit({
1678
+ admin: actor.username,
1679
+ action: 'local_model_use',
1680
+ target: entry.id,
1681
+ ...(actor.ip ? { ip: actor.ip } : {}),
1682
+ detail: { cli: cli.id, context: entry.context },
1683
+ })
1684
+ .catch(() => { });
1685
+ return this.answer();
1686
+ });
1687
+ }
1688
+ installAgent(request, actor) {
1689
+ return this.exclusive(async () => {
1690
+ await this.settle();
1691
+ const state = await this.currentState();
1692
+ if (state.state === 'installing')
1693
+ return conflict('job-running');
1694
+ if (!INSTALL_STATE_TABLE[state.state].actions.includes('install-agent'))
1695
+ return conflict('wrong-state');
1696
+ // One installer at a time, whichever agent it is for.
1697
+ if (this.agentInstall)
1698
+ return conflict('job-running');
1699
+ // Checked against what the server itself lists right now, before anything runs.
1700
+ const catalog = this.deps.getCatalog();
1701
+ const facts = await this.deps.buildHarnessFacts(catalog);
1702
+ const row = buildHarnessRows(state, catalog, facts).find((candidate) => candidate.cli === request.cli);
1703
+ if (!row) {
1704
+ return { ok: false, status: 400, message: { text: LOCAL_MODEL_INSTALL_LABELS.refusedAgentNotOffered } };
1705
+ }
1706
+ // Already there (a second click, or it was installed by hand meanwhile): nothing to do.
1707
+ if (row.status === 'ready')
1708
+ return this.answer();
1709
+ if (row.status !== 'installable') {
1710
+ return {
1711
+ ok: false,
1712
+ status: 400,
1713
+ message: { text: LOCAL_MODEL_INSTALL_LABELS.refusedAgentNotInstallable, vars: { cli: row.cliLabel } },
1714
+ };
1715
+ }
1716
+ this.agentFailures.delete(row.cli);
1717
+ const controller = new AbortController();
1718
+ const cli = row.cli;
1719
+ const run = {
1720
+ cli,
1721
+ controller,
1722
+ promise: this.installCodingAgent(cli, actor, controller.signal)
1723
+ .then((outcome) => {
1724
+ if (outcome.kind === 'fail')
1725
+ this.agentFailures.set(cli, { detail: outcome.detail });
1726
+ })
1727
+ .catch((err) => {
1728
+ this.agentFailures.set(cli, { detail: getErrorMessage(err) });
1729
+ })
1730
+ .finally(() => {
1731
+ if (this.agentInstall === run)
1732
+ this.agentInstall = undefined;
1733
+ }),
1734
+ };
1735
+ this.agentInstall = run;
1736
+ return this.answer();
1737
+ });
1738
+ }
1739
+ deleteLibraryModel(request, actor) {
1740
+ return this.exclusive(async () => {
1741
+ await this.settle();
1742
+ const state = await this.currentState();
1743
+ if (state.state === 'installing')
1744
+ return conflict('job-running');
1745
+ if (!INSTALL_STATE_TABLE[state.state].actions.includes('delete-model') || !state.runtime) {
1746
+ return conflict('wrong-state');
1747
+ }
1748
+ const id = request.modelId;
1749
+ // Never a path, and never another registry's name: the same shape a catalogue id has.
1750
+ if (!LOCAL_MODEL_ID_PATTERN.test(id)) {
1751
+ return { ok: false, status: 400, message: { text: LOCAL_MODEL_INSTALL_LABELS.refusedNotOnThisMac } };
1752
+ }
1753
+ const entry = libraryOf(state).find((candidate) => candidate.id === id);
1754
+ if (state.model?.id === id)
1755
+ return conflict('model-active', {}, { model: state.model.label });
1756
+ // Only the runtime deletes a model, and only its answer says what is on disk.
1757
+ const target = baseUrlOf(state.runtime.port);
1758
+ let version;
1759
+ if (this.deps.supervisor.status().running) {
1760
+ try {
1761
+ version = await this.deps.getRuntimeVersion(target, AbortSignal.timeout(RUNTIME_READ_TIMEOUT_MS));
1762
+ }
1763
+ catch {
1764
+ version = undefined;
1765
+ }
1766
+ }
1767
+ if (version === undefined)
1768
+ return conflict('runtime-not-running');
1769
+ const listed = (await this.deps.listTags(target, AbortSignal.timeout(RUNTIME_READ_TIMEOUT_MS))).find((model) => model.name === id);
1770
+ if (!entry && !listed) {
1771
+ return { ok: false, status: 400, message: { text: LOCAL_MODEL_INSTALL_LABELS.refusedNotOnThisMac } };
1772
+ }
1773
+ // Asked of the runtime also for a checked model it did not list just now: its answer
1774
+ // (deleted, or "not found") is what says the model is gone, never an empty listing.
1775
+ let gone = false;
1776
+ try {
1777
+ gone = await this.deps.deleteModel(target, id, AbortSignal.timeout(RUNTIME_READ_TIMEOUT_MS));
1778
+ }
1779
+ catch {
1780
+ gone = false;
1781
+ }
1782
+ if (!gone) {
1783
+ return {
1784
+ ok: false,
1785
+ status: 500,
1786
+ message: { text: LOCAL_MODEL_INSTALL_LABELS.deleteFailed, vars: { model: entry?.label ?? id } },
1787
+ };
1788
+ }
1789
+ if (entry) {
1790
+ await this.record((current) => {
1791
+ const library = libraryOf(current).filter((candidate) => candidate.id !== id);
1792
+ return { ...current, library };
1793
+ });
1794
+ }
1795
+ this.forgetStore();
1796
+ if (actor) {
1797
+ void this.deps
1798
+ .audit({
1799
+ admin: actor.username,
1800
+ action: 'local_model_delete',
1801
+ target: id,
1802
+ ...(actor.ip ? { ip: actor.ip } : {}),
1803
+ detail: { verified: entry !== undefined, bytes: listed?.size ?? entry?.bytes ?? 0 },
1804
+ })
1805
+ .catch(() => { });
1806
+ }
1807
+ return this.answer();
1808
+ });
1809
+ }
1148
1810
  /**
1149
- * Writes the event that starts a job (`install` or `resume`) and starts the job. `undefined`:
1811
+ * Writes the event that starts a job (`install`, `use` or `resume`) and starts the job. `undefined`:
1150
1812
  * started. A state file that cannot be written for lack of space is not a 500: the job did
1151
1813
  * not start, and the view says `disk-full` with its "Try again" (a first install, which has
1152
1814
  * no job to show it on, is answered with that sentence).
@@ -1228,6 +1890,16 @@ class LocalModelServiceImpl {
1228
1890
  return (await this.beginJob(actor, { type: 'resume' })) ?? this.answer();
1229
1891
  });
1230
1892
  }
1893
+ /**
1894
+ * A job that starts from a model the person had stopped runs the runtime, and that model is
1895
+ * then in use: the Stop is undone, like Start undoes it, so the runtime starts with the
1896
+ * server again. Without this the model would be running now and stay down after a restart.
1897
+ */
1898
+ async undoStop() {
1899
+ await this.record((current) => current.runtime && !current.runtime.enabled
1900
+ ? { ...current, runtime: { ...current.runtime, enabled: true } }
1901
+ : undefined);
1902
+ }
1231
1903
  /** 409 `sessions-open` while live sessions use a connection of ours, else `undefined`. */
1232
1904
  sessionsOpen(state, liveSessionNames) {
1233
1905
  if (!state.connection || liveSessionNames.length === 0)
@@ -1281,6 +1953,7 @@ class LocalModelServiceImpl {
1281
1953
  });
1282
1954
  this.portInUse = false;
1283
1955
  this.startFailed = undefined;
1956
+ this.forgetStore();
1284
1957
  await this.record((current) => current.runtime ? { ...current, runtime: { ...current.runtime, enabled: false } } : undefined);
1285
1958
  return this.answer();
1286
1959
  }
@@ -1299,6 +1972,7 @@ class LocalModelServiceImpl {
1299
1972
  const started = await this.startRuntime(state);
1300
1973
  if (started.ok)
1301
1974
  await this.refreshDigest(await this.deps.readState());
1975
+ this.forgetStore();
1302
1976
  return this.answer();
1303
1977
  });
1304
1978
  }
@@ -1329,6 +2003,7 @@ class LocalModelServiceImpl {
1329
2003
  this.portInUse = false;
1330
2004
  this.startFailed = undefined;
1331
2005
  this.digestStatus = undefined;
2006
+ this.forgetStore();
1332
2007
  if (actor) {
1333
2008
  void this.deps
1334
2009
  .audit({
@@ -1387,6 +2062,8 @@ class LocalModelServiceImpl {
1387
2062
  const job = this.job;
1388
2063
  // The state file keeps saying `installing`: the next start reads that as a paused job.
1389
2064
  job?.controller.abort();
2065
+ // An agent installer beside an installed model: its process group is ended, nothing is recorded.
2066
+ this.agentInstall?.controller.abort();
1390
2067
  // The runtime is signalled at once, not after the job let go: the server may exit soon.
1391
2068
  const stopped = Promise.resolve()
1392
2069
  .then(() => this.deps.supervisor.stop())
@@ -1399,8 +2076,9 @@ class LocalModelServiceImpl {
1399
2076
  await stopped;
1400
2077
  }
1401
2078
  async idle() {
1402
- while (this.job)
1403
- await this.job.promise.catch(() => { });
2079
+ while (this.job || this.agentInstall) {
2080
+ await (this.job ?? this.agentInstall)?.promise.catch(() => { });
2081
+ }
1404
2082
  }
1405
2083
  // ---------- The job ----------
1406
2084
  startJob(actor) {
@@ -1439,6 +2117,8 @@ class LocalModelServiceImpl {
1439
2117
  // A step that finished stays finished, also when Cancel arrived while it ran. Its
1440
2118
  // download figures go first, so the next step is never shown with them.
1441
2119
  this.clearProgress();
2120
+ // A model arrived, was checked or was connected: the library is read again.
2121
+ this.forgetStore();
1442
2122
  await this.dispatch({ type: 'step-done' });
1443
2123
  continue;
1444
2124
  }
@@ -1562,32 +2242,9 @@ class LocalModelServiceImpl {
1562
2242
  if (!running.runtime)
1563
2243
  return { kind: 'fail', code: 'internal', detail: 'The runtime has no port.' };
1564
2244
  const target = baseUrlOf(running.runtime.port);
1565
- // What a replaced job left of another model goes first, so two models never share the store.
1566
- if (running.replacedModelId) {
1567
- try {
1568
- await this.deps.deleteModel(target, running.replacedModelId, signal);
1569
- }
1570
- catch {
1571
- /* a leftover is not a reason to stop: Remove with the models deletes it */
1572
- }
1573
- if (signal.aborted)
1574
- return CANCELLED;
1575
- // A download that was interrupted left partial blobs and no model: the runtime answers
1576
- // "not found" for it and deletes nothing. No download is in flight here, so every
1577
- // partial file in the store is a dead one.
1578
- try {
1579
- const freed = await this.deps.removePartialModelBlobs(this.paths());
1580
- if (freed > 0)
1581
- console.log(`[local-model] Deleted ${formatGb(freed)} GB a replaced download had left.`);
1582
- }
1583
- catch {
1584
- /* as above */
1585
- }
1586
- await this.record((current) => {
1587
- const { replacedModelId: _replaced, ...rest } = current;
1588
- return rest;
1589
- });
1590
- }
2245
+ // What a replaced job left of another model goes first, so no unchecked leftover stays in the store.
2246
+ if (await this.dropReplacedModel(running, target, signal))
2247
+ return CANCELLED;
1591
2248
  const pulled = await this.deps.pullModel(target, state.model.id, {
1592
2249
  signal,
1593
2250
  onProgress: (progress) => this.onProgress(progress),
@@ -1618,6 +2275,40 @@ class LocalModelServiceImpl {
1618
2275
  await this.record((current) => current.model ? { ...current, model: { ...current.model, pullBytes } } : undefined);
1619
2276
  return DONE;
1620
2277
  }
2278
+ /**
2279
+ * Deletes what a replaced job left of ANOTHER model (`replacedModelId`): the model through
2280
+ * the runtime when it was downloaded whole, and the partial blobs of an interrupted download.
2281
+ * A no-op without one. True when the job was cancelled meanwhile.
2282
+ */
2283
+ async dropReplacedModel(running, target, signal) {
2284
+ if (!running.replacedModelId)
2285
+ return false;
2286
+ try {
2287
+ await this.deps.deleteModel(target, running.replacedModelId, signal);
2288
+ }
2289
+ catch {
2290
+ /* a leftover is not a reason to stop: Remove with the models deletes it */
2291
+ }
2292
+ if (signal.aborted)
2293
+ return true;
2294
+ // A download that was interrupted left partial blobs and no model: the runtime answers
2295
+ // "not found" for it and deletes nothing. No download is in flight here, so every
2296
+ // partial file in the store is a dead one.
2297
+ try {
2298
+ const freed = await this.deps.removePartialModelBlobs(this.paths());
2299
+ if (freed > 0)
2300
+ console.log(`[local-model] Deleted ${formatGb(freed)} GB a replaced download had left.`);
2301
+ }
2302
+ catch {
2303
+ /* as above */
2304
+ }
2305
+ await this.record((current) => {
2306
+ const { replacedModelId: _replaced, ...rest } = current;
2307
+ return rest;
2308
+ });
2309
+ this.forgetStore();
2310
+ return false;
2311
+ }
1621
2312
  async stepVerify(state, signal) {
1622
2313
  if (!state.model)
1623
2314
  return { kind: 'fail', code: 'internal', detail: 'The job has no model.' };
@@ -1629,6 +2320,26 @@ class LocalModelServiceImpl {
1629
2320
  return { kind: 'fail', code: 'internal', detail: 'The runtime has no port.' };
1630
2321
  const target = baseUrlOf(running.runtime.port);
1631
2322
  const { id, context } = state.model;
2323
+ // A switch has no download step, so the leftovers of the job it replaced go here.
2324
+ if (await this.dropReplacedModel(running, target, signal))
2325
+ return CANCELLED;
2326
+ // A switch names the digest the model was checked with (`use`). Another one under the
2327
+ // same name is other weights or another template: it is not loaded, let alone connected.
2328
+ const expected = state.model.digest;
2329
+ if (expected) {
2330
+ const before = await this.deps.readModelDigest(target, id, signal);
2331
+ if (signal.aborted)
2332
+ return CANCELLED;
2333
+ if (compareModelDigest(expected, before) !== 'same') {
2334
+ return {
2335
+ kind: 'fail',
2336
+ code: 'model-changed',
2337
+ detail: before
2338
+ ? 'The runtime reports another digest for the model.'
2339
+ : 'The runtime no longer lists the model.',
2340
+ };
2341
+ }
2342
+ }
1632
2343
  const verified = await this.deps.verifyModel(target, id, context, signal);
1633
2344
  if (!verified.ok) {
1634
2345
  if (verified.code === 'cancelled')
@@ -1671,8 +2382,47 @@ class LocalModelServiceImpl {
1671
2382
  detail: 'The runtime reports no digest for the model.',
1672
2383
  };
1673
2384
  }
2385
+ if (expected && compareModelDigest(expected, digest) !== 'same') {
2386
+ return { kind: 'fail', code: 'model-changed', detail: 'The runtime reports another digest for the model.' };
2387
+ }
1674
2388
  const loaded = verified.loaded;
1675
- await this.record((current) => current.model ? { ...current, model: { ...current.model, digest }, loaded: { ...loaded } } : undefined);
2389
+ // The model is one of the library from here on: checked, with the digest a later switch
2390
+ // must find again, its size on disk and the coding agent of this job.
2391
+ let bytes;
2392
+ try {
2393
+ bytes = (await this.deps.listTags(target, AbortSignal.timeout(RUNTIME_READ_TIMEOUT_MS))).find((model) => model.name === id)?.size;
2394
+ }
2395
+ catch {
2396
+ bytes = undefined;
2397
+ }
2398
+ let verifiedAt;
2399
+ try {
2400
+ verifiedAt = new Date(this.deps.now()).toISOString();
2401
+ }
2402
+ catch {
2403
+ verifiedAt = undefined;
2404
+ }
2405
+ await this.record((current) => {
2406
+ if (!current.model)
2407
+ return undefined;
2408
+ const known = (current.library ?? []).find((entry) => entry.id === id);
2409
+ const size = bytes && bytes > 0 ? bytes : (current.model.pullBytes ?? known?.bytes);
2410
+ const entry = {
2411
+ id,
2412
+ label: current.model.label,
2413
+ context,
2414
+ digest,
2415
+ ...(size ? { bytes: size } : {}),
2416
+ ...(current.cli ? { cli: current.cli } : {}),
2417
+ ...(verifiedAt ? { verifiedAt } : {}),
2418
+ };
2419
+ return {
2420
+ ...current,
2421
+ model: { ...current.model, digest },
2422
+ loaded: { ...loaded },
2423
+ library: upsertLibraryEntry(current.library ?? [], entry),
2424
+ };
2425
+ });
1676
2426
  this.digestStatus = 'same';
1677
2427
  this.digestCheckedAt = this.deps.now();
1678
2428
  return DONE;
@@ -1680,25 +2430,37 @@ class LocalModelServiceImpl {
1680
2430
  async stepAgent(state, actor, signal) {
1681
2431
  if (!state.cli)
1682
2432
  return { kind: 'fail', code: 'internal', detail: 'The job has no coding agent.' };
1683
- const cli = state.cli.id;
1684
- const vars = this.errorVars('harness-failed', state);
2433
+ const outcome = await this.installCodingAgent(state.cli.id, actor, signal);
2434
+ if (outcome.kind !== 'fail')
2435
+ return outcome;
2436
+ return {
2437
+ kind: 'fail',
2438
+ code: 'harness-failed',
2439
+ vars: this.errorVars('harness-failed', state),
2440
+ detail: outcome.detail,
2441
+ };
2442
+ }
2443
+ /**
2444
+ * Installs one coding agent with its STOCK command, through the install slot it shares with
2445
+ * the CLI management routes. What the `agent` step of a job and `installAgent()` both run.
2446
+ * `done` also when the agent is already there; `fail` carries what to show as the detail.
2447
+ */
2448
+ async installCodingAgent(cli, actor, signal) {
1685
2449
  // A resumed job, or an installer that finished before a restart: the binary may be there.
1686
2450
  if (await this.deps.recheckCliInstalled(cli))
1687
- return DONE;
2451
+ return { kind: 'done' };
1688
2452
  if (signal.aborted)
1689
- return CANCELLED;
2453
+ return { kind: 'cancelled' };
1690
2454
  // Only a coding agent of the catalogue, and only its STOCK install command.
1691
2455
  if (!this.deps.getCatalog().harnesses.some((row) => row.cli === cli)) {
1692
- return { kind: 'fail', code: 'harness-failed', vars, detail: 'Not a coding agent of the local model catalogue.' };
2456
+ return { kind: 'fail', detail: 'Not a coding agent of the local model catalogue.' };
1693
2457
  }
1694
2458
  const command = this.deps.stockInstallCommand(cli);
1695
- if (!command) {
1696
- return { kind: 'fail', code: 'harness-failed', vars, detail: 'No install command for this platform.' };
1697
- }
2459
+ if (!command)
2460
+ return { kind: 'fail', detail: 'No install command for this platform.' };
1698
2461
  const release = this.deps.tryBeginCliInstall(cli);
1699
- if (!release) {
1700
- return { kind: 'fail', code: 'harness-failed', vars, detail: 'Another install of this coding agent is running.' };
1701
- }
2462
+ if (!release)
2463
+ return { kind: 'fail', detail: 'Another install of this coding agent is running.' };
1702
2464
  let result;
1703
2465
  try {
1704
2466
  result = await this.deps.runInstallCommand(command, { signal });
@@ -1725,14 +2487,14 @@ class LocalModelServiceImpl {
1725
2487
  // are forgotten either way, and what counts is whether the binary is found now.
1726
2488
  const installed = await this.deps.recheckCliInstalled(cli);
1727
2489
  if (result.aborted || signal.aborted)
1728
- return CANCELLED;
2490
+ return { kind: 'cancelled' };
1729
2491
  if (installed)
1730
- return DONE;
2492
+ return { kind: 'done' };
1731
2493
  const detail = result.timedOut
1732
2494
  ? `The installer was stopped after ${Math.round(CLI_INSTALL_TIMEOUT_MS / 1000)} seconds.`
1733
2495
  : result.output.slice(-INSTALLER_DETAIL_CHARS).trim() ||
1734
2496
  (result.code === 0 ? 'The installer finished, but the program was not found afterwards.' : 'No output.');
1735
- return { kind: 'fail', code: 'harness-failed', vars, detail };
2497
+ return { kind: 'fail', detail };
1736
2498
  }
1737
2499
  async stepConnect(state, signal) {
1738
2500
  if (!state.model)