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,1240 @@
1
+ /**
2
+ * @fileoverview The model runtime: which build Codeman runs, how it gets onto the disk, and
3
+ * how it is kept running.
4
+ *
5
+ * What this module does:
6
+ * - THE PIN. `OLLAMA_RUNTIME_PIN` is a compiled constant. No file, setting, environment
7
+ * variable or request can change the URL, the size or the hash.
8
+ * - DOWNLOAD (`ensureRuntimeInstalled()`). The archive is streamed to
9
+ * `LocalModelPaths.archivePartial` while it is hashed. A cut stream is continued with a
10
+ * Range request, at most `RUNTIME_DOWNLOAD_RETRIES` times. A body longer than `pin.bytes`
11
+ * is refused. The sha256 is compared BEFORE anything is unpacked, and a mismatch deletes the
12
+ * file. Unpacking is `/usr/bin/tar` into `LocalModelPaths.unpackDir`, then one rename to
13
+ * `LocalModelPaths.runtimeDir`.
14
+ * - ENVIRONMENT (`runtimeEnv()`, pure). The child's environment is built from an ALLOWLIST:
15
+ * PATH, TMPDIR, LANG and the proxy variables (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`, in
16
+ * either case) are copied from the server's; HOME is the private one; and exactly these are
17
+ * set: `OLLAMA_HOST=127.0.0.1:<port>`, `OLLAMA_MODELS`, `OLLAMA_CONTEXT_LENGTH`,
18
+ * `OLLAMA_NO_CLOUD=1`, `OLLAMA_KEEP_ALIVE=10m`, `OLLAMA_NUM_PARALLEL=1`,
19
+ * `OLLAMA_MAX_LOADED_MODELS=1`, and the four memory settings of the llama.cpp runner (see
20
+ * MEMORY below). Nothing else gets through: no `CODEMAN_*` and none of the user's own
21
+ * `OLLAMA_*` or `LLAMA_ARG_*`.
22
+ * - MEMORY (what the catalogue's figures for its `llamacpp` rows assume, so change both
23
+ * together: test/local-model-catalog.test.ts holds them to each other). Read in the
24
+ * runtime's v0.40.15 source, not yet measured on a Mac:
25
+ * - `OLLAMA_KV_CACHE_TYPE=q8_0` becomes `--cache-type-k q8_0 --cache-type-v q8_0` of
26
+ * llama-server (llm/llama_server.go): the K/V cache takes 34 bytes per 32 values, 17/32
27
+ * of f16. The runtime's FAQ calls the quality loss "very small". Never q4_0: its loss
28
+ * grows with the context, and a coding agent works at long contexts.
29
+ * - `OLLAMA_FLASH_ATTENTION=1` becomes `--flash-attn on`. A quantized V cache needs flash
30
+ * attention, and left unset the runtime passes `auto`, or `off` where it thinks the GPU
31
+ * cannot, which would make every load with a q8_0 cache fail.
32
+ * - `LLAMA_ARG_CACHE_RAM=1024` bounds llama-server's host prompt cache (the copies of
33
+ * earlier prompts it keeps in memory) to 1024 MiB. The runtime passes no `--cache-ram`
34
+ * for a coding model, and llama-server reads the variable from the environment it
35
+ * inherits (`cmd.Env = os.Environ()`). Unbounded, that cache can grow by gigabytes in a
36
+ * session; 1024 MiB is counted in every `llamacpp` row's `overheadBytes`.
37
+ * - `LLAMA_ARG_CTX_CHECKPOINTS=8` bounds the context checkpoints llama-server keeps per
38
+ * slot (`--ctx-checkpoints`, read from the environment the same way). The llama.cpp the
39
+ * runtime bundles (b12111, the runtime's LLAMA_CPP_VERSION) makes them for every model
40
+ * of the catalogue's `llamacpp` rows: a checkpoint is a host copy of the state that
41
+ * cannot be rolled back (the recurrent state of the linear-attention layers, or the
42
+ * sliding-window cache), two or three per request, and llama-server keeps up to 32 by
43
+ * default. 32 copies of the 27B's 157 MB state are 5 GB, most of which an agent never
44
+ * uses: its next request restores the newest checkpoint of the previous one. 8
45
+ * (llama.cpp's own default from b6800 to b8200; it became 32 at b8250, together with a
46
+ * checkpoint every 8,192 tokens of a long prompt) keeps the last few requests. The cost:
47
+ * a prompt that differs from the last checkpoints further back (a compaction, a cleared
48
+ * old tool result) is processed again from the newest checkpoint before that point, or
49
+ * from its start. 8 checkpoints are counted in every `llamacpp` row's `overheadBytes`.
50
+ * The MLX runner reads none of the four (nothing under mlxrunner/ does): an `mlx` row's
51
+ * figures do not depend on them.
52
+ * - PORT (`chooseRuntimePort()`). Chosen ONCE by binding, from `RUNTIME_PORT_FIRST` across
53
+ * `RUNTIME_PORT_SPAN`, then stored by the caller. Never searched again on a later start.
54
+ * - SUPERVISOR (`createRuntimeSupervisor()`). The runtime is a NON-detached child of the
55
+ * server. `start()` first looks at the port: a listener that answers `/api/version` and
56
+ * whose pid (`previousPid`) runs a binary under our runtime folder is our own orphan and is
57
+ * adopted or replaced; any other listener is the answer `port-in-use`. An orphan is ADOPTED
58
+ * only when keeping it keeps something: it answers the pinned version and has a model loaded
59
+ * at the wanted context. Otherwise it is REPLACED (SIGTERM, then a child of our own), which
60
+ * loses nothing and gives back what an orphan cannot: its log, so the measured budget, and
61
+ * its exit. A child that exits by itself is restarted, at most `RUNTIME_MAX_RESTARTS` times
62
+ * since the last `start()`; `stop()` sends SIGTERM. The supervisor does not write the state
63
+ * file: it reports through `onChange`, and its caller stores the pid and the port. The pid
64
+ * is reported the moment the child is SPAWNED, before it answers, so a server that is
65
+ * killed during a start still leaves a pid that names the runtime as ours. `stop()` takes
66
+ * that stored pid too (`previousPid`): a runtime an earlier server left behind is ended the
67
+ * same way, when its command line is a binary under our runtime folder. `start()` runs the
68
+ * pinned version, or with `version` another one that is unpacked beside it (the version an
69
+ * installed model was installed with).
70
+ * - BUDGET (`parseInferenceComputeTotal()`, pure). Right after it starts, the runtime prints
71
+ * the device total in its log line "inference compute" (`total="37.4 GiB"`). The supervisor
72
+ * reads the child's output for it and reports it as `measuredTotalBytes`.
73
+ * - REMOVAL (`removeLocalModelFiles()`). Deletes the runtime, the private home and, when
74
+ * asked, the models. Only inside `LocalModelPaths.root`, and never through a `root` that
75
+ * is itself a symbolic link. `removePartialModelBlobs()` deletes what an interrupted
76
+ * download left in the model store.
77
+ *
78
+ * Under vitest nothing spawns and nothing is fetched unless a test injects it: the default
79
+ * `spawn` and `fetch` of the dependency objects refuse there, the default `commandOfPid`
80
+ * knows no pid and the default `kill` signals nothing.
81
+ */
82
+ import { execFile, spawn as nodeSpawn } from 'node:child_process';
83
+ import { createHash } from 'node:crypto';
84
+ import { createReadStream } from 'node:fs';
85
+ import { lstat, mkdir, open, readdir, realpath, rename, rm, rmdir, stat, unlink } from 'node:fs/promises';
86
+ import { createServer } from 'node:net';
87
+ import { join, resolve as resolvePath } from 'node:path';
88
+ import { getRuntimeVersion, listRunning } from './ollama-client.js';
89
+ import { isInsideLocalModelRoot, localModelPaths, runtimeBinaryForVersion } from './paths.js';
90
+ // ---------- The pin and the constants ----------
91
+ /** The one runtime build Codeman downloads and runs. See the file header. */
92
+ export const OLLAMA_RUNTIME_PIN = Object.freeze({
93
+ id: 'ollama',
94
+ version: '0.40.15',
95
+ url: 'https://github.com/ollama/ollama/releases/download/v0.40.15/ollama-darwin.tgz',
96
+ bytes: 185_971_671,
97
+ sha256: '607c79d5d6315ef9d896db83adde736a4c0057196329843544e79b95afb260a8',
98
+ // Measured on a MacBook on 2026-11-06: the unpacked folder takes 579 MB.
99
+ unpackedBytes: 579_000_000,
100
+ minMacosMajor: 14,
101
+ });
102
+ /** The first loopback port tried for the runtime. Not 11434: that is the default of a runtime the user may run. */
103
+ export const RUNTIME_PORT_FIRST = 11435;
104
+ /** How many ports are tried from `RUNTIME_PORT_FIRST`. */
105
+ export const RUNTIME_PORT_SPAN = 20;
106
+ /** How often in a row a runtime that exited by itself is started again. */
107
+ export const RUNTIME_MAX_RESTARTS = 3;
108
+ /** How often a cut archive download is continued. */
109
+ export const RUNTIME_DOWNLOAD_RETRIES = 3;
110
+ /** `OLLAMA_KEEP_ALIVE`: how long the model stays loaded after the last request. */
111
+ export const RUNTIME_KEEP_ALIVE = '10m';
112
+ /** `OLLAMA_KV_CACHE_TYPE`: the K/V cache type of the llama.cpp runner. The catalogue's `llamacpp` rows are computed for it. */
113
+ export const RUNTIME_KV_CACHE_TYPE = 'q8_0';
114
+ /** `LLAMA_ARG_CACHE_RAM`, in MiB: the bound of llama-server's host prompt cache. Counted in every `llamacpp` row's overhead. */
115
+ export const RUNTIME_HOST_PROMPT_CACHE_MIB = 1024;
116
+ /** `LLAMA_ARG_CTX_CHECKPOINTS`: the context checkpoints llama-server keeps per slot. Counted in every `llamacpp` row's overhead. */
117
+ export const RUNTIME_CTX_CHECKPOINTS = 8;
118
+ /** The name of the runtime's binary inside its folder and inside the archive. */
119
+ const RUNTIME_BINARY_NAME = 'ollama';
120
+ /** A download that delivers no byte for this long is treated as cut. */
121
+ const DOWNLOAD_IDLE_TIMEOUT_MS = 60_000;
122
+ /** The first wait before a cut download is continued; it doubles with every retry. */
123
+ const DOWNLOAD_RETRY_DELAY_MS = 500;
124
+ /** The least time between two progress reports of the download. */
125
+ const DOWNLOAD_PROGRESS_INTERVAL_MS = 200;
126
+ /** How long `/usr/bin/tar` may take for the 579 MB of the runtime. */
127
+ const UNTAR_TIMEOUT_MS = 180_000;
128
+ /** How long a started runtime has to answer `/api/version`. The first start on the test Mac took a few seconds. */
129
+ const START_TIMEOUT_MS = 30_000;
130
+ /** The wait between two `/api/version` requests while the runtime starts. */
131
+ const START_POLL_MS = 150;
132
+ /** How long `start()` waits for the budget line once the runtime answers. It is printed within a second. */
133
+ const BUDGET_WAIT_MS = 3_000;
134
+ /** How long a runtime gets to exit after SIGTERM before it is sent SIGKILL. */
135
+ const STOP_GRACE_MS = 5_000;
136
+ /** How long the exit is awaited after SIGKILL. */
137
+ const STOP_KILL_WAIT_MS = 2_000;
138
+ /** The wait before a runtime that exited by itself is started again. */
139
+ const RESTART_DELAY_MS = 1_000;
140
+ /** How often an adopted orphan is looked at: it is not our child, so its exit is not an event. */
141
+ const ORPHAN_POLL_MS = 5_000;
142
+ /** How long `ps` may take. */
143
+ const PS_TIMEOUT_MS = 2_000;
144
+ /** How many of the runtime's last log lines are kept for the detail of a failed start. */
145
+ const LOG_TAIL_LINES = 12;
146
+ /** A log line longer than this is cut: the runtime logs request bodies in some modes. */
147
+ const LOG_LINE_MAX_CHARS = 2_000;
148
+ /** How much of a failure text is kept as `detail`. */
149
+ const MAX_DETAIL_CHARS = 600;
150
+ const UNDER_VITEST = Boolean(process.env.VITEST);
151
+ /** A default dependency that refuses under vitest: a test must inject its own. */
152
+ class NotInjectedError extends Error {
153
+ constructor(what) {
154
+ super(`${what} is not available under vitest: the test must inject its own`);
155
+ this.name = 'NotInjectedError';
156
+ }
157
+ }
158
+ // ---------- Small helpers ----------
159
+ function clip(text) {
160
+ const trimmed = text.trim();
161
+ return trimmed.length > MAX_DETAIL_CHARS ? `${trimmed.slice(0, MAX_DETAIL_CHARS)}...` : trimmed;
162
+ }
163
+ function errorText(err) {
164
+ if (err instanceof Error) {
165
+ // undici wraps the reason ("fetch failed") and keeps the useful part in `cause`.
166
+ const cause = err.cause;
167
+ return clip(cause instanceof Error && cause.message ? `${err.message}: ${cause.message}` : err.message);
168
+ }
169
+ return clip(String(err));
170
+ }
171
+ function errnoOf(err) {
172
+ const code = err?.code;
173
+ return typeof code === 'string' ? code : undefined;
174
+ }
175
+ function isDiskFull(err) {
176
+ const code = errnoOf(err);
177
+ return code === 'ENOSPC' || code === 'EDQUOT' || /no space left on device/i.test(errorText(err));
178
+ }
179
+ /** A wait on the real clock that does not keep the process alive. For grace periods, which an injected `sleep` must not shorten. */
180
+ function pause(ms) {
181
+ return new Promise((resolve) => {
182
+ setTimeout(resolve, ms).unref();
183
+ });
184
+ }
185
+ function realSleep(ms) {
186
+ return new Promise((resolve) => setTimeout(resolve, ms));
187
+ }
188
+ /** The size of a file, 0 when it is not there. */
189
+ async function fileSize(path) {
190
+ try {
191
+ const info = await stat(path);
192
+ return info.isFile() ? info.size : 0;
193
+ }
194
+ catch {
195
+ return 0;
196
+ }
197
+ }
198
+ async function isFile(path) {
199
+ try {
200
+ return (await stat(path)).isFile();
201
+ }
202
+ catch {
203
+ return false;
204
+ }
205
+ }
206
+ // ---------- Pure ----------
207
+ const BINARY_UNIT_BYTES = {
208
+ B: 1,
209
+ KiB: 1024,
210
+ MiB: 1024 ** 2,
211
+ GiB: 1024 ** 3,
212
+ TiB: 1024 ** 4,
213
+ };
214
+ /**
215
+ * The device total of the runtime's log line "inference compute", in bytes, or `undefined`
216
+ * for any other line. The real line (a MacBook, 2026-11-06):
217
+ *
218
+ * `time=... level=INFO source=types.go:32 msg="inference compute" id=0 ... type=iGPU total="37.4 GiB" available="37.4 GiB"`
219
+ *
220
+ * reads 40,157,944,217 (37.4 x 1024^3, rounded down). The value is the quoted text after
221
+ * ` total=`: a number and a binary unit (`B`, `KiB`, `MiB`, `GiB`, `TiB`). `total_vram=` of the
222
+ * line "vram-based default context" is not read.
223
+ */
224
+ export function parseInferenceComputeTotal(line) {
225
+ if (!line.includes('msg="inference compute"'))
226
+ return undefined;
227
+ // The key must stand alone: `total_vram=` and `subtotal=` are other keys.
228
+ const match = /(?:^|\s)total="(\d+(?:\.\d+)?) ?(B|KiB|MiB|GiB|TiB)"/.exec(line);
229
+ if (!match)
230
+ return undefined;
231
+ const bytes = Math.floor(Number(match[1]) * BINARY_UNIT_BYTES[match[2]]);
232
+ return Number.isFinite(bytes) && bytes > 0 ? bytes : undefined;
233
+ }
234
+ /** The names copied from the server's environment when they are set. Everything else stays behind. */
235
+ const RUNTIME_ENV_COPIED = [
236
+ 'PATH',
237
+ 'TMPDIR',
238
+ 'LANG',
239
+ 'HTTP_PROXY',
240
+ 'HTTPS_PROXY',
241
+ 'NO_PROXY',
242
+ 'http_proxy',
243
+ 'https_proxy',
244
+ 'no_proxy',
245
+ ];
246
+ /** The environment of the runtime child: the allowlist of the file header, nothing more. Pure. */
247
+ export function runtimeEnv(input) {
248
+ const env = {};
249
+ for (const name of RUNTIME_ENV_COPIED) {
250
+ const value = input.source[name];
251
+ if (typeof value === 'string' && value !== '')
252
+ env[name] = value;
253
+ }
254
+ env.HOME = input.home;
255
+ env.OLLAMA_HOST = `127.0.0.1:${input.port}`;
256
+ env.OLLAMA_MODELS = input.modelsDir;
257
+ env.OLLAMA_CONTEXT_LENGTH = String(input.contextLength);
258
+ env.OLLAMA_NO_CLOUD = '1';
259
+ env.OLLAMA_KEEP_ALIVE = RUNTIME_KEEP_ALIVE;
260
+ env.OLLAMA_NUM_PARALLEL = '1';
261
+ env.OLLAMA_MAX_LOADED_MODELS = '1';
262
+ // The memory settings of the llama.cpp runner (file header, MEMORY). Inert for an MLX model.
263
+ env.OLLAMA_KV_CACHE_TYPE = RUNTIME_KV_CACHE_TYPE;
264
+ env.OLLAMA_FLASH_ATTENTION = '1';
265
+ env.LLAMA_ARG_CACHE_RAM = String(RUNTIME_HOST_PROMPT_CACHE_MIB);
266
+ env.LLAMA_ARG_CTX_CHECKPOINTS = String(RUNTIME_CTX_CHECKPOINTS);
267
+ return env;
268
+ }
269
+ /** A path without the `/private` macOS puts in front of `/var`, `/tmp` and `/etc`. */
270
+ function withoutPrivatePrefix(path) {
271
+ return path.startsWith('/private/') ? path.slice('/private'.length) : path;
272
+ }
273
+ /**
274
+ * Whether `command` (one line of `ps -o command= -p <pid>`) is a process whose binary lies
275
+ * under `runtimeRoot` (`LocalModelPaths.runtimeRoot`): our own runtime, so an orphan of an
276
+ * earlier server. Pure. `/private` in front of a path is the same path on macOS.
277
+ *
278
+ * It tells our orphan from a runtime the user started, so that only ours is ever signalled.
279
+ * It is not a defence against another program of the same account, which can name itself
280
+ * anything.
281
+ */
282
+ export function isOwnRuntimeCommand(command, runtimeRoot) {
283
+ const root = withoutPrivatePrefix(runtimeRoot.trim()).replace(/\/+$/, '');
284
+ if (!root.startsWith('/') || root === '')
285
+ return false;
286
+ const text = withoutPrivatePrefix(command.trimStart());
287
+ if (!text.startsWith(`${root}/`))
288
+ return false;
289
+ // A `..` segment could lead out of the folder again.
290
+ return !/(?:^|\/)\.\.(?:\/|\s|$)/.test(text);
291
+ }
292
+ const CANCELLED = { ok: false, code: 'cancelled' };
293
+ /** The default `fetch` of the download: the global one, refused under vitest. */
294
+ const defaultFetch = (input, init) => {
295
+ if (UNDER_VITEST)
296
+ return Promise.reject(new NotInjectedError('fetch'));
297
+ return fetch(input, init);
298
+ };
299
+ /** The default `untar`: `/usr/bin/tar -xzf <archive> -C <intoDir>`, bounded. */
300
+ function untarWithSystemTar(archive, intoDir, signal) {
301
+ return new Promise((resolve, reject) => {
302
+ execFile('/usr/bin/tar', ['-xzf', archive, '-C', intoDir], { timeout: UNTAR_TIMEOUT_MS, ...(signal ? { signal } : {}) }, (err, _stdout, stderr) => {
303
+ if (!err)
304
+ return resolve();
305
+ const said = typeof stderr === 'string' && stderr.trim() !== '' ? stderr : err.message;
306
+ reject(new Error(clip(said)));
307
+ });
308
+ });
309
+ }
310
+ /** Whether the pinned runtime is unpacked on disk (its binary exists). Never throws. */
311
+ export async function isRuntimeInstalled(pin, paths) {
312
+ try {
313
+ const resolved = paths ?? localModelPaths((pin ?? OLLAMA_RUNTIME_PIN).version);
314
+ return await isFile(resolved.binary);
315
+ }
316
+ catch {
317
+ return false;
318
+ }
319
+ }
320
+ /** Feeds a file on disk into `hash`: the part of the archive an earlier run left behind. */
321
+ async function hashFile(path, hash, signal) {
322
+ for await (const chunk of createReadStream(path, signal ? { signal } : {})) {
323
+ hash.update(chunk);
324
+ }
325
+ }
326
+ /**
327
+ * Downloads the pinned archive to `paths.archivePartial` and proves its hash. On success the
328
+ * file is complete and verified; nothing was unpacked. Never throws.
329
+ */
330
+ async function downloadArchive(pin, paths, deps, options) {
331
+ const { signal, onProgress } = options;
332
+ const idleTimeoutMs = options.idleTimeoutMs ?? DOWNLOAD_IDLE_TIMEOUT_MS;
333
+ const partial = paths.archivePartial;
334
+ // What an earlier run left: continue after it. More than the whole archive cannot be it.
335
+ let offset = await fileSize(partial);
336
+ if (offset > pin.bytes) {
337
+ await rm(partial, { force: true });
338
+ offset = 0;
339
+ }
340
+ let hash = createHash('sha256');
341
+ if (offset > 0)
342
+ await hashFile(partial, hash, signal);
343
+ let lastReport = Number.NEGATIVE_INFINITY;
344
+ const report = (force) => {
345
+ if (!onProgress)
346
+ return;
347
+ const at = Date.now();
348
+ if (!force && at - lastReport < DOWNLOAD_PROGRESS_INTERVAL_MS)
349
+ return;
350
+ lastReport = at;
351
+ try {
352
+ onProgress({ completedBytes: offset, totalBytes: pin.bytes });
353
+ }
354
+ catch {
355
+ // A display that fails must not fail the download.
356
+ }
357
+ };
358
+ /** One request, written to the file as far as it gets. */
359
+ const attempt = async () => {
360
+ const controller = new AbortController();
361
+ const onAbort = () => controller.abort();
362
+ signal?.addEventListener('abort', onAbort, { once: true });
363
+ let idle;
364
+ let wentIdle = false;
365
+ const armIdle = () => {
366
+ clearTimeout(idle);
367
+ idle = setTimeout(() => {
368
+ wentIdle = true;
369
+ controller.abort();
370
+ }, idleTimeoutMs);
371
+ };
372
+ // Opened BEFORE the request, in append mode: once the answer is there, nothing is awaited
373
+ // until its body is being read. A body that is cut while nobody reads it loses what had
374
+ // arrived, and the continuation would start further back than it has to.
375
+ const file = await open(partial, 'a', 0o600);
376
+ // The file is deleted after it is closed: a download that cannot be the pinned archive.
377
+ let unlinkAfter = false;
378
+ const startOver = async () => {
379
+ await file.truncate(0);
380
+ offset = 0;
381
+ hash = createHash('sha256');
382
+ };
383
+ const damaged = (detail) => {
384
+ unlinkAfter = true;
385
+ return { kind: 'failed', result: { ok: false, code: 'runtime-damaged', detail } };
386
+ };
387
+ try {
388
+ armIdle();
389
+ let res;
390
+ try {
391
+ res = await deps.fetch(pin.url, {
392
+ ...(offset > 0 ? { headers: { range: `bytes=${offset}-` } } : {}),
393
+ signal: controller.signal,
394
+ redirect: 'follow',
395
+ });
396
+ }
397
+ catch (err) {
398
+ if (signal?.aborted)
399
+ return { kind: 'cancelled' };
400
+ if (err instanceof NotInjectedError) {
401
+ return { kind: 'failed', result: { ok: false, code: 'runtime-download-failed', detail: err.message } };
402
+ }
403
+ return { kind: 'ended', detail: wentIdle ? 'The download server did not answer' : errorText(err) };
404
+ }
405
+ const discard = async () => {
406
+ await res.body?.cancel().catch(() => undefined);
407
+ };
408
+ // The size the server says the whole archive has, when it says one.
409
+ let declaredTotal;
410
+ // The whole archive from its first byte although a range was asked for: the file starts over.
411
+ let restart = false;
412
+ if (res.status === 206) {
413
+ const range = /^bytes (\d+)-\d+\/(\d+)$/.exec(res.headers.get('content-range') ?? '');
414
+ // A 206 that does not start where the file ends cannot be appended to it.
415
+ if (!range || Number(range[1]) !== offset) {
416
+ await discard();
417
+ await startOver();
418
+ return { kind: 'ended', detail: 'The server answered another range than the one asked for' };
419
+ }
420
+ declaredTotal = Number(range[2]);
421
+ }
422
+ else if (res.status === 200) {
423
+ restart = offset > 0;
424
+ const length = res.headers.get('content-length');
425
+ if (length !== null && !res.headers.get('content-encoding') && /^\d+$/.test(length)) {
426
+ declaredTotal = Number(length);
427
+ }
428
+ }
429
+ else if (res.status === 416) {
430
+ // The file on disk is not a prefix of what the server has.
431
+ await discard();
432
+ await startOver();
433
+ return { kind: 'ended', detail: 'The server refused the range (HTTP 416)' };
434
+ }
435
+ else {
436
+ await discard();
437
+ return { kind: 'ended', detail: `The download server answered HTTP ${res.status}` };
438
+ }
439
+ if (declaredTotal !== undefined && declaredTotal !== pin.bytes) {
440
+ await discard();
441
+ return damaged(`The download is ${declaredTotal} bytes, the pinned archive has ${pin.bytes}`);
442
+ }
443
+ if (!res.body)
444
+ return { kind: 'ended', detail: 'The download server sent no body' };
445
+ try {
446
+ if (restart)
447
+ await startOver();
448
+ for await (const chunk of res.body) {
449
+ armIdle();
450
+ // Refused before a byte of it is written: a longer body can never have the pinned hash.
451
+ if (offset + chunk.length > pin.bytes) {
452
+ return damaged(`The download is longer than the ${pin.bytes} bytes of the pinned archive`);
453
+ }
454
+ await file.appendFile(chunk);
455
+ hash.update(chunk);
456
+ offset += chunk.length;
457
+ report(false);
458
+ }
459
+ }
460
+ catch (err) {
461
+ // Whatever was written past the last hashed byte is cut off, so file and hash agree.
462
+ await file.truncate(offset).catch(() => undefined);
463
+ if (signal?.aborted)
464
+ return { kind: 'cancelled' };
465
+ if (isDiskFull(err)) {
466
+ return { kind: 'failed', result: { ok: false, code: 'disk-full', detail: errorText(err) } };
467
+ }
468
+ return {
469
+ kind: 'ended',
470
+ detail: wentIdle
471
+ ? `The download delivered nothing for ${Math.max(1, Math.round(idleTimeoutMs / 1000))} s`
472
+ : errorText(err),
473
+ };
474
+ }
475
+ return { kind: 'ended' };
476
+ }
477
+ finally {
478
+ clearTimeout(idle);
479
+ signal?.removeEventListener('abort', onAbort);
480
+ await file.close().catch(() => undefined);
481
+ // An empty file is no start of a download either.
482
+ if (unlinkAfter || offset === 0)
483
+ await rm(partial, { force: true }).catch(() => undefined);
484
+ }
485
+ };
486
+ // A download that continues says at once how far it already is.
487
+ if (offset > 0)
488
+ report(true);
489
+ let failures = 0;
490
+ while (offset < pin.bytes) {
491
+ if (signal?.aborted)
492
+ return CANCELLED;
493
+ const outcome = await attempt();
494
+ report(true);
495
+ if (outcome.kind === 'cancelled')
496
+ return CANCELLED;
497
+ if (outcome.kind === 'failed')
498
+ return outcome.result;
499
+ if (offset >= pin.bytes)
500
+ break;
501
+ // Cut, or ended early: continue from where the file ends, a bounded number of times.
502
+ failures += 1;
503
+ if (failures > RUNTIME_DOWNLOAD_RETRIES) {
504
+ return {
505
+ ok: false,
506
+ code: 'runtime-download-failed',
507
+ detail: outcome.detail ?? `The download ended at ${offset} of ${pin.bytes} bytes`,
508
+ };
509
+ }
510
+ await deps.sleep(DOWNLOAD_RETRY_DELAY_MS * 2 ** (failures - 1));
511
+ }
512
+ if (signal?.aborted)
513
+ return CANCELLED;
514
+ // The proof, BEFORE anything is unpacked.
515
+ const digest = hash.digest('hex');
516
+ if (digest !== pin.sha256.toLowerCase()) {
517
+ await rm(partial, { force: true });
518
+ return {
519
+ ok: false,
520
+ code: 'runtime-damaged',
521
+ detail: `The sha256 of the download is ${digest}, the pinned archive has ${pin.sha256}`,
522
+ };
523
+ }
524
+ return { ok: true };
525
+ }
526
+ /**
527
+ * Unpacks the verified archive into the temporary folder and renames it to the runtime folder.
528
+ * Never throws.
529
+ */
530
+ async function unpackArchive(paths, deps, signal) {
531
+ const fail = async (err) => {
532
+ await rm(paths.unpackDir, { recursive: true, force: true }).catch(() => undefined);
533
+ if (signal?.aborted)
534
+ return CANCELLED;
535
+ return { ok: false, code: isDiskFull(err) ? 'disk-full' : 'runtime-unpack-failed', detail: errorText(err) };
536
+ };
537
+ try {
538
+ await rm(paths.unpackDir, { recursive: true, force: true });
539
+ await mkdir(paths.unpackDir, { recursive: true, mode: 0o700 });
540
+ await deps.untar(paths.archivePartial, paths.unpackDir, signal);
541
+ if (signal?.aborted)
542
+ return await fail(new Error('aborted'));
543
+ if (!(await isFile(join(paths.unpackDir, RUNTIME_BINARY_NAME)))) {
544
+ return await fail(new Error(`The archive holds no ${RUNTIME_BINARY_NAME} binary`));
545
+ }
546
+ // A folder without its binary is a leftover of an unpack that was interrupted.
547
+ await rm(paths.runtimeDir, { recursive: true, force: true });
548
+ await rename(paths.unpackDir, paths.runtimeDir);
549
+ await rm(paths.archivePartial, { force: true });
550
+ return { ok: true };
551
+ }
552
+ catch (err) {
553
+ return fail(err);
554
+ }
555
+ }
556
+ /**
557
+ * Makes sure the pinned runtime is unpacked: nothing to do when it is, else download (with
558
+ * Range resume), compare the hash, unpack, rename. Idempotent, so a resumed job calls it
559
+ * again. Never throws: every outcome is a `RuntimeInstallResult`.
560
+ */
561
+ export async function ensureRuntimeInstalled(options = {}) {
562
+ let phase = 'download';
563
+ try {
564
+ const pin = options.pin ?? OLLAMA_RUNTIME_PIN;
565
+ const paths = options.paths ?? localModelPaths(pin.version);
566
+ const deps = {
567
+ fetch: options.deps?.fetch ?? defaultFetch,
568
+ untar: options.deps?.untar ?? untarWithSystemTar,
569
+ sleep: options.deps?.sleep ?? realSleep,
570
+ };
571
+ if (await isFile(paths.binary))
572
+ return { ok: true, binaryPath: paths.binary, alreadyInstalled: true };
573
+ if (options.signal?.aborted)
574
+ return CANCELLED;
575
+ await mkdir(paths.runtimeRoot, { recursive: true, mode: 0o700 });
576
+ const downloaded = await downloadArchive(pin, paths, deps, options);
577
+ if (!downloaded.ok)
578
+ return downloaded;
579
+ phase = 'unpack';
580
+ const unpacked = await unpackArchive(paths, deps, options.signal);
581
+ if (!unpacked.ok)
582
+ return unpacked;
583
+ return { ok: true, binaryPath: paths.binary, alreadyInstalled: false };
584
+ }
585
+ catch (err) {
586
+ if (options.signal?.aborted)
587
+ return CANCELLED;
588
+ if (isDiskFull(err))
589
+ return { ok: false, code: 'disk-full', detail: errorText(err) };
590
+ return {
591
+ ok: false,
592
+ code: phase === 'download' ? 'runtime-download-failed' : 'runtime-unpack-failed',
593
+ detail: errorText(err),
594
+ };
595
+ }
596
+ }
597
+ /**
598
+ * Decides what removing `target` means, and refuses what must not be removed. A symlink in the
599
+ * place of a folder is unlinked and never followed; a real folder is deleted only when its
600
+ * real path is still inside the real root. Nothing is deleted here.
601
+ */
602
+ async function planRemoval(target, root) {
603
+ if (!isInsideLocalModelRoot(target, root) || resolvePath(target) === resolvePath(root)) {
604
+ throw new Error(`Refusing to delete ${target}: it is not a folder inside ${root}`);
605
+ }
606
+ let info;
607
+ try {
608
+ info = await lstat(target);
609
+ }
610
+ catch (err) {
611
+ if (errnoOf(err) === 'ENOENT')
612
+ return { target, how: 'absent' };
613
+ throw err;
614
+ }
615
+ // The link goes, what it points at stays: that is somebody else's folder.
616
+ if (info.isSymbolicLink())
617
+ return { target, how: 'unlink' };
618
+ const [realTarget, realRoot] = await Promise.all([realpath(target), realpath(root)]);
619
+ if (!isInsideLocalModelRoot(realTarget, realRoot) || realTarget === realRoot) {
620
+ throw new Error(`Refusing to delete ${target}: it resolves to ${realTarget}, outside ${realRoot}`);
621
+ }
622
+ return { target, how: 'delete' };
623
+ }
624
+ /**
625
+ * Whether `root` may be deleted in: it is absent (nothing to do) or a real folder. A `root`
626
+ * that is itself a symbolic link is REFUSED: every check below compares against the real
627
+ * path of the root, so a link in its place would make whatever it points at pass as ours.
628
+ */
629
+ async function rootIsDeletable(root) {
630
+ let info;
631
+ try {
632
+ info = await lstat(root);
633
+ }
634
+ catch (err) {
635
+ if (errnoOf(err) === 'ENOENT')
636
+ return 'absent';
637
+ throw err;
638
+ }
639
+ if (info.isSymbolicLink()) {
640
+ throw new Error(`Refusing to delete in ${root}: it is a symbolic link, not the folder Codeman made`);
641
+ }
642
+ if (!info.isDirectory())
643
+ throw new Error(`Refusing to delete in ${root}: it is not a folder`);
644
+ return 'folder';
645
+ }
646
+ /**
647
+ * Deletes what this feature put on disk: every runtime folder and archive, the private home
648
+ * and, when asked, the models. Refuses any path that is not inside `LocalModelPaths.root`,
649
+ * refuses a `root` that is a symbolic link, follows no symlink out of it, and removes `root`
650
+ * itself only when it is empty afterwards. Every folder is judged BEFORE the first one is
651
+ * deleted, so a refusal deletes nothing. The state file and the coding agent are not its
652
+ * business.
653
+ */
654
+ export async function removeLocalModelFiles(options) {
655
+ const paths = options.paths ?? localModelPaths(OLLAMA_RUNTIME_PIN.version);
656
+ if ((await rootIsDeletable(paths.root)) === 'absent')
657
+ return;
658
+ const targets = [paths.runtimeRoot, paths.homeDir, ...(options.models ? [paths.modelsDir] : [])];
659
+ const plan = [];
660
+ for (const target of targets)
661
+ plan.push(await planRemoval(target, paths.root));
662
+ for (const step of plan) {
663
+ if (step.how === 'unlink')
664
+ await unlink(step.target);
665
+ // `rm` removes a symlink it meets inside the tree, never the tree behind it.
666
+ if (step.how === 'delete')
667
+ await rm(step.target, { recursive: true, force: true });
668
+ }
669
+ // Empty now (the models went too, or there never were any): the folder itself goes.
670
+ await rmdir(paths.root).catch(() => undefined);
671
+ }
672
+ /** The marker the runtime puts into the name of a blob it has not finished downloading. */
673
+ const PARTIAL_BLOB_MARK = '-partial';
674
+ /**
675
+ * Deletes what an interrupted download left in the model store: the files directly in
676
+ * `<models>/blobs` whose name carries the runtime's partial marker (`sha256-<hex>-partial`
677
+ * and its numbered parts). A model the runtime has no manifest for cannot be deleted through
678
+ * the runtime (it answers "not found" and touches no blob), so its partial blobs are removed
679
+ * here. Call it only while NO download is in flight: every partial file is then a dead one.
680
+ *
681
+ * Only regular files, only that one folder, only inside `LocalModelPaths.root`; a `root`, a
682
+ * model store or a blob folder that is a symbolic link is left alone. Resolves with the bytes
683
+ * that were freed. Never throws: a file that cannot be deleted stays for Remove.
684
+ */
685
+ export async function removePartialModelBlobs(paths) {
686
+ let freed = 0;
687
+ try {
688
+ const resolved = paths ?? localModelPaths(OLLAMA_RUNTIME_PIN.version);
689
+ const blobs = join(resolved.modelsDir, 'blobs');
690
+ if (!isInsideLocalModelRoot(blobs, resolved.root))
691
+ return 0;
692
+ for (const folder of [resolved.root, resolved.modelsDir, blobs]) {
693
+ const info = await lstat(folder);
694
+ if (info.isSymbolicLink() || !info.isDirectory())
695
+ return 0;
696
+ }
697
+ for (const name of await readdir(blobs)) {
698
+ if (!name.includes(PARTIAL_BLOB_MARK))
699
+ continue;
700
+ const file = join(blobs, name);
701
+ try {
702
+ const info = await lstat(file);
703
+ if (!info.isFile())
704
+ continue;
705
+ await unlink(file);
706
+ freed += info.size;
707
+ }
708
+ catch {
709
+ // Gone already, or not ours to delete: Remove with the models takes the rest.
710
+ }
711
+ }
712
+ }
713
+ catch {
714
+ // No model store yet: nothing was left behind.
715
+ }
716
+ return freed;
717
+ }
718
+ // ---------- Port ----------
719
+ /** Whether nothing holds `port` on 127.0.0.1, decided by binding it and letting go again. */
720
+ export function isLoopbackPortFree(port) {
721
+ return new Promise((resolve) => {
722
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
723
+ return resolve(false);
724
+ const probe = createServer();
725
+ probe.unref();
726
+ probe.once('error', () => resolve(false));
727
+ probe.listen(port, '127.0.0.1', () => {
728
+ probe.close(() => resolve(true));
729
+ });
730
+ });
731
+ }
732
+ /** The first free loopback port of the span, or `undefined` when none is free. Chosen once, then stored by the caller. */
733
+ export async function chooseRuntimePort(options = {}) {
734
+ const first = options.first ?? RUNTIME_PORT_FIRST;
735
+ const span = options.span ?? RUNTIME_PORT_SPAN;
736
+ const isFree = options.isFree ?? isLoopbackPortFree;
737
+ const avoid = new Set(options.avoid ?? []);
738
+ for (let port = first; port < first + span; port++) {
739
+ if (avoid.has(port))
740
+ continue;
741
+ try {
742
+ if (await isFree(port))
743
+ return port;
744
+ }
745
+ catch {
746
+ // A probe that fails says nothing about the port: it is not taken as free.
747
+ }
748
+ }
749
+ return undefined;
750
+ }
751
+ const defaultSpawn = (command, args, options) => {
752
+ if (UNDER_VITEST)
753
+ throw new NotInjectedError('spawn');
754
+ return nodeSpawn(command, [...args], options);
755
+ };
756
+ /** `ps -o command= -p <pid>`: the command line of a pid, `undefined` when it is gone. Spawns nothing under vitest. */
757
+ function defaultCommandOfPid(pid) {
758
+ return new Promise((resolve) => {
759
+ if (UNDER_VITEST || !Number.isInteger(pid) || pid <= 1)
760
+ return resolve(undefined);
761
+ execFile('/bin/ps', ['-o', 'command=', '-p', String(pid)], { timeout: PS_TIMEOUT_MS }, (err, stdout) => {
762
+ const line = typeof stdout === 'string' ? stdout.trim() : '';
763
+ resolve(err || line === '' ? undefined : line);
764
+ });
765
+ });
766
+ }
767
+ const defaultKill = (pid, signal) => {
768
+ if (UNDER_VITEST || !Number.isInteger(pid) || pid <= 1)
769
+ return;
770
+ try {
771
+ process.kill(pid, signal);
772
+ }
773
+ catch {
774
+ // Gone already.
775
+ }
776
+ };
777
+ function hasExited(child) {
778
+ return child.exitCode !== null || child.signalCode !== null;
779
+ }
780
+ /** A supervisor. The server keeps ONE (see `getLocalModelService()` in install-job.ts). */
781
+ export function createRuntimeSupervisor(overrides = {}) {
782
+ const pin = overrides.pin ?? OLLAMA_RUNTIME_PIN;
783
+ const deps = {
784
+ spawn: overrides.spawn ?? defaultSpawn,
785
+ fetch: overrides.fetch ?? defaultFetch,
786
+ env: overrides.env ?? process.env,
787
+ commandOfPid: overrides.commandOfPid ?? defaultCommandOfPid,
788
+ kill: overrides.kill ?? defaultKill,
789
+ isPortFree: overrides.isPortFree ?? isLoopbackPortFree,
790
+ sleep: overrides.sleep ?? realSleep,
791
+ onChange: overrides.onChange ?? (() => undefined),
792
+ startTimeoutMs: overrides.startTimeoutMs ?? START_TIMEOUT_MS,
793
+ orphanPollMs: overrides.orphanPollMs ?? ORPHAN_POLL_MS,
794
+ budgetWaitMs: overrides.budgetWaitMs ?? BUDGET_WAIT_MS,
795
+ };
796
+ // Resolved on first use: `localModelPaths()` creates the data dir, which making a supervisor must not.
797
+ let resolvedPaths = overrides.paths;
798
+ const paths = () => (resolvedPaths ??= localModelPaths(pin.version));
799
+ /** Our child, once it answered. */
800
+ let child;
801
+ /** A child that was spawned and has not answered yet. */
802
+ let starting;
803
+ /** An orphan of an earlier server that was adopted: not our child, so it is signalled by pid. */
804
+ let adoptedPid;
805
+ let orphanTimer;
806
+ /** What the last `start()` asked for: what a restart starts again. */
807
+ let wanted;
808
+ /** The version the running child was started as. */
809
+ let runningVersion;
810
+ /** Bumped by every `start()` and `stop()`: work of an older generation stops when it notices. */
811
+ let generation = 0;
812
+ /** The restart loop that is running, if one is. */
813
+ let restarting;
814
+ /** `start()` and `stop()` run one after the other. */
815
+ let queue = Promise.resolve();
816
+ let state = { running: false, restarts: 0, gaveUp: false };
817
+ function setState(patch) {
818
+ const next = { ...state, ...patch };
819
+ for (const key of Object.keys(next)) {
820
+ if (next[key] === undefined)
821
+ delete next[key];
822
+ }
823
+ const changed = Object.keys(next).length !== Object.keys(state).length ||
824
+ Object.keys(next).some((key) => next[key] !== state[key]);
825
+ state = next;
826
+ if (!changed)
827
+ return;
828
+ try {
829
+ deps.onChange({ ...state });
830
+ }
831
+ catch {
832
+ // A caller that throws must not stop the supervisor.
833
+ }
834
+ }
835
+ function serialize(work) {
836
+ const run = queue.then(work, work);
837
+ queue = run.catch(() => undefined);
838
+ return run;
839
+ }
840
+ const isOwn = (command) => command !== undefined && isOwnRuntimeCommand(command, paths().runtimeRoot);
841
+ /** SIGTERM, then SIGKILL after the grace period. Resolves once the child is gone. */
842
+ async function stopChild(proc) {
843
+ // A child that never got a pid was never started: there is no exit to wait for.
844
+ if (hasExited(proc) || proc.pid === undefined)
845
+ return;
846
+ const gone = new Promise((resolve) => proc.once('exit', () => resolve()));
847
+ try {
848
+ if (!proc.kill('SIGTERM'))
849
+ return;
850
+ }
851
+ catch {
852
+ return;
853
+ }
854
+ const force = setTimeout(() => {
855
+ try {
856
+ proc.kill('SIGKILL');
857
+ }
858
+ catch {
859
+ // Gone already.
860
+ }
861
+ }, STOP_GRACE_MS);
862
+ force.unref();
863
+ await Promise.race([gone, pause(STOP_GRACE_MS + STOP_KILL_WAIT_MS)]);
864
+ clearTimeout(force);
865
+ }
866
+ /** The same for a pid that is not our child: signalled through `deps.kill`, watched through `ps`. */
867
+ async function stopOrphan(pid) {
868
+ const goneWithin = async (ms) => {
869
+ const until = Date.now() + ms;
870
+ for (;;) {
871
+ if (!isOwn(await deps.commandOfPid(pid)))
872
+ return true;
873
+ if (Date.now() >= until)
874
+ return false;
875
+ await pause(100);
876
+ }
877
+ };
878
+ deps.kill(pid, 'SIGTERM');
879
+ if (await goneWithin(STOP_GRACE_MS))
880
+ return;
881
+ deps.kill(pid, 'SIGKILL');
882
+ await goneWithin(STOP_KILL_WAIT_MS);
883
+ }
884
+ /** Stops whatever runs now: our child, one that is starting, an adopted orphan. */
885
+ async function stopCurrent() {
886
+ clearInterval(orphanTimer);
887
+ orphanTimer = undefined;
888
+ const procs = [child, starting].filter((proc) => proc !== undefined);
889
+ // Forgotten first, so that its exit is not taken for a crash.
890
+ child = undefined;
891
+ starting = undefined;
892
+ const orphan = adoptedPid;
893
+ adoptedPid = undefined;
894
+ await Promise.all(procs.map((proc) => stopChild(proc)));
895
+ if (orphan !== undefined)
896
+ await stopOrphan(orphan);
897
+ }
898
+ /** The runtime exited by itself: start it again, a bounded number of times. */
899
+ function restart() {
900
+ if (restarting)
901
+ return;
902
+ const gen = generation;
903
+ const loop = async () => {
904
+ while (gen === generation && wanted) {
905
+ if (state.restarts >= RUNTIME_MAX_RESTARTS) {
906
+ setState({ gaveUp: true });
907
+ return;
908
+ }
909
+ setState({ restarts: state.restarts + 1 });
910
+ await deps.sleep(RESTART_DELAY_MS);
911
+ if (gen !== generation || !wanted)
912
+ return;
913
+ const launched = await launch(wanted.port, wanted.contextLength, wanted.version, gen);
914
+ // Running again: a later exit comes back here through the child's exit handler.
915
+ if (launched.ok)
916
+ return;
917
+ }
918
+ };
919
+ restarting = loop()
920
+ .catch(() => undefined)
921
+ .finally(() => {
922
+ restarting = undefined;
923
+ });
924
+ }
925
+ /** Spawns the runtime and waits until it answers. The child becomes `child` only then. */
926
+ async function launch(port, contextLength, version, gen) {
927
+ const folders = paths();
928
+ let spawned;
929
+ try {
930
+ // The pinned build, or the one an installed model was installed with.
931
+ const binary = version === pin.version ? folders.binary : runtimeBinaryForVersion(folders, version);
932
+ await mkdir(folders.homeDir, { recursive: true, mode: 0o700 });
933
+ await mkdir(folders.modelsDir, { recursive: true, mode: 0o700 });
934
+ // Asked to stop in the meantime: nothing is started only to be stopped again.
935
+ if (gen !== generation)
936
+ return { ok: false, detail: 'The start was replaced by a newer request' };
937
+ spawned = deps.spawn(binary, ['serve'], {
938
+ env: runtimeEnv({
939
+ source: deps.env,
940
+ home: folders.homeDir,
941
+ modelsDir: folders.modelsDir,
942
+ port,
943
+ contextLength,
944
+ }),
945
+ cwd: folders.homeDir,
946
+ stdio: ['ignore', 'pipe', 'pipe'],
947
+ // A child of the server, in its process group: it is not left behind by a normal exit.
948
+ detached: false,
949
+ });
950
+ }
951
+ catch (err) {
952
+ return { ok: false, detail: errorText(err) };
953
+ }
954
+ starting = spawned;
955
+ // Said at once, before the child answers: the caller stores the pid, so a server that is
956
+ // killed during this start still leaves a pid that names the runtime as ours.
957
+ if (spawned.pid !== undefined)
958
+ setState({ pid: spawned.pid });
959
+ // The child's output: the budget line, and the last lines for the detail of a failure.
960
+ // It is read for as long as the child lives, so a full pipe never blocks it.
961
+ const tail = [];
962
+ let measured;
963
+ let budgetSeen = () => undefined;
964
+ const budget = new Promise((resolve) => {
965
+ budgetSeen = resolve;
966
+ });
967
+ const onLine = (text) => {
968
+ const line = text.length > LOG_LINE_MAX_CHARS ? text.slice(0, LOG_LINE_MAX_CHARS) : text;
969
+ if (line.trim() === '')
970
+ return;
971
+ tail.push(line);
972
+ if (tail.length > LOG_TAIL_LINES)
973
+ tail.shift();
974
+ const total = parseInferenceComputeTotal(line);
975
+ if (total === undefined)
976
+ return;
977
+ measured = total;
978
+ if (child === spawned)
979
+ setState({ measuredTotalBytes: total });
980
+ budgetSeen();
981
+ };
982
+ for (const stream of [spawned.stdout, spawned.stderr]) {
983
+ if (!stream)
984
+ continue;
985
+ let pending = '';
986
+ stream.setEncoding('utf8');
987
+ stream.on('data', (chunk) => {
988
+ pending += chunk;
989
+ let breakAt = pending.indexOf('\n');
990
+ while (breakAt >= 0) {
991
+ onLine(pending.slice(0, breakAt));
992
+ pending = pending.slice(breakAt + 1);
993
+ breakAt = pending.indexOf('\n');
994
+ }
995
+ // A line without an end is cut, so the buffer cannot grow without bound.
996
+ if (pending.length > LOG_LINE_MAX_CHARS)
997
+ pending = pending.slice(0, LOG_LINE_MAX_CHARS);
998
+ });
999
+ stream.on('error', () => undefined);
1000
+ }
1001
+ let ended;
1002
+ let goneNow = () => undefined;
1003
+ const gone = new Promise((resolve) => {
1004
+ goneNow = resolve;
1005
+ });
1006
+ // The last resort when the server exits without its shutdown: the child must not outlive it.
1007
+ const onProcessExit = () => {
1008
+ try {
1009
+ spawned.kill('SIGTERM');
1010
+ }
1011
+ catch {
1012
+ // Gone already.
1013
+ }
1014
+ };
1015
+ process.once('exit', onProcessExit);
1016
+ spawned.once('error', (err) => {
1017
+ // A spawn that failed emits no exit.
1018
+ if (spawned.pid === undefined)
1019
+ process.off('exit', onProcessExit);
1020
+ ended ??= `The runtime could not be started: ${errorText(err)}`;
1021
+ goneNow();
1022
+ });
1023
+ spawned.once('exit', (code, signal) => {
1024
+ process.off('exit', onProcessExit);
1025
+ ended ??= signal ? `The runtime was ended by ${signal}` : `The runtime exited with code ${String(code)}`;
1026
+ goneNow();
1027
+ if (starting === spawned)
1028
+ starting = undefined;
1029
+ if (child !== spawned)
1030
+ return;
1031
+ // Our running child exited by itself.
1032
+ child = undefined;
1033
+ setState({ running: false, pid: undefined });
1034
+ restart();
1035
+ });
1036
+ const fail = async (reason) => {
1037
+ if (starting === spawned)
1038
+ starting = undefined;
1039
+ await stopChild(spawned);
1040
+ // The pid that was announced at the spawn is no runtime any more.
1041
+ if (state.pid === spawned.pid && child !== spawned)
1042
+ setState({ pid: undefined });
1043
+ const log = tail.join('\n');
1044
+ return { ok: false, detail: clip(log === '' ? reason : `${reason}\n${log}`) };
1045
+ };
1046
+ const target = { baseUrl: `http://127.0.0.1:${port}`, fetch: deps.fetch };
1047
+ const deadline = Date.now() + deps.startTimeoutMs;
1048
+ for (;;) {
1049
+ if (ended !== undefined)
1050
+ return fail(ended);
1051
+ if (gen !== generation)
1052
+ return fail('The start was replaced by a newer request');
1053
+ const answered = await getRuntimeVersion(target);
1054
+ if (ended !== undefined)
1055
+ return fail(ended);
1056
+ if (answered !== undefined) {
1057
+ if (answered !== version)
1058
+ return fail(`The runtime answers as version ${answered}, not ${version}`);
1059
+ break;
1060
+ }
1061
+ if (Date.now() >= deadline) {
1062
+ return fail(`The runtime did not answer within ${Math.round(deps.startTimeoutMs / 1000)} seconds`);
1063
+ }
1064
+ await deps.sleep(START_POLL_MS);
1065
+ }
1066
+ // The budget line follows the first answer within a moment. An older runtime may not print it.
1067
+ if (measured === undefined)
1068
+ await Promise.race([budget, gone, pause(deps.budgetWaitMs)]);
1069
+ if (ended !== undefined)
1070
+ return fail(ended);
1071
+ if (gen !== generation)
1072
+ return fail('The start was replaced by a newer request');
1073
+ starting = undefined;
1074
+ child = spawned;
1075
+ runningVersion = version;
1076
+ const pid = spawned.pid ?? 0;
1077
+ setState({
1078
+ running: true,
1079
+ pid,
1080
+ port,
1081
+ contextLength,
1082
+ measuredTotalBytes: measured,
1083
+ gaveUp: false,
1084
+ });
1085
+ return { ok: true, pid, ...(measured !== undefined ? { measuredTotalBytes: measured } : {}) };
1086
+ }
1087
+ /** Keeps an orphan of an earlier server: it is watched by pid, because its exit is no event of ours. */
1088
+ function adopt(pid, port, contextLength, version) {
1089
+ adoptedPid = pid;
1090
+ runningVersion = version;
1091
+ setState({ running: true, pid, port, contextLength, measuredTotalBytes: undefined, gaveUp: false });
1092
+ let looking = false;
1093
+ orphanTimer = setInterval(() => {
1094
+ if (looking || adoptedPid !== pid)
1095
+ return;
1096
+ looking = true;
1097
+ void deps
1098
+ .commandOfPid(pid)
1099
+ .catch(() => undefined)
1100
+ .then((command) => {
1101
+ looking = false;
1102
+ if (adoptedPid !== pid || isOwn(command))
1103
+ return;
1104
+ // The orphan is gone: from here on the runtime is a child of our own.
1105
+ clearInterval(orphanTimer);
1106
+ orphanTimer = undefined;
1107
+ adoptedPid = undefined;
1108
+ setState({ running: false, pid: undefined });
1109
+ restart();
1110
+ });
1111
+ }, deps.orphanPollMs);
1112
+ orphanTimer.unref();
1113
+ }
1114
+ /** Whether keeping this orphan keeps something: a model is loaded, and at the wanted context. */
1115
+ async function worthAdopting(target, contextLength) {
1116
+ const loaded = await listRunning(target);
1117
+ return loaded.length > 0 && loaded.every((model) => model.contextLength === contextLength);
1118
+ }
1119
+ /** Waits for the port to come free after an orphan was told to go. */
1120
+ async function portFreeWithin(port, ms) {
1121
+ const until = Date.now() + ms;
1122
+ for (;;) {
1123
+ if (await deps.isPortFree(port).catch(() => false))
1124
+ return true;
1125
+ if (Date.now() >= until)
1126
+ return false;
1127
+ await pause(100);
1128
+ }
1129
+ }
1130
+ async function doStart(options) {
1131
+ const { port, contextLength, previousPid } = options;
1132
+ const version = options.version ?? pin.version;
1133
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
1134
+ return { ok: false, code: 'runtime-start-failed', detail: `Not a port: ${String(port)}` };
1135
+ }
1136
+ if (!Number.isInteger(contextLength) || contextLength < 1) {
1137
+ return { ok: false, code: 'runtime-start-failed', detail: `Not a context length: ${String(contextLength)}` };
1138
+ }
1139
+ // Already running as asked: nothing to do.
1140
+ const alive = (child !== undefined && !hasExited(child)) || adoptedPid !== undefined;
1141
+ if (alive &&
1142
+ state.running &&
1143
+ state.port === port &&
1144
+ state.contextLength === contextLength &&
1145
+ runningVersion === version) {
1146
+ return {
1147
+ ok: true,
1148
+ pid: state.pid ?? 0,
1149
+ port,
1150
+ orphan: 'none',
1151
+ ...(state.measuredTotalBytes !== undefined ? { measuredTotalBytes: state.measuredTotalBytes } : {}),
1152
+ };
1153
+ }
1154
+ generation += 1;
1155
+ const gen = generation;
1156
+ await restarting;
1157
+ await stopCurrent();
1158
+ wanted = { port, contextLength, version };
1159
+ runningVersion = undefined;
1160
+ setState({
1161
+ running: false,
1162
+ pid: undefined,
1163
+ port: undefined,
1164
+ contextLength: undefined,
1165
+ measuredTotalBytes: undefined,
1166
+ restarts: 0,
1167
+ gaveUp: false,
1168
+ });
1169
+ // Who holds the port, if anybody does.
1170
+ const target = { baseUrl: `http://127.0.0.1:${port}`, fetch: deps.fetch };
1171
+ const ownOrphan = previousPid !== undefined &&
1172
+ Number.isInteger(previousPid) &&
1173
+ isOwn(await deps.commandOfPid(previousPid).catch(() => undefined))
1174
+ ? previousPid
1175
+ : undefined;
1176
+ const answering = await getRuntimeVersion(target);
1177
+ let orphan = 'none';
1178
+ if (ownOrphan !== undefined) {
1179
+ if (answering === version && (await worthAdopting(target, contextLength))) {
1180
+ adopt(ownOrphan, port, contextLength, version);
1181
+ return { ok: true, pid: ownOrphan, port, orphan: 'adopted' };
1182
+ }
1183
+ await stopOrphan(ownOrphan);
1184
+ orphan = 'replaced';
1185
+ }
1186
+ else if (answering !== undefined) {
1187
+ return {
1188
+ ok: false,
1189
+ code: 'port-in-use',
1190
+ detail: `A model runtime that Codeman did not start answers on port ${port} (version ${answering})`,
1191
+ };
1192
+ }
1193
+ if (!(await portFreeWithin(port, orphan === 'replaced' ? STOP_GRACE_MS : 0))) {
1194
+ return { ok: false, code: 'port-in-use', detail: `Another program holds port ${port}` };
1195
+ }
1196
+ const launched = await launch(port, contextLength, version, gen);
1197
+ if (!launched.ok)
1198
+ return { ok: false, code: 'runtime-start-failed', detail: launched.detail };
1199
+ return {
1200
+ ok: true,
1201
+ pid: launched.pid,
1202
+ port,
1203
+ orphan,
1204
+ ...(launched.measuredTotalBytes !== undefined ? { measuredTotalBytes: launched.measuredTotalBytes } : {}),
1205
+ };
1206
+ }
1207
+ async function doStop(options = {}) {
1208
+ generation += 1;
1209
+ wanted = undefined;
1210
+ await restarting;
1211
+ await stopCurrent();
1212
+ runningVersion = undefined;
1213
+ // A runtime an earlier server left behind: not a child of this process, known only by the
1214
+ // pid the state file kept. Ended when (and only when) its command line is our own binary.
1215
+ const { previousPid } = options;
1216
+ if (previousPid !== undefined && Number.isInteger(previousPid) && previousPid > 1) {
1217
+ if (isOwn(await deps.commandOfPid(previousPid).catch(() => undefined)))
1218
+ await stopOrphan(previousPid);
1219
+ }
1220
+ setState({
1221
+ running: false,
1222
+ pid: undefined,
1223
+ port: undefined,
1224
+ contextLength: undefined,
1225
+ measuredTotalBytes: undefined,
1226
+ restarts: 0,
1227
+ gaveUp: false,
1228
+ });
1229
+ }
1230
+ return {
1231
+ start: (options) => serialize(() => doStart(options)).catch((err) => ({ ok: false, code: 'runtime-start-failed', detail: errorText(err) })),
1232
+ stop: (options) => {
1233
+ // At once, not when its turn comes: a start that is still waiting for the runtime gives up.
1234
+ generation += 1;
1235
+ return serialize(() => doStop(options)).catch(() => undefined);
1236
+ },
1237
+ status: () => ({ ...state }),
1238
+ };
1239
+ }
1240
+ //# sourceMappingURL=runtime.js.map