aicodeman 1.49.0 → 1.50.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 (324) hide show
  1. package/README.md +30 -4
  2. package/dist/cli-install-runner.d.ts +112 -0
  3. package/dist/cli-install-runner.d.ts.map +1 -0
  4. package/dist/cli-install-runner.js +289 -0
  5. package/dist/cli-install-runner.js.map +1 -0
  6. package/dist/cli.d.ts.map +1 -1
  7. package/dist/cli.js +2 -2
  8. package/dist/cli.js.map +1 -1
  9. package/dist/config/attachment-guard.d.ts +11 -0
  10. package/dist/config/attachment-guard.d.ts.map +1 -1
  11. package/dist/config/attachment-guard.js +21 -1
  12. package/dist/config/attachment-guard.js.map +1 -1
  13. package/dist/config/local-model-catalog.d.ts +188 -0
  14. package/dist/config/local-model-catalog.d.ts.map +1 -0
  15. package/dist/config/local-model-catalog.js +556 -0
  16. package/dist/config/local-model-catalog.js.map +1 -0
  17. package/dist/config-backup.js +1 -1
  18. package/dist/config-backup.js.map +1 -1
  19. package/dist/custom-model-hosts-writer.d.ts +50 -0
  20. package/dist/custom-model-hosts-writer.d.ts.map +1 -0
  21. package/dist/custom-model-hosts-writer.js +110 -0
  22. package/dist/custom-model-hosts-writer.js.map +1 -0
  23. package/dist/git-clone.d.ts.map +1 -1
  24. package/dist/git-clone.js +21 -1
  25. package/dist/git-clone.js.map +1 -1
  26. package/dist/git-fetch.d.ts.map +1 -1
  27. package/dist/git-fetch.js +6 -0
  28. package/dist/git-fetch.js.map +1 -1
  29. package/dist/git-workspace-status.d.ts.map +1 -1
  30. package/dist/git-workspace-status.js +4 -0
  31. package/dist/git-workspace-status.js.map +1 -1
  32. package/dist/git-worktrees.d.ts.map +1 -1
  33. package/dist/git-worktrees.js +6 -0
  34. package/dist/git-worktrees.js.map +1 -1
  35. package/dist/hooks-config.d.ts +15 -3
  36. package/dist/hooks-config.d.ts.map +1 -1
  37. package/dist/hooks-config.js +108 -4
  38. package/dist/hooks-config.js.map +1 -1
  39. package/dist/live-worktree.d.ts +73 -15
  40. package/dist/live-worktree.d.ts.map +1 -1
  41. package/dist/live-worktree.js +200 -32
  42. package/dist/live-worktree.js.map +1 -1
  43. package/dist/local-model/connect.d.ts +155 -0
  44. package/dist/local-model/connect.d.ts.map +1 -0
  45. package/dist/local-model/connect.js +243 -0
  46. package/dist/local-model/connect.js.map +1 -0
  47. package/dist/local-model/developer-tools.d.ts +45 -0
  48. package/dist/local-model/developer-tools.d.ts.map +1 -0
  49. package/dist/local-model/developer-tools.js +105 -0
  50. package/dist/local-model/developer-tools.js.map +1 -0
  51. package/dist/local-model/format.d.ts +39 -0
  52. package/dist/local-model/format.d.ts.map +1 -0
  53. package/dist/local-model/format.js +48 -0
  54. package/dist/local-model/format.js.map +1 -0
  55. package/dist/local-model/hardware.d.ts +125 -0
  56. package/dist/local-model/hardware.d.ts.map +1 -0
  57. package/dist/local-model/hardware.js +336 -0
  58. package/dist/local-model/hardware.js.map +1 -0
  59. package/dist/local-model/harness-facts.d.ts +77 -0
  60. package/dist/local-model/harness-facts.d.ts.map +1 -0
  61. package/dist/local-model/harness-facts.js +145 -0
  62. package/dist/local-model/harness-facts.js.map +1 -0
  63. package/dist/local-model/install-job.d.ts +431 -0
  64. package/dist/local-model/install-job.d.ts.map +1 -0
  65. package/dist/local-model/install-job.js +1822 -0
  66. package/dist/local-model/install-job.js.map +1 -0
  67. package/dist/local-model/ollama-client.d.ts +216 -0
  68. package/dist/local-model/ollama-client.d.ts.map +1 -0
  69. package/dist/local-model/ollama-client.js +636 -0
  70. package/dist/local-model/ollama-client.js.map +1 -0
  71. package/dist/local-model/paths.d.ts +64 -0
  72. package/dist/local-model/paths.d.ts.map +1 -0
  73. package/dist/local-model/paths.js +75 -0
  74. package/dist/local-model/paths.js.map +1 -0
  75. package/dist/local-model/recommend.d.ts +118 -0
  76. package/dist/local-model/recommend.d.ts.map +1 -0
  77. package/dist/local-model/recommend.js +430 -0
  78. package/dist/local-model/recommend.js.map +1 -0
  79. package/dist/local-model/runtime.d.ts +339 -0
  80. package/dist/local-model/runtime.d.ts.map +1 -0
  81. package/dist/local-model/runtime.js +1240 -0
  82. package/dist/local-model/runtime.js.map +1 -0
  83. package/dist/local-model/state-store.d.ts +45 -0
  84. package/dist/local-model/state-store.d.ts.map +1 -0
  85. package/dist/local-model/state-store.js +261 -0
  86. package/dist/local-model/state-store.js.map +1 -0
  87. package/dist/readmymind-collectors.d.ts.map +1 -1
  88. package/dist/readmymind-collectors.js +4 -0
  89. package/dist/readmymind-collectors.js.map +1 -1
  90. package/dist/reboot-restore.d.ts +3 -1
  91. package/dist/reboot-restore.d.ts.map +1 -1
  92. package/dist/reboot-restore.js.map +1 -1
  93. package/dist/session.d.ts +29 -7
  94. package/dist/session.d.ts.map +1 -1
  95. package/dist/session.js +63 -10
  96. package/dist/session.js.map +1 -1
  97. package/dist/types/common.d.ts +5 -0
  98. package/dist/types/common.d.ts.map +1 -1
  99. package/dist/types/index.d.ts +4 -0
  100. package/dist/types/index.d.ts.map +1 -1
  101. package/dist/types/index.js +4 -0
  102. package/dist/types/index.js.map +1 -1
  103. package/dist/types/local-model-install.d.ts +533 -0
  104. package/dist/types/local-model-install.d.ts.map +1 -0
  105. package/dist/types/local-model-install.js +169 -0
  106. package/dist/types/local-model-install.js.map +1 -0
  107. package/dist/types/local-model.d.ts +551 -0
  108. package/dist/types/local-model.d.ts.map +1 -0
  109. package/dist/types/local-model.js +115 -0
  110. package/dist/types/local-model.js.map +1 -0
  111. package/dist/types/session.d.ts +17 -6
  112. package/dist/types/session.d.ts.map +1 -1
  113. package/dist/types/session.js.map +1 -1
  114. package/dist/utils/cli-executable-resolver.d.ts +18 -0
  115. package/dist/utils/cli-executable-resolver.d.ts.map +1 -1
  116. package/dist/utils/cli-executable-resolver.js +34 -2
  117. package/dist/utils/cli-executable-resolver.js.map +1 -1
  118. package/dist/utils/git-availability.d.ts +65 -0
  119. package/dist/utils/git-availability.d.ts.map +1 -0
  120. package/dist/utils/git-availability.js +134 -0
  121. package/dist/utils/git-availability.js.map +1 -0
  122. package/dist/web/agent-skill-default-migration.d.ts +60 -0
  123. package/dist/web/agent-skill-default-migration.d.ts.map +1 -0
  124. package/dist/web/agent-skill-default-migration.js +97 -0
  125. package/dist/web/agent-skill-default-migration.js.map +1 -0
  126. package/dist/web/approval-inbox.d.ts +10 -0
  127. package/dist/web/approval-inbox.d.ts.map +1 -1
  128. package/dist/web/approval-inbox.js +15 -0
  129. package/dist/web/approval-inbox.js.map +1 -1
  130. package/dist/web/case-state-sync.d.ts +28 -0
  131. package/dist/web/case-state-sync.d.ts.map +1 -0
  132. package/dist/web/case-state-sync.js +41 -0
  133. package/dist/web/case-state-sync.js.map +1 -0
  134. package/dist/web/ports/config-port.d.ts +1 -1
  135. package/dist/web/ports/config-port.d.ts.map +1 -1
  136. package/dist/web/public/admin-ui.js.gz +0 -0
  137. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  138. package/dist/web/public/{app.9ea37070.js → app.07398d90.js} +1 -1
  139. package/dist/web/public/app.07398d90.js.br +0 -0
  140. package/dist/web/public/app.07398d90.js.gz +0 -0
  141. package/dist/web/public/approvals-ui.js.gz +0 -0
  142. package/dist/web/public/constants.782170e1.js.gz +0 -0
  143. package/dist/web/public/cron-ui.js.gz +0 -0
  144. package/dist/web/public/edit-history-ui.js.gz +0 -0
  145. package/dist/web/public/entrance-animations.js.gz +0 -0
  146. package/dist/web/public/foreign-sessions.js.gz +0 -0
  147. package/dist/web/public/git-status-ui.js.gz +0 -0
  148. package/dist/web/public/header-divider.eb2d2463.js.gz +0 -0
  149. package/dist/web/public/home-sessions.js +38 -18
  150. package/dist/web/public/home-sessions.js.br +0 -0
  151. package/dist/web/public/home-sessions.js.gz +0 -0
  152. package/dist/web/public/host-wake-ui.js.gz +0 -0
  153. package/dist/web/public/{i18n.a5e82c95.js → i18n.519d025e.js} +2 -2
  154. package/dist/web/public/i18n.519d025e.js.br +0 -0
  155. package/dist/web/public/i18n.519d025e.js.gz +0 -0
  156. package/dist/web/public/image-input.a5d0f8f3.js.gz +0 -0
  157. package/dist/web/public/index.html +88 -13
  158. package/dist/web/public/index.html.br +0 -0
  159. package/dist/web/public/index.html.gz +0 -0
  160. package/dist/web/public/input-cjk.8bc46081.js.gz +0 -0
  161. package/dist/web/public/{keyboard-accessory.b941676c.js → keyboard-accessory.0800fc44.js} +160 -2
  162. package/dist/web/public/keyboard-accessory.0800fc44.js.br +0 -0
  163. package/dist/web/public/keyboard-accessory.0800fc44.js.gz +0 -0
  164. package/dist/web/public/local-model-ui.js +1735 -0
  165. package/dist/web/public/local-model-ui.js.br +0 -0
  166. package/dist/web/public/local-model-ui.js.gz +0 -0
  167. package/dist/web/public/mobile-handlers.f7c3f692.js.gz +0 -0
  168. package/dist/web/public/mobile-ime-preview.2dbaf262.js.gz +0 -0
  169. package/dist/web/public/mobile-overview.js +30 -14
  170. package/dist/web/public/mobile-overview.js.br +0 -0
  171. package/dist/web/public/mobile-overview.js.gz +0 -0
  172. package/dist/web/public/mobile.4dfd5c55.css +1 -0
  173. package/dist/web/public/mobile.4dfd5c55.css.br +0 -0
  174. package/dist/web/public/mobile.4dfd5c55.css.gz +0 -0
  175. package/dist/web/public/notification-manager.feb82c04.js.gz +0 -0
  176. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  177. package/dist/web/public/{panels-ui.8bcd4473.js → panels-ui.9ba2683e.js} +100 -98
  178. package/dist/web/public/panels-ui.9ba2683e.js.br +0 -0
  179. package/dist/web/public/panels-ui.9ba2683e.js.gz +0 -0
  180. package/dist/web/public/ralph-panel.b350e2ef.js.gz +0 -0
  181. package/dist/web/public/ralph-wizard.b6c0dd19.js.gz +0 -0
  182. package/dist/web/public/readmymind-ui.js.gz +0 -0
  183. package/dist/web/public/reboot-restore-ui.js +2 -0
  184. package/dist/web/public/reboot-restore-ui.js.br +0 -0
  185. package/dist/web/public/reboot-restore-ui.js.gz +0 -0
  186. package/dist/web/public/respawn-ui.304ba0d4.js.gz +0 -0
  187. package/dist/web/public/sanitize-html.e7147e76.js.gz +0 -0
  188. package/dist/web/public/session-lineage.js.gz +0 -0
  189. package/dist/web/public/{session-ui.a7c8c095.js → session-ui.8f300b14.js} +21 -21
  190. package/dist/web/public/session-ui.8f300b14.js.br +0 -0
  191. package/dist/web/public/session-ui.8f300b14.js.gz +0 -0
  192. package/dist/web/public/{settings-ui.18f92052.js → settings-ui.8b37cf07.js} +14 -14
  193. package/dist/web/public/settings-ui.8b37cf07.js.br +0 -0
  194. package/dist/web/public/settings-ui.8b37cf07.js.gz +0 -0
  195. package/dist/web/public/spreadsheet-preview-worker.js.gz +0 -0
  196. package/dist/web/public/spreadsheet-preview.75c751de.js.gz +0 -0
  197. package/dist/web/public/spreadsheet-xlsx-core.js.gz +0 -0
  198. package/dist/web/public/styles.21b93520.css +1 -0
  199. package/dist/web/public/styles.21b93520.css.br +0 -0
  200. package/dist/web/public/styles.21b93520.css.gz +0 -0
  201. package/dist/web/public/subagent-windows.07277a58.js.gz +0 -0
  202. package/dist/web/public/sw.js +2 -2
  203. package/dist/web/public/sw.js.br +0 -0
  204. package/dist/web/public/sw.js.gz +0 -0
  205. package/dist/web/public/tab-layout-browser.2d6189f7.js.gz +0 -0
  206. package/dist/web/public/tab-rail-resize.b5cdceaf.js.gz +0 -0
  207. package/dist/web/public/terminal-keycode229-recovery.98843069.js.gz +0 -0
  208. package/dist/web/public/terminal-split.js.gz +0 -0
  209. package/dist/web/public/terminal-tile.js.gz +0 -0
  210. package/dist/web/public/{terminal-ui.a7883640.js → terminal-ui.f92eae28.js} +2 -2
  211. package/dist/web/public/terminal-ui.f92eae28.js.br +0 -0
  212. package/dist/web/public/terminal-ui.f92eae28.js.gz +0 -0
  213. package/dist/web/public/tile-grid.js.gz +0 -0
  214. package/dist/web/public/ultracode-panel.js.gz +0 -0
  215. package/dist/web/public/ultracode-windows.js.gz +0 -0
  216. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  217. package/dist/web/public/vendor/exceljs.min.js.gz +0 -0
  218. package/dist/web/public/vendor/fflate.min.js.gz +0 -0
  219. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  220. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  221. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  222. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  223. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  224. package/dist/web/public/vendor/xterm-predictive-echo.276b11d9.js.gz +0 -0
  225. package/dist/web/public/vendor/xterm-zerolag-input.1be42307.js.gz +0 -0
  226. package/dist/web/public/vendor/xterm.css.gz +0 -0
  227. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  228. package/dist/web/public/{voice-input.2342c37b.js → voice-input.d0580528.js} +232 -137
  229. package/dist/web/public/voice-input.d0580528.js.br +0 -0
  230. package/dist/web/public/voice-input.d0580528.js.gz +0 -0
  231. package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
  232. package/dist/web/public/webview-tabs.js.gz +0 -0
  233. package/dist/web/public/whats-new.json +9 -9
  234. package/dist/web/repo-status.d.ts.map +1 -1
  235. package/dist/web/repo-status.js +4 -0
  236. package/dist/web/repo-status.js.map +1 -1
  237. package/dist/web/route-helpers.d.ts +29 -0
  238. package/dist/web/route-helpers.d.ts.map +1 -1
  239. package/dist/web/route-helpers.js +37 -0
  240. package/dist/web/route-helpers.js.map +1 -1
  241. package/dist/web/routes/approval-routes.d.ts.map +1 -1
  242. package/dist/web/routes/approval-routes.js +3 -2
  243. package/dist/web/routes/approval-routes.js.map +1 -1
  244. package/dist/web/routes/case-routes.d.ts.map +1 -1
  245. package/dist/web/routes/case-routes.js +31 -5
  246. package/dist/web/routes/case-routes.js.map +1 -1
  247. package/dist/web/routes/cli-registry-routes.d.ts +1 -27
  248. package/dist/web/routes/cli-registry-routes.d.ts.map +1 -1
  249. package/dist/web/routes/cli-registry-routes.js +11 -202
  250. package/dist/web/routes/cli-registry-routes.js.map +1 -1
  251. package/dist/web/routes/custom-model-routes.d.ts +15 -0
  252. package/dist/web/routes/custom-model-routes.d.ts.map +1 -1
  253. package/dist/web/routes/custom-model-routes.js +114 -33
  254. package/dist/web/routes/custom-model-routes.js.map +1 -1
  255. package/dist/web/routes/file-routes.d.ts +4 -2
  256. package/dist/web/routes/file-routes.d.ts.map +1 -1
  257. package/dist/web/routes/file-routes.js +160 -24
  258. package/dist/web/routes/file-routes.js.map +1 -1
  259. package/dist/web/routes/html-view-routes.d.ts.map +1 -1
  260. package/dist/web/routes/html-view-routes.js +12 -3
  261. package/dist/web/routes/html-view-routes.js.map +1 -1
  262. package/dist/web/routes/index.d.ts +1 -0
  263. package/dist/web/routes/index.d.ts.map +1 -1
  264. package/dist/web/routes/index.js +1 -0
  265. package/dist/web/routes/index.js.map +1 -1
  266. package/dist/web/routes/local-model-routes.d.ts +103 -0
  267. package/dist/web/routes/local-model-routes.d.ts.map +1 -0
  268. package/dist/web/routes/local-model-routes.js +210 -0
  269. package/dist/web/routes/local-model-routes.js.map +1 -0
  270. package/dist/web/routes/reboot-restore-routes.d.ts.map +1 -1
  271. package/dist/web/routes/reboot-restore-routes.js +16 -0
  272. package/dist/web/routes/reboot-restore-routes.js.map +1 -1
  273. package/dist/web/routes/session-routes.d.ts.map +1 -1
  274. package/dist/web/routes/session-routes.js +22 -27
  275. package/dist/web/routes/session-routes.js.map +1 -1
  276. package/dist/web/routes/system-routes.d.ts +2 -2
  277. package/dist/web/routes/system-routes.d.ts.map +1 -1
  278. package/dist/web/routes/system-routes.js +23 -4
  279. package/dist/web/routes/system-routes.js.map +1 -1
  280. package/dist/web/schemas.d.ts +30 -0
  281. package/dist/web/schemas.d.ts.map +1 -1
  282. package/dist/web/schemas.js +52 -5
  283. package/dist/web/schemas.js.map +1 -1
  284. package/dist/web/self-update.d.ts.map +1 -1
  285. package/dist/web/self-update.js +4 -0
  286. package/dist/web/self-update.js.map +1 -1
  287. package/dist/web/sensitive-path.d.ts.map +1 -1
  288. package/dist/web/sensitive-path.js +5 -0
  289. package/dist/web/sensitive-path.js.map +1 -1
  290. package/dist/web/server.d.ts +20 -0
  291. package/dist/web/server.d.ts.map +1 -1
  292. package/dist/web/server.js +83 -7
  293. package/dist/web/server.js.map +1 -1
  294. package/dist/web/voice-stream.d.ts +4 -3
  295. package/dist/web/voice-stream.d.ts.map +1 -1
  296. package/dist/web/voice-stream.js +5 -4
  297. package/dist/web/voice-stream.js.map +1 -1
  298. package/package.json +2 -1
  299. package/skills/codeman/SKILL.md +318 -24
  300. package/skills/codeman/preamble.sh +242 -16
  301. package/skills/codeman/reference/recipes.md +1 -1
  302. package/skills/codeman/reference/verbs.md +101 -1
  303. package/dist/web/public/app.9ea37070.js.br +0 -0
  304. package/dist/web/public/app.9ea37070.js.gz +0 -0
  305. package/dist/web/public/i18n.a5e82c95.js.br +0 -0
  306. package/dist/web/public/i18n.a5e82c95.js.gz +0 -0
  307. package/dist/web/public/keyboard-accessory.b941676c.js.br +0 -0
  308. package/dist/web/public/keyboard-accessory.b941676c.js.gz +0 -0
  309. package/dist/web/public/mobile.67c8eb5b.css +0 -1
  310. package/dist/web/public/mobile.67c8eb5b.css.br +0 -0
  311. package/dist/web/public/mobile.67c8eb5b.css.gz +0 -0
  312. package/dist/web/public/panels-ui.8bcd4473.js.br +0 -0
  313. package/dist/web/public/panels-ui.8bcd4473.js.gz +0 -0
  314. package/dist/web/public/session-ui.a7c8c095.js.br +0 -0
  315. package/dist/web/public/session-ui.a7c8c095.js.gz +0 -0
  316. package/dist/web/public/settings-ui.18f92052.js.br +0 -0
  317. package/dist/web/public/settings-ui.18f92052.js.gz +0 -0
  318. package/dist/web/public/styles.6a718331.css +0 -1
  319. package/dist/web/public/styles.6a718331.css.br +0 -0
  320. package/dist/web/public/styles.6a718331.css.gz +0 -0
  321. package/dist/web/public/terminal-ui.a7883640.js.br +0 -0
  322. package/dist/web/public/terminal-ui.a7883640.js.gz +0 -0
  323. package/dist/web/public/voice-input.2342c37b.js.br +0 -0
  324. package/dist/web/public/voice-input.2342c37b.js.gz +0 -0
@@ -0,0 +1,1822 @@
1
+ /**
2
+ * @fileoverview The local model install job: its state table, the pure reducer over it, the
3
+ * pure view of it, and the service that drives it.
4
+ *
5
+ * ONE job at a time. The job is five steps in a fixed order (`LOCAL_MODEL_INSTALL_STEPS`:
6
+ * runtime, model, verify, agent, connect; `agent` is left out when the coding agent is
7
+ * installed). Its state is one of five (`LocalModelInstallState`), stored in the state file.
8
+ *
9
+ * The state table. "On disk" names what lies under the local model folder; the two writes
10
+ * outside it belong to the `connect` step.
11
+ *
12
+ * | State | On disk | A server restart | Cancel | Allowed next actions |
13
+ * |--------------|-------------------------------------------|-----------------------------|------------------------|---------------------------------|
14
+ * | `idle` | nothing, or leftovers a Remove could not | stays `idle` | refused (409) | install |
15
+ * | | delete (never read back) | | | |
16
+ * | `installing` | what the finished steps wrote, plus what | becomes `paused` at the | becomes `paused` at | cancel |
17
+ * | | the current step has written so far | same step; nothing resumes | the same step | |
18
+ * | | (see the step table) | without a click | | |
19
+ * | `paused` | as `installing` at that step, nothing in | stays `paused` | refused (409) | resume, install (another |
20
+ * | | flight | | | choice), remove |
21
+ * | `failed` | as `installing` at that step, nothing in | stays `failed`, same error | refused (409) | resume (try again), install |
22
+ * | | flight | | | (another choice), remove |
23
+ * | `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 | | |
26
+ *
27
+ * The step table. Every step is IDEMPOTENT, so Resume and "Try again" re-enter the step the
28
+ * job stopped in; they first make sure the runtime runs when the step needs it.
29
+ *
30
+ * | Step | Adds to disk | Cancel | Resume |
31
+ * |-----------|---------------------------------------|------------------------------------------|------------------------------------------------|
32
+ * | `runtime` | the archive's partial file, then the | aborts the download, the partial file | continues the partial file with a Range |
33
+ * | | unpacked runtime, then the private | stays | request, or skips what is already unpacked |
34
+ * | | home once the runtime started | | |
35
+ * | `model` | the model store: partial blobs, then | aborts the pull request, which stops the | pulls again; the runtime continues its partial |
36
+ * | | the model | download; the partial blobs stay | blobs |
37
+ * | `verify` | nothing (the model is loaded into | aborts the request in flight | runs the three checks again from the first |
38
+ * | | memory) | | |
39
+ * | `agent` | whatever the coding agent's own | kills the installer's process group | looks for the binary first and runs the |
40
+ * | | installer writes, outside our folder; | | installer only when it is still missing |
41
+ * | | never removed by us | | |
42
+ * | `connect` | our endpoint record and the settings | honoured before the first write; once | writes both again |
43
+ * | | flag: the two writes outside our | the writes began they finish and the job | |
44
+ * | | folder. The state file claims them | ends `installed` | |
45
+ * | | first | | |
46
+ *
47
+ * How the memory budget gets measured before a model is downloaded (ONE consent, bound to the
48
+ * size shown): the person confirms `Candidate.installBytes` once. The `runtime` step then
49
+ * gets and starts the runtime, reads the device total from its log and judges the choice
50
+ * again with it (`modelFitsBudget()`; `recommend()` with the same options names the next
51
+ * model). When the chosen model at the chosen context no longer fits, the job fails right
52
+ * there with `does-not-fit` and the next model that fits, BEFORE the model download starts. When it fits, the job goes on without a second question: the sizes that were
53
+ * confirmed did not change. From then on the GET reports `budgetSource: 'measured'`.
54
+ *
55
+ * Rules:
56
+ * - `reduceInstallJob()` is PURE and total: an event the transition table does not list for
57
+ * the current state is refused by returning the SAME object, which the service answers
58
+ * with 409 `wrong-state`.
59
+ * - The reducer moves the state, the step, the error and the progress. The FACTS a step
60
+ * learns (the port and pid, the measured total, the pull's total, the digest, what the
61
+ * runtime loaded, the previous settings flag) are written by the service through
62
+ * `mutateLocalModelState()` and never change the state.
63
+ * - A job read as `installing` at boot was interrupted by the restart: the service applies
64
+ * 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).
69
+ * - Install is checked before anything is downloaded: admin only in multi-user mode; the
70
+ * model, the context and the coding agent must be a row the current recommendation offers;
71
+ * the coding agent must be a harness row of the catalogue; `acknowledgedBytes` must be the
72
+ * server's own total.
73
+ * - No CLI id is compared with a literal here: the coding agent is a catalogue row plus a
74
+ * `HarnessFact`.
75
+ *
76
+ * The service (`createLocalModelService()`), beyond the reducer:
77
+ * - Verbs run one at a time on one queue, so two installs sent together cannot both find the
78
+ * state free. The view is not on that queue: the window polls it every second.
79
+ * - An interrupted step is never recorded as failed, whatever its last call answered (an
80
+ * aborted request looks like a network error): the job looks at its own signal before it
81
+ * writes `failed`. Cancel writes `paused` itself; a server that is stopping writes nothing,
82
+ * so the file still says `installing` and the next start reads that as a paused job.
83
+ * - A download's progress is kept in memory, written to the state file every few seconds and
84
+ * when the job pauses or fails. The view shows the live figure and its speed.
85
+ * - What blocks a session on an installed model (another program on the port, a runtime that
86
+ * keeps stopping or did not start, a model whose digest changed) is found live and shown as
87
+ * `error` on the view. It is never stored, and the state stays `installed`.
88
+ * - `launchRefusalMessage()` is what every path that STARTS a coding agent on the managed
89
+ * endpoint asks first: a new session with the model, a model applied to a session, the
90
+ * attach that starts an agent in a session that has none, and the rebuild after a reboot.
91
+ * The digest is read again for every one of them. Two things are not launches and are not
92
+ * asked: a pane that survived a server restart (its agent is already running), and a
93
+ * respawn cycle (it types into the agent that runs).
94
+ * - With a model installed, `boot()` puts the saved endpoint record back when it is gone (a
95
+ * config-backup restore can take it away), starts the runtime unless it was stopped, and
96
+ * reads the digest again.
97
+ * - A runtime an earlier server left behind (a crash, a forced quit) is never left running
98
+ * under a deleted folder or beside a second one: its pid is stored the moment it is
99
+ * spawned, a start adopts or replaces it, and Stop, Remove and the boot of anything that
100
+ * is not a running installation end it (`RuntimeSupervisor.stop({ previousPid })`).
101
+ * - An installed model keeps the runtime VERSION it was installed with: when a later build
102
+ * pins another version, the stored one is started for as long as its folder is unpacked.
103
+ * - A job whose end could not be written to the state file (a full disk) is not lost: the
104
+ * outcome is kept in memory, the view shows it, Resume and a new install start from it, and
105
+ * the next verb writes it. The same holds for any `installing` in the file while this
106
+ * process runs no job, which is what a restart leaves too.
107
+ * - Stop and "Use another port" are refused (409 `sessions-open`) while live sessions use
108
+ * the model: their coding agents were given the address when they started.
109
+ */
110
+ import { appendAdminAudit } from '../web/admin-audit.js';
111
+ import { CLI_INSTALL_TIMEOUT_MS, forgetResolvedCli, runInstallCommand, stockInstallCommand, tryBeginCliInstall, } from '../cli-install-runner.js';
112
+ import { getCli } from '../config/cli-registry/registry.js';
113
+ import { getDataDir } from '../config/instance.js';
114
+ import { getLocalModelCatalog } from '../config/local-model-catalog.js';
115
+ import { readCustomModelHosts } from '../custom-model-hosts.js';
116
+ import { getErrorMessage, LOCAL_MODEL_ERROR_LABELS, LOCAL_MODEL_ERROR_NEXT, LOCAL_MODEL_INSTALL_LABELS, LOCAL_MODEL_INSTALL_STEPS, } from '../types.js';
117
+ import { isCliEntryInstalled, probeStockCliAvailability } from '../utils/cli-installed-probes.js';
118
+ import { compareModelDigest, connectLocalModel, disconnectLocalModel, ensureLocalEndpoint, inspectLocalEndpoint, isLocalModelEndpointId, LOCAL_MODEL_ENDPOINT_ID, moveLocalEndpoint, } from './connect.js';
119
+ import { checkDeveloperTools } from './developer-tools.js';
120
+ import { formatGb } from './format.js';
121
+ import { readHardware } from './hardware.js';
122
+ import { buildHarnessFacts } from './harness-facts.js';
123
+ import { deleteModel, getRuntimeVersion, listOpenAiModels, listRunning, pullModel, readModelDigest, verifyModel, } from './ollama-client.js';
124
+ import { localModelPaths, runtimeBinaryForVersion } from './paths.js';
125
+ import { modelFitsBudget, needBytes, recommend } from './recommend.js';
126
+ import { chooseRuntimePort, createRuntimeSupervisor, ensureRuntimeInstalled, isRuntimeInstalled, OLLAMA_RUNTIME_PIN, removeLocalModelFiles, removePartialModelBlobs, RUNTIME_PORT_FIRST, } from './runtime.js';
127
+ import { IDLE_LOCAL_MODEL_STATE, mutateLocalModelState, readLocalModelState } from './state-store.js';
128
+ /** The state table of the file header, as data. */
129
+ export const INSTALL_STATE_TABLE = {
130
+ idle: {
131
+ onDisk: 'Nothing of ours. The local model folder is absent, or holds leftovers an earlier Remove could not delete; they are never read back.',
132
+ afterRestart: 'idle',
133
+ restart: 'Nothing happens.',
134
+ afterCancel: null,
135
+ cancel: 'Refused: no job is running.',
136
+ actions: ['install'],
137
+ },
138
+ installing: {
139
+ 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.',
140
+ afterRestart: 'paused',
141
+ restart: 'The job comes back paused at the same step. Nothing is downloaded, started or installed until the person presses Resume.',
142
+ afterCancel: 'paused',
143
+ cancel: 'The step in flight is interrupted the way its step row says, and the job is paused at that step.',
144
+ actions: ['cancel'],
145
+ },
146
+ paused: {
147
+ onDisk: 'As installing at that step, with nothing in flight.',
148
+ afterRestart: 'paused',
149
+ restart: 'Stays paused.',
150
+ afterCancel: null,
151
+ cancel: 'Refused: no job is running.',
152
+ actions: ['resume', 'install', 'remove'],
153
+ },
154
+ failed: {
155
+ onDisk: 'As installing at that step, with nothing in flight.',
156
+ afterRestart: 'failed',
157
+ restart: 'Stays failed, with the same error.',
158
+ afterCancel: null,
159
+ cancel: 'Refused: no job is running.',
160
+ actions: ['resume', 'install', 'remove'],
161
+ },
162
+ 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.',
164
+ afterRestart: 'installed',
165
+ 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
+ afterCancel: null,
167
+ cancel: 'Refused: no job is running.',
168
+ actions: ['start-session', 'start', 'stop', 'remove'],
169
+ },
170
+ };
171
+ /** The step table of the file header, as data. */
172
+ export const INSTALL_STEP_TABLE = {
173
+ runtime: {
174
+ does: 'Downloads the pinned runtime archive unless it is unpacked already, compares its sha256, unpacks it, chooses the port once, starts the runtime, reads the measured memory budget from its log and judges the chosen model against it.',
175
+ onDisk: 'runtime/ollama-<version>.tgz.partial while it downloads, runtime/ollama-<version>/ once unpacked, home/ once the runtime started.',
176
+ cancel: 'Aborts the download. The partial file stays. A runtime that already runs keeps running.',
177
+ resume: 'Continues the partial file with a Range request, or skips the download when the folder is unpacked. Starting the runtime again is a no-op when it runs.',
178
+ progress: true,
179
+ needsRuntime: false,
180
+ errors: [
181
+ 'runtime-download-failed',
182
+ 'runtime-damaged',
183
+ 'runtime-unpack-failed',
184
+ 'runtime-start-failed',
185
+ 'port-in-use',
186
+ 'does-not-fit',
187
+ 'disk-full',
188
+ 'internal',
189
+ ],
190
+ },
191
+ model: {
192
+ does: 'Pulls the model through the runtime, reading the progress stream line by line.',
193
+ onDisk: 'models/ with partial blobs, then the finished model.',
194
+ cancel: 'Aborts the pull request, which stops the download. The partial blobs stay.',
195
+ resume: 'Pulls again. The runtime continues its partial blobs.',
196
+ progress: true,
197
+ needsRuntime: true,
198
+ errors: [
199
+ 'pull-failed',
200
+ 'model-not-found',
201
+ 'runtime-start-failed',
202
+ 'runtime-stopped',
203
+ 'port-in-use',
204
+ 'disk-full',
205
+ 'internal',
206
+ ],
207
+ },
208
+ verify: {
209
+ does: 'Loads the model with one tiny chat, checks that the runtime put all of it on the GPU at the chosen context, runs one tool probe, and stores the digest the runtime reports.',
210
+ onDisk: 'Nothing new. The model is loaded into memory.',
211
+ cancel: 'Aborts the request in flight.',
212
+ resume: 'Runs the three checks again from the first.',
213
+ progress: false,
214
+ needsRuntime: true,
215
+ errors: [
216
+ 'load-failed',
217
+ 'does-not-fit',
218
+ 'context-not-applied',
219
+ 'no-tool-call',
220
+ 'probe-unfinished',
221
+ 'runtime-start-failed',
222
+ 'port-in-use',
223
+ 'internal',
224
+ ],
225
+ },
226
+ agent: {
227
+ does: 'Installs the coding agent with its stock install command through the shared CLI install runner, writes the admin audit entry, forgets the cached lookups of its binary and looks for it again.',
228
+ onDisk: 'Whatever the coding agent installer writes, outside the local model folder (its own folder in the home directory). Never removed by us.',
229
+ cancel: 'Kills the whole process group of the installer.',
230
+ resume: 'Looks for the binary first and runs the installer only when it is still missing.',
231
+ progress: false,
232
+ needsRuntime: false,
233
+ errors: ['harness-failed', 'internal'],
234
+ },
235
+ connect: {
236
+ does: 'Claims the connection in the state file (with the value the custom model endpoints setting has now), then writes the endpoint record and switches that setting on.',
237
+ onDisk: 'Our record in custom-model-hosts.json and the flag in settings.json: the two writes outside the local model folder. The state file records the claim before either is written, so neither can exist without it.',
238
+ cancel: 'Honoured before the first write. Once the writes began they finish and the job ends installed. A job interrupted between the claim and the writes has a claim with nothing behind it, which Resume fills in and Remove undoes.',
239
+ resume: 'Writes both again. Both are idempotent, and the claim keeps the value the setting had before.',
240
+ progress: false,
241
+ needsRuntime: true,
242
+ errors: ['endpoint-id-taken', 'connect-failed', 'internal'],
243
+ },
244
+ };
245
+ /**
246
+ * Which state an event leads to, by current state. A pair that is not listed is REFUSED: the
247
+ * reducer returns the object it was given. One entry needs a word: `step-done` in
248
+ * `installing` leads to `installing` at the next step, and to `installed` when the step that
249
+ * finished was the last of the job's `steps`.
250
+ */
251
+ export const INSTALL_TRANSITIONS = {
252
+ idle: { install: 'installing', restart: 'idle', remove: 'idle' },
253
+ installing: {
254
+ progress: 'installing',
255
+ 'step-done': 'installing',
256
+ fail: 'failed',
257
+ cancel: 'paused',
258
+ restart: 'paused',
259
+ },
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' },
263
+ };
264
+ /** The steps a job runs, in order: all of `LOCAL_MODEL_INSTALL_STEPS`, without `agent` when the coding agent is installed. Pure. */
265
+ export function jobSteps(input) {
266
+ return LOCAL_MODEL_INSTALL_STEPS.filter((step) => step !== 'agent' || !input.agentInstalled);
267
+ }
268
+ /** A byte count as a download reports it: a whole number that is not negative. */
269
+ const isByteCount = (value) => Number.isSafeInteger(value) && value >= 0;
270
+ /**
271
+ * The state file after `event`. Pure: no IO, no clock (`updatedAt` is the state store's
272
+ * 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.
275
+ *
276
+ * 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.
279
+ */
280
+ export function reduceInstallJob(current, event) {
281
+ if (INSTALL_TRANSITIONS[current.state][event.type] === undefined)
282
+ return current;
283
+ switch (event.type) {
284
+ case 'install': {
285
+ const steps = event.steps.filter((step, index) => event.steps.indexOf(step) === index);
286
+ if (steps.length === 0 ||
287
+ steps.length !== event.steps.length ||
288
+ steps.some((step) => !LOCAL_MODEL_INSTALL_STEPS.includes(step))) {
289
+ return current;
290
+ }
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;
294
+ return {
295
+ schema: 1,
296
+ state: 'installing',
297
+ step: steps[0],
298
+ steps,
299
+ model: { id: event.model.id, label: event.model.label, context: event.model.context },
300
+ ...(replacedModelId ? { replacedModelId } : {}),
301
+ cli: { id: event.cli.id, label: event.cli.label },
302
+ ...(current.runtime ? { runtime: current.runtime } : {}),
303
+ ...(current.connection ? { connection: current.connection } : {}),
304
+ };
305
+ }
306
+ case 'progress': {
307
+ if (!isByteCount(event.completedBytes) || !isByteCount(event.totalBytes))
308
+ return current;
309
+ return { ...current, progress: { completedBytes: event.completedBytes, totalBytes: event.totalBytes } };
310
+ }
311
+ case 'step-done': {
312
+ const steps = current.steps ?? [];
313
+ const index = current.step ? steps.indexOf(current.step) : -1;
314
+ if (index === -1)
315
+ return current;
316
+ if (index < steps.length - 1) {
317
+ const { progress: _progress, ...rest } = current;
318
+ return { ...rest, step: steps[index + 1] };
319
+ }
320
+ // The last step: the model is connected.
321
+ if (!current.model || !current.cli || !current.runtime)
322
+ return current;
323
+ return {
324
+ schema: 1,
325
+ state: 'installed',
326
+ model: current.model,
327
+ cli: current.cli,
328
+ runtime: current.runtime,
329
+ ...(current.loaded ? { loaded: current.loaded } : {}),
330
+ ...(current.connection ? { connection: current.connection } : {}),
331
+ };
332
+ }
333
+ case 'fail':
334
+ return {
335
+ ...current,
336
+ state: 'failed',
337
+ error: {
338
+ code: event.code,
339
+ ...(event.vars && Object.keys(event.vars).length > 0 ? { vars: event.vars } : {}),
340
+ ...(event.detail ? { detail: event.detail } : {}),
341
+ ...(event.nextModelId ? { nextModelId: event.nextModelId } : {}),
342
+ },
343
+ };
344
+ case 'cancel':
345
+ return { ...current, state: 'paused' };
346
+ case 'restart':
347
+ // Only a running job changes: the restart interrupted it, and it waits for a click.
348
+ return current.state === 'installing' ? { ...current, state: 'paused' } : current;
349
+ case 'resume': {
350
+ const { error: _error, ...rest } = current;
351
+ return { ...rest, state: 'installing' };
352
+ }
353
+ case 'remove':
354
+ return { schema: 1, state: 'idle' };
355
+ }
356
+ }
357
+ /** An error code with its sentence, its slots and its one next step. Pure. */
358
+ export function buildInstallError(code, extra = {}) {
359
+ const next = extra.next ?? LOCAL_MODEL_ERROR_NEXT[code];
360
+ return {
361
+ code,
362
+ message: {
363
+ text: LOCAL_MODEL_ERROR_LABELS[code],
364
+ ...(extra.vars && Object.keys(extra.vars).length > 0 ? { vars: extra.vars } : {}),
365
+ },
366
+ next,
367
+ ...(next === 'next-model' && extra.nextModel ? { nextModel: extra.nextModel } : {}),
368
+ ...(extra.detail ? { detail: extra.detail } : {}),
369
+ };
370
+ }
371
+ /**
372
+ * What blocks a session in state `installed`, found live and never stored: another program
373
+ * on the port, a runtime that keeps stopping, a runtime that did not start, a model that
374
+ * changed. `undefined` when nothing does, which includes a runtime the person stopped. Pure.
375
+ */
376
+ export function installedBlocker(state, live) {
377
+ if (state.state !== 'installed')
378
+ return undefined;
379
+ if (!live.running && live.portInUse) {
380
+ return buildInstallError('port-in-use', { vars: { port: String(state.runtime?.port ?? '') } });
381
+ }
382
+ if (!live.running && live.gaveUp)
383
+ return buildInstallError('runtime-stopped');
384
+ if (!live.running && live.startFailed) {
385
+ // Start is the verb an installed model has: it tries the start again.
386
+ return buildInstallError('runtime-start-failed', {
387
+ next: 'start',
388
+ ...(live.startFailed.detail ? { detail: live.startFailed.detail } : {}),
389
+ });
390
+ }
391
+ if (live.digest === 'changed')
392
+ return buildInstallError('model-changed');
393
+ return undefined;
394
+ }
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) {
397
+ const actions = INSTALL_STATE_TABLE[state.state].actions;
398
+ if (state.state !== 'installed')
399
+ return [...actions];
400
+ const blocked = installedBlocker(state, live) !== undefined;
401
+ return actions.filter((action) => {
402
+ if (action === 'start')
403
+ return !live.running;
404
+ if (action === 'stop')
405
+ return live.running;
406
+ if (action === 'start-session')
407
+ return live.running && !blocked;
408
+ return true;
409
+ });
410
+ }
411
+ /** How far a download is, as the window prints it. Pure. */
412
+ function buildProgress(progress, bytesPerSecond) {
413
+ const view = {
414
+ completedBytes: progress.completedBytes,
415
+ totalBytes: progress.totalBytes,
416
+ completedGb: formatGb(progress.completedBytes),
417
+ totalGb: formatGb(progress.totalBytes),
418
+ };
419
+ if (bytesPerSecond !== undefined && Number.isFinite(bytesPerSecond) && bytesPerSecond >= 0) {
420
+ view.bytesPerSecond = Math.round(bytesPerSecond);
421
+ view.mbPerSecond = String(Math.round(bytesPerSecond / 1_000_000));
422
+ const left = progress.totalBytes - progress.completedBytes;
423
+ if (bytesPerSecond > 0 && left >= 0)
424
+ view.secondsLeft = Math.ceil(left / bytesPerSecond);
425
+ }
426
+ return view;
427
+ }
428
+ /** The `install` object of the GET. Pure: every size text comes from `formatGb()`, every sentence from `LOCAL_MODEL_INSTALL_LABELS`. */
429
+ export function buildInstallView(state, live) {
430
+ const runtimeDownload = live.runtimeInstalled ? 0 : live.pin.bytes;
431
+ const view = {
432
+ state: state.state,
433
+ running: live.running,
434
+ developerTools: live.developerTools,
435
+ runtime: {
436
+ version: live.pin.version,
437
+ installed: live.runtimeInstalled,
438
+ downloadBytes: runtimeDownload,
439
+ downloadGb: formatGb(runtimeDownload),
440
+ unpackedGb: formatGb(live.pin.unpackedBytes),
441
+ },
442
+ folder: live.folder,
443
+ actions: allowedActions(state, live),
444
+ };
445
+ if (state.state === 'idle')
446
+ return view;
447
+ if (state.model) {
448
+ view.model = { id: state.model.id, label: state.model.label };
449
+ view.context = state.model.context;
450
+ }
451
+ if (state.cli) {
452
+ view.cli = state.cli.id;
453
+ view.cliLabel = state.cli.label;
454
+ }
455
+ if (state.runtime)
456
+ view.port = state.runtime.port;
457
+ if (state.state === 'installed') {
458
+ if (state.loaded) {
459
+ view.loaded = {
460
+ context: state.loaded.context,
461
+ memoryBytes: state.loaded.sizeBytes,
462
+ memoryGb: formatGb(state.loaded.sizeBytes),
463
+ onGpu: state.loaded.sizeVramBytes === state.loaded.sizeBytes,
464
+ };
465
+ }
466
+ if (state.connection)
467
+ view.endpointId = state.connection.endpointId;
468
+ const blocker = installedBlocker(state, live);
469
+ if (blocker)
470
+ view.error = blocker;
471
+ return view;
472
+ }
473
+ if (state.step)
474
+ view.step = state.step;
475
+ if (state.steps)
476
+ view.steps = [...state.steps];
477
+ // A download whose total is not known yet has nothing to show.
478
+ if (state.progress && state.progress.totalBytes > 0) {
479
+ view.progress = buildProgress(state.progress, state.state === 'installing' ? live.bytesPerSecond : undefined);
480
+ }
481
+ if (state.state === 'failed' && state.error) {
482
+ view.error = buildInstallError(state.error.code, {
483
+ vars: state.error.vars,
484
+ detail: state.error.detail,
485
+ nextModel: live.nextModel,
486
+ // A job has no Start verb: what helps there is to run the step again.
487
+ ...(LOCAL_MODEL_ERROR_NEXT[state.error.code] === 'start' ? { next: 'retry' } : {}),
488
+ });
489
+ }
490
+ return view;
491
+ }
492
+ /** A sentence of the install as plain English text, its slots filled. For an API error message and the log. Pure. */
493
+ export function formatInstallMessage(message) {
494
+ const vars = message.vars ?? {};
495
+ return message.text.replace(/\{([a-zA-Z]+)\}/g, (slot, key) => Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : slot);
496
+ }
497
+ /** How often a download's progress is written to the state file. The window reads the live figure, not the file. */
498
+ const PROGRESS_FLUSH_MS = 5_000;
499
+ /** How long a digest read stays good for the view. A session launch always reads it again. */
500
+ const DIGEST_RECHECK_MS = 30_000;
501
+ /** How long a read of the runtime's listings may take. */
502
+ const RUNTIME_READ_TIMEOUT_MS = 5_000;
503
+ /** The window a download speed is measured over when the source reports none. */
504
+ const SPEED_WINDOW_MS = 5_000;
505
+ /** How much of an installer's output is kept as the error detail. */
506
+ const INSTALLER_DETAIL_CHARS = 1_000;
507
+ const DONE = { kind: 'done' };
508
+ const CANCELLED = { kind: 'cancelled' };
509
+ const baseUrlOf = (port) => ({ baseUrl: `http://127.0.0.1:${port}` });
510
+ function conflict(reason, extra = {}, vars) {
511
+ const text = {
512
+ 'job-running': LOCAL_MODEL_INSTALL_LABELS.conflictJobRunning,
513
+ 'already-installed': LOCAL_MODEL_INSTALL_LABELS.conflictAlreadyInstalled,
514
+ 'size-changed': LOCAL_MODEL_INSTALL_LABELS.conflictSizeChanged,
515
+ 'sessions-open': LOCAL_MODEL_INSTALL_LABELS.conflictSessionsOpen,
516
+ 'wrong-state': LOCAL_MODEL_INSTALL_LABELS.conflictWrongState,
517
+ }[reason];
518
+ return { ok: false, status: 409, conflict: { reason, message: { text, ...(vars ? { vars } : {}) }, ...extra } };
519
+ }
520
+ /** A supervisor that is built when it is first started, so a server that never installs a model builds none. */
521
+ function lazySupervisor(build) {
522
+ let instance;
523
+ return {
524
+ start: (options) => (instance ??= build()).start(options),
525
+ stop: async (options) => {
526
+ // Built for a stored pid too: a runtime an earlier server left behind has no instance here.
527
+ if (instance || options?.previousPid !== undefined)
528
+ await (instance ??= build()).stop(options);
529
+ },
530
+ status: () => (instance ? instance.status() : { running: false, restarts: 0, gaveUp: false }),
531
+ };
532
+ }
533
+ /** Whether a write failed for lack of space. */
534
+ function isDiskFullError(err) {
535
+ const code = typeof err === 'object' && err !== null ? err.code : undefined;
536
+ return code === 'ENOSPC' || code === 'EDQUOT' || /no space left on device/i.test(getErrorMessage(err));
537
+ }
538
+ /** Forgets the cached lookups of a CLI's binaries the way the CLI registry routes do, then probes it again. */
539
+ async function recheckCliInstalledNow(cli) {
540
+ const entry = getCli(cli);
541
+ if (!entry)
542
+ return false;
543
+ forgetResolvedCli(cli, entry.discovery.binaries);
544
+ const stockAvailability = await probeStockCliAvailability();
545
+ return isCliEntryInstalled(entry, stockAvailability);
546
+ }
547
+ class LocalModelServiceImpl {
548
+ deps;
549
+ /** The one job of this process, while it runs. */
550
+ job;
551
+ /** Verbs run one at a time, so two installs cannot both find the state free. */
552
+ verbChain = Promise.resolve();
553
+ recovery;
554
+ stopping = false;
555
+ /** A verb wrote `installing` and is about to start the job: the view must not take that for a job that is gone. */
556
+ jobStarting = false;
557
+ /**
558
+ * How the last job ended when the state file could not be told (a full disk): the failure,
559
+ * or nothing for a pause, and the download as it stood. Shown from memory and written by
560
+ * the next verb.
561
+ */
562
+ unrecorded;
563
+ /** The download in flight, as last reported. The state file gets it every few seconds. */
564
+ liveProgress;
565
+ lastProgressFlush = 0;
566
+ speedSamples = [];
567
+ /** The last start found another program on the stored port. */
568
+ portInUse = false;
569
+ /** The last start failed for another reason, with what the runtime said. Cleared by a start that works and by Stop. */
570
+ startFailed;
571
+ digestStatus;
572
+ digestCheckedAt = 0;
573
+ constructor(deps) {
574
+ const pin = deps.pin ?? OLLAMA_RUNTIME_PIN;
575
+ this.deps = {
576
+ readHardware: () => readHardware(),
577
+ getCatalog: getLocalModelCatalog,
578
+ buildHarnessFacts: (catalog) => buildHarnessFacts(catalog),
579
+ recommend,
580
+ modelFitsBudget,
581
+ isRuntimeInstalled,
582
+ ensureRuntimeInstalled,
583
+ chooseRuntimePort,
584
+ removeLocalModelFiles,
585
+ supervisor: lazySupervisor(() => createRuntimeSupervisor({ pin, paths: this.paths(), onChange: (status) => this.onRuntimeChange(status) })),
586
+ pullModel,
587
+ verifyModel,
588
+ readModelDigest,
589
+ listOpenAiModels,
590
+ listRunning,
591
+ getRuntimeVersion,
592
+ deleteModel,
593
+ removePartialModelBlobs,
594
+ checkDeveloperTools: () => checkDeveloperTools(),
595
+ stockInstallCommand,
596
+ tryBeginCliInstall,
597
+ runInstallCommand,
598
+ recheckCliInstalled: recheckCliInstalledNow,
599
+ audit: (entry) => appendAdminAudit({ ...entry, detail: entry.detail }),
600
+ inspectLocalEndpoint,
601
+ connectLocalModel,
602
+ moveLocalEndpoint,
603
+ ensureLocalEndpoint,
604
+ disconnectLocalModel,
605
+ isEndpointIdTaken: async () => (await readCustomModelHosts(getDataDir())).some((host) => host.id === LOCAL_MODEL_ENDPOINT_ID),
606
+ readState: readLocalModelState,
607
+ mutateState: mutateLocalModelState,
608
+ now: () => Date.now(),
609
+ ...deps,
610
+ pin,
611
+ };
612
+ }
613
+ // ---------- Small helpers ----------
614
+ paths() {
615
+ return this.deps.paths ?? localModelPaths(this.deps.pin.version);
616
+ }
617
+ /** Runs `fn` after every verb that was asked before it. */
618
+ exclusive(fn) {
619
+ const run = this.verbChain.then(fn);
620
+ this.verbChain = run.catch(() => { });
621
+ return run;
622
+ }
623
+ /** Applies one event of the running job to the stored state. False when the reducer refused it. */
624
+ async dispatch(event) {
625
+ const { after } = await this.deps.mutateState((current) => {
626
+ const next = reduceInstallJob(current, event);
627
+ return next === current ? undefined : next;
628
+ });
629
+ return after !== undefined;
630
+ }
631
+ /**
632
+ * `state` as it stands once a job that is over is counted as over: `installing` in the file
633
+ * while this process runs no job is a job that ended without the file knowing. It is
634
+ * `failed` with the outcome kept in memory, or `paused` when there is none (a restart, a
635
+ * Cancel whose write was refused). A paused or failed job with an outcome in memory is a
636
+ * Resume that could not be written. Pure apart from reading `this.job` and `this.unrecorded`.
637
+ */
638
+ settled(state) {
639
+ if (this.job)
640
+ return state;
641
+ const failure = this.unrecorded?.failure;
642
+ let next;
643
+ if (state.state === 'installing') {
644
+ next = failure
645
+ ? reduceInstallJob(state, { type: 'fail', ...failure })
646
+ : reduceInstallJob(state, { type: 'restart' });
647
+ }
648
+ else if (failure && (state.state === 'paused' || state.state === 'failed')) {
649
+ // A Resume that could not even be written (the disk is full): the job did not start,
650
+ // and it says why instead of looking as if the click did nothing.
651
+ next = reduceInstallJob({ ...state, state: 'installing' }, { type: 'fail', ...failure });
652
+ }
653
+ else {
654
+ return state;
655
+ }
656
+ const progress = this.unrecorded?.progress;
657
+ return progress ? { ...next, progress } : next;
658
+ }
659
+ /**
660
+ * The stored state as a view or a verb must see it: settled, unless a verb is just starting a
661
+ * job. A job writes its last state BEFORE it lets go of `this.job`, so when the job ended while
662
+ * this read was out, the read may hold the `installing` from before that write; it is read
663
+ * again rather than settled, or it would show as an interrupted (`paused`) job for a tick.
664
+ */
665
+ async currentState() {
666
+ const jobAtRead = this.job;
667
+ let state = await this.deps.readState();
668
+ if (jobAtRead && !this.job)
669
+ state = await this.deps.readState();
670
+ return this.jobStarting ? state : this.settled(state);
671
+ }
672
+ /**
673
+ * Applies one event of a VERB to the stored state, after settling it (`settled()`), in one
674
+ * write. False when the reducer refused the event; the settlement is written all the same.
675
+ */
676
+ async verbDispatch(event) {
677
+ let applied = false;
678
+ let settledNow = false;
679
+ await this.deps.mutateState((current) => {
680
+ const base = this.settled(current);
681
+ settledNow = base !== current;
682
+ const next = reduceInstallJob(base, event);
683
+ applied = next !== base;
684
+ if (applied)
685
+ return next;
686
+ return settledNow ? base : undefined;
687
+ });
688
+ if (settledNow || applied)
689
+ this.unrecorded = undefined;
690
+ return applied;
691
+ }
692
+ /**
693
+ * Writes the settlement alone, so the file says what the view already shows. Best effort: a
694
+ * write that is refused (the disk is still full) changes nothing, the outcome stays in
695
+ * memory and the next verb tries again.
696
+ */
697
+ async settle() {
698
+ try {
699
+ let settledNow = false;
700
+ await this.deps.mutateState((current) => {
701
+ const base = this.settled(current);
702
+ settledNow = base !== current;
703
+ return settledNow ? base : undefined;
704
+ });
705
+ if (settledNow)
706
+ this.unrecorded = undefined;
707
+ }
708
+ catch (err) {
709
+ console.warn(`[local-model] Could not write the state of the install: ${getErrorMessage(err)}`);
710
+ }
711
+ }
712
+ /** Writes facts a step learned. Never moves the state, and writes nothing once the job's state is gone. */
713
+ async record(change) {
714
+ await this.deps.mutateState((current) => (current.state === 'idle' ? undefined : change(current)));
715
+ }
716
+ /**
717
+ * A job the state file still calls `installing` when this process has none is one a restart
718
+ * interrupted: it becomes `paused`. Written once per process, before the first view or verb,
719
+ * whether or not `boot()` ran yet. This is the one write a GET makes; a job that ends later
720
+ * without the file knowing is shown from memory (`settled()`) and written by the next verb.
721
+ */
722
+ recovered() {
723
+ this.recovery ??= this.settle();
724
+ return this.recovery;
725
+ }
726
+ async isRuntimeOnDisk() {
727
+ try {
728
+ return await this.deps.isRuntimeInstalled(this.deps.pin, this.paths());
729
+ }
730
+ catch {
731
+ return false;
732
+ }
733
+ }
734
+ /**
735
+ * The runtime version to start: the pinned one when it is unpacked, else the version the
736
+ * state file records when THAT is still unpacked (a model installed by an earlier build
737
+ * with another pin keeps running), else the pinned one, whose start then says what is
738
+ * missing.
739
+ */
740
+ async runtimeVersionToRun(state) {
741
+ const pinned = this.deps.pin.version;
742
+ const stored = state.runtime?.version;
743
+ if (!stored || stored === pinned || (await this.isRuntimeOnDisk()))
744
+ return pinned;
745
+ try {
746
+ const paths = this.paths();
747
+ const binary = runtimeBinaryForVersion(paths, stored);
748
+ if (await this.deps.isRuntimeInstalled({ ...this.deps.pin, version: stored }, { ...paths, binary })) {
749
+ return stored;
750
+ }
751
+ }
752
+ catch {
753
+ /* not a version this build can name: the pinned one is tried */
754
+ }
755
+ return pinned;
756
+ }
757
+ errorVars(code, state) {
758
+ const model = state.model?.label ?? '';
759
+ switch (code) {
760
+ case 'port-in-use':
761
+ return { port: String(state.runtime?.port ?? RUNTIME_PORT_FIRST) };
762
+ case 'model-not-found':
763
+ case 'does-not-fit':
764
+ case 'load-failed':
765
+ case 'no-tool-call':
766
+ case 'probe-unfinished':
767
+ return { model };
768
+ case 'harness-failed':
769
+ return { cli: state.cli?.label ?? '' };
770
+ case 'endpoint-id-taken':
771
+ return { id: LOCAL_MODEL_ENDPOINT_ID };
772
+ default:
773
+ return undefined;
774
+ }
775
+ }
776
+ /**
777
+ * The model to offer after `failed` did not work: the best one the current recommendation
778
+ * offers that is another model. With `smallerThan` (the memory the failed model needs, for
779
+ * `does-not-fit`) only a model that needs LESS is offered: one that needs more would fail
780
+ * the same way. `undefined` when there is none.
781
+ */
782
+ async nextModelId(failed, options, rule = {}) {
783
+ try {
784
+ const hw = await this.deps.readHardware();
785
+ const catalog = this.deps.getCatalog();
786
+ const facts = await this.deps.buildHarnessFacts(catalog);
787
+ const rec = this.deps.recommend(hw, catalog, facts, options ?? (await this.recommendOptions()));
788
+ const rows = [rec.pick, ...rec.alternatives].filter((row) => row !== undefined && row.modelId !== failed.id);
789
+ if (!rule.needsLessMemory)
790
+ return rows[0]?.modelId;
791
+ // What the failed model needs: its row when the recommendation still has it, else the
792
+ // catalogue's figures for it at the context that was chosen.
793
+ const failedRow = [rec.pick, ...rec.alternatives].find((row) => row?.modelId === failed.id);
794
+ const entry = catalog.models.find((model) => model.id === failed.id);
795
+ const limit = failedRow && failedRow.context === failed.context
796
+ ? failedRow.needBytes
797
+ : entry
798
+ ? needBytes(entry, failed.context)
799
+ : undefined;
800
+ if (limit === undefined || !Number.isFinite(limit))
801
+ return undefined;
802
+ return rows.find((row) => row.needBytes < limit)?.modelId;
803
+ }
804
+ catch {
805
+ return undefined;
806
+ }
807
+ }
808
+ // ---------- Progress ----------
809
+ onProgress(progress) {
810
+ const now = this.deps.now();
811
+ let bytesPerSecond = progress.bytesPerSecond;
812
+ if (bytesPerSecond === undefined) {
813
+ // The archive download reports bytes only: the speed is what arrived over the last seconds.
814
+ this.speedSamples.push({ at: now, bytes: progress.completedBytes });
815
+ while (this.speedSamples.length > 2 && now - this.speedSamples[1].at >= SPEED_WINDOW_MS)
816
+ this.speedSamples.shift();
817
+ const first = this.speedSamples[0];
818
+ const elapsed = now - first.at;
819
+ if (elapsed >= 1_000 && progress.completedBytes >= first.bytes) {
820
+ bytesPerSecond = ((progress.completedBytes - first.bytes) * 1_000) / elapsed;
821
+ }
822
+ }
823
+ this.liveProgress = {
824
+ completedBytes: progress.completedBytes,
825
+ totalBytes: progress.totalBytes,
826
+ ...(bytesPerSecond !== undefined ? { bytesPerSecond } : {}),
827
+ };
828
+ if (now - this.lastProgressFlush >= PROGRESS_FLUSH_MS) {
829
+ this.lastProgressFlush = now;
830
+ void this.flushProgress().catch(() => { });
831
+ }
832
+ }
833
+ async flushProgress() {
834
+ const progress = this.liveProgress;
835
+ if (!progress)
836
+ return;
837
+ await this.dispatch({
838
+ type: 'progress',
839
+ completedBytes: progress.completedBytes,
840
+ totalBytes: progress.totalBytes,
841
+ });
842
+ }
843
+ /** The download as it stands, for a job that ends: what a paused or failed job keeps. */
844
+ progressNow() {
845
+ const progress = this.liveProgress;
846
+ return progress ? { completedBytes: progress.completedBytes, totalBytes: progress.totalBytes } : undefined;
847
+ }
848
+ clearProgress() {
849
+ this.liveProgress = undefined;
850
+ this.speedSamples = [];
851
+ this.lastProgressFlush = 0;
852
+ }
853
+ // ---------- The runtime ----------
854
+ /** Starts the runtime on the stored port (a no-op when it runs with this context) and stores what the start learned. */
855
+ async startRuntime(state) {
856
+ if (!state.runtime || !state.model) {
857
+ return { ok: false, code: 'runtime-start-failed', detail: 'No port was chosen for the runtime yet.' };
858
+ }
859
+ const { port } = state.runtime;
860
+ const version = await this.runtimeVersionToRun(state);
861
+ let result;
862
+ try {
863
+ result = await this.deps.supervisor.start({
864
+ port,
865
+ contextLength: state.model.context,
866
+ ...(state.runtime.pid !== undefined ? { previousPid: state.runtime.pid } : {}),
867
+ ...(version !== this.deps.pin.version ? { version } : {}),
868
+ });
869
+ }
870
+ catch (err) {
871
+ result = { ok: false, code: 'runtime-start-failed', detail: getErrorMessage(err) };
872
+ }
873
+ this.portInUse = !result.ok && result.code === 'port-in-use';
874
+ // Kept, so an installed model whose runtime does not start says so instead of only "stopped".
875
+ this.startFailed =
876
+ !result.ok && result.code === 'runtime-start-failed'
877
+ ? { ...(result.detail ? { detail: result.detail } : {}) }
878
+ : undefined;
879
+ if (result.ok) {
880
+ const { pid, measuredTotalBytes } = result;
881
+ await this.record((current) => current.runtime
882
+ ? {
883
+ ...current,
884
+ runtime: {
885
+ ...current.runtime,
886
+ version,
887
+ pid,
888
+ ...(measuredTotalBytes !== undefined ? { measuredTotalBytes } : {}),
889
+ },
890
+ }
891
+ : undefined);
892
+ }
893
+ return result;
894
+ }
895
+ startFailure(result, state) {
896
+ return {
897
+ kind: 'fail',
898
+ code: result.code,
899
+ vars: this.errorVars(result.code, state),
900
+ ...(result.detail ? { detail: result.detail } : {}),
901
+ };
902
+ }
903
+ /** Reads the model's digest from the running runtime and compares it with the stored one. */
904
+ async refreshDigest(state) {
905
+ let current;
906
+ if (state.runtime && state.model && this.deps.supervisor.status().running) {
907
+ try {
908
+ current = await this.deps.readModelDigest(baseUrlOf(state.runtime.port), state.model.id, AbortSignal.timeout(RUNTIME_READ_TIMEOUT_MS));
909
+ }
910
+ catch {
911
+ current = undefined;
912
+ }
913
+ }
914
+ this.digestStatus = compareModelDigest(state.model?.digest, current);
915
+ this.digestCheckedAt = this.deps.now();
916
+ return this.digestStatus;
917
+ }
918
+ onRuntimeChange(status) {
919
+ // The pid is stored from the moment the child is spawned, not only once it answers: a
920
+ // server that is killed in between must still find its own runtime at the next start.
921
+ if (status.pid === undefined)
922
+ return;
923
+ const { pid, measuredTotalBytes } = status;
924
+ void this.record((current) => {
925
+ if (!current.runtime)
926
+ return undefined;
927
+ const samePid = current.runtime.pid === pid;
928
+ const sameTotal = measuredTotalBytes === undefined || current.runtime.measuredTotalBytes === measuredTotalBytes;
929
+ if (samePid && sameTotal)
930
+ return undefined;
931
+ return {
932
+ ...current,
933
+ runtime: { ...current.runtime, pid, ...(measuredTotalBytes !== undefined ? { measuredTotalBytes } : {}) },
934
+ };
935
+ }).catch(() => { });
936
+ }
937
+ // ---------- The view ----------
938
+ async liveFacts(state) {
939
+ const status = this.deps.supervisor.status();
940
+ let developerTools = 'unknown';
941
+ try {
942
+ developerTools = await this.deps.checkDeveloperTools();
943
+ }
944
+ catch {
945
+ /* said as unknown: the sentence is not shown */
946
+ }
947
+ let nextModel;
948
+ const nextModelId = state.error?.nextModelId;
949
+ if (nextModelId) {
950
+ try {
951
+ const entry = this.deps.getCatalog().models.find((model) => model.id === nextModelId);
952
+ if (entry)
953
+ nextModel = { modelId: entry.id, modelLabel: entry.label };
954
+ }
955
+ catch {
956
+ /* no model is offered then */
957
+ }
958
+ }
959
+ return {
960
+ running: status.running,
961
+ gaveUp: status.gaveUp,
962
+ portInUse: this.portInUse,
963
+ ...(this.startFailed ? { startFailed: this.startFailed } : {}),
964
+ ...(state.state === 'installed' && this.digestStatus ? { digest: this.digestStatus } : {}),
965
+ developerTools,
966
+ runtimeInstalled: await this.isRuntimeOnDisk(),
967
+ ...(this.liveProgress?.bytesPerSecond !== undefined ? { bytesPerSecond: this.liveProgress.bytesPerSecond } : {}),
968
+ ...(nextModel ? { nextModel } : {}),
969
+ pin: this.deps.pin,
970
+ folder: this.paths().root,
971
+ };
972
+ }
973
+ async view() {
974
+ try {
975
+ await this.recovered();
976
+ let state = await this.currentState();
977
+ if (state.state === 'installing' && this.liveProgress) {
978
+ state = {
979
+ ...state,
980
+ progress: {
981
+ completedBytes: this.liveProgress.completedBytes,
982
+ totalBytes: this.liveProgress.totalBytes,
983
+ },
984
+ };
985
+ }
986
+ if (state.state === 'installed' &&
987
+ this.deps.supervisor.status().running &&
988
+ this.deps.now() - this.digestCheckedAt >= DIGEST_RECHECK_MS) {
989
+ // In the background: the window polls every second and must not wait for the runtime.
990
+ this.digestCheckedAt = this.deps.now();
991
+ void this.refreshDigest(state).catch(() => { });
992
+ }
993
+ return buildInstallView(state, await this.liveFacts(state));
994
+ }
995
+ catch (err) {
996
+ console.warn(`[local-model] Could not build the install view: ${getErrorMessage(err)}`);
997
+ return buildInstallView(IDLE_LOCAL_MODEL_STATE, {
998
+ running: false,
999
+ gaveUp: false,
1000
+ portInUse: false,
1001
+ developerTools: 'unknown',
1002
+ runtimeInstalled: false,
1003
+ pin: this.deps.pin,
1004
+ folder: '',
1005
+ });
1006
+ }
1007
+ }
1008
+ async recommendOptions() {
1009
+ let measuredTotalBytes;
1010
+ try {
1011
+ await this.recovered();
1012
+ measuredTotalBytes = (await this.deps.readState()).runtime?.measuredTotalBytes;
1013
+ }
1014
+ catch {
1015
+ measuredTotalBytes = undefined;
1016
+ }
1017
+ return {
1018
+ ...(measuredTotalBytes !== undefined ? { measuredTotalBytes } : {}),
1019
+ runtimeDownloadBytes: (await this.isRuntimeOnDisk()) ? 0 : this.deps.pin.bytes,
1020
+ };
1021
+ }
1022
+ async launchRefusal(endpointId) {
1023
+ if (!isLocalModelEndpointId(endpointId))
1024
+ return undefined;
1025
+ try {
1026
+ await this.recovered();
1027
+ const state = await this.currentState();
1028
+ // A record with the reserved id that this feature did not write is not ours to judge.
1029
+ if (state.connection?.endpointId !== endpointId)
1030
+ return undefined;
1031
+ const status = this.deps.supervisor.status();
1032
+ if (state.state !== 'installed' || !state.runtime || !state.model || !status.running) {
1033
+ if (this.portInUse)
1034
+ return buildInstallError('port-in-use', { vars: this.errorVars('port-in-use', state) });
1035
+ if (status.gaveUp)
1036
+ return buildInstallError('runtime-stopped');
1037
+ if (this.startFailed)
1038
+ return buildInstallError('runtime-start-failed', { next: 'start' });
1039
+ return buildInstallError('runtime-not-running');
1040
+ }
1041
+ const digest = await this.refreshDigest(state);
1042
+ if (digest === 'same')
1043
+ return undefined;
1044
+ if (digest === 'unknown') {
1045
+ // No digest to compare: either the runtime stopped answering, or the model is gone.
1046
+ let version;
1047
+ try {
1048
+ version = await this.deps.getRuntimeVersion(baseUrlOf(state.runtime.port), AbortSignal.timeout(RUNTIME_READ_TIMEOUT_MS));
1049
+ }
1050
+ catch {
1051
+ version = undefined;
1052
+ }
1053
+ if (version === undefined)
1054
+ return buildInstallError('runtime-not-running');
1055
+ this.digestStatus = 'changed';
1056
+ }
1057
+ return buildInstallError('model-changed');
1058
+ }
1059
+ catch (err) {
1060
+ console.warn(`[local-model] The launch check failed: ${getErrorMessage(err)}`);
1061
+ return buildInstallError('runtime-not-running');
1062
+ }
1063
+ }
1064
+ async launchRefusalMessage(endpointId, modelId) {
1065
+ const refusal = await this.launchRefusal(endpointId);
1066
+ if (refusal)
1067
+ return formatInstallMessage(refusal.message);
1068
+ if (!isLocalModelEndpointId(endpointId))
1069
+ return undefined;
1070
+ try {
1071
+ const state = await this.deps.readState();
1072
+ if (state.connection?.endpointId === endpointId && state.model && state.model.id !== modelId) {
1073
+ return formatInstallMessage({
1074
+ text: LOCAL_MODEL_INSTALL_LABELS.refusedOtherModel,
1075
+ vars: { model: state.model.label },
1076
+ });
1077
+ }
1078
+ }
1079
+ catch {
1080
+ /* an unreadable state is "nothing of ours": nothing to refuse */
1081
+ }
1082
+ return undefined;
1083
+ }
1084
+ // ---------- Verbs ----------
1085
+ async answer() {
1086
+ return { ok: true, view: await this.view() };
1087
+ }
1088
+ install(request, actor) {
1089
+ return this.exclusive(async () => {
1090
+ await this.settle();
1091
+ const state = await this.currentState();
1092
+ if (state.state === 'installing')
1093
+ return conflict('job-running');
1094
+ if (state.state === 'installed')
1095
+ return conflict('already-installed');
1096
+ // Everything below is checked against what the server itself offers right now, before
1097
+ // anything is downloaded.
1098
+ const hw = await this.deps.readHardware();
1099
+ const catalog = this.deps.getCatalog();
1100
+ const facts = await this.deps.buildHarnessFacts(catalog);
1101
+ const options = await this.recommendOptions();
1102
+ const rec = this.deps.recommend(hw, catalog, facts, options);
1103
+ const rows = [rec.pick, ...rec.alternatives].filter((row) => row !== undefined);
1104
+ const candidate = rows.find((row) => row.modelId === request.modelId);
1105
+ if (!candidate || candidate.context !== request.context) {
1106
+ return { ok: false, status: 400, message: { text: LOCAL_MODEL_INSTALL_LABELS.refusedModelNotOffered } };
1107
+ }
1108
+ // A row without the list (an older shape) still names its one coding agent in the flat fields.
1109
+ const harnesses = candidate.harnesses ?? [
1110
+ { cli: candidate.cli, cliLabel: candidate.cliLabel, installed: candidate.cliInstalled },
1111
+ ];
1112
+ const harness = harnesses.find((row) => row.cli === request.cli);
1113
+ if (!harness || !catalog.harnesses.some((row) => row.cli === request.cli)) {
1114
+ return { ok: false, status: 400, message: { text: LOCAL_MODEL_INSTALL_LABELS.refusedAgentNotOffered } };
1115
+ }
1116
+ if (!harness.installed && !this.deps.stockInstallCommand(harness.cli)) {
1117
+ return {
1118
+ ok: false,
1119
+ status: 400,
1120
+ message: { text: LOCAL_MODEL_INSTALL_LABELS.refusedAgentNotInstallable, vars: { cli: harness.cliLabel } },
1121
+ };
1122
+ }
1123
+ const expectedBytes = candidate.installBytes ?? candidate.downloadBytes + (options.runtimeDownloadBytes ?? 0);
1124
+ if (request.acknowledgedBytes !== expectedBytes) {
1125
+ const expectedGb = formatGb(expectedBytes);
1126
+ return conflict('size-changed', { expectedBytes, expectedGb }, { size: expectedGb });
1127
+ }
1128
+ // Said now, not after the download: a saved endpoint that already has our id and is not ours.
1129
+ if (!state.connection && (await this.deps.isEndpointIdTaken())) {
1130
+ return {
1131
+ ok: false,
1132
+ status: 400,
1133
+ message: buildInstallError('endpoint-id-taken', { vars: { id: LOCAL_MODEL_ENDPOINT_ID } }).message,
1134
+ };
1135
+ }
1136
+ const refused = await this.beginJob(actor, {
1137
+ type: 'install',
1138
+ model: { id: candidate.modelId, label: candidate.modelLabel, context: candidate.context },
1139
+ cli: { id: harness.cli, label: harness.cliLabel },
1140
+ steps: jobSteps({ agentInstalled: harness.installed }),
1141
+ });
1142
+ if (refused)
1143
+ return refused;
1144
+ void this.deps
1145
+ .audit({
1146
+ admin: actor.username,
1147
+ action: 'local_model_install',
1148
+ target: candidate.modelId,
1149
+ ...(actor.ip ? { ip: actor.ip } : {}),
1150
+ detail: { cli: harness.cli, context: candidate.context, bytes: expectedBytes },
1151
+ })
1152
+ .catch(() => { });
1153
+ return this.answer();
1154
+ });
1155
+ }
1156
+ /**
1157
+ * Writes the event that starts a job (`install` or `resume`) and starts the job. `undefined`:
1158
+ * started. A state file that cannot be written for lack of space is not a 500: the job did
1159
+ * not start, and the view says `disk-full` with its "Try again" (a first install, which has
1160
+ * no job to show it on, is answered with that sentence).
1161
+ */
1162
+ async beginJob(actor, event) {
1163
+ this.jobStarting = true;
1164
+ try {
1165
+ const started = await this.verbDispatch(event);
1166
+ if (!started)
1167
+ return conflict('wrong-state');
1168
+ this.startJob(actor);
1169
+ return undefined;
1170
+ }
1171
+ catch (err) {
1172
+ if (!isDiskFullError(err))
1173
+ throw err;
1174
+ // A first install has no job to show the failure on: the sentence goes back as it is.
1175
+ if (event.type === 'install' && (await this.currentState().catch(() => undefined))?.state === 'idle') {
1176
+ return { ok: false, status: 507, message: { text: LOCAL_MODEL_INSTALL_LABELS.errDiskFull } };
1177
+ }
1178
+ const kept = this.unrecorded?.progress;
1179
+ this.unrecorded = {
1180
+ failure: { code: 'disk-full', detail: getErrorMessage(err) },
1181
+ ...(kept ? { progress: kept } : {}),
1182
+ };
1183
+ return this.answer();
1184
+ }
1185
+ finally {
1186
+ this.jobStarting = false;
1187
+ }
1188
+ }
1189
+ cancel() {
1190
+ return this.exclusive(async () => {
1191
+ // Taken before anything is awaited: a Cancel that arrives while a job runs is answered
1192
+ // with the view after it, also when the job finishes in the same moment.
1193
+ const job = this.job;
1194
+ if (!job) {
1195
+ // No job in this process: a job a restart interrupted is paused, never running.
1196
+ await this.settle();
1197
+ return conflict('wrong-state');
1198
+ }
1199
+ job.controller.abort();
1200
+ await job.promise.catch(() => { });
1201
+ // The step may have finished the job while it was being interrupted (the connect step
1202
+ // completes its two writes). Then there is nothing left to pause, and the view says so.
1203
+ // Otherwise the job is paused with its download as it stood, in ONE write.
1204
+ const progress = this.progressNow();
1205
+ try {
1206
+ await this.deps.mutateState((current) => {
1207
+ if (current.state !== 'installing')
1208
+ return undefined;
1209
+ const kept = progress ? reduceInstallJob(current, { type: 'progress', ...progress }) : current;
1210
+ return reduceInstallJob(kept, { type: 'cancel' });
1211
+ });
1212
+ }
1213
+ catch (err) {
1214
+ // The job IS stopped. The file could not be told: the view shows the pause from memory.
1215
+ console.warn(`[local-model] Could not write the paused install: ${getErrorMessage(err)}`);
1216
+ this.unrecorded = { ...(progress ? { progress } : {}) };
1217
+ }
1218
+ this.clearProgress();
1219
+ return this.answer();
1220
+ });
1221
+ }
1222
+ resume(request, actor, liveSessionNames = []) {
1223
+ return this.exclusive(async () => {
1224
+ await this.settle();
1225
+ const state = await this.currentState();
1226
+ if (state.state === 'installing')
1227
+ return conflict('job-running');
1228
+ if (state.state !== 'paused' && state.state !== 'failed')
1229
+ return conflict('wrong-state');
1230
+ if (request.newPort === true && state.runtime) {
1231
+ const open = this.sessionsOpen(state, liveSessionNames);
1232
+ if (open)
1233
+ return open;
1234
+ await this.changePort(state);
1235
+ }
1236
+ return (await this.beginJob(actor, { type: 'resume' })) ?? this.answer();
1237
+ });
1238
+ }
1239
+ /** 409 `sessions-open` while live sessions use a connection of ours, else `undefined`. */
1240
+ sessionsOpen(state, liveSessionNames) {
1241
+ if (!state.connection || liveSessionNames.length === 0)
1242
+ return undefined;
1243
+ const sessions = [...liveSessionNames];
1244
+ return conflict('sessions-open', { sessions }, { sessions: sessions.join(', ') });
1245
+ }
1246
+ /**
1247
+ * Chooses another port than the stored one and moves the saved endpoint with it. False when
1248
+ * no other port is free. The state file first, then the saved endpoint: a state write that
1249
+ * fails changes nothing, and a refused endpoint write puts the old port back, so the two
1250
+ * never disagree. The stored pid stays: when it is still our own runtime on the OLD port,
1251
+ * the next start ends it instead of leaving a second runtime behind.
1252
+ */
1253
+ async changePort(state) {
1254
+ if (!state.runtime)
1255
+ return false;
1256
+ const previous = state.runtime.port;
1257
+ const port = await this.deps.chooseRuntimePort({ avoid: [previous] });
1258
+ if (port === undefined)
1259
+ return false;
1260
+ const setPort = (value) => this.record((current) => current.runtime ? { ...current, runtime: { ...current.runtime, port: value } } : undefined);
1261
+ await setPort(port);
1262
+ if (state.connection) {
1263
+ try {
1264
+ await this.deps.moveLocalEndpoint(port);
1265
+ }
1266
+ catch (err) {
1267
+ await setPort(previous).catch(() => { });
1268
+ throw err;
1269
+ }
1270
+ }
1271
+ this.portInUse = false;
1272
+ return true;
1273
+ }
1274
+ runtime(request, liveSessionNames = []) {
1275
+ return this.exclusive(async () => {
1276
+ await this.settle();
1277
+ let state = await this.currentState();
1278
+ if (state.state === 'installing')
1279
+ return conflict('job-running');
1280
+ if (state.state !== 'installed' || !state.runtime)
1281
+ return conflict('wrong-state');
1282
+ if (request.action === 'stop') {
1283
+ // Their coding agents keep calling the address they were started with.
1284
+ const open = this.sessionsOpen(state, liveSessionNames);
1285
+ if (open)
1286
+ return open;
1287
+ await this.deps.supervisor.stop({
1288
+ ...(state.runtime.pid !== undefined ? { previousPid: state.runtime.pid } : {}),
1289
+ });
1290
+ this.portInUse = false;
1291
+ this.startFailed = undefined;
1292
+ await this.record((current) => current.runtime ? { ...current, runtime: { ...current.runtime, enabled: false } } : undefined);
1293
+ return this.answer();
1294
+ }
1295
+ if (request.newPort === true) {
1296
+ const open = this.sessionsOpen(state, liveSessionNames);
1297
+ if (open)
1298
+ return open;
1299
+ // The old child, when one is still alive, holds the old port: it must go first.
1300
+ await this.deps.supervisor.stop({
1301
+ ...(state.runtime.pid !== undefined ? { previousPid: state.runtime.pid } : {}),
1302
+ });
1303
+ await this.changePort(state);
1304
+ }
1305
+ await this.record((current) => current.runtime ? { ...current, runtime: { ...current.runtime, enabled: true } } : undefined);
1306
+ state = await this.deps.readState();
1307
+ const started = await this.startRuntime(state);
1308
+ if (started.ok)
1309
+ await this.refreshDigest(await this.deps.readState());
1310
+ return this.answer();
1311
+ });
1312
+ }
1313
+ remove(request, liveSessionNames, actor) {
1314
+ return this.exclusive(async () => {
1315
+ await this.settle();
1316
+ const state = await this.currentState();
1317
+ if (state.state === 'installing')
1318
+ return conflict('job-running');
1319
+ const open = this.sessionsOpen(state, liveSessionNames);
1320
+ if (open)
1321
+ return open;
1322
+ // Our child, and a runtime an earlier server left behind (known by the stored pid): no
1323
+ // file is deleted under a process that still runs from it.
1324
+ await this.deps.supervisor.stop({
1325
+ ...(state.runtime?.pid !== undefined ? { previousPid: state.runtime.pid } : {}),
1326
+ });
1327
+ // The two writes outside our folder are undone first: when one is refused, nothing was
1328
+ // deleted yet and the person can try again.
1329
+ if (state.connection) {
1330
+ await this.deps.disconnectLocalModel({ flagWasEnabled: state.connection.flagWasEnabled });
1331
+ }
1332
+ const removeModel = request.removeModel === true;
1333
+ await this.deps.removeLocalModelFiles({ models: removeModel, paths: this.paths() });
1334
+ await this.verbDispatch({ type: 'remove' });
1335
+ this.clearProgress();
1336
+ this.unrecorded = undefined;
1337
+ this.portInUse = false;
1338
+ this.startFailed = undefined;
1339
+ this.digestStatus = undefined;
1340
+ if (actor) {
1341
+ void this.deps
1342
+ .audit({
1343
+ admin: actor.username,
1344
+ action: 'local_model_remove',
1345
+ target: state.model?.id ?? '',
1346
+ ...(actor.ip ? { ip: actor.ip } : {}),
1347
+ detail: { removeModel },
1348
+ })
1349
+ .catch(() => { });
1350
+ }
1351
+ return this.answer();
1352
+ });
1353
+ }
1354
+ async boot() {
1355
+ try {
1356
+ await this.recovered();
1357
+ const state = await this.currentState();
1358
+ const installed = state.state === 'installed' && state.runtime !== undefined && state.model !== undefined;
1359
+ // The record of the connection can be gone while the model is still installed (a
1360
+ // config-backup restore of an older endpoint store): it is put back, never replaced.
1361
+ if (installed && state.connection && state.runtime && state.model) {
1362
+ const restored = await this.deps.ensureLocalEndpoint({
1363
+ port: state.runtime.port,
1364
+ modelId: state.model.id,
1365
+ context: state.model.context,
1366
+ });
1367
+ if (restored)
1368
+ console.warn('[local-model] The saved endpoint of the model on this Mac was missing and was put back.');
1369
+ }
1370
+ if (!installed || !state.runtime?.enabled) {
1371
+ // Nothing starts the runtime here (a job waits for a click, the person stopped the
1372
+ // model). One an earlier server left behind is ended: it holds the model's memory,
1373
+ // and a later Remove must not delete its folder under it.
1374
+ if (state.runtime?.pid !== undefined) {
1375
+ await this.deps.supervisor.stop({ previousPid: state.runtime.pid });
1376
+ }
1377
+ return;
1378
+ }
1379
+ const started = await this.startRuntime(state);
1380
+ if (!started.ok) {
1381
+ console.warn(`[local-model] The runtime did not start: ${started.code}${started.detail ? ` (${started.detail})` : ''}`);
1382
+ return;
1383
+ }
1384
+ const digest = await this.refreshDigest(await this.deps.readState());
1385
+ if (digest === 'changed') {
1386
+ console.warn('[local-model] The model changed since it was installed. Sessions on it are refused.');
1387
+ }
1388
+ }
1389
+ catch (err) {
1390
+ console.warn(`[local-model] Start-up check failed: ${getErrorMessage(err)}`);
1391
+ }
1392
+ }
1393
+ async shutdown() {
1394
+ this.stopping = true;
1395
+ const job = this.job;
1396
+ // The state file keeps saying `installing`: the next start reads that as a paused job.
1397
+ job?.controller.abort();
1398
+ // The runtime is signalled at once, not after the job let go: the server may exit soon.
1399
+ const stopped = Promise.resolve()
1400
+ .then(() => this.deps.supervisor.stop())
1401
+ .catch((err) => {
1402
+ console.warn(`[local-model] Stopping the runtime failed: ${getErrorMessage(err)}`);
1403
+ });
1404
+ if (job) {
1405
+ await Promise.race([job.promise.catch(() => { }), new Promise((resolve) => setTimeout(resolve, 3_000).unref())]);
1406
+ }
1407
+ await stopped;
1408
+ }
1409
+ async idle() {
1410
+ while (this.job)
1411
+ await this.job.promise.catch(() => { });
1412
+ }
1413
+ // ---------- The job ----------
1414
+ startJob(actor) {
1415
+ const controller = new AbortController();
1416
+ this.clearProgress();
1417
+ this.unrecorded = undefined;
1418
+ const job = {
1419
+ controller,
1420
+ promise: this.runJob(actor, controller.signal).finally(() => {
1421
+ if (this.job === job)
1422
+ this.job = undefined;
1423
+ }),
1424
+ };
1425
+ this.job = job;
1426
+ }
1427
+ /** Runs the steps from the stored one on, until the job is installed, failed or interrupted. Never rejects. */
1428
+ async runJob(actor, signal) {
1429
+ try {
1430
+ for (;;) {
1431
+ const state = await this.deps.readState();
1432
+ if (state.state !== 'installing' || !state.step || signal.aborted)
1433
+ return;
1434
+ let outcome;
1435
+ try {
1436
+ outcome = await this.runStep(state.step, state, actor, signal);
1437
+ }
1438
+ catch (err) {
1439
+ // A write of the step itself that found no space is a full disk, not a mystery.
1440
+ outcome = {
1441
+ kind: 'fail',
1442
+ code: isDiskFullError(err) ? 'disk-full' : 'internal',
1443
+ detail: getErrorMessage(err),
1444
+ };
1445
+ }
1446
+ if (outcome.kind === 'done') {
1447
+ // A step that finished stays finished, also when Cancel arrived while it ran. Its
1448
+ // download figures go first, so the next step is never shown with them.
1449
+ this.clearProgress();
1450
+ await this.dispatch({ type: 'step-done' });
1451
+ continue;
1452
+ }
1453
+ // An interrupted step is not a failed one, whatever its last call answered. Cancel
1454
+ // writes `paused` itself; a server that is stopping writes nothing.
1455
+ if (outcome.kind === 'cancelled' || signal.aborted || this.stopping)
1456
+ return;
1457
+ const failure = {
1458
+ code: outcome.code,
1459
+ ...(outcome.vars ? { vars: outcome.vars } : {}),
1460
+ ...(outcome.detail ? { detail: outcome.detail } : {}),
1461
+ ...(outcome.nextModelId ? { nextModelId: outcome.nextModelId } : {}),
1462
+ };
1463
+ const progress = this.progressNow();
1464
+ try {
1465
+ // The failure and the download as it stood, in ONE write.
1466
+ await this.deps.mutateState((current) => {
1467
+ const kept = progress ? reduceInstallJob(current, { type: 'progress', ...progress }) : current;
1468
+ const next = reduceInstallJob(kept, { type: 'fail', ...failure });
1469
+ return next === current ? undefined : next;
1470
+ });
1471
+ }
1472
+ catch (err) {
1473
+ // The disk that failed the step also refuses the state file. The outcome is not
1474
+ // lost: the view shows it from memory and the next verb writes it.
1475
+ console.warn(`[local-model] Could not write why the install stopped: ${getErrorMessage(err)}`);
1476
+ this.unrecorded = { failure, ...(progress ? { progress } : {}) };
1477
+ }
1478
+ this.clearProgress();
1479
+ return;
1480
+ }
1481
+ }
1482
+ catch (err) {
1483
+ // A write of the job itself was refused (the step that finished could not be recorded).
1484
+ console.warn(`[local-model] The install job stopped: ${getErrorMessage(err)}`);
1485
+ const progress = this.progressNow();
1486
+ this.unrecorded = {
1487
+ failure: { code: isDiskFullError(err) ? 'disk-full' : 'internal', detail: getErrorMessage(err) },
1488
+ ...(progress ? { progress } : {}),
1489
+ };
1490
+ this.clearProgress();
1491
+ }
1492
+ }
1493
+ runStep(step, state, actor, signal) {
1494
+ switch (step) {
1495
+ case 'runtime':
1496
+ return this.stepRuntime(state, signal);
1497
+ case 'model':
1498
+ return this.stepModel(state, signal);
1499
+ case 'verify':
1500
+ return this.stepVerify(state, signal);
1501
+ case 'agent':
1502
+ return this.stepAgent(state, actor, signal);
1503
+ case 'connect':
1504
+ return this.stepConnect(state, signal);
1505
+ }
1506
+ }
1507
+ /** Makes sure the runtime runs before a step that needs it. `undefined`: it runs. */
1508
+ async needRuntime(signal) {
1509
+ const state = await this.deps.readState();
1510
+ const started = await this.startRuntime(state);
1511
+ if (signal.aborted)
1512
+ return CANCELLED;
1513
+ return started.ok ? undefined : this.startFailure(started, state);
1514
+ }
1515
+ async stepRuntime(state, signal) {
1516
+ if (!state.model)
1517
+ return { kind: 'fail', code: 'internal', detail: 'The job has no model.' };
1518
+ const installed = await this.deps.ensureRuntimeInstalled({
1519
+ pin: this.deps.pin,
1520
+ paths: this.paths(),
1521
+ signal,
1522
+ onProgress: (progress) => this.onProgress(progress),
1523
+ });
1524
+ if (!installed.ok) {
1525
+ if (installed.code === 'cancelled')
1526
+ return CANCELLED;
1527
+ return { kind: 'fail', code: installed.code, ...(installed.detail ? { detail: installed.detail } : {}) };
1528
+ }
1529
+ if (signal.aborted)
1530
+ return CANCELLED;
1531
+ // The port is chosen ONCE. A job that already has one keeps it.
1532
+ if (!state.runtime) {
1533
+ const port = await this.deps.chooseRuntimePort();
1534
+ if (port === undefined)
1535
+ return { kind: 'fail', code: 'port-in-use', vars: this.errorVars('port-in-use', state) };
1536
+ await this.record((current) => current.runtime ? undefined : { ...current, runtime: { version: this.deps.pin.version, port, enabled: true } });
1537
+ }
1538
+ const withPort = await this.deps.readState();
1539
+ const started = await this.startRuntime(withPort);
1540
+ if (signal.aborted)
1541
+ return CANCELLED;
1542
+ if (!started.ok)
1543
+ return this.startFailure(started, withPort);
1544
+ // The budget is MEASURED now: the runtime printed the device total when it started. The
1545
+ // model is judged against it before a byte of it is downloaded.
1546
+ const measuredTotalBytes = started.measuredTotalBytes ?? withPort.runtime?.measuredTotalBytes;
1547
+ if (measuredTotalBytes !== undefined) {
1548
+ const hw = await this.deps.readHardware();
1549
+ const catalog = this.deps.getCatalog();
1550
+ const options = { measuredTotalBytes, runtimeDownloadBytes: 0 };
1551
+ if (!this.deps.modelFitsBudget(hw, catalog, state.model.id, state.model.context, options)) {
1552
+ const nextModelId = await this.nextModelId(state.model, options, { needsLessMemory: true });
1553
+ return {
1554
+ kind: 'fail',
1555
+ code: 'does-not-fit',
1556
+ vars: this.errorVars('does-not-fit', state),
1557
+ ...(nextModelId ? { nextModelId } : {}),
1558
+ };
1559
+ }
1560
+ }
1561
+ return DONE;
1562
+ }
1563
+ async stepModel(state, signal) {
1564
+ if (!state.model)
1565
+ return { kind: 'fail', code: 'internal', detail: 'The job has no model.' };
1566
+ const blocked = await this.needRuntime(signal);
1567
+ if (blocked)
1568
+ return blocked;
1569
+ const running = await this.deps.readState();
1570
+ if (!running.runtime)
1571
+ return { kind: 'fail', code: 'internal', detail: 'The runtime has no port.' };
1572
+ const target = baseUrlOf(running.runtime.port);
1573
+ // What a replaced job left of another model goes first, so two models never share the store.
1574
+ if (running.replacedModelId) {
1575
+ try {
1576
+ await this.deps.deleteModel(target, running.replacedModelId, signal);
1577
+ }
1578
+ catch {
1579
+ /* a leftover is not a reason to stop: Remove with the models deletes it */
1580
+ }
1581
+ if (signal.aborted)
1582
+ return CANCELLED;
1583
+ // A download that was interrupted left partial blobs and no model: the runtime answers
1584
+ // "not found" for it and deletes nothing. No download is in flight here, so every
1585
+ // partial file in the store is a dead one.
1586
+ try {
1587
+ const freed = await this.deps.removePartialModelBlobs(this.paths());
1588
+ if (freed > 0)
1589
+ console.log(`[local-model] Deleted ${formatGb(freed)} GB a replaced download had left.`);
1590
+ }
1591
+ catch {
1592
+ /* as above */
1593
+ }
1594
+ await this.record((current) => {
1595
+ const { replacedModelId: _replaced, ...rest } = current;
1596
+ return rest;
1597
+ });
1598
+ }
1599
+ const pulled = await this.deps.pullModel(target, state.model.id, {
1600
+ signal,
1601
+ onProgress: (progress) => this.onProgress(progress),
1602
+ });
1603
+ if (!pulled.ok) {
1604
+ if (pulled.code === 'cancelled')
1605
+ return CANCELLED;
1606
+ // A runtime that is gone for good looks like a broken network to the pull. It is not.
1607
+ const status = this.deps.supervisor.status();
1608
+ if (pulled.code === 'pull-failed' && (status.gaveUp || !status.running)) {
1609
+ return {
1610
+ kind: 'fail',
1611
+ code: 'runtime-stopped',
1612
+ ...(pulled.detail ? { detail: pulled.detail } : {}),
1613
+ };
1614
+ }
1615
+ const nextModelId = pulled.code === 'model-not-found' ? await this.nextModelId(state.model) : undefined;
1616
+ return {
1617
+ kind: 'fail',
1618
+ code: pulled.code,
1619
+ vars: this.errorVars(pulled.code, state),
1620
+ ...(pulled.detail ? { detail: pulled.detail } : {}),
1621
+ ...(nextModelId ? { nextModelId } : {}),
1622
+ };
1623
+ }
1624
+ // From here on every size shown for the model is the pull's own total.
1625
+ const pullBytes = pulled.totalBytes;
1626
+ await this.record((current) => current.model ? { ...current, model: { ...current.model, pullBytes } } : undefined);
1627
+ return DONE;
1628
+ }
1629
+ async stepVerify(state, signal) {
1630
+ if (!state.model)
1631
+ return { kind: 'fail', code: 'internal', detail: 'The job has no model.' };
1632
+ const blocked = await this.needRuntime(signal);
1633
+ if (blocked)
1634
+ return blocked;
1635
+ const running = await this.deps.readState();
1636
+ if (!running.runtime)
1637
+ return { kind: 'fail', code: 'internal', detail: 'The runtime has no port.' };
1638
+ const target = baseUrlOf(running.runtime.port);
1639
+ const { id, context } = state.model;
1640
+ const verified = await this.deps.verifyModel(target, id, context, signal);
1641
+ if (!verified.ok) {
1642
+ if (verified.code === 'cancelled')
1643
+ return CANCELLED;
1644
+ let vars = this.errorVars(verified.code, state);
1645
+ if (verified.code === 'context-not-applied') {
1646
+ let actual = '?';
1647
+ try {
1648
+ const loaded = (await this.deps.listRunning(target, AbortSignal.timeout(RUNTIME_READ_TIMEOUT_MS))).find((model) => model.name === id);
1649
+ if (loaded)
1650
+ actual = String(loaded.contextLength);
1651
+ }
1652
+ catch {
1653
+ /* the sentence then says "?" */
1654
+ }
1655
+ vars = { model: state.model.label, actual, wanted: String(context) };
1656
+ }
1657
+ const nextModelId = verified.code === 'does-not-fit'
1658
+ ? await this.nextModelId(state.model, undefined, { needsLessMemory: true })
1659
+ : verified.code === 'no-tool-call'
1660
+ ? await this.nextModelId(state.model)
1661
+ : undefined;
1662
+ return {
1663
+ kind: 'fail',
1664
+ code: verified.code,
1665
+ ...(vars ? { vars } : {}),
1666
+ ...(verified.detail ? { detail: verified.detail } : {}),
1667
+ ...(nextModelId ? { nextModelId } : {}),
1668
+ };
1669
+ }
1670
+ // The digest of what was just checked: what a session launch compares with from now on.
1671
+ const digest = await this.deps.readModelDigest(target, id, signal);
1672
+ if (signal.aborted)
1673
+ return CANCELLED;
1674
+ if (!digest) {
1675
+ return {
1676
+ kind: 'fail',
1677
+ code: 'load-failed',
1678
+ vars: this.errorVars('load-failed', state),
1679
+ detail: 'The runtime reports no digest for the model.',
1680
+ };
1681
+ }
1682
+ const loaded = verified.loaded;
1683
+ await this.record((current) => current.model ? { ...current, model: { ...current.model, digest }, loaded: { ...loaded } } : undefined);
1684
+ this.digestStatus = 'same';
1685
+ this.digestCheckedAt = this.deps.now();
1686
+ return DONE;
1687
+ }
1688
+ async stepAgent(state, actor, signal) {
1689
+ if (!state.cli)
1690
+ return { kind: 'fail', code: 'internal', detail: 'The job has no coding agent.' };
1691
+ const cli = state.cli.id;
1692
+ const vars = this.errorVars('harness-failed', state);
1693
+ // A resumed job, or an installer that finished before a restart: the binary may be there.
1694
+ if (await this.deps.recheckCliInstalled(cli))
1695
+ return DONE;
1696
+ if (signal.aborted)
1697
+ return CANCELLED;
1698
+ // Only a coding agent of the catalogue, and only its STOCK install command.
1699
+ if (!this.deps.getCatalog().harnesses.some((row) => row.cli === cli)) {
1700
+ return { kind: 'fail', code: 'harness-failed', vars, detail: 'Not a coding agent of the local model catalogue.' };
1701
+ }
1702
+ const command = this.deps.stockInstallCommand(cli);
1703
+ if (!command) {
1704
+ return { kind: 'fail', code: 'harness-failed', vars, detail: 'No install command for this platform.' };
1705
+ }
1706
+ const release = this.deps.tryBeginCliInstall(cli);
1707
+ if (!release) {
1708
+ return { kind: 'fail', code: 'harness-failed', vars, detail: 'Another install of this coding agent is running.' };
1709
+ }
1710
+ let result;
1711
+ try {
1712
+ result = await this.deps.runInstallCommand(command, { signal });
1713
+ }
1714
+ finally {
1715
+ release();
1716
+ }
1717
+ void this.deps
1718
+ .audit({
1719
+ admin: actor.username,
1720
+ action: 'cli_install',
1721
+ target: cli,
1722
+ ...(actor.ip ? { ip: actor.ip } : {}),
1723
+ detail: {
1724
+ command,
1725
+ exitCode: result.code,
1726
+ timedOut: result.timedOut,
1727
+ aborted: result.aborted,
1728
+ via: 'local-model',
1729
+ },
1730
+ })
1731
+ .catch(() => { });
1732
+ // Even a failed or interrupted install may have left a binary behind: the cached lookups
1733
+ // are forgotten either way, and what counts is whether the binary is found now.
1734
+ const installed = await this.deps.recheckCliInstalled(cli);
1735
+ if (result.aborted || signal.aborted)
1736
+ return CANCELLED;
1737
+ if (installed)
1738
+ return DONE;
1739
+ const detail = result.timedOut
1740
+ ? `The installer was stopped after ${Math.round(CLI_INSTALL_TIMEOUT_MS / 1000)} seconds.`
1741
+ : result.output.slice(-INSTALLER_DETAIL_CHARS).trim() ||
1742
+ (result.code === 0 ? 'The installer finished, but the program was not found afterwards.' : 'No output.');
1743
+ return { kind: 'fail', code: 'harness-failed', vars, detail };
1744
+ }
1745
+ async stepConnect(state, signal) {
1746
+ if (!state.model)
1747
+ return { kind: 'fail', code: 'internal', detail: 'The job has no model.' };
1748
+ const blocked = await this.needRuntime(signal);
1749
+ if (blocked)
1750
+ return blocked;
1751
+ const running = await this.deps.readState();
1752
+ if (!running.runtime)
1753
+ return { kind: 'fail', code: 'internal', detail: 'The runtime has no port.' };
1754
+ const { port } = running.runtime;
1755
+ const { id, context } = state.model;
1756
+ // The record names the model exactly as the runtime lists it for a coding agent.
1757
+ const listed = await this.deps.listOpenAiModels(baseUrlOf(port), signal);
1758
+ if (signal.aborted)
1759
+ return CANCELLED;
1760
+ if (!listed.includes(id)) {
1761
+ return { kind: 'fail', code: 'connect-failed', detail: `The runtime does not list ${id}.` };
1762
+ }
1763
+ // The connection is CLAIMED in the state file before either write, so no record of ours
1764
+ // can exist that the state file does not know: a state write that fails, or a server that
1765
+ // is killed between the two, leaves at worst a claim with nothing behind it.
1766
+ let claim = running.connection;
1767
+ if (!claim) {
1768
+ let found;
1769
+ try {
1770
+ found = await this.deps.inspectLocalEndpoint({ port, modelId: id, context });
1771
+ }
1772
+ catch (err) {
1773
+ return { kind: 'fail', code: 'connect-failed', detail: getErrorMessage(err) };
1774
+ }
1775
+ if (signal.aborted)
1776
+ return CANCELLED;
1777
+ // A record with our id that says something else is somebody else's: never overwritten.
1778
+ if (found.record === 'other') {
1779
+ return { kind: 'fail', code: 'endpoint-id-taken', vars: this.errorVars('endpoint-id-taken', state) };
1780
+ }
1781
+ // A record that already says what ours would say can only be ours (the routes refuse
1782
+ // the id): the flag was then switched on by us, and its earlier value is not known, so
1783
+ // it is never switched off again.
1784
+ claim = {
1785
+ endpointId: LOCAL_MODEL_ENDPOINT_ID,
1786
+ flagWasEnabled: found.record === 'same' ? true : found.flagEnabled,
1787
+ };
1788
+ const claimed = claim;
1789
+ await this.record((current) => ({ ...current, connection: claimed }));
1790
+ }
1791
+ if (signal.aborted)
1792
+ return CANCELLED;
1793
+ // From here on the two writes run to their end: Cancel no longer interrupts.
1794
+ const connected = await this.deps.connectLocalModel({
1795
+ port,
1796
+ modelId: id,
1797
+ context,
1798
+ ours: true,
1799
+ flagWasEnabled: claim.flagWasEnabled,
1800
+ });
1801
+ if (!connected.ok) {
1802
+ return {
1803
+ kind: 'fail',
1804
+ code: connected.code,
1805
+ vars: this.errorVars(connected.code, state),
1806
+ ...(connected.detail ? { detail: connected.detail } : {}),
1807
+ };
1808
+ }
1809
+ return DONE;
1810
+ }
1811
+ }
1812
+ /** A service over `deps`. A test builds its own with fakes. */
1813
+ export function createLocalModelService(deps = {}) {
1814
+ return new LocalModelServiceImpl(deps);
1815
+ }
1816
+ let processService;
1817
+ /** The one service of this process, built on first use with the real modules. What the routes and server.ts call. */
1818
+ export function getLocalModelService() {
1819
+ processService ??= createLocalModelService();
1820
+ return processService;
1821
+ }
1822
+ //# sourceMappingURL=install-job.js.map